@zero2webmaster/starter-kit 0.15.0 → 0.16.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.
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.16.0 | **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.16.0 | Last Updated: 2026-08-12*
@@ -58,6 +58,11 @@ const INDEX_HTML_TEMPLATE = `<!DOCTYPE html>
58
58
  <meta name="description" content="{{description}}" />
59
59
  <link rel="canonical" href="__SITE_URL__/" />
60
60
 
61
+ <!-- Browser-tab icon. Generated placeholder (brand primary + initial) — it is
62
+ here so the tab is never blank. Replace icon.svg's contents with real
63
+ artwork, or point this at a favicon.ico, whenever you have one. -->
64
+ <link rel="icon" href="/icon.svg" type="image/svg+xml" />
65
+
61
66
  <!-- Open Graph -->
62
67
  <meta property="og:title" content="{{brand_name}} — {{slug}}" />
63
68
  <meta property="og:description" content="{{description}}" />
@@ -192,6 +197,7 @@ Per Z2W standing org requirement 2026-05-30. Run before adding a new page AND be
192
197
  - [ ] \`<title>\` is unique and intentional (not just brand name)
193
198
  - [ ] \`<meta name="description">\` is unique and intentional
194
199
  - [ ] \`<link rel="canonical">\` set
200
+ - [ ] \`<link rel="icon">\` present (copy it from \`index.html\` — a new HTML file added by hand starts with a blank tab)
195
201
  - [ ] OG + Twitter Card tags present; \`og:image\` resolves
196
202
  - [ ] Exactly one \`<h1>\` stating the page's primary topic
197
203
  - [ ] Heading hierarchy logical (H1 → H2 → H3, no skipped levels)
@@ -207,6 +213,7 @@ Per Z2W standing org requirement 2026-05-30. Run before adding a new page AND be
207
213
  - [ ] Exactly one \`<h1>\` per page; heading hierarchy logical
208
214
  - [ ] Canonical URL set on every page
209
215
  - [ ] OG + Twitter Card tags present; OG image resolves
216
+ - [ ] **Browser tab shows an icon.** \`icon.svg\` + the \`<link rel="icon">\` in \`index.html\` ship by default, so this should pass — check it anyway, because there is no build step here and nothing automated can. Verify against the SERVED site: \`curl -sI <url>/icon.svg\` returns \`200\` with \`content-type: image/svg+xml\`
210
217
  - [ ] Meaningful images have descriptive alt text; decorative images have \`alt=""\`
211
218
  - [ ] JSON-LD present where warranted; validates in Google Rich Results test
212
219
  - [ ] \`sitemap.xml\` generates correctly; \`robots.txt\` references it
@@ -220,6 +227,7 @@ Per Z2W standing org requirement 2026-05-30. Run before adding a new page AND be
220
227
  - ✅ \`sitemap.xml\`
221
228
  - ✅ \`robots.txt\` (references sitemap)
222
229
  - ✅ \`_headers\` — preview deploys emit \`X-Robots-Tag: noindex, nofollow\`
230
+ - ✅ \`icon.svg\` + \`<link rel="icon">\` — a generated brand mark so the browser tab is never blank
223
231
 
224
232
  ## Still author-driven (you fill these in)
225
233
 
@@ -228,6 +236,30 @@ Per Z2W standing org requirement 2026-05-30. Run before adding a new page AND be
228
236
  - ⏳ Drop a real 1200x630 \`public/og-image.png\` in place of the placeholder
229
237
  - ⏳ Tune the \`_headers\` preview-URL pattern if your domain layout differs from the default \`*.pages.dev\` pattern
230
238
  `;
