@marktiderman/genesis-cli 1.22.1 → 1.24.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
@@ -1042,6 +1042,7 @@ __export(config_exports, {
1042
1042
  readGenesisConfig: () => readGenesisConfig,
1043
1043
  validateAppFolder: () => validateAppFolder,
1044
1044
  validateConfig: () => validateConfig,
1045
+ validateEnvironments: () => validateEnvironments,
1045
1046
  validateLinks: () => validateLinks,
1046
1047
  validatePrivacy: () => validatePrivacy,
1047
1048
  validateSupabase: () => validateSupabase
@@ -1049,6 +1050,24 @@ __export(config_exports, {
1049
1050
  function privacyDataType(type) {
1050
1051
  return PRIVACY_DATA_TYPES[type.toLowerCase()];
1051
1052
  }
1053
+ function validateEnvironments(raw, source = "config") {
1054
+ const fail = (msg) => {
1055
+ throw new GenesisConfigError(`${source}: ${msg}`);
1056
+ };
1057
+ if (!isObject2(raw)) return fail(`"environments" must be an object`);
1058
+ for (const key2 of Object.keys(raw)) if (!ENVIRONMENT_KEYS.has(key2)) fail(`environments: unknown setting "${key2}" (known: previews, label, branchPrefix)`);
1059
+ const out = {};
1060
+ if (raw.previews !== void 0) {
1061
+ 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)})`);
1062
+ out.previews = raw.previews;
1063
+ }
1064
+ for (const key2 of ["label", "branchPrefix"]) {
1065
+ if (raw[key2] === void 0) continue;
1066
+ if (typeof raw[key2] !== "string") fail(`environments.${key2} must be a string ("" turns that check off)`);
1067
+ out[key2] = raw[key2];
1068
+ }
1069
+ return out;
1070
+ }
1052
1071
  function appPath2(v, where2, fail) {
1053
1072
  if (typeof v !== "string" || !v.trim()) return fail(`${where2} must be a non-empty path`);
1054
1073
  if (path30.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
@@ -1107,6 +1126,7 @@ function readGenesisConfig(root) {
1107
1126
  if (supabase !== true) out.supabase = supabase;
1108
1127
  }
1109
1128
  if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
1129
+ if (raw.environments !== void 0) out.environments = validateEnvironments(raw.environments, file);
1110
1130
  return out;
1111
1131
  }
1112
1132
  function isPlainFolder(value) {
@@ -1300,6 +1320,7 @@ function validateConfig(raw, source = "config") {
1300
1320
  if (!want) fail(`${pack}: unknown setting "${k}"`);
1301
1321
  if (want === "string" && typeof v !== "string") fail(`${pack}.${k} must be a string`);
1302
1322
  if (want === "list" && !isStringList(v)) fail(`${pack}.${k} must be a list of strings`);
1323
+ if (want === "boolean" && typeof v !== "boolean") fail(`${pack}.${k} must be true or false`);
1303
1324
  if (want === "string" && !v.trim()) fail(`${pack}.${k} must not be empty`);
1304
1325
  if (want === "path") block[k] = appPath2(v, `${pack}.${k}`, fail);
1305
1326
  }
@@ -1325,7 +1346,7 @@ function isObject2(v) {
1325
1346
  function isStringList(v) {
1326
1347
  return Array.isArray(v) && v.every((x) => typeof x === "string");
1327
1348
  }
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;
1349
+ var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, ENVIRONMENT_KEYS, 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;
1329
1350
  var init_config = __esm({
1330
1351
  "src/doctor/config.ts"() {
1331
1352
  GenesisConfigError = class extends Error {
@@ -1379,6 +1400,7 @@ var init_config = __esm({
1379
1400
  "third-party advertising": "NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising",
1380
1401
  other: "NSPrivacyCollectedDataTypePurposeOther"
1381
1402
  };
1403
+ ENVIRONMENT_KEYS = /* @__PURE__ */ new Set(["previews", "label", "branchPrefix", "$comment"]);
1382
1404
  STRING_LISTS = ["src", "extensions", "ignore", "tokenFiles", "ignoreTokenPrefixes", "localPrimitiveDirs", "build", "componentPackages"];
1383
1405
  STRINGS = ["uiPackage", "rulesDoc"];
1384
1406
  KNOWN = /* @__PURE__ */ new Set([
@@ -1410,7 +1432,7 @@ var init_config = __esm({
1410
1432
  PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
1411
1433
  PACK_KEYS = {
1412
1434
  native: { routerRoot: "path" },
1413
- supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
1435
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string", automaticBranching: "boolean" },
1414
1436
  packages: { base: "string" }
1415
1437
  };
1416
1438
  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 +2045,7 @@ function globToRegExp(glob) {
2023
2045
  }
2024
2046
  function globMatcher(globs) {
2025
2047
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
2026
- return (path61) => res.some((re) => re.test(path61));
2048
+ return (path62) => res.some((re) => re.test(path62));
2027
2049
  }
2028
2050
  var init_glob = __esm({
2029
2051
  "src/doctor/glob.ts"() {
@@ -4202,6 +4224,7 @@ var init_rules = __esm({
4202
4224
  "migration-edited",
4203
4225
  "migration-testing-kit",
4204
4226
  "migration-view-rls",
4227
+ "exposed-schema-created-later",
4205
4228
  // packages pack
4206
4229
  "package-app-import",
4207
4230
  "package-undeclared-dependency",
@@ -6194,6 +6217,66 @@ function checkSupabasePack(ctx) {
6194
6217
  checkViewInvoker(ctx, migrations, exposed);
6195
6218
  checkDefinerSearchPath(ctx, migrations);
6196
6219
  checkTestingKit(ctx, migrations);
6220
+ checkExposedSchemasCreatedLater(ctx, dir, migrations, settings2.exposedSchemas, settings2.automaticBranching !== false);
6221
+ }
6222
+ function apiSchemas(toml) {
6223
+ const lines = toml.split("\n");
6224
+ const start = lines.findIndex((l) => /^\s*\[api\]\s*(?:#.*)?$/.test(l));
6225
+ if (start < 0) return null;
6226
+ let end = lines.findIndex((l, i) => i > start && /^\s*\[/.test(l));
6227
+ if (end < 0) end = lines.length;
6228
+ const bare3 = (l) => {
6229
+ let quoted = false;
6230
+ for (let i = 0; i < l.length; i++) {
6231
+ if (l[i] === '"' && l[i - 1] !== "\\") quoted = !quoted;
6232
+ else if (l[i] === "#" && !quoted) return l.slice(0, i);
6233
+ }
6234
+ return l;
6235
+ };
6236
+ const body = lines.slice(start + 1, end).map(bare3);
6237
+ const enabled = !body.some((l) => /^\s*enabled\s*=\s*false\b/.test(l));
6238
+ const at = body.findIndex((l) => /^\s*schemas\s*=/.test(l));
6239
+ if (at < 0) return { enabled, schemas: [], line: start + 1 };
6240
+ let list = "";
6241
+ for (let i = at; i < body.length; i++) {
6242
+ list += `${body[i]}
6243
+ `;
6244
+ if (body[i].includes("]")) break;
6245
+ }
6246
+ const inner = /\[([\s\S]*?)\]/.exec(list)?.[1] ?? "";
6247
+ const schemas = [...inner.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((m) => (m[1] ?? m[2]).trim().toLowerCase()).filter(Boolean);
6248
+ return { enabled, schemas, line: start + at + 2 };
6249
+ }
6250
+ function checkExposedSchemasCreatedLater(ctx, dir, migrations, configured, branching) {
6251
+ const created = /* @__PURE__ */ new Map();
6252
+ for (const { file, statements } of migrations) {
6253
+ for (const { sql, line } of statements) {
6254
+ const m = /^create schema (?:if not exists )?"?([\w$]+)"?/.exec(sql);
6255
+ if (m && m[1] !== "authorization" && !created.has(m[1])) created.set(m[1], { file, line });
6256
+ }
6257
+ }
6258
+ const tomlFile = path30.posix.join(path30.posix.dirname(dir), "config.toml");
6259
+ const tomlText = existsSync(path30.join(ctx.root, tomlFile)) ? readFileSync(path30.join(ctx.root, tomlFile), "utf8") : null;
6260
+ const api2 = tomlText === null ? null : apiSchemas(tomlText);
6261
+ const sources = [];
6262
+ if (api2?.enabled) for (const schema of api2.schemas) sources.push({ schema, file: tomlFile, line: api2.line, where: `${tomlFile} [api] schemas` });
6263
+ for (const schema of api2?.enabled === false ? [] : configured ?? []) {
6264
+ const s = schema.toLowerCase();
6265
+ if (!sources.some((x) => x.schema === s)) sources.push({ schema: s, file: "genesis.config.json", where: "doctor.supabase.exposedSchemas" });
6266
+ }
6267
+ for (const { schema, file, line, where: where2 } of sources) {
6268
+ if (PLATFORM_SCHEMAS.has(schema)) continue;
6269
+ const by = created.get(schema);
6270
+ if (by && !branching) continue;
6271
+ ctx.report({
6272
+ rule: "exposed-schema-created-later",
6273
+ level: "warn",
6274
+ file,
6275
+ ...line ? { line } : {},
6276
+ subject: schema,
6277
+ 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`
6278
+ });
6279
+ }
6197
6280
  }
