cohorte 3.0.0-dev.8 → 3.0.0

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 (229) hide show
  1. package/CHANGELOG.md +1532 -0
  2. package/README.md +316 -62
  3. package/bin/cli.js +212 -0
  4. package/bin/report.js +141 -0
  5. package/core/agents/cohorte-profile-reader.md +50 -0
  6. package/core/agents/cohorte-release.md +58 -0
  7. package/core/agents/cohorte-review.md +174 -0
  8. package/core/agents/implementer.template.md +146 -0
  9. package/core/commands/cohorte-align-ds.md +33 -0
  10. package/core/commands/cohorte-audit.md +67 -0
  11. package/core/commands/cohorte-brainstorm.md +73 -0
  12. package/core/commands/cohorte-build.md +241 -0
  13. package/core/commands/cohorte-doctor.md +133 -0
  14. package/core/commands/cohorte-fix.md +80 -0
  15. package/core/commands/cohorte-fleet.md +111 -0
  16. package/core/commands/cohorte-init-pipeline.md +30 -0
  17. package/core/commands/cohorte-intake.md +92 -0
  18. package/core/commands/cohorte-patch.md +118 -0
  19. package/core/commands/cohorte-refactor.md +57 -0
  20. package/core/commands/cohorte-retro.md +85 -0
  21. package/core/commands/cohorte-review.md +224 -0
  22. package/core/commands/cohorte-ship.md +155 -0
  23. package/core/commands/cohorte-spec.md +105 -0
  24. package/core/commands/cohorte-update-pipeline.md +115 -0
  25. package/core/hooks/gate.py +2931 -0
  26. package/core/templates/agent-handoff.md +34 -0
  27. package/core/templates/brainstorm-return.md +42 -0
  28. package/core/templates/decisions.template.md +42 -0
  29. package/core/templates/design-brief.md +37 -0
  30. package/core/templates/patch.template.md +86 -0
  31. package/core/templates/pr-body.md +25 -0
  32. package/core/templates/review-feedback.md +46 -0
  33. package/core/templates/spec.template.md +88 -0
  34. package/core/templates/steps/init-pipeline/01-detect-stack.md +44 -0
  35. package/core/templates/steps/init-pipeline/02-interview-gaps.md +55 -0
  36. package/core/templates/steps/init-pipeline/03-draft-profile.md +9 -0
  37. package/core/templates/steps/init-pipeline/04-write-render.md +91 -0
  38. package/core/templates/steps/init-pipeline/05-report.md +11 -0
  39. package/core/templates/steps/review-pr/01-pr-mode.md +54 -0
  40. package/core/workflows/audit.js +306 -0
  41. package/core/workflows/loop.js +687 -0
  42. package/core/workflows/refactor.js +291 -0
  43. package/core/workflows/review.js +491 -0
  44. package/install.ps1 +72 -0
  45. package/install.sh +69 -0
  46. package/lib/doctor.js +472 -0
  47. package/lib/install.js +377 -0
  48. package/lib/project.js +322 -0
  49. package/lib/render.js +121 -0
  50. package/lib/versions.js +145 -0
  51. package/lib/yaml.js +174 -0
  52. package/package.json +36 -17
  53. package/profile/PIPELINE.template.md +250 -0
  54. package/profile/SCHEMA.md +749 -0
  55. package/profile/cohorte.config.template.yaml +43 -0
  56. package/scripts/feature-diff.sh +118 -0
  57. package/scripts/kanban-move.sh +307 -0
  58. package/scripts/metrics/collect.mjs +542 -0
  59. package/scripts/metrics/prices.json +42 -0
  60. package/scripts/new-feature.sh.template +122 -0
  61. package/scripts/preflight.sh +114 -0
  62. package/scripts/remove-feature.sh.template +56 -0
  63. package/assets/manifest.json +0 -203
  64. package/assets/migrations/config/README.md +0 -12
  65. package/assets/migrations/state/0001_init.sql +0 -154
  66. package/assets/prompts/README.md +0 -11
  67. package/assets/prompts/agents/brainstormer.md +0 -3
  68. package/assets/prompts/agents/fixer.md +0 -7
  69. package/assets/prompts/agents/implementer.md +0 -12
  70. package/assets/prompts/agents/reviewer.md +0 -8
  71. package/assets/prompts/agents/security-reviewer.md +0 -7
  72. package/assets/prompts/agents/spec-author.md +0 -3
  73. package/assets/prompts/phases/build.md +0 -5
  74. package/assets/prompts/phases/review.md +0 -5
  75. package/assets/prompts/phases/test.md +0 -5
  76. package/assets/prompts/system.md +0 -11
  77. package/assets/schemas/agent-output.schema.json +0 -225
  78. package/assets/schemas/auth-status.schema.json +0 -87
  79. package/assets/schemas/command-result.schema.json +0 -192
  80. package/assets/schemas/commands.schema.json +0 -959
  81. package/assets/schemas/config.schema.json +0 -2281
  82. package/assets/schemas/doctor-report.schema.json +0 -104
  83. package/assets/schemas/events.schema.json +0 -8514
  84. package/assets/schemas/fake-script.schema.json +0 -549
  85. package/assets/schemas/inspect.schema.json +0 -3133
  86. package/assets/schemas/manifest.schema.json +0 -79
  87. package/assets/schemas/ownership.schema.json +0 -52
  88. package/assets/schemas/policy-verdict.schema.json +0 -282
  89. package/assets/schemas/project-model.schema.json +0 -783
  90. package/assets/schemas/project-status.schema.json +0 -217
  91. package/assets/schemas/reconcile-plan.schema.json +0 -154
  92. package/assets/schemas/run-diff.schema.json +0 -177
  93. package/assets/schemas/run-snapshot-manifest.schema.json +0 -2104
  94. package/assets/schemas/run-state.schema.json +0 -1755
  95. package/assets/schemas/runtime-capabilities.schema.json +0 -1545
  96. package/assets/schemas/sandbox-capabilities.schema.json +0 -116
  97. package/assets/schemas/skill.schema.json +0 -87
  98. package/assets/schemas/spec.schema.json +0 -202
  99. package/assets/schemas/tool-catalogue.schema.json +0 -655
  100. package/assets/schemas/trust-record.schema.json +0 -38
  101. package/assets/skills/README.md +0 -9
  102. package/assets/skills/inspect-surface.md +0 -4
  103. package/dist/agent-host.mjs +0 -2187
  104. package/dist/agent-host.mjs.map +0 -1
  105. package/dist/bundle-manifest.json +0 -128
  106. package/dist/chunks/__host-DgGPyco9.mjs +0 -18
  107. package/dist/chunks/__host-DgGPyco9.mjs.map +0 -1
  108. package/dist/chunks/align-ds-r_X_1aQ_.mjs +0 -93
  109. package/dist/chunks/align-ds-r_X_1aQ_.mjs.map +0 -1
  110. package/dist/chunks/approve-Cv135UqI.mjs +0 -19
  111. package/dist/chunks/approve-Cv135UqI.mjs.map +0 -1
  112. package/dist/chunks/audit-B4ZWQ_DI.mjs +0 -179
  113. package/dist/chunks/audit-B4ZWQ_DI.mjs.map +0 -1
  114. package/dist/chunks/auth-BT5oVp76.mjs +0 -132
  115. package/dist/chunks/auth-BT5oVp76.mjs.map +0 -1
  116. package/dist/chunks/auth-Dnlksuo5.mjs +0 -141
  117. package/dist/chunks/auth-Dnlksuo5.mjs.map +0 -1
  118. package/dist/chunks/brainstorm-SJwOIEif.mjs +0 -123
  119. package/dist/chunks/brainstorm-SJwOIEif.mjs.map +0 -1
  120. package/dist/chunks/build-C_-mbZfD.mjs +0 -19
  121. package/dist/chunks/build-C_-mbZfD.mjs.map +0 -1
  122. package/dist/chunks/cancel-KV_cpsqS.mjs +0 -15
  123. package/dist/chunks/cancel-KV_cpsqS.mjs.map +0 -1
  124. package/dist/chunks/canonical-C8UxeEmB.mjs +0 -57
  125. package/dist/chunks/canonical-C8UxeEmB.mjs.map +0 -1
  126. package/dist/chunks/catalogue-IaCJdfB8.mjs +0 -1549
  127. package/dist/chunks/catalogue-IaCJdfB8.mjs.map +0 -1
  128. package/dist/chunks/compose-DRKjQcn0.mjs +0 -7333
  129. package/dist/chunks/compose-DRKjQcn0.mjs.map +0 -1
  130. package/dist/chunks/config-Cqu5XQoP.mjs +0 -96
  131. package/dist/chunks/config-Cqu5XQoP.mjs.map +0 -1
  132. package/dist/chunks/contract-DjssDPpS.mjs +0 -335
  133. package/dist/chunks/contract-DjssDPpS.mjs.map +0 -1
  134. package/dist/chunks/contract-bQ9FJl4N.mjs +0 -123
  135. package/dist/chunks/contract-bQ9FJl4N.mjs.map +0 -1
  136. package/dist/chunks/deny-ClTxSvHJ.mjs +0 -15
  137. package/dist/chunks/deny-ClTxSvHJ.mjs.map +0 -1
  138. package/dist/chunks/diff-Qw0II0sj.mjs +0 -101
  139. package/dist/chunks/diff-Qw0II0sj.mjs.map +0 -1
  140. package/dist/chunks/discover-BZPolSZG.mjs +0 -21
  141. package/dist/chunks/discover-BZPolSZG.mjs.map +0 -1
  142. package/dist/chunks/doctor-DcDFPvQM.mjs +0 -222
  143. package/dist/chunks/doctor-DcDFPvQM.mjs.map +0 -1
  144. package/dist/chunks/fix-C9roGiQz.mjs +0 -82
  145. package/dist/chunks/fix-C9roGiQz.mjs.map +0 -1
  146. package/dist/chunks/fleet-yWHQY2ya.mjs +0 -297
  147. package/dist/chunks/fleet-yWHQY2ya.mjs.map +0 -1
  148. package/dist/chunks/gc-BBXlBF5w.mjs +0 -161
  149. package/dist/chunks/gc-BBXlBF5w.mjs.map +0 -1
  150. package/dist/chunks/init--FxxkrcT.mjs +0 -63
  151. package/dist/chunks/init--FxxkrcT.mjs.map +0 -1
  152. package/dist/chunks/inspect-Buby4cQD.mjs +0 -22
  153. package/dist/chunks/inspect-Buby4cQD.mjs.map +0 -1
  154. package/dist/chunks/intake-C1pesxCJ.mjs +0 -12
  155. package/dist/chunks/intake-C1pesxCJ.mjs.map +0 -1
  156. package/dist/chunks/logs-Giq5sUau.mjs +0 -25
  157. package/dist/chunks/logs-Giq5sUau.mjs.map +0 -1
  158. package/dist/chunks/loop-BWsUpyus.mjs +0 -212
  159. package/dist/chunks/loop-BWsUpyus.mjs.map +0 -1
  160. package/dist/chunks/migrate-DuYCAbE3.mjs +0 -33
  161. package/dist/chunks/migrate-DuYCAbE3.mjs.map +0 -1
  162. package/dist/chunks/models-Btp6X2YZ.mjs +0 -24
  163. package/dist/chunks/models-Btp6X2YZ.mjs.map +0 -1
  164. package/dist/chunks/obsidian-BHLkXx_H.mjs +0 -235
  165. package/dist/chunks/obsidian-BHLkXx_H.mjs.map +0 -1
  166. package/dist/chunks/patch-sAgVqjpx.mjs +0 -50
  167. package/dist/chunks/patch-sAgVqjpx.mjs.map +0 -1
  168. package/dist/chunks/pause-BASBfKLO.mjs +0 -16
  169. package/dist/chunks/pause-BASBfKLO.mjs.map +0 -1
  170. package/dist/chunks/policy-Du7WVBFX.mjs +0 -139
  171. package/dist/chunks/policy-Du7WVBFX.mjs.map +0 -1
  172. package/dist/chunks/providers-Dx78imKj.mjs +0 -19
  173. package/dist/chunks/providers-Dx78imKj.mjs.map +0 -1
  174. package/dist/chunks/reconcile-BHn66X3C.mjs +0 -50
  175. package/dist/chunks/reconcile-BHn66X3C.mjs.map +0 -1
  176. package/dist/chunks/refactor-DV3RfGjk.mjs +0 -153
  177. package/dist/chunks/refactor-DV3RfGjk.mjs.map +0 -1
  178. package/dist/chunks/render-DyZr5Lgi.mjs +0 -53
  179. package/dist/chunks/render-DyZr5Lgi.mjs.map +0 -1
  180. package/dist/chunks/resume-GJQRb2Eb.mjs +0 -15
  181. package/dist/chunks/resume-GJQRb2Eb.mjs.map +0 -1
  182. package/dist/chunks/retro-Dr-2RTNN.mjs +0 -78
  183. package/dist/chunks/retro-Dr-2RTNN.mjs.map +0 -1
  184. package/dist/chunks/retry-CLrUem1H.mjs +0 -15
  185. package/dist/chunks/retry-CLrUem1H.mjs.map +0 -1
  186. package/dist/chunks/review-ZsBqp3vZ.mjs +0 -35
  187. package/dist/chunks/review-ZsBqp3vZ.mjs.map +0 -1
  188. package/dist/chunks/run-BGabwbDL.mjs +0 -109
  189. package/dist/chunks/run-BGabwbDL.mjs.map +0 -1
  190. package/dist/chunks/run-tool-C3rAv4XF.mjs +0 -26
  191. package/dist/chunks/run-tool-C3rAv4XF.mjs.map +0 -1
  192. package/dist/chunks/scan-C5uDr7Yq.mjs +0 -167
  193. package/dist/chunks/scan-C5uDr7Yq.mjs.map +0 -1
  194. package/dist/chunks/schema-Bq9qtgsd.mjs +0 -583
  195. package/dist/chunks/schema-Bq9qtgsd.mjs.map +0 -1
  196. package/dist/chunks/send-BdnJ85Nz.mjs +0 -19
  197. package/dist/chunks/send-BdnJ85Nz.mjs.map +0 -1
  198. package/dist/chunks/ship-BizfUe62.mjs +0 -140
  199. package/dist/chunks/ship-BizfUe62.mjs.map +0 -1
  200. package/dist/chunks/shutdown-BM92Iyv2.mjs +0 -15
  201. package/dist/chunks/shutdown-BM92Iyv2.mjs.map +0 -1
  202. package/dist/chunks/skip-DZG5kpcH.mjs +0 -18
  203. package/dist/chunks/skip-DZG5kpcH.mjs.map +0 -1
  204. package/dist/chunks/spec-C2h3U64g.mjs +0 -65
  205. package/dist/chunks/spec-C2h3U64g.mjs.map +0 -1
  206. package/dist/chunks/spec-path-tptqR7W8.mjs +0 -10
  207. package/dist/chunks/spec-path-tptqR7W8.mjs.map +0 -1
  208. package/dist/chunks/src-Bfr1yzsn.mjs +0 -1689
  209. package/dist/chunks/src-Bfr1yzsn.mjs.map +0 -1
  210. package/dist/chunks/src-CPW2_Ons.mjs +0 -5487
  211. package/dist/chunks/src-CPW2_Ons.mjs.map +0 -1
  212. package/dist/chunks/src-Cu3TxNob.mjs +0 -783
  213. package/dist/chunks/src-Cu3TxNob.mjs.map +0 -1
  214. package/dist/chunks/src-DNsLSxgm.mjs +0 -928
  215. package/dist/chunks/src-DNsLSxgm.mjs.map +0 -1
  216. package/dist/chunks/src-DbS9gkJy.mjs +0 -117
  217. package/dist/chunks/src-DbS9gkJy.mjs.map +0 -1
  218. package/dist/chunks/src-yi5whv3n.mjs +0 -2118
  219. package/dist/chunks/src-yi5whv3n.mjs.map +0 -1
  220. package/dist/chunks/status-SMjiOMYy.mjs +0 -29
  221. package/dist/chunks/status-SMjiOMYy.mjs.map +0 -1
  222. package/dist/chunks/tail-BuhT-2PH.mjs +0 -25
  223. package/dist/chunks/tail-BuhT-2PH.mjs.map +0 -1
  224. package/dist/chunks/update-BXIppsbi.mjs +0 -16
  225. package/dist/chunks/update-BXIppsbi.mjs.map +0 -1
  226. package/dist/chunks/update-pipeline-Du-Gu1Pl.mjs +0 -56
  227. package/dist/chunks/update-pipeline-Du-Gu1Pl.mjs.map +0 -1
  228. package/dist/cli.mjs +0 -186
  229. package/dist/cli.mjs.map +0 -1
