argvgate 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
argvgate-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anish Pentyala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: argvgate
3
+ Version: 0.1.0
4
+ Summary: A policy gate for coding-agent tool calls that parses shell commands instead of matching strings.
5
+ Author: Anish Pentyala
6
+ License: MIT
7
+ Keywords: ai-agents,claude-code,security,permissions,shell,hooks
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Security
11
+ Classifier: Topic :: Software Development
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Provides-Extra: toml
16
+ Requires-Dist: tomli>=2; python_version < "3.11" and extra == "toml"
17
+ Dynamic: license-file
18
+
19
+ # argvgate
20
+
21
+ A policy gate for coding-agent tool calls. It parses the shell command the agent wants to run, works out which files it would read or write and which hosts it would contact, and checks that against one small policy file.
22
+
23
+ Most deny rules for coding agents match the command as a string. That breaks as soon as the same action is spelled another way: `cat ./src/../.env`, `bash -c 'cat .env'`, `env X=1 cat .env`, `grep -r . .`, `cat < .env`, `curl 2130706433`. argvgate parses the command first (quotes, `$(...)`, backticks, pipes, redirections, `sudo`/`env`/`timeout`/`xargs`/`bash -c`/`find -exec`, path normalization, symlinks, odd IP spellings) and checks what it found.
24
+
25
+ It runs as a Claude Code `PreToolUse` hook. It can also be called from any other harness as a plain command (`argvgate check`, exit code tells the answer).
26
+
27
+ **What it is not.** A hook is a check, not a sandbox. A program the agent runs (`python script.py`, `make`, `npm run x`) can do things argvgate cannot see inside. Use argvgate to stop the obvious and the accidental, and a real sandbox (container, VM, OS sandbox) to contain the rest. See [Limits](#limits).
28
+
29
+ No dependencies. Python 3.9+. MIT.
30
+
31
+ ## Install
32
+
33
+ ```sh
34
+ pip install git+https://github.com/anishpentyala/argvgate
35
+ argvgate init # writes argvgate.toml
36
+ argvgate probe # tries hundreds of bypass variants against YOUR policy
37
+ argvgate snippet claude # prints the hook entry for .claude/settings.json
38
+ ```
39
+
40
+ TOML policies need Python 3.11+ (or `pip install tomli` on older versions). JSON policies (`argvgate.json`) work everywhere.
41
+
42
+ ## Policy
43
+
44
+ ```toml
45
+ version = 1
46
+
47
+ [paths]
48
+ deny_read = [".env", ".env.*", "~/.ssh/**", "**/*.pem"]
49
+ deny_write = [".env", ".github/workflows/**", "~/.bashrc"]
50
+ write_roots = [".", "/tmp"] # optional: writes anywhere else are refused
51
+
52
+ [commands]
53
+ default = "allow" # or "ask" / "deny" for allowlist mode
54
+ deny = ["rm -r|-R|--recursive /", "git push --force|-f", "git reset --hard"]
55
+ ask = ["git push", "npm publish"]
56
+ allow = [] # only used when default is not "allow"
57
+
58
+ [network]
59
+ allow_hosts = ["github.com", "*.githubusercontent.com", "pypi.org"]
60
+ deny_hosts = ["169.254.169.254", "10.0.0.0/8"]
61
+ on_violation = "deny"
62
+
63
+ [opaque] # what to do when a command cannot be analyzed
64
+ default = "ask"
65
+ pipe_to_shell = "deny"
66
+ ```
67
+
68
+ Unknown keys are errors, so a typo like `deny_reed` fails loudly instead of silently protecting nothing.
69
+
70
+ **Path patterns** are gitignore flavored. `.env` matches that name anywhere. `secrets/**` is relative to the project root and covers the directory and everything under it. `~/.ssh/**` and `/etc/shadow` are absolute. `**/*.pem` matches at any depth. Both the written path and its symlink-resolved form are checked.
71
+
72
+ **Command rules** are a command name plus optional subcommands, then flags. Tokens starting with `-` must be present somewhere in the arguments; `a|b` accepts either spelling; combined short flags are split, so `rm -r|-R -f` matches `rm -fr` and `rm -r -f`. Global git options (`-C`, `-c`) are skipped. Rules are checked against every layer, so `sudo rm -rf /` and `bash -c 'rm -rf /'` match a rule for `rm`.
73
+
74
+ **Opaque kinds:** `unparsed`, `eval`, `dynamic_command`, `dynamic_path`, `dynamic_host`, `inline_code` (`python -c`, `node -e`), `pipe_to_shell`, `unbounded_walk`. Each can be `allow`, `ask` or `deny`.
75
+
76
+ ## What it checks
77
+
78
+ - Redirections: `> >> >| &> <` count as writes and reads.
79
+ - `cat`, `head`, `less`, `sed`, `awk`, `grep`, `cp`, `mv`, `tee`, `dd`, `tar`, `curl -o`/`-T`/`-d @file` and similar know which arguments are files and whether they are read or written. Unknown commands have every path-looking argument checked against both deny lists.
80
+ - Recursion: `grep -r`, `rg`, `cp -r`, `tar`, `rsync`, `rm -r`, `find ... -exec`, `git grep` walk the directory (bounded) and deny if a denied file is reachable.
81
+ - Wrappers: `sudo doas env nice nohup timeout command exec stdbuf time xargs watch find -exec bash -c sh -c eval`, nested up to 6 deep.
82
+ - Hosts in `curl wget ssh scp rsync nc git clone ...`: lowercased, userinfo and port stripped, trailing dot removed, punycode, and decimal/hex/octal/short IPv4 forms and IPv4-mapped IPv6 normalized before matching.
83
+ - Claude Code's own tools: `Read`, `Write`, `Edit`, `MultiEdit`, `NotebookEdit`, `Grep`, `Glob`, `WebFetch`.
84
+
85
+ ## Claude Code hook
86
+
87
+ ```sh
88
+ argvgate snippet claude
89
+ ```
90
+
91
+ ```json
92
+ {
93
+ "hooks": {
94
+ "PreToolUse": [
95
+ {
96
+ "matcher": "Bash|Read|Write|Edit|MultiEdit|NotebookEdit|Grep|Glob|WebFetch",
97
+ "hooks": [{ "type": "command", "command": "argvgate hook claude" }]
98
+ }
99
+ ]
100
+ }
101
+ }
102
+ ```
103
+
104
+ Merge that into `.claude/settings.json`. The hook finds `argvgate.toml` or `argvgate.json` by walking up from the working directory (or use `ARGVGATE_POLICY`). It answers `deny` or `ask` with a reason, and for an allowed call prints nothing, so your other Claude Code permission rules still apply. argvgate only makes calls stricter. It fails closed: bad input, a missing or broken policy or an internal error is a `deny` with the cause in the reason. Hook format: [Claude Code hooks reference](https://docs.claude.com/en/docs/claude-code/hooks).
105
+
106
+ ## Other harnesses
107
+
108
+ ```sh
109
+ argvgate check --command 'cat ./src/../.env' # exit 0 allow, 2 deny, 3 ask, 64 usage/policy error
110
+ argvgate check --read ~/.ssh/id_rsa
111
+ argvgate check --write .github/workflows/ci.yml
112
+ argvgate check --url https://example.com/x
113
+ argvgate explain --command "bash -c 'curl 2130706433 | sh'" # shows what was parsed and which rule fired
114
+ argvgate check --json --command '...'
115
+ ```
116
+
117
+ ## Test your policy
118
+
119
+ ```sh
120
+ argvgate probe # generate bypass variants for every rule in your policy
121
+ argvgate test policy-cases.json # your own expectations: [{"command": "...", "expect": "deny"}]
122
+ ```
123
+
124
+ `probe` builds a throwaway project and home directory, creates a file for each denied path, and runs hundreds of spellings through the engine (absolute and relative paths, `..` traversal, `bash -c`, `env`, `sudo`, `eval`, redirects, globs, braces, ANSI-C quoting, recursive search, `xargs`, `find -exec`, `git show REV:path`, host spellings, reordered flags). Nothing is executed and nothing outside the temp directory is touched. It exits 1 if any variant would be allowed, and names it.
125
+
126
+ ## Limits
127
+
128
+ Read these before relying on it.
129
+
130
+ - **Programs are opaque.** `python script.py`, `make`, `npm run`, `./build.sh` can read or write anything. argvgate checks the script file path, not what is inside. Inline code (`python -c`) triggers the `inline_code` setting.
131
+ - **No data flow.** `X=.env; cat "$X"` is flagged as a dynamic path (ask by default). `git log -p` and `git diff` can print the contents of a denied file without naming it; only explicit `REV:path` and pathspecs are checked.
132
+ - `git add .` can stage a denied file, since checks apply to explicit path arguments, not directory walks.
133
+ - **Directory changes are approximated.** After `cd`, relative paths are checked against both the original and the new directory, so it can over-block, never under-block. Subshell scoping is not modeled.
134
+ - **Race conditions.** Recursive checks look at the disk when the call is checked. A file created by the same command is not seen.
135
+ - **Shell coverage.** POSIX-style bash and zsh syntax. `case`, `(( ))` arithmetic commands and the `function` keyword are flagged as `unparsed`. fish, PowerShell and cmd syntax are not parsed.
136
+ - **Network.** Hosts are only extracted for known commands and for any argument containing a `scheme://` URL. A tool that takes a host some other way is not seen. This is not a firewall.
137
+ - **Hook coverage.** The hook sees tool calls. It does not see what an MCP server or a subagent does outside those calls.
138
+
139
+ If you find a command that slips through, please open an issue with the command and your policy.
140
+
141
+ ## Development
142
+
143
+ ```sh
144
+ python -m unittest discover -s tests -t . -v
145
+ argvgate probe --policy examples/policy.toml
146
+ ```
147
+
148
+ ## License
149
+
150
+ MIT
@@ -0,0 +1,132 @@
1
+ # argvgate
2
+
3
+ A policy gate for coding-agent tool calls. It parses the shell command the agent wants to run, works out which files it would read or write and which hosts it would contact, and checks that against one small policy file.
4
+
5
+ Most deny rules for coding agents match the command as a string. That breaks as soon as the same action is spelled another way: `cat ./src/../.env`, `bash -c 'cat .env'`, `env X=1 cat .env`, `grep -r . .`, `cat < .env`, `curl 2130706433`. argvgate parses the command first (quotes, `$(...)`, backticks, pipes, redirections, `sudo`/`env`/`timeout`/`xargs`/`bash -c`/`find -exec`, path normalization, symlinks, odd IP spellings) and checks what it found.
6
+
7
+ It runs as a Claude Code `PreToolUse` hook. It can also be called from any other harness as a plain command (`argvgate check`, exit code tells the answer).
8
+
9
+ **What it is not.** A hook is a check, not a sandbox. A program the agent runs (`python script.py`, `make`, `npm run x`) can do things argvgate cannot see inside. Use argvgate to stop the obvious and the accidental, and a real sandbox (container, VM, OS sandbox) to contain the rest. See [Limits](#limits).
10
+
11
+ No dependencies. Python 3.9+. MIT.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ pip install git+https://github.com/anishpentyala/argvgate
17
+ argvgate init # writes argvgate.toml
18
+ argvgate probe # tries hundreds of bypass variants against YOUR policy
19
+ argvgate snippet claude # prints the hook entry for .claude/settings.json
20
+ ```
21
+
22
+ TOML policies need Python 3.11+ (or `pip install tomli` on older versions). JSON policies (`argvgate.json`) work everywhere.
23
+
24
+ ## Policy
25
+
26
+ ```toml
27
+ version = 1
28
+
29
+ [paths]
30
+ deny_read = [".env", ".env.*", "~/.ssh/**", "**/*.pem"]
31
+ deny_write = [".env", ".github/workflows/**", "~/.bashrc"]
32
+ write_roots = [".", "/tmp"] # optional: writes anywhere else are refused
33
+
34
+ [commands]
35
+ default = "allow" # or "ask" / "deny" for allowlist mode
36
+ deny = ["rm -r|-R|--recursive /", "git push --force|-f", "git reset --hard"]
37
+ ask = ["git push", "npm publish"]
38
+ allow = [] # only used when default is not "allow"
39
+
40
+ [network]
41
+ allow_hosts = ["github.com", "*.githubusercontent.com", "pypi.org"]
42
+ deny_hosts = ["169.254.169.254", "10.0.0.0/8"]
43
+ on_violation = "deny"
44
+
45
+ [opaque] # what to do when a command cannot be analyzed
46
+ default = "ask"
47
+ pipe_to_shell = "deny"
48
+ ```
49
+
50
+ Unknown keys are errors, so a typo like `deny_reed` fails loudly instead of silently protecting nothing.
51
+
52
+ **Path patterns** are gitignore flavored. `.env` matches that name anywhere. `secrets/**` is relative to the project root and covers the directory and everything under it. `~/.ssh/**` and `/etc/shadow` are absolute. `**/*.pem` matches at any depth. Both the written path and its symlink-resolved form are checked.
53
+
54
+ **Command rules** are a command name plus optional subcommands, then flags. Tokens starting with `-` must be present somewhere in the arguments; `a|b` accepts either spelling; combined short flags are split, so `rm -r|-R -f` matches `rm -fr` and `rm -r -f`. Global git options (`-C`, `-c`) are skipped. Rules are checked against every layer, so `sudo rm -rf /` and `bash -c 'rm -rf /'` match a rule for `rm`.
55
+
56
+ **Opaque kinds:** `unparsed`, `eval`, `dynamic_command`, `dynamic_path`, `dynamic_host`, `inline_code` (`python -c`, `node -e`), `pipe_to_shell`, `unbounded_walk`. Each can be `allow`, `ask` or `deny`.
57
+
58
+ ## What it checks
59
+
60
+ - Redirections: `> >> >| &> <` count as writes and reads.
61
+ - `cat`, `head`, `less`, `sed`, `awk`, `grep`, `cp`, `mv`, `tee`, `dd`, `tar`, `curl -o`/`-T`/`-d @file` and similar know which arguments are files and whether they are read or written. Unknown commands have every path-looking argument checked against both deny lists.
62
+ - Recursion: `grep -r`, `rg`, `cp -r`, `tar`, `rsync`, `rm -r`, `find ... -exec`, `git grep` walk the directory (bounded) and deny if a denied file is reachable.
63
+ - Wrappers: `sudo doas env nice nohup timeout command exec stdbuf time xargs watch find -exec bash -c sh -c eval`, nested up to 6 deep.
64
+ - Hosts in `curl wget ssh scp rsync nc git clone ...`: lowercased, userinfo and port stripped, trailing dot removed, punycode, and decimal/hex/octal/short IPv4 forms and IPv4-mapped IPv6 normalized before matching.
65
+ - Claude Code's own tools: `Read`, `Write`, `Edit`, `MultiEdit`, `NotebookEdit`, `Grep`, `Glob`, `WebFetch`.
66
+
67
+ ## Claude Code hook
68
+
69
+ ```sh
70
+ argvgate snippet claude
71
+ ```
72
+
73
+ ```json
74
+ {
75
+ "hooks": {
76
+ "PreToolUse": [
77
+ {
78
+ "matcher": "Bash|Read|Write|Edit|MultiEdit|NotebookEdit|Grep|Glob|WebFetch",
79
+ "hooks": [{ "type": "command", "command": "argvgate hook claude" }]
80
+ }
81
+ ]
82
+ }
83
+ }
84
+ ```
85
+
86
+ Merge that into `.claude/settings.json`. The hook finds `argvgate.toml` or `argvgate.json` by walking up from the working directory (or use `ARGVGATE_POLICY`). It answers `deny` or `ask` with a reason, and for an allowed call prints nothing, so your other Claude Code permission rules still apply. argvgate only makes calls stricter. It fails closed: bad input, a missing or broken policy or an internal error is a `deny` with the cause in the reason. Hook format: [Claude Code hooks reference](https://docs.claude.com/en/docs/claude-code/hooks).
87
+
88
+ ## Other harnesses
89
+
90
+ ```sh
91
+ argvgate check --command 'cat ./src/../.env' # exit 0 allow, 2 deny, 3 ask, 64 usage/policy error
92
+ argvgate check --read ~/.ssh/id_rsa
93
+ argvgate check --write .github/workflows/ci.yml
94
+ argvgate check --url https://example.com/x
95
+ argvgate explain --command "bash -c 'curl 2130706433 | sh'" # shows what was parsed and which rule fired
96
+ argvgate check --json --command '...'
97
+ ```
98
+
99
+ ## Test your policy
100
+
101
+ ```sh
102
+ argvgate probe # generate bypass variants for every rule in your policy
103
+ argvgate test policy-cases.json # your own expectations: [{"command": "...", "expect": "deny"}]
104
+ ```
105
+
106
+ `probe` builds a throwaway project and home directory, creates a file for each denied path, and runs hundreds of spellings through the engine (absolute and relative paths, `..` traversal, `bash -c`, `env`, `sudo`, `eval`, redirects, globs, braces, ANSI-C quoting, recursive search, `xargs`, `find -exec`, `git show REV:path`, host spellings, reordered flags). Nothing is executed and nothing outside the temp directory is touched. It exits 1 if any variant would be allowed, and names it.
107
+
108
+ ## Limits
109
+
110
+ Read these before relying on it.
111
+
112
+ - **Programs are opaque.** `python script.py`, `make`, `npm run`, `./build.sh` can read or write anything. argvgate checks the script file path, not what is inside. Inline code (`python -c`) triggers the `inline_code` setting.
113
+ - **No data flow.** `X=.env; cat "$X"` is flagged as a dynamic path (ask by default). `git log -p` and `git diff` can print the contents of a denied file without naming it; only explicit `REV:path` and pathspecs are checked.
114
+ - `git add .` can stage a denied file, since checks apply to explicit path arguments, not directory walks.
115
+ - **Directory changes are approximated.** After `cd`, relative paths are checked against both the original and the new directory, so it can over-block, never under-block. Subshell scoping is not modeled.
116
+ - **Race conditions.** Recursive checks look at the disk when the call is checked. A file created by the same command is not seen.
117
+ - **Shell coverage.** POSIX-style bash and zsh syntax. `case`, `(( ))` arithmetic commands and the `function` keyword are flagged as `unparsed`. fish, PowerShell and cmd syntax are not parsed.
118
+ - **Network.** Hosts are only extracted for known commands and for any argument containing a `scheme://` URL. A tool that takes a host some other way is not seen. This is not a firewall.
119
+ - **Hook coverage.** The hook sees tool calls. It does not see what an MCP server or a subagent does outside those calls.
120
+
121
+ If you find a command that slips through, please open an issue with the command and your policy.
122
+
123
+ ## Development
124
+
125
+ ```sh
126
+ python -m unittest discover -s tests -t . -v
127
+ argvgate probe --policy examples/policy.toml
128
+ ```
129
+
130
+ ## License
131
+
132
+ MIT
@@ -0,0 +1,8 @@
1
+ """argvgate: a policy gate for coding-agent tool calls, built on a real shell parser."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .engine import Decision, Engine, Finding # noqa: E402
6
+ from .policy import Policy, PolicyError, from_dict, load # noqa: E402
7
+
8
+ __all__ = ["Decision", "Engine", "Finding", "Policy", "PolicyError", "from_dict", "load", "__version__"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,230 @@
1
+ """Command line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+ from typing import List, Optional
10
+
11
+ from . import __version__, hook, probe
12
+ from .engine import Decision, Engine
13
+ from .policy import PolicyError, find_policy, load
14
+
15
+ EXIT = {"allow": 0, "deny": 2, "ask": 3}
16
+ USAGE_ERROR = 64
17
+
18
+ STARTER = '''# argvgate policy. Docs: https://github.com/anishpentyala/argvgate
19
+ version = 1
20
+
21
+ [paths]
22
+ # Gitignore-style patterns. A name with no slash matches anywhere.
23
+ # Matching a directory also covers everything under it.
24
+ deny_read = [".env", ".env.*", "~/.ssh/**", "~/.aws/**", "~/.gnupg/**", "**/*.pem", "**/id_rsa*"]
25
+ deny_write = [".env", ".env.*", ".git/hooks/**", ".github/workflows/**", "~/.ssh/**", "~/.bashrc", "~/.zshrc"]
26
+ # If set, writes anywhere else are refused. Relative entries are relative to the project root.
27
+ write_roots = [".", "/tmp"]
28
+
29
+ [commands]
30
+ default = "allow"
31
+ # Tokens that start with "-" are flags that must be present (a|b means either).
32
+ deny = [
33
+ "rm -r|-R|--recursive /",
34
+ "rm -r|-R|--recursive ~",
35
+ "git push --force|-f",
36
+ "git reset --hard",
37
+ "chmod -R|--recursive 777",
38
+ ]
39
+ ask = ["git push", "npm publish", "pip install", "docker run"]
40
+
41
+ [network]
42
+ # Uncomment to restrict where curl, wget, ssh, git clone and friends may connect.
43
+ # allow_hosts = ["github.com", "*.githubusercontent.com", "pypi.org", "files.pythonhosted.org"]
44
+ on_violation = "deny"
45
+
46
+ [opaque]
47
+ # What to do when a command cannot be analyzed (eval of a variable, python -c, curl | sh ...).
48
+ default = "ask"
49
+ pipe_to_shell = "deny"
50
+ '''
51
+
52
+ CLAUDE_SNIPPET = {
53
+ "hooks": {
54
+ "PreToolUse": [
55
+ {
56
+ "matcher": "Bash|Read|Write|Edit|MultiEdit|NotebookEdit|Grep|Glob|WebFetch",
57
+ "hooks": [{"type": "command", "command": "argvgate hook claude"}],
58
+ }
59
+ ]
60
+ }
61
+ }
62
+
63
+
64
+ def _load_policy(args) -> "object":
65
+ path = args.policy or os.environ.get("ARGVGATE_POLICY") or find_policy(args.cwd or os.getcwd())
66
+ if not path:
67
+ raise PolicyError("no policy found; pass --policy or run `argvgate init`")
68
+ return load(path), path
69
+
70
+
71
+ def _print_decision(dec: Decision, as_json: bool, explain: bool) -> None:
72
+ if as_json:
73
+ print(json.dumps({
74
+ "action": dec.action,
75
+ "reason": dec.reason(),
76
+ "findings": [{"action": f.action, "kind": f.kind, "detail": f.detail, "rule": f.rule} for f in dec.findings],
77
+ "trace": dec.trace if explain else [],
78
+ }, indent=2))
79
+ return
80
+ print(dec.action.upper())
81
+ for f in dec.findings:
82
+ print(" " + f.line())
83
+ if explain:
84
+ print("trace:")
85
+ for line in dec.trace:
86
+ print(" " + line)
87
+
88
+
89
+ def cmd_check(args) -> int:
90
+ policy, _ = _load_policy(args)
91
+ eng = Engine(policy, cwd=args.cwd)
92
+ if args.command is not None:
93
+ dec = eng.check_bash(args.command)
94
+ elif args.read is not None:
95
+ dec = eng.check_path("read", args.read)
96
+ elif args.write is not None:
97
+ dec = eng.check_path("write", args.write)
98
+ elif args.url is not None:
99
+ dec = eng.check_url(args.url)
100
+ else:
101
+ print("argvgate: give one of --command, --read, --write, --url", file=sys.stderr)
102
+ return USAGE_ERROR
103
+ _print_decision(dec, args.json, args.explain or args.prog == "explain")
104
+ return EXIT[dec.action]
105
+
106
+
107
+ def cmd_hook(args) -> int:
108
+ if args.agent != "claude":
109
+ print("argvgate: only 'claude' is supported", file=sys.stderr)
110
+ return USAGE_ERROR
111
+ return hook.run(sys.stdin, sys.stdout, args.policy, args.on_missing_policy)
112
+
113
+
114
+ def cmd_probe(args) -> int:
115
+ policy, path = _load_policy(args)
116
+ results, missed = probe.run(policy)
117
+ print("argvgate probe: %s" % path)
118
+ groups = {}
119
+ for r in results:
120
+ g = groups.setdefault(r.group, [0, 0])
121
+ g[0] += 1
122
+ g[1] += 1 if r.action == "allow" else 0
123
+ for g, (n, m) in groups.items():
124
+ print(" %-60s %3d variants, %d allowed" % (g[:60], n, m))
125
+ print("%d variants checked, %d blocked or flagged, %d allowed" % (len(results), len(results) - len(missed), len(missed)))
126
+ if missed:
127
+ print("\nAllowed variants (each one is a gap in this policy or in argvgate):")
128
+ for r in missed:
129
+ print(" [%s] %s" % (r.group, r.command))
130
+ return 1
131
+ return 0
132
+
133
+
134
+ def cmd_test(args) -> int:
135
+ policy, _ = _load_policy(args)
136
+ with open(args.cases, "r", encoding="utf-8") as fh:
137
+ cases = json.load(fh)
138
+ if isinstance(cases, dict):
139
+ cases = cases.get("cases", [])
140
+ bad = 0
141
+ for i, c in enumerate(cases):
142
+ eng = Engine(policy, cwd=c.get("cwd") or args.cwd)
143
+ tool = c.get("tool", "Bash")
144
+ ti = c.get("input") or ({"command": c["command"]} if "command" in c else {})
145
+ dec = eng.check_tool(tool, ti)
146
+ want = c["expect"]
147
+ ok = dec.action == want
148
+ bad += 0 if ok else 1
149
+ label = c.get("command") or json.dumps(ti)
150
+ print("%s %-5s (want %-5s) %s" % ("ok " if ok else "FAIL", dec.action, want, label))
151
+ print("%d cases, %d failed" % (len(cases), bad))
152
+ return 1 if bad else 0
153
+
154
+
155
+ def cmd_init(args) -> int:
156
+ path = args.path
157
+ if os.path.exists(path):
158
+ print("argvgate: %s already exists; not overwriting" % path, file=sys.stderr)
159
+ return 1
160
+ with open(path, "w", encoding="utf-8") as fh:
161
+ fh.write(STARTER)
162
+ print("wrote %s" % path)
163
+ print("next: argvgate probe --policy %s (tries bypass variants against it)" % path)
164
+ return 0
165
+
166
+
167
+ def cmd_snippet(args) -> int:
168
+ print(json.dumps(CLAUDE_SNIPPET, indent=2))
169
+ return 0
170
+
171
+
172
+ def build_parser() -> argparse.ArgumentParser:
173
+ p = argparse.ArgumentParser(prog="argvgate", description="Policy gate for coding-agent tool calls.")
174
+ p.add_argument("--version", action="version", version="argvgate " + __version__)
175
+ sub = p.add_subparsers(dest="prog")
176
+
177
+ def common(sp):
178
+ sp.add_argument("--policy", help="policy file (default: nearest argvgate.toml/json, or $ARGVGATE_POLICY)")
179
+ sp.add_argument("--cwd", help="working directory to evaluate relative paths from (default: current)")
180
+
181
+ for name in ("check", "explain"):
182
+ sp = sub.add_parser(name, help="evaluate one command, path or URL (exit 0 allow, 2 deny, 3 ask)")
183
+ common(sp)
184
+ sp.add_argument("--command")
185
+ sp.add_argument("--read")
186
+ sp.add_argument("--write")
187
+ sp.add_argument("--url")
188
+ sp.add_argument("--json", action="store_true")
189
+ sp.add_argument("--explain", action="store_true", help="show what was parsed")
190
+ sp.set_defaults(func=cmd_check)
191
+
192
+ sp = sub.add_parser("hook", help="run as a PreToolUse hook (reads the tool call from stdin)")
193
+ sp.add_argument("agent", choices=["claude"])
194
+ sp.add_argument("--policy")
195
+ sp.add_argument("--on-missing-policy", choices=["deny", "ask", "allow"], default="deny")
196
+ sp.set_defaults(func=cmd_hook)
197
+
198
+ sp = sub.add_parser("probe", help="try bypass variants against your policy; exit 1 if any is allowed")
199
+ common(sp)
200
+ sp.set_defaults(func=cmd_probe)
201
+
202
+ sp = sub.add_parser("test", help="run a JSON file of {command, expect} cases against the policy")
203
+ common(sp)
204
+ sp.add_argument("cases")
205
+ sp.set_defaults(func=cmd_test)
206
+
207
+ sp = sub.add_parser("init", help="write a starter policy")
208
+ sp.add_argument("--path", default="argvgate.toml")
209
+ sp.set_defaults(func=cmd_init)
210
+
211
+ sp = sub.add_parser("snippet", help="print the Claude Code settings.json hook entry")
212
+ sp.add_argument("agent", choices=["claude"])
213
+ sp.set_defaults(func=cmd_snippet)
214
+ return p
215
+
216
+
217
+ def main(argv: Optional[List[str]] = None) -> int:
218
+ parser = build_parser()
219
+ args = parser.parse_args(argv)
220
+ if not getattr(args, "func", None):
221
+ parser.print_help()
222
+ return USAGE_ERROR
223
+ try:
224
+ return args.func(args)
225
+ except PolicyError as exc:
226
+ print("argvgate: %s" % exc, file=sys.stderr)
227
+ return USAGE_ERROR
228
+ except OSError as exc:
229
+ print("argvgate: %s" % exc, file=sys.stderr)
230
+ return USAGE_ERROR