6198
6281
  function checkTestingKit(ctx, migrations) {
6199
6282
  for (const { file, statements } of migrations) {
@@ -6456,7 +6539,7 @@ function checkDefinerSearchPath(ctx, migrations) {
6456
6539
  });
6457
6540
  }
6458
6541
  }
6459
- var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, MULTIWORD_TYPE;
6542
+ var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, MULTIWORD_TYPE, PLATFORM_SCHEMAS;
6460
6543
  var init_supabase = __esm({
6461
6544
  "src/doctor/supabase.ts"() {
6462
6545
  init_config();
@@ -6476,6 +6559,7 @@ var init_supabase = __esm({
6476
6559
  float8: "double precision"
6477
6560
  };
6478
6561
  MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
6562
+ PLATFORM_SCHEMAS = /* @__PURE__ */ new Set(["public", "graphql_public", "graphql", "extensions", "storage", "auth", "realtime", "vault"]);
6479
6563
  }
6480
6564
  });
6481
6565
  function nodeModulesOf(dir) {
@@ -8091,6 +8175,18 @@ var init_ratchet = __esm({
8091
8175
  ]);
8092
8176
  }
8093
8177
  });
8178
+ function pathTaken(file) {
8179
+ try {
8180
+ lstatSync(file);
8181
+ return true;
8182
+ } catch {
8183
+ try {
8184
+ return readdirSync(path30.dirname(file)).some((n) => n.toLowerCase() === path30.basename(file).toLowerCase());
8185
+ } catch {
8186
+ return false;
8187
+ }
8188
+ }
8189
+ }
8094
8190
  function primitivesCatalog(packages) {
8095
8191
  const rows = [...CORE];
8096
8192
  for (const rule of preferRules(packages)) {
@@ -8132,7 +8228,74 @@ function formatPrimitives(rows) {
8132
8228
  }
8133
8229
  return lines.join("\n");
8134
8230
  }
8135
- function renderSkill(rows) {
8231
+ function skillDescription(text) {
8232
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1];
8233
+ if (!fm) return "";
8234
+ const lines = fm.split(/\r?\n/);
8235
+ const i = lines.findIndex((l) => /^description:/.test(l));
8236
+ if (i < 0) return "";
8237
+ const first = lines[i].replace(/^description:\s*/, "").trim();
8238
+ if (first && !/^[>|][+-]?$/.test(first)) return first.replace(/^["']|["']$/g, "");
8239
+ const more = [];
8240
+ for (const l of lines.slice(i + 1)) {
8241
+ if (!/^\s+\S/.test(l)) break;
8242
+ more.push(l.trim());
8243
+ }
8244
+ return more.join(" ");
8245
+ }
8246
+ function stableGuidePath(root, p) {
8247
+ const real2 = (f) => {
8248
+ try {
8249
+ return realpathSync(f);
8250
+ } catch {
8251
+ return null;
8252
+ }
8253
+ };
8254
+ const want = real2(p.dir);
8255
+ for (let dir = root, level = 0; level <= GUIDE_SEARCH_LEVELS; level++) {
8256
+ const found = path30.join(dir, "node_modules", p.name);
8257
+ if (existsSync(found)) {
8258
+ const file = path30.join(found, "SKILL.md");
8259
+ return want !== null && real2(found) === want && existsSync(file) ? file : null;
8260
+ }
8261
+ if (existsSync(path30.join(dir, ".git")) || existsSync(path30.join(dir, "pnpm-workspace.yaml"))) return null;
8262
+ const up = path30.dirname(dir);
8263
+ if (up === dir) return null;
8264
+ dir = up;
8265
+ }
8266
+ return null;
8267
+ }
8268
+ function packageGuides(root, packages) {
8269
+ const guides = [];
8270
+ for (const p of packages) {
8271
+ const stable = p.local ? path30.join(p.dir, "SKILL.md") : stableGuidePath(root, p);
8272
+ const text = stable === null ? null : read(stable);
8273
+ if (stable === null || text === null) continue;
8274
+ const description = skillDescription(text);
8275
+ const at = description.indexOf("Load before");
8276
+ guides.push({ package: p.name, path: path30.relative(root, stable).split(path30.sep).join("/"), when: at >= 0 ? description.slice(at) : description });
8277
+ }
8278
+ return guides.sort((a, b) => a.package.localeCompare(b.package));
8279
+ }
8280
+ function unlistedGuides(root, packages) {
8281
+ const listed = new Set(packageGuides(root, packages).map((g) => g.package));
8282
+ return packages.filter((p) => !p.local && !listed.has(p.name) && existsSync(path30.join(p.dir, "SKILL.md"))).map((p) => p.name).sort();
8283
+ }
8284
+ function guidesSection(guides) {
8285
+ if (!guides.length) return [];
8286
+ return [
8287
+ "### Package guides (they match the installed versions)",
8288
+ "",
8289
+ "Before using a package's primitives, read its guide:",
8290
+ "",
8291
+ ...guides.map((g) => `- \`${g.path}\` (${g.package}): ${g.when}`),
8292
+ ""
8293
+ ];
8294
+ }
8295
+ function agentRules() {
8296
+ return RULES;
8297
+ }
8298
+ function renderSkill(rows, guides = []) {
8136
8299
  return [
8137
8300
  "---",
8138
8301
  "name: genesis",
@@ -8145,6 +8308,7 @@ function renderSkill(rows) {
8145
8308
  "",
8146
8309
  ...RULES.map((r) => `- ${r}`),
8147
8310
  "",
8311
+ ...guidesSection(guides),
8148
8312
  "## What to use for each need",
8149
8313
  "",
8150
8314
  catalogTable(rows, { docs: true }),
@@ -8153,7 +8317,7 @@ function renderSkill(rows) {
8153
8317
  ""
8154
8318
  ].join("\n");
8155
8319
  }
8156
- function renderAgentsBlock(rows) {
8320
+ function renderAgentsBlock(rows, guides = []) {
8157
8321
  return [
8158
8322
  AGENTS_START,
8159
8323
  "## Building with Genesis",
@@ -8164,6 +8328,7 @@ function renderAgentsBlock(rows) {
8164
8328
  "",
8165
8329
  ...RULES.map((r) => `- ${r}`),
8166
8330
  "",
8331
+ ...guidesSection(guides),
8167
8332
  catalogTable(rows),
8168
8333
  AGENTS_END
8169
8334
  ].join("\n");
@@ -8193,12 +8358,13 @@ function currentAgentsBlock(agents) {
8193
8358
  }
8194
8359
  function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
8195
8360
  const rows = primitivesCatalog(packages);
8361
+ const guides = packageGuides(root, packages);
8196
8362
  const changed = [];
8197
8363
  const agents = path30.join(root, agentsFile);
8198
8364
  const before = read(agents);
8199
- const after = mergeAgentsBlock(before, renderAgentsBlock(rows));
8365
+ const after = mergeAgentsBlock(before, renderAgentsBlock(rows, guides));
8200
8366
  const skill = path30.join(root, SKILL_PATH);
8201
- const skillText = renderSkill(rows);
8367
+ const skillText = renderSkill(rows, guides);
8202
8368
  if (read(skill)?.replace(/\r\n/g, "\n") !== skillText) {
8203
8369
  mkdirSync(path30.dirname(skill), { recursive: true });
8204
8370
  writeFileSync(skill, skillText);
@@ -8208,15 +8374,44 @@ function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
8208
8374
  writeFileSync(agents, after);
8209
8375
  changed.push(agentsFile);
8210
8376
  }
8377
+ const claude = path30.join(root, "CLAUDE.md");
8378
+ if (agentsFile === "AGENTS.md" && !pathTaken(claude)) {
8379
+ writeFileSync(claude, CLAUDE_IMPORT);
8380
+ changed.push("CLAUDE.md");
8381
+ }
8211
8382
  return changed;
8212
8383
  }
8384
+ function claudeState(root) {
8385
+ const file = path30.join(root, "CLAUDE.md");
8386
+ let names = [];
8387
+ try {
8388
+ names = readdirSync(root);
8389
+ } catch {
8390
+ }
8391
+ if (!names.includes("CLAUDE.md")) return names.some((n) => n.toLowerCase() === "claude.md") ? "blocked" : "missing";
8392
+ let text;
8393
+ try {
8394
+ text = readFileSync(file, "utf8");
8395
+ } catch {
8396
+ return "blocked";
8397
+ }
8398
+ if (/^@AGENTS\.md\b/m.test(text)) return "ok";
8399
+ try {
8400
+ if (realpathSync(file) === realpathSync(path30.join(root, "AGENTS.md"))) return "ok";
8401
+ } catch {
8402
+ }
8403
+ return "no-import";
8404
+ }
8213
8405
  function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
8214
8406
  const rows = primitivesCatalog(packages);
8407
+ const guides = packageGuides(root, packages);
8215
8408
  const skill = read(path30.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
8216
8409
  const block = currentAgentsBlock(read(path30.join(root, agentsFile)));
8217
8410
  return {
8218
- skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
8219
- agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
8411
+ skill: skill === null ? "missing" : skill === renderSkill(rows, guides) ? "ok" : "stale",
8412
+ agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows, guides) ? "ok" : "stale",
8413
+ // Only the default AGENTS.md gets a CLAUDE.md written for it, so only then is a missing one reported.
8414
+ claude: agentsFile !== "AGENTS.md" ? "ok" : claudeState(root)
8220
8415
  };
8221
8416
  }
8222
8417
  function checkAgentGuide(ctx) {
@@ -8234,12 +8429,27 @@ function checkAgentGuide(ctx) {
8234
8429
  }[state.agents];
8235
8430
  ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
8236
8431
  }
8432
+ if (state.claude === "no-import") {
8433
+ 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" });
8434
+ }
8435
+ if (state.claude === "missing") {
8436
+ 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\`)` });
8437
+ }
8438
+ if (state.claude === "blocked") {
8439
+ 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}` });
8440
+ }
8441
+ const unlisted = unlistedGuides(ctx.root, ctx.packages);
8442
+ if (unlisted.length) {
8443
+ 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.` });
8444
+ }
8237
8445
  }
