@zero2webmaster/starter-kit 0.15.0 → 0.15.1

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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # z2w-starter-kit
2
2
 
3
- **Version:** 0.15.0 | **Framework:** 2.13.0
3
+ **Version:** 0.15.1 | **Framework:** 2.13.0
4
4
 
5
5
  > Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
6
6
 
@@ -83,7 +83,8 @@ The Claude Code skill at `~/.claude/skills/instantiate-z2w-project/SKILL.md` and
83
83
 
84
84
  ## Status
85
85
 
86
- - **v0.15.0 (current)** deletes the embedded Agent Coordination block in favour of a **pointer**, because this CLI is an *emitter* and a stale copy here is minted into every new Z2W project. `z2w-agent-coordination` measured currency across the ecosystem on 2026-08-07 and found **0 of 37 files at canonical** — 34 stale, 3 frozen paraphrases — and named "delete the copy, keep a pointer" its preferred remedy; the block had grown 4,274 B → 34,515 B in ten weeks, so every bump re-asked ~21 projects for a bigger paste. Scaffolded `CLAUDE.md` files now carry heading + fingerprint + session-start steps 1 and 1b (read the live block; it wins) + the Hard rules, and drop ~24 KB of auto-loaded context each. **The Hard rules stay embedded on purpose** — a leaked secret or an overwritten neighbour is irreversible, so those must hold even when the clone is unreachable. The old byte-diff guard was replaced rather than dropped (pointer conformance + an anti-regrowth byte ceiling, both canary-verified), and a real defect in it was fixed: it read a local bulletin checkout without ever checking that the checkout was current, and that clone was **215 commits behind**, so it compared against stale canon while reporting a shrinking gap.
86
+ - **v0.15.1 (current)** ships `scripts/rollup-integrations.mjs` **in the npm tarball**, which is the one thing standing between the Project Registry reconciler and a schedule. `z2w-agent-coordination` accepted this project's proposal to host it on a cron and built the workflow, then found neither delivery route worked: a checkout of this private repo needs a PAT that could read every private repo in the org, and although the package *is* published, the tarball shipped **no `scripts/` at all** — `files` listed `dist/**` + README + LICENSE and the reconciler matched none of those globs. *"It is published"* and *"the script is reachable"* were two different facts. A runner can now `npm i @zero2webmaster/starter-kit@latest` and get it with **zero credentials**. Guarded by `src/package-contents.test.ts`, which runs `npm pack --dry-run --json` and asserts on the **artifact** rather than the glob — nothing here could previously tell a shipped file from an unshipped one.
87
+ - **v0.15.0** deletes the embedded Agent Coordination block in favour of a **pointer**, because this CLI is an *emitter* and a stale copy here is minted into every new Z2W project. `z2w-agent-coordination` measured currency across the ecosystem on 2026-08-07 and found **0 of 37 files at canonical** — 34 stale, 3 frozen paraphrases — and named "delete the copy, keep a pointer" its preferred remedy; the block had grown 4,274 B → 34,515 B in ten weeks, so every bump re-asked ~21 projects for a bigger paste. Scaffolded `CLAUDE.md` files now carry heading + fingerprint + session-start steps 1 and 1b (read the live block; it wins) + the Hard rules, and drop ~24 KB of auto-loaded context each. **The Hard rules stay embedded on purpose** — a leaked secret or an overwritten neighbour is irreversible, so those must hold even when the clone is unreachable. The old byte-diff guard was replaced rather than dropped (pointer conformance + an anti-regrowth byte ceiling, both canary-verified), and a real defect in it was fixed: it read a local bulletin checkout without ever checking that the checkout was current, and that clone was **215 commits behind**, so it compared against stale canon while reporting a shrinking gap.
87
88
  - **v0.14.0** makes card-path bot protection a scaffold standard, and fixes a defect that made **every** Next.js scaffold's server modules impossible to unit-test. A new `acceptsCards` input inserts a standard pointing at [[stripe-elements-confirm-path]] §8 for every project type that has a runtime request surface, and — for Next.js — emits the protected endpoint shape rather than a bare one: a Turnstile verifier whose verdict is five-valued and **fails open**, an abuse policy sized for card entry (30 per 10 minutes per source, no global cap) rather than copied from order submission, the browser widget with `appearance: "interaction-only"` and every failure callback wired, and an emitted test that greps the consuming project's own `app/` and fails the next card path added bare. The enumeration grep ships *with* the standard, because a rule that says "protect the card path" without saying how to enumerate card paths passes review and misses a route. Separately: `import "server-only"` is a build-time poison pill that made every server module in every scaffold fail to LOAD under vitest — while `next build`, `tsc --noEmit` and the emitted suite all passed — so scaffolds now emit a `server-only` test stub plus the `@/*` alias that mirrors `tsconfig.json`.
88
89
  - **v0.9.5** gives the Project Registry a **write path for the events it describes**. `z2w-agent-command-center` reported two stale `production_status` rows and asked for a writer; investigating found two different causes wearing one face. `site-control`'s row would have been fixed by the reconciler that already exists — nothing ever ran it. `email-engine`'s row **could not** be fixed, because `scripts/rollup-integrations.mjs` allowed a backtick before the status value but not an asterisk, so every project that **bolded** its Live status parsed as null and vanished from the report — indistinguishable from a row already in sync. That was 3 of the 15 sections declaring a status (20%), two of which said LIVE. The parser now reads the forms agents actually write, and reports declared-but-unreadable separately from never-declared, at zero as well as non-zero. Six rows reconciled. Also: the `command_center` role (scoped to the two approval columns), a CHECK that makes `summary_state = 'approved'` unreachable without them, and `status_qualifier` for the projects that kept writing a sixth value into a five-value enum.
