rungate 0.4.0 → 0.5.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 (65) hide show
  1. package/config/behavioral-sc-map.json +170 -0
  2. package/config/brief-policies.json +28 -0
  3. package/config/ceremony-profiles.json +207 -0
  4. package/config/check-registry.json +114 -0
  5. package/config/matcher-registry.json +142 -0
  6. package/config/prove-evidence.schema.json +65 -0
  7. package/config/spec-policies.json +36 -0
  8. package/config/universal-rules.yaml +15 -0
  9. package/config/workflow-schema.json +279 -0
  10. package/lib/ac-quality.ts +119 -0
  11. package/lib/cli-commands.ts +7 -1
  12. package/lib/config-loader.ts +129 -5
  13. package/lib/conformity.ts +1122 -31
  14. package/lib/context-docs.ts +182 -0
  15. package/lib/create-brief.ts +22 -17
  16. package/lib/create-sc.ts +35 -8
  17. package/lib/doc-scan-targets.ts +435 -0
  18. package/lib/gate-check-audit.ts +9 -9
  19. package/lib/github.ts +195 -0
  20. package/lib/js-top-level-code.ts +27 -2
  21. package/lib/organize.ts +129 -40
  22. package/lib/package-closure.ts +387 -0
  23. package/lib/project-aliases.ts +100 -0
  24. package/lib/release-preflight.ts +352 -48
  25. package/lib/rungate-schema.ts +23 -1
  26. package/lib/sc-cover.ts +92 -1
  27. package/lib/sc-ids.ts +151 -0
  28. package/lib/scaffold/defaults.ts +40 -0
  29. package/lib/scaffold/managed-workflow.ts +125 -27
  30. package/lib/scaffold/owned-files.ts +6 -0
  31. package/lib/scaffold/profiles.ts +94 -0
  32. package/lib/scaffold/rehearsal.ts +355 -0
  33. package/lib/scaffold/steps.ts +787 -105
  34. package/lib/scaffold/write-steps.ts +208 -0
  35. package/lib/scratch-cleanup.ts +198 -0
  36. package/lib/scratch-roots.ts +94 -0
  37. package/lib/source-anchor.ts +144 -0
  38. package/lib/success-doc.ts +779 -0
  39. package/lib/suite-run-reading.ts +194 -0
  40. package/lib/test-census.ts +199 -0
  41. package/lib/trajectory.ts +377 -0
  42. package/lib/validators/spec-validators.ts +52 -35
  43. package/lib/workflow-security.ts +152 -7
  44. package/lib/workflow-test-harness.ts +349 -0
  45. package/lib/worktree-cleanup.ts +123 -7
  46. package/lib/worktree-repo.ts +165 -0
  47. package/package.json +10 -1
  48. package/scripts/audit-specs.ts +134 -37
  49. package/scripts/audit-transcript.ts +259 -0
  50. package/scripts/create-sc.ts +15 -1
  51. package/scripts/create-success.ts +162 -0
  52. package/scripts/detect-sc-drift.ts +200 -0
  53. package/scripts/extract-constraints.ts +16 -36
  54. package/scripts/scaffold-project.ts +51 -137
  55. package/scripts/split-spec.ts +315 -0
  56. package/scripts/sync-sc-status.ts +751 -0
  57. package/specs/SPEC-TEMPLATE.md +200 -0
  58. package/templates/SUCCESS-TEMPLATE.md +72 -0
  59. package/templates/agent-briefs/_shared.md +9 -0
  60. package/templates/agent-briefs/aditi.md +46 -0
  61. package/templates/agent-briefs/discovery.md +37 -0
  62. package/templates/agent-briefs/marcus.md +39 -0
  63. package/templates/agent-briefs/quinn.md +67 -0
  64. package/templates/agent-briefs/rook.md +40 -0
  65. package/templates/agent-briefs/serena.md +39 -0
