@intentius/chant 0.124.76 → 0.124.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/dist/__fixtures__/agent-guard/plywood.d.ts +8 -0
  2. package/dist/__fixtures__/agent-guard/plywood.d.ts.map +1 -0
  3. package/dist/__fixtures__/agent-guard/plywood.js +19 -0
  4. package/dist/__fixtures__/agent-guard/terragucci.d.ts +8 -0
  5. package/dist/__fixtures__/agent-guard/terragucci.d.ts.map +1 -0
  6. package/dist/__fixtures__/agent-guard/terragucci.js +30 -0
  7. package/dist/__fixtures__/gated-ledger.d.ts +10 -0
  8. package/dist/__fixtures__/gated-ledger.d.ts.map +1 -0
  9. package/dist/__fixtures__/gated-ledger.js +51 -0
  10. package/dist/__fixtures__/notify-messages/events.d.ts +9 -0
  11. package/dist/__fixtures__/notify-messages/events.d.ts.map +1 -0
  12. package/dist/__fixtures__/notify-messages/events.js +21 -0
  13. package/dist/__fixtures__/product-words.d.ts +14 -0
  14. package/dist/__fixtures__/product-words.d.ts.map +1 -1
  15. package/dist/__fixtures__/product-words.js +11 -0
  16. package/dist/__fixtures__/terragucci-notify.d.ts +66 -0
  17. package/dist/__fixtures__/terragucci-notify.d.ts.map +1 -0
  18. package/dist/__fixtures__/terragucci-notify.js +133 -0
  19. package/dist/action-pins.d.ts +8 -0
  20. package/dist/action-pins.d.ts.map +1 -1
  21. package/dist/action-pins.js +9 -0
  22. package/dist/agent-guard.d.ts +143 -0
  23. package/dist/agent-guard.d.ts.map +1 -0
  24. package/dist/agent-guard.js +455 -0
  25. package/dist/ci-commit.d.ts +120 -5
  26. package/dist/ci-commit.d.ts.map +1 -1
  27. package/dist/ci-commit.js +214 -23
  28. package/dist/ci-own-jobs.d.ts +81 -0
  29. package/dist/ci-own-jobs.d.ts.map +1 -0
  30. package/dist/ci-own-jobs.js +233 -0
  31. package/dist/ci-product-words.d.ts +18 -4
  32. package/dist/ci-product-words.d.ts.map +1 -1
  33. package/dist/ci-product-words.js +26 -6
  34. package/dist/ci-product.d.ts +40 -1
  35. package/dist/ci-product.d.ts.map +1 -1
  36. package/dist/ci-product.js +40 -1
  37. package/dist/cli/handlers/approve.d.ts +5 -1
  38. package/dist/cli/handlers/approve.d.ts.map +1 -1
  39. package/dist/cli/handlers/approve.js +17 -11
  40. package/dist/cli/handlers/build.d.ts +1 -1
  41. package/dist/cli/handlers/build.d.ts.map +1 -1
  42. package/dist/cli/handlers/build.js +88 -2
  43. package/dist/cli/handlers/commit.d.ts.map +1 -1
  44. package/dist/cli/handlers/commit.js +3 -1
  45. package/dist/cli/handlers/notify-relay.d.ts +18 -1
  46. package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
  47. package/dist/cli/handlers/notify-relay.js +90 -14
  48. package/dist/cli/handlers/pr.d.ts.map +1 -1
  49. package/dist/cli/handlers/pr.js +3 -1
  50. package/dist/cli/handlers/release.d.ts +5 -1
  51. package/dist/cli/handlers/release.d.ts.map +1 -1
  52. package/dist/cli/handlers/release.js +21 -9
  53. package/dist/cli/handlers/run-generate.d.ts.map +1 -1
  54. package/dist/cli/handlers/run-generate.js +2 -1
  55. package/dist/cli/main.d.ts.map +1 -1
  56. package/dist/cli/main.js +21 -1
  57. package/dist/cli/parse-args.d.ts.map +1 -1
  58. package/dist/cli/parse-args.js +60 -4
  59. package/dist/cli/registry.d.ts +16 -0
  60. package/dist/cli/registry.d.ts.map +1 -1
  61. package/dist/components/pr-env-components.d.ts +65 -0
  62. package/dist/components/pr-env-components.d.ts.map +1 -0
  63. package/dist/components/pr-env-components.js +162 -0
  64. package/dist/components/pr-policy.d.ts +15 -0
  65. package/dist/components/pr-policy.d.ts.map +1 -1
  66. package/dist/components/pr-policy.js +24 -1
  67. package/dist/components/release-compile.d.ts +15 -3
  68. package/dist/components/release-compile.d.ts.map +1 -1
  69. package/dist/components/release-compile.js +66 -15
  70. package/dist/config.d.ts +14 -8
  71. package/dist/config.d.ts.map +1 -1
  72. package/dist/config.js +16 -1
  73. package/dist/gate-policy.d.ts +14 -1
  74. package/dist/gate-policy.d.ts.map +1 -1
  75. package/dist/gate-policy.js +16 -6
  76. package/dist/lexicon.d.ts +25 -1
  77. package/dist/lexicon.d.ts.map +1 -1
  78. package/dist/lexicon.js +10 -0
  79. package/dist/lifecycle/gated-op.d.ts +95 -0
  80. package/dist/lifecycle/gated-op.d.ts.map +1 -0
  81. package/dist/lifecycle/gated-op.js +96 -0
  82. package/dist/lifecycle/git.d.ts.map +1 -1
  83. package/dist/lifecycle/git.js +83 -2
  84. package/dist/lifecycle/release-images.d.ts +77 -3
  85. package/dist/lifecycle/release-images.d.ts.map +1 -1
  86. package/dist/lifecycle/release-images.js +132 -6
  87. package/dist/notify-product.d.ts +11 -2
  88. package/dist/notify-product.d.ts.map +1 -1
  89. package/dist/notify-product.js +16 -4
  90. package/dist/notify-relay-repo.d.ts +131 -0
  91. package/dist/notify-relay-repo.d.ts.map +1 -0
  92. package/dist/notify-relay-repo.js +202 -0
  93. package/dist/notify-relay.d.ts +25 -1
  94. package/dist/notify-relay.d.ts.map +1 -1
  95. package/dist/notify-relay.js +27 -2
  96. package/dist/notify.d.ts +36 -4
  97. package/dist/notify.d.ts.map +1 -1
  98. package/dist/notify.js +31 -21
  99. package/dist/notify.schema.json +1 -0
  100. package/dist/op/activities/review-product.d.ts +111 -0
  101. package/dist/op/activities/review-product.d.ts.map +1 -0
  102. package/dist/op/activities/review-product.js +116 -0
  103. package/dist/op/op-waves-capability.js +2 -2
  104. package/dist/policy-engine.d.ts +95 -0
  105. package/dist/policy-engine.d.ts.map +1 -0
  106. package/dist/policy-engine.js +157 -0
  107. package/dist/pr-forge-reads.d.ts +124 -0
  108. package/dist/pr-forge-reads.d.ts.map +1 -0
  109. package/dist/pr-forge-reads.js +322 -0
  110. package/dist/pr-forge.d.ts +14 -0
  111. package/dist/pr-forge.d.ts.map +1 -1
  112. package/dist/pr-forge.js +21 -13
  113. package/dist/pr-plan-note.d.ts +293 -0
  114. package/dist/pr-plan-note.d.ts.map +1 -0
  115. package/dist/pr-plan-note.js +362 -0
  116. package/dist/release-floors.d.ts +9 -1
  117. package/dist/release-floors.d.ts.map +1 -1
  118. package/dist/release-floors.js +9 -1
  119. package/dist/state-export.d.ts +126 -0
  120. package/dist/state-export.d.ts.map +1 -0
  121. package/dist/state-export.js +156 -0
  122. package/dist/state-migration.d.ts +148 -0
  123. package/dist/state-migration.d.ts.map +1 -0
  124. package/dist/state-migration.js +146 -0
  125. package/dist/state-unlock.d.ts +167 -0
  126. package/dist/state-unlock.d.ts.map +1 -0
  127. package/dist/state-unlock.js +196 -0
  128. package/dist/wave-runtime.mjs +332 -332
  129. package/dist/workspace/declaration.schema.json +1 -1
  130. package/dist/workspace/release-workflow.d.ts +10 -0
  131. package/dist/workspace/release-workflow.d.ts.map +1 -1
  132. package/dist/workspace/release-workflow.js +10 -4
  133. package/package.json +1 -1
  134. package/src/__fixtures__/agent-guard/plywood.ts +27 -0
  135. package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
  136. package/src/__fixtures__/gated-ledger.ts +58 -0
  137. package/src/__fixtures__/notify-messages/events.ts +23 -0
  138. package/src/__fixtures__/notify-messages/messages.json +50 -0
  139. package/src/__fixtures__/pr-loop/terragucci-plan.note.golden.md +53 -0
  140. package/src/__fixtures__/pr-loop/terragucci-plan.note.json +83 -0
  141. package/src/__fixtures__/product-words.ts +12 -0
  142. package/src/__fixtures__/review-agent/terragucci-review.json +94 -0
  143. package/src/__fixtures__/terragucci-notify.ts +170 -0
  144. package/src/action-pins.test.ts +12 -1
  145. package/src/action-pins.ts +11 -0
  146. package/src/agent-guard.test.ts +319 -0
  147. package/src/agent-guard.ts +547 -0
  148. package/src/ci-commit.test.ts +213 -2
  149. package/src/ci-commit.ts +258 -27
  150. package/src/ci-own-jobs.test.ts +108 -0
  151. package/src/ci-own-jobs.ts +252 -0
  152. package/src/ci-product-words.ts +35 -7
  153. package/src/ci-product.ts +81 -1
  154. package/src/cli/handlers/approve-cwd.test.ts +112 -0
  155. package/src/cli/handlers/approve.ts +22 -11
  156. package/src/cli/handlers/build-own-jobs.test.ts +80 -0
  157. package/src/cli/handlers/build-pr-loop-control.test.ts +87 -0
  158. package/src/cli/handlers/build-run-group.test.ts +59 -0
  159. package/src/cli/handlers/build.ts +83 -3
  160. package/src/cli/handlers/commit.ts +3 -0
  161. package/src/cli/handlers/notify-relay.ts +99 -17
  162. package/src/cli/handlers/pr.ts +3 -1
  163. package/src/cli/handlers/release.ts +20 -10
  164. package/src/cli/handlers/run-generate.ts +2 -1
  165. package/src/cli/main.ts +21 -1
  166. package/src/cli/parse-args.ts +45 -3
  167. package/src/cli/registry.ts +16 -0
  168. package/src/components/pr-env-components.test.ts +137 -0
  169. package/src/components/pr-env-components.ts +213 -0
  170. package/src/components/pr-policy.test.ts +41 -1
  171. package/src/components/pr-policy.ts +25 -1
  172. package/src/components/release-compile.test.ts +47 -0
  173. package/src/components/release-compile.ts +70 -13
  174. package/src/config.ts +23 -3
  175. package/src/gate-policy-bundle.test.ts +14 -0
  176. package/src/gate-policy.test.ts +7 -0
  177. package/src/gate-policy.ts +22 -7
  178. package/src/lexicon.ts +28 -1
  179. package/src/lifecycle/gated-op.ts +158 -0
  180. package/src/lifecycle/git.test.ts +92 -0
  181. package/src/lifecycle/git.ts +71 -2
  182. package/src/lifecycle/release-images-dockerfile.test.ts +221 -0
  183. package/src/lifecycle/release-images.ts +167 -8
  184. package/src/notify-message-words.test.ts +186 -0
  185. package/src/notify-product.ts +17 -4
  186. package/src/notify-relay-repo.test.ts +284 -0
  187. package/src/notify-relay-repo.ts +234 -0
  188. package/src/notify-relay.test.ts +12 -0
  189. package/src/notify-relay.ts +29 -3
  190. package/src/notify.schema.json +1 -0
  191. package/src/notify.ts +59 -19
  192. package/src/op/activities/review-product.test.ts +116 -0
  193. package/src/op/activities/review-product.ts +200 -0
  194. package/src/op/op-waves-capability.ts +2 -2
  195. package/src/op/schedule-overdue.test.ts +26 -0
  196. package/src/policy-engine.test.ts +162 -0
  197. package/src/policy-engine.ts +200 -0
  198. package/src/pr-forge-reads.test.ts +285 -0
  199. package/src/pr-forge-reads.ts +424 -0
  200. package/src/pr-forge.ts +30 -16
  201. package/src/pr-plan-note.test.ts +105 -0
  202. package/src/pr-plan-note.ts +521 -0
  203. package/src/release-floors.ts +13 -1
  204. package/src/state-export.test.ts +124 -0
  205. package/src/state-export.ts +227 -0
  206. package/src/state-migration.test.ts +133 -0
  207. package/src/state-migration.ts +236 -0
  208. package/src/state-unlock.test.ts +165 -0
  209. package/src/state-unlock.ts +293 -0
  210. package/src/workspace/declaration.schema.json +1 -1
  211. package/src/workspace/release-workflow.test.ts +34 -0
  212. package/src/workspace/release-workflow.ts +19 -4
