rungate 0.4.1 → 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 (42) 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/cli-commands.ts +7 -1
  11. package/lib/conformity.ts +965 -30
  12. package/lib/github.ts +195 -0
  13. package/lib/js-top-level-code.ts +27 -2
  14. package/lib/package-closure.ts +278 -2
  15. package/lib/release-preflight.ts +196 -0
  16. package/lib/scaffold/defaults.ts +40 -0
  17. package/lib/scaffold/managed-workflow.ts +125 -27
  18. package/lib/scaffold/owned-files.ts +6 -0
  19. package/lib/scaffold/profiles.ts +94 -0
  20. package/lib/scaffold/rehearsal.ts +27 -2
  21. package/lib/scaffold/steps.ts +654 -84
  22. package/lib/scaffold/write-steps.ts +50 -9
  23. package/lib/source-anchor.ts +144 -0
  24. package/lib/success-doc.ts +779 -0
  25. package/lib/suite-run-reading.ts +194 -0
  26. package/lib/test-census.ts +199 -0
  27. package/lib/trajectory.ts +377 -0
  28. package/lib/validators/spec-validators.ts +32 -4
  29. package/lib/workflow-security.ts +101 -0
  30. package/lib/workflow-test-harness.ts +349 -0
  31. package/package.json +6 -1
  32. package/scripts/create-success.ts +162 -0
  33. package/scripts/scaffold-project.ts +27 -3
  34. package/specs/SPEC-TEMPLATE.md +200 -0
  35. package/templates/SUCCESS-TEMPLATE.md +72 -0
  36. package/templates/agent-briefs/_shared.md +9 -0
  37. package/templates/agent-briefs/aditi.md +46 -0
  38. package/templates/agent-briefs/discovery.md +37 -0
  39. package/templates/agent-briefs/marcus.md +39 -0
  40. package/templates/agent-briefs/quinn.md +67 -0
  41. package/templates/agent-briefs/rook.md +40 -0
  42. package/templates/agent-briefs/serena.md +39 -0
@@ -394,3 +394,199 @@ export async function awaitRegistryServes(
394
394
  /* c8 ignore next */
395
395
  throw new Error("unreachable: the loop returns on its last attempt");
396
396
  }
