---
title: "Security Best Practices"
description: "Autohand operates on your code with real file system access and command execution. This guide covers how to configure permissions, protect sensitive files, sandbox commands, and set up team-wide security policies."
seo:
  description: "Set up Autohand Code CLI securely with permission modes, fine-grained access control, sandbox isolation, sensitive file protection, hook-based guardrails, and team."
---

:::tip
**Related Skills:** Enhance your security posture with specialized skills from [Skilled](https://skilled.autohand.ai). Browse [security scanning skills](https://skilled.autohand.ai/categories/quality), [security audit workflows](https://skilled.autohand.ai/categories/workflows), and [compliance skills](https://skilled.autohand.ai/categories/devops) to protect your codebase.
:::

## Permission modes

Autohand has three permission modes that control how much freedom the agent has when interacting with your system. Choosing the right mode depends on the task and how much you trust the environment.

### Interactive mode (default)

The agent asks for your approval before performing any potentially dangerous action. This is the safest mode for daily work. Every file write, command execution, and deletion prompts you with a yes/no confirmation.

```bash
# Default behavior, no flag needed
autohand "Refactor the auth module"

# The agent will prompt before each action:
# Allow writing to src/auth/middleware.ts? [y/n]
# Allow running: npm test? [y/n]
```

Use interactive mode when you are exploring a codebase for the first time, working on sensitive parts of your system, or running Autohand on a project you are not familiar with.

### Unrestricted mode

The agent performs all actions without asking for permission. This is useful for trusted, well-scoped tasks where you have already reviewed the plan.

```bash
# Allow all actions without prompts
autohand --unrestricted "Add unit tests for every file in src/utils/"
```

:::warning[Caution]
Unrestricted mode gives the agent full access to read, write, and execute within your workspace. Only use it on isolated branches or when you can easily revert changes.
:::

### Restricted mode

The agent can only read files and search the codebase. It cannot write files, run commands, or make any modifications. This is the right choice for code review and analysis tasks.

```bash
# Read-only mode for safe analysis
autohand --restricted "Review the payment flow for security vulnerabilities"

# Also useful in CI where you don't want any side effects.
# CI runners need --bare and the Autohand provider variables.
git diff main...HEAD | autohand --bare --restricted \
  -p "Review this diff for bugs"
```

### Comparing the modes

| Capability | Interactive | Unrestricted | Restricted |
| --- | --- | --- | --- |
| Read files | Yes | Yes | Yes |
| Write files | With approval | Yes | No |
| Run commands | With approval | Yes | No |
| Delete files | With approval | Yes | No |
| Best for | Daily development | Trusted automation | Code review, CI |

## Fine-grained permissions

Beyond the three main modes, you can define exactly which tools and commands the agent is allowed to use. Permission patterns let you whitelist safe operations and block dangerous ones.

### Whitelist patterns

Limit a run to specific tools. The agent is only offered the tools you list:

```bash
# Offer only file tools and shell commands for this run
autohand --allowed-tools "read_file,list_tree,write_file,apply_patch,run_command" \
  "Fix all lint errors and run the tests"
```

### Blacklist patterns

Block specific dangerous operations while allowing everything else:

```bash
# Remove the delete tool for this run
autohand --disallowed-tools "delete_path" \
  "Clean up the unused modules in src/legacy/"
```

### Pattern matching syntax

The `--allowed-tools` and `--disallowed-tools` flags take tool names, separated by commas or given by repeating the flag. They apply to one run and are never saved. To allow or block specific commands and paths, add patterns in the format `tool_name:argument_pattern` to `permissions.allowList` and `permissions.denyList` in your configuration. The `*` wildcard matches any string.

```bash
# Review only: offer read tools and no shell or write tools
autohand --allowed-tools "read_file,list_tree" \
  "Explain how the service layer is structured"

# Allow edits but remove shell commands and deletion
autohand --disallowed-tools "run_command,delete_path" \
  "Refactor the service layer"
```

### Permission patterns in configuration

Instead of passing flags every time, set default permissions in your project configuration file:

```json
// .autohand/config.json
{
  "permissions": {
    "allowList": [
      "run_command:npm *",
      "run_command:node *",
      "run_command:git add *",
      "run_command:git commit *",
      "write_file:src/*",
      "write_file:tests/*"
    ],
    "denyList": [
      "run_command:rm -rf *",
      "run_command:git push --force*",
      "write_file:.env*",
      "write_file:*.pem",
      "delete_path:/"
    ]
  }
}
```

The config file applies to everyone on the team, so it is a good place to encode your project's safety rules.

## YOLO mode safety

YOLO mode (also called `--yes` or `--unrestricted`) lets the agent run without prompts. Used carelessly, it can overwrite files or run destructive commands. The key to using it safely is pairing it with deny patterns that act as guardrails.

### Safe YOLO with deny patterns

Allow everything except the operations you never want to happen. Deny list entries in your configuration, such as `run_command:rm *` and `run_command:git push *`, still apply in `--unrestricted` mode. Add a per-run tool restriction on top:

```bash
# YOLO mode with safety rails (config deny list plus no delete tool)
autohand --unrestricted \
  --disallowed-tools "delete_path" \
  "Add error handling to all API routes"
```

### Scoped YOLO for testing

When generating tests, you usually want the agent to create files freely. Name the target directory in the prompt, remove tools the job does not need, and use a config file with deny list entries for the job. Review the diff before merging, because the prompt alone does not enforce paths.

```bash
# Test generation with a dedicated config and no delete tool
AUTOHAND_CONFIG=.autohand/config.tests.json autohand --unrestricted \
  --disallowed-tools "delete_path" \
  "Generate comprehensive tests for the billing module. Only create or edit files under tests/."
```

### YOLO in CI with safety nets

In CI environments, combine YOLO mode with restricted scope and dry-run checks:

```bash
# CI: auto-fix lint errors, but verify with dry-run first
autohand --unrestricted --dry-run \
  -p "Fix all ESLint errors in src/"

# If dry-run looks good, apply for real (block git push with a config deny list entry)
autohand --unrestricted \
  --disallowed-tools "delete_path" \
  -p "Fix all ESLint errors in src/"
```

:::tip
**Tip:** Always run `--dry-run` first to preview what YOLO mode will do. This lets you verify the scope of changes before they happen.
:::

## Workspace safety

Autohand automatically prevents the agent from operating on directories it should never touch. These built-in protections stop accidental damage to your system.

### Protected directories

The agent will refuse to write or execute commands in these locations, regardless of permissions:

- `/` (root directory)
- `~` (home directory, unless your project lives there)
- `/etc`, `/usr`, `/bin`, `/sbin` (system directories)
- `/System`, `/Library` (macOS system directories)
- `C:\Windows`, `C:\Program Files` (Windows system directories)

If you try to point Autohand at your home directory, it will ask you to narrow the scope:

```bash
# This will be rejected
autohand --add-dir ~ "Clean up old projects"
# Error: Cannot operate on home directory. Please specify a project subdirectory.

# This is fine
autohand --add-dir ~/projects/my-app "Clean up unused modules"
```

### Scope limiting with --add-dir

By default, Autohand operates in the current working directory. You can expand its scope with `--add-dir`, but only to specific directories you trust:

```bash
# Work across two related projects
autohand --add-dir ../shared-lib "Update the shared library types to match the API changes in this project"

# Add a data directory for analysis
autohand --add-dir ./data --restricted "Analyze the CSV files in the data directory and suggest schema improvements"
```

### Git worktree isolation

For risky operations, use a git worktree so that changes happen on a separate branch in an isolated directory:

```bash
# Create an isolated worktree for the refactoring
git worktree add ../refactoring-branch -b refactoring
cd ../refactoring-branch
autohand --unrestricted "Refactor the entire API layer to use the new router"

# Review changes, then merge if they look good
git diff main
cd ../main-project
git merge refactoring
```

## Hook-based guardrails [#hook-guardrails]

Hooks let you run custom logic before or after the agent takes an action. You can use them to enforce policies, log activity, and block specific operations based on your own rules.

Each hook is an entry in the `hooks.hooks` array of a config file: your global `~/.autohand/config.json`, or the project's `.autohand/config.json` (project hooks only run after you trust that workspace's content). The command runs through the shell in the workspace root and receives the event context as `HOOK_*` environment variables, as JSON on stdin, and through `{{variable}}` placeholders. Exit code 2 blocks the action and shows the stderr text as the reason. There is no separate `hooks.json` file.