89
90
  - **v0.9.4** corrects a **privacy understatement in the emitted Sentry standard**. It had told every scaffolded web app to set `sendDefaultPii: true` and described the consequence as *"user IP + request headers"*. Verified against `@sentry/core` 10.69.0's own `defaultPiiToCollectionOptions()`, that flag resolves **ten** axes on — including `httpBodies` in all four directions, `databaseQueryData`, `stackFrameVariables` (local variable values), and `genAI: { inputs: true, outputs: true }`, which is the user's prompt and the model's completion. The standard now prescribes one complete `dataCollection` block, carries both counter-intuitive traps (a partial block flips the baseline to all-on; `stackFrameVariables` is on in *both* branches so `sendDefaultPii: false` cannot reach it), and makes the **resolver** the binding check rather than any list in a doc. Also retires the registry's `project_type` column in favour of `stack` + `audience`.
@@ -114,4 +115,4 @@ Inquiries: kerry@zero2webmaster.com.
114
115
  ---
115
116
 
116
117
  *Scaffolded 2026-05-28 via the [[instantiate-z2w-project]] Claude Code skill v1; reconciled against the consolidated skill v1.1.0 (brief-first + Agent Coordination block) on 2026-05-29.*
117
- *Version: 0.15.0 | Last Updated: 2026-08-08*
118
+ *Version: 0.15.1 | Last Updated: 2026-08-08*
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero2webmaster/starter-kit",
3
- "version": "0.15.0",
3
+ "version": "0.15.1",
4
4
  "description": "Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.",
