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