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
package/lib/sc-cover.ts CHANGED
@@ -44,7 +44,7 @@
44
44
  import { readdirSync, readFileSync } from "fs";
45
45
  import { join } from "path";
46
46
 
47
- import { isBehavioralSC, matchPattern } from "./conformity";
47
+ import { collectTestableSpecs, isBehavioralSC, matchPattern, planSCTests } from "./conformity";
48
48
  import { buildScRegistry, isTemplateSpec, parseScDeclarations, type ScDeclaration } from "./sc-ids";
49
49
 
50
50
  export interface UncoveredSc {
@@ -148,3 +148,94 @@ export function ratchetViolations(
148
148
  }
149
149
  return out.sort();
150
150
  }
151
+
152
+ /**
153
+ * The two halves of "checked, and the engine can build no assertion" (#441).
154
+ *
155
+ * `UNMATCHED_CHECKED_RATCHET` was one number counting both, and its docblock
156
+ * read it as debt: SCs marked done that carry no assertion and are therefore
157
+ * wishes. That reading was right at 54. It stopped being right once the repo
158
+ * started writing criteria about REFUSALS, because the registry's whole
159
+ * vocabulary — file-exists, content-contains, count-threshold — is claims
160
+ * about the state of the tree, and there is no state of a tree that expresses
161
+ * "X refuses, and says which of two things happened".
162
+ *
163
+ * So the number rose on #397, #398 and #399 for criteria that are all covered
164
+ * by executed tests, and the only way to lower it would have been to rewrite
165
+ * them as weaker claims about file contents. A ratchet that rises whenever an
166
+ * issue writes a good behavioural criterion is measuring the matcher's
167
+ * vocabulary, not the project's honesty.
168
+ *
169
+ * - `unclaimed` — no test file declares it. The wish the old docblock meant.
170
+ * - `claimed` — a test file declares it per
171
+ * `.claude/rules/claiming-sc-coverage.md`, and the engine still cannot
172
+ * build the assertion. A measure of the vocabulary.
173
+ *
174
+ * `SUPERSEDED` ticks are excluded from BOTH, matching `uncoveredTickedScs`.
175
+ * A tick that points at its replacement is not a criterion anybody owes a
176
+ * test for, and leaving it in would have put one criterion in `unclaimed`
177
+ * that the census next door deliberately drops — a disagreement between two
178
+ * numbers about the same tree, arrived at by accident.
179
+ */
180
+ export interface UnmatchedSplit {
181
+ unclaimed: UncoveredSc[];
182
+ claimed: UncoveredSc[];
183
+ }
184
+
185
+ export function splitUnmatchedChecked(opts: {
186
+ projectRoot: string;
187
+ claimed: Set<string>;
188
+ scopedKey: (specFile: string, id: string) => string;
189
+ }): UnmatchedSplit {
190
+ const { projectRoot, claimed, scopedKey } = opts;
191
+ const out: UnmatchedSplit = { unclaimed: [], claimed: [] };
192
+
193
+ for (const [specFile, meta] of collectTestableSpecs(projectRoot)) {
194
+ for (const entry of planSCTests(meta.scs)) {
195
+ if (entry.kind !== "unmatched") continue;
196
+ if (isSuperseded(entry.sc.statement)) continue;
197
+ const row = { id: entry.sc.id, specFile, statement: entry.sc.statement };
198
+ if (claimed.has(scopedKey(specFile, entry.sc.id))) out.claimed.push(row);
199
+ else out.unclaimed.push(row);
200
+ }
201
+ }
202
+ return out;
203
+ }
204
+
205
+ /**
206
+ * Where the unclaimed half disagrees with the uncovered census next door.
207
+ *
208
+ * Measured before this existed: of 155 unclaimed criteria, **154** were
209
+ * already in `uncoveredTickedScs`'s census, which
210
+ * `test/ticked-sc-cover.test.ts` ratchets per spec, both directions, naming
211
+ * the ids. Banking the unclaimed count as a SECOND global number would have
212
+ * been two deciders answering one question — the fourth shape in
213
+ * `.claude/rules/checks-must-be-able-to-fail.md` — and a mutation of either
214
+ * would have left the other holding every case up.
215
+ *
216
+ * So this returns the DIFFERENCE rather than a count, and the test asserts
217
+ * the difference is exactly what is explained below. The per-spec ratchet
218
+ * stays the one place a new untested criterion is refused; this is the
219
+ * relationship between the two populations, checked rather than assumed.
220
+ *
221
+ * The two known residues, both of them the other function behaving correctly
222
+ * and this one being narrower:
223
+ *
224
+ * - `collectTestableSpecs` skips a spec whose frontmatter says
225
+ * `testable: no`, and `readSpecs` does not. `DA-COMPLIANCE-SPEC.md` is one.
226
+ * - `uncoveredTickedScs` also counts a criterion whose matcher MATCHES and
227
+ * then FAILS, which is not `unmatched` and so is invisible here.
228
+ */
229
+ export function unclaimedCensusResidue(opts: {
230
+ unclaimed: UncoveredSc[];
231
+ census: UncoveredSc[];
232
+ scopedKey: (specFile: string, id: string) => string;
233
+ }): { onlyUnclaimed: string[]; onlyCensus: string[] } {
234
+ const { scopedKey } = opts;
235
+ const a = new Set(opts.unclaimed.map(u => scopedKey(u.specFile, u.id)));
236
+ const b = new Set(opts.census.map(u => scopedKey(u.specFile, u.id)));
237
+ return {
238
+ onlyUnclaimed: [...a].filter(k => !b.has(k)).sort(),
239
+ onlyCensus: [...b].filter(k => !a.has(k)).sort(),
240
+ };
241
+ }
package/lib/sc-ids.ts CHANGED
@@ -140,6 +140,46 @@ export function isIssueShaped(id: string): boolean {
140
140
  return /^SC-\d$/.test(id);
141
141
  }