5
5
  "author": {
6
6
  "name": "Dr. Kerry Kriger",
@@ -24,6 +24,7 @@
24
24
  "files": [
25
25
  "dist/**/*.js",
26
26
  "dist/**/*.d.ts",
27
+ "scripts/rollup-integrations.mjs",
27
28
  "README.md",
28
29
  "LICENSE"
29
30
  ],
@@ -0,0 +1,573 @@
1
+ #!/usr/bin/env node
2
+ // rollup-integrations.mjs — Ecosystem integration/live-status rollup (registry-owner side).
3
+ //
4
+ // WHAT IT DOES
5
+ // Reads every `projects/*.md` bulletin file in the z2w-agent-coordination repo,
6
+ // parses its `## Integrations (consumes / provides)` section (the block adopted into
7
+ // the canonical Agent Coordination protocol — see ECOSYSTEM-INTEGRATION-MAP-PROPOSAL.md),
8
+ // and upserts each project's `production_status` + `consumes` edges into the
9
+ // software-projects registry (Neon `projects` table). This is the mechanism that keeps
10
+ // the registry's ecosystem map + live-status true without anyone hand-maintaining it —
11
+ // agents write their `## Integrations` section at session end, this rolls it up.
12
+ //
13
+ // WHY IT EXISTS
14
+ // Root cause of the 2026-07-20 miss: no single place reliably answered "is app X live?"
15
+ // or "who consumes app X?". The bulletin is where each agent already writes state every
16
+ // session, so it is the lowest-friction capture point; this script is the bulletin → registry pipe.
17
+ //
18
+ // SAFETY
19
+ // DRY-RUN BY DEFAULT — prints the diff it WOULD apply and writes nothing. Pass --apply to
20
+ // write. Reads Z2W_INVENTORY_DATABASE_URL from the environment (use `node --env-file`).
21
+ // Only ever touches rows whose slug already exists in the registry (never inserts); an
22
+ // `## Integrations` section for an unknown slug is reported and skipped, not created.
23
+ // Idempotent: a bulletin file with no `## Integrations` section is skipped cleanly, so this
24
+ // is safe to run before the protocol block has propagated to every project.
25
+ //
26
+ // ADDITIVE BY DEFAULT (2026-07-25). Edges are UNIONed with what's already in the row, so a
27
+ // parse miss can never delete a known-good edge — it can only fail to add one. `--prune`
28
+ // opts into letting the bulletin be authoritative (removals allowed, listed before writing).
29
+ //
30
+ // NO SILENT ZERO (2026-07-25). An `## Integrations` section that yields zero edges is
31
+ // WARNED about and counted separately. Rationale: for five days this script reported
32
+ // "4 sections scanned → 0 rows would change" — indistinguishable from "already in sync" —
33
+ // while in fact every adopting project had written a non-canonical edge form and the
34
+ // pipeline was completely inert. A zero result must never look like a healthy one.
35
+ //
36
+ // NO SILENT ZERO, STATUS HALF (2026-08-02). The rule above covered EDGES only, so the
37
+ // identical defect sat in the sibling field for another eight days: a `**Live status:**`
38
+ // line the parser could not read yielded null, no diff, and no mention in the report.
39
+ // Measured on the live bulletin the day it was found, the parser read NOTHING from 3 of
40
+ // the 15 sections declaring a status (20%) — every one of them because the agent BOLDED
41
+ // the value and the regex allowed only a backtick. Two of the three said LIVE.
42
+ // `email-engine`'s row therefore said `Scaffolded` for ten days, and the miss was found
43
+ // by another project's auditor rather than by the reconciler built to prevent it.
44
+ // Three counters are now always printed, at zero as well: rows changed, status lines
45
+ // DECLARED-BUT-UNREADABLE (a defect), and sections with NO status line (legitimate on a
46
+ // young project — skipped and reported, never defaulted). Absence is not a value.
47
+ //
48
+ // ONE DIRECTION ONLY — bulletin → registry, NEVER the reverse. If the registry could
49
+ // write back to a project's Live status line, a stale row would overwrite the owning
50
+ // agent's own fresh statement and destroy the ground truth this script follows.
51
+ // (Constraint from `site-control` via `z2w-agent-command-center`, 2026-08-01.)
52
+ //
53
+ // A STATUS FIX MUST NOT DESTROY THE FIELD BESIDE IT (2026-08-02). `live_status_as_of` is
54
+ // written with COALESCE, not `?? null`: a section can state a status in prose without
55
+ // restating an "as of" date, and the old form wrote NULL over a date the registry
56
+ // already held. Same principle the edges half follows — a parse MISS may fail to add,
57
+ // never delete.
58
+ //
59
+ // ACCEPTED EDGE FORMS (canonical first; the others exist because agents wrote them)
60
+ // - consumes: contact-registry — why ← canonical, trusted, any target
61
+ // - **consumes:** `a` (why), `b` (why) ← inline list; parens stripped before split
62
+ // - `file-server` — why ← bare bullet under **Consumes**; CONSERVATIVE:
63
+ // only registry slugs or `x:qualifier` targets,
64
+ // else prose/skill names become fake edges
65
+ //
66
+ // ROUND-TRIP BEFORE HANDOFF (2026-07-26). `--emit-prefill <slug>` generates a §8.10-conformant
67
+ // `## Integrations` block for another project to paste, and REFUSES to print it unless it parses
68
+ // back through this file's own parseSection() to exactly the values that went in. Rationale: the
69
+ // hand-written pre-fill given to z2w-member-match on 2026-07-25 deviated from §8.10 (no `provides:`
70
+ // prefix on the empty marker; the parenthetical + colon stripped from both sub-section headers) and
71
+ // would not have parsed — while its cover note told them to "paste this verbatim." That was the
72
+ // third time in two weeks a payload was generated for a known consumer without ever being run
73
+ // through that consumer. Generating and validating now share one code path, so they cannot diverge.
74
+ //
75
+ // USAGE
76
+ // node --env-file=.env scripts/rollup-integrations.mjs # dry-run (default)
77
+ // node --env-file=.env scripts/rollup-integrations.mjs --apply # write to Neon
78
+ // node --env-file=.env scripts/rollup-integrations.mjs --apply --prune # let bulletin remove edges
79
+ // node --env-file=.env scripts/rollup-integrations.mjs --status-only --apply # status + qualifier ONLY
80
+ // node --env-file=.env scripts/rollup-integrations.mjs --status-only --strict # non-zero exit on any gap
81
+ //
82
+ // `--status-only` reconciles `production_status` / `live_status_as_of` / `status_qualifier`
83
+ // and leaves `consumes` alone. The two halves carry different confidence: a Live status is
84
+ // one declared enum value, while an edge is best-effort prose parsing that still produces
85
+ // artifacts (the inline-list splitter reads `live-status` out of audit-engine's trailing
86
+ // sentence as an edge). Being able to apply the trustworthy half beats holding it hostage.
87
+ //
88
+ // `--strict` exits non-zero when anything was unreadable. A human reads the warnings; a
89
+ // SCHEDULED runner needs a failure it cannot ignore, so any cron invocation should pass it.
90
+ // node --env-file=.env scripts/rollup-integrations.mjs --bulletin /path/to/z2w-agent-coordination
91
+ // node --env-file=.env scripts/rollup-integrations.mjs --emit-prefill z2w-member-match
92
+ // node scripts/rollup-integrations.mjs --emit-prefill some-project \
93
+ // --status Live --as-of 2026-07-26 --consumes contact-registry,fathom # no DB needed
94
+ //
95
+ // The `## Integrations` block format this parser expects (per the proposal):
96
+ // ## Integrations (consumes / provides)
97
+ // **Live status:** `Live` (as of 2026-07-20)
98
+ // **Consumes** ...:
99
+ // - consumes: contact-registry — reads member/party records
100
+ // - consumes: email-service-router:SES — outbound send
101
+ // **Provides** ...:
102
+ // - provides: agents.z2w.us — status feed <-- read for reconciliation only; `provides`
103
+ // is DERIVED from reverse `consumes`, not stored.
104
+
105
+ import { readdir, readFile } from "node:fs/promises";
106
+ import { join } from "node:path";
107
+ import { pathToFileURL } from "node:url";
108
+ import { neon } from "@neondatabase/serverless";
109
+
110
+ const VALID_STATUS = new Set(["Planning", "Scaffolded", "Live", "Dormant", "Retired"]);
111
+
112
+ const DEFAULT_BULLETIN_DIRS = [
113
+ join(process.env.HOME ?? "", "Desktop/Zero2Webmaster/AI/Cursor Projects/z2w-agent-coordination"),
114
+ join(process.env.HOME ?? "", ".cache/z2w-coordination"),
115
+ ];
116
+
117
+ export function parseArgs(argv) {
118
+ const args = { apply: false, bulletin: null, emitPrefill: null };
119
+ for (let i = 2; i < argv.length; i++) {
120
+ if (argv[i] === "--apply") args.apply = true;
121
+ else if (argv[i] === "--prune") args.prune = true;
122
+ else if (argv[i] === "--status-only") args.statusOnly = true;
123
+ else if (argv[i] === "--strict") args.strict = true;
124
+ else if (argv[i] === "--bulletin") args.bulletin = argv[++i];
125
+ else if (argv[i] === "--emit-prefill") args.emitPrefill = argv[++i];
126
+ else if (argv[i] === "--status") args.status = argv[++i];
127
+ else if (argv[i] === "--as-of") args.asOf = argv[++i];
128
+ else if (argv[i] === "--consumes") args.consumes = argv[++i];
129
+ else if (argv[i] === "--provides") args.provides = argv[++i];
130
+ }
131
+ return args;
132
+ }
133
+
134
+ // Extract the `## Integrations` section body (everything until the next `## ` heading).
135
+ export function extractIntegrationsSection(md) {
136
+ const lines = md.split("\n");
137
+ let start = -1;
138
+ for (let i = 0; i < lines.length; i++) {
139
+ if (/^##\s+Integrations\b/i.test(lines[i])) { start = i + 1; break; }
140
+ }
141
+ if (start === -1) return null;
142
+ const body = [];
143
+ for (let i = start; i < lines.length; i++) {
144
+ if (/^##\s+/.test(lines[i])) break;
145
+ body.push(lines[i]);
146
+ }
147
+ return body.join("\n");
148
+ }
149
+
150
+ // A slug as agents actually write it: bare, or wrapped in backticks/bold, optionally
151
+ // with a `:qualifier` naming a concrete backend (`email-service-router:SES`).
152
+ function cleanSlug(raw) {
153
+ const s = String(raw).trim().replace(/^[`*_]+|[`*_]+$/g, "").trim();
154
+ if (!s || /^\(none/i.test(s)) return null;
155
+ // Reject prose that isn't a slug (spaces, sentence punctuation).
156
+ if (!/^[a-z0-9][a-z0-9._-]*(:[A-Za-z0-9._-]+)?$/i.test(s)) return null;
157
+ return s;
158
+ }
159
+
160
+ /**
161
+ * Parse the `## Integrations` section.
162
+ *
163
+ * The canonical form (AGENT_PROTOCOL §8.10 / bulletin README §4) is one edge per line:
164
+ * - consumes: contact-registry — why
165
+ *
166
+ * But every project that adopted the section first wrote something else, and a parser
167
+ * that only accepts the canonical form reports ZERO matches — which looks exactly like
168
+ * "already in sync" (see `zeroEdges` handling in main(); 2026-07-25). So we also accept
169
+ * the two variants seen in the wild, while keeping the canonical form primary:
170
+ * - `file-server` — campaign cover images (bullet under a **Consumes** heading)
171
+ * - **consumes:** `a` (why), `b` (why), `c` (inline comma list)
172
+ */
173
+ export function parseSection(section, knownSlugs = new Set()) {
174
+ const result = { liveStatus: null, statusDeclared: false, statusQualifier: null, asOf: null, consumes: [] };
175
+
176
+ // The label is matched on its own, SEPARATELY from the value, so the caller can tell
177
+ // "declared but unreadable" (a defect) from "never declared" (a young project, and
178
+ // legitimately absent — the section is lazily created). Folding the two into one regex
179
+ // is what hid email-engine: a non-match returned null for both cases at once, so no
180
+ // warning could fire on the first without crying wolf about the second. [[zero-is-not-a-pass]]
181
+ //
182
+ // The label must be BOLD (`**Live status**`) — that is the §8.10 form, and requiring it
183
+ // keeps the phrase "live status" in ordinary prose from registering as a declaration.
184
+ const statusLine = section.match(/^.*\*\*Live status\b.*$/im);
185
+ if (statusLine) {
186
+ result.statusDeclared = true;
187
+ // Strip the label — tolerating `**Live status:**` and `**Live status**:` — then strip
188
+ // any emphasis the agent wrapped the VALUE in before reading the first word. The old
189
+ // regex allowed a backtick here and nothing else, so every project that bolded its
190
+ // value ("**LIVE IN PRODUCTION since …**") parsed as null and was silently skipped.
191
+ const value = statusLine[0]
192
+ .replace(/^.*?\*\*Live status\*{0,2}\s*:?\s*\*{0,2}\s*:?\s*/i, "")
193
+ .replace(/^[`*_"'\s]+/, "");
194
+ const word = value.match(/^[A-Za-z]+/);
195
+ if (word) {
196
+ const s = word[0].charAt(0).toUpperCase() + word[0].slice(1).toLowerCase();
197
+ // Loosening the EMPHASIS handling must not loosen the VOCABULARY: a value that
198
+ // opens on prose ("**Not yet deployed**") still falls through to null, and the
199
+ // caller's unreadable-status warning is what surfaces it.
200
+ if (VALID_STATUS.has(s)) result.liveStatus = s;
201
+
202
+ // A qualifier is the parenthetical IMMEDIATELY following the status word — the form
203
+ // femperium-lead-gen wrote by hand (`Live (degraded)`) when five enum values could
204
+ // not say what it meant. It is deliberately NOT "any parenthetical on the line":
205
+ // almost every §8.10 line ends in "(as of YYYY-MM-DD)", and a looser rule would put
206
+ // a date into a field meant to be rendered as prose beside the badge.
207
+ if (result.liveStatus) {
208
+ const after = value.slice(word[0].length).match(/^\s*\(([^)]*)\)/);
209
+ const q = after?.[1].trim();
210
+ // 1..120 mirrors the column's own CHECK, so the parser can never hand the writer
211
+ // a value the database will reject (site-control's parenthetical is a paragraph).
212
+ if (q && q.length <= 120 && !/^as of\b/i.test(q)) result.statusQualifier = q;
213
+ }
214
+ }
215
+ }
216
+ const asOfMatch = section.match(/as of\s+(\d{4}-\d{2}-\d{2})/i);
217
+ if (asOfMatch) result.asOf = asOfMatch[1];
218
+
219
+ // Track which half of the section we're in, so a bare-slug bullet under **Provides**
220
+ // is never mistaken for a consumes edge (provides is DERIVED, never stored).
221
+ let inConsumes = false;
222
+ for (const line of section.split("\n")) {
223
+ if (/^\s*\*{0,2}Consumes\b/i.test(line.replace(/^[-*]\s*/, ""))) inConsumes = true;
224
+ else if (/^\s*\*{0,2}Provides\b/i.test(line.replace(/^[-*]\s*/, ""))) inConsumes = false;
225
+
226
+ // (a) canonical: `- consumes: slug — why` / (b) inline list: `- **consumes:** a, b, c`
227
+ const labelled = line.match(/^\s*[-*]\s*\*{0,2}consumes:?\*{0,2}:?\s*(.+)$/i);
228
+ if (labelled) {
229
+ // Strip parentheticals BEFORE splitting: the per-edge "(why…)" notes contain
230
+ // commas of their own, and splitting first shreds every slug after the first.
231
+ // Also cut at "Later phases:" — those are aspirational, not current edges.
232
+ const body = labelled[1]
233
+ .replace(/\([^)]*\)/g, "")
234
+ .split(/\bLater phases?\b\s*:?/i)[0];
235
+ for (const part of body.split(",")) {
236
+ const head = part.split(/\s+[—–-]\s+/)[0];
237
+ const slug = cleanSlug(head);
238
+ if (slug) result.consumes.push(slug);
239
+ }
240
+ continue;
241
+ }
242
+
243
+ // (c) prose bullet under the **Consumes** heading: "- `file-server` — why".
244
+ // CONSERVATIVE: an unlabelled bullet is inference, not a declaration, so accept it
245
+ // only when the target is a real registry slug or carries a `:qualifier` (a
246
+ // deliberate backend). Otherwise a nearby skill name or stray word becomes a fake
247
+ // edge — `stripe-payment-metadata-contract` did exactly that on the first run.
248
+ if (inConsumes) {
249
+ const bullet = line.match(/^\s*[-*]\s+(.+)$/);
250
+ if (bullet) {
251
+ const head = bullet[1].split(/\s+[—–-]\s+/)[0].replace(/\([^)]*\)/g, "");
252
+ const slug = cleanSlug(head);
253
+ if (slug && (knownSlugs.has(slug.split(":")[0]) || slug.includes(":"))) {
254
+ result.consumes.push(slug);
255
+ }
256
+ }
257
+ }
258
+ }
259
+ // de-dupe, preserve order
260
+ result.consumes = [...new Set(result.consumes)];
261
+ return result;
262
+ }
263
+
264
+ /**
265
+ * Build a `## Integrations` block that conforms to AGENT_PROTOCOL.md §8.10 exactly.
266
+ *
267
+ * The four things the 2026-07-25 hand-written pre-fill got wrong, all encoded here:
268
+ * 1. The heading carries its parenthetical: `## Integrations (consumes / provides)`.
269
+ * 2. BOTH sub-section headers keep their parenthetical AND their trailing colon —
270
+ * `**Consumes** (Z2W apps/engines this project depends on or calls):`
271
+ * 3. Every edge line carries its `consumes:` / `provides:` LABEL prefix.
272
+ * 4. The empty marker is labelled too — `- provides: (none yet)`, never a bare
273
+ * `(none yet)`. §8.10: "never leave a listed sub-section blank."
274
+ */
275
+ export function buildPrefill({ status, asOf, consumes = [], provides = [], note = null }) {
276
+ if (!VALID_STATUS.has(status)) {
277
+ throw new Error(`invalid Live status "${status}" — must be one of: ${[...VALID_STATUS].join(" | ")}`);
278
+ }
279
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(asOf ?? "")) {
280
+ throw new Error(`invalid as-of date "${asOf}" — must be YYYY-MM-DD`);
281
+ }
282
+ const line = (label, e) =>
283
+ typeof e === "string" ? `- ${label}: ${e}` : `- ${label}: ${e.slug} — ${e.why}`;
284
+
285
+ const out = [
286
+ "## Integrations (consumes / provides)",
287
+ "",
288
+ `**Live status:** \`${status}\` (as of ${asOf})`,
289
+ "",
290
+ "**Consumes** (Z2W apps/engines this project depends on or calls):",
291
+ ...(consumes.length ? consumes.map((e) => line("consumes", e)) : ["- consumes: (none yet)"]),
292
+ "",
293
+ "**Provides** (Z2W apps that depend on this project):",
294
+ ...(provides.length ? provides.map((e) => line("provides", e)) : ["- provides: (none yet)"]),
295
+ ];
296
+ if (note) out.push("", `> ${note}`);
297
+ return out.join("\n") + "\n";
298
+ }
299
+
300
+ /**
301
+ * Round-trip a generated pre-fill through THIS FILE'S OWN parser and assert it
302
+ * reads back to exactly what went in. This is the guard that makes a pre-fill
303
+ * safe to hand another agent: the block and its consumer are validated by one
304
+ * code path, so "canonical" is proven rather than asserted.
305
+ *
306
+ * Returns { ok, parsed, problems[] }. Callers must refuse to emit when !ok.
307
+ */
308
+ export function validatePrefill(block, expected, knownSlugs = new Set()) {
309
+ const problems = [];
310
+ const section = extractIntegrationsSection(block);
311
+ if (section == null) {
312
+ return { ok: false, parsed: null, problems: ["the block has no `## Integrations` heading the parser can find"] };
313
+ }
314
+ const parsed = parseSection(section, knownSlugs);
315
+
316
+ if (parsed.liveStatus !== expected.status) {
317
+ problems.push(`Live status did not round-trip: expected ${expected.status}, parsed ${parsed.liveStatus ?? "null"}`);
318
+ }
319
+ if (parsed.asOf !== expected.asOf) {
320
+ problems.push(`as-of date did not round-trip: expected ${expected.asOf}, parsed ${parsed.asOf ?? "null"}`);
321
+ }
322
+ const want = (expected.consumes ?? []).map((e) => (typeof e === "string" ? e : e.slug)).sort();
323
+ const got = [...parsed.consumes].sort();
324
+ if (JSON.stringify(want) !== JSON.stringify(got)) {
325
+ problems.push(`consumes edges did not round-trip: expected [${want.join(", ")}], parsed [${got.join(", ")}]`);
326
+ }
327
+ // A non-empty declaration that parses to zero edges is the silent-no-op shape.
328
+ if (want.length > 0 && got.length === 0) {
329
+ problems.push("ZERO edges parsed from a non-empty declaration — this is the silent-no-op failure");
330
+ }
331
+ return { ok: problems.length === 0, parsed, problems };
332
+ }
333
+
334
+ function resolveBulletinDir(explicit) {
335
+ const candidates = explicit ? [explicit] : DEFAULT_BULLETIN_DIRS;
336
+ return candidates;
337
+ }
338
+
339
+ /** `--emit-prefill <slug>`: generate a validated block, or fail loudly. */
340
+ async function emitPrefill(args) {
341
+ const slug = args.emitPrefill;
342
+ let status = args.status ?? null;
343
+ let asOf = args.asOf ?? null;
344
+ let consumes = args.consumes ? args.consumes.split(",").map((s) => s.trim()).filter(Boolean) : null;
345
+ const provides = args.provides ? args.provides.split(",").map((s) => s.trim()).filter(Boolean) : [];
346
+ let known = new Set();
347
+
348
+ // Prefer the registry (the source of truth this project owns) for anything the
349
+ // caller did not override. No DB URL + full flags is a valid offline path.
350
+ const dbUrl = (process.env.Z2W_INVENTORY_DATABASE_URL ?? "").trim();
351
+ if (dbUrl) {
352
+ const sql = neon(dbUrl);
353
+ known = new Set((await sql`SELECT slug FROM projects`).map((r) => r.slug));
354
+ const [row] = await sql`SELECT production_status, consumes, live_status_as_of FROM projects WHERE slug = ${slug}`;
355
+ if (!row) {
356
+ console.error(`✗ ${slug} is not in the registry. Pass --status/--as-of/--consumes to emit anyway.`);
357
+ if (!status || !asOf) process.exit(1);
358
+ } else {
359
+ status ??= row.production_status;
360
+ consumes ??= row.consumes ?? [];
361
+ asOf ??= row.live_status_as_of
362
+ ? new Date(row.live_status_as_of).toISOString().slice(0, 10)
363
+ : null;
364
+ }
365
+ }
366
+ if (!asOf) {
367
+ console.error("✗ No as-of date. Pass --as-of YYYY-MM-DD (never guess a date).");
368
+ process.exit(1);
369
+ }
370
+ if (!status) {
371
+ console.error(`✗ No Live status. Pass --status <${[...VALID_STATUS].join("|")}>.`);
372
+ process.exit(1);
373
+ }
374
+
375
+ const expected = { status, asOf, consumes: consumes ?? [] };
376
+ let block;
377
+ try {
378
+ block = buildPrefill(expected);
379
+ } catch (err) {
380
+ // Clear sentence, not a stack trace (Z2W CLI readability rule).
381
+ console.error(`✗ Cannot build the pre-fill: ${err.message}`);
382
+ process.exit(1);
383
+ }
384
+ const { ok, parsed, problems } = validatePrefill(block, expected, known);
385
+
386
+ if (!ok) {
387
+ console.error("✗ REFUSING TO EMIT — the generated block does not round-trip through this script's own parser:");
388
+ for (const p of problems) console.error(` • ${p}`);
389
+ console.error("\n Fix buildPrefill()/parseSection() before handing anything to another project.");
390
+ process.exit(1);
391
+ }
392
+
393
+ console.error(`✓ Round-tripped through parseSection(): status ${parsed.liveStatus}, as of ${parsed.asOf}, ${parsed.consumes.length} edge(s) [${parsed.consumes.join(", ")}]`);
394
+ const unknown = parsed.consumes.filter((c) => known.size > 0 && !known.has(c.split(":")[0]));
395
+ if (unknown.length) console.error(` ⓘ not registry slugs (external backends, or check for typos): ${unknown.join(", ")}`);
396
+ console.error(` Paste the block below into projects/${slug}.md, directly above \`## Current focus\`.\n`);
397
+ process.stdout.write(block);
398
+ }
399
+
400
+ async function main() {
401
+ const args = parseArgs(process.argv);
402
+
403
+ // Pre-fill generation is a separate, read-only mode — it never touches the registry.
404
+ if (args.emitPrefill) return emitPrefill(args);
405
+
406
+ const dbUrl = (process.env.Z2W_INVENTORY_DATABASE_URL ?? "").trim();
407
+ if (!dbUrl) {
408
+ console.error("✗ Z2W_INVENTORY_DATABASE_URL not set. Run with: node --env-file=.env scripts/rollup-integrations.mjs");
409
+ process.exit(1);
410
+ }
411
+
412
+ // Locate the bulletin dir + projects/ subfolder.
413
+ const { access } = await import("node:fs/promises");
414
+ let projectsDir = null;
415
+ for (const base of resolveBulletinDir(args.bulletin)) {
416
+ const candidate = join(base, "projects");
417
+ try { await access(candidate); projectsDir = candidate; break; } catch { /* try next */ }
418
+ }
419
+ if (!projectsDir) {
420
+ console.error("✗ Could not find a z2w-agent-coordination/projects directory. Pass --bulletin <path>.");
421
+ process.exit(1);
422
+ }
423
+
424
+ const files = (await readdir(projectsDir)).filter((f) => f.endsWith(".md") && !f.startsWith("_"));
425
+ const sql = neon(dbUrl);
426
+ const known = new Set((await sql`SELECT slug FROM projects`).map((r) => r.slug));
427
+
428
+ let parsed = 0, skippedNoSection = 0, skippedUnknown = 0, changed = 0;
429
+ const plan = [];
430
+ const zeroEdges = [];
431
+ const unreadableStatus = []; // line present, value unreadable — a DEFECT
432
+ const noStatusLine = []; // no line at all — legitimate; skip and report
433
+
434
+ for (const file of files.sort()) {
435
+ const slug = file.replace(/\.md$/, "");
436
+ const md = await readFile(join(projectsDir, file), "utf8");
437
+ const section = extractIntegrationsSection(md);
438
+ if (section == null) { skippedNoSection++; continue; }
439
+ parsed++;
440
+ if (!known.has(slug)) { skippedUnknown++; console.warn(` ⚠ ${slug}: has ## Integrations but no registry row — skipped (never auto-inserted).`); continue; }
441
+
442
+ const { liveStatus, statusDeclared, statusQualifier, asOf, consumes } = parseSection(section, known);
443
+
444
+ // NO SILENT ZERO, STATUS HALF (2026-08-02). The `zeroEdges` counter below has caught
445
+ // an inert EDGE pipeline since 2026-07-25; the STATUS field had no equivalent, so a
446
+ // Live status the parser could not read produced `liveStatus = null`, a falsy
447
+ // `statusChanged`, and a project that vanished from the report — identical on screen
448
+ // to a row already in sync. That is how email-engine's row said `Scaffolded` for ten
449
+ // days while its bulletin said LIVE IN PRODUCTION, and why the miss was found by
450
+ // another project's auditor rather than by the reconciler built to prevent it.
451
+ //
452
+ // The two cases are counted SEPARATELY and deliberately: an absent line is normal on
453
+ // a young project and must never be treated as a value, while an unreadable line is
454
+ // always a defect in either the bulletin or this parser.
455
+ if (statusDeclared && !liveStatus) {
456
+ unreadableStatus.push(slug);
457
+ console.warn(` ⚠ ${slug}: **Live status:** line present but UNREADABLE — no row change will be proposed. Expected one of: ${[...VALID_STATUS].join(" | ")}.`);
458
+ } else if (!statusDeclared) {
459
+ noStatusLine.push(slug);
460
+ }
461
+
462
+ // NO SILENT ZERO. A section that yields nothing is a parse failure or an empty
463
+ // declaration — either way it must NOT be reported the same as "already in sync."
464
+ // (2026-07-25: all 4 adopting projects wrote a non-canonical edge form, so the
465
+ // rollup printed "0 rows would change" for five days while the pipeline was inert.)
466
+ if (consumes.length === 0 && !/\(none/i.test(section)) {
467
+ zeroEdges.push(slug);
468
+ console.warn(` ⚠ ${slug}: ## Integrations present but ZERO edges parsed — check the line form (expected \`- consumes: {slug} — {why}\`).`);
469
+ }
470
+
471
+ const [current] = await sql`SELECT production_status, status_qualifier, consumes FROM projects WHERE slug = ${slug}`;
472
+ const curConsumes = current?.consumes ?? [];
473
+
474
+ // ADDITIVE BY DEFAULT. Prose parsing is best-effort, so a miss must never DELETE a
475
+ // known-good edge — it may only fail to add a new one. `--prune` opts into letting
476
+ // the bulletin be authoritative (i.e. removing edges it no longer declares).
477
+ const nextConsumes = args.prune ? consumes : [...new Set([...curConsumes, ...consumes])];
478
+ const dropped = curConsumes.filter((c) => !nextConsumes.includes(c));
479
+
480
+ const statusChanged = liveStatus && liveStatus !== current?.production_status;
481
+
482
+ // The qualifier gets its OWN trigger rather than riding along on statusChanged.
483
+ // It belongs to the status DECLARATION, so a project that recovers from "(degraded)"
484
+ // while staying `Live` changes no enum value — and a qualifier that can only be
485
+ // written when the badge moves would sit there saying "degraded" after the outage
486
+ // ended. That is worse than not having the column, because a stale caveat is read as
487
+ // current. Only reconciled when a readable status exists: absence of a whole section
488
+ // must never be read as "the qualifier was cleared".
489
+ const qualifierChanged = Boolean(liveStatus) && (statusQualifier ?? null) !== (current?.status_qualifier ?? null);
490
+ // `--status-only` reconciles production_status WITHOUT touching edges. The two halves
491
+ // have different confidence: a Live status is a single declared enum value, while an
492
+ // edge is best-effort prose parsing that still produces artifacts (the inline-list
493
+ // splitter reads `live-status` out of audit-engine's trailing sentence as an edge).
494
+ // Being able to apply the trustworthy half alone beats holding it hostage to the other.
495
+ const consumesChanged = !args.statusOnly
496
+ && nextConsumes.length > 0
497
+ && JSON.stringify([...nextConsumes].sort()) !== JSON.stringify([...curConsumes].sort());
498
+ if (!statusChanged && !qualifierChanged && !consumesChanged) continue;
499
+
500
+ // Surface edges we can't match to a registry row: valid (external backends render as
501
+ // "external" on the graph) but also how a stray non-app string sneaks in from prose.
502
+ const unknownTargets = nextConsumes.filter((c) => !known.has(c.split(":")[0]));
503
+
504
+ changed++;
505
+ plan.push({ slug, liveStatus, statusQualifier, asOf, consumes: nextConsumes, statusChanged, qualifierChanged, consumesChanged, current });
506
+ console.log(` • ${slug}: ` +
507
+ (statusChanged ? `status ${current?.production_status ?? "∅"} → ${liveStatus} ` : "") +
508
+ (qualifierChanged ? `qualifier ${current?.status_qualifier ? `"${current.status_qualifier}"` : "∅"} → ${statusQualifier ? `"${statusQualifier}"` : "∅"} ` : "") +
509
+ (consumesChanged ? `consumes [${curConsumes.join(", ") || "∅"}] → [${nextConsumes.join(", ")}]` : ""));
510
+ if (dropped.length) console.warn(` ⚠ --prune REMOVES: ${dropped.join(", ")}`);
511
+ if (consumesChanged && unknownTargets.length) console.warn(` ⓘ not registry slugs (external, or prose noise — check): ${unknownTargets.join(", ")}`);
512
+
513
+ if (args.apply) {
514
+ if (qualifierChanged) {
515
+ await sql`UPDATE projects SET status_qualifier = ${statusQualifier ?? null}, updated_at = now() WHERE slug = ${slug}`;
516
+ }
517
+ if (statusChanged) {
518
+ // COALESCE, not `?? null`. A section can state a status without restating an
519
+ // "as of" date (email-engine writes "LIVE IN PRODUCTION since 2026-07-23" in
520
+ // prose), and the old form wrote NULL over a date the registry already held —
521
+ // a status fix that quietly destroyed the field beside it. Same principle the
522
+ // edges half already follows: a parse MISS may fail to add, never delete.
523
+ await sql`UPDATE projects
524
+ SET production_status = ${liveStatus},
525
+ live_status_as_of = COALESCE(${asOf ?? null}::date, live_status_as_of),
526
+ updated_at = now()
527
+ WHERE slug = ${slug}`;
528
+ }
529
+ if (consumesChanged) {
530
+ // MUST write nextConsumes, not consumes. `consumes` is the raw parse of THIS
531
+ // bulletin file; `nextConsumes` is the additive union with what's already in
532
+ // the row (or the raw parse under --prune). Writing `consumes` here defeated
533
+ // the entire ADDITIVE-BY-DEFAULT guarantee documented above and made the
534
+ // dry-run diff a LIE — the plan printed the union while the write applied the
535
+ // parse, so any edge the parser missed was silently DELETED without --prune.
536
+ // Found 2026-07-26 while adding the pre-fill round-trip.
537
+ await sql`UPDATE projects SET consumes = ${nextConsumes}, updated_at = now() WHERE slug = ${slug}`;
538
+ }
539
+ }
540
+ }
541
+
542
+ console.log("");
543
+ console.log(`Bulletin files scanned: ${files.length}`);
544
+ console.log(` with ## Integrations: ${parsed} (no section: ${skippedNoSection}, unknown slug: ${skippedUnknown})`);
545
+ console.log(` rows ${args.apply ? "UPDATED" : "that WOULD change"}: ${changed}`);
546
+ if (zeroEdges.length > 0) {
547
+ console.log(` ⚠ sections with ZERO edges parsed: ${zeroEdges.length} (${zeroEdges.join(", ")})`);
548
+ console.log(` A zero here is NOT "in sync" — it means the section's line form didn't match. Fix the bulletin or the parser.`);
549
+ }
550
+ // Report BOTH, always, even at zero — the count is the coverage number, and a silent
551
+ // absence is the thing this whole block exists to make impossible.
552
+ console.log(` ⚠ Live status declared but UNREADABLE: ${unreadableStatus.length}${unreadableStatus.length ? ` (${unreadableStatus.join(", ")})` : ""}`);
553
+ if (unreadableStatus.length > 0) {
554
+ console.log(` These rows CANNOT be reconciled and are not counted above. Fix the bulletin line or this parser.`);
555
+ }
556
+ console.log(` ⓘ no Live status line at all (skipped, not defaulted): ${noStatusLine.length}${noStatusLine.length ? ` (${noStatusLine.join(", ")})` : ""}`);
557
+
558
+ if (!args.apply && changed > 0) console.log(`\nDry-run only. Re-run with --apply to write these ${changed} change(s) to Neon.`);
559
+
560
+ // A scheduled runner needs a non-zero exit to be visible; a human at a terminal reads
561
+ // the warnings. So strictness is opt-in, and any scheduled invocation should pass it.
562
+ if (args.strict && (unreadableStatus.length > 0 || zeroEdges.length > 0)) {
563
+ console.error(`\n✗ --strict: ${unreadableStatus.length} unreadable status line(s) + ${zeroEdges.length} zero-edge section(s). Exiting non-zero so this does not pass unnoticed.`);
564
+ process.exit(1);
565
+ }
566
+ }
567
+
568
+ // Run only when invoked as a script, so the pure functions above (parseSection,
569
+ // buildPrefill, validatePrefill) can be imported by the test suite without the
570
+ // script executing or requiring a DB URL.
571
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
572
+ main().catch((err) => { console.error(err); process.exit(1); });
573
+ }