rungate 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/lib/ac-quality.ts +119 -0
  2. package/lib/brief-precedence.ts +114 -0
  3. package/lib/ci-checkout.ts +27 -1
  4. package/lib/compliance-backfill.ts +16 -4
  5. package/lib/compliance-report.ts +109 -8
  6. package/lib/config-loader.ts +129 -5
  7. package/lib/config-readers.ts +86 -0
  8. package/lib/conformity.ts +520 -27
  9. package/lib/context-docs.ts +182 -0
  10. package/lib/create-brief.ts +22 -17
  11. package/lib/create-sc.ts +55 -33
  12. package/lib/decomposition-waves.ts +197 -0
  13. package/lib/doc-scan-targets.ts +435 -0
  14. package/lib/gate-check-audit.ts +190 -0
  15. package/lib/generators/agents-md.ts +10 -5
  16. package/lib/issue-extraction.ts +368 -0
  17. package/lib/organize.ts +129 -40
  18. package/lib/package-closure.ts +111 -0
  19. package/lib/phase2-decomposition.ts +270 -0
  20. package/lib/prior-branch.ts +24 -1
  21. package/lib/project-aliases.ts +100 -0
  22. package/lib/prove-label-gate.ts +93 -0
  23. package/lib/release-preflight.ts +225 -15
  24. package/lib/rungate-schema.ts +36 -2
  25. package/lib/sc-cover.ts +92 -1
  26. package/lib/sc-ids.ts +151 -0
  27. package/lib/scaffold/pre-push-hook.ts +165 -0
  28. package/lib/scaffold/rehearsal.ts +330 -0
  29. package/lib/scaffold/steps.ts +175 -122
  30. package/lib/scaffold/write-steps.ts +167 -0
  31. package/lib/scope-denylist.ts +258 -0
  32. package/lib/scratch-cleanup.ts +198 -0
  33. package/lib/scratch-roots.ts +94 -0
  34. package/lib/task-completion-checks.ts +50 -3
  35. package/lib/typescript-project.ts +233 -0
  36. package/lib/validators/spec-validators.ts +23 -34
  37. package/lib/verified-push.ts +179 -2
  38. package/lib/workflow-security.ts +51 -7
  39. package/lib/worktree-cleanup.ts +318 -20
  40. package/lib/worktree-repo.ts +465 -0
  41. package/package.json +8 -2
  42. package/scripts/audit-specs.ts +134 -37
  43. package/scripts/audit-transcript.ts +259 -0
  44. package/scripts/create-sc.ts +15 -1
  45. package/scripts/detect-sc-drift.ts +200 -0
  46. package/scripts/extract-constraints.ts +16 -36
  47. package/scripts/scaffold-project.ts +26 -136
  48. package/scripts/split-spec.ts +315 -0
  49. package/scripts/sync-sc-status.ts +751 -0
