> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rafter.so/llms.txt
> Use this file to discover all available pages before exploring further.

# Safe Command Execution

> Execute shell commands with security validation and risk assessment

# Safe Command Execution

Rafter validates shell commands before execution to prevent dangerous operations.

## Quick Start

Execute a command with security checks:

```bash theme={null}
rafter agent exec "npm install"
```

## How It Works

When you run `rafter agent exec`, Rafter:

1. **Evaluates the command** against security policies
2. **Scans staged files** (for git commands)
3. **Assesses risk level** (low/medium/high/critical)
4. **Blocks or requires approval** based on risk
5. **Logs the execution** to audit log

## Risk Levels

<AccordionGroup>
  <Accordion title="🔴 Critical (Blocked)">
    Commands that can cause catastrophic damage:

    * `rm -rf /` - Delete entire filesystem
    * `:(){ :|:& };:` - Fork bomb
    * `dd if=/dev/zero of=/dev/sda` - Wipe disk
    * `mkfs.*` - Format filesystems
    * `> /dev/sda` - Overwrite disk

    **These are always blocked**, even with `--force`.
  </Accordion>

  <Accordion title="🟠 High (Requires Approval)">
    Commands with significant risk:

    * `rm -rf <directory>` - Recursive deletion
    * `sudo rm` - Delete with elevated privileges
    * `chmod 777` - Insecure permissions
    * `curl ... | sh` - Pipe to shell
    * `git push --force` - Force push
    * `npm publish` - Publish packages
    * `docker system prune` - Delete Docker data

    **Requires user approval** unless `--force` flag is used.
  </Accordion>

  <Accordion title="🟡 Medium (Context-Dependent)">
    Commands that need elevated privileges:

    * `sudo` - Any sudo command
    * `chmod` - Change permissions
    * `kill -9` - Force kill processes
    * `systemctl` - System service management

    **Moderate risk level**: Requires approval, allowed in minimal mode.
  </Accordion>

  <Accordion title="🟢 Low (Allowed)">
    Standard commands with minimal risk:

    * `npm install` - Install packages
    * `git commit` - Commit changes
    * `ls`, `cat`, `grep` - Read operations
    * `echo`, `touch` - Basic file operations

    **Allowed immediately** across all risk levels.
  </Accordion>
</AccordionGroup>

## Usage Examples

### Safe Command

Executes immediately:

```bash theme={null}
rafter agent exec "npm install express"
```

### Git Commit with Auto-Scan

Scans staged files before committing:

```bash theme={null}
rafter agent exec "git commit -m 'Add authentication'"
```

If secrets are detected in staged files, the commit is blocked:

```
⚠️  Secrets detected in staged files!

Found 2 secret(s) in 1 file(s)

Run 'rafter secrets' for details.
```

> **Note:** `rafter agent scan` still works but is deprecated — it will be removed in a future major version.

### High-Risk Command

Requires approval:

```bash theme={null}
rafter agent exec "sudo rm /var/log/old-logs/*.log"
```

You'll see:

```
⚠️  Command requires approval

Risk Level: HIGH
Command: sudo rm /var/log/old-logs/*.log
Reason: Matches approval pattern: sudo rm

Approve this command? (yes/no):
```

### Force Execution

Skip approval with `--force` (logged in audit):

```bash theme={null}
rafter agent exec "sudo systemctl restart nginx" --force
```

<Warning>
  The `--force` flag skips approval but is **logged in the audit trail**. Use responsibly.
</Warning>

### Skip File Scanning

Skip pre-execution scanning for git commands:

```bash theme={null}
rafter agent exec "git commit -m 'Fix typo'" --skip-scan
```

## Command Policies

Configure how Rafter handles commands:

### Policy Modes

<CodeGroup>
  ```bash Approve Dangerous (Default) theme={null}
  # Requires approval for high/critical commands
  rafter agent config set agent.commandPolicy.mode approve-dangerous
  ```

  ```bash Deny List theme={null}
  # Block specific patterns, allow everything else
  rafter agent config set agent.commandPolicy.mode deny-list
  ```

  ```bash Allow All theme={null}
  # Allow all commands (not recommended)
  rafter agent config set agent.commandPolicy.mode allow-all
  ```
