rungate 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/hooks/ActionVerificationGate.hook.ts +96 -0
  2. package/hooks/AgentBriefGuard.hook.ts +38 -0
  3. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  4. package/hooks/AutoVerifyGate.hook.ts +79 -0
  5. package/hooks/BashToolGuard.hook.ts +65 -0
  6. package/hooks/BashWriteGuard.hook.ts +60 -0
  7. package/hooks/CommitEnforcement.hook.ts +130 -0
  8. package/hooks/DocHygiene.hook.ts +148 -0
  9. package/hooks/GateEnforcement.hook.ts +58 -0
  10. package/hooks/GateResultProtection.hook.ts +69 -0
  11. package/hooks/HarnessAFKGate.hook.ts +85 -0
  12. package/hooks/HookCurrency.hook.ts +99 -0
  13. package/hooks/IssueCloseGuard.hook.ts +149 -0
  14. package/hooks/MergeGuard.hook.ts +58 -0
  15. package/hooks/PostCompact.hook.ts +60 -0
  16. package/hooks/ProjectStateSync.hook.ts +103 -0
  17. package/hooks/SkillGuard.hook.ts +69 -0
  18. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  19. package/hooks/SpecSCGuard.hook.ts +123 -0
  20. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  21. package/hooks/TaskCompleted.hook.ts +51 -0
  22. package/hooks/TeamInit.hook.ts +85 -0
  23. package/hooks/TestSuiteGuard.hook.ts +70 -0
  24. package/hooks/TestSuiteRelease.hook.ts +85 -0
  25. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  26. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  27. package/hooks/WorkflowStateGuard.hook.ts +40 -0
  28. package/hooks/lib/agent-config.json +9 -0
  29. package/hooks/lib/agentDetection.ts +201 -0
  30. package/hooks/lib/comment-template.ts +86 -0
  31. package/hooks/lib/findWorkflow.ts +101 -0
  32. package/hooks/lib/parseStdin.ts +37 -0
  33. package/hooks/lib/paths.ts +111 -0
  34. package/hooks/lib/utils.ts +338 -0
  35. package/lib/affected-tests.ts +427 -0
  36. package/lib/agent-audit.ts +2 -3
  37. package/lib/agent-worktree.ts +287 -0
  38. package/lib/agents-md-sections.ts +81 -16
  39. package/lib/bash-write-guard.ts +373 -0
  40. package/lib/behavioral-cache.ts +150 -2
  41. package/lib/branch-cleanup.ts +279 -7
  42. package/lib/branch-protection.ts +790 -0
  43. package/lib/brief-ac-alignment.ts +104 -0
  44. package/lib/brief-references.ts +205 -0
  45. package/lib/bun-version.ts +93 -14
  46. package/lib/check-remedy.ts +140 -0
  47. package/lib/ci-checkout.ts +17 -0
  48. package/lib/ci-history-depth.ts +159 -0
  49. package/lib/ci-setup-step.ts +96 -0
  50. package/lib/claude-code-action.ts +85 -0
  51. package/lib/claude-tool-vocabulary.ts +188 -0
  52. package/lib/cli-commands.ts +15 -0
  53. package/lib/commit-sha.ts +42 -0
  54. package/lib/commit-subject.ts +90 -0
  55. package/lib/compliance-report.ts +377 -45
  56. package/lib/compliance.ts +191 -17
  57. package/lib/config-loader.ts +39 -1
  58. package/lib/config-trackable.ts +400 -0
  59. package/lib/conformity.ts +1087 -100
  60. package/lib/containment.ts +238 -0
  61. package/lib/content-hash.ts +24 -0
  62. package/lib/create-sc.ts +249 -16
  63. package/lib/dev-liveness.ts +180 -0
  64. package/lib/discovery-branch-points.ts +432 -0
  65. package/lib/discovery-stability.ts +481 -0
  66. package/lib/distribution-currency.ts +236 -0
  67. package/lib/doc-routing.ts +157 -0
  68. package/lib/evidence-prevalidator.ts +224 -2
  69. package/lib/evidence-satisfiability.ts +534 -12
  70. package/lib/failure-intake.ts +323 -0
  71. package/lib/fallow-availability.ts +157 -0
  72. package/lib/fs-write-capabilities.ts +232 -0
  73. package/lib/gate-enforcement.ts +222 -28
  74. package/lib/gate-names.ts +72 -0
  75. package/lib/gate-result-protection.ts +427 -0
  76. package/lib/gate-run-split.ts +147 -0
  77. package/lib/generators/agents-md.ts +140 -32
  78. package/lib/git-isolation.ts +140 -0
  79. package/lib/github.ts +15 -0
  80. package/lib/google-auth-action.ts +93 -0
  81. package/lib/harness-project.ts +48 -0
  82. package/lib/harness-provenance.ts +255 -0
  83. package/lib/hook-evidence.ts +235 -0
  84. package/lib/hook-scopes.ts +386 -0
  85. package/lib/hook-target-tree.ts +398 -0
  86. package/lib/hook-trees.ts +447 -0
  87. package/lib/intake-sources.ts +380 -0
  88. package/lib/js-top-level-code.ts +78 -10
  89. package/lib/junit-checks.ts +52 -0
  90. package/lib/late-env-spawn.ts +331 -0
  91. package/lib/launch-base.ts +376 -0
  92. package/lib/line-citation.ts +372 -0
  93. package/lib/orphan-reaper.ts +468 -0
  94. package/lib/parity-binding.ts +205 -0
  95. package/lib/paths.ts +96 -3
  96. package/lib/per-test-timeouts.ts +219 -0
  97. package/lib/phase2-decomposition.ts +1 -1
  98. package/lib/plan-coverage.ts +151 -0
  99. package/lib/prior-branch.ts +201 -8
  100. package/lib/process-table.ts +146 -0
  101. package/lib/project-state-derivation.ts +219 -0
  102. package/lib/project-state-root.ts +258 -0
  103. package/lib/published-artifact.ts +669 -0
  104. package/lib/readdir-sorted.ts +45 -0
  105. package/lib/review-execution-reading.ts +206 -0
  106. package/lib/review-tool-agreement.ts +433 -0
  107. package/lib/rule-promotion.ts +234 -0
  108. package/lib/rule-retirement.ts +525 -0
  109. package/lib/run-branch.ts +612 -0
  110. package/lib/rungate-schema.ts +19 -0
  111. package/lib/runner-home.ts +274 -0
  112. package/lib/sc-id-cross-tree.ts +103 -15
  113. package/lib/sc-ids.ts +121 -13
  114. package/lib/sc-reservations.ts +289 -0
  115. package/lib/scaffold/ai-review-findings.ts +409 -0
  116. package/lib/scaffold/ai-review-step.ts +5406 -64
  117. package/lib/scaffold/defaults.ts +82 -1
  118. package/lib/scaffold/managed-workflow.ts +587 -192
  119. package/lib/scaffold/owned-files.ts +152 -45
  120. package/lib/scaffold/pre-push-hook.ts +49 -5
  121. package/lib/scaffold/steps.ts +1836 -275
  122. package/lib/scaffold/workflow-census.ts +217 -0
  123. package/lib/scaffold/workflow-drift.ts +217 -0
  124. package/lib/scaffold/write-steps.ts +4 -0
  125. package/lib/scan-budget.ts +247 -0
  126. package/lib/scanner.ts +43 -51
  127. package/lib/scratch-roots.ts +50 -5
  128. package/lib/screenshot-discovery.ts +121 -0
  129. package/lib/screenshot-upload.ts +41 -1
  130. package/lib/secret-patterns.ts +511 -8
  131. package/lib/security-verdict.ts +1 -1
  132. package/lib/shell-path-interpolation.ts +594 -0
  133. package/lib/ship-mode.ts +219 -0
  134. package/lib/source-slice.ts +294 -0
  135. package/lib/stale-cleanup.ts +37 -3
  136. package/lib/suite-flake.ts +278 -0
  137. package/lib/suite-measurement.ts +23 -4
  138. package/lib/suite-run-reading.ts +241 -1
  139. package/lib/suite-timeout-margin.ts +193 -0
  140. package/lib/test-case-bodies.ts +883 -0
  141. package/lib/test-case-deletion.ts +653 -0
  142. package/lib/test-census.ts +97 -29
  143. package/lib/test-command-positions.ts +274 -0
  144. package/lib/test-suite-lock.ts +159 -16
  145. package/lib/text-dependents.ts +875 -0
  146. package/lib/tool-probe.ts +31 -9
  147. package/lib/top-level-cd.ts +393 -0
  148. package/lib/tree-entries.ts +89 -0
  149. package/lib/ts-ast.ts +200 -0
  150. package/lib/walk-test-files.ts +97 -0
  151. package/lib/workflow-actions.ts +263 -0
  152. package/lib/workflow-security.ts +29 -0
  153. package/lib/workflow-taint.ts +732 -0
  154. package/lib/worktree-cleanup.ts +65 -38
  155. package/lib/worktree-collect.ts +177 -5
  156. package/lib/worktree-repo.ts +68 -3
  157. package/package.json +4 -1
  158. package/scripts/ai-review-findings.ts +45 -0
  159. package/scripts/check-installed-hook-currency.ts +825 -0
  160. package/scripts/create-sc.ts +21 -1
  161. package/scripts/extract-constraints.ts +107 -7
  162. package/scripts/generate-code-map.ts +23 -30
  163. package/scripts/scaffold-project.ts +8 -1
  164. package/scripts/sync-sc-status.ts +77 -16
