rungate 0.2.1 → 0.4.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 (129) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Collect the output of N parallel agents, each working in its own worktree,
3
+ * into one tree that can be staged and committed (#81).
4
+ *
5
+ * `workflows/ship.js` flattened every agent's `filesChanged` into a single list
6
+ * and then kept only the LAST agent's `worktreePath`. `relativizePaths` only
7
+ * tries `[commitDir, PROJECT_ROOT]`, so paths belonging to the other N-1
8
+ * worktrees stayed absolute and `buildSafeGitAdd` rejected them — correctly, it
9
+ * refuses absolute paths. Eleven agents produced 37 minutes of valid work on
10
+ * run wf_5e32e9d4-dd2 and none of it could be committed.
11
+ *
12
+ * The losing information was the pairing: which files came from which worktree.
13
+ * Keep that, and collection is straightforward.
14
+ *
15
+ * Copying rather than merging branches is deliberate. The parallel path is only
16
+ * taken when the sub-issues have NON-OVERLAPPING file sets (ship.js falls back
17
+ * to a single sequential agent otherwise), so no two worktrees can claim the
18
+ * same file and there is nothing for a merge to resolve. A copy also leaves the
19
+ * agents' worktrees untouched, which matters when one sibling fails and the
20
+ * others' work has to survive.
21
+ */
22
+
23
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, realpathSync } from "fs";
24
+ import { dirname, isAbsolute, join, relative, resolve } from "path";
25
+
26
+ export interface AgentBuildResult {
27
+ worktreePath?: string;
28
+ filesChanged?: string[];
29
+ }
30
+
31
+ export interface WorktreeGroup {
32
+ worktreePath: string;
33
+ /** Paths relative to `worktreePath`. */
34
+ files: string[];
35
+ }
36
+
37
+ export interface CollectResult {
38
+ /** Paths relative to the project root — safe to hand to buildSafeGitAdd. */
39
+ copied: string[];
40
+ /** Absolute source paths an agent claimed to have written that do not exist. */
41
+ missing: string[];
42
+ }
43
+
44
+ /**
45
+ * True when `child` is at or beneath `parent`, comparing LEXICALLY.
46
+ *
47
+ * Used only to reject obviously-escaping paths before touching the disk.
48
+ * Lexical containment alone is not a security boundary: `resolve` and
49
+ * `relative` never consult the filesystem, so `wt/lib/a.ts` is "inside" the
50
+ * worktree by string even when `wt/lib` is a symlink to somewhere else
51
+ * entirely. `realIsInside` is the check that actually decides.
52
+ */
53
+ function isInside(parent: string, child: string): boolean {
54
+ const rel = relative(resolve(parent), resolve(child));
55
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
56
+ }
57
+
58
+ /**
59
+ * True when `child`'s REAL path is at or beneath `parent`'s real path.
60
+ *
61
+ * `child` may not exist yet (a destination), so walk up to the deepest
62
+ * ancestor that does, resolve that, and re-attach the remainder. This is what
63
+ * catches a symlinked intermediate directory, which lexical comparison cannot.
64
+ */
65
+ function realIsInside(parent: string, child: string): boolean {
66
+ let realParent: string;
67
+ try {
68
+ realParent = realpathSync(resolve(parent));
69
+ } catch {
70
+ return false;
71
+ }
72
+
73
+ let probe = resolve(child);
74
+ const tail: string[] = [];
75
+ while (!existsSync(probe)) {
76
+ const up = dirname(probe);
77
+ if (up === probe) return false; // walked to the filesystem root
78
+ tail.unshift(relative(up, probe));
79
+ probe = up;
80
+ }
81
+
82
+ let realChild: string;
83
+ try {
84
+ realChild = join(realpathSync(probe), ...tail);
85
+ } catch {
86
+ return false;
87
+ }
88
+
89
+ const rel = relative(realParent, realChild);
90
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
91
+ }
92
+
93
+ /**
94
+ * Pair each agent's reported files with the worktree it reported them from,
95
+ * converting to worktree-relative paths and discarding anything that escapes.
96
+ *
97
+ * An agent naming a file outside its own worktree is either confused or
98
+ * hostile. Either way, copying it would write somewhere nobody authorised, so
99
+ * it is dropped here rather than being handed to the copy step.
100
+ */
101
+ /**
102
+ * Remove a trailing parenthesised annotation from a reported path (#279).
103
+ *
104
+ * Agents describe what they did to a file as they list it:
105
+ *
106
+ * "lib/strip-js-comments.ts (NEW, 178 lines)"
107
+ * "test/spec-compliance.test.ts (MOD: +SHIP_CODE at L8-28)"
108
+ *
109
+ * Only a trailing ` (...)` is an annotation. Splitting on the first space
110
+ * instead would mangle `docs/my notes.md` into a miss, which trades a silent
111
+ * drop for a silent rejection — the same bug facing the other way.
112
+ */
113
+ export function stripPathAnnotation(entry: string): string {
114
+ const m = entry.match(/^(.*?)\s+\([^()]*\)$/);
115
+ return m ? m[1] : entry;
116
+ }
117
+
118
+ export function groupFilesByWorktree(results: AgentBuildResult[]): WorktreeGroup[] {
119
+ const groups: WorktreeGroup[] = [];
120
+
121
+ for (const r of results || []) {
122
+ const wt = (r?.worktreePath || "").trim();
123
+ // No worktree means nothing can be resolved against it. Silently keeping
124
+ // the files would reintroduce the absolute paths that caused #81.
125
+ if (!wt) continue;
126
+
127
+ const files: string[] = [];
128
+ for (const raw of r.filesChanged || []) {
129
+ const p = String(raw).trim();
130
+ if (!p) continue;
131
+ const abs = isAbsolute(p) ? p : join(wt, p);
132
+ if (!isInside(wt, abs)) continue;
133
+ const rel = relative(wt, abs);
134
+ if (rel) files.push(rel);
135
+ }
136
+ if (files.length > 0) groups.push({ worktreePath: wt, files });
137
+ }
138
+
139
+ return groups;
140
+ }
141
+
142
+ /**
143
+ * Copy each group's files from its worktree into `projectRoot`.
144
+ *
145
+ * Throws rather than skipping when a destination would land outside
146
+ * `projectRoot`. A traversal here is not a path to sanitise away quietly — it
147
+ * means the inputs cannot be trusted, and the caller must abort the commit
148
+ * rather than proceed with a partially-collected tree.
149
+ */
150
+ export function collectWorktreeFiles(
151
+ groups: WorktreeGroup[],
152
+ projectRoot: string,
153
+ allowedWorktrees: string[],
154
+ ): CollectResult {
155
+ const copied: string[] = [];
156
+ const missing: string[] = [];
157
+
158
+ // `allowedWorktrees` is required, and an empty list authorises nothing.
159
+ // Making it optional with an "allow anything" default would restore exactly
160
+ // the hole it exists to close, in the quietest possible way.
161
+ const allowed = new Set<string>();
162
+ for (const w of allowedWorktrees || []) {
163
+ try {
164
+ allowed.add(realpathSync(resolve(w)));
165
+ } catch {
166
+ // A worktree the caller named but that does not exist authorises nothing.
167
+ }
168
+ }
169
+
170
+ for (const group of groups) {
171
+ // Every other check in this function validates a path against
172
+ // `group.worktreePath`. That value arrives from `agentResults` and is
173
+ // agent-reported, so until it is checked the containment root is chosen by
174
+ // the same party the checks defend against: `worktreePath: "/"` makes every
175
+ // file on the machine "inside the worktree". The destination stays within
176
+ // the project root, so the payload is not a write outside — it is a read of
177
+ // anything on disk INTO the repo, which the caller then stages, commits and
178
+ // pushes. Authorise the root against the caller's list before trusting it.
179
+ let realWorktree: string;
180
+ try {
181
+ realWorktree = realpathSync(resolve(group.worktreePath));
182
+ } catch {
183
+ throw new Error(`refusing an unresolvable worktree path: ${group.worktreePath}`);
184
+ }
185
+ if (!allowed.has(realWorktree)) {
186
+ throw new Error(`refusing a worktree the caller did not authorise: ${group.worktreePath}`);
187
+ }
188
+
189
+ for (const rawRel of group.files) {
190
+ // #279: an agent may annotate the path it reports — run wf_ea3e428f-64f
191
+ // wrote "lib/strip-js-comments.ts (NEW, 178 lines)" for all five of its
192
+ // files, and joining that whole string onto the worktree missed every
193
+ // one of them. 926 lines were dropped and the script exited zero.
194
+ //
195
+ // The literal entry is tried FIRST so a real path that happens to end in
196
+ // parentheses keeps working, and a genuinely missing file stays missing
197
+ // after stripping rather than becoming a second silent drop.
198
+ const stripped = stripPathAnnotation(rawRel);
199
+ const rel =
200
+ stripped !== rawRel && !existsSync(resolve(group.worktreePath, rawRel))
201
+ ? stripped
202
+ : rawRel;
203
+
204
+ const dest = resolve(projectRoot, rel);
205
+ if (!isInside(projectRoot, dest)) {
206
+ throw new Error(`refusing to write outside the project root: ${rel}`);
207
+ }
208
+
209
+ const src = resolve(group.worktreePath, rel);
210
+
211
+ // lstat, not stat: it describes the link itself rather than its target.
212
+ // copyFileSync FOLLOWS links, so a source symlink would copy a file the
213
+ // agent was never given — lexical containment cannot see that, because
214
+ // the path sits inside the worktree by string.
215
+ const st = lstatSync(src, { throwIfNoEntry: false });
216
+ if (!st) {
217
+ missing.push(src);
218
+ continue;
219
+ }
220
+ if (st.isSymbolicLink()) {
221
+ throw new Error(`refusing to collect a symlink: ${rel}`);
222
+ }
223
+ if (!st.isFile()) {
224
+ missing.push(src);
225
+ continue;
226
+ }
227
+ // A hard link defeats every check above: lstat reports a regular file and
228
+ // the path genuinely is inside the worktree, because a hard link has no
229
+ // target path to resolve — it is a second name for the same inode. Only
230
+ // the link count gives it away. Source files written by an agent have
231
+ // one name; anything else is reaching for a file it was not given.
232
+ if (st.nlink > 1) {
233
+ throw new Error(`refusing to collect a hard link: ${rel}`);
234
+ }
235
+ // Catches a symlinked intermediate directory (`wt/lib` -> elsewhere),
236
+ // which the lstat above cannot see because the leaf is a real file.
237
+ if (!realIsInside(group.worktreePath, src)) {
238
+ throw new Error(`refusing to read outside the worktree: ${rel}`);
239
+ }
240
+
241
+ // Same path on both sides: the agent worked directly in the project root
242
+ // (the single-agent path). copyFileSync onto itself would truncate.
243
+ if (src !== dest) {
244
+ // Check BEFORE creating anything. `mkdirSync(recursive)` used to run
245
+ // first, so a pre-existing symlink in the project root meant the
246
+ // directories had already been created outside it by the time the
247
+ // check threw — the refusal was correct and still left a side effect
248
+ // where it had no business writing. realIsInside walks up to the
249
+ // deepest existing ancestor, so it answers correctly for a path that
250
+ // does not exist yet.
251
+ if (!realIsInside(projectRoot, dirname(dest))) {
252
+ throw new Error(`destination directory escapes the project root: ${rel}`);
253
+ }
254
+ mkdirSync(dirname(dest), { recursive: true });
255
+ // And again after: mkdir resolved and created real directories, but a
256
+ // symlinked component could have been introduced between the two.
257
+ if (!realIsInside(projectRoot, dirname(dest))) {
258
+ throw new Error(`destination directory escapes the project root: ${rel}`);
259
+ }
260
+ // The leaf can be a symlink even when its directory is clean, and
261
+ // copyFileSync writes THROUGH a link to whatever it targets. Checking
262
+ // the directory alone would still let a planted link in the project
263
+ // root overwrite a file outside it.
264
+ const dst = lstatSync(dest, { throwIfNoEntry: false });
265
+ if (dst?.isSymbolicLink()) {
266
+ throw new Error(`refusing to overwrite a symlink in the project root: ${rel}`);
267
+ }
268
+ if (dst && !dst.isFile()) {
269
+ throw new Error(`refusing to overwrite a non-regular file: ${rel}`);
270
+ }
271
+ // Same inode trick on the destination side: copyFileSync writes
272
+ // through a hard link into whatever else shares the inode.
273
+ if (dst && dst.nlink > 1) {
274
+ throw new Error(`refusing to overwrite a hard link: ${rel}`);
275
+ }
276
+ copyFileSync(src, dest);
277
+ }
278
+ copied.push(relative(projectRoot, dest));
279
+ }
280
+ }
281
+
282
+ return { copied: [...new Set(copied)], missing };
283
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Worktree isolation — creates and cleans up git worktrees
3
+ * for test-brief agent spawning.
4
+ *
5
+ * Agent runs in a git worktree with throwaway writes.
6
+ * Transcript file persists outside the worktree for auditing.
7
+ *
8
+ * SC-407: Worktree isolation mechanism
9
+ */
10
+
11
+ import { existsSync, mkdirSync } from "fs";
12
+ import { join } from "path";
13
+ import { spawnSync } from "child_process";
14
+
15
+ export interface WorktreeConfig {
16
+ projectRoot: string;
17
+ branchPrefix?: string;
18
+ transcriptDir?: string;
19
+ }
20
+
21
+ export interface WorktreeResult {
22
+ worktreePath: string;
23
+ branchName: string;
24
+ transcriptDir: string;
25
+ cleanup: () => void;
26
+ }
27
+
28
+ /**
29
+ * Create an isolated git worktree for agent testing.
30
+ * Transcript directory is created outside the worktree so it persists after cleanup.
31
+ */
32
+ export function createWorktree(config: WorktreeConfig): WorktreeResult {
33
+ const { projectRoot, branchPrefix = "test-brief" } = config;
34
+
35
+ const id = `${branchPrefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
36
+ const branchName = id;
37
+ const worktreePath = join(projectRoot, ".claude", "worktrees", id);
38
+
39
+ // Transcript dir persists outside worktree
40
+ const transcriptDir = config.transcriptDir || join(projectRoot, ".rungate", "test-brief-transcripts", id);
41
+ if (!existsSync(transcriptDir)) {
42
+ mkdirSync(transcriptDir, { recursive: true });
43
+ }
44
+
45
+ // Create worktree
46
+ const result = spawnSync("git", ["worktree", "add", "-b", branchName, worktreePath, "HEAD"], {
47
+ cwd: projectRoot,
48
+ timeout: 30_000,
49
+ encoding: "utf-8",
50
+ });
51
+
52
+ if (result.status !== 0) {
53
+ throw new Error(`Failed to create worktree: ${result.stderr}`);
54
+ }
55
+
56
+ return {
57
+ worktreePath,
58
+ branchName,
59
+ transcriptDir,
60
+ cleanup() {
61
+ removeWorktree(projectRoot, worktreePath, branchName);
62
+ },
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Remove a git worktree and its branch.
68
+ * Internal — use WorktreeResult.cleanup() instead.
69
+ */
70
+ function removeWorktree(projectRoot: string, worktreePath: string, branchName: string): void {
71
+ spawnSync("git", ["worktree", "remove", "--force", worktreePath], {
72
+ cwd: projectRoot,
73
+ timeout: 15_000,
74
+ encoding: "utf-8",
75
+ });
76
+
77
+ spawnSync("git", ["branch", "-D", branchName], {
78
+ cwd: projectRoot,
79
+ timeout: 5_000,
80
+ encoding: "utf-8",
81
+ });
82
+ }
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Which repository is an isolated agent actually standing in? (#218)
3
+ *
4
+ * On run `wf_5e3ed885-98c` the first Marcus was spawned in a worktree of the
5
+ * repository the run targets, and the remediation Marcus in a worktree of
6
+ * ANOTHER project entirely — a different checkout, with a different `origin`,
7
+ * for an issue targeting this one. The operator had changed directory
8
+ * mid-run, and `isolation: "worktree"` is resolved by the agent runtime
9
+ * against the session's cwd rather than the workflow's `projectRoot`.
10
+ *
11
+ * (The two repositories are named in the issue and in
12
+ * `test/worktree-repo.test.ts`'s replay, not here: the harness must not name
13
+ * one of its consumers — see `test/anti.test.ts` SC-A1 and #304.)
14
+ *
15
+ * `workflows/ship.js:674` already pins `opts.cwd = PROJECT_ROOT` for every
16
+ * isolated spawn and has since 2026-09-23 — three weeks BEFORE the incident.
17
+ * The pin did not hold, so the fix cannot be another way of deriving the path.
18
+ * It has to be a reading of where the agent actually ended up.
19
+ *
20
+ * ## Why a slug comparison and not a path comparison
21
+ *
22
+ * A path prefix check answers "is this under the directory I expected", which
23
+ * is the question whose answer was already wrong: the run's idea of the
24
+ * directory is the thing that drifted. `git remote get-url origin` is a fact
25
+ * about the checkout, read from the checkout, and it is the same identity the
26
+ * run was given in its `repo` argument. Comparing those two cannot be
27
+ * satisfied by a path that merely looks right.
28
+ *
29
+ * ## Fail-closed, with the two "no answer" cases kept apart
30
+ *
31
+ * An unreadable remote and an absent one are both refusals. They are not the
32
+ * same refusal: "the worktree has no origin" is a detached or bare checkout,
33
+ * and "nothing reported a remote" means the reading never happened. A guard
34
+ * that collapsed them would let a reading that never ran read as a checkout
35
+ * with no remote, which is this repo's defining defect
36
+ * (`.claude/rules/checks-must-be-able-to-fail.md`).
37
+ */
38
+
39
+ import { spawnSync } from "child_process";
40
+
41
+ /** Returned by `readWorktreeRemote`, so a failure carries its own reason. */
42
+ export interface RemoteReading {
43
+ /** The raw URL git printed, or null if it printed nothing usable. */
44
+ url: string | null;
45
+ /** Non-null when the read itself failed — git missing, path gone, non-zero exit. */
46
+ error: string | null;
47
+ }
48
+
49
+ /** How a worktree's identity reading can go wrong. One value per refusal kind. */
50
+ export type IdentityVerdict = "match" | "mismatch" | "unreadable" | "unreported";
51
+
52
+ export interface IdentityResult {
53
+ verdict: IdentityVerdict;
54
+ /** The slug the worktree reports, when one could be parsed. */
55
+ actual: string | null;
56
+ /** The slug the run expects, normalised the same way. */
57
+ expected: string | null;
58
+ /** Null when the verdict is `match`; otherwise an operator-facing sentence. */
59
+ refusal: string | null;
60
+ }
61
+
62
+ /**
63
+ * `owner/name`, from any remote URL form git hands back.
64
+ *
65
+ * Handles the three this repo actually sees, and normalises case because
66
+ * GitHub slugs are case-insensitive while a clone URL may not match the
67
+ * canonical casing:
68
+ *
69
+ * git@github.com:owner/name.git
70
+ * https://github.com/owner/name.git
71
+ * https://x-access-token:TOKEN@github.com/owner/name
72
+ *
73
+ * Returns null rather than a guess for anything else. A guessed slug compared
74
+ * against a real one produces a refusal nobody can act on, and a guessed slug
75
+ * that happens to match is worse.
76
+ */
77
+ export function repoSlug(remote: string | null | undefined): string | null {
78
+ if (typeof remote !== "string") return null;
79
+ let s = remote.trim();
80
+ if (!s) return null;
81
+
82
+ // Strip a trailing `.git` and any trailing slashes, in that order — a URL
83
+ // can carry both (`…/name.git/`).
84
+ s = s.replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
85
+
86
+ // scp-style: `git@host:owner/name`. The colon is the separator, and there
87
+ // is no `//` after it, which is what distinguishes this from a URL.
88
+ const scp = s.match(/^[^/]*@[^/:]+:(.+)$/);
89
+ if (scp) return normaliseSlug(scp[1]!);
90
+
91
+ // URL-style, with or without credentials in the authority.
92
+ const url = s.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]*\/(.+)$/i);
93
+ if (url) return normaliseSlug(url[1]!);
94
+
95
+ // Already a bare slug — this is how the run's own `repo` argument arrives.
96
+ if (/^[^/\s]+\/[^/\s]+$/.test(s)) return normaliseSlug(s);
97
+
98
+ return null;
99
+ }
100
+
101
+ /**
102
+ * Exactly two segments, lowercased.
103
+ *
104
+ * EXACTLY two, not "the last two". Taking the tail of a longer path is a
105
+ * parser differential: `https://github.com/evil/repo/owner/name` is a path
106
+ * git reads as the repository `evil/repo/owner/name`, and a tail-taking
107
+ * parser reads it as `owner/name` and reports a MATCH. The remote being
108
+ * compared originates in an agent reply, so a parser that can be talked into
109
+ * agreeing is the whole guard.
110
+ *
111
+ * The cost is a self-hosted layout with a group prefix, which returns null
112
+ * and lands in the `unreadable` refusal. That is a loud, visible outcome
113
+ * naming the string it could not read — the right direction for a check to
114
+ * be wrong in.
115
+ */
116
+ function normaliseSlug(path: string): string | null {
117
+ const parts = path.split("/").filter(Boolean);
118
+ if (parts.length !== 2) return null;
119
+ return parts.join("/").toLowerCase();
120
+ }
121
+
122
+ /**
123
+ * A remote URL with every credential-bearing part replaced.
124
+ *
125
+ * Refusals are logged, and a CI checkout's origin is
126
+ * `https://x-access-token:TOKEN@host/owner/name`. Quoting the raw string
127
+ * into a run log writes a live token somewhere it will be read, copied into
128
+ * an issue, and kept.
129
+ *
130
+ * Three places, not one. The first draft redacted only the authority, which
131
+ * the push security review flagged as incomplete sanitisation, and it was
132
+ * right — a remote is not always well formed, and these strings reach the
133
+ * redactor precisely BECAUSE they could not be parsed:
134
+ *
135
+ * - the authority's userinfo, `user:pass@` or a bare `token@`
136
+ * - a query string, `?access_token=…` — git accepts one, and an
137
+ * `insteadOf` rewrite is a common way for one to end up there
138
+ * - anything left that is shaped like a key, anywhere in the string. A
139
+ * deny-list of parameter names is a list someone has to keep; the shape
140
+ * check is what covers the form nobody listed
141
+ *
142
+ * The control arm is the point of the third rule being narrow: a redactor
143
+ * that mangled every URL would satisfy every token case and make every
144
+ * refusal unreadable, which is a worse outcome than the leak for the 99% of
145
+ * refusals that quote an ordinary string.
146
+ */
147
+ const KEY_SHAPED = /\b(?:gh[pousr]_[A-Za-z0-9]{16,}|sk-[A-Za-z0-9]{16,}|AKIA[A-Z0-9]{12,})\b/g;
148
+
149
+ export function redactRemote(remote: string): string {
150
+ return String(remote)
151
+ .replace(/(^[a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, "$1<redacted>@")
152
+ .replace(/^([^/\s]*):[^/\s@]*@/, "$1:<redacted>@")
153
+ .replace(/([?&][^=&\s]*(?:token|auth|key|secret|password|pat)[^=&\s]*=)[^&\s]+/gi, "$1<redacted>")
154
+ .replace(KEY_SHAPED, "<redacted>");
155
+ }
156
+
157
+ /**
158
+ * Read a worktree's `origin` URL.
159
+ *
160
+ * `spawnSync` with an argument array and `-C`, never a shell string: the path
161
+ * originates in an agent reply (#155) and a shell would read whatever is in
162
+ * it. The timeout is short because this runs on a path that is already
163
+ * suspected of being wrong, and a hang here would stall the run at exactly
164
+ * the moment it needs to refuse.
165
+ */
166
+ export function readWorktreeRemote(worktreePath: string): RemoteReading {
167
+ if (typeof worktreePath !== "string" || !worktreePath.trim()) {
168
+ return { url: null, error: "no worktree path was given" };
169
+ }
170
+ const got = spawnSync("git", ["-C", worktreePath, "remote", "get-url", "origin"], {
171
+ timeout: 10_000,
172
+ encoding: "utf-8",
173
+ });
174
+ // Redacted on the way out, not at the call site. git's own stderr quotes
175
+ // the remote back at you — "fatal: 'https://user:TOKEN@host/x' does not
176
+ // appear to be a git repository" — so the error string is a second channel
177
+ // for the same credential the URL carries, and a caller that redacted only
178
+ // `url` would leak it through `error`.
179
+ if (got.error) return { url: null, error: redactRemote(got.error.message) };
180
+ if (got.status !== 0) {
181
+ const said = String(got.stderr || "").trim().split("\n")[0] || `git exited ${got.status}`;
182
+ return { url: null, error: redactRemote(said) };
183
+ }
184
+ const url = String(got.stdout || "").trim();
185
+ return url ? { url, error: null } : { url: null, error: "git printed no url" };
186
+ }
187
+
188
+ /**
189
+ * Does the worktree belong to the repository this run is for?
190
+ *
191
+ * `reported` is the remote URL as the worktree stated it — read in-process by
192
+ * `readWorktreeRemote`, or carried back in an agent's reply where the caller
193
+ * cannot run git (`workflows/ship.js` has no subprocess access, #69).
194
+ *
195
+ * Every non-match is a refusal that NAMES both sides. The #218 incident was
196
+ * recoverable only because the agent's own findings said which repo it was in
197
+ * and which the issue targeted; a refusal that omits either is one an
198
+ * operator has to go to the transcript for.
199
+ */
200
+ export function worktreeIdentity(
201
+ worktreePath: string,
202
+ expectedRepo: string | null | undefined,
203
+ reported: string | null | undefined,
204
+ ): IdentityResult {
205
+ const expected = repoSlug(expectedRepo);
206
+ const where = worktreePath || "(no path reported)";
207
+
208
+ if (!expected) {
209
+ // The run does not know its own repo, so there is nothing to compare
210
+ // against. Refusing is the only honest answer: passing here would make
211
+ // the guard silently inert for exactly the misconfigured run most likely
212
+ // to need it.
213
+ return {
214
+ verdict: "unreported",
215
+ actual: null,
216
+ expected: null,
217
+ refusal:
218
+ `${where} could not be checked — the run did not state a repository to compare against ` +
219
+ // Redacted too. `repo` is normally a bare slug, but this branch fires
220
+ // precisely when it was NOT one, and "whatever was passed instead"
221
+ // is exactly the value that might be a URL with a token in it.
222
+ `(repo was ${JSON.stringify(expectedRepo == null ? null : redactRemote(String(expectedRepo)))}), ` +
223
+ `so a worktree in any repository would pass (#218)`,
224
+ };
225
+ }
226
+
227
+ if (reported === null || reported === undefined || String(reported).trim() === "") {
228
+ return {
229
+ verdict: "unreported",
230
+ actual: null,
231
+ expected,
232
+ refusal:
233
+ `${where} reported no origin remote, so there is nothing to compare against ${expected} — ` +
234
+ `a reading that never happened is not a checkout that matched (#218)`,
235
+ };
236
+ }
237
+
238
+ const actual = repoSlug(reported);
239
+ if (!actual) {
240
+ return {
241
+ verdict: "unreadable",
242
+ actual: null,
243
+ expected,
244
+ refusal:
245
+ `${where} reported an origin this run cannot read as owner/name ` +
246
+ `(${JSON.stringify(redactRemote(String(reported).trim()))}), ` +
247
+ `so it cannot be compared against ${expected} (#218)`,
248
+ };
249
+ }
250
+
251
+ if (actual === expected) return { verdict: "match", actual, expected, refusal: null };
252
+
253
+ return {
254
+ verdict: "mismatch",
255
+ actual,
256
+ expected,
257
+ refusal:
258
+ `${where} is a worktree of ${actual}, but this run targets ${expected} — ` +
259
+ `an isolated agent resolved its worktree from ambient cwd rather than the run's projectRoot. ` +
260
+ `Work done there would be written into the wrong repository (#218).`,
261
+ };
262
+ }
263
+
264
+ /** One result row as the workflow reports them: a path and the remote it read. */
265
+ export interface WorktreeReport {
266
+ worktreePath?: string | null;
267
+ worktreeRepo?: string | null;
268
+ }
269
+
270
+ /**
271
+ * Every refusal across a run's agent results, in reported order.
272
+ *
273
+ * By default a row with no `worktreePath` is SKIPPED rather than refused: an
274
+ * agent that ran without isolation has no worktree to check, and refusing
275
+ * those would fire the guard on every non-isolated spawn in a run. A row that
276
+ * HAS a path and no remote is the `unreported` refusal — the agent was asked
277
+ * and did not answer, which is a different state.
278
+ *
279
+ * `requirePath` closes that default where it is a bypass. The push security
280
+ * review called it an authorization bypass and it is one: at a collection
281
+ * boundary, every row WILL be committed from, so "no path" is not "nothing to
282
+ * check" — it is a row claiming files with no checkable origin, and omitting
283
+ * one field would skip the guard entirely. Callers that are about to act on
284
+ * the rows pass `true`; callers merely surveying them do not.
285
+ */
286
+ export function worktreeIdentityViolations(
287
+ reports: readonly WorktreeReport[] | null | undefined,
288
+ expectedRepo: string | null | undefined,
289
+ opts: { requirePath?: boolean } = {},
290
+ ): string[] {
291
+ if (!Array.isArray(reports)) return [];
292
+ const out: string[] = [];
293
+ for (const r of reports) {
294
+ const path = r && typeof r.worktreePath === "string" ? r.worktreePath.trim() : "";
295
+ if (!path && !opts.requirePath) continue;
296
+ const got = worktreeIdentity(path, expectedRepo, r?.worktreeRepo);
297
+ if (got.refusal) out.push(got.refusal);
298
+ }
299
+ return out;
300
+ }