@zero2webmaster/starter-kit 0.30.0 → 0.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # z2w-starter-kit
2
2
 
3
- **Version:** 0.30.0 | **Framework:** 2.19.0
3
+ **Version:** 0.32.1 | **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.30.0 | Last Updated: 2026-09-11*
138
+ *Version: 0.32.1 | Last Updated: 2026-09-19*
package/dist/audience.js CHANGED
@@ -169,6 +169,29 @@ const PRIVATE_RESOURCES = [
169
169
  { resource: "Skill Vault", re: /\bSkill Vault\b/ },
170
170
  { resource: "the coordination bulletin repo", re: /zero2webmaster\/z2w-agent-coordination/ },
171
171
  { resource: "the local skills symlink tree", re: /[~.]\/\.(claude|cursor)\/skills/ },
172
+ // 🔴 A NAMED Vault skill, which the three entries above cannot see. Added
173
+ // 2026-09-19 after `cursor-project-templates` asked (via `grantor`'s
174
+ // in-app-user-guide filing) whether the canonical body may carry
175
+ // *"See the `in-app-user-guide` skill."* to external customers.
176
+ //
177
+ // Measured before answering, and the answer was not the obvious one: that
178
+ // sentence names a resource an outside reader cannot open, is phrased as an
179
+ // instruction, and **fired none of the checks above** — it contains neither
180
+ // the words "Skill Vault", nor the bulletin repo, nor a symlink path. So the
181
+ // guard that exists to catch exactly this class was blind to the most natural
182
+ // way of writing it. `stripVaultPointers` does not save it either: it
183
+ // downgrades `[[slug]]` to bare prose, which leaves the instruction intact and
184
+ // merely un-linked.
185
+ //
186
+ // Matches a skill referenced by slug in either notation — `[[slug]]` or
187
+ // `` `slug` `` — immediately followed by the word "skill", which is how every
188
+ // such pointer in this ecosystem is written. Narrow on purpose: it needs BOTH
189
+ // the slug notation AND the following noun, so ordinary prose about "a skill"
190
+ // does not fire it.
191
+ {
192
+ resource: "a private Skill Vault skill, named as an instruction",
193
+ re: /(\[\[[a-z0-9][a-z0-9-]*\]\]|`[a-z0-9][a-z0-9-]*`)\s+skill\b/i,
194
+ },
172
195
  ];
