rungate 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/hooks/ActionVerificationGate.hook.ts +96 -0
  2. package/hooks/AgentBriefGuard.hook.ts +38 -0
  3. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  4. package/hooks/AutoVerifyGate.hook.ts +79 -0
  5. package/hooks/BashToolGuard.hook.ts +65 -0
  6. package/hooks/BashWriteGuard.hook.ts +60 -0
  7. package/hooks/CommitEnforcement.hook.ts +130 -0
  8. package/hooks/DocHygiene.hook.ts +148 -0
  9. package/hooks/GateEnforcement.hook.ts +58 -0
  10. package/hooks/GateResultProtection.hook.ts +69 -0
  11. package/hooks/HarnessAFKGate.hook.ts +85 -0
  12. package/hooks/HookCurrency.hook.ts +99 -0
  13. package/hooks/IssueCloseGuard.hook.ts +149 -0
  14. package/hooks/MergeGuard.hook.ts +58 -0
  15. package/hooks/PostCompact.hook.ts +60 -0
  16. package/hooks/ProjectStateSync.hook.ts +103 -0
  17. package/hooks/SkillGuard.hook.ts +69 -0
  18. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  19. package/hooks/SpecSCGuard.hook.ts +123 -0
  20. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  21. package/hooks/TaskCompleted.hook.ts +51 -0
  22. package/hooks/TeamInit.hook.ts +85 -0
  23. package/hooks/TestSuiteGuard.hook.ts +70 -0
  24. package/hooks/TestSuiteRelease.hook.ts +85 -0
  25. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  26. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  27. package/hooks/WorkflowStateGuard.hook.ts +40 -0
  28. package/hooks/lib/agent-config.json +9 -0
  29. package/hooks/lib/agentDetection.ts +201 -0
  30. package/hooks/lib/comment-template.ts +86 -0
  31. package/hooks/lib/findWorkflow.ts +101 -0
  32. package/hooks/lib/parseStdin.ts +37 -0
  33. package/hooks/lib/paths.ts +111 -0
  34. package/hooks/lib/utils.ts +338 -0
  35. package/lib/affected-tests.ts +427 -0
  36. package/lib/agent-audit.ts +2 -3
  37. package/lib/agent-worktree.ts +287 -0
  38. package/lib/agents-md-sections.ts +81 -16
  39. package/lib/bash-write-guard.ts +373 -0
  40. package/lib/behavioral-cache.ts +150 -2
  41. package/lib/branch-cleanup.ts +279 -7
  42. package/lib/branch-protection.ts +790 -0
  43. package/lib/brief-ac-alignment.ts +104 -0
  44. package/lib/brief-references.ts +205 -0
  45. package/lib/bun-version.ts +93 -14
  46. package/lib/check-remedy.ts +140 -0
  47. package/lib/ci-checkout.ts +17 -0
  48. package/lib/ci-history-depth.ts +159 -0
  49. package/lib/ci-setup-step.ts +96 -0
  50. package/lib/claude-code-action.ts +85 -0
  51. package/lib/claude-tool-vocabulary.ts +188 -0
  52. package/lib/cli-commands.ts +15 -0
  53. package/lib/commit-sha.ts +42 -0
  54. package/lib/commit-subject.ts +90 -0
  55. package/lib/compliance-report.ts +377 -45
  56. package/lib/compliance.ts +191 -17
  57. package/lib/config-loader.ts +39 -1
  58. package/lib/config-trackable.ts +400 -0
  59. package/lib/conformity.ts +1087 -100
  60. package/lib/containment.ts +238 -0
  61. package/lib/content-hash.ts +24 -0
  62. package/lib/create-sc.ts +249 -16
  63. package/lib/dev-liveness.ts +180 -0
  64. package/lib/discovery-branch-points.ts +432 -0
  65. package/lib/discovery-stability.ts +481 -0
  66. package/lib/distribution-currency.ts +236 -0
  67. package/lib/doc-routing.ts +157 -0
  68. package/lib/evidence-prevalidator.ts +224 -2
  69. package/lib/evidence-satisfiability.ts +534 -12
  70. package/lib/failure-intake.ts +323 -0
  71. package/lib/fallow-availability.ts +157 -0
  72. package/lib/fs-write-capabilities.ts +232 -0
  73. package/lib/gate-enforcement.ts +222 -28
  74. package/lib/gate-names.ts +72 -0
  75. package/lib/gate-result-protection.ts +427 -0
  76. package/lib/gate-run-split.ts +147 -0
  77. package/lib/generators/agents-md.ts +140 -32
  78. package/lib/git-isolation.ts +140 -0
  79. package/lib/github.ts +15 -0
  80. package/lib/google-auth-action.ts +93 -0
  81. package/lib/harness-project.ts +48 -0
  82. package/lib/harness-provenance.ts +255 -0
  83. package/lib/hook-evidence.ts +235 -0
  84. package/lib/hook-scopes.ts +386 -0
  85. package/lib/hook-target-tree.ts +398 -0
  86. package/lib/hook-trees.ts +447 -0
  87. package/lib/intake-sources.ts +380 -0
  88. package/lib/js-top-level-code.ts +78 -10
  89. package/lib/junit-checks.ts +52 -0
  90. package/lib/late-env-spawn.ts +331 -0
  91. package/lib/launch-base.ts +376 -0
  92. package/lib/line-citation.ts +372 -0
  93. package/lib/orphan-reaper.ts +468 -0
  94. package/lib/parity-binding.ts +205 -0
  95. package/lib/paths.ts +96 -3
  96. package/lib/per-test-timeouts.ts +219 -0
  97. package/lib/phase2-decomposition.ts +1 -1
  98. package/lib/plan-coverage.ts +151 -0
  99. package/lib/prior-branch.ts +201 -8
  100. package/lib/process-table.ts +146 -0
  101. package/lib/project-state-derivation.ts +219 -0
  102. package/lib/project-state-root.ts +258 -0
  103. package/lib/published-artifact.ts +669 -0
  104. package/lib/readdir-sorted.ts +45 -0
  105. package/lib/review-execution-reading.ts +206 -0
  106. package/lib/review-tool-agreement.ts +433 -0
  107. package/lib/rule-promotion.ts +234 -0
  108. package/lib/rule-retirement.ts +525 -0
  109. package/lib/run-branch.ts +612 -0
  110. package/lib/rungate-schema.ts +19 -0
  111. package/lib/runner-home.ts +274 -0
  112. package/lib/sc-id-cross-tree.ts +103 -15
  113. package/lib/sc-ids.ts +121 -13
  114. package/lib/sc-reservations.ts +289 -0
  115. package/lib/scaffold/ai-review-findings.ts +409 -0
  116. package/lib/scaffold/ai-review-step.ts +5406 -64
  117. package/lib/scaffold/defaults.ts +82 -1
  118. package/lib/scaffold/managed-workflow.ts +587 -192
  119. package/lib/scaffold/owned-files.ts +152 -45
  120. package/lib/scaffold/pre-push-hook.ts +49 -5
  121. package/lib/scaffold/steps.ts +1836 -275
  122. package/lib/scaffold/workflow-census.ts +217 -0
  123. package/lib/scaffold/workflow-drift.ts +217 -0
  124. package/lib/scaffold/write-steps.ts +4 -0
  125. package/lib/scan-budget.ts +247 -0
  126. package/lib/scanner.ts +43 -51
  127. package/lib/scratch-roots.ts +50 -5
  128. package/lib/screenshot-discovery.ts +121 -0
  129. package/lib/screenshot-upload.ts +41 -1
  130. package/lib/secret-patterns.ts +511 -8
  131. package/lib/security-verdict.ts +1 -1
  132. package/lib/shell-path-interpolation.ts +594 -0
  133. package/lib/ship-mode.ts +219 -0
  134. package/lib/source-slice.ts +294 -0
  135. package/lib/stale-cleanup.ts +37 -3
  136. package/lib/suite-flake.ts +278 -0
  137. package/lib/suite-measurement.ts +23 -4
  138. package/lib/suite-run-reading.ts +241 -1
  139. package/lib/suite-timeout-margin.ts +193 -0
  140. package/lib/test-case-bodies.ts +883 -0
  141. package/lib/test-case-deletion.ts +653 -0
  142. package/lib/test-census.ts +97 -29
  143. package/lib/test-command-positions.ts +274 -0
  144. package/lib/test-suite-lock.ts +159 -16
  145. package/lib/text-dependents.ts +875 -0
  146. package/lib/tool-probe.ts +31 -9
  147. package/lib/top-level-cd.ts +393 -0
  148. package/lib/tree-entries.ts +89 -0
  149. package/lib/ts-ast.ts +200 -0
  150. package/lib/walk-test-files.ts +97 -0
  151. package/lib/workflow-actions.ts +263 -0
  152. package/lib/workflow-security.ts +29 -0
  153. package/lib/workflow-taint.ts +732 -0
  154. package/lib/worktree-cleanup.ts +65 -38
  155. package/lib/worktree-collect.ts +177 -5
  156. package/lib/worktree-repo.ts +68 -3
  157. package/package.json +4 -1
  158. package/scripts/ai-review-findings.ts +45 -0
  159. package/scripts/check-installed-hook-currency.ts +825 -0
  160. package/scripts/create-sc.ts +21 -1
  161. package/scripts/extract-constraints.ts +107 -7
  162. package/scripts/generate-code-map.ts +23 -30
  163. package/scripts/scaffold-project.ts +8 -1
  164. package/scripts/sync-sc-status.ts +77 -16
