rungate 0.7.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 (63) 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 +29 -0
  36. package/lib/bash-write-guard.ts +373 -0
  37. package/lib/branch-cleanup.ts +279 -7
  38. package/lib/config-trackable.ts +9 -0
  39. package/lib/distribution-currency.ts +55 -5
  40. package/lib/failure-intake.ts +7 -1
  41. package/lib/gate-enforcement.ts +222 -28
  42. package/lib/gate-names.ts +72 -0
  43. package/lib/gate-result-protection.ts +427 -0
  44. package/lib/intake-sources.ts +380 -0
  45. package/lib/late-env-spawn.ts +331 -0
  46. package/lib/launch-base.ts +128 -5
  47. package/lib/paths.ts +96 -3
  48. package/lib/phase2-decomposition.ts +1 -1
  49. package/lib/published-artifact.ts +162 -18
  50. package/lib/sc-id-cross-tree.ts +84 -8
  51. package/lib/scaffold/ai-review-findings.ts +7 -1
  52. package/lib/scaffold/ai-review-step.ts +861 -116
  53. package/lib/scaffold/defaults.ts +82 -1
  54. package/lib/scaffold/steps.ts +436 -44
  55. package/lib/security-verdict.ts +1 -1
  56. package/lib/shell-path-interpolation.ts +594 -0
  57. package/lib/text-dependents.ts +875 -0
  58. package/lib/workflow-security.ts +29 -0
  59. package/lib/workflow-taint.ts +732 -0
  60. package/lib/worktree-cleanup.ts +65 -38
  61. package/lib/worktree-repo.ts +32 -2
  62. package/package.json +3 -1
  63. package/scripts/check-installed-hook-currency.ts +825 -0
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Spawn sites that may be relying on an environment Bun does not pass on.
3
+ *
4
+ * ## The runtime divergence, with its control
5
+ *
6
+ * Under Bun, a `process.env` write made AFTER process start does not reach a
7
+ * child spawned with no explicit `env` option. Under Node it does. Measured
8
+ * 2026-10-22, Bun 1.3.14 and Node v26.3.0, same script and same machine:
9
+ *
10
+ * ```ts
11
+ * process.env.RG_LATE_PROBE = "set-in-process";
12
+ * execFileSync("printenv", ["RG_LATE_PROBE"], { encoding: "utf8" });
13
+ * ```
14
+ *
15
+ * | runtime | no `env:` option | `env: { ...process.env }` |
16
+ * |---|---|---|
17
+ * | `bun probe.ts` | **child does not have it** | `"set-in-process"` |
18
+ * | `node probe.ts` | `"set-in-process"` | `"set-in-process"` |
19
+ *
20
+ * **The Node row is why this is a runtime divergence and not a bad probe.**
21
+ * Without it the next reader reasonably concludes that `printenv` or the
22
+ * variable name was at fault; the only difference between the two rows is
23
+ * which binary ran the identical file. It applies to `Bun.spawnSync` too,
24
+ * not only to the `node:child_process` shims — measured separately, both
25
+ * report the process's STARTUP value.
26
+ *
27
+ * Note the second column: the spread is not ceremony. `{ ...process.env }`
28
+ * reads the live object, so an explicit env is both the diagnosis and the
29
+ * whole fix.
30
+ *
31
+ * Anything scaffolded onto Bun inherits this, so it is worth stating
32
+ * wherever this harness tells a consumer how to write a test that spawns.
33
+ *
34
+ * ## Why a scan and not a list
35
+ *
36
+ * The failure is silent. The child takes its default path, and the assertion
37
+ * usually still passes — for a reason unrelated to the feature under test.
38
+ * Found on #1048 only because a mutation row came back 4 where 5 was
39
+ * predicted; the case was green on every tree, including the one with the
40
+ * feature deleted.
41
+ *
42
+ * So the population is DERIVED, never enumerated. A hand-written list of
43
+ * today's members is written by the person who just fixed them, which means
44
+ * it cannot fail on the day it ships and nothing adds tomorrow's member to
45
+ * it. `lateEnvSpawnSites` recomputes the population from the tree on every
46
+ * run, and a new un-exempted instance is red with no list to update.
47
+ *
48
+ * ## What a member is, and what it is not
49
+ *
50
+ * A member is a spawn call, in a test file that ALSO writes `process.env`,
51
+ * which passes no `env:` option. That is a shape worth looking at and not a
52
+ * defect: an env write and a spawn in one file does not mean the child reads
53
+ * the variable. Plenty of writes are consumed in-process, which works fine.
54
+ *
55
+ * The per-site question is **does this child read the variable this test just
56
+ * set?** A site where the answer is no says so in a `late-env-ok:` comment,
57
+ * and the reason has to be long enough to be a reason — see `MIN_REASON`.
58
+ *
59
+ * Comments and string literals are blanked before matching, via
60
+ * `lib/strip-js-comments.ts` with `blankLiterals`. Two of the eight files
61
+ * #1096 listed by hand are in it because a `grep` counted `execSync` inside a
62
+ * comment and a third because it matched `process.env.X === "1"`, which is a
63
+ * READ. A scanner that reads raw source cannot tell a call from a sentence
64
+ * about a call — `.claude/rules/checks-must-be-able-to-fail.md`.
65
+ *
66
+ * Issue: #1096. Found during #1048 (PR #1090).
67
+ */
68
+
69
+ import { readdirSync, readFileSync, statSync } from "fs";
70
+ import { join, relative, sep } from "path";
71
+
72
+ import { stripJsComments } from "./strip-js-comments";
73
+
74
+ /**
75
+ * How long a `late-env-ok:` reason has to be.
76
+ *
77
+ * A marker nobody has to justify is a marker everybody applies, which is the
78
+ * exemption list this scan exists to avoid wearing a different hat.
79
+ * `lib/gate-check-audit.ts` sets the same kind of floor at 80 for a check
80
+ * waiver; this one is lower because the question here is narrower — name the
81
+ * variable and say why the child does not read it.
82
+ */
83
+ export const MIN_REASON = 40;
84
+
85
+ /** The marker that exempts one site, followed by why. */
86
+ export const EXEMPT_MARKER = "late-env-ok:";
87
+
88
+ /**
89
+ * A write to `process.env.<CAPS>`, excluding comparisons.
90
+ *
91
+ * `=(?![=>])` is the whole discrimination: `process.env.X === "1"` is a read,
92
+ * and `process.env.X =>` cannot occur but costs nothing to exclude.
93
+ */
94
+ const ENV_WRITE = /\bprocess\.env\.([A-Z][A-Z0-9_]*)\s*=(?![=>])/g;
95
+
96
+ /** `delete process.env.X` changes the environment just as a write does. */
97
+ const ENV_DELETE = /\bdelete\s+process\.env\.([A-Z][A-Z0-9_]*)/g;
98
+
99
+ /** Every way this repository starts a child process. */
100
+ const SPAWN = /\b(?:Bun\.spawnSync|Bun\.spawn|spawnSync|execFileSync|execSync|spawn|execFile|exec)\s*\(/g;
101
+
102
+ /**
103
+ * An explicit `env` option, in either spelling.
104
+ *
105
+ * The shorthand half is load-bearing and was added after the first run read
106
+ * `test/sync-spec-tests-paths.test.ts:225` as bare. That site builds
107
+ * `const env = { ...process.env }; delete env.HARNESS_ROOT;` and passes
108
+ * `{ cwd, env, … }` — which is not merely explicit, it is the most careful
109
+ * site in the population. A detector that only knew `env:` would have
110
+ * reported the one author who got this exactly right.
111
+ *
112
+ * `(?<![.\w])` keeps `process.env }` out of the shorthand arm: a spread of
113
+ * the whole environment AS the options object is not an env option, and
114
+ * without the guard every `{ ...process.env }` would exempt its own call.
115
+ */
116
+ const ENV_OPTION = /(?<![.\w])env\s*(?::|(?=[,}]))/;
117
+
118
+ export interface LateEnvSite {
119
+ /** Repo-relative, POSIX separators, so a violation message is stable. */
120
+ file: string;
121
+ line: number;
122
+ callee: string;
123
+ /** The variables this file writes late. Named, so the reader can judge. */
124
+ vars: string[];
125
+ /** The stated reason this site does not need an explicit env, if any. */
126
+ exemption: string | null;
127
+ }
128
+
129
+ export class UnreadableScanError extends Error {
130
+ constructor(message: string) {
131
+ super(message);
132
+ this.name = "UnreadableScanError";
133
+ }
134
+ }
135
+
136
+ function testFiles(root: string): string[] {
137
+ const out: string[] = [];
138
+ const walk = (dir: string) => {
139
+ let entries: string[];
140
+ try {
141
+ entries = readdirSync(dir);
142
+ } catch {
143
+ return;
144
+ }
145
+ for (const e of entries) {
146
+ const p = join(dir, e);
147
+ if (statSync(p).isDirectory()) walk(p);
148
+ else if (p.endsWith(".test.ts")) out.push(p);
149
+ }
150
+ };
151
+ walk(join(root, "test"));
152
+ return out.sort();
153
+ }
154
+
155
+ /**
156
+ * The argument list of a call whose `(` is at `open`, or null if unbalanced.
157
+ *
158
+ * Counted over the literal-blanked view, which is the only view a bracket
159
+ * matcher may count over: a `)` inside a prompt string is text.
160
+ */
161
+ function argumentList(blanked: string, open: number): string | null {
162
+ let depth = 0;
163
+ for (let i = open; i < blanked.length; i++) {
164
+ const c = blanked[i];
165
+ if (c === "(") depth++;
166
+ else if (c === ")") {
167
+ depth--;
168
+ if (depth === 0) return blanked.slice(open + 1, i);
169
+ }
170
+ }
171
+ return null;
172
+ }
173
+
174
+ /**
175
+ * The contiguous comment block immediately above line `line` (1-based),
176
+ * plus that line itself so a trailing marker counts.
177
+ */
178
+ function commentBlockAbove(lines: string[], line: number): string {
179
+ /** Only the comment part of a line, so a reason cannot be padded by code. */
180
+ const commentPart = (raw: string): string | null => {
181
+ const t = raw.trim();
182
+ if (t.startsWith("//")) return t.slice(2).trim();
183
+ if (t.startsWith("*/")) return t.slice(2).replace(/^\*+/, "").trim();
184
+ if (t.startsWith("*")) return t.replace(/^\*+/, "").replace(/\*\/\s*$/, "").trim();
185
+ if (t.startsWith("/*")) return t.slice(2).replace(/^\*+/, "").replace(/\*\/\s*$/, "").trim();
186
+ return null;
187
+ };
188
+
189
+ const block: string[] = [];
190
+ for (let i = line - 2; i >= 0; i--) {
191
+ const part = commentPart(lines[i]);
192
+ if (part === null) break;
193
+ block.unshift(part);
194
+ }
195
+ // A trailing marker on the call's own line, comment part only. Without
196
+ // this restriction the reason runs on into the call text and a
197
+ // seven-character excuse measures sixty-six — which is the floor being
198
+ // satisfied by the code it is attached to.
199
+ const own = lines[line - 1] ?? "";
200
+ const slashes = own.indexOf("//");
201
+ if (slashes !== -1) block.push(own.slice(slashes + 2).trim());
202
+ return block.join("\n");
203
+ }
204
+
205
+ /**
206
+ * Every spawn site in a test file that also changes `process.env`.
207
+ *
208
+ * Throws rather than returning `[]` when it can see no test files or no
209
+ * spawn calls at all: an empty population and a scanner that stopped working
210
+ * are the same output, and only one of them is a result
211
+ * (`.claude/rules/checks-must-be-able-to-fail.md`).
212
+ */
213
+ export interface LateEnvReading {
214
+ /** Test files walked. */
215
+ filesScanned: number;
216
+ /** Spawn calls the pattern matched, across all of them. */
217
+ spawnsExamined: number;
218
+ /** Of those, the files that also change `process.env`. */
219
+ candidateFiles: number;
220
+ /** Spawn sites inside a candidate file that pass no `env`. */
221
+ sites: LateEnvSite[];
222
+ }
223
+
224
+ /**
225
+ * The reading, with its own coverage beside it.
226
+ *
227
+ * `1 site` and `1 site of 3 examined` are the same number and different
228
+ * facts, and `1 of 900` is a third. A scan that reports a verdict reports
229
+ * how much it read — `.claude/rules/config-access.md`'s `36/426`.
230
+ */
231
+ export function lateEnvSpawnReading(root: string): LateEnvReading {
232
+ return scan(root);
233
+ }
234
+
235
+ export function lateEnvSpawnSites(root: string): LateEnvSite[] {
236
+ return scan(root).sites;
237
+ }
238
+
239
+ function scan(root: string): LateEnvReading {
240
+ const files = testFiles(root);
241
+ if (files.length === 0) {
242
+ throw new UnreadableScanError(`no test files under ${join(root, "test")} — the walk found nothing to scan`);
243
+ }
244
+
245
+ const sites: LateEnvSite[] = [];
246
+ let spawnsSeen = 0;
247
+ let candidateFiles = 0;
248
+
249
+ for (const file of files) {
250
+ const raw = readFileSync(file, "utf-8");
251
+ const blanked = stripJsComments(raw, { blankLiterals: true });
252
+
253
+ const vars = [
254
+ ...new Set([
255
+ ...[...blanked.matchAll(ENV_WRITE)].map(m => m[1]),
256
+ ...[...blanked.matchAll(ENV_DELETE)].map(m => m[1]),
257
+ ]),
258
+ ].sort();
259
+
260
+ const spawns = [...blanked.matchAll(SPAWN)];
261
+ spawnsSeen += spawns.length;
262
+ if (vars.length === 0) continue;
263
+ candidateFiles++;
264
+
265
+ const rawLines = raw.split("\n");
266
+ for (const m of spawns) {
267
+ const at = m.index!;
268
+ const open = blanked.indexOf("(", at);
269
+ const args = argumentList(blanked, open);
270
+ if (args === null) {
271
+ throw new UnreadableScanError(
272
+ `${relative(root, file)}: a spawn call's argument list is unbalanced — the scan cannot say whether it passes env`,
273
+ );
274
+ }
275
+ if (ENV_OPTION.test(args)) continue;
276
+
277
+ const line = raw.slice(0, at).split("\n").length;
278
+ // The marker is read from RAW source: `stripJsComments` preserves every
279
+ // offset but blanks the comment it lives in.
280
+ //
281
+ // The window is the comment block ATTACHED to the call — every
282
+ // contiguous comment line immediately above it, plus the call's own
283
+ // line for a trailing marker. A fixed count of lines was the first
284
+ // version and it is the wrong shape: a reason long enough to satisfy
285
+ // MIN_REASON usually needs more lines than the window allows, so the
286
+ // floor and the window would fight each other and the way to win is
287
+ // to write a shorter reason.
288
+ const window = commentBlockAbove(rawLines, line);
289
+ const marked = window.indexOf(EXEMPT_MARKER);
290
+ const reason = marked === -1
291
+ ? null
292
+ : window.slice(marked + EXEMPT_MARKER.length)
293
+ .split("\n").map(l => l.replace(/^[\s*/]+/, "")).join(" ").trim();
294
+
295
+ sites.push({
296
+ file: relative(root, file).split(sep).join("/"),
297
+ line,
298
+ callee: m[0].replace(/\s*\($/, ""),
299
+ vars,
300
+ exemption: reason,
301
+ });
302
+ }
303
+ }
304
+
305
+ if (spawnsSeen === 0) {
306
+ throw new UnreadableScanError(
307
+ "no spawn calls were found in any test file — the spawn pattern has stopped matching",
308
+ );
309
+ }
310
+ return { filesScanned: files.length, spawnsExamined: spawnsSeen, candidateFiles, sites };
311
+ }
312
+
313
+ /**
314
+ * The sites that are neither explicit nor justified.
315
+ *
316
+ * Split from the scan so a case can assert the POPULATION is non-empty while
317
+ * asserting the violations are empty. Those are different claims, and a scan
318
+ * that found nothing satisfies the second one on its own.
319
+ */
320
+ export function lateEnvSpawnViolations(root: string): string[] {
321
+ return scan(root).sites
322
+ .filter(s => s.exemption === null || s.exemption.length < MIN_REASON)
323
+ .map(s =>
324
+ `${s.file}:${s.line} ${s.callee} passes no env: option, and this file writes ` +
325
+ `${s.vars.join(", ")}. Under Bun the child will NOT see those writes. Pass ` +
326
+ `env: { ...process.env } — or, if the child does not read them, say why in a ` +
327
+ `"${EXEMPT_MARKER} <reason>" comment within three lines above the call ` +
328
+ `(at least ${MIN_REASON} characters).` +
329
+ (s.exemption === null ? "" : ` The reason given is ${s.exemption.length} characters.`),
330
+ );
331
+ }
@@ -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
  }
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
  }