### Block writes to production configs

Prevent the agent from modifying production configuration files:

```json
// .autohand/config.json
{
  "hooks": {
    "hooks": [
      {
        "event": "pre-tool",
        "description": "Block production config edits",
        "filter": {
          "tool": ["write_file", "append_file", "search_replace", "apply_patch", "delete_path"],
          "path": ["config/production.*", "docker-compose.prod.yml"]
        },
        "command": "echo 'Production config files are managed by the infrastructure team. Change config/development.* and promote through your deployment pipeline.' >&2; exit 2"
      }
    ]
  }
}
```

### Require approval for database commands

Add an extra confirmation step before any database-related commands. Printing `{"decision": "ask"}` forces a permission prompt; `{"decision": "deny"}` rejects the command:

```json
// .autohand/config.json
{
  "hooks": {
    "hooks": [
      {
        "event": "pre-tool",
        "description": "Gate database commands",
        "filter": { "tool": ["run_command"] },
        "command": "~/.autohand/hooks/db-guard.sh"
      }
    ]
  }
}
```

With `~/.autohand/hooks/db-guard.sh`:

```bash
#!/bin/bash
COMMAND=$(jq -r '.tool_input.command // ""')

case "$COMMAND" in
  psql*)
    echo '{"decision": "deny", "reason": "Direct database access is not allowed through the agent."}' ;;
  *migrate*|*seed*)
    echo '{"decision": "ask", "reason": "This command changes the database. Confirm before proceeding."}' ;;
esac
exit 0
```

