rungate 0.4.1 → 0.6.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 (87) 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/agents-md-sections.ts +144 -0
  11. package/lib/branch-diff.ts +139 -0
  12. package/lib/bun-version.ts +268 -0
  13. package/lib/ci-checkout.ts +1 -1
  14. package/lib/cli-commands.ts +7 -1
  15. package/lib/compliance.ts +13 -11
  16. package/lib/config-loader.ts +12 -0
  17. package/lib/conformity.ts +1147 -116
  18. package/lib/context-docs.ts +143 -28
  19. package/lib/create-brief.ts +2 -1
  20. package/lib/create-sc.ts +90 -4
  21. package/lib/doc-scan-targets.ts +9 -0
  22. package/lib/evidence-command-transport.ts +160 -0
  23. package/lib/evidence-prevalidator.ts +22 -0
  24. package/lib/fallow-availability.ts +129 -0
  25. package/lib/gate-refusal-currency.ts +112 -0
  26. package/lib/gate-timeouts.ts +82 -0
  27. package/lib/generators/agent-briefs.ts +4 -1
  28. package/lib/generators/agents-md.ts +71 -23
  29. package/lib/generators/code-map.ts +2 -1
  30. package/lib/generators/types.ts +8 -0
  31. package/lib/git-dates.ts +55 -0
  32. package/lib/github.ts +195 -0
  33. package/lib/js-top-level-code.ts +27 -2
  34. package/lib/junit-checks.ts +484 -0
  35. package/lib/local-calendar-day.ts +78 -0
  36. package/lib/package-closure.ts +278 -2
  37. package/lib/project-state-shape.ts +59 -0
  38. package/lib/promote-outputs.ts +6 -2
  39. package/lib/release-preflight.ts +196 -0
  40. package/lib/report-provenance.ts +156 -0
  41. package/lib/sc-claim-forms.ts +75 -0
  42. package/lib/sc-id-cross-tree.ts +311 -0
  43. package/lib/scaffold/ai-review-step.ts +180 -0
  44. package/lib/scaffold/defaults.ts +40 -0
  45. package/lib/scaffold/managed-workflow.ts +125 -27
  46. package/lib/scaffold/owned-files.ts +48 -2
  47. package/lib/scaffold/profiles.ts +94 -0
  48. package/lib/scaffold/rehearsal.ts +232 -73
  49. package/lib/scaffold/steps.ts +777 -152
  50. package/lib/scaffold/write-steps.ts +56 -13
  51. package/lib/scanner.ts +38 -12
  52. package/lib/source-anchor.ts +144 -0
  53. package/lib/spec-listing.ts +148 -0
  54. package/lib/spec-requirements.ts +209 -0
  55. package/lib/success-doc.ts +779 -0
  56. package/lib/suite-run-reading.ts +364 -0
  57. package/lib/test-census.ts +199 -0
  58. package/lib/test-command.ts +133 -0
  59. package/lib/test-suite-lock.ts +166 -10
  60. package/lib/tool-probe.ts +120 -0
  61. package/lib/tracked-vs-ignored.ts +234 -0
  62. package/lib/trajectory.ts +377 -0
  63. package/lib/validators/spec-validators.ts +35 -6
  64. package/lib/workflow-security.ts +101 -0
  65. package/lib/workflow-test-harness.ts +349 -0
  66. package/package.json +6 -1
  67. package/scripts/audit-specs.ts +247 -12
  68. package/scripts/audit-transcript.ts +2 -1
  69. package/scripts/convert-spec.ts +2 -1
  70. package/scripts/create-sc.ts +17 -7
  71. package/scripts/create-spec.ts +2 -1
  72. package/scripts/create-success.ts +163 -0
  73. package/scripts/extract-constraints.ts +90 -19
  74. package/scripts/generate-code-map.ts +53 -12
  75. package/scripts/scaffold-project.ts +31 -4
  76. package/scripts/split-spec.ts +2 -1
  77. package/scripts/sync-sc-status.ts +57 -5
  78. package/scripts/sync-spec-tests.ts +2 -1
  79. package/specs/SPEC-TEMPLATE.md +200 -0
  80. package/templates/SUCCESS-TEMPLATE.md +72 -0
  81. package/templates/agent-briefs/_shared.md +9 -0
  82. package/templates/agent-briefs/aditi.md +46 -0
  83. package/templates/agent-briefs/discovery.md +37 -0
  84. package/templates/agent-briefs/marcus.md +39 -0
  85. package/templates/agent-briefs/quinn.md +67 -0
  86. package/templates/agent-briefs/rook.md +40 -0
  87. package/templates/agent-briefs/serena.md +39 -0
