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,594 @@
1
+ /**
2
+ * shell-path-interpolation.ts — the decision behind the quoting half of the
3
+ * `cd` rewrite (#1086)
4
+ *
5
+ * One question: does this source line hand a shell a DIRECTORY it built by
6
+ * interpolation, without quoting it?
7
+ *
8
+ * ## What actually breaks, stated as the thing it is
9
+ *
10
+ * Not injection. Every value that reaches these positions in this repo's
11
+ * workflows is a CLI argument or something derived from a repo slug and an
12
+ * issue NUMBER — `PROJECT_ROOT`, `HARNESS_ROOT`, `WORK_DIR`, `commitDir`,
13
+ * `marcusWorktreePath`. No issue title and no agent-reported text reaches
14
+ * them, and #1086 traced each one to its origin before filing.
15
+ *
16
+ * What breaks is a consumer who checks out into `/Users/x/My Projects/thing`.
17
+ * The prompt renders
18
+ *
19
+ * git -C /Users/x/My Projects/thing status
20
+ *
21
+ * and git reads `-C /Users/x/My` with two stray arguments after it. The
22
+ * agent told to run that command gets an error naming a directory nobody
23
+ * typed. `test/workflow-prompt-top-level-cd.test.ts` runs exactly that
24
+ * against a real shell and a real git rather than asserting it here.
25
+ *
26
+ * ## Why #1077 made the count go UP, and why that was still the right fix
27
+ *
28
+ * #1056 replaced `cd <dir> && git …` with `git -C <dir> …` throughout the
29
+ * workflow prompts. The old form interpolated the path bare and so does the
30
+ * new one, so a rewrite that fixed the `cd` carried the unquoted path to
31
+ * every site it touched. The directory was always unquoted; #1077 only made
32
+ * there be more places where it is.
33
+ *
34
+ * ## The reason this is a module and not a grep
35
+ *
36
+ * `workflows/ship.js` already defines `shellQuote` and already calls it 65
37
+ * times. A reader who greps the file finds those 65 and concludes the file
38
+ * handles quoting. Partial application reads as full application, which is
39
+ * why the 64 sites measured on `91386f0f` survived every review of the file
40
+ * they are in. A decider makes the unquoted ones enumerable instead of
41
+ * inferable.
42
+ *
43
+ * ## The direction this is allowed to be wrong in
44
+ *
45
+ * Toward REFUSAL, same as `lib/top-level-cd.ts`. A false refusal costs one
46
+ * `shellQuote(…)`; a false allow costs a consumer a pipeline that fails in a
47
+ * prompt they cannot edit.
48
+ *
49
+ * So `grep -C ${n}` (context lines, not a directory) would be refused if it
50
+ * ever appeared with an interpolated count, and `-C` is matched without
51
+ * asking which program precedes it.
52
+ *
53
+ * ## Double quotes are REFUSED, and that is the point of the exercise
54
+ *
55
+ * `git -C "${PROJECT_ROOT}"` survives a space and is still refused here. It
56
+ * is the cheapest wrong fix for #1086: it answers the failure that was filed
57
+ * and leaves `$(…)` and backticks expanding inside the quotes. That is not
58
+ * hypothetical in this file — `gitDerivedStaging` in `workflows/ship.js`
59
+ * carries a comment about a security review that caught exactly this shape,
60
+ * where a `worktreePath` of `/tmp/$(touch pwned)` executed inside a
61
+ * double-quoted echo while the `git` command beside it was safe.
62
+ *
63
+ * Single quotes are the only shell quoting with no interior expansion at
64
+ * all, which is why `shellQuote` emits them and why nothing else is accepted.
65
+ *
66
+ * ## KNOWN GAPS — declared, not discovered later
67
+ *
68
+ * - **Only flag-position and `cd`-position arguments are examined.** A path
69
+ * interpolated somewhere a human reads as a path but a parser cannot —
70
+ * `mkdir -p ${WORK_DIR}`, `> ${WORK_DIR}/issue.json`, prose naming a
71
+ * directory — is NOT refused. Widening to every `${…}` on a command line
72
+ * would refuse most of the prompt text in these files, which is English.
73
+ * - **The quoter is recognised by NAME.** `QUOTER_NAMES` below is a fixed
74
+ * list, so a future `q` that is not a quoter would be accepted. Two of the
75
+ * three spellings exist because the block they live in is extracted by
76
+ * marker and executed standalone by its own test, so it cannot reference
77
+ * anything outside itself; new code should use `shellQuote`.
78
+ * - **A quoted value reaching the site through a variable** is accepted via
79
+ * `launderedQuoterSites`, which resolves the name against the scope chain
80
+ * at the use. This used to be a file-wide name scan, and a later
81
+ * `const d = somethingElse()` in another function laundered the name —
82
+ * closed in #1106, with the measurement in that function's docblock.
83
+ * What remains is narrower: the resolver trusts `acorn`'s parse, so a name
84
+ * introduced by something it models as a binding and a human does not —
85
+ * or the reverse — is resolved acorn's way, not the shell's.
86
+ *
87
+ * Issue: #1086. Related: #1056 (the `cd` rewrite), #992 (the guard it serves).
88
+ */
89
+
90
+ import { parse } from "acorn";
91
+
92
+ import { stripJsComments } from "./strip-js-comments";
93
+
94
+ /**
95
+ * Argument positions that name a DIRECTORY on every command this repo's
96
+ * workflow prompts use.
97
+ *
98
+ * This is the same ladder `lib/top-level-cd.ts` tells callers to climb when
99
+ * it refuses their `cd` — `git -C`, `bun --cwd`, `npm --prefix`, and a
100
+ * `--project` flag. Refusing a `cd` into one of these and then interpolating
101
+ * the path bare is the half-done rewrite #1086 is about, so the two lists
102
+ * being the same list is deliberate.
103
+ */
104
+ export const PATH_FLAGS = ["-C", "--cwd", "--prefix", "--project"] as const;
105
+
106
+ /**
107
+ * Names this project binds to a single-quoting function.
108
+ *
109
+ * `shellQuote` is the one to use. The other three exist because the blocks
110
+ * they live in are extracted by marker and executed standalone by their own
111
+ * tests, so a reference to the module-level `shellQuote` is a test that
112
+ * cannot run: `quote` is a PARAMETER of `suiteCaptureCommand`
113
+ * (`test/recorder-command-executed.test.ts`), `q` is a local arrow in the
114
+ * rook-review-scope block (`test/security-verdict-blocks.test.ts`), and
115
+ * `shellSingleQuote` is declared inside the phase-2 decomposition block
116
+ * (`test/evidence-command-roundtrip.test.ts`). See the gap declared above:
117
+ * this is a name list, not a proof that the name quotes.
118
+ */
119
+ export const QUOTER_NAMES = ["shellQuote", "shellSingleQuote", "quote", "q"] as const;
120
+
121
+ export interface BarePathInterpolation {
122
+ /** The argument position that takes the path: a flag, or `cd`. */
123
+ form: string;
124
+ /** The interpolation exactly as written, e.g. `${PROJECT_ROOT}`. */
125
+ expression: string;
126
+ /**
127
+ * `double` when the site is written `"${…}"`. Refused like `none`, and
128
+ * distinguished because the remedy sentence is a different one: the author
129
+ * reached for a fix and reached for the one that stops at spaces.
130
+ */
131
+ quoting: "none" | "double";
132
+ }
133
+
134
+ /** `${…}` content that is a call to a known quoter, spanning the whole thing. */
135
+ function isQuoterCall(expression: string): boolean {
136
+ const m = expression.match(/^([A-Za-z_$][\w$]*)\s*\(/);
137
+ if (!m || !(QUOTER_NAMES as readonly string[]).includes(m[1])) return false;
138
+ // The call must cover the entire expression. `shellQuote(a) + b` does not:
139
+ // the concatenated tail reaches the shell unquoted.
140
+ return matchingParen(expression, expression.indexOf("(")) === expression.length - 1;
141
+ }
142
+
143
+ /** Index of the `)` closing the `(` at `open`, or -1. Quote-aware. */
144
+ function matchingParen(s: string, open: number): number {
145
+ let depth = 0;
146
+ let quote: string | null = null;
147
+ for (let i = open; i < s.length; i++) {
148
+ const ch = s[i];
149
+ if (quote) {
150
+ if (ch === "\\") i++;
151
+ else if (ch === quote) quote = null;
152
+ continue;
153
+ }
154
+ if (ch === "'" || ch === '"' || ch === "`") { quote = ch; continue; }
155
+ if (ch === "(") depth++;
156
+ else if (ch === ")" && --depth === 0) return i;
157
+ }
158
+ return -1;
159
+ }
160
+
161
+ /**
162
+ * Index just past the `}` closing the `${` whose `{` is at `open`, or -1.
163
+ *
164
+ * Brace-counting rather than a regex because the expressions nest:
165
+ * `${shellQuote(`${HARNESS_ROOT}/scripts/x.ts`)}` has three levels and
166
+ * `${PROJECT_ROOT || '.'}` carries a quoted brace-free string that a lazy
167
+ * `[^}]*` happens to survive and a greedy one does not.
168
+ */
169
+ function endOfInterpolation(s: string, open: number): number {
170
+ let depth = 0;
171
+ let quote: string | null = null;
172
+ for (let i = open; i < s.length; i++) {
173
+ const ch = s[i];
174
+ if (quote) {
175
+ if (ch === "\\") i++;
176
+ else if (ch === quote) quote = null;
177
+ continue;
178
+ }
179
+ if (ch === "'" || ch === '"') { quote = ch; continue; }
180
+ if (ch === "{") depth++;
181
+ else if (ch === "}" && --depth === 0) return i + 1;
182
+ }
183
+ return -1;
184
+ }
185
+
186
+ /**
187
+ * The SOURCE OFFSET of every `${name}` that resolves to a quoter binding.
188
+ *
189
+ * One entry per interpolation site, keyed by the offset of the identifier
190
+ * itself, so the decision travels with the site rather than with anything
191
+ * around it. A caller asks "is the identifier at THIS offset laundered?" and
192
+ * gets an answer about that identifier and no other.
193
+ *
194
+ * `${d}` three lines below `const d = shellQuote(dir)` is not refused, which
195
+ * is how `gitDerivedStaging` in `workflows/ship.js` is written and is written
196
+ * that way on purpose — the quoted value is used twice and one use sits
197
+ * inside a double-quoted `echo`, where re-quoting at the site would be wrong.
198
+ * The exemplar predates this check; the check accommodates it rather than the
199
+ * other way round.
200
+ *
201
+ * ## Why this resolves scopes instead of scanning names (#1106)
202
+ *
203
+ * The first version of this returned ONE set of names for the whole file,
204
+ * which made the exemption an alias granted by bare name. A security review
205
+ * measured the consequence: `ship.js` binds `d` four times and only the one
206
+ * at `gitDerivedStaging` is a quoter, so injecting `git -C ${d}` beside any
207
+ * of the other three produced **0 refusals**, while the same line with
208
+ * `${zz}` produced **1**. The decider laundered an unquoted interpolation
209
+ * whenever the variable happened to share a name with a quoter elsewhere in
210
+ * the file.
211
+ *
212
+ * **"Bound exactly once in the file" is NOT the fix, and measuring says so.**
213
+ * It sounds equivalent and is not: under it `ship.js`'s `d` — four
214
+ * declarations — stops being laundered everywhere, including at the two real
215
+ * `git -C ${d}` uses inside `gitDerivedStaging`, which are correctly quoted.
216
+ * That turns 0 refusals into 2 false ones and breaks the exemplar this check
217
+ * exists to accommodate. The correct claim is the narrower one: *bound, in a
218
+ * scope that encloses this use, to a quoter* — which is what this computes.
219
+ *
220
+ * Resolution is innermost-scope-outward over a real parse, so a parameter, a
221
+ * destructuring target, a `catch` binding and a `for` head all shadow an
222
+ * outer quoter. A name scan cannot see any of those, because none of them is
223
+ * spelled `const NAME =`.
224
+ *
225
+ * ## Why an OFFSET and not a line (#1131)
226
+ *
227
+ * #1106's first repair keyed the exemption by line, as a set of names. A line
228
+ * is still coarser than the decision: these files are 10,000-line
229
+ * template-literal soup, two functions share a line routinely, and under a
230
+ * per-line name set the quoter's own `${d}` exempted every other `${d}`
231
+ * beside it. That is the same alias defect #1106 closed, with a smaller
232
+ * radius. Keyed by `expr.start` there is no radius at all.
233
+ *
234
+ * ## A reassignment clears the flag
235
+ *
236
+ * Pass 1 records what a name was bound to AT ITS DECLARATION. `let d =
237
+ * shellQuote(x)` followed by `d = something()` leaves the declaration saying
238
+ * `shellQuote`, so the exemption outlives the value that earned it. Any
239
+ * assignment or update to a quoter-bound name clears the flag — toward
240
+ * refusal, which is the direction this is allowed to be wrong in.
241
+ *
242
+ * It is LATENT, not observed: measured across the six `workflows/*.js` on
243
+ * 2026-10-22 there are **3** quoter declarations (`script` and `d` in
244
+ * `ship.js`, `d` in `prove.js`) and **0** reassignments of any of them, all
245
+ * three being `const`. So this moves no live reading and is here because the
246
+ * next quoter binding does not have to be a `const`.
247
+ *
248
+ * ## It fails CLOSED
249
+ *
250
+ * A source acorn cannot parse launders nothing, so an unparseable file is
251
+ * refused on every bare interpolation rather than exempted on all of them.
252
+ * The opposite default would make a syntax error the most effective way to
253
+ * switch this check off.
254
+ */
255
+ export function launderedQuoterSites(source: string): ReadonlySet<number> {
256
+ const sites = new Set<number>();
257
+
258
+ let program: AcornNode;
259
+ try {
260
+ program = parse(source, {
261
+ ecmaVersion: "latest",
262
+ sourceType: "module",
263
+ // The workflow files are function BODIES, not modules — every one of
264
+ // them carries a top-level `return`, and without these two acorn
265
+ // rejects all six. Measured: with them, all six parse.
266
+ allowReturnOutsideFunction: true,
267
+ allowAwaitOutsideFunction: true,
268
+ }) as unknown as AcornNode;
269
+ } catch {
270
+ return sites; // fail closed: nothing is laundered
271
+ }
272
+
273
+ interface Scope {
274
+ parent: Scope | null;
275
+ /** name -> the offset at which it is bound, and whether that is a quoter. */
276
+ names: Map<string, { start: number; quoter: boolean }>;
277
+ }
278
+ const scopeOf = new Map<AcornNode, Scope>();
279
+
280
+ const bindName = (scope: Scope, name: string, start: number, quoter: boolean) => {
281
+ // First binding in a scope wins the position; a redeclaration of the same
282
+ // name in one scope is only ever a reason NOT to launder, so a later
283
+ // non-quoter binding clears the flag rather than being ignored.
284
+ const prior = scope.names.get(name);
285
+ if (prior === undefined) scope.names.set(name, { start, quoter });
286
+ else if (!quoter) prior.quoter = false;
287
+ };
288
+
289
+ /** Every name a binding pattern introduces. */
290
+ const patternNames = (value: unknown, out: string[]): void => {
291
+ if (!isNode(value)) return;
292
+ const node = value as AcornNode;
293
+ switch (node.type) {
294
+ case "Identifier": out.push(node.name as string); break;
295
+ case "ObjectPattern":
296
+ for (const p of asNodes(node.properties)) patternNames(p.value ?? p.argument, out);
297
+ break;
298
+ case "ArrayPattern": for (const e of asNodes(node.elements)) patternNames(e, out); break;
299
+ case "AssignmentPattern": patternNames(node.left, out); break;
300
+ case "RestElement": patternNames(node.argument, out); break;
301
+ default: break;
302
+ }
303
+ };
304
+
305
+ const isQuoterInit = (init: unknown): boolean => {
306
+ if (!isNode(init)) return false;
307
+ const node = init as AcornNode;
308
+ if (node.type !== "CallExpression") return false;
309
+ const callee = node.callee;
310
+ return (
311
+ isNode(callee) &&
312
+ (callee as AcornNode).type === "Identifier" &&
313
+ (QUOTER_NAMES as readonly string[]).includes((callee as AcornNode).name as string)
314
+ );
315
+ };
316
+
317
+ const SCOPED = new Set([
318
+ "Program", "FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression",
319
+ "BlockStatement", "ForStatement", "ForInStatement", "ForOfStatement", "CatchClause",
320
+ ]);
321
+
322
+ // Pass 1: build the scope tree and its bindings.
323
+ const build = (node: AcornNode, parent: Scope | null): void => {
324
+ let scope = parent;
325
+ if (SCOPED.has(node.type)) {
326
+ scope = { parent, names: new Map() };
327
+ scopeOf.set(node, scope);
328
+ }
329
+ if (scope) {
330
+ if (node.type === "VariableDeclarator") {
331
+ const names: string[] = [];
332
+ patternNames(node.id, names);
333
+ // A quoter only ever launders a PLAIN identifier binding: destructuring
334
+ // out of a quoter's return value is not a quoted string.
335
+ const quoter =
336
+ isNode(node.id) && (node.id as AcornNode).type === "Identifier" && isQuoterInit(node.init);
337
+ for (const n of names) bindName(scope, n, node.start as number, quoter);
338
+ } else if (
339
+ node.type === "FunctionDeclaration" || node.type === "FunctionExpression" ||
340
+ node.type === "ArrowFunctionExpression"
341
+ ) {
342
+ const names: string[] = [];
343
+ for (const p of asNodes(node.params)) patternNames(p, names);
344
+ for (const n of names) bindName(scope, n, node.start as number, false);
345
+ if (isNode(node.id) && parent) {
346
+ bindName(parent, (node.id as AcornNode).name as string, node.start as number, false);
347
+ }
348
+ } else if (node.type === "CatchClause" && node.param) {
349
+ const names: string[] = [];
350
+ patternNames(node.param, names);
351
+ for (const n of names) bindName(scope, n, node.start as number, false);
352
+ } else if (node.type === "ClassDeclaration" && isNode(node.id)) {
353
+ bindName(scope, (node.id as AcornNode).name as string, node.start as number, false);
354
+ }
355
+ }
356
+ for (const child of childNodes(node)) build(child, scope);
357
+ };
358
+ build(program, null);
359
+
360
+ /** The innermost binding of `name` visible from `scope`, if any. */
361
+ const bindingFor = (scope: Scope | null, name: string) => {
362
+ for (let s = scope; s; s = s.parent) {
363
+ const b = s.names.get(name);
364
+ if (b) return b;
365
+ }
366
+ return undefined;
367
+ };
368
+
369
+ // Pass 1.5: any assignment to a binding clears its quoter flag, wherever in
370
+ // the file it sits. Position is not consulted deliberately — a use BEFORE
371
+ // the assignment is still laundered by the declaration under a positional
372
+ // reading, and this check's one allowed direction of error is refusal.
373
+ const clearReassigned = (node: AcornNode, scope: Scope | null): void => {
374
+ const here = scopeOf.get(node) ?? scope;
375
+ const target =
376
+ node.type === "AssignmentExpression" ? node.left
377
+ : node.type === "UpdateExpression" ? node.argument
378
+ : undefined;
379
+ // Through `patternNames`, so `[d] = xs` and `({ d } = o)` clear it too.
380
+ // A `MemberExpression` target yields no names: `a.b = x` does not rebind
381
+ // `a`, and treating it as a rebind would refuse the exemplar.
382
+ const names: string[] = [];
383
+ patternNames(target, names);
384
+ for (const n of names) {
385
+ const b = bindingFor(here, n);
386
+ if (b) b.quoter = false;
387
+ }
388
+ for (const child of childNodes(node)) clearReassigned(child, here);
389
+ };
390
+ clearReassigned(program, null);
391
+
392
+ // Pass 2: resolve every bare `${name}` against the scope chain at its site.
393
+ const resolve = (scope: Scope | null, name: string, useStart: number): boolean => {
394
+ for (let s = scope; s; s = s.parent) {
395
+ const b = s.names.get(name);
396
+ // A binding that starts AFTER the use does not govern it. Requiring
397
+ // this is the safe direction: it only ever withholds laundering.
398
+ if (b && b.start <= useStart) return b.quoter;
399
+ if (b) return false;
400
+ }
401
+ return false;
402
+ };
403
+
404
+ const visit = (node: AcornNode, scope: Scope | null): void => {
405
+ const here = scopeOf.get(node) ?? scope;
406
+ if (node.type === "TemplateLiteral") {
407
+ for (const expr of asNodes(node.expressions)) {
408
+ if (expr.type !== "Identifier") continue;
409
+ if (expr.start === undefined) continue;
410
+ if (!resolve(here, expr.name as string, expr.start)) continue;
411
+ sites.add(expr.start);
412
+ }
413
+ }
414
+ for (const child of childNodes(node)) visit(child, here);
415
+ };
416
+ visit(program, null);
417
+
418
+ return sites;
419
+ }
420
+
421
+ /** Child AST nodes of `node`, in no particular order. */
422
+ function childNodes(node: AcornNode): AcornNode[] {
423
+ const out: AcornNode[] = [];
424
+ for (const key of Object.keys(node)) {
425
+ if (key === "loc" || key === "type" || key === "start" || key === "end") continue;
426
+ const value = (node as Record<string, unknown>)[key];
427
+ if (Array.isArray(value)) {
428
+ for (const v of value) if (isNode(v)) out.push(v as AcornNode);
429
+ } else if (isNode(value)) out.push(value as AcornNode);
430
+ }
431
+ return out;
432
+ }
433
+
434
+ function isNode(v: unknown): boolean {
435
+ return !!v && typeof v === "object" && typeof (v as { type?: unknown }).type === "string";
436
+ }
437
+
438
+ /** The AST nodes in an array-valued AST property, skipping holes. */
439
+ function asNodes(v: unknown): AcornNode[] {
440
+ return Array.isArray(v) ? (v.filter(isNode) as AcornNode[]) : [];
441
+ }
442
+
443
+ /** The shape of an acorn node this module reads. Deliberately loose. */
444
+ type AcornNode = {
445
+ type: string;
446
+ start?: number;
447
+ end?: number;
448
+ [key: string]: unknown;
449
+ };
450
+
451
+ /**
452
+ * Every unquoted directory interpolation on this line.
453
+ *
454
+ * THE decider: the conformity scan, and anything later that wants the same
455
+ * question answered, calls this and nothing else. A second spelling of the
456
+ * parse somewhere else would be the two-deciders-that-agree defect
457
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape) — mutate
458
+ * this one and the other would keep its caller green.
459
+ *
460
+ * Takes a LINE rather than a file because the unit a report has to name is a
461
+ * line, and because these sources are 10,000-line template-literal soup
462
+ * where no larger unit has a boundary worth finding.
463
+ *
464
+ * `isLaundered` is asked about ONE SITE — the name and the offset of the
465
+ * identifier inside this line — rather than handed a set of exempt names
466
+ * (#1131). A set is an alias: it answers for every occurrence that spells
467
+ * itself the same way, and two functions share a line here routinely. The
468
+ * default says no to everything, so a caller that does not resolve bindings
469
+ * refuses more rather than less.
470
+ */
471
+ export function barePathInterpolations(
472
+ line: string,
473
+ isLaundered: (name: string, offsetInLine: number) => boolean = () => false,
474
+ ): BarePathInterpolation[] {
475
+ const found: BarePathInterpolation[] = [];
476
+
477
+ // `-C`/`--cwd`/`--prefix`/`--project` followed by its value, and the `cd`
478
+ // builtin followed by its target. `cd` is here as well as in
479
+ // `lib/top-level-cd.ts` because the two ask different questions about it:
480
+ // that one asks whether the shell moves, this one asks whether the path
481
+ // survives a space. A subshell `( cd ${X} && … )` passes the first and
482
+ // fails the second.
483
+ const anchor = new RegExp(
484
+ `(?:^|[\\s"'\`(;&|])(${PATH_FLAGS.map(f => f.replace(/[-]/g, "\\-")).join("|")}|cd)(?:=|\\s+)`,
485
+ "g",
486
+ );
487
+
488
+ let m: RegExpExecArray | null;
489
+ while ((m = anchor.exec(line))) {
490
+ const form = m[1];
491
+ let at = m.index + m[0].length;
492
+
493
+ const doubleQuoted = line[at] === '"';
494
+ if (doubleQuoted) at++;
495
+ if (line.slice(at, at + 2) !== "${") continue; // a literal path is not ours
496
+
497
+ const end = endOfInterpolation(line, at + 1);
498
+ if (end === -1) continue; // unbalanced: the line is not what it looks like
499
+
500
+ const expression = line.slice(at, end);
501
+ const raw = expression.slice(2, -1);
502
+ const inner = raw.trim();
503
+
504
+ if (isQuoterCall(inner)) continue;
505
+ // The identifier's OWN offset within the line, so the caller answers
506
+ // about this site rather than about anything else sharing the line.
507
+ // `at` is the `$`; `+2` clears `${`; the rest is whatever `trim` took,
508
+ // because `${ d }` is legal and the parser's identifier starts at `d`.
509
+ if (isLaundered(inner, at + 2 + (raw.length - raw.trimStart().length))) continue;
510
+
511
+ found.push({
512
+ form,
513
+ expression: doubleQuoted ? `"${expression}"` : expression,
514
+ quoting: doubleQuoted ? "double" : "none",
515
+ });
516
+ }
517
+
518
+ return found;
519
+ }
520
+
521
+ /** A refusal, located. */
522
+ export interface LocatedBarePath extends BarePathInterpolation {
523
+ /** 1-based line number in the ORIGINAL source. */
524
+ line: number;
525
+ }
526
+
527
+ /**
528
+ * Every unquoted directory interpolation in a whole source file.
529
+ *
530
+ * ## Comments are stripped, and that is a decision with a measurement
531
+ *
532
+ * `stripJsComments` blanks comment text while preserving every byte offset,
533
+ * so the line numbers reported here are the source's own. Without it,
534
+ * `workflows/ship.js` is refused at the docblock above `gitAddForCommit`,
535
+ * which reads *"the commit still ran `cd ${commitDir}`, so nothing was
536
+ * staged"* — prose ABOUT a defect, counted as the defect. That was one of the
537
+ * seven hits the first run of this scan produced and the only false one.
538
+ *
539
+ * It is also the right view for the opposite reason: a quoting fix applied
540
+ * inside a comment changes nothing a shell ever sees, so a check that could
541
+ * be satisfied by editing a comment is a check that can be satisfied without
542
+ * fixing anything.
543
+ *
544
+ * The stripper is template-literal aware, which matters here more than
545
+ * anywhere else in the tree — these files are mostly prompt text, and a `//`
546
+ * inside a prompt is a URL, not a comment.
547
+ */
548
+ export function barePathInterpolationsIn(source: string): LocatedBarePath[] {
549
+ const code = stripJsComments(source);
550
+ // Over the STRIPPED copy, so a `const d = shellQuote(x)` written in a
551
+ // comment cannot launder the name `d` for real code elsewhere.
552
+ //
553
+ // Per SITE, not per file (#1106) and not per line (#1131). Both coarser
554
+ // keys made the exemption an alias granted by bare name: a file-wide set
555
+ // laundered a `${d}` anywhere in `ship.js` because some other function
556
+ // bound a `d` to a quoter, and a per-line set did the same to every `${d}`
557
+ // sharing a line with the quoter's own use.
558
+ const laundered = launderedQuoterSites(code);
559
+ const found: LocatedBarePath[] = [];
560
+ let lineStart = 0;
561
+ for (const [i, line] of code.split("\n").entries()) {
562
+ // Both the parse and this split are over `code`, so the offsets are one
563
+ // numbering rather than two that have to be kept in step. The reported
564
+ // `line` is the source's own for the separate reason that
565
+ // `stripJsComments` blanks comment text without moving a newline.
566
+ const at = lineStart;
567
+ for (const b of barePathInterpolations(line, (_n, off) => laundered.has(at + off))) {
568
+ found.push({ ...b, line: i + 1 });
569
+ }
570
+ lineStart += line.length + 1; // the "\n" `split` removed
571
+ }
572
+ return found;
573
+ }
574
+
575
+ /**
576
+ * What a caller is told, naming the one accepted remedy and refusing the
577
+ * cheap one by name.
578
+ *
579
+ * Spelled here rather than at the call site so the refusal and the advice
580
+ * cannot drift, the same reason `refusalMessage` lives inside
581
+ * `lib/top-level-cd.ts`.
582
+ */
583
+ export const BARE_PATH_REMEDY =
584
+ "#1086: a directory is interpolated into a shell command unquoted, so a " +
585
+ "consumer whose checkout is at `/Users/x/My Projects/thing` gets " +
586
+ "`git -C /Users/x/My Projects/thing status` and an error naming a " +
587
+ "directory nobody typed. Wrap the interpolation in `shellQuote(…)` at the " +
588
+ "site, or bind it once (`const d = shellQuote(dir)`) and interpolate the " +
589
+ "bound name. Do NOT write `\"${…}\"` instead: double quotes stop at the " +
590
+ "space and leave `$(…)` and backticks expanding, which is the shape a " +
591
+ "security review already caught once in `gitDerivedStaging`. Workflow " +
592
+ "files cannot import (#69), so each one carries its own copy of " +
593
+ "`shellQuote`; `lib/workflow-security.ts` is the source of truth and " +
594
+ "`test/workflow-prompt-top-level-cd.test.ts` fails on any divergence.";