142
142
 
143
+ /**
144
+ * Ids at or above this number are reserved for test fixtures and will never
145
+ * be allocated to a real criterion (#399).
146
+ *
147
+ * **The namespace has two halves and only one of them was ever guarded.**
148
+ * `nextSCNumber`, `crossSpecCollisions`, `crossFormCollisions` and
149
+ * `requiresQualification` all reason over `specs/` — correctly, and blind to
150
+ * the other half. A test file that writes `- [ ] SC-9441: AGENTS.md exists`
151
+ * inside a string literal has put a checkbox declaration into the live
152
+ * namespace where no guard can see it, so the allocator proposes 900 as free,
153
+ * every collision detector agrees it is free, and the number collides with a
154
+ * literal the suite depends on. That is
155
+ * `.claude/rules/checks-must-be-able-to-fail.md`'s second shape: a detector
156
+ * narrower than what it detects.
157
+ *
158
+ * **It is not hypothetical.** `test/stale-issue-scanner.test.ts` plants
159
+ * `SC-379` and `SC-380` as fixtures, and
160
+ * `specs/CONFIG-DRIVEN-TESTING-SPEC.md:77-78` declares both as real tracked
161
+ * criteria. The collision #399 was filed to prevent had already landed.
162
+ *
163
+ * 9000 rather than 9900, which is what the issue proposed: the convention the
164
+ * tree already follows is 9000+, measured — 209 fixture mentions sit at
165
+ * 9001..9902 across eight files, against 24 strays below. Picking the floor
166
+ * the repo converged on costs no migrations that were not already needed, and
167
+ * `test/sc-claim-forms.test.ts` argued for the convention first.
168
+ */
169
+ export const FIXTURE_SC_FLOOR = 9000;
170
+
171
+ /**
172
+ * Is this id reserved for fixtures?
173
+ *
174
+ * ONE exported predicate, consulted by the allocator and by the stray guard,
175
+ * so there is a single binding to mutate rather than a convention each caller
176
+ * reimplements — which is what the four spec-only guards above already are.
177
+ */
178
+ export function isFixtureScId(id: string): boolean {
179
+ const n = Number(id.replace(/^SC-/, ""));
180
+ return Number.isInteger(n) && n >= FIXTURE_SC_FLOOR;
181
+ }
182
+
143
183
  /**
144
184
  * The registry: which spec files declare each id.
145
185
  *
@@ -342,3 +382,114 @@ export function isQualifiedBy(source: string, at: number, specFile: string): boo
342
382
  .toLowerCase();
343
383
  return qualifierTokens(specFile).some(t => window.includes(t.toLowerCase()));
344
384
  }
385
+
386
+ // ── The other half of the namespace: ids spelled in source ──
387
+
388
+ /** Directories whose sources can spell an SC id. */
389
+ export const SC_SOURCE_DIRS: readonly string[] = ["test", "lib", "scripts", "gates"];
390
+
391
+ /** One mention of an SC id in a source file. */
392
+ export interface ScMentionInSource {
393
+ id: string;
394
+ file: string;
395
+ /** True when the mention sits in a comment rather than in code. */
396
+ inComment: boolean;
397
+ }
398
+
399
+ /**
400
+ * Every numeric SC id spelled anywhere under `SC_SOURCE_DIRS`.
401
+ *
402
+ * Deliberately NOT restricted to declaring forms. The allocator's question is
403
+ * "could handing out this number break something", and a fixture spelled in
404
+ * any position — a string literal, an array of ids, a `-t` filter — breaks
405
+ * the same way once a spec claims the number. `commentClaimForm` draws the
406
+ * narrower line for CREDIT, and that line is settled and must not move
407
+ * (`.claude/rules/claiming-sc-coverage.md`); this is a different question
408
+ * asked for a different purpose, and widening it here cannot credit anything.
409
+ */
410
+ export function scMentionsInSource(root: string): ScMentionInSource[] {
411
+ const { readdirSync, readFileSync } = require("fs") as typeof import("fs");
412
+ const { join } = require("path") as typeof import("path");
413
+ const { commentMask } = require("./strip-js-comments") as typeof import("./strip-js-comments");
414
+ const out: ScMentionInSource[] = [];
415
+
416
+ const walk = (dir: string): void => {
417
+ let entries;
418
+ try {
419
+ entries = readdirSync(dir, { withFileTypes: true });
420
+ } catch {
421
+ return; // a source dir this consumer does not have
422
+ }
423
+ for (const e of entries) {
424
+ if (e.name === "node_modules" || e.name === ".git") continue;
425
+ const p = join(dir, e.name);
426
+ if (e.isDirectory()) { walk(p); continue; }
427
+ if (!e.name.endsWith(".ts") && !e.name.endsWith(".js")) continue;
428
+ const src = readFileSync(p, "utf-8");
429
+ if (!src.includes("SC-")) continue;
430
+ const mask = commentMask(src);
431
+ for (const m of src.matchAll(/SC-(\d+)(?!\d)/g)) {
432
+ out.push({ id: m[0], file: p.slice(root.length + 1), inComment: mask[m.index!] === true });
433
+ }
434
+ }
435
+ };
436
+ for (const d of SC_SOURCE_DIRS) walk(join(root, d));
437
+ return out;
438
+ }
439
+
440
+ /** Ids spelled in source, with the files that spell them. */
441
+ export function scIdsSpelledInSource(root: string): Map<string, string[]> {
442
+ const found = new Map<string, string[]>();
443
+ for (const m of scMentionsInSource(root)) {
444
+ const files = found.get(m.id) ?? [];
445
+ if (!files.includes(m.file)) files.push(m.file);
446
+ found.set(m.id, files);
447
+ }
448
+ return found;
449
+ }
450
+
451
+ /**
452
+ * Fixture ids living in the live namespace: spelled in source, declared by
453
+ * no spec, and below `FIXTURE_SC_FLOOR`.
454
+ *
455
+ * "Declared by no spec" is what makes it a fixture rather than a coverage
456
+ * claim. `// covers SC-640` names a real criterion and must not be moved;
457
+ * `{ id: "SC-9441", done: true }` names nothing and is a number the
458
+ * allocator is free to hand out tomorrow. The difference is in the registry,
459
+ * not in the spelling, which is why this takes one.
460
+ *
461
+ * ## What this deliberately does NOT catch, and why
462
+ *
463
+ * A fixture reusing an id a spec ALREADY declares is invisible here, and
464
+ * that case is real — two instances, both found by hand rather than by any
465
+ * guard:
466
+ *
467
+ * - `test/stale-issue-scanner.test.ts` plants `SC-379`/`SC-380`, both
468
+ * declared in `specs/CONFIG-DRIVEN-TESTING-SPEC.md:77-78`.
469
+ * - `test/sync-sc-status-matching.test.ts` planted `SC-91`/`SC-92`/`SC-93`,
470
+ * all declared in `specs/bootstrap-data-flow/success-criteria.md`, under a
471
+ * comment reading "with IDs this repo does not use so the file does not
472
+ * claim them" — true when written, false by the time it mattered, and
473
+ * nothing could notice.
474
+ *
475
+ * **Catching those by POSITION was tried and is wrong.** "In a comment it is
476
+ * a citation, in code it is a fixture" reports 338 violations on this tree,
477
+ * because `test("SC-1504: …")` is a test TITLE — a claim form
478
+ * `.claude/rules/claiming-sc-coverage.md` lists as valid and settled. And a
479
+ * planted fixture string containing `test("SC-91: …")` is textually
480
+ * identical to a real title, so no position rule separates them. Widening
481
+ * here would have swapped a guard that misses two cases for one that
482
+ * misreports three hundred, which is the worse trade in the direction this
483
+ * repo has already chosen: toward NOT reporting.
484
+ *
485
+ * The residue is filed rather than hidden. See #399's PR.
486
+ */
487
+ export function strayFixtureIds(root: string, reg: ScRegistry): Map<string, string[]> {
488
+ const stray = new Map<string, string[]>();
489
+ for (const [id, files] of scIdsSpelledInSource(root)) {
490
+ if (reg.declaredById.has(id)) continue;
491
+ if (isFixtureScId(id)) continue;
492
+ stray.set(id, files);
493
+ }
494
+ return stray;
495
+ }
@@ -23,9 +23,36 @@ export interface HookRegistration {
23
23
  hookFor: string;
24
24
  command: string;
25
25
  enabled: boolean;
26
+ /**
27
+ * Which settings file is supposed to register this hook (#479).
28
+ *
29
+ * `user` — machine-wide, registered in `~/.claude/settings.json`, as
30
+ * `HOOK-ARCHITECTURE-SPEC.md` SC-518 requires for anything that must fire in
31
+ * sessions rooted outside the project. The repo cannot read that file, so
32
+ * the reconciler reports these UNMEASURED and never counts them as checked.
33
+ *
34
+ * `project` — acts on the current project's own files or agents, registered
35
+ * in the committed `.claude/settings.json`. Repo-owned, so "is it
36
+ * registered" is a fact CI can check — which is the half #199 concluded was
37
+ * impossible, having measured only the user-scoped eleven.
38
+ *
39
+ * Required, deliberately. An absent scope defaulting to `user` would excuse
40
+ * every entry that forgot one, and that is how sixteen entries came to claim
41
+ * `enabled: true` with five of them inert.
42
+ */
43
+ scope: "project" | "user";
26
44
  matcher?: string;
27
45
  description: string;
28
46
  deployToConsumers?: boolean;
47
+ /**
48
+ * Why an `enabled: false` entry is off. Required when it is (#479 SC-1662).
49
+ *
50
+ * Off and never-registered look identical in a file; the difference is
51
+ * whether anyone decided. Without the reason, the next person to read the
52
+ * inventory cannot tell a considered no from an oversight, and the fastest
53
+ * way to resolve that ambiguity is to flip it back on.
54
+ */
55
+ disabledReason?: string;
29
56
  }