### Log all file modifications

Keep an audit trail of every file the agent modifies and every shell command it runs:

```json
// .autohand/config.json
{
  "hooks": {
    "hooks": [
      {
        "event": "file-modified",
        "async": true,
        "command": "echo \"$(date -u +%Y-%m-%dT%H:%M:%SZ) $HOOK_CHANGE_TYPE $HOOK_PATH\" >> .autohand/audit.log"
      },
      {
        "event": "post-tool",
        "async": true,
        "filter": { "tool": ["run_command"] },
        "command": "echo \"$(date -u +%Y-%m-%dT%H:%M:%SZ) EXEC\" {{command}} >> .autohand/audit.log"
      }
    ]
  }
}
```

### Enforce code style on writes

Automatically format files after the agent writes them:

```json
// .autohand/config.json
{
  "hooks": {
    "hooks": [
      {
        "event": "file-modified",
        "filter": { "path": ["**/*.ts"] },
        "command": "npx prettier --write {{file}}"
      },
      {
        "event": "file-modified",
        "filter": { "path": ["**/*.py"] },
        "command": "black {{file}}"
      }
    ]
  }
}
```

## Sensitive file protection [#sensitive-files]

Certain files should never be read or modified by the agent. Environment files, API keys, certificates, and credentials need explicit protection.

### Default protected patterns

Autohand automatically avoids reading or writing these file patterns:

- `.env`, `.env.*` - Environment variable files
- `*.pem`, `*.key`, `*.cert` - Certificates and keys
- `id_rsa`, `id_ed25519` - SSH keys
- `credentials.json`, `serviceAccountKey.json` - Cloud credentials

If the agent tries to read a protected file, it will receive an empty result with a note that the file is protected.

### Custom protection patterns

Add your own patterns to the deny list in the configuration:

```json
// .autohand/config.json
{
  "permissions": {
    "denyList": [
      "read_file:.env*",
      "read_file:*.secret",
      "read_file:config/secrets/*",
      "read_file:**/credentials*",
      "write_file:.env*",
      "write_file:*.pem",
      "write_file:*.key",
      "write_file:config/production.*"
    ]
  }
}
```

### Using .autohandignore

Create an `.autohandignore` file (similar to `.gitignore`) to exclude files from the agent's view entirely:

```bash
# .autohandignore
.env
.env.*
*.pem
*.key
*.cert
config/secrets/
credentials/
**/serviceAccountKey.json
**/*.secret.yaml
node_modules/
.git/
```

Files listed in `.autohandignore` will not appear in search results, will not be read by the agent, and will not be offered as context. This is the strongest form of protection because the agent does not even know these files exist.

### Verifying protection

Test that your protections work by asking the agent to read a protected file:

