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
@@ -60,7 +60,9 @@
60
60
  * battery's reach entirely.
61
61
  */
62
62
  import { spawnSync } from "child_process";
63
+ import { resolve } from "path";
63
64
 
65
+ import { canonicalRoot } from "./paths";
64
66
  import { readWorktreeRemote, redactRemote, repoSlug } from "./worktree-repo";
65
67
 
66
68
  /**
@@ -86,6 +88,19 @@ export type LaunchBaseReading =
86
88
  | { reading: "DIFFERENT_REPO"; cwd: string; projectRoot: string; refusal: string }
87
89
  /** Same repository, different working tree or branch. Failure 2, quiet version. */
88
90
  | { reading: "DIFFERENT_CHECKOUT"; cwd: string; projectRoot: string; refusal: string }
91
+ /**
92
+ * A root is reached through a symlink, so it has two spellings (#1129).
93
+ *
94
+ * This reading exists because its absence was the gap. `--show-toplevel`
95
+ * RESOLVES symlinks, so both spellings of one directory produce one
96
+ * answer and the comparison below reads `SAME_CHECKOUT` — the one gate
97
+ * that sees both the session and the root is structurally blind to the
98
+ * difference, and then hands the unresolved string onward to a workflow
99
+ * that can only compare strings. "The roots are canonical" and "the roots
100
+ * are two spellings that happen to resolve alike" were indistinguishable
101
+ * in this output; they no longer are.
102
+ */
103
+ | { reading: "NON_CANONICAL_ROOT"; cwd: string; projectRoot: string; refusal: string }
89
104
  /**
90
105
  * Something could not be read. NOT a pass: a reading that could not be
91
106
  * taken is indistinguishable from a clean one, and only one of them is
@@ -131,14 +146,94 @@ function branchOf(dir: string): string | null {
131
146
  * separates "the tree the run was handed" from "another tree of the same
132
147
  * project", and that distinction is the whole of failure 2's quiet half.
133
148
  */