239
+ /**
240
+ * The browser-tab icon for a static Pages deploy — the `cf-pages` counterpart
241
+ * to `nextjs`'s generated `app/icon.tsx`.
242
+ *
243
+ * Emitted for the same reason: NOTHING CATCHES ITS ABSENCE. There is no build
244
+ * step here at all, so a blank tab has even fewer signals than in the Next.js
245
+ * case — the only symptom is a human looking at the tab, which is how it was
246
+ * eventually found (Kerry, 2026-08-09).
247
+ *
248
+ * SVG rather than a generated PNG because a static host has no runtime to
249
+ * render one, and an inline SVG needs no toolchain, no binary asset in git, and
250
+ * no build. Modern browsers all accept `rel="icon"` with `image/svg+xml`.
251
+ *
252
+ * Real artwork later: replace this file's contents, or drop a `favicon.ico` at
253
+ * the site root and point the `<link rel="icon">` in `index.html` at it. The
254
+ * generated mark is a floor, not something to undo.
255
+ */
256
+ const ICON_SVG_TEMPLATE = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="{{brand_name}}">
257
+ <title>{{brand_name}}</title>
258
+ <rect width="32" height="32" fill="{{primary_color}}" />
259
+ <text x="16" y="17" fill="#ffffff" font-family="system-ui, sans-serif" font-size="20" font-weight="700"
260
+ text-anchor="middle" dominant-baseline="central">{{brand_initial}}</text>
261
+ </svg>
262
+ `;
231
263
  export function scaffoldCfPages(inputs, opts) {
232
264
  const spec = resolveBrandSpec(inputs);
233
265
  const base = commonBaseFiles(inputs, opts, NARRATIVE);
@@ -238,6 +270,7 @@ export function scaffoldCfPages(inputs, opts) {
238
270
  { path: "_headers", content: sub(HEADERS_TEMPLATE, inputs, opts, spec) },
239
271
  { path: "_redirects", content: sub(REDIRECTS_TEMPLATE, inputs, opts, spec) },
240
272
  { path: "public/og-image.txt", content: OG_IMAGE_PLACEHOLDER },
273
+ { path: "icon.svg", content: sub(ICON_SVG_TEMPLATE, inputs, opts, spec) },
241
274
  { path: "health.json", content: HEALTH_JSON_TEMPLATE },
242
275
  {
243
276
  path: "SEO-CHECKLIST.md",
@@ -62,6 +62,12 @@ export declare function commonMarketing(inputs: ScaffoldInputs, opts: Scaffolder
62
62
  export declare function commonBackups(inputs: ScaffoldInputs, opts: ScaffolderOptions | undefined, spec: BrandPresetSpec): ScaffoldFile;
63
63
  export declare function commonVersion(): ScaffoldFile;
64
64
  export declare function commonCursorignore(): ScaffoldFile;
65
+ /**
66
+ * Tracked project config, NOT ignored — see CURSOR_INDEXING_IGNORE_TEMPLATE for
67
+ * the 2026-08-12 ruling and why the previous gitignore position was
68
+ * self-defeating.
69
+ */
70
+ export declare function commonCursorIndexingIgnore(): ScaffoldFile;
65
71
  export declare function commonDirective(inputs: ScaffoldInputs, opts: ScaffolderOptions | undefined, spec: BrandPresetSpec): ScaffoldFile;
66
72
  /**
67
73
  * Per-type `.gitignore` body. Sources: skill's "Inline mini-templates"
@@ -446,7 +446,50 @@ __pycache__/
446
446
  *.zip
447
447
  .specstory/
448
448
  .vscode/
449
- .cursorindexingignore
449
+ `;
450
+ /**
451
+ * `.cursorindexingignore` — EMITTED as tracked project config.
452
+ *
453
+ * **Ruling, 2026-08-12, at `audit-engine`'s request (their `standards.
454
+ * gitignore-entries` check had been held since 2026-07-27 over exactly this,
455
+ * ~48 findings behind it).** The portfolio openly disagreed with itself:
456
+ * `contest-management` documents in its own `.gitignore` that the file IS
457
+ * project config and should be tracked, `cursor-project-templates` ships it as
458
+ * content, 33 of 57 non-archived org repos track it — while this scaffolder's
459
+ * 2026-07-12 fix put it in the emitted `.gitignore`, and `dashboard-engine`
460
+ * untracked theirs. Both positions were held in writing by projects that had
461
+ * thought about it, so it needed a ruling rather than 33 bug reports.
462
+ *
463
+ * **The answer is TRACKED**, and the deciding evidence is that the file has a
464
+ * real, deliberate, IDENTICAL body everywhere it exists — Templates,
465
+ * `contest-management` and `leaderboard` are byte-for-byte the same two lines,
466
+ * naming this repo's own `.specstory/` directory. That is authored project
467
+ * config in the same category as `.gitignore`, `.editorconfig` or `.nvmrc`: a
468
+ * statement about THIS repository, true for every clone and every developer.
469
+ * It is not a per-machine preference like `.vscode/`.
470
+ *
471
+ * **The gitignore position was self-defeating, which is what settles it.**
472
+ * `cursor-project-templates` ships this file as canonical content; if the
473
+ * scaffolded `.gitignore` names it, that content can never reach a clone — the
474
+ * file would be emitted, immediately made invisible to git, and its carefully
475
+ * chosen rules would silently fail to travel. A canonical file that cannot
476
+ * propagate is worse than no canonical file.
477
+ *
478
+ * **And the 2026-07-12 problem is still solved, by better means.** That fix was
479
+ * motivated by a real symptom: a freshly-scaffolded repo opening to a dirty
480
+ * tree with one mystery untracked file, which stopped a first-session agent
481
+ * (`contact-registry`). EMITTING the file fixes that at least as well as
482
+ * ignoring it did — `git status` is clean because the file is tracked and lands
483
+ * in the initial commit, not because it is hidden — and the project gains a
484
+ * useful setting instead of losing one. The premise that failed was "Cursor
485
+ * auto-creates this," which is true of the empty machine-written case and false
486
+ * of the authored one the portfolio actually has.
487
+ *
488
+ * Body is copied verbatim from the canonical file rather than paraphrased.
489
+ */
490
+ const CURSOR_INDEXING_IGNORE_TEMPLATE = `
491
+ # Don't index SpecStory auto-save files, but allow explicit context inclusion via @ references
492
+ .specstory/**
450
493
  `;