@@ -14,9 +14,41 @@
14
14
  * would carry, then walk the relative imports of every published source file
15
15
  * and assert each target is in that set. One `catch` here would turn a
16
16
  * malformed package.json into "no violations", so there is none.
17
+ *
18
+ * ## Imports were half of it (#484)
19
+ *
20
+ * The version of this module that shipped with #446 asked one question —
21
+ * *does every relative IMPORT resolve to a published file?* — and `0.4.1` went
22
+ * out with `SUCCESS.md` recording that the distribution had been verified. It
23
+ * had been verified for imports.
24
+ *
25
+ * `lib/conformity.ts:495` does not import its matcher registry. It builds a
26
+ * path and reads it:
27
+ *
28
+ * join(dirname(fileURLToPath(import.meta.url)), "..", "config", "matcher-registry.json")
29
+ *
30
+ * `config/` was not in `files[]`, so `resolveMatcher()` threw ENOENT for every
31
+ * consumer, and `bunx rungate create-sc --list` — a command the README
32
+ * documents — died the same way. Same defect as #446, different syntax, and
33
+ * the guard written for #446 was structurally incapable of seeing it: a
34
+ * detector narrower than what it detects, which is the shape
35
+ * `.claude/rules/checks-must-be-able-to-fail.md` names third.
36
+ *
37
+ * What made it latent rather than loud is worth recording. An external
38
+ * consumer does not reach `resolveMatcher` until one of its success criteria
39
+ * MATCHES a registry pattern. Measured on `pov-plugin`: 21 pass, 0 fail, over
40
+ * a library that could not load its own registry, purely because all 40 of its
41
+ * SCs were unmatched. The reward for making its spec more testable would have
42
+ * been an ENOENT crash, and nothing connected those two events.
43
+ *
44
+ * So both syntaxes are asked the same question here, and `runtimeReads` is
45
+ * deliberately NOT a second copy of the import walker — the two find different
46
+ * things and both feed the one `packageClosureViolations` binding, so there is
47
+ * still exactly one decider to mutate.
17
48
  */
18
- import { existsSync, readdirSync, readFileSync, statSync } from "fs";
49
+ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "fs";
19
50
  import { join, dirname, relative, resolve } from "path";
51
+ import { stripStringsAndComments } from "./js-top-level-code";
20
52
 
21
53
  /** Extensions a bare specifier may acquire, in the order a resolver tries. */
22
54
  const CANDIDATE_SUFFIXES = ["", ".ts", ".tsx", ".js", ".mjs", ".json", "/index.ts", "/index.js"];
@@ -32,15 +64,57 @@ export function publishedFiles(root: string, patterns: string[]): Set<string> {
32
64
  if (!existsSync(abs)) return;
33
65
  for (const entry of readdirSync(abs)) {
34
66
  const childRel = `${rel}/${entry}`.replace(/\/+/g, "/");
35
- if (statSync(join(root, childRel)).isDirectory()) addDir(childRel);
67
+ const childAbs = join(root, childRel);
68
+ // `lstat`, not `stat`. A symlink inside a published directory points
69
+ // wherever it likes, and `relative()` cannot see that because the path
70
+ // STRING is still under the root — a `linked/` symlink enumerated
71
+ // `secret.txt` from a directory outside the package entirely. npm would
72
+ // follow it into the tarball too, so this is a packaging hazard either
73
+ // way and the honest answer is to refuse rather than to model it.
74
+ const st = lstatSync(childAbs);
75
+ if (st.isSymbolicLink()) {
76
+ throw new Error(`package.json files[] reaches a symlink at "${childRel}" — refusing to resolve it`);
77
+ }
78
+ if (st.isDirectory()) addDir(childRel);
36
79
  else out.add(childRel);
37
80
  }
38
81
  }
39
82
 
