@zero2webmaster/starter-kit 0.32.1 → 0.36.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.32.1 | **Framework:** 2.19.0
3
+ **Version:** 0.36.0 | **Framework:** 2.19.0
4
4
 
5
5
  > Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
6
6
 
@@ -135,4 +135,4 @@ Inquiries: kerry@zero2webmaster.com.
135
135
  ---
136
136
 
137
137
  *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.*
138
- *Version: 0.32.1 | Last Updated: 2026-09-19*
138
+ *Version: 0.36.0 | Last Updated: 2026-09-22*
@@ -59,6 +59,18 @@ export interface ProjectDescriptor {
59
59
  slug: string;
60
60
  description: string;
61
61
  projectType: ProjectType;
62
+ /**
63
+ * Present and `true` only on a descriptor REVERSE-ENGINEERED from an existing
64
+ * repo by `scripts/check-descriptor.mjs --write`, rather than emitted here at
65
+ * scaffold time from authoritative inputs. Absent on a scaffolded descriptor.
66
+ *
67
+ * It exists because the two are otherwise indistinguishable, and they do not
68
+ * deserve the same confidence: a scaffolded descriptor's `projectType` and
69
+ * `dbStrategy` were STATED by the person creating the project, whereas a
70
+ * backfilled one's were INFERRED from files. A consumer deciding whether to
71
+ * run a `remote-write` task unattended should be able to see the difference.
72
+ */
73
+ backfilled?: boolean;
62
74
  /** Who produced this file, and when. Both are needed to judge staleness. */
63
75
  generatedBy: string;
64
76
  generatedOn: string;
@@ -88,6 +100,19 @@ export interface ProjectDescriptor {
88
100
  taskSource: TaskSource;
89
101
  tasks: Partial<Record<TaskVerb, ProjectTask>>;
90
102
  }
103
+ /**
104
+ * Map the npm scripts a scaffold actually emitted onto the closed vocabulary.
105
+ *
106
+ * The left side of each pair is the VERB; the right side is the list of script
107
+ * names that legitimately implement it, most-preferred first. A verb with no
108
+ * matching script yields NO task — see design rule 3.
109
+ *
110
+ * `db:push` implements `migrate` because it is the command that APPLIES schema
111
+ * to a database. `db:generate` deliberately maps to nothing: it writes migration
112
+ * files locally and is a different act with a different safety class, and a
113
+ * closed vocabulary drops what does not fit rather than bending a verb to cover it.
114
+ */
115
+ export declare const NPM_SCRIPT_FOR_VERB: Readonly<Record<TaskVerb, readonly string[]>>;
91
116
  /**
92
117
  * Compose the descriptor for a completed scaffold.
93
118
  *
@@ -110,7 +110,7 @@ function task(verb, command) {
110
110
  * files locally and is a different act with a different safety class, and a
111
111
  * closed vocabulary drops what does not fit rather than bending a verb to cover it.
112
112
  */
113
- const NPM_SCRIPT_FOR_VERB = {
113
+ export const NPM_SCRIPT_FOR_VERB = {
114
114
  dev: ["dev"],
115
115
  build: ["build"],
116
116
  test: ["test"],
@@ -13,6 +13,30 @@ export declare function withPwaWiring(layout: string): string;
13
13
  * restating four paths per assertion — same job as NEXTJS_SEO_BASELINE_PATHS.
14
14
  */
15
15
  export declare const NEXTJS_PWA_PATHS: readonly ["public/manifest.json", "public/icon.svg", "public/sw.js", "components/ServiceWorker.tsx"];
16
+ /**
17
+ * Vercel's Ignored Build Step, committed in-repo so it is reviewable and
18
+ * survives a re-import (a dashboard setting is neither). Filed by
19
+ * `audit-engine` 2026-09-22: across 19 Z2W Vercel projects, 35.6% of commits to
20
+ * `main` changed no application code, and build CPU was 71% of the bill.
21
+ *
22
+ * 🔴 Vercel's exit codes are INVERTED — `0` SKIPS the build, anything else
23
+ * builds. Every branch below that is not "provably prose-only" exits 1, so a
24
+ * wrong rule costs a build and never a deploy:
25
+ *
26
+ * - The base is `VERCEL_GIT_PREVIOUS_SHA`, the last SUCCESSFUL deploy — never
27
+ * `HEAD^`, which sees only the last commit of a push. A code commit followed
28
+ * by a docs commit, pushed together (every Z2W session end), would otherwise
29
+ * skip the code. A canceled deploy is not "successful", so skipped pushes
30
+ * accumulate against the same base until one real change builds them all.
31
+ * - An EMPTY base BUILDS. `audit-engine`'s dashboard rule falls back to
32
+ * `HEAD^` there, which is fine for a long-deployed `main` but wrong for a new
33
+ * scaffold: a repo with history is linked to Vercel later, and its first
34
+ * deploy must not be skipped because the newest commit was a STATUS.md edit.
35
+ * - A base missing from Vercel's shallow clone fails `cat-file` → builds.
36
+ *
37
+ * Must stay ≤ 256 characters (the vercel.json schema's `maxLength`).
38
+ */
39
+ export declare const VERCEL_IGNORE_COMMAND: string;
16
40
  export declare function scaffoldNextjs(inputs: ScaffoldInputs, opts?: ScaffolderOptions): ScaffoldFile[];
17
41
  /**
18
42
  * Exported for tests + the eventual standards-conflict resolver in Step 5 so
@@ -2994,7 +2994,7 @@ import {
2994
2994
  type ContrastRole,
2995
2995
  } from "../lib/a11y/contrast";
2996
2996
 
2997
- // NOT \\\`__dirname\\\` — this package is "type": "module", where it is undefined.
2997
+ // NOT \`__dirname\` — this package is "type": "module", where it is undefined.
2998
2998
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
2999
2999
  const CSS_RAW = readFileSync(join(ROOT, "app/globals.css"), "utf8");
3000
3000
 
@@ -5356,6 +5356,126 @@ function withExtraDevDeps(pkgJson, extra) {
5356
5356
  obj.devDependencies = { ...obj.devDependencies, ...extra };
5357
5357
  return JSON.stringify(obj, null, 2) + "\n";
5358
5358
  }
5359
+ /**
5360
+ * Vercel's Ignored Build Step, committed in-repo so it is reviewable and
5361
+ * survives a re-import (a dashboard setting is neither). Filed by
5362
+ * `audit-engine` 2026-09-22: across 19 Z2W Vercel projects, 35.6% of commits to
5363
+ * `main` changed no application code, and build CPU was 71% of the bill.
5364
+ *
5365
+ * 🔴 Vercel's exit codes are INVERTED — `0` SKIPS the build, anything else
5366
+ * builds. Every branch below that is not "provably prose-only" exits 1, so a
5367
+ * wrong rule costs a build and never a deploy:
5368
+ *
5369
+ * - The base is `VERCEL_GIT_PREVIOUS_SHA`, the last SUCCESSFUL deploy — never
5370
+ * `HEAD^`, which sees only the last commit of a push. A code commit followed
5371
+ * by a docs commit, pushed together (every Z2W session end), would otherwise
5372
+ * skip the code. A canceled deploy is not "successful", so skipped pushes
5373
+ * accumulate against the same base until one real change builds them all.
5374
+ * - An EMPTY base BUILDS. `audit-engine`'s dashboard rule falls back to
5375
+ * `HEAD^` there, which is fine for a long-deployed `main` but wrong for a new
5376
+ * scaffold: a repo with history is linked to Vercel later, and its first
5377
+ * deploy must not be skipped because the newest commit was a STATUS.md edit.
5378
+ * - A base missing from Vercel's shallow clone fails `cat-file` → builds.
5379
+ *
5380
+ * Must stay ≤ 256 characters (the vercel.json schema's `maxLength`).
5381
+ */
5382
+ export const VERCEL_IGNORE_COMMAND = [
5383
+ 'B="$VERCEL_GIT_PREVIOUS_SHA"',
5384
+ '[ -n "$B" ] || exit 1',
5385
+ 'git cat-file -e "$B^{commit}" 2>/dev/null || exit 1',
5386
+ `git diff --quiet "$B" HEAD -- . ':(exclude)*.md' ':(exclude)docs/' ':(exclude)drafts/' || exit 1`,
5387
+ "exit 0",
5388
+ ].join("; ");
5389
+ const VERCEL_JSON = JSON.stringify({ $schema: "https://openapi.vercel.sh/vercel.json", ignoreCommand: VERCEL_IGNORE_COMMAND }, null, 2) + "\n";
5390
+ // The consumer-side guard. The one way the rule above loses a real deploy is a
5391
+ // project that later starts building pages FROM Markdown — so the check has to
5392
+ // live in the project, where that change happens, not in this CLI.
5393
+ const VERCEL_IGNORE_TEST_TEMPLATE = `/**
5394
+ * vercel.json carries an Ignored Build Step: a push that changes nothing but
5395
+ * Markdown (STATUS.md, HANDOFF.md, CHANGELOG.md, ...) does NOT rebuild the site.
5396
+ * Measured 2026-09-22 across 19 Zero2Webmaster Vercel projects: 35.6% of commits
5397
+ * to main changed no application code, and build CPU was 71% of the Vercel bill.
5398
+ *
5399
+ * Vercel's exit codes are INVERTED: exit 0 SKIPS the build, anything else builds.
5400
+ * Every failure path in the rule exits 1, so a broken rule costs a build, never
5401
+ * a deploy. The diff base is VERCEL_GIT_PREVIOUS_SHA (the last SUCCESSFUL
5402
+ * deploy), never HEAD^ — HEAD^ sees only the last commit of a push, so a code
5403
+ * commit and a docs commit pushed together would skip the code.
5404
+ *
5405
+ * THE ONE WAY THIS RULE LOSES A REAL DEPLOY: this project starts building pages
5406
+ * FROM Markdown. A content edit then changes only *.md files, and never ships.
5407
+ * The last test below fails the moment that becomes possible. When it does,
5408
+ * remove ':(exclude)*.md' from vercel.json — or delete the ignoreCommand.
5409
+ */
5410
+ import { describe, it, expect } from "vitest";
5411
+ import { readFileSync, readdirSync, existsSync } from "node:fs";
5412
+ import { join, dirname } from "node:path";
5413
+ import { fileURLToPath } from "node:url";
5414
+
5415
+ // NOT \`__dirname\` — this package is "type": "module", where it is undefined.
5416
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
5417
+
5418
+ const TOOLCHAIN_EXACT = [
5419
+ "@next/mdx",
5420
+ "next-mdx-remote",
5421
+ "gray-matter",
5422
+ "velite",
5423
+ "markdown-it",
5424
+ "marked",
5425
+ "react-markdown",
5426
+ ];
5427
+ const TOOLCHAIN_PREFIX = ["@mdx-js/", "contentlayer", "fumadocs", "remark", "rehype"];
5428
+
5429
+ function isMarkdownToolchain(name: string): boolean {
5430
+ return TOOLCHAIN_EXACT.includes(name) || TOOLCHAIN_PREFIX.some((p) => name.startsWith(p));
5431
+ }
5432
+
5433
+ function markdownUnder(dir: string): string[] {
5434
+ const abs = join(ROOT, dir);
5435
+ if (!existsSync(abs)) return [];
5436
+ const out: string[] = [];
5437
+ for (const e of readdirSync(abs, { withFileTypes: true })) {
5438
+ if (e.name === "node_modules" || e.name.startsWith(".")) continue;
5439
+ const rel = join(dir, e.name);
5440
+ if (e.isDirectory()) out.push(...markdownUnder(rel));
5441
+ else if (e.name.endsWith(".md")) out.push(rel);
5442
+ }
5443
+ return out;
5444
+ }
5445
+
5446
+ const vercelPath = join(ROOT, "vercel.json");
5447
+ const rule: string = existsSync(vercelPath)
5448
+ ? (JSON.parse(readFileSync(vercelPath, "utf8")).ignoreCommand ?? "")
5449
+ : "";
5450
+
5451
+ describe("vercel.json Ignored Build Step", () => {
5452
+ it("fits the 256-character limit in Vercel's vercel.json schema", () => {
5453
+ expect(rule.length).toBeLessThanOrEqual(256);
5454
+ });
5455
+
5456
+ it("diffs against the last successful deploy, never against HEAD^", () => {
5457
+ if (!rule) return; // no rule at all is a sanctioned choice
5458
+ expect(rule).toContain("VERCEL_GIT_PREVIOUS_SHA");
5459
+ expect(rule).not.toContain("HEAD^");
5460
+ });
5461
+
5462
+ it("does not skip Markdown-only pushes in a project that builds pages from Markdown", () => {
5463
+ if (!rule.includes("*.md")) return;
5464
+ const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
5465
+ const deps = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies });
5466
+ const found = [
5467
+ ...deps.filter(isMarkdownToolchain),
5468
+ ...["app", "content", "posts"].flatMap(markdownUnder),
5469
+ ];
5470
+ expect(
5471
+ found,
5472
+ "This project can now build pages from Markdown, but vercel.json skips builds " +
5473
+ "when only *.md files change — so a content edit would never deploy. " +
5474
+ "Remove ':(exclude)*.md' from the ignoreCommand in vercel.json.",
5475
+ ).toEqual([]);
5476
+ });
5477
+ });
5478
+ `;
5359
5479
  export function scaffoldNextjs(inputs, opts) {
5360
5480
  const spec = resolveBrandSpec(inputs);
5361
5481
  const base = commonBaseFiles(inputs, opts, NARRATIVE);
@@ -5440,6 +5560,10 @@ export function scaffoldNextjs(inputs, opts) {
5440
5560
  },
5441
5561
  { path: "tsconfig.json", content: sub(TSCONFIG_TEMPLATE, inputs, opts, spec) },
5442
5562
  { path: "vitest.config.ts", content: VITEST_CONFIG_TEMPLATE },
5563
+ // Skip Vercel builds for prose-only pushes; the test guards the one case
5564
+ // where that would lose a deploy (a project that builds pages from Markdown).
5565
+ { path: "vercel.json", content: VERCEL_JSON },
5566
+ { path: "test/vercel-ignore.test.ts", content: VERCEL_IGNORE_TEST_TEMPLATE },
5443
5567
  { path: "test/server-only.stub.ts", content: SERVER_ONLY_STUB_TEMPLATE },
5444
5568
  { path: "app/globals.css", content: globalsCss(spec.primaryColor) },
5445
5569
  { path: "components/FormBits.tsx", content: sub(FORM_BITS_TEMPLATE, inputs, opts, spec) },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero2webmaster/starter-kit",
3
- "version": "0.32.1",
3
+ "version": "0.36.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",
@@ -26,6 +26,7 @@
26
26
  "dist/**/*.d.ts",
27
27
  "scripts/rollup-integrations.mjs",
28
28
  "scripts/check-descriptor.mjs",
29
+ "scripts/check-conformance.mjs",
29
30
  "README.md",
30
31
  "LICENSE"
31
32
  ],
@@ -0,0 +1,332 @@
1
+ #!/usr/bin/env node
2
+ //
3
+ // Check a repo against the Z2W PROJECT STANDARD — the files every scaffolded
4
+ // project is given, whoever built it and whenever.
5
+ //
6
+ // node scripts/check-conformance.mjs <project-dir> [<project-dir> …]
7
+ // node scripts/check-conformance.mjs --strict <project-dir> # non-zero on any gap
8
+ // node scripts/check-conformance.mjs --denominator # print the standard, examine nothing
9
+ //
10
+ // WHY THIS EXISTS, and it is a routing answer as much as a tool.
11
+ //
12
+ // Three projects have now asked, in three weeks, for the same thing in three
13
+ // different words: `ebooks` ("this repo was never scaffolded — the standard is
14
+ // N things, which ones have I never heard of?"), `audit-engine` ("who audits
15
+ // the auditor? a self-audit can only measure against a standard the auditor
16
+ // already holds"), and Kerry ("ensure you have everything we expect our
17
+ // projects to have, such as roadmap, status, handoff files etc."). The third
18
+ // request for one dimension is the signal that it should be a tool rather than
19
+ // a session — a hand-run audit answers one repo once, and the next asker
20
+ // re-derives it from somebody's memory of the standard.
21
+ //
22
+ // 🔴 THE DENOMINATOR IS DERIVED FROM THE EMITTER, NOT WRITTEN DOWN HERE.
23
+ // A hand-maintained list of "the standard files" is a second copy of a fact the
24
+ // scaffolder already holds, and this repo has measured what happens to those:
25
+ // `--version` reported `0.6.0` for twenty-five published releases because a
26
+ // constant nobody bumped stayed perfectly self-consistent. So the standard is
27
+ // computed, every run, as the INTERSECTION of what `scaffoldByType()` emits for
28
+ // all eight project types. A file is part of the standard if and only if every
29
+ // kind of Z2W project is given it. Change the scaffolder and this check changes
30
+ // with it, in the same commit, with nothing to remember.
31
+ //
32
+ // WHAT IT DELIBERATELY DOES NOT DO.
33
+ //
34
+ // · It never compares CONTENT. Every mature project has rewritten its README;
35
+ // that is the project working, not drifting. Presence is the only claim a
36
+ // structural standard can honestly make.
37
+ // · It never grades. "You are missing 3 of 16" is a measurement; "you fail"
38
+ // is a judgement that belongs to the project, which may have a reason. Some
39
+ // of these files are recent additions the standard gained after a repo was
40
+ // built, and this check cannot know that.
41
+ // · It reports TYPE-SPECIFIC expectations separately and advisorily, because
42
+ // a mature repo legitimately restructures its own source tree.
43
+ //
44
+ // WHAT IT REFUSES TO DO. It will not report a pass over a directory it could
45
+ // not read, and it exits 2 rather than printing a clean sweep when it examined
46
+ // nothing. `PRESENT` / `MISSING` / `UNREADABLE` / `SKIPPED` are four distinct
47
+ // outcomes and none of them is silence. It also fails closed on an unrecognised
48
+ // flag: a check that can be AIMED must never be silently misaimed, or it
49
+ // examines the wrong thing thoroughly and reports a green pass for somewhere
50
+ // else. [[zero-is-not-a-pass]]
51
+ //
52
+ import { existsSync, readFileSync, statSync } from "node:fs";
53
+ import { join, resolve, basename } from "node:path";
54
+
55
+ const KNOWN_FLAGS = ["--strict", "--denominator", "--json", "--help"];
56
+
57
+ const argv = process.argv.slice(2);
58
+ const unknown = argv.filter((a) => a.startsWith("--") && !KNOWN_FLAGS.includes(a.split("=")[0]));
59
+ if (unknown.length) {
60
+ console.error(
61
+ `❌ Unrecognised flag(s): ${unknown.join(", ")}\n` +
62
+ ` Known: ${KNOWN_FLAGS.join(", ")}\n` +
63
+ ` Refusing to run. An ignored flag would silently change what this examines\n` +
64
+ ` and report a confident result about the wrong thing.`,
65
+ );
66
+ process.exit(1);
67
+ }
68
+
69
+ const args = {
70
+ strict: argv.includes("--strict"),
71
+ denominatorOnly: argv.includes("--denominator"),
72
+ json: argv.includes("--json"),
73
+ };
74
+ const targets = argv.filter((a) => !a.startsWith("--"));
75
+
76
+ if (argv.includes("--help")) {
77
+ console.log(readFileSync(new URL(import.meta.url), "utf8").split("\n").slice(1)
78
+ .filter((l) => l.startsWith("//")).map((l) => l.replace(/^\/\/ ?/, "")).join("\n"));
79
+ process.exit(0);
80
+ }
81
+
82
+ // ── The standard, DERIVED ────────────────────────────────────────────────────
83
+
84
+ const { scaffoldByType, PROJECT_TYPES } = await import("../dist/index.js");
85
+
86
+ /** Probe inputs for one project type. Neutral on every optional axis, so the
87
+ * emitted set is the floor for that type rather than one configuration of it. */
88
+ function probeInputs(projectType, over = {}) {
89
+ return {
90
+ // The slug is a PARAMETER, not a constant, because several scaffolders put
91
+ // it inside the paths they emit (`src/<slug>/main.py`). Probing with a
92
+ // throwaway slug reports `src/conformance-probe/main.py` as absent from
93
+ // every repo on earth — a finding that is 100% false positive and trains
94
+ // the reader to skip the whole type-specific section. Callers pass the
95
+ // repo's REAL slug so the derived paths are the ones that repo would have.
96
+ slug: "conformance-probe",
97
+ description: "A throwaway project used to derive the project standard.",
98
+ projectType,
99
+ brand: "zero2webmaster",
100
+ githubOrg: "zero2webmaster",
101
+ targetPath: "/tmp/conformance-probe",
102
+ dbStrategy: "none",
103
+ hasWebUi: false,
104
+ hasCron: false,
105
+ participateInBulletin: true,
106
+ ...over,
107
+ };
108
+ }
109
+
110
+ function emittedPaths(projectType, over = {}) {
111
+ return new Set(
112
+ scaffoldByType(probeInputs(projectType, over), {
113
+ date: new Date().toISOString().slice(0, 10),
114
+ frameworkVersion: "0.0.0",
115
+ }).map((f) => f.path),
116
+ );
117
+ }
118
+
119
+ /** THE STANDARD: paths every project type is given. Intersection, not a list. */
120
+ function deriveUniversal() {
121
+ let universal = null;
122
+ for (const t of PROJECT_TYPES) {
123
+ const set = emittedPaths(t);
124
+ universal = universal === null ? set : new Set([...universal].filter((p) => set.has(p)));
125
+ }
126
+ // A guard against the vacuous denominator: an empty standard would pass every
127
+ // repo on earth, and an empty PROJECT_TYPES would produce one silently.
128
+ if (!universal || universal.size === 0) {
129
+ console.error(
130
+ "❌ Derived an EMPTY project standard from the scaffolder. Refusing to run:\n" +
131
+ " an empty standard reports every repo as fully conformant, which is the\n" +
132
+ " exact false pass this check exists to prevent.",
133
+ );
134
+ process.exit(2);
135
+ }
136
+ return [...universal].sort();
137
+ }
138
+
139
+ /** Paths emitted for THIS project's declared shape, beyond the universal set. */
140
+ function deriveTypeSpecific(descriptor, slug) {
141
+ const t = descriptor?.projectType;
142
+ if (!t || !PROJECT_TYPES.includes(t)) return null; // cannot evaluate — not a guess
143
+ const over = {};
144
+ // A slug the scaffolder will accept. Python packages cannot hold a hyphen, and
145
+ // an invalid slug would throw and silently cost the whole type-specific half.
146
+ if (/^[a-z][a-z0-9-]{2,49}$/.test(slug)) over.slug = slug;
147
+ if (descriptor?.stack?.hasWebUi === true) over.hasWebUi = true;
148
+ if (descriptor?.stack?.hasCron === true) over.hasCron = true;
149
+ if (descriptor?.stack?.database && descriptor.stack.database !== "unknown"
150
+ && descriptor.stack.database !== "none") {
151
+ over.dbStrategy = descriptor.stack.database;
152
+ }
153
+ if (descriptor?.coordination?.participates === false) over.participateInBulletin = false;
154
+ let set;
155
+ try {
156
+ set = emittedPaths(t, over);
157
+ } catch {
158
+ set = emittedPaths(t); // an unsupported dbStrategy must not abort the whole run
159
+ }
160
+ return { paths: [...set].sort(), applied: over };
161
+ }
162
+
163
+ const UNIVERSAL = deriveUniversal();
164
+
165
+ if (args.denominatorOnly) {
166
+ console.log(`The Z2W project standard is ${UNIVERSAL.length} files — every path emitted by`);
167
+ console.log(`ALL ${PROJECT_TYPES.length} project types (${PROJECT_TYPES.join(", ")}).`);
168
+ console.log(`Derived from this repo's own scaffolder at run time, never from a list.\n`);
169
+ for (const p of UNIVERSAL) console.log(` ${p}`);
170
+ process.exit(0);
171
+ }
172
+
173
+ if (targets.length === 0) {
174
+ console.error(
175
+ "❌ No project directory given, so nothing was examined.\n" +
176
+ " Usage: node scripts/check-conformance.mjs <project-dir> [<project-dir> …]\n" +
177
+ " Run with --denominator to print the standard without examining anything.",
178
+ );
179
+ process.exit(2);
180
+ }
181
+
182
+ // ── Examine ──────────────────────────────────────────────────────────────────
183
+
184
+ const results = [];
185
+
186
+ for (const raw of targets) {
187
+ const dir = resolve(raw);
188
+ const name = basename(dir);
189
+
190
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) {
191
+ results.push({ name, dir, outcome: "UNREADABLE", reason: "not a directory that exists" });
192
+ continue;
193
+ }
194
+ // A repo is the unit. A directory that is not one is SKIPPED with a reason,
195
+ // never counted as a clean pass.
196
+ if (!existsSync(join(dir, ".git"))) {
197
+ results.push({ name, dir, outcome: "SKIPPED", reason: "no .git — not a project repo" });
198
+ continue;
199
+ }
200
+
201
+ let descriptor = null;
202
+ let descriptorState = "absent";
203
+ const descPath = join(dir, "z2w-project.json");
204
+ if (existsSync(descPath)) {
205
+ try {
206
+ descriptor = JSON.parse(readFileSync(descPath, "utf8"));
207
+ descriptorState = descriptor?.backfilled === true ? "backfilled" : "declared";
208
+ } catch {
209
+ descriptorState = "unparseable";
210
+ }
211
+ }
212
+
213
+ const missing = UNIVERSAL.filter((p) => !existsSync(join(dir, p)));
214
+ const present = UNIVERSAL.length - missing.length;
215
+
216
+ // AGENTS.md / GEMINI.md are mirrors, not standard files — the scaffolder never
217
+ // emits them and CLAUDE.md says never to create them just to hold a block. So
218
+ // they are reported as an observation, never as a gap.
219
+ const mirrors = ["AGENTS.md", "GEMINI.md"].filter((f) => existsSync(join(dir, f)));
220
+
221
+ const typeSpec = deriveTypeSpecific(descriptor, descriptor?.slug ?? name);
222
+ const typeMissing = typeSpec
223
+ ? typeSpec.paths.filter((p) => !UNIVERSAL.includes(p) && !existsSync(join(dir, p)))
224
+ : null;
225
+
226
+ results.push({
227
+ name, dir, outcome: missing.length === 0 ? "CONFORMS" : "GAPS",
228
+ present, total: UNIVERSAL.length, missing, mirrors,
229
+ descriptorState, projectType: descriptor?.projectType ?? null,
230
+ typeMissing, typeTotal: typeSpec ? typeSpec.paths.length : null,
231
+ });
232
+ }
233
+
234
+ // ── Report ───────────────────────────────────────────────────────────────────
235
+
236
+ // 🔴 PEER RARITY — the half that makes a gap READABLE, and the half a single-repo
237
+ // audit structurally cannot produce.
238
+ //
239
+ // "You are missing BACKUPS.md" invites the reading "you were built wrong". The
240
+ // portfolio says otherwise: 37 of 57 repos lack it, which is not 37 mistakes —
241
+ // it is a standard that GREW, with no mechanism to deliver an addition to the
242
+ // repos scaffolded before it existed. That is the capture-learnings enrolment
243
+ // bug again (the step was right; 25 of 41 projects never received it), and it
244
+ // belongs to THIS project, not to the repo being measured.
245
+ //
246
+ // So a gap shared with most peers and a gap unique to one repo are different
247
+ // findings with different owners, and they must not print the same line.
248
+ const peerCount = {};
249
+ const examinedRepos = results.filter((r) => r.outcome === "CONFORMS" || r.outcome === "GAPS");
250
+ for (const r of examinedRepos) for (const m of r.missing) peerCount[m] = (peerCount[m] ?? 0) + 1;
251
+ const N = examinedRepos.length;
252
+ /** A gap is SHARED once most examined peers have it too — but only when enough
253
+ * peers were examined to say so. With one repo there is no peer set, and the
254
+ * honest answer is "not measured", never "unique to you". */
255
+ function rarity(path) {
256
+ if (N < 5) return null;
257
+ const n = peerCount[path] ?? 0;
258
+ return { n, of: N, shared: n > N / 2 };
259
+ }
260
+
261
+ if (args.json) {
262
+ console.log(JSON.stringify({ standard: UNIVERSAL, peerCount, examined: N, results }, null, 2));
263
+ } else {
264
+ console.log(`The Z2W project standard is ${UNIVERSAL.length} files, derived from this repo's`);
265
+ console.log(`scaffolder as the intersection of all ${PROJECT_TYPES.length} project types.\n`);
266
+
267
+ for (const r of results) {
268
+ if (r.outcome === "UNREADABLE" || r.outcome === "SKIPPED") {
269
+ console.log(`⚪ ${r.name} — ${r.outcome}: ${r.reason}`);
270
+ console.log(` ${r.dir}\n`);
271
+ continue;
272
+ }
273
+ const icon = r.outcome === "CONFORMS" ? "✅" : "🟠";
274
+ console.log(`${icon} ${r.name} — ${r.present} of ${r.total} standard files present`);
275
+ console.log(` ${r.dir}`);
276
+ if (r.missing.length) {
277
+ const yours = r.missing.filter((m) => !rarity(m)?.shared);
278
+ const common = r.missing.filter((m) => rarity(m)?.shared);
279
+ if (N < 5) {
280
+ console.log(` MISSING: ${r.missing.join(", ")}`);
281
+ console.log(` ⓘ only ${N} repo(s) examined — too few to say whether peers share these gaps.`);
282
+ } else {
283
+ if (yours.length) console.log(` MISSING, and rare among peers: ` +
284
+ yours.map((m) => `${m} (${rarity(m).n}/${N})`).join(", "));
285
+ if (common.length) console.log(` MISSING, but so are most peers — a DELIVERY gap, not this repo's: ` +
286
+ common.map((m) => `${m} (${rarity(m).n}/${N})`).join(", "));
287
+ }
288
+ }
289
+ if (r.mirrors.length) console.log(` also keeps (not standard, a mirror): ${r.mirrors.join(", ")}`);
290
+ if (r.descriptorState === "absent") {
291
+ console.log(` ⓘ no z2w-project.json, so the TYPE-SPECIFIC half could not be evaluated`);
292
+ } else if (r.descriptorState === "unparseable") {
293
+ console.log(` ⚠ z2w-project.json is unparseable — type-specific half NOT evaluated`);
294
+ } else if (!r.projectType) {
295
+ console.log(` ⓘ descriptor declares no projectType — type-specific half NOT evaluated`);
296
+ } else {
297
+ const inferred = r.descriptorState === "backfilled" ? " (INFERRED, backfilled)" : "";
298
+ console.log(` type ${r.projectType}${inferred}: ${r.typeMissing.length} of ` +
299
+ `${r.typeTotal - r.total} type-specific paths absent` +
300
+ (r.typeMissing.length ? ` — ${r.typeMissing.slice(0, 8).join(", ")}` +
301
+ (r.typeMissing.length > 8 ? `, +${r.typeMissing.length - 8} more` : "") : ""));
302
+ console.log(` ⓘ type-specific absences are ADVISORY — a mature repo restructures its own source tree.`);
303
+ }
304
+ console.log("");
305
+ }
306
+
307
+ const examined = results.filter((r) => r.outcome === "CONFORMS" || r.outcome === "GAPS").length;
308
+ const conforms = results.filter((r) => r.outcome === "CONFORMS").length;
309
+ const skipped = results.filter((r) => r.outcome === "SKIPPED").length;
310
+ const unreadable = results.filter((r) => r.outcome === "UNREADABLE").length;
311
+
312
+ console.log(`Examined ${examined} of ${results.length} target(s) against a ${UNIVERSAL.length}-file standard.`);
313
+ console.log(` fully conformant: ${conforms}`);
314
+ console.log(` with gaps: ${examined - conforms}`);
315
+ console.log(` skipped: ${skipped} (not a repo)`);
316
+ console.log(` unreadable: ${unreadable}`);
317
+ if (N >= 5) {
318
+ const shared = Object.entries(peerCount).filter(([p]) => rarity(p).shared)
319
+ .sort((a, b) => b[1] - a[1]);
320
+ if (shared.length) {
321
+ console.log(`\n🔴 ${shared.length} standard file(s) are absent from MOST of the ${N} repos examined.`);
322
+ console.log(` That is a DELIVERY gap owned by the scaffolder, not ${shared.length} misbuilt projects:`);
323
+ for (const [p, n] of shared) console.log(` ${String(n).padStart(3)} / ${N} ${p}`);
324
+ }
325
+ }
326
+ if (examined === 0) {
327
+ console.error(`\n❌ Examined 0 of ${results.length} target(s). This is NOT a clean sweep —\n` +
328
+ ` nothing was examined, and a zero here says nothing about conformance.`);
329
+ process.exit(2);
330
+ }
331
+ if (args.strict && examined - conforms > 0) process.exit(1);
332
+ }