451
494
  const DIRECTIVE_TEMPLATE = `# System Architecture — {{slug}}
452
495
 
@@ -787,6 +830,17 @@ export function commonVersion() {
787
830
  export function commonCursorignore() {
788
831
  return { path: ".cursorignore", content: CURSORIGNORE_TEMPLATE };
789
832
  }
833
+ /**
834
+ * Tracked project config, NOT ignored — see CURSOR_INDEXING_IGNORE_TEMPLATE for
835
+ * the 2026-08-12 ruling and why the previous gitignore position was
836
+ * self-defeating.
837
+ */
838
+ export function commonCursorIndexingIgnore() {
839
+ return {
840
+ path: ".cursorindexingignore",
841
+ content: CURSOR_INDEXING_IGNORE_TEMPLATE.trimStart(),
842
+ };
843
+ }
790
844
  export function commonDirective(inputs, opts, spec) {
791
845
  return {
792
846
  path: "directives/system-architecture.md",
@@ -885,8 +939,9 @@ const GITIGNORE_SECRET_SCRATCH_BLOCK = `
885
939
  .tmp/
886
940
  # SpecStory chat transcripts — local only; can contain pasted secrets
887
941
  .specstory/
888
- # Cursor's own index-management file — local, auto-created; keeps git status clean
889
- .cursorindexingignore
942
+ # NOTE: \`.cursorindexingignore\` is deliberately NOT ignored — it is TRACKED
943
+ # project config, and this scaffold emits one. See the ruling in
944
+ # CURSOR_INDEXING_IGNORE_TEMPLATE's docblock.
890
945
  # Editor/extension-local settings — created unbidden, nobody's project config.
891
946
  # If a shared setting is ever genuinely wanted, force-add the ONE narrow file
892
947
  # (e.g. \`git add -f .vscode/extensions.json\`).
@@ -1036,6 +1091,7 @@ export function commonBaseFiles(inputs, opts, perTypeNarrative) {
1036
1091
  commonBackups(inputs, opts, spec),
1037
1092
  commonVersion(),
1038
1093
  commonCursorignore(),
1094
+ commonCursorIndexingIgnore(),
1039
1095
  gitignoreFor(inputs.projectType),
1040
1096
  commonDirective(inputs, opts, spec),
1041
1097
  ];