30
57
 
31
58
  /**
@@ -89,6 +116,10 @@ export function buildDefaultRoles(): Record<string, Record<string, unknown>> {
89
116
  *
90
117
  * `${RUNGATE_HOOKS_DIR}` stays unexpanded on disk — deployHooksToConsumers
91
118
  * resolves it at deploy time, so the file survives the harness moving.
119
+ *
120
+ * Every entry carries a `scope` (#479). It is not decoration: it is the only
121
+ * thing that tells a reconciler whether "not registered here" is a defect or
122
+ * a fact about a file the repo does not own.
92
123
  */
93
124
  export function buildDefaultHooks(): HookRegistration[] {
94
125
  return [
@@ -97,6 +128,7 @@ export function buildDefaultHooks(): HookRegistration[] {
97
128
  hookFor: "PreToolUse",
98
129
  command: "bun ${RUNGATE_HOOKS_DIR}/BashToolGuard.hook.ts",
99
130
  enabled: true,
131
+ scope: "user",
100
132
  matcher: "Bash",
101
133
  description: "Blocks cat/head/tail file reading — agents must use the Read tool",
102
134
  },
@@ -105,6 +137,7 @@ export function buildDefaultHooks(): HookRegistration[] {
105
137
  hookFor: "PreToolUse",
106
138
  command: "bun ${RUNGATE_HOOKS_DIR}/TestSuiteGuard.hook.ts",
107
139
  enabled: true,
140
+ scope: "user",
108
141
  matcher: "Bash",
109
142
  description: "Blocks a third full test suite run in one session — forces targeted tests",
110
143
  },
@@ -113,6 +146,7 @@ export function buildDefaultHooks(): HookRegistration[] {
113
146
  hookFor: "PreToolUse",
114
147
  command: "bun ${RUNGATE_HOOKS_DIR}/AgentBriefGuard.hook.ts",
115
148
  enabled: true,
149
+ scope: "project",
116
150
  matcher: "Agent",
117
151
  description: "Validates agent brief templates and enforces the ship-active marker",
118
152
  },
@@ -121,6 +155,7 @@ export function buildDefaultHooks(): HookRegistration[] {
121
155
  hookFor: "SubagentStop",
122
156
  command: "bun ${RUNGATE_HOOKS_DIR}/AgentVerdictCapture.hook.ts",
123
157
  enabled: true,
158
+ scope: "user",
124
159
  description: "Captures agent verdicts and writes them to workflow-state.json",
125
160
  },
126
161
  {
@@ -128,6 +163,7 @@ export function buildDefaultHooks(): HookRegistration[] {
128
163
  hookFor: "PostToolUse",
129
164
  command: "bun ${RUNGATE_HOOKS_DIR}/AutoVerifyGate.hook.ts",
130
165
  enabled: true,
166
+ scope: "user",
131
167
  matcher: "Agent",
132
168
  description: "Nudges the DA to run the verify gate after an agent completes",
133
169
  },
@@ -136,6 +172,7 @@ export function buildDefaultHooks(): HookRegistration[] {
136
172
  hookFor: "PostToolUse",
137
173
  command: "bun ${RUNGATE_HOOKS_DIR}/CommitEnforcement.hook.ts",
138
174
  enabled: true,
175
+ scope: "user",
139
176
  matcher: "Agent",
140
177
  description: "Detects uncommitted changes left behind in agent worktrees",
141
178
  },
@@ -144,6 +181,7 @@ export function buildDefaultHooks(): HookRegistration[] {
144
181
  hookFor: "PreToolUse",
145
182
  command: "bun ${RUNGATE_HOOKS_DIR}/GateEnforcement.hook.ts",
146
183
  enabled: true,
184
+ scope: "user",
147
185
  matcher: ".*",
148
186
  description: "Nags on gate failures and blocks Skill calls after max strikes",
149
187
  },
@@ -152,6 +190,7 @@ export function buildDefaultHooks(): HookRegistration[] {
152
190
  hookFor: "PostCompact",
153
191
  command: "bun ${RUNGATE_HOOKS_DIR}/PostCompact.hook.ts",
154
192
  enabled: true,
193
+ scope: "user",
155
194
  description: "Re-injects critical rules after context window compaction",
156
195
  },
157
196
  {
@@ -159,6 +198,7 @@ export function buildDefaultHooks(): HookRegistration[] {
159
198
  hookFor: "SessionStart",
160
199
  command: "bun ${RUNGATE_HOOKS_DIR}/StaleTTLCleanup.hook.ts",
161
200
  enabled: true,
201
+ scope: "user",
162
202
  description: "Cleans up stale workflow-state.json and ship-active files",
163
203
  },
164
204
  ];
@@ -147,6 +147,78 @@ function jobsSectionOf(sections: Section[]): Section | undefined {
147
147
  return sections.find(s => s.key === "jobs");
148
148
  }
149
149
 
150
+ /** Every top-level key a workflow declares, in file order (#482). */
151
+ export function topLevelKeyOrder(text: string): string[] {
152
+ return splitTopLevel(text).map(s => s.key).filter(k => k !== "");
153
+ }
154
+
155
+ /**
156
+ * Top-level keys declared more than once, in first-seen order (#482).
157
+ *
158
+ * YAML forbids duplicate mapping keys and GitHub Actions rejects the file, so
159
+ * this is not a style question — it is a workflow that will not run. It
160
+ * happens when somebody restores a block they believe the merge deleted and
161
+ * the original is still further down, which is the incident this issue is
162
+ * about.
163
+ *
164
+ * The repo has no YAML dependency on purpose — every reader in this file
165
+ * parses the shape by hand — so the property detected is the one that causes
166
+ * the parse error rather than the parser's message.
167
+ */
168
+ export function duplicateTopLevelKeys(text: string): string[] {
169
+ const seen = new Set<string>();
170
+ const dupes: string[] = [];
171
+ for (const key of topLevelKeyOrder(text)) {
172
+ if (seen.has(key) && !dupes.includes(key)) dupes.push(key);
173
+ seen.add(key);
174
+ }
175
+ return dupes;
176
+ }
177
+
178
+ export interface MovedKey {
179
+ key: string;
180
+ from: number;
181
+ to: number;
182
+ }
183
+
184
+ /**
185
+ * Top-level keys that changed line position between two versions (#482).
186
+ *
187
+ * **Keys added or removed are excluded, deliberately.** They shift the index
188
+ * of everything after them, so counting those as movement makes the signal
189
+ * fire on the ordinary case — a scaffold adding its own key — and a report
190
+ * that fires every time is a report nobody reads. What is left is the thing
191
+ * worth saying: a key that exists in both and is somewhere else.
192
+ */
193
+ export function movedTopLevelKeys(before: string, after: string): MovedKey[] {
194
+ const index = (text: string): Map<string, number> => {
195
+ const out = new Map<string, number>();
196
+ const lines = text.split("\n");
197
+ for (let i = 0; i < lines.length; i++) {
198
+ const m = TOP_LEVEL_KEY.exec(lines[i]);
199
+ if (m && !out.has(m[1])) out.set(m[1], i);
200
+ }
201
+ return out;
202
+ };
203
+ const b = index(before);
204
+ const a = index(after);
205
+
206
+ // Movement is a change of RANK among the keys both versions have, not a
207
+ // change of line number. A key inserted above `b` moves `b`'s line and
208
+ // leaves its position in the file's structure exactly where the consumer
209
+ // put it; reporting that would fire on every scaffold that adds a key.
210
+ const common = [...b.keys()].filter(k => a.has(k));
211
+ const rankBefore = new Map(common.slice().sort((x, y) => b.get(x)! - b.get(y)!).map((k, i) => [k, i]));
212
+ const rankAfter = new Map(common.slice().sort((x, y) => a.get(x)! - a.get(y)!).map((k, i) => [k, i]));
213
+
214
+ const moved: MovedKey[] = [];
215
+ for (const key of common) {
216
+ if (rankBefore.get(key) === rankAfter.get(key)) continue;
217
+ moved.push({ key, from: b.get(key)!, to: a.get(key)! });
218
+ }
219
+ return moved;
220
+ }
221
+
150
222
  /** Every job name in a workflow file, in file order. */
151
223
  export function jobNames(text: string): string[] {
152
224
  const jobs = jobsSectionOf(splitTopLevel(text));
@@ -179,36 +251,62 @@ export function mergeManagedWorkflow(before: string, generated: string): string
179
251
  const beforeJobs = jobsSectionOf(b);
180
252
  const beforeByKey = new Map(b.filter(s => s.key !== "").map(s => [s.key, s] as const));
181
253
 
182
- const out: string[] = [];
183
- for (const section of g) {
184
- // The ownership rule, and the only one this file needs to state:
185
- //
186
- // the harness owns the JOBS it generates, and its own preamble.
187
- // every other top-level key belongs to the consumer, if the consumer
188
- // already has one.
189
- //
190
- // The generated `on:` is a default for a file that does not exist yet, not
191
- // a claim on one that does. Replacing a consumer's `on:` wholesale is how
192
- // DailyBriefDashboard lost its `workflow_dispatch` trigger and its
193
- // `paths-ignore` list to a write that reported success — and a consumer's
194
- // trailing comments live in the section of the key above them, so this is
195
- // also what keeps those.
196
- if (section.key === "jobs" && beforeJobs) out.push(...mergeJobsSection(beforeJobs, section));
197
- else if (section.key !== "" && beforeByKey.has(section.key)) {
198
- out.push(...beforeByKey.get(section.key)!.lines);
199
- } else out.push(...section.lines);
200
- }
254
+ // Walk the CONSUMER's sections, not the generated ones (#482).
255
+ //
256
+ // The previous form emitted the generated order and appended the consumer's
257
+ // extra keys at the end. Nothing was lost — `lostLines` is a line set and
258
+ // correctly stayed quiet — but `concurrency:` arrived 460 lines below the
259
+ // comment introducing it, because a comment above a top-level key lives in
260
+ // the section of the key ABOVE it and so does not travel. A reader of the
261
+ // resulting diff concluded the block had been deleted and restored it by
262
+ // hand; the file then declared the key twice and stopped parsing.
263
+ //
264
+ // So the consumer's order is the order. The harness owns the jobs it
265
+ // generates and its own preamble; it does not own where in the file the
266
+ // consumer's keys sit, and moving them manufactures a deletion signal that
267
+ // is more expensive than a deletion.
268
+ const generatedByKey = new Map(g.filter(s => s.key !== "").map(s => [s.key, s] as const));
269
+ const emitted = new Set<string>();
270
+ const sectionFor = (section: Section): string[] => {
271
+ if (section.key === "jobs" && beforeJobs) {
272
+ const generatedJobs = generatedByKey.get("jobs");
273
+ return generatedJobs ? mergeJobsSection(beforeJobs, generatedJobs) : section.lines;
274
+ }
275
+ // Every non-jobs key the consumer already has is the consumer's, whichever
276
+ // side we are walking. The generated `on:` is a default for a file that
277
+ // does not exist yet, not a claim on one that does.
278
+ if (section.key !== "" && beforeByKey.has(section.key)) return beforeByKey.get(section.key)!.lines;
279
+ return section.lines;
280
+ };
201
281
 
202
- const extraSections = b.filter(s => s.key !== "" && !generatedKeys.has(s.key));
203
- if (extraSections.length > 0) {
204
- while (out.length > 0 && out[out.length - 1].trim() === "") out.pop();
205
- for (const section of extraSections) {
206
- out.push("");
207
- out.push(...splitTrailingBlanks(section.lines)[0]);
282
+ const ordered: string[] = [];
283
+ for (const section of b) {
284
+ if (section.key === "") {
285
+ // The consumer's leading preamble is replaced by the generated one,
286
+ // which carries the managed banner. It is the one part of the file the
287
+ // harness does author.
288
+ const genHead = g.find(s => s.key === "");
289
+ if (genHead) ordered.push(...genHead.lines);
290
+ continue;
208
291
  }
209
- out.push("");
292
+ ordered.push(...sectionFor(section));
293
+ emitted.add(section.key);
210
294
  }
211
- return out.join("\n");
295
+ // Generated keys the consumer does not have, appended in generated order.
296
+ // Preserving the consumer's layout must not mean refusing to take anything
297
+ // new.
298
+ for (const section of g) {
299
+ if (section.key === "" || emitted.has(section.key)) continue;
300
+ ordered.push(...splitTrailingBlanks(section.lines)[0]);
301
+ ordered.push("");
302
+ }
303
+ // A `before` with no top-level key at all — empty, or something that is not
304
+ // a workflow — has no layout to preserve and nothing to carry, so the
305
+ // generated file is the answer. Returned directly rather than walked by a
306
+ // second merge loop: two code paths producing the same bytes for the same
307
+ // input is one decider too many, and the dead one is the one no mutation
308
+ // can reach.
309
+ return b.some(s => s.key !== "") ? ordered.join("\n") : generated;
212
310
  }
213
311
 
214
312
  /**
@@ -129,6 +129,12 @@ export const OWNED_FILES: OwnedFile[] = [
129
129
  customize: "DA-owned (#296) — generated from project-state.json by the DA",
130
130
  avoid: "Don't edit directly; don't expect re-scaffold to update it",
131
131
  },
132
+ {
133
+ path: "SUCCESS.md",
134
+ strategy: "create-only",
135
+ customize: "Seeded as a template (#485) — fill in the claims; `bunx rungate create-success` re-seeds",
136
+ avoid: "Don't leave it as the seed; SUCCESS-1 refuses a template, and re-scaffold will not fill it in",
137
+ },
132
138
  ];
133
139
 
134
140
  /**
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Scaffold profiles — how much of the harness a project opted into.
3
+ *
4
+ * `full` is everything, and is the default: no existing consumer changes
5
+ * behaviour by upgrading. `minimal` produces the AI-friendly repo — AGENTS.md,
6
+ * the CLAUDE.md bridge, `.claude/rules/`, `specs/` and `docs/` layout,
7
+ * project-state, and the conformity test — and leaves out the parts that only
8
+ * mean something to a project running the ship harness.
9
+ *
10
+ * Why this exists: before #449 there was no way to get the structure without
11
+ * the harness. A consumer repo was hand-built around the gap, which put it
12
+ * outside the thing that keeps projects conformant — the drift it will develop
13
+ * is exactly what the scaffold exists to prevent.
14
+ *
15
+ * **Both maps carry a reason per entry, deliberately.** An exclusion with no
16
+ * stated reason is indistinguishable from an oversight, and the next reader
17
+ * cannot tell whether deleting it is safe. `STEPS_NOT_REHEARSED` in
18
+ * `./rehearsal.ts` is the pattern and the same rename protection applies:
19
+ * `test/scaffold-profile.test.ts` asserts every named step and rule still
20
+ * exists, so a rename cannot silently empty a map and re-enable the step.
21
+ */
22
+
23
+ export type ScaffoldProfile = "full" | "minimal";
24
+
25
+ export const SCAFFOLD_PROFILES: readonly ScaffoldProfile[] = ["full", "minimal"] as const;
26
+
27
+ export const DEFAULT_PROFILE: ScaffoldProfile = "full";
28
+
29
+ /**
30
+ * Write steps `minimal` does not run, by the exported symbol each is called
31
+ * through in `./write-steps.ts`.
32
+ */
33
+ export const STEPS_NOT_MINIMAL: ReadonlyMap<string, string> = new Map([
34
+ [
35
+ // The path is described rather than spelled out because this reason is a
36
+ // STRING, and CONFIG-1 counts a config path literal in a string as a
37
+ // direct access site. `scanConfigAccess` strips comments before matching,
38
+ // so a doc comment naming the path is fine — a map value is not. That
39
+ // distinction is deliberate: CONFIG-2 exists because ship.js hid eleven
40
+ // real config reads inside template literals. Spelling it out here cost
41
+ // two red tests on the first run of this file.
42
+ "generateOrAuditProjectHarness",
43
+ "writes the harness config directory, which configures a ship pipeline this project does not run",
44
+ ],
45
+ [
46
+ "generateAgentBriefsStep",
47
+ "writes marcus.md and quinn.md, briefs for agents only the ship workflow spawns",
48
+ ],
49
+ [
50
+ "createCiWorkflows",
51
+ "writes ci.yml and gates.yml, which invoke harness gates the project has not opted into",
52
+ ],
53
+ ]);
54
+
55
+ /**
56
+ * Scoped rules `minimal` does not write, by filename in `.claude/rules/`.
57
+ *
58
+ * A rule is instructions to an agent. Shipping one that points at machinery
59
+ * the project does not have is worse than shipping nothing — the agent follows
60
+ * it, the command is absent, and the failure looks like the agent's fault.
61
+ */
62
+ export const RULES_NOT_MINIMAL: ReadonlyMap<string, string> = new Map([
63
+ [
64
+ "ship-workflow.md",
65
+ 'instructs an agent to route all work through Skill("ship"), which has no harness here to route into',
66
+ ],
67
+ [
68
+ "harness-managed.md",
69
+ "lists harness-owned files as do-not-edit, most of which this profile never writes",
70
+ ],
71
+ ]);
72
+
73
+ export function isStepIncluded(step: string, profile: ScaffoldProfile): boolean {
74
+ return profile === "full" || !STEPS_NOT_MINIMAL.has(step);
75
+ }
76
+
77
+ export function isRuleIncluded(filename: string, profile: ScaffoldProfile): boolean {
78
+ return profile === "full" || !RULES_NOT_MINIMAL.has(filename);
79
+ }
80
+
81
+ /**
82
+ * Throws on an unrecognised value rather than falling back to the default.
83
+ * A typo'd `--profile=minimial` that silently scaffolded the full harness
84
+ * would be the Silent Default Substitution anti-pattern in
85
+ * `.claude/rules/config-access.md`: the run looks like it honoured the flag
86
+ * and the output says otherwise.
87
+ */
88
+ export function parseProfile(raw: string | null | undefined): ScaffoldProfile {
89
+ if (raw === null || raw === undefined) return DEFAULT_PROFILE;
90
+ if ((SCAFFOLD_PROFILES as readonly string[]).includes(raw)) return raw as ScaffoldProfile;
91
+ throw new Error(
92
+ `Invalid --profile value: ${raw}. Valid values: ${SCAFFOLD_PROFILES.join(", ")}`,
93
+ );
94
+ }