@marktiderman/genesis-cli 1.23.0 → 1.25.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/dist/cli.js CHANGED
@@ -1029,6 +1029,7 @@ var init_migrations = __esm({
1029
1029
  var config_exports = {};
1030
1030
  __export(config_exports, {
1031
1031
  DoctorConfigError: () => DoctorConfigError,
1032
+ EXTENSION_REASON_MIN: () => EXTENSION_REASON_MIN,
1032
1033
  GenesisConfigError: () => GenesisConfigError,
1033
1034
  META_RULES: () => META_RULES,
1034
1035
  PRIVACY_DATA_TYPES: () => PRIVACY_DATA_TYPES,
@@ -1042,6 +1043,7 @@ __export(config_exports, {
1042
1043
  readGenesisConfig: () => readGenesisConfig,
1043
1044
  validateAppFolder: () => validateAppFolder,
1044
1045
  validateConfig: () => validateConfig,
1046
+ validateEnvironments: () => validateEnvironments,
1045
1047
  validateLinks: () => validateLinks,
1046
1048
  validatePrivacy: () => validatePrivacy,
1047
1049
  validateSupabase: () => validateSupabase
@@ -1049,6 +1051,24 @@ __export(config_exports, {
1049
1051
  function privacyDataType(type) {
1050
1052
  return PRIVACY_DATA_TYPES[type.toLowerCase()];
1051
1053
  }
1054
+ function validateEnvironments(raw, source = "config") {
1055
+ const fail = (msg) => {
1056
+ throw new GenesisConfigError(`${source}: ${msg}`);
1057
+ };
1058
+ if (!isObject2(raw)) return fail(`"environments" must be an object`);
1059
+ for (const key2 of Object.keys(raw)) if (!ENVIRONMENT_KEYS.has(key2)) fail(`environments: unknown setting "${key2}" (known: previews, label, branchPrefix)`);
1060
+ const out = {};
1061
+ if (raw.previews !== void 0) {
1062
+ if (raw.previews !== "on-demand" && raw.previews !== "every-pr" && raw.previews !== "off") fail(`environments.previews must be "on-demand", "every-pr" or "off" (got ${JSON.stringify(raw.previews)})`);
1063
+ out.previews = raw.previews;
1064
+ }
1065
+ for (const key2 of ["label", "branchPrefix"]) {
1066
+ if (raw[key2] === void 0) continue;
1067
+ if (typeof raw[key2] !== "string") fail(`environments.${key2} must be a string ("" turns that check off)`);
1068
+ out[key2] = raw[key2];
1069
+ }
1070
+ return out;
1071
+ }
1052
1072
  function appPath2(v, where2, fail) {
1053
1073
  if (typeof v !== "string" || !v.trim()) return fail(`${where2} must be a non-empty path`);
1054
1074
  if (path30.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
@@ -1107,6 +1127,7 @@ function readGenesisConfig(root) {
1107
1127
  if (supabase !== true) out.supabase = supabase;
1108
1128
  }
1109
1129
  if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
1130
+ if (raw.environments !== void 0) out.environments = validateEnvironments(raw.environments, file);
1110
1131
  return out;
1111
1132
  }
1112
1133
  function isPlainFolder(value) {
@@ -1244,6 +1265,30 @@ function validateConfig(raw, source = "config") {
1244
1265
  }
1245
1266
  });
1246
1267
  }
1268
+ if (c.extend !== void 0) {
1269
+ if (!Array.isArray(c.extend)) fail(`"extend" must be a list of { rule, file, buildsOn, reason, upstream? }`);
1270
+ const seen = /* @__PURE__ */ new Set();
1271
+ c.extend.forEach((e, i) => {
1272
+ const where2 = `extend[${i}]`;
1273
+ if (!isObject2(e)) return fail(`${where2} must be an object`);
1274
+ for (const k of Object.keys(e)) if (!EXTENSION_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: ${[...EXTENSION_KEYS].join(", ")})`);
1275
+ for (const k of ["rule", "file", "buildsOn", "reason"]) if (typeof e[k] !== "string" || !e[k].trim()) fail(`${where2} needs "${k}"`);
1276
+ const { rule, file, buildsOn, reason } = e;
1277
+ if (META_RULES.has(rule) || CONFIG_RULES.has(rule)) fail(`${where2} can't extend ${rule}: it is about the config, not the app's code`);
1278
+ if (!rule.includes("/")) fail(`${where2} can't extend ${rule}: only package rules declare extension points (a built-in rule's findings are fixed, or recorded as allow debt)`);
1279
+ if (/[*?[\]{}]/.test(file)) fail(`${where2}.file must be one file, not a glob: each extension is reviewed on its own`);
1280
+ e.file = appPath2(file, `${where2}.file`, fail);
1281
+ if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(buildsOn)) fail(`${where2}.buildsOn must name a Genesis export, or a part of one ("FormBuilder", "ResourceView.slots")`);
1282
+ const text = reason.trim();
1283
+ if (text.length < EXTENSION_REASON_MIN.chars || text.split(/\s+/).length < EXTENSION_REASON_MIN.words) {
1284
+ fail(`${where2} (${rule}) needs a reason of at least ${EXTENSION_REASON_MIN.words} words and ${EXTENSION_REASON_MIN.chars} characters: why the rule's primitive doesn't fit this file`);
1285
+ }
1286
+ if (e.upstream !== void 0 && (typeof e.upstream !== "string" || !e.upstream.trim())) fail(`${where2}.upstream must be a link to the gap's write-up`);
1287
+ const key2 = `${rule}\0${e.file}`;
1288
+ if (seen.has(key2)) fail(`${where2} extends ${rule} in ${e.file} twice`);
1289
+ seen.add(key2);
1290
+ });
1291
+ }
1247
1292
  if (c.patterns !== void 0) {
1248
1293
  if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
1249
1294
  c.patterns.forEach((p, i) => {
@@ -1300,6 +1345,7 @@ function validateConfig(raw, source = "config") {
1300
1345
  if (!want) fail(`${pack}: unknown setting "${k}"`);
1301
1346
  if (want === "string" && typeof v !== "string") fail(`${pack}.${k} must be a string`);
1302
1347
  if (want === "list" && !isStringList(v)) fail(`${pack}.${k} must be a list of strings`);
1348
+ if (want === "boolean" && typeof v !== "boolean") fail(`${pack}.${k} must be true or false`);
1303
1349
  if (want === "string" && !v.trim()) fail(`${pack}.${k} must not be empty`);
1304
1350
  if (want === "path") block[k] = appPath2(v, `${pack}.${k}`, fail);
1305
1351
  }
@@ -1325,7 +1371,7 @@ function isObject2(v) {
1325
1371
  function isStringList(v) {
1326
1372
  return Array.isArray(v) && v.every((x) => typeof x === "string");
1327
1373
  }
1328
- var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, STRING_LISTS, STRINGS, KNOWN, LEVELS, META_RULES, PATTERN_KEYS, PACKAGE_RULE_KEYS, CONTRACT_KEYS, PACKS, PACK_KEYS, PLAIN_FOLDER, PRIVACY_KEYS, DATA_USE_KEYS, LINK_KEYS, HOST;
1374
+ var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, ENVIRONMENT_KEYS, STRING_LISTS, STRINGS, KNOWN, LEVELS, META_RULES, CONFIG_RULES, EXTENSION_KEYS, EXTENSION_REASON_MIN, PATTERN_KEYS, PACKAGE_RULE_KEYS, CONTRACT_KEYS, PACKS, PACK_KEYS, PLAIN_FOLDER, PRIVACY_KEYS, DATA_USE_KEYS, LINK_KEYS, HOST;
1329
1375
  var init_config = __esm({
1330
1376
  "src/doctor/config.ts"() {
1331
1377
  GenesisConfigError = class extends Error {
@@ -1379,6 +1425,7 @@ var init_config = __esm({
1379
1425
  "third-party advertising": "NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising",
1380
1426
  other: "NSPrivacyCollectedDataTypePurposeOther"
1381
1427
  };
1428
+ ENVIRONMENT_KEYS = /* @__PURE__ */ new Set(["previews", "label", "branchPrefix", "$comment"]);
1382
1429
  STRING_LISTS = ["src", "extensions", "ignore", "tokenFiles", "ignoreTokenPrefixes", "localPrimitiveDirs", "build", "componentPackages"];
1383
1430
  STRINGS = ["uiPackage", "rulesDoc"];
1384
1431
  KNOWN = /* @__PURE__ */ new Set([
@@ -1389,6 +1436,7 @@ var init_config = __esm({
1389
1436
  "forbiddenImports",
1390
1437
  "rules",
1391
1438
  "allow",
1439
+ "extend",
1392
1440
  "patterns",
1393
1441
  "plugins",
1394
1442
  "packs",
@@ -1403,14 +1451,17 @@ var init_config = __esm({
1403
1451
  "$comment"
1404
1452
  ]);
1405
1453
  LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
1406
- META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
1454
+ META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped", "extension-invalid"]);
1455
+ CONFIG_RULES = /* @__PURE__ */ new Set(["stale-exception", "stale-extension", "package-rule-override"]);
1456
+ EXTENSION_KEYS = /* @__PURE__ */ new Set(["rule", "file", "buildsOn", "reason", "upstream"]);
1457
+ EXTENSION_REASON_MIN = { chars: 40, words: 6 };
1407
1458
  PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
1408
1459
  PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
1409
1460
  CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
1410
1461
  PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
1411
1462
  PACK_KEYS = {
1412
1463
  native: { routerRoot: "path" },
1413
- supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
1464
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string", automaticBranching: "boolean" },
1414
1465
  packages: { base: "string" }
1415
1466
  };
1416
1467
  PLAIN_FOLDER = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}){0,7}$/;
@@ -2023,7 +2074,7 @@ function globToRegExp(glob) {
2023
2074
  }
2024
2075
  function globMatcher(globs) {
2025
2076
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
2026
- return (path61) => res.some((re) => re.test(path61));
2077
+ return (path62) => res.some((re) => re.test(path62));
2027
2078
  }
2028
2079
  var init_glob = __esm({
2029
2080
  "src/doctor/glob.ts"() {
@@ -2068,6 +2119,9 @@ function scanFiles(root, config) {
2068
2119
  for (const pkg of local) walk4(pkg.dir);
2069
2120
  return files;
2070
2121
  }
2122
+ function withText(file, text) {
2123
+ return { ...file, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(file.ext)) };
2124
+ }
2071
2125
  function lineAt(text, index) {
2072
2126
  let line = 1;
2073
2127
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
@@ -4202,6 +4256,7 @@ var init_rules = __esm({
4202
4256
  "migration-edited",
4203
4257
  "migration-testing-kit",
4204
4258
  "migration-view-rls",
4259
+ "exposed-schema-created-later",
4205
4260
  // packages pack
4206
4261
  "package-app-import",
4207
4262
  "package-undeclared-dependency",
@@ -4227,6 +4282,10 @@ var init_rules = __esm({
4227
4282
  "ratchet-skipped",
4228
4283
  "allow-grew",
4229
4284
  "rules-weakened",
4285
+ "extension-added",
4286
+ // declared extensions (extensions.ts)
4287
+ "stale-extension",
4288
+ "extension-invalid",
4230
4289
  // agent guide (primitives.ts)
4231
4290
  "agent-guide-stale",
4232
4291
  // supabase pack: contracts (contracts.ts)
@@ -4359,6 +4418,33 @@ function readSource(abs) {
4359
4418
  return null;
4360
4419
  }
4361
4420
  }
4421
+ function blankStrings(code) {
4422
+ if (lastBlanked?.source === code) return lastBlanked.blanked;
4423
+ const out = code.split("");
4424
+ for (let i = 0; i < code.length; i++) {
4425
+ const ch = code[i];
4426
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
4427
+ let j = i - 1;
4428
+ while (j >= 0 && /[ \t]/.test(code[j])) j--;
4429
+ const before = j >= 0 ? code[j] : "\n";
4430
+ const word = /[\w$]/.test(before) ? /(?:^|[^\w$])(return|case|typeof|in|of|yield|await)$/.test(code.slice(Math.max(0, j - 8), j + 1)) : false;
4431
+ if (/[\w$)\]]/.test(before) && !word) continue;
4432
+ let k = i + 1;
4433
+ for (; k < code.length; k++) {
4434
+ const c = code[k];
4435
+ if (c === "\\") {
4436
+ k++;
4437
+ continue;
4438
+ }
4439
+ if (c === ch) break;
4440
+ if (c === "\n" && ch !== "`") break;
4441
+ }
4442
+ for (let x = i + 1; x < k && x < code.length; x++) if (code[x] !== "\n") out[x] = " ";
4443
+ i = k;
4444
+ }
4445
+ lastBlanked = { source: code, blanked: out.join("") };
4446
+ return lastBlanked.blanked;
4447
+ }
4362
4448
  function tagEnd(code, start) {
4363
4449
  let depth = 0;
4364
4450
  let quote2 = null;
@@ -4380,7 +4466,8 @@ function tagEnd(code, start) {
4380
4466
  }
4381
4467
  return { end: code.length, selfClosing: false };
4382
4468
  }
4383
- function openElementsAt(code, index, track) {
4469
+ function openElementsAt(source, index, track) {
4470
+ const code = blankStrings(source);
4384
4471
  const open = [];
4385
4472
  const re = /<(\/?)([A-Z][\w.]*)(?=[\s>/])/g;
4386
4473
  for (let m = re.exec(code); m && m.index < index; m = re.exec(code)) {
@@ -4419,12 +4506,13 @@ function namedImportsFrom(code, pkg) {
4419
4506
  }
4420
4507
  return out;
4421
4508
  }
4422
- var SCRIPT_EXTS2, JSX_EXTS2, RESOLVE_EXTS;
4509
+ var SCRIPT_EXTS2, JSX_EXTS2, RESOLVE_EXTS, lastBlanked;
4423
4510
  var init_source = __esm({
4424
4511
  "src/doctor/source.ts"() {
4425
4512
  SCRIPT_EXTS2 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
4426
4513
  JSX_EXTS2 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
4427
4514
  RESOLVE_EXTS = [".tsx", ".ts", ".jsx", ".js"];
4515
+ lastBlanked = null;
4428
4516
  }
4429
4517
  });
4430
4518
  function nativePackage(ctx) {
@@ -5360,6 +5448,9 @@ function validatePrefer(raw, where2, fail, unknownKey) {
5360
5448
  if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
5361
5449
  if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
5362
5450
  for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
5451
+ if (raw.extensible !== void 0 && !(isStringList2(raw.extensible) && raw.extensible.every((n) => /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)))) {
5452
+ fail(`${at}.extensible must be a list of export names, or parts of one ("ResourceView.slots")`);
5453
+ }
5363
5454
  if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
5364
5455
  const forbid = raw.forbid;
5365
5456
  for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
@@ -5372,6 +5463,7 @@ function validatePrefer(raw, where2, fail, unknownKey) {
5372
5463
  const unless = raw.unless;
5373
5464
  for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
5374
5465
  if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
5466
+ if (unless.inside !== void 0 && !(isStringList2(unless.inside) && unless.inside.every((n) => /^[A-Z][\w.]*$/.test(n)))) fail(`${at}.unless.inside must be a list of component names`);
5375
5467
  if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
5376
5468
  }
5377
5469
  return raw;
@@ -5487,6 +5579,7 @@ function compile(rule, setting, routes) {
5487
5579
  imports: (rule.forbid.imports ?? []).map(specMatcher),
5488
5580
  ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
5489
5581
  unlessRenders: new Set(rule.unless?.renders ?? []),
5582
+ unlessInside: new Set(rule.unless?.inside ?? []),
5490
5583
  ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
5491
5584
  };
5492
5585
  }
@@ -5495,7 +5588,7 @@ function messageFor(rule, found) {
5495
5588
  const docs = rule.docs ? ` See ${rule.docs}` : "";
5496
5589
  return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
5497
5590
  }
5498
- function wrappersIn(file, elements, c) {
5591
+ function wrappersIn(file, elements, names, accept) {
5499
5592
  const out = /* @__PURE__ */ new Map();
5500
5593
  const decls = [...file.code.matchAll(TOP_LEVEL)];
5501
5594
  const listed = /* @__PURE__ */ new Map();
@@ -5508,12 +5601,12 @@ function wrappersIn(file, elements, c) {
5508
5601
  for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
5509
5602
  decls.forEach((d, i) => {
5510
5603
  const name = d[3];
5511
- if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
5604
+ if (!/^[A-Z]/.test(name) || names.has(name)) return;
5512
5605
  const end = decls[i + 1]?.index ?? file.code.length;
5513
- const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
5514
- if (!hit) return;
5515
- const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
5516
- for (const n of names) out.set(n, hit[1]);
5606
+ const hit = elements.find((m) => m.index > d.index && m.index < end && names.has(m[1]));
5607
+ if (!hit || accept && !accept(d.index, end)) return;
5608
+ const exported = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
5609
+ for (const n of exported) out.set(n, hit[1]);
5517
5610
  });
5518
5611
  return out;
5519
5612
  }
@@ -5521,6 +5614,32 @@ function runPrefer(ctx, c) {
5521
5614
  const own = c.rule.packageDir;
5522
5615
  const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
5523
5616
  const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
5617
+ const scanned = new Map(ctx.files.map((f) => [f.absolutePath, f]));
5618
+ const importedBy = /* @__PURE__ */ new Map();
5619
+ const importsOf = (file) => {
5620
+ if (!importedBy.has(file)) importedBy.set(file, localImportedNames(ctx.root, file));
5621
+ return importedBy.get(file);
5622
+ };
5623
+ const builders = /* @__PURE__ */ new Map();
5624
+ const buildersIn = (abs) => {
5625
+ if (!builders.has(abs)) {
5626
+ const target = scanned.get(abs) ?? readSource(abs);
5627
+ const code = target ? "ext" in target ? target.code : stripBlockComments(target.code, true) : "";
5628
+ const childrenInside = (start, end) => [...code.slice(start, end).matchAll(CHILDREN)].some((m) => openElementsAt(code, start + m.index, (n) => c.unlessInside.has(n)).length > 0);
5629
+ builders.set(abs, code ? wrappersIn({ code }, [...code.matchAll(ELEMENT)], c.unlessInside, childrenInside) : /* @__PURE__ */ new Map());
5630
+ }
5631
+ return builders.get(abs);
5632
+ };
5633
+ const nestedInBuilder = (file, index) => {
5634
+ if (!c.unlessInside.size) return false;
5635
+ const imported = importsOf(file);
5636
+ const isBuilder = (name) => {
5637
+ if (c.unlessInside.has(name)) return true;
5638
+ const from = name.includes(".") ? void 0 : imported.get(name);
5639
+ return from !== void 0 && buildersIn(from.file).has(from.name);
5640
+ };
5641
+ return openElementsAt(file.code, index, isBuilder).length > 0;
5642
+ };
5524
5643
  const wrappers = /* @__PURE__ */ new Map();
5525
5644
  const renderedBy = /* @__PURE__ */ new Map();
5526
5645
  for (const file of checked) {
@@ -5528,16 +5647,17 @@ function runPrefer(ctx, c) {
5528
5647
  const elements = [...file.code.matchAll(ELEMENT)];
5529
5648
  renderedBy.set(file, elements);
5530
5649
  if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
5531
- const found = wrappersIn(file, elements, c);
5650
+ const found = wrappersIn(file, elements, c.jsx);
5532
5651
  if (found.size) wrappers.set(file.absolutePath, found);
5533
5652
  }
5534
5653
  for (const file of checked) {
5535
5654
  const elements = renderedBy.get(file) ?? [];
5536
5655
  if (exempt(file, elements.map((m) => m[1]))) continue;
5537
5656
  const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
5538
- const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
5657
+ const imported = wrappers.size && elements.length ? importsOf(file) : null;
5539
5658
  for (const m of elements) {
5540
5659
  const name = m[1];
5660
+ if (nestedInBuilder(file, m.index)) continue;
5541
5661
  if (c.jsx.has(name)) {
5542
5662
  report(lineAt(file.code, m.index), name, `renders <${name}>`);
5543
5663
  continue;
@@ -5554,6 +5674,7 @@ function runPrefer(ctx, c) {
5554
5674
  if (c.pattern) {
5555
5675
  c.pattern.lastIndex = 0;
5556
5676
  for (const m of file.code.matchAll(c.pattern)) {
5677
+ if (nestedInBuilder(file, m.index)) continue;
5557
5678
  const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
5558
5679
  report(lineAt(file.code, m.index), text, `has ${text}`);
5559
5680
  }
@@ -5618,7 +5739,7 @@ function unknownPackageRuleSettings(config, packages, reported) {
5618
5739
  function packageRuleIds(packages) {
5619
5740
  return new Set(preferRules(packages).map((r) => r.ruleId));
5620
5741
  }
5621
- var PackageDeclarationError, GENESIS, ID, LEVELS2, PREFER_KEYS, FORBID_KEYS, UNLESS_KEYS, PRIMITIVE_KEYS, DECLARATION_KEYS, SCRIPT_GLOBS, isObject3, isStringList2, discoveryCache, specMatcher, JSX, ELEMENT, SCRIPT, TOP_LEVEL, EXPORT_LIST, EXPORT_DEFAULT_NAME, isNative;
5742
+ var PackageDeclarationError, GENESIS, ID, LEVELS2, PREFER_KEYS, FORBID_KEYS, UNLESS_KEYS, PRIMITIVE_KEYS, DECLARATION_KEYS, SCRIPT_GLOBS, isObject3, isStringList2, discoveryCache, specMatcher, JSX, ELEMENT, SCRIPT, CHILDREN, TOP_LEVEL, EXPORT_LIST, EXPORT_DEFAULT_NAME, isNative;
5622
5743
  var init_package_rules = __esm({
5623
5744
  "src/doctor/package-rules.ts"() {
5624
5745
  init_discover();
@@ -5630,6 +5751,7 @@ var init_package_rules = __esm({
5630
5751
  init_routes();
5631
5752
  init_scan();
5632
5753
  init_source();
5754
+ init_color_literals();
5633
5755
  init_rules();
5634
5756
  PackageDeclarationError = class extends Error {
5635
5757
  name = "PackageDeclarationError";
@@ -5637,9 +5759,9 @@ var init_package_rules = __esm({
5637
5759
  GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
5638
5760
  ID = /^[a-z0-9][a-z0-9-]*$/;
5639
5761
  LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
5640
- PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
5762
+ PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly", "extensible"]);
5641
5763
  FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
5642
- UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
5764
+ UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "inside", "pattern"]);
5643
5765
  PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
5644
5766
  DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "catalog", "primitives", "plugin", "$comment"]);
5645
5767
  SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
@@ -5650,6 +5772,7 @@ var init_package_rules = __esm({
5650
5772
  JSX = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
5651
5773
  ELEMENT = /(?<![\w$.])<([A-Z][\w.]*)(?=[\s>/<])/g;
5652
5774
  SCRIPT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
5775
+ CHILDREN = /\{\s*(?:props\.)?children\s*\}/g;
5653
5776
  TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
5654
5777
  EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
5655
5778
  EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
@@ -6194,6 +6317,66 @@ function checkSupabasePack(ctx) {
6194
6317
  checkViewInvoker(ctx, migrations, exposed);
6195
6318
  checkDefinerSearchPath(ctx, migrations);
6196
6319
  checkTestingKit(ctx, migrations);
6320
+ checkExposedSchemasCreatedLater(ctx, dir, migrations, settings2.exposedSchemas, settings2.automaticBranching !== false);
6321
+ }
6322
+ function apiSchemas(toml) {
6323
+ const lines = toml.split("\n");
6324
+ const start = lines.findIndex((l) => /^\s*\[api\]\s*(?:#.*)?$/.test(l));
6325
+ if (start < 0) return null;
6326
+ let end = lines.findIndex((l, i) => i > start && /^\s*\[/.test(l));
6327
+ if (end < 0) end = lines.length;
6328
+ const bare3 = (l) => {
6329
+ let quoted = false;
6330
+ for (let i = 0; i < l.length; i++) {
6331
+ if (l[i] === '"' && l[i - 1] !== "\\") quoted = !quoted;
6332
+ else if (l[i] === "#" && !quoted) return l.slice(0, i);
6333
+ }
6334
+ return l;
6335
+ };
6336
+ const body = lines.slice(start + 1, end).map(bare3);
6337
+ const enabled = !body.some((l) => /^\s*enabled\s*=\s*false\b/.test(l));
6338
+ const at = body.findIndex((l) => /^\s*schemas\s*=/.test(l));
6339
+ if (at < 0) return { enabled, schemas: [], line: start + 1 };
6340
+ let list = "";
6341
+ for (let i = at; i < body.length; i++) {
6342
+ list += `${body[i]}
6343
+ `;
6344
+ if (body[i].includes("]")) break;
6345
+ }
6346
+ const inner = /\[([\s\S]*?)\]/.exec(list)?.[1] ?? "";
6347
+ const schemas = [...inner.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((m) => (m[1] ?? m[2]).trim().toLowerCase()).filter(Boolean);
6348
+ return { enabled, schemas, line: start + at + 2 };
6349
+ }
6350
+ function checkExposedSchemasCreatedLater(ctx, dir, migrations, configured, branching) {
6351
+ const created = /* @__PURE__ */ new Map();
6352
+ for (const { file, statements } of migrations) {
6353
+ for (const { sql, line } of statements) {
6354
+ const m = /^create schema (?:if not exists )?"?([\w$]+)"?/.exec(sql);
6355
+ if (m && m[1] !== "authorization" && !created.has(m[1])) created.set(m[1], { file, line });
6356
+ }
6357
+ }
6358
+ const tomlFile = path30.posix.join(path30.posix.dirname(dir), "config.toml");
6359
+ const tomlText = existsSync(path30.join(ctx.root, tomlFile)) ? readFileSync(path30.join(ctx.root, tomlFile), "utf8") : null;
6360
+ const api2 = tomlText === null ? null : apiSchemas(tomlText);
6361
+ const sources = [];
6362
+ if (api2?.enabled) for (const schema of api2.schemas) sources.push({ schema, file: tomlFile, line: api2.line, where: `${tomlFile} [api] schemas` });
6363
+ for (const schema of api2?.enabled === false ? [] : configured ?? []) {
6364
+ const s = schema.toLowerCase();
6365
+ if (!sources.some((x) => x.schema === s)) sources.push({ schema: s, file: "genesis.config.json", where: "doctor.supabase.exposedSchemas" });
6366
+ }
6367
+ for (const { schema, file, line, where: where2 } of sources) {
6368
+ if (PLATFORM_SCHEMAS.has(schema)) continue;
6369
+ const by = created.get(schema);
6370
+ if (by && !branching) continue;
6371
+ ctx.report({
6372
+ rule: "exposed-schema-created-later",
6373
+ level: "warn",
6374
+ file,
6375
+ ...line ? { line } : {},
6376
+ subject: schema,
6377
+ message: by ? `${where2} exposes ${schema}, which only a migration creates (${by.file}:${by.line}); a Supabase branch points its Data API at ${schema} before it runs migrations, so a fresh preview branch fails its health check. Turn off Supabase's automatic branching (Genesis docs/APP-CI.md, "Previews"), then set doctor.supabase.automaticBranching to false` : `${where2} exposes ${schema}, which no migration creates, so a database built from the migrations can't serve it (a Supabase branch fails its health check); create it in a migration or stop exposing it`
6378
+ });
6379
+ }
6197
6380
  }
6198
6381
  function checkTestingKit(ctx, migrations) {
6199
6382
  for (const { file, statements } of migrations) {
@@ -6456,7 +6639,7 @@ function checkDefinerSearchPath(ctx, migrations) {
6456
6639
  });
6457
6640
  }
6458
6641
  }
6459
- var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, MULTIWORD_TYPE;
6642
+ var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, MULTIWORD_TYPE, PLATFORM_SCHEMAS;
6460
6643
  var init_supabase = __esm({
6461
6644
  "src/doctor/supabase.ts"() {
6462
6645
  init_config();
@@ -6476,6 +6659,7 @@ var init_supabase = __esm({
6476
6659
  float8: "double precision"
6477
6660
  };
6478
6661
  MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
6662
+ PLATFORM_SCHEMAS = /* @__PURE__ */ new Set(["public", "graphql_public", "graphql", "extensions", "storage", "auth", "realtime", "vault"]);
6479
6663
  }
6480
6664
  });
6481
6665
  function nodeModulesOf(dir) {
@@ -7989,20 +8173,41 @@ function git3(root, args) {
7989
8173
  return r.status === 0 ? r.stdout : null;
7990
8174
  }
7991
8175
  function changedSince(root, base) {
7992
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
8176
+ const mergeBase = mergeBaseOf2(root, base);
7993
8177
  if (!mergeBase) return null;
7994
8178
  const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
7995
8179
  const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
7996
8180
  if (committed === null || untracked === null) return null;
7997
8181
  return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
7998
8182
  }
8183
+ function originsSince(root, base) {
8184
+ const out = /* @__PURE__ */ new Map();
8185
+ const mergeBase = mergeBaseOf2(root, base);
8186
+ if (!mergeBase) return out;
8187
+ const diff = git3(root, ["diff", "-z", "-M", "--name-status", "--relative", mergeBase, "--"]);
8188
+ if (diff === null) return out;
8189
+ const parts = diff.split("\0");
8190
+ for (let i = 0; i < parts.length; ) {
8191
+ const status = parts[i++] ?? "";
8192
+ if (!status) continue;
8193
+ if (status.startsWith("R") || status.startsWith("C")) {
8194
+ const from = parts[i++];
8195
+ const to = parts[i++];
8196
+ if (status.startsWith("R")) out.set(to, from);
8197
+ } else i++;
8198
+ }
8199
+ return out;
8200
+ }
8201
+ function mergeBaseOf2(root, base) {
8202
+ return git3(root, ["merge-base", base, "HEAD"])?.trim() || null;
8203
+ }
7999
8204
  function showAt(dir, rev, file) {
8000
8205
  const at = `${rev}:./${file}`;
8001
8206
  if (git3(dir, ["cat-file", "-e", at]) === null) return void 0;
8002
8207
  return git3(dir, ["show", at]);
8003
8208
  }
8004
8209
  function configAtBase(root, base, explicitFile) {
8005
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
8210
+ const mergeBase = mergeBaseOf2(root, base);
8006
8211
  if (!mergeBase) return null;
8007
8212
  const candidates = explicitFile ? [{ dir: path30.dirname(explicitFile), file: path30.basename(explicitFile), explicit: true }] : [
8008
8213
  { dir: root, file: "genesis.config.json", explicit: false },
@@ -8023,7 +8228,12 @@ function configAtBase(root, base, explicitFile) {
8023
8228
  continue;
8024
8229
  }
8025
8230
  const b = objectOr(block);
8026
- return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
8231
+ return {
8232
+ allow: Array.isArray(b.allow) ? b.allow : [],
8233
+ extend: Array.isArray(b.extend) ? b.extend : [],
8234
+ rules: objectOr(b.rules),
8235
+ packageRules: objectOr(b.packageRules)
8236
+ };
8027
8237
  }
8028
8238
  return "absent";
8029
8239
  }
@@ -8036,6 +8246,16 @@ function allowGrew(allow, before, base) {
8036
8246
  message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
8037
8247
  }));
8038
8248
  }
8249
+ function extensionsAdded(extend, before, base) {
8250
+ const had = new Set(before.map((e) => `${e.rule}\0${e.file}\0${e.buildsOn}`));
8251
+ return extend.filter((e) => !had.has(`${e.rule}\0${e.file}\0${e.buildsOn}`)).map((e) => ({
8252
+ rule: "extension-added",
8253
+ level: "info",
8254
+ file: e.file,
8255
+ subject: e.rule,
8256
+ message: `extends ${e.rule} since ${base}, building on ${e.buildsOn}: "${e.reason}"${e.upstream ? ` (upstream: ${e.upstream})` : ""}; the pull request's review accepts it, and it covers only the findings the file has now`
8257
+ }));
8258
+ }
8039
8259
  function rulesWeakened(config, before, base) {
8040
8260
  const out = [];
8041
8261
  const levelIn = (c, rule) => c.rules?.[rule] ?? c.packageRules?.[rule]?.level;
@@ -8063,18 +8283,63 @@ function touched(file, changed) {
8063
8283
  for (const c of changed) if (c.startsWith(prefix)) return true;
8064
8284
  return false;
8065
8285
  }
8286
+ function isRatcheted(rule, config, newOnly) {
8287
+ return !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
8288
+ }
8289
+ function countFindings(findings) {
8290
+ const counts = /* @__PURE__ */ new Map();
8291
+ for (const f of findings) counts.set(countKey(f.file, f.rule), (counts.get(countKey(f.file, f.rule)) ?? 0) + 1);
8292
+ return counts;
8293
+ }
8066
8294
  function applyRatchet(findings, options) {
8067
- const { config, newOnly, changed, base, isAppPath } = options;
8068
- const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
8295
+ const { config, newOnly, changed, base, isAppPath, baseCounts, existedAtBase } = options;
8296
+ const originOf = options.originOf ?? ((f) => f);
8297
+ const counts = countFindings(findings.map((f) => ({ file: originOf(f.file), rule: f.rule })));
8069
8298
  return findings.map((f) => {
8070
- if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
8071
- return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
8299
+ if (f.level === "info" || !isRatcheted(f.rule, config, newOnly) || !isAppPath(f.file)) return f;
8300
+ if (!touched(f.file, changed)) return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
8301
+ const origin = originOf(f.file);
8302
+ if (!baseCounts || !existedAtBase?.(origin)) return f;
8303
+ const now = counts.get(countKey(origin, f.rule)) ?? 0;
8304
+ const was = baseCounts.get(countKey(origin, f.rule)) ?? 0;
8305
+ const where2 = origin === f.file ? "this file" : `the files from ${origin}`;
8306
+ if (now > was) return { ...f, message: `${f.message} (${now} ${f.rule} findings in ${where2}, ${was} at the merge base with ${base}: don't add to the debt)` };
8307
+ return { ...f, level: "info", message: `${f.message} (ratcheted: ${now} in ${where2}, ${was} at the merge base with ${base})` };
8072
8308
  });
8073
8309
  }
8074
- var objectOr, allowKey, RANK, NEVER_RATCHETED;
8310
+ function snapshotAtBase(root, base, files, changed, originOf = (f) => f) {
8311
+ const mergeBase = mergeBaseOf2(root, base);
8312
+ if (!mergeBase) return null;
8313
+ const out = [];
8314
+ const seen = /* @__PURE__ */ new Set();
8315
+ for (const f of files) {
8316
+ if (!changed.has(f.path)) {
8317
+ if (!seen.has(f.path)) out.push(f);
8318
+ seen.add(f.path);
8319
+ continue;
8320
+ }
8321
+ const origin = originOf(f.path);
8322
+ if (seen.has(origin)) continue;
8323
+ seen.add(origin);
8324
+ const text = showAt(root, mergeBase, origin);
8325
+ if (text === null) return null;
8326
+ if (text !== void 0) out.push(withText({ ...f, path: origin, absolutePath: path30.join(root, origin) }, text));
8327
+ }
8328
+ const cache2 = /* @__PURE__ */ new Map();
8329
+ return {
8330
+ mergeBase,
8331
+ files: out,
8332
+ existed(file) {
8333
+ if (!cache2.has(file)) cache2.set(file, git3(root, ["cat-file", "-e", `${mergeBase}:./${file}`]) !== null);
8334
+ return cache2.get(file);
8335
+ }
8336
+ };
8337
+ }
8338
+ var objectOr, allowKey, RANK, NEVER_RATCHETED, countKey;
8075
8339
  var init_ratchet = __esm({
8076
8340
  "src/doctor/ratchet.ts"() {
8077
8341
  init_config();
8342
+ init_scan();
8078
8343
  objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
8079
8344
  allowKey = (a) => `${a.rule}\0${a.file ?? ""}\0${a.match ?? ""}`;
8080
8345
  RANK = { off: 0, info: 1, warn: 2, error: 3 };
@@ -8087,10 +8352,141 @@ var init_ratchet = __esm({
8087
8352
  "plugin-error",
8088
8353
  "build",
8089
8354
  "agent-guide-stale",
8090
- "contracts-stale"
8355
+ "contracts-stale",
8356
+ "stale-extension",
8357
+ "extension-added"
8091
8358
  ]);
8359
+ countKey = (file, rule) => `${file}\0${rule}`;
8092
8360
  }
8093
8361
  });
8362
+
8363
+ // src/doctor/extensions.ts
8364
+ function pointProblem(entry, packages) {
8365
+ const rule = preferRules(packages).find((r) => r.ruleId === entry.rule);
8366
+ if (!rule?.extensible?.length) return `${entry.rule} declares no extension points, so it can't be extended (debt goes in allow, and is fixed)`;
8367
+ if (!rule.extensible.includes(entry.buildsOn)) return `${entry.buildsOn} isn't one of ${entry.rule}'s extension points (${rule.extensible.join(", ")})`;
8368
+ return null;
8369
+ }
8370
+ function extensionProblem(entry, ctx) {
8371
+ const point = pointProblem(entry, ctx.packages);
8372
+ if (point) return point;
8373
+ const name = entry.buildsOn.split(".")[0];
8374
+ const replaces = preferRules(ctx.packages).find((r) => r.forbid.jsx?.includes(name));
8375
+ if (replaces) return `${name} is what ${replaces.ruleId} replaces (use ${replaces.use}); a legacy component can't be built on`;
8376
+ const flagged = ctx.raw.find((f) => f.file === entry.file && f.subject === name);
8377
+ if (flagged) return `${name} is flagged in this file by ${flagged.rule}; build on a current Genesis primitive`;
8378
+ const file = ctx.files.find((f) => f.path === entry.file);
8379
+ if (!file) return `${entry.file} isn't one of the files the doctor scans`;
8380
+ const imported = genesisNamedImports(file.code).some((i) => i.names.includes(name));
8381
+ if (!imported) return `${entry.file} doesn't import ${name} from a Genesis package; buildsOn names the extension point the file uses`;
8382
+ if (!usesPoint(blankStrings(file.code), entry.buildsOn)) {
8383
+ const prop = entry.buildsOn.split(".")[1];
8384
+ return prop ? `${entry.file} doesn't pass ${prop} to <${name}>; an extension point is one the file uses` : `${entry.file} imports ${name} but doesn't render or call it; an extension point is one the file uses`;
8385
+ }
8386
+ return null;
8387
+ }
8388
+ function usesPoint(code, point) {
8389
+ const [name, prop] = point.split(".");
8390
+ const n = escape2(name);
8391
+ if (!prop) return new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])|(?<![\\w$.])${n}\\s*(?:<[^>()]*>)?\\s*\\(`).test(code);
8392
+ for (const m of code.matchAll(new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])`, "g"))) {
8393
+ const { end } = tagEnd(code, m.index);
8394
+ if (new RegExp(`(?<![\\w$.])${escape2(prop)}\\s*=`).test(code.slice(m.index, end))) return true;
8395
+ }
8396
+ return false;
8397
+ }
8398
+ function applyExtensions(findings, ctx) {
8399
+ const entries = ctx.config.extend ?? [];
8400
+ if (!entries.length) return findings;
8401
+ const staleLevel = ctx.config.rules?.["stale-extension"];
8402
+ const covered = /* @__PURE__ */ new Set();
8403
+ const grew = /* @__PURE__ */ new Map();
8404
+ const out = [];
8405
+ const invalid = (entry, problem) => out.push({ rule: "extension-invalid", level: "error", file: entry.file, line: 0, subject: entry.rule, message: `the extension of ${entry.rule} isn't accepted: ${problem}` });
8406
+ for (const entry of entries) {
8407
+ if (ctx.config.rules?.[entry.rule] === "off" || ctx.config.packageRules?.[entry.rule]?.level === "off") continue;
8408
+ const point = pointProblem(entry, ctx.packages);
8409
+ if (point) {
8410
+ invalid(entry, point);
8411
+ continue;
8412
+ }
8413
+ const hits = findings.filter((f) => f.rule === entry.rule && f.file === entry.file);
8414
+ if (!hits.length) {
8415
+ if (staleLevel === "off") continue;
8416
+ out.push({
8417
+ rule: "stale-extension",
8418
+ level: staleLevel ?? "warn",
8419
+ file: entry.file,
8420
+ line: 0,
8421
+ subject: entry.rule,
8422
+ message: `the extension of ${entry.rule} (building on ${entry.buildsOn}) no longer matches a finding in this file; remove it from doctor.extend`
8423
+ });
8424
+ continue;
8425
+ }
8426
+ const problem = extensionProblem(entry, ctx);
8427
+ if (problem) {
8428
+ invalid(entry, problem);
8429
+ continue;
8430
+ }
8431
+ const limit = ctx.limit?.(entry);
8432
+ if (limit !== void 0 && hits.length > limit) {
8433
+ for (const h of hits) grew.set(h, `${h.message} (the extension of ${entry.rule} here covers the ${limit} at the merge base; this file now has ${hits.length}, so they all count)`);
8434
+ continue;
8435
+ }
8436
+ for (const h of hits) covered.add(h);
8437
+ }
8438
+ const kept = findings.filter((f) => !covered.has(f)).map((f) => grew.has(f) ? { ...f, message: grew.get(f) } : f);
8439
+ return [...kept, ...out].sort(byPlace);
8440
+ }
8441
+ function dedupeFindings(findings) {
8442
+ const groups = /* @__PURE__ */ new Map();
8443
+ const order = [];
8444
+ for (const f of findings) {
8445
+ if (f.subject === void 0 || !f.line) {
8446
+ order.push([f]);
8447
+ continue;
8448
+ }
8449
+ const key2 = `${f.file}\0${f.line}\0${f.subject}`;
8450
+ const list = groups.get(key2) ?? [];
8451
+ const group = list.find((g) => !g.some((x) => x.rule === f.rule));
8452
+ if (group) group.push(f);
8453
+ else {
8454
+ const fresh = [f];
8455
+ list.push(fresh);
8456
+ groups.set(key2, list);
8457
+ order.push(fresh);
8458
+ }
8459
+ }
8460
+ return order.map((group) => {
8461
+ if (group.length === 1) return group[0];
8462
+ const primary = group.reduce((a, b) => RANK2[b.level] > RANK2[a.level] ? b : a);
8463
+ const rules = [primary.rule, ...group.filter((g) => g !== primary).map((g) => g.rule)];
8464
+ return { ...primary, rules, message: `${primary.message} (also ${rules.slice(1).join(", ")})` };
8465
+ });
8466
+ }
8467
+ var escape2, byPlace, RANK2;
8468
+ var init_extensions = __esm({
8469
+ "src/doctor/extensions.ts"() {
8470
+ init_stability();
8471
+ init_source();
8472
+ init_package_rules();
8473
+ escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8474
+ byPlace = (x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule);
8475
+ RANK2 = { info: 0, warn: 1, error: 2 };
8476
+ }
8477
+ });
8478
+ function pathTaken(file) {
8479
+ try {
8480
+ lstatSync(file);
8481
+ return true;
8482
+ } catch {
8483
+ try {
8484
+ return readdirSync(path30.dirname(file)).some((n) => n.toLowerCase() === path30.basename(file).toLowerCase());
8485
+ } catch {
8486
+ return false;
8487
+ }
8488
+ }
8489
+ }
8094
8490
  function primitivesCatalog(packages) {
8095
8491
  const rows = [...CORE];
8096
8492
  for (const rule of preferRules(packages)) {
@@ -8132,7 +8528,74 @@ function formatPrimitives(rows) {
8132
8528
  }
8133
8529
  return lines.join("\n");
8134
8530
  }
8135
- function renderSkill(rows) {
8531
+ function skillDescription(text) {
8532
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1];
8533
+ if (!fm) return "";
8534
+ const lines = fm.split(/\r?\n/);
8535
+ const i = lines.findIndex((l) => /^description:/.test(l));
8536
+ if (i < 0) return "";
8537
+ const first = lines[i].replace(/^description:\s*/, "").trim();
8538
+ if (first && !/^[>|][+-]?$/.test(first)) return first.replace(/^["']|["']$/g, "");
8539
+ const more = [];
8540
+ for (const l of lines.slice(i + 1)) {
8541
+ if (!/^\s+\S/.test(l)) break;
8542
+ more.push(l.trim());
8543
+ }
8544
+ return more.join(" ");
8545
+ }
8546
+ function stableGuidePath(root, p) {
8547
+ const real2 = (f) => {
8548
+ try {
8549
+ return realpathSync(f);
8550
+ } catch {
8551
+ return null;
8552
+ }
8553
+ };
8554
+ const want = real2(p.dir);
8555
+ for (let dir = root, level = 0; level <= GUIDE_SEARCH_LEVELS; level++) {
8556
+ const found = path30.join(dir, "node_modules", p.name);
8557
+ if (existsSync(found)) {
8558
+ const file = path30.join(found, "SKILL.md");
8559
+ return want !== null && real2(found) === want && existsSync(file) ? file : null;
8560
+ }
8561
+ if (existsSync(path30.join(dir, ".git")) || existsSync(path30.join(dir, "pnpm-workspace.yaml"))) return null;
8562
+ const up = path30.dirname(dir);
8563
+ if (up === dir) return null;
8564
+ dir = up;
8565
+ }
8566
+ return null;
8567
+ }
8568
+ function packageGuides(root, packages) {
8569
+ const guides = [];
8570
+ for (const p of packages) {
8571
+ const stable = p.local ? path30.join(p.dir, "SKILL.md") : stableGuidePath(root, p);
8572
+ const text = stable === null ? null : read(stable);
8573
+ if (stable === null || text === null) continue;
8574
+ const description = skillDescription(text);
8575
+ const at = description.indexOf("Load before");
8576
+ guides.push({ package: p.name, path: path30.relative(root, stable).split(path30.sep).join("/"), when: at >= 0 ? description.slice(at) : description });
8577
+ }
8578
+ return guides.sort((a, b) => a.package.localeCompare(b.package));
8579
+ }
8580
+ function unlistedGuides(root, packages) {
8581
+ const listed = new Set(packageGuides(root, packages).map((g) => g.package));
8582
+ return packages.filter((p) => !p.local && !listed.has(p.name) && existsSync(path30.join(p.dir, "SKILL.md"))).map((p) => p.name).sort();
8583
+ }
8584
+ function guidesSection(guides) {
8585
+ if (!guides.length) return [];
8586
+ return [
8587
+ "### Package guides (they match the installed versions)",
8588
+ "",
8589
+ "Before using a package's primitives, read its guide:",
8590
+ "",
8591
+ ...guides.map((g) => `- \`${g.path}\` (${g.package}): ${g.when}`),
8592
+ ""
8593
+ ];
8594
+ }
8595
+ function agentRules() {
8596
+ return RULES;
8597
+ }
8598
+ function renderSkill(rows, guides = []) {
8136
8599
  return [
8137
8600
  "---",
8138
8601
  "name: genesis",
@@ -8145,6 +8608,7 @@ function renderSkill(rows) {
8145
8608
  "",
8146
8609
  ...RULES.map((r) => `- ${r}`),
8147
8610
  "",
8611
+ ...guidesSection(guides),
8148
8612
  "## What to use for each need",
8149
8613
  "",
8150
8614
  catalogTable(rows, { docs: true }),
@@ -8153,7 +8617,7 @@ function renderSkill(rows) {
8153
8617
  ""
8154
8618
  ].join("\n");
8155
8619
  }
8156
- function renderAgentsBlock(rows) {
8620
+ function renderAgentsBlock(rows, guides = []) {
8157
8621
  return [
8158
8622
  AGENTS_START,
8159
8623
  "## Building with Genesis",
@@ -8164,6 +8628,7 @@ function renderAgentsBlock(rows) {
8164
8628
  "",
8165
8629
  ...RULES.map((r) => `- ${r}`),
8166
8630
  "",
8631
+ ...guidesSection(guides),
8167
8632
  catalogTable(rows),
8168
8633
  AGENTS_END
8169
8634
  ].join("\n");
@@ -8193,12 +8658,13 @@ function currentAgentsBlock(agents) {
8193
8658
  }
8194
8659
  function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
8195
8660
  const rows = primitivesCatalog(packages);
8661
+ const guides = packageGuides(root, packages);
8196
8662
  const changed = [];
8197
8663
  const agents = path30.join(root, agentsFile);
8198
8664
  const before = read(agents);
8199
- const after = mergeAgentsBlock(before, renderAgentsBlock(rows));
8665
+ const after = mergeAgentsBlock(before, renderAgentsBlock(rows, guides));
8200
8666
  const skill = path30.join(root, SKILL_PATH);
8201
- const skillText = renderSkill(rows);
8667
+ const skillText = renderSkill(rows, guides);
8202
8668
  if (read(skill)?.replace(/\r\n/g, "\n") !== skillText) {
8203
8669
  mkdirSync(path30.dirname(skill), { recursive: true });
8204
8670
  writeFileSync(skill, skillText);
@@ -8208,15 +8674,44 @@ function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
8208
8674
  writeFileSync(agents, after);
8209
8675
  changed.push(agentsFile);
8210
8676
  }
8677
+ const claude = path30.join(root, "CLAUDE.md");
8678
+ if (agentsFile === "AGENTS.md" && !pathTaken(claude)) {
8679
+ writeFileSync(claude, CLAUDE_IMPORT);
8680
+ changed.push("CLAUDE.md");
8681
+ }
8211
8682
  return changed;
8212
8683
  }
8684
+ function claudeState(root) {
8685
+ const file = path30.join(root, "CLAUDE.md");
8686
+ let names = [];
8687
+ try {
8688
+ names = readdirSync(root);
8689
+ } catch {
8690
+ }
8691
+ if (!names.includes("CLAUDE.md")) return names.some((n) => n.toLowerCase() === "claude.md") ? "blocked" : "missing";
8692
+ let text;
8693
+ try {
8694
+ text = readFileSync(file, "utf8");
8695
+ } catch {
8696
+ return "blocked";
8697
+ }
8698
+ if (/^@AGENTS\.md\b/m.test(text)) return "ok";
8699
+ try {
8700
+ if (realpathSync(file) === realpathSync(path30.join(root, "AGENTS.md"))) return "ok";
8701
+ } catch {
8702
+ }
8703
+ return "no-import";
8704
+ }
8213
8705
  function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
8214
8706
  const rows = primitivesCatalog(packages);
8707
+ const guides = packageGuides(root, packages);
8215
8708
  const skill = read(path30.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
8216
8709
  const block = currentAgentsBlock(read(path30.join(root, agentsFile)));
8217
8710
  return {
8218
- skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
8219
- agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
8711
+ skill: skill === null ? "missing" : skill === renderSkill(rows, guides) ? "ok" : "stale",
8712
+ agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows, guides) ? "ok" : "stale",
8713
+ // Only the default AGENTS.md gets a CLAUDE.md written for it, so only then is a missing one reported.
8714
+ claude: agentsFile !== "AGENTS.md" ? "ok" : claudeState(root)
8220
8715
  };
8221
8716
  }
8222
8717
  function checkAgentGuide(ctx) {
@@ -8234,12 +8729,27 @@ function checkAgentGuide(ctx) {
8234
8729
  }[state.agents];
8235
8730
  ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
8236
8731
  }
8732
+ if (state.claude === "no-import") {
8733
+ ctx.report({ rule: "agent-guide-stale", level: "info", file: "CLAUDE.md", message: "doesn't import AGENTS.md (`@AGENTS.md`), so reviewers and cloud project threads that read only CLAUDE.md don't see the Genesis guide" });
8734
+ }
8735
+ if (state.claude === "missing") {
8736
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: "CLAUDE.md", message: `is missing, so reviewers and cloud project threads that read only CLAUDE.md never see AGENTS.md; ${fix} (it writes \`@AGENTS.md\`)` });
8737
+ }
8738
+ if (state.claude === "blocked") {
8739
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: "CLAUDE.md", message: `can't be read: something else is in its place (another case of the name such as claude.md, a dangling link, a folder or an unreadable file), and genesis agents won't write over it; ${BLOCKED_FIX}` });
8740
+ }
8741
+ const unlisted = unlistedGuides(ctx.root, ctx.packages);
8742
+ if (unlisted.length) {
8743
+ ctx.report({ rule: "agent-guide-stale", level: "info", file: "AGENTS.md", message: `leaves out the guide of ${unlisted.join(", ")}: it's only inside pnpm's store, under a path that changes with unrelated bumps. Add the package as a direct dependency to list its guide.` });
8744
+ }
8237
8745
  }
8238
- var GENESIS_DOCS, CORE, cell, importCell, SKILL_PATH, AGENTS_START, AGENTS_END, RULES, read;
8746
+ var GENESIS_DOCS, read, CLAUDE_IMPORT, CORE, cell, importCell, SKILL_PATH, AGENTS_START, AGENTS_END, RULES, GUIDE_SEARCH_LEVELS, BLOCKED_FIX;
8239
8747
  var init_primitives = __esm({
8240
8748
  "src/doctor/primitives.ts"() {
8241
8749
  init_package_rules();
8242
8750
  GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
8751
+ read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
8752
+ CLAUDE_IMPORT = "@AGENTS.md\n";
8243
8753
  CORE = [
8244
8754
  {
8245
8755
  need: "anything, before building it",
@@ -8281,14 +8791,105 @@ var init_primitives = __esm({
8281
8791
  AGENTS_START = "<!-- genesis-primitives:start -->";
8282
8792
  AGENTS_END = "<!-- genesis-primitives:end -->";
8283
8793
  RULES = [
8284
- "Use the Genesis primitive for the need first: reuse, then extend, then invent (docs/FRAMEWORK.md, G1 to G6).",
8794
+ `Use the Genesis primitive for the need first: reuse, then extend, then invent (G1 to G6 in ${GENESIS_DOCS}/FRAMEWORK.md).`,
8285
8795
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
8286
8796
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
8287
8797
  "Screens never call the database client (`supabase.from`, `.rpc`) directly: reads go through a view or a named data function, writes through the resource's provider rules.",
8288
8798
  "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
8289
8799
  "Run `genesis doctor` before you finish; it enforces these rules."
8290
8800
  ];
8291
- read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
8801
+ GUIDE_SEARCH_LEVELS = 4;
8802
+ BLOCKED_FIX = "rename or replace it with a CLAUDE.md file (or remove the dangling link), then run genesis agents";
8803
+ }
8804
+ });
8805
+ function subagentContext(root, packages) {
8806
+ const guides = packageGuides(root, packages);
8807
+ return [
8808
+ "This is a Genesis app. Follow these rules (the app's AGENTS.md has the full guide):",
8809
+ ...agentRules().map((r) => `- ${r}`),
8810
+ ...guides.length ? ["", "Package guides (they match the installed versions):", ...guides.map((g) => `- ${g.path}: ${g.when}`)] : []
8811
+ ].join("\n");
8812
+ }
8813
+ function subagentHookOutput(root, packages) {
8814
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: "SubagentStart", additionalContext: subagentContext(root, packages) } });
8815
+ }
8816
+ function checkSettingsShape(settings2) {
8817
+ const fail = (msg) => {
8818
+ throw new Error(`${SETTINGS_PATH}: ${msg}; fix it by hand, then run genesis agents --hooks again.`);
8819
+ };
8820
+ if (!isObject4(settings2)) fail("must be a JSON object");
8821
+ const s = settings2;
8822
+ if (s.hooks !== void 0) {
8823
+ if (!isObject4(s.hooks)) fail('"hooks" must be an object');
8824
+ const start = s.hooks["SubagentStart"];
8825
+ if (start !== void 0) {
8826
+ if (!Array.isArray(start)) fail('"hooks.SubagentStart" must be a list');
8827
+ for (const e of start) if (!isObject4(e) || !Array.isArray(e.hooks) || !e.hooks.every(isObject4)) fail('each "hooks.SubagentStart" entry needs a "hooks" list of objects');
8828
+ }
8829
+ }
8830
+ if (s.permissions !== void 0) {
8831
+ if (!isObject4(s.permissions)) fail('"permissions" must be an object');
8832
+ const deny = s.permissions.deny;
8833
+ if (deny !== void 0 && (!Array.isArray(deny) || !deny.every((d) => typeof d === "string"))) fail('"permissions.deny" must be a list of strings');
8834
+ }
8835
+ }
8836
+ function mergeAgentHooks(settings2) {
8837
+ checkSettingsShape(settings2);
8838
+ const out = structuredClone(settings2);
8839
+ const hooks = out.hooks ??= {};
8840
+ const others = (hooks["SubagentStart"] ?? []).map((e) => ({ ...e, hooks: e.hooks.filter((h) => !isGenesisHook(h)) })).filter((e) => e.hooks.length > 0);
8841
+ hooks["SubagentStart"] = [...others, { matcher: SUBAGENT_MATCHER, hooks: [{ type: "command", command: SUBAGENT_HOOK_COMMAND }] }];
8842
+ const permissions = out.permissions ??= {};
8843
+ const deny = permissions.deny ?? [];
8844
+ permissions.deny = [...deny, ...DENY_RULES.filter((r) => !deny.includes(r))];
8845
+ return out;
8846
+ }
8847
+ function writeAgentHooks(root) {
8848
+ const file = path30.join(root, SETTINGS_PATH);
8849
+ const before = existsSync(file) ? readFileSync(file, "utf8") : null;
8850
+ let current = {};
8851
+ if (before !== null) {
8852
+ try {
8853
+ current = JSON.parse(before);
8854
+ } catch {
8855
+ throw new Error(`${SETTINGS_PATH} isn't valid JSON; fix it by hand, then run genesis agents --hooks again.`);
8856
+ }
8857
+ }
8858
+ checkSettingsShape(current);
8859
+ const after = `${JSON.stringify(mergeAgentHooks(current), null, 2)}
8860
+ `;
8861
+ if (before !== null && JSON.stringify(JSON.parse(before)) === JSON.stringify(JSON.parse(after))) return [];
8862
+ mkdirSync(path30.dirname(file), { recursive: true });
8863
+ writeFileSync(file, after);
8864
+ return [SETTINGS_PATH];
8865
+ }
8866
+ function agentHooksState(root) {
8867
+ let settings2;
8868
+ try {
8869
+ settings2 = JSON.parse(readFileSync(path30.join(root, SETTINGS_PATH), "utf8"));
8870
+ } catch {
8871
+ return "none";
8872
+ }
8873
+ const start = isObject4(settings2) && isObject4(settings2.hooks) ? settings2.hooks["SubagentStart"] : void 0;
8874
+ const commands = (Array.isArray(start) ? start : []).flatMap((e) => isObject4(e) && Array.isArray(e.hooks) ? e.hooks : []).filter((h) => isObject4(h) && isGenesisHook(h)).map((h) => h.command);
8875
+ if (!commands.length) return "none";
8876
+ return commands.every((c) => c === SUBAGENT_HOOK_COMMAND) ? "ok" : "stale";
8877
+ }
8878
+ function checkAgentHooks(ctx) {
8879
+ if (agentHooksState(ctx.root) === "stale") {
8880
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: SETTINGS_PATH, message: "has an older Genesis SubagentStart hook command; run genesis agents --hooks and commit the result" });
8881
+ }
8882
+ }
8883
+ var SETTINGS_PATH, SUBAGENT_HOOK_COMMAND, SUBAGENT_MATCHER, DENY_RULES, isObject4, isGenesisHook;
8884
+ var init_agent_hooks = __esm({
8885
+ "src/doctor/agent-hooks.ts"() {
8886
+ init_primitives();
8887
+ SETTINGS_PATH = ".claude/settings.json";
8888
+ SUBAGENT_HOOK_COMMAND = '"$CLAUDE_PROJECT_DIR"/node_modules/.bin/genesis agents --hook subagent-start --dir "$CLAUDE_PROJECT_DIR" 2>/dev/null || true';
8889
+ SUBAGENT_MATCHER = "Explore|Plan";
8890
+ DENY_RULES = ["Read(./.env)", "Read(./.env.*)"];
8891
+ isObject4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8892
+ isGenesisHook = (h) => typeof h.command === "string" && h.command.includes("genesis agents --hook");
8292
8893
  }
8293
8894
  });
8294
8895
  function appFolderOf(root) {
@@ -9256,18 +9857,28 @@ var init_figma_routes = __esm({
9256
9857
  // src/doctor/index.ts
9257
9858
  var doctor_exports = {};
9258
9859
  __export(doctor_exports, {
9860
+ BLOCKED_FIX: () => BLOCKED_FIX,
9259
9861
  BUILTIN_RULES: () => BUILTIN_RULES,
9862
+ CLAUDE_IMPORT: () => CLAUDE_IMPORT,
9863
+ DENY_RULES: () => DENY_RULES,
9260
9864
  DoctorConfigError: () => DoctorConfigError,
9261
9865
  GenesisConfigError: () => GenesisConfigError,
9262
9866
  PackageDeclarationError: () => PackageDeclarationError,
9867
+ SETTINGS_PATH: () => SETTINGS_PATH,
9263
9868
  SKILL_PATH: () => SKILL_PATH,
9869
+ SUBAGENT_HOOK_COMMAND: () => SUBAGENT_HOOK_COMMAND,
9264
9870
  agentGuideState: () => agentGuideState,
9871
+ agentHooksState: () => agentHooksState,
9872
+ agentRules: () => agentRules,
9873
+ applyExtensions: () => applyExtensions,
9265
9874
  builtinChecks: () => builtinChecks,
9266
9875
  catalogTable: () => catalogTable,
9267
9876
  changedSince: () => changedSince,
9268
9877
  clearPackageRulesCache: () => clearPackageRulesCache,
9878
+ dedupeFindings: () => dedupeFindings,
9269
9879
  defineDoctorPlugin: () => defineDoctorPlugin,
9270
9880
  discoverPackages: () => discoverPackages,
9881
+ extensionProblem: () => extensionProblem,
9271
9882
  findPackageDir: () => findPackageDir,
9272
9883
  formatPrimitives: () => formatPrimitives,
9273
9884
  formatReport: () => formatReport,
@@ -9276,7 +9887,9 @@ __export(doctor_exports, {
9276
9887
  globToRegExp: () => globToRegExp,
9277
9888
  loadConfig: () => loadConfig,
9278
9889
  loadGenesis: () => loadGenesis,
9890
+ mergeAgentHooks: () => mergeAgentHooks,
9279
9891
  nativeLayouts: () => nativeLayouts,
9892
+ packageGuides: () => packageGuides,
9280
9893
  parseExportNames: () => parseExportNames,
9281
9894
  parseRulesMarkdown: () => parseRulesMarkdown,
9282
9895
  postgresContract: () => postgresContract,
@@ -9293,13 +9906,18 @@ __export(doctor_exports, {
9293
9906
  ruleNamespace: () => ruleNamespace,
9294
9907
  runDoctor: () => runDoctor,
9295
9908
  satisfies: () => satisfies,
9909
+ skillDescription: () => skillDescription,
9296
9910
  sqlStatements: () => sqlStatements,
9911
+ subagentContext: () => subagentContext,
9912
+ subagentHookOutput: () => subagentHookOutput,
9297
9913
  toJson: () => toJson,
9914
+ unlistedGuides: () => unlistedGuides,
9298
9915
  validateConfig: () => validateConfig,
9299
9916
  validateDeclaration: () => validateDeclaration,
9300
9917
  validateLinks: () => validateLinks,
9301
9918
  webRoutes: () => webRoutes,
9302
- writeAgentGuide: () => writeAgentGuide
9919
+ writeAgentGuide: () => writeAgentGuide,
9920
+ writeAgentHooks: () => writeAgentHooks
9303
9921
  });
9304
9922
  async function runDoctor(options = {}) {
9305
9923
  const root = path30.resolve(options.root ?? process.cwd());
@@ -9317,14 +9935,8 @@ async function runDoctor(options = {}) {
9317
9935
  }
9318
9936
  const raw = [];
9319
9937
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
9320
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
9321
- try {
9322
- await plugin.check(ctx);
9323
- } catch (err) {
9324
- if (err instanceof DoctorConfigError) throw err;
9325
- raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
9326
- }
9327
- }
9938
+ const appChecks = [...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins];
9939
+ await runChecks(ctx, [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...appChecks]);
9328
9940
  if (options.build) {
9329
9941
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
9330
9942
  if (failure) raw.push(failure);
@@ -9334,30 +9946,57 @@ async function runDoctor(options = {}) {
9334
9946
  let changed = null;
9335
9947
  let skipped = false;
9336
9948
  const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
9337
- if (options.base && (ratchetNeeded || config.ratchet)) {
9949
+ if (options.base && (ratchetNeeded || config.ratchet || config.extend?.length)) {
9338
9950
  changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
9339
9951
  skipped ||= !changed;
9340
9952
  }
9341
9953
  const configFile = "file" in loaded ? loaded.file : null;
9342
- const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
9954
+ const guarded = (config.allow?.length ?? 0) + (config.extend?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
9343
9955
  let configSkipped = false;
9956
+ let baseExtend = [];
9344
9957
  if (options.base && configFile) {
9345
9958
  const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
9959
+ if (before && before !== "absent") baseExtend = before.extend;
9960
+ if (before === "absent") raw.push(...extensionsAdded(config.extend ?? [], [], options.base));
9346
9961
  if (before && before !== "absent") {
9347
9962
  raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
9348
9963
  raw.push(...rulesWeakened(config, before, options.base));
9964
+ raw.push(...extensionsAdded(config.extend ?? [], before.extend, options.base));
9349
9965
  }
9350
9966
  configSkipped = !before && guarded;
9351
9967
  }
9352
9968
  if (skipped || configSkipped) {
9353
9969
  raw.push(
9354
- configSkipped ? { rule: "ratchet-skipped", level: "error", file: "genesis config", message: `couldn't compare allow, rules and packageRules against ${options.base} (not a git repository, or the ref isn't fetched; in CI check out with fetch-depth: 0)` } : { rule: "ratchet-skipped", level: "warn", file: "genesis config", message: `couldn't compare against ${options.base} (not a git repository, or the ref isn't fetched); every rule ran at its full level` }
9970
+ configSkipped ? { rule: "ratchet-skipped", level: "error", file: "genesis config", message: `couldn't compare allow, extend, rules and packageRules against ${options.base} (not a git repository, or the ref isn't fetched; in CI check out with fetch-depth: 0)` } : { rule: "ratchet-skipped", level: "warn", file: "genesis config", message: `couldn't compare against ${options.base} (not a git repository, or the ref isn't fetched); every rule ran at its full level` }
9355
9971
  );
9356
9972
  }
9357
- let findings = applyConfig(raw, config, packageRuleIds(packages));
9973
+ const packageIds = packageRuleIds(packages);
9974
+ const extensionCtx = { config, files, packages, raw };
9975
+ const configured = applyConfig(raw, config, packageIds);
9976
+ let findings = applyExtensions(configured, extensionCtx);
9358
9977
  if (options.base && changed) {
9359
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path30.join(root, f)) });
9360
- }
9978
+ const isAppPath = (f) => existsSync(path30.join(root, f));
9979
+ const origins = options.changedFiles ? /* @__PURE__ */ new Map() : originsSince(root, options.base);
9980
+ const originOf = (f) => origins.get(f) ?? f;
9981
+ const dueRules = new Set(findings.filter((f) => f.level !== "info" && isRatcheted(f.rule, config, newOnly) && isAppPath(f.file) && touched(f.file, changed)).map((f) => f.rule));
9982
+ const heldExtensions = (config.extend ?? []).filter((e) => touched(e.file, changed) && baseExtend.some((b) => b.rule === e.rule && (b.file === e.file || b.file === originOf(e.file))));
9983
+ for (const e of heldExtensions) dueRules.add(e.rule);
9984
+ const snapshot = dueRules.size ? snapshotAtBase(root, options.base, files, changed, originOf) : null;
9985
+ let baseCounts;
9986
+ if (snapshot) {
9987
+ const before = [];
9988
+ await runChecks({ ...ctx, files: snapshot.files, report: (f) => before.push(f) }, baseChecks(dueRules, packageIds, packagePlugins, () => [...builtinChecks(config, { contracts: false, figma: false }), ...appChecks]));
9989
+ baseCounts = countFindings(applyConfig(before, config, packageIds));
9990
+ if (heldExtensions.length) {
9991
+ const counts = baseCounts;
9992
+ const held = new Set(heldExtensions);
9993
+ findings = applyExtensions(configured, { ...extensionCtx, limit: (e) => held.has(e) ? counts.get(countKey(originOf(e.file), e.rule)) ?? 0 : void 0 });
9994
+ }
9995
+ }
9996
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath, originOf, ...snapshot && baseCounts ? { baseCounts, existedAtBase: snapshot.existed } : {} });
9997
+ }
9998
+ findings = dedupeFindings(findings);
9999
+ const extensionsNew = (config.extend ?? []).filter((e) => findings.some((f) => f.rule === "extension-added" && f.file === e.file && f.subject === e.rule));
9361
10000
  const errors = findings.filter((f) => f.level === "error").length;
9362
10001
  const warnings = findings.filter((f) => f.level === "warn").length;
9363
10002
  const infos = findings.length - errors - warnings;
@@ -9371,9 +10010,24 @@ async function runDoctor(options = {}) {
9371
10010
  primitives: primitivesSummary(packages),
9372
10011
  errors,
9373
10012
  warnings,
9374
- infos
10013
+ infos,
10014
+ ...extensionsNew.length ? { extensionsAdded: extensionsNew } : {}
9375
10015
  };
9376
10016
  }
10017
+ function baseChecks(rules, preferIds, packagePlugins, all) {
10018
+ if ([...rules].every((r) => preferIds.has(r))) return packagePlugins.filter((p) => p.name === "package-rules");
10019
+ return all();
10020
+ }
10021
+ async function runChecks(ctx, checks) {
10022
+ for (const plugin of checks) {
10023
+ try {
10024
+ await plugin.check(ctx);
10025
+ } catch (err) {
10026
+ if (err instanceof DoctorConfigError) throw err;
10027
+ ctx.report({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
10028
+ }
10029
+ }
10030
+ }
9377
10031
  function builtinChecks(config, options = {}) {
9378
10032
  const packs = {
9379
10033
  native: { name: "native", check: checkNativePack },
@@ -9399,7 +10053,10 @@ function builtinChecks(config, options = {}) {
9399
10053
  { name: "studio-server-imports", check: checkStudioServerImports },
9400
10054
  { name: "removed-scope-names", check: checkRemovedScopeNames },
9401
10055
  { name: "stability-imports", check: checkStabilityImports },
9402
- { name: "agent-guide", check: checkAgentGuide },
10056
+ { name: "agent-guide", check: (ctx) => {
10057
+ checkAgentGuide(ctx);
10058
+ checkAgentHooks(ctx);
10059
+ } },
9403
10060
  { name: "overlays", check: (ctx) => checkOverlays(ctx) },
9404
10061
  { name: "lock-files", check: checkLockFiles },
9405
10062
  { name: "database-elsewhere", check: checkDatabaseHome },
@@ -9464,10 +10121,14 @@ function formatReport(result, options = {}) {
9464
10121
  `Genesis doctor: ${g.uiPackage}@${g.uiVersion}, ${g.components.length} components, ${g.tokens.size} tokens, ${result.ruleCount} app rules; raw tags checked: ${[...g.rawTags.keys()].join(", ") || "none"}`
9465
10122
  ];
9466
10123
  for (const f of result.findings) {
9467
- lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
10124
+ lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${(f.rules ?? [f.rule]).join(", ")}] ${f.message}`);
9468
10125
  }
9469
10126
  lines.push(options.verbose ? `Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}` : `Available but unused: ${result.unused.length} (genesis doctor --verbose lists them)`);
9470
10127
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
10128
+ if (result.extensionsAdded?.length) {
10129
+ lines.push(`Extensions added on this branch (${result.extensionsAdded.length}); the pull request's review accepts each:`);
10130
+ for (const e of result.extensionsAdded) lines.push(` ${e.file} [${e.rule}] builds on ${e.buildsOn}: ${e.reason}${e.upstream ? ` (upstream: ${e.upstream})` : ""}`);
10131
+ }
9471
10132
  const info = result.infos ? `, ${result.infos} info` : "";
9472
10133
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
9473
10134
  return lines.join("\n");
@@ -9481,7 +10142,8 @@ function toJson(result) {
9481
10142
  infos: result.infos,
9482
10143
  findings: result.findings,
9483
10144
  unused: result.unused,
9484
- primitives: result.primitives
10145
+ primitives: result.primitives,
10146
+ ...result.extensionsAdded ? { extensionsAdded: result.extensionsAdded } : {}
9485
10147
  };
9486
10148
  }
9487
10149
  function genesisSummary(g) {
@@ -9516,8 +10178,10 @@ var init_doctor = __esm({
9516
10178
  init_stability();
9517
10179
  init_package_rules();
9518
10180
  init_ratchet();
10181
+ init_extensions();
9519
10182
  init_contracts();
9520
10183
  init_primitives();
10184
+ init_agent_hooks();
9521
10185
  init_overlays();
9522
10186
  init_lock_files();
9523
10187
  init_database2();
@@ -9538,7 +10202,9 @@ var init_doctor = __esm({
9538
10202
  init_package_rules();
9539
10203
  init_primitives();
9540
10204
  init_ratchet();
10205
+ init_extensions();
9541
10206
  init_contracts();
10207
+ init_agent_hooks();
9542
10208
  RATCHETED_BY_DEFAULT = ["deprecated-import", "genesis-eslint-config"];
9543
10209
  }
9544
10210
  });
@@ -9685,13 +10351,13 @@ __export(features_exports, {
9685
10351
  runFeaturesCheck: () => runFeaturesCheck,
9686
10352
  runFeaturesFind: () => runFeaturesFind
9687
10353
  });
9688
- function isObject4(value) {
10354
+ function isObject5(value) {
9689
10355
  return typeof value === "object" && value !== null && !Array.isArray(value);
9690
10356
  }
9691
10357
  function readObject(file, key2) {
9692
10358
  try {
9693
10359
  const json = JSON.parse(readFileSync(file, "utf-8"));
9694
- return isObject4(json[key2]) ? json[key2] : {};
10360
+ return isObject5(json[key2]) ? json[key2] : {};
9695
10361
  } catch {
9696
10362
  return {};
9697
10363
  }
@@ -9713,9 +10379,9 @@ async function loadRegistry(input) {
9713
10379
  const load = async (file) => await jiti.import(path30.join(root, file));
9714
10380
  const mod = await load(registry);
9715
10381
  const features2 = mod.features ?? mod.default;
9716
- if (!isObject4(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
10382
+ if (!isObject5(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
9717
10383
  const flags = options.flagsFile ? (await load(options.flagsFile)).flags : mod.flags;
9718
- if (flags !== void 0 && !isObject4(flags)) {
10384
+ if (flags !== void 0 && !isObject5(flags)) {
9719
10385
  throw new Error(`${options.flagsFile ?? registry}'s \`flags\` export must be an object (from defineFlags).`);
9720
10386
  }
9721
10387
  const { dir: _dir, registry: _registry, flagsFile: _flagsFile, prs: _prs, gh: _gh, ...rest } = options;
@@ -9989,8 +10655,8 @@ function routeTags(source) {
9989
10655
  }
9990
10656
  function wireStudioRoute(source, route, pageImportPath) {
9991
10657
  const tags = routeTags(source);
9992
- const relative18 = route.replace(/^\//, "");
9993
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative18.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
10658
+ const relative19 = route.replace(/^\//, "");
10659
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative19.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
9994
10660
  if (existing) {
9995
10661
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
9996
10662
  }
@@ -9998,17 +10664,17 @@ function wireStudioRoute(source, route, pageImportPath) {
9998
10664
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
9999
10665
  if (roots.length !== 1) {
10000
10666
  return {
10001
- skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative18}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
10667
+ skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative19}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
10002
10668
  };
10003
10669
  }
10004
10670
  const layout = roots[0];
10005
10671
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
10006
- if (base && !relative18.startsWith(`${base}/`)) {
10672
+ if (base && !relative19.startsWith(`${base}/`)) {
10007
10673
  return {
10008
10674
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
10009
10675
  };
10010
10676
  }
10011
- const childPath = base ? relative18.slice(base.length + 1) : relative18;
10677
+ const childPath = base ? relative19.slice(base.length + 1) : relative19;
10012
10678
  const guard = GUARD.exec(source)?.[1];
10013
10679
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
10014
10680
  const before = source.slice(0, layout.close);
@@ -11258,7 +11924,7 @@ function promotions(root, name) {
11258
11924
  });
11259
11925
  }
11260
11926
  function mergeJson(base, mine, theirs) {
11261
- if (isObject5(base) && isObject5(mine) && isObject5(theirs)) {
11927
+ if (isObject6(base) && isObject6(mine) && isObject6(theirs)) {
11262
11928
  const out = {};
11263
11929
  for (const key2 of /* @__PURE__ */ new Set([...Object.keys(mine), ...Object.keys(theirs)])) {
11264
11930
  const inMine = key2 in mine;
@@ -11422,7 +12088,7 @@ function ownManifestFields(mergedText, upstreamText) {
11422
12088
  if (!ours || !up) continue;
11423
12089
  for (const [dep, spec] of Object.entries(up)) if (typeof spec === "string" && spec.startsWith("workspace:") && typeof ours[dep] === "string") ours[dep] = spec;
11424
12090
  }
11425
- const sorted2 = (v) => isObject5(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sorted2(v[k])])) : Array.isArray(v) ? v.map(sorted2) : v;
12091
+ const sorted2 = (v) => isObject6(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sorted2(v[k])])) : Array.isArray(v) ? v.map(sorted2) : v;
11426
12092
  return [.../* @__PURE__ */ new Set([...Object.keys(mine), ...Object.keys(theirs)])].filter((k) => JSON.stringify(sorted2(mine[k])) !== JSON.stringify(sorted2(theirs[k]))).sort();
11427
12093
  }
11428
12094
  function folderReferences(root, plan) {
@@ -11475,14 +12141,14 @@ function pinManifest(root, plan, file, text) {
11475
12141
  }
11476
12142
  }
11477
12143
  for (const o of [json.overrides, json.resolutions, json.pnpm?.overrides]) {
11478
- if (isObject5(o) && local(o[plan.name])) {
12144
+ if (isObject6(o) && local(o[plan.name])) {
11479
12145
  delete o[plan.name];
11480
12146
  touched2 = true;
11481
12147
  }
11482
12148
  }
11483
12149
  const names = (entry) => typeof entry === "string" && path30.resolve(here, entry) === overlay;
11484
12150
  const ws = json.workspaces;
11485
- const list = Array.isArray(ws) ? ws : isObject5(ws) && Array.isArray(ws.packages) ? ws.packages : null;
12151
+ const list = Array.isArray(ws) ? ws : isObject6(ws) && Array.isArray(ws.packages) ? ws.packages : null;
11486
12152
  if (list?.some(names)) {
11487
12153
  const kept = list.filter((entry) => !names(entry));
11488
12154
  if (Array.isArray(ws)) json.workspaces = kept;
@@ -11573,7 +12239,7 @@ function overlayChecklist(plans) {
11573
12239
  }
11574
12240
  return lines;
11575
12241
  }
11576
- var GENESIS_REPOSITORY, SKIP, FETCH_TIMEOUT_MS, isObject5, same, LOCAL_SUFFIX;
12242
+ var GENESIS_REPOSITORY, SKIP, FETCH_TIMEOUT_MS, isObject6, same, LOCAL_SUFFIX;
11577
12243
  var init_overlays2 = __esm({
11578
12244
  "src/upgrade/overlays.ts"() {
11579
12245
  init_owned();
@@ -11586,7 +12252,7 @@ var init_overlays2 = __esm({
11586
12252
  GENESIS_REPOSITORY = "https://github.com/marktiderman/genesis.git";
11587
12253
  SKIP = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo", ".git"]);
11588
12254
  FETCH_TIMEOUT_MS = 12e4;
11589
- isObject5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
12255
+ isObject6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11590
12256
  same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
11591
12257
  LOCAL_SUFFIX = /[+-]local\.(0|[1-9]\d*)$/;
11592
12258
  }
@@ -12300,9 +12966,9 @@ async function runScaffold(opts, fs2) {
12300
12966
  function joinPath(...parts) {
12301
12967
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
12302
12968
  }
12303
- function dirname(path61) {
12304
- const idx = path61.lastIndexOf("/");
12305
- return idx === -1 ? "." : path61.slice(0, idx);
12969
+ function dirname(path62) {
12970
+ const idx = path62.lastIndexOf("/");
12971
+ return idx === -1 ? "." : path62.slice(0, idx);
12306
12972
  }
12307
12973
  function brandPackageJson(consumer, genesisVersion) {
12308
12974
  return JSON.stringify(
@@ -12686,8 +13352,18 @@ program.command("primitives").description("Deprecated name of `genesis catalog`
12686
13352
  for (const note of packages.flatMap((p) => p.ignored ?? [])) console.error(`! ${note}`);
12687
13353
  if (broken.length) process.exitCode = 1;
12688
13354
  });
12689
- program.command("agents").description(`Write the agent guide from the installed Genesis packages: .claude/skills/genesis/SKILL.md and a marked block in AGENTS.md`).option("--check", "Write nothing; exit 1 if either is missing or out of date (for CI)", false).option("--rules", "Check the repo against the agent rules of engagement a script can check (docs/agents/RULES.md); exit 1 on a break", false).option("--batch <pattern>", "With --rules: the branch pattern staging batches use in workflow filters", "staging/**").option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
13355
+ program.command("agents").description(`Write the agent guide from the installed Genesis packages: .claude/skills/genesis/SKILL.md and a marked block in AGENTS.md`).option("--check", "Write nothing; exit 1 if either is missing or out of date (for CI)", false).option("--rules", "Check the repo against the agent rules of engagement a script can check (docs/agents/RULES.md); exit 1 on a break", false).option("--batch <pattern>", "With --rules: the branch pattern staging batches use in workflow filters", "staging/**").option("--hooks", "Also write the agent hooks into .claude/settings.json: the Genesis rules for Explore and Plan subagents, and deny rules for secret files", false).option("--hook <name>", "Run as a Claude Code hook and print its output (subagent-start); never fails").option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
12690
13356
  const root = path30.resolve(opts.dir);
13357
+ if (opts.hook) {
13358
+ try {
13359
+ if (opts.hook === "subagent-start") {
13360
+ const doctor2 = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
13361
+ console.log(doctor2.subagentHookOutput(root, doctor2.discoverPackages(root)));
13362
+ }
13363
+ } catch {
13364
+ }
13365
+ return;
13366
+ }
12691
13367
  if (opts.rules && opts.check) return program.error("--rules checks the repo, --check the agent guide: run them one at a time");
12692
13368
  if (opts.rules) {
12693
13369
  if (!existsSync(path30.join(root, "packages")) && !existsSync(path30.join(root, ".github", "workflows"))) {
@@ -12711,16 +13387,23 @@ program.command("agents").description(`Write the agent guide from the installed
12711
13387
  }
12712
13388
  if (opts.check) {
12713
13389
  const state = doctor.agentGuideState(root, packages);
12714
- const bad = Object.entries(state).filter(([, v]) => v !== "ok");
13390
+ const bad = Object.entries(state).filter(([k, v]) => v !== "ok" && !(k === "claude" && v === "no-import"));
13391
+ if (doctor.agentHooksState(root) === "stale") bad.push([doctor.SETTINGS_PATH, "has an older Genesis hook"]);
12715
13392
  if (bad.length) {
12716
- console.error(`\u2717 The agent guide is ${bad.map(([k, v]) => `${k === "skill" ? doctor.SKILL_PATH : "AGENTS.md"} ${v}`).join(", ")}. Run \`genesis agents\` and commit the result.`);
13393
+ const guideBad = bad.some(([k]) => k !== doctor.SETTINGS_PATH && k !== "claude");
13394
+ const fix = [
13395
+ ...guideBad || state.claude === "missing" ? ["Run `genesis agents` and commit the result."] : [],
13396
+ ...state.claude === "blocked" ? [`For CLAUDE.md, ${doctor.BLOCKED_FIX}.`] : [],
13397
+ ...bad.some(([k]) => k === doctor.SETTINGS_PATH) ? ["Run `genesis agents --hooks` to update the hook."] : []
13398
+ ].join(" ");
13399
+ console.error(`\u2717 The agent guide is ${bad.map(([k, v]) => k === doctor.SETTINGS_PATH ? `${k} ${v}` : `${k === "skill" ? doctor.SKILL_PATH : k === "claude" ? "CLAUDE.md" : "AGENTS.md"} ${v}`).join(", ")}. ${fix}`);
12717
13400
  process.exitCode = 1;
12718
13401
  return;
12719
13402
  }
12720
13403
  console.log("\u2714 The agent guide matches the installed Genesis packages.");
12721
13404
  return;
12722
13405
  }
12723
- const changed = doctor.writeAgentGuide(root, packages);
13406
+ const changed = [...doctor.writeAgentGuide(root, packages), ...opts.hooks ? doctor.writeAgentHooks(root) : []];
12724
13407
  console.log(changed.length ? `\u2714 Wrote ${changed.join(", ")}` : "= The agent guide is up to date.");
12725
13408
  });
12726
13409
  var features = program.command("features").description('The feature registry: one typed features.ts, everything else generated from it. Settings: genesis.config.json "features" (or package.json "genesisFeatures")');
@@ -12803,22 +13486,22 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
12803
13486
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
12804
13487
  const root = path30.resolve(opts.dir);
12805
13488
  const packageJson = JSON.parse(await fs.readFile(path30.join(root, "package.json"), "utf-8").catch(() => "{}"));
12806
- const existsSync45 = (await import('fs')).existsSync;
13489
+ const existsSync46 = (await import('fs')).existsSync;
12807
13490
  const readSync = (await import('fs')).readFileSync;
12808
- const readdirSync20 = (await import('fs')).readdirSync;
13491
+ const readdirSync21 = (await import('fs')).readdirSync;
12809
13492
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
12810
13493
  throw new Error("--host must be next, tanstack-start or supabase-function.");
12811
13494
  }
12812
13495
  const plan = planStudioInit2(
12813
13496
  {
12814
13497
  packageJson,
12815
- exists: (p) => existsSync45(path30.join(root, p)),
12816
- read: (p) => existsSync45(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
13498
+ exists: (p) => existsSync46(path30.join(root, p)),
13499
+ read: (p) => existsSync46(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
12817
13500
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
12818
13501
  listDeep: (p) => {
12819
13502
  const out = [];
12820
13503
  const walk4 = (rel) => {
12821
- for (const entry of readdirSync20(path30.join(root, rel), { withFileTypes: true })) {
13504
+ for (const entry of readdirSync21(path30.join(root, rel), { withFileTypes: true })) {
12822
13505
  const child = `${rel}/${entry.name}`;
12823
13506
  if (entry.isDirectory()) walk4(child);
12824
13507
  else out.push(child);
@@ -12832,7 +13515,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
12832
13515
  },
12833
13516
  list: (p) => {
12834
13517
  try {
12835
- return readdirSync20(path30.join(root, p));
13518
+ return readdirSync21(path30.join(root, p));
12836
13519
  } catch {
12837
13520
  return [];
12838
13521
  }
@@ -12853,14 +13536,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
12853
13536
  console.log(`+ ${file.path} (appended)`);
12854
13537
  continue;
12855
13538
  }
12856
- if (existsSync45(target) && !opts.force) {
13539
+ if (existsSync46(target) && !opts.force) {
12857
13540
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
12858
13541
  continue;
12859
13542
  }
12860
13543
  await fs.writeFile(target, file.content, "utf-8");
12861
13544
  console.log(`+ ${file.path}`);
12862
13545
  }
12863
- const pm = existsSync45(path30.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync45(path30.join(root, "yarn.lock")) ? "yarn add" : existsSync45(path30.join(root, "bun.lock")) || existsSync45(path30.join(root, "bun.lockb")) ? "bun add" : "npm install";
13546
+ const pm = existsSync46(path30.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync46(path30.join(root, "yarn.lock")) ? "yarn add" : existsSync46(path30.join(root, "bun.lock")) || existsSync46(path30.join(root, "bun.lockb")) ? "bun add" : "npm install";
12864
13547
  console.log("");
12865
13548
  console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
12866
13549
  console.log(` 1. ${pm} ${plan.install.map((p) => /[\s<>|]/.test(p) ? `"${p}"` : p).join(" ")}`);