@@ -0,0 +1,355 @@
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
+ * The root the operator actually named, kept so the notice can say what it
87
+ * was SUBSTITUTED for (#481).
88
+ *
89
+ * `dir` always comes from `mkdtemp` and is therefore always absolute. So the
90
+ * audit takes the absolute code path no matter what the operator typed, and
91
+ * `bunx rungate scaffold .` was rehearsed as an absolute invocation, passed,
92
+ * and then threw in the real run on every repo-root owned file. The
93
+ * rehearsal was not wrong about the steps; it was silent about the input it
94
+ * had replaced.
95
+ */
96
+ source: string;
97
+ }
98
+
99
+ /**
100
+ * Symlinks in the clone whose target resolves outside it.
101
+ *
102
+ * **A rehearsal is only a rehearsal while every write lands in the copy, and
103
+ * a symlink is a hole straight through the floor.** `cp -R` preserves
104
+ * symlinks rather than following them, so a clone of a tree containing
105
+ * `AGENTS.md -> /elsewhere/AGENTS.md` carries a link to the ORIGINAL file,
106
+ * and the first step that writes `AGENTS.md` overwrites it. Reproduced
107
+ * directly: write through a cloned symlink, read the original, see the new
108
+ * bytes.
109
+ *
110
+ * That is #370's damage — scaffold destroying a real file — arriving through
111
+ * the preview built to prevent it, and in the one mode whose entire promise
112
+ * is that it writes nothing. Found by the commit security review.
113
+ *
114
+ * Reported rather than deleted. Removing the links would let the audit
115
+ * proceed over a tree that is not the consumer's, so it would answer a
116
+ * question nobody asked; `.claude/rules/config-access.md` is the governing
117
+ * idea — a reading that cannot be taken safely is UNMEASURED, and UNMEASURED
118
+ * is not SKIP.
119
+ */
120
+ export function escapingSymlinks(dir: string): string[] {
121
+ const root = realpathSync(dir);
122
+ const out: string[] = [];
123
+ const walk = (rel: string) => {
124
+ let entries;
125
+ try {
126
+ entries = readdirSync(join(root, rel), { withFileTypes: true });
127
+ } catch (err) {
128
+ // NOT `return`. A directory we cannot read is a directory whose
129
+ // symlinks we did not check, and a check that skips what it cannot
130
+ // see reports the same empty list as a tree with nothing wrong —
131
+ // `.claude/rules/checks-must-be-able-to-fail.md`'s fail-open shape,
132
+ // found by the commit security review. Unreadable counts as
133
+ // escaping, so the audit refuses rather than previewing blind.
134
+ out.push(`${rel || "."} (unreadable: ${(err as Error).message})`);
135
+ return;
136
+ }
137
+ for (const e of entries) {
138
+ const child = rel ? join(rel, e.name) : e.name;
139
+ if (e.isSymbolicLink()) {
140
+ if (linkEscapes(root, child)) out.push(child);
141
+ } else if (e.isDirectory()) {
142
+ walk(child);
143
+ }
144
+ }
145
+ };
146
+ walk("");
147
+ return out.sort();
148
+ }
149
+
150
+ /**
151
+ * Does the link at `root/rel` resolve outside `root`?
152
+ *
153
+ * `realpathSync` is right for a link whose target exists and wrong for one
154
+ * whose target does not: it throws, and the first version treated a throw as
155
+ * "resolves to the link's own path", i.e. inside the root, i.e. safe. A
156
+ * DANGLING link to `/etc/thing` was therefore not flagged — and a step that
157
+ * writes through it creates `/etc/thing`. A dangling link is the more
158
+ * dangerous case, not the less, because writing is exactly what makes the
159
+ * target exist. Found by the commit security review.
160
+ */
161
+ function linkEscapes(root: string, rel: string): boolean {
162
+ const link = join(root, rel);
163
+ try {
164
+ const target = realpathSync(link);
165
+ return target !== root && !target.startsWith(root + sep);
166
+ } catch {
167
+ // Unresolvable: fall back to the literal target, resolved against the
168
+ // link's own directory the way the kernel would.
169
+ try {
170
+ const literal = resolve(join(link, ".."), readlinkSync(link));
171
+ return literal !== root && !literal.startsWith(root + sep);
172
+ } catch {
173
+ // Cannot even read the link. Unknown is not safe.
174
+ return true;
175
+ }
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Copy `root` somewhere disposable.
181
+ *
182
+ * `.git` is copied rather than skipped: five steps shell out to
183
+ * `git -C <root>` for the origin URL, a file's last-commit date and
184
+ * `status --porcelain`, and a clone with no repository would make those steps
185
+ * take different branches than they will under `--fix` — which is the exact
186
+ * disagreement this module exists to remove.
187
+ */
188
+ export function cloneForRehearsal(root: string): Rehearsal {
189
+ const parent = mkdtempSync(join(tmpdir(), "rungate-rehearsal-"));
190
+ const dir = join(parent, "tree");
191
+ const fail = (why: string): never => {
192
+ rmSync(parent, { recursive: true, force: true });
193
+ throw new Error(`audit did NOT run: ${why}`);
194
+ };
195
+
196
+ // `-c` asks for an APFS clonefile. It fails on filesystems that cannot do
197
+ // it, so the fallback is explicit rather than a silent slow path.
198
+ //
199
+ // Both attempts go through `attemptCopy`, which clears the destination
200
+ // first. A failed `cp` may have copied some of the tree before giving up,
201
+ // and falling back on top of that leaves a PARTIAL clone — the steps then
202
+ // run over a tree missing files, report less than `--fix` will do, and
203
+ // look like a clean preview, which is this module's whole subject. The
204
+ // first draft cleared only in the fallback, and the mutation battery
205
+ // scored that guard 0: `cp -Rc` succeeds on every machine the tests run
206
+ // on, so no test could ever reach the second branch. One shared helper
207
+ // removes the ordering rather than testing it.
208
+ let method: Rehearsal["method"] = "clone";
209
+ if (attemptCopy(["-Rc", root, dir], 300_000) !== 0) {
210
+ if (attemptCopy(["-R", root, dir], 600_000) !== 0) {
211
+ return fail("the tree could not be copied");
212
+ }
213
+ method = "copy";
214
+ }
215
+
216
+ // Pruning happens through `rmSync(..., { recursive: true })`, which
217
+ // follows a symlinked PARENT. `.claude/worktrees` in a tree where
218
+ // `.claude -> /real/.claude` therefore resolves outside the clone and
219
+ // deletes the consumer's real worktrees — a destructive path traversal
220
+ // performed by the mode that promises to write nothing. Found by the
221
+ // commit security review.
222
+ //
223
+ // So nothing is deleted through a symlink. Each excluded path is walked
224
+ // component by component; the moment a component is a link, the link
225
+ // itself is unlinked (never followed) and the walk stops. `node_modules`
226
+ // being a symlink is the common case — the pre-push hook makes one — and
227
+ // must stay cheap rather than refusing the audit.
228
+ for (const rel of REHEARSAL_EXCLUDES) {
229
+ prunePathWithoutFollowingLinks(dir, rel);
230
+ }
231
+
232
+ const missing = missingTopLevel(root, dir);
233
+ if (missing.length > 0) {
234
+ return fail(`the copy is incomplete — ${missing.length} top-level entr(ies) missing: ${missing.slice(0, 5).join(", ")}`);
235
+ }
236
+
237
+ const escaping = escapingSymlinks(dir);
238
+ if (escaping.length > 0) {
239
+ return fail(
240
+ `the tree contains ${escaping.length} symlink(s) pointing outside it, and a step writing through one ` +
241
+ `would modify the real file rather than the copy — which is the damage a preview exists to prevent (#370). ` +
242
+ `Offending paths: ${escaping.slice(0, 5).join(", ")}${escaping.length > 5 ? ", …" : ""}. ` +
243
+ `Re-run with --fix if you intend those writes, or replace the symlinks with real files.`,
244
+ );
245
+ }
246
+
247
+ return { dir, parent, method, source: root };
248
+ }
249
+
250
+ /**
251
+ * Copy into `dir`, having first removed whatever is there.
252
+ *
253
+ * The clear is unconditional so there is one code path rather than two with
254
+ * an ordering between them. See `cloneForRehearsal` for why.
255
+ */
256
+ function attemptCopy(args: string[], timeout: number): number {
257
+ const dest = args[args.length - 1]!;
258
+ rmSync(dest, { recursive: true, force: true });
259
+ return spawnSync("cp", args, { encoding: "utf-8", timeout }).status ?? 1;
260
+ }
261
+
262
+ /**
263
+ * Top-level entries present in `root` but absent from its copy at `dir`.
264
+ *
265
+ * The copy has to BE the tree, not most of it. Compared at the top level
266
+ * only — a full walk would cost more than the clone did — which is enough to
267
+ * catch a truncated copy that exited 0.
268
+ *
269
+ * **Only a WHOLE top-level exclude is forgiven.** `.claude/worktrees` prunes
270
+ * a child, so `.claude` itself must still be present; matching on the first
271
+ * path component instead excuses a missing `.claude` entirely, which is the
272
+ * under-reporting this module exists to stop. Exported so that reading is one
273
+ * binding a test can feed a genuinely partial copy — the first version of
274
+ * SC-1514 re-implemented this comparison inside the test and therefore never
275
+ * ran the real one, and the mutation battery scored it 0.
276
+ */
277
+ export function missingTopLevel(root: string, dir: string): string[] {
278
+ const forgiven = new Set(REHEARSAL_EXCLUDES.filter(x => !x.includes("/")));
279
+ const got = new Set(readdirSync(dir));
280
+ return readdirSync(root).filter(n => !forgiven.has(n) && !got.has(n));
281
+ }
282
+
283
+ /**
284
+ * Remove `root/rel`, never passing through a symlink on the way.
285
+ *
286
+ * Two different answers, depending on WHERE the link is:
287
+ *
288
+ * - **The link is the path itself** (`node_modules -> /elsewhere/mods`):
289
+ * unlink it. `rmSync` on a link removes the link and leaves the target
290
+ * alone, and an excluded directory is one we did not want in the clone
291
+ * anyway. This is the common case — the pre-push hook makes exactly this
292
+ * link — and it has to stay cheap rather than refusing the audit.
293
+ *
294
+ * - **The link is an ANCESTOR** (`.claude -> /real/.claude`, pruning
295
+ * `.claude/worktrees`): leave it entirely alone. Unlinking it would throw
296
+ * away `.claude` — rules, agents, config — and the steps would then run
297
+ * over a tree missing the directory half of them read, reporting less than
298
+ * `--fix` will do. That is #398 itself, reintroduced by its own fix. It is
299
+ * also invisible to the completeness check, which cannot ask for `.claude`
300
+ * back while `.claude/worktrees` is on the exclude list.
301
+ *
302
+ * Deleting through it is worse still: `rmSync(..., { recursive: true })`
303
+ * follows a symlinked parent, so the consumer's real worktrees go. So
304
+ * neither — the link stays, and `escapingSymlinks` refuses the audit a
305
+ * moment later because an ancestor pointing out of the clone is exactly
306
+ * what it is for. Found by the commit security review.
307
+ */
308
+ function prunePathWithoutFollowingLinks(root: string, rel: string): void {
309
+ let current = root;
310
+ const parts = rel.split("/").filter(Boolean);
311
+ for (let i = 0; i < parts.length; i++) {
312
+ current = join(current, parts[i]!);
313
+ let st;
314
+ try { st = lstatSync(current); } catch { return; } // absent: nothing to prune
315
+ const last = i === parts.length - 1;
316
+ if (st.isSymbolicLink()) {
317
+ if (last) rmSync(current, { force: true });
318
+ return; // an ancestor link: prune nothing, and let the refusal catch it
319
+ }
320
+ if (!last && !st.isDirectory()) return;
321
+ }
322
+ rmSync(current, { recursive: true, force: true });
323
+ }
324
+
325
+ /** Throw the clone away. Safe to call twice. */
326
+ export function discardRehearsal(r: Rehearsal): void {
327
+ // `r.parent`, not `join(r.dir, "..")`. Deriving a deletion target by
328
+ // walking up from a path is how a cleanup ends up removing something it
329
+ // does not own; the owner is recorded at creation instead. Leaving the
330
+ // mkdtemp behind is the leak #437 is about, so it is the parent that goes.
331
+ rmSync(r.parent, { recursive: true, force: true });
332
+ }
333
+
334
+ /**
335
+ * The line audit prints so a reader knows the report was produced by running
336
+ * the real thing, not by predicting it — and knows what it did not run.
337
+ */
338
+ /**
339
+ * What the rehearsal did, and — the half #481 was missing — what it did NOT.
340
+ *
341
+ * A rehearsal substitutes one input by construction: the root. Steps run
342
+ * against `r.dir`, which `mkdtemp` makes absolute, so nothing that depends on
343
+ * the FORM of the operator's argument is exercised. That is not a bug to fix;
344
+ * a rehearsal has to run somewhere else or it is not a rehearsal. It is a
345
+ * thing the notice has to SAY, because an unrehearsed input reported as
346
+ * rehearsed is `UNMEASURED is not SKIP` wearing a dry run's clothes: the
347
+ * audit printed `CREATED: project-state.json` for a write that threw.
348
+ */
349
+ export function rehearsalNotice(r: Rehearsal): string {
350
+ const skipped = [...STEPS_NOT_REHEARSED.keys()].join(", ");
351
+ return `Mode: audit — rehearsed against a ${r.method} of the tree, which was then discarded. ` +
352
+ `Not rehearsed: ${skipped}. ` +
353
+ `Root SUBSTITUTED: the steps ran against ${r.dir}, not ${r.source} — anything that depends ` +
354
+ `on the form of that argument is UNMEASURED by this audit. Pass --fix to apply.`;
355
+ }