@@ -0,0 +1,2931 @@
1
+ #!/usr/bin/env python3
2
+ """Cohorte PreToolUse gate for Claude Code (3.0 — Claude Code only).
3
+
4
+ Installed per project as `.claude/hooks/cohorte-gate.py` and registered in the project's
5
+ `.claude/settings.json` as a PreToolUse hook:
6
+
7
+ python3 "$CLAUDE_PROJECT_DIR/.claude/hooks/cohorte-gate.py" matcher: Bash|Task|Agent
8
+
9
+ It reads the PreToolUse payload on stdin and either stays silent (allow, exit 0) or prints
10
+ one `hookSpecificOutput.permissionDecision` of "ask" or "deny" (exit 0). Stdlib only,
11
+ Python >= 3.8.
12
+
13
+ What it does, in order of authority:
14
+
15
+ 1. Inert outside Cohorte projects. With no `.claude/pipeline.json` pointer and no
16
+ `gate-config.json` in the project, every call is allowed silently: this file can be
17
+ registered somewhere that is not a Cohorte repo without changing anything.
18
+ 2. Built-in hard floor (any Cohorte project, even with no gate-config.json): a force push
19
+ or a remote deletion whose destination is the default branch is denied. "Force" covers
20
+ `-f`, `--force`, `--force-with-lease[=…]`, `--force-if-includes`, abbreviations
21
+ (`--forc`), combined short flags (`-uf`), `--mirror`, `--delete`/`-d`, and `+`/`:`
22
+ refspecs.
23
+ 3. Self-protection: a Bash command that writes, moves, truncates or deletes the files
24
+ the gate depends on is denied (`.claude/gate-config.json`, `.claude/preflight.ok`,
25
+ `.claude/settings.json`, `.claude/settings.local.json`, `.claude/hooks/cohorte-gate.py`,
26
+ the legacy `.cohorte/gate-config.json`, `~/.claude/settings*.json`). The same applies to
27
+ deleting `.claude/pipeline.json` or a directory that contains any of them. A
28
+ Write/Edit/MultiEdit/NotebookEdit call aimed at one of them gets "ask".
29
+ 4. Project rules from `.claude/gate-config.json` (`deny` / `ask` / `ask_on_default_branch`).
30
+ These are matched as tokens, not substrings (see "Matching").
31
+ 5. Preflight phase gate: a Task/Agent dispatch of a listed subagent needs a fresh
32
+ `.claude/preflight.ok` stamp whose content digest equals the dispatch checkout's.
33
+
34
+ Matching. The command is lexed like a shell does it: quotes, escapes, `\\`-newline
35
+ continuations, comments, heredocs (bodies are data unless fed to a shell), `$(…)`,
36
+ backticks, `<(…)`, subshells, redirections, and the separators `; && || | |& &` and newline.
37
+ Each simple command loses its prefixes (`VAR=val`, `env`, `command`, `builtin`, `exec`,
38
+ `nice`, `time`, `nohup`, `timeout`, `sudo`, …). Its basename is lowercased (`GIT`,
39
+ `/usr/bin/git`, `\\git` and `"git"` are all `git`). A pattern is lexed the same way. It
40
+ matches when its command name is equal and its positional words come, in order, at the
41
+ start of the command's positional words. Each of its flags must be present in the command,
42
+ compared by meaning: `-rf` = `-r -f` = `-fr` = `--recursive --force`. For git, global options
43
+ (`-c`, `-C`, `--git-dir`, `--no-pager`, …) are skipped, git aliases are expanded, and long
44
+ options can be abbreviated. For `git push`, every force form listed above satisfies a `-f`
45
+ or `--force` pattern. Package runners are looked through: `npx`/`pnpm exec`/`yarn`/
46
+ `bunx`/`uv run`/`python -m`… `prisma migrate reset` matches `prisma migrate reset`.
47
+
48
+ A pattern that itself contains a separator (`curl | sh`) matches a run of consecutive
49
+ commands that each match their part, joined by the same separator.
50
+
51
+ Indirection (`sh -c`, `bash <<EOF`, `eval`, `$(…)`, `| sh`, `source` of a just-written
52
+ file, inline `python -c`/`node -e` code that spawns processes, xargs, find -exec, git
53
+ aliases) is followed when the inner text is static. When it can't be judged statically,
54
+ the call gets "ask", but only if there are rules to protect (deny/ask patterns, or the
55
+ floor when the hidden text mentions git). A deny pattern found in the raw hidden text is a
56
+ deny.
57
+
58
+ Branch awareness. `ask_on_default_branch` patterns fire when the branch is the default
59
+ branch or unknown. The branch is unknown on a detached HEAD, outside a repo, after a
60
+ `cd` that can't be resolved, and for the rest of a chain after `git checkout`/`switch`,
61
+ `pushd`/`popd`, a subshell, `git -C`, or `GIT_DIR`/`GIT_WORK_TREE`. A plain `cd <dir>`
62
+ chained with `&&` or `;` is followed (never through `|`). For `git push`, the destination
63
+ also counts: `src:dst`, `HEAD`, the upstream/push target of a bare push, `--all`/`--mirror`.
64
+
65
+ Permission modes. In `bypassPermissions` and `dontAsk` nobody answers a prompt, so every
66
+ "ask" becomes a "deny" with the reason attached. `default`, `acceptEdits` and `plan` keep
67
+ "ask".
68
+
69
+ Fail closed. If the project is active and the payload is a Bash/Task/Agent call that
70
+ can't be evaluated (wrong types, internal error, unparseable JSON that still looks like a
71
+ tool call), the answer is "deny". A command the lexer can't parse (an unbalanced quote) is
72
+ not an internal error: it is denied if its raw text contains a deny pattern, and otherwise
73
+ gets "ask" when rules exist. When gate-config.json is invalid (unparseable or wrong types),
74
+ the floor and self-protection still deny, and every other Bash command and every dispatch
75
+ gets "ask" until the config is fixed.
76
+
77
+ Explicit mode, for scripts and humans:
78
+
79
+ cohorte-gate.py --check [--cwd DIR] [--unattended] [--] <command…>
80
+ cohorte-gate.py --check-dispatch [--cwd DIR] [--unattended] [--] <subagent_type>
81
+
82
+ It prints `gate: allow` / `gate: ask — …` / `gate: deny — …` and exits 0 / 1 / 2. Options
83
+ are only read before the command (or before `--`). A legacy `--runtime claude` argument is
84
+ accepted and ignored.
85
+
86
+ This is a strong guard against agent mistakes on the common forms, not a sandbox. A script
87
+ file that does a force push (`./release.sh`, `npm run x`, `make`) is not inspected. Branch
88
+ protection on the remote is the real boundary.
89
+ """
90
+
91
+ import fnmatch
92
+ import glob
93
+ import json
94
+ import os
95
+ import re
96
+ import shlex
97
+ import shutil
98
+ import subprocess
99
+ import sys
100
+ import tempfile
101
+ import time
102
+
103
+ # ── time budget ──────────────────────────────────────────────────────────────
104
+ # The hook is registered with onFailure "block": a timeout blocks the tool call. Every git
105
+ # call draws on one global budget, and an exhausted budget answers "ask", never "allow".
106
+ DEFAULT_BUDGET_S = 6.0
107
+ _START = time.monotonic()
108
+
109
+
110
+ def _budget():
111
+ try:
112
+ b = float(os.environ.get("COHORTE_GATE_BUDGET_S", "") or DEFAULT_BUDGET_S)
113
+ except ValueError:
114
+ b = DEFAULT_BUDGET_S
115
+ return max(0.0, min(b, DEFAULT_BUDGET_S)) # can only be lowered (stricter), never raised
116
+
117
+
118
+ BUDGET_S = _budget()
119
+
120
+
121
+ def remaining():
122
+ return BUDGET_S - (time.monotonic() - _START)
123
+
124
+
125
+ _GIT_ENV = None
126
+
127
+
128
+ def git_env(extra=None):
129
+ global _GIT_ENV
130
+ if _GIT_ENV is None:
131
+ _GIT_ENV = {k: v for k, v in os.environ.items()
132
+ if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR",
133
+ "GIT_OBJECT_DIRECTORY", "GIT_CEILING_DIRECTORIES")}
134
+ _GIT_ENV["GIT_OPTIONAL_LOCKS"] = "0"
135
+ _GIT_ENV["LC_ALL"] = "C"
136
+ _GIT_ENV["GIT_TERMINAL_PROMPT"] = "0"
137
+ if extra:
138
+ e = dict(_GIT_ENV)
139
+ e.update(extra)
140
+ return e
141
+ return _GIT_ENV
142
+
143
+
144
+ class TimedOut(Exception):
145
+ pass
146
+
147
+
148
+ def run_git(args, cwd, timeout=3.0, env=None, raise_timeout=False):
149
+ """(returncode, stdout) — or None when git can't run here or the budget is spent."""
150
+ left = remaining()
151
+ if left <= 0.05:
152
+ if raise_timeout:
153
+ raise TimedOut()
154
+ return None
155
+ try:
156
+ p = subprocess.run(["git"] + list(args), cwd=cwd, stdin=subprocess.DEVNULL,
157
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
158
+ universal_newlines=True, timeout=min(timeout, left),
159
+ env=env or git_env())
160
+ except subprocess.TimeoutExpired:
161
+ if raise_timeout:
162
+ raise TimedOut()
163
+ return None
164
+ except Exception:
165
+ return None
166
+ return p.returncode, p.stdout
167
+
168
+
169
+ def warn(msg):
170
+ try:
171
+ sys.stderr.write("cohorte-gate: %s\n" % msg)
172
+ except Exception:
173
+ pass
174
+
175
+
176
+ # ── lexer ────────────────────────────────────────────────────────────────────
177
+ DYN = "\x00" # stands for a run-time expansion inside a word's value
178
+
179
+
180
+ class ParseError(Exception):
181
+ pass
182
+
183
+
184
+ class Word(object):
185
+ __slots__ = ("value", "raw", "dynamic", "glob", "quoted", "substs")
186
+
187
+ def __init__(self, value="", raw=""):
188
+ self.value = value
189
+ self.raw = raw
190
+ self.dynamic = False
191
+ self.glob = False
192
+ self.quoted = False
193
+ self.substs = [] # inner command lists ($(…), `…`, <(…))
194
+
195
+ @property
196
+ def head(self):
197
+ return self.value.split(DYN, 1)[0]
198
+
199
+ def __repr__(self):
200
+ return "Word(%r)" % self.raw
201
+
202
+
203
+ def static_word(v):
204
+ return Word(v, v)
205
+
206
+
207
+ def wildcard_word():
208
+ w = Word(DYN, "$…")
209
+ w.dynamic = True
210
+ return w
211
+
212
+
213
+ class Redir(object):
214
+ __slots__ = ("op", "fd", "target")
215
+
216
+ def __init__(self, op, fd, target):
217
+ self.op, self.fd, self.target = op, fd, target
218
+
219
+
220
+ class Heredoc(object):
221
+ __slots__ = ("body", "quoted", "substs")
222
+
223
+ def __init__(self, body, quoted, substs):
224
+ self.body, self.quoted, self.substs = body, quoted, substs
225
+
226
+
227
+ class Seg(object):
228
+ __slots__ = ("words", "redirs", "sep", "heredocs", "subshell", "funcdef", "start", "end",
229
+ "src")
230
+
231
+ def __init__(self, src, start, subshell):
232
+ self.words = []
233
+ self.redirs = []
234
+ self.sep = None
235
+ self.heredocs = []
236
+ self.subshell = subshell
237
+ self.funcdef = False
238
+ self.start = start
239
+ self.end = start
240
+ self.src = src
241
+
242
+ @property
243
+ def text(self):
244
+ return self.src[self.start:self.end].strip()
245
+
246
+
247
+ SIMPLE_ESC = {"n": "\n", "t": "\t", "r": "\r", "a": "\a", "b": "\b", "e": "\x1b", "E": "\x1b",
248
+ "f": "\f", "v": "\v", "\\": "\\", "'": "'", '"': '"', "?": "?"}
249
+
250
+
251
+ def ansi_c(s):
252
+ out = []
253
+ i = 0
254
+ n = len(s)
255
+ while i < n:
256
+ c = s[i]
257
+ if c != "\\" or i + 1 >= n:
258
+ out.append(c)
259
+ i += 1
260
+ continue
261
+ d = s[i + 1]
262
+ i += 2
263
+ if d in SIMPLE_ESC:
264
+ out.append(SIMPLE_ESC[d])
265
+ elif d == "x":
266
+ m = re.match(r"[0-9a-fA-F]{1,2}", s[i:])
267
+ if m:
268
+ out.append(chr(int(m.group(), 16)))
269
+ i += len(m.group())
270
+ else:
271
+ out.append("\\x")
272
+ elif d in "uU":
273
+ m = re.match(r"[0-9a-fA-F]{1,%d}" % (8 if d == "U" else 4), s[i:])
274
+ if m:
275
+ try:
276
+ out.append(chr(int(m.group(), 16)))
277
+ except ValueError:
278
+ pass
279
+ i += len(m.group())
280
+ else:
281
+ out.append("\\" + d)
282
+ elif d in "01234567":
283
+ m = re.match(r"[0-7]{1,3}", s[i - 1:])
284
+ out.append(chr(int(m.group(), 8) & 0xFF))
285
+ i += len(m.group()) - 1
286
+ elif d == "c" and i < n:
287
+ out.append(chr(ord(s[i]) & 0x1F))
288
+ i += 1
289
+ else:
290
+ out.append("\\" + d)
291
+ return "".join(out).replace("\x00", "")
292
+
293
+
294
+ class Lexer(object):
295
+ """Just enough of the POSIX/bash grammar to find every simple command and its words."""
296
+
297
+ def __init__(self, src):
298
+ self.s = src
299
+ self.n = len(src)
300
+ self.i = 0
301
+ self.pending = [] # heredocs waiting for the end of the line
302
+ self.depth = 0 # $( … ) nesting, for `EOF)` heredoc ends
303
+
304
+ def peek(self, k=0):
305
+ j = self.i + k
306
+ return self.s[j] if j < self.n else ""
307
+
308
+ def parse(self):
309
+ segs = self.parse_list(None, False)
310
+ return segs
311
+
312
+ def _push(self, segs, seg, sep):
313
+ seg.sep = sep
314
+ seg.end = self.i
315
+ if seg.words or seg.redirs:
316
+ segs.append(seg)
317
+
318
+ def parse_list(self, closer, subshell):
319
+ segs = []
320
+ seg = Seg(self.s, self.i, subshell)
321
+ while True:
322
+ if self.i >= self.n:
323
+ if closer:
324
+ raise ParseError("unterminated `(` or `$(`")
325
+ self._push(segs, seg, None)
326
+ return segs
327
+ c = self.s[self.i]
328
+ if c == "\\" and self.peek(1) == "\n":
329
+ self.i += 2
330
+ continue
331
+ if c in " \t\r":
332
+ self.i += 1
333
+ continue
334
+ if c == "#":
335
+ j = self.s.find("\n", self.i)
336
+ self.i = self.n if j < 0 else j
337
+ continue
338
+ if c == "\n":
339
+ self.i += 1
340
+ self._push(segs, seg, "\n")
341
+ self._read_heredocs()
342
+ seg = Seg(self.s, self.i, subshell)
343
+ continue
344
+ if c == ";":
345
+ self.i += 1
346
+ while self.peek() in (";", "&"):
347
+ self.i += 1
348
+ self._push(segs, seg, ";")
349
+ seg = Seg(self.s, self.i, subshell)
350
+ continue
351
+ if c == "&":
352
+ if self.peek(1) == "&":
353
+ self.i += 2
354
+ self._push(segs, seg, "&&")
355
+ elif self.peek(1) == ">":
356
+ self._redir(seg, None)
357
+ continue
358
+ else:
359
+ self.i += 1
360
+ self._push(segs, seg, "&")
361
+ seg = Seg(self.s, self.i, subshell)
362
+ continue
363
+ if c == "|":
364
+ if self.peek(1) == "|":
365
+ self.i += 2
366
+ self._push(segs, seg, "||")
367
+ elif self.peek(1) == "&":
368
+ self.i += 2
369
+ self._push(segs, seg, "|&")
370
+ else:
371
+ self.i += 1
372
+ self._push(segs, seg, "|")
373
+ seg = Seg(self.s, self.i, subshell)
374
+ continue
375
+ if c in "<>":
376
+ if self.peek(1) == "(":
377
+ start = self.i
378
+ self.i += 2
379
+ self.depth += 1
380
+ inner = self.parse_list(")", False)
381
+ self.depth -= 1
382
+ w = Word(DYN, self.s[start:self.i])
383
+ w.dynamic = True
384
+ w.substs.append(inner)
385
+ seg.words.append(w)
386
+ continue
387
+ self._redir(seg, None)
388
+ continue
389
+ if c == "(":
390
+ if not seg.words and not seg.redirs:
391
+ self.i += 1
392
+ if self.peek() == "(": # (( arithmetic ))
393
+ self.i += 1
394
+ self._skip_arith()
395
+ continue
396
+ inner = self.parse_list(")", True)
397
+ segs.extend(inner)
398
+ seg = Seg(self.s, self.i, subshell)
399
+ continue
400
+ if self.peek(1) == ")" and len(seg.words) == 1:
401
+ self.i += 2
402
+ seg.funcdef = True
403
+ continue
404
+ raise ParseError("unexpected `(`")
405
+ if c == ")":
406
+ if closer == ")":
407
+ self.i += 1
408
+ self._push(segs, seg, None)
409
+ return segs
410
+ raise ParseError("unexpected `)`")
411
+ w = self.read_word()
412
+ if self.peek() in ("<", ">") and w.raw.isdigit():
413
+ self._redir(seg, w.raw)
414
+ continue
415
+ seg.words.append(w)
416
+
417
+ def _redir(self, seg, fd):
418
+ s, i = self.s, self.i
419
+ for op in ("&>>", "&>", "<<<", "<<-", "<<", "<>", "<&", "<", ">>", ">&", ">|", ">"):
420
+ if s.startswith(op, i):
421
+ break
422
+ self.i = i + len(op)
423
+ while self.peek() in (" ", "\t"):
424
+ self.i += 1
425
+ if self.i >= self.n or self.peek() in ";&|<>()\n":
426
+ raise ParseError("missing redirection target after `%s`" % op)
427
+ target = self.read_word()
428
+ if op in ("<<", "<<-"):
429
+ quoted = target.quoted or any(ch in target.raw for ch in "'\"\\")
430
+ self.pending.append((target.value.replace(DYN, ""), op == "<<-", quoted, seg))
431
+ seg.redirs.append(Redir(op, fd, target))
432
+
433
+ def _read_heredocs(self):
434
+ while self.pending:
435
+ delim, strip, quoted, seg = self.pending.pop(0)
436
+ lines = []
437
+ while self.i < self.n:
438
+ j = self.s.find("\n", self.i)
439
+ line = self.s[self.i:] if j < 0 else self.s[self.i:j]
440
+ nxt = self.n if j < 0 else j + 1
441
+ cmp = line.lstrip("\t") if strip else line
442
+ if cmp == delim:
443
+ self.i = nxt
444
+ break
445
+ if self.depth and cmp.startswith(delim) and cmp[len(delim):].lstrip().startswith(")"):
446
+ # `EOF)` closing a $( … ) on the delimiter line — bash accepts it
447
+ self.i += len(line) - len(cmp) + len(delim)
448
+ break
449
+ lines.append(line)
450
+ self.i = nxt
451
+ body = "\n".join(lines)
452
+ substs = [] if quoted else expansions_in(body)
453
+ seg.heredocs.append(Heredoc(body, quoted, substs))
454
+
455
+ def _skip_arith(self):
456
+ d = 2
457
+ while self.i < self.n:
458
+ c = self.s[self.i]
459
+ self.i += 1
460
+ if c == "(":
461
+ d += 1
462
+ elif c == ")":
463
+ d -= 1
464
+ if d == 0:
465
+ return
466
+ raise ParseError("unterminated arithmetic expression")
467
+
468
+ def _skip_balanced(self):
469
+ """Skip `( … )` (array assignments), honouring quotes."""
470
+ d = 0
471
+ while self.i < self.n:
472
+ c = self.s[self.i]
473
+ if c == "\\":
474
+ self.i += 2
475
+ continue
476
+ if c in "'\"":
477
+ j = self.s.find(c, self.i + 1)
478
+ if j < 0:
479
+ raise ParseError("unterminated quote")
480
+ self.i = j + 1
481
+ continue
482
+ self.i += 1
483
+ if c == "(":
484
+ d += 1
485
+ elif c == ")":
486
+ d -= 1
487
+ if d == 0:
488
+ return
489
+ raise ParseError("unterminated `(`")
490
+
491
+ def read_word(self):
492
+ w = Word()
493
+ start = self.i
494
+ buf = []
495
+ s = self.s
496
+ while self.i < self.n:
497
+ c = s[self.i]
498
+ if c in " \t\r\n":
499
+ break
500
+ if c in ";&|<>()":
501
+ if c == "(" and buf and "".join(buf).endswith("=") and not w.quoted:
502
+ self._skip_balanced()
503
+ buf.append(DYN)
504
+ w.dynamic = True
505
+ continue
506
+ if c in "<>" and self.peek(1) == "(" and buf:
507
+ break
508
+ break
509
+ if c == "\\":
510
+ nx = self.peek(1)
511
+ if nx == "\n":
512
+ self.i += 2
513
+ continue
514
+ if nx:
515
+ buf.append(nx)
516
+ w.quoted = True
517
+ self.i += 2
518
+ continue
519
+ if c == "'":
520
+ j = s.find("'", self.i + 1)
521
+ if j < 0:
522
+ raise ParseError("unterminated single quote")
523
+ buf.append(s[self.i + 1:j])
524
+ w.quoted = True
525
+ self.i = j + 1
526
+ continue
527
+ if c == '"':
528
+ self.i += 1
529
+ self._read_dq(w, buf, '"')
530
+ w.quoted = True
531
+ continue
532
+ if c == "$":
533
+ self._read_dollar(w, buf, False)
534
+ continue
535
+ if c == "`":
536
+ self._read_backtick(w, buf)
537
+ continue
538
+ if c in "*?[":
539
+ w.glob = True
540
+ buf.append(c)
541
+ self.i += 1
542
+ w.value = "".join(buf)
543
+ w.raw = s[start:self.i]
544
+ if not w.quoted and "{" in w.raw and "," in w.raw and "}" in w.raw:
545
+ w.dynamic = True # brace expansion: {a,b}
546
+ return w
547
+
548
+ def _read_dq(self, w, buf, term):
549
+ s = self.s
550
+ while True:
551
+ if self.i >= self.n:
552
+ if term:
553
+ raise ParseError("unterminated double quote")
554
+ return
555
+ c = s[self.i]
556
+ if term and c == term:
557
+ self.i += 1
558
+ return
559
+ if c == "\\":
560
+ nx = self.peek(1)
561
+ if nx == "\n":
562
+ self.i += 2
563
+ continue
564
+ if nx and nx in '$`"\\':
565
+ buf.append(nx)
566
+ self.i += 2
567
+ continue
568
+ buf.append("\\")
569
+ self.i += 1
570
+ continue
571
+ if c == "$":
572
+ self._read_dollar(w, buf, True)
573
+ continue
574
+ if c == "`":
575
+ self._read_backtick(w, buf)
576
+ continue
577
+ buf.append(c)
578
+ self.i += 1
579
+
580
+ def _read_dollar(self, w, buf, in_dq):
581
+ s = self.s
582
+ nx = self.peek(1)
583
+ if nx == "(":
584
+ if self.peek(2) == "(":
585
+ self.i += 3
586
+ self._skip_arith()
587
+ else:
588
+ self.i += 2
589
+ self.depth += 1
590
+ inner = self.parse_list(")", False)
591
+ self.depth -= 1
592
+ w.substs.append(inner)
593
+ buf.append(DYN)
594
+ w.dynamic = True
595
+ return
596
+ if nx == "{":
597
+ j = self.i + 2
598
+ d = 1
599
+ while j < self.n:
600
+ ch = s[j]
601
+ if ch == "\\":
602
+ j += 2
603
+ continue
604
+ if ch in "'\"" and not in_dq:
605
+ k = s.find(ch, j + 1)
606
+ if k < 0:
607
+ raise ParseError("unterminated quote in ${…}")
608
+ j = k + 1
609
+ continue
610
+ if ch == "{":
611
+ d += 1
612
+ elif ch == "}":
613
+ d -= 1
614
+ if d == 0:
615
+ break
616
+ j += 1
617
+ if j >= self.n:
618
+ raise ParseError("unterminated ${…}")
619
+ self.i = j + 1
620
+ buf.append(DYN)
621
+ w.dynamic = True
622
+ return
623
+ if nx == "'" and not in_dq:
624
+ j = self.i + 2
625
+ while j < self.n and s[j] != "'":
626
+ j += 2 if s[j] == "\\" else 1
627
+ if j >= self.n:
628
+ raise ParseError("unterminated $'…'")
629
+ buf.append(ansi_c(s[self.i + 2:j]))
630
+ w.quoted = True
631
+ self.i = j + 1
632
+ return
633
+ if nx == '"' and not in_dq:
634
+ self.i += 2
635
+ self._read_dq(w, buf, '"')
636
+ w.quoted = True
637
+ return
638
+ if nx and (nx.isalnum() or nx == "_"):
639
+ j = self.i + 1
640
+ if nx.isdigit():
641
+ j += 1
642
+ else:
643
+ while j < self.n and (s[j].isalnum() or s[j] == "_"):
644
+ j += 1
645
+ self.i = j
646
+ buf.append(DYN)
647
+ w.dynamic = True
648
+ return
649
+ if nx and nx in "@*#?$!-":
650
+ self.i += 2
651
+ buf.append(DYN)
652
+ w.dynamic = True
653
+ return
654
+ buf.append("$")
655
+ self.i += 1
656
+
657
+ def _read_backtick(self, w, buf):
658
+ s = self.s
659
+ j = self.i + 1
660
+ inner = []
661
+ while j < self.n:
662
+ ch = s[j]
663
+ if ch == "\\" and j + 1 < self.n and s[j + 1] in "`$\\":
664
+ inner.append(s[j + 1])
665
+ j += 2
666
+ continue
667
+ if ch == "`":
668
+ break
669
+ inner.append(ch)
670
+ j += 1
671
+ if j >= self.n:
672
+ raise ParseError("unterminated backtick")
673
+ self.i = j + 1
674
+ w.substs.append(Lexer("".join(inner)).parse())
675
+ buf.append(DYN)
676
+ w.dynamic = True
677
+
678
+
679
+ def expansions_in(text):
680
+ """Command substitutions inside an unquoted heredoc body (they run when it expands)."""
681
+ if "$(" not in text and "`" not in text:
682
+ return []
683
+ lx = Lexer(text)
684
+ w = Word()
685
+ try:
686
+ lx._read_dq(w, [], None)
687
+ except ParseError:
688
+ return [[]]
689
+ return w.substs
690
+
691
+
692
+ def parse_command(text):
693
+ return Lexer(text.replace("\x00", "")).parse()
694
+
695
+
696
+ # ── command normalisation ────────────────────────────────────────────────────
697
+ ASSIGN_RE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)\+?=")
698
+ RESERVED_SKIP = {"if", "then", "else", "elif", "do", "while", "until", "!", "{", "}", "time"}
699
+ RESERVED_HEADER = {"for", "case", "select", "function", "done", "fi", "esac", "in", "coproc", "}"}
700
+ GIT_ENV_VARS = {"GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE"}
701
+ SHELLS = {"sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "fish", "yash", "posh"}
702
+ INTERP_RE = re.compile(r"^(python[0-9.]*|pypy[0-9.]*|node|nodejs|perl[0-9.]*|ruby|php|deno|bun)$")
703
+
704
+
705
+ def cmd_name(v):
706
+ b = v.replace("\\", "/").rsplit("/", 1)[-1].lower()
707
+ if b.endswith(".exe"):
708
+ b = b[:-4]
709
+ return b
710
+
711
+
712
+ def is_assignment(w):
713
+ return bool(ASSIGN_RE.match(w.raw))
714
+
715
+
716
+ def is_flag_word(w):
717
+ v = w.value
718
+ return (not w.dynamic) and len(v) > 1 and v.startswith("-") and v != "--"
719
+
720
+
721
+ PREFIX_NAMES = {"env", "command", "builtin", "exec", "nice", "time", "sudo", "doas", "nohup",
722
+ "setsid", "chronic", "unbuffer", "caffeinate", "ionice", "stdbuf", "timeout"}
723
+ PREFIXES_SEEN = [] # filled by the last strip_prefixes() call
724
+
725
+
726
+ def strip_prefixes(words):
727
+ """Drop `VAR=val`, `env …`, `command`, `sudo`, … in front of the real command.
728
+ Returns (argv, assigned names, env -S string or None, relocated, lookup_only)."""
729
+ i = 0
730
+ n = len(words)
731
+ assigns = []
732
+ env_s = None
733
+ relocated = False
734
+ del PREFIXES_SEEN[:]
735
+
736
+ def val(k):
737
+ return words[k].value if k < n else ""
738
+
739
+ while i < n:
740
+ while i < n and is_assignment(words[i]):
741
+ assigns.append(ASSIGN_RE.match(words[i].raw).group(1))
742
+ i += 1
743
+ if i >= n or words[i].dynamic:
744
+ break
745
+ name = cmd_name(words[i].value)
746
+ if name in PREFIX_NAMES:
747
+ PREFIXES_SEEN.append(name)
748
+ if name == "env":
749
+ i += 1
750
+ while i < n:
751
+ v = val(i)
752
+ if words[i].dynamic:
753
+ break
754
+ if v in ("-u", "--unset"):
755
+ i += 2
756
+ elif v in ("-C", "--chdir"):
757
+ relocated = True
758
+ i += 2
759
+ elif v.startswith("--chdir="):
760
+ relocated = True
761
+ i += 1
762
+ elif v in ("-S", "--split-string"):
763
+ env_s = words[i + 1] if i + 1 < n else None
764
+ return [], assigns, env_s, relocated, False
765
+ elif v.startswith("-S") or v.startswith("--split-string="):
766
+ env_s = static_word(v[2:] if v.startswith("-S") else v.split("=", 1)[1])
767
+ return [], assigns, env_s, relocated, False
768
+ elif v == "--":
769
+ i += 1
770
+ break
771
+ elif is_assignment(words[i]):
772
+ assigns.append(ASSIGN_RE.match(words[i].raw).group(1))
773
+ i += 1
774
+ elif v.startswith("-") and len(v) > 1:
775
+ i += 1
776
+ else:
777
+ break
778
+ continue
779
+ if name in ("command", "builtin"):
780
+ i += 1
781
+ while i < n and val(i).startswith("-") and val(i) != "--":
782
+ if "v" in val(i) or "V" in val(i):
783
+ return [], assigns, None, relocated, True
784
+ i += 1
785
+ if val(i) == "--":
786
+ i += 1
787
+ continue
788
+ if name == "exec":
789
+ i += 1
790
+ while i < n and val(i).startswith("-"):
791
+ i += 2 if val(i) == "-a" else 1
792
+ continue
793
+ if name == "nice":
794
+ i += 1
795
+ while i < n and val(i).startswith("-"):
796
+ i += 2 if val(i) in ("-n", "--adjustment") else 1
797
+ continue
798
+ if name == "time":
799
+ i += 1
800
+ while i < n and val(i).startswith("-"):
801
+ i += 2 if val(i) in ("-o", "-f", "--output", "--format") else 1
802
+ continue
803
+ if name in ("sudo", "doas"):
804
+ i += 1
805
+ while i < n and val(i).startswith("-"):
806
+ v = val(i)
807
+ if v == "--":
808
+ i += 1
809
+ break
810
+ if v in ("-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U", "-T", "--user",
811
+ "--group", "--chdir", "--host", "--prompt", "--role", "--type",
812
+ "--other-user", "--command-timeout"):
813
+ i += 2
814
+ else:
815
+ i += 1
816
+ continue
817
+ if name in ("nohup", "setsid", "chronic", "unbuffer", "caffeinate", "ionice", "stdbuf"):
818
+ i += 1
819
+ while i < n and val(i).startswith("-"):
820
+ v = val(i)
821
+ i += 2 if (v in ("-c", "-n", "-t", "-i", "-o", "-e", "-w", "-s", "-p")
822
+ and name in ("ionice", "stdbuf", "caffeinate")) else 1
823
+ continue
824
+ if name == "timeout":
825
+ i += 1
826
+ while i < n and val(i).startswith("-"):
827
+ i += 2 if val(i) in ("-s", "-k", "--signal", "--kill-after") else 1
828
+ i += 1 # the duration
829
+ continue
830
+ break
831
+ return words[i:], assigns, env_s, relocated, False
832
+
833
+
834
+ # ── git ──────────────────────────────────────────────────────────────────────
835
+ GIT_GLOBAL_WITH_ARG = {"-c", "-C", "--git-dir", "--work-tree", "--namespace", "--super-prefix",
836
+ "--config-env", "--list-cmds", "--attr-source"}
837
+ GIT_BUILTINS = set("""add am annotate apply archive bisect blame branch bugreport bundle
838
+ cat-file check-attr check-ignore check-mailmap check-ref-format checkout checkout-index cherry
839
+ cherry-pick citool clean clone column commit commit-graph commit-tree config count-objects
840
+ credential describe diagnose diff diff-files diff-index diff-tree difftool fast-export
841
+ fast-import fetch fetch-pack filter-branch fmt-merge-msg for-each-ref for-each-repo
842
+ format-patch fsck gc get-tar-commit-id grep gui hash-object help hook index-pack init
843
+ instaweb interpret-trailers log ls-files ls-remote ls-tree mailinfo mailsplit maintenance
844
+ merge merge-base merge-file merge-index merge-tree mergetool mktag mktree multi-pack-index mv
845
+ name-rev notes pack-objects pack-refs patch-id prune prune-packed pull push range-diff
846
+ read-tree rebase reflog remote repack replace replay request-pull rerere reset restore
847
+ rev-list rev-parse revert rm scalar send-email send-pack shortlog show show-branch show-index
848
+ show-ref sparse-checkout stage stash status stripspace submodule switch symbolic-ref tag
849
+ unpack-file unpack-objects update-index update-ref update-server-info var verify-commit
850
+ verify-pack verify-tag version whatchanged worktree write-tree lfs""".split())
851
+
852
+ PUSH_LONG = ["all", "branches", "mirror", "delete", "tags", "dry-run", "porcelain", "force",
853
+ "force-with-lease", "no-force-with-lease", "force-if-includes",
854
+ "no-force-if-includes", "recurse-submodules", "no-recurse-submodules", "thin",
855
+ "no-thin", "quiet", "verbose", "progress", "no-progress", "prune", "no-prune",
856
+ "verify", "no-verify", "follow-tags", "no-follow-tags", "signed", "no-signed",
857
+ "atomic", "no-atomic", "push-option", "repo", "set-upstream", "receive-pack",
858
+ "exec", "ipv4", "ipv6"]
859
+ PUSH_LONG_WITH_ARG = {"push-option", "repo", "receive-pack", "exec"}
860
+ FORCE_LONG = {"force", "force-with-lease", "force-if-includes"}
861
+ BRANCH_SUBST_RE = re.compile(
862
+ r'^"?\$\(\s*git\s+(branch\s+--show-current|rev-parse\s+--abbrev-ref\s+HEAD|'
863
+ r'symbolic-ref\s+(-q\s+)?--short\s+(-q\s+)?HEAD|branch\s+--show)\s*\)"?$')
864
+
865
+
866
+ class GitInv(object):
867
+ def __init__(self):
868
+ self.sub = None
869
+ self.sub_index = None
870
+ self.args = []
871
+ self.relocated = False # -C / --git-dir / --work-tree
872
+ self.dynamic_global = False
873
+ self.c_aliases = {}
874
+
875
+
876
+ def parse_git(args):
877
+ g = GitInv()
878
+ i = 0
879
+ while i < len(args):
880
+ w = args[i]
881
+ if w.dynamic:
882
+ g.dynamic_global = True
883
+ return g
884
+ v = w.value
885
+ if v == "-C":
886
+ g.relocated = True
887
+ i += 2
888
+ continue
889
+ if v == "-c":
890
+ if i + 1 < len(args) and not args[i + 1].dynamic:
891
+ kv = args[i + 1].value
892
+ k, _, val = kv.partition("=")
893
+ if k.lower().startswith("alias."):
894
+ g.c_aliases[k[6:]] = val
895
+ i += 2
896
+ continue
897
+ if v in ("--git-dir", "--work-tree"):
898
+ g.relocated = True
899
+ i += 2
900
+ continue
901
+ if v.startswith("--git-dir=") or v.startswith("--work-tree="):
902
+ g.relocated = True
903
+ i += 1
904
+ continue
905
+ if v in GIT_GLOBAL_WITH_ARG:
906
+ i += 2
907
+ continue
908
+ if v.startswith("-"):
909
+ i += 1
910
+ continue
911
+ g.sub = v
912
+ g.sub_index = i
913
+ g.args = args[i + 1:]
914
+ break
915
+ return g
916
+
917
+
918
+ def resolve_long(name, table):
919
+ if name in table:
920
+ return [name]
921
+ return [o for o in table if o.startswith(name)] if name else []
922
+
923
+
924
+ class PushInfo(object):
925
+ def __init__(self):
926
+ self.force = False # a force flag (-f, --force*, abbreviations)
927
+ self.delete = False # --delete / -d
928
+ self.mirror = False
929
+ self.all = False
930
+ self.tags = False
931
+ self.plus_ref = False # +refspec
932
+ self.colon_delete = False # :dst refspec
933
+ self.wild = False # an argument computed at run time
934
+ self.flags = set()
935
+ self.positionals = []
936
+ self.repo = None
937
+
938
+ @property
939
+ def force_like(self):
940
+ return (self.force or self.delete or self.mirror or self.plus_ref or self.colon_delete)
941
+
942
+ @property
943
+ def delete_like(self):
944
+ return self.delete or self.colon_delete or self.mirror
945
+
946
+
947
+ def analyze_push_args(args):
948
+ pi = PushInfo()
949
+ i = 0
950
+ end_opts = False
951
+ prev_takes_value = False
952
+ while i < len(args):
953
+ w = args[i]
954
+ v = w.value
955
+ if w.dynamic:
956
+ h = w.head
957
+ if not end_opts and h.startswith("--") and "=" in h:
958
+ name = h[2:].split("=", 1)[0]
959
+ c = resolve_long(name, PUSH_LONG)
960
+ if FORCE_LONG.intersection(c):
961
+ pi.force = True
962
+ elif BRANCH_SUBST_RE.match(w.raw) or (w.raw.startswith('"') and not h.startswith("-")
963
+ and not h.startswith("+")):
964
+ # "$(git branch --show-current)" (resolved later) or a quoted "$BRANCH": one
965
+ # word, so not a flag — but its destination is unknown.
966
+ pi.positionals.append(w)
967
+ elif not prev_takes_value:
968
+ pi.wild = True
969
+ pi.positionals.append(w)
970
+ prev_takes_value = False
971
+ i += 1
972
+ continue
973
+ prev_takes_value = False
974
+ if not end_opts and v == "--":
975
+ end_opts = True
976
+ i += 1
977
+ continue
978
+ if not end_opts and v.startswith("--") and len(v) > 2:
979
+ name, eq, _ = v[2:].partition("=")
980
+ cands = resolve_long(name, PUSH_LONG)
981
+ if FORCE_LONG.intersection(cands):
982
+ pi.force = True
983
+ if "delete" in cands:
984
+ pi.delete = True
985
+ if "mirror" in cands:
986
+ pi.mirror = True
987
+ if "all" in cands or "branches" in cands:
988
+ pi.all = True
989
+ if "tags" in cands:
990
+ pi.tags = True
991
+ pi.flags.add("--" + (cands[0] if len(cands) == 1 else name))
992
+ if len(cands) == 1 and cands[0] in PUSH_LONG_WITH_ARG and not eq:
993
+ if cands[0] == "repo" and i + 1 < len(args):
994
+ pi.repo = args[i + 1]
995
+ prev_takes_value = True
996
+ i += 1
997
+ if i < len(args) and not args[i].dynamic:
998
+ i += 1
999
+ prev_takes_value = False
1000
+ continue
1001
+ i += 1
1002
+ continue
1003
+ if not end_opts and v.startswith("-") and len(v) > 1:
1004
+ rest = v[1:]
1005
+ for k, ch in enumerate(rest):
1006
+ pi.flags.add("-" + ch)
1007
+ if ch == "f":
1008
+ pi.force = True
1009
+ elif ch == "d":
1010
+ pi.delete = True
1011
+ elif ch == "o":
1012
+ if k == len(rest) - 1:
1013
+ prev_takes_value = True
1014
+ if i + 1 < len(args) and not args[i + 1].dynamic:
1015
+ i += 1
1016
+ prev_takes_value = False
1017
+ break
1018
+ i += 1
1019
+ continue
1020
+ pi.positionals.append(w)
1021
+ i += 1
1022
+ refs = pi.positionals if pi.repo is not None else pi.positionals[1:]
1023
+ for r in refs:
1024
+ if not r.dynamic:
1025
+ rv = r.value
1026
+ if rv.startswith("+"):
1027
+ pi.plus_ref = True
1028
+ rv = rv[1:]
1029
+ if rv.startswith(":") and len(rv) > 1:
1030
+ pi.colon_delete = True
1031
+ return pi
1032
+
1033
+
1034
+ def normalize_ref(name):
1035
+ if name.startswith("refs/heads/"):
1036
+ return name[len("refs/heads/"):]
1037
+ if name.startswith("refs/"):
1038
+ return None
1039
+ return name
1040
+
1041
+
1042
+ # ── config ───────────────────────────────────────────────────────────────────
1043
+ DEFAULT_AGENTS = ["cohorte-review", "review"]
1044
+ RENAMED_AGENTS = {"review": "cohorte-review", "release": "cohorte-release",
1045
+ "profile-reader": "cohorte-profile-reader"}
1046
+
1047
+
1048
+ def _with_renamed_aliases(agents):
1049
+ """Every listed agent plus its 2.x/3.x counterpart, order kept, no duplicates."""
1050
+ out = []
1051
+ reverse = {v: k for k, v in RENAMED_AGENTS.items()}
1052
+ for a in agents:
1053
+ for name in (a, RENAMED_AGENTS.get(a), reverse.get(a)):
1054
+ if name and name not in out:
1055
+ out.append(name)
1056
+ return out
1057
+
1058
+
1059
+ class ConfigError(Exception):
1060
+ pass
1061
+
1062
+
1063
+ def _pattern_list(obj, key, warnings, path):
1064
+ if key not in obj:
1065
+ return []
1066
+ v = obj[key]
1067
+ if isinstance(v, str):
1068
+ warnings.append("%s: `%s` is a string, read as a one-element list" % (path, key))
1069
+ v = [v]
1070
+ if not isinstance(v, list):
1071
+ raise ConfigError("`%s` must be a list of strings (got %s)" % (key, type(v).__name__))
1072
+ out = []
1073
+ for item in v:
1074
+ if not isinstance(item, str):
1075
+ raise ConfigError("`%s` must contain only strings (found %s)" % (key, json.dumps(item)))
1076
+ if not item.strip():
1077
+ warnings.append("%s: empty pattern in `%s` ignored" % (path, key))
1078
+ continue
1079
+ out.append(item.strip())
1080
+ return out
1081
+
1082
+
1083
+ def validate_config(obj, path, warnings):
1084
+ if not isinstance(obj, dict):
1085
+ raise ConfigError("the top level must be a JSON object")
1086
+ cfg = {}
1087
+ for key in ("deny", "ask", "ask_on_default_branch"):
1088
+ cfg[key] = _pattern_list(obj, key, warnings, path)
1089
+ db = obj.get("default_branch")
1090
+ if db is not None and not isinstance(db, str):
1091
+ raise ConfigError("`default_branch` must be a string")
1092
+ cfg["default_branch"] = db.strip() if isinstance(db, str) and db.strip() else None
1093
+ pf = obj.get("preflight")
1094
+ if pf is None:
1095
+ cfg["preflight"] = None
1096
+ else:
1097
+ if not isinstance(pf, dict):
1098
+ raise ConfigError("`preflight` must be an object")
1099
+ enabled = pf.get("enabled", False)
1100
+ if not isinstance(enabled, bool):
1101
+ raise ConfigError("`preflight.enabled` must be true or false")
1102
+ agents = pf.get("agents")
1103
+ if agents is None:
1104
+ agents = list(DEFAULT_AGENTS)
1105
+ else:
1106
+ if isinstance(agents, str):
1107
+ agents = [agents]
1108
+ if not isinstance(agents, list) or not all(isinstance(a, str) for a in agents):
1109
+ raise ConfigError("`preflight.agents` must be a list of strings")
1110
+ agents = [a.strip() for a in agents if a.strip()] or list(DEFAULT_AGENTS)
1111
+ # 3.0 renamed the fixed agents (review → cohorte-review …). A 2.x gate-config.json lists
1112
+ # the bare names explicitly, so gate both spellings or every migrated repo silently
1113
+ # loses its phase gate.
1114
+ agents = _with_renamed_aliases(agents)
1115
+ age = pf.get("max_age_minutes", 30)
1116
+ if age is None:
1117
+ age = 30
1118
+ if isinstance(age, bool) or not isinstance(age, (int, float)) or age < 0 or age != age:
1119
+ raise ConfigError("`preflight.max_age_minutes` must be a number >= 0")
1120
+ cfg["preflight"] = {"enabled": enabled, "agents": agents, "max_age_minutes": float(age)}
1121
+ return cfg
1122
+
1123
+
1124
+ def git_top_and_common(cwd):
1125
+ r = run_git(["rev-parse", "--show-toplevel", "--git-common-dir"], cwd)
1126
+ if not r or r[0] != 0:
1127
+ return None, None
1128
+ lines = r[1].splitlines()
1129
+ top = os.path.realpath(lines[0]) if lines and lines[0] else None
1130
+ main = None
1131
+ if len(lines) > 1 and lines[1]:
1132
+ common = lines[1]
1133
+ if not os.path.isabs(common):
1134
+ common = os.path.join(cwd, common)
1135
+ common = os.path.realpath(common)
1136
+ if os.path.basename(common) == ".git":
1137
+ main = os.path.dirname(common)
1138
+ return top, main
1139
+
1140
+
1141
+ def resolve_roots(cwd):
1142
+ """Project roots to read config from: the cwd's checkout, $CLAUDE_PROJECT_DIR, and the
1143
+ main checkout of a linked worktree — every one that exists, cwd's first."""
1144
+ roots = []
1145
+
1146
+ def add(p):
1147
+ if p and os.path.isdir(p):
1148
+ rp = os.path.realpath(p)
1149
+ if rp not in roots:
1150
+ roots.append(rp)
1151
+
1152
+ top = main = None
1153
+ if cwd and os.path.isdir(cwd):
1154
+ top, main = git_top_and_common(cwd)
1155
+ if top:
1156
+ add(top)
1157
+ else:
1158
+ d = os.path.realpath(cwd)
1159
+ home = os.path.realpath(os.path.expanduser("~"))
1160
+ while True:
1161
+ c = os.path.join(d, ".claude")
1162
+ if (os.path.isfile(os.path.join(c, "gate-config.json"))
1163
+ or os.path.isfile(os.path.join(c, "pipeline.json"))):
1164
+ add(d)
1165
+ break
1166
+ parent = os.path.dirname(d)
1167
+ if parent == d or d == home:
1168
+ break
1169
+ d = parent
1170
+ env = os.environ.get("CLAUDE_PROJECT_DIR") or ""
1171
+ if env:
1172
+ add(env)
1173
+ add(main)
1174
+ return roots, top
1175
+
1176
+
1177
+ class Ctx(object):
1178
+ def __init__(self, cwd, mode):
1179
+ self.cwd0 = os.path.realpath(cwd) if cwd and os.path.isdir(cwd) else None
1180
+ self.mode = mode
1181
+ self.roots, self.top0 = resolve_roots(self.cwd0)
1182
+ self.warnings = []
1183
+ self.errors = []
1184
+ self.config_found = False
1185
+ merged = {"deny": [], "ask": [], "ask_on_default_branch": [], "default_branches": [],
1186
+ "preflight": None}
1187
+ for r in self.roots:
1188
+ for sub in (".claude", ".cohorte"):
1189
+ p = os.path.join(r, sub, "gate-config.json")
1190
+ if not os.path.isfile(p):
1191
+ continue
1192
+ if sub == ".cohorte" and os.path.isfile(os.path.join(r, ".claude", "gate-config.json")):
1193
+ self.warnings.append("%s and .claude/gate-config.json both exist; their "
1194
+ "rules are combined" % p)
1195
+ self.config_found = True
1196
+ try:
1197
+ with open(p, "r", encoding="utf-8") as fh:
1198
+ obj = json.load(fh)
1199
+ cfg = validate_config(obj, p, self.warnings)
1200
+ except ConfigError as e:
1201
+ self.errors.append("%s: %s" % (p, e))
1202
+ continue
1203
+ except Exception as e:
1204
+ self.errors.append("%s: not valid JSON (%s)" % (p, e))
1205
+ continue
1206
+ for k in ("deny", "ask", "ask_on_default_branch"):
1207
+ for pat in cfg[k]:
1208
+ if pat not in merged[k]:
1209
+ merged[k].append(pat)
1210
+ if cfg["default_branch"] and cfg["default_branch"] not in merged["default_branches"]:
1211
+ merged["default_branches"].append(cfg["default_branch"])
1212
+ if merged["preflight"] is None and cfg["preflight"] is not None:
1213
+ merged["preflight"] = cfg["preflight"]
1214
+ self.cfg = merged
1215
+ self.has_pointer = any(os.path.isfile(os.path.join(r, ".claude", "pipeline.json"))
1216
+ for r in self.roots)
1217
+ self.active = self.has_pointer or self.config_found
1218
+ for w in self.warnings:
1219
+ warn(w)
1220
+ self.deny_pats = [compile_pattern(p) for p in merged["deny"]]
1221
+ self.ask_pats = [compile_pattern(p) for p in merged["ask"]]
1222
+ self.branch_pats = [compile_pattern(p) for p in merged["ask_on_default_branch"]]
1223
+ self.has_rules = bool(merged["deny"] or merged["ask"] or merged["ask_on_default_branch"]
1224
+ or self.errors)
1225
+ self._defaults = None
1226
+ self._branches = {}
1227
+ self._aliases = {}
1228
+ self._build_protected()
1229
+
1230
+ def _build_protected(self):
1231
+ write, delete = set(), set()
1232
+
1233
+ def add(s, p):
1234
+ s.add(os.path.normpath(p))
1235
+ s.add(os.path.realpath(p))
1236
+
1237
+ for r in self.roots:
1238
+ for rel in ((".claude", "gate-config.json"), (".claude", "preflight.ok"),
1239
+ (".claude", "settings.json"), (".claude", "settings.local.json"),
1240
+ (".claude", "hooks", "cohorte-gate.py"), (".cohorte", "gate-config.json")):
1241
+ add(write, os.path.join(r, *rel))
1242
+ add(delete, os.path.join(r, ".claude", "pipeline.json"))
1243
+ home = os.path.expanduser("~")
1244
+ for rel in ("settings.json", "settings.local.json"):
1245
+ add(write, os.path.join(home, ".claude", rel))
1246
+ self.protected = write
1247
+ self.delete_protected = write | delete
1248
+
1249
+ # git state, cached
1250
+ def current_branch(self, cwd):
1251
+ if cwd not in self._branches:
1252
+ r = run_git(["symbolic-ref", "-q", "--short", "HEAD"], cwd)
1253
+ self._branches[cwd] = r[1].strip() if r and r[0] == 0 and r[1].strip() else None
1254
+ return self._branches[cwd]
1255
+
1256
+ def defaults(self):
1257
+ if self._defaults is None:
1258
+ if self.cfg["default_branches"]:
1259
+ self._defaults = list(self.cfg["default_branches"])
1260
+ else:
1261
+ d = ["main", "master"]
1262
+ if self.cwd0:
1263
+ r = run_git(["symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD"],
1264
+ self.cwd0)
1265
+ if r and r[0] == 0 and "/" in r[1].strip():
1266
+ name = r[1].strip().split("/", 1)[1]
1267
+ if name not in d:
1268
+ d.insert(0, name)
1269
+ self._defaults = d
1270
+ return self._defaults
1271
+
1272
+ def is_default(self, branch):
1273
+ return any(fnmatch.fnmatchcase(d, branch) if any(c in branch for c in "*?[") else d == branch
1274
+ for d in self.defaults())
1275
+
1276
+ def git_alias(self, sub, cwd):
1277
+ key = (sub, cwd)
1278
+ if key not in self._aliases:
1279
+ r = run_git(["config", "--get", "alias." + sub], cwd)
1280
+ self._aliases[key] = r[1].strip() if r and r[0] == 0 and r[1].strip() else None
1281
+ return self._aliases[key]
1282
+
1283
+
1284
+ # ── patterns ─────────────────────────────────────────────────────────────────
1285
+ class PatSeg(object):
1286
+ def __init__(self, name, args, sep):
1287
+ self.name = name
1288
+ self.args = args
1289
+ self.sep = sep
1290
+ self.git = parse_git(args) if name == "git" else None
1291
+ self.core = runner_core(name, args) if name != "git" else None
1292
+ self.prefix_only = False
1293
+
1294
+
1295
+ class Pattern(object):
1296
+ def __init__(self, text):
1297
+ self.text = text
1298
+ self.norm = " ".join(text.lower().split())
1299
+ self.segs = []
1300
+ try:
1301
+ segs = parse_command(text)
1302
+ except ParseError:
1303
+ warn("pattern `%s` can't be tokenized; it is matched as raw text" % text)
1304
+ return
1305
+ for s in segs:
1306
+ words = [w for w in s.words]
1307
+ while words and not words[0].quoted and words[0].value in RESERVED_SKIP:
1308
+ words.pop(0)
1309
+ argv = strip_prefixes(words)[0]
1310
+ if not argv:
1311
+ if not words or words[0].dynamic:
1312
+ continue
1313
+ argv = words # a wrapper-only pattern such as `sudo`
1314
+ ps = PatSeg(cmd_name(argv[0].value), argv[1:], s.sep)
1315
+ ps.prefix_only = True
1316
+ self.segs.append(ps)
1317
+ continue
1318
+ self.segs.append(PatSeg(cmd_name(argv[0].value), argv[1:], s.sep))
1319
+
1320
+ @property
1321
+ def multi(self):
1322
+ return len(self.segs) > 1
1323
+
1324
+
1325
+ def compile_pattern(text):
1326
+ return Pattern(text)
1327
+
1328
+
1329
+ def runner_core(name, args, depth=0):
1330
+ """(name, args) of the program a package runner / launcher runs, or None."""
1331
+ if depth > 3:
1332
+ return None
1333
+ a = list(args)
1334
+
1335
+ def skip_opts(k, with_arg=()):
1336
+ while k < len(a):
1337
+ if a[k].dynamic:
1338
+ return None
1339
+ v = a[k].value
1340
+ if v == "--":
1341
+ return k + 1
1342
+ if v.startswith("-") and len(v) > 1:
1343
+ k += 2 if v in with_arg else 1
1344
+ continue
1345
+ return k
1346
+ return None
1347
+
1348
+ k = None
1349
+ if name in ("npx", "bunx", "pnpx"):
1350
+ k = skip_opts(0, ("-p", "--package", "-c", "--call"))
1351
+ elif name in ("pnpm", "yarn", "npm", "bun"):
1352
+ k = skip_opts(0, ("--filter", "-F", "-C", "--dir", "--prefix", "-w", "--workspace", "--cwd"))
1353
+ if k is not None and k < len(a) and a[k].value in ("exec", "dlx", "x", "run"):
1354
+ k = skip_opts(k + 1, ("--filter", "-F", "-C", "--dir", "--prefix"))
1355
+ elif name == "npm":
1356
+ return None
1357
+ elif name in ("uv", "poetry", "pipenv", "rye", "pdm", "hatch") and a and a[0].value == "run":
1358
+ k = skip_opts(1, ("--with", "--python", "-p", "--env", "-e"))
1359
+ elif name == "bundle" and a and a[0].value == "exec":
1360
+ k = skip_opts(1)
1361
+ elif name in ("cross-env", "env-cmd", "dotenv"):
1362
+ k = 0
1363
+ while k < len(a) and (is_assignment(a[k]) or a[k].value.startswith("-")):
1364
+ if a[k].value == "--":
1365
+ k += 1
1366
+ break
1367
+ k += 2 if a[k].value in ("-e", "-f", "-c") else 1
1368
+ elif INTERP_RE.match(name) and name.startswith("py"):
1369
+ for j, w in enumerate(a):
1370
+ if w.value == "-m" and j + 1 < len(a):
1371
+ k = j + 1
1372
+ break
1373
+ if not w.value.startswith("-"):
1374
+ break
1375
+ if k is None or k >= len(a) or a[k].dynamic:
1376
+ return None
1377
+ inner = cmd_name(a[k].value)
1378
+ rest = a[k + 1:]
1379
+ deeper = runner_core(inner, rest, depth + 1)
1380
+ return deeper or (inner, rest)
1381
+
1382
+
1383
+ WRAPPERS = {"docker", "podman", "nerdctl", "docker-compose", "kubectl", "oc", "lima", "colima"}
1384
+
1385
+
1386
+ def wrapper_cores(name, args):
1387
+ """Container wrappers (`docker compose exec api node ace …`, `kubectl exec pod -- psql`)
1388
+ run a command given as later words: try a pattern at every later static word."""
1389
+ if name not in WRAPPERS:
1390
+ return []
1391
+ out = []
1392
+ for k, w in enumerate(args):
1393
+ if w.dynamic or w.value.startswith("-"):
1394
+ continue
1395
+ out.append((cmd_name(w.value), args[k + 1:]))
1396
+ core = runner_core(cmd_name(w.value), args[k + 1:])
1397
+ if core:
1398
+ out.append(core)
1399
+ return out[:40]
1400
+
1401
+
1402
+ def short_flags(v):
1403
+ return ["-" + c for c in v[1:]]
1404
+
1405
+
1406
+ def flag_names(tokens, aliases=None):
1407
+ out = set()
1408
+ for w in tokens:
1409
+ if w.dynamic:
1410
+ h = w.head
1411
+ if h.startswith("--") and "=" in h:
1412
+ out.add(h.split("=", 1)[0])
1413
+ continue
1414
+ v = w.value
1415
+ if v == "--":
1416
+ break
1417
+ if len(v) < 2 or not v.startswith("-"):
1418
+ continue
1419
+ if v.startswith("--"):
1420
+ out.add(v.split("=", 1)[0])
1421
+ else:
1422
+ out.update(short_flags(v))
1423
+ if aliases:
1424
+ out = {aliases.get(f, f) for f in out}
1425
+ return out
1426
+
1427
+
1428
+ FLAG_ALIASES = {
1429
+ "rm": {"-R": "-r", "--recursive": "-r", "--force": "-f", "--dir": "-d"},
1430
+ "cp": {"-R": "-r", "--recursive": "-r", "--force": "-f"},
1431
+ }
1432
+
1433
+
1434
+ def is_wildcard(tokens, idx):
1435
+ """A run-time word that could be any word (or flag) — unless it is the value of the
1436
+ flag right before it (`-m "$(cat <<EOF …)"`)."""
1437
+ w = tokens[idx]
1438
+ if not w.dynamic:
1439
+ return False
1440
+ h = w.head
1441
+ if h.startswith("-") and "=" in h:
1442
+ return False
1443
+ if idx > 0:
1444
+ p = tokens[idx - 1]
1445
+ if is_flag_word(p) and "=" not in p.value:
1446
+ return False
1447
+ return True
1448
+
1449
+
1450
+ def wild_flag(tokens, idx):
1451
+ """A run-time word that could expand to flags: unquoted (field splitting) or visibly
1452
+ starting with `-`, and not after `--`."""
1453
+ if not is_wildcard(tokens, idx):
1454
+ return False
1455
+ if any(not t.dynamic and t.value == "--" for t in tokens[:idx]):
1456
+ return False
1457
+ w = tokens[idx]
1458
+ return not w.raw.startswith('"') or w.head.startswith("-")
1459
+
1460
+
1461
+ def pos_match(ppos, tokens, eq):
1462
+ """Pattern positionals in order at the start of the command's positionals. A
1463
+ positional may be skipped only when it follows a flag (it may be that flag's value)."""
1464
+ def rec(pi, ci):
1465
+ if pi == len(ppos):
1466
+ return "match"
1467
+ best = None
1468
+ prev_flag = False
1469
+ end_opts = False
1470
+ j = ci
1471
+ while j < len(tokens):
1472
+ w = tokens[j]
1473
+ if is_wildcard(tokens, j):
1474
+ return "possible"
1475
+ if w.dynamic:
1476
+ prev_flag = False
1477
+ j += 1
1478
+ continue
1479
+ if not end_opts and w.value == "--":
1480
+ end_opts = True
1481
+ j += 1
1482
+ continue
1483
+ if not end_opts and is_flag_word(w):
1484
+ prev_flag = "=" not in w.value
1485
+ j += 1
1486
+ continue
1487
+ if eq(ppos[pi], w):
1488
+ r = rec(pi + 1, j + 1)
1489
+ if r == "match":
1490
+ return r
1491
+ best = best or r
1492
+ if not prev_flag:
1493
+ return best
1494
+ prev_flag = False
1495
+ j += 1
1496
+ return best
1497
+ return rec(0, 0)
1498
+
1499
+
1500
+ def match_args(pargs, cargs, git=False, aliases=None, eq=None):
1501
+ eq = eq or (lambda p, w: p.value == w.value)
1502
+ ppos = [w for w in pargs if not is_flag_word(w)]
1503
+ pflags = [w for w in pargs if is_flag_word(w)]
1504
+ res = pos_match(ppos, cargs, eq)
1505
+ if res is None:
1506
+ return None
1507
+ cflags = flag_names(cargs, aliases)
1508
+ wild = any(wild_flag(cargs, k) for k in range(len(cargs)))
1509
+ for pf in pflags:
1510
+ need = flag_names([pf], aliases)
1511
+ for f in need:
1512
+ ok = f in cflags
1513
+ if not ok and git and f.startswith("--"):
1514
+ ok = any(c.startswith("--") and len(c) >= 4 and f.startswith(c) for c in cflags)
1515
+ if not ok:
1516
+ if wild:
1517
+ res = "possible"
1518
+ else:
1519
+ return None
1520
+ return res
1521
+
1522
+
1523
+ def push_eq(p, w):
1524
+ v = w.value
1525
+ if p.value == v:
1526
+ return True
1527
+ v = v.lstrip("+")
1528
+ if p.value == v:
1529
+ return True
1530
+ if ":" in v and p.value == v.split(":", 1)[1]:
1531
+ return True
1532
+ return False
1533
+
1534
+
1535
+ def match_push(pat_args, cargs, pi):
1536
+ pflags = [w for w in pat_args if is_flag_word(w)]
1537
+ ppos = [w for w in pat_args if not is_flag_word(w)]
1538
+ res = pos_match(ppos, pi.positionals, push_eq)
1539
+ if res is None:
1540
+ return None
1541
+ pp = analyze_push_args(pflags)
1542
+ needs = []
1543
+ if pp.force:
1544
+ needs.append(pi.force_like)
1545
+ if pp.delete:
1546
+ needs.append(pi.delete_like)
1547
+ if pp.mirror:
1548
+ needs.append(pi.mirror)
1549
+ if pp.all:
1550
+ needs.append(pi.all or pi.mirror)
1551
+ if pp.tags:
1552
+ needs.append(pi.tags)
1553
+ semantic = {"-f", "-d", "--force", "--force-with-lease", "--force-if-includes", "--delete",
1554
+ "--mirror", "--all", "--branches", "--tags"}
1555
+ for f in pp.flags:
1556
+ if f in semantic:
1557
+ continue
1558
+ ok = f in pi.flags or (f.startswith("--") and any(
1559
+ c.startswith("--") and len(c) >= 4 and f.startswith(c) for c in pi.flags))
1560
+ needs.append(ok)
1561
+ if not all(needs):
1562
+ return "possible" if pi.wild else None
1563
+ if pi.wild and res == "match":
1564
+ return "match"
1565
+ return res
1566
+
1567
+
1568
+ # ── analysis ─────────────────────────────────────────────────────────────────
1569
+ PROTECTED_HINT_RE = re.compile(r"(^|/)\.claude(/|$)|gate-config\.json|preflight\.ok|"
1570
+ r"settings(\.local)?\.json|cohorte-gate\.py|pipeline\.json|"
1571
+ r"(^|/)\.cohorte(/|$)")
1572
+ PROTECTED_NAME_RE = re.compile(r"gate-config\.json|preflight\.ok|\.claude/settings(\.local)?\.json|"
1573
+ r"cohorte-gate\.py")
1574
+ SPAWN_RE = {
1575
+ "py": re.compile(r"\bos\.(system|popen|exec\w*|spawn\w*)|\bsubprocess\b|\bpty\.spawn|"
1576
+ r"\bcommands\.getoutput|\bpexpect\b|\bsh\.\w+\("),
1577
+ "js": re.compile(r"child_process|\bexecSync\b|\bspawnSync\b|\bexecFileSync\b|\bexecFile\(|"
1578
+ r"\bexec\(|\bspawn\(|Bun\.spawn|Deno\.(Command|run)|\$`|zx"),
1579
+ "pl": re.compile(r"\bsystem\b|\bexec\b|`|\bqx\b|IO\.popen|Open3|\bspawn\b|%x|\bpopen\b|"
1580
+ r"\bshell_exec\b|\bpassthru\b|\bproc_open\b"),
1581
+ }
1582
+ STRING_LIT_RE = re.compile(r"'((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\"")
1583
+ PROTECTED_BASENAMES = {"gate-config.json", "preflight.ok", "settings.json", "settings.local.json",
1584
+ "cohorte-gate.py", "pipeline.json", ".claude", ".cohorte", "hooks", "~", "",
1585
+ ".", ".."}
1586
+
1587
+
1588
+ def suspicious(tail, raw):
1589
+ """For a path the gate can't resolve: could it name a protected file? Its static tail
1590
+ decides — `…/.claude/pipeline-metrics.jsonl` can't, `$DIR/.claude/settings.json` can."""
1591
+ base = os.path.basename(tail.rstrip("/")) if tail else ""
1592
+ if tail and "/" in tail and base not in PROTECTED_BASENAMES and not tail.endswith("/"):
1593
+ return False
1594
+ return bool(PROTECTED_HINT_RE.search(raw))
1595
+
1596
+
1597
+ MAX_DEPTH = 6
1598
+ WRITE_OPS = {">", ">>", ">|", "&>", "&>>", "<>"}
1599
+
1600
+
1601
+ def norm_lower(s):
1602
+ return " ".join(s.lower().split())
1603
+
1604
+
1605
+ def lang_of(name):
1606
+ if name.startswith("py"):
1607
+ return "py"
1608
+ if name in ("node", "nodejs", "deno", "bun"):
1609
+ return "js"
1610
+ return "pl"
1611
+
1612
+
1613
+ class State(object):
1614
+ def __init__(self, cwd):
1615
+ self.cwd = cwd
1616
+ self.cwd_known = cwd is not None
1617
+ self.sticky = False # branch unknown for the rest of the chain
1618
+ self.written = set()
1619
+ self.git_aliases = {}
1620
+
1621
+ def copy(self):
1622
+ s = State(self.cwd)
1623
+ s.cwd_known = self.cwd_known
1624
+ s.sticky = self.sticky
1625
+ s.written = set(self.written)
1626
+ s.git_aliases = dict(self.git_aliases)
1627
+ return s
1628
+
1629
+
1630
+ class Inv(object):
1631
+ def __init__(self, name, args, seg):
1632
+ self.name = name
1633
+ self.args = args
1634
+ self.seg = seg
1635
+ self.git = None
1636
+ self.push = None
1637
+ self.push_touches = False
1638
+ self.push_unknown = False
1639
+ self.core = None
1640
+ self.cores = []
1641
+ self.prefixes = []
1642
+
1643
+
1644
+ def short(text, n=90):
1645
+ t = " ".join(text.split())
1646
+ return t if len(t) <= n else t[:n - 1] + "…"
1647
+
1648
+
1649
+ class Analyzer(object):
1650
+ def __init__(self, ctx):
1651
+ self.ctx = ctx
1652
+ self.findings = []
1653
+
1654
+ def deny(self, why):
1655
+ self.findings.append(("deny", why))
1656
+
1657
+ def ask(self, why):
1658
+ self.findings.append(("ask", why))
1659
+
1660
+ def verdict(self):
1661
+ for level in ("deny", "ask"):
1662
+ hits = [w for (lv, w) in self.findings if lv == level]
1663
+ if hits:
1664
+ uniq = []
1665
+ for h in hits:
1666
+ if h not in uniq:
1667
+ uniq.append(h)
1668
+ more = " (+%d more)" % (len(uniq) - 1) if len(uniq) > 1 else ""
1669
+ return level, uniq[0] + more
1670
+ return None
1671
+
1672
+ # -- hidden text ----------------------------------------------------------
1673
+ def raw_deny(self, text):
1674
+ t = norm_lower(text)
1675
+ for p in self.ctx.deny_pats:
1676
+ if p.norm and p.norm in t:
1677
+ self.deny("`%s` is forbidden by the project's gate, and it appears in text "
1678
+ "that will be executed" % p.text)
1679
+ return True
1680
+ return False
1681
+
1682
+ def opaque(self, what, text):
1683
+ if self.raw_deny(text):
1684
+ return
1685
+ if self.ctx.has_rules or re.search(r"git|push", text, re.I):
1686
+ self.ask("%s, so the gate can't check it against the rules — confirm (`%s`)"
1687
+ % (what, short(text)))
1688
+
1689
+ def unparseable(self, text, err):
1690
+ if self.raw_deny(text):
1691
+ return
1692
+ if self.ctx.has_rules or re.search(r"git|push|\.claude", text, re.I):
1693
+ self.ask("the gate can't parse this command (%s), so it can't verify it — confirm"
1694
+ % err)
1695
+
1696
+ def analyze_text(self, text, state, depth):
1697
+ if depth > MAX_DEPTH:
1698
+ self.opaque("commands are nested too deep", text)
1699
+ return
1700
+ try:
1701
+ segs = parse_command(text)
1702
+ except ParseError as e:
1703
+ self.unparseable(text, e)
1704
+ return
1705
+ self.walk(segs, state, depth, text)
1706
+
1707
+ def walk(self, segs, state, depth, text=""):
1708
+ invs = []
1709
+ for idx, seg in enumerate(segs):
1710
+ prev = segs[idx - 1] if idx else None
1711
+ prev_inv = invs[-1] if invs else None
1712
+ if seg.subshell:
1713
+ state.sticky = True
1714
+ self.walk_substs(seg, state, depth)
1715
+ invs.append(self.eval_segment(seg, prev, prev_inv, state, depth))
1716
+ self.multi_patterns(segs, invs, state)
1717
+ for p in self.ctx.deny_pats + self.ctx.ask_pats:
1718
+ if not p.segs and p.norm in norm_lower(text):
1719
+ (self.deny if p in self.ctx.deny_pats else self.ask)(
1720
+ "`%s` (raw-text rule) matches this command" % p.text)
1721
+
1722
+ def walk_substs(self, seg, state, depth):
1723
+ words = list(seg.words) + [r.target for r in seg.redirs]
1724
+ for w in words:
1725
+ for sub in w.substs:
1726
+ self.walk(sub, state.copy(), depth + 1)
1727
+ for h in seg.heredocs:
1728
+ for sub in h.substs:
1729
+ self.walk(sub, state.copy(), depth + 1)
1730
+
1731
+ # -- one simple command ----------------------------------------------------
1732
+ def eval_segment(self, seg, prev, prev_inv, state, depth):
1733
+ words = list(seg.words)
1734
+ if seg.funcdef:
1735
+ while words and words[0].value != "{":
1736
+ words.pop(0)
1737
+ for r in seg.redirs:
1738
+ if r.op in WRITE_OPS or (r.op == ">&" and not (r.target.value.isdigit()
1739
+ or r.target.value == "-")):
1740
+ self.check_path(r.target, state, "write", "a redirection")
1741
+ self.remember_written(r.target, state)
1742
+ while words and not words[0].quoted and words[0].value in RESERVED_SKIP:
1743
+ words.pop(0)
1744
+ if words and not words[0].quoted and words[0].value in RESERVED_HEADER:
1745
+ return None
1746
+ if words and words[-1].value == "}" and not words[-1].quoted:
1747
+ words.pop()
1748
+ argv, assigns, env_s, relocated, lookup = strip_prefixes(words)
1749
+ prefixes = list(PREFIXES_SEEN)
1750
+ seg_unknown = relocated
1751
+ if GIT_ENV_VARS.intersection(assigns):
1752
+ state.sticky = True
1753
+ seg_unknown = True
1754
+ if env_s is not None:
1755
+ if env_s.dynamic:
1756
+ self.opaque("`env -S` runs a string built at run time", seg.text)
1757
+ else:
1758
+ self.analyze_text(env_s.value, state.copy(), depth + 1)
1759
+ return None
1760
+ if lookup or not argv:
1761
+ return None
1762
+ cmd = argv[0]
1763
+ if cmd.dynamic:
1764
+ self.opaque("the command name is computed at run time", seg.text)
1765
+ return None
1766
+ name = cmd_name(cmd.value)
1767
+ args = argv[1:]
1768
+ inv = Inv(name, args, seg)
1769
+ inv.prefixes = prefixes
1770
+
1771
+ if name == "git":
1772
+ g = self.expand_git(args, state, depth)
1773
+ if g is None:
1774
+ return None
1775
+ inv.git = g
1776
+ inv.args = args = (argv[1:1 + (g.sub_index or 0)] + [static_word(g.sub)] + g.args
1777
+ if g.sub else args)
1778
+ if g.relocated:
1779
+ seg_unknown = True
1780
+ if g.dynamic_global:
1781
+ self.opaque("git's arguments are computed at run time", seg.text)
1782
+ else:
1783
+ inv.core = runner_core(name, args)
1784
+ inv.cores = wrapper_cores(name, args)
1785
+
1786
+ here_unknown = seg_unknown or state.sticky or not state.cwd_known
1787
+ if inv.git and inv.git.sub == "push":
1788
+ self.eval_push(inv, state, here_unknown)
1789
+ self.match_config(inv, state, here_unknown)
1790
+ self.indirection(inv, seg, prev, prev_inv, state, depth)
1791
+ self.protect(inv, state, seg_unknown)
1792
+ self.update_state(inv, seg, state, assigns)
1793
+ return inv
1794
+
1795
+ def expand_git(self, args, state, depth):
1796
+ for _ in range(4):
1797
+ g = parse_git(args)
1798
+ if g.sub is None or g.sub in GIT_BUILTINS:
1799
+ if g.sub == "config":
1800
+ self.git_config_alias(g, state, depth)
1801
+ return g
1802
+ alias = g.c_aliases.get(g.sub) or state.git_aliases.get(g.sub)
1803
+ if alias is None and state.cwd_known and not g.relocated:
1804
+ alias = self.ctx.git_alias(g.sub, state.cwd)
1805
+ if alias is None:
1806
+ return g
1807
+ if alias.startswith("!"):
1808
+ extra = " ".join(shlex.quote(a.value) for a in g.args if not a.dynamic)
1809
+ self.analyze_text(alias[1:] + " " + extra, state.copy(), depth + 1)
1810
+ return None
1811
+ try:
1812
+ segs = parse_command(alias)
1813
+ except ParseError:
1814
+ self.opaque("git alias `%s` can't be parsed" % g.sub, alias)
1815
+ return None
1816
+ aw = segs[0].words if segs else []
1817
+ args = args[:g.sub_index] + aw + g.args
1818
+ return parse_git(args)
1819
+
1820
+ def git_config_alias(self, g, state, depth):
1821
+ a = g.args
1822
+ for k, w in enumerate(a):
1823
+ if not w.dynamic and w.value.lower().startswith("alias.") and k + 1 < len(a):
1824
+ val = a[k + 1]
1825
+ name = w.value[6:]
1826
+ if val.dynamic:
1827
+ self.opaque("a git alias is defined from a run-time value", val.raw)
1828
+ return
1829
+ state.git_aliases[name] = val.value
1830
+ inner = val.value[1:] if val.value.startswith("!") else "git " + val.value
1831
+ self.analyze_text(inner, state.copy(), depth + 1)
1832
+ return
1833
+
1834
+ def branch_gated(self, state, here_unknown):
1835
+ if here_unknown or state.sticky or not state.cwd_known:
1836
+ return True
1837
+ b = self.ctx.current_branch(state.cwd)
1838
+ return b is None or self.ctx.is_default(b)
1839
+
1840
+ # -- git push --------------------------------------------------------------
1841
+ def push_targets(self, state, here_unknown):
1842
+ """Branch names a bare `git push` may update, and whether that is unknown."""
1843
+ if here_unknown:
1844
+ return set(), True
1845
+ cwd = state.cwd
1846
+ names = set()
1847
+ cur = self.ctx.current_branch(cwd)
1848
+ if cur is None:
1849
+ return set(), True
1850
+ names.add(cur)
1851
+ for spec in ("@{push}", "@{upstream}"):
1852
+ r = run_git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", spec], cwd)
1853
+ if r and r[0] == 0 and "/" in r[1].strip():
1854
+ names.add(r[1].strip().split("/", 1)[1])
1855
+ all_ = False
1856
+ r = run_git(["config", "--get-regexp", r"^(push\.default|remote\..*\.push)$"], cwd)
1857
+ if r and r[0] == 0:
1858
+ for line in r[1].splitlines():
1859
+ key, _, val = line.partition(" ")
1860
+ if key == "push.default" and val.strip() == "matching":
1861
+ all_ = True
1862
+ elif key.endswith(".push"):
1863
+ return names, True
1864
+ return names, all_ and "ALL"
1865
+
1866
+ def eval_push(self, inv, state, here_unknown):
1867
+ pi = analyze_push_args(inv.git.args)
1868
+ inv.push = pi
1869
+ dests = set()
1870
+ unknown = False
1871
+ touches = pi.all or pi.mirror
1872
+ refs = pi.positionals if pi.repo is not None else pi.positionals[1:]
1873
+ skip = False
1874
+ for r in refs:
1875
+ if skip:
1876
+ skip = False
1877
+ continue
1878
+ if r.dynamic:
1879
+ if BRANCH_SUBST_RE.match(r.raw) and not here_unknown:
1880
+ cur = self.ctx.current_branch(state.cwd)
1881
+ if cur:
1882
+ dests.add(cur)
1883
+ continue
1884
+ unknown = True
1885
+ continue
1886
+ v = r.value
1887
+ if v == "tag":
1888
+ skip = True
1889
+ continue
1890
+ v = v.lstrip("+")
1891
+ if ":" in v:
1892
+ src, dst = v.split(":", 1)
1893
+ if not dst:
1894
+ dst = src
1895
+ else:
1896
+ src = dst = v
1897
+ if dst in ("HEAD", "@") or (":" not in v and src in ("HEAD", "@")):
1898
+ names, unk = self.push_targets(state, here_unknown)
1899
+ dests |= names
1900
+ unknown = unknown or unk is True
1901
+ touches = touches or unk == "ALL"
1902
+ continue
1903
+ n = normalize_ref(dst)
1904
+ if n is None:
1905
+ continue
1906
+ dests.add(n)
1907
+ if ":" not in v and not here_unknown and n == src:
1908
+ rr = run_git(["rev-parse", "--abbrev-ref", "--symbolic-full-name",
1909
+ src + "@{upstream}"], state.cwd)
1910
+ if rr and rr[0] == 0 and "/" in rr[1].strip():
1911
+ dests.add(rr[1].strip().split("/", 1)[1])
1912
+ if not refs and not pi.all and not pi.mirror:
1913
+ names, unk = self.push_targets(state, here_unknown)
1914
+ dests |= names
1915
+ unknown = unknown or unk is True
1916
+ touches = touches or unk == "ALL"
1917
+ touches = touches or any(self.ctx.is_default(d) for d in dests)
1918
+ inv.push_touches = touches
1919
+ inv.push_unknown = unknown or (pi.wild and not dests)
1920
+ defaults = "/".join("`%s`" % d for d in self.ctx.defaults()[:2])
1921
+ if pi.force_like and touches:
1922
+ self.deny("a force push or remote deletion that reaches the default branch %s is "
1923
+ "never allowed in a Cohorte project (built-in hard floor: %s). Push to a "
1924
+ "feature branch instead; the remote's branch protection is the real "
1925
+ "boundary" % (defaults, short(inv.seg.text, 70)))
1926
+ elif pi.force_like and inv.push_unknown:
1927
+ self.ask("force push (or remote deletion) whose destination the gate can't resolve "
1928
+ "— make sure it does not reach %s, then confirm" % defaults)
1929
+ elif pi.wild:
1930
+ self.ask("`git push` with arguments computed at run time — the gate can't tell if "
1931
+ "it forces or where it lands; confirm")
1932
+
1933
+ # -- config rules ------------------------------------------------------------
1934
+ def match_inv(self, pat_seg, inv):
1935
+ if inv is None:
1936
+ return None
1937
+ if pat_seg.prefix_only:
1938
+ return "match" if (pat_seg.name in inv.prefixes or pat_seg.name == inv.name) else None
1939
+ if pat_seg.name == "git":
1940
+ if inv.name != "git" or inv.git is None:
1941
+ return None
1942
+ g = inv.git
1943
+ if g.sub is None:
1944
+ return "possible" if g.dynamic_global else None
1945
+ if pat_seg.git.sub is None:
1946
+ return "match"
1947
+ if pat_seg.git.sub != g.sub:
1948
+ return None
1949
+ if g.sub == "push" and inv.push is not None:
1950
+ return match_push(pat_seg.git.args, g.args, inv.push)
1951
+ return match_args(pat_seg.git.args, g.args, git=True)
1952
+ best = None
1953
+ cands = [(inv.name, inv.args)] + ([inv.core] if inv.core else []) + inv.cores
1954
+ pcands = [(pat_seg.name, pat_seg.args)] + ([pat_seg.core] if pat_seg.core else [])
1955
+ for pn, pa in pcands:
1956
+ for cn, ca in cands:
1957
+ if pn != cn:
1958
+ continue
1959
+ r = match_args(pa, ca, aliases=FLAG_ALIASES.get(cn))
1960
+ if r == "match":
1961
+ return r
1962
+ best = best or r
1963
+ return best
1964
+
1965
+ def match_config(self, inv, state, here_unknown):
1966
+ ctx = self.ctx
1967
+ for p in ctx.deny_pats:
1968
+ if p.multi or not p.segs:
1969
+ continue
1970
+ r = self.match_inv(p.segs[0], inv)
1971
+ if r == "match":
1972
+ self.deny("`%s` is forbidden by the project's gate (gate-config.json deny)" % p.text)
1973
+ elif r == "possible":
1974
+ self.ask("`%s` builds arguments at run time and might match the deny rule `%s` "
1975
+ "— confirm" % (short(inv.seg.text, 60), p.text))
1976
+ for p in ctx.ask_pats:
1977
+ if p.multi or not p.segs:
1978
+ continue
1979
+ if self.match_inv(p.segs[0], inv):
1980
+ self.ask("`%s` is a gated command — confirm first (gate-config.json ask)" % p.text)
1981
+ for p in ctx.branch_pats:
1982
+ if p.multi or not p.segs:
1983
+ continue
1984
+ if not self.match_inv(p.segs[0], inv):
1985
+ continue
1986
+ gated = self.branch_gated(state, here_unknown)
1987
+ why = "the branch is the default branch or can't be determined"
1988
+ if inv.push is not None and (inv.push_touches or inv.push_unknown):
1989
+ gated = True
1990
+ why = "the push reaches the default branch (or its destination is unknown)"
1991
+ if gated:
1992
+ self.ask("`%s` is gated on the default branch %s and %s — confirm "
1993
+ "(it runs freely on feature branches)"
1994
+ % (p.text, "/".join("`%s`" % d for d in ctx.defaults()[:2]), why))
1995
+
1996
+ def multi_patterns(self, segs, invs, state):
1997
+ def ns(s):
1998
+ return ";" if s in (";", "\n", None) else s
1999
+ tiers = [("deny", self.ctx.deny_pats), ("ask", self.ctx.ask_pats),
2000
+ ("branch", self.ctx.branch_pats)]
2001
+ for tier, pats in tiers:
2002
+ for p in pats:
2003
+ if not p.multi:
2004
+ continue
2005
+ k = len(p.segs)
2006
+ for start in range(0, len(segs) - k + 1):
2007
+ ok = True
2008
+ for j, ps in enumerate(p.segs):
2009
+ if not self.match_inv(ps, invs[start + j]):
2010
+ ok = False
2011
+ break
2012
+ if j < k - 1 and ns(segs[start + j].sep) != ns(ps.sep):
2013
+ ok = False
2014
+ break
2015
+ if not ok:
2016
+ continue
2017
+ if tier == "deny":
2018
+ self.deny("`%s` is forbidden by the project's gate" % p.text)
2019
+ elif tier == "ask" or self.branch_gated(state, False):
2020
+ self.ask("`%s` is a gated command sequence — confirm" % p.text)
2021
+ break
2022
+
2023
+ # -- indirection ---------------------------------------------------------------
2024
+ def indirection(self, inv, seg, prev, prev_inv, state, depth):
2025
+ name, args = inv.name, inv.args
2026
+ if name in SHELLS:
2027
+ code, script, sargs = self.shell_args(args)
2028
+ if code is not None:
2029
+ if code.dynamic:
2030
+ self.opaque("`%s -c` runs a command string built at run time" % name, code.raw)
2031
+ else:
2032
+ self.analyze_text(code.value, state.copy(), depth + 1)
2033
+ elif script is not None:
2034
+ self.run_script(name, script, sargs, state, depth)
2035
+ else:
2036
+ self.stdin_code(name, "sh", seg, prev, prev_inv, state, depth)
2037
+ return
2038
+ if name == "preflight.sh":
2039
+ self.preflight_args(args, state, depth)
2040
+ return
2041
+ if name == "eval":
2042
+ text = " ".join(a.value for a in args)
2043
+ if any(a.dynamic for a in args):
2044
+ self.opaque("`eval` of a string built at run time", " ".join(a.raw for a in args))
2045
+ else:
2046
+ self.analyze_text(text, state, depth + 1)
2047
+ return
2048
+ if name in ("source", "."):
2049
+ if args:
2050
+ self.run_script(name, args[0], args[1:], state, depth)
2051
+ return
2052
+ if INTERP_RE.match(name):
2053
+ lang = lang_of(name)
2054
+ code, has_script = self.interp_code(name, args)
2055
+ if code is not None:
2056
+ self.code_check(lang, code.raw if code.dynamic else code.value, state, depth)
2057
+ elif not has_script:
2058
+ self.stdin_code(name, lang, seg, prev, prev_inv, state, depth)
2059
+ return
2060
+ if name in ("xargs",):
2061
+ k = 0
2062
+ with_arg = {"-I", "-L", "-l", "-n", "-P", "-s", "-d", "-E", "-e", "-a",
2063
+ "--max-args", "--delimiter", "--arg-file", "--max-procs", "--replace",
2064
+ "--max-lines", "--max-chars", "--eof"}
2065
+ while k < len(args) and args[k].value.startswith("-") and not args[k].dynamic:
2066
+ k += 2 if args[k].value in with_arg else 1
2067
+ rest = args[k:] or [static_word("echo")]
2068
+ self.synthetic(rest + [wildcard_word()], seg, state, depth)
2069
+ return
2070
+ if name == "find":
2071
+ k = 0
2072
+ while k < len(args):
2073
+ v = args[k].value
2074
+ if v in ("-exec", "-execdir", "-ok", "-okdir"):
2075
+ j = k + 1
2076
+ while j < len(args) and args[j].value not in (";", "+"):
2077
+ j += 1
2078
+ if j > k + 1:
2079
+ self.synthetic(args[k + 1:j], seg, state, depth)
2080
+ k = j
2081
+ k += 1
2082
+ return
2083
+ if name == "watch":
2084
+ k = 0
2085
+ while k < len(args) and args[k].value.startswith("-"):
2086
+ k += 2 if args[k].value in ("-n", "--interval", "-d") else 1
2087
+ if k < len(args):
2088
+ if any(a.dynamic for a in args[k:]):
2089
+ self.opaque("`watch` runs a command built at run time", seg.text)
2090
+ else:
2091
+ self.analyze_text(" ".join(a.value for a in args[k:]), state.copy(), depth + 1)
2092
+ return
2093
+ if name in ("su", "runuser"):
2094
+ for k, a in enumerate(args):
2095
+ if a.value in ("-c", "--command") and k + 1 < len(args):
2096
+ c = args[k + 1]
2097
+ if c.dynamic:
2098
+ self.opaque("`su -c` runs a command built at run time", c.raw)
2099
+ else:
2100
+ self.analyze_text(c.value, state.copy(), depth + 1)
2101
+ return
2102
+ if name == "trap" and args:
2103
+ a = args[0]
2104
+ if a.dynamic:
2105
+ self.opaque("`trap` installs a command built at run time", a.raw)
2106
+ elif a.value not in ("-", "") and not a.value.startswith("-"):
2107
+ self.analyze_text(a.value, state.copy(), depth + 1)
2108
+ return
2109
+ if name == "alias":
2110
+ for a in args:
2111
+ if "=" in a.value:
2112
+ val = a.value.split("=", 1)[1]
2113
+ if a.dynamic:
2114
+ self.opaque("an alias is defined from a run-time value", a.raw)
2115
+ elif val:
2116
+ self.analyze_text(val, state.copy(), depth + 1)
2117
+ return
2118
+ if name in ("ssh", "mosh"):
2119
+ k = 0
2120
+ with_arg = set("-b -c -D -E -e -F -I -i -J -L -l -m -O -o -p -Q -R -S -W -w -B".split())
2121
+ while k < len(args) and args[k].value.startswith("-") and not args[k].dynamic:
2122
+ k += 2 if args[k].value in with_arg else 1
2123
+ rest = args[k + 1:]
2124
+ if rest:
2125
+ remote = state.copy()
2126
+ remote.cwd_known = False
2127
+ remote.sticky = True
2128
+ if any(a.dynamic for a in rest):
2129
+ self.opaque("`ssh` runs a remote command built at run time", seg.text)
2130
+ else:
2131
+ self.analyze_text(" ".join(a.value for a in rest), remote, depth + 1)
2132
+ return
2133
+ if name in ("npx", "bunx", "pnpx"):
2134
+ for k, a in enumerate(args):
2135
+ if a.value in ("-c", "--call") and k + 1 < len(args):
2136
+ c = args[k + 1]
2137
+ if c.dynamic:
2138
+ self.opaque("`npx -c` runs a command built at run time", c.raw)
2139
+ else:
2140
+ self.analyze_text(c.value, state.copy(), depth + 1)
2141
+
2142
+ def synthetic(self, words, seg, state, depth):
2143
+ s = Seg(seg.src, seg.start, False)
2144
+ s.end = seg.end
2145
+ s.words = list(words)
2146
+ s.sep = seg.sep
2147
+ self.eval_segment(s, None, None, state.copy(), depth + 1)
2148
+
2149
+ def shell_args(self, args):
2150
+ code_next = False
2151
+ k = 0
2152
+ while k < len(args):
2153
+ a = args[k]
2154
+ v = a.value
2155
+ if a.dynamic and not code_next:
2156
+ return None, a, args[k + 1:]
2157
+ if code_next:
2158
+ return a, None, args[k + 1:]
2159
+ if v == "--" or v == "-":
2160
+ k += 1
2161
+ break
2162
+ if v in ("-o", "+o", "-O", "+O", "--rcfile", "--init-file"):
2163
+ k += 2
2164
+ continue
2165
+ if v.startswith("--"):
2166
+ k += 1
2167
+ continue
2168
+ if len(v) > 1 and v[0] in "-+":
2169
+ if v[0] == "-" and "c" in v[1:]:
2170
+ code_next = True
2171
+ k += 1
2172
+ continue
2173
+ break
2174
+ if code_next:
2175
+ return (args[k] if k < len(args) else static_word("")), None, args[k + 1:]
2176
+ if k < len(args):
2177
+ return None, args[k], args[k + 1:]
2178
+ return None, None, []
2179
+
2180
+ def run_script(self, name, script, sargs, state, depth):
2181
+ if script.dynamic:
2182
+ self.opaque("`%s` runs a script whose path is computed at run time" % name, script.raw)
2183
+ return
2184
+ if self.path_key(script, state) in state.written:
2185
+ self.opaque("`%s` runs a file written earlier in this same command" % name,
2186
+ script.value)
2187
+ return
2188
+ if cmd_name(script.value) == "preflight.sh":
2189
+ self.preflight_args(sargs, state, depth)
2190
+
2191
+ def preflight_args(self, args, state, depth):
2192
+ """preflight.sh <report> "<cmd>"…: it truncates <report>, and runs each cmd via sh -c."""
2193
+ if not args:
2194
+ return
2195
+ self.check_path(args[0], state, "write", "preflight.sh's report argument")
2196
+ for a in args[1:]:
2197
+ if a.dynamic:
2198
+ self.opaque("preflight.sh runs a check command built at run time", a.raw)
2199
+ else:
2200
+ self.analyze_text(a.value, state.copy(), depth + 1)
2201
+
2202
+ def interp_code(self, name, args):
2203
+ lang = lang_of(name)
2204
+ k = 0
2205
+ while k < len(args):
2206
+ a = args[k]
2207
+ v = a.value
2208
+ if a.dynamic:
2209
+ return None, True
2210
+ if lang == "py":
2211
+ if v.startswith("-") and not v.startswith("--") and "c" in v[1:]:
2212
+ i = v.index("c", 1)
2213
+ rest = v[i + 1:]
2214
+ if rest:
2215
+ return static_word(rest), False
2216
+ return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2217
+ if v in ("-m",) or (v.startswith("-m") and len(v) > 2):
2218
+ return None, True
2219
+ if v in ("-W", "-X", "-Q"):
2220
+ k += 2
2221
+ continue
2222
+ if v == "-":
2223
+ return None, False
2224
+ elif lang == "js":
2225
+ if v in ("-e", "--eval", "-p", "--print") or v.startswith("--eval=") \
2226
+ or v.startswith("--print="):
2227
+ if "=" in v:
2228
+ return static_word(v.split("=", 1)[1]), False
2229
+ return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2230
+ if name == "deno" and v == "eval":
2231
+ return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2232
+ if v in ("-r", "--require", "--import", "--loader", "-C", "--conditions"):
2233
+ k += 2
2234
+ continue
2235
+ if name in ("deno", "bun") and not v.startswith("-"):
2236
+ return None, True
2237
+ else:
2238
+ letters = {"php": "r", "ruby": "e"}.get(name, "eE")
2239
+ if v.startswith("-") and not v.startswith("--") and any(c in v[1:] for c in letters):
2240
+ j = min(v.index(c, 1) for c in letters if c in v[1:])
2241
+ rest = v[j + 1:]
2242
+ if rest and not rest.startswith("."):
2243
+ return static_word(rest), False
2244
+ return (args[k + 1] if k + 1 < len(args) else static_word("")), False
2245
+ if v == "--":
2246
+ return None, k + 1 < len(args)
2247
+ if not v.startswith("-"):
2248
+ return None, True
2249
+ k += 1
2250
+ return None, False
2251
+
2252
+ def code_check(self, lang, code, state, depth):
2253
+ if PROTECTED_NAME_RE.search(code):
2254
+ self.ask("inline code references a file the Cohorte gate depends on (gate config, "
2255
+ "settings or preflight stamp) — confirm it only reads it")
2256
+ if not SPAWN_RE[lang].search(code):
2257
+ return
2258
+ joined = re.sub(r"(['\"])\s*\+\s*\1", "", code)
2259
+ for m in STRING_LIT_RE.finditer(joined):
2260
+ lit = m.group(1) if m.group(1) is not None else m.group(2)
2261
+ if lit and " " in lit:
2262
+ self.analyze_text(lit, state.copy(), depth + 1)
2263
+ self.opaque("inline code starts processes", joined)
2264
+
2265
+ def stdin_code(self, name, lang, seg, prev, prev_inv, state, depth):
2266
+ def feed(text, static):
2267
+ if lang == "sh":
2268
+ if static:
2269
+ self.analyze_text(text, state.copy(), depth + 1)
2270
+ else:
2271
+ self.opaque("`%s` reads commands built at run time" % name, text)
2272
+ else:
2273
+ self.code_check(lang, text, state, depth)
2274
+
2275
+ for h in seg.heredocs:
2276
+ feed(h.body, True)
2277
+ return
2278
+ for r in seg.redirs:
2279
+ if r.op == "<<<":
2280
+ feed(r.target.raw if r.target.dynamic else r.target.value, not r.target.dynamic)
2281
+ return
2282
+ if r.op == "<":
2283
+ if r.target.dynamic or self.path_key(r.target, state) in state.written:
2284
+ self.opaque("`%s` reads commands from a file written or computed in this "
2285
+ "same command" % name, seg.text)
2286
+ return
2287
+ if prev is not None and prev.sep in ("|", "|&"):
2288
+ if prev_inv is not None and prev_inv.name in ("echo", "printf") \
2289
+ and not any(a.dynamic for a in prev_inv.args):
2290
+ vals = [a.value for a in prev_inv.args]
2291
+ if prev_inv.name == "echo":
2292
+ while vals and re.match(r"^-[neE]+$", vals[0]):
2293
+ vals.pop(0)
2294
+ text = " ".join(vals)
2295
+ else:
2296
+ text = vals[0] if vals else ""
2297
+ for v in vals[1:]:
2298
+ text = text.replace("%s", v, 1) if "%s" in text else text + " " + v
2299
+ text = text.replace("\\n", "\n")
2300
+ feed(text, True)
2301
+ else:
2302
+ self.opaque("`%s` executes whatever the pipe feeds it" % name,
2303
+ prev.text + " | " + seg.text)
2304
+
2305
+ # -- self-protection --------------------------------------------------------------
2306
+ def path_key(self, w, state):
2307
+ v = os.path.expanduser(w.value)
2308
+ if not os.path.isabs(v) and state.cwd_known:
2309
+ v = os.path.join(state.cwd, v)
2310
+ return os.path.normpath(v)
2311
+
2312
+ def remember_written(self, w, state):
2313
+ if not w.dynamic:
2314
+ state.written.add(self.path_key(w, state))
2315
+
2316
+ def classify_path(self, w, state, mode, relocated=False):
2317
+ ctx = self.ctx
2318
+ if w.dynamic:
2319
+ t = w.raw
2320
+ if len(t) >= 2 and t[0] == t[-1] == '"':
2321
+ t = t[1:-1]
2322
+ for var, val in (("CLAUDE_PROJECT_DIR", os.environ.get("CLAUDE_PROJECT_DIR")),
2323
+ ("HOME", os.path.expanduser("~")),
2324
+ ("PWD", state.cwd if state.cwd_known else None)):
2325
+ if val:
2326
+ # Forward slashes: a Windows value (C:\\Users\\…) would otherwise read as
2327
+ # shell escapes below and every expanded path would look suspect.
2328
+ val = val.replace("\\", "/")
2329
+ t = t.replace("${%s}" % var, val).replace("$" + var, val)
2330
+ if "$" in t or "`" in t or "'" in t or '"' in t or "\\" in t:
2331
+ return "suspect" if suspicious(w.value.split(DYN)[-1], w.raw) else None
2332
+ w = static_word(t)
2333
+ v = os.path.expanduser(w.value)
2334
+ if not v:
2335
+ return None
2336
+ if not os.path.isabs(v):
2337
+ if relocated or not state.cwd_known:
2338
+ return "suspect" if suspicious(v, v) else None
2339
+ v = os.path.join(state.cwd, v)
2340
+ prot = ctx.delete_protected if mode in ("delete", "recursive", "chmod") else ctx.protected
2341
+ targets = [v]
2342
+ if w.glob:
2343
+ pat = os.path.normpath(v)
2344
+ if any(fnmatch.fnmatchcase(p, pat) for p in prot):
2345
+ return "protected"
2346
+ try:
2347
+ targets = glob.glob(v)[:500]
2348
+ except Exception:
2349
+ targets = []
2350
+ for t in targets:
2351
+ for cand in {os.path.normpath(os.path.abspath(t)), os.path.realpath(t)}:
2352
+ if cand in prot:
2353
+ return "protected"
2354
+ if mode in ("delete", "recursive", "chmod"):
2355
+ pre = cand if cand.endswith(os.sep) else cand + os.sep
2356
+ if any(p.startswith(pre) for p in prot):
2357
+ return "protected" if mode == "delete" else "suspect"
2358
+ return None
2359
+
2360
+ def check_path(self, w, state, mode, via, relocated=False):
2361
+ kind = self.classify_path(w, state, mode, relocated)
2362
+ if kind is None:
2363
+ return
2364
+ verb = {"write": "overwrite", "delete": "delete or move", "recursive": "overwrite",
2365
+ "chmod": "change the permissions of"}[mode]
2366
+ if kind == "protected" and mode in ("write", "delete"):
2367
+ self.deny("%s would %s `%s`, which the Cohorte gate depends on (self-protection). "
2368
+ "Edit gate rules through PIPELINE.md and /cohorte-update-pipeline, or ask "
2369
+ "the human" % (via, verb, w.raw))
2370
+ else:
2371
+ self.ask("%s may %s a file the Cohorte gate depends on (`%s`) — confirm"
2372
+ % (via, verb, w.raw))
2373
+
2374
+ def protect(self, inv, state, relocated):
2375
+ name, args = inv.name, inv.args
2376
+
2377
+ def positionals(tokens, with_arg=()):
2378
+ out = []
2379
+ end = False
2380
+ k = 0
2381
+ while k < len(tokens):
2382
+ w = tokens[k]
2383
+ v = w.value
2384
+ if not end and v == "--":
2385
+ end = True
2386
+ elif not end and is_flag_word(w):
2387
+ if v in with_arg:
2388
+ k += 1
2389
+ else:
2390
+ out.append(w)
2391
+ k += 1
2392
+ return out
2393
+
2394
+ def recursive(tokens):
2395
+ fl = flag_names(tokens)
2396
+ return bool(fl & {"-r", "-R", "-a", "--recursive", "--archive"})
2397
+
2398
+ def copy_like(srcs, dst, label, mv=False):
2399
+ for s in srcs:
2400
+ if mv:
2401
+ self.check_path(s, state, "delete", "`%s`" % label, relocated)
2402
+ self.check_path(dst, state, "write", "`%s`" % label, relocated)
2403
+ dk = self.path_key(dst, state) if not dst.dynamic else None
2404
+ if dk and state.cwd_known and (os.path.isdir(dk) or dst.value.endswith("/")):
2405
+ for s in srcs:
2406
+ if not s.dynamic:
2407
+ self.check_path(static_word(os.path.join(dk, os.path.basename(
2408
+ s.value.rstrip("/")))), state, "write", "`%s`" % label, relocated)
2409
+ if recursive(args) or mv:
2410
+ self.check_path(dst, state, "recursive", "`%s`" % label, relocated)
2411
+
2412
+ if name in ("rm", "unlink", "shred", "rmdir", "srm", "trash", "trash-put"):
2413
+ for p in positionals(args):
2414
+ self.check_path(p, state, "delete", "`%s`" % name, relocated)
2415
+ elif name in ("mv", "cp", "install", "ln", "rsync", "scp", "ditto"):
2416
+ pos = positionals(args, ("-t", "--target-directory", "-S", "--suffix", "-m",
2417
+ "--mode", "-o", "-g", "-e", "--exclude", "--include"))
2418
+ target = None
2419
+ for k, w in enumerate(args):
2420
+ if w.value in ("-t", "--target-directory") and k + 1 < len(args):
2421
+ target = args[k + 1]
2422
+ elif w.value.startswith("--target-directory="):
2423
+ target = static_word(w.value.split("=", 1)[1])
2424
+ if target is not None:
2425
+ copy_like(pos, static_word(target.value.rstrip("/") + "/")
2426
+ if not target.dynamic else target, name, mv=(name == "mv"))
2427
+ elif len(pos) >= 2:
2428
+ copy_like(pos[:-1], pos[-1], name, mv=(name == "mv"))
2429
+ elif name == "tee":
2430
+ for p in positionals(args):
2431
+ self.check_path(p, state, "write", "`tee`", relocated)
2432
+ self.remember_written(p, state)
2433
+ elif name == "truncate":
2434
+ for p in positionals(args, ("-s", "-r", "--size", "--reference")):
2435
+ self.check_path(p, state, "write", "`truncate`", relocated)
2436
+ elif name in ("sed", "gsed", "perl", "ruby"):
2437
+ inplace = any(
2438
+ not w.dynamic and (w.value.startswith("--in-place") or (
2439
+ w.value.startswith("-") and not w.value.startswith("--")
2440
+ and "i" in w.value[1:].split(".")[0]))
2441
+ for w in args)
2442
+ if inplace:
2443
+ for p in positionals(args, ("-e", "-f")):
2444
+ self.check_path(p, state, "write", "`%s -i`" % name, relocated)
2445
+ elif name == "dd":
2446
+ for w in args:
2447
+ if w.value.startswith("of="):
2448
+ self.check_path(static_word(w.value[3:]) if not w.dynamic else w,
2449
+ state, "write", "`dd of=`", relocated)
2450
+ elif name in ("curl", "wget"):
2451
+ opts = ("-o", "--output") if name == "curl" else ("-O", "--output-document")
2452
+ for k, w in enumerate(args):
2453
+ v = w.value
2454
+ if v in opts and k + 1 < len(args):
2455
+ self.check_path(args[k + 1], state, "write", "`%s %s`" % (name, v), relocated)
2456
+ elif any(v.startswith(o + "=") for o in opts if o.startswith("--")):
2457
+ self.check_path(static_word(v.split("=", 1)[1]), state, "write",
2458
+ "`%s`" % name, relocated)
2459
+ elif name in ("chmod", "chown", "chgrp", "chflags", "chattr", "setfacl"):
2460
+ for p in positionals(args)[1:]:
2461
+ self.check_path(p, state, "chmod", "`%s`" % name, relocated)
2462
+ elif name == "find" and any(w.value == "-delete" for w in args):
2463
+ for w in args:
2464
+ if w.value.startswith("-") or w.value in ("(", "!", ")"):
2465
+ break
2466
+ self.check_path(w, state, "delete", "`find -delete`", relocated)
2467
+ elif name == "git" and inv.git and inv.git.sub in ("rm", "mv"):
2468
+ g = inv.git
2469
+ pos = positionals(g.args)
2470
+ reloc = relocated or g.relocated
2471
+ if g.sub == "rm" and not any(w.value == "--cached" for w in g.args):
2472
+ for p in pos:
2473
+ self.check_path(p, state, "delete", "`git rm`", reloc)
2474
+ elif g.sub == "mv" and len(pos) >= 2:
2475
+ for p in pos[:-1]:
2476
+ self.check_path(p, state, "delete", "`git mv`", reloc)
2477
+ self.check_path(pos[-1], state, "write", "`git mv`", reloc)
2478
+
2479
+ # -- chain state -----------------------------------------------------------------
2480
+ def update_state(self, inv, seg, state, assigns):
2481
+ name, args = inv.name, inv.args
2482
+ if name == "cd":
2483
+ sep = seg.sep
2484
+ if sep in ("|", "|&", "&"):
2485
+ return
2486
+ if sep == "||":
2487
+ state.cwd_known = False
2488
+ return
2489
+ pos = [w for w in args if not (is_flag_word(w) and w.value in ("-L", "-P", "-e", "-@"))]
2490
+ if pos and pos[0].value == "--" and not pos[0].dynamic:
2491
+ pos = pos[1:]
2492
+ if not pos:
2493
+ target = os.path.expanduser("~")
2494
+ else:
2495
+ w = pos[0]
2496
+ if w.value == "-" and not w.dynamic:
2497
+ state.cwd_known = False
2498
+ return
2499
+ if w.dynamic:
2500
+ k = self.classify_dynamic_dir(w, state)
2501
+ if k is None:
2502
+ state.cwd_known = False
2503
+ return
2504
+ target = k
2505
+ else:
2506
+ target = os.path.expanduser(w.value)
2507
+ if not os.path.isabs(target):
2508
+ if not state.cwd_known:
2509
+ return
2510
+ target = os.path.join(state.cwd, target)
2511
+ if os.path.isdir(target):
2512
+ state.cwd = os.path.realpath(target)
2513
+ state.cwd_known = True
2514
+ else:
2515
+ state.cwd_known = False
2516
+ return
2517
+ if name in ("pushd", "popd"):
2518
+ state.cwd_known = False
2519
+ state.sticky = True
2520
+ return
2521
+ if name in ("export", "declare", "typeset", "readonly", "local"):
2522
+ for a in args:
2523
+ m = ASSIGN_RE.match(a.raw) or re.match(r"^([A-Za-z_][A-Za-z0-9_]*)$", a.raw)
2524
+ if m and m.group(1) in GIT_ENV_VARS:
2525
+ state.sticky = True
2526
+ return
2527
+ if name == "git" and inv.git:
2528
+ g = inv.git
2529
+ if g.relocated:
2530
+ state.sticky = True
2531
+ sub = g.sub
2532
+ if sub in ("switch", "bisect"):
2533
+ state.sticky = True
2534
+ elif sub == "checkout" and not any(w.value == "--" for w in g.args):
2535
+ state.sticky = True
2536
+ elif sub == "branch" and (flag_names(g.args) & {"-m", "-M", "--move"}):
2537
+ state.sticky = True
2538
+
2539
+ def classify_dynamic_dir(self, w, state):
2540
+ t = w.raw
2541
+ if len(t) >= 2 and t[0] == t[-1] == '"':
2542
+ t = t[1:-1]
2543
+ # Only $HOME: CLAUDE_PROJECT_DIR is set for hooks but usually NOT in the agent's
2544
+ # Bash call, so resolving it here could judge the branch in the wrong directory.
2545
+ val = os.path.expanduser("~")
2546
+ t = t.replace("${HOME}", val).replace("$HOME", val)
2547
+ if "$" in t or "`" in t or "'" in t or '"' in t or "\\" in t:
2548
+ return None
2549
+ return t
2550
+
2551
+
2552
+ # ── preflight phase gate ─────────────────────────────────────────────────────
2553
+ HEX_RE = re.compile(r"^[0-9a-f]{40}([0-9a-f]{24})?$")
2554
+ DIGEST_EXCLUDES = (".claude", "specs")
2555
+ LEGACY_EXCLUDES = (".claude", ".cohorte", "specs")
2556
+
2557
+
2558
+ def tree_digest(cwd, excludes):
2559
+ """The digest preflight.sh stamps: the git tree id of the working tree at `cwd`, built in
2560
+ a throwaway index seeded from the real one (backdated so same-second edits are
2561
+ re-hashed), with `excludes` dropped. Must stay identical to preflight.sh.
2562
+ Returns the tree id, None on failure; raises TimedOut when the budget is spent."""
2563
+ tmp = None
2564
+ try:
2565
+ r = run_git(["rev-parse", "--absolute-git-dir"], cwd, raise_timeout=True)
2566
+ if not r or r[0] != 0:
2567
+ return None
2568
+ real_index = os.path.join(r[1].strip(), "index")
2569
+ fd, tmp = tempfile.mkstemp(prefix="cohorte-idx-")
2570
+ os.close(fd)
2571
+ if os.path.exists(real_index):
2572
+ shutil.copyfile(real_index, tmp)
2573
+ old = time.time() - 5
2574
+ os.utime(tmp, (old, old))
2575
+ else:
2576
+ os.unlink(tmp)
2577
+ env = git_env({"GIT_INDEX_FILE": tmp})
2578
+ run_git(["rm", "--cached", "-r", "-q", "--ignore-unmatch", "--"] + list(excludes),
2579
+ cwd, timeout=10, env=env, raise_timeout=True)
2580
+ add = run_git(["add", "-A", "--", "."] + [":(exclude)%s" % e for e in excludes],
2581
+ cwd, timeout=30, env=env, raise_timeout=True)
2582
+ if not add or add[0] != 0:
2583
+ return None
2584
+ out = run_git(["write-tree"], cwd, timeout=10, env=env, raise_timeout=True)
2585
+ if not out or out[0] != 0:
2586
+ return None
2587
+ return out[1].strip() or None
2588
+ finally:
2589
+ for p in ((tmp, tmp + ".lock") if tmp else ()):
2590
+ try:
2591
+ os.unlink(p)
2592
+ except Exception:
2593
+ pass
2594
+
2595
+
2596
+ class Dispatch(object):
2597
+ def __init__(self, ctx):
2598
+ self.ctx = ctx
2599
+ self._digests = None
2600
+
2601
+ def current_digests(self, cwd, top):
2602
+ """Digests of the dispatch checkout: at its toplevel and at cwd (preflight.sh digests
2603
+ relative to its pwd), with today's and the legacy (.cohorte-excluding) excludes."""
2604
+ if self._digests is None:
2605
+ out = set()
2606
+ dirs = [top] + ([cwd] if cwd and cwd != top else [])
2607
+ variants = [DIGEST_EXCLUDES]
2608
+ if any(os.path.exists(os.path.join(d, ".cohorte")) for d in dirs):
2609
+ variants.append(LEGACY_EXCLUDES)
2610
+ try:
2611
+ for d in dirs:
2612
+ for ex in variants:
2613
+ dg = tree_digest(d, ex)
2614
+ if dg:
2615
+ out.add(dg)
2616
+ except TimedOut:
2617
+ self._digests = "timeout"
2618
+ return self._digests
2619
+ self._digests = out
2620
+ return self._digests
2621
+
2622
+ def check_stamp(self, path, cwd, top, max_age):
2623
+ try:
2624
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
2625
+ raw = fh.read(4096)
2626
+ except Exception:
2627
+ return "the preflight stamp can't be read"
2628
+ fields = raw.split()
2629
+ if not fields:
2630
+ return "the preflight stamp is empty"
2631
+ try:
2632
+ epoch = float(fields[0])
2633
+ if epoch != epoch or epoch in (float("inf"), float("-inf")):
2634
+ raise ValueError()
2635
+ except ValueError:
2636
+ return "the preflight stamp is unreadable (expected `<epoch> <sha> <digest>`)"
2637
+ now = time.time()
2638
+ if epoch > now + 60:
2639
+ return "the preflight stamp is dated in the future (forged, or a clock problem)"
2640
+ if max_age <= 0:
2641
+ return "preflight.max_age_minutes is 0, so every stamp counts as stale"
2642
+ age_min = (now - epoch) / 60
2643
+ if age_min > max_age:
2644
+ return "the preflight stamp is %.0f min old (max %g)" % (age_min, max_age)
2645
+ if top is None:
2646
+ return None # not a git checkout: freshness is all that can be checked
2647
+ if len(fields) < 3:
2648
+ return ("the preflight stamp has no content digest (a legacy or hand-written stamp "
2649
+ "— expected `<epoch> <sha> <digest>`)")
2650
+ digest = fields[2].lower()
2651
+ if digest == "none" or not HEX_RE.match(digest):
2652
+ return "the preflight stamp has no valid content digest"
2653
+ current = self.current_digests(cwd, top)
2654
+ if current == "timeout":
2655
+ return "the code digest could not be computed within the gate's time budget"
2656
+ if not current:
2657
+ return "the current code digest could not be computed"
2658
+ if digest not in current:
2659
+ return ("the code changed since the preflight ran (or the stamp was made for "
2660
+ "another checkout)")
2661
+ return None
2662
+
2663
+ def evaluate(self, tool_input, cwd):
2664
+ ctx = self.ctx
2665
+ sub = tool_input.get("subagent_type")
2666
+ if sub is None:
2667
+ sub = tool_input.get("agent_type", "")
2668
+ if sub is None:
2669
+ sub = ""
2670
+ if not isinstance(sub, str):
2671
+ raise TypeError("tool_input.subagent_type is not a string")
2672
+ if ctx.errors:
2673
+ return ("ask", "gate-config.json is invalid (%s), so the preflight phase gate can't be "
2674
+ "evaluated — fix it, then confirm this dispatch" % "; ".join(ctx.errors))
2675
+ pf = ctx.cfg["preflight"]
2676
+ if not pf or not pf["enabled"] or not sub:
2677
+ return None
2678
+ if not any(sub == a or sub.endswith(":" + a) for a in pf["agents"]):
2679
+ return None
2680
+ top = None
2681
+ if cwd:
2682
+ top = git_top_and_common(cwd)[0]
2683
+ if top is None and remaining() <= 0.05:
2684
+ why = "the checkout could not be inspected within the gate's time budget"
2685
+ return ("ask", "Phase gate: dispatching `%s`, but %s — confirm to dispatch anyway."
2686
+ % (sub, why))
2687
+ cands = []
2688
+ for d in ([top] if top else []) + ctx.roots:
2689
+ p = os.path.join(d, ".claude", "preflight.ok")
2690
+ if os.path.isfile(p) and p not in cands:
2691
+ cands.append(p)
2692
+ if not cands:
2693
+ why = "no preflight stamp was found (.claude/preflight.ok)"
2694
+ else:
2695
+ why = None
2696
+ for p in cands:
2697
+ r = self.check_stamp(p, cwd, top, pf["max_age_minutes"])
2698
+ if r is None:
2699
+ return None
2700
+ why = why or r
2701
+ return ("ask", "Phase gate: dispatching `%s`, but %s. Run the deterministic pre-flight "
2702
+ "first (<core>/pipeline/scripts/preflight.sh — typecheck + lint + tests, from this "
2703
+ "checkout) so agents never review red code, or confirm to dispatch anyway "
2704
+ "(PIPELINE.md gate.preflight)." % (sub, why))
2705
+
2706
+
2707
+ # ── entry points ─────────────────────────────────────────────────────────────
2708
+ DISPATCH_TOOLS = {"Task", "Agent"}
2709
+ EDIT_TOOLS = {"Write", "Edit", "MultiEdit", "NotebookEdit"}
2710
+ GATED_TOOLS = {"Bash"} | DISPATCH_TOOLS | EDIT_TOOLS
2711
+ UNATTENDED_MODES = {"bypassPermissions", "dontAsk"}
2712
+
2713
+
2714
+ class PayloadError(Exception):
2715
+ pass
2716
+
2717
+
2718
+ def default_cwd():
2719
+ env = os.environ.get("CLAUDE_PROJECT_DIR") or ""
2720
+ if env and os.path.isdir(env):
2721
+ return env
2722
+ try:
2723
+ return os.getcwd()
2724
+ except Exception:
2725
+ return None
2726
+
2727
+
2728
+ def evaluate(payload):
2729
+ """The decision for one PreToolUse payload: None (allow) or (decision, reason)."""
2730
+ tool = payload.get("tool_name")
2731
+ if not isinstance(tool, str):
2732
+ raise PayloadError("tool_name is missing or not a string")
2733
+ if tool not in GATED_TOOLS:
2734
+ return None
2735
+ cwd = payload.get("cwd")
2736
+ if not isinstance(cwd, str) or not cwd or not os.path.isdir(cwd):
2737
+ cwd = default_cwd()
2738
+ mode = payload.get("permission_mode")
2739
+ if not isinstance(mode, str):
2740
+ mode = None
2741
+ ctx = Ctx(cwd, mode)
2742
+ if not ctx.active:
2743
+ return None
2744
+ ti = payload.get("tool_input")
2745
+ if not isinstance(ti, dict):
2746
+ raise PayloadError("tool_input is not an object")
2747
+ decision = None
2748
+ if tool == "Bash":
2749
+ cmd = ti.get("command")
2750
+ if not isinstance(cmd, str):
2751
+ raise PayloadError("tool_input.command is not a string")
2752
+ an = Analyzer(ctx)
2753
+ an.analyze_text(cmd, State(ctx.cwd0), 0)
2754
+ decision = an.verdict()
2755
+ if ctx.errors and (decision is None or decision[0] != "deny"):
2756
+ decision = ("ask", "gate-config.json is invalid (%s), so every command needs "
2757
+ "confirmation until it is fixed (the hard floor and self-protection "
2758
+ "still apply)" % "; ".join(ctx.errors))
2759
+ elif tool in DISPATCH_TOOLS:
2760
+ decision = Dispatch(ctx).evaluate(ti, ctx.cwd0)
2761
+ else:
2762
+ fp = ti.get("file_path")
2763
+ if fp is None:
2764
+ fp = ti.get("notebook_path")
2765
+ if isinstance(fp, str) and fp:
2766
+ p = fp if os.path.isabs(fp) else os.path.join(ctx.cwd0 or ".", fp)
2767
+ p = os.path.expanduser(p)
2768
+ if os.path.normpath(p) in ctx.protected or os.path.realpath(p) in ctx.protected:
2769
+ decision = ("ask", "`%s` edits `%s`, a file the Cohorte gate depends on "
2770
+ "(self-protection) — confirm this change is intended" % (tool, fp))
2771
+ if decision is None:
2772
+ return None
2773
+ level, reason = decision
2774
+ if level == "ask" and mode in UNATTENDED_MODES:
2775
+ level = "deny"
2776
+ reason += (" (denied outright: permission mode `%s` has nobody to confirm — re-run it "
2777
+ "interactively if it is intended)" % mode)
2778
+ return level, "Cohorte gate: " + reason
2779
+
2780
+
2781
+ def emit(decision, reason):
2782
+ sys.stdout.write(json.dumps({"hookSpecificOutput": {
2783
+ "hookEventName": "PreToolUse",
2784
+ "permissionDecision": decision,
2785
+ "permissionDecisionReason": reason,
2786
+ }}) + "\n")
2787
+
2788
+
2789
+ def is_active_fallback(payload=None):
2790
+ try:
2791
+ cwd = None
2792
+ if isinstance(payload, dict) and isinstance(payload.get("cwd"), str) \
2793
+ and os.path.isdir(payload["cwd"]):
2794
+ cwd = payload["cwd"]
2795
+ return Ctx(cwd or default_cwd(), None).active
2796
+ except Exception:
2797
+ return True
2798
+
2799
+
2800
+ def hook(raw):
2801
+ try:
2802
+ payload = json.loads(raw) if raw and raw.strip() else None
2803
+ except Exception:
2804
+ payload = None
2805
+ if not isinstance(payload, dict):
2806
+ # Not a payload at all ⇒ nothing to gate. Something that looks like a tool call we
2807
+ # can't read ⇒ refuse it in an active project (fail closed).
2808
+ if re.search(r'"tool_(name|input)"', raw or "") and is_active_fallback():
2809
+ emit("deny", "Cohorte gate: the hook payload is not valid JSON, so this tool call "
2810
+ "can't be checked — refused for safety (fail closed).")
2811
+ return 0
2812
+ tool = payload.get("tool_name")
2813
+ try:
2814
+ decision = evaluate(payload)
2815
+ except Exception as e:
2816
+ if (not isinstance(tool, str) or tool in ("Bash",) or tool in DISPATCH_TOOLS) \
2817
+ and is_active_fallback(payload):
2818
+ emit("deny", "Cohorte gate failed closed: this call could not be evaluated "
2819
+ "(%s: %s). Refused for safety." % (type(e).__name__, e))
2820
+ return 0
2821
+ if decision:
2822
+ emit(*decision)
2823
+ return 0
2824
+
2825
+
2826
+ def check_cli(argv):
2827
+ mode = argv[0]
2828
+ rest = argv[1:]
2829
+ cwd = os.getcwd()
2830
+ unattended = False
2831
+ i = 0
2832
+ while i < len(rest):
2833
+ a = rest[i]
2834
+ if a == "--":
2835
+ i += 1
2836
+ break
2837
+ if a == "--unattended":
2838
+ unattended = True
2839
+ elif a == "--cwd" and i + 1 < len(rest):
2840
+ cwd = rest[i + 1]
2841
+ i += 1
2842
+ elif a.startswith("--cwd="):
2843
+ cwd = a[6:]
2844
+ else:
2845
+ break
2846
+ i += 1
2847
+ words = rest[i:]
2848
+ if not words:
2849
+ sys.stderr.write("usage: cohorte-gate.py %s [--cwd DIR] [--unattended] [--] <%s>\n"
2850
+ % (mode, "command" if mode == "--check" else "subagent_type"))
2851
+ return 2
2852
+ subject = words[0] if len(words) == 1 else " ".join(shlex.quote(w) for w in words)
2853
+ payload = {"cwd": os.path.abspath(cwd),
2854
+ "permission_mode": "bypassPermissions" if unattended else "default"}
2855
+ if mode == "--check":
2856
+ payload["tool_name"] = "Bash"
2857
+ payload["tool_input"] = {"command": subject}
2858
+ else:
2859
+ payload["tool_name"] = "Agent"
2860
+ payload["tool_input"] = {"subagent_type": subject}
2861
+ try:
2862
+ decision = evaluate(payload)
2863
+ except Exception as e:
2864
+ decision = ("deny", "Cohorte gate failed closed: %s: %s" % (type(e).__name__, e))
2865
+ if not decision:
2866
+ print("gate: allow")
2867
+ return 0
2868
+ print("gate: %s — %s" % decision)
2869
+ return 2 if decision[0] == "deny" else 1
2870
+
2871
+
2872
+ def strip_runtime(argv):
2873
+ out = []
2874
+ i = 0
2875
+ while i < len(argv):
2876
+ a = argv[i]
2877
+ if a == "--runtime" and i + 1 < len(argv):
2878
+ rt = argv[i + 1]
2879
+ i += 2
2880
+ elif a.startswith("--runtime="):
2881
+ rt = a[10:]
2882
+ i += 1
2883
+ else:
2884
+ out.append(a)
2885
+ i += 1
2886
+ continue
2887
+ if rt != "claude":
2888
+ warn("--runtime %s is no longer supported (Cohorte 3 is Claude Code only); "
2889
+ "answering in Claude Code's format" % rt)
2890
+ return out
2891
+
2892
+
2893
+ def _utf8_streams():
2894
+ """Claude Code reads hook output as UTF-8; Windows consoles default to a code page."""
2895
+ for s in (sys.stdout, sys.stderr):
2896
+ try:
2897
+ s.reconfigure(encoding="utf-8")
2898
+ except Exception:
2899
+ pass
2900
+
2901
+
2902
+ def main():
2903
+ _utf8_streams()
2904
+ argv = sys.argv[1:]
2905
+ if argv and argv[0] in ("--check", "--check-dispatch"):
2906
+ return check_cli(argv)
2907
+ argv = strip_runtime(argv)
2908
+ if argv and argv[0] in ("--check", "--check-dispatch"):
2909
+ return check_cli(argv)
2910
+ try:
2911
+ data = sys.stdin.buffer.read()
2912
+ except Exception as e:
2913
+ # Could not even read the call: refuse it in an active project (fail closed).
2914
+ if is_active_fallback():
2915
+ emit("deny", "Cohorte gate: the hook payload could not be read (%s) — refused for "
2916
+ "safety (fail closed)." % type(e).__name__)
2917
+ return 0
2918
+ return hook(data.decode("utf-8", errors="replace"))
2919
+
2920
+
2921
+ if __name__ == "__main__":
2922
+ try:
2923
+ sys.exit(main())
2924
+ except SystemExit:
2925
+ raise
2926
+ except BaseException as e: # last resort: a crash must not read as "allow"
2927
+ try:
2928
+ emit("deny", "Cohorte gate crashed (%s: %s) — refused for safety." % (type(e).__name__, e))
2929
+ except Exception:
2930
+ pass
2931
+ sys.exit(0)