```bash
# Verify sensitive files are protected
autohand --restricted "Can you read the contents of .env?"
# Expected: The agent reports that the file is protected or not accessible
```

## Isolated execution

Autohand does not have a built-in sandbox flag. Permission controls decide which tools the agent may call, and the operating system decides what those calls can reach. When the agent needs write access or runs unattended, run it inside an environment that limits what a mistake can touch, such as a container, a disposable CI runner, or a dedicated virtual machine.

### Run the agent in a container

A container limits file system access to the mounted project and lets you control network access and environment variables. See [Run Autohand in Docker](/tutorials/run-autohand-in-docker) for a complete setup.

```bash
# Mount only the project and pass only the key the agent needs.
# A container has no stored sign-in, so run the CLI with --bare.
docker run --rm -it \
  -v "$PWD":/workspace -w /workspace \
  -e AUTOHAND_PROVIDER=autohandai \
  -e AUTOHAND_API_KEY \
  -e AUTOHAND_AI_API_KEY="$AUTOHAND_API_KEY" \
  your-autohand-image \
  autohand --bare -p "Install the testing dependencies and run the full test suite"
```

### What each layer protects

- **Permission flags and config rules** decide which tools and commands the agent may use.
- **`--allowed-tools` and `--disallowed-tools`** narrow the tools for a single run.
- **`--worktree`** separates working files and branches. It does not isolate credentials, networks, or operating system access.
- **Containers and disposable runners** limit the files, network, and secrets that the process can reach.

### Isolation in CI