134
- export function launchBaseReading(cwd: string, projectRoot: string): LaunchBaseReading {
149
+ /**
150
+ * The roots that are not their own canonical spelling, as a reading (#1129).
151
+ *
152
+ * Returns `null` when every root given resolves to itself — which is the
153
+ * only state the rest of `launchBaseReading` can reason about, because
154
+ * every comparison downstream of it is between strings.
155
+ *
156
+ * `harnessRoot` is optional and skipped when absent rather than treated as
157
+ * canonical. `harnessRootFor()` in `lib/paths.ts` canonicalises the roots it
158
+ * produces, but it is not the only producer — a hand-typed `--harness-root`
159
+ * never goes through it, which is why this takes the value rather than
160
+ * trusting the producer.
161
+ *
162
+ * An unresolvable root is UNMEASURED and refuses. It is deliberately NOT
163
+ * folded into NON_CANONICAL_ROOT: "this root has two names" is fixed by
164
+ * relaunching with the other one, and "this root does not exist" is not, so
165
+ * collapsing them would hand the operator a remedy that cannot work.
166
+ */
167
+ function nonCanonicalRoots(roots: {
168
+ projectRoot: string;
169
+ harnessRoot?: string;
170
+ }): { reading: "NON_CANONICAL_ROOT" | "UNMEASURED"; refusal: string } | null {
171
+ for (const [name, given] of Object.entries(roots)) {
172
+ if (typeof given !== "string" || !given.trim()) continue;
173
+ let canonical: string;
174
+ try {
175
+ canonical = canonicalRoot(given);
176
+ } catch (e: any) {
177
+ return {
178
+ reading: "UNMEASURED",
179
+ refusal:
180
+ `${name} ${safe(given)} cannot be resolved to a real path (${redactRemote(String(e?.message || e))}). ` +
181
+ "Whether this run's containment checks would agree with the paths git reports is therefore " +
182
+ "unknown, and unknown is not canonical — it is refused rather than passed through unresolved (#1129)",
183
+ };
184
+ }
185
+ if (canonical === given) continue;
186
+
187
+ // TWO conditions, and they are reported apart because only one of them
188
+ // is about symlinks. Comparing `canonical` straight back against the raw
189
+ // string folds them together, and then a root spelled `…/rungate/` is
190
+ // refused with "which is a symlink to …/rungate" — a false statement
191
+ // about the operator's disk, offering as a remedy the path they just
192
+ // typed with one character removed. Found by the AI review of PR #1150.
193
+ //
194
+ // Both still refuse. A non-normalised root breaks the comparison in
195
+ // ship.js just as surely: it builds `${root}/.claude/worktrees/` and a
196
+ // trailing slash makes that a doubled separator no git-reported path
197
+ // matches. The verdict is the same; the sentence is not.
198
+ const normalised = resolve(given);
199
+ const why =
200
+ canonical !== normalised
201
+ ? `it is a symlink to ${safe(canonical)} — one directory under two names`
202
+ : `it is not a normalised path; it names ${safe(canonical)} with redundant or relative segments`;
203
+
204
+ return {
205
+ reading: "NON_CANONICAL_ROOT",
206
+ refusal:
207
+ `${name} was given as ${safe(given)}, and ${why}. ` +
208
+ "`git rev-parse --show-toplevel` resolves symlinks and every path git reports is canonical, " +
209
+ "but `collectDestination` in workflows/ship.js compares roots as STRINGS and cannot resolve " +
210
+ "anything: the sandbox has no filesystem (#69). So this run would refuse its own agent " +
211
+ `worktrees, and the refusal would read as "this directory is not yours". Relaunch with ` +
212
+ `${name} set to ${safe(canonical)}`,
213
+ };
214
+ }
215
+ return null;
216
+ }
217
+
218
+ export function launchBaseReading(
219
+ cwd: string,
220
+ projectRoot: string,
221
+ harnessRoot?: string,
222
+ ): LaunchBaseReading {
135
223
  // RAW for probing, REDACTED for reporting, and the two are never mixed
136
224
  // up: `git -C` must receive the real path, and a redacted one would send
137
225
  // the probe to a directory that does not exist — which resolves to
138
226
  // CWD_NOT_A_REPO and reads exactly like the finding this module exists
139
227
  // to report. Everything returned is built from `here`; everything handed
140
228
  // to git comes from `raw`.
141
- const raw = { cwd: String(cwd ?? ""), projectRoot: String(projectRoot ?? "") };
229
+ const raw = {
230
+ cwd: String(cwd ?? ""),
231
+ projectRoot: String(projectRoot ?? ""),
232
+ // Absent stays absent rather than becoming "": the canonicality check
233
+ // skips a root it was not given, and an empty string would be
234
+ // indistinguishable from a caller that passed one and got it wrong.
235
+ harnessRoot: harnessRoot === undefined ? undefined : String(harnessRoot ?? ""),
236
+ };
142
237
  // Redacted ON THE READING, not at each call site. `check-launch-base.ts`
143
238
  // serialises the whole object, and a caller that had to remember to
144
239
  // redact is a control one caller will forget.
@@ -183,7 +278,31 @@ export function launchBaseReading(cwd: string, projectRoot: string): LaunchBaseR
183
278
  };
184
279
  }
185
280
 
186
- if (cwdTop === rootTop) return { ...here, reading: "SAME_CHECKOUT" };
281
+ if (cwdTop === rootTop) {
282
+ // #1129 refines THIS answer and only this one, and the position is the
283
+ // whole point. `--show-toplevel` resolves symlinks, so two spellings of
284
+ // one directory arrive here as one toplevel and the comparison above
285
+ // cannot tell them apart — the unresolved string then travels on to
286
+ // `collectDestination`, which compares it by `startsWith` against paths
287
+ // git has already resolved.
288
+ //
289
+ // It is NOT checked earlier. A symlinked root is the mildest thing that
290
+ // can be wrong here: CWD_NOT_A_REPO, DIFFERENT_REPO and
291
+ // DIFFERENT_CHECKOUT are all worse and all more urgent, and a
292
+ // canonicality check placed above them MASKS them. Measured — on macOS
293
+ // `tmpdir()` is `/var/folders/...`, itself a symlink to `/private/var`,
294
+ // so every fixture built under it is non-canonical by accident: the
295
+ // early placement turned 15 cases in this module's own suite into
296
+ // NON_CANONICAL_ROOT, on macOS only, while Linux CI (`tmpdir()` is
297
+ // `/tmp`, not a link) stayed green. A check that changes which defect
298
+ // you are told about, per platform, is worse than the defect.
299
+ const nonCanonical = nonCanonicalRoots({
300
+ projectRoot: raw.projectRoot,
301
+ harnessRoot: raw.harnessRoot,
302
+ });
303
+ if (nonCanonical) return { ...here, ...nonCanonical };
304
+ return { ...here, reading: "SAME_CHECKOUT" };
305
+ }
187
306
 