@@ -6,4 +6,4 @@ export declare function scaffoldNextjs(inputs: ScaffoldInputs, opts?: Scaffolder
6
6
  * they can assert / require the canonical SEO baseline file list without
7
7
  * hardcoding the paths in two places.
8
8
  */
9
- export declare const NEXTJS_SEO_BASELINE_PATHS: readonly ["app/layout.tsx", "app/page.tsx", "app/sitemap.ts", "app/robots.ts", "lib/seo/canonical-host.mjs", "lib/seo/page-metadata.ts", "app/opengraph-image.tsx", "lib/analytics/utm.ts", "lib/analytics/Analytics.tsx", "lib/analytics/RouteTracker.tsx", "SEO-CHECKLIST.md", ".env.example"];
9
+ export declare const NEXTJS_SEO_BASELINE_PATHS: readonly ["app/layout.tsx", "app/page.tsx", "app/sitemap.ts", "app/robots.ts", "lib/seo/canonical-host.mjs", "lib/seo/page-metadata.ts", "app/opengraph-image.tsx", "app/icon.tsx", "lib/analytics/utm.ts", "lib/analytics/Analytics.tsx", "lib/analytics/RouteTracker.tsx", "SEO-CHECKLIST.md", ".env.example"];
@@ -83,6 +83,7 @@ The components carry **no** \`"use client"\` on purpose, so a Server Component c
83
83
  - \`app/robots.ts\` — robots generator. Indexable requires BOTH a production deployment AND a real canonical domain in \`NEXT_PUBLIC_SITE_URL\`; anything else emits \`Disallow: /\`. **Both files are prerendered at build time, so changing \`NEXT_PUBLIC_SITE_URL\` needs a redeploy.**
84
84
  - \`lib/seo/canonical-host.mjs\` — the one canonical-host predicate, shared by \`app/robots.ts\` and \`next.config.mjs\` so the indexability gate and the alias redirect cannot disagree.
85
85
  - \`app/opengraph-image.tsx\` — default OG image (replace placeholder before launch).
86
+ - \`app/icon.tsx\` — the browser-tab icon, generated from the brand color + initial so the tab is never blank. Next picks it up from the filename alone. To use real artwork, drop an \`icon.png\`/\`icon.svg\` in the same folder — a static file takes precedence, so you do not delete this one.
86
87
  - \`SEO-CHECKLIST.md\` — per-page checklist; consult before adding new pages.
87
88
 
88
89
  **Before launch:** run the SEO baseline pre-launch audit from CLAUDE.md.
@@ -1821,6 +1822,56 @@ describe("card-path bot protection", () => {
1821
1822
  });
1822
1823
  });
1823
1824
  `;
1825
+ /**
1826
+ * The Postgres connection string, appended whenever `dbStrategy` is
1827
+ * `neon-postgres`.
1828
+ *
1829
+ * **This path never had it.** Reported 2026-08-11 by `commerce-engine` on the
1830
+ * first working session of a repo scaffolded the day before, with the question
1831
+ * *"regression, or a path that never had it?"* — `git log -S DATABASE_URL` on
1832
+ * this file returns exactly one commit (v0.14.0, the card-path work), so the
1833
+ * answer is the latter: the `nextjs` scaffolder has never declared its own
1834
+ * connection string. `node-service` always has; only this type was missing it.
1835
+ *
1836
+ * What made a long-standing hole finally visible is worth recording, because it
1837
+ * is the reason nobody noticed for months. Until v0.14.0, `neon-postgres` on a
1838
+ * `nextjs` scaffold emitted no code that READ the variable — the project wired
1839
+ * its own DB layer by hand and declared the var while doing it. v0.14.0's
1840
+ * durable rate limiter is the first emitted module to read it, and it FAILS
1841
+ * OPEN by design (correctly — a limiter outage must never become a payment
1842
+ * outage). So the undocumented variable does not crash the project: it takes
1843
+ * payments with `durable: false` on every request, forever, which the module's
1844
+ * own comment calls "the right behaviour for an outage and the wrong state to
1845
+ * ship in deliberately." Leaving the var undeclared made shipping that state
1846
+ * the DEFAULT.
1847
+ *
1848
+ * Note the shape, which generalises past this variable: **a fail-open
1849
+ * dependency plus an undocumented config key is silent by construction.** Every
1850
+ * signal — build, typecheck, tests, the running app — reports success.
1851
+ *
1852
+ * The three caveats are `commerce-engine`'s own text, offered on the thread and
1853
+ * lifted with thanks; each is a mistake a first-timer makes exactly once.
1854
+ */
1855
+ const NEON_DB_ENV_BLOCK = `
1856
+ # ── Database (Neon Postgres) ─────────────────────────────────────────────────
1857
+ # Connection string for this project's Postgres database.
1858
+ # Create/copy from: https://console.neon.tech/ → your project → Connection Details
1859
+ #
1860
+ # Use the POOLED connection string (the host contains \`-pooler\`). A serverless
1861
+ # app opens a connection per invocation; the direct endpoint runs out.
1862
+ #
1863
+ # Run migrations and seeds as the OWNER role, but connect the APP as a role that
1864
+ # does NOT bypass RLS. \`neondb_owner\` — the role the Neon console hands you —
1865
+ # has \`rolbypassrls = true\`, and BYPASSRLS is evaluated BEFORE any policy is
1866
+ # consulted, so every policy you wrote becomes dead code while
1867
+ # \`pg_tables.rowsecurity\` still reads \`true\`. Check with:
1868
+ # SELECT rolname, rolbypassrls FROM pg_roles WHERE rolname = current_user;
1869
+ #
1870
+ # \`/api/health\` must never touch the database (per [[neon-postgres]] — routine
1871
+ # probes burn the Free tier's 100 CU-hour quota and defeat scale-to-zero). The
1872
+ # scaffolded health route is DB-free; keep it that way.
1873
+ DATABASE_URL=postgresql://user:pass@host-pooler.region.aws.neon.tech/dbname?sslmode=require
1874
+ `;
1824
1875
  const CARD_PATH_ENV_BLOCK = `
1825
1876
  # --- Card-path bot protection (Cloudflare Turnstile) -------------------------
1826
1877
  # Create a widget: https://dash.cloudflare.com/?to=/:account/turnstile
@@ -2691,6 +2742,85 @@ export default function OpengraphImage() {
2691
2742
  );
2692
2743
  }
2693
2744
  `;
2745
+ /**
2746
+ * The browser-tab icon, generated rather than sourced.
2747
+ *
2748
+ * Emitted because NOTHING CATCHES ITS ABSENCE. `next build`, `tsc --noEmit`,
2749
+ * lint and a full test suite are all green with no favicon; the only symptom is
2750
+ * a blank browser tab, which nobody files a bug about. `project-creator` — a
2751
+ * scaffold of this CLI — went through a production launch, four verification
2752
+ * sessions and an SEO pre-launch audit with a blank tab, until Kerry looked at
2753
+ * the tab himself (2026-08-09: *"any user-facing page should have a favicon if
2754
+ * that file or a usable logo file exists"*). Same shape as the OG-image checks
2755
+ * already in the baseline: an asset only a human looking at a rendered surface
2756
+ * will miss.
2757
+ *
2758
+ * Same technique as `app/opengraph-image.tsx` — `ImageResponse` with no source
2759
+ * asset — so **"we have no logo yet" is not a reason to defer it**, which is
2760
+ * precisely the reasoning that left every scaffold with a blank tab.
2761
+ *
2762
+ * Real artwork later needs no code change: an `icon.png` / `icon.svg` in the
2763
+ * same folder TAKES PRECEDENCE over `icon.tsx`, so the generated mark is a
2764
+ * floor rather than something to undo.
2765
+ *
2766
+ * The initial is derived in the emitted code rather than substituted at
2767
+ * scaffold time so it stays correct when the project renames its brand — and a
2768
+ * single glyph is deliberate: a three-letter wordmark is mush at 32px.
2769
+ */
2770
+ const APP_ICON_TEMPLATE = `// Browser-tab icon (favicon). Next.js picks this up from the FILENAME alone
2771
+ // and emits <link rel="icon"> — no app/layout.tsx change is needed.
2772
+ //
2773
+ // This is a generated placeholder, not a design: brand primary as the field,
2774
+ // the brand's first initial in white. It exists so the tab is never blank.
2775
+ //
2776
+ // To replace it with real artwork, drop an \`icon.png\` or \`icon.svg\` into this
2777
+ // same folder. A static icon file TAKES PRECEDENCE over this route, so you do
2778
+ // NOT need to delete this file first.
2779
+
2780
+ import { ImageResponse } from "next/og";
2781
+
2782
+ // NO \`runtime = "edge"\` here, deliberately — copying it from
2783
+ // app/opengraph-image.tsx is the obvious move and it is the wrong one.
2784
+ // Measured on a real build: with edge, \`next build\` warns "Using edge runtime
2785
+ // on a page currently disables static generation for that page" and /icon is
2786
+ // listed \`ƒ (Dynamic) server-rendered on demand\`. Without it, /icon is
2787
+ // \`○ (Static)\` and the PNG is prerendered to .next/server/app/icon.body at
2788
+ // build time — byte-identical output, no function invocation per request.
2789
+ // A favicon is fetched on essentially every cold page load, so this is the
2790
+ // difference between a CDN hit and an invocation. It also agrees with the
2791
+ // portable-stack standard this same scaffold emits: Node runtime over Edge
2792
+ // unless Edge is actually required.
2793
+ export const size = { width: 32, height: 32 };
2794
+ export const contentType = "image/png";
2795
+
2796
+ // Derived here rather than baked in at scaffold time so a brand rename stays
2797
+ // correct. One glyph on purpose — a wordmark is unreadable at 32px.
2798
+ const INITIAL = "{{brand_name}}".trim().charAt(0).toUpperCase();
2799
+
2800
+ export default function Icon() {
2801
+ return new ImageResponse(
2802
+ (
2803
+ <div
2804
+ style={{
2805
+ fontSize: 22,
2806
+ background: "{{primary_color}}",
2807
+ color: "#ffffff",
2808
+ width: "100%",
2809
+ height: "100%",
2810
+ display: "flex",
2811
+ alignItems: "center",
2812
+ justifyContent: "center",
2813
+ fontFamily: "system-ui, sans-serif",
2814
+ fontWeight: 700,
2815
+ }}
2816
+ >
2817
+ {INITIAL}
2818
+ </div>
2819
+ ),
2820
+ { ...size },
2821
+ );
2822
+ }
2823
+ `;
2694
2824
  const SEO_CHECKLIST_TEMPLATE = `# SEO Checklist — {{slug}}
2695
2825
 
2696
2826
  Per Z2W standing org requirement 2026-05-30. Run before adding a new page AND before launch.
@@ -2717,6 +2847,7 @@ Per Z2W standing org requirement 2026-05-30. Run before adding a new page AND be
2717
2847
  - [ ] Exactly one \`<h1>\` per page; heading hierarchy logical
2718
2848
  - [ ] Canonical URL set on every page
2719
2849
  - [ ] OG + Twitter Card tags present; OG image resolves
2850
+ - [ ] **Browser tab shows an icon.** \`app/icon.tsx\` ships a generated placeholder, so this should already pass — check it anyway, because nothing automated can: build, typecheck, lint and tests are all green with a blank tab. Verify against the SERVED page, not the source: \`curl -s <url> | grep -o '<link rel="icon"[^>]*>'\` then open that href and confirm it returns an image
2720
2851
  - [ ] Meaningful images have descriptive alt text; decorative images have \`alt=""\`
2721
2852
  - [ ] JSON-LD present where warranted; validates in Google Rich Results test
2722
2853
  - [ ] \`sitemap.xml\` generates correctly; \`robots.txt\` references it
@@ -2835,6 +2966,13 @@ export function scaffoldNextjs(inputs, opts) {
2835
2966
  if (durableLimit)
2836
2967
  packageJson = withExtraDeps(packageJson, NEON_DRIVER_DEP);
2837
2968
  let envExample = sub(ENV_EXAMPLE_TEMPLATE, inputs, opts, spec);
2969
+ // Gated on the DB STRATEGY, not on `durableLimit` — the variable belongs to
2970
+ // the project's database, not to the one emitted module that happens to read
2971
+ // it today. Gating it on the limiter would re-open the same hole for the next
2972
+ // emitted module, and would leave a `neon-postgres` project that takes no
2973
+ // cards with an undeclared connection string.
2974
+ if (inputs.dbStrategy === "neon-postgres")
2975
+ envExample += NEON_DB_ENV_BLOCK;
2838
2976
  if (sendsEmail)
2839
2977
  envExample += EMAIL_ENV_BLOCK;
2840
2978
  // The host allowlist serves auth email (magic links derive URLs from the Host)
@@ -2899,6 +3037,7 @@ export function scaffoldNextjs(inputs, opts) {
2899
3037
  path: "app/opengraph-image.tsx",
2900
3038
  content: sub(APP_OG_IMAGE_TEMPLATE, inputs, opts, spec),
2901
3039
  },
3040
+ { path: "app/icon.tsx", content: sub(APP_ICON_TEMPLATE, inputs, opts, spec) },
2902
3041
  {
2903
3042
  path: "SEO-CHECKLIST.md",
2904
3043
  content: sub(SEO_CHECKLIST_TEMPLATE, inputs, opts, spec),
@@ -2966,6 +3105,11 @@ export const NEXTJS_SEO_BASELINE_PATHS = [
2966
3105
  // and downgrades the Twitter card.
2967
3106
  "lib/seo/page-metadata.ts",
2968
3107
  "app/opengraph-image.tsx",
3108
+ // The browser-tab icon. In this list because its absence is invisible to
3109
+ // every automated signal — build, typecheck, lint and tests are all green
3110
+ // with a blank tab — so a path-list assertion is the only thing that can
3111
+ // notice it going missing.
3112
+ "app/icon.tsx",
2969
3113
  // Fathom (SEO baseline item 7) — the three-file pattern; the loader alone
2970
3114
  // (data-auto="false" with no RouteTracker) records zero pageviews.
2971
3115
  "lib/analytics/utm.ts",
@@ -41,6 +41,19 @@ export declare function upperSnakeFromSlug(slug: string): string;
41
41
  * map to the WP AGENTS line; everything else to the generic line.
42
42
  */
43
43
  export declare function frameworkVersionForType(projectType: ProjectType): string;
44
+ /**
45
+ * A single uppercase glyph for the generated favicon in static scaffolds
46
+ * (`cf-pages`), where there is no runtime to derive one.
47
+ *
48
+ * ONE letter is deliberate — a three-letter wordmark is mush at 32px.
49
+ *
50
+ * Restricted to `[A-Za-z0-9]` because the value is interpolated into SVG
51
+ * markup: a brand whose name opens with `&` or `<` would otherwise emit an
52
+ * XML-malformed icon, and a broken favicon fails exactly as silently as an
53
+ * absent one. The `slug` fallback cannot itself fail — slugs are validated
54
+ * against `^[a-z][a-z0-9-]{2,49}$`, so character 0 is always a letter.
55
+ */
56
+ export declare function brandInitial(brandName: string, slug: string): string;
44
57
  /**
45
58
  * Build the placeholder → value map for a set of inputs. Exposed (not just
46
59
  * used internally by applySubstitutions) so callers can inspect or extend
@@ -68,6 +68,22 @@ function resolveBrandSpec(inputs, opts) {
68
68
  return opts.brandSpec;
69
69
  return getBrandSpec(inputs.brand, inputs.customBrand, inputs.githubOrg);
70
70
  }
71
+ /**
72
+ * A single uppercase glyph for the generated favicon in static scaffolds
73
+ * (`cf-pages`), where there is no runtime to derive one.
74
+ *
75
+ * ONE letter is deliberate — a three-letter wordmark is mush at 32px.
76
+ *
77
+ * Restricted to `[A-Za-z0-9]` because the value is interpolated into SVG
78
+ * markup: a brand whose name opens with `&` or `<` would otherwise emit an
79
+ * XML-malformed icon, and a broken favicon fails exactly as silently as an
80
+ * absent one. The `slug` fallback cannot itself fail — slugs are validated
81
+ * against `^[a-z][a-z0-9-]{2,49}$`, so character 0 is always a letter.
82
+ */
83
+ export function brandInitial(brandName, slug) {
84
+ const fromBrand = /[A-Za-z0-9]/.exec(brandName);
85
+ return (fromBrand ? fromBrand[0] : slug.charAt(0)).toUpperCase();
86
+ }
71
87
  /**
72
88
  * Build the placeholder → value map for a set of inputs. Exposed (not just
73
89
  * used internally by applySubstitutions) so callers can inspect or extend
@@ -84,6 +100,7 @@ export function buildSubstitutionMap(inputs, opts = {}) {
84
100
  description: inputs.description,
85
101
  brand_name: spec.brandName,
86
102
  brand_name_rule: spec.brandNameRule,
103
+ brand_initial: brandInitial(spec.brandName, inputs.slug),
87
104
  primary_color: spec.primaryColor,
88
105
  accent_color: spec.accentColor,
89
106
  author: spec.author,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero2webmaster/starter-kit",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
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
+ }