rungate 0.7.0 → 0.8.1

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 (108) hide show
  1. package/gates/.gate-salt +1 -0
  2. package/gates/SCHEMA-GUIDE.md +485 -0
  3. package/gates/ac-quality.test.ts +106 -0
  4. package/gates/adversarial.test.ts +283 -0
  5. package/gates/brief-assembler.test.ts +487 -0
  6. package/gates/brief-assembler.ts +448 -0
  7. package/gates/bunfig.toml +2 -0
  8. package/gates/chain.test.ts +91 -0
  9. package/gates/e2e-smoke.test.ts +234 -0
  10. package/gates/error-classifier.test.ts +250 -0
  11. package/gates/error-classifier.ts +99 -0
  12. package/gates/gate-executor.ts +3071 -0
  13. package/gates/orchestrator.test.ts +968 -0
  14. package/gates/orchestrator.ts +827 -0
  15. package/gates/preload.ts +89 -0
  16. package/gates/prompts/ac-adversary.md +20 -0
  17. package/gates/prompts/evidence-validator.md +22 -0
  18. package/gates/prompts/prove-reproducer.md +53 -0
  19. package/gates/prompts.sha256 +3 -0
  20. package/gates/prove.test.ts +164 -0
  21. package/gates/rook-state.test.ts +108 -0
  22. package/gates/run-attribution.ts +290 -0
  23. package/gates/run-gate.ts +163 -0
  24. package/gates/schema-parity.test.ts +378 -0
  25. package/gates/schema.ts +1209 -0
  26. package/gates/self-heal.test.ts +511 -0
  27. package/gates/self-heal.ts +125 -0
  28. package/gates/ship-orchestrator.test.ts +399 -0
  29. package/gates/ship-orchestrator.ts +384 -0
  30. package/gates/spec-compliance-probe.ts +159 -0
  31. package/gates/test-fixtures/broken-no-environments.json +110 -0
  32. package/gates/test-fixtures/consumer-directory-layout.json +90 -0
  33. package/gates/test-fixtures/valid-standard.json +91 -0
  34. package/gates/test-utils.ts +43 -0
  35. package/gates/typecheck-gate.ts +111 -0
  36. package/gates/witness.ts +349 -0
  37. package/gates/workflow.test.ts +2018 -0
  38. package/hooks/ActionVerificationGate.hook.ts +96 -0
  39. package/hooks/AgentBriefGuard.hook.ts +38 -0
  40. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  41. package/hooks/AutoVerifyGate.hook.ts +79 -0
  42. package/hooks/BashToolGuard.hook.ts +65 -0
  43. package/hooks/BashWriteGuard.hook.ts +60 -0
  44. package/hooks/CommitEnforcement.hook.ts +130 -0
  45. package/hooks/DocHygiene.hook.ts +148 -0
  46. package/hooks/GateEnforcement.hook.ts +58 -0
  47. package/hooks/GateResultProtection.hook.ts +95 -0
  48. package/hooks/HarnessAFKGate.hook.ts +85 -0
  49. package/hooks/HookCurrency.hook.ts +99 -0
  50. package/hooks/IssueCloseGuard.hook.ts +149 -0
  51. package/hooks/MergeGuard.hook.ts +58 -0
  52. package/hooks/PostCompact.hook.ts +60 -0
  53. package/hooks/ProjectStateSync.hook.ts +103 -0
  54. package/hooks/SkillGuard.hook.ts +69 -0
  55. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  56. package/hooks/SpecSCGuard.hook.ts +123 -0
  57. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  58. package/hooks/TaskCompleted.hook.ts +51 -0
  59. package/hooks/TeamInit.hook.ts +85 -0
  60. package/hooks/TestSuiteGuard.hook.ts +70 -0
  61. package/hooks/TestSuiteRelease.hook.ts +85 -0
  62. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  63. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  64. package/hooks/WorkflowStateGuard.hook.ts +64 -0
  65. package/hooks/lib/agent-config.json +9 -0
  66. package/hooks/lib/agentDetection.ts +201 -0
  67. package/hooks/lib/comment-template.ts +86 -0
  68. package/hooks/lib/findWorkflow.ts +101 -0
  69. package/hooks/lib/parseStdin.ts +37 -0
  70. package/hooks/lib/paths.ts +111 -0
  71. package/hooks/lib/utils.ts +338 -0
  72. package/lib/affected-tests.ts +29 -0
  73. package/lib/bash-write-guard.ts +627 -0
  74. package/lib/branch-cleanup.ts +279 -7
  75. package/lib/config-trackable.ts +9 -0
  76. package/lib/distribution-currency.ts +55 -5
  77. package/lib/failure-intake.ts +7 -1
  78. package/lib/gate-enforcement.ts +360 -38
  79. package/lib/gate-names.ts +72 -0
  80. package/lib/gate-result-protection.ts +437 -0
  81. package/lib/generators/code-map.ts +55 -4
  82. package/lib/generators/types.ts +27 -1
  83. package/lib/intake-sources.ts +380 -0
  84. package/lib/js-top-level-code.ts +20 -2
  85. package/lib/junit-checks.ts +239 -1
  86. package/lib/late-env-spawn.ts +331 -0
  87. package/lib/launch-base.ts +128 -5
  88. package/lib/package-closure.ts +114 -0
  89. package/lib/paths.ts +96 -3
  90. package/lib/phase2-decomposition.ts +1 -1
  91. package/lib/published-artifact.ts +162 -18
  92. package/lib/sc-id-cross-tree.ts +84 -8
  93. package/lib/scaffold/ai-review-findings.ts +149 -4
  94. package/lib/scaffold/ai-review-step.ts +1006 -132
  95. package/lib/scaffold/defaults.ts +82 -1
  96. package/lib/scaffold/steps.ts +642 -54
  97. package/lib/scanner.ts +4 -2
  98. package/lib/security-verdict.ts +1 -1
  99. package/lib/shell-path-interpolation.ts +594 -0
  100. package/lib/text-dependents.ts +875 -0
  101. package/lib/transcript-checker.ts +6 -0
  102. package/lib/workflow-security.ts +29 -0
  103. package/lib/workflow-taint.ts +732 -0
  104. package/lib/worktree-cleanup.ts +65 -38
  105. package/lib/worktree-repo.ts +32 -2
  106. package/package.json +4 -1
  107. package/scripts/check-installed-hook-currency.ts +825 -0
  108. package/scripts/generate-code-map.ts +13 -8
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Where observed-failure candidates come from, and how a source refuses when
3
+ * its input is not there (#545).
4
+ *
5
+ * ## The decision this file is, and why it comes before a fourth scanner
6
+ *
7
+ * #545 names four intake sources. `lib/failure-intake.ts` ships one — `git
8
+ * log` — and its docblock records why the other three stopped there: each
9
+ * needs something a check running in the configuration CI runs it in does not
10
+ * have.
11
+ *
12
+ * | Source | Needs | Present under an empty `HOME`, no credentials |
13
+ * |---|---|---|
14
+ * | `git log` fix/revert | the repository | yes |
15
+ * | gate refusals | a populated run store | no |
16
+ * | CI failures on merged PRs | an authenticated API client | no |
17
+ * | transcript corrections | a session store, and a confidentiality decision | no |
18
+ *
19
+ * **A miner whose input is absent has no failing input, so it passes
20
+ * vacuously.** Adding a second scanner before deciding how absence is
21
+ * reported produces a detector that is green everywhere it matters — the
22
+ * defect class `.claude/rules/checks-must-be-able-to-fail.md` opens with, one
23
+ * level up, because here the thing that cannot fail is the thing that decides
24
+ * what the rules are.
25
+ *
26
+ * So this module is the contract, not a scanner:
27
+ *
28
+ * - every source declares a **precondition** naming what it needs;
29
+ * - a source whose precondition is unmet reports `UNMEASURED` with a reason
30
+ * that names the source AND the missing input — never an empty candidate
31
+ * list;
32
+ * - the aggregate reads `MEASURED` only if **every registered source** did,
33
+ * so a reading cannot be completed by the sources that happened to work;
34
+ * - and `test/intake-sources.test.ts` drives every registered source in a
35
+ * **barren context** — an empty directory, no repository, no store — and
36
+ * requires each to refuse there. A scanner added without a reachable
37
+ * unavailable state fails that case rather than passing silently.
38
+ *
39
+ * That last point is the mechanical half. It is cheap to write a source that
40
+ * reports `MEASURED` over nothing; it is not possible to register one here
41
+ * and keep the suite green.
42
+ *
43
+ * ## Why gate refusals are the second source and the other two are not
44
+ *
45
+ * The run store is **offline, local, and needs no credential** — the same
46
+ * three properties that made `git log` first. CI failures need an
47
+ * authenticated client, and transcripts need a confidentiality decision
48
+ * nobody has made; both are still unregistered, deliberately, because
49
+ * registering a source whose `read` cannot run is dead code wearing a
50
+ * contract.
51
+ *
52
+ * ## What a gate refusal contributes that a commit subject cannot
53
+ *
54
+ * A `fix:` subject is one author's account of one failure. A gate refusal is
55
+ * the harness's own record that a check stopped a run, and it REPEATS.
56
+ * Measured across this machine's 44 run stores: 111 refusal entries over 19
57
+ * distinct check names, 28 of the 44 runs carrying at least one. The most
58
+ * frequent single check accounts for 22 of them.
59
+ *
60
+ * That ratio is the reason the dedup key here is the CHECK NAME and not the
61
+ * entry: one candidate per entry would produce 111 candidates ranked by
62
+ * recency, dominated by repeats of one check, against a promotion budget of
63
+ * 16. One candidate per distinct check produces 19, and the repetition
64
+ * becomes evidence rather than noise.
65
+ *
66
+ * ## WHAT THIS DOES NOT COVER
67
+ *
68
+ * - **A check that fails because it is broken, not because the tree is.** A
69
+ * flaky or mis-written gate check repeats exactly like a real one, and
70
+ * nothing here reads the detail to tell them apart. The repetition this
71
+ * module treats as evidence is the same signal in both cases.
72
+ * - **Occurrence count does not reach the ranker.** It is written into the
73
+ * candidate's `context`, where a human reads it, and `lib/rule-promotion.ts`
74
+ * ranks on `evidence` alone. Wiring frequency into the score is a change to
75
+ * #544's criterion and is deliberately not taken here.
76
+ * - **The store is this machine's, not the project's.** A candidate mined
77
+ * here cites a run id nobody else can resolve. That is why the source is
78
+ * UNMEASURED on a runner rather than merely empty — the citation is as
79
+ * local as the evidence.
80
+ */
81
+
82
+ import { existsSync, readdirSync, readFileSync } from "fs";
83
+ import { join } from "path";
84
+
85
+ import { contentHash } from "./content-hash";
86
+ import type { EvidenceCandidate, FailureIntakeReading } from "./failure-intake";
87
+ import { mineFixCommits } from "./failure-intake";
88
+ import { workStoreRoot } from "./paths";
89
+
90
+ /**
91
+ * Prefixes a reason that means "this source could not be read here", as
92
+ * distinct from "this source was read and found nothing".
93
+ *
94
+ * Exported because a caller distinguishing the cases must compare against the
95
+ * producer's own spelling rather than a second copy of it.
96
+ */
97
+ export const SOURCE_UNAVAILABLE = "SOURCE_UNAVAILABLE";
98
+
99
+ /** The run store held no `workflow-state.json` this process could read. */
100
+ export const NO_RUN_STORE = "NO_RUN_STORE";
101
+ /** The store exists and a state file in it would not parse. */
102
+ export const RUN_STORE_UNREADABLE = "RUN_STORE_UNREADABLE";
103
+
104
+ /** Everything a source is allowed to read. Explicit so a test can be barren. */
105
+ export interface IntakeContext {
106
+ /** The project being mined. */
107
+ projectRoot: string;
108
+ /** The run store root — `lib/paths.ts` owns the default. */
109
+ workStore: string;
110
+ }
111
+
112
+ /**
113
+ * The default context. Separate from `mineObservedFailures` so a caller can
114
+ * mine a project without inheriting this machine's store, and so the test can
115
+ * build one that is barren by construction.
116
+ */
117
+ export function defaultIntakeContext(projectRoot: string): IntakeContext {
118
+ return { projectRoot, workStore: workStoreRoot() };
119
+ }
120
+
121
+ export interface IntakeSource {
122
+ /** Stable id. Appears in every reason this source produces. */
123
+ id: string;
124
+ /** What the source needs, in words a reader can act on. */
125
+ needs: string;
126
+ /**
127
+ * `null` when the source can be read here; otherwise a short reason naming
128
+ * what is absent. A source that can never return non-null has no reachable
129
+ * unavailable state, which `test/intake-sources.test.ts` refuses.
130
+ */
131
+ precondition(ctx: IntakeContext): string | null;
132
+ /** Only called when `precondition` returned `null`. */
133
+ read(ctx: IntakeContext): FailureIntakeReading;
134
+ }
135
+
136
+ /**
137
+ * The aggregate reading — `MEASURED` only when every registered source was,
138
+ * and a union rather than a record so that **`candidates` exists only on the
139
+ * measured variant**.
140
+ *
141
+ * The hazard that shape is for: a reader who takes `candidates.length`
142
+ * without consulting `reading` gets a number that looks like a measurement
143
+ * and is a function of something else entirely. The worked instance is this
144
+ * repository's own development checkout — `mineFixCommits` correctly reports
145
+ * `UNMEASURED` / `SHALLOW_HISTORY` there and still returns 182 candidates,
146
+ * because the clone has a depth. 182 is a reading of a clone parameter, not
147
+ * of the project's history, and nothing about the list says so.
148
+ *
149
+ * Adjacency does not fix that. A warning beside a number is read after the
150
+ * number, if at all. So on the `UNMEASURED` variant the key is **absent**: a
151
+ * consumer that narrows on `reading` is handed `candidates`, and one that
152
+ * does not gets a type error at compile time and `undefined` at runtime,
153
+ * which throws instead of returning something plausible. The partial list is
154
+ * still reachable — withholding it would make a partial reading and an empty
155
+ * one look alike — but under a name nobody reaches for by accident.
156
+ *
157
+ * **Applied here and deliberately not to `FailureIntakeReading`.** That type
158
+ * is shipped and has a production consumer, and that consumer already does
159
+ * the right thing: `scripts/extract-constraints.ts` spreads
160
+ * `evidence.candidates` into the promotion AND passes the reading as an
161
+ * `upstream`, so `promoteCandidates` folds `UNMEASURED` into its own verdict.
162
+ * The hazard is latent there, not live. Converting a shipped type to prevent
163
+ * a hazard nobody has hit is a wider change than this one should make.
164
+ */
165
+ export type AggregateIntakeReading =
166
+ | {
167
+ reading: "MEASURED";
168
+ unmeasuredReasons: string[];
169
+ /** Per source, so "read and empty" and "not readable" stay tellable apart. */
170
+ bySource: Record<string, FailureIntakeReading>;
171
+ /** Every candidate every source produced. Present only on this variant. */
172
+ candidates: EvidenceCandidate[];
173
+ }
174
+ | {
175
+ reading: "UNMEASURED";
176
+ unmeasuredReasons: string[];
177
+ bySource: Record<string, FailureIntakeReading>;
178
+ /**
179
+ * What the sources that COULD be read produced. Deliberately not
180
+ * spelled `candidates`: counting these is a decision, and the name is
181
+ * the place that decision gets made.
182
+ */
183
+ partialCandidates: EvidenceCandidate[];
184
+ };
185
+
186
+ // ── The gate-refusal source ──────────────────────────────────────────────
187
+
188
+ /** One refusal entry, as `workflow-state.json` writes it. */
189
+ interface StoredFailure {
190
+ check?: unknown;
191
+ result?: unknown;
192
+ }
193
+
194
+ function refusalsIn(state: unknown): Array<{ gate: string; check: string; ts: string }> {
195
+ const out: Array<{ gate: string; check: string; ts: string }> = [];
196
+ const gates = (state as { gates?: unknown } | null)?.gates;
197
+ if (!gates || typeof gates !== "object") return out;
198
+ for (const [gate, entry] of Object.entries(gates as Record<string, unknown>)) {
199
+ const e = entry as { failures?: unknown; ts?: unknown } | null;
200
+ if (!e || !Array.isArray(e.failures)) continue;
201
+ const ts = typeof e.ts === "string" ? e.ts : "";
202
+ for (const f of e.failures as StoredFailure[]) {
203
+ if (!f || typeof f.check !== "string" || f.check.trim().length === 0) continue;
204
+ out.push({ gate, check: f.check.trim(), ts });
205
+ }
206
+ }
207
+ return out;
208
+ }
209
+
210
+ /**
211
+ * Mine gate refusals out of the run store.
212
+ *
213
+ * **An unreadable state file is a refusal, not a skip.** `lib/gate-
214
+ * enforcement.ts`'s reader of the same files wraps its walk in
215
+ * `catch { /* skip *\/ }`, which converts a corrupt store into an empty one —
216
+ * the fail-open `.claude/rules/config-access.md` names by name. Here a file
217
+ * that will not parse pushes `RUN_STORE_UNREADABLE` and the reading says so,
218
+ * because "no run ever refused" and "I could not read the runs" are opposite
219
+ * facts about this project's history.
220
+ */
221
+ export function mineGateRefusals(workStore: string): FailureIntakeReading {
222
+ const unmeasuredReasons: string[] = [];
223
+ if (!existsSync(workStore)) {
224
+ return { reading: "UNMEASURED", unmeasuredReasons: [NO_RUN_STORE], commitsScanned: 0, candidates: [] };
225
+ }
226
+
227
+ let dirs: string[];
228
+ try {
229
+ dirs = readdirSync(workStore, { withFileTypes: true })
230
+ .filter((d) => d.isDirectory())
231
+ .map((d) => d.name);
232
+ } catch (e) {
233
+ return {
234
+ reading: "UNMEASURED",
235
+ unmeasuredReasons: [`${RUN_STORE_UNREADABLE}: ${(e as Error).message}`],
236
+ commitsScanned: 0,
237
+ candidates: [],
238
+ };
239
+ }
240
+
241
+ /** check name → the evidence, newest kept. */
242
+ const byCheck = new Map<
243
+ string,
244
+ { gate: string; ts: string; slug: string; issues: number[]; occurrences: number; runs: Set<string> }
245
+ >();
246
+ let statesRead = 0;
247
+
248
+ for (const slug of dirs.sort()) {
249
+ const path = join(workStore, slug, "workflow-state.json");
250
+ if (!existsSync(path)) continue;
251
+ let state: unknown;
252
+ try {
253
+ state = JSON.parse(readFileSync(path, "utf-8"));
254
+ } catch (e) {
255
+ unmeasuredReasons.push(`${RUN_STORE_UNREADABLE}: ${slug}: ${(e as Error).message}`);
256
+ continue;
257
+ }
258
+ statesRead++;
259
+ const issue = (state as { issue?: unknown }).issue;
260
+ const issues = typeof issue === "number" ? [issue] : [];
261
+ for (const r of refusalsIn(state)) {
262
+ const prior = byCheck.get(r.check);
263
+ if (prior === undefined) {
264
+ byCheck.set(r.check, {
265
+ gate: r.gate, ts: r.ts, slug, issues, occurrences: 1, runs: new Set([slug]),
266
+ });
267
+ continue;
268
+ }
269
+ prior.occurrences++;
270
+ prior.runs.add(slug);
271
+ // Newest citation wins, matching `mineFixCommits`' newest-first rule, so
272
+ // a reader following the citation lands on the most recent observation.
273
+ // An entry with no `ts` never displaces one that has a date.
274
+ if (r.ts !== "" && r.ts > prior.ts) {
275
+ prior.ts = r.ts;
276
+ prior.gate = r.gate;
277
+ prior.slug = slug;
278
+ prior.issues = issues;
279
+ }
280
+ }
281
+ }
282
+
283
+ // A store directory with no state files in it is not a measured zero: the
284
+ // walk found nothing to read, which is the NO_RUN_STORE case arriving by a
285
+ // different route.
286
+ if (statesRead === 0) unmeasuredReasons.push(NO_RUN_STORE);
287
+
288
+ const candidates: EvidenceCandidate[] = [];
289
+ for (const [check, ev] of [...byCheck.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
290
+ // A refusal with no date is not evidence-backed — `CandidateEvidence`
291
+ // says so in its own comment — so it is dropped rather than dated `""`.
292
+ if (ev.ts === "") continue;
293
+ candidates.push({
294
+ rule: check,
295
+ source: `run:${ev.slug}`,
296
+ context:
297
+ `gate '${ev.gate}' refused on this check — ` +
298
+ `${ev.occurrences} occurrence(s) across ${ev.runs.size} run(s)`,
299
+ hash: contentHash(check),
300
+ evidence: { kind: "gate-refusal", date: ev.ts, citation: ev.slug, issues: ev.issues },
301
+ });
302
+ }
303
+
304
+ return {
305
+ reading: unmeasuredReasons.length > 0 ? "UNMEASURED" : "MEASURED",
306
+ unmeasuredReasons,
307
+ // Reusing the field's meaning: units of history this source actually read.
308
+ commitsScanned: statesRead,
309
+ candidates,
310
+ };
311
+ }
312
+
313
+ // ── The registry ─────────────────────────────────────────────────────────
314
+
315
+ /**
316
+ * Every source that is wired up. Adding one here puts it under
317
+ * `test/intake-sources.test.ts`'s barren-context case immediately — which is
318
+ * the point, and is why the two unregistered sources below are named in prose
319
+ * rather than stubbed in code.
320
+ */
321
+ export const INTAKE_SOURCES: readonly IntakeSource[] = [
322
+ {
323
+ id: "fix-commits",
324
+ needs: "a git repository with unshallowed history",
325
+ precondition: (ctx) =>
326
+ existsSync(join(ctx.projectRoot, ".git")) ? null : "no git repository at the project root",
327
+ read: (ctx) => mineFixCommits(ctx.projectRoot),
328
+ },
329
+ {
330
+ id: "gate-refusals",
331
+ needs: "a populated rungate run store (RUNGATE_WORK_DIR, or $HOME/.rungate)",
332
+ precondition: (ctx) =>
333
+ existsSync(ctx.workStore) ? null : `no run store at ${ctx.workStore}`,
334
+ read: (ctx) => mineGateRefusals(ctx.workStore),
335
+ },
336
+ ];
337
+
338
+ /**
339
+ * Read every registered source, and say which ones could not be read.
340
+ *
341
+ * The aggregate is `MEASURED` only when every source was. A reading completed
342
+ * by the sources that happened to work is the Silent Default Substitution
343
+ * this whole module exists to refuse: zero CI-failure candidates because
344
+ * there is no API client reads exactly like zero because CI never failed.
345
+ */
346
+ export function mineObservedFailures(
347
+ ctx: IntakeContext,
348
+ sources: readonly IntakeSource[] = INTAKE_SOURCES,
349
+ ): AggregateIntakeReading {
350
+ const bySource: Record<string, FailureIntakeReading> = {};
351
+ const unmeasuredReasons: string[] = [];
352
+ const candidates: EvidenceCandidate[] = [];
353
+
354
+ for (const source of sources) {
355
+ const missing = source.precondition(ctx);
356
+ if (missing !== null) {
357
+ const reason = `${SOURCE_UNAVAILABLE}: ${source.id}: ${missing} (needs ${source.needs})`;
358
+ bySource[source.id] = {
359
+ reading: "UNMEASURED",
360
+ unmeasuredReasons: [reason],
361
+ commitsScanned: 0,
362
+ candidates: [],
363
+ };
364
+ unmeasuredReasons.push(reason);
365
+ continue;
366
+ }
367
+ const reading = source.read(ctx);
368
+ bySource[source.id] = reading;
369
+ for (const r of reading.unmeasuredReasons) unmeasuredReasons.push(`${source.id}: ${r}`);
370
+ candidates.push(...reading.candidates);
371
+ }
372
+
373
+ // The discriminator and the key are chosen together, in one place, so the
374
+ // two cannot disagree — there is no path that reports UNMEASURED and still
375
+ // hands back a `candidates` a caller can count without asking.
376
+ if (unmeasuredReasons.length > 0) {
377
+ return { reading: "UNMEASURED", unmeasuredReasons, bySource, partialCandidates: candidates };
378
+ }
379
+ return { reading: "MEASURED", unmeasuredReasons, bySource, candidates };
380
+ }
@@ -104,10 +104,24 @@ export function regexCanFollowToken(token: string): boolean {
104
104
  * module on purpose. Two functions that each decide what a comment is are two
105
105
  * deciders, and the one that is wrong is invisible — see
106
106
  * `.claude/rules/checks-must-be-able-to-fail.md`.
107
+ *
108
+ * `keepTemplateText` additionally keeps the literal text of a template, which
109
+ * `keepStringContents` alone still blanks.
110
+ *
111
+ * Added for #1174, which scans published source for INSTRUCTIONS naming a
112
+ * path — and three of the six in the tree are built with `${HARNESS_ROOT}`
113
+ * inside a template, so under `keepStringContents` alone the scanner read a
114
+ * clean tree and the detector would have been narrower than what it detects.
115
+ * It is a flag here for the same reason `keepStringContents` is: the
116
+ * alternative was a comment-stripper in `lib/package-closure.ts`, which is the
117
+ * second decider this docstring already argues against.
107
118
  */
108
119
  export function stripStringsAndComments(
109
120
  src: string,
110
- { keepStringContents = false }: { keepStringContents?: boolean } = {},
121
+ {
122
+ keepStringContents = false,
123
+ keepTemplateText = false,
124
+ }: { keepStringContents?: boolean; keepTemplateText?: boolean } = {},
111
125
  ): string {
112
126
  let out = "";
113
127
  let i = 0;
@@ -126,6 +140,10 @@ export function stripStringsAndComments(
126
140
  // Inside a template, but NOT inside one of its interpolations.
127
141
  if (templates.length > 0 && templates[templates.length - 1] === 0) {
128
142
  if (c === "\\") {
143
+ // Both characters, or neither. Emitting the escaped character without
144
+ // its backslash would hand the caller a string that differs from the
145
+ // source it is about to match paths against.
146
+ if (keepTemplateText) out += src.slice(i, i + 2);
129
147
  i += 2;
130
148
  continue;
131
149
  }
@@ -144,7 +162,7 @@ export function stripStringsAndComments(
144
162
  continue;
145
163
  }
146
164
  // Template text: drop it, but keep newlines so line numbers survive.
147
- out += c === "\n" ? "\n" : "";
165
+ out += keepTemplateText || c === "\n" ? c : "";
148
166
  i++;
149
167
  continue;
150
168
  }