8238
- var GENESIS_DOCS, CORE, cell, importCell, SKILL_PATH, AGENTS_START, AGENTS_END, RULES, read;
8446
+ var GENESIS_DOCS, read, CLAUDE_IMPORT, CORE, cell, importCell, SKILL_PATH, AGENTS_START, AGENTS_END, RULES, GUIDE_SEARCH_LEVELS, BLOCKED_FIX;
8239
8447
  var init_primitives = __esm({
8240
8448
  "src/doctor/primitives.ts"() {
8241
8449
  init_package_rules();
8242
8450
  GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
8451
+ read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
8452
+ CLAUDE_IMPORT = "@AGENTS.md\n";
8243
8453
  CORE = [
8244
8454
  {
8245
8455
  need: "anything, before building it",
@@ -8281,14 +8491,105 @@ var init_primitives = __esm({
8281
8491
  AGENTS_START = "<!-- genesis-primitives:start -->";
8282
8492
  AGENTS_END = "<!-- genesis-primitives:end -->";
8283
8493
  RULES = [
8284
- "Use the Genesis primitive for the need first: reuse, then extend, then invent (docs/FRAMEWORK.md, G1 to G6).",
8494
+ `Use the Genesis primitive for the need first: reuse, then extend, then invent (G1 to G6 in ${GENESIS_DOCS}/FRAMEWORK.md).`,
8285
8495
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
8286
8496
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
8287
8497
  "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
8498
  "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
8289
8499
  "Run `genesis doctor` before you finish; it enforces these rules."
8290
8500
  ];
8291
- read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
8501
+ GUIDE_SEARCH_LEVELS = 4;
8502
+ BLOCKED_FIX = "rename or replace it with a CLAUDE.md file (or remove the dangling link), then run genesis agents";
8503
+ }
8504
+ });
8505
+ function subagentContext(root, packages) {
8506
+ const guides = packageGuides(root, packages);
8507
+ return [
8508
+ "This is a Genesis app. Follow these rules (the app's AGENTS.md has the full guide):",
8509
+ ...agentRules().map((r) => `- ${r}`),
8510
+ ...guides.length ? ["", "Package guides (they match the installed versions):", ...guides.map((g) => `- ${g.path}: ${g.when}`)] : []
8511
+ ].join("\n");
8512
+ }
8513
+ function subagentHookOutput(root, packages) {
8514
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: "SubagentStart", additionalContext: subagentContext(root, packages) } });
8515
+ }
8516
+ function checkSettingsShape(settings2) {
8517
+ const fail = (msg) => {
8518
+ throw new Error(`${SETTINGS_PATH}: ${msg}; fix it by hand, then run genesis agents --hooks again.`);
8519
+ };
8520
+ if (!isObject4(settings2)) fail("must be a JSON object");
8521
+ const s = settings2;
8522
+ if (s.hooks !== void 0) {
8523
+ if (!isObject4(s.hooks)) fail('"hooks" must be an object');
8524
+ const start = s.hooks["SubagentStart"];
8525
+ if (start !== void 0) {
8526
+ if (!Array.isArray(start)) fail('"hooks.SubagentStart" must be a list');
8527
+ 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');
8528
+ }
8529
+ }
8530
+ if (s.permissions !== void 0) {
8531
+ if (!isObject4(s.permissions)) fail('"permissions" must be an object');
8532
+ const deny = s.permissions.deny;
8533
+ if (deny !== void 0 && (!Array.isArray(deny) || !deny.every((d) => typeof d === "string"))) fail('"permissions.deny" must be a list of strings');
8534
+ }
8535
+ }
8536
+ function mergeAgentHooks(settings2) {
8537
+ checkSettingsShape(settings2);
8538
+ const out = structuredClone(settings2);
8539
+ const hooks = out.hooks ??= {};
8540
+ const others = (hooks["SubagentStart"] ?? []).map((e) => ({ ...e, hooks: e.hooks.filter((h) => !isGenesisHook(h)) })).filter((e) => e.hooks.length > 0);
8541
+ hooks["SubagentStart"] = [...others, { matcher: SUBAGENT_MATCHER, hooks: [{ type: "command", command: SUBAGENT_HOOK_COMMAND }] }];
8542
+ const permissions = out.permissions ??= {};
8543
+ const deny = permissions.deny ?? [];
8544
+ permissions.deny = [...deny, ...DENY_RULES.filter((r) => !deny.includes(r))];
8545
+ return out;
8546
+ }
8547
+ function writeAgentHooks(root) {
8548
+ const file = path30.join(root, SETTINGS_PATH);
8549
+ const before = existsSync(file) ? readFileSync(file, "utf8") : null;
8550
+ let current = {};
8551
+ if (before !== null) {
8552
+ try {
8553
+ current = JSON.parse(before);
8554
+ } catch {
8555
+ throw new Error(`${SETTINGS_PATH} isn't valid JSON; fix it by hand, then run genesis agents --hooks again.`);
8556
+ }
8557
+ }
8558
+ checkSettingsShape(current);
8559
+ const after = `${JSON.stringify(mergeAgentHooks(current), null, 2)}
8560
+ `;
8561
+ if (before !== null && JSON.stringify(JSON.parse(before)) === JSON.stringify(JSON.parse(after))) return [];
8562
+ mkdirSync(path30.dirname(file), { recursive: true });
8563
+ writeFileSync(file, after);
8564
+ return [SETTINGS_PATH];
8565
+ }
8566
+ function agentHooksState(root) {
8567
+ let settings2;
8568
+ try {
8569
+ settings2 = JSON.parse(readFileSync(path30.join(root, SETTINGS_PATH), "utf8"));
8570
+ } catch {
8571
+ return "none";
8572
+ }
8573
+ const start = isObject4(settings2) && isObject4(settings2.hooks) ? settings2.hooks["SubagentStart"] : void 0;
8574
+ 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);
8575
+ if (!commands.length) return "none";
8576
+ return commands.every((c) => c === SUBAGENT_HOOK_COMMAND) ? "ok" : "stale";
8577
+ }
8578
+ function checkAgentHooks(ctx) {
8579
+ if (agentHooksState(ctx.root) === "stale") {
8580
+ 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" });
8581
+ }
8582
+ }
8583
+ var SETTINGS_PATH, SUBAGENT_HOOK_COMMAND, SUBAGENT_MATCHER, DENY_RULES, isObject4, isGenesisHook;
8584
+ var init_agent_hooks = __esm({
8585
+ "src/doctor/agent-hooks.ts"() {
8586
+ init_primitives();
8587
+ SETTINGS_PATH = ".claude/settings.json";
8588
+ SUBAGENT_HOOK_COMMAND = '"$CLAUDE_PROJECT_DIR"/node_modules/.bin/genesis agents --hook subagent-start --dir "$CLAUDE_PROJECT_DIR" 2>/dev/null || true';
8589
+ SUBAGENT_MATCHER = "Explore|Plan";
8590
+ DENY_RULES = ["Read(./.env)", "Read(./.env.*)"];
8591
+ isObject4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8592
+ isGenesisHook = (h) => typeof h.command === "string" && h.command.includes("genesis agents --hook");
8292
8593
  }
8293
8594
  });