83
+ /** npm expands these; this checker does not, and must not pretend to. */
84
+ const GLOB_META = /[*?[\]{}!]/;
85
+
40
86
  for (const pattern of patterns) {
87
+ // A glob is not a path, and treating it as one resolves to NOTHING:
88
+ // `files: ["scripts/*.ts"]` produced a published set containing only
89
+ // package.json, so the closure loop had almost nothing to walk and
90
+ // reported zero violations over a package it had not looked at. That is
91
+ // the same vacuous-scan failure CONFIG-1 refuses, reached through the
92
+ // manifest instead of through the file walk.
93
+ if (GLOB_META.test(pattern)) {
94
+ throw new Error(
95
+ `package.json files[] entry "${pattern}" is a glob, which this checker does not expand — ` +
96
+ `it would report a clean closure over files it never resolved`,
97
+ );
98
+ }
41
99
  const clean = pattern.replace(/^\.\//, "").replace(/\/$/, "");
42
100
  const abs = join(root, clean);
101
+ // A files[] entry that climbs out of the package is never legitimate, and
102
+ // this function walks directories recursively — so an unchecked `../..`
103
+ // would enumerate the filesystem above the project. Refuse rather than
104
+ // normalise: npm would not publish it either, and silently reading it as
105
+ // the directory it resolves to would hide a malformed manifest.
106
+ if (relative(root, abs).startsWith("..")) {
107
+ throw new Error(`package.json files[] entry "${pattern}" escapes the package root`);
108
+ }
43
109
  if (!existsSync(abs)) continue;
110
+ // The same lstat the recursion does. A first draft checked only inside
111
+ // addDir, so `files: ["linked/"]` — the symlink named as the entry itself
112
+ // — walked straight past it and enumerated a directory outside the
113
+ // package. The guard has to sit on every path that becomes a published
114
+ // name, not only on the ones reached by recursion.
115
+ if (lstatSync(abs).isSymbolicLink()) {
116
+ throw new Error(`package.json files[] entry "${pattern}" is a symlink — refusing to resolve it`);
117
+ }
44
118
  if (statSync(abs).isDirectory()) addDir(clean);
45
119
  else out.add(clean);
46
120
  }
@@ -68,6 +142,142 @@ export function relativeImports(source: string): string[] {
68
142
  return found;
69
143
  }
70
144
 
145
+ /**
146
+ * A path a module builds from its OWN location and then reads at runtime.
147
+ *
148
+ * `up` is how many directories above the source file the path starts, and
149
+ * `segments` is what is appended. The two anchors below both mean "the
150
+ * directory this module is in", so they are 0; every `dirname()` wrapped
151
+ * around one, and every `".."` among the segments, adds a level.
152
+ */
153
+ export interface RuntimeRead {
154
+ /** The expression as written, for the violation message. */
155
+ expression: string;
156
+ /** Directories above the source file's own directory. */
157
+ up: number;
158
+ /** Literal path segments below that, `..` already folded into `up`. */
159
+ segments: string[];
160
+ }
161
+
162
+ /** Spellings of "the directory this module lives in". */
163
+ const MODULE_DIR_ANCHORS = [
164
+ /\bdirname\s*\(\s*fileURLToPath\s*\(\s*import\.meta\.url\s*\)\s*\)/,
165
+ /\bimport\.meta\.dir\b/,
166
+ /\b__dirname\b/,
167
+ ];
168
+
169
+ /** Split a `join(...)` argument list on top-level commas. */
170
+ function splitArgs(argText: string): string[] {
171
+ const args: string[] = [];
172
+ let depth = 0;
173
+ let quote: string | null = null;
174
+ let current = "";
175
+ for (let i = 0; i < argText.length; i++) {
176
+ const c = argText[i];
177
+ if (quote) {
178
+ if (c === quote && argText[i - 1] !== "\\") quote = null;
179
+ current += c;
180
+ continue;
181
+ }
182
+ if (c === '"' || c === "'" || c === "`") { quote = c; current += c; continue; }
183
+ if (c === "(" || c === "[" || c === "{") depth++;
184
+ if (c === ")" || c === "]" || c === "}") depth--;
185
+ if (c === "," && depth === 0) { args.push(current.trim()); current = ""; continue; }
186
+ current += c;
187
+ }
188
+ if (current.trim()) args.push(current.trim());
189
+ return args;
190
+ }
191
+
192
+ /**
193
+ * A segment the scanner is willing to resolve.
194
+ *
195
+ * No backslash: an escaped character means the written text and the runtime
196
+ * string differ, and resolving the text would name a path the code does not
197
+ * read. Such a segment falls through to `unresolved`, where it is reported,
198
+ * rather than being turned into a plausible wrong answer.
199
+ */
200
+ const STRING_LITERAL = /^["'`]([^"'`\\]*)["'`]$/;
201
+
202
+ /**
203
+ * Every `join(<this module's directory>, ...literals)` in a source file.
204
+ *
205
+ * Only fully-literal segment lists are returned. A `join` whose segments come
206
+ * from a variable cannot be resolved statically and is NOT silently dropped —
207
+ * `unresolvedModuleRelativeJoins` counts those separately so a new one is
208
+ * visible rather than absorbed, which is the fail-open this whole module
209
+ * exists to avoid.
210
+ */
211
+ export function runtimeReads(source: string): RuntimeRead[] {
212
+ return scanModuleRelativeJoins(source).resolved;
213
+ }
214
+
215
+ /** Module-relative `join(...)` calls whose segments are not all literals. */
216
+ export function unresolvedModuleRelativeJoins(source: string): string[] {
217
+ return scanModuleRelativeJoins(source).unresolved;
218
+ }
219
+
220
+ function scanModuleRelativeJoins(raw: string): { resolved: RuntimeRead[]; unresolved: string[] } {
221
+ const resolved: RuntimeRead[] = [];
222
+ const unresolved: string[] = [];
223
+
224
+ // Comments out, string contents kept. The first draft of this scanner read
225
+ // raw source and reported THIS MODULE's own docstring — which quotes the
226
+ // `join(dirname(fileURLToPath(...)), "..", "config", ...)` expression to
227
+ // explain the bug — as a live violation. A detector that cannot tell a call
228
+ // from a sentence about a call is #454 again.
229
+ const source = stripStringsAndComments(raw, { keepStringContents: true });
230
+
231
+ for (let i = source.indexOf("join"); i !== -1; i = source.indexOf("join", i + 1)) {
232
+ // `join` must be the whole identifier, and an open paren must follow.
233
+ if (i > 0 && /[A-Za-z0-9_$.]/.test(source[i - 1])) continue;
234
+ let j = i + 4;
235
+ while (j < source.length && /\s/.test(source[j])) j++;
236
+ if (source[j] !== "(") continue;
237
+
238
+ // Walk to the matching close paren.
239
+ let depth = 0;
240
+ let k = j;
241
+ for (; k < source.length; k++) {
242
+ if (source[k] === "(") depth++;
243
+ else if (source[k] === ")") { depth--; if (depth === 0) break; }
244
+ }
245
+ if (depth !== 0) continue;
246
+
247
+ const argText = source.slice(j + 1, k);
248
+ const args = splitArgs(argText);
249
+ if (args.length < 2) continue;
250
+
251
+ const anchor = args[0];
252
+ if (!MODULE_DIR_ANCHORS.some(a => a.test(anchor))) continue;
253
+
254
+ // `dirname(fileURLToPath(import.meta.url))` IS the anchor, so remove it
255
+ // before counting the dirname() calls that genuinely climb.
256
+ const climbing = anchor.replace(MODULE_DIR_ANCHORS[0], "");
257
+ let up = (climbing.match(/\bdirname\s*\(/g) || []).length;
258
+
259
+ const expression = `join(${args.join(", ")})`;
260
+ const segments: string[] = [];
261
+ let literal = true;
262
+ for (const arg of args.slice(1)) {
263
+ const m = STRING_LITERAL.exec(arg);
264
+ if (!m) { literal = false; break; }
265
+ for (const part of m[1].split("/").filter(Boolean)) {
266
+ if (part === "..") { if (segments.length) segments.pop(); else up++; }
267
+ else if (part !== ".") segments.push(part);
268
+ }
269
+ }
270
+
271
+ // `join(import.meta.dir, "..")` with nothing below it is the "find the
272
+ // package root" idiom, not a read of a particular file. Eleven published
273
+ // modules use it and none of them is a closure question.
274
+ if (literal && segments.length > 0) resolved.push({ expression, up, segments });
275
+ else if (!literal) unresolved.push(expression);
276
+ }
277
+
278
+ return { resolved, unresolved };
279
+ }
280
+
71
281
  /**
72
282
  * The single binding. `test/package-closure.test.ts` builds a mutant of this
73
283
  * module with the body short-circuited to `return []` and asserts the suite
@@ -76,11 +286,64 @@ export function relativeImports(source: string): string[] {
76
286
  */
77
287
  export function packageClosureViolations(root: string, published: Set<string>): string[] {
78
288
  const violations: string[] = [];
289
+ let scanned = 0;
79
290
 
80
291
  for (const file of published) {
81
292
  if (!SOURCE_EXT.test(file)) continue;
293
+ scanned++;
82
294
  const source = readFileSync(join(root, file), "utf-8");
83
295
 
296
+ // A module-relative path the scanner could not resolve statically is
297
+ // UNMEASURED, and unmeasured is not clean. The first draft of this module
298
+ // exported `unresolvedModuleRelativeJoins`, tested it in isolation, and
299
+ // never called it from here — so its own docstring claimed these were
300
+ // "NOT silently dropped" while the only path that produces violations
301
+ // dropped them. Found by the push security review, in the same commit
302
+ // that adds a section about exactly this to
303
+ // `.claude/rules/checks-must-be-able-to-fail.md`.
304
+ //
305
+ // Enforced strictly because the live tree has zero: there is no migration
306
+ // window to ratchet through, so a new one fails immediately.
307
+ for (const expression of unresolvedModuleRelativeJoins(source)) {
308
+ violations.push(
309
+ `${file} builds ${expression} from its own directory and the segments are not all literal — ` +
310
+ `the scanner cannot say what it reads, so whether it ships is UNMEASURED`,
311
+ );
312
+ }
313
+
314
+ // `join` resolved by identifier. An aliased import would be invisible, so
315
+ // it is refused rather than missed — the blind spot is small, and the
316
+ // point is that entering it cannot be silent.
317
+ if (/\bimport\s*\{[^}]*\bjoin\s+as\s+\w/.test(source)) {
318
+ violations.push(
319
+ `${file} imports join under an alias, which this scanner resolves by name and would not see`,
320
+ );
321
+ }
322
+
323
+ // #484. A path built from the module's own location and read at runtime
324
+ // asks the same question an import does, so it is answered here and not
325
+ // in a second checker that could drift from this one.
326
+ for (const read of runtimeReads(source)) {
327
+ let dir = dirname(join(root, file));
328
+ for (let n = 0; n < read.up; n++) dir = dirname(dir);
329
+ const target = join(dir, ...read.segments);
330
+ const targetRel = relative(root, target);
331
+
332
+ // Outside the package entirely is not this check's business.
333
+ if (targetRel.startsWith("..")) continue;
334
+ if (!existsSync(target)) continue;
335
+
336
+ const isPublished = statSync(target).isDirectory()
337
+ ? [...published].some(p => p === targetRel || p.startsWith(`${targetRel}/`))
338
+ : published.has(targetRel);
339
+
340
+ if (!isPublished) {
341
+ violations.push(
342
+ `${file} reads ${read.expression} at runtime -> ${targetRel}, which files[] does not publish`,
343
+ );
344
+ }
345
+ }
346
+
84
347
  for (const specifier of relativeImports(source)) {
85
348
  const target = resolve(dirname(join(root, file)), specifier);
86
349
  const targetRel = relative(root, target);
@@ -97,6 +360,19 @@ export function packageClosureViolations(root: string, published: Set<string>):
97
360
  }
98
361
  }
99
362
  }
363
+
364
+ // A closure check that walked no source reports a closed package and cannot
365
+ // be told from one. Every way of producing an empty set found so far — a
366
+ // glob entry, a files[] naming only non-source, a wrong root — throws or
367
+ // refuses somewhere above; this is the backstop for the next one, because
368
+ // the list of ways is not knowable in advance. ADR-002 D4, same argument.
369
+ if (scanned === 0) {
370
+ return [
371
+ "package closure: NO published source files were scanned. A check that reads nothing " +
372
+ "reports nothing and cannot be told from a closed package — refusing rather than " +
373
+ "reporting clean.",
374
+ ];
375
+ }
100
376
  return violations.sort();
101
377
  }
102
378
 
@@ -164,3 +164,62 @@ export function missingStateVerdict(opts: {
164
164
  }
165
165
  return { verdict: "SKIP", detail: "project-state.json not found and no PROJECT-STATE.md to maintain — nothing to do" };
166
166
  }
167
+
168
+ /** One rendered session, and the entries the selection could not place. */
169
+ export interface SessionSelection<T> {
170
+ /** Newest first, at most `limit` of them. */
171
+ rendered: T[];
172
+ /**
173
+ * Entries whose `date` does not begin with an ISO date.
174
+ *
175
+ * They are NOT excluded — they rank below every dated entry, in array
176
+ * order, which is the only information left about them and is exactly
177
+ * what the old renderer used for everything. A project whose dates are
178
+ * all free-form therefore renders exactly as it did before.
179
+ *
180
+ * They are reported by name, because an entry nobody can order is a
181
+ * thing worth saying out loud: it will be outranked by any dated entry,
182
+ * however old, and that is surprising if you cannot see it.
183
+ */
184
+ undated: T[];
185
+ }
186
+
187
+ const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})\b/;
188
+
189
+ /**
190
+ * The `limit` NEWEST sessions, chosen by date (#572).
191
+ *
192
+ * The renderer used to take `[...sessions].reverse().slice(0, 3)` — "the
193
+ * last three entries of the array", which is correct exactly while the
194
+ * array is in append order and which nothing anywhere enforced. Session 48
195
+ * was written to `sessions[0]`, so eight merged issues never appeared in
196
+ * PROJECT-STATE.md, the file AGENTS.md tells the next session to read
197
+ * first. The script printed `✅ rewrote` every time, because it had in fact
198
+ * rewritten the file.
199
+ *
200
+ * This is the second instance of that bug in the same function. The first
201
+ * was `slice(0, 3)` rendering the three OLDEST entries, and the fix was
202
+ * `.reverse()` — which repaired the symptom and left the defect: the
203
+ * renderer still had no idea which sessions were newest, it just trusted a
204
+ * position. Choosing by date removes the position from the question
205
+ * entirely, so where an entry is written stops mattering.
206
+ *
207
+ * Ties keep array order with the later index first, which is the only
208
+ * information left when two entries share a day — and several do.
209
+ */
210
+ export function selectRecentSessions<T extends { date: string }>(
211
+ sessions: readonly T[],
212
+ limit: number,
213
+ ): SessionSelection<T> {
214
+ const undated: T[] = [];
215
+ const ranked = sessions.map((s, i) => {
216
+ const m = ISO_DATE.exec(s.date ?? "");
217
+ if (m === null) undated.push(s);
218
+ // An undated entry sorts below every dated one. `""` is less than any
219
+ // ISO date, so the comparison needs no second branch — and a branch
220
+ // that exists only for the empty case is a branch no fixture reaches.
221
+ return { s, key: m === null ? "" : m[0], i };
222
+ });
223
+ ranked.sort((a, b) => (a.key === b.key ? b.i - a.i : a.key < b.key ? 1 : -1));
224
+ return { rendered: ranked.slice(0, limit).map(d => d.s), undated };
225
+ }
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, renameSync, statSync } from "fs";
2
2
  import { join, basename } from "path";