@@ -0,0 +1,547 @@
1
+ /**
2
+ * The agent guard (#4770): a speed bump that keeps a coding agent in a
3
+ * checkout from running what applies, approves or overrides, so the change
4
+ * goes through a pull request and a person's approval. terragucci and
5
+ * plywood each had one; a product now passes its words and rules here.
6
+ *
7
+ * Two layers, both written by {@link installAgentGuard}:
8
+ *
9
+ * - a Claude Code PreToolUse hook on Bash: one Node script that reads the
10
+ * tool call on stdin and blocks (exit 2, Claude Code's block code) a
11
+ * command line that would run a refused command;
12
+ * - a wrapper per engine binary, for the agent's shell to put ahead of the
13
+ * real binary on PATH: it refuses the same commands and runs the next
14
+ * binary of that name on PATH for everything else.
15
+ *
16
+ * The rule lives once, in {@link makeGuard}. The script carries its source
17
+ * (`makeGuard.toString()`) and its config as JSON, and imports Node's modules
18
+ * only; {@link agentGuard} runs the same function in process, so a product's
19
+ * `guard check` and the hook give the same answers.
20
+ *
21
+ * Two installs: `local` writes the script and wrappers under the checkout's
22
+ * git directory, with absolute paths, and the hook into
23
+ * `.claude/settings.local.json`, listed in `.git/info/exclude`; `project`
24
+ * writes the script to `.claude/hooks/<product>-guard.mjs` and the hook into
25
+ * `.claude/settings.json` as `$CLAUDE_PROJECT_DIR/...`, meant to be
26
+ * committed, and the wrappers to `.<product>/agent-bin`.
27
+ *
28
+ * An agent that calls the real binary by its path, through a script, or with
29
+ * credentials of its own gets past it; the control is the credentials. Roots
30
+ * are written into the script, so the guard is written again after they
31
+ * change.
32
+ */
33
+ import { spawnSync } from "node:child_process";
34
+ import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
35
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
36
+
37
+ /** The first chant with the shared agent guard (#4770). Products feature-detect on it, or on `installAgentGuard`. */
38
+ export const AGENT_GUARD_FLOOR = "0.124.77";
39
+
40
+ /** What the guard refuses of one engine binary (tofu, pulumi, terragrunt). Flag names are written with their dashes. */
41
+ export interface AgentGuardEngine {
42
+ /** Subcommands refused: `apply`, `up`. */
43
+ refuse: string[];
44
+ /** A subcommand's second words refused: `{ state: ["rm", "mv"] }`. */
45
+ refuseSub?: Record<string, string[]>;
46
+ /** Flags refused with any subcommand, also as `--x=v`: `-auto-approve`. One or two dashes both match. */
47
+ refuseFlags?: string[];
48
+ /** Flags that take the next word as their value, skipped when finding the subcommand: `-C`, `--stack`. */
49
+ valuedFlags?: string[];
50
+ /** Flags whose value is the directory the command runs in, as `-x dir` or `-x=dir`: `-chdir`. One or two dashes both match. */
51
+ dirFlags?: string[];
52
+ /** Flags that run the command in every root under the directory: terragrunt's `--all`. */
53
+ allFlags?: string[];
54
+ /** Leading words dropped before the subcommand, the first match only; `all` as with `allFlags`: terragrunt's `run-all`, `stack run`, `run`. */
55
+ prefixes?: Array<{ words: string[]; all?: boolean }>;
56
+ }
57
+
58
+ /** The product's rules. */
59
+ export interface AgentGuardRules {
60
+ /** The engine binaries the guard wraps and checks, by name. */
61
+ engines: Record<string, AgentGuardEngine>;
62
+ /**
63
+ * The product's own commands refused anywhere inside the repo: each is the
64
+ * leading non-flag words (`["stage", "tf-apply"]`, `["approve"]`), and
65
+ * `flagValues` a flag with the value it is refused with, with any command
66
+ * (`["--mode", "apply"]`).
67
+ */
68
+ product?: { commands: string[][]; flagValues?: Array<[string, string]> };
69
+ /** The exit code a wrapper refuses with. Default 3. The hook always exits 2, Claude Code's block code. */
70
+ wrapperExit?: number;
71
+ }
72
+
73
+ /** The product's words. */
74
+ export interface AgentGuardWords {
75
+ /** The product's name and bin, as the agent types it: every refusal starts `<product> guard: `. */
76
+ product: string;
77
+ /** The refusal after that prefix, with `{what}` for the refused command (`tofu apply`) and `{where}` for {@link where}, or nothing. */
78
+ refusal: string;
79
+ /** With roots, what `{where}` becomes, with `{root}` for the root, relative to the repo. Default ` in {root}`. */
80
+ where?: string;
81
+ }
82
+
83
+ export interface AgentGuardSpec {
84
+ words: AgentGuardWords;
85
+ rules: AgentGuardRules;
86
+ }
87
+
88
+ /** What the script is given. `repo` or `repoFromScript` (a path from the script's directory) names the checkout. */
89
+ export interface AgentGuardConfig extends AgentGuardSpec {
90
+ repo?: string;
91
+ repoFromScript?: string;
92
+ /** Roots relative to the repo, where engine commands are refused; absent refuses them anywhere. */
93
+ roots?: string[];
94
+ }
95
+
96
+ /** A refusal: the binary, the refused command (`apply`, `state rm`, `-auto-approve`, `approve`), the root, and the message. */
97
+ export interface AgentGuardVerdict {
98
+ bin: string;
99
+ command: string;
100
+ what: string;
101
+ where?: string;
102
+ message: string;
103
+ }
104
+
105
+ /** The Node functions the rule uses, handed in so {@link makeGuard} stays self-contained. */
106
+ export interface AgentGuardDeps {
107
+ realpathSync: (p: string) => string;
108
+ resolve: (...p: string[]) => string;
109
+ basename: (p: string) => string;
110
+ join: (...p: string[]) => string;
111
+ relative: (from: string, to: string) => string;
112
+ sep: string;
113
+ home: string | undefined;
114
+ scriptDir?: string;
115
+ }
116
+
117
+ export interface AgentGuard {
118
+ /** The first refusal a shell command line earns, following `cd` from `cwd`. */
119
+ checkCommand(text: string, cwd: string): AgentGuardVerdict | undefined;
120
+ /** What one engine binary's command line would do that the guard refuses. */
121
+ verdict(bin: string, args: string[], cwd: string): AgentGuardVerdict | undefined;
122
+ /** What the product's own command line would do that the guard refuses, run in `cwd`. */
123
+ productVerdict(args: string[], cwd: string): AgentGuardVerdict | undefined;
124
+ repo: string;
125
+ }
126
+
127
+ /**
128
+ * The rule. It references nothing outside itself: the guard's script carries
129
+ * its source text, so keep it to its parameters and ES2020.
130
+ */
131
+ export function makeGuard(config: AgentGuardConfig, deps: AgentGuardDeps): AgentGuard {
132
+ const { realpathSync, resolve, basename, join, relative, sep } = deps;
133
+ const real = (p: string): string => {
134
+ try {
135
+ return realpathSync(p);
136
+ } catch {
137
+ return resolve(p);
138
+ }
139
+ };
140
+ const repo = real(config.repo !== undefined ? config.repo : resolve(deps.scriptDir || ".", config.repoFromScript || "."));
141
+ const roots = config.roots === undefined ? undefined : config.roots.map((r) => real(join(repo, r)));
142
+ const words = config.words;
143
+ const rules = config.rules;
144
+ const inside = (at: string, dir: string): boolean => at === dir || at.startsWith(dir === sep ? dir : dir + sep);
145
+ const bare = (f: string): string => f.replace(/^--?/, "");
146
+ const flagIs = (a: string, names: string[] | undefined): boolean => {
147
+ if (!names || !/^--?[^-]/.test(a)) return false;
148
+ const n = bare(a).replace(/=.*$/, "");
149
+ return names.some((f) => bare(f) === n);
150
+ };
151
+
152
+ const message = (what: string, where: string | undefined): string => {
153
+ const at = where === undefined ? "" : (words.where === undefined ? " in {root}" : words.where).split("{root}").join(where);
154
+ return words.product + " guard: " + words.refusal.split("{what}").join(what).split("{where}").join(at);
155
+ };
156
+
157
+ function verdict(bin: string, args: string[], cwd: string): AgentGuardVerdict | undefined {
158
+ const e = rules.engines[bin];
159
+ if (!e) return undefined;
160
+ let dir = cwd;
161
+ let all = false;
162
+ let refusedFlag: string | undefined;
163
+ const ws: string[] = [];
164
+ for (let i = 0; i < args.length; i++) {
165
+ const a = args[i];
166
+ if (flagIs(a, e.dirFlags)) {
167
+ const eq = a.indexOf("=");
168
+ if (eq >= 0) dir = resolve(cwd, a.slice(eq + 1));
169
+ else if (i + 1 < args.length) dir = resolve(cwd, args[++i]);
170
+ } else if (e.allFlags && e.allFlags.indexOf(a) >= 0) all = true;
171
+ else if (flagIs(a, e.refuseFlags)) refusedFlag = refusedFlag || a.replace(/=.*$/, "");
172
+ else if (e.valuedFlags && e.valuedFlags.indexOf(a) >= 0) i++;
173
+ else if (a !== "--" && !a.startsWith("-")) ws.push(a);
174
+ }
175
+ for (const p of e.prefixes || []) {
176
+ if (p.words.every((w, i) => ws[i] === w)) {
177
+ ws.splice(0, p.words.length);
178
+ if (p.all) all = true;
179
+ break;
180
+ }
181
+ }
182
+ const cmd = ws[0];
183
+ const sub = cmd !== undefined && e.refuseSub && Object.prototype.hasOwnProperty.call(e.refuseSub, cmd) ? e.refuseSub[cmd] : undefined;
184
+ const command = cmd !== undefined && e.refuse.indexOf(cmd) >= 0 ? cmd : sub && ws[1] !== undefined && sub.indexOf(ws[1]) >= 0 ? cmd + " " + ws[1] : refusedFlag;
185
+ if (command === undefined) return undefined;
186
+ let where: string | undefined;
187
+ if (roots !== undefined) {
188
+ const at = real(dir);
189
+ const hit = roots.find((r) => r === at || (all && inside(r, at)));
190
+ if (!hit) return undefined;
191
+ where = relative(repo, hit) || ".";
192
+ }
193
+ const what = bin + " " + command;
194
+ return { bin, command, what, ...(where === undefined ? {} : { where }), message: message(what, where) };
195
+ }
196
+
197
+ function productVerdict(args: string[], cwd: string): AgentGuardVerdict | undefined {
198
+ const p = rules.product;
199
+ if (!p || !inside(real(cwd), repo)) return undefined;
200
+ const ws = args.filter((a) => !a.startsWith("-"));
201
+ const bin = words.product;
202
+ const found = (command: string): AgentGuardVerdict => ({ bin, command, what: bin + " " + command, message: message(bin + " " + command, undefined) });
203
+ for (const c of p.commands) if (c.every((w, i) => ws[i] === w)) return found(c.join(" "));
204
+ for (const [flag, value] of p.flagValues || []) {
205
+ const i = args.findIndex((a) => a === flag || a.startsWith(flag + "="));
206
+ if (i >= 0 && (args[i] === flag + "=" + value || (args[i] === flag && args[i + 1] === value))) return found(((ws[0] === undefined ? "" : ws[0] + " ") + flag + " " + value).trim());
207
+ }
208
+ return undefined;
209
+ }
210
+
211
+ type Token = { word?: string; op?: string };
212
+ /** A shell command line's words and operators, quotes taken off. Enough for a guard, not a shell. */
213
+ function lex(text: string): Token[] {
214
+ const out: Token[] = [];
215
+ let cur: string | null = null;
216
+ const end = (): void => {
217
+ if (cur !== null) out.push({ word: cur });
218
+ cur = null;
219
+ };
220
+ for (let i = 0; i < text.length; i++) {
221
+ const c = text[i];
222
+ if (c === "'") {
223
+ const j = text.indexOf("'", i + 1);
224
+ cur = (cur === null ? "" : cur) + (j < 0 ? text.slice(i + 1) : text.slice(i + 1, j));
225
+ i = j < 0 ? text.length : j;
226
+ } else if (c === '"') {
227
+ let s = "";
228
+ for (i++; i < text.length && text[i] !== '"'; i++) {
229
+ if (text[i] === "\\" && i + 1 < text.length) i++;
230
+ s += text[i];
231
+ }
232
+ cur = (cur === null ? "" : cur) + s;
233
+ } else if (c === "\\" && i + 1 < text.length) cur = (cur === null ? "" : cur) + text[++i];
234
+ else if (c === "$" && text[i + 1] === "(") {
235
+ end();
236
+ out.push({ op: "$(" });
237
+ i++;
238
+ } else if (";&|\n()`".indexOf(c) >= 0) {
239
+ end();
240
+ out.push({ op: c });
241
+ } else if (/\s/.test(c)) end();
242
+ else cur = (cur === null ? "" : cur) + c;
243
+ }
244
+ end();
245
+ return out;
246
+ }
247
+
248
+ /** Words that run the words after them as the command, with their flags that take a value. */
249
+ const LAUNCHERS: Record<string, string[]> = {
250
+ command: [],
251
+ builtin: [],
252
+ exec: ["-a"],
253
+ env: ["-u", "--unset", "-C", "--chdir", "-S", "--split-string"],
254
+ sudo: ["-u", "-g", "-h", "-p", "-C", "-D", "-r", "-t", "-U"],
255
+ doas: ["-u", "-C"],
256
+ time: ["-f", "-o", "--format", "--output"],
257
+ nohup: [],
258
+ nice: ["-n", "--adjustment"],
259
+ xargs: ["-a", "-d", "-E", "-e", "-I", "-i", "-L", "-l", "-n", "-P", "-s", "--arg-file", "--delimiter", "--max-args", "--max-procs"],
260
+ };
261
+ const SHELLS = ["sh", "bash", "zsh", "dash", "ksh"];
262
+ const RUNNERS = ["npx", "bunx", "pnpx"];
263
+ const RUNNER_VALUED = ["-p", "--package", "-c", "--call"];
264
+
265
+ function checkCommand(text: string, cwd: string, depth = 0): AgentGuardVerdict | undefined {
266
+ if (depth > 3) return undefined;
267
+ let dir = cwd;
268
+ const segments: string[][] = [[]];
269
+ for (const t of lex(text)) {
270
+ if (t.op) segments.push([]);
271
+ else segments[segments.length - 1].push(t.word as string);
272
+ }
273
+ for (let seg of segments) {
274
+ for (;;) {
275
+ if (seg.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(seg[0])) seg = seg.slice(1);
276
+ else if (seg.length && Object.prototype.hasOwnProperty.call(LAUNCHERS, basename(seg[0]))) {
277
+ const valued = LAUNCHERS[basename(seg[0])];
278
+ seg = seg.slice(1);
279
+ while (seg.length && seg[0].startsWith("-") && seg[0] !== "-") {
280
+ if (seg[0] === "--") {
281
+ seg = seg.slice(1);
282
+ break;
283
+ }
284
+ seg = seg.slice(valued.indexOf(seg[0]) >= 0 ? 2 : 1);
285
+ }
286
+ } else break;
287
+ }
288
+ if (!seg.length) continue;
289
+ const head = basename(seg[0]);
290
+ if (head === "cd") {
291
+ const home = deps.home === undefined ? dir : deps.home;
292
+ const to = seg[1] === undefined || seg[1] === "~" ? home : seg[1].startsWith("~/") ? join(home, seg[1].slice(2)) : seg[1];
293
+ if (to !== "-") dir = resolve(dir, to);
294
+ continue;
295
+ }
296
+ if (SHELLS.indexOf(head) >= 0) {
297
+ const c = seg.findIndex((a, i) => i > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(a));
298
+ if (c >= 0 && seg[c + 1] !== undefined) {
299
+ const v = checkCommand(seg[c + 1], dir, depth + 1);
300
+ if (v) return v;
301
+ }
302
+ continue;
303
+ }
304
+ if (head === "eval") {
305
+ const v = checkCommand(seg.slice(1).join(" "), dir, depth + 1);
306
+ if (v) return v;
307
+ continue;
308
+ }
309
+ let rest = seg;
310
+ if (RUNNERS.indexOf(head) >= 0) {
311
+ rest = rest.slice(1);
312
+ while (rest.length && rest[0].startsWith("-")) rest = rest.slice(RUNNER_VALUED.indexOf(rest[0]) >= 0 ? 2 : 1);
313
+ if (!rest.length) continue;
314
+ }
315
+ // npx names a package as @scope/name, with a version after an @.
316
+ const name = basename(rest[0]).replace(/@.*$/, "");
317
+ const v = Object.prototype.hasOwnProperty.call(rules.engines, name) ? verdict(name, rest.slice(1), dir) : name === words.product ? productVerdict(rest.slice(1), dir) : undefined;
318
+ if (v) return v;
319
+ }
320
+ return undefined;
321
+ }
322
+
323
+ return { checkCommand: (text, cwd) => checkCommand(text, cwd), verdict, productVerdict, repo };
324
+ }
325
+
326
+ /** The guard in process, for a product's `guard check`: the rule the hook runs. */
327
+ export function agentGuard(spec: AgentGuardSpec, at: { repo: string; roots?: string[] }): AgentGuard {
328
+ return makeGuard({ ...spec, repo: at.repo, ...(at.roots ? { roots: at.roots } : {}) }, nodeDeps());
329
+ }
330
+
331
+ function nodeDeps(scriptDir?: string): AgentGuardDeps {
332
+ return { realpathSync, resolve, basename, join, relative, sep, home: process.env.HOME, ...(scriptDir ? { scriptDir } : {}) };
333
+ }
334
+
335
+ /** The guard's script: {@link makeGuard}'s source, the config, and the hook and wrapper entry points. */
336
+ export function agentGuardScript(config: AgentGuardConfig): string {
337
+ const p = JSON.stringify(config.words.product);
338
+ return `// Written by ${config.words.product} guard. Run it again after the pipeline's roots change.
339
+ import { spawnSync } from "node:child_process";
340
+ import { accessSync, constants, realpathSync, statSync } from "node:fs";
341
+ import { basename, delimiter, dirname, join, relative, resolve, sep } from "node:path";
342
+ import { fileURLToPath } from "node:url";
343
+
344
+ const CONFIG = ${JSON.stringify(config)};
345
+ const PRODUCT = ${p};
346
+ // esbuild with keepNames (tsx) wraps the function's inner functions in __name.
347
+ const __name = (f) => f;
348
+ ${makeGuard.toString()}
349
+ const guard = makeGuard(CONFIG, { realpathSync, resolve, basename, join, relative, sep, home: process.env.HOME, scriptDir: dirname(fileURLToPath(import.meta.url)) });
350
+ export const checkCommand = guard.checkCommand;
351
+ export const verdict = guard.verdict;
352
+
353
+ const real = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };
354
+
355
+ /** The next binary of this name on PATH, past the wrappers' own directory. */
356
+ function realBinary(bin, self) {
357
+ const skip = real(self);
358
+ for (const d of (process.env.PATH ?? "").split(delimiter)) {
359
+ if (!d || real(d) === skip) continue;
360
+ const p = join(d, bin);
361
+ try {
362
+ accessSync(p, constants.X_OK);
363
+ if (statSync(p).isFile()) return p;
364
+ } catch {}
365
+ }
366
+ return undefined;
367
+ }
368
+
369
+ if (process.argv[1] && real(process.argv[1]) === real(fileURLToPath(import.meta.url))) {
370
+ const [mode, ...rest] = process.argv.slice(2);
371
+ if (mode === "wrap") {
372
+ const [bin, self, ...args] = rest;
373
+ const v = verdict(bin, args, process.cwd());
374
+ if (v) {
375
+ process.stderr.write(v.message + "\\n");
376
+ process.exit(${config.rules.wrapperExit ?? 3});
377
+ }
378
+ const exe = realBinary(bin, self);
379
+ if (!exe) {
380
+ process.stderr.write(PRODUCT + " guard: no " + bin + " on PATH besides the guard's own\\n");
381
+ process.exit(127);
382
+ }
383
+ for (const s of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(s, () => {});
384
+ const r = spawnSync(exe, args, { stdio: "inherit" });
385
+ if (r.error) {
386
+ process.stderr.write(PRODUCT + " guard: " + r.error.message + "\\n");
387
+ process.exit(127);
388
+ }
389
+ if (r.signal) {
390
+ process.removeAllListeners(r.signal);
391
+ process.kill(process.pid, r.signal);
392
+ }
393
+ process.exit(r.status ?? 1);
394
+ } else if (mode === "hook" || mode === undefined) {
395
+ let input = "";
396
+ for await (const chunk of process.stdin) input += chunk;
397
+ let event;
398
+ try { event = JSON.parse(input); } catch { process.exit(0); }
399
+ const command = event?.tool_input?.command;
400
+ if (typeof command !== "string") process.exit(0);
401
+ const v = checkCommand(command, typeof event.cwd === "string" && event.cwd ? event.cwd : process.cwd());
402
+ if (v) {
403
+ process.stderr.write(v.message + "\\n");
404
+ process.exit(2);
405
+ }
406
+ process.exit(0);
407
+ }
408
+ }
409
+ `;
410
+ }
411
+
412
+ const shq = (s: string): string => `'${s.split("'").join(`'\\''`)}'`;
413
+
414
+ /** A wrapper on PATH: the guard's script for one binary. `node` absolute (with `node` on PATH as the fallback) or undefined for `node`; `script` absolute, or relative to the wrapper's directory. */
415
+ export function agentGuardWrapper(product: string, bin: string, script: string, node?: string): string {
416
+ const at = isAbsolute(script) ? shq(script) : `"$here/"${shq(script)}`;
417
+ return `#!/bin/sh
418
+ # Written by ${product} guard: refuses what the guard refuses of ${bin}, and runs the next ${bin} on PATH for the rest.
419
+ here=$(cd "$(dirname "$0")" && pwd)
420
+ NODE=${node ? shq(node) : "node"}
421
+ ${node ? `[ -x "$NODE" ] || NODE=node\n` : ""}exec "$NODE" ${at} wrap ${bin} "$here" "$@"
422
+ `;
423
+ }
424
+
425
+ /** Claude Code's settings files: the shared one, and the local one it keeps out of commits. */
426
+ export const CLAUDE_SETTINGS_SHARED = ".claude/settings.json";
427
+ export const CLAUDE_SETTINGS_LOCAL = ".claude/settings.local.json";
428
+
429
+ /**
430
+ * A Claude Code settings file's text with the guard's PreToolUse hook on
431
+ * Bash, in place of an earlier one (an entry naming `command` or any of
432
+ * `markers`). Everything else in the file is kept. Throws when the file is
433
+ * not a JSON object.
434
+ */
435
+ export function withAgentGuardHook(text: string | undefined, command: string, at: string, markers: readonly string[] = [], fail: (message: string) => Error = (m) => new Error(m)): string {
436
+ let doc: Record<string, unknown> = {};
437
+ if (text !== undefined && text.trim() !== "") {
438
+ let parsed: unknown;
439
+ try {
440
+ parsed = JSON.parse(text);
441
+ } catch (e) {
442
+ throw fail(`${at} is not JSON (${(e as Error).message}); fix it, then write the guard again`);
443
+ }
444
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw fail(`${at} is not a JSON object`);
445
+ doc = parsed as Record<string, unknown>;
446
+ }
447
+ const hooks = (doc.hooks && typeof doc.hooks === "object" && !Array.isArray(doc.hooks) ? doc.hooks : {}) as Record<string, unknown>;
448
+ const pre = Array.isArray(hooks.PreToolUse) ? (hooks.PreToolUse as unknown[]) : [];
449
+ const needles = [JSON.stringify(command).slice(1, -1), ...markers.map((m) => JSON.stringify(m).slice(1, -1))];
450
+ const kept = pre.filter((e) => !needles.some((n) => JSON.stringify(e).includes(n)));
451
+ doc.hooks = { ...hooks, PreToolUse: [...kept, { matcher: "Bash", hooks: [{ type: "command", command }] }] };
452
+ return `${JSON.stringify(doc, null, 2)}\n`;
453
+ }
454
+
455
+ export interface AgentGuardInstallOptions extends AgentGuardSpec {
456
+ /** The checkout's top directory. */
457
+ repo: string;
458
+ /** `local` (under the git directory, kept out of commits) or `project` (in `.claude/`, to commit). */
459
+ install: "local" | "project";
460
+ /** Roots relative to the repo where engine commands are refused; absent refuses them anywhere. */
461
+ roots?: string[];
462
+ /** `local` only: where to write the script and `bin/`, in place of `<git-dir>/<product>/guard`. */
463
+ dir?: string;
464
+ /** `local` only: the Node the wrappers and the hook run. Default: this one. `project` runs `node`. */
465
+ node?: string;
466
+ /** Leave Claude Code's settings alone. */
467
+ noHook?: boolean;
468
+ /** The error the product throws for a broken settings file or a missing git checkout. */
469
+ fail?: (message: string) => Error;
470
+ }
471
+
472
+ export interface AgentGuardInstall {
473
+ /** The script, the wrappers' directory, absolute. */
474
+ script: string;
475
+ bin: string;
476
+ /** The settings file the hook went into, when it did. */
477
+ hook?: string;
478
+ /** The hook's command as Claude Code runs it. */
479
+ hookCommand: string;
480
+ /** The files written, relative to the repo when inside it. */
481
+ written: string[];
482
+ /** The line the agent's shell runs to put the wrappers ahead of the binaries. */
483
+ path: string;
484
+ }
485
+
486
+ /** Write the guard: the script, a wrapper per engine, and the hook. */
487
+ export function installAgentGuard(o: AgentGuardInstallOptions): AgentGuardInstall {
488
+ const fail = o.fail ?? ((m: string) => new Error(m));
489
+ const product = o.words.product;
490
+ const repo = resolve(o.repo);
491
+ const git = (args: string[]): string => {
492
+ const r = spawnSync("git", ["-C", repo, ...args], { encoding: "utf-8" });
493
+ if (r.status !== 0) throw fail(`${product} guard runs in a git checkout (git ${args.join(" ")}: ${(r.stderr || "").trim()})`);
494
+ return r.stdout.trim();
495
+ };
496
+ const spec: AgentGuardSpec = { words: o.words, rules: o.rules };
497
+ const roots = o.roots ? { roots: o.roots } : {};
498
+ const shown = (p: string): string => (p.startsWith(repo + sep) ? relative(repo, p) : p);
499
+ const written: string[] = [];
500
+ const put = (p: string, text: string, mode?: number): void => {
501
+ mkdirSync(dirname(p), { recursive: true });
502
+ writeFileSync(p, text);
503
+ if (mode !== undefined) chmodSync(p, mode);
504
+ written.push(shown(p));
505
+ };
506
+
507
+ let script: string;
508
+ let bin: string;
509
+ let settings: string;
510
+ let hookCommand: string;
511
+ let markers: string[];
512
+ if (o.install === "local") {
513
+ const dir = o.dir ? resolve(repo, o.dir) : join(git(["rev-parse", "--absolute-git-dir"]), product, "guard");
514
+ const node = o.node ?? process.execPath;
515
+ script = join(dir, "guard.mjs");
516
+ bin = join(dir, "bin");
517
+ put(script, agentGuardScript({ ...spec, repo, ...roots }));
518
+ for (const b of Object.keys(o.rules.engines)) put(join(bin, b), agentGuardWrapper(product, b, script, node), 0o755);
519
+ settings = CLAUDE_SETTINGS_LOCAL;
520
+ hookCommand = `"${node}" "${script}" hook`;
521
+ markers = [`${product}/guard/guard.mjs`];
522
+ } else {
523
+ const rel = `.claude/hooks/${product}-guard.mjs`;
524
+ script = join(repo, rel);
525
+ bin = join(repo, `.${product}`, "agent-bin");
526
+ put(script, agentGuardScript({ ...spec, repoFromScript: "../..", ...roots }));
527
+ for (const b of Object.keys(o.rules.engines)) put(join(bin, b), agentGuardWrapper(product, b, relative(bin, script)), 0o755);
528
+ settings = CLAUDE_SETTINGS_SHARED;
529
+ hookCommand = `node "$CLAUDE_PROJECT_DIR/${rel}" hook`;
530
+ markers = [`${product}-guard.mjs`];
531
+ }
532
+
533
+ let hook: string | undefined;
534
+ if (!o.noHook) {
535
+ hook = join(repo, settings);
536
+ put(hook, withAgentGuardHook(existsSync(hook) ? readFileSync(hook, "utf-8") : undefined, hookCommand, settings, markers, fail));
537
+ // The local hook names paths on this machine: keep the file out of commits unless git already ignores it.
538
+ if (o.install === "local" && spawnSync("git", ["-C", repo, "check-ignore", "-q", settings]).status !== 0) {
539
+ const common = git(["rev-parse", "--git-common-dir"]);
540
+ const exclude = join(isAbsolute(common) ? common : resolve(repo, common), "info", "exclude");
541
+ mkdirSync(dirname(exclude), { recursive: true });
542
+ const now = existsSync(exclude) ? readFileSync(exclude, "utf-8") : "";
543
+ writeFileSync(exclude, `${now}${now === "" || now.endsWith("\n") ? "" : "\n"}/${settings}\n`);
544
+ }
545
+ }
546
+ return { script, bin, ...(hook ? { hook } : {}), hookCommand, written, path: `export PATH="${bin}:$PATH"` };
547
+ }