8294
8595
  function appFolderOf(root) {
@@ -9256,12 +9557,19 @@ var init_figma_routes = __esm({
9256
9557
  // src/doctor/index.ts
9257
9558
  var doctor_exports = {};
9258
9559
  __export(doctor_exports, {
9560
+ BLOCKED_FIX: () => BLOCKED_FIX,
9259
9561
  BUILTIN_RULES: () => BUILTIN_RULES,
9562
+ CLAUDE_IMPORT: () => CLAUDE_IMPORT,
9563
+ DENY_RULES: () => DENY_RULES,
9260
9564
  DoctorConfigError: () => DoctorConfigError,
9261
9565
  GenesisConfigError: () => GenesisConfigError,
9262
9566
  PackageDeclarationError: () => PackageDeclarationError,
9567
+ SETTINGS_PATH: () => SETTINGS_PATH,
9263
9568
  SKILL_PATH: () => SKILL_PATH,
9569
+ SUBAGENT_HOOK_COMMAND: () => SUBAGENT_HOOK_COMMAND,
9264
9570
  agentGuideState: () => agentGuideState,
9571
+ agentHooksState: () => agentHooksState,
9572
+ agentRules: () => agentRules,
9265
9573
  builtinChecks: () => builtinChecks,
9266
9574
  catalogTable: () => catalogTable,
9267
9575
  changedSince: () => changedSince,
@@ -9276,7 +9584,9 @@ __export(doctor_exports, {
9276
9584
  globToRegExp: () => globToRegExp,
9277
9585
  loadConfig: () => loadConfig,
9278
9586
  loadGenesis: () => loadGenesis,
9587
+ mergeAgentHooks: () => mergeAgentHooks,
9279
9588
  nativeLayouts: () => nativeLayouts,
9589
+ packageGuides: () => packageGuides,
9280
9590
  parseExportNames: () => parseExportNames,
9281
9591
  parseRulesMarkdown: () => parseRulesMarkdown,
9282
9592
  postgresContract: () => postgresContract,
@@ -9293,13 +9603,18 @@ __export(doctor_exports, {
9293
9603
  ruleNamespace: () => ruleNamespace,
9294
9604
  runDoctor: () => runDoctor,
9295
9605
  satisfies: () => satisfies,
9606
+ skillDescription: () => skillDescription,
9296
9607
  sqlStatements: () => sqlStatements,
9608
+ subagentContext: () => subagentContext,
9609
+ subagentHookOutput: () => subagentHookOutput,
9297
9610
  toJson: () => toJson,
9611
+ unlistedGuides: () => unlistedGuides,
9298
9612
  validateConfig: () => validateConfig,
9299
9613
  validateDeclaration: () => validateDeclaration,
9300
9614
  validateLinks: () => validateLinks,
9301
9615
  webRoutes: () => webRoutes,
9302
- writeAgentGuide: () => writeAgentGuide
9616
+ writeAgentGuide: () => writeAgentGuide,
9617
+ writeAgentHooks: () => writeAgentHooks
9303
9618
  });
9304
9619
  async function runDoctor(options = {}) {
9305
9620
  const root = path30.resolve(options.root ?? process.cwd());
@@ -9399,7 +9714,10 @@ function builtinChecks(config, options = {}) {
9399
9714
  { name: "studio-server-imports", check: checkStudioServerImports },
9400
9715
  { name: "removed-scope-names", check: checkRemovedScopeNames },
9401
9716
  { name: "stability-imports", check: checkStabilityImports },
9402
- { name: "agent-guide", check: checkAgentGuide },
9717
+ { name: "agent-guide", check: (ctx) => {
9718
+ checkAgentGuide(ctx);
9719
+ checkAgentHooks(ctx);
9720
+ } },
9403
9721
  { name: "overlays", check: (ctx) => checkOverlays(ctx) },
9404
9722
  { name: "lock-files", check: checkLockFiles },
9405
9723
  { name: "database-elsewhere", check: checkDatabaseHome },
@@ -9518,6 +9836,7 @@ var init_doctor = __esm({
9518
9836
  init_ratchet();
9519
9837
  init_contracts();
9520
9838
  init_primitives();
9839
+ init_agent_hooks();
9521
9840
  init_overlays();
9522
9841
  init_lock_files();
9523
9842
  init_database2();
@@ -9539,6 +9858,7 @@ var init_doctor = __esm({
9539
9858
  init_primitives();
9540
9859
  init_ratchet();
9541
9860
  init_contracts();
9861
+ init_agent_hooks();
9542
9862
  RATCHETED_BY_DEFAULT = ["deprecated-import", "genesis-eslint-config"];
9543
9863
  }
9544
9864
  });
@@ -9685,13 +10005,13 @@ __export(features_exports, {
9685
10005
  runFeaturesCheck: () => runFeaturesCheck,
9686
10006
  runFeaturesFind: () => runFeaturesFind
9687
10007
  });
9688
- function isObject4(value) {
10008
+ function isObject5(value) {
9689
10009
  return typeof value === "object" && value !== null && !Array.isArray(value);
9690
10010
  }
9691
10011
  function readObject(file, key2) {
9692
10012
  try {
9693
10013
  const json = JSON.parse(readFileSync(file, "utf-8"));
9694
- return isObject4(json[key2]) ? json[key2] : {};
10014
+ return isObject5(json[key2]) ? json[key2] : {};
9695
10015
  } catch {
9696
10016
  return {};
9697
10017
  }
@@ -9713,9 +10033,9 @@ async function loadRegistry(input) {
9713
10033
  const load = async (file) => await jiti.import(path30.join(root, file));
9714
10034
  const mod = await load(registry);
9715
10035
  const features2 = mod.features ?? mod.default;
9716
- if (!isObject4(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
10036
+ if (!isObject5(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
9717
10037
  const flags = options.flagsFile ? (await load(options.flagsFile)).flags : mod.flags;
9718
- if (flags !== void 0 && !isObject4(flags)) {
10038
+ if (flags !== void 0 && !isObject5(flags)) {
9719
10039
  throw new Error(`${options.flagsFile ?? registry}'s \`flags\` export must be an object (from defineFlags).`);
9720
10040
  }
9721
10041
  const { dir: _dir, registry: _registry, flagsFile: _flagsFile, prs: _prs, gh: _gh, ...rest } = options;
@@ -9989,8 +10309,8 @@ function routeTags(source) {
9989
10309
  }
9990
10310
  function wireStudioRoute(source, route, pageImportPath) {
9991
10311
  const tags = routeTags(source);
9992
- const relative18 = route.replace(/^\//, "");
9993
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative18.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
10312
+ const relative19 = route.replace(/^\//, "");
10313
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative19.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
9994
10314
  if (existing) {
9995
10315
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
9996
10316
  }
@@ -9998,17 +10318,17 @@ function wireStudioRoute(source, route, pageImportPath) {
9998
10318
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
9999
10319
  if (roots.length !== 1) {
10000
10320
  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.`
10321
+ 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
10322
  };
10003
10323
  }
10004
10324
  const layout = roots[0];
10005
10325
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
10006
- if (base && !relative18.startsWith(`${base}/`)) {
10326
+ if (base && !relative19.startsWith(`${base}/`)) {
10007
10327
  return {
10008
10328
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
10009
10329
  };
10010
10330
  }
10011
- const childPath = base ? relative18.slice(base.length + 1) : relative18;
10331
+ const childPath = base ? relative19.slice(base.length + 1) : relative19;
10012
10332
  const guard = GUARD.exec(source)?.[1];
10013
10333
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
10014
10334
  const before = source.slice(0, layout.close);
@@ -11258,7 +11578,7 @@ function promotions(root, name) {
11258
11578
  });
11259
11579
  }
11260
11580
  function mergeJson(base, mine, theirs) {
11261
- if (isObject5(base) && isObject5(mine) && isObject5(theirs)) {
11581
+ if (isObject6(base) && isObject6(mine) && isObject6(theirs)) {
11262
11582
  const out = {};
11263
11583
  for (const key2 of /* @__PURE__ */ new Set([...Object.keys(mine), ...Object.keys(theirs)])) {
11264
11584
  const inMine = key2 in mine;
@@ -11422,7 +11742,7 @@ function ownManifestFields(mergedText, upstreamText) {
11422
11742
  if (!ours || !up) continue;
11423
11743
  for (const [dep, spec] of Object.entries(up)) if (typeof spec === "string" && spec.startsWith("workspace:") && typeof ours[dep] === "string") ours[dep] = spec;
11424
11744
  }
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;
11745
+ 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
11746
  return [.../* @__PURE__ */ new Set([...Object.keys(mine), ...Object.keys(theirs)])].filter((k) => JSON.stringify(sorted2(mine[k])) !== JSON.stringify(sorted2(theirs[k]))).sort();
11427
11747
  }
11428
11748
  function folderReferences(root, plan) {
@@ -11475,14 +11795,14 @@ function pinManifest(root, plan, file, text) {
11475
11795
  }
11476
11796
  }
11477
11797
  for (const o of [json.overrides, json.resolutions, json.pnpm?.overrides]) {
11478
- if (isObject5(o) && local(o[plan.name])) {
11798
+ if (isObject6(o) && local(o[plan.name])) {
11479
11799
  delete o[plan.name];
11480
11800
  touched2 = true;
11481
11801
  }
11482
11802
  }
11483
11803
  const names = (entry) => typeof entry === "string" && path30.resolve(here, entry) === overlay;
11484
11804
  const ws = json.workspaces;
11485
- const list = Array.isArray(ws) ? ws : isObject5(ws) && Array.isArray(ws.packages) ? ws.packages : null;
11805
+ const list = Array.isArray(ws) ? ws : isObject6(ws) && Array.isArray(ws.packages) ? ws.packages : null;
11486
11806
  if (list?.some(names)) {
11487
11807
  const kept = list.filter((entry) => !names(entry));
11488
11808
  if (Array.isArray(ws)) json.workspaces = kept;
@@ -11573,7 +11893,7 @@ function overlayChecklist(plans) {
11573
11893
  }
11574
11894
  return lines;
11575
11895
  }
11576
- var GENESIS_REPOSITORY, SKIP, FETCH_TIMEOUT_MS, isObject5, same, LOCAL_SUFFIX;
11896
+ var GENESIS_REPOSITORY, SKIP, FETCH_TIMEOUT_MS, isObject6, same, LOCAL_SUFFIX;
11577
11897
  var init_overlays2 = __esm({
11578
11898
  "src/upgrade/overlays.ts"() {
11579
11899
  init_owned();
@@ -11586,7 +11906,7 @@ var init_overlays2 = __esm({
11586
11906
  GENESIS_REPOSITORY = "https://github.com/marktiderman/genesis.git";
11587
11907
  SKIP = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo", ".git"]);
11588
11908
  FETCH_TIMEOUT_MS = 12e4;
11589
- isObject5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11909
+ isObject6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11590
11910
  same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
11591
11911
  LOCAL_SUFFIX = /[+-]local\.(0|[1-9]\d*)$/;
11592
11912
  }
@@ -12300,9 +12620,9 @@ async function runScaffold(opts, fs2) {
12300
12620
  function joinPath(...parts) {
12301
12621
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
12302
12622
  }
12303
- function dirname(path61) {
12304
- const idx = path61.lastIndexOf("/");
12305
- return idx === -1 ? "." : path61.slice(0, idx);
12623
+ function dirname(path62) {
12624
+ const idx = path62.lastIndexOf("/");
12625
+ return idx === -1 ? "." : path62.slice(0, idx);
12306
12626
  }
12307
12627
  function brandPackageJson(consumer, genesisVersion) {
12308
12628
  return JSON.stringify(
@@ -12686,8 +13006,18 @@ program.command("primitives").description("Deprecated name of `genesis catalog`
12686
13006
  for (const note of packages.flatMap((p) => p.ignored ?? [])) console.error(`! ${note}`);
12687
13007
  if (broken.length) process.exitCode = 1;
12688
13008
  });
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) => {
13009
+ 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
13010
  const root = path30.resolve(opts.dir);
13011
+ if (opts.hook) {
13012
+ try {
13013
+ if (opts.hook === "subagent-start") {
13014
+ const doctor2 = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
13015
+ console.log(doctor2.subagentHookOutput(root, doctor2.discoverPackages(root)));
13016
+ }
13017
+ } catch {
13018
+ }
13019
+ return;
13020
+ }
12691
13021
  if (opts.rules && opts.check) return program.error("--rules checks the repo, --check the agent guide: run them one at a time");
12692
13022
  if (opts.rules) {
12693
13023
  if (!existsSync(path30.join(root, "packages")) && !existsSync(path30.join(root, ".github", "workflows"))) {
@@ -12711,16 +13041,23 @@ program.command("agents").description(`Write the agent guide from the installed
12711
13041
  }
12712
13042
  if (opts.check) {
12713
13043
  const state = doctor.agentGuideState(root, packages);
12714
- const bad = Object.entries(state).filter(([, v]) => v !== "ok");
13044
+ const bad = Object.entries(state).filter(([k, v]) => v !== "ok" && !(k === "claude" && v === "no-import"));
13045
+ if (doctor.agentHooksState(root) === "stale") bad.push([doctor.SETTINGS_PATH, "has an older Genesis hook"]);
12715
13046
  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.`);
13047
+ const guideBad = bad.some(([k]) => k !== doctor.SETTINGS_PATH && k !== "claude");
13048
+ const fix = [
13049
+ ...guideBad || state.claude === "missing" ? ["Run `genesis agents` and commit the result."] : [],
13050
+ ...state.claude === "blocked" ? [`For CLAUDE.md, ${doctor.BLOCKED_FIX}.`] : [],
13051
+ ...bad.some(([k]) => k === doctor.SETTINGS_PATH) ? ["Run `genesis agents --hooks` to update the hook."] : []
13052
+ ].join(" ");
13053
+ 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
13054
  process.exitCode = 1;
12718
13055
  return;
12719
13056
  }
12720
13057
  console.log("\u2714 The agent guide matches the installed Genesis packages.");
12721
13058
  return;
12722
13059
  }
12723
- const changed = doctor.writeAgentGuide(root, packages);
13060
+ const changed = [...doctor.writeAgentGuide(root, packages), ...opts.hooks ? doctor.writeAgentHooks(root) : []];
12724
13061
  console.log(changed.length ? `\u2714 Wrote ${changed.join(", ")}` : "= The agent guide is up to date.");
12725
13062
  });
12726
13063
  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 +13140,22 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
12803
13140
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
12804
13141
  const root = path30.resolve(opts.dir);
12805
13142
  const packageJson = JSON.parse(await fs.readFile(path30.join(root, "package.json"), "utf-8").catch(() => "{}"));
12806
- const existsSync45 = (await import('fs')).existsSync;
13143
+ const existsSync46 = (await import('fs')).existsSync;
12807
13144
  const readSync = (await import('fs')).readFileSync;
12808
- const readdirSync20 = (await import('fs')).readdirSync;
13145
+ const readdirSync21 = (await import('fs')).readdirSync;
12809
13146
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
12810
13147
  throw new Error("--host must be next, tanstack-start or supabase-function.");
12811
13148
  }
12812
13149
  const plan = planStudioInit2(
12813
13150
  {
12814
13151
  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,
13152
+ exists: (p) => existsSync46(path30.join(root, p)),
13153
+ read: (p) => existsSync46(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
12817
13154
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
12818
13155
  listDeep: (p) => {
12819
13156
  const out = [];
12820
13157
  const walk4 = (rel) => {
12821
- for (const entry of readdirSync20(path30.join(root, rel), { withFileTypes: true })) {
13158
+ for (const entry of readdirSync21(path30.join(root, rel), { withFileTypes: true })) {
12822
13159
  const child = `${rel}/${entry.name}`;
12823
13160
  if (entry.isDirectory()) walk4(child);
12824
13161
  else out.push(child);
@@ -12832,7 +13169,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
12832
13169
  },
12833
13170
  list: (p) => {
12834
13171
  try {
12835
- return readdirSync20(path30.join(root, p));
13172
+ return readdirSync21(path30.join(root, p));
12836
13173
  } catch {
12837
13174
  return [];
12838
13175
  }
@@ -12853,14 +13190,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
12853
13190
  console.log(`+ ${file.path} (appended)`);
12854
13191
  continue;
12855
13192
  }
12856
- if (existsSync45(target) && !opts.force) {
13193
+ if (existsSync46(target) && !opts.force) {
12857
13194
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
12858
13195
  continue;
12859
13196
  }
12860
13197
  await fs.writeFile(target, file.content, "utf-8");
12861
13198
  console.log(`+ ${file.path}`);
12862
13199
  }
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";
13200
+ 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
13201
  console.log("");
12865
13202
  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
13203
  console.log(` 1. ${pm} ${plan.install.map((p) => /[\s<>|]/.test(p) ? `"${p}"` : p).join(" ")}`);