</CodeGroup>

### Custom Blocked Patterns

Add patterns to always block:

```bash theme={null}
# View current blocked patterns
rafter agent config get agent.commandPolicy.blockedPatterns

# Add custom pattern (requires manual config edit)
# Edit ~/.rafter/config.json:
{
  "agent": {
    "commandPolicy": {
      "blockedPatterns": [
        "rm -rf /",
        "custom-dangerous-command"
      ]
    }
  }
}
```

### Custom Approval Patterns

Patterns requiring approval:

```json theme={null}
{
  "agent": {
    "commandPolicy": {
      "requireApproval": [
        "rm -rf",
        "sudo rm",
        "git push --force",
        "npm publish"
      ]
    }
  }
}
```

## Audit Logging

All command executions are logged:

```bash theme={null}
# View command executions
rafter agent audit --event command_intercepted

# View blocked commands
rafter agent audit --event command_intercepted | grep BLOCKED

# View overrides
rafter agent audit --event policy_override
```

Audit entries include:

* Timestamp
* Command executed
* Risk level
* Action taken (allowed/blocked/overridden)
* User justification (for overrides)

## Integration with Agents

### OpenClaw

When integrated with OpenClaw, commands are automatically routed through Rafter:

```
User: "Commit the changes"
OpenClaw: rafter agent exec "git commit -m '...'"
Rafter: Evaluates command risk → Scans staged files for secrets → Allows if clean
```

### Claude Code

Claude Code integration uses PreToolUse hooks to intercept commands before execution, plus MCP tools for agent-initiated scans. See [Claude Code Integration](/guides/agent-security/claude-code-integration) for setup, and [MCP Integration](/guides/agent-security/mcp-integration) for the MCP server.

## Exit Codes

Rafter uses standard exit codes:

* `0` - Success
* `1` - Command blocked or execution failed

Use in scripts:

```bash theme={null}
if rafter agent exec "dangerous-command"; then
    echo "Command succeeded"
else
    echo "Command blocked or failed"
fi
```

## Best Practices

<Card title="Recommended Practices" icon="list-check">
  1. **Always use for git commits**: Evaluates risk and scans staged files
  2. **Never bypass with `--force` in production**: Use only when necessary
  3. **Review audit logs**: Check `rafter agent audit` after suspicious activity
  4. **Configure policies**: Adjust `commandPolicy.mode` for your environment
  5. **Test in development**: Ensure policies work before deploying to agents
</Card>

## Advanced Configuration

### Risk Level vs Policy Mode

<Card title="Understanding the Difference">
  * **Risk Level** (`agent.riskLevel`): Controls overall security stance
  * **Policy Mode** (`agent.commandPolicy.mode`): Controls specific command handling

  Example:

  * `riskLevel: aggressive` + `mode: approve-dangerous` = Very secure
  * `riskLevel: minimal` + `mode: allow-all` = Permissive
</Card>

### Custom Risk Assessment

Future feature: Define custom risk patterns and severity levels.

## Troubleshooting

### Command Incorrectly Blocked

If a safe command is blocked:

1. Check current policy:
   ```bash theme={null}
   rafter agent config get agent.commandPolicy
   ```

2. Switch to a more permissive mode:
   ```bash theme={null}
   rafter agent config set agent.commandPolicy.mode allow-all
   ```

3. Report false positive: [rafter-cli/issues](https://github.com/raftersecurity/rafter-cli/issues)

### Secrets Not Detected

If secrets aren't caught during git commits:

1. Ensure scanning is enabled (default):
   ```bash theme={null}
   rafter agent exec "git commit -m 'message'"
   # (without --skip-scan)
   ```

2. Test scanner separately:
   ```bash theme={null}
   rafter secrets
   ```

## Next Steps

<CardGroup cols={2}>
  <Card title="OpenClaw Integration" icon="robot" href="/guides/agent-security/openclaw-integration">
    Set up with OpenClaw agents
  </Card>

  <Card title="Command Reference" icon="book" href="/guides/agent-security/reference">
    Complete CLI command reference
  </Card>
</CardGroup>