@@ -12,6 +12,61 @@
12
12
  import { readdirSync, realpathSync, statSync, existsSync, readFileSync, rmSync } from "fs";
13
13
  import { join, isAbsolute } from "path";
14
14
  import { spawnSync } from "child_process";
15
+ import { gitIsolatedArgs, gitIsolatedEnv } from "./git-isolation";
16
+
17
+ /**
18
+ * The ONE place this module runs `git` (#1097).
19
+ *
20
+ * ## Why isolation matters more here than anywhere it has been applied yet
21
+ *
22
+ * Every other consumer of `lib/git-isolation.ts` reads. This one deletes.
23
+ * The chain is three steps and it was live on `origin/main`:
24
+ *
25
+ * 1. `core.excludesFile` makes an untracked file invisible to
26
+ * `git status --porcelain`. Measured on git 2.50.1 by #1048/#1090.
27
+ * 2. The dirty check below reads clean, so the worktree falls through
28
+ * every remaining check.
29
+ * 3. `git worktree remove --force` takes the tree, and the file that
30
+ * existed in exactly one place is gone.
31
+ *
32
+ * **The guard meant to spare the work is the reading that was tampered
33
+ * with**, which is why no amount of care in the checks downstream of it
34
+ * helps. #1090 isolated the census — the module that REPORTS the same
35
+ * reading — and did not touch this one.
36
+ *
37
+ * Latent rather than active when this shipped: none of
38
+ * `core.excludesFile`, `core.hooksPath` or `core.fsmonitor` was set in any
39
+ * scope on the machine (measured 2026-10-22). What makes it worth fixing
40
+ * is that a global gitignore is ordinary advice, setting one silently arms
41
+ * this, and the failure is silent — the summary prints `N removed` and
42
+ * nothing says what was in them.
43
+ *
44
+ * ## One seam, not the flags at each site
45
+ *
46
+ * There are eight `git` invocations in this module. `lib/git-isolation.ts`
47
+ * is the single declaring position for WHAT isolation is; this is the
48
+ * single declaring position for WHERE this module applies it. Pasting the
49
+ * `-c` flags at eight call sites is the cheaper change and is measured as
50
+ * the cheapest WRONG fix in #1090's battery: it works, and it reinstates
51
+ * the drifting spellings #1001 removed.
52
+ *
53
+ * ## WHAT THIS DOES NOT COVER
54
+ *
55
+ * `rmSync` on an orphaned checkout, in the `removeOrphans` arm below. Git
56
+ * has no registration for that directory — that is the definition of the
57
+ * bucket — so there is no git invocation there to isolate and no config
58
+ * that could steer it. It is a recursive delete of content nothing has
59
+ * classified, which is why it is off by default; that is #436's argument
60
+ * and this change does not touch it.
61
+ */
62
+ function cleanupGit(args: readonly string[], cwd: string, timeout: number) {
63
+ return spawnSync("git", gitIsolatedArgs(args), {
64
+ cwd,
65
+ encoding: "utf-8",
66
+ timeout,
67
+ env: gitIsolatedEnv(),
68
+ });
69
+ }
15
70
 