@@ -0,0 +1,732 @@
1
+ /**
2
+ * Which values in a `workflows/*.js` prompt builder came out of an agent, and
3
+ * which of those reach a template literal without passing a sanitiser (#1103).
4
+ *
5
+ * ## Why this module exists rather than a list
6
+ *
7
+ * #1100 shipped a census holding "bare interpolations of agent-derived
8
+ * bindings" at zero. It held zero, and three agent-derived branch bindings
9
+ * were bare at the time it was written. The population was a hand-written
10
+ * array of six names, enumerated by the same work that quoted the six — so it
11
+ * contained exactly the sites that had been fixed. **A census whose membership
12
+ * is written down by the fix cannot fail on the day it ships: it measures the
13
+ * fix, not the property.** Its positive control caught a RENAME leaving the
14
+ * sweep scanning for an absent symbol; nothing caught an OMISSION, and
15
+ * omission is what happened.
16
+ *
17
+ * So membership is computed here. The caller may still say a derived name is
18
+ * safe, but it has to say so about a name this module produced, which means a
19
+ * new binding appears as an unclassified name rather than as silence.
20
+ *
21
+ * ## The derivation, and where it is deliberately imprecise
22
+ *
23
+ * Three steps, each a fixpoint:
24
+ *
25
+ * 1. **Spawners.** `agent` and `parallel` are the only injected globals that
26
+ * run an agent — that is `lib/workflow-test-harness.ts`'s list, not a guess,
27
+ * and the harness is what these files actually run against. Any function in
28
+ * the file whose body calls a spawner is itself a spawner, which picks up
29
+ * `timedAgent`, `briefedAgent`, `runImplement` and the rest without naming
30
+ * them. Naming the wrappers is the omission trap again, one level up.
31
+ *
32
+ * 2. **Seeds, at any scope.** A binding initialised from a spawner call holds
33
+ * agent text. Block scope matters here and the first draft of this analysis
34
+ * got it wrong: `priorBranchResult` is a top-level `let` whose agent value
35
+ * arrives from `priorResult`, a `const` inside an `if` block. Restricting
36
+ * the scan to top-level declarations missed the one binding #1103 was filed
37
+ * about.
38
+ *
39
+ * 3. **Members, at top level only.** A top-level binding whose assignment
40
+ * mentions a seed, or another member, is a member. Top-level because those
41
+ * are the bindings prompts interpolate; widening to every scope taints loop
42
+ * variables and then, within two hops, `WORK_DIR`. Measured: 200 names and
43
+ * 490 sites, against 39 and 107 — an over-approximation that large is not a
44
+ * stricter check, it is an unreadable one.
45
+ *
46
+ * The result over-approximates on purpose. `projectConfig` is read back
47
+ * through an agent, so everything derived from it is a member even though the
48
+ * values originate in `rungate.json`. That is the right direction to be wrong
49
+ * in: a name that does not belong costs one line of classification, a name
50
+ * that is missing costs what #1103 cost.
51
+ *
52
+ * ## Why an AST
53
+ *
54
+ * The same argument `lib/ts-ast.ts` makes. The regex this replaces skipped any
55
+ * line matching `/^\s*(\/\/|\*|\/\*)/` as "a comment" — and inside a template
56
+ * literal, a line starting `*` or `//` is CONTENT. Several of these prompts
57
+ * are markdown-ish and full of bullet lines. It also read `${commitDir}` and
58
+ * not `${ commitDir }` or `${commitDir.path}`. In a tree a comment is absent
59
+ * entirely, a prompt's bullet is a quasi, and all three spellings are one
60
+ * `Identifier` inside one `TemplateLiteral` expression.
61
+ */
62
+
63
+ import { parse } from "acorn";
64
+
65
+ /**
66
+ * The injected globals that run an agent.
67
+ *
68
+ * From `lib/workflow-test-harness.ts`, which stubs exactly these to run a
69
+ * workflow with no agents. If the runtime grows a third, the harness has to
70
+ * stub it or every test of it hangs — so that file failing loudly is what
71
+ * keeps this list honest, rather than this list being audited.
72
+ */
73
+ export const AGENT_SPAWNING_GLOBALS: readonly string[] = ["agent", "parallel"];
74
+
75
+ /**
76
+ * Calls that make a value safe to interpolate.
77
+ *
78
+ * `shellQuote` single-quotes for a shell. `heredocSafe` makes a value safe
79
+ * inside the heredoc it is given the delimiter for. Both are named rather than
80
+ * pattern-matched: a function is a sanitiser because someone decided it is,
81
+ * and adding one here is the decision, visible in a diff.
82
+ */
83
+ export const SANITISERS: readonly string[] = ["shellQuote"];
84
+
85
+ /**
86
+ * Calls whose arguments reach the run's own output and never a shell.
87
+ *
88
+ * Checked as an enclosing CALL, not as a word to the left on the same line.
89
+ * The regex this replaces did the latter, which exempted every line of a
90
+ * multi-line literal after the one holding `log(` — and failed to exempt the
91
+ * first line of a `log()` whose template began on the next.
92
+ */
93
+ export const MESSAGE_CALLEES: readonly string[] = [
94
+ "log",
95
+ "refuse",
96
+ "terminalFailure",
97
+ "shipFailed",
98
+ "warn",
99
+ "Error",
100
+ ];
101
+
102
+ const PARSE_OPTIONS = {
103
+ ecmaVersion: "latest",
104
+ sourceType: "module",
105
+ // Workflows are executed as the body of an async function (#69), so they
106
+ // legitimately carry top-level `return` and `await`.
107
+ allowReturnOutsideFunction: true,
108
+ allowAwaitOutsideFunction: true,
109
+ allowHashBang: true,
110
+ } as const;
111
+
112
+ type Node = { type: string; start: number; end: number; [key: string]: unknown };
113
+
114
+ function isNode(value: unknown): value is Node {
115
+ return (
116
+ typeof value === "object" &&
117
+ value !== null &&
118
+ typeof (value as Node).type === "string" &&
119
+ typeof (value as Node).start === "number"
120
+ );
121
+ }
122
+
123
+ function* walk(node: Node): Generator<Node> {
124
+ yield node;
125
+ for (const value of Object.values(node)) {
126
+ if (Array.isArray(value)) {
127
+ for (const child of value) if (isNode(child)) yield* walk(child);
128
+ } else if (isNode(value)) {
129
+ yield* walk(value);
130
+ }
131
+ }
132
+ }
133
+
134
+ /** `a.b.c()` and `a()` both root at `a`; anything else has no name. */
135
+ function calleeName(node: unknown): string | null {
136
+ if (!isNode(node)) return null;
137
+ if (node.type === "Identifier") return node.name as string;
138
+ if (node.type === "MemberExpression") return calleeName(node.object);
139
+ return null;
140
+ }
141
+
142
+ /**
143
+ * Every name a binding target introduces.
144
+ *
145
+ * Destructuring counts (#1113). `const { branch } = await agent(…)` binds
146
+ * `branch` to agent text as surely as `const r = await agent(…)` binds `r`,
147
+ * and a reader of `bindings()` that only emitted for `Identifier` saw neither
148
+ * the name nor the hole where it should have been — a checker's silence,
149
+ * which is the thing this module exists to stop. Nested patterns, array
150
+ * patterns, defaults and rest elements all reach the same place.
151
+ */
152
+ function boundNames(target: Node): string[] {
153
+ if (target.type === "Identifier") return [target.name as string];
154
+ const names: string[] = [];
155
+ for (const node of walk(target)) {
156
+ if (node.type === "Property" && isNode(node.value)) names.push(...boundNames(node.value));
157
+ if (node.type === "RestElement" && isNode(node.argument)) names.push(...boundNames(node.argument));
158
+ if (node.type === "AssignmentPattern" && isNode(node.left)) names.push(...boundNames(node.left));
159
+ if (node.type === "ArrayPattern") {
160
+ for (const el of node.elements as (Node | null)[]) if (el && isNode(el)) names.push(...boundNames(el));
161
+ }
162
+ }
163
+ // A property VALUE that is a plain Identifier is the bound name; the KEY is
164
+ // not, and `walk` reaches both, so the dedupe is not cosmetic.
165
+ return [...new Set(names)];
166
+ }
167
+
168
+ /** Every `<name> = <expression>` in the tree, declaration or assignment. */
169
+ function bindings(tree: Node): { name: string; rhs: Node; topLevel: boolean }[] {
170
+ const top = new Set<string>();
171
+ for (const stmt of tree.body as Node[]) {
172
+ if (stmt.type !== "VariableDeclaration") continue;
173
+ for (const dec of stmt.declarations as Node[]) {
174
+ if (isNode(dec.id)) for (const name of boundNames(dec.id)) top.add(name);
175
+ }
176
+ }
177
+ const out: { name: string; rhs: Node; topLevel: boolean }[] = [];
178
+ for (const node of walk(tree)) {
179
+ if (node.type === "VariableDeclarator" && isNode(node.id) && isNode(node.init)) {
180
+ for (const name of boundNames(node.id)) out.push({ name, rhs: node.init, topLevel: top.has(name) });
181
+ }
182
+ if (node.type === "AssignmentExpression" && isNode(node.left) && isNode(node.right)) {
183
+ for (const name of boundNames(node.left)) out.push({ name, rhs: node.right, topLevel: top.has(name) });
184
+ }
185
+ }
186
+ return out;
187
+ }
188
+
189
+ /** A name that holds agent text, and the byte range over which it does. */
190
+ interface TaintScope {
191
+ name: string;
192
+ why: string;
193
+ from: number;
194
+ to: number;
195
+ /**
196
+ * Byte spans inside `[from, to]` where the name means something else.
197
+ *
198
+ * A byte span is not a lexical scope. An inner function that re-binds the
199
+ * name sits INSIDE the outer span, so without this it inherits the outer
200
+ * verdict instead of shadowing it — and for an alias that means an inner
201
+ * `quote` which is a plain string formatter is read as a sanitiser
202
+ * everywhere the outer function's body reaches. Fail-open, and invisible.
203
+ */
204
+ holes?: [number, number][];
205
+ }
206
+
207
+ /** Is `at` inside the scope, and not inside one of its shadowed holes? */
208
+ function covers(scope: TaintScope, at: number): boolean {
209
+ if (at < scope.from || at > scope.to) return false;
210
+ return !(scope.holes ?? []).some(([from, to]) => at >= from && at <= to);
211
+ }
212
+
213
+ /**
214
+ * Spans inside `fn` where `name` is re-bound and therefore is not `fn`'s.
215
+ *
216
+ * Nested parameters, nested `var`/`let`/`const`, and nested function
217
+ * declarations all shadow. The function's own node is skipped, or every
218
+ * parameter would shadow itself.
219
+ */
220
+ function shadowsOf(fn: Node, name: string): [number, number][] {
221
+ const holes: [number, number][] = [];
222
+ for (const node of walk(fn)) {
223
+ if (node === fn) continue;
224
+ const isFn =
225
+ node.type === "FunctionDeclaration" ||
226
+ node.type === "FunctionExpression" ||
227
+ node.type === "ArrowFunctionExpression";
228
+ if (isFn) {
229
+ if (paramNames(node).includes(name)) holes.push([node.start, node.end]);
230
+ if (isNode(node.id) && node.id.name === name) holes.push([node.start, node.end]);
231
+ continue;
232
+ }
233
+ if (node.type === "VariableDeclarator" && isNode(node.id) && boundNames(node.id).includes(name)) {
234
+ // From the declarator to the end of the function: a `const` rebinding
235
+ // the name governs the rest of its block, and the block's end is the
236
+ // nearest cheap over-approximation that stays FAIL-CLOSED.
237
+ holes.push([node.start, fn.end]);
238
+ }
239
+ }
240
+ return holes;
241
+ }
242
+
243
+ /**
244
+ * Names in `fns` whose identifier is used anywhere other than as a callee.
245
+ *
246
+ * If a function's identifier is assigned, passed as an argument, returned or
247
+ * stored, then `callsByFunction` cannot see every call site — and unanimity
248
+ * over the subset you can see is not unanimity. The honest answer is to
249
+ * decline to grant that function's parameters any alias at all, so this list
250
+ * is consulted to FAIL CLOSED rather than to widen anything.
251
+ */
252
+ function escapedFunctions(tree: Node, fns: Map<string, Node>): Set<string> {
253
+ const referencedAsCallee = new Set<Node>();
254
+ const declarationIds = new Set<Node>();
255
+ const notAReference = new Set<Node>();
256
+
257
+ for (const node of walk(tree)) {
258
+ if (node.type === "CallExpression" && isNode(node.callee) && node.callee.type === "Identifier") {
259
+ referencedAsCallee.add(node.callee);
260
+ }
261
+ if (isNode(node.id) && node.id.type === "Identifier") declarationIds.add(node.id);
262
+ // `a.foo` and `{ foo: … }` mention the name without referring to the
263
+ // binding, unless the lookup is computed.
264
+ if (node.type === "MemberExpression" && !node.computed && isNode(node.property)) {
265
+ notAReference.add(node.property);
266
+ }
267
+ if (node.type === "Property" && !node.computed && isNode(node.key)) notAReference.add(node.key);
268
+ }
269
+
270
+ const escaped = new Set<string>();
271
+ for (const node of walk(tree)) {
272
+ if (node.type !== "Identifier" || !fns.has(node.name as string)) continue;
273
+ if (referencedAsCallee.has(node) || declarationIds.has(node) || notAReference.has(node)) continue;
274
+ escaped.add(node.name as string);
275
+ }
276
+ return escaped;
277
+ }
278
+
279
+ /** Parameter names of a function node, in order; non-Identifier params are null. */
280
+ function paramNames(fn: Node): (string | null)[] {
281
+ return (fn.params as Node[]).map(p => (p.type === "Identifier" ? (p.name as string) : null));
282
+ }
283
+
284
+ /** Functions declared in the file, by name, including `const f = () => …`. */
285
+ function functionsByName(tree: Node): Map<string, Node> {
286
+ const fns = new Map<string, Node>();
287
+ for (const node of walk(tree)) {
288
+ if (node.type === "FunctionDeclaration" && isNode(node.id)) fns.set(node.id.name as string, node);
289
+ if (
290
+ node.type === "VariableDeclarator" &&
291
+ isNode(node.id) &&
292
+ node.id.type === "Identifier" &&
293
+ isNode(node.init) &&
294
+ (node.init.type === "ArrowFunctionExpression" || node.init.type === "FunctionExpression")
295
+ ) {
296
+ fns.set(node.id.name as string, node.init);
297
+ }
298
+ }
299
+ return fns;
300
+ }
301
+
302
+ export interface TaintedName {
303
+ /** The binding. */
304
+ name: string;
305
+ /** How it came to hold agent text — the sentence a reader needs. */
306
+ from: string;
307
+ }
308
+
309
+ /**
310
+ * The whole analysis: which names hold agent text, and over what byte range.
311
+ *
312
+ * A range rather than a flat set because a helper's parameter is agent-derived
313
+ * inside that helper and means nothing outside it. The top-level bindings get
314
+ * the whole file.
315
+ */
316
+ function analyse(source: string): { members: Map<string, string>; scopes: TaintScope[]; aliasScopes: TaintScope[]; seeds: Set<string> } {
317
+ const tree = parse(source, PARSE_OPTIONS) as unknown as Node;
318
+ const fns = functionsByName(tree);
319
+ const all = bindings(tree);
320
+
321
+ const spawners = new Set<string>(AGENT_SPAWNING_GLOBALS);
322
+ for (let again = true; again; ) {
323
+ again = false;
324
+ for (const [name, fn] of fns) {
325
+ if (spawners.has(name)) continue;
326
+ for (const node of walk(fn)) {
327
+ if (node.type === "CallExpression" && spawners.has(calleeName(node.callee) ?? "")) {
328
+ spawners.add(name);
329
+ again = true;
330
+ break;
331
+ }
332
+ }
333
+ }
334
+ }
335
+
336
+ const seeds = new Set<string>();
337
+ for (const { name, rhs } of all) {
338
+ for (const node of walk(rhs)) {
339
+ if (node.type === "CallExpression" && spawners.has(calleeName(node.callee) ?? "")) {
340
+ seeds.add(name);
341
+ break;
342
+ }
343
+ }
344
+ }
345
+
346
+ // A binding whose every assignment is a sanitiser call is sanitised, and
347
+ // the name carries that forward. Without this, `const safeProofComment =
348
+ // heredocSafe(proofComment, DELIM)` is a member and every use of it has to
349
+ // be classified by hand — which is asking a reader to re-derive something
350
+ // the call already said. Every assignment, not the first: a name sanitised
351
+ // on one branch and not on another is not sanitised.
352
+ const sanitised = new Set<string>();
353
+ for (const { name } of all) {
354
+ const assignments = all.filter(a => a.name === name);
355
+ const allSanitised = assignments.every(
356
+ a => a.rhs.type === "CallExpression" && SANITISERS.includes(calleeName(a.rhs.callee) ?? ""),
357
+ );
358
+ if (allSanitised) sanitised.add(name);
359
+ }
360
+
361
+ const members = new Map<string, string>();
362
+ const scopes: TaintScope[] = [];
363
+ const whole = { from: 0, to: source.length };
364
+
365
+ /** Is `name` agent-derived at this position? */
366
+ const taintedAt = (name: string, at: number) =>
367
+ scopes.some(s => s.name === name && at >= s.from && at <= s.to);
368
+
369
+ const addScope = (scope: TaintScope) => {
370
+ if (scopes.some(s => s.name === scope.name && s.from === scope.from && s.to === scope.to)) {
371
+ return false;
372
+ }
373
+ scopes.push(scope);
374
+ return true;
375
+ };
376
+
377
+ for (const { name, topLevel } of all) {
378
+ if (topLevel && seeds.has(name) && !sanitised.has(name)) {
379
+ members.set(name, "an agent call");
380
+ addScope({ name, why: "an agent call", ...whole });
381
+ }
382
+ }
383
+
384
+ // Where a helper's parameter is, so argument taint can be given a range.
385
+ const fnRanges = new Map<string, Node>(fns);
386
+
387
+ // ── The quoter travels as an argument, so the alias is a sanitiser too ──
388
+ //
389
+ // `suiteCaptureCommand(projectRoot, testCommand, workDir, shellQuote)` with
390
+ // `function suiteCaptureCommand(projectRoot, testCommand, workDir, quote)`
391
+ // is this repo's idiom for a helper that must quote without importing
392
+ // (#69). Inside that helper the sanitiser is called `quote`, and a check
393
+ // that only knows the name `shellQuote` reads every one of its correctly
394
+ // quoted sites as bare — the mirror image of the rename this all started
395
+ // with, and it would bury the real findings in noise.
396
+ // ── "inside that function" is the load-bearing clause (#1114) ──
397
+ //
398
+ // The first version of this held a flat `Set<string>` of parameter NAMES,
399
+ // so the moment any function anywhere bound `shellQuote` to a parameter
400
+ // called `quote`, the name `quote` was a sanitiser in all four files — and
401
+ // an unrelated helper with its own `quote` parameter, bound to anything at
402
+ // all, got a free pass on every interpolation while the census reported
403
+ // clean. Latent rather than live when it was found (three functions take a
404
+ // `quote`, all seven call sites pass the real one), which is exactly the
405
+ // kind of hole that becomes live on somebody else's unrelated commit.
406
+ //
407
+ // So an alias is a RANGE, like every other fact in this module, and it is
408
+ // UNANIMOUS: a function called twice, once with `shellQuote` and once with
409
+ // something else, sanitises on neither. That is the rule `sanitised` above
410
+ // already uses for assignments — "every assignment, not the first" — and
411
+ // the asymmetry between them was the second half of the bug.
412
+ //
413
+ // The transitive arm stays but is a fixpoint rather than a single pass:
414
+ // whether an alias reached a further parameter used to depend on where the
415
+ // call sites happened to sit in `walk` order, so the same tree could
416
+ // analyse two ways.
417
+ const aliasScopes: TaintScope[] = [];
418
+ const isAliasAt = (name: string, at: number) =>
419
+ aliasScopes.some(a => a.name === name && covers(a, at));
420
+ /** `shellQuote`, or a parameter that is one AT THIS POSITION. */
421
+ const sanitisesAt = (name: string | null, at: number) =>
422
+ !!name && (SANITISERS.includes(name) || isAliasAt(name, at));
423
+
424
+ // Only an identifier in callee position is a call this analysis can see, and
425
+ // only a function whose identifier never escapes has a call set it can
426
+ // enumerate. Both halves fail closed.
427
+ const escaped = escapedFunctions(tree, fnRanges);
428
+ const callsByFunction = new Map<string, Node[]>();
429
+ for (const node of walk(tree)) {
430
+ if (node.type !== "CallExpression") continue;
431
+ if (!isNode(node.callee) || node.callee.type !== "Identifier") continue;
432
+ const name = node.callee.name as string;
433
+ if (!fnRanges.has(name)) continue;
434
+ callsByFunction.set(name, [...(callsByFunction.get(name) ?? []), node]);
435
+ }
436
+
437
+ for (let again = true; again; ) {
438
+ again = false;
439
+ for (const [fnName, fn] of fnRanges) {
440
+ // Unanimity over a call set you cannot enumerate is not unanimity.
441
+ if (escaped.has(fnName)) continue;
442
+ const calls = callsByFunction.get(fnName) ?? [];
443
+ // A function nobody calls tells us nothing about its parameters.
444
+ if (calls.length === 0) continue;
445
+ paramNames(fn).forEach((param, i) => {
446
+ if (!param) return;
447
+ // Exact range, not `isAliasAt`: a nested parameter of the same name
448
+ // lands inside this one's span, and an `isAliasAt` guard would skip
449
+ // evaluating it on its OWN call sites and let it inherit this
450
+ // verdict. Only an identical span is the same fact already recorded.
451
+ if (aliasScopes.some(a => a.name === param && a.from === fn.start && a.to === fn.end)) return;
452
+ const everyCallSite = calls.every(call => {
453
+ const arg = (call.arguments as Node[])[i];
454
+ // A call site that omits the argument is a call site that does not
455
+ // pass the quoter.
456
+ return !!arg && arg.type === "Identifier" && sanitisesAt(arg.name as string, arg.start);
457
+ });
458
+ if (!everyCallSite) return;
459
+ aliasScopes.push({
460
+ name: param,
461
+ why: `${fnName}()'s quoter`,
462
+ from: fn.start,
463
+ to: fn.end,
464
+ holes: shadowsOf(fn, param),
465
+ });
466
+ again = true;
467
+ });
468
+ }
469
+ }
470
+
471
+ for (let again = true; again; ) {
472
+ again = false;
473
+
474
+ // Top-level bindings, as before.
475
+ for (const { name, rhs, topLevel } of all) {
476
+ if (!topLevel || members.has(name) || sanitised.has(name)) continue;
477
+ for (const node of walk(rhs)) {
478
+ if (node.type !== "Identifier") continue;
479
+ const ref = node.name as string;
480
+ const why = seeds.has(ref) ? `${ref}, an agent reply` : taintedAt(ref, node.start) ? ref : null;
481
+ if (!why) continue;
482
+ members.set(name, why);
483
+ addScope({ name, why, ...whole });
484
+ again = true;
485
+ break;
486
+ }
487
+ }
488
+
489
+ // ── The rename, and why a source-side list could not survive it (#1103) ──
490
+ //
491
+ // `workflowProbeCommand(commitDir)` with `function workflowProbeCommand(dir)`
492
+ // puts an agent-derived path into a shell string under a name no list has
493
+ // ever heard of, and nobody forgot anything: the value crossed a function
494
+ // boundary and changed its name, which is what function boundaries are for.
495
+ //
496
+ // So taint crosses with it. A member passed as an argument taints the
497
+ // parameter it binds to, over that function's body and no further.
498
+ // Sanitisers and message calls are excluded — `shellQuote(commitDir)`
499
+ // taints nothing, which is the whole point of calling it, and a parameter
500
+ // the call site bound to `shellQuote` counts as one (`quote` in
501
+ // `suiteCaptureCommand(…, shellQuote)`).
502
+ //
503
+ // ONE hop, from a top-level member only, and that is a measured choice
504
+ // rather than a simplification. Counted on this tree:
505
+ //
506
+ // members only, no parameters 38 names / 106 sites
507
+ // + one hop from a member ← this 54 names / 137 sites
508
+ // + locals inside those helpers 88 names / 200 sites
509
+ // + transitive parameter-to-parameter 149 names / 343 sites
510
+ //
511
+ // The last two are almost entirely refusal-sentence builders. They are
512
+ // not a stricter check at that size, they are a list nobody reads, and a
513
+ // classification nobody reads is the failure this whole file is about.
514
+ //
515
+ // **The hole this leaves, stated rather than hidden:** a local declared
516
+ // INSIDE a helper and derived from a tainted parameter is not followed —
517
+ // `function f(dir) { const d = `${dir}/x`; return `cmd ${d}` }` reports
518
+ // the `${dir}`, not the `${d}`. The first interpolation is still caught,
519
+ // so the helper cannot go dark; a helper that only ever uses the derived
520
+ // copy can.
521
+ for (const node of walk(tree)) {
522
+ if (node.type !== "CallExpression") continue;
523
+ const callee = calleeName(node.callee);
524
+ if (!callee || sanitisesAt(callee, node.start) || MESSAGE_CALLEES.includes(callee)) continue;
525
+ const fn = fnRanges.get(callee);
526
+ if (!fn) continue;
527
+ const params = paramNames(fn);
528
+ (node.arguments as Node[]).forEach((arg, i) => {
529
+ const param = params[i];
530
+ if (!param) return;
531
+ // `helper(shellQuote(commitDir))` passes a quoted value, so the
532
+ // parameter is not agent text. Without this, every helper that takes
533
+ // an already-quoted path — which is the shape #1112 adds — would be
534
+ // reported, and the fix for it would be to UNQUOTE the call site.
535
+ let tainted = false;
536
+ for (const sub of walk(arg)) {
537
+ if (sub.type === "CallExpression" && sanitisesAt(calleeName(sub.callee), sub.start)) continue;
538
+ if (sub.type === "Identifier" && members.has(sub.name as string)) {
539
+ const insideSanitiser = [...walk(arg)].some(
540
+ c =>
541
+ c.type === "CallExpression" &&
542
+ sanitisesAt(calleeName(c.callee), c.start) &&
543
+ sub.start >= c.start &&
544
+ sub.end <= c.end,
545
+ );
546
+ if (insideSanitiser) continue;
547
+ tainted = true;
548
+ break;
549
+ }
550
+ }
551
+ if (!tainted) return;
552
+ if (addScope({ name: param, why: `${callee}()'s argument ${i + 1}`, from: fn.start, to: fn.end })) {
553
+ again = true;
554
+ }
555
+ });
556
+ }
557
+
558
+ }
559
+
560
+ return { members, scopes, aliasScopes, seeds };
561
+ }
562
+
563
+ /**
564
+ * Top-level bindings in one workflow file that can hold text an agent wrote.
565
+ *
566
+ * The named half of the analysis, kept as its own export because the floor
567
+ * assertion in the test reads it: a derivation that stopped matching would
568
+ * otherwise report a clean tree rather than an empty one.
569
+ */
570
+ export function agentDerivedNames(source: string): Map<string, string> {
571
+ return analyse(source).members;
572
+ }
573
+
574
+ export interface BareInterpolation {
575
+ /** `workflows/ship.js:7170`. */
576
+ where: string;
577
+ /** The binding this expression reads. */
578
+ name: string;
579
+ /** The interpolated expression, as written. */
580
+ expression: string;
581
+ }
582
+
583
+ /**
584
+ * Every `${…}` in a template literal that reads an agent-derived binding and
585
+ * is neither sanitised nor inside a message call.
586
+ *
587
+ * Prompt PROSE counts, deliberately. "This line is only prose" is a judgement
588
+ * a checker cannot make, a prompt line is one edit away from being a command,
589
+ * and `git -C '/path' <subcommand>` is better advice to an agent anyway.
590
+ */
591
+ export function bareAgentInterpolations(relPath: string, source: string): BareInterpolation[] {
592
+ const tree = parse(source, PARSE_OPTIONS) as unknown as Node;
593
+ const { scopes, aliasScopes, seeds } = analyse(source);
594
+ /**
595
+ * `shellQuote(x)`, or a helper parameter that is the quoter AT THIS
596
+ * POSITION — a name, a function, and a byte range, never a bare name
597
+ * (#1114).
598
+ */
599
+ const sanitisedCall = (expr: Node) => {
600
+ // Identifier callee only. `calleeName` roots `x.quote(…)` at `quote`, so
601
+ // going through it accepted a METHOD that merely shares a name with the
602
+ // quoter — and it is the same rule the message exemption below already
603
+ // applies, so this is a consistency fix as much as a security one.
604
+ if (!isNode(expr.callee) || expr.callee.type !== "Identifier") return false;
605
+ const callee = expr.callee.name as string;
606
+ if (SANITISERS.includes(callee)) return true;
607
+ return aliasScopes.some(a => a.name === callee && covers(a, expr.start));
608
+ };
609
+ const taintedAt = (name: string, at: number) =>
610
+ scopes.some(s => s.name === name && at >= s.from && at <= s.to);
611
+
612
+ /**
613
+ * Identifiers in `expr` that are NOT inside a sanitiser call.
614
+ *
615
+ * `${probe(shellQuote(commitDir))}` is not a bare interpolation of
616
+ * `commitDir`: the only thing reaching the string is what `shellQuote`
617
+ * returned. Checking only the outermost call missed this, and the cheapest
618
+ * way to silence the resulting report would have been to unquote the call
619
+ * site — a check that pays for green with the defect it exists to find.
620
+ */
621
+ const unsanitisedIdentifiers = (expr: Node): Node[] => {
622
+ const safeRanges: [number, number][] = [];
623
+ for (const sub of walk(expr)) {
624
+ if (sub.type !== "CallExpression" || !sanitisedCall(sub)) continue;
625
+ // The ARGUMENTS the quoter consumes, not the whole call expression.
626
+ // `shellQuote` returns a quoted copy of what it is given; an identifier
627
+ // somewhere else in the same expression — a computed callee, say — is
628
+ // not something it ever saw, and whitelisting the entire span
629
+ // suppressed it anyway.
630
+ for (const arg of sub.arguments as Node[]) if (isNode(arg)) safeRanges.push([arg.start, arg.end]);
631
+ }
632
+ return [...walk(expr)].filter(
633
+ sub =>
634
+ sub.type === "Identifier" &&
635
+ !safeRanges.some(([from, to]) => sub.start >= from && sub.end <= to),
636
+ );
637
+ };
638
+
639
+ // ── The message exemption is an ARGUMENT, not a byte range (#1113) ──
640
+ //
641
+ // `log(\`… ${f(\`git -C ${dir} x\`)} …\`)` has a command inside it, and a
642
+ // range test exempts the lot because the inner literal sits between the
643
+ // outer call's first and last byte. Only the literals the call receives
644
+ // DIRECTLY are messages. `callee.type === "Identifier"` as well, so
645
+ // `log.foo(…)` and `logger.warn(…)` are not this exemption — `calleeName`
646
+ // walks a member chain to its root on purpose, and that is the wrong
647
+ // question here.
648
+ const messageLiterals = new Set<Node>();
649
+ const messageConcats = new Set<Node>();
650
+ for (const node of walk(tree)) {
651
+ if (node.type !== "CallExpression" && node.type !== "NewExpression") continue;
652
+ if (!isNode(node.callee) || node.callee.type !== "Identifier") continue;
653
+ if (!MESSAGE_CALLEES.includes(node.callee.name as string)) continue;
654
+ for (const arg of node.arguments as Node[]) {
655
+ if (arg.type === "TemplateLiteral") messageLiterals.add(arg);
656
+ // `log('a: ' + \`b ${x}\`)` is still one message.
657
+ if (arg.type === "BinaryExpression") {
658
+ messageConcats.add(arg);
659
+ for (const sub of walk(arg)) {
660
+ if (sub.type === "TemplateLiteral") messageLiterals.add(sub);
661
+ if (sub.type === "BinaryExpression") messageConcats.add(sub);
662
+ }
663
+ }
664
+ }
665
+ }
666
+
667
+ const found: BareInterpolation[] = [];
668
+ const record = (at: number, name: string, expr: Node) => {
669
+ const where = `${relPath}:${source.slice(0, at).split("\n").length}`;
670
+ if (found.some(f => f.where === where && f.name === name)) return;
671
+ found.push({
672
+ where,
673
+ name,
674
+ expression: source.slice(expr.start, expr.end).replace(/\s+/g, " ").slice(0, 80),
675
+ });
676
+ };
677
+
678
+ // ── A template literal is not the only way to build a string (#1113) ──
679
+ //
680
+ // `'git -C ' + workDir + ' status'` reaches the same shell and was
681
+ // invisible, which is a sink SHAPE the scanner could not see rather than a
682
+ // value it decided was safe — the same class of silence as the comment
683
+ // regex and the destructuring. Measured at 18 sites and 7 names on this
684
+ // tree, every one of them a name the template scan already reports, so it
685
+ // costs no new classifications and closes the shape.
686
+ //
687
+ // A string literal has to be in the expression: `a + b` on two numbers is
688
+ // arithmetic, and `${count + 1}` is not a command.
689
+ for (const node of walk(tree)) {
690
+ if (node.type !== "BinaryExpression" || node.operator !== "+") continue;
691
+ if (messageConcats.has(node)) continue;
692
+ let hasStringLiteral = false;
693
+ const names = new Set<string>();
694
+ for (const sub of walk(node)) {
695
+ if (sub.type === "Literal" && typeof sub.value === "string") hasStringLiteral = true;
696
+ }
697
+ for (const sub of unsanitisedIdentifiers(node)) {
698
+ const ref = sub.name as string;
699
+ if (seeds.has(ref) || taintedAt(ref, sub.start)) names.add(ref);
700
+ }
701
+ if (!hasStringLiteral) continue;
702
+ for (const name of names) record(node.start, name, node);
703
+ }
704
+
705
+ for (const node of walk(tree)) {
706
+ if (node.type !== "TemplateLiteral") continue;
707
+ if (messageLiterals.has(node)) continue;
708
+ for (const expr of node.expressions as Node[]) {
709
+ if (expr.type === "CallExpression" && sanitisedCall(expr)) continue;
710
+ const names = new Set<string>();
711
+ for (const sub of unsanitisedIdentifiers(expr)) {
712
+ const ref = sub.name as string;
713
+ // A SEED is reported wherever it is interpolated, whatever its scope.
714
+ // Members are top-level only — measured, and the 200/490 count that
715
+ // justifies that restriction is about PROPAGATION, which is a
716
+ // different question from whether to report a value that came
717
+ // straight out of an agent call (#1113).
718
+ if (seeds.has(ref) || taintedAt(ref, sub.start)) names.add(ref);
719
+ }
720
+ if (names.size === 0) continue;
721
+ const line = source.slice(0, expr.start).split("\n").length;
722
+ for (const name of names) {
723
+ found.push({
724
+ where: `${relPath}:${line}`,
725
+ name,
726
+ expression: source.slice(expr.start, expr.end).replace(/\s+/g, " ").slice(0, 80),
727
+ });
728
+ }
729
+ }
730
+ }
731
+ return found;
732
+ }