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,100 @@
1
+ /**
2
+ * The names a cross-project document actually calls a project by (#442).
3
+ *
4
+ * `scanExternalSources` matched on `basename(projectRoot)` and nothing else,
5
+ * in both of its match modes. Measured by the reporting session against a
6
+ * real document in a sibling project:
7
+ *
8
+ * grep -ic "dailybriefdashboard" -> 0
9
+ * grep -ic "ddb" -> 2
10
+ *
11
+ * That generalises. A document written in one project that refers to another
12
+ * calls it by nickname, abbreviation, product name or repo slug — almost
13
+ * never by the literal name of the directory it happens to be checked out
14
+ * into. An exact substring match on the folder name is the wrong matcher for
15
+ * the only situation the feature exists to serve, and the feature has never
16
+ * fired for any project.
17
+ */
18
+
19
+ import { existsSync, readFileSync } from "fs";
20
+ import { basename, join } from "path";
21
+
22
+ /**
23
+ * Below this length an alias matches so much that it is noise.
24
+ *
25
+ * Two characters inside word boundaries is already thin; one is a letter,
26
+ * and a one-letter alias proposes adopting most of a directory. The same
27
+ * shape bit #437, where a one-character prefix made `isScratchEntry`
28
+ * accept `.claude`.
29
+ */
30
+ export const MIN_ALIAS_LENGTH = 2;
31
+
32
+ function escapeRegex(s: string): string {
33
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
34
+ }
35
+
36
+ /** `owner/name` from a git remote URL, in either of the two forms git writes. */
37
+ export function remoteSlug(remoteUrl: string): string | null {
38
+ const m = /(?:github\.com[:/])([^/\s]+)\/([^/\s]+?)(?:\.git)?\s*$/.exec(remoteUrl.trim());
39
+ if (!m) return null;
40
+ return `${m[1]}/${m[2]}`;
41
+ }
42
+
43
+ /**
44
+ * Every name this project answers to, lowercased and de-duplicated.
45
+ *
46
+ * The repo name and the GitHub slug are DERIVED rather than typed, which is
47
+ * the point of SC-1: a project should not have to write down facts the tree
48
+ * already states. `configured` is for the ones only a human knows — the
49
+ * abbreviation, the product name, the thing the team says out loud.
50
+ */
51
+ export function projectAliases(projectRoot: string, configured: string[] = []): string[] {
52
+ const out: string[] = [basename(projectRoot)];
53
+
54
+ // `.git/config` rather than spawning git: this runs inside scaffold, and a
55
+ // subprocess per scaffolded project is a cost with no payoff when the file
56
+ // is right there. An unreadable or absent one simply contributes nothing —
57
+ // not a fail-open, because the directory name is always present and the
58
+ // caller is told which aliases were used.
59
+ const gitConfig = join(projectRoot, ".git", "config");
60
+ if (existsSync(gitConfig)) {
61
+ let text = "";
62
+ try {
63
+ text = readFileSync(gitConfig, "utf-8");
64
+ } catch {
65
+ text = "";
66
+ }
67
+ for (const m of text.matchAll(/^\s*url\s*=\s*(.+)$/gm)) {
68
+ const slug = remoteSlug(m[1]!);
69
+ if (!slug) continue;
70
+ out.push(slug);
71
+ out.push(slug.split("/")[1]!);
72
+ }
73
+ }
74
+
75
+ out.push(...configured);
76
+
77
+ const seen = new Set<string>();
78
+ return out
79
+ .map(a => a.trim().toLowerCase())
80
+ .filter(a => a.length >= MIN_ALIAS_LENGTH && !seen.has(a) && (seen.add(a), true));
81
+ }
82
+
83
+ /**
84
+ * Whether any alias appears in `text` as a WORD.
85
+ *
86
+ * ONE decider, used by both match modes. They were two separate expressions
87
+ * — `entry.toLowerCase().includes(projectName)` and
88
+ * `content.toLowerCase().includes(projectName)` — which meant two places to
89
+ * fix and two places for them to drift apart.
90
+ *
91
+ * Word boundaries rather than substring, because the aliases that make this
92
+ * feature work are short: `ddb` as a substring matches `oddball`, and a
93
+ * three-letter abbreviation proposing adoption of every document that
94
+ * happens to contain those letters is worse than the matcher that never
95
+ * fired. A slug like `owner/name` is bounded by `/`, which `\b` handles.
96
+ */
97
+ export function matchesAnyAlias(text: string, aliases: string[]): boolean {
98
+ const haystack = text.toLowerCase();
99
+ return aliases.some(a => new RegExp(`\\b${escapeRegex(a)}\\b`).test(haystack));
100
+ }
@@ -151,7 +151,11 @@ export function preflightRefusal(
151
151
  `${treeVersion}, so the tag would describe a release that is not the one cut`
152
152
  );