397
+
398
+ /**
399
+ * What `npm publish` said about its own result (#472).
400
+ *
401
+ * The postflight has refused three consecutive successful releases — 0.3.0,
402
+ * 0.4.0, 0.4.1 — and the last missed by 48 seconds. #407 answered that by
403
+ * widening the budget and #445 by fixing the wording, and both left the same
404
+ * mechanism in place: a blind poll of an eventually-consistent document,
405
+ * guessing at how long propagation takes.
406
+ *
407
+ * The evidence was already on the page. The publish step's own output says:
408
+ *
409
+ * ```
410
+ * npm notice Your package is being processed and may take a few minutes to become available.
411
+ * + rungate@0.4.1
412
+ * ```
413
+ *
414
+ * So the registry is not silent about the asynchrony — it states it, in the
415
+ * step immediately above the one guessing at it, and it issues a RECEIPT. That
416
+ * receipt is written synchronously at publish time and the packument is not,
417
+ * which is the entire reason the two readings disagree.
418
+ */
419
+ export interface PublishReceipt {
420
+ /** The version on npm's `+ pkg@version` line, or null if there is no such line. */
421
+ version: string | null;
422
+ /** npm's own statement that the registry read will lag behind this publish. */
423
+ propagationWarned: boolean;
424
+ /** Bytes of log read, so an empty file is distinguishable from a missing line. */
425
+ bytes: number;
426
+ }
427
+
428
+ /** Regex-safe form of a package name, which may contain `@`, `/`, `.` and `-`. */
429
+ function escapeForRegex(s: string): string {
430
+ return s.replace(/[.*+?^${}()|[\]\\\/]/g, "\\$&");
431
+ }
432
+
433
+ /**
434
+ * Read npm's receipt out of the publish step's captured output.
435
+ *
436
+ * The `+ name@version` line is npm's statement that the registry ACCEPTED the
437
+ * publish. Anchored to the start of a line so a version named in prose — and
438
+ * `npm notice` prints the name and version several times — cannot be mistaken
439
+ * for the receipt.
440
+ */
441
+ export function parsePublishReceipt(pkg: string, log: string): PublishReceipt {
442
+ // ANSI is STRIPPED first. npm colourises `+ pkg@version` whenever it
443
+ // believes it is on a TTY, and `FORCE_COLOR` is set by plenty of CI images
444
+ // — with colour the anchor never matches, the guard finds no receipt and
445
+ // REFUSES a release that published perfectly. Fail-closed, but it is #472's
446
+ // own symptom arriving through the fix for #472. Found by the security
447
+ // review of the first commit.
448
+ const plain = log.replace(/\u001b\[[0-9;]*m/g, "");
449
+ // Leading whitespace is tolerated and TRAILING content is not: an indent
450
+ // comes from a log wrapper, whereas text after the version is a different
451
+ // statement — `+ rungate@0.4.1 (dry-run)` must not read as a publish.
452
+ const m = plain.match(new RegExp(`^[ \\t]*\\+\\s*${escapeForRegex(pkg)}@(\\S+)[ \\t]*$`, "m"));
453
+ return {
454
+ version: m ? m[1] : null,
455
+ propagationWarned: /being processed and may take/i.test(plain),
456
+ bytes: log.length,
457
+ };
458
+ }
459
+
460
+ /** What the postflight concluded, and which exit code says so. */
461
+ export interface PostflightDecision {
462
+ /** `confirmed` exits 0, `refused` exits REFUSE_EXIT, `unmeasured` exits UNMEASURED_EXIT. */
463
+ outcome: "confirmed" | "refused" | "unmeasured";
464
+ /** The whole message, already worded for the reader of a failed release job. */
465
+ message: string;
466
+ }
467
+
468
+ /**
469
+ * The ONE binding that decides whether a release happened (#472).
470
+ *
471
+ * Two questions were being asked as one, and only the second of them is slow:
472
+ *
473
+ * | Question | Answerable | Evidence |
474
+ * |---|---|---|
475
+ * | did npm ACCEPT this publish? | synchronously, at publish time | the `+ pkg@version` receipt |
476
+ * | does the registry SERVE it? | eventually, minutes later | the packument |
477
+ *
478
+ * The postflight exists to catch a pipeline that quietly did nothing — a
479
+ * skipped `if:`, a swallowed error, a duplicate npm rejected. **The receipt
480
+ * catches all three and catches them immediately**: a skipped step produces no
481
+ * output, a swallowed error produces no `+` line, and a rejected duplicate
482
+ * makes npm exit non-zero with an E403 and no receipt. It is a strictly better
483
+ * detector for the thing the check is for, and it does not need a budget.
484
+ *
485
+ * So propagation stops being fatal — but ONLY when the receipt corroborates
486
+ * it. With a receipt naming this version, an exhausted budget is a known
487
+ * propagation delay and the job passes with the delay stated out loud. With
488
+ * NO receipt available, exhaustion is still `unmeasured` and still stops the
489
+ * job, which is #445's behaviour unchanged. That fall-back is what keeps this
490
+ * able to fail if the log capture is ever removed from the workflow.
491
+ *
492
+ * **Two deciders, and each has an input only it can reach**
493
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape). The receipt
494
+ * is the only thing that can see a publish npm rejected while the registry
495
+ * still serves a previous version; the packument read is the only thing that
496
+ * can see a receipt for a version the registry never accepted. Neither
497
+ * subsumes the other, and the test gives each a case the other passes.
498
+ */
499
+ export function postflightDecision(
500
+ pkg: string,
501
+ treeVersion: string,
502
+ reading: PostflightReading,
503
+ receipt: PublishReceipt | null,
504
+ ): PostflightDecision {
505
+ // The receipt is checked FIRST and refuses on its own, before the registry
506
+ // is consulted at all. A publish step that reported no success is an
507
+ // ESTABLISHED failure, not an ambiguous reading — and checking it after the
508
+ // registry would let a packument that happens to serve the version (because
509
+ // it was published last month) wave through a step that did nothing today.
510
+ if (receipt !== null) {
511
+ if (receipt.version === null) {
512
+ return {
513
+ outcome: "refused",
514
+ message:
515
+ `the publish step produced no receipt. npm prints \`+ ${pkg}@${treeVersion}\` ` +
516
+ `on a successful publish and the captured output (${receipt.bytes} bytes) has ` +
517
+ `no such line, so the registry did not accept a publish in this job. A skipped ` +
518
+ `step, a swallowed error and a duplicate version npm rejected all look like ` +
519
+ `this, and all three are a release that did not happen.`,
520
+ };
521
+ }
522
+ if (receipt.version !== treeVersion) {
523
+ return {
524
+ outcome: "refused",
525
+ message:
526
+ `the publish step published ${pkg}@${receipt.version}, but this tree is ` +
527
+ `${treeVersion}. The receipt and package.json must name the same version or ` +
528
+ `the tag describes something that was never shipped.`,
529
+ };
530
+ }
531
+ }
532
+
533
+ if (reading.verdict.published) {
534
+ return {
535
+ outcome: "confirmed",
536
+ message:
537
+ `the registry serves ${pkg}@${treeVersion} ` +
538
+ `(read ${reading.attempts} time${reading.attempts === 1 ? "" : "s"}, ` +
539
+ `waited ${Math.round(reading.waitedMs / 1000)}s)` +
540
+ (reading.verdict.note ? `\npostflight note: ${reading.verdict.note}` : ""),
541
+ };
542
+ }
543
+
544
+ // Absent from the packument. With a receipt this is no longer ambiguous:
545
+ // npm said it accepted the publish, and said in the same breath that the
546
+ // registry would lag. Passing here is a fail-open and it is deliberate, so
547
+ // it is LOUD — `.claude/rules/config-access.md` permits the tradeoff and
548
+ // forbids the silent version.
549
+ // BOTH halves are required, and the second is the one the security review
550
+ // of the first commit found inert. `propagationWarned` was parsed, carried
551
+ // and printed while deciding nothing: a receipt alone waived the registry
552
+ // read whether or not npm had said the registry would lag. That made the
553
+ // live pipeline unable to fail here at all — the workflow always passes
554
+ // `--publish-log`, so every real release took this branch — which is the
555
+ // defect `.claude/rules/checks-must-be-able-to-fail.md` is about, inside
556
+ // the commit whose subject is that defect.
557
+ //
558
+ // Requiring npm's own statement keeps the waiver tied to evidence. If npm
559
+ // stops printing it the release goes UNMEASURED and someone reads this
560
+ // comment, which is the fail-closed direction a release gate owes.
561
+ if (receipt !== null && receipt.version === treeVersion && receipt.propagationWarned) {
562
+ return {
563
+ outcome: "confirmed",
564
+ message:
565
+ `PROPAGATION PENDING — npm accepted ${pkg}@${treeVersion} and the registry is ` +
566
+ `not serving it yet after ${reading.attempts} read` +
567
+ `${reading.attempts === 1 ? "" : "s"} over ${Math.round(reading.waitedMs / 1000)}s. ` +
568
+ `This is NOT a confirmed read of the registry; it is the publish receipt plus ` +
569
+ `npm's own statement that the packument lags. The release is treated as landed ` +
570
+ `because the receipt is written synchronously and the packument is not. ` +
571
+ `Verify with \`${confirmCommand(pkg, treeVersion)}\`.`,
572
+ };
573
+ }
574
+
575
+ // A receipt with no lag warning is NOT waived. npm accepted something and
576
+ // did not say the registry would be slow, so the absence is unexplained and
577
+ // the guard says so rather than picking the convenient reading.
578
+ if (receipt !== null && receipt.version === treeVersion) {
579
+ return {
580
+ outcome: "unmeasured",
581
+ message:
582
+ `UNMEASURED: npm printed a receipt for ${pkg}@${treeVersion} but did NOT print its ` +
583
+ `"being processed and may take a few minutes" notice, and the registry is still not ` +
584
+ `serving the version after ${reading.attempts} read` +
585
+ `${reading.attempts === 1 ? "" : "s"} over ${Math.round(reading.waitedMs / 1000)}s. ` +
586
+ `A receipt waives the registry read only when npm itself says the read will lag. ` +
587
+ `Settle it with \`${confirmCommand(pkg, treeVersion)}\`.`,
588
+ };
589
+ }
590
+
591
+ return { outcome: "unmeasured", message: reading.verdict.unmeasured ?? "no reading was taken" };
592
+ }
@@ -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
+ }
@@ -82,6 +82,18 @@ export interface Rehearsal {
82
82
  parent: string;
83
83
  /** `clone` when copy-on-write was used, `copy` when it fell back. */
84
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;
85
97
  }
86
98
 
87
99
  /**
@@ -232,7 +244,7 @@ export function cloneForRehearsal(root: string): Rehearsal {
232
244
  );
233
245
  }
234
246
 
235
- return { dir, parent, method };
247
+ return { dir, parent, method, source: root };
236
248
  }
237
249
 
238
250
  /**
@@ -323,8 +335,21 @@ export function discardRehearsal(r: Rehearsal): void {
323
335
  * The line audit prints so a reader knows the report was produced by running
324
336
  * the real thing, not by predicting it — and knows what it did not run.
325
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
+ */
326
349
  export function rehearsalNotice(r: Rehearsal): string {
327
350
  const skipped = [...STEPS_NOT_REHEARSED.keys()].join(", ");
328
351
  return `Mode: audit — rehearsed against a ${r.method} of the tree, which was then discarded. ` +
329
- `Not rehearsed: ${skipped}. Pass --fix to apply.`;
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.`;
330
355
  }