README
¶
agent-command-guard
An AST- and path-aware PreToolUse guard for shell and direct file operations
proposed by coding agents.
It parses POSIX shell input with
mvdan.cc/sh and native Windows input with the
PowerShell parser. It walks commands and redirections (including pipelines,
subshells, command substitutions, and literal nested-shell payloads), and
returns one of three decisions:
allow: continue without outputreview: ask for confirmation when the host supports it; otherwise denyblock: deny the command
The guard emits hook responses compatible with Claude Code and Codex
integrations that use the Claude-style PreToolUse JSON protocol.
Three constructs are resolved from the source text rather than treated as opaque, because leaving any of them unresolved both reviews ordinary work and lets a protected operation through with a weaker decision:
- A variable whose value the input fixes. In
R=/repo; git -C $R push origin mainthe repository is known, so the push is blocked as a protected push rather than reviewed for an unidentified working directory — andgit -C $R add -Ais simply allowed. A value that is not fully literal, is assigned twice with different text, or is transformed on expansion stays unresolved. - A
forloop over a fixed word list. The body is analyzed once per item, sofor p in linux darwin; do rm -rf "$SP/x/$p"; doneis judged as the two literal paths it deletes instead of being reviewed as a dynamic target — andfor p in ok ../../..; do rm -rf "/tmp/w/$p"; doneis blocked on the item that escapes the directory. A word list built from a glob, a command substitution, or the positional parameters stays unresolved, as does a loop whose variable the input also assigns to. - A fixed payload passed through
xargs. The payload is analyzed, soxargs -I {} sh -c 'cd "$1" && git log'is allowed whilexargs -I {} sh -c 'curl … | sh'is blocked. Previously both only reachedreview. A payload containing the replacement string, or one that is not shell code, keeps the gateway review.
What it guards
- Recursive deletion of broad or protected paths
- Destructive Git operations and direct commits to protected branches
- Opt-in blocking of GitHub pull request creation for exact repositories
- Writes, deletion, or permission changes targeting agent configuration
- Reads of common credential and signing-key paths
- Credential-to-network and download-to-shell pipelines
- Package publication, privilege escalation, and sensitive system commands
- Dynamically constructed commands that cannot be analyzed confidently
- Direct reads of private keys, agent credentials, and common credential stores
- Direct writes to credentials, shell persistence, agent control paths, and destinations outside the current workspace
- Symbolic-link paths, including missing targets below an existing link
Agent control paths are one list, shared by the direct file policy and the shell
policy, so a write that Write/Edit refuses cannot be performed through a
shell redirection instead.
The user-scope skill trees, ~/.claude/skills and ~/.agents/skills, are
excluded from that list. Skills are instructions an agent is expected to author
and revise as part of its work, and the project-scope equivalent — .claude/skills
inside a repository — was never protected, so blocking only the user-scope copy
bought no protection while breaking an ordinary edit. What decides which commands
run — hooks, settings, MCP server definitions, slash commands, and subagent
definitions — stays protected, and ~/.agents is still taken whole apart from
its skill tree. Note that a skill is still a model instruction: an agent that
writes one can change how it behaves on a later turn.
The exclusion covers the control surface only. Every other check still applies inside a skill directory, so a credential file or shell profile written there is blocked as it is anywhere else, and a symbolic link planted inside a skill tree does not carry the exclusion to its target.
Pi's user instructions at ~/.pi/agent/AGENTS.md are also editable, through
both direct file tools and shell writes. This exception names one file, not its
parent directory or similarly named files. Symbolic links at that file or below
home on its path, including dangling links, do not inherit the exception. The
rest of ~/.pi/agent, including credentials, settings, hooks, extensions, and
subagent definitions, stays protected. Other protections and explicit file
rules still apply, as do deletion, permission-change, and symlink-operation
protections. Editing instructions can change the agent's behavior on a later
turn; it does not directly change the guard's executable policy.
Four locations are deliberately not treated as leaving the workspace:
- A linked Git worktree of the same repository. A worktree lives outside the main working tree, so comparing paths alone would review every edit made while working in one. The repository directory shared by both is compared instead.
- The agent memory store at
~/.claude/projects/<project>/memory. An agent is expected to record and prune its own memories there, and the directory holds no configuration that could weaken this guard. The surrounding checks still apply, so a credential file inside it is still blocked, and a path elsewhere under~/.claude/projectsremains protected. - The skill trees described above, for the same reason: an agent maintains them wherever it happens to be running.
- The exact Pi instruction file described above, subject to the same link checks.
The policy is intentionally conservative, but it is not a sandbox. It cannot prove that an allowed command is harmless, and a process can perform actions that are not visible in its command-line syntax. Use it as one layer alongside OS permissions, agent sandboxing, and repository protections.
Install
Prebuilt archives for macOS, Linux, and Windows are attached to each
GitHub release.
Linux archives are also the correct choice for WSL2; install the Linux binary
inside the WSL distribution rather than invoking the Windows executable from
WSL. Each release includes SHA256SUMS and a GitHub artifact attestation.
The archive names identify the operating system and architecture, for example:
agent-command-guard_vX.Y.Z_darwin_arm64.tar.gzagent-command-guard_vX.Y.Z_linux_amd64.tar.gzagent-command-guard_vX.Y.Z_windows_amd64.zip
Verify a downloaded archive against SHA256SUMS. With the GitHub CLI, its
provenance can also be verified:
gh attestation verify <archive> --repo tomatoaiu/agent-command-guard
Go 1.25 or newer is required only when installing from source. This repository pins its development toolchain with mise.
go install github.com/tomatoaiu/agent-command-guard@latest
You can also build from a checkout:
go build -o agent-command-guard .
Check the installed version with agent-command-guard --version.
Usage
The program reads one hook event as JSON from standard input. Shell commands
are read from tool_input.command or tool_input.cmd. Read, Edit, and
Write paths are read from tool_input.file_path or tool_input.path.
printf '%s\n' '{"tool_input":{"command":"git clean -fd"},"cwd":"/tmp"}' | \
agent-command-guard --explain
printf '%s\n' '{"tool_name":"Read","tool_input":{"file_path":".env"},"cwd":"/tmp/project"}' | \
agent-command-guard --explain
For a multi-file apply_patch call, the host adapter must extract every target
path and submit one Write event per path. A file tool with a missing, invalid,
or control-character-containing path is blocked rather than silently allowed.
Use --agent claude or --agent codex for hook output. A review result maps
to ask for Claude and to deny for Codex because the Codex hook path does
not currently provide an interactive review response.
Shell syntax is selected automatically: powershell on native Windows and
posix on other operating systems, including WSL2. Override detection with
--shell posix or --shell powershell when necessary. PowerShell parsing uses
pwsh when installed and otherwise uses Windows PowerShell.
Codex
Codex discovers user hooks at ~/.codex/hooks.json. Register an adapter for
shell and direct file tools. The adapter should normalize every apply_patch
target to a Write event before invoking the guard:
{
"hooks": {
"PreToolUse": [
{
"matcher": "^(Bash|Read|Edit|Write|NotebookEdit|apply_patch)$",
"hooks": [
{
"type": "command",
"command": "agent-command-guard --agent codex"
}
]
}
]
}
}
Review and trust a newly added or changed hook with /hooks in Codex. Codex
does not support permissionDecision: "ask" for PreToolUse, so a review
result is deliberately emitted as deny.
On native Windows, Codex still exposes shell calls to hooks with the canonical
Bash matcher. A hooks file shared across operating systems can use the
commandWindows hook override:
{
"hooks": {
"PreToolUse": [
{
"matcher": "^Bash$",
"hooks": [
{
"type": "command",
"command": "agent-command-guard --agent codex --shell posix",
"commandWindows": "C:\\Users\\YOU\\bin\\agent-command-guard.exe --agent codex --shell powershell"
}
]
}
]
}
}
For WSL2, keep the repository, Codex installation, guard binary, and hook configuration inside WSL and use the ordinary POSIX command shown above.
To skip Codex's separate approval prompt for a narrowly verified temporary
directory cleanup, register the same binary for PermissionRequest:
{
"hooks": {
"PermissionRequest": [
{
"matcher": "^Bash$",
"hooks": [
{
"type": "command",
"command": "agent-command-guard --permission-request"
}
]
}
]
}
}
This mode approves only a single literal recursive rm invocation whose
existing directory targets are direct children of the operating system's
temporary directory. Variables, globs, command chains, symbolic links,
repository/worktree roots, missing targets, and temporary roots themselves do
not receive an approval decision and continue through Codex's normal prompt.
The fast path is POSIX-only; PowerShell Remove-Item requests always continue
through Codex's normal approval flow.
Claude Code
Register an adapter in Claude Code's PreToolUse hooks for shell and direct
file tools:
#!/bin/sh
exec agent-command-guard --agent claude
For example, the relevant portion of ~/.claude/settings.json is:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Read|Edit|Write|NotebookEdit",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/agent-command-guard.sh"
}
]
}
]
}
}
Claude Code supports the interactive ask decision used for review results.
Both adapters load the same policy file automatically, so no hook changes are
needed when rules are added or edited. Claude Code on native Windows
uses Git Bash,
so pass --shell posix; Claude Code inside WSL also uses the POSIX mode.
Output language
Guard messages are emitted in English by default. Set the output language to Japanese in the TOML configuration when desired:
[output]
language = "ja"
Supported values are en and ja. The setting applies to --explain output
and to both Codex and Claude Code hook responses. Stable rule IDs and decision
values remain language-independent.
Custom rules
The guard automatically loads agent-command-guard/config.toml from the OS
user configuration directory (~/.config on Linux,
~/Library/Application Support on macOS, and %AppData% on Windows). Use
--config /path/to/config.toml to load a specific file. A missing default file
is ignored, while a missing or invalid explicitly selected file is an error.
Shell command rules
Command rules are checked from top to bottom before the built-in shell policy.
The direct file policy cannot be weakened by a command rule. The first matching
command rule wins. command is a Go regular expression matched against the
entire trimmed shell input. directories contains cwd roots; descendants also
match. Relative directory paths are resolved from the configuration file's
directory, and ~/ is supported.
# Allow one exact command everywhere. Regex metacharacters must be escaped when
# needed; single-quoted TOML strings are convenient for regular expressions.
[[rules]]
id = "allow-known-git-clean"
action = "allow"
command = 'git clean -fd'
# Skip all built-in checks in a disposable workspace and its descendants.
[[rules]]
id = "ignore-scratch-workspace"
action = "allow"
directories = ["~/src/scratch"]
# Rules can combine both conditions and can also force review or block.
[[rules]]
id = "review-deploy-in-production"
action = "review"
command = 'deploy .*'
directories = ["~/src/production"]
An allow command rule bypasses the built-in shell policy, so keep broad
rules limited to locations where that behavior is intentional. Because the
pattern is matched against the whole shell input before it is parsed, a rule
written for one command also covers anything composed with it: a rule for
python3 -c ... matches python3 -c ... && rm -rf ~ as well. To silence one
specific finding without giving up the rest of the analysis, use a suppression
instead.
Direct file rules
File rules scope a decision to explicitly listed direct operations and target
roots. directories is optional and restricts the caller's cwd. Descendants
of each root or directory match. The first matching file rule wins.
[[file_rules]]
id = "allow-trusted-dotfiles-source"
action = "allow"
operations = ["edit", "write"]
roots = ["~/src/dotfiles"]
# Optional: only apply when the agent is working in these directories.
directories = ["~/src/projects"]
Operations are read, edit, and write. Tool aliases such as MultiEdit
and NotebookEdit map to edit; apply_patch maps to write. Operations not
listed in a rule retain the built-in decision.
File rules are evaluated only after invalid inputs and built-in credential,
key, persistence, agent-control, and guard self-protection checks. Those checks
are non-overridable. An allow file rule can suppress the contextual
outside-workspace-write review, but cannot suppress a built-in block or a
credential or persistence review. A review or block rule can make an
otherwise allowed operation stricter.
Configured target roots, target paths, caller directories, and cwd values are
normalized. A rule matches only when both the normalized path and the path with
its longest existing symbolic-link prefix resolved remain inside the configured
root. A symlink escape therefore does not inherit an allow decision. Relative
roots and directories are resolved from the configuration file's directory;
~/ is supported.
Available actions for both rule types are allow, review, and block. Rule
IDs must be unique across command and file rules. Omitted command IDs are
generated as custom-rule-N; omitted file IDs use custom-file-rule-N.
Suppressing a built-in finding
A suppression removes one built-in finding instead of bypassing the policy.
The shell input is still parsed, so every other command in the same input keeps
its decision. This is what an allow command rule cannot express, because a
regular expression cannot tell a separator apart from the same character inside
a quoted argument.
[[suppress]]
rule_id = "inline-interpreter-code"
commands = ["python3", "node"]
directories = ["~/src"]
rule_id is required. commands restricts the entry to the named commands and
matches every command reported by that rule when omitted. directories
restricts the caller's cwd, and descendants match. Relative directories are
resolved from the configuration file's directory, and ~/ is supported.
With the entry above:
| Input | Result |
|---|---|
python3 -c "..." |
allowed |
python3 -c "..." && sudo rm -rf /etc |
still blocked on sudo |
python3 -c "..." ; sudo rm -rf /etc |
still blocked on sudo |
ruby -e "..." |
unchanged, because ruby is not listed |
python3 -c "open('~/.claude/settings.json','w')" |
still blocked |
That last row is the reason inline code is read even when the review is
suppressed. The guard cannot parse a Python or JavaScript program, so a write it
performs is invisible; without reading the payload, suppressing this one review
would have been a way past every path protection in the policy. A payload naming
a protected or credential path is refused as protected-interpreter-payload,
which is a block and therefore not suppressible.
Only findings that are context dependent enough to be a false positive in a
trusted workspace can be suppressed. inline-interpreter-code is currently the
only such rule. Credential, persistence, agent-control, and guard
self-protection findings are not suppressible, matching the guarantee that file
rules already provide, and an unknown or non-suppressible rule_id is a
configuration error rather than a silently ignored entry. A block decision is
never suppressed.
Trusting reviewed osascript files
A reviewed AppleScript file can be allowed without bypassing analysis of the rest of the shell input. Configure only the exact active files the agent may execute but must not edit:
[macos]
trusted_osascript_files = [
"~/.claude/scripts/mail/search-by-subject.applescript",
"~/.claude/scripts/calendar/get-today-events.applescript",
]
A literal path to one of these regular files is allowed through osascript.
Inline -e programs, stdin programs, alternate -l interpreters, dynamic
script paths, and all other files remain blocked. Commands composed around the
invocation are still analyzed, so a dangerous command after the script is not
hidden by the exception.
The configured files become protected write targets for both shell and direct
file operations. Keep the editable source elsewhere, review it, and deploy it
through a managed path such as chezmoi. Relative paths are resolved from the
configuration file's directory, and ~/ is supported.
Blocking GitHub pull request creation
Pull request creation can be blocked for exact GitHub repository identities.
The guard does not query repository visibility; the repository list remains in
the user's configuration and applies equally to private and public repositories.
host defaults to github.com and supports GitHub Enterprise hosts.
[[github.pull_request_create_blocks]]
repository = "example/internal-tools"
[[github.pull_request_create_blocks]]
host = "git.example.test"
repository = "example/service"
Host, owner, and repository matching is exact and case-insensitive. The guard blocks these GitHub CLI creation paths:
gh pr createand itsgh pr newaliasgh agent-task createand theagent,agents, andagent-tasksaliases, because an agent task produces a pull requestgh stack submit- a mutating
gh api repos/OWNER/REPOSITORY/pullsREST request - a GraphQL mutation containing
createPullRequest, whether inline or loaded from a regular query file
The target is resolved, in order, from -R/--repo, inherited or literal
GH_REPO and GH_HOST assignments, and Git remotes in the current checkout.
Literal cd, env --chdir, and PowerShell location changes are tracked. This
makes the policy follow a repository into linked worktrees without putting local
checkout paths in the configuration. If any possible remote matches a configured
identity, creation is blocked. A direct creation command whose target is
unresolved also fails closed while the block list is nonempty.
Read-only PR commands, recognized help invocations, gh extension list, and
supported --dry-run modes remain allowed. This policy is independent of the
Git branch policy: it does not block local git merge or git push, and it
does not change a configured protected-branch exception.
The policy is deliberately conservative around indirection. An unknown gh
alias or custom root command is blocked when its resolved checkout is
configured—or cannot be resolved—because its expansion may create a pull
request. gh extension exec is treated the same way. Changes to a remote or
default repository before a creation command make that target unresolved. A
mutating gh api call with a dynamic endpoint requires review. A GraphQL
query supplied as query=@file is inspected when the file is regular, valid
UTF-8, and no larger than 1 MiB; an unreadable or otherwise unresolved query
also requires review and is therefore denied by hosts without interactive
review. GraphQL's createPullRequest identifies a repository by node ID,
which cannot be matched to OWNER/REPOSITORY offline, so an explicit mutation
is blocked whenever at least one repository block is configured.
This remains command-line policy rather than an authorization boundary. A
browser, MCP tool, custom executable, or allowed interpreter can create a pull
request without exposing that action as recognizable gh syntax. For strict
enforcement, also use a separate agent credential without Pull requests: write
while retaining the Git transport permissions needed for direct pushes.
Protected Git branches
main, master, and the repository's origin/HEAD branch are protected by
default. Add repository-specific branch names or glob patterns in the same
configuration file:
[git]
protected_branches = ["develop", "release/*"]
The built-in Git policy allows ordinary pushes and local or remote deletion of
unprotected branches. It blocks pushes, direct commits, and deletion targeting
protected branches. A plain force push remains review on unprotected
branches, while --force-with-lease is allowed. Remote tag deletion and a
remote deletion whose target cannot be determined remain review.
For a repository that intentionally commits and pushes directly to a protected
branch, use a structured exception instead of an allow command regex. Each
entry is one exact repository/branch policy cell; remote is required when
operations contains push:
[[git.protected_branch_exceptions]]
repository = "~/.local/share/chezmoi"
branch = "main"
operations = ["commit", "push"]
remote = "origin"
Repository paths support ~/ and paths relative to the configuration file.
The guard compares the configured path with Git's canonical top-level working
tree, so a subdirectory and git -C work while another checkout or worktree
does not inherit the exception. Existing symbolic links are resolved when the
configuration is loaded; a link created afterward fails closed.
On POSIX shells, each direct, literal Git invocation is checked independently. Composition, pipelines, and redirections therefore keep the exception only for the Git operation that matches it, while every neighboring command and write target keeps its normal policy:
git commit -m "wip $(date +%F)" 2>&1 | tail -5
git push origin main && git status
A quoted command substitution used as the single value of -m is accepted
because it cannot turn into another Git option; the command inside the
substitution is still analyzed independently. An unquoted dynamic argument,
--no-verify (including abbreviated forms), wrappers, subshells, prefix
assignments, environment overrides, and Git configuration overrides other than
exactly -c commit.gpgsign=false do not receive the exception. A literal
cd /path && git ... is followed on its success path, so
the branch is checked in the selected checkout rather than the caller's
checkout. Ambiguous working-directory changes remain review.
Protected pushes must name the configured remote and the same source and target
branch explicitly, for example git push origin main, main:main, or the
equivalent full refs/heads/ form. Bare pushes, push options, force variants,
deletion, bulk or mirror pushes, multiple refspecs, and HEAD:main remain
blocked. A wrong repository, branch, remote, or unsafe Git argument receives the
usual protected-branch rule; an unsafe neighboring command can still raise the
overall result to block.
PowerShell structured exceptions remain limited to one standalone invocation;
compound, pipeline, redirection, and indirect forms retain their actionable
protected-branch-exception-* diagnostics.
Development
mise install
mise run check
mise run fuzz
Commits merged to main are collected by Release Please. Merge its generated
release pull request to publish the corresponding vX.Y.Z GitHub release and
the six platform archives. Use Conventional Commit titles so the next version
and changelog can be derived automatically.
License
MIT
Documentation
¶
There is no documentation for this package.
Source Files
¶
- agent_control.go
- analyzer.go
- assignments.go
- config.go
- exposure.go
- file_modes.go
- file_policy.go
- file_rule.go
- git_command.go
- git_policy.go
- github_api.go
- github_config.go
- github_context.go
- github_policy.go
- i18n.go
- interpreter_payload.go
- main.go
- osascript.go
- posix_context.go
- powershell.go
- publishing.go
- readonly_commands.go
- sensitive_trees.go
- shell.go
- suppress.go
- system_destruction.go
- version.go
- workspace.go