polyctl 0.7.0__py3-none-any.whl

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.
Files changed (99) hide show
  1. polyctl/__init__.py +7 -0
  2. polyctl/__main__.py +5 -0
  3. polyctl/a2a.py +226 -0
  4. polyctl/a2a_mcp.py +546 -0
  5. polyctl/acp.py +417 -0
  6. polyctl/adapters/README.md +101 -0
  7. polyctl/adapters/aider.json +32 -0
  8. polyctl/adapters/amazon-q.json +15 -0
  9. polyctl/adapters/amp.json +16 -0
  10. polyctl/adapters/antigravity.json +120 -0
  11. polyctl/adapters/claude-code.json +229 -0
  12. polyctl/adapters/cloud-generic.json +57 -0
  13. polyctl/adapters/codex.json +47 -0
  14. polyctl/adapters/command-code.json +45 -0
  15. polyctl/adapters/copilot.json +17 -0
  16. polyctl/adapters/cursor-agent.json +29 -0
  17. polyctl/adapters/deepseek.json +13 -0
  18. polyctl/adapters/droid.json +34 -0
  19. polyctl/adapters/gemini.json +30 -0
  20. polyctl/adapters/grok.json +22 -0
  21. polyctl/adapters/hermes.json +34 -0
  22. polyctl/adapters/kilocode.json +30 -0
  23. polyctl/adapters/kimi.json +23 -0
  24. polyctl/adapters/kiro.json +332 -0
  25. polyctl/adapters/ollama.json +29 -0
  26. polyctl/adapters/omp.json +34 -0
  27. polyctl/adapters/openai-api.json +68 -0
  28. polyctl/adapters/opencode.json +162 -0
  29. polyctl/adapters/pi.json +24 -0
  30. polyctl/adapters/pr-agent.json +54 -0
  31. polyctl/adapters/profiles.json +9 -0
  32. polyctl/adapters/qoder.json +163 -0
  33. polyctl/adapters/qwen.json +27 -0
  34. polyctl/adapters/reasonix.json +25 -0
  35. polyctl/adapters/rewriters/rtk.json +24 -0
  36. polyctl/adapters/trae.json +31 -0
  37. polyctl/adapters/vendors.json +42 -0
  38. polyctl/adapters/warp.json +88 -0
  39. polyctl/allowlist.py +1756 -0
  40. polyctl/api_review.py +920 -0
  41. polyctl/cli.py +835 -0
  42. polyctl/conformance_harness.py +9 -0
  43. polyctl/demo.py +503 -0
  44. polyctl/drivers.py +146 -0
  45. polyctl/email.py +160 -0
  46. polyctl/features.py +98 -0
  47. polyctl/journal.py +144 -0
  48. polyctl/language.py +945 -0
  49. polyctl/lib.py +1296 -0
  50. polyctl/matrix.py +660 -0
  51. polyctl/mcp.py +1362 -0
  52. polyctl/ntfy.py +169 -0
  53. polyctl/outbound.py +39 -0
  54. polyctl/parts/__init__.py +5 -0
  55. polyctl/parts/cli_authority.py +2615 -0
  56. polyctl/parts/cli_channels.py +1325 -0
  57. polyctl/parts/cli_checks.py +2293 -0
  58. polyctl/parts/cli_completion.py +686 -0
  59. polyctl/parts/cli_evidence.py +141 -0
  60. polyctl/parts/cli_gain.py +375 -0
  61. polyctl/parts/cli_harness.py +392 -0
  62. polyctl/parts/cli_hooks.py +1816 -0
  63. polyctl/parts/cli_install.py +638 -0
  64. polyctl/parts/cli_lanes.py +106 -0
  65. polyctl/parts/cli_maintenance.py +2536 -0
  66. polyctl/parts/cli_next.py +248 -0
  67. polyctl/parts/cli_pr.py +53 -0
  68. polyctl/parts/cli_project.py +2857 -0
  69. polyctl/parts/cli_review.py +5158 -0
  70. polyctl/parts/cli_status.py +898 -0
  71. polyctl/parts/lib_adapters.py +2933 -0
  72. polyctl/parts/lib_alarms.py +2106 -0
  73. polyctl/parts/lib_events.py +224 -0
  74. polyctl/parts/lib_evidence.py +412 -0
  75. polyctl/parts/lib_gates.py +2099 -0
  76. polyctl/parts/lib_lanes.py +829 -0
  77. polyctl/parts/lib_mail.py +1541 -0
  78. polyctl/parts/lib_next.py +652 -0
  79. polyctl/parts/lib_pr.py +331 -0
  80. polyctl/parts/lib_slices.py +3337 -0
  81. polyctl/parts/lib_state.py +2415 -0
  82. polyctl/parts/lib_transcript.py +4118 -0
  83. polyctl/pressure.py +325 -0
  84. polyctl/prices.json +47 -0
  85. polyctl/procs.py +1194 -0
  86. polyctl/settings.py +505 -0
  87. polyctl/skill/SKILL.md +365 -0
  88. polyctl/skillkit.py +503 -0
  89. polyctl/storage.py +2055 -0
  90. polyctl/telegram.py +327 -0
  91. polyctl/tiers.py +123 -0
  92. polyctl/verdicts.py +41 -0
  93. polyctl/watchdog.py +3887 -0
  94. polyctl/web.py +337 -0
  95. polyctl-0.7.0.dist-info/METADATA +235 -0
  96. polyctl-0.7.0.dist-info/RECORD +99 -0
  97. polyctl-0.7.0.dist-info/WHEEL +4 -0
  98. polyctl-0.7.0.dist-info/entry_points.txt +5 -0
  99. polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