A fresh CI runner is a disposable environment. Give the job only the secrets it needs and block the operations you never want to happen. The runner has no stored Autohand sign-in, so run the CLI with `--bare` and the variables in [Authenticate in CI and containers](/working-with-autohand-code/headless-mode#ci-authentication):

```yaml
# GitHub Actions with a narrow tool policy
- name: Autohand Fix
  env:
    AUTOHAND_PROVIDER: autohandai
    AUTOHAND_API_KEY: ${{ secrets.AUTOHAND_API_KEY }}
    AUTOHAND_AI_API_KEY: ${{ secrets.AUTOHAND_API_KEY }}
  run: |
    autohand --bare --unrestricted \
      --disallowed-tools "delete_path" \
      -p "Fix the failing tests in src/api/"
```

## Local model privacy

You can run Autohand with a local model so that prompts and code context go to a model server you run instead of a cloud provider. This suits codebases with strict data residency rules. Telemetry, settings sync and sharing are controlled separately; see [Enterprise Security](/guides/enterprise-security#data-handling).

### Using Ollama

Run a model locally with Ollama and point Autohand at it:

```bash
# Pull and start a model
ollama pull deepseek-coder:33b

# Point Autohand to the local model
AUTOHAND_PROVIDER=ollama \
autohand --model deepseek-coder:33b \
  -p "Refactor the authentication middleware"
```

### Using llama.cpp

For maximum control over the inference stack:

```bash
# Start llama.cpp server
./llama-server -m models/codellama-34b.Q5_K_M.gguf --port 8080

# Connect Autohand (the llamacpp provider uses http://localhost:8080 by default;
# set llamacpp.baseUrl or llamacpp.port in ~/.autohand/config.json for another address)
AUTOHAND_PROVIDER=llamacpp \
autohand --model codellama-34b \
  -p "Add input validation to the user registration endpoint"
```

### Using MLX on Apple Silicon

Take advantage of Apple's Metal framework for fast local inference on M-series Macs:

```bash
# Install MLX server
pip install mlx-lm

# Start the server
mlx_lm.server --model mlx-community/deepseek-coder-33b-4bit --port 8080

# Connect Autohand (the mlx provider uses http://localhost:8080 by default)
AUTOHAND_PROVIDER=mlx \
autohand --model mlx-community/deepseek-coder-33b-4bit \
  -p "Write tests for the payment processing module"
```

## Team security

When multiple developers use Autohand on the same project, you need consistent policies. Configuration files checked into the repository ensure that everyone operates under the same security rules.

### Shared permission policies

Commit your security configuration to the repository so every team member inherits it:

```json
// .autohand/config.json (committed to repo)
{
  "permissions": {
    "allowList": [
      "run_command:npm *",
      "run_command:bun *",
      "run_command:git add *",
      "run_command:git commit *",
      "write_file:src/*",
      "write_file:tests/*"
    ],
    "denyList": [
      "run_command:rm -rf *",
      "run_command:git push --force*",
      "run_command:git rebase*",
      "write_file:.env*",
      "write_file:*.pem",
      "write_file:*.key",
      "write_file:config/production.*",
      "write_file:infrastructure/*",
      "delete_path:*"
    ]
  }
}
```

### Protecting company secrets

Use a combination of `.autohandignore` and deny patterns to keep secrets out of the agent's reach:

```bash
# .autohandignore (committed to repo)
# Secrets and credentials
.env
.env.*
config/secrets/
*.pem
*.key

# Internal documentation
docs/internal/
docs/architecture/threat-model.md

# Infrastructure
terraform/*.tfvars
ansible/vault/
```

### Audit logging with hooks

Set up hooks to log every action the agent takes, creating an audit trail for compliance:

```json
// .autohand/config.json (committed to repo)
{
  "hooks": {
    "hooks": [
      {
        "event": "post-tool",
        "async": true,
        "description": "Append every tool call to the audit log",
        "command": "jq -c --arg user \"$(whoami)\" '{timestamp: (now | todate), tool: .tool_name, input: .tool_input, success: .tool_success, user: $user}' >> .autohand/audit.jsonl"
      }
    ]
  }
}
```

The audit log records who ran the agent, what it did, and when. Add `.autohand/audit.jsonl` to your `.gitignore` but ship it to your central logging system for compliance teams.

### Role-based permissions

For larger teams, use environment-specific config files that give different access levels to different roles:

```bash
# Developers: standard permissions
AUTOHAND_CONFIG=.autohand/config.dev.json autohand "Fix the failing tests"

# Senior engineers: expanded permissions
AUTOHAND_CONFIG=.autohand/config.senior.json autohand "Refactor the database layer"

# CI bot: restricted to read-only analysis (runs with --bare on the runner)
AUTOHAND_CONFIG=.autohand/config.ci.json autohand --bare --restricted \
  -p "Review the latest changes"
```

## Security checklist

Use this checklist when setting up Autohand for a new project or team. Each item takes a few minutes and significantly reduces risk.

![Autohand permission system prompting for approval before file operations](/demos/autohand-permissions.gif)

### Initial setup

- Create `.autohand/config.json` with deny patterns for dangerous operations
- Create `.autohandignore` to exclude secrets, keys, and internal docs
- Commit both files to the repository
- Store API keys in environment variables, never in config files

### Daily usage

- Use interactive mode (the default) for most work
- Use `--restricted` for code review and analysis
- Use `--dry-run` before running `--unrestricted`
- Review the agent's plan before confirming batch operations

### CI/CD pipelines

- Run Autohand in command mode with `--bare -p` in CI environments, with `AUTOHAND_PROVIDER`, `AUTOHAND_API_KEY`, and `AUTOHAND_AI_API_KEY` set
- Default to `--restricted` for review and analysis jobs
- Run the agent on a disposable runner or in a container when it needs write access in CI
- Store `AUTOHAND_API_KEY` as a CI secret, not in the workflow file
- Set timeouts on all Autohand steps to prevent hanging jobs

### Team rollout

- Document your team's Autohand security policy
- Set up audit logging with hooks
- Ship audit logs to your central logging platform
- Review and update deny patterns quarterly
- Test your protections by trying to access blocked resources

### Enterprise environments

- Evaluate local model deployment for regulated environments
- Configure network-level controls for cloud API access
- Set up role-based permission configs for different team tiers
- Integrate audit logs with your SIEM or compliance platform
- Include Autohand configuration in your security review process

<AcademyCta course="deploying-autohand-with-confidence" title="Deploying Autohand with confidence" blurb="Plan a rollout, write a shared permission policy, and make informed privacy choices." />

## Next steps

- [CI/CD Automation](/guides/ci-cd-automation) - Set up Autohand in your build pipelines
- [Hooks Reference](/working-with-autohand-code/hooks) - Full documentation on hook configuration
- [YOLO Mode](/working-with-autohand-code/yolo-mode) - Detailed reference for unrestricted operation
- [Configuration](/working-with-autohand-code/configuration) - All configuration options explained
- [Enterprise Security](/guides/enterprise-security) - Advanced deployment and compliance