173
196
  /**
174
197
  * Verbs that turn a mention into an instruction. Without this the check fires on
@@ -0,0 +1,106 @@
1
+ import type { ProjectType, ScaffoldInputs } from "./index.js";
2
+ import type { ScaffoldFile } from "./scaffolders/common.js";
3
+ /**
4
+ * Schema version of the descriptor document itself. Bump on any BREAKING change
5
+ * to the shape (a removed field, a renamed field, a changed meaning). Adding an
6
+ * optional field is not breaking and does not bump it.
7
+ */
8
+ export declare const DESCRIPTOR_VERSION = 1;
9
+ /** The emitted file's path, relative to the project root. */
10
+ export declare const DESCRIPTOR_PATH = "z2w-project.json";
11
+ /**
12
+ * The CLOSED task vocabulary. See design rule 2 above.
13
+ *
14
+ * Deliberately at the repo root and NOT under a dotfolder: Finder hides
15
+ * dotfolders, and this ecosystem has already lost time to exactly that (Kerry
16
+ * could not open `~/.cache/z2w-coordination`, which is why the bulletin clone
17
+ * grew a visible Desktop symlink). A descriptor a human cannot see is a
18
+ * descriptor a human cannot correct.
19
+ */
20
+ export declare const TASK_VERBS: readonly ["dev", "build", "test", "typecheck", "lint", "deploy", "migrate", "seed"];
21
+ export type TaskVerb = (typeof TASK_VERBS)[number];
22
+ /**
23
+ * How dangerous running the task is, for an autonomy classifier that must decide
24
+ * whether to run it unattended.
25
+ *
26
+ * - `read-only` — inspects the tree and writes nothing an operator would miss.
27
+ * - `local-write` — writes to the working tree or binds a local port. Reversible
28
+ * with `git checkout` / killing a process.
29
+ * - `remote-write`— reaches a system outside this machine: a production deploy,
30
+ * a live database, a third-party API. NOT reversible by the
31
+ * agent that ran it.
32
+ *
33
+ * 🔴 Classified CONSERVATIVELY, and the asymmetry is deliberate. Understating a
34
+ * class is the error that costs something irreversible; overstating it costs one
35
+ * confirmation prompt. So `test` is `local-write` rather than `read-only` even
36
+ * though most suites touch nothing, and `migrate` is `remote-write` even when it
37
+ * is pointed at a dev branch. [[unknown-means-denied]]
38
+ */
39
+ export declare const SAFETY_CLASSES: readonly ["read-only", "local-write", "remote-write"];
40
+ export type SafetyClass = (typeof SAFETY_CLASSES)[number];
41
+ /**
42
+ * The safety class of each verb. A property of the VERB, which is the whole
43
+ * reason the vocabulary is closed — an open vocabulary could not have this table.
44
+ */
45
+ export declare const VERB_SAFETY: Readonly<Record<TaskVerb, SafetyClass>>;
46
+ export interface ProjectTask {
47
+ /** The exact command to run, from the project root. */
48
+ command: string;
49
+ /** How dangerous it is — see {@link SafetyClass}. */
50
+ safety: SafetyClass;
51
+ }
52
+ /**
53
+ * How the `tasks` map was derived. Present so a consumer can tell "this project
54
+ * genuinely has no runnable tasks" from "nothing looked". See design rule 3.
55
+ */
56
+ export type TaskSource = "package.json-scripts" | "pyproject" | "static-site" | "none";
57
+ export interface ProjectDescriptor {
58
+ descriptorVersion: number;
59
+ slug: string;
60
+ description: string;
61
+ projectType: ProjectType;
62
+ /** Who produced this file, and when. Both are needed to judge staleness. */
63
+ generatedBy: string;
64
+ generatedOn: string;
65
+ stack: {
66
+ runtime: "node" | "python" | "php" | "static" | "none";
67
+ database: string;
68
+ hasWebUi: boolean;
69
+ hasCron: boolean;
70
+ };
71
+ repo: {
72
+ host: "github";
73
+ org: string;
74
+ name: string;
75
+ url: string;
76
+ };
77
+ deploy: {
78
+ /** `null` where the scaffold genuinely does not determine one. */
79
+ target: string | null;
80
+ };
81
+ coordination: {
82
+ participates: boolean;
83
+ /** `null` when this project does not participate in the bulletin. */
84
+ bulletinRepo: string | null;
85
+ bulletinFile: string | null;
86
+ agentIdentifier: string | null;
87
+ };
88
+ taskSource: TaskSource;
89
+ tasks: Partial<Record<TaskVerb, ProjectTask>>;
90
+ }
91
+ /**
92
+ * Compose the descriptor for a completed scaffold.
93
+ *
94
+ * `files` must be the FULL emitted file list — the derivation reads it, so
95
+ * calling this before the type-specific files are appended would silently
96
+ * produce an empty `tasks` map.
97
+ */
98
+ export declare function buildProjectDescriptor(inputs: ScaffoldInputs, files: readonly ScaffoldFile[], opts?: {
99
+ date?: string;
100
+ cliVersion?: string;
101
+ }): ProjectDescriptor;
102
+ /** The descriptor as an emittable {@link ScaffoldFile}. */
103
+ export declare function descriptorFile(inputs: ScaffoldInputs, files: readonly ScaffoldFile[], opts?: {
104
+ date?: string;
105
+ cliVersion?: string;
106
+ }): ScaffoldFile;
@@ -0,0 +1,278 @@
1
+ // The machine-readable PROJECT DESCRIPTOR.
2
+ //
3
+ // One file, emitted at scaffold time into every project this CLI creates, so a
4
+ // surface that is NOT Cursor — a launcher, `project-creator`, an agent runner,
5
+ // a dashboard — can answer two questions about a Z2W project without a human
6
+ // reading its README:
7
+ //
8
+ // 1. WHAT IS THIS? slug, type, stack, repo, deploy target, bulletin file.
9
+ // 2. WHAT MAY I DO IN IT, AND HOW DANGEROUS IS IT? a `tasks` map over a
10
+ // CLOSED verb vocabulary, each task carrying a SAFETY CLASS.
11
+ //
12
+ // Scope ruled on the coordination bulletin 2026-09-13 (the three-way IDE split):
13
+ // `z2w-agent-command-center` owns the RANKING — *which* project to work on next.
14
+ // This descriptor answers the other half — *what may be done in that project*.
15
+ // The two are deliberately separate artifacts owned by separate projects.
16
+ //
17
+ // ─────────────────────────── THREE DESIGN RULES ───────────────────────────
18
+ //
19
+ // **1. The safety class lives ON the task, never in a parallel manifest.**
20
+ // A second list drifts from the first, and the drift is silent because both
21
+ // halves stay internally consistent. One task, one command, one class.
22
+ //
23
+ // **2. The vocabulary is CLOSED.** Eight verbs, fixed below. A project that does
24
+ // something outside them does not get a ninth verb invented for it — it gets no
25
+ // task, and the consumer falls back to a human. An open vocabulary would make
26
+ // the safety classification unbounded, which defeats the point: a classifier
27
+ // cannot reason about a verb it has never seen.
28
+ //
29
+ // **3. A task is emitted ONLY when the scaffold actually provides the command.**
30
+ // The tasks are DERIVED from the emitted file list — package.json `scripts` for
31
+ // the Node types, the known entry points for python — never from a per-type
32
+ // table written from memory. A descriptor claiming `npm run lint` for a project
33
+ // with no lint script is worse than a descriptor with no lint task at all: the
34
+ // consumer runs it, gets `npm ERR! Missing script`, and learns to distrust the
35
+ // whole file. This is the same discipline as [[zero-is-not-a-pass]] — "no task"
36
+ // and "not measured" must not be the same value, which is why `tasks` is always
37
+ // present (possibly empty) and `taskSource` always says how it was derived.
38
+ /**
39
+ * Schema version of the descriptor document itself. Bump on any BREAKING change
40
+ * to the shape (a removed field, a renamed field, a changed meaning). Adding an
41
+ * optional field is not breaking and does not bump it.
42
+ */
43
+ export const DESCRIPTOR_VERSION = 1;
44
+ /** The emitted file's path, relative to the project root. */
45
+ export const DESCRIPTOR_PATH = "z2w-project.json";
46
+ /**
47
+ * The CLOSED task vocabulary. See design rule 2 above.
48
+ *
49
+ * Deliberately at the repo root and NOT under a dotfolder: Finder hides
50
+ * dotfolders, and this ecosystem has already lost time to exactly that (Kerry
51
+ * could not open `~/.cache/z2w-coordination`, which is why the bulletin clone
52
+ * grew a visible Desktop symlink). A descriptor a human cannot see is a
53
+ * descriptor a human cannot correct.
54
+ */
55
+ export const TASK_VERBS = [
56
+ "dev",
57
+ "build",
58
+ "test",
59
+ "typecheck",
60
+ "lint",
61
+ "deploy",
62
+ "migrate",
63
+ "seed",
64
+ ];
65
+ /**
66
+ * How dangerous running the task is, for an autonomy classifier that must decide
67
+ * whether to run it unattended.
68
+ *
69
+ * - `read-only` — inspects the tree and writes nothing an operator would miss.
70
+ * - `local-write` — writes to the working tree or binds a local port. Reversible
71
+ * with `git checkout` / killing a process.
72
+ * - `remote-write`— reaches a system outside this machine: a production deploy,
73
+ * a live database, a third-party API. NOT reversible by the
74
+ * agent that ran it.
75
+ *
76
+ * 🔴 Classified CONSERVATIVELY, and the asymmetry is deliberate. Understating a
77
+ * class is the error that costs something irreversible; overstating it costs one
78
+ * confirmation prompt. So `test` is `local-write` rather than `read-only` even
79
+ * though most suites touch nothing, and `migrate` is `remote-write` even when it
80
+ * is pointed at a dev branch. [[unknown-means-denied]]
81
+ */
82
+ export const SAFETY_CLASSES = ["read-only", "local-write", "remote-write"];
83
+ /**
84
+ * The safety class of each verb. A property of the VERB, which is the whole
85
+ * reason the vocabulary is closed — an open vocabulary could not have this table.
86
+ */
87
+ export const VERB_SAFETY = {
88
+ typecheck: "read-only",
89
+ lint: "read-only",
90
+ build: "local-write",
91
+ test: "local-write",
92
+ dev: "local-write",
93
+ deploy: "remote-write",
94
+ migrate: "remote-write",
95
+ seed: "remote-write",
96
+ };
97
+ /** Build a task entry, taking the safety class from the verb table. */
98
+ function task(verb, command) {
99
+ return { command, safety: VERB_SAFETY[verb] };
100
+ }
101
+ /**
102
+ * Map the npm scripts a scaffold actually emitted onto the closed vocabulary.
103
+ *
104
+ * The left side of each pair is the VERB; the right side is the list of script
105
+ * names that legitimately implement it, most-preferred first. A verb with no
106
+ * matching script yields NO task — see design rule 3.
107
+ *
108
+ * `db:push` implements `migrate` because it is the command that APPLIES schema
109
+ * to a database. `db:generate` deliberately maps to nothing: it writes migration
110
+ * files locally and is a different act with a different safety class, and a
111
+ * closed vocabulary drops what does not fit rather than bending a verb to cover it.
112
+ */
113
+ const NPM_SCRIPT_FOR_VERB = {
114
+ dev: ["dev"],
115
+ build: ["build"],
116
+ test: ["test"],
117
+ typecheck: ["typecheck"],
118
+ lint: ["lint"],
119
+ deploy: ["deploy"],
120
+ migrate: ["db:push", "migrate", "db:migrate"],
121
+ seed: ["db:seed", "seed"],
122
+ };
123
+ function tasksFromPackageJson(content) {
124
+ let scripts = {};
125
+ try {
126
+ const parsed = JSON.parse(content);
127
+ scripts = parsed.scripts ?? {};
128
+ }
129
+ catch {
130
+ // An unparseable package.json is a real possibility (a template escaping
131
+ // slip has shipped from this repo before — see CLAUDE.md § "a green test
132
+ // suite is NOT evidence that a scaffold is correct"). Report "none" rather
133
+ // than guessing, so the descriptor never claims a task it could not read.
134
+ return { source: "none", tasks: {} };
135
+ }
136
+ const tasks = {};
137
+ for (const verb of TASK_VERBS) {
138
+ const candidates = NPM_SCRIPT_FOR_VERB[verb];
139
+ const hit = candidates.find((name) => typeof scripts[name] === "string");
140
+ if (hit === undefined)
141
+ continue;
142
+ // `npm test` is the built-in alias; everything else needs `run`.
143
+ tasks[verb] = task(verb, hit === "test" ? "npm test" : `npm run ${hit}`);
144
+ }
145
+ return { source: "package.json-scripts", tasks };
146
+ }
147
+ /**
148
+ * Python has no scripts table, so the commands come from what the scaffolder
149
+ * demonstrably emits: a FastAPI app under `src/<slug_under>/main.py` (run with
150
+ * uvicorn, exactly as the emitted README documents it) and pytest as a declared
151
+ * dev dependency with a real `tests/` tree.
152
+ *
153
+ * Both are checked against the file list rather than assumed — if the python
154
+ * scaffolder stops emitting `main.py`, the `dev` task disappears instead of
155
+ * becoming a lie.
156
+ */
157
+ function tasksFromPyproject(inputs, paths) {
158
+ const tasks = {};
159
+ const pkg = inputs.slug.replace(/-/g, "_");
160
+ if (paths.has(`src/${pkg}/main.py`)) {
161
+ tasks.dev = task("dev", `uvicorn ${pkg}.main:app --reload`);
162
+ }
163
+ if ([...paths].some((p) => p.startsWith("tests/"))) {
164
+ tasks.test = task("test", "pytest");
165
+ }
166
+ return { source: "pyproject", tasks };
167
+ }
168
+ /**
169
+ * A static Cloudflare Pages site has no package.json at all. Its two real
170
+ * commands are the wrangler invocations the emitted README documents.
171
+ */
172
+ function tasksForStaticSite() {
173
+ return {
174
+ source: "static-site",
175
+ tasks: {
176
+ dev: task("dev", "npx wrangler pages dev ."),
177
+ deploy: task("deploy", "npx wrangler pages deploy ."),
178
+ },
179
+ };
180
+ }
181
+ /**
182
+ * Derive the deploy target from the files the scaffold actually emitted, not
183
+ * from a per-type table. `null` means "this scaffold does not determine one" —
184
+ * which is the honest answer for a WordPress plugin (the target is whatever site
185
+ * installs it) and a protocol repo (nothing deploys).
186
+ */
187
+ function deployTarget(projectType, paths) {
188
+ if (paths.has("wrangler.jsonc") || paths.has("wrangler.toml")) {
189
+ return "cloudflare-workers";
190
+ }
191
+ if (projectType === "cf-pages")
192
+ return "cloudflare-pages";
193
+ if (projectType === "nextjs")
194
+ return "vercel";
195
+ if (paths.has("Dockerfile"))
196
+ return "container";
197
+ if (projectType === "library")
198
+ return "npm";
199
+ return null;
200
+ }
201
+ function runtimeFor(projectType) {
202
+ switch (projectType) {
203
+ case "python-service":
204
+ return "python";
205
+ case "wp-plugin":
206
+ return "php";
207
+ case "cf-pages":
208
+ return "static";
209
+ case "protocol-repo":
210
+ return "none";
211
+ default:
212
+ return "node";
213
+ }
214
+ }
215
+ /**
216
+ * Compose the descriptor for a completed scaffold.
217
+ *
218
+ * `files` must be the FULL emitted file list — the derivation reads it, so
219
+ * calling this before the type-specific files are appended would silently
220
+ * produce an empty `tasks` map.
221
+ */
222
+ export function buildProjectDescriptor(inputs, files, opts) {
223
+ const paths = new Set(files.map((f) => f.path));
224
+ const pkg = files.find((f) => f.path === "package.json");
225
+ let derived;
226
+ if (pkg) {
227
+ derived = tasksFromPackageJson(pkg.content);
228
+ }
229
+ else if (paths.has("pyproject.toml")) {
230
+ derived = tasksFromPyproject(inputs, paths);
231
+ }
232
+ else if (inputs.projectType === "cf-pages") {
233
+ derived = tasksForStaticSite();
234
+ }
235
+ else {
236
+ // wp-plugin and protocol-repo genuinely have no runnable commands. `none`
237
+ // is a measured answer, not a failure to look.
238
+ derived = { source: "none", tasks: {} };
239
+ }
240
+ const participates = inputs.participateInBulletin;
241
+ return {
242
+ descriptorVersion: DESCRIPTOR_VERSION,
243
+ slug: inputs.slug,
244
+ description: inputs.description,
245
+ projectType: inputs.projectType,
246
+ generatedBy: `@zero2webmaster/starter-kit@${opts?.cliVersion ?? "unknown"}`,
247
+ generatedOn: opts?.date ?? new Date().toISOString().slice(0, 10),
248
+ stack: {
249
+ runtime: runtimeFor(inputs.projectType),
250
+ database: inputs.dbStrategy,
251
+ hasWebUi: inputs.hasWebUi,
252
+ hasCron: inputs.hasCron,
253
+ },
254
+ repo: {
255
+ host: "github",
256
+ org: inputs.githubOrg,
257
+ name: inputs.slug,
258
+ url: `https://github.com/${inputs.githubOrg}/${inputs.slug}`,
259
+ },
260
+ deploy: { target: deployTarget(inputs.projectType, paths) },
261
+ coordination: {
262
+ participates,
263
+ bulletinRepo: participates ? "zero2webmaster/z2w-agent-coordination" : null,
264
+ bulletinFile: participates ? `projects/${inputs.slug}.md` : null,
265
+ agentIdentifier: participates ? inputs.slug : null,
266
+ },
267
+ taskSource: derived.source,
268
+ tasks: derived.tasks,
269
+ };
270
+ }
271
+ /** The descriptor as an emittable {@link ScaffoldFile}. */
272
+ export function descriptorFile(inputs, files, opts) {
273
+ const descriptor = buildProjectDescriptor(inputs, files, opts);
274
+ return {
275
+ path: DESCRIPTOR_PATH,
276
+ content: `${JSON.stringify(descriptor, null, 2)}\n`,
277
+ };
278
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The three CROSS-REPO sources this repo's drift guards read — and the switch
3
+ * that decides whether their ABSENCE is allowed to be silent.
4
+ *
5
+ * WHY THIS FILE EXISTS
6
+ * --------------------
7
+ * Six of this suite's tests compare something this CLI emits against the
8
+ * canonical text it claims to mirror. All three canonical texts live in OTHER
9
+ * private repos, so until 2026-09-13 every one of those tests was written as
10
+ * `it.skipIf(!existsSync(pathOnKerrysLaptop))`.
11
+ *
12
+ * That was correct when nothing else could reach them, and it became the
13
+ * problem the moment CI existed: the coordination-pointer conformance byte-diff
14
+ * — built in v0.30.0 *after* the emitted pointer had drifted to a 62%-similar
15
+ * paraphrase that four fingerprint bumps missed — ran on exactly one machine,
16
+ * and it was the machine CI exists to stop trusting.
17
+ *
18
+ * THE PART THAT IS NOT ABOUT CREDENTIALS
19
+ * --------------------------------------
20
+ * Granting CI read access to those repos is necessary and not sufficient. A
21
+ * skip reads as green, so if the token lapses, the checkout silently fails, or
22
+ * a file is renamed upstream, the guards return to not running and NOTHING GOES
23
+ * RED. We would be paying for a credential with no guarantee it is still in
24
+ * use — which is [[zero-is-not-a-pass]] wearing a purchase order.
25
+ *
26
+ * So absence is configurable, and the two audiences get opposite defaults:
27
+ *
28
+ * - a contributor's laptop (no env var): missing source => SKIP, as before.
29
+ * - CI (`Z2W_REQUIRE_DRIFT_SOURCES=1`): missing source => HARD FAILURE.
30
+ *
31
+ * RESOLUTION IS REPORTED, NOT JUST PERFORMED
32
+ * ------------------------------------------
33
+ * Each source is found by walking a list of candidate paths, and taking the
34
+ * first that exists is selection by POSITION, not by evidence — a named trap in
35
+ * [[zero-is-not-a-pass]]. The stale bulletin clone that sat 215 commits behind
36
+ * while a guard reported a shrinking gap was exactly this. So every resolution
37
+ * carries WHICH candidate won and WHY, and the suite prints it.
38
+ */
39
+ export type DriftSourceName = "coordination" | "templates" | "skill";
40
+ /** Where CI drops the sibling checkouts. Overridable so the layout is not magic. */
41
+ export declare const driftSourcesDir: () => string;
42
+ /**
43
+ * `1` means a missing source is a FAILURE, not a skip. CI sets it; laptops
44
+ * don't. Deliberately an opt-IN to strictness rather than an opt-out: a
45
+ * contributor who has none of these repos must still be able to run the suite.
46
+ */
47
+ export declare const driftSourcesRequired: () => boolean;
48
+ export interface ResolvedDriftSource {
49
+ readonly name: DriftSourceName;
50
+ readonly repo: string;
51
+ readonly guards: string;
52
+ /** The file, if it was found anywhere. */
53
+ readonly path?: string;
54
+ /** WHICH candidate won. Never infer this from `path` — say it. */
55
+ readonly origin: "ci-checkout" | "local" | "absent";
56
+ /** Everything looked at, in order, so a wrong answer is diagnosable. */
57
+ readonly candidatesTried: readonly string[];
58
+ }
59
+ /** Find one source. Never throws — callers decide what absence means. */
60
+ export declare const resolveDriftSource: (name: DriftSourceName) => ResolvedDriftSource;
61
+ /**
62
+ * The `skipIf` condition. Skip ONLY when the source is missing AND nobody has
63
+ * declared it mandatory. Under `Z2W_REQUIRE_DRIFT_SOURCES=1` this returns false
64
+ * even with no file, so the test RUNS and `demandDriftSource` fails it loudly.
65
+ */
66
+ export declare const skipUnlessRequired: (source: ResolvedDriftSource) => boolean;
67
+ /** The path, or a failure that says exactly what is missing and how to supply it. */
68
+ export declare const demandDriftSource: (source: ResolvedDriftSource) => string;
69
+ /**
70
+ * A one-line, always-visible statement of what was (or was not) measured.
71
+ * A silent skip is how a blind guard hides, so every source prints either way.
72
+ */
73
+ export declare const describeDriftSource: (source: ResolvedDriftSource) => string;
74
+ /**
75
+ * The ref to compare a source checkout against when asking "is this copy
76
+ * current?".
77
+ *
78
+ * Three shapes have to work: a laptop clone (has `origin/main`), an
79
+ * `actions/checkout` of another repo (has a remote-tracking ref, but the branch
80
+ * name is the repo's default and not necessarily `main`), and anything else.
81
+ * Returns undefined rather than guessing — the caller must treat "cannot
82
+ * determine" as a failure, never as a clean result.
83
+ */
84
+ export declare const upstreamRefFor: (repoDir: string) => string | undefined;
85
+ /**
86
+ * The canonical text of a file, READ FROM THE UPSTREAM REF rather than from a
87
+ * working tree.
88
+ *
89
+ * 🔴 WHY THIS EXISTS (2026-09-18). The conformance guards used to read
90
+ * `AGENT_PROTOCOL.md` off the working tree of the shared bulletin clone, and
91
+ * fail when that tree differed from `origin/main` with the remedy
92
+ * `git -C <repo> pull --ff-only`. Both halves are wrong, and they are wrong in
93
+ * a way that compounds:
94
+ *
95
+ * 1. **Nothing ever pulls that clone, by design.** Since 2026-08-29 every
96
+ * session takes a linked WORKTREE from it and works there; the shared tree
97
+ * itself carries a `pre-commit` guard that REFUSES commits and is left
98
+ * alone on purpose. Measured today it was **79 commits behind origin/main**
99
+ * and dirty with three other sessions' in-flight files.
100
+ * 2. **So the guard's remedy instructs an action the coordination protocol
101
+ * forbids** — `agent-workspace.sh` prints "do not pull it, do not commit
102
+ * it" about that exact directory. A guard whose only fix is a prohibited
103
+ * command is a guard that will be muted, and muting it restores the blind
104
+ * spot it was built to close.
105
+ *
106
+ * Reading the ref removes the dependency on any checkout's currency: the
107
+ * baseline is whatever `origin/main` holds, fetched at the moment we ask. That
108
+ * is strictly stronger than "the working tree happens to match", which is all
109
+ * the old test could assert.
110
+ *
111
+ * It THROWS rather than falling back to the working file. A fallback here would
112
+ * silently restore the stale-canon comparison this replaces, and the whole
113
+ * point of the drift-sources rework is that an unverifiable baseline must never
114
+ * render as a clean one ([[zero-is-not-a-pass]]).
115
+ */
116
+ export interface CanonicalRead {
117
+ /** The file's contents at `ref`. */
118
+ readonly text: string;
119
+ /** Which ref was treated as upstream — say it, never infer it. */
120
+ readonly ref: string;
121
+ /** The commit the text was read from, short form. */
122
+ readonly sha: string;
123
+ /**
124
+ * How the ref we read got to be the ref we read. Three states, not a boolean:
125
+ * a fetch we CHOSE not to run and a fetch that FAILED are different facts, and
126
+ * collapsing them into `false` would report a CI run — where skipping is
127
+ * correct and deliberate — as "the remote was unreachable". That is the
128
+ * [[zero-is-not-a-pass]] shape applied to our own telemetry.
129
+ */
130
+ readonly refreshed: "fetched" | "skipped" | "unreachable";
131
+ }
132
+ export interface ReadCanonicalOptions {
133
+ /**
134
+ * Refresh the ref from the remote before reading it. Default true.
135
+ *
136
+ * 🔴 Pass `false` for a CI checkout. `actions/checkout` provisions the repo at
137
+ * run start, so its ref is current by construction and a fetch buys nothing —
138
+ * but it COSTS, and on 2026-09-18 that cost was a red build: the fetch ran
139
+ * past vitest's 5 s per-test budget on the runner while finishing instantly on
140
+ * the laptop. Local green, CI red, for a network call that was pure overhead.
141
+ */
142
+ readonly fetch?: boolean;
143
+ }
144
+ export declare const readCanonicalFile: (repoDir: string, relPath: string, options?: ReadCanonicalOptions) => CanonicalRead;
@@ -0,0 +1,204 @@
1
+ /**
2
+ * The three CROSS-REPO sources this repo's drift guards read — and the switch
3
+ * that decides whether their ABSENCE is allowed to be silent.
4
+ *
5
+ * WHY THIS FILE EXISTS
6
+ * --------------------
7
+ * Six of this suite's tests compare something this CLI emits against the
8
+ * canonical text it claims to mirror. All three canonical texts live in OTHER
9
+ * private repos, so until 2026-09-13 every one of those tests was written as
10
+ * `it.skipIf(!existsSync(pathOnKerrysLaptop))`.
11
+ *
12
+ * That was correct when nothing else could reach them, and it became the
13
+ * problem the moment CI existed: the coordination-pointer conformance byte-diff
14
+ * — built in v0.30.0 *after* the emitted pointer had drifted to a 62%-similar
15
+ * paraphrase that four fingerprint bumps missed — ran on exactly one machine,
16
+ * and it was the machine CI exists to stop trusting.
17
+ *
18
+ * THE PART THAT IS NOT ABOUT CREDENTIALS
19
+ * --------------------------------------
20
+ * Granting CI read access to those repos is necessary and not sufficient. A
21
+ * skip reads as green, so if the token lapses, the checkout silently fails, or
22
+ * a file is renamed upstream, the guards return to not running and NOTHING GOES
23
+ * RED. We would be paying for a credential with no guarantee it is still in
24
+ * use — which is [[zero-is-not-a-pass]] wearing a purchase order.
25
+ *
26
+ * So absence is configurable, and the two audiences get opposite defaults:
27
+ *
28
+ * - a contributor's laptop (no env var): missing source => SKIP, as before.
29
+ * - CI (`Z2W_REQUIRE_DRIFT_SOURCES=1`): missing source => HARD FAILURE.
30
+ *
31
+ * RESOLUTION IS REPORTED, NOT JUST PERFORMED
32
+ * ------------------------------------------
33
+ * Each source is found by walking a list of candidate paths, and taking the
34
+ * first that exists is selection by POSITION, not by evidence — a named trap in
35
+ * [[zero-is-not-a-pass]]. The stale bulletin clone that sat 215 commits behind
36
+ * while a guard reported a shrinking gap was exactly this. So every resolution
37
+ * carries WHICH candidate won and WHY, and the suite prints it.
38
+ */
39
+ import { execFileSync } from "node:child_process";
40
+ import { existsSync } from "node:fs";
41
+ import { homedir } from "node:os";
42
+ import { isAbsolute, join, resolve } from "node:path";
43
+ /** Where CI drops the sibling checkouts. Overridable so the layout is not magic. */
44
+ export const driftSourcesDir = () => {
45
+ const dir = process.env.Z2W_DRIFT_SOURCES_DIR ?? ".drift-sources";
46
+ return isAbsolute(dir) ? dir : resolve(process.cwd(), dir);
47
+ };
48
+ /**
49
+ * `1` means a missing source is a FAILURE, not a skip. CI sets it; laptops
50
+ * don't. Deliberately an opt-IN to strictness rather than an opt-out: a
51
+ * contributor who has none of these repos must still be able to run the suite.
52
+ */
53
+ export const driftSourcesRequired = () => process.env.Z2W_REQUIRE_DRIFT_SOURCES === "1";
54
+ const SPECS = {
55
+ coordination: {
56
+ repo: "z2w-agent-coordination",
57
+ relPath: "AGENT_PROTOCOL.md",
58
+ localCandidates: () => [
59
+ // Since 2026-08-29 these are ONE clone (the Desktop path is a symlink),
60
+ // but both spellings are kept so a machine that predates that still works.
61
+ join(homedir(), "Desktop/Zero2Webmaster/AI/Cursor Projects/z2w-agent-coordination/AGENT_PROTOCOL.md"),
62
+ join(homedir(), ".cache/z2w-coordination/AGENT_PROTOCOL.md"),
63
+ ],
64
+ guards: "the emitted Agent Coordination pointer is upstream's steps 1 + 1b VERBATIM, " +
65
+ "and the fingerprint we stamp is the one upstream publishes",
66
+ },
67
+ templates: {
68
+ repo: "cursor-project-templates",
69
+ relPath: "Resources/CAPTURE_LEARNINGS_BLOCK.md",
70
+ localCandidates: () => [
71
+ join(homedir(), "Desktop/Zero2Webmaster/AI/Templates/Resources/CAPTURE_LEARNINGS_BLOCK.md"),
72
+ ],
73
+ guards: "the emitted Capture Learnings block is byte-identical to the canonical source",
74
+ },
75
+ skill: {
76
+ repo: "z2w-skill-vault",
77
+ relPath: "instantiate-z2w-project/references/standards-block.md",
78
+ localCandidates: () => [
79
+ // On the laptop this resolves through the Vault's sync.sh symlink.
80
+ join(homedir(), ".claude/skills/instantiate-z2w-project/references/standards-block.md"),
81
+ join(homedir(), "Desktop/Zero2Webmaster/AI/Skill Vault/instantiate-z2w-project/references/standards-block.md"),
82
+ ],
83
+ guards: "OP #2 reverse mirror — no standard exists in the skill that this CLI fails to emit",
84
+ },
85
+ };
86
+ /** Find one source. Never throws — callers decide what absence means. */
87
+ export const resolveDriftSource = (name) => {
88
+ const spec = SPECS[name];
89
+ const ciPath = join(driftSourcesDir(), spec.repo, spec.relPath);
90
+ const localCandidates = spec.localCandidates();
91
+ const candidatesTried = [ciPath, ...localCandidates];
92
+ // CI's explicitly provisioned checkout outranks whatever is ambiently lying
93
+ // around, so a runner can never accidentally measure a developer's stale copy.
94
+ if (existsSync(ciPath)) {
95
+ return { name, repo: spec.repo, guards: spec.guards, path: ciPath, origin: "ci-checkout", candidatesTried };
96
+ }
97
+ const local = localCandidates.find((p) => existsSync(p));
98
+ if (local) {
99
+ return { name, repo: spec.repo, guards: spec.guards, path: local, origin: "local", candidatesTried };
100
+ }
101
+ return { name, repo: spec.repo, guards: spec.guards, origin: "absent", candidatesTried };
102
+ };
103
+ /**
104
+ * The `skipIf` condition. Skip ONLY when the source is missing AND nobody has
105
+ * declared it mandatory. Under `Z2W_REQUIRE_DRIFT_SOURCES=1` this returns false
106
+ * even with no file, so the test RUNS and `demandDriftSource` fails it loudly.
107
+ */
108
+ export const skipUnlessRequired = (source) => !source.path && !driftSourcesRequired();
109
+ /** The path, or a failure that says exactly what is missing and how to supply it. */
110
+ export const demandDriftSource = (source) => {
111
+ if (source.path)
112
+ return source.path;
113
+ const spec = SPECS[source.name];
114
+ throw new Error(`Drift source "${source.name}" is REQUIRED here and was not found.\n` +
115
+ ` What stops being checked: ${source.guards}.\n` +
116
+ ` Expected: zero2webmaster/${spec.repo} -> ${spec.relPath}\n` +
117
+ ` Looked in, in order:\n${source.candidatesTried.map((p) => ` - ${p}`).join("\n")}\n` +
118
+ ` On a runner this means the checkout did not happen: the app token is missing or\n` +
119
+ ` expired, the App is not installed on ${spec.repo}, or the file moved upstream.\n` +
120
+ ` This is deliberately a FAILURE and not a skip — see src/drift-sources.ts.`);
121
+ };
122
+ /**
123
+ * A one-line, always-visible statement of what was (or was not) measured.
124
+ * A silent skip is how a blind guard hides, so every source prints either way.
125
+ */
126
+ export const describeDriftSource = (source) => source.path
127
+ ? `[drift source: ${source.name}] using ${source.origin} copy at ${source.path}`
128
+ : `[drift source: ${source.name}] ABSENT — not measured. This is NOT a pass.`;
129
+ /**
130
+ * The ref to compare a source checkout against when asking "is this copy
131
+ * current?".
132
+ *
133
+ * Three shapes have to work: a laptop clone (has `origin/main`), an
134
+ * `actions/checkout` of another repo (has a remote-tracking ref, but the branch
135
+ * name is the repo's default and not necessarily `main`), and anything else.
136
+ * Returns undefined rather than guessing — the caller must treat "cannot
137
+ * determine" as a failure, never as a clean result.
138
+ */
139
+ export const upstreamRefFor = (repoDir) => {
140
+ const git = (args) => {
141
+ try {
142
+ return execFileSync("git", args, { cwd: repoDir, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
143
+ }
144
+ catch {
145
+ return undefined;
146
+ }
147
+ };
148
+ // `origin/HEAD` is the honest answer when it exists: it names the default
149
+ // branch rather than assuming one.
150
+ const head = git(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
151
+ if (head)
152
+ return head;
153
+ for (const ref of ["origin/main", "origin/master"]) {
154
+ if (git(["rev-parse", "--verify", "--quiet", ref]))
155
+ return ref;
156
+ }
157
+ // Last resort: ask the remote directly. A shallow CI checkout still answers.
158
+ if (git(["fetch", "--depth=1", "--quiet", "origin", "HEAD"]) !== undefined) {
159
+ if (git(["rev-parse", "--verify", "--quiet", "FETCH_HEAD"]))
160
+ return "FETCH_HEAD";
161
+ }
162
+ return undefined;
163
+ };
164
+ export const readCanonicalFile = (repoDir, relPath, options = {}) => {
165
+ const git = (args) => execFileSync("git", args, {
166
+ cwd: repoDir,
167
+ encoding: "utf8",
168
+ stdio: ["ignore", "pipe", "pipe"],
169
+ timeout: 15_000,
170
+ // Never let git stop and ask for a password. Without this a credential-less
171
+ // fetch BLOCKS instead of failing, which reads as a hang rather than as the
172
+ // recoverable "remote unreachable" this function is designed to tolerate.
173
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "echo" },
174
+ });
175
+ // Best-effort refresh. A failure here is NOT fatal — an offline laptop and a
176
+ // CI runner that just checked the repo out both have a usable ref already —
177
+ // but whether it happened is reported rather than assumed.
178
+ let refreshed = "skipped";
179
+ if (options.fetch !== false) {
180
+ try {
181
+ git(["fetch", "--quiet", "origin"]);
182
+ refreshed = "fetched";
183
+ }
184
+ catch {
185
+ refreshed = "unreachable";
186
+ }
187
+ }
188
+ const ref = upstreamRefFor(repoDir);
189
+ if (!ref) {
190
+ throw new Error(`cannot determine the upstream ref for ${repoDir}, so there is no baseline to compare ` +
191
+ `against. Failing on purpose: an unverifiable baseline is not a clean one.`);
192
+ }
193
+ let text;
194
+ try {
195
+ text = git(["show", `${ref}:${relPath}`]);
196
+ }
197
+ catch (err) {
198
+ throw new Error(`cannot read ${relPath} at ${ref} in ${repoDir} (${err.message}). ` +
199
+ `Failing on purpose rather than falling back to the working tree, which is ` +
200
+ `${refreshed === "fetched" ? "" : "possibly "}stale and which nothing is allowed to pull.`);
201
+ }
202
+ const sha = git(["rev-parse", "--short", ref]).trim();
203
+ return { text, ref, sha, refreshed };
204
+ };
package/dist/index.d.ts CHANGED
@@ -2,7 +2,26 @@ import { writeScaffold } from "./writer.js";
2
2
  import type { AudienceGateReport } from "./writer.js";
3
3
  import type { ScaffoldFile } from "./scaffolders/common.js";
4
4
  import type { StandardDecision } from "./standards.js";
5
- export declare const version = "0.6.0";
5
+ /**
6
+ * This package's version, READ FROM `package.json` at load time rather than
7
+ * written here by hand.
8
+ *
9
+ * 🔴 It was a hand-maintained literal until 2026-09-19, and it had drifted to
10
+ * `0.6.0` while the package was `0.31.0` — twenty-five minor versions, and it
11
+ * was PUBLISHED that way, so `npx @zero2webmaster/starter-kit --version`
12
+ * answered `0.6.0` for months. Nothing could have caught it: the constant was
13
+ * internally consistent, every test that used it asserted against itself, and
14
+ * the version-bump checklist in CLAUDE.md greps for the OLD version string —
15
+ * which by then appeared nowhere near this line.
16
+ *
17
+ * Deriving it removes the class rather than the instance. `../package.json`
18
+ * resolves correctly from both `src/` (vitest) and `dist/` (the built CLI and
19
+ * the published tarball, where the layout is `package/dist/` + `package/package.json`).
20
+ * `src/index.test.ts` additionally asserts the two agree, so a packaging change
21
+ * that broke the path would fail loudly instead of silently reintroducing a
22
+ * stale literal.
23
+ */
24
+ export declare const version: string;
6
25
  export type ProjectType = "wp-plugin" | "cf-worker" | "cf-pages" | "nextjs" | "python-service" | "node-service" | "library" | "protocol-repo";
7
26
  export type BrandPreset = "save-the-frogs" | "bansuri-bliss" | "zero2webmaster" | "custom";
8
27
  /**
package/dist/index.js CHANGED
@@ -17,11 +17,31 @@
17
17
  // `resolveStandards`, `scaffoldByType`, `parseScaffoldInputs`, …) so consumers
18
18
  // import from the package root instead of deep-importing dist internals.
19
19
  //
20
+ import { createRequire } from "node:module";
20
21
  import * as path from "node:path";
21
22
  import { Writable } from "node:stream";
22
23
  import { isValidSlug } from "./parse-brief.js";
23
24
  import { writeScaffold } from "./writer.js";
24
- export const version = "0.6.0";
25
+ /**
26
+ * This package's version, READ FROM `package.json` at load time rather than
27
+ * written here by hand.
28
+ *
29
+ * 🔴 It was a hand-maintained literal until 2026-09-19, and it had drifted to
30
+ * `0.6.0` while the package was `0.31.0` — twenty-five minor versions, and it
31
+ * was PUBLISHED that way, so `npx @zero2webmaster/starter-kit --version`
32
+ * answered `0.6.0` for months. Nothing could have caught it: the constant was
33
+ * internally consistent, every test that used it asserted against itself, and
34
+ * the version-bump checklist in CLAUDE.md greps for the OLD version string —
35
+ * which by then appeared nowhere near this line.
36
+ *
37
+ * Deriving it removes the class rather than the instance. `../package.json`
38
+ * resolves correctly from both `src/` (vitest) and `dist/` (the built CLI and
39
+ * the published tarball, where the layout is `package/dist/` + `package/package.json`).
40
+ * `src/index.test.ts` additionally asserts the two agree, so a packaging change
41
+ * that broke the path would fail loudly instead of silently reintroducing a
42
+ * stale literal.
43
+ */
44
+ export const version = createRequire(import.meta.url)("../package.json").version;
25
45
  // Canonical enum value-arrays. These live here, next to the type unions they
26
46
  // enumerate, so both the CLI's confirm/wizard flows (which re-export them) and
27
47
  // the programmatic `validateScaffoldInputs` share one source of truth. Keep
@@ -5,6 +5,8 @@
5
5
  // Used by the writer (ROADMAP Step 6) which performs the actual filesystem
6
6
  // writes; pure-functional today so Step 4 tests can snapshot output without
7
7
  // any FS dependency.
8
+ import { version as cliVersion } from "../index.js";
9
+ import { descriptorFile } from "../descriptor.js";
8
10
  import { scaffoldCfPages } from "./cf-pages.js";
9
11
  import { scaffoldCfWorker } from "./cf-worker.js";
10
12
  import { scaffoldLibrary } from "./library.js";
@@ -38,5 +40,18 @@ export function scaffoldByType(inputs, opts) {
38
40
  "wp-plugin": scaffoldWpPlugin,
39
41
  "protocol-repo": scaffoldProtocolRepo,
40
42
  };
41
- return dispatch[inputs.projectType](inputs, opts);
43
+ const files = dispatch[inputs.projectType](inputs, opts);
44
+ // The machine-readable project descriptor, appended HERE rather than inside
45
+ // each per-type scaffolder, for two reasons that are both load-bearing:
46
+ //
47
+ // 1. ENROLMENT. Every type reaches this function, so a new project type
48
+ // cannot ship without a descriptor by forgetting to opt in. Emitting it
49
+ // per-type would repeat the capture-learnings enrolment bug — where the
50
+ // step was correct but 25 of 41 projects never got it.
51
+ // 2. DERIVATION. `descriptorFile` reads the COMPLETED file list to work out
52
+ // which tasks the project really provides. Inside a scaffolder the
53
+ // type-specific files (package.json above all) do not exist yet, so the
54
+ // derivation would silently see nothing and emit an empty `tasks` map.
55
+ files.push(descriptorFile(inputs, files, { date: opts?.date, cliVersion }));
56
+ return files;
42
57
  }
@@ -78,7 +78,7 @@ export interface StandardsResolution {
78
78
  * family — the safe default for anything else with `has_web_ui=true`.
79
79
  */
80
80
  export declare function fathomEnvVarFor(projectType: ProjectType): string;
81
- export declare const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.33";
81
+ export declare const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.34";
82
82
  /**
83
83
  * The canonical **Capture Learnings** block, emitted VERBATIM into every
84
84
  * scaffolded `CLAUDE.md`.
package/dist/standards.js CHANGED
@@ -475,7 +475,7 @@ const NEON_CAREFUL_BODY = `### Neon-careful (Neon Postgres)
475
475
  // Two consecutive handoffs compared this constant against the DOCUMENT version
476
476
  // and reported a "15-version gap" that did not exist — the real gap was 4. Read
477
477
  // the `<!-- ... canonical-block vX.Y.Z -->` comment, never the `**Version:**` line.
478
- export const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.33";
478
+ export const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.34";
479
479
  /**
480
480
  * The canonical **Capture Learnings** block, emitted VERBATIM into every
481
481
  * scaffolded `CLAUDE.md`.
@@ -606,6 +606,7 @@ This project participates in the Z2W cross-project coordination bulletin.
606
606
  - **Private repo only.** The bulletin must remain \`--visibility private\`.
607
607
  - **Never edit another project's file directly.** Cross-project signaling goes through \`[→ {their-project}]\` prefixes in the target's \`## Open questions\` section.
608
608
  - **Append-only within sections.** Trimming expired entries is a separate operation flagged in the commit message.
609
+ - **A worktree isolates your INDEX and WORKING TREE, and nothing else.** \`config\`, remotes, refs, hooks and the \`stash\` stack all belong to the REPOSITORY and are shared with the shared clone and every other worktree. So a throwaway worktree is not a disposable repo: \`git remote remove\`, \`git config\`, \`git branch -D\`, \`git stash\` and \`git gc\` reach the whole repository from inside it — one session disarmed a repo's \`origin\` this way (2026-09-18) and nothing in its output looked wrong. When you are finished, REMOVE the worktree; never tidy it with a command that writes to config, remotes, refs or the stash. And never move in-flight edits with \`git stash\` — \`refs/stash\` is one stack per repository, so a bare \`git stash pop\` takes whoever stashed last. Copy the files instead, or take your worktree at session START so there is nothing to move. [[shared-clone-concurrency]]
609
610
 
610
611
  Reference the protocol's conventions by NAME, never by §-number — the numbering renumbers upstream, and step 1b gives you the live text anyway.
611
612
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero2webmaster/starter-kit",
3
- "version": "0.30.0",
3
+ "version": "0.32.1",
4
4
  "description": "Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.",
5
5
  "author": {
6
6
  "name": "Dr. Kerry Kriger",
@@ -25,6 +25,7 @@
25
25
  "dist/**/*.js",
26
26
  "dist/**/*.d.ts",
27
27
  "scripts/rollup-integrations.mjs",
28
+ "scripts/check-descriptor.mjs",
28
29
  "README.md",
29
30
  "LICENSE"
30
31
  ],
@@ -38,7 +39,8 @@
38
39
  "start": "node dist/cli.js",
39
40
  "test": "vitest run",
40
41
  "test:watch": "vitest",
41
- "prepublishOnly": "npm run typecheck && npm run build"
42
+ "prepublishOnly": "npm run typecheck && npm run build",
43
+ "check:descriptor": "node scripts/check-descriptor.mjs"
42
44
  },
43
45
  "dependencies": {
44
46
  "@inquirer/prompts": "^7.0.0",
@@ -0,0 +1,308 @@
1
+ #!/usr/bin/env node
2
+ //
3
+ // Check — and optionally BACKFILL — a project's `z2w-project.json` descriptor.
4
+ //
5
+ // node scripts/check-descriptor.mjs <project-dir> [<project-dir> …]
6
+ // node scripts/check-descriptor.mjs --write <project-dir> # backfill/repair
7
+ // node scripts/check-descriptor.mjs --strict <project-dir> # non-zero on drift
8
+ //
9
+ // WHY THIS EXISTS. A descriptor is a CLAIM about a project, written once at
10
+ // scaffold time, and claims go stale. This ecosystem has measured exactly what
11
+ // happens when a generated artifact has no invalidation step: the coordination
12
+ // block hit **0 of 37 projects current**, with 15 of them eleven versions
13
+ // behind, and nobody could tell — every copy was internally consistent. A cache
14
+ // with no invalidation step is not a cache, it is a fork.
15
+ //
16
+ // So the descriptor ships with this checker from day one rather than acquiring
17
+ // one after the first drift incident. It re-derives what the descriptor SHOULD
18
+ // say from the project on disk and diffs it against what the descriptor DOES
19
+ // say.
20
+ //
21
+ // WHAT IT REFUSES TO DO. It never reports "ok" for a directory it could not
22
+ // read. A missing descriptor is `MISSING`, an unparseable one is `UNREADABLE`,
23
+ // and a directory that is not a project at all is `SKIPPED` — three distinct
24
+ // outcomes, none of which is silence. "I examined nothing" and "I examined
25
+ // everything and found nothing wrong" must never print the same line.
26
+ // [[zero-is-not-a-pass]]
27
+ //
28
+ // --write is the BACKFILL GENERATOR. The ~50 Live Z2W projects predate the
29
+ // descriptor, and emitting it only into NEW projects would repeat the
30
+ // capture-learnings enrolment bug — where the step was right and 25 of 41
31
+ // projects never received it. Point this at an existing repo and it writes a
32
+ // correct descriptor derived from that repo's real files.
33
+
34
+ import { readFileSync, writeFileSync, existsSync, readdirSync } from "node:fs";
35
+ import { join, basename, resolve } from "node:path";
36
+
37
+ const DESCRIPTOR_PATH = "z2w-project.json";
38
+ const DESCRIPTOR_VERSION = 1;
39
+
40
+ const VERB_SAFETY = {
41
+ typecheck: "read-only",
42
+ lint: "read-only",
43
+ build: "local-write",
44
+ test: "local-write",
45
+ dev: "local-write",
46
+ deploy: "remote-write",
47
+ migrate: "remote-write",
48
+ seed: "remote-write",
49
+ };
50
+
51
+ const NPM_SCRIPT_FOR_VERB = {
52
+ dev: ["dev"],
53
+ build: ["build"],
54
+ test: ["test"],
55
+ typecheck: ["typecheck"],
56
+ lint: ["lint"],
57
+ deploy: ["deploy"],
58
+ migrate: ["db:push", "migrate", "db:migrate"],
59
+ seed: ["db:seed", "seed"],
60
+ };
61
+
62
+ function readJson(path) {
63
+ try {
64
+ return { ok: true, value: JSON.parse(readFileSync(path, "utf8")) };
65
+ } catch (err) {
66
+ return { ok: false, error: err.message };
67
+ }
68
+ }
69
+
70
+ /** Derive the tasks a project REALLY provides, from its files on disk. */
71
+ function deriveTasks(dir) {
72
+ const pkgPath = join(dir, "package.json");
73
+ if (existsSync(pkgPath)) {
74
+ const parsed = readJson(pkgPath);
75
+ if (!parsed.ok) return { taskSource: "none", tasks: {} };
76
+ const scripts = parsed.value.scripts ?? {};
77
+ const tasks = {};
78
+ for (const [verb, candidates] of Object.entries(NPM_SCRIPT_FOR_VERB)) {
79
+ const hit = candidates.find((n) => typeof scripts[n] === "string");
80
+ if (!hit) continue;
81
+ tasks[verb] = {
82
+ command: hit === "test" ? "npm test" : `npm run ${hit}`,
83
+ safety: VERB_SAFETY[verb],
84
+ };
85
+ }
86
+ return { taskSource: "package.json-scripts", tasks };
87
+ }
88
+
89
+ if (existsSync(join(dir, "pyproject.toml"))) {
90
+ const tasks = {};
91
+ const srcDir = join(dir, "src");
92
+ if (existsSync(srcDir)) {
93
+ for (const entry of readdirSync(srcDir)) {
94
+ if (existsSync(join(srcDir, entry, "main.py"))) {
95
+ tasks.dev = {
96
+ command: `uvicorn ${entry}.main:app --reload`,
97
+ safety: VERB_SAFETY.dev,
98
+ };
99
+ break;
100
+ }
101
+ }
102
+ }
103
+ if (existsSync(join(dir, "tests"))) {
104
+ tasks.test = { command: "pytest", safety: VERB_SAFETY.test };
105
+ }
106
+ return { taskSource: "pyproject", tasks };
107
+ }
108
+
109
+ if (existsSync(join(dir, "_headers")) || existsSync(join(dir, "index.html"))) {
110
+ return {
111
+ taskSource: "static-site",
112
+ tasks: {
113
+ dev: { command: "npx wrangler pages dev .", safety: VERB_SAFETY.dev },
114
+ deploy: {
115
+ command: "npx wrangler pages deploy .",
116
+ safety: VERB_SAFETY.deploy,
117
+ },
118
+ },
119
+ };
120
+ }
121
+
122
+ return { taskSource: "none", tasks: {} };
123
+ }
124
+
125
+ /** Compare the descriptor's task claims against what the project really has. */
126
+ function findDrift(dir, descriptor) {
127
+ const problems = [];
128
+ const derived = deriveTasks(dir);
129
+
130
+ if (descriptor.descriptorVersion !== DESCRIPTOR_VERSION) {
131
+ problems.push(
132
+ `descriptorVersion is ${descriptor.descriptorVersion}, this checker knows version ${DESCRIPTOR_VERSION}`,
133
+ );
134
+ }
135
+
136
+ const claimed = descriptor.tasks ?? {};
137
+
138
+ // A claimed task whose command no longer exists is the failure that matters:
139
+ // a consumer runs it and gets an error, then stops trusting the whole file.
140
+ for (const [verb, t] of Object.entries(claimed)) {
141
+ if (!(verb in VERB_SAFETY)) {
142
+ problems.push(`task "${verb}" is not in the closed vocabulary`);
143
+ continue;
144
+ }
145
+ if (t.safety !== VERB_SAFETY[verb]) {
146
+ problems.push(
147
+ `task "${verb}" is labelled ${t.safety}, but the vocabulary says ${VERB_SAFETY[verb]}`,
148
+ );
149
+ }
150
+ const real = derived.tasks[verb];
151
+ if (!real) {
152
+ problems.push(
153
+ `task "${verb}" claims \`${t.command}\` but the project no longer provides it`,
154
+ );
155
+ } else if (real.command !== t.command) {
156
+ problems.push(
157
+ `task "${verb}" claims \`${t.command}\` but the project now provides \`${real.command}\``,
158
+ );
159
+ }
160
+ }
161
+
162
+ // A task the project gained since the descriptor was written. Lower severity
163
+ // — nothing breaks — but it is the signal that the file is drifting.
164
+ for (const verb of Object.keys(derived.tasks)) {
165
+ if (!(verb in claimed)) {
166
+ problems.push(
167
+ `the project provides "${verb}" (\`${derived.tasks[verb].command}\`) but the descriptor does not list it`,
168
+ );
169
+ }
170
+ }
171
+
172
+ if (descriptor.taskSource !== derived.taskSource) {
173
+ problems.push(
174
+ `taskSource says "${descriptor.taskSource}" but the project reads as "${derived.taskSource}"`,
175
+ );
176
+ }
177
+
178
+ return problems;
179
+ }
180
+
181
+ /** Build a complete descriptor for an EXISTING project — the backfill path. */
182
+ function backfill(dir, existing) {
183
+ const derived = deriveTasks(dir);
184
+ const name = basename(resolve(dir));
185
+ const pkg = readJson(join(dir, "package.json"));
186
+ const org = existing?.repo?.org ?? "zero2webmaster";
187
+ const slug = existing?.slug ?? name;
188
+
189
+ return {
190
+ descriptorVersion: DESCRIPTOR_VERSION,
191
+ slug,
192
+ description:
193
+ existing?.description ??
194
+ (pkg.ok ? (pkg.value.description ?? "") : ""),
195
+ projectType: existing?.projectType ?? null,
196
+ generatedBy: "scripts/check-descriptor.mjs --write",
197
+ generatedOn: new Date().toISOString().slice(0, 10),
198
+ stack: existing?.stack ?? {
199
+ runtime: existsSync(join(dir, "pyproject.toml"))
200
+ ? "python"
201
+ : pkg.ok
202
+ ? "node"
203
+ : "none",
204
+ database: existing?.stack?.database ?? "unknown",
205
+ hasWebUi: existing?.stack?.hasWebUi ?? false,
206
+ hasCron: existing?.stack?.hasCron ?? false,
207
+ },
208
+ repo: existing?.repo ?? {
209
+ host: "github",
210
+ org,
211
+ name: slug,
212
+ url: `https://github.com/${org}/${slug}`,
213
+ },
214
+ deploy: existing?.deploy ?? { target: null },
215
+ coordination: existing?.coordination ?? {
216
+ participates: false,
217
+ bulletinRepo: null,
218
+ bulletinFile: null,
219
+ agentIdentifier: null,
220
+ },
221
+ taskSource: derived.taskSource,
222
+ tasks: derived.tasks,
223
+ };
224
+ }
225
+
226
+ function main() {
227
+ const argv = process.argv.slice(2);
228
+ const write = argv.includes("--write");
229
+ const strict = argv.includes("--strict");
230
+ const dirs = argv.filter((a) => !a.startsWith("--"));
231
+
232
+ if (dirs.length === 0) {
233
+ console.error(
234
+ "usage: check-descriptor.mjs [--write] [--strict] <project-dir> [<project-dir> …]",
235
+ );
236
+ process.exit(2);
237
+ }
238
+
239
+ let examined = 0;
240
+ let ok = 0;
241
+ let drifted = 0;
242
+ let missing = 0;
243
+ let unreadable = 0;
244
+ let written = 0;
245
+
246
+ for (const dir of dirs) {
247
+ const path = join(dir, DESCRIPTOR_PATH);
248
+ const label = basename(resolve(dir));
249
+
250
+ if (!existsSync(dir)) {
251
+ console.log(`SKIPPED ${label} — not a directory`);
252
+ continue;
253
+ }
254
+ examined += 1;
255
+
256
+ if (!existsSync(path)) {
257
+ if (write) {
258
+ writeFileSync(path, `${JSON.stringify(backfill(dir, null), null, 2)}\n`);
259
+ console.log(`WROTE ${label} — descriptor created`);
260
+ written += 1;
261
+ } else {
262
+ console.log(`MISSING ${label} — no ${DESCRIPTOR_PATH}`);
263
+ missing += 1;
264
+ }
265
+ continue;
266
+ }
267
+
268
+ const parsed = readJson(path);
269
+ if (!parsed.ok) {
270
+ console.log(`UNREADABLE ${label} — ${parsed.error}`);
271
+ unreadable += 1;
272
+ continue;
273
+ }
274
+
275
+ const problems = findDrift(dir, parsed.value);
276
+ if (problems.length === 0) {
277
+ console.log(`OK ${label} — descriptor matches the project`);
278
+ ok += 1;
279
+ continue;
280
+ }
281
+
282
+ drifted += 1;
283
+ console.log(`DRIFT ${label}`);
284
+ for (const p of problems) console.log(` - ${p}`);
285
+ if (write) {
286
+ writeFileSync(
287
+ path,
288
+ `${JSON.stringify(backfill(dir, parsed.value), null, 2)}\n`,
289
+ );
290
+ console.log(` → rewritten`);
291
+ written += 1;
292
+ }
293
+ }
294
+
295
+ // Always print the denominator. "0 problems" is only meaningful next to the
296
+ // number of projects actually examined.
297
+ console.log(
298
+ `\nexamined: ${examined} ok: ${ok} drift: ${drifted} missing: ${missing} unreadable: ${unreadable} written: ${written}`,
299
+ );
300
+
301
+ if (examined === 0) {
302
+ console.error("\nRefusing to report a pass: nothing was examined.");
303
+ process.exit(2);
304
+ }
305
+ if (strict && (drifted > 0 || missing > 0 || unreadable > 0)) process.exit(1);
306
+ }
307
+
308
+ main();