polyctl/allowlist.py ADDED
@@ -0,0 +1,1756 @@
1
+ """What a tool grant admits, measured against polyctl's own guarantees (#58).
2
+
3
+ An allowlist that grants `git commit:*` grants `git commit --no-verify`, the one
4
+ flag that skips the only commit-time enforcement; one that grants `polyctl:*` grants
5
+ `polyctl push allow`; one that grants an interpreter grants everything, because any
6
+ command can be written as a script. So each rule is asked what it would admit,
7
+ command by command, instead of being read for its intent.
8
+
9
+ `polyctl verify` is not among the forbidden commands, though it runs what `.polyctl/gates.json` names and an
10
+ implementer can write that file: a grant that lets an implementer test its work runs code it wrote,
11
+ whatever the command is called. What holds there is the commit hook and `polyctl commit`, a verification's
12
+ binding to the gate definitions it ran (#61), and the push window - not this list (GRANTS-AUDIT-2).
13
+ """
14
+ import os
15
+ from functools import lru_cache
16
+ import posixpath
17
+ import re
18
+
19
+ # (why no actor polyctl runs may be granted it, the command)
20
+ FORBIDDEN = (
21
+ ("skips the commit hook", "git commit --no-verify -m x"),
22
+ ("skips the commit hook", "git commit -n -m x"),
23
+ ("redirects the commit hook", "git -c core.hooksPath=/dev/null commit -m x"),
24
+ ("rewrites the hook configuration", "git config core.hooksPath /dev/null"),
25
+ ("opens a push window", "polyctl push allow 30"),
26
+ ("waives a gate", "polyctl waive review --slice s --by b --why w"),
27
+ ("records a review polyctl did not run", "polyctl collect-review n --response r --model m --by b"),
28
+ ("records a person's review", "polyctl person-review --by p --verdict APPROVED --digest d"),
29
+ ("opts into same-family review", "polyctl config set review.same_family labeled --by p"),
30
+ ("opts into same-family review", "polyctl init --review-tier same-family --by p"),
31
+ # A person's act on the record since FEATURE-RECORDED; a grant that admits it hands an agent the record too.
32
+ ("switches review off", "polyctl features off review --by p"),
33
+ ("switches the inventory review off", "polyctl features off inventory_review --by p"),
34
+ ("switches the Windows reviewer job off", "polyctl features off windows_job --by p"),
35
+ ("switches the project to lite mode", "polyctl mode lite --by p"),
36
+ ("switches the project to lite mode", "polyctl config set mode lite --by p"),
37
+ ("names the family that wrote a waived range", "polyctl catchup --author-family f --by b"),
38
+ ("states which waived slices only moved code", "polyctl catchup --move-only s --by b"),
39
+ ("replaces a waived range's commit claims", "polyctl catchup --boundary text --by b"),
40
+ # What a person has seen of the harness configuration an agent changed lets every turn start again (HARNESS-CONFIG),
41
+ # by its digest or by a yes at the terminal (HARNESS-SEEN-OWN).
42
+ ("records harness configuration as seen", "polyctl harness seen --by p --digest d"),
43
+ ("records harness configuration as seen", "polyctl harness seen --by p --ask"),
44
+ ("grants a coordination commit", "polyctl commit-ok --by p"),
45
+ ("attests a restored backup", "polyctl restore s --by p"),
46
+ ("attests a restored backup", "polyctl restore s --by p --ask"),
47
+ ("attests a restored backup", "polyctl restore s --ask --by p"),
48
+ ("attests a restored backup", "polyctl restore s --by=p --ask"),
49
+ ("attests a restored backup", "polyctl restore s --b p --a"),
50
+ ("attests a restored backup", "polyctl restore s --b=p --a"),
51
+ ("attests a restored backup", "polyctl restore s --ask"),
52
+ ("removes the hooks", "polyctl hooks uninstall"),
53
+ ("installs a menu bar plugin", "polyctl surfaces install swiftbar --dir d"),
54
+ ("removes a menu bar plugin", "polyctl surfaces uninstall swiftbar --dir d"),
55
+ ("pages a person", "polyctl doctor --check --notify"),
56
+ ("runs any command", "polyctl lock -- sh -c x"),
57
+ ("runs arbitrary code", "python3 -c x"),
58
+ ("runs arbitrary code", "python -c x"),
59
+ ("runs arbitrary code", "python -m x"),
60
+ ("runs arbitrary code", "python3 -m x"),
61
+ ("runs arbitrary code", "py -m x"),
62
+ ("runs arbitrary code", "node -e x"),
63
+ ("runs arbitrary code", "npx x"),
64
+ ("runs arbitrary code", "npm run x"),
65
+ ("runs arbitrary code", "pytest -p x"),
66
+ ("runs arbitrary code", "bash -c x"),
67
+ ("runs arbitrary code", "sh -c x"),
68
+ ("runs arbitrary code", "zsh -c x"),
69
+ ("runs arbitrary code", "find . -exec sh -c x ;"),
70
+ ("runs arbitrary code", "xargs sh -c x"),
71
+ ("runs arbitrary code", "env sh -c x"),
72
+ ("runs arbitrary code", "uv run x"),
73
+ ("runs arbitrary code", "make x"),
74
+ # Windows' own ways to run a line of code, as `python -c` runs one: the py launcher, PowerShell and cmd.exe each
75
+ # run the text they are handed, and a grant of any of them was asked about none (WINDOWS-SAY-WHY). Git Bash, which
76
+ # runs a harness's Bash tool on Windows, hands cmd its switch as `//c`.
77
+ ("runs arbitrary code", "py -c x"),
78
+ ("runs arbitrary code", "py -3 -c x"),
79
+ ("runs arbitrary code", "python.exe -c x"),
80
+ ("runs arbitrary code", "powershell -Command x"),
81
+ ("runs arbitrary code", "powershell -c x"),
82
+ ("runs arbitrary code", "powershell -EncodedCommand x"),
83
+ ("runs arbitrary code", "powershell.exe -Command x"),
84
+ ("runs arbitrary code", "PowerShell -Command x"),
85
+ ("runs arbitrary code", "pwsh -Command x"),
86
+ ("runs arbitrary code", "pwsh -c x"),
87
+ ("runs arbitrary code", "cmd /c x"),
88
+ ("runs arbitrary code", "cmd //c x"),
89
+ ("runs arbitrary code", "cmd.exe /c x"),
90
+ )
91
+
92
+
93
+ # The architect decides. An implementer granted this could restart its own round
94
+ # budget with a re-specification it wrote itself (#65).
95
+ IMPLEMENTER_FORBIDDEN = (
96
+ ("re-specifies a slice, restarting its round budget", "polyctl decide x --scope s"),
97
+ ("changes the settings that govern its own review", "polyctl config set review_timeout 1"),
98
+ # Whether work is dropped is scope; the implementer parks a slice instead (SLICE-LIFECYCLE).
99
+ ("abandons a slice, which the architect decides", "polyctl slice abandon --why w"),
100
+ )
101
+
102
+ # The architect decides and edits polyctl's coordination files; a wake writes no product code
103
+ # (GRANTS-PINNED). A rule admitting one of these hands it a write its playbook never asks for.
104
+ ARCHITECT_FORBIDDEN = (
105
+ ("removes a product file", "rm agent-mail/x src/app.py"),
106
+ ("writes a product file", "git diff --output=src/app.py"),
107
+ ("writes a product file", "git log --output=src/app.py"),
108
+ ("writes a product file", "git show --output=src/app.py"),
109
+ ("writes a product file", "cp agent-mail/x src/app.py"),
110
+ ("writes a product file", "mv agent-mail/x src/app.py"),
111
+ ("writes a product file", "tee src/app.py"),
112
+ )
113
+
114
+ # Programs that run the command after them, each with its own options declared whole, as getopt declares them: the
115
+ # letters of its short options, with ":" after one that takes a value and "::" after one that takes it only attached,
116
+ # and its long options, with "=" after one that takes a value and "=?" after one that takes it only after "="
117
+ # (ALLOWLIST-NORMALIZE). A rule admitting one with any arguments admits what it would admit of the command after it:
118
+ # `Bash(timeout 60 pytest:*)` admits `timeout 60 pytest -p x`, which loads any plugin, and `Bash(nice:*)` admits every
119
+ # command there is. Each holds the options of GNU's program and of BSD's and macOS's both: the reading listed only
120
+ # those that take a value and took any other for one that takes none, so `Bash(env -P /usr/bin git:*)` read
121
+ # `/usr/bin` as the program, where macOS's env takes it as the folder to find git in (ALLOWLIST-DEPTH).
122
+ WRAPPERS = {
123
+ # coreutils env and BSD's: -a, -C and the long options are GNU's, -L, -P and -U BSD's.
124
+ "env": ("0iva:C:L:P:S:U:u:", ("ignore-environment", "null", "debug", "list-signal-handling", "help", "version",
125
+ "argv0=", "chdir=", "split-string=", "unset=", "block-signal=?",
126
+ "default-signal=?", "ignore-signal=?")),
127
+ "timeout": ("fpvk:s:", ("foreground", "preserve-status", "verbose", "help", "version", "kill-after=",
128
+ "signal=")),
129
+ "nice": ("n:", ("help", "version", "adjustment=")),
130
+ "nohup": ("", ("help", "version")),
131
+ "stdbuf": ("e:i:o:", ("help", "version", "error=", "input=", "output=")),
132
+ # findutils xargs and BSD's: -a, -d, and -e, -i and -l, whose value is attached or none, are GNU's; -J, -R and -S
133
+ # BSD's.
134
+ "xargs": ("0oprtxE:I:J:L:P:R:S:a:d:n:s:e::i::l::", ("null", "open-tty", "interactive", "no-run-if-empty",
135
+ "verbose", "exit", "show-limits", "help", "version",
136
+ "arg-file=", "delimiter=", "max-args=", "max-chars=",
137
+ "max-procs=", "process-slot-var=", "eof=?", "max-lines=?",
138
+ "replace=?")),
139
+ # bash's keyword (-p), GNU time and BSD's.
140
+ "time": ("ahlpqvVf:o:", ("append", "portability", "quiet", "verbose", "help", "version", "format=", "output=")),
141
+ "command": ("pvV", ()),
142
+ "exec": ("cla:", ()),
143
+ # The shells' own: bash's and zsh's builtin, zsh's precommand modifiers, the ! before a pipeline, bash's coproc.
144
+ "builtin": ("", ()),
145
+ "noglob": ("", ()),
146
+ "nocorrect": ("", ()),
147
+ "-": ("", ()),
148
+ "!": ("", ()),
149
+ "coproc": ("", ()),
150
+ "caffeinate": ("dimsut:w:", ()),
151
+ "sudo": ("ABbEeHiKklNnPSsVvC:D:R:T:U:g:p:r:t:u:h:", ("askpass", "bell", "background", "edit", "set-home", "help",
152
+ "login", "remove-timestamp", "reset-timestamp", "list",
153
+ "no-update", "non-interactive", "preserve-groups", "stdin",
154
+ "shell", "version", "validate", "chdir=", "chroot=",
155
+ "close-from=", "command-timeout=", "group=", "host=",
156
+ "other-user=", "prompt=", "role=", "type=", "user=",
157
+ "preserve-env=?")),
158
+ }
159
+ # GNU's names for its own on macOS, where Homebrew installs coreutils and findutils beside the system's programs.
160
+ WRAPPERS.update({"g" + name: WRAPPERS[name]
161
+ for name in ("env", "nice", "nohup", "stdbuf", "time", "timeout", "xargs")})
162
+ # Words a wrapper reads before the command that are not options: timeout's duration.
163
+ WRAPPER_OPERANDS = {"timeout": 1, "gtimeout": 1}
164
+ # A wrapper's options after which the reading cannot say what runs: env -S splits a string of its own into the
165
+ # command, env -P names where the program is found, as PATH does, sudo -e edits files with whichever editor the
166
+ # environment names, and sudo -R runs the program from another root (ALLOWLIST-DEPTH).
167
+ WRAPPER_RUNS_ANY = {"env": ("-S", "--split-string", "-P", "-L", "-U", "-a", "--argv0"),
168
+ "genv": ("-S", "--split-string", "-P", "-L", "-U", "-a", "--argv0"),
169
+ "exec": ("-a",),
170
+ "sudo": ("-e", "--edit", "-R", "--chroot", "-A", "--askpass", "-s", "--shell")}
171
+ # A wrapper's options with which it runs nothing: `command -v git` says where git is.
172
+ WRAPPER_DESCRIBES = {"command": ("-v", "-V")}
173
+ # A wrapper's options with which, given no command, it starts a shell that reads its commands from what it is handed:
174
+ # `echo 'git commit -n -m x' | sudo -s` runs the commit (ALLOWLIST-DEPTH).
175
+ WRAPPER_SHELLS = {"sudo": ("-s", "-i", "--shell", "--login")}
176
+ # Wrappers whose adjustment may stand as an option of its own: `nice -10 git commit -n` runs git.
177
+ WRAPPER_NUMBERS = ("nice", "gnice")
178
+ # xargs without replacement appends arbitrary arguments. Replacement may rewrite any command word and fails
179
+ # closed, including -i/--replace with their default string (ALLOWLIST-DEPTH).
180
+ XARGS = ("xargs", "gxargs")
181
+ XARGS_REPLACES = ("-I", "-J", "-i", "--replace")
182
+ WRAPPER_RUNS_ANY.update({name: XARGS_REPLACES for name in XARGS})
183
+ # A word a shell reads as a variable for the command after it, not as its program: `FOO=1 git commit -n` runs git
184
+ # (ALLOWLIST-DEPTH).
185
+ SHELL_ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
186
+ # The variables such a word, or env's, may set and leave the command as the reading reads it: the locale, the terminal
187
+ # and its colours, the time zone, CI. Any other may change what runs - PATH names the program, LD_PRELOAD and
188
+ # NODE_OPTIONS load code into it, PYTEST_ADDOPTS hands it options, GIT_CONFIG_COUNT and its keys hand git
189
+ # `core.hooksPath` - and a rule that sets one reads as any command: `Bash(GIT_CONFIG_COUNT=1
190
+ # GIT_CONFIG_KEY_0=core.hooksPath GIT_CONFIG_VALUE_0=/dev/null git commit -m x)` read as `git commit -m x`
191
+ # (ALLOWLIST-DEPTH).
192
+ INERT_VARIABLES = re.compile(r"LANG|LANGUAGE|LC_[A-Z]+|TZ|TERM|COLUMNS|LINES|NO_COLOR|FORCE_COLOR|CLICOLOR(_FORCE)?|CI")
193
+ # git's own options before its subcommand, as git.c reads them - each matched whole, never abbreviated or run
194
+ # together - with whether it takes a value, as the next word or after "=". -v, --version, -h and --help end them, as
195
+ # the subcommand each stands for. They change where git works and what it shows, not what a subcommand does to the
196
+ # commit hook, except -c and --config-env, which set configuration, and --exec-path=, which names the folder git runs
197
+ # its own programs from: `git commit` runs `git maintenance` from it (ALLOWLIST-DEPTH).
198
+ GIT_OPTIONS = {
199
+ "-C": True, "-c": True, "--attr-source": True, "--config-env": True, "--git-dir": True, "--list-cmds": True,
200
+ "--namespace": True, "--shallow-file": True, "--super-prefix": True, "--work-tree": True,
201
+ "-P": False, "-p": False, "--bare": False, "--exec-path": False, "--glob-pathspecs": False, "--html-path": False,
202
+ "--icase-pathspecs": False, "--info-path": False, "--literal-pathspecs": False, "--man-path": False,
203
+ "--no-advice": False, "--no-lazy-fetch": False, "--no-optional-locks": False, "--no-pager": False,
204
+ "--no-replace-objects": False, "--noglob-pathspecs": False, "--paginate": False,
205
+ }
206
+ # The configuration -c or --config-env may set and leave the command as the reading reads it: none of these names a
207
+ # command git runs, a file it reads more configuration from or where its hooks are. Any other key reads as any
208
+ # command - `alias.x=!sh` runs a shell, `core.fsmonitor` a program, `include.path` a file that may set
209
+ # `core.hooksPath` - and `core.hooksPath` itself redirects the commit hook (ALLOWLIST-DEPTH).
210
+ INERT_GIT_CONFIG = re.compile(r"user\.(name|email)|(color|advice)\..+|core\.(quotepath|abbrev)|init\.defaultbranch|"
211
+ r"safe\.directory")
212
+ @lru_cache(maxsize=1)
213
+ def _polyctl_tables():
214
+ """Every polyctl command's options, derived lazily to avoid the cli/allowlist import cycle."""
215
+ from . import cli
216
+ parser = cli.build_parser()
217
+ commands = next(action.choices for action in parser._actions if isinstance(action.choices, dict))
218
+ return {name: {flag: action.nargs != 0 for action in command._actions for flag in action.option_strings}
219
+ for name, command in {None: parser, **commands}.items()}
220
+
221
+
222
+ # Directory-valued polyctl options, scoped by command so note --to and email --from retain their meanings.
223
+ # Only the global, separate word pair `-C .` is a proven no-op; every other spelling fails closed.
224
+ POLYCTL_DIRECTORY_OPTIONS = {None: ("-C", "--root"), "backup": ("--to",), "content": ("--from",)}
225
+
226
+
227
+ GRANT_ALL = ("--dangerously-skip-permissions", "--trust-all-tools", "--yolo", "--full-auto",
228
+ "--dangerously-bypass-approvals-and-sandbox")
229
+
230
+ # The tool a `--trust-tools` list trusts every command through: Kiro trusts tools by name, and its shell
231
+ # tool runs whatever command it is given (kiro.dev/docs/reference/built-in-tools, read 2026-09-30).
232
+ SHELL_TOOLS = ("bash", "shell", "execute_bash", "execute_cmd", "*")
233
+
234
+
235
+ def admits(rule, command):
236
+ """Would this one Claude Code permission rule let `command` run?
237
+
238
+ A `*` stands for any text, spaces included, wherever it is in the rule, and a trailing
239
+ `:*` is written the same as a trailing ` *`, which also admits the bare command
240
+ (code.claude.com/docs/en/permissions, "Wildcard patterns", read 2026-09-17). Read as a
241
+ prefix only, `Bash(rm agent-mail/*)` looked like one directory's files and admits
242
+ `rm agent-mail/x src/app.py`.
243
+
244
+ One command is asked at a time, as the harness asks: it splits a compound command at `&&`,
245
+ `||`, `;`, `|`, `|&`, `&` and newlines and runs it only when a rule admits each part, so
246
+ `Bash(git add *)` does not run `git add . && git commit --no-verify` (the same page,
247
+ "Compound commands", read 2026-09-30). A forbidden command is forbidden standing alone.
248
+ """
249
+ rule = str(rule).strip()
250
+ if rule in ("Bash", "Bash(*)"):
251
+ return True
252
+ if not (rule.startswith("Bash(") and rule.endswith(")")):
253
+ return False
254
+ # A run of wildcards admits what one does. Asked as written, each `*` a `.*` the matcher tried every split of,
255
+ # `Bash(********Z)` did not answer one command in ten seconds, and the audit asks each rule a hundred
256
+ # (ALLOWLIST-DEPTH).
257
+ # A program word the rule leaves to a wildcard is matched as the harness matches it, the command's as written too:
258
+ # read by its name, `Bash(/usr/*/git status:*)` admitted `git status` and not `/usr/bin/python3 -c x /tmp/git
259
+ # status` (ALLOWLIST-DEPTH).
260
+ head = rule[len("Bash("):-1]
261
+ wild = _wild_program(head)
262
+ body = re.sub(r"\*{2,}", "*", head if wild else _program_word(head))
263
+ command = str(command) if wild else _program_word(command)
264
+ if body.endswith(":*"):
265
+ body = body[:-2] + " *"
266
+ if "*" not in body:
267
+ return command == body
268
+ if body.endswith(" *") and body.count("*") == 1 and command == body[:-2]:
269
+ return True
270
+ return re.fullmatch(".*".join(re.escape(part) for part in body.split("*")), command, re.S) is not None
271
+
272
+
273
+ def _program_file(word):
274
+ """A path, drive-relative name or stream is a file, never a trusted bare program."""
275
+ return any(char in word for char in "/\\:")
276
+
277
+
278
+ def _program_name(word):
279
+ """Fold a bare Windows name only; never discard a program file's path or stream."""
280
+ if _program_file(word):
281
+ return word
282
+ program = word.strip("\"'").upper().casefold().rstrip(". ")
283
+ for extension in (".exe", ".cmd", ".bat", ".com"):
284
+ if program.endswith(extension):
285
+ return program[:-len(extension)]
286
+ return program
287
+
288
+
289
+ # A command's or a rule's program word, ending at a space or at a rule's `:*`; a quoted one is one word, spaces and all:
290
+ # `"C:\Program Files\...\python.exe"`.
291
+ PROGRAM_WORD = re.compile(r"(?:\"([^\"]*)\"|'([^']*)'|(\S+?))(:\*|\s|$)(.*)", re.S)
292
+
293
+
294
+ def _program_word(text):
295
+ """A command or a rule with its program read as Windows starts it - `powershell.exe -c x` is `powershell -c x` -
296
+ the program ending at a space or at a rule's `:*`. Each forbidden command was asked as one spelling, and a rule
297
+ written with another admitted it unnamed (the review of WINDOWS-SAY-WHY).
298
+
299
+ A program word with a wildcard in it is left as it is, its folder too: read as its name, `Bash(/usr/*/git
300
+ status:*)` was asked as `Bash(git status:*)` (ALLOWLIST-DEPTH)."""
301
+ found = PROGRAM_WORD.match(str(text))
302
+ if not found or _wild_program(text):
303
+ return str(text)
304
+ program = next(group for group in found.groups()[:3] if group is not None)
305
+ return _program_name(program) + found.group(4) + found.group(5)
306
+
307
+
308
+ def _wild_program(text):
309
+ """Whether a rule's program word holds a wildcard anywhere, its folder included (ALLOWLIST-DEPTH)."""
310
+ found = PROGRAM_WORD.match(str(text))
311
+ return bool(found) and "*" in next(group for group in found.groups()[:3] if group is not None)
312
+
313
+
314
+ # Programs that run whatever code they are handed: an interpreter or a shell. A rule that grants one runs anything,
315
+ # whatever arguments it fixes, so the audit reads it as a closed world rather than as spellings to list; only an exact
316
+ # command asking its version or its help is no grant of code (the review of WINDOWS-SAY-WHY). Each by its versioned
317
+ # name too, as a distribution installs it: only python's was read so, and `Bash(ruby3.2 -e:*)` passed
318
+ # (ALLOWLIST-DEPTH).
319
+ INTERPRETERS = re.compile(r"(python|pythonw|pypy|py|node|nodejs|deno|bun|ruby|perl|php|lua|powershell|pwsh|cmd|bash|"
320
+ r"sh|zsh|fish|dash|ksh|csh|tcsh|osascript|wscript|cscript|mshta)(\d+(\.\d+)*)?")
321
+ HARMLESS_ARGUMENTS = {"--version", "-v", "-V", "--help", "-h", "/?"}
322
+
323
+
324
+ def interpreter_rule(rule):
325
+ """The interpreter a rule grants with arguments that could hand it code, or None (WINDOWS-SAY-WHY).
326
+
327
+ It is read as the command the rule runs; a rule read as any command at all is named as that (ALLOWLIST-DEPTH)."""
328
+ reading = _rule_reading(rule)
329
+ if not reading:
330
+ return None
331
+ said, tail = reading[0], reading[1]
332
+ if not said or not INTERPRETERS.fullmatch(said[0]):
333
+ return None
334
+ if tail is None and _harmless(said[1:]):
335
+ return None
336
+ return said[0]
337
+
338
+
339
+ def _permission_values(argv, flags, prompt=None):
340
+ """Read both variadic grant forms without treating polyctl's prompt as a tool (TRIAGE-3-MEDIUM)."""
341
+ out = []
342
+ for i, arg in enumerate(argv):
343
+ flag, equals, value = str(arg).partition("=")
344
+ if flag not in flags:
345
+ continue
346
+ values = [value] if equals else []
347
+ after = i + 1
348
+ while after < len(argv) and not str(argv[after]).startswith("-"):
349
+ values.append(str(argv[after]))
350
+ after += 1
351
+ for value in values:
352
+ if value != prompt and not re.fullmatch(r"\{[a-z_]+\}", value):
353
+ out.extend(_tools(value))
354
+ return out
355
+
356
+
357
+ def rules(argv, prompt=None):
358
+ """Every word of a multi-value tool grant, excluding polyctl's prompt (TRIAGE-3-MEDIUM)."""
359
+ return _permission_values(argv, ("--allowedTools", "--allowed-tools"), prompt)
360
+
361
+
362
+ def _tools(value):
363
+ """Use the same tool-list grammar as grant rewriting and role pins."""
364
+ from . import lib as A
365
+ return A.split_tool_list(value)
366
+
367
+
368
+ def trusted_tools(argv, prompt=None):
369
+ """Tools trusted by name, including every variadic value (TRIAGE-3-MEDIUM)."""
370
+ return _permission_values(argv, ("--trust-tools",), prompt)
371
+
372
+
373
+ def grants_everything(argv, options=None):
374
+ """Does this argv, as polyctl would run it, grant every tool?
375
+
376
+ The watchdog starts an argv that carries no scope of its own with what its adapter
377
+ declares for a turn nobody attends (`options.unattended`) or, where it declares none,
378
+ its trust_all: such a harness has no allowlist, and grants every tool either way unless
379
+ what is appended scopes it.
380
+ """
381
+ from . import lib as A
382
+ args = [str(arg) for arg in argv]
383
+ adapter = A.command_adapter(args)
384
+ trust = ((adapter or {}).get("options") or {}).get("trust_all") or []
385
+ if (any(arg in GRANT_ALL for arg in args) or A.bypass_arguments(args)
386
+ or (trust and any(args[i:i + len(trust)] == trust for i in range(len(args))))):
387
+ return True
388
+ if A.carries_scope(args):
389
+ return False
390
+ options = options or {}
391
+ if isinstance(options.get("unattended"), list):
392
+ return not A.carries_scope(options["unattended"])
393
+ return "trust_all" in options
394
+
395
+
396
+ def problems(argv, options=None, role=None, prompt=None):
397
+ """(reason, command, rule) for everything this grant admits that it must not.
398
+
399
+ A grant of every tool is one finding with command and rule '*'. The rules are the
400
+ argv's own and those its adapter's `options.unattended` appends, each with what a
401
+ command rewriter makes of it, as a turn polyctl starts holds them (GRANTS-RTK); and each
402
+ forbidden command is asked in the forms a rewriter would run it as, too.
403
+ """
404
+ from . import lib as A
405
+ if grants_everything(argv, options):
406
+ return [("grants every tool", "*", "*")]
407
+ appended = A.unattended_flags({"options": options or {}}, argv)[0]
408
+ shell = next((tool for tool in trusted_tools(list(argv) + appended, prompt=prompt)
409
+ if tool.lower() in SHELL_TOOLS or tool == "Bash(*)"), None)
410
+ if shell:
411
+ return [("trusts the shell tool, which runs every command", "*", f"--trust-tools {shell}")]
412
+ granted = rules(A.admit_rewrites(list(argv), prompt=prompt)[0] + appended, prompt=prompt)
413
+ forbidden = FORBIDDEN + (IMPLEMENTER_FORBIDDEN if role == "implementer" else ()) \
414
+ + (ARCHITECT_FORBIDDEN if role == "architect" else ())
415
+ found = []
416
+ for reason, command in forbidden + through_rewriters(forbidden):
417
+ rule = next((r for r in granted if admits(r, command)), None)
418
+ if rule:
419
+ found.append((reason, command, rule))
420
+ # A rule that admits a forbidden command only as the command it runs - behind a program that runs what
421
+ # follows it, a rewriter's wrapper or git's global options - is named once, for the first such command,
422
+ # and a rule already named for a form it admits as it stands is not named again (ALLOWLIST-NORMALIZE).
423
+ named = {rule for _, _, rule in found}
424
+ plains = {rule: normalized_rule(rule) for rule in granted}
425
+ unwrapped = [(rule, plains[rule]) for rule in granted if rule not in named and plains[rule]]
426
+ for reason, command in forbidden:
427
+ for rule, plain in unwrapped:
428
+ if rule not in named and admits(plain, command):
429
+ found.append((f"{reason}, as the command it runs", command, rule))
430
+ named.add(rule)
431
+ # An interpreter or a shell is named whatever its rule fixes after it (WINDOWS-SAY-WHY).
432
+ for rule in granted:
433
+ program = interpreter_rule(rule) if rule not in named else None
434
+ if program:
435
+ found.append(("runs arbitrary code", f"{program} ...", rule))
436
+ named.add(rule)
437
+ # Every other rule is asked what its own command does: an exact rule was compared with the forbidden commands as
438
+ # strings, so `Bash(git commit --no-verify -m y)` skipped the hook unnamed beside the sample's `-m x`, and a
439
+ # person's act written out in full passed but for the words that start it (GRANTS-PREFIX, ALLOWLIST-DEPTH).
440
+ operations = OPERATIONS + (IMPLEMENTER_OPERATIONS if role == "implementer" else ()) \
441
+ + (ARCHITECT_OPERATIONS if role == "architect" else ())
442
+ effects = {rule: [] for rule in granted}
443
+ readings = {rule: _rule_reading(rule, effects[rule]) for rule in granted}
444
+ if role == "architect":
445
+ for rule in granted:
446
+ if rule not in named and any(path is None or _outside(path) for path in effects[rule]):
447
+ found.append(("writes a product file", "wrapper output", rule))
448
+ named.add(rule)
449
+ _name_operations(found, named, granted, readings, operations)
450
+ if role == "implementer":
451
+ # Every setting polyctl reads governs the loop an implementer works in - its round budget, its review's
452
+ # timeout, how long a waiver lasts - and only `review_timeout` was asked, so a grant of
453
+ # `polyctl config set round_budget:*` went unnamed. Each rule is named once, for the first it admits
454
+ # (SETTINGS-2), as it stands or as the command it runs: `Bash(timeout 60 polyctl config set round_budget:*)`
455
+ # was asked only as it stands, and passed (ALLOWLIST-DEPTH).
456
+ for rule in granted:
457
+ command = next((c for c in settings_commands()
458
+ if admits(rule, c) or plains[rule] and admits(plains[rule], c)), None) \
459
+ if rule not in named else None
460
+ if command:
461
+ found.append(("changes a setting that governs its own work", command, rule))
462
+ named.add(rule)
463
+ # And by what its own command does, as every forbidden command is: `polyctl config set round_budget 9`
464
+ # (ALLOWLIST-DEPTH).
465
+ _name_operations(found, named, granted, readings, _settings_operations())
466
+ return found
467
+
468
+
469
+ def _name_operations(found, named, granted, readings, operations):
470
+ """Name each rule not named yet for the first operation its command performs, or could, past its fixed words: an
471
+ exact rule by the command it runs, a rule with a wildcard by the operation it leaves to it (ALLOWLIST-DEPTH)."""
472
+ for rule in granted:
473
+ reading = readings.get(rule)
474
+ if rule in named or reading is False:
475
+ continue
476
+ said, tail, config = reading[:3] if reading else ([], "", ())
477
+ operation = next(((reason, shown) for reason, shown, performs in operations
478
+ if reading is None or performs(said, tail, config)), None)
479
+ if operation:
480
+ reason, shown = operation
481
+ # An exact rule is shown as the command it runs, with the configuration git is handed.
482
+ runs = " ".join(_configured_words(said, config))
483
+ found.append((reason, runs if reading and tail is None else f"{shown} ...", rule))
484
+ named.add(rule)
485
+
486
+
487
+ def settings_commands():
488
+ """`polyctl config set` for each setting polyctl reads, as an implementer's grant is asked it (SETTINGS-2)."""
489
+ from . import settings as S
490
+ return tuple(f"polyctl config set {key} 1" for key in sorted(S.SETTINGS))
491
+
492
+
493
+ # ---- the reading: a rule as the command it runs ------------------------------------------------------------------
494
+
495
+ def _lex(text):
496
+ r"""Read plain space-separated words and at most one terminal prefix wildcard.
497
+
498
+ No quotes, escapes, expansions or redirections are interpreted. Shipped grants
499
+ need none of them. The only wildcard is a final, separate `*` word; `:*` is converted to
500
+ ` *` by _rule_body. Everything else fails closed before any option is read.
501
+ """
502
+ prefix = text[:-1] if text.endswith("*") else text
503
+ if any(c in "\"'\\;&|<>()$`!{}*?[]^#%" or c.isspace() and c != " "
504
+ or ord(c) < 32 or ord(c) == 127 for c in prefix):
505
+ return None
506
+ words = [word for word in prefix.split(" ") if word]
507
+ if any(word.startswith(("=", "~")) or "=~" in word or ":~" in word for word in words):
508
+ return None # command or tilde expansion, not git's HEAD~1
509
+ if not text.endswith("*"):
510
+ return words, None, ""
511
+ if not prefix or prefix.endswith(" "):
512
+ return words, "", "*"
513
+ return None # An attached wildcard leaves a word unknown, even if its prefix is a known command.
514
+
515
+
516
+ def _rewriters():
517
+ """The command rewriters' own names, and the words of each of their wrappers that runs the command after it."""
518
+ from . import lib as A
519
+ names, runners = set(), []
520
+ for rewriter in A.command_rewriters():
521
+ names.add(_program_name(str(rewriter["command"]).strip()))
522
+ declared = rewriter.get("runs_any_command")
523
+ runners.extend([_program_name(runner.split()[0])] + runner.split()[1:]
524
+ for runner in (declared if isinstance(declared, list) else [])
525
+ if isinstance(runner, str) and runner.strip())
526
+ return names, runners
527
+
528
+
529
+ def _letters(short):
530
+ """A getopt short-option string as {letter: 0 for none, 1 for a value, 2 for one only attached}."""
531
+ found, at = {}, 0
532
+ while at < len(short):
533
+ colons = len(short[at + 1:]) - len(short[at + 1:].lstrip(":"))
534
+ found[short[at]] = min(colons, 2)
535
+ at += 1 + colons
536
+ return found
537
+
538
+
539
+ def _options(words, short, long, at=0, interspersed=True, numbers=False):
540
+ """Read getopt options once, including clusters and values that begin with '-'.
541
+
542
+ Return (operands, options with their values, next index, waiting for a value).
543
+ None means an option is not in the grammar. Callers must propagate that result;
544
+ they cannot assume an unknown option takes no value and resume at the next word.
545
+ """
546
+ letters, operands, given, ended = _letters(short), [], [], False
547
+ while at < len(words):
548
+ word = words[at]
549
+ if ended or not word.startswith("-") or word == "-":
550
+ if not interspersed:
551
+ break
552
+ operands.append(word)
553
+ elif word == "--":
554
+ if not interspersed:
555
+ return operands, given, at + 1, False
556
+ ended = True
557
+ elif numbers and re.fullmatch(r"-[-+]?\d+", word):
558
+ # `nice -5`: the adjustment stands as one number, recorded under the pseudo-option the
559
+ # wrappers of WRAPPER_NUMBERS declare inert; the reading walks past it, not into an
560
+ # unknown option (ALLOWLIST-DEPTH).
561
+ given.append(("-number", word))
562
+ elif word.startswith("--"):
563
+ asked, equals, value = word[2:].partition("=")
564
+ matches = [option for option in long if option.rstrip("=?") == asked] or [
565
+ option for option in long if asked and option.rstrip("=?").startswith(asked)]
566
+ if len(matches) != 1:
567
+ return None
568
+ option = matches[0]
569
+ if equals and not option.endswith(("=", "=?")):
570
+ return None
571
+ if option.endswith("=") and not equals:
572
+ if at + 1 == len(words):
573
+ return operands, given + [("--" + option.rstrip("=?"), None)], len(words), True
574
+ at += 1
575
+ value = words[at]
576
+ given.append(("--" + option.rstrip("=?"), value if equals or option.endswith("=") else None))
577
+ else:
578
+ for index, letter in enumerate(word[1:], 1):
579
+ kind = letters.get(letter)
580
+ if kind is None:
581
+ return None
582
+ value = None
583
+ if kind:
584
+ value = word[index + 1:] or None
585
+ if value is None and kind == 1:
586
+ if at + 1 == len(words):
587
+ return operands, given + [("-" + letter, None)], len(words), True
588
+ at += 1
589
+ value = words[at]
590
+ given.append(("-" + letter, value))
591
+ if kind:
592
+ break
593
+ at += 1
594
+ return operands, given, at, False
595
+
596
+
597
+ # Only these option grammars support exact semantic readings. New/unknown options
598
+ # fail closed, so additions to a tool cannot silently acquire a harmless meaning.
599
+ FILE_OPTIONS = {
600
+ "cp": ("aBbcdfHilLnPpRrsS:t:Tuvx", ("archive", "attributes-only", "backup=?", "copy-contents", "debug",
601
+ "force", "interactive", "link", "no-clobber", "no-dereference", "parents", "preserve=?", "no-preserve=",
602
+ "recursive", "reflink=?", "remove-destination", "sparse=", "strip-trailing-slashes", "suffix=",
603
+ "symbolic-link", "target-directory=", "no-target-directory", "update=?", "verbose", "one-file-system",
604
+ "context=?", "help", "version")),
605
+ "mv": ("bfhinS:t:Tuv", ("backup=?", "debug", "exchange", "force", "interactive", "no-clobber", "no-copy",
606
+ "strip-trailing-slashes", "suffix=", "target-directory=", "no-target-directory", "update=?", "verbose",
607
+ "context", "help", "version")),
608
+ "rm": ("dfiIPRrvW", ("dir", "force", "interactive=?", "one-file-system", "no-preserve-root", "preserve-root=?",
609
+ "recursive", "verbose", "help", "version")),
610
+ "tee": ("aip", ("append", "ignore-interrupts", "output-error=?", "help", "version")),
611
+ }
612
+ GIT_CONFIG_READS = ("--get", "--get-all", "--get-regexp", "--get-urlmatch", "--get-color", "--get-colorbool", "--list", "-l")
613
+ GIT_CONFIG_WRITES = ("set", "unset", "rename-section", "remove-section", "edit")
614
+ GIT_CONFIG_WRITE_OPTIONS = ("--add", "--replace-all", "--unset", "--unset-all", "--rename-section", "--remove-section",
615
+ "--edit", "-e", "--append")
616
+ GIT_CONFIG_OPTIONS = ("f:t:zle", tuple(option[2:] for option in GIT_CONFIG_READS + GIT_CONFIG_WRITE_OPTIONS
617
+ if option.startswith("--")) + (
618
+ "global", "system", "local", "worktree", "file=", "blob=", "type=", "bool", "int", "bool-or-int", "path",
619
+ "expiry-date", "null", "name-only", "show-origin", "show-scope", "includes", "no-includes", "default=",
620
+ "fixed-value", "comment=", "no-comment", "value=", "all", "regexp", "url=", "help"))
621
+ GIT_DIFF_OPTIONS = ("psuU:WqvabRwzB::M::C::D", ("patch", "no-patch", "stat=?", "numstat", "shortstat", "summary",
622
+ "name-only", "name-status", "check", "binary", "full-index", "color=?", "no-color", "word-diff=?",
623
+ "no-ext-diff", "no-textconv", "cached", "staged", "relative=?", "reverse", "quiet", "exit-code", "output=",
624
+ "unified=", "function-context", "ignore-all-space", "ignore-space-change", "help"))
625
+ GIT_LOG_OPTIONS = (GIT_DIFF_OPTIONS[0] + "n:", GIT_DIFF_OPTIONS[1] + (
626
+ "oneline", "pretty=?", "format=", "decorate=?", "no-decorate", "all", "graph", "first-parent",
627
+ "no-merges", "merges", "max-count=", "since=", "until=", "author=", "grep=", "date=", "abbrev-commit"))
628
+ GIT_TOOL_OPTIONS = {
629
+ "config": GIT_CONFIG_OPTIONS,
630
+ "commit": ("aC:c:F:m:t:nqvseuS::", ("all", "reuse-message=", "reedit-message=", "file=", "message=", "template=",
631
+ "no-verify", "no-edit", "edit", "amend", "signoff", "quiet", "verbose", "allow-empty", "allow-empty-message",
632
+ "dry-run", "only", "include", "interactive", "patch", "reset-author", "author=", "date=", "fixup=",
633
+ "squash=", "cleanup=", "status", "no-status", "gpg-sign=?", "no-gpg-sign", "help")),
634
+ "status": ("sbzuv", ("short", "branch", "porcelain=?", "long", "verbose", "null", "show-stash",
635
+ "untracked-files=?", "ignored=?", "ignore-submodules=?", "column=?", "no-column", "help")),
636
+ "add": ("nvpifAuN", ("dry-run", "verbose", "patch", "interactive", "force", "update", "all", "intent-to-add",
637
+ "refresh", "ignore-errors", "ignore-missing", "renormalize", "chmod=", "pathspec-from-file=",
638
+ "pathspec-file-nul", "help")),
639
+ "format-patch": (GIT_LOG_OPTIONS[0] + "o:", GIT_LOG_OPTIONS[1] + ("output-directory=", "stdout", "cover-letter",
640
+ "numbered", "no-numbered", "start-number=", "suffix=", "subject-prefix=", "to=", "cc=", "thread=?")),
641
+ "archive": ("o:v", ("output=", "format=", "prefix=", "remote=", "exec=", "list", "verbose", "help")),
642
+ }
643
+ GIT_TOOL_OPTIONS.update({name: GIT_DIFF_OPTIONS for name in ("diff", "diff-files", "diff-index", "diff-tree", "range-diff")})
644
+ GIT_TOOL_OPTIONS.update({name: GIT_LOG_OPTIONS for name in ("log", "show", "whatchanged", "stash")})
645
+ TOOL_OPTIONS = dict(FILE_OPTIONS, **{
646
+ "ls": ("aAbBcCdDfFgGhHiklLmnpqQrRsStTuUvwx1", ("all", "almost-all", "color=?", "classify=?", "directory", "help",
647
+ "version", "human-readable", "recursive", "reverse", "size", "sort=", "time=", "format=", "quoting-style=")),
648
+ "cat": ("AbeEnstTuv", ("show-all", "number-nonblank", "show-ends", "number", "squeeze-blank", "show-tabs",
649
+ "show-nonprinting", "help", "version")),
650
+ "pytest": ("qvxsra::k:m:p:c:o:n:", ("quiet", "verbose", "exitfirst", "maxfail=", "disable-warnings", "collect-only",
651
+ "tb=", "help", "version", "no-header", "no-summary", "strict-markers", "strict-config")),
652
+ "npm": ("v", ("version", "help", "prefix=", "workspace=", "workspaces", "silent")),
653
+ "uv": ("qv", ("help", "version", "offline", "directory=", "project=", "no-progress")),
654
+ "find": ("", ()), # find's expression grammar is validated separately
655
+ })
656
+ TOOL_OPTIONS["py.test"] = TOOL_OPTIONS["pytest"]
657
+ # These shipped instruments have no fixed options in their grants. Any explicit
658
+ # option not declared here is unknown; a trailing wildcard remains an open prefix.
659
+ TOOL_OPTIONS.update({name: ("", ()) for name in ("grep", "head", "tail", "ps", "lsof", "read")})
660
+
661
+
662
+ # Only these script-command paths are understood. Other uv tool operations, such
663
+ # as installation, are deliberately unknown rather than guessed harmless.
664
+ SCRIPT_COMMANDS = {
665
+ "npm": {"test": True, "run": True, "run-script": True, "rum": True, "urn": True, "exec": True, "x": True},
666
+ "uv": {"sync": True, "run": True, "tool": {"run": True}},
667
+ }
668
+
669
+
670
+ # A grammar is not an effect classification. Every admitted git command has a policy;
671
+ # commands outside this map remain unknown even if an option grammar is later supplied.
672
+ # The four shipped read/add commands retain their existing implicit-config allowance.
673
+ # Explicit program selection is never covered by that allowance.
674
+ GIT_EFFECTS = {
675
+ "status": "shipped-read", "diff": "shipped-read", "log": "shipped-read", "add": "index",
676
+ "commit": "code", "config": "config", "format-patch": "file", "archive": "archive", "stash": "stash",
677
+ "diff-files": "code", "diff-index": "code", "diff-tree": "code", "range-diff": "code",
678
+ "show": "code", "whatchanged": "code",
679
+ }
680
+
681
+
682
+ def _option_names(table):
683
+ return {"-" + letter for letter in _letters(table[0])} | {"--" + word.rstrip("=?") for word in table[1]}
684
+
685
+
686
+ # Explicit inert inventory: adding parser syntax alone grants no new option semantics.
687
+ # These options only modify the already classified command. Side effects are listed below.
688
+ INERT_OPTIONS = {
689
+ ('wrapper', 'env'): (
690
+ '--block-signal --debug --default-signal --help --ignore-environment --ignore-signal '
691
+ '--list-signal-handling --null --unset --version -0 -i -u -v'),
692
+ ('wrapper', 'timeout'): (
693
+ '--foreground --help --kill-after --preserve-status --signal --verbose --version -f -k -p -s '
694
+ '-v'),
695
+ ('wrapper', 'nice'): (
696
+ '--adjustment --help --version -n -number'),
697
+ ('wrapper', 'nohup'): (
698
+ '--help --version'),
699
+ ('wrapper', 'stdbuf'): (
700
+ '--error --help --input --output --version -e -i -o'),
701
+ ('wrapper', 'xargs'): (
702
+ '--arg-file --delimiter --eof --exit --help --interactive --max-args --max-chars --max-lines '
703
+ '--max-procs --no-run-if-empty --null --open-tty --process-slot-var --replace --show-limits '
704
+ '--verbose --version -0 -E -I -J -L -P -R -S -a -d -e -i -l -n -o -p -r -s -t -x'),
705
+ ('wrapper', 'time'): (
706
+ '--append --format --help --portability --quiet --verbose --version -V -a -f -h -l -p -q -v'),
707
+ ('wrapper', 'command'): (
708
+ '-V -p -v'),
709
+ ('wrapper', 'exec'): (
710
+ '-c -l'),
711
+ ('wrapper', 'builtin'): (
712
+ ''),
713
+ ('wrapper', 'noglob'): (
714
+ ''),
715
+ ('wrapper', 'nocorrect'): (
716
+ ''),
717
+ ('wrapper', '-'): (
718
+ ''),
719
+ ('wrapper', '!'): (
720
+ ''),
721
+ ('wrapper', 'coproc'): (
722
+ ''),
723
+ ('wrapper', 'caffeinate'): (
724
+ '-d -i -m -s -t -u -w'),
725
+ ('wrapper', 'sudo'): (
726
+ '--background --bell --close-from --command-timeout --group --help --host --list --no-update '
727
+ '--non-interactive --other-user --preserve-env --preserve-groups --prompt --remove-timestamp '
728
+ '--reset-timestamp --role --set-home --stdin --type --user --validate --version -B -C -E -H '
729
+ '-K -N -P -S -T -U -V -b -g -h -k -l -n -p -r -t -u -v'),
730
+ ('wrapper', 'genv'): (
731
+ '--block-signal --debug --default-signal --help --ignore-environment --ignore-signal '
732
+ '--list-signal-handling --null --unset --version -0 -i -u -v'),
733
+ ('wrapper', 'gnice'): (
734
+ '--adjustment --help --version -n -number'),
735
+ ('wrapper', 'gnohup'): (
736
+ '--help --version'),
737
+ ('wrapper', 'gstdbuf'): (
738
+ '--error --help --input --output --version -e -i -o'),
739
+ ('wrapper', 'gtime'): (
740
+ '--append --format --help --portability --quiet --verbose --version -V -a -f -h -l -p -q -v'),
741
+ ('wrapper', 'gtimeout'): (
742
+ '--foreground --help --kill-after --preserve-status --signal --verbose --version -f -k -p -s '
743
+ '-v'),
744
+ ('wrapper', 'gxargs'): (
745
+ '--arg-file --delimiter --eof --exit --help --interactive --max-args --max-chars --max-lines '
746
+ '--max-procs --no-run-if-empty --null --open-tty --process-slot-var --replace --show-limits '
747
+ '--verbose --version -0 -E -I -J -L -P -R -S -a -d -e -i -l -n -o -p -r -s -t -x'),
748
+ ('tool', 'cp'): (
749
+ '--archive --attributes-only --context --copy-contents --debug --force --help --interactive '
750
+ '--link --no-clobber --no-dereference --no-preserve --no-target-directory --one-file-system '
751
+ '--parents --preserve --recursive --reflink --remove-destination --sparse '
752
+ '--strip-trailing-slashes --symbolic-link --update --verbose --version -B -H -L -P -R -T -a '
753
+ '-c -d -f -i -l -n -p -r -s -u -v -x'),
754
+ ('tool', 'mv'): (
755
+ '--context --debug --exchange --force --help --interactive --no-clobber --no-copy '
756
+ '--no-target-directory --strip-trailing-slashes --update --verbose --version -T -f -h -i -n '
757
+ '-u -v'),
758
+ ('tool', 'rm'): (
759
+ '--dir --force --help --interactive --no-preserve-root --one-file-system --preserve-root '
760
+ '--recursive --verbose --version -I -P -R -W -d -f -i -r -v'),
761
+ ('tool', 'tee'): (
762
+ '--append --help --ignore-interrupts --output-error --version -a -i -p'),
763
+ ('tool', 'ls'): (
764
+ '--all --almost-all --classify --color --directory --format --help --human-readable '
765
+ '--quoting-style --recursive --reverse --size --sort --time --version -1 -A -B -C -D -F -G '
766
+ '-H -L -Q -R -S -T -U -a -b -c -d -f -g -h -i -k -l -m -n -p -q -r -s -t -u -v -w -x'),
767
+ ('tool', 'cat'): (
768
+ '--help --number --number-nonblank --show-all --show-ends --show-nonprinting --show-tabs '
769
+ '--squeeze-blank --version -A -E -T -b -e -n -s -t -u -v'),
770
+ ('tool', 'pytest'): (
771
+ '--collect-only --disable-warnings --exitfirst --help --maxfail --no-header --no-summary '
772
+ '--quiet --strict-config --strict-markers --tb --verbose --version -a -k -m -n -q -r -s -v '
773
+ '-x'),
774
+ ('tool', 'npm'): (
775
+ '--help --silent --version -v'),
776
+ ('tool', 'uv'): (
777
+ '--help --no-progress --offline --version -q -v'),
778
+ ('tool', 'find'): (
779
+ ''),
780
+ ('tool', 'py.test'): (
781
+ '--collect-only --disable-warnings --exitfirst --help --maxfail --no-header --no-summary '
782
+ '--quiet --strict-config --strict-markers --tb --verbose --version -a -k -m -n -q -r -s -v '
783
+ '-x'),
784
+ ('tool', 'grep'): (
785
+ ''),
786
+ ('tool', 'head'): (
787
+ ''),
788
+ ('tool', 'tail'): (
789
+ ''),
790
+ ('tool', 'ps'): (
791
+ ''),
792
+ ('tool', 'lsof'): (
793
+ ''),
794
+ ('tool', 'read'): (
795
+ ''),
796
+ ('git', 'config'): (
797
+ '--all --blob --bool --bool-or-int --comment --default --expiry-date --fixed-value --get '
798
+ '--get-all --get-color --get-colorbool --get-regexp --get-urlmatch --help --includes --int '
799
+ '--list --name-only --no-comment --no-includes --null --path --regexp --show-origin '
800
+ '--show-scope --type --url --value -l -t -z'),
801
+ ('git', 'commit'): (
802
+ '--all --allow-empty --allow-empty-message --amend --author --cleanup --date --dry-run '
803
+ '--file --fixup --help --include --message --no-edit --no-gpg-sign --no-status --no-verify '
804
+ '--only --quiet --reset-author --reuse-message --signoff --squash --status --template '
805
+ '--verbose -C -F -a -m -n -q -s -t -u -v'),
806
+ ('git', 'status'): (
807
+ '--branch --column --help --ignore-submodules --ignored --long --no-column --null '
808
+ '--porcelain --short --show-stash --untracked-files --verbose -b -s -u -v -z'),
809
+ ('git', 'add'): (
810
+ '--all --chmod --dry-run --force --help --ignore-errors --ignore-missing --intent-to-add '
811
+ '--interactive --patch --pathspec-file-nul --pathspec-from-file --refresh --renormalize '
812
+ '--update --verbose -A -N -f -i -n -p -u -v'),
813
+ ('git', 'format-patch'): (
814
+ '--abbrev-commit --all --author --binary --cached --cc --check --color --cover-letter --date '
815
+ '--decorate --exit-code --first-parent --format --full-index --function-context --graph '
816
+ '--grep --help --ignore-all-space --ignore-space-change --max-count --merges --name-only '
817
+ '--name-status --no-color --no-decorate --no-ext-diff --no-merges --no-numbered --no-patch '
818
+ '--no-textconv --numbered --numstat --oneline --patch --pretty --quiet --relative --reverse '
819
+ '--shortstat --since --staged --start-number --stat --stdout --subject-prefix --suffix '
820
+ '--summary --thread --to --unified --until --word-diff -B -C -D -M -R -U -W -a -b -n -p -q '
821
+ '-s -u -v -w -z'),
822
+ ('git', 'archive'): (
823
+ '--help --list --prefix --verbose -v'),
824
+ ('git', 'diff'): (
825
+ '--binary --cached --check --color --exit-code --full-index --function-context --help '
826
+ '--ignore-all-space --ignore-space-change --name-only --name-status --no-color --no-ext-diff '
827
+ '--no-patch --no-textconv --numstat --patch --quiet --relative --reverse --shortstat '
828
+ '--staged --stat --summary --unified --word-diff -B -C -D -M -R -U -W -a -b -p -q -s -u -v '
829
+ '-w -z'),
830
+ ('git', 'diff-files'): (
831
+ '--binary --cached --check --color --exit-code --full-index --function-context --help '
832
+ '--ignore-all-space --ignore-space-change --name-only --name-status --no-color --no-ext-diff '
833
+ '--no-patch --no-textconv --numstat --patch --quiet --relative --reverse --shortstat '
834
+ '--staged --stat --summary --unified --word-diff -B -C -D -M -R -U -W -a -b -p -q -s -u -v '
835
+ '-w -z'),
836
+ ('git', 'diff-index'): (
837
+ '--binary --cached --check --color --exit-code --full-index --function-context --help '
838
+ '--ignore-all-space --ignore-space-change --name-only --name-status --no-color --no-ext-diff '
839
+ '--no-patch --no-textconv --numstat --patch --quiet --relative --reverse --shortstat '
840
+ '--staged --stat --summary --unified --word-diff -B -C -D -M -R -U -W -a -b -p -q -s -u -v '
841
+ '-w -z'),
842
+ ('git', 'diff-tree'): (
843
+ '--binary --cached --check --color --exit-code --full-index --function-context --help '
844
+ '--ignore-all-space --ignore-space-change --name-only --name-status --no-color --no-ext-diff '
845
+ '--no-patch --no-textconv --numstat --patch --quiet --relative --reverse --shortstat '
846
+ '--staged --stat --summary --unified --word-diff -B -C -D -M -R -U -W -a -b -p -q -s -u -v '
847
+ '-w -z'),
848
+ ('git', 'range-diff'): (
849
+ '--binary --cached --check --color --exit-code --full-index --function-context --help '
850
+ '--ignore-all-space --ignore-space-change --name-only --name-status --no-color --no-ext-diff '
851
+ '--no-patch --no-textconv --numstat --patch --quiet --relative --reverse --shortstat '
852
+ '--staged --stat --summary --unified --word-diff -B -C -D -M -R -U -W -a -b -p -q -s -u -v '
853
+ '-w -z'),
854
+ ('git', 'log'): (
855
+ '--abbrev-commit --all --author --binary --cached --check --color --date --decorate '
856
+ '--exit-code --first-parent --format --full-index --function-context --graph --grep --help '
857
+ '--ignore-all-space --ignore-space-change --max-count --merges --name-only --name-status '
858
+ '--no-color --no-decorate --no-ext-diff --no-merges --no-patch --no-textconv --numstat '
859
+ '--oneline --patch --pretty --quiet --relative --reverse --shortstat --since --staged --stat '
860
+ '--summary --unified --until --word-diff -B -C -D -M -R -U -W -a -b -n -p -q -s -u -v -w -z'),
861
+ ('git', 'show'): (
862
+ '--abbrev-commit --all --author --binary --cached --check --color --date --decorate '
863
+ '--exit-code --first-parent --format --full-index --function-context --graph --grep --help '
864
+ '--ignore-all-space --ignore-space-change --max-count --merges --name-only --name-status '
865
+ '--no-color --no-decorate --no-ext-diff --no-merges --no-patch --no-textconv --numstat '
866
+ '--oneline --patch --pretty --quiet --relative --reverse --shortstat --since --staged --stat '
867
+ '--summary --unified --until --word-diff -B -C -D -M -R -U -W -a -b -n -p -q -s -u -v -w -z'),
868
+ ('git', 'whatchanged'): (
869
+ '--abbrev-commit --all --author --binary --cached --check --color --date --decorate '
870
+ '--exit-code --first-parent --format --full-index --function-context --graph --grep --help '
871
+ '--ignore-all-space --ignore-space-change --max-count --merges --name-only --name-status '
872
+ '--no-color --no-decorate --no-ext-diff --no-merges --no-patch --no-textconv --numstat '
873
+ '--oneline --patch --pretty --quiet --relative --reverse --shortstat --since --staged --stat '
874
+ '--summary --unified --until --word-diff -B -C -D -M -R -U -W -a -b -n -p -q -s -u -v -w -z'),
875
+ ('git', 'stash'): (
876
+ '--abbrev-commit --all --author --binary --cached --check --color --date --decorate '
877
+ '--exit-code --first-parent --format --full-index --function-context --graph --grep --help '
878
+ '--ignore-all-space --ignore-space-change --max-count --merges --name-only --name-status '
879
+ '--no-color --no-decorate --no-ext-diff --no-merges --no-patch --no-textconv --numstat '
880
+ '--oneline --patch --pretty --quiet --relative --reverse --shortstat --since --staged --stat '
881
+ '--summary --unified --until --word-diff -B -C -D -M -R -U -W -a -b -n -p -q -s -u -v -w -z'),
882
+ ('global', 'git'): (
883
+ '--glob-pathspecs --html-path --icase-pathspecs --info-path --list-cmds --literal-pathspecs '
884
+ '--man-path --no-advice --no-lazy-fetch --no-optional-locks --no-pager --no-replace-objects '
885
+ '--noglob-pathspecs -P'),
886
+ }
887
+ OPTION_EFFECTS = {key: dict.fromkeys(options.split(), "inert") for key, options in INERT_OPTIONS.items()}
888
+ DIRECTORY_OPTIONS = {
889
+ ("wrapper", "env"): ("-C", "--chdir"), ("wrapper", "genv"): ("-C", "--chdir"),
890
+ ("wrapper", "sudo"): ("-D", "--chdir", "-R", "--chroot", "-i", "--login"),
891
+ ("global", "git"): ("-C", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--bare"),
892
+ ("tool", "npm"): ("--prefix", "--workspace", "--workspaces"),
893
+ ("tool", "uv"): ("--directory", "--project"),
894
+ }
895
+ CODE_OPTIONS = {
896
+ **{("wrapper", name): options for name, options in WRAPPER_RUNS_ANY.items()},
897
+ ("global", "git"): ("-c", "--config-env", "--exec-path", "-p", "--paginate", "--attr-source"),
898
+ ("git", "archive"): ("--exec", "--remote", "--format"),
899
+ ("git", "commit"): ("-c", "--reedit-message", "-e", "--edit", "-S", "--gpg-sign", "--interactive", "--patch"),
900
+ ("git", "config"): ("-e", "--edit"),
901
+ ("tool", "pytest"): ("-p", "-c", "-o"), ("tool", "py.test"): ("-p", "-c", "-o"),
902
+ }
903
+ FILE_OUTPUT_OPTIONS = {
904
+ ("wrapper", "time"): ("-o", "--output"), ("wrapper", "gtime"): ("-o", "--output"),
905
+ ("global", "git"): ("--shallow-file",),
906
+ **{("git", name): ("--output",) for name in
907
+ ("diff", "diff-files", "diff-index", "diff-tree", "range-diff", "log", "show", "whatchanged", "stash")},
908
+ ("git", "format-patch"): ("-o", "--output", "--output-directory"),
909
+ ("git", "archive"): ("-o", "--output"),
910
+ ("tool", "cp"): ("-t", "--target-directory", "-S", "--suffix", "-b", "--backup"),
911
+ ("tool", "mv"): ("-t", "--target-directory", "-S", "--suffix", "-b", "--backup"),
912
+ ("git", "config"): GIT_CONFIG_WRITE_OPTIONS + ("-f", "--file", "--global", "--system", "--local", "--worktree"),
913
+ }
914
+ for _effect, _groups in (("file", FILE_OUTPUT_OPTIONS), ("code", CODE_OPTIONS), ("directory", DIRECTORY_OPTIONS)):
915
+ for _key, _options_with_effect in _groups.items():
916
+ OPTION_EFFECTS[_key].update(dict.fromkeys(_options_with_effect, _effect))
917
+ OPTION_EFFECTS["tool", "find"].update(dict.fromkeys((
918
+ "-name", "-iname", "-path", "-ipath", "-type", "-maxdepth", "-mindepth", "-mtime", "-size",
919
+ "-print", "-print0", "-empty", "-depth", "-prune", "-H", "-L", "-P"), "inert"))
920
+ OPTION_EFFECTS["tool", "find"].update(dict.fromkeys(("-exec", "-execdir", "-ok", "-okdir"), "code"))
921
+
922
+
923
+ def _classified_options(kind, name, given):
924
+ """Only reviewed option names, and no unresolved directory selection."""
925
+ known = OPTION_EFFECTS.get((kind, name))
926
+ if known is None:
927
+ return False
928
+ for option, value in given:
929
+ if option not in known:
930
+ return False
931
+ if known[option] == "directory":
932
+ # These are literal chdir operations. '.' cannot change the base, including
933
+ # in a sequence; repository/project selectors are not equivalent to chdir.
934
+ noop = ((kind == "wrapper" and name in ("env", "genv") and option in ("-C", "--chdir"))
935
+ or (kind == "wrapper" and name == "sudo" and option in ("-D", "--chdir"))
936
+ or (kind == "global" and name == "git" and option == "-C"))
937
+ if not noop or value != ".":
938
+ return False
939
+ return True
940
+
941
+
942
+ def _script_command(program, operands):
943
+ """A known leaf (runs code or not), remaining subcommands, or None for an unknown command."""
944
+ node = SCRIPT_COMMANDS[program]
945
+ for operand in operands:
946
+ if not isinstance(node, dict):
947
+ break # arguments to the selected command are not subcommands
948
+ node = node.get(operand)
949
+ if node is None:
950
+ return None
951
+ return node
952
+
953
+
954
+ def _tool_options(said):
955
+ """The validated options and operands of a tool, or None for unknown options."""
956
+ if not said:
957
+ return [], [], 0, False
958
+ name = said[0]
959
+ if name == "polyctl":
960
+ return _polyctl_options(said)
961
+ if name == "git":
962
+ if len(said) < 2 or said[1] == "":
963
+ return [], [], 0, False
964
+ table = GIT_TOOL_OPTIONS.get(said[1]) if said[1] in GIT_EFFECTS else None
965
+ if table is None:
966
+ if said[1] in ("-v", "--version", "-h", "--help"):
967
+ return _options(said[2:], "", ())
968
+ else:
969
+ return None
970
+ parsed = _options(said[2:], *table)
971
+ return parsed if parsed is not None and _classified_options("git", said[1], parsed[1]) else None
972
+ if INTERPRETERS.fullmatch(name) or name in ("make", "gmake", "npx", "uvx"):
973
+ # Already named as running arbitrary code unless exactly help/version.
974
+ return [], [], 0, False
975
+ if name == "find":
976
+ values = {"-name", "-iname", "-path", "-ipath", "-type", "-maxdepth", "-mindepth", "-mtime", "-size"}
977
+ flags = {"-print", "-print0", "-empty", "-depth", "-prune", "-H", "-L", "-P"}
978
+ operands, given, at = [], [], 1
979
+ while at < len(said):
980
+ word = said[at]
981
+ if word.startswith("-") and word not in OPTION_EFFECTS["tool", "find"]:
982
+ return None
983
+ if word in ("-exec", "-execdir", "-ok", "-okdir"):
984
+ return operands, given + [(word, None)], len(said), False # runs its command arguments
985
+ if word in values:
986
+ if at + 1 == len(said):
987
+ return operands, given + [(word, None)], len(said), True
988
+ given.append((word, said[at + 1]))
989
+ at += 2
990
+ continue
991
+ if word in flags:
992
+ given.append((word, None))
993
+ elif word.startswith("-"):
994
+ return None
995
+ else:
996
+ operands.append(word)
997
+ at += 1
998
+ return operands, given, at, False
999
+ table = TOOL_OPTIONS.get(name)
1000
+ parsed = _options(said[1:], *table) if table is not None else None
1001
+ if parsed is not None and not _classified_options("tool", name, parsed[1]):
1002
+ return None
1003
+ if parsed is not None and name in SCRIPT_COMMANDS and _script_command(name, parsed[0]) is None:
1004
+ return None
1005
+ return parsed
1006
+
1007
+
1008
+ def _polyctl_options(said):
1009
+ if len(said) < 2 or said[1] == "":
1010
+ return [], [], 0, False
1011
+ table = _polyctl_tables().get(said[1])
1012
+ if table is None:
1013
+ return None
1014
+ at, ended = 2, False
1015
+ while at < len(said):
1016
+ word = said[at]
1017
+ if word == "--":
1018
+ ended = True
1019
+ elif not ended and word.startswith("-") and word != "-":
1020
+ option, attached = _argparse_option(word, table)
1021
+ if option is None or option in POLYCTL_DIRECTORY_OPTIONS.get(said[1], ()):
1022
+ return None
1023
+ if table[option] and not attached:
1024
+ at += 1
1025
+ at += 1
1026
+ return [], [], 0, False
1027
+
1028
+
1029
+ DESCRIBES = "describes"
1030
+
1031
+
1032
+ def _wrapper(name, words, at, tail, rest, effects=None):
1033
+ """Where the command a wrapper runs starts, read past its own options and operands from `at`, as (at, words,
1034
+ tail, rest); None where the reading cannot tell what runs, DESCRIBES where it runs nothing (ALLOWLIST-DEPTH).
1035
+
1036
+ getopt reads a wrapper's options until its first word that is none, or `--`: a cluster of short ones letter by
1037
+ letter, until one that takes a value, which is the rest of the cluster or the next word; a long one by any start
1038
+ of its name that names no other, its value after `=` or, for one that needs it, the next word. An option the
1039
+ declaration does not hold leaves the cluster, and what runs after it, unread; so does a wildcard among them, since
1040
+ a `*` there can be the rest of them and any command after."""
1041
+ # env's single '-' is its no-environment option, before NAME=VALUE operands.
1042
+ if name in ("env", "genv") and words[at:at + 1] == ["-"]:
1043
+ at += 1
1044
+ parsed = _options(words, *WRAPPERS[name], at=at, interspersed=False, numbers=name in WRAPPER_NUMBERS)
1045
+ if parsed is None:
1046
+ return None
1047
+ _, given, at, waiting = parsed
1048
+ if not _classified_options("wrapper", name, given):
1049
+ return None
1050
+ if effects is not None:
1051
+ effects.extend(value for option, value in given if option in FILE_OUTPUT_OPTIONS.get(("wrapper", name), ()))
1052
+ if name in ("nohup", "gnohup"):
1053
+ effects.append(None) # nohup.out in cwd or HOME, depending on descriptors and permissions
1054
+ options = {option for option, _ in given}
1055
+ if name in XARGS and options.intersection(XARGS_REPLACES):
1056
+ return None # Replacement may rewrite any word, including the program or subcommand.
1057
+ if waiting:
1058
+ return None if tail is not None else (len(words), words, tail, rest)
1059
+ if any(OPTION_EFFECTS["wrapper", name][option] == "code" for option in options):
1060
+ return None
1061
+ if options & set(WRAPPER_DESCRIBES.get(name, ())):
1062
+ return DESCRIBES
1063
+ at += WRAPPER_OPERANDS.get(name, 0)
1064
+ if at > len(words):
1065
+ return None if tail is not None else (len(words), words, tail, rest)
1066
+ if at == len(words) and options & set(WRAPPER_SHELLS.get(name, ())):
1067
+ return None
1068
+ if name in XARGS:
1069
+ return at, words, "", "*" # stdin appends arguments after the fixed command words.
1070
+ return at, words, tail, rest
1071
+
1072
+
1073
+ def _git(words, at, tail, rest):
1074
+ """git's reading from after its program: its own options taken off, and the configuration -c sets kept for what
1075
+ it does to the hook (ALLOWLIST-DEPTH)."""
1076
+ config = []
1077
+ while at < len(words):
1078
+ word = words[at]
1079
+ if word == "":
1080
+ return [], None, (), rest
1081
+ name, equals, value = word.partition("=") if word.startswith("--") else (word, "", "")
1082
+ if name not in GIT_OPTIONS:
1083
+ if word.startswith("-") and word not in ("-v", "--version", "-h", "--help"):
1084
+ return None
1085
+ break
1086
+ if name == "--exec-path" and equals:
1087
+ return None
1088
+ if equals and not GIT_OPTIONS[name]:
1089
+ return None
1090
+ if GIT_OPTIONS[name] and not equals:
1091
+ if at + 1 >= len(words):
1092
+ return None if tail is not None else ([], None, (), rest)
1093
+ at += 1
1094
+ value, word = words[at], f"{name} {words[at]}"
1095
+ at += 1
1096
+ if not _classified_options("global", "git", [(name, value)]):
1097
+ return None
1098
+ if name in ("-p", "--paginate", "--attr-source", "--shallow-file"):
1099
+ return None
1100
+ if name in ("-c", "--config-env"):
1101
+ key = value.split("=", 1)[0].lower()
1102
+ if key != "core.hookspath" and not INERT_GIT_CONFIG.fullmatch(key):
1103
+ return None
1104
+ config.append((key, word))
1105
+ if at >= len(words) and tail is not None:
1106
+ return None
1107
+ return ["git"] + words[at:], tail, tuple(config), rest
1108
+
1109
+
1110
+ def _argparse_option(word, table):
1111
+ """(the option of `table` an argparse word names, whether its value is attached) - a long one by any start of its
1112
+ name that names no other - or (None, False)."""
1113
+ if word in table:
1114
+ return word, False
1115
+ name, equals, _ = word.partition("=")
1116
+ if equals and name in table:
1117
+ return (name, True) if table[name] else (None, False)
1118
+ if not word.startswith("--") and word[:2] in table:
1119
+ return (word[:2], True) if table[word[:2]] else (None, False)
1120
+ found = [option for option in table if option.startswith("--") and option.startswith(name)] \
1121
+ if name.startswith("--") else []
1122
+ return (found[0], bool(equals)) if len(found) == 1 and (not equals or table[found[0]]) else (None, False)
1123
+
1124
+
1125
+ def _polyctl_subcommand(words, at, tail):
1126
+ """Where polyctl's subcommand stands, read past polyctl's own options from `at`; None where a wildcard or an option the
1127
+ parser does not declare stands among them."""
1128
+ table = _polyctl_tables()[None]
1129
+ while at < len(words):
1130
+ word = words[at]
1131
+ if word == "--":
1132
+ at += 1
1133
+ continue
1134
+ if not word.startswith("-") or word == "-":
1135
+ return at
1136
+ option, attached = _argparse_option(word, table)
1137
+ if option is None:
1138
+ return None
1139
+ if option in POLYCTL_DIRECTORY_OPTIONS[None]:
1140
+ # Do not decode attached roots: argparse keeps the '=' in -Csrc=.'s value.
1141
+ # The audit accepts only this literal pair, including no long-option alias.
1142
+ if word != "-C" or words[at + 1:at + 2] != ["."]:
1143
+ return None
1144
+ if table[option] and not attached:
1145
+ if at + 1 >= len(words):
1146
+ return None if tail is not None else len(words)
1147
+ at += 1
1148
+ at += 1
1149
+ return at
1150
+
1151
+
1152
+ def _polyctl_lock(words, at):
1153
+ """Where the command `polyctl lock` runs starts, read past its own options from `at`; None for one it does not
1154
+ declare."""
1155
+ table = _polyctl_tables()["lock"]
1156
+ while at < len(words):
1157
+ word = words[at]
1158
+ if word == "--":
1159
+ return at + 1
1160
+ if not word.startswith("-") or word == "-":
1161
+ return at
1162
+ option, attached = _argparse_option(word, table)
1163
+ if option is None:
1164
+ return None
1165
+ at += 2 if table[option] and not attached else 1
1166
+ return at
1167
+
1168
+
1169
+ def _reading(text, effects=None):
1170
+ """What a command, or a rule's text, runs: (the complete words it runs as, its program's name first; an empty
1171
+ string for a trailing argument wildcard, or None for an exact command; the git configuration; the wildcard).
1172
+ None where
1173
+ the reading cannot tell what runs, which admits any command; no words where nothing runs (ALLOWLIST-DEPTH).
1174
+
1175
+ Each program that runs the command after it is taken off with its own options, however deep, and so are a
1176
+ rewriter, a shell's `NAME=VALUE` that changes nothing the reading reads, git's own options and polyctl's. Every program
1177
+ the reading meets is a word it needs, the last one too, and so are a wrapper's options and operands, git's and
1178
+ polyctl's own options and the word where they end: a wildcard in any of them, its folder included, can be the rest of
1179
+ them and any command after, and an option or a variable the reading does not know may change what runs, so each
1180
+ reads as any command."""
1181
+ lexed = _lex(text)
1182
+ if lexed is None:
1183
+ return None
1184
+ words, tail, rest = lexed
1185
+ rewriters, runners = _rewriters()
1186
+ at = 0
1187
+ while True:
1188
+ if at >= len(words):
1189
+ return None if tail is not None else ([], None, (), rest)
1190
+ word = words[at]
1191
+ if word == "":
1192
+ return [], None, (), rest
1193
+ if SHELL_ASSIGNMENT.match(word):
1194
+ if not INERT_VARIABLES.fullmatch(word.split("=", 1)[0]):
1195
+ return None
1196
+ at += 1
1197
+ continue
1198
+ if _program_file(word):
1199
+ return [word] + words[at + 1:], tail, (), rest
1200
+ name = _program_name(word)
1201
+ # A program Windows names otherwise - `gi\t`, `C:\x\git.exe`, `gi^t` for cmd.exe - is either, and a short
1202
+ # name, `POWERS~1` for powershell, is whichever long one it stands for.
1203
+ if re.search(r"~\d", name):
1204
+ return None
1205
+ if name in WRAPPERS:
1206
+ step = _wrapper(name, words, at + 1, tail, rest, effects)
1207
+ if step is None:
1208
+ return None
1209
+ if step == DESCRIBES:
1210
+ return [], None, (), rest
1211
+ at, words, tail, rest = step
1212
+ if name in ("env", "genv"):
1213
+ while at < len(words) and "=" in words[at]:
1214
+ if not INERT_VARIABLES.fullmatch(words[at].split("=", 1)[0]):
1215
+ return None
1216
+ at += 1
1217
+ continue
1218
+ runner = next((runner for runner in runners
1219
+ if runner[0] == name and words[at + 1:at + len(runner)] == runner[1:]), None)
1220
+ if runner or name in rewriters:
1221
+ at += len(runner) if runner else 1
1222
+ # Nothing declares which option of a rewriter or its wrapper takes the next word: with more words after
1223
+ # it, the program could be either.
1224
+ if words[at:at + 1] and words[at].startswith("-"):
1225
+ if words[at + 1:] or tail is not None or words[at] not in HARMLESS_ARGUMENTS:
1226
+ return None
1227
+ return [], None, (), rest
1228
+ continue
1229
+ if name == "polyctl":
1230
+ sub = _polyctl_subcommand(words, at + 1, tail)
1231
+ if sub is None:
1232
+ return None
1233
+ if sub < len(words) and words[sub] == "lock":
1234
+ at = _polyctl_lock(words, sub + 1)
1235
+ if at is None:
1236
+ return None
1237
+ continue
1238
+ if sub >= len(words) and tail is not None:
1239
+ return None
1240
+ if tail is not None and POLYCTL_DIRECTORY_OPTIONS.get(words[sub]):
1241
+ return None # Additional arguments may select a directory the reading cannot resolve.
1242
+ if _tool_options(["polyctl"] + words[sub:]) is None:
1243
+ return None
1244
+ return ["polyctl"] + words[sub:], tail, (), rest
1245
+ if name == "git":
1246
+ reading = _git(words, at + 1, tail, rest)
1247
+ if reading is None or _tool_options(reading[0]) is None:
1248
+ return None
1249
+ return reading
1250
+ if _tool_options([name] + words[at + 1:]) is None:
1251
+ return None
1252
+ return [name] + words[at + 1:], tail, (), rest
1253
+
1254
+
1255
+ def _rule_body(rule):
1256
+ """A Bash rule's text, a trailing `:*` written as the ` *` it means; None for a rule of another tool."""
1257
+ rule = str(rule).strip()
1258
+ if rule in ("Bash", "Bash(*)"):
1259
+ return "*"
1260
+ if not (rule.startswith("Bash(") and rule.endswith(")")):
1261
+ return None
1262
+ body = rule[len("Bash("):-1]
1263
+ return body[:-2] + " *" if body.endswith(":*") else body
1264
+
1265
+
1266
+ def _rule_reading(rule, effects=None):
1267
+ """A rule's reading; False for a rule of another tool."""
1268
+ body = _rule_body(rule)
1269
+ return False if body is None else _reading(body, effects)
1270
+
1271
+
1272
+ def unwrap(words):
1273
+ """The words a command runs as, with each program that runs the command after it, a rewriter's wrappers
1274
+ and git's global options taken off (ALLOWLIST-NORMALIZE).
1275
+
1276
+ `timeout 60 pytest -p x` runs as `pytest -p x`, `rtk proxy git commit -n` as `git commit -n`, `rtk git -C .
1277
+ commit -n` as `git commit -n`. Every one is taken off, however deep: the reading stopped after eight, and `nice`
1278
+ nine times before `polyctl features off review --by p` read as a `nice` command nothing forbids. `["*"]` where the
1279
+ reading cannot tell what runs, and the text after a rule's fixed words kept as it stands (ALLOWLIST-DEPTH).
1280
+ """
1281
+ reading = _reading(" ".join(str(word) for word in words))
1282
+ if reading is None:
1283
+ return ["*"]
1284
+ said, tail, config, rest = reading
1285
+ said = _configured_words(said, config)
1286
+ return said if tail is None else said + (tail + rest).split()
1287
+
1288
+
1289
+ def _configured_words(said, config):
1290
+ """Restore git's configuration without changing argv word boundaries."""
1291
+ return said[:1] + [word for _, option in config for word in option.split()] + said[1:]
1292
+
1293
+
1294
+ def _spelled(words, tail, rest):
1295
+ """A reading written back as a rule's text, a lone trailing wildcard as `:*`."""
1296
+ if tail is None:
1297
+ return " ".join(words)
1298
+ return " ".join(words) + ":*"
1299
+
1300
+
1301
+ def normalized_rule(rule):
1302
+ """The rule a rule is, read as the command it runs: `Bash(timeout 60 pytest:*)` is `Bash(pytest:*)`, and
1303
+ `Bash(nice:*)`, whose command is any at all, is `Bash(*)`. None for a rule whose command is already plain, or
1304
+ that runs none (ALLOWLIST-NORMALIZE).
1305
+
1306
+ An exact rule is read as the exact command it runs: `Bash(nice git commit --no-verify -m x)` skips the hook as
1307
+ `Bash(git commit --no-verify -m x)` does. A wildcard where the reading needs a word makes a rule `Bash(*)` -
1308
+ `Bash(timeout * pytest:*)` admits `timeout 1 sh -c x pytest`, and `Bash(ls*)` admits `ls/../build.sh` - and one
1309
+ after complete words stays there: `Bash(timeout 60 git commit:*)` is `Bash(git commit:*)`. Each was left to
1310
+ the samples, which a rule behind a wrapper does not admit as it stands (ALLOWLIST-DEPTH).
1311
+ """
1312
+ body = _rule_body(rule)
1313
+ if body is None:
1314
+ return None
1315
+ reading = _reading(body)
1316
+ if reading is None:
1317
+ return "Bash(*)"
1318
+ said, tail, config, rest = reading
1319
+ said = _configured_words(said, config)
1320
+ if not said:
1321
+ return None
1322
+ plain = _spelled(said, tail, rest)
1323
+ words, own_tail, own_rest = _lex(body)
1324
+ return None if not config and plain == _spelled([_program_name(words[0])] + words[1:], own_tail, own_rest) else f"Bash({plain})"
1325
+
1326
+
1327
+ # ---- what polyctl forbids, as an operation a command performs ---------------------------------------------------------
1328
+
1329
+ def _harmless(args):
1330
+ """Whether these arguments only ask a program its version or its help."""
1331
+ return bool(args) and all(arg in HARMLESS_ARGUMENTS for arg in args)
1332
+
1333
+
1334
+ def _argparse_words(args, table):
1335
+ """(the positionals, the option words, whether the last option waits for its value) of an argparse command line,
1336
+ given which options take a value: an option may stand among the positionals, and everything after `--` is one.
1337
+ An option the table does not hold is taken to take none, and argparse refuses the command then anyway."""
1338
+ positionals, options, at, ended = [], [], 0, False
1339
+ while at < len(args):
1340
+ word = args[at]
1341
+ if ended or not word.startswith("-") or word == "-":
1342
+ positionals.append(word)
1343
+ elif word == "--":
1344
+ ended = True
1345
+ else:
1346
+ options.append(word)
1347
+ option, attached = _argparse_option(word, table)
1348
+ if option and table[option] and not attached:
1349
+ if at + 1 >= len(args):
1350
+ return positionals, options, True
1351
+ at += 1
1352
+ at += 1
1353
+ return positionals, options, False
1354
+
1355
+
1356
+ def _names(word, option):
1357
+ """Whether an argparse word names `option`: whole, before an `=`, or by a start of its name - read here as naming
1358
+ every option it starts, which can only name more."""
1359
+ name = word.split("=", 1)[0]
1360
+ return name == option or name.startswith("--") and len(name) > 2 and option.startswith(name)
1361
+
1362
+
1363
+ def _polyctl_act(subcommand, positionals=(), options=()):
1364
+ """An operation of polyctl's own: its subcommand, the values each positional after it may hold for the operation, and
1365
+ the options it needs, each named by any start of its name. A rule with a wildcard after its fixed words performs
1366
+ it where they do not rule it out: the wildcard can add the rest (GRANTS-PREFIX, ALLOWLIST-DEPTH)."""
1367
+ def performs(said, tail, config):
1368
+ if said[:1] != ["polyctl"]:
1369
+ return False
1370
+ if len(said) < 2:
1371
+ return tail is not None
1372
+ if said[1] != subcommand:
1373
+ return False
1374
+ fixed, given, waiting = _argparse_words(said[2:], _polyctl_tables()[subcommand])
1375
+ for index, values in enumerate(positionals):
1376
+ if index < len(fixed):
1377
+ if fixed[index] not in values:
1378
+ return False
1379
+ elif tail is None:
1380
+ return False
1381
+ else:
1382
+ return True
1383
+ return tail is not None or all(any(_names(word, option) for word in given) for option in options)
1384
+ return performs
1385
+
1386
+
1387
+ def _git_subcommand(said, tail, names):
1388
+ """Whether a git command's subcommand is one of `names`, or may be where a rule's fixed words end before it."""
1389
+ if said[:1] != ["git"]:
1390
+ return False
1391
+ if len(said) < 2:
1392
+ return tail is not None
1393
+ return said[1] in names
1394
+
1395
+
1396
+ def _skips_the_hook(said, tail, config):
1397
+ if not _git_subcommand(said, tail, ("commit",)):
1398
+ return False
1399
+ parsed = _tool_options(said)
1400
+ return tail is not None or parsed is None or any(option in ("-n", "--no-verify") for option, _ in parsed[1])
1401
+
1402
+
1403
+ def _redirects_the_hook(said, tail, config):
1404
+ return said[:1] == ["git"] and any(key == "core.hookspath" for key, _ in config)
1405
+
1406
+
1407
+ # A config read must be proved from parsed options, never from a token that merely
1408
+ # looks like a read flag: it may be --comment's value, or a positional after --.
1409
+ def _rewrites_the_hooks(said, tail, config):
1410
+ if not _git_subcommand(said, tail, ("config",)):
1411
+ return False
1412
+ parsed = _options(said[2:], *GIT_CONFIG_OPTIONS)
1413
+ if parsed is None or tail is not None:
1414
+ return True
1415
+ operands, given, _, waiting = parsed
1416
+ options = {option for option, _ in given}
1417
+ writes = options.intersection(GIT_CONFIG_WRITE_OPTIONS) or set(operands).intersection(GIT_CONFIG_WRITES)
1418
+ reads = options.intersection(GIT_CONFIG_READS) or operands[:1] in (["get"], ["list"])
1419
+ if reads and not writes and not waiting:
1420
+ return False
1421
+ if options.intersection(("--file", "-f", "--edit", "-e", "--rename-section", "--remove-section")):
1422
+ return True
1423
+ if set(operands).intersection(("rename-section", "remove-section", "edit")):
1424
+ return True
1425
+ return any(key.lower() == "core.hookspath" or key.lower().split(".", 1)[0] in ("include", "includeif")
1426
+ for key in operands)
1427
+
1428
+
1429
+ def _config_read(parsed):
1430
+ if parsed is None:
1431
+ return False
1432
+ operands, given, _, waiting = parsed
1433
+ options = {option for option, _ in given}
1434
+ return (not waiting and not options.intersection(GIT_CONFIG_WRITE_OPTIONS)
1435
+ and not set(operands).intersection(GIT_CONFIG_WRITES)
1436
+ and bool(options.intersection(GIT_CONFIG_READS) or operands[:1] in (["get"], ["list"])))
1437
+
1438
+
1439
+ def _git_runs_code(said, tail, config):
1440
+ if said[:1] != ["git"] or len(said) < 2:
1441
+ return False
1442
+ kind = GIT_EFFECTS.get(said[1])
1443
+ if kind is None:
1444
+ return False
1445
+ if tail is None and _harmless(said[2:]):
1446
+ return False
1447
+ parsed = _tool_options(said)
1448
+ if parsed is None:
1449
+ return True
1450
+ operands, given, _, _ = parsed
1451
+ options = {option for option, _ in given}
1452
+ if any(OPTION_EFFECTS["git", said[1]][option] == "code"
1453
+ and not (said[1] == "archive" and option == "--format" and value in ("tar", "zip"))
1454
+ for option, value in given):
1455
+ return True
1456
+ if kind in ("shipped-read", "index", "file"):
1457
+ return False
1458
+ if kind == "code":
1459
+ return True # hooks, editors, signers, external diff or text conversion
1460
+ if kind == "archive":
1461
+ return (tail is not None or bool(options & {"--exec", "--remote"})
1462
+ or any(option == "--format" and value not in ("tar", "zip") for option, value in given)
1463
+ or any(option in ("-o", "--output") and value and "." in posixpath.basename(value)
1464
+ and not value.endswith((".tar", ".zip")) for option, value in given))
1465
+ if kind == "stash":
1466
+ # Restoring/storing can run filters or reference-transaction hooks; list/show
1467
+ # take log/diff options that can request configured text conversion. No stash
1468
+ # action is one of the shipped implicit-execution exceptions.
1469
+ return True
1470
+ if kind == "config":
1471
+ if tail is not None:
1472
+ return True
1473
+ if _config_read(parsed):
1474
+ return False
1475
+ if options & {"-e", "--edit"} or operands[:1] == ["edit"]:
1476
+ return True
1477
+ key = operands[1:2] if operands[:1] in (["set"], ["unset"]) else operands[:1]
1478
+ return not key or not INERT_GIT_CONFIG.fullmatch(key[0].lower())
1479
+ return True
1480
+
1481
+
1482
+ def _git_writes_tree(said, tail, config):
1483
+ if not _git_subcommand(said, tail, ("stash", "add")):
1484
+ return False
1485
+ if tail is not None or len(said) < 2:
1486
+ return True
1487
+ parsed = _tool_options(said)
1488
+ if parsed is None:
1489
+ return True
1490
+ if said[1] == "add":
1491
+ return True # index content controls what the next commit writes
1492
+ return not parsed[0] or parsed[0][0] not in ("list", "show")
1493
+
1494
+
1495
+ def _git_writes_a_file(said, tail, config):
1496
+ # Commands that take a diff's options take `--output`; format-patch and archive write to `-o` as well.
1497
+ if not _git_subcommand(said, tail, ("diff", "diff-files", "diff-index", "diff-tree", "log", "show", "whatchanged",
1498
+ "format-patch", "range-diff", "stash", "archive", "config")):
1499
+ return False
1500
+ if tail is not None:
1501
+ return True
1502
+ parsed = _tool_options(said)
1503
+ if parsed is None:
1504
+ return True
1505
+ if said[1] == "config":
1506
+ return not _config_read(parsed)
1507
+ options = {option for option, _ in parsed[1]}
1508
+ return bool(options & {"-o", "--output", "--output-directory"}) or (
1509
+ said[1] == "format-patch" and "--stdout" not in options)
1510
+
1511
+
1512
+ def _runs_any_argument(*programs):
1513
+ """npx and uvx run the package they are handed, any arguments but a version's or help's."""
1514
+ def performs(said, tail, config):
1515
+ return bool(said) and said[0] in programs and (tail is not None or not _harmless(said[1:]) and len(said) > 1)
1516
+ return performs
1517
+
1518
+
1519
+ def _runs_a_script(program):
1520
+ """Judge only parsed subcommand operands; an option value is never a command."""
1521
+ def possible(node):
1522
+ return any(possible(child) for child in node.values()) if isinstance(node, dict) else node
1523
+
1524
+ def performs(said, tail, config):
1525
+ if said[:1] != [program]:
1526
+ return False
1527
+ parsed = _tool_options(said)
1528
+ if parsed is None:
1529
+ return True
1530
+ operands, _, _, waiting = parsed
1531
+ node = _script_command(program, operands)
1532
+ if not isinstance(node, dict):
1533
+ return node is not False
1534
+ if tail is None:
1535
+ return False
1536
+ return possible(node)
1537
+ return performs
1538
+
1539
+
1540
+ def _loads_a_plugin(said, tail, config):
1541
+ if not said or said[0] not in ("pytest", "py.test"):
1542
+ return False
1543
+ # Tests and conftest.py execute code even without an explicit plugin. Config
1544
+ # (-c) and override (-o) options can additionally select plugins via addopts.
1545
+ return tail is not None or not _harmless(said[1:])
1546
+
1547
+
1548
+ def _finds_and_runs(said, tail, config):
1549
+ if said[:1] != ["find"]:
1550
+ return False
1551
+ parsed = _tool_options(said)
1552
+ return tail is not None or parsed is None or any(
1553
+ option in ("-exec", "-execdir", "-ok", "-okdir") for option, _ in parsed[1])
1554
+
1555
+
1556
+ def _makes(said, tail, config):
1557
+ # make runs what a Makefile an implementer writes says, whichever target it names: bare, the first.
1558
+ return bool(said) and said[0] in ("make", "gmake") and (tail is not None or not _harmless(said[1:]))
1559
+
1560
+
1561
+ # polyctl's coordination files, which the architect edits; any other path is a product file to it (GRANTS-PINNED).
1562
+ COORDINATION = ("agent-mail", ".polyctl/backlog.md", ".polyctl/board.md", ".polyctl/inbox")
1563
+
1564
+
1565
+ def _outside(path):
1566
+ """Whether a path a command names is outside polyctl's coordination files, as far as its words tell."""
1567
+ path = path.replace("\\", "/")
1568
+ if path[:1] in ("/", "~") or re.match(r"[A-Za-z]:", path):
1569
+ return True
1570
+ path = posixpath.normpath(path)
1571
+ return not any(path == place or path.startswith(place + "/") for place in COORDINATION)
1572
+
1573
+
1574
+ def _touches_a_product_file(*programs):
1575
+ """rm, cp, mv or tee naming a path outside polyctl's coordination files, as an operand or as cp's and mv's target."""
1576
+ def performs(said, tail, config):
1577
+ if not said or said[0] not in programs:
1578
+ return False
1579
+ if tail is not None:
1580
+ return True
1581
+ parsed = _options(said[1:], *FILE_OPTIONS[said[0]])
1582
+ if parsed is None:
1583
+ return True
1584
+ paths, given, _, waiting = parsed
1585
+ paths += [value for option, value in given if option in ("-t", "--target-directory") and value is not None]
1586
+ if any(option in ("-b", "--backup", "-S", "--suffix") for option, _ in given):
1587
+ # Even a plain suffix can leave the exact-file allowlist: .polyctl/board.md~
1588
+ # is not .polyctl/board.md. Do not guess which numbered backup/destination exists.
1589
+ return True
1590
+ if waiting:
1591
+ return True
1592
+ return any(map(_outside, paths))
1593
+ return performs
1594
+
1595
+
1596
+ # Each forbidden command above, as the operation it performs: (why, how it is shown, whether a command's reading
1597
+ # performs it). An exact rule was compared with the samples as strings, so `Bash(git commit --no-verify -m y)` passed
1598
+ # beside the sample's `-m x`; the samples are still asked of a rule with a wildcard, as the harness matches it, and
1599
+ # tests/test_allowlist_depth.py holds each sample to its operation (ALLOWLIST-DEPTH). `polyctl lock` is read as the
1600
+ # wrapper it is, and an interpreter as the closed world INTERPRETERS is.
1601
+ OPERATIONS = (
1602
+ ("runs code the project may hold", "program file",
1603
+ lambda said, tail, config: bool(said) and _program_file(said[0])),
1604
+ ("skips the commit hook", "git commit --no-verify", _skips_the_hook),
1605
+ ("redirects the commit hook", "git -c core.hooksPath=", _redirects_the_hook),
1606
+ ("rewrites the hook configuration", "git config core.hooksPath", _rewrites_the_hooks),
1607
+ ("runs arbitrary code", "git hooks, filters or selected programs", _git_runs_code),
1608
+ ("opens a push window", "polyctl push allow", _polyctl_act("push", (("allow",),))),
1609
+ ("waives a gate", "polyctl waive", _polyctl_act("waive")),
1610
+ ("records a review polyctl did not run", "polyctl collect-review", _polyctl_act("collect-review")),
1611
+ ("records a person's review", "polyctl person-review", _polyctl_act("person-review")),
1612
+ ("opts into same-family review", "polyctl config set review.same_family",
1613
+ _polyctl_act("config", (("set",), ("review.same_family",)))),
1614
+ ("opts into same-family review", "polyctl init --review-tier", _polyctl_act("init", (), ("--review-tier",))),
1615
+ ("switches review off", "polyctl features off review", _polyctl_act("features", (("off",), ("review",)))),
1616
+ ("switches the inventory review off", "polyctl features off inventory_review",
1617
+ _polyctl_act("features", (("off",), ("inventory_review",)))),
1618
+ ("switches the Windows reviewer job off", "polyctl features off windows_job",
1619
+ _polyctl_act("features", (("off",), ("windows_job",)))),
1620
+ ("switches the project to lite mode", "polyctl mode lite", _polyctl_act("mode", (("lite",),))),
1621
+ ("switches the project to lite mode", "polyctl config set mode",
1622
+ _polyctl_act("config", (("set",), ("mode",), ("lite",)))),
1623
+ ("names the family that wrote a waived range", "polyctl catchup --author-family",
1624
+ _polyctl_act("catchup", (), ("--author-family",))),
1625
+ ("states which waived slices only moved code", "polyctl catchup --move-only", _polyctl_act("catchup", (), ("--move-only",))),
1626
+ ("replaces a waived range's commit claims", "polyctl catchup --boundary", _polyctl_act("catchup", (), ("--boundary",))),
1627
+ ("records harness configuration as seen", "polyctl harness seen --digest",
1628
+ _polyctl_act("harness", (("seen",),), ("--digest",))),
1629
+ ("records harness configuration as seen", "polyctl harness seen --ask", _polyctl_act("harness", (("seen",),), ("--ask",))),
1630
+ ("grants a coordination commit", "polyctl commit-ok --by", _polyctl_act("commit-ok", (), ("--by",))),
1631
+ ("grants a coordination commit", "polyctl commit-ok --ask", _polyctl_act("commit-ok", (), ("--ask",))),
1632
+ ("grants a coordination commit", "polyctl commit-ok --digest", _polyctl_act("commit-ok", (), ("--digest",))),
1633
+ ("attests a restored backup", "polyctl restore --by", _polyctl_act("restore", (), ("--by",))),
1634
+ ("attests a restored backup", "polyctl restore --ask", _polyctl_act("restore", (), ("--ask",))),
1635
+ ("removes the hooks", "polyctl hooks uninstall", _polyctl_act("hooks", (("uninstall",),))),
1636
+ ("installs a menu bar plugin", "polyctl surfaces install", _polyctl_act("surfaces", (("install",),))),
1637
+ ("removes a menu bar plugin", "polyctl surfaces uninstall", _polyctl_act("surfaces", (("uninstall",),))),
1638
+ ("pages a person", "polyctl doctor --check --notify", _polyctl_act("doctor", (), ("--check", "--notify"))),
1639
+ ("runs arbitrary code", "npx", _runs_any_argument("npx", "uvx")),
1640
+ ("runs arbitrary code", "npm run", _runs_a_script("npm")),
1641
+ ("runs arbitrary code", "uv run", _runs_a_script("uv")),
1642
+ ("runs arbitrary code", "pytest -p", _loads_a_plugin),
1643
+ ("runs arbitrary code", "find -exec", _finds_and_runs),
1644
+ ("runs arbitrary code", "make", _makes),
1645
+ )
1646
+ IMPLEMENTER_OPERATIONS = (
1647
+ ("abandons a slice, which the architect decides", "polyctl slice abandon", _polyctl_act("slice", (("abandon",),))),
1648
+ ("re-specifies a slice, restarting its round budget", "polyctl decide --scope", _polyctl_act("decide", (), ("--scope",))),
1649
+ ("changes the settings that govern its own review", "polyctl config set review_timeout",
1650
+ _polyctl_act("config", (("set",), ("review_timeout",)))),
1651
+ )
1652
+ ARCHITECT_OPERATIONS = (
1653
+ ("removes a product file", "rm", _touches_a_product_file("rm")),
1654
+ ("writes the working tree or index", "git tree or index write", _git_writes_tree),
1655
+ ("writes a product file", "git diff --output", _git_writes_a_file),
1656
+ ("writes a product file", "cp, mv or tee", _touches_a_product_file("cp", "mv", "tee")),
1657
+ )
1658
+
1659
+
1660
+ def _settings_operations():
1661
+ """Exact values and unsets also change the loop's settings (SETTINGS-2, TRIAGE-1-LOW, ALLOWLIST-DEPTH)."""
1662
+ return tuple(("changes a setting that governs its own work", f"polyctl config {action}",
1663
+ _polyctl_act("config", ((action,),))) for action in ("set", "unset"))
1664
+
1665
+
1666
+ def through_rewriters(forbidden):
1667
+ """Each forbidden (reason, command) as a command rewriter would be handed it, and each of the rewriter's
1668
+ wrappers that runs whatever follows it, as forbidden as the command itself (GRANTS-RTK).
1669
+
1670
+ A rewriter runs a command it has no filter for as it is, and passes the words after one it
1671
+ filters to the program it stands for (measured on rtk: `rtk sh -c x` ran sh, and
1672
+ `rtk git -c core.fsmonitor=<command> status` ran the command, as `git -c` does), so a rule
1673
+ admitting `rtk git commit -n -m x` skips the commit hook as `Bash(git commit:*)` does. A grant
1674
+ polyctl composes gains only the rewritten form of a rule it already holds, which admits none of
1675
+ these; asking them is what names a wider rule a person writes, `Bash(rtk:*)` or
1676
+ `Bash(rtk git:*)`, the way the command's own rule is named.
1677
+ """
1678
+ from . import lib as A
1679
+ found, asked = [], set()
1680
+ for rewriter in A.command_rewriters():
1681
+ name = rewriter["command"].strip()
1682
+ declared = rewriter.get("runs_any_command")
1683
+ wrappers = [wrapper.strip() for wrapper in declared if isinstance(wrapper, str) and wrapper.strip()] \
1684
+ if isinstance(declared, list) else []
1685
+ for reason, command in [(reason, f"{name} {command}") for reason, command in forbidden] \
1686
+ + [("runs any command", f"{wrapper} sh -c x") for wrapper in wrappers]:
1687
+ # `rtk env sh -c x` is both rtk's form of `env sh -c x` and its env wrapper; it is asked once.
1688
+ if command not in asked:
1689
+ asked.add(command)
1690
+ found.append((reason, command))
1691
+ return tuple(found)
1692
+
1693
+
1694
+ # A reviewer reads. Tools a reviewer may use, and the Claude Code flags that keep
1695
+ # every configured MCP server from starting (#24).
1696
+ REVIEWER_TOOLS = ("Read", "Grep", "Glob")
1697
+ # The same, as ACP names the kind of a tool call an agent asks leave for: Read reads, Grep and Glob search.
1698
+ # A reviewer's ACP session is let run these, once each, and nothing else; a call of a kind that changes
1699
+ # something, seen to have run, ran without that leave (ACP-REVIEWER).
1700
+ REVIEWER_TOOL_KINDS = ("read", "search")
1701
+ WRITING_TOOL_KINDS = ("edit", "delete", "move", "execute")
1702
+
1703
+
1704
+ def reviewer_problems(argv, prompt=None):
1705
+ """What a reviewer's argv can reach beyond reading, as short phrases (#24).
1706
+
1707
+ On 2026-09-07 a reviewer run as `claude -p … --allowedTools ""` started four MCP
1708
+ servers and pulled several hundred tool descriptions into the review: an allow
1709
+ list gates permissions, not which servers start. A reviewer whose adapter declares
1710
+ MCP isolation needs its required flags and none of its forbidden ones; any
1711
+ reviewer is refused every tool and any tool that writes.
1712
+ """
1713
+ args = [str(arg) for arg in argv or []]
1714
+ if not args:
1715
+ return []
1716
+ found = []
1717
+ if any(arg in GRANT_ALL for arg in args):
1718
+ found.append("it is granted every tool")
1719
+ extra = sorted({rule.split("(", 1)[0] for rule in rules(args, prompt=prompt)} - set(REVIEWER_TOOLS))
1720
+ if extra:
1721
+ found.append("its allowed tools go beyond reading: " + ", ".join(extra))
1722
+ # Which harness starts MCP servers unless told not to, and with which flags, is its
1723
+ # adapter's to declare (`options.mcp_isolation`, #76); so is the mode it runs in (GRANTS-PINNED).
1724
+ from . import lib as A
1725
+ found.extend(A.pin_conflicts(args, "reviewer"))
1726
+ pinned = {flag for flag, _ in A.role_pin(args, "reviewer")}
1727
+ for argument in A.bypass_arguments(args):
1728
+ flag = argument.split(" ", 1)[0].split("=", 1)[0]
1729
+ if argument not in GRANT_ALL and flag not in pinned:
1730
+ found.append(f"it carries {argument}, which approves for it, sandboxes nothing or checks no permission")
1731
+ program = os.path.basename(args[0]).lower().split(".")[0]
1732
+ for adapter in A.package_adapters().values():
1733
+ if program not in A.adapter_binaries(adapter):
1734
+ continue
1735
+ isolation = (adapter.get("options") or {}).get("mcp_isolation") or {}
1736
+ for flag in isolation.get("required") or []:
1737
+ if flag not in args:
1738
+ found.append(f"it starts every configured MCP server (no {flag})")
1739
+ for flag in isolation.get("forbidden") or []:
1740
+ if any(arg == flag or arg.startswith(flag + "=") for arg in args):
1741
+ found.append(f"it loads MCP servers from {flag}")
1742
+ return found
1743
+
1744
+
1745
+ def describe(role, name, found):
1746
+ """One doctor line for an actor's findings, or None when there are none."""
1747
+ if not found:
1748
+ return None
1749
+ if found[0][1] == "*":
1750
+ what = "is granted every tool" if found[0][2] == "*" else \
1751
+ f"trusts the shell tool ({found[0][2]}), which runs every command"
1752
+ return (f"{role} ({name}) {what}, so no allowlist keeps out a hook bypass "
1753
+ f"or a push; the commit hook and polyctl commit are what hold")
1754
+ parts = [f"{rule} admits `{command}` ({reason})" for reason, command, rule in found]
1755
+ shown = "; ".join(parts[:4])
1756
+ return f"{role} ({name}): {shown}" + (f"; and {len(parts) - 4} more" if len(parts) > 4 else "")