16
71
  export interface CleanupResult {
17
72
  removed: string[];
@@ -78,15 +133,11 @@ export interface CleanupOptions {
78
133
  * safety check reverted.
79
134
  */
80
135
  export function unpushedCommitCount(projectRoot: string, branch: string): number | null {
81
- const remotes = spawnSync("git", ["remote"], {
82
- cwd: projectRoot, encoding: "utf-8", timeout: 5000,
83
- });
136
+ const remotes = cleanupGit(["remote"], projectRoot, 5000);
84
137
  if (remotes.status !== 0) return null;
85
138
  if (!remotes.stdout.split("\n").map(r => r.trim()).includes("origin")) return 0;
86
139
 
87
- const count = spawnSync("git", ["rev-list", "--count", branch, "--not", "--remotes=origin"], {
88
- cwd: projectRoot, encoding: "utf-8", timeout: 10_000,
89
- });
140
+ const count = cleanupGit(["rev-list", "--count", branch, "--not", "--remotes=origin"], projectRoot, 10_000);
90
141
  if (count.status !== 0) return null;
91
142
  const n = parseInt(count.stdout.trim(), 10);
92
143
  return Number.isFinite(n) ? n : null;
@@ -124,13 +175,11 @@ export type OriginState =
124
175
  | { kind: "on-origin" };
125
176
 
126
177
  export function originState(projectRoot: string, branch: string): OriginState {
127
- const remotes = spawnSync("git", ["remote"], { cwd: projectRoot, encoding: "utf-8", timeout: 5000 });
178
+ const remotes = cleanupGit(["remote"], projectRoot, 5000);
128
179
  if (remotes.status !== 0) return { kind: "unknown" };
129
180
  if (!remotes.stdout.split("\n").map(r => r.trim()).includes("origin")) return { kind: "no-origin" };
130
181
 
131
- const count = spawnSync("git", ["rev-list", "--count", branch, "--not", "--remotes=origin"], {
132
- cwd: projectRoot, encoding: "utf-8", timeout: 10_000,
133
- });
182
+ const count = cleanupGit(["rev-list", "--count", branch, "--not", "--remotes=origin"], projectRoot, 10_000);
134
183
  if (count.status !== 0) return { kind: "unknown" };
135
184
  const n = parseInt(count.stdout.trim(), 10);
136
185
  if (!Number.isFinite(n)) return { kind: "unknown" };
@@ -193,9 +242,7 @@ export function removalKeepReason(
193
242
  * permission — the same rule `unpushedCommitCount` follows for `null`.
194
243
  */
195
244
  export function lockedWorktreePaths(projectRoot: string): Set<string> | null {
196
- const list = spawnSync("git", ["worktree", "list", "--porcelain"], {
197
- cwd: projectRoot, encoding: "utf-8", timeout: 15_000,
198
- });
245
+ const list = cleanupGit(["worktree", "list", "--porcelain"], projectRoot, 15_000);
199
246
  if (list.status !== 0) return null;
200
247
 
201
248
  const paths = new Set<string>();
@@ -420,11 +467,7 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
420
467
  }
421
468
 
422
469
  // Check for uncommitted changes
423
- const statusCheck = spawnSync("git", ["status", "--porcelain"], {
424
- cwd: worktreePath,
425
- encoding: "utf-8",
426
- timeout: 5000,
427
- });
470
+ const statusCheck = cleanupGit(["status", "--porcelain"], worktreePath, 5000);
428
471
 
429
472
  if (statusCheck.status !== 0) {
430
473
  result.errors.push(`Failed to check git status for ${entry}: ${statusCheck.stderr}`);
@@ -438,11 +481,7 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
438
481
  }
439
482
 
440
483
  // Get branch name
441
- const branchCheck = spawnSync("git", ["-C", worktreePath, "branch", "--show-current"], {
442
- cwd: projectRoot,
443
- encoding: "utf-8",
444
- timeout: 5000,
445
- });
484
+ const branchCheck = cleanupGit(["-C", worktreePath, "branch", "--show-current"], projectRoot, 5000);
446
485
 
447
486
  if (branchCheck.status !== 0) {
448
487
  result.errors.push(`Failed to get branch name for ${entry}: ${branchCheck.stderr}`);
@@ -475,11 +514,7 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
475
514
  // asks whether BRANCH is an ancestor of main. Reversed, every branch cut
476
515
  // from main would look merged and cleanup would delete unmerged work.
477
516
  // test/unit/worktree-cleanup-merge.test.ts pins both directions.
478
- const mergeCheck = spawnSync("git", ["merge-base", "--is-ancestor", branchName, "main"], {
479
- cwd: projectRoot,
480
- encoding: "utf-8",
481
- timeout: 5000,
482
- });
517
+ const mergeCheck = cleanupGit(["merge-base", "--is-ancestor", branchName, "main"], projectRoot, 5000);
483
518
 
484
519
  // Exit 0 = merged, 1 = not merged. Anything else (128: bad revision, no
485
520
  // `main`, not a repo) is an error, NOT a verdict — treating it as "not
@@ -507,11 +542,7 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
507
542
  }
508
543
 
509
544
  // All safety checks passed — remove the worktree
510
- const removeResult = spawnSync("git", ["worktree", "remove", "--force", worktreePath], {
511
- cwd: projectRoot,
512
- encoding: "utf-8",
513
- timeout: 15000,
514
- });
545
+ const removeResult = cleanupGit(["worktree", "remove", "--force", worktreePath], projectRoot, 15000);
515
546
 
516
547
  if (removeResult.status !== 0) {
517
548
  result.errors.push(`Failed to remove ${entry}: ${removeResult.stderr}`);
@@ -521,11 +552,7 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
521
552
  }
522
553
 
523
554
  // Prune worktree references
524
- const pruneResult = spawnSync("git", ["worktree", "prune"], {
525
- cwd: projectRoot,
526
- encoding: "utf-8",
527
- timeout: 5000,
528
- });
555
+ const pruneResult = cleanupGit(["worktree", "prune"], projectRoot, 5000);
529
556
 
530
557
  if (pruneResult.status !== 0) {
531
558
  result.errors.push(`Failed to prune worktree references: ${pruneResult.stderr}`);
@@ -20,7 +20,17 @@
20
20
  * others' work has to survive.
21
21
  */
22
22
 
23
- import { copyFileSync, existsSync, lstatSync, mkdirSync, realpathSync } from "fs";
23
+ import {
24
+ copyFileSync,
25
+ existsSync,
26
+ lstatSync,
27
+ mkdirSync,
28
+ mkdtempSync,
29
+ realpathSync,
30
+ rmSync,
31
+ utimesSync,
32
+ } from "fs";
33
+ import { tmpdir } from "os";
24
34
  import { dirname, isAbsolute, join, relative, resolve } from "path";
25
35
 
26
36
  export interface AgentBuildResult {
@@ -140,12 +150,94 @@ export function groupFilesByWorktree(results: AgentBuildResult[]): WorktreeGroup
140
150
  }
141
151
 
142
152
  /**
143
- * Copy each group's files from its worktree into `projectRoot`.
153
+ * One write this call made, and what undoing it means (#750).
154
+ *
155
+ * Recorded BEFORE the write, not after. A `copyFileSync` that throws partway
156
+ * has already truncated the destination, so an entry appended afterwards
157
+ * would never exist for exactly the write that needs undoing most.
158
+ */
159
+ type CollectUndo =
160
+ /** The destination did not exist: undoing it means REMOVING, not restoring. */
161
+ | { kind: "created-file"; dest: string }
162
+ /** The destination existed: its bytes and timestamps are held aside. */
163
+ | { kind: "overwritten-file"; dest: string; backup: string; atime: Date; mtime: Date }
164
+ /** The topmost directory `mkdirSync(recursive)` created for a destination. */
165
+ | { kind: "created-dir"; dir: string };
166
+
167
+ /**
168
+ * Where a rollback holds the previous bytes of a destination it overwrote.
169
+ *
170
+ * **Outside the project root, and exported so that is checkable.** A backup
171
+ * staged inside the tree being collected into is a file the caller stages,
172
+ * commits and pushes the moment the cleanup that removes it does not run.
173
+ * Inlining `mkdtempSync` at the one call site made that property true and
174
+ * unobservable: the directory is removed on the success path and on the
175
+ * failure path, so every post-call assertion reads the same either way —
176
+ * measured as battery row M8, **0 red**, which is what a vacuous case looks
177
+ * like from the outside. One binding, so there is one thing to mutate.
178
+ */
179
+ export function collectBackupRoot(): string {
180
+ return mkdtempSync(join(tmpdir(), "rungate-collect-undo-"));
181
+ }
182
+
183
+ /** Raised when the copy failed AND putting the tree back also failed. */
184
+ export class CollectRollbackError extends Error {
185
+ constructor(
186
+ readonly cause: unknown,
187
+ readonly rollbackFailures: string[],
188
+ ) {
189
+ super(
190
+ `${cause instanceof Error ? cause.message : String(cause)}\n` +
191
+ `AND the project root could NOT be put back: ${rollbackFailures.join("; ")}. ` +
192
+ `The tree is in an unknown state — do not stage or commit it.`,
193
+ );
194
+ this.name = "CollectRollbackError";
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Copy each group's files from its worktree into `projectRoot`, atomically in
200
+ * the only sense that matters here: **a throw leaves the project root as it
201
+ * was.**
144
202
  *
145
203
  * Throws rather than skipping when a destination would land outside
146
204
  * `projectRoot`. A traversal here is not a path to sanitise away quietly — it
147
205
  * means the inputs cannot be trusted, and the caller must abort the commit
148
206
  * rather than proceed with a partially-collected tree.
207
+ *
208
+ * ## Why a journal, and not the two cheaper designs (#750)
209
+ *
210
+ * Eleven throw sites sit between the group loop and the `copyFileSync`. Any
211
+ * that fires after the first successful copy used to leave copied files in
212
+ * the project root with nothing putting them back, and `workflows/ship.js`
213
+ * then reported a failed collect over a half-written tree.
214
+ *
215
+ * #750 offered three designs and asked for one with a reason.
216
+ *
217
+ * - **Validate every file before copying anything** is the issue's own named
218
+ * cheapest wrong fix, and it is wrong for a reason that survives careful
219
+ * implementation: every one of these checks is an `lstat` of a path the
220
+ * AGENT controls. Answering at T1 and copying at T2 lets the answer change
221
+ * in between, and the property asked for is about the resulting tree, not
222
+ * about the order the checks run in.
223
+ * - **Stage into a temp directory and move into place in one pass** narrows
224
+ * the window without closing it: N renames are N operations, and a throw
225
+ * during the Nth leaves N−1 done. It also degrades silently when the
226
+ * staging directory is on another filesystem, where `renameSync` raises
227
+ * `EXDEV` and the "one atomic move" becomes a copy again.
228
+ * - **A journal** — this one — delivers the property for a throw from
229
+ * ANYWHERE, including one this function did not generate: an `ENOSPC` from
230
+ * `copyFileSync`, an `EACCES` from `mkdirSync`, a race that no amount of
231
+ * pre-validation can see.
232
+ *
233
+ * ## Undoing can itself fail, and that is a different state
234
+ *
235
+ * A rollback that cannot complete leaves a tree nobody has validated, which
236
+ * is worse than the original failure and must not be reported as it. It
237
+ * raises `CollectRollbackError` carrying both the original cause and every
238
+ * undo that failed. Swallowing them would make a half-restored tree
239
+ * indistinguishable from a clean refusal — `0`, `{}` and silence are
240
+ * indistinguishable from success (`.claude/rules/config-access.md`).
149
241
  */
150
242
  export function collectWorktreeFiles(
151
243
  groups: WorktreeGroup[],
@@ -155,6 +247,67 @@ export function collectWorktreeFiles(
155
247
  const copied: string[] = [];
156
248
  const missing: string[] = [];
157
249
 
250
+ /** Every write this call has made, oldest first. Undone in reverse. */
251
+ const journal: CollectUndo[] = [];
252
+ /** Created on the first OVERWRITE, so a run that overwrites nothing makes none. */
253
+ let backupDir: string | null = null;
254
+
255
+ const backupOf = (dest: string): string => {
256
+ backupDir ??= collectBackupRoot();
257
+ const slot = join(backupDir, String(journal.length));
258
+ copyFileSync(dest, slot);
259
+ return slot;
260
+ };
261
+
262
+ const undoAll = (): string[] => {
263
+ const failures: string[] = [];
264
+ // Reverse order, so a file created inside a directory this call also
265
+ // created is removed before the directory is.
266
+ for (const entry of [...journal].reverse()) {
267
+ try {
268
+ if (entry.kind === "created-file") {
269
+ rmSync(entry.dest, { force: true });
270
+ } else if (entry.kind === "overwritten-file") {
271
+ copyFileSync(entry.backup, entry.dest);
272
+ // Bytes alone are not "as it was" for anything keyed on mtime — a
273
+ // build cache, a watcher, `make`. Restored from the stat taken
274
+ // before the overwrite.
275
+ utimesSync(entry.dest, entry.atime, entry.mtime);
276
+ } else {
277
+ // Recursive is safe here and only here: `mkdirSync(recursive)`
278
+ // returns a path only when it CREATED it, so everything beneath
279
+ // this directory was created by this call, and the files among
280
+ // them have already been removed by the entries above.
281
+ rmSync(entry.dir, { recursive: true, force: true });
282
+ }
283
+ } catch (e) {
284
+ failures.push(`${entry.kind} ${"dest" in entry ? entry.dest : entry.dir}: ${String(e)}`);
285
+ }
286
+ }
287
+ return failures;
288
+ };
289
+
290
+ try {
291
+ collect();
292
+ } catch (cause) {
293
+ const failures = undoAll();
294
+ cleanupBackups();
295
+ throw failures.length > 0 ? new CollectRollbackError(cause, failures) : cause;
296
+ }
297
+ cleanupBackups();
298
+ return { copied: [...new Set(copied)], missing };
299
+
300
+ function cleanupBackups(): void {
301
+ // Best effort, and genuinely best effort: a leftover temp directory is
302
+ // litter, not a correctness problem, and raising from here would mask
303
+ // the error being propagated.
304
+ if (backupDir) {
305
+ try { rmSync(backupDir, { recursive: true, force: true }); } catch { /* litter only */ }
306
+ backupDir = null;
307
+ }
308
+ }
309
+
310
+ function collect(): void {
158
311
  // `allowedWorktrees` is required, and an empty list authorises nothing.
159
312
  // Making it optional with an "allow anything" default would restore exactly
160
313
  // the hole it exists to close, in the quietest possible way.
@@ -251,7 +404,11 @@ export function collectWorktreeFiles(
251
404
  if (!realIsInside(projectRoot, dirname(dest))) {
252
405
  throw new Error(`destination directory escapes the project root: ${rel}`);
253
406
  }
254
- mkdirSync(dirname(dest), { recursive: true });
407
+ // The return value is the TOPMOST directory it created, or undefined
408
+ // when every component already existed. Journaling it is what makes
409
+ // an empty directory tree not survive a refusal.
410
+ const createdDir = mkdirSync(dirname(dest), { recursive: true });
411
+ if (createdDir) journal.push({ kind: "created-dir", dir: createdDir });
255
412
  // And again after: mkdir resolved and created real directories, but a
256
413
  // symlinked component could have been introduced between the two.
257
414
  if (!realIsInside(projectRoot, dirname(dest))) {
@@ -273,11 +430,26 @@ export function collectWorktreeFiles(
273
430
  if (dst && dst.nlink > 1) {
274
431
  throw new Error(`refusing to overwrite a hard link: ${rel}`);
275
432
  }
433
+
434
+ // Journal BEFORE the write. `copyFileSync` truncates the destination
435
+ // before it finishes, so an entry appended after a successful copy
436
+ // would be missing for precisely the case that needs it most — a
437
+ // copy that threw partway and left a truncated file.
438
+ journal.push(
439
+ dst
440
+ ? {
441
+ kind: "overwritten-file",
442
+ dest,
443
+ backup: backupOf(dest),
444
+ atime: dst.atime,
445
+ mtime: dst.mtime,
446
+ }
447
+ : { kind: "created-file", dest },
448
+ );
276
449
  copyFileSync(src, dest);
277
450
  }
278
451
  copied.push(relative(projectRoot, dest));
279
452
  }
280
453
  }
281
-
282
- return { copied: [...new Set(copied)], missing };
454
+ }
283
455
  }
@@ -186,6 +186,40 @@ export function readWorktreeRemote(worktreePath: string): RemoteReading {
186
186
  return url ? { url, error: null } : { url: null, error: "git printed no url" };
187
187
  }
188
188
 
189
+ /**
190
+ * Is this value a filesystem path rather than a remote?
191
+ *
192
+ * Only to SAY SO in a refusal — nothing branches on it, and `unreadable` is
193
+ * still `unreadable` (#218 is unchanged). The reading is already unusable;
194
+ * what #872 adds is the operator being told WHICH unusable thing it is,
195
+ * because the measured instance was an agent writing the parent checkout's
196
+ * directory into `worktreeRepo` after printing the right URL.
197
+ *
198
+ * ABSOLUTE only. `owner/name` is itself two segments with a slash, so a rule
199
+ * that called anything slash-shaped a path would describe a near-miss slug as
200
+ * a directory — a refusal naming the wrong mistake is worse than one naming
201
+ * none. Three forms: POSIX, `~`-relative, and Windows drive or UNC.
202
+ *
203
+ * No regex literal, and that is not a style choice. Written as one, this
204
+ * needs an escaped forward slash — and `stripStringsAndComments` mangles a
205
+ * `\/`-bearing literal in `workflows/ship.js`'s context into `/^(?:\/x/`,
206
+ * which does not parse. Two CI shards went red on it. The same literal
207
+ * strips cleanly in isolation, so the differential is real and is filed
208
+ * separately; here the fix is to not write the construct.
209
+ */
210
+ export function looksLikeFilesystemPath(reported: unknown): boolean {
211
+ const s = String(reported).trim();
212
+ if (s.startsWith("/") || s.startsWith("~/") || s.startsWith("\\\\")) return true;
213
+ // A Windows drive: one letter, a colon, then either separator.
214
+ const drive = s.charCodeAt(0) | 32;
215
+ return drive >= 97 && drive <= 122 && s[1] === ":" && (s[2] === "\\" || s[2] === "/");
216
+ }
217
+
218
+ /** The clause both copies append, so the two cannot word it differently. */
219
+ const PATH_SHAPED_CLAUSE =
220
+ " — that value is a filesystem path, and worktreeRepo is the URL " +
221
+ "`git remote get-url origin` printed, never a path (#872)";
222
+
189
223
  /**
190
224
  * Does the worktree belong to the repository this run is for?
191
225
  *
@@ -245,7 +279,8 @@ export function worktreeIdentity(
245
279
  refusal:
246
280
  `${where} reported an origin this run cannot read as owner/name ` +
247
281
  `(${JSON.stringify(redactRemote(String(reported).trim()))}), ` +
248
- `so it cannot be compared against ${expected} (#218)`,
282
+ `so it cannot be compared against ${expected} (#218)` +
283
+ (looksLikeFilesystemPath(reported) ? PATH_SHAPED_CLAUSE : ""),
249
284
  };
250
285
  }
251
286
 
@@ -447,11 +482,27 @@ export interface WorktreeReport {
447
482
  * check" — it is a row claiming files with no checkable origin, and omitting
448
483
  * one field would skip the guard entirely. Callers that are about to act on
449
484
  * the rows pass `true`; callers merely surveying them do not.
485
+ *
486
+ * `allowPath` is the DESTINATION question asked at the same boundary (#1098).
487
+ * Identity answers "which repository is this a worktree of", read off the
488
+ * remote; it says nothing about whether the directory is one this run may act
489
+ * in. In `workflows/ship.js` those were two checks ~350 lines apart, and the
490
+ * second ran after two agents had already been told to validate and to fix
491
+ * inside the path. Asked here, every reported path is vetted once, before
492
+ * anything is interpolated into a prompt.
493
+ *
494
+ * It is asked where identity had nothing to say, not instead of it: a row in
495
+ * the wrong repository keeps #218's own refusal, which names the repository.
496
+ *
497
+ * The predicate is INJECTED, not referenced: ship.js's allowlist is declared
498
+ * in a different marked block and the identity block is sliced out and
499
+ * executed on its own. Absent, nothing is allowlisted — a caller merely
500
+ * surveying rows has no destination to vet.
450
501
  */
451
502
  export function worktreeIdentityViolations(
452
503
  reports: readonly WorktreeReport[] | null | undefined,
453
504
  expectedRepo: string | null | undefined,
454
- opts: { requirePath?: boolean } = {},
505
+ opts: { requirePath?: boolean; allowPath?: (path: string) => unknown } = {},
455
506
  ): string[] {
456
507
  if (!Array.isArray(reports)) return [];
457
508
  const out: string[] = [];
@@ -459,7 +510,21 @@ export function worktreeIdentityViolations(
459
510
  const path = r && typeof r.worktreePath === "string" ? r.worktreePath.trim() : "";
460
511
  if (!path && !opts.requirePath) continue;
461
512
  const got = worktreeIdentity(path, expectedRepo, r?.worktreeRepo);
462
- if (got.refusal) out.push(got.refusal);
513
+ if (got.refusal) {
514
+ out.push(got.refusal);
515
+ continue;
516
+ }
517
+ // AFTER the identity reading, and only where identity had nothing to
518
+ // say. A row that is a worktree of the wrong repository keeps #218's own
519
+ // refusal, which names the repository. What this adds is the case
520
+ // identity CANNOT see: a checkout of the RIGHT repository sitting in a
521
+ // directory this run does not own, which reads as a match.
522
+ if (path && typeof opts.allowPath === "function" && !opts.allowPath(path)) {
523
+ out.push(
524
+ `${path} is not this run's project root nor one of its agent worktrees, ` +
525
+ `so it is not a directory this run may act in (#1098)`,
526
+ );
527
+ }
463
528
  }
464
529
  return out;
465
530
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rungate",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Ship harness — conformity tests, scaffold, and agent briefs for AI-first development",
6
6
  "repository": {
@@ -14,6 +14,7 @@
14
14
  "files": [
15
15
  "bin/",
16
16
  "lib/",
17
+ "hooks/",
17
18
  "prompts/",
18
19
  "config/",
19
20
  "templates/",
@@ -27,10 +28,12 @@
27
28
  "scripts/create-spec.ts",
28
29
  "scripts/create-success.ts",
29
30
  "scripts/create-sc.ts",
31
+ "scripts/ai-review-findings.ts",
30
32
  "scripts/split-spec.ts",
31
33
  "scripts/sync-sc-status.ts",
32
34
  "scripts/audit-transcript.ts",
33
35
  "scripts/detect-sc-drift.ts",
36
+ "scripts/check-installed-hook-currency.ts",
34
37
  "package.json"
35
38
  ],
36
39
  "exports": {
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Adjudicate an AI review's findings payload (#675).
4
+ *
5
+ * Usage:
6
+ * bunx rungate ai-review-findings <path-to-findings.json> # a consumer
7
+ * bun bin/rungate.ts ai-review-findings <path> # this repo
8
+ *
9
+ * The reading, the severity table, the contradiction check and the exit code
10
+ * all live in `lib/scaffold/ai-review-findings.ts` and none of them is
11
+ * restated here. This file exists for ONE reason, and it is a reachability
12
+ * problem rather than a logic one.
13
+ *
14
+ * ## Why a wrapper, when the module already has a `main`
15
+ *
16
+ * `lib/scaffold/ai-review-findings.ts` ends with
17
+ * `if (import.meta.main) process.exit(main(process.argv.slice(2)))` and its
18
+ * `main` is documented as "the CLI the generated workflow step runs". Two
19
+ * things stop that being reachable from a scaffolded project:
20
+ *
21
+ * - **A consumer has no copy of rungate's sources at a path it can name.**
22
+ * The reader is inside the installed package, and the generated workflow
23
+ * cannot hardcode `node_modules/rungate/lib/scaffold/…` without becoming a
24
+ * second declaring position for a path the package controls.
25
+ * `lib/cli-commands.ts` is the one place that says where a command lives,
26
+ * and `test/cli-contract.test.ts` holds it to `package.json`'s `files`.
27
+ * - **`import.meta.main` is FALSE under the dispatcher.** `bin/rungate.ts`
28
+ * rewrites `process.argv` and then `await import(script)` — the import IS
29
+ * the invocation — so a module guarded on `import.meta.main` loads, runs
30
+ * nothing, and the dispatcher exits 0. That is a subcommand that reports
31
+ * success having adjudicated nothing, which is the exact shape of defect
32
+ * #675 is about. This file calls `main` unconditionally, so there is no
33
+ * state in which it is dispatched and does not decide.
34
+ *
35
+ * The exit code is the module's, not this file's. `aiReviewExitCode` routes
36
+ * every refusal through `AI_REVIEW_REQUIRED_EXIT` in
37
+ * `lib/scaffold/ai-review-step.ts`, which is the one constant a mutant zeroes
38
+ * — see `test/ai-review-exit-binding.test.ts`. A `process.exit(1)` written
39
+ * here would be a second non-zero exit that the mutation cannot reach, and
40
+ * the case would go green over a refusal that no longer came from the
41
+ * constant.
42
+ */
43
+ import { main } from "../lib/scaffold/ai-review-findings";
44
+
45
+ process.exit(main(process.argv.slice(2)));