@zero2webmaster/starter-kit 0.31.0 → 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.
@@ -0,0 +1,743 @@
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
+ // 🔴 EVERY FIELD THE BACKFILL WRITES IS EITHER MEASURED FROM DISK OR SAYS IT IS
35
+ // UNKNOWN — it never asserts a default. This is not a style preference. The
36
+ // first cut of this generator wrote `hasWebUi: false`, `hasCron: false` and
37
+ // `coordination.participates: false` for every project, having looked at
38
+ // nothing, because those are the falsy defaults of their types. Three of those
39
+ // would have been FLAT LIES about `leaderboard` alone, and a consumer cannot
40
+ // tell a measured `false` from an unexamined one. A boolean here is written
41
+ // only from a POSITIVE detection over the file tree; anything undeterminable is
42
+ // `null` or `"unknown"`, which a consumer can see and escalate.
43
+ // [[zero-is-not-a-pass]] [[unknown-means-denied]]
44
+
45
+ import { readFileSync, writeFileSync, existsSync, readdirSync, statSync } from "node:fs";
46
+ import { join, basename, resolve } from "node:path";
47
+ import { execFileSync } from "node:child_process";
48
+ import { pathToFileURL } from "node:url";
49
+
50
+ // ─────────────────────────── THE SHARED VOCABULARY ───────────────────────────
51
+ //
52
+ // These four tables are the SAME facts as `src/descriptor.ts`. They are spelled
53
+ // again here because this script is a plain `.mjs` that must run with no build
54
+ // step and no TypeScript loader — importing `dist/` would make the checker
55
+ // unusable in a repo whose `dist/` is stale or absent, which is precisely the
56
+ // repo most likely to need checking.
57
+ //
58
+ // 🔴 A second copy of a fact the repo already holds drifts silently, because
59
+ // each copy stays internally consistent — this project shipped `--version`
60
+ // reporting `0.6.0` for four months for exactly that reason. So the copy is
61
+ // PINNED: `src/check-descriptor.test.ts` imports both this module and
62
+ // `src/descriptor.ts` and fails the moment any of the four tables disagree.
63
+ // The duplication is deliberate; the silence is not.
64
+ export const DESCRIPTOR_PATH = "z2w-project.json";
65
+ export const DESCRIPTOR_VERSION = 1;
66
+
67
+ export const VERB_SAFETY = {
68
+ typecheck: "read-only",
69
+ lint: "read-only",
70
+ build: "local-write",
71
+ test: "local-write",
72
+ dev: "local-write",
73
+ deploy: "remote-write",
74
+ migrate: "remote-write",
75
+ seed: "remote-write",
76
+ };
77
+
78
+ export const NPM_SCRIPT_FOR_VERB = {
79
+ dev: ["dev"],
80
+ build: ["build"],
81
+ test: ["test"],
82
+ typecheck: ["typecheck"],
83
+ lint: ["lint"],
84
+ deploy: ["deploy"],
85
+ migrate: ["db:push", "migrate", "db:migrate"],
86
+ seed: ["db:seed", "seed"],
87
+ };
88
+
89
+ /** The closed project-type vocabulary, mirroring `ProjectType` in src/index.ts. */
90
+ export const PROJECT_TYPES = [
91
+ "wp-plugin",
92
+ "cf-worker",
93
+ "cf-pages",
94
+ "nextjs",
95
+ "python-service",
96
+ "node-service",
97
+ "library",
98
+ "protocol-repo",
99
+ ];
100
+
101
+ /** The closed database vocabulary, mirroring `DbStrategy` in src/index.ts. */
102
+ export const DB_STRATEGIES = [
103
+ "none",
104
+ "neon-postgres",
105
+ "supabase",
106
+ "sqlite",
107
+ "mysql-wp",
108
+ "other",
109
+ ];
110
+
111
+ function readJson(path) {
112
+ try {
113
+ return { ok: true, value: JSON.parse(readFileSync(path, "utf8")) };
114
+ } catch (err) {
115
+ return { ok: false, error: err.message };
116
+ }
117
+ }
118
+
119
+ function readTextOrNull(path) {
120
+ try {
121
+ return readFileSync(path, "utf8");
122
+ } catch {
123
+ return null;
124
+ }
125
+ }
126
+
127
+ function isDir(path) {
128
+ try {
129
+ return statSync(path).isDirectory();
130
+ } catch {
131
+ return false;
132
+ }
133
+ }
134
+
135
+ /** Every dependency name declared by a package.json, both prod and dev. */
136
+ function allDeps(pkg) {
137
+ if (!pkg.ok) return new Set();
138
+ const v = pkg.value;
139
+ return new Set([
140
+ ...Object.keys(v.dependencies ?? {}),
141
+ ...Object.keys(v.devDependencies ?? {}),
142
+ ]);
143
+ }
144
+
145
+ /** Derive the tasks a project REALLY provides, from its files on disk. */
146
+ export function deriveTasks(dir) {
147
+ const pkgPath = join(dir, "package.json");
148
+ if (existsSync(pkgPath)) {
149
+ const parsed = readJson(pkgPath);
150
+ if (!parsed.ok) return { taskSource: "none", tasks: {} };
151
+ const scripts = parsed.value.scripts ?? {};
152
+ const tasks = {};
153
+ for (const [verb, candidates] of Object.entries(NPM_SCRIPT_FOR_VERB)) {
154
+ const hit = candidates.find((n) => typeof scripts[n] === "string");
155
+ if (!hit) continue;
156
+ tasks[verb] = {
157
+ command: hit === "test" ? "npm test" : `npm run ${hit}`,
158
+ safety: VERB_SAFETY[verb],
159
+ };
160
+ }
161
+ return { taskSource: "package.json-scripts", tasks };
162
+ }
163
+
164
+ if (existsSync(join(dir, "pyproject.toml"))) {
165
+ const tasks = {};
166
+ const srcDir = join(dir, "src");
167
+ if (existsSync(srcDir)) {
168
+ for (const entry of readdirSync(srcDir)) {
169
+ if (existsSync(join(srcDir, entry, "main.py"))) {
170
+ tasks.dev = {
171
+ command: `uvicorn ${entry}.main:app --reload`,
172
+ safety: VERB_SAFETY.dev,
173
+ };
174
+ break;
175
+ }
176
+ }
177
+ }
178
+ if (existsSync(join(dir, "tests"))) {
179
+ tasks.test = { command: "pytest", safety: VERB_SAFETY.test };
180
+ }
181
+ return { taskSource: "pyproject", tasks };
182
+ }
183
+
184
+ if (existsSync(join(dir, "_headers")) || existsSync(join(dir, "index.html"))) {
185
+ return {
186
+ taskSource: "static-site",
187
+ tasks: {
188
+ dev: { command: "npx wrangler pages dev .", safety: VERB_SAFETY.dev },
189
+ deploy: {
190
+ command: "npx wrangler pages deploy .",
191
+ safety: VERB_SAFETY.deploy,
192
+ },
193
+ },
194
+ };
195
+ }
196
+
197
+ return { taskSource: "none", tasks: {} };
198
+ }
199
+
200
+ // ───────────────────────── THE BACKFILL DERIVATIONS ─────────────────────────
201
+ //
202
+ // Each returns a MEASURED value or an explicit unknown. None returns a default.
203
+
204
+ /** True when the directory holds a top-level PHP file with a WordPress plugin header. */
205
+ function looksLikeWpPlugin(dir) {
206
+ let entries;
207
+ try {
208
+ entries = readdirSync(dir);
209
+ } catch {
210
+ return false;
211
+ }
212
+ return entries
213
+ .filter((e) => e.endsWith(".php"))
214
+ .some((e) => (readTextOrNull(join(dir, e)) ?? "").includes("Plugin Name:"));
215
+ }
216
+
217
+ function hasWranglerConfig(dir) {
218
+ return ["wrangler.toml", "wrangler.jsonc", "wrangler.json"].some((f) =>
219
+ existsSync(join(dir, f)),
220
+ );
221
+ }
222
+
223
+ /**
224
+ * Infer the project type from the files on disk. `null` where the tree does not
225
+ * determine one — an honest answer a human can correct, unlike a wrong guess.
226
+ *
227
+ * Order matters: the checks run most-specific first, because several markers
228
+ * legitimately co-occur (a Next.js app may carry a Dockerfile; a Worker repo may
229
+ * carry an index.html for its docs).
230
+ */
231
+ export function detectProjectType(dir, pkg) {
232
+ const deps = allDeps(pkg);
233
+ if (deps.has("next")) return "nextjs";
234
+ if (hasWranglerConfig(dir)) {
235
+ // A Pages project and a Worker project both carry wrangler config. Pages is
236
+ // distinguished by `pages_build_output_dir` or a `pages:` script.
237
+ const cfg =
238
+ readTextOrNull(join(dir, "wrangler.toml")) ??
239
+ readTextOrNull(join(dir, "wrangler.jsonc")) ??
240
+ readTextOrNull(join(dir, "wrangler.json")) ??
241
+ "";
242
+ return cfg.includes("pages_build_output_dir") ? "cf-pages" : "cf-worker";
243
+ }
244
+ if (existsSync(join(dir, "pyproject.toml"))) return "python-service";
245
+ if (looksLikeWpPlugin(dir)) return "wp-plugin";
246
+ if (existsSync(join(dir, "AGENT_PROTOCOL.md"))) return "protocol-repo";
247
+ if (!pkg.ok && (existsSync(join(dir, "index.html")) || existsSync(join(dir, "_headers")))) {
248
+ return "cf-pages";
249
+ }
250
+ if (pkg.ok) {
251
+ if (pkg.value.bin) return "library";
252
+ // A server with no framework marker is a node-service; a package that only
253
+ // exports is a library. Neither is certain, so prefer the weaker claim.
254
+ if (pkg.value.exports || pkg.value.main) return "library";
255
+ return "node-service";
256
+ }
257
+ return null;
258
+ }
259
+
260
+ export function detectRuntime(dir, projectType, pkg) {
261
+ if (projectType === "python-service" || existsSync(join(dir, "pyproject.toml"))) {
262
+ return "python";
263
+ }
264
+ if (projectType === "wp-plugin") return "php";
265
+ if (projectType === "protocol-repo") return "none";
266
+ if (pkg.ok) return "node";
267
+ if (projectType === "cf-pages") return "static";
268
+ return "none";
269
+ }
270
+
271
+ /**
272
+ * Detect the database from declared dependencies and migration tooling.
273
+ * `"unknown"` when nothing on disk says — never `"none"`, which is a CLAIM that
274
+ * the project uses no database.
275
+ */
276
+ export function detectDatabase(dir, projectType, pkg) {
277
+ const deps = allDeps(pkg);
278
+ if (deps.has("@neondatabase/serverless") || existsSync(join(dir, ".neon"))) {
279
+ return "neon-postgres";
280
+ }
281
+ if (deps.has("@supabase/supabase-js")) return "supabase";
282
+ if (deps.has("better-sqlite3") || deps.has("sqlite3")) return "sqlite";
283
+ if (projectType === "wp-plugin") return "mysql-wp";
284
+ if (deps.has("pg") || deps.has("postgres") || deps.has("drizzle-orm")) {
285
+ // Postgres, but the host is not stated on disk. `other` is the vocabulary's
286
+ // honest bucket — it says "a database, not one of the named ones".
287
+ return "other";
288
+ }
289
+ if (existsSync(join(dir, "pyproject.toml"))) {
290
+ const py = readTextOrNull(join(dir, "pyproject.toml")) ?? "";
291
+ if (/psycopg|asyncpg|sqlalchemy/i.test(py)) return "other";
292
+ }
293
+ return "unknown";
294
+ }
295
+
296
+ /** A web UI is detected POSITIVELY — a router directory or a static entry page. */
297
+ export function detectHasWebUi(dir) {
298
+ for (const p of ["app", "src/app", "pages", "src/pages", "public/index.html", "index.html"]) {
299
+ const full = join(dir, p);
300
+ if (p.endsWith(".html") ? existsSync(full) : isDir(full)) return true;
301
+ }
302
+ return false;
303
+ }
304
+
305
+ /** A cron is detected POSITIVELY — a scheduled workflow or a Worker cron trigger. */
306
+ export function detectHasCron(dir) {
307
+ const wf = join(dir, ".github", "workflows");
308
+ if (isDir(wf)) {
309
+ for (const f of readdirSync(wf)) {
310
+ if (!/\.ya?ml$/.test(f)) continue;
311
+ const body = readTextOrNull(join(wf, f)) ?? "";
312
+ if (/^\s*schedule:/m.test(body)) return true;
313
+ }
314
+ }
315
+ for (const f of ["wrangler.toml", "wrangler.jsonc", "wrangler.json"]) {
316
+ const body = readTextOrNull(join(dir, f));
317
+ if (body && /crons/.test(body)) return true;
318
+ }
319
+ if (existsSync(join(dir, "vercel.json"))) {
320
+ const body = readTextOrNull(join(dir, "vercel.json")) ?? "";
321
+ if (/"crons"/.test(body)) return true;
322
+ }
323
+ return false;
324
+ }
325
+
326
+ /**
327
+ * Read the repo identity from git itself. Guessing `zero2webmaster/<foldername>`
328
+ * would be right most of the time and silently wrong for the rest — and a wrong
329
+ * repo URL in a machine-readable descriptor sends a consumer to someone else's
330
+ * repository. `null` when there is no origin to read.
331
+ */
332
+ export function detectRepo(dir) {
333
+ let url;
334
+ try {
335
+ url = execFileSync("git", ["-C", dir, "remote", "get-url", "origin"], {
336
+ encoding: "utf8",
337
+ stdio: ["ignore", "pipe", "ignore"],
338
+ }).trim();
339
+ } catch {
340
+ return null;
341
+ }
342
+ const m =
343
+ /^git@github\.com:(.+?)\/(.+?)(?:\.git)?$/.exec(url) ??
344
+ /^https:\/\/github\.com\/(.+?)\/(.+?)(?:\.git)?$/.exec(url) ??
345
+ /^ssh:\/\/git@github\.com\/(.+?)\/(.+?)(?:\.git)?$/.exec(url);
346
+ if (!m) return null;
347
+ return {
348
+ host: "github",
349
+ org: m[1],
350
+ name: m[2],
351
+ url: `https://github.com/${m[1]}/${m[2]}`,
352
+ };
353
+ }
354
+
355
+ /**
356
+ * The deploy target, from the deployment config present in the working copy.
357
+ *
358
+ * Note `.vercel/project.json` is normally GITIGNORED, so it is a signal only
359
+ * when this runs on a machine that has linked the project — which is exactly
360
+ * the backfill's situation and not a clone's. `vercel.json` is the committed
361
+ * signal. Both are checked; neither is inferred from the other.
362
+ */
363
+ export function detectDeployTarget(dir, projectType) {
364
+ if (existsSync(join(dir, ".vercel", "project.json")) || existsSync(join(dir, "vercel.json"))) {
365
+ return "vercel";
366
+ }
367
+ if (hasWranglerConfig(dir)) {
368
+ return projectType === "cf-pages" ? "cloudflare-pages" : "cloudflare-workers";
369
+ }
370
+ if (existsSync(join(dir, "netlify.toml"))) return "netlify";
371
+ if (existsSync(join(dir, "fly.toml"))) return "fly";
372
+ if (existsSync(join(dir, "render.yaml"))) return "render";
373
+ if (projectType === "nextjs") return "vercel";
374
+ if (existsSync(join(dir, "Dockerfile"))) return "container";
375
+ return null;
376
+ }
377
+
378
+ /**
379
+ * Whether the project participates in the coordination bulletin, read from its
380
+ * own CLAUDE.md. The agent identifier is taken from the canonical
381
+ * `**Agent identifier:** \`slug\`` line where present.
382
+ */
383
+ export function detectCoordination(dir, slug) {
384
+ const claude =
385
+ readTextOrNull(join(dir, "CLAUDE.md")) ?? readTextOrNull(join(dir, "AGENTS.md"));
386
+ if (claude === null) {
387
+ return {
388
+ participates: null,
389
+ bulletinRepo: null,
390
+ bulletinFile: null,
391
+ agentIdentifier: null,
392
+ };
393
+ }
394
+ if (!claude.includes("z2w-agent-coordination")) {
395
+ return {
396
+ participates: false,
397
+ bulletinRepo: null,
398
+ bulletinFile: null,
399
+ agentIdentifier: null,
400
+ };
401
+ }
402
+ const m = /\*\*Agent identifier:\*\*\s*`([^`]+)`/.exec(claude);
403
+ const id = m ? m[1] : slug;
404
+ return {
405
+ participates: true,
406
+ bulletinRepo: "zero2webmaster/z2w-agent-coordination",
407
+ bulletinFile: `projects/${id}.md`,
408
+ agentIdentifier: id,
409
+ };
410
+ }
411
+
412
+ /** A one-line description: package.json first, then the README's opening prose. */
413
+ export function detectDescription(dir, pkg) {
414
+ if (pkg.ok && typeof pkg.value.description === "string" && pkg.value.description.trim()) {
415
+ return pkg.value.description.trim();
416
+ }
417
+ const readme = readTextOrNull(join(dir, "README.md"));
418
+ if (readme === null) return "";
419
+ for (const raw of readme.split("\n")) {
420
+ const line = raw.trim();
421
+ if (!line) continue;
422
+ if (line.startsWith("#")) continue;
423
+ if (line.startsWith("!") || line.startsWith("[!")) continue; // badges
424
+ if (line.startsWith(">")) continue; // blockquote / callout
425
+ if (line.startsWith("|") || /^[-=*_]{3,}$/.test(line)) continue; // table, rule
426
+ if (line.startsWith("<")) continue; // raw HTML / comment
427
+ // A bolded `**Key:** value` header line is METADATA, not a description.
428
+ // Without this, projects whose README opens with a status/brand/version
429
+ // banner get a descriptor whose `description` reads "Brand:**
430
+ // Zero2Webmaster" — syntactically fine, semantically noise.
431
+ if (/^\*\*[^*]+:\*\*/.test(line)) continue;
432
+ if (/^\*\*[^*]+\*\*\s*[:|]/.test(line)) continue;
433
+ return line.replace(/^\*\*/, "").replace(/\*\*$/, "").slice(0, 300);
434
+ }
435
+ return "";
436
+ }
437
+
438
+ /** Compare the descriptor's task claims against what the project really has. */
439
+ function findDrift(dir, descriptor) {
440
+ const problems = [];
441
+ const derived = deriveTasks(dir);
442
+
443
+ if (descriptor.descriptorVersion !== DESCRIPTOR_VERSION) {
444
+ problems.push(
445
+ `descriptorVersion is ${descriptor.descriptorVersion}, this checker knows version ${DESCRIPTOR_VERSION}`,
446
+ );
447
+ }
448
+
449
+ const claimed = descriptor.tasks ?? {};
450
+
451
+ // A claimed task whose command no longer exists is the failure that matters:
452
+ // a consumer runs it and gets an error, then stops trusting the whole file.
453
+ for (const [verb, t] of Object.entries(claimed)) {
454
+ if (!(verb in VERB_SAFETY)) {
455
+ problems.push(`task "${verb}" is not in the closed vocabulary`);
456
+ continue;
457
+ }
458
+ if (t.safety !== VERB_SAFETY[verb]) {
459
+ problems.push(
460
+ `task "${verb}" is labelled ${t.safety}, but the vocabulary says ${VERB_SAFETY[verb]}`,
461
+ );
462
+ }
463
+ const real = derived.tasks[verb];
464
+ if (!real) {
465
+ problems.push(
466
+ `task "${verb}" claims \`${t.command}\` but the project no longer provides it`,
467
+ );
468
+ } else if (real.command !== t.command) {
469
+ problems.push(
470
+ `task "${verb}" claims \`${t.command}\` but the project now provides \`${real.command}\``,
471
+ );
472
+ }
473
+ }
474
+
475
+ // A task the project gained since the descriptor was written. Lower severity
476
+ // — nothing breaks — but it is the signal that the file is drifting.
477
+ for (const verb of Object.keys(derived.tasks)) {
478
+ if (!(verb in claimed)) {
479
+ problems.push(
480
+ `the project provides "${verb}" (\`${derived.tasks[verb].command}\`) but the descriptor does not list it`,
481
+ );
482
+ }
483
+ }
484
+
485
+ if (descriptor.taskSource !== derived.taskSource) {
486
+ problems.push(
487
+ `taskSource says "${descriptor.taskSource}" but the project reads as "${derived.taskSource}"`,
488
+ );
489
+ }
490
+
491
+ // 🔴 EVERYTHING EXCEPT `tasks` USED TO BE INVISIBLE HERE, and the blind spot was
492
+ // not theoretical. `ebooks` gained the `CLAUDE.md` it had never had; its
493
+ // descriptor went on claiming `coordination.participates: null`; and this
494
+ // function reported `OK` — because it only ever compared the tasks half. Six of
495
+ // the eight field groups could rot indefinitely while the checker said the file
496
+ // matched the project. A checker that examines two fields and reports on eight
497
+ // is the exact failure it was written to prevent. [[zero-is-not-a-pass]]
498
+ //
499
+ // Only fields the tree can still ANSWER are compared. Where a derivation comes
500
+ // back unmeasured, the recorded value is the only information there is, so its
501
+ // presence is not drift.
502
+ const pkg = readJson(join(dir, "package.json"));
503
+ const slug = descriptor.slug ?? basename(resolve(dir));
504
+ const projectType = descriptor.projectType ?? detectProjectType(dir, pkg);
505
+
506
+ // 🔴 AN ABSENT KEY IS NOT A WRONG VALUE, and conflating the two makes this
507
+ // check useless. A descriptor written by an older schema simply has no
508
+ // `stack.runtime`; reporting that as drift floods the report with rows nobody
509
+ // can act on, and a report nobody can act on gets ignored wholesale. But a key
510
+ // PRESENT and holding `null` — which is exactly what `ebooks` carried — is a
511
+ // claim, and a claim can be wrong. So presence is tested, never truthiness.
512
+ const has = (obj, key) =>
513
+ obj !== null && typeof obj === "object" && Object.prototype.hasOwnProperty.call(obj, key);
514
+
515
+ // ONLY the authoritative fields appear here. A disagreement on an inferred
516
+ // field (`projectType`, `database`, `deploy.target`) is not drift — it is
517
+ // usually a human having corrected a guess, and reporting it as drift would
518
+ // train people to stop correcting the file.
519
+ const comparisons = [
520
+ ["stack.hasWebUi", has(descriptor.stack, "hasWebUi"), descriptor.stack?.hasWebUi, detectHasWebUi(dir)],
521
+ ["stack.hasCron", has(descriptor.stack, "hasCron"), descriptor.stack?.hasCron, detectHasCron(dir)],
522
+ [
523
+ "coordination.participates",
524
+ has(descriptor.coordination, "participates"),
525
+ descriptor.coordination?.participates,
526
+ detectCoordination(dir, slug).participates,
527
+ ],
528
+ ["repo.url", has(descriptor.repo, "url"), descriptor.repo?.url, detectRepo(dir)?.url ?? null],
529
+ ];
530
+
531
+ for (const [field, claimed_present, claimed, real] of comparisons) {
532
+ if (!claimed_present) continue;
533
+ // The derivation could not answer, so the recorded value is the only
534
+ // information there is. Its presence is not drift.
535
+ if (isUnmeasured(real)) continue;
536
+ // A recorded value the tree cannot currently corroborate stands too — only a
537
+ // DISAGREEMENT between two known values is drift.
538
+ if (claimed === real) continue;
539
+ problems.push(
540
+ `${field} says ${JSON.stringify(claimed ?? null)} but the project now reads as ${JSON.stringify(real)}`,
541
+ );
542
+ }
543
+
544
+ return problems;
545
+ }
546
+
547
+ /**
548
+ * Is this value the derivation's way of saying "I could not tell"?
549
+ *
550
+ * `null` and `"unknown"` are the two shapes an undeterminable field takes. They
551
+ * are NOT data, so they must never beat a value someone recorded by hand.
552
+ */
553
+ function isUnmeasured(v) {
554
+ return v === null || v === undefined || v === "unknown";
555
+ }
556
+
557
+ /**
558
+ * ─────────── WHICH WINS: THE FILE TREE, OR THE VALUE SOMEONE RECORDED? ───────────
559
+ *
560
+ * The answer is NOT "whichever is newer", and it is not uniform across fields. It
561
+ * depends on whether the detector for that field MEASURES something or GUESSES.
562
+ *
563
+ * **AUTHORITATIVE detectors read a fact that exists in the tree and nowhere else.**
564
+ * `hasCron` is a scheduled workflow being present. `participates` is the project's
565
+ * own `CLAUDE.md` naming the bulletin. `repo.url` is what `git remote` says. For
566
+ * these the tree is simply the truth, a recorded value that disagrees is STALE,
567
+ * and re-deriving is the entire point of having a checker.
568
+ *
569
+ * **BEST-GUESS detectors infer from circumstantial evidence and say so.**
570
+ * `detectProjectType`'s own comment reads *"Neither is certain, so prefer the
571
+ * weaker claim"* before returning `node-service`. Letting that overwrite a human's
572
+ * `"library"` would be a guess silently deleting knowledge — and worse, it would
573
+ * break the promise that editing the file by hand sticks, which is the only reason
574
+ * anyone would correct it.
575
+ *
576
+ * 🔴 Both halves matter, and the first draft of this rule got it half right. It
577
+ * said "a measurement beats a stale record" and applied that to EVERY field, which
578
+ * fixed the real `ebooks` bug (a descriptor frozen at `participates: null` while the
579
+ * project had since gained its `CLAUDE.md`) and simultaneously introduced a new one:
580
+ * a hand-set `projectType` being reverted by a fallback branch. A generator gets to
581
+ * override a person only where it actually KNOWS better.
582
+ */
583
+
584
+ /** Fields whose detector reads a fact, not a hint. The tree wins; drift is real. */
585
+ function authoritative(existing, derived) {
586
+ if (!isUnmeasured(derived)) return derived;
587
+ return isUnmeasured(existing) ? derived : existing;
588
+ }
589
+
590
+ /** Fields whose detector infers. A recorded value wins; only fill a blank. */
591
+ function bestGuess(existing, derived) {
592
+ return isUnmeasured(existing) ? derived : existing;
593
+ }
594
+
595
+ /**
596
+ * Build a complete descriptor for an EXISTING project — the backfill path.
597
+ *
598
+ * Derivable fields are RE-DERIVED on every write (see {@link preferMeasured}).
599
+ * A human-authored value survives only where the tree genuinely cannot answer —
600
+ * `description` and `deploy.target` being the usual cases — so editing the file
601
+ * by hand still works for the fields where a person knows more than the files do.
602
+ */
603
+ export function backfill(dir, existing) {
604
+ const derived = deriveTasks(dir);
605
+ const name = basename(resolve(dir));
606
+ const pkg = readJson(join(dir, "package.json"));
607
+ const slug = existing?.slug ?? name;
608
+
609
+ // projectType is INFERRED (its detector has an explicit "neither is certain"
610
+ // fallback), so a recorded value stands. repo comes from `git remote`, which is
611
+ // a fact, so the tree wins.
612
+ const projectType = bestGuess(existing?.projectType, detectProjectType(dir, pkg));
613
+ const repo = authoritative(existing?.repo, detectRepo(dir));
614
+ const derivedCoord = detectCoordination(dir, slug);
615
+ // `participates` is the field that decides whether the whole coordination
616
+ // object is meaningful, so the object is taken as a unit on that field.
617
+ const coordination = isUnmeasured(derivedCoord.participates)
618
+ ? (existing?.coordination ?? derivedCoord)
619
+ : derivedCoord;
620
+
621
+ return {
622
+ descriptorVersion: DESCRIPTOR_VERSION,
623
+ slug,
624
+ // Description is the one field a person reliably knows better than the files,
625
+ // so a recorded non-empty value is kept even when a README exists.
626
+ description: existing?.description || detectDescription(dir, pkg),
627
+ projectType,
628
+ generatedBy: "scripts/check-descriptor.mjs --write",
629
+ generatedOn: new Date().toISOString().slice(0, 10),
630
+ // Says plainly that this descriptor was reverse-engineered from an existing
631
+ // repo rather than emitted at scaffold time from authoritative inputs. A
632
+ // consumer that needs certainty can treat it as lower-confidence; without
633
+ // this flag the two are indistinguishable.
634
+ backfilled: existing?.backfilled ?? true,
635
+ stack: {
636
+ // runtime is derived FROM projectType, so it inherits that field's
637
+ // uncertainty. database is read from declared dependencies, which is
638
+ // circumstantial — a dependency is not a connection.
639
+ runtime: bestGuess(existing?.stack?.runtime, detectRuntime(dir, projectType, pkg)),
640
+ database: bestGuess(existing?.stack?.database, detectDatabase(dir, projectType, pkg)),
641
+ // Booleans are positive detections over the tree, so they are always
642
+ // re-measured — a project that gained a cron must stop saying it has none.
643
+ hasWebUi: detectHasWebUi(dir),
644
+ hasCron: detectHasCron(dir),
645
+ },
646
+ repo,
647
+ // A deploy target can be real and have no config file in the repo (a host
648
+ // configured entirely in a dashboard), so a recorded value is never overruled.
649
+ deploy: {
650
+ target: bestGuess(existing?.deploy?.target, detectDeployTarget(dir, projectType)),
651
+ },
652
+ coordination,
653
+ taskSource: derived.taskSource,
654
+ tasks: derived.tasks,
655
+ };
656
+ }
657
+
658
+ export function main(argv = process.argv.slice(2)) {
659
+ const write = argv.includes("--write");
660
+ const strict = argv.includes("--strict");
661
+ const dirs = argv.filter((a) => !a.startsWith("--"));
662
+
663
+ if (dirs.length === 0) {
664
+ console.error(
665
+ "usage: check-descriptor.mjs [--write] [--strict] <project-dir> [<project-dir> …]",
666
+ );
667
+ process.exit(2);
668
+ }
669
+
670
+ let examined = 0;
671
+ let ok = 0;
672
+ let drifted = 0;
673
+ let missing = 0;
674
+ let unreadable = 0;
675
+ let written = 0;
676
+
677
+ for (const dir of dirs) {
678
+ const path = join(dir, DESCRIPTOR_PATH);
679
+ const label = basename(resolve(dir));
680
+
681
+ if (!existsSync(dir)) {
682
+ console.log(`SKIPPED ${label} — not a directory`);
683
+ continue;
684
+ }
685
+ examined += 1;
686
+
687
+ if (!existsSync(path)) {
688
+ if (write) {
689
+ writeFileSync(path, `${JSON.stringify(backfill(dir, null), null, 2)}\n`);
690
+ console.log(`WROTE ${label} — descriptor created`);
691
+ written += 1;
692
+ } else {
693
+ console.log(`MISSING ${label} — no ${DESCRIPTOR_PATH}`);
694
+ missing += 1;
695
+ }
696
+ continue;
697
+ }
698
+
699
+ const parsed = readJson(path);
700
+ if (!parsed.ok) {
701
+ console.log(`UNREADABLE ${label} — ${parsed.error}`);
702
+ unreadable += 1;
703
+ continue;
704
+ }
705
+
706
+ const problems = findDrift(dir, parsed.value);
707
+ if (problems.length === 0) {
708
+ console.log(`OK ${label} — descriptor matches the project`);
709
+ ok += 1;
710
+ continue;
711
+ }
712
+
713
+ drifted += 1;
714
+ console.log(`DRIFT ${label}`);
715
+ for (const p of problems) console.log(` - ${p}`);
716
+ if (write) {
717
+ writeFileSync(
718
+ path,
719
+ `${JSON.stringify(backfill(dir, parsed.value), null, 2)}\n`,
720
+ );
721
+ console.log(` → rewritten`);
722
+ written += 1;
723
+ }
724
+ }
725
+
726
+ // Always print the denominator. "0 problems" is only meaningful next to the
727
+ // number of projects actually examined.
728
+ console.log(
729
+ `\nexamined: ${examined} ok: ${ok} drift: ${drifted} missing: ${missing} unreadable: ${unreadable} written: ${written}`,
730
+ );
731
+
732
+ if (examined === 0) {
733
+ console.error("\nRefusing to report a pass: nothing was examined.");
734
+ process.exit(2);
735
+ }
736
+ if (strict && (drifted > 0 || missing > 0 || unreadable > 0)) process.exit(1);
737
+ }
738
+
739
+ // Run only when invoked as a command. Importable as a module so the test suite
740
+ // can pin the shared vocabulary tables against `src/descriptor.ts`.
741
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
742
+ main();
743
+ }