153
153
  }
154
- if (state.versions.includes(treeVersion)) {
154
+ // `registryServes`, not a second `versions.includes` here (#445). Two
155
+ // deciders answering the same question about the same input are
156
+ // behaviourally one guard, and no behavioural test can tell them apart —
157
+ // the fourth shape in .claude/rules/checks-must-be-able-to-fail.md.
158
+ if (registryServes(state, treeVersion)) {
155
159
  return (
156
160
  `rungate@${treeVersion} is already on the registry — publishing it again is ` +
157
161
  `rejected by npm, and a job that treats that rejection as success reports a ` +
@@ -162,30 +166,109 @@ export function preflightRefusal(
162
166
  }
163
167
 
164
168
  /**
165
- * The single place that decides whether a release actually happened. `null`
166
- * allows.
169
+ * The ONE question the postflight answers: is the version on the registry?
170
+ *
171
+ * The `versions` list, not `dist-tags.latest` (#445). They are different
172
+ * facts and #364 conflated them. A version that appears in `versions` has
173
+ * been published — `npm install rungate@0.4.0` resolves — whatever `latest`
174
+ * currently points at, because a dist-tag is a pointer that moves on its own
175
+ * schedule and can be aimed anywhere. Reading `latest` to answer "did the
176
+ * publish take effect" is reading a pointer to answer a question about the
177
+ * thing pointed at.
178
+ *
179
+ * Exported as its own binding so there is exactly one place to mutate.
180
+ * `preflightRefusal` asks the same predicate in the opposite direction — the
181
+ * version must NOT be here before, and MUST be here after — which is the
182
+ * whole of the two-readings design in one field.
183
+ */
184
+ export function registryServes(state: RegistryState, version: string): boolean {
185
+ return state.versions.includes(version);
186
+ }
187
+
188
+ /**
189
+ * What the postflight established, and what it could not (#445).
190
+ *
191
+ * Three states, not two, because `v0.3.0` and `v0.4.0` both published
192
+ * successfully and both were recorded as failures. The old shape had only
193
+ * `refusal | null`, so a stale read had nowhere to go but into a refusal, and
194
+ * the refusal it got said *the publish step did not take effect* — a cause
195
+ * the guard had not established and could not establish from where it stood.
196
+ */
197
+ export interface PostflightVerdict {
198
+ /** `true` only when the registry serves the version being cut. */
199
+ published: boolean;
200
+ /**
201
+ * Set when the release is published but `latest` still points elsewhere.
202
+ * Reported, never decided on: a lagging dist-tag is propagation, and the
203
+ * guard calling it a failed publish is the whole of #445.
204
+ */
205
+ note: string | null;
206
+ /**
207
+ * Set when the version is absent from the packument. Deliberately NOT a
208
+ * finding — both explanations are named and neither is chosen. See
209
+ * `.claude/rules/config-access.md`: a reading that could not be obtained is
210
+ * UNMEASURED, and `0`, `{}`, `null` and `SKIP` are indistinguishable from
211
+ * success while UNMEASURED is not.
212
+ */
213
+ unmeasured: string | null;
214
+ }
215
+
216
+ /** The command a human runs to settle what this guard cannot. */
217
+ export function confirmCommand(pkg: string, version: string): string {
218
+ return `npm view ${pkg}@${version} version`;
219
+ }
220
+
221
+ /**
222
+ * The single place that decides whether a release actually happened.
167
223
  *
168
224
  * Run AFTER the publish step, against a freshly read registry. This is the
169
225
  * half that cannot be satisfied by doing nothing: a skipped, swallowed or
170
- * silently-failed publish leaves `latest` where it was.
226
+ * silently-failed publish leaves the registry without the version.
227
+ *
228
+ * What it will not do is say WHY the version is missing. From one stale read
229
+ * "the publish did not take effect" and "the packument has not propagated"
230
+ * are the same observation, and #407 answered that by waiting longer, which
231
+ * is a bigger guess rather than a different mechanism. This answers it by
232
+ * declining to guess and naming the command that settles it.
171
233
  */
172
- export function postflightRefusal(treeVersion: string, latestAfter: string | null): string | null {
173
- if (latestAfter === null) {
174
- return (
175
- `the registry has no latest version for rungate after the publish step — ` +
176
- `the release did not happen, whatever the job's exit code says`
177
- );
178
- }
179
- if (latestAfter !== treeVersion) {
180
- return (
181
- `the registry's latest is ${latestAfter}, not the ${treeVersion} this run was ` +
182
- `cutting — the publish step did not take effect`
183
- );
234
+ export function postflightVerdict(
235
+ pkg: string,
236
+ treeVersion: string,
237
+ state: RegistryState,
238
+ read: { attempts: number; waitedMs: number },
239
+ ): PostflightVerdict {
240
+ const seconds = Math.round(read.waitedMs / 1000);
241
+ const reads = `${read.attempts} read${read.attempts === 1 ? "" : "s"} over ${seconds}s`;
242
+
243
+ if (registryServes(state, treeVersion)) {
244
+ return {
245
+ published: true,
246
+ note:
247
+ state.latest === treeVersion
248
+ ? null
249
+ : `the registry serves ${pkg}@${treeVersion} while dist-tags.latest is ` +
250
+ `${state.latest ?? "unset"} — the publish landed and the tag has not ` +
251
+ `caught up. That is propagation and it is not a failed publish`,
252
+ unmeasured: null,
253
+ };
184
254
  }
185
- return null;
255
+
256
+ return {
257
+ published: false,
258
+ note: null,
259
+ unmeasured:
260
+ `UNMEASURED: ${pkg}@${treeVersion} is absent from the registry's packument ` +
261
+ `after ${reads} (dist-tags.latest is ${state.latest ?? "unset"}). Two ` +
262
+ `explanations fit this reading and nothing available here tells them apart: ` +
263
+ `the publish did not take effect, or the packument has not propagated. ` +
264
+ `The publish may well have succeeded. Settle it with ` +
265
+ `\`${confirmCommand(pkg, treeVersion)}\` — if that prints ${treeVersion} the ` +
266
+ `release landed and only this job's result is wrong; if it fails, the publish ` +
267
+ `did not happen and the release must be cut again.`,
268
+ };
186
269
  }
187
270
 
188
- /** What a postflight poll saw, and how hard it had to look (#407). */
271
+ /** What a postflight poll saw, and how hard it had to look (#407, #445). */
189
272
  export interface PostflightReading {
190
273
  /** The `latest` dist-tag on the final read. */
191
274
  latest: string | null;
@@ -193,13 +276,30 @@ export interface PostflightReading {
193
276
  attempts: number;
194
277
  /** Time spent sleeping between reads, in ms. */
195
278
  waitedMs: number;
196
- /** The refusal, or `null` to allow. */
197
- refusal: string | null;
279
+ /** What the final read established. */
280
+ verdict: PostflightVerdict;
198
281
  }
199
282
 
200
- /** Defaults sized for npm's observed read-after-write lag: up to ~30s. */
201
- export const POSTFLIGHT_ATTEMPTS = 10;
202
- export const POSTFLIGHT_DELAY_MS = 3_000;
283
+ /**
284
+ * The whole poll window, as ONE exported constant (#445 SC-4).
285
+ *
286
+ * #407 shipped the window as two numbers — ten attempts, three seconds apart
287
+ * — so widening it meant reasoning about their product, and the next person
288
+ * to widen it would raise whichever one they noticed. One constant, one edit,
289
+ * and `POSTFLIGHT_DELAY_MS` below cannot change the window no matter what it
290
+ * is set to. The positive control in `test/release-guard.test.ts` proves the
291
+ * guard still refuses an absent version, so widening this cannot quietly turn
292
+ * the check off.
293
+ */
294
+ export const POSTFLIGHT_BUDGET_MS = 120_000;
295
+
296
+ /** How often to re-read inside the budget. A cadence, not a budget knob. */
297
+ export const POSTFLIGHT_DELAY_MS = 5_000;
298
+
299
+ /** Reads the budget buys at a given cadence. The first read costs no wait. */
300
+ export function postflightAttempts(budgetMs: number, delayMs: number): number {
301
+ return Math.floor(budgetMs / delayMs) + 1;
302
+ }
203
303
 
204
304
  /**
205
305
  * Poll the registry until it serves `treeVersion`, or give up and refuse (#407).
@@ -218,9 +318,16 @@ export const POSTFLIGHT_DELAY_MS = 3_000;
218
318
  * ## The bound is the point
219
319
  *
220
320
  * Retrying until it goes green would turn this into the defect in the other
221
- * direction. The loop is bounded, a publish that never lands still refuses,
222
- * and the refusal says how long it waited — otherwise "it refused" and "it
223
- * did not wait long enough" are indistinguishable to whoever reads the log.
321
+ * direction. The loop is bounded, a version that never appears is never
322
+ * reported as published, and the reading says how many times it looked and
323
+ * for how long — so a reader can tell a bounded search from an impatient one
324
+ * without the guard having to interpret the number for them.
325
+ *
326
+ * ## What it stopped claiming (#445)
327
+ *
328
+ * Exhausting the budget used to produce a refusal naming a cause. It now
329
+ * produces `verdict.unmeasured`, which names both causes and neither. See
330
+ * `postflightVerdict`.
224
331
  *
225
332
  * ## Why an intermediate throw retries and the last one does not
226
333
  *
@@ -239,45 +346,46 @@ export async function awaitRegistryServes(
239
346
  opts: {
240
347
  fetchImpl?: typeof fetch;
241
348
  base?: string;
242
- attempts?: number;
349
+ budgetMs?: number;
243
350
  delayMs?: number;
244
351
  sleep?: (ms: number) => Promise<void>;
245
352
  } = {},
246
353
  ): Promise<PostflightReading> {
247
- const attempts = opts.attempts ?? POSTFLIGHT_ATTEMPTS;
354
+ const budgetMs = opts.budgetMs ?? POSTFLIGHT_BUDGET_MS;
248
355
  const delayMs = opts.delayMs ?? POSTFLIGHT_DELAY_MS;
249
- // A zero-attempt poll reads nothing and would fall out of the loop with no
250
- // refusal — a check that never runs, reported as a check that passed.
251
- if (!Number.isInteger(attempts) || attempts < 1) {
252
- throw new Error(`postflight needs at least one attempt, got ${opts.attempts}`);
356
+ // An unbounded budget is the defect in the other direction — a poll that
357
+ // retries until it goes green cannot fail — and a zero delay divides the
358
+ // budget by nothing and never terminates.
359
+ if (!Number.isFinite(budgetMs) || budgetMs < 0 || !Number.isFinite(delayMs) || delayMs <= 0) {
360
+ throw new Error(
361
+ `postflight needs a finite non-negative budget and a positive delay, got ` +
362
+ `${opts.budgetMs} / ${opts.delayMs}`,
363
+ );
253
364
  }
365
+ const attempts = postflightAttempts(budgetMs, delayMs);
254
366
  const sleep = opts.sleep ?? ((ms: number) => new Promise(r => setTimeout(r, ms)));
255
367
 
256
368
  let waitedMs = 0;
257
- let latest: string | null = null;
258
- let refusal: string | null = null;
259
369
 
260
370
  for (let attempt = 1; attempt <= attempts; attempt++) {
261
371
  const last = attempt === attempts;
372
+ let state: RegistryState;
262
373
  try {
263
- const state = await registryState(pkg, opts.fetchImpl ?? fetch, opts.base);
264
- latest = state.latest;
265
- refusal = postflightRefusal(treeVersion, latest);
374
+ state = await registryState(pkg, opts.fetchImpl ?? fetch, opts.base);
266
375
  } catch (e) {
376
+ // A transient error is exactly what polling is for. The FINAL one
377
+ // rethrows, because `registryState` throws rather than returning an
378
+ // empty state precisely so that "could not measure" cannot read as
379
+ // "nothing wrong", and swallowing it here would put that back.
267
380
  if (last) throw e;
268
- refusal = `could not read the registry: ${(e as Error).message}`;
381
+ await sleep(delayMs);
382
+ waitedMs += delayMs;
383
+ continue;
269
384
  }
270
385
 
271
- if (refusal === null) return { latest, attempts: attempt, waitedMs, refusal: null };
272
- if (last) {
273
- return {
274
- latest,
275
- attempts: attempt,
276
- waitedMs,
277
- refusal:
278
- `${refusal} — read ${attempt} times over ${Math.round(waitedMs / 1000)}s, ` +
279
- `which is long enough that this is not the registry catching up`,
280
- };
386
+ const verdict = postflightVerdict(pkg, treeVersion, state, { attempts: attempt, waitedMs });
387
+ if (verdict.published || last) {
388
+ return { latest: state.latest, attempts: attempt, waitedMs, verdict };
281
389
  }
282
390
  await sleep(delayMs);
283
391
  waitedMs += delayMs;
@@ -286,3 +394,199 @@ export async function awaitRegistryServes(
286
394
  /* c8 ignore next */
287
395
  throw new Error("unreachable: the loop returns on its last attempt");
288
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
+ }
@@ -162,7 +162,29 @@ export const ProjectHarnessSchema = z.object({
162
162
  forbiddenCommands: z.array(z.string()).optional(),
163
163
  consumers: z.array(z.string()).optional(),
164
164
  promptKeywords: z.record(z.array(z.string())).optional(),
165
- contextDocs: z.record(z.string().nullable()).optional(),
165
+ /**
166
+ * Both authored shapes, because both have always been consumed (#439).
167
+ *
168
+ * This was `z.record(...)` — object only — while `gates/brief-assembler.ts`
169
+ * read `Array.isArray(docs) ? docs : Object.values(docs)` and
170
+ * `gates/brief-assembler.test.ts` tested the array form explicitly. The
171
+ * contradiction was invisible because the assembler parsed the file itself
172
+ * with `JSON.parse` and never reached the validator. Routing it through
173
+ * the loader is what made the schema and the consumer meet.
174
+ *
175
+ * The ENTRIES are `unknown` on purpose, which is the only place in this
176
+ * schema that is true. `lib/context-docs.ts` is the single decider for what
177
+ * a declared doc becomes, and it reports per entry — "docs/x.md: not a
178
+ * string" names the offender, where a schema throw would refuse the whole
179
+ * brief and name the key. Validating the entries here as well would be a
180
+ * second decider agreeing with the first, and the first would then be
181
+ * unreachable in production: its "not a string" arm could never fire, and
182
+ * no test could tell. See `.claude/rules/checks-must-be-able-to-fail.md`.
183
+ */
184
+ contextDocs: z.union([
185
+ z.record(z.unknown()),
186
+ z.array(z.unknown()),
187
+ ]).optional(),
166
188
  mcp: z.array(McpServerSchema).optional(),
167
189
  research: z.array(ResearchToolSchema).optional(),
168
190
  roles: z.record(RoleSchema).optional(),