@@ -0,0 +1,165 @@
1
+ /**
2
+ * The generated `.git/hooks/pre-push`, as one binding (#397).
3
+ *
4
+ * It lived as a template literal inside `createGitHooks`, where nothing could
5
+ * run it. The hook is a shell script with an exit code, so
6
+ * `.claude/rules/checks-must-be-able-to-fail.md`'s worked pattern applies
7
+ * directly: route every refusal through one exit-code constant and drive the
8
+ * script against planted fixture repositories. That is what
9
+ * `test/pre-push-hook.test.ts` does, and it is why this is a module rather
10
+ * than a string in the middle of a 2,400-line generator.
11
+ *
12
+ * ## What was wrong
13
+ *
14
+ * The hook could not PASS in any consumer whose `bun.lock` is gitignored, and
15
+ * it failed closed with "Conformity tests failed against the commits being
16
+ * pushed" — which is not what happened. Found on agentgrit on 2026-10-14
17
+ * with conformity at 43 pass, 0 fail in the working tree and the push
18
+ * rejected.
19
+ *
20
+ * The lockfile comparison read `$tmp/bun.lock`, which comes from the git
21
+ * checkout. A gitignored lockfile is never in the checkout, so the `cmp`
22
+ * branch could not be taken and every push fell through to
23
+ * `bun install --frozen-lockfile` with no lockfile to freeze against. For a
24
+ * consumer with a `file:` or `link:` dependency on a sibling directory it
25
+ * then failed a second, independent way: a relative path does not resolve
26
+ * from `/tmp`.
27
+ *
28
+ * `.claude/rules/checks-must-be-able-to-fail.md` is about guards that cannot
29
+ * fail. This is the inverse and the damage is the same shape, because the
30
+ * message is wrong either way — a developer reading "conformity failed" goes
31
+ * and looks at conformity, which is green.
32
+ *
33
+ * ## The three outcomes, and why UNMEASURED blocks
34
+ *
35
+ * | what happened | exit | message |
36
+ * |---|---|---|
37
+ * | conformity ran and failed | refuse | the conformity message |
38
+ * | the suite could not be run at all | refuse | UNMEASURED, naming the cause |
39
+ * | conformity ran and passed | 0 | — |
40
+ *
41
+ * UNMEASURED blocks, and that is a decision rather than an accident of
42
+ * control flow. A pre-push gate that waves a commit through when it could not
43
+ * check is the fail-open this repo keeps finding; `SKIP` is indistinguishable
44
+ * from success and `UNMEASURED` is not
45
+ * (`.claude/rules/config-access.md`). What makes it tolerable is that it says
46
+ * which of the two happened and names `--no-verify` itself, so the developer
47
+ * is not hunting a green suite for a failure that never occurred.
48
+ */
49
+
50
+ /** The ONE exit code every refusal routes through. Asserted to appear once. */
51
+ export const PRE_PUSH_REFUSE_EXIT = 1;
52
+
53
+ export const PRE_PUSH_MANAGED_MARKER = "# Managed by rungate — conformity check before push";
54
+
55
+ /**
56
+ * The conformity suite the hook runs. One literal, so the test that plants a
57
+ * passing and a failing fixture writes the same path the hook reads.
58
+ */
59
+ export const PRE_PUSH_SUITE = "test/scaffold-conformity.test.ts";
60
+
61
+ export function prePushHookScript(): string {
62
+ return `#!/bin/sh
63
+ ${PRE_PUSH_MANAGED_MARKER}
64
+ #
65
+ # Three outcomes, not two: conformity FAILED, conformity could not be RUN,
66
+ # and conformity passed. The first two used to share a message and a status
67
+ # variable, so an install that could not happen was reported as a test that
68
+ # did not pass (#397).
69
+ REFUSE=${PRE_PUSH_REFUSE_EXIT}
70
+ ZERO=0000000000000000000000000000000000000000
71
+ TOPLEVEL=$(git rev-parse --show-toplevel) || exit $REFUSE
72
+ conformity=0
73
+ unmeasured=0
74
+ why=""
75
+
76
+ while read -r _lref lsha _rref _rsha; do
77
+ # Branch deletion: there is no commit to check out.
78
+ [ "$lsha" = "$ZERO" ] && continue
79
+
80
+ tmp=$(mktemp -d) || exit $REFUSE
81
+ if ! git worktree add --detach --quiet "$tmp" "$lsha"; then
82
+ unmeasured=1
83
+ why="the pushed commit $lsha could not be checked out"
84
+ rm -rf "$tmp"
85
+ break
86
+ fi
87
+
88
+ # Which node_modules the pushed commit expects.
89
+ #
90
+ # The old test was \`[ -f "$tmp/bun.lock" ] && cmp -s ...\`, which treats "the
91
+ # checkout has no lockfile" as "the dependencies differ" and installs. But a
92
+ # lockfile absent from the checkout is a lockfile git does not track — it is
93
+ # gitignored, or the project has none — and then there is nothing in this
94
+ # push that can change the dependency graph. The working tree's modules are
95
+ # the right ones by definition, and installing is both slower and less
96
+ # accurate.
97
+ if [ ! -f "$tmp/bun.lock" ]; then
98
+ ln -s "$TOPLEVEL/node_modules" "$tmp/node_modules" 2>/dev/null
99
+ elif [ -f "$TOPLEVEL/bun.lock" ] && cmp -s "$TOPLEVEL/bun.lock" "$tmp/bun.lock"; then
100
+ ln -s "$TOPLEVEL/node_modules" "$tmp/node_modules" 2>/dev/null
101
+ else
102
+ echo "pre-push: dependencies differ from the working tree — installing from the pushed lockfile" >&2
103
+ if ! ( cd "$tmp" && bun install --frozen-lockfile ) >&2; then
104
+ # NOT a conformity result. A relative \`file:\`/\`link:\` dependency does
105
+ # not resolve from a temp directory, and a lockfile that cannot be
106
+ # frozen is an environment fault in this hook's own sandbox.
107
+ unmeasured=1
108
+ why="dependencies could not be installed in the temporary checkout"
109
+ fi
110
+ fi
111
+
112
+ if [ "$unmeasured" -eq 0 ]; then
113
+ out=$( cd "$tmp" && bun test ${PRE_PUSH_SUITE} 2>&1 )
114
+ rc=$?
115
+ echo "$out" >&2
116
+
117
+ # A suite that FAILED and a suite that never RAN both exit non-zero: a
118
+ # missing file, an unresolvable import, and a red assertion are one exit
119
+ # code. Two things in bun's summary tell them apart, and both are needed.
120
+ #
121
+ # Counted tests. The summary prints \`N pass\` / \`N fail\`; a file that is
122
+ # not there prints neither. Zero counted tests is UNMEASURED even when the
123
+ # exit code is 0, because a suite passing vacuously is exactly what
124
+ # .claude/rules/checks-must-be-able-to-fail.md exists to catch.
125
+ #
126
+ # Counted ERRORS. A module that will not resolve is reported as \`1 fail\`
127
+ # AND \`1 error\` — measured on bun 1.3.14 — so the counted-tests test
128
+ # alone calls it a conformity failure, which is the wrong half of the
129
+ # distinction this hook exists to draw. A red assertion prints no error
130
+ # line at all. An unhandled error between tests means the suite did not
131
+ # run as written, whatever the fail count says.
132
+ if echo "$out" | grep -qE '^[[:space:]]*[1-9][0-9]* error'; then
133
+ unmeasured=1
134
+ why="the conformity suite did not load (an unhandled error, usually an import that will not resolve)"
135
+ elif echo "$out" | grep -qE '^[[:space:]]*[1-9][0-9]* (pass|fail)'; then
136
+ [ "$rc" -ne 0 ] && conformity=1
137
+ else
138
+ unmeasured=1
139
+ why="the conformity suite ran no tests (the file is not in the pushed commit, or it declares none)"
140
+ fi
141
+ fi
142
+
143
+ # Always clean up. An early exit here would leak a worktree on every failed
144
+ # push, which is how #68 reached 39 stale worktrees and 243 MB.
145
+ git worktree remove --force "$tmp" 2>/dev/null
146
+ rm -rf "$tmp"
147
+
148
+ [ "$conformity" -ne 0 ] && break
149
+ [ "$unmeasured" -ne 0 ] && break
150
+ done
151
+
152
+ if [ "$unmeasured" -ne 0 ]; then
153
+ echo "ERROR: pre-push did NOT run the conformity suite — $why." >&2
154
+ echo " This is UNMEASURED, not a test failure: your conformity tests may be green." >&2
155
+ echo " Fix the cause, or push with --no-verify once you have run" >&2
156
+ echo " \\\`bun test ${PRE_PUSH_SUITE}\\\` in the real tree yourself." >&2
157
+ exit $REFUSE
158
+ fi
159
+ if [ "$conformity" -ne 0 ]; then
160
+ echo "ERROR: Conformity tests failed against the commits being pushed — fix before pushing" >&2
161
+ exit $REFUSE
162
+ fi
163
+ exit 0
164
+ `;
165
+ }
@@ -0,0 +1,330 @@
1
+ /**
2
+ * Audit by rehearsal (#398).
3
+ *
4
+ * `rungate scaffold <path>` without `--fix` called itself a preview and
5
+ * reported `0 created, 0 replaced, 0 skipped, 0 refused` on a tree that
6
+ * `--fix` then rewrote — 28 paths on this repo's own fixture, 16 on agentgrit.
7
+ * The cause was structural rather than a missing branch: audit was four
8
+ * `existsSync` checks and fix was twenty-five write steps, two bodies of code
9
+ * sharing nothing. Two implementations of the same question can only agree by
10
+ * someone keeping them in step by hand, and nobody was.
11
+ *
12
+ * `--fix` is the DESTRUCTIVE mode — #370 is `--fix` truncating
13
+ * `.claude/rules/checks-must-be-able-to-fail.md` from 262 lines to 65 — so
14
+ * audit is the one thing standing between a consumer and that damage. A
15
+ * preview that under-reports is worse than no preview at all, because it
16
+ * turns "I checked first" into false confidence.
17
+ *
18
+ * ## So audit does not predict what fix would do. It does it, somewhere else.
19
+ *
20
+ * Clone the tree, run the REAL steps against the clone, report what they say,
21
+ * throw the clone away. The two modes then agree by construction rather than
22
+ * by maintenance, and a step added later cannot forget its audit branch
23
+ * because there is no audit branch to forget.
24
+ *
25
+ * On APFS `cp -Rc` is a copy-on-write clone — measured at 0.2s for this repo —
26
+ * so the cost is bounded by metadata rather than by tree size. Where clonefile
27
+ * is unsupported it falls back to a real copy, which is slower and still
28
+ * correct; `rehearsalCloneCommand` reports which one ran so a slow audit is
29
+ * explicable rather than mysterious.
30
+ *
31
+ * ## The two steps that must not be rehearsed
32
+ *
33
+ * A rehearsal is only safe while every step it runs stays inside the clone.
34
+ * Two do not, and both would do real damage from a mode whose entire promise
35
+ * is that it writes nothing:
36
+ *
37
+ * - `deployHooksToConsumers` resolves `consumer.startsWith("/")` and writes to
38
+ * absolute paths in OTHER repositories (`steps.ts:2222`). Rehearsing it
39
+ * would deploy hooks to every consumer on the machine during a preview.
40
+ * - `postScaffoldCommit` creates a commit. In a clone whose `.git` is a file
41
+ * pointing back at the real repository — which is what a git worktree's is —
42
+ * that commit would land in the original.
43
+ *
44
+ * They are named here rather than skipped inline so the exclusion is one list
45
+ * a test can read, and so each one carries the reason it is on it. An
46
+ * exclusion without a stated reason is indistinguishable from an oversight,
47
+ * and the next person to read it cannot tell whether removing it is safe.
48
+ */
49
+
50
+ import { spawnSync } from "child_process";
51
+ import { mkdtempSync, rmSync, lstatSync, readdirSync, readlinkSync, realpathSync } from "fs";
52
+ import { tmpdir } from "os";
53
+ import { join, resolve, sep } from "path";
54
+
55
+ /**
56
+ * Steps a rehearsal must not run, and why. Keys are the exported function
57
+ * names in `lib/scaffold/steps.ts`; `test/scaffold-audit-agreement.test.ts`
58
+ * asserts each one still exists, so a rename cannot silently empty this list
59
+ * and re-enable the step.
60
+ */
61
+ export const STEPS_NOT_REHEARSED: ReadonlyMap<string, string> = new Map([
62
+ [
63
+ "deployHooksToConsumers",
64
+ "writes to absolute paths in other repositories, which a preview must never touch",
65
+ ],
66
+ [
67
+ "postScaffoldCommit",
68
+ "creates a commit, and a clone's .git may point back at the real repository",
69
+ ],
70
+ ]);
71
+
72
+ /** Directories never worth cloning: huge, regenerable, or another tree entirely. */
73
+ export const REHEARSAL_EXCLUDES: readonly string[] = [
74
+ "node_modules",
75
+ ".claude/worktrees",
76
+ ];
77
+
78
+ export interface Rehearsal {
79
+ /** The clone the steps ran against. Always inside the OS temp directory. */
80
+ dir: string;
81
+ /** The mkdtemp that owns `dir`. Tracked so cleanup never walks `..`. */
82
+ parent: string;
83
+ /** `clone` when copy-on-write was used, `copy` when it fell back. */
84
+ method: "clone" | "copy";
85
+ }
86
+
87
+ /**
88
+ * Symlinks in the clone whose target resolves outside it.
89
+ *
90
+ * **A rehearsal is only a rehearsal while every write lands in the copy, and
91
+ * a symlink is a hole straight through the floor.** `cp -R` preserves
92
+ * symlinks rather than following them, so a clone of a tree containing
93
+ * `AGENTS.md -> /elsewhere/AGENTS.md` carries a link to the ORIGINAL file,
94
+ * and the first step that writes `AGENTS.md` overwrites it. Reproduced
95
+ * directly: write through a cloned symlink, read the original, see the new
96
+ * bytes.
97
+ *
98
+ * That is #370's damage — scaffold destroying a real file — arriving through
99
+ * the preview built to prevent it, and in the one mode whose entire promise
100
+ * is that it writes nothing. Found by the commit security review.
101
+ *
102
+ * Reported rather than deleted. Removing the links would let the audit
103
+ * proceed over a tree that is not the consumer's, so it would answer a
104
+ * question nobody asked; `.claude/rules/config-access.md` is the governing
105
+ * idea — a reading that cannot be taken safely is UNMEASURED, and UNMEASURED
106
+ * is not SKIP.
107
+ */
108
+ export function escapingSymlinks(dir: string): string[] {
109
+ const root = realpathSync(dir);
110
+ const out: string[] = [];
111
+ const walk = (rel: string) => {
112
+ let entries;
113
+ try {
114
+ entries = readdirSync(join(root, rel), { withFileTypes: true });
115
+ } catch (err) {
116
+ // NOT `return`. A directory we cannot read is a directory whose
117
+ // symlinks we did not check, and a check that skips what it cannot
118
+ // see reports the same empty list as a tree with nothing wrong —
119
+ // `.claude/rules/checks-must-be-able-to-fail.md`'s fail-open shape,
120
+ // found by the commit security review. Unreadable counts as
121
+ // escaping, so the audit refuses rather than previewing blind.
122
+ out.push(`${rel || "."} (unreadable: ${(err as Error).message})`);
123
+ return;
124
+ }
125
+ for (const e of entries) {
126
+ const child = rel ? join(rel, e.name) : e.name;
127
+ if (e.isSymbolicLink()) {
128
+ if (linkEscapes(root, child)) out.push(child);
129
+ } else if (e.isDirectory()) {
130
+ walk(child);
131
+ }
132
+ }
133
+ };
134
+ walk("");
135
+ return out.sort();
136
+ }
137
+
138
+ /**
139
+ * Does the link at `root/rel` resolve outside `root`?
140
+ *
141
+ * `realpathSync` is right for a link whose target exists and wrong for one
142
+ * whose target does not: it throws, and the first version treated a throw as
143
+ * "resolves to the link's own path", i.e. inside the root, i.e. safe. A
144
+ * DANGLING link to `/etc/thing` was therefore not flagged — and a step that
145
+ * writes through it creates `/etc/thing`. A dangling link is the more
146
+ * dangerous case, not the less, because writing is exactly what makes the
147
+ * target exist. Found by the commit security review.
148
+ */
149
+ function linkEscapes(root: string, rel: string): boolean {
150
+ const link = join(root, rel);
151
+ try {
152
+ const target = realpathSync(link);
153
+ return target !== root && !target.startsWith(root + sep);
154
+ } catch {
155
+ // Unresolvable: fall back to the literal target, resolved against the
156
+ // link's own directory the way the kernel would.
157
+ try {
158
+ const literal = resolve(join(link, ".."), readlinkSync(link));
159
+ return literal !== root && !literal.startsWith(root + sep);
160
+ } catch {
161
+ // Cannot even read the link. Unknown is not safe.
162
+ return true;
163
+ }
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Copy `root` somewhere disposable.
169
+ *
170
+ * `.git` is copied rather than skipped: five steps shell out to
171
+ * `git -C <root>` for the origin URL, a file's last-commit date and
172
+ * `status --porcelain`, and a clone with no repository would make those steps
173
+ * take different branches than they will under `--fix` — which is the exact
174
+ * disagreement this module exists to remove.
175
+ */
176
+ export function cloneForRehearsal(root: string): Rehearsal {
177
+ const parent = mkdtempSync(join(tmpdir(), "rungate-rehearsal-"));
178
+ const dir = join(parent, "tree");
179
+ const fail = (why: string): never => {
180
+ rmSync(parent, { recursive: true, force: true });
181
+ throw new Error(`audit did NOT run: ${why}`);
182
+ };
183
+
184
+ // `-c` asks for an APFS clonefile. It fails on filesystems that cannot do
185
+ // it, so the fallback is explicit rather than a silent slow path.
186
+ //
187
+ // Both attempts go through `attemptCopy`, which clears the destination
188
+ // first. A failed `cp` may have copied some of the tree before giving up,
189
+ // and falling back on top of that leaves a PARTIAL clone — the steps then
190
+ // run over a tree missing files, report less than `--fix` will do, and
191
+ // look like a clean preview, which is this module's whole subject. The
192
+ // first draft cleared only in the fallback, and the mutation battery
193
+ // scored that guard 0: `cp -Rc` succeeds on every machine the tests run
194
+ // on, so no test could ever reach the second branch. One shared helper
195
+ // removes the ordering rather than testing it.
196
+ let method: Rehearsal["method"] = "clone";
197
+ if (attemptCopy(["-Rc", root, dir], 300_000) !== 0) {
198
+ if (attemptCopy(["-R", root, dir], 600_000) !== 0) {
199
+ return fail("the tree could not be copied");
200
+ }
201
+ method = "copy";
202
+ }
203
+
204
+ // Pruning happens through `rmSync(..., { recursive: true })`, which
205
+ // follows a symlinked PARENT. `.claude/worktrees` in a tree where
206
+ // `.claude -> /real/.claude` therefore resolves outside the clone and
207
+ // deletes the consumer's real worktrees — a destructive path traversal
208
+ // performed by the mode that promises to write nothing. Found by the
209
+ // commit security review.
210
+ //
211
+ // So nothing is deleted through a symlink. Each excluded path is walked
212
+ // component by component; the moment a component is a link, the link
213
+ // itself is unlinked (never followed) and the walk stops. `node_modules`
214
+ // being a symlink is the common case — the pre-push hook makes one — and
215
+ // must stay cheap rather than refusing the audit.
216
+ for (const rel of REHEARSAL_EXCLUDES) {
217
+ prunePathWithoutFollowingLinks(dir, rel);
218
+ }
219
+
220
+ const missing = missingTopLevel(root, dir);
221
+ if (missing.length > 0) {
222
+ return fail(`the copy is incomplete — ${missing.length} top-level entr(ies) missing: ${missing.slice(0, 5).join(", ")}`);
223
+ }
224
+
225
+ const escaping = escapingSymlinks(dir);
226
+ if (escaping.length > 0) {
227
+ return fail(
228
+ `the tree contains ${escaping.length} symlink(s) pointing outside it, and a step writing through one ` +
229
+ `would modify the real file rather than the copy — which is the damage a preview exists to prevent (#370). ` +
230
+ `Offending paths: ${escaping.slice(0, 5).join(", ")}${escaping.length > 5 ? ", …" : ""}. ` +
231
+ `Re-run with --fix if you intend those writes, or replace the symlinks with real files.`,
232
+ );
233
+ }
234
+
235
+ return { dir, parent, method };
236
+ }
237
+
238
+ /**
239
+ * Copy into `dir`, having first removed whatever is there.
240
+ *
241
+ * The clear is unconditional so there is one code path rather than two with
242
+ * an ordering between them. See `cloneForRehearsal` for why.
243
+ */
244
+ function attemptCopy(args: string[], timeout: number): number {
245
+ const dest = args[args.length - 1]!;
246
+ rmSync(dest, { recursive: true, force: true });
247
+ return spawnSync("cp", args, { encoding: "utf-8", timeout }).status ?? 1;
248
+ }
249
+
250
+ /**
251
+ * Top-level entries present in `root` but absent from its copy at `dir`.
252
+ *
253
+ * The copy has to BE the tree, not most of it. Compared at the top level
254
+ * only — a full walk would cost more than the clone did — which is enough to
255
+ * catch a truncated copy that exited 0.
256
+ *
257
+ * **Only a WHOLE top-level exclude is forgiven.** `.claude/worktrees` prunes
258
+ * a child, so `.claude` itself must still be present; matching on the first
259
+ * path component instead excuses a missing `.claude` entirely, which is the
260
+ * under-reporting this module exists to stop. Exported so that reading is one
261
+ * binding a test can feed a genuinely partial copy — the first version of
262
+ * SC-1514 re-implemented this comparison inside the test and therefore never
263
+ * ran the real one, and the mutation battery scored it 0.
264
+ */
265
+ export function missingTopLevel(root: string, dir: string): string[] {
266
+ const forgiven = new Set(REHEARSAL_EXCLUDES.filter(x => !x.includes("/")));
267
+ const got = new Set(readdirSync(dir));
268
+ return readdirSync(root).filter(n => !forgiven.has(n) && !got.has(n));
269
+ }
270
+
271
+ /**
272
+ * Remove `root/rel`, never passing through a symlink on the way.
273
+ *
274
+ * Two different answers, depending on WHERE the link is:
275
+ *
276
+ * - **The link is the path itself** (`node_modules -> /elsewhere/mods`):
277
+ * unlink it. `rmSync` on a link removes the link and leaves the target
278
+ * alone, and an excluded directory is one we did not want in the clone
279
+ * anyway. This is the common case — the pre-push hook makes exactly this
280
+ * link — and it has to stay cheap rather than refusing the audit.
281
+ *
282
+ * - **The link is an ANCESTOR** (`.claude -> /real/.claude`, pruning
283
+ * `.claude/worktrees`): leave it entirely alone. Unlinking it would throw
284
+ * away `.claude` — rules, agents, config — and the steps would then run
285
+ * over a tree missing the directory half of them read, reporting less than
286
+ * `--fix` will do. That is #398 itself, reintroduced by its own fix. It is
287
+ * also invisible to the completeness check, which cannot ask for `.claude`
288
+ * back while `.claude/worktrees` is on the exclude list.
289
+ *
290
+ * Deleting through it is worse still: `rmSync(..., { recursive: true })`
291
+ * follows a symlinked parent, so the consumer's real worktrees go. So
292
+ * neither — the link stays, and `escapingSymlinks` refuses the audit a
293
+ * moment later because an ancestor pointing out of the clone is exactly
294
+ * what it is for. Found by the commit security review.
295
+ */
296
+ function prunePathWithoutFollowingLinks(root: string, rel: string): void {
297
+ let current = root;
298
+ const parts = rel.split("/").filter(Boolean);
299
+ for (let i = 0; i < parts.length; i++) {
300
+ current = join(current, parts[i]!);
301
+ let st;
302
+ try { st = lstatSync(current); } catch { return; } // absent: nothing to prune
303
+ const last = i === parts.length - 1;
304
+ if (st.isSymbolicLink()) {
305
+ if (last) rmSync(current, { force: true });
306
+ return; // an ancestor link: prune nothing, and let the refusal catch it
307
+ }
308
+ if (!last && !st.isDirectory()) return;
309
+ }
310
+ rmSync(current, { recursive: true, force: true });
311
+ }
312
+
313
+ /** Throw the clone away. Safe to call twice. */
314
+ export function discardRehearsal(r: Rehearsal): void {
315
+ // `r.parent`, not `join(r.dir, "..")`. Deriving a deletion target by
316
+ // walking up from a path is how a cleanup ends up removing something it
317
+ // does not own; the owner is recorded at creation instead. Leaving the
318
+ // mkdtemp behind is the leak #437 is about, so it is the parent that goes.
319
+ rmSync(r.parent, { recursive: true, force: true });
320
+ }
321
+
322
+ /**
323
+ * The line audit prints so a reader knows the report was produced by running
324
+ * the real thing, not by predicting it — and knows what it did not run.
325
+ */
326
+ export function rehearsalNotice(r: Rehearsal): string {
327
+ const skipped = [...STEPS_NOT_REHEARSED.keys()].join(", ");
328
+ return `Mode: audit — rehearsed against a ${r.method} of the tree, which was then discarded. ` +
329
+ `Not rehearsed: ${skipped}. Pass --fix to apply.`;
330
+ }