3
+ import { localCalendarDay } from "./local-calendar-day";
3
4
 
4
5
  interface PromoteResult {
5
6
  promoted: string[];
@@ -32,7 +33,10 @@ export function promoteOutputs(projectRoot: string): PromoteResult {
32
33
  const data = JSON.parse(readFileSync(councilJson, "utf-8"));
33
34
  const topic = data.topic || slug;
34
35
  const topicSlug = topic.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60);
35
- const date = data.capturedAt?.slice(0, 10) || new Date().toISOString().slice(0, 10);
36
+ // `capturedAt` is an ISO INSTANT written by the council run, so
37
+ // slicing it is reading a recorded field rather than stamping a day.
38
+ // The fallback — nothing recorded — is a day stamp and is local (#600).
39
+ const date = data.capturedAt?.slice(0, 10) || localCalendarDay();
36
40
  const destDir = join(projectRoot, "docs", "council");
37
41
  const destFile = join(destDir, `${date}-${topicSlug}.md`);
38
42
 
@@ -140,7 +144,7 @@ function buildResearchMarkdown(data: any, topic: string): string {
140
144
  "---",
141
145
  "doc-type: research",
142
146
  "status: active",
143
- `created: ${new Date().toISOString().slice(0, 10)}`,
147
+ `created: ${localCalendarDay()}`,
144
148
  `governs: ${topic}`,
145
149
  "---",
146
150
  "",
@@ -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
+ }