188
307
  // Different trees. Which KIND of different decides what the operator does
189
308
  // next, so the two are never collapsed.
@@ -247,7 +366,11 @@ export function launchBaseReading(cwd: string, projectRoot: string): LaunchBaseR
247
366
  * reading that clears: UNMEASURED refuses with the rest, because a check
248
367
  * that could not be run is not a check that passed.
249
368
  */
250
- export function launchBaseRefusal(cwd: string, projectRoot: string): string | null {
251
- const reading = launchBaseReading(cwd, projectRoot);
369
+ export function launchBaseRefusal(
370
+ cwd: string,
371
+ projectRoot: string,
372
+ harnessRoot?: string,
373
+ ): string | null {
374
+ const reading = launchBaseReading(cwd, projectRoot, harnessRoot);
252
375
  return reading.reading === "SAME_CHECKOUT" ? null : reading.refusal;
253
376
  }
@@ -278,6 +278,98 @@ function scanModuleRelativeJoins(raw: string): { resolved: RuntimeRead[]; unreso
278
278
  return { resolved, unresolved };
279
279
  }
280
280
 
281
+ /**
282
+ * A path an instruction STRING tells the user to run, rooted at the installed
283
+ * harness rather than at the user's own project.
284
+ *
285
+ * ## The third syntax (#1174)
286
+ *
287
+ * The two scanners above ask what published CODE reaches. Neither can see a
288
+ * path that only ever appears in a message, and a message is how this package
289
+ * hands a consumer the way out of a refusal.
290
+ *
291
+ * `REPAIR_HINT` in `lib/gate-result-protection.ts` is the documented repair
292
+ * for a corrupt `workflow-state.json`, and it names
293
+ * `<harness>/gates/orchestrator.ts`. `gates/` had **zero** entries in the
294
+ * published `0.8.0` tarball, so that command could not resolve for any npm
295
+ * consumer — and by #1137's design the guard printing it is deliberately
296
+ * unbypassable, so there was no second route out. `packageClosureViolations`
297
+ * reported the package closed the whole time, because every IMPORT and every
298
+ * READ did resolve. A detector narrower than what it detects, which is the
299
+ * shape `.claude/rules/checks-must-be-able-to-fail.md` names second and which
300
+ * #484 records one paragraph above having already made once.
301
+ *
302
+ * Shipping `hooks/` for the first time in 0.8.0 took this from two
303
+ * instructions to six. A published directory brings its instructions with it,
304
+ * so closing one packaging gap widens this surface rather than narrowing it —
305
+ * which is the argument for a check here instead of a one-time fix.
306
+ *
307
+ * ## Only harness-rooted paths count
308
+ *
309
+ * `lib/typescript-project.ts` emits `bun scripts/typecheck.ts`, and that
310
+ * `scripts/` is the CONSUMER's, where the scaffold writes one. Resolving a
311
+ * bare relative path against this package would invent a defect in the
312
+ * commonest kind of instruction we emit. So the path has to say it means the
313
+ * harness: an explicit `$HARNESS_ROOT`/`<harness>` anchor, or the `./` of a
314
+ * `bun -e` one-liner, which these hints run from the harness root.
315
+ */
316
+ export interface InstructionPath {
317
+ /** How the string named the harness root, for the violation message. */
318
+ anchor: string;
319
+ /** Package-relative path the instruction names. */
320
+ path: string;
321
+ }
322
+
323
+ /** Spellings of "the installed harness package root" inside a message. */
324
+ const HARNESS_ROOT_ANCHOR =
325
+ /(\$\{HARNESS_ROOT\}|\$HARNESS_ROOT|<harness>)\/((?:[\w.-]+\/)*[\w.-]+\.\w+)/g;
326
+
327
+ /**
328
+ * The import specifier of a `bun -e` one-liner — a `./`-rooted path after the
329
+ * `from` keyword. Quotes are optional here because the hint is itself inside
330
+ * a string, so they arrive backslash-escaped as often as not.
331
+ *
332
+ * Spelled without an example of the thing it matches on purpose:
333
+ * `relativeImports` above scans RAW source, so a docstring quoting a real
334
+ * specifier is read as a phantom import and the mutation battery in
335
+ * `test/package-closure.test.ts` aborts rewriting it. Found by that battery.
336
+ */
337
+ const BUN_EVAL_SPECIFIER = /from\s*\\?["']?\.\/((?:[\w.-]+\/)*[\w.-]+\.\w+)/g;
338
+
339
+ export function instructionPaths(raw: string): InstructionPath[] {
340
+ // Comments out, string and template text kept. `runtimeReads` does the same
341
+ // thing for the same reason, and here the live tree proves it is needed in
342
+ // both directions: `lib/shell-path-interpolation.ts` explains shell quoting
343
+ // with a `${HARNESS_ROOT}/scripts/x.ts` example in a DOCSTRING, which a
344
+ // scanner reading raw source reports as a shipped instruction; and three of
345
+ // the six real instructions are template literals, which `keepStringContents`
346
+ // alone blanks. Either half alone gets the live tree wrong.
347
+ const source = stripStringsAndComments(raw, {
348
+ keepStringContents: true,
349
+ keepTemplateText: true,
350
+ });
351
+ const found: InstructionPath[] = [];
352
+ let m: RegExpExecArray | null;
353
+
354
+ HARNESS_ROOT_ANCHOR.lastIndex = 0;
355
+ while ((m = HARNESS_ROOT_ANCHOR.exec(source)) !== null) {
356
+ found.push({ anchor: m[1], path: m[2] });
357
+ }
358
+
359
+ // Scoped to the line carrying the `bun -e`, not to `./` generally: a bare
360
+ // `./` in any other message is relative to wherever the user is standing,
361
+ // and this package cannot say where that is.
362
+ for (const line of source.split("\n")) {
363
+ if (!line.includes("bun -e")) continue;
364
+ BUN_EVAL_SPECIFIER.lastIndex = 0;
365
+ while ((m = BUN_EVAL_SPECIFIER.exec(line)) !== null) {
366
+ found.push({ anchor: "bun -e .", path: m[1] });
367
+ }
368
+ }
369
+
370
+ return found;
371
+ }
372
+
281
373
  /**
282
374
  * The single binding. `test/package-closure.test.ts` builds a mutant of this
283
375
  * module with the body short-circuited to `return []` and asserts the suite
@@ -344,6 +436,28 @@ export function packageClosureViolations(root: string, published: Set<string>):
344
436
  }
345
437
  }
346
438
 
439
+ // #1174. An instruction naming a path the tarball does not carry is the
440
+ // same closure property again, in the one syntax neither scanner above
441
+ // can reach — so it is answered here, against the same `published` set,
442
+ // rather than in a fourth checker that could drift from these three.
443
+ for (const { anchor, path } of instructionPaths(source)) {
444
+ // Absent from the working tree too is a different bug — a stale or
445
+ // illustrative path — and not this check's business. Same rule the
446
+ // import walker below applies, and on the live tree it is what keeps
447
+ // `$HARNESS_ROOT/scripts/x.ts` out of the violation list.
448
+ if (!existsSync(join(root, path))) continue;
449
+
450
+ const isPublished = statSync(join(root, path)).isDirectory()
451
+ ? [...published].some(p => p.startsWith(`${path}/`))
452
+ : published.has(path);
453
+
454
+ if (!isPublished) {
455
+ violations.push(
456
+ `${file} instructs the user to run ${anchor}/${path}, which files[] does not publish`,
457
+ );
458
+ }
459
+ }
460
+
347
461
  for (const specifier of relativeImports(source)) {
348
462
  const target = resolve(dirname(join(root, file)), specifier);
349
463
  const targetRel = relative(root, target);
package/lib/paths.ts CHANGED
@@ -33,6 +33,56 @@ const FIXES =
33
33
  "Either set HARNESS_ROOT to the root of the run, " +
34
34
  "or pass the root you mean explicitly: harnessRootFor(root).";
35
35
 
36
+ /**
37
+ * One spelling of a root, with symlinks followed (#1129).
38
+ *
39
+ * `resolve()` normalises `..` and relative segments and stops there — it does
40
+ * NOT follow symlinks, so two names for one directory survive it as two
41
+ * strings. That is only a cosmetic difference until something compares roots
42
+ * by `startsWith`, and `collectDestination` in `workflows/ship.js` does
43
+ * exactly that. It has no choice: `workflows/*.js` runs in a sandbox with no
44
+ * module loading and no `process` or `Bun` (#69, enforced by
45
+ * `scripts/validate-workflow.ts`), so `realpathSync` is unreachable from that
46
+ * file. A string compare and a realpath compare agree on every already-
47
+ * canonical path and disagree the moment one side is reached through a link.
48
+ *
49
+ * This repository is the live instance: it is reachable under both its
50
+ * canonical name and a symlink named after the repo, and the symlinked one is
51
+ * the name a person types. A run launched with it would compare an unresolved
52
+ * root against a resolved worktree path and refuse a directory that is in
53
+ * fact inside it.
54
+ *
55
+ * So the resolution happens HERE, at the one producer, rather than at the
56
+ * hundreds of sites that consume a root. Every consumer then gets one
57
+ * spelling and the sandboxed comparison is left with nothing to disagree
58
+ * about.
59
+ *
60
+ * An unresolvable root THROWS rather than falling back to `resolve()`. The
61
+ * fallback is the tempting line and it is the bug: a root that resolves to
62
+ * nothing would be compared against happily, and the run would refuse its own
63
+ * worktrees for a reason naming neither the root nor the fact that it was
64
+ * never checked. Unknown is not canonical.
65
+ */
66
+ export function canonicalRoot(root: string): string {
67
+ if (!root || !root.trim()) {
68
+ throw new Error(
69
+ `canonicalRoot() was given an empty root at ${callSite()}. ` +
70
+ "An explicit root is the caller naming the tree it means; there is no tree to fall back to.",
71
+ );
72
+ }
73
+ const normalised = resolve(root);
74
+ try {
75
+ return realpathSync(normalised);
76
+ } catch (e: any) {
77
+ throw new Error(
78
+ `canonicalRoot() cannot be resolved for ${normalised} (from ${callSite()}): ${e?.message || e}. ` +
79
+ "A root that does not resolve is unmeasured, not canonical — it is refused here rather than " +
80
+ "passed through unresolved, because a comparison against it would silently disagree with every " +
81
+ "path git reports (#1129).",
82
+ );
83
+ }
84
+ }
85
+
36
86
  /**
37
87
  * The harness root the CALLER means, stated rather than inferred (#105).
38
88
  *
@@ -41,6 +91,24 @@ const FIXES =
41
91
  * tree it is pointed at. For those, "whichever tree this module happens to sit
42
92
  * in" is not a default, it is a coin flip between the run's root and the
43
93
  * worktree the agent is editing, and the losing side gets written to.
94
+ *
95
+ * Canonical since #1129, and that is a behaviour change worth stating: this
96
+ * used to return `resolve(root)`, which left a symlinked spelling intact for
97
+ * every downstream comparison.
98
+ *
99
+ * A root that does not EXIST is still returned normalised, and that
100
+ * asymmetry with `canonicalRoot()` is deliberate rather than an oversight.
101
+ * This is a path helper, not a gate: its callers name a tree, and naming one
102
+ * that is not on this disk is legitimate — `scripts/sync-spec-tests.ts`
103
+ * takes a root from `argv[2]` and `gates/run-gate.ts` takes one from
104
+ * `HARNESS_ROOT`, and both are exercised with trees that do not exist.
105
+ * Throwing here would turn "you named a tree I cannot see" into a crash in
106
+ * the middle of unrelated work.
107
+ *
108
+ * The refusal the acceptance asks for lives where the DECISION is made
109
+ * instead: `launchBaseReading` reads an unresolvable root as UNMEASURED and
110
+ * refuses the launch. That is the one place a root being unreadable should
111
+ * stop something, and it is reached before any agent is spawned.
44
112
  */
45
113
  export function harnessRootFor(root: string): string {
46
114
  if (!root || !root.trim()) {
@@ -49,7 +117,11 @@ export function harnessRootFor(root: string): string {
49
117
  "An explicit root is the caller naming the tree it means; there is no tree to fall back to.",
50
118
  );
51
119
  }
52
- return resolve(root);
120
+ try {
121
+ return canonicalRoot(root);
122
+ } catch {
123
+ return resolve(root);
124
+ }
53
125
  }
54
126
 
55
127
  export interface ImplicitRootOptions {
@@ -175,10 +247,31 @@ export function paiRoot(): string {
175
247
  return process.env.PAI_ROOT || paiHomeDir();
176
248
  }
177
249
 
250
+ /**
251
+ * The run store's root — every run's `workflow-state.json` lives one level
252
+ * under this.
253
+ *
254
+ * Extracted from `workDir` rather than written beside it (#545). The
255
+ * expression was about to have a second author: `lib/intake-sources.ts` mines
256
+ * gate refusals out of the store and needs the ROOT, not a per-slug path, and
257
+ * `lib/gap-scanner.ts` already assembles its own copy. Two places spelling one
258
+ * location is the shape `paiHomeDir`'s own docstring above records going
259
+ * wrong — same anonymous expression, two meanings, nothing in the output
260
+ * saying which.
261
+ *
262
+ * `process.env.HOME || ""` is kept exactly as it was. It is not what I would
263
+ * write — it degrades to a relative `.rungate` when HOME is unset, which is
264
+ * the defect `paiHomeDir` was fixed for — but changing it here would alter
265
+ * `workDir`'s behaviour under an empty HOME, which is the configuration the
266
+ * intake tests deliberately run in. Noted rather than silently repaired.
267
+ */
268
+ export function workStoreRoot(): string {
269
+ return process.env.RUNGATE_WORK_DIR || join(process.env.HOME || "", ".rungate");
270
+ }
271
+
178
272
  export function workDir(slug: string): string {
179
273
  if (slug.includes('..') || slug.startsWith('/')) throw new Error(`Invalid slug: ${slug}`);
180
- const base = process.env.RUNGATE_WORK_DIR || join(process.env.HOME || "", ".rungate");
181
- return join(base, slug);
274
+ return join(workStoreRoot(), slug);
182
275
  }
183
276
 
184
277
  export function gateSaltPath(): string {
@@ -184,7 +184,7 @@ export function acListBlock(acs: readonly DecomposedAc[]): string {
184
184
  export function phase2AcsCommand(harnessRoot: string, workDir: string, acs: readonly DecomposedAc[]): string {
185
185
  const payload = JSON.stringify(acs.map(a => ({ id: a.id, statement: a.statement, specElement: a.specElement })));
186
186
  return (
187
- `cd ${harnessRoot} && bun -e 'require("fs").writeFileSync(process.argv[1], process.argv[2])' ` +
187
+ `bun --cwd ${shellSingleQuote(harnessRoot)} -e 'require("fs").writeFileSync(process.argv[1], process.argv[2])' ` +
188
188
  `${workDir}/phase2-acs.json ${shellSingleQuote(payload)}`
189
189
  );
190
190
  }