@marktiderman/genesis-cli 1.23.0 → 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.
@@ -109,6 +109,12 @@ interface SupabasePackConfig {
109
109
  * tell new migrations from applied ones.
110
110
  */
111
111
  since?: string;
112
+ /**
113
+ * Whether Supabase's automatic branching (a branch per pull request) is on for this project.
114
+ * `false` records that it's off, so `exposed-schema-created-later` stops flagging a schema
115
+ * that a migration creates. Default: unknown, treated as on.
116
+ */
117
+ automaticBranching?: boolean;
112
118
  }
113
119
  /** The `doctor` block of genesis.config.json (or package.json `genesis.doctor`). */
114
120
  interface DoctorConfig {
@@ -412,6 +418,17 @@ interface GenesisConfigFile {
412
418
  supabase?: GenesisSupabase;
413
419
  /** Where this app sits in its repository (`mobile`), when that isn't the root: see {@link validateAppFolder}. */
414
420
  appFolder?: string;
421
+ /** Preview defaults the templates read (templates/vercel/ignore-build.sh): see {@link validateEnvironments}. */
422
+ environments?: GenesisEnvironments;
423
+ }
424
+ /** The app's preview defaults. A variable set where the build runs wins over these; these win over Genesis's defaults. */
425
+ interface GenesisEnvironments {
426
+ /** on-demand (the default), every-pr or off. */
427
+ previews?: "on-demand" | "every-pr" | "off";
428
+ /** The pull request label that asks for a preview; "" turns the label check off. */
429
+ label?: string;
430
+ /** The branch prefix that asks for a preview; "" turns the branch check off. */
431
+ branchPrefix?: string;
415
432
  }
416
433
  interface LoadedConfig {
417
434
  config: DoctorConfig;
package/dist/doctor.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { D as DoctorConfig, l as GenesisFacts, m as PatternRule, h as DoctorPlugin, S as SourceFile, g as DoctorContext, n as PreferRule, o as DeclaringPackage, q as PackageDeclaration, i as DoctorResult, F as Finding } from './config-HOmiOLQc.js';
2
- export { A as AllowEntry, C as CompanionPackage, s as ContractsConfig, f as DoctorConfigError, t as DoctorPack, u as FindingInput, c as GenesisConfigError, j as GenesisConfigFile, b as GenesisLinks, k as GenesisSupabase, L as Level, N as NativePackConfig, w as PackageRuleSetting, x as PackagesPackConfig, y as PluginSpec, z as PrimitiveEntry, R as RuleSetting, B as SupabasePackConfig, E as loadConfig, r as readGenesisConfig, H as validateConfig, v as validateLinks } from './config-HOmiOLQc.js';
1
+ import { D as DoctorConfig, l as GenesisFacts, m as PatternRule, h as DoctorPlugin, S as SourceFile, g as DoctorContext, n as PreferRule, o as DeclaringPackage, q as PackageDeclaration, i as DoctorResult, F as Finding } from './config-DRHg7V3Z.js';
2
+ export { A as AllowEntry, C as CompanionPackage, s as ContractsConfig, f as DoctorConfigError, t as DoctorPack, u as FindingInput, c as GenesisConfigError, j as GenesisConfigFile, b as GenesisLinks, k as GenesisSupabase, L as Level, N as NativePackConfig, w as PackageRuleSetting, x as PackagesPackConfig, y as PluginSpec, z as PrimitiveEntry, R as RuleSetting, B as SupabasePackConfig, E as loadConfig, r as readGenesisConfig, H as validateConfig, v as validateLinks } from './config-DRHg7V3Z.js';
3
3
  import '@marktiderman/genesis-features';
4
4
 
5
5
  /** The installed folder of `name`, looking in node_modules from `from` upward (works with hoisting and pnpm). */
@@ -27,7 +27,7 @@ declare function parseRulesMarkdown(markdown: string): PatternRule[];
27
27
  declare function defineDoctorPlugin(plugin: DoctorPlugin): DoctorPlugin;
28
28
 
29
29
  /** Ids of the built-in rules, for `rules` overrides and `allow` entries. */
30
- declare const BUILTIN_RULES: readonly ["local-primitives", "figma-routes", "starter-leftover", "forbidden-import", "raw-tag", "palette-color", "arbitrary-color", "raw-color", "undefined-token", "shadowed-export", "version-skew", "duplicate-genesis-package", "peer-range-mismatch", "hand-rolled-sub-nav", "local-genesis-copy", "resource-workspace", "page-layout", "iso-date-slice", "resource-view-tree", "studio-server-auth-import", "removed-scope-name", "scope-practice-id", "deprecated-import", "beta-import", "native-raw-primitive", "native-literal-color", "native-custom-header", "native-screen-layout", "store-readiness", "eas-placeholder", "migration-grants", "migration-rls", "migration-definer-search-path", "migration-edited", "migration-testing-kit", "migration-view-rls", "package-app-import", "package-undeclared-dependency", "package-migration-test", "package-migration-number", "package-migration-edited", "package-unregistered", "package-unversioned-change", "package-export-missing", "package-block-invalid", "package-untagged-tests", "package-doctor-declaration", "overlay-unmarked", "overlay-invalid", "overlay-age", "overlay-version", "overlay-behind", "package-rules-invalid", "package-rule-override", "ratchet-skipped", "allow-grew", "rules-weakened", "agent-guide-stale", "contracts-stale", "lock-files", "database-elsewhere", "genesis-eslint-config"];
30
+ declare const BUILTIN_RULES: readonly ["local-primitives", "figma-routes", "starter-leftover", "forbidden-import", "raw-tag", "palette-color", "arbitrary-color", "raw-color", "undefined-token", "shadowed-export", "version-skew", "duplicate-genesis-package", "peer-range-mismatch", "hand-rolled-sub-nav", "local-genesis-copy", "resource-workspace", "page-layout", "iso-date-slice", "resource-view-tree", "studio-server-auth-import", "removed-scope-name", "scope-practice-id", "deprecated-import", "beta-import", "native-raw-primitive", "native-literal-color", "native-custom-header", "native-screen-layout", "store-readiness", "eas-placeholder", "migration-grants", "migration-rls", "migration-definer-search-path", "migration-edited", "migration-testing-kit", "migration-view-rls", "exposed-schema-created-later", "package-app-import", "package-undeclared-dependency", "package-migration-test", "package-migration-number", "package-migration-edited", "package-unregistered", "package-unversioned-change", "package-export-missing", "package-block-invalid", "package-untagged-tests", "package-doctor-declaration", "overlay-unmarked", "overlay-invalid", "overlay-age", "overlay-version", "overlay-behind", "package-rules-invalid", "package-rule-override", "ratchet-skipped", "allow-grew", "rules-weakened", "agent-guide-stale", "contracts-stale", "lock-files", "database-elsewhere", "genesis-eslint-config"];
31
31
 
32
32
  /**
33
33
  * Minimal globs for config: `*` matches within a folder, `**` across folders,
@@ -170,6 +170,11 @@ interface ResolvedPreferRule extends PreferRule {
170
170
  /** The prefer rules of every package that declares any. */
171
171
  declare function preferRules(packages: readonly DeclaringPackage[]): ResolvedPreferRule[];
172
172
 
173
+ /**
174
+ * The CLAUDE.md written when an app has none, so tools that read only CLAUDE.md (reviewers,
175
+ * cloud project threads) load the same AGENTS.md every other agent reads.
176
+ */
177
+ declare const CLAUDE_IMPORT = "@AGENTS.md\n";
173
178
  /** One row of the catalog. */
174
179
  interface PrimitiveRow {
175
180
  need: string;
@@ -195,17 +200,42 @@ declare function catalogTable(rows: readonly PrimitiveRow[], options?: {
195
200
  /** `genesis catalog` (and its old name, `genesis primitives`): the catalog for a terminal. */
196
201
  declare function formatPrimitives(rows: readonly PrimitiveRow[]): string;
197
202
  declare const SKILL_PATH = ".claude/skills/genesis/SKILL.md";
203
+ /** An installed package's own agent guide: its `SKILL.md`, which matches the installed version. */
204
+ interface PackageGuide {
205
+ package: string;
206
+ /** Relative to the app root, POSIX separators: `node_modules/<package>/SKILL.md`, or a local package's own folder. */
207
+ path: string;
208
+ /** When to read it, from the guide's `description`. */
209
+ when: string;
210
+ }
211
+ /** The `description` in a SKILL.md's frontmatter, with a folded (`>`, `>-`) or literal (`|`) value joined into one line. */
212
+ declare function skillDescription(text: string): string;
213
+ /**
214
+ * The `SKILL.md` each installed package ships, so agents read the version the app actually has. Only
215
+ * paths that stay put are listed: a local package's folder, or `node_modules/<package>/SKILL.md` at
216
+ * the app or a workspace folder above it. A package reached only through the umbrella lives in
217
+ * pnpm's store under a path that changes with unrelated dependency bumps, so it's left out rather
218
+ * than going stale; `unlistedGuides` names those.
219
+ */
220
+ declare function packageGuides(root: string, packages: readonly DeclaringPackage[]): PackageGuide[];
221
+ /** Packages that ship a guide the agent guide can't point at, because it's only inside pnpm's store. */
222
+ declare function unlistedGuides(root: string, packages: readonly DeclaringPackage[]): string[];
223
+ /** The rules every agent follows, for callers outside this file (the subagent hook). */
224
+ declare function agentRules(): readonly string[];
198
225
  /** `.claude/skills/genesis/SKILL.md`, generated. */
199
- declare function renderSkill(rows: readonly PrimitiveRow[]): string;
226
+ declare function renderSkill(rows: readonly PrimitiveRow[], guides?: readonly PackageGuide[]): string;
200
227
  /** The AGENTS.md block, generated (markers included). */
201
- declare function renderAgentsBlock(rows: readonly PrimitiveRow[]): string;
228
+ declare function renderAgentsBlock(rows: readonly PrimitiveRow[], guides?: readonly PackageGuide[]): string;
202
229
  /** `genesis agents`: write the skill and the AGENTS.md block. Returns the files it changed. Writes nothing when AGENTS.md's block is broken. */
203
230
  declare function writeAgentGuide(root: string, packages: readonly DeclaringPackage[], agentsFile?: string): string[];
204
231
  /** What `agent-guide-stale` found: the generated files that are missing or differ. */
205
232
  declare function agentGuideState(root: string, packages: readonly DeclaringPackage[], agentsFile?: string): {
206
233
  skill: "ok" | "missing" | "stale";
207
234
  agents: "ok" | "missing" | "stale" | "broken";
235
+ claude: "ok" | "missing" | "blocked" | "no-import";
208
236
  };
237
+ /** The fix for a blocked CLAUDE.md, which `genesis agents` can't make itself. */
238
+ declare const BLOCKED_FIX = "rename or replace it with a CLAUDE.md file (or remove the dangling link), then run genesis agents";
209
239
 
210
240
  /**
211
241
  * App-relative paths changed since the merge base with `base`: committed on
@@ -222,6 +252,43 @@ declare function postgresContract(url: string, schemas: string[]): Promise<{
222
252
  tables: number;
223
253
  }>;
224
254
 
255
+ declare const SETTINGS_PATH = ".claude/settings.json";
256
+ /**
257
+ * The command the hook runs. `--dir` points it at the app, so a session started in a subfolder still
258
+ * gets the package guides. It fails open: with no install, the subagent simply starts without the rules.
259
+ */
260
+ declare const SUBAGENT_HOOK_COMMAND = "\"$CLAUDE_PROJECT_DIR\"/node_modules/.bin/genesis agents --hook subagent-start --dir \"$CLAUDE_PROJECT_DIR\" 2>/dev/null || true";
261
+ /** Secret files no agent should read: the deny rules apply everywhere, cloud sessions included. */
262
+ declare const DENY_RULES: string[];
263
+ /** The text a subagent receives: the rules, then where each installed package's guide is. */
264
+ declare function subagentContext(root: string, packages: readonly DeclaringPackage[]): string;
265
+ /** `genesis agents --hook subagent-start`: the hook's JSON output. */
266
+ declare function subagentHookOutput(root: string, packages: readonly DeclaringPackage[]): string;
267
+ type HookEntry = {
268
+ matcher?: string;
269
+ hooks: {
270
+ type: string;
271
+ command?: string;
272
+ }[];
273
+ };
274
+ type Settings = {
275
+ hooks?: Record<string, HookEntry[]>;
276
+ permissions?: {
277
+ deny?: string[];
278
+ [k: string]: unknown;
279
+ };
280
+ [k: string]: unknown;
281
+ };
282
+ /** The settings with Genesis's hook and deny rules in place; nothing of the app's own is removed. */
283
+ declare function mergeAgentHooks(settings: Settings): Settings;
284
+ /** `genesis agents --hooks`: write the hook and deny rules into `.claude/settings.json`. Returns the files it changed. */
285
+ declare function writeAgentHooks(root: string): string[];
286
+ /**
287
+ * Whether the app has Genesis's hook, and whether it's the current command: an app that adopted an
288
+ * older one keeps it until `genesis agents --hooks` runs again. A settings file that can't be read is "none".
289
+ */
290
+ declare function agentHooksState(root: string): "none" | "ok" | "stale";
291
+
225
292
  interface RunDoctorOptions {
226
293
  /** The app root. Default `process.cwd()`. */
227
294
  root?: string;
@@ -288,4 +355,4 @@ declare function genesisSummary(g: GenesisFacts): {
288
355
  };
289
356
  };
290
357
 
291
- export { BUILTIN_RULES, DeclaringPackage, DoctorConfig, DoctorContext, DoctorPlugin, DoctorResult, Finding, GenesisFacts, type GenesisInstall, PackageDeclaration, PackageDeclarationError, PatternRule, PreferRule, type PrimitiveRow, type ReleaseManifest, type ResolvedPreferRule, type RouteFile, type RunDoctorOptions, SKILL_PATH, SourceFile, agentGuideState, builtinChecks, catalogTable, changedSince, clearPackageRulesCache, defineDoctorPlugin, discoverPackages, findPackageDir, formatPrimitives, formatReport, genesisInstalls, genesisSummary, globToRegExp, loadGenesis, nativeLayouts, parseExportNames, parseRulesMarkdown, postgresContract, postgresSource, preferRules, primitivesCatalog, primitivesSummary, readPackageExports, readReleaseManifest, renderAgentsBlock, renderSkill, routesDir, ruleNamespace, runDoctor, satisfies, sqlStatements, toJson, validateDeclaration, webRoutes, writeAgentGuide };
358
+ export { BLOCKED_FIX, BUILTIN_RULES, CLAUDE_IMPORT, DENY_RULES, DeclaringPackage, DoctorConfig, DoctorContext, DoctorPlugin, DoctorResult, Finding, GenesisFacts, type GenesisInstall, PackageDeclaration, PackageDeclarationError, type PackageGuide, PatternRule, PreferRule, type PrimitiveRow, type ReleaseManifest, type ResolvedPreferRule, type RouteFile, type RunDoctorOptions, SETTINGS_PATH, SKILL_PATH, SUBAGENT_HOOK_COMMAND, SourceFile, agentGuideState, agentHooksState, agentRules, builtinChecks, catalogTable, changedSince, clearPackageRulesCache, defineDoctorPlugin, discoverPackages, findPackageDir, formatPrimitives, formatReport, genesisInstalls, genesisSummary, globToRegExp, loadGenesis, mergeAgentHooks, nativeLayouts, packageGuides, parseExportNames, parseRulesMarkdown, postgresContract, postgresSource, preferRules, primitivesCatalog, primitivesSummary, readPackageExports, readReleaseManifest, renderAgentsBlock, renderSkill, routesDir, ruleNamespace, runDoctor, satisfies, skillDescription, sqlStatements, subagentContext, subagentHookOutput, toJson, unlistedGuides, validateDeclaration, webRoutes, writeAgentGuide, writeAgentHooks };
package/dist/doctor.js CHANGED
@@ -817,6 +817,25 @@ var PRIVACY_PURPOSES = {
817
817
  "third-party advertising": "NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising",
818
818
  other: "NSPrivacyCollectedDataTypePurposeOther"
819
819
  };
820
+ var ENVIRONMENT_KEYS = /* @__PURE__ */ new Set(["previews", "label", "branchPrefix", "$comment"]);
821
+ function validateEnvironments(raw, source = "config") {
822
+ const fail = (msg) => {
823
+ throw new GenesisConfigError(`${source}: ${msg}`);
824
+ };
825
+ if (!isObject(raw)) return fail(`"environments" must be an object`);
826
+ for (const key2 of Object.keys(raw)) if (!ENVIRONMENT_KEYS.has(key2)) fail(`environments: unknown setting "${key2}" (known: previews, label, branchPrefix)`);
827
+ const out = {};
828
+ if (raw.previews !== void 0) {
829
+ 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)})`);
830
+ out.previews = raw.previews;
831
+ }
832
+ for (const key2 of ["label", "branchPrefix"]) {
833
+ if (raw[key2] === void 0) continue;
834
+ if (typeof raw[key2] !== "string") fail(`environments.${key2} must be a string ("" turns that check off)`);
835
+ out[key2] = raw[key2];
836
+ }
837
+ return out;
838
+ }
820
839
  var STRING_LISTS = ["src", "extensions", "ignore", "tokenFiles", "ignoreTokenPrefixes", "localPrimitiveDirs", "build", "componentPackages"];
821
840
  var STRINGS = ["uiPackage", "rulesDoc"];
822
841
  var KNOWN = /* @__PURE__ */ new Set([
@@ -848,7 +867,7 @@ var CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
848
867
  var PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
849
868
  var PACK_KEYS = {
850
869
  native: { routerRoot: "path" },
851
- supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
870
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string", automaticBranching: "boolean" },
852
871
  packages: { base: "string" }
853
872
  };
854
873
  function appPath(v, where2, fail) {
@@ -909,6 +928,7 @@ function readGenesisConfig(root) {
909
928
  if (supabase !== true) out.supabase = supabase;
910
929
  }
911
930
  if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
931
+ if (raw.environments !== void 0) out.environments = validateEnvironments(raw.environments, file);
912
932
  return out;
913
933
  }
914
934
  var PLAIN_FOLDER = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}){0,7}$/;
@@ -1107,6 +1127,7 @@ function validateConfig(raw, source = "config") {
1107
1127
  if (!want) fail(`${pack}: unknown setting "${k}"`);
1108
1128
  if (want === "string" && typeof v !== "string") fail(`${pack}.${k} must be a string`);
1109
1129
  if (want === "list" && !isStringList(v)) fail(`${pack}.${k} must be a list of strings`);
1130
+ if (want === "boolean" && typeof v !== "boolean") fail(`${pack}.${k} must be true or false`);
1110
1131
  if (want === "string" && !v.trim()) fail(`${pack}.${k} must not be empty`);
1111
1132
  if (want === "path") block[k] = appPath(v, `${pack}.${k}`, fail);
1112
1133
  }
@@ -1158,7 +1179,7 @@ function globToRegExp(glob) {
1158
1179
  }
1159
1180
  function globMatcher(globs) {
1160
1181
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1161
- return (path48) => res.some((re) => re.test(path48));
1182
+ return (path49) => res.some((re) => re.test(path49));
1162
1183
  }
1163
1184
  var GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
1164
1185
  var BLOCK_ID = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
@@ -2714,6 +2735,7 @@ var BUILTIN_RULES = [
2714
2735
  "migration-edited",
2715
2736
  "migration-testing-kit",
2716
2737
  "migration-view-rls",
2738
+ "exposed-schema-created-later",
2717
2739
  // packages pack
2718
2740
  "package-app-import",
2719
2741
  "package-undeclared-dependency",
@@ -4860,6 +4882,67 @@ function checkSupabasePack(ctx) {
4860
4882
  checkViewInvoker(ctx, migrations, exposed);
4861
4883
  checkDefinerSearchPath(ctx, migrations);
4862
4884
  checkTestingKit(ctx, migrations);
4885
+ checkExposedSchemasCreatedLater(ctx, dir, migrations, settings.exposedSchemas, settings.automaticBranching !== false);
4886
+ }
4887
+ var PLATFORM_SCHEMAS = /* @__PURE__ */ new Set(["public", "graphql_public", "graphql", "extensions", "storage", "auth", "realtime", "vault"]);
4888
+ function apiSchemas(toml) {
4889
+ const lines = toml.split("\n");
4890
+ const start = lines.findIndex((l) => /^\s*\[api\]\s*(?:#.*)?$/.test(l));
4891
+ if (start < 0) return null;
4892
+ let end = lines.findIndex((l, i) => i > start && /^\s*\[/.test(l));
4893
+ if (end < 0) end = lines.length;
4894
+ const bare = (l) => {
4895
+ let quoted = false;
4896
+ for (let i = 0; i < l.length; i++) {
4897
+ if (l[i] === '"' && l[i - 1] !== "\\") quoted = !quoted;
4898
+ else if (l[i] === "#" && !quoted) return l.slice(0, i);
4899
+ }
4900
+ return l;
4901
+ };
4902
+ const body = lines.slice(start + 1, end).map(bare);
4903
+ const enabled = !body.some((l) => /^\s*enabled\s*=\s*false\b/.test(l));
4904
+ const at = body.findIndex((l) => /^\s*schemas\s*=/.test(l));
4905
+ if (at < 0) return { enabled, schemas: [], line: start + 1 };
4906
+ let list = "";
4907
+ for (let i = at; i < body.length; i++) {
4908
+ list += `${body[i]}
4909
+ `;
4910
+ if (body[i].includes("]")) break;
4911
+ }
4912
+ const inner = /\[([\s\S]*?)\]/.exec(list)?.[1] ?? "";
4913
+ const schemas = [...inner.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((m) => (m[1] ?? m[2]).trim().toLowerCase()).filter(Boolean);
4914
+ return { enabled, schemas, line: start + at + 2 };
4915
+ }
4916
+ function checkExposedSchemasCreatedLater(ctx, dir, migrations, configured, branching) {
4917
+ const created = /* @__PURE__ */ new Map();
4918
+ for (const { file, statements } of migrations) {
4919
+ for (const { sql, line } of statements) {
4920
+ const m = /^create schema (?:if not exists )?"?([\w$]+)"?/.exec(sql);
4921
+ if (m && m[1] !== "authorization" && !created.has(m[1])) created.set(m[1], { file, line });
4922
+ }
4923
+ }
4924
+ const tomlFile = path21.posix.join(path21.posix.dirname(dir), "config.toml");
4925
+ const tomlText = existsSync(path21.join(ctx.root, tomlFile)) ? readFileSync(path21.join(ctx.root, tomlFile), "utf8") : null;
4926
+ const api2 = tomlText === null ? null : apiSchemas(tomlText);
4927
+ const sources = [];
4928
+ if (api2?.enabled) for (const schema of api2.schemas) sources.push({ schema, file: tomlFile, line: api2.line, where: `${tomlFile} [api] schemas` });
4929
+ for (const schema of api2?.enabled === false ? [] : configured ?? []) {
4930
+ const s = schema.toLowerCase();
4931
+ if (!sources.some((x) => x.schema === s)) sources.push({ schema: s, file: "genesis.config.json", where: "doctor.supabase.exposedSchemas" });
4932
+ }
4933
+ for (const { schema, file, line, where: where2 } of sources) {
4934
+ if (PLATFORM_SCHEMAS.has(schema)) continue;
4935
+ const by = created.get(schema);
4936
+ if (by && !branching) continue;
4937
+ ctx.report({
4938
+ rule: "exposed-schema-created-later",
4939
+ level: "warn",
4940
+ file,
4941
+ ...line ? { line } : {},
4942
+ subject: schema,
4943
+ 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`
4944
+ });
4945
+ }
4863
4946
  }
4864
4947
  function checkTestingKit(ctx, migrations) {
4865
4948
  for (const { file, statements } of migrations) {
@@ -6110,6 +6193,20 @@ async function checkContracts(ctx, read2 = postgresContract) {
6110
6193
  }
6111
6194
  }
6112
6195
  var GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
6196
+ var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
6197
+ var CLAUDE_IMPORT = "@AGENTS.md\n";
6198
+ function pathTaken(file) {
6199
+ try {
6200
+ lstatSync(file);
6201
+ return true;
6202
+ } catch {
6203
+ try {
6204
+ return readdirSync(path21.dirname(file)).some((n) => n.toLowerCase() === path21.basename(file).toLowerCase());
6205
+ } catch {
6206
+ return false;
6207
+ }
6208
+ }
6209
+ }
6113
6210
  var CORE = [
6114
6211
  {
6115
6212
  need: "anything, before building it",
@@ -6192,14 +6289,82 @@ var SKILL_PATH = ".claude/skills/genesis/SKILL.md";
6192
6289
  var AGENTS_START = "<!-- genesis-primitives:start -->";
6193
6290
  var AGENTS_END = "<!-- genesis-primitives:end -->";
6194
6291
  var RULES = [
6195
- "Use the Genesis primitive for the need first: reuse, then extend, then invent (docs/FRAMEWORK.md, G1 to G6).",
6292
+ `Use the Genesis primitive for the need first: reuse, then extend, then invent (G1 to G6 in ${GENESIS_DOCS}/FRAMEWORK.md).`,
6196
6293
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
6197
6294
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
6198
6295
  "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.",
6199
6296
  "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
6200
6297
  "Run `genesis doctor` before you finish; it enforces these rules."
6201
6298
  ];
6202
- function renderSkill(rows) {
6299
+ function skillDescription(text) {
6300
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1];
6301
+ if (!fm) return "";
6302
+ const lines = fm.split(/\r?\n/);
6303
+ const i = lines.findIndex((l) => /^description:/.test(l));
6304
+ if (i < 0) return "";
6305
+ const first = lines[i].replace(/^description:\s*/, "").trim();
6306
+ if (first && !/^[>|][+-]?$/.test(first)) return first.replace(/^["']|["']$/g, "");
6307
+ const more = [];
6308
+ for (const l of lines.slice(i + 1)) {
6309
+ if (!/^\s+\S/.test(l)) break;
6310
+ more.push(l.trim());
6311
+ }
6312
+ return more.join(" ");
6313
+ }
6314
+ var GUIDE_SEARCH_LEVELS = 4;
6315
+ function stableGuidePath(root, p) {
6316
+ const real2 = (f) => {
6317
+ try {
6318
+ return realpathSync(f);
6319
+ } catch {
6320
+ return null;
6321
+ }
6322
+ };
6323
+ const want = real2(p.dir);
6324
+ for (let dir = root, level = 0; level <= GUIDE_SEARCH_LEVELS; level++) {
6325
+ const found = path21.join(dir, "node_modules", p.name);
6326
+ if (existsSync(found)) {
6327
+ const file = path21.join(found, "SKILL.md");
6328
+ return want !== null && real2(found) === want && existsSync(file) ? file : null;
6329
+ }
6330
+ if (existsSync(path21.join(dir, ".git")) || existsSync(path21.join(dir, "pnpm-workspace.yaml"))) return null;
6331
+ const up = path21.dirname(dir);
6332
+ if (up === dir) return null;
6333
+ dir = up;
6334
+ }
6335
+ return null;
6336
+ }
6337
+ function packageGuides(root, packages) {
6338
+ const guides = [];
6339
+ for (const p of packages) {
6340
+ const stable = p.local ? path21.join(p.dir, "SKILL.md") : stableGuidePath(root, p);
6341
+ const text = stable === null ? null : read(stable);
6342
+ if (stable === null || text === null) continue;
6343
+ const description = skillDescription(text);
6344
+ const at = description.indexOf("Load before");
6345
+ guides.push({ package: p.name, path: path21.relative(root, stable).split(path21.sep).join("/"), when: at >= 0 ? description.slice(at) : description });
6346
+ }
6347
+ return guides.sort((a, b) => a.package.localeCompare(b.package));
6348
+ }
6349
+ function unlistedGuides(root, packages) {
6350
+ const listed = new Set(packageGuides(root, packages).map((g) => g.package));
6351
+ return packages.filter((p) => !p.local && !listed.has(p.name) && existsSync(path21.join(p.dir, "SKILL.md"))).map((p) => p.name).sort();
6352
+ }
6353
+ function guidesSection(guides) {
6354
+ if (!guides.length) return [];
6355
+ return [
6356
+ "### Package guides (they match the installed versions)",
6357
+ "",
6358
+ "Before using a package's primitives, read its guide:",
6359
+ "",
6360
+ ...guides.map((g) => `- \`${g.path}\` (${g.package}): ${g.when}`),
6361
+ ""
6362
+ ];
6363
+ }
6364
+ function agentRules() {
6365
+ return RULES;
6366
+ }
6367
+ function renderSkill(rows, guides = []) {
6203
6368
  return [
6204
6369
  "---",
6205
6370
  "name: genesis",
@@ -6212,6 +6377,7 @@ function renderSkill(rows) {
6212
6377
  "",
6213
6378
  ...RULES.map((r) => `- ${r}`),
6214
6379
  "",
6380
+ ...guidesSection(guides),
6215
6381
  "## What to use for each need",
6216
6382
  "",
6217
6383
  catalogTable(rows, { docs: true }),
@@ -6220,7 +6386,7 @@ function renderSkill(rows) {
6220
6386
  ""
6221
6387
  ].join("\n");
6222
6388
  }
6223
- function renderAgentsBlock(rows) {
6389
+ function renderAgentsBlock(rows, guides = []) {
6224
6390
  return [
6225
6391
  AGENTS_START,
6226
6392
  "## Building with Genesis",
@@ -6231,6 +6397,7 @@ function renderAgentsBlock(rows) {
6231
6397
  "",
6232
6398
  ...RULES.map((r) => `- ${r}`),
6233
6399
  "",
6400
+ ...guidesSection(guides),
6234
6401
  catalogTable(rows),
6235
6402
  AGENTS_END
6236
6403
  ].join("\n");
@@ -6258,15 +6425,15 @@ function currentAgentsBlock(agents) {
6258
6425
  if (span === "broken") return "broken";
6259
6426
  return agents.slice(span.start, span.end).replace(/\r\n/g, "\n");
6260
6427
  }
6261
- var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
6262
6428
  function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
6263
6429
  const rows = primitivesCatalog(packages);
6430
+ const guides = packageGuides(root, packages);
6264
6431
  const changed = [];
6265
6432
  const agents = path21.join(root, agentsFile);
6266
6433
  const before = read(agents);
6267
- const after = mergeAgentsBlock(before, renderAgentsBlock(rows));
6434
+ const after = mergeAgentsBlock(before, renderAgentsBlock(rows, guides));
6268
6435
  const skill = path21.join(root, SKILL_PATH);
6269
- const skillText = renderSkill(rows);
6436
+ const skillText = renderSkill(rows, guides);
6270
6437
  if (read(skill)?.replace(/\r\n/g, "\n") !== skillText) {
6271
6438
  mkdirSync(path21.dirname(skill), { recursive: true });
6272
6439
  writeFileSync(skill, skillText);
@@ -6276,15 +6443,44 @@ function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
6276
6443
  writeFileSync(agents, after);
6277
6444
  changed.push(agentsFile);
6278
6445
  }
6446
+ const claude = path21.join(root, "CLAUDE.md");
6447
+ if (agentsFile === "AGENTS.md" && !pathTaken(claude)) {
6448
+ writeFileSync(claude, CLAUDE_IMPORT);
6449
+ changed.push("CLAUDE.md");
6450
+ }
6279
6451
  return changed;
6280
6452
  }
6453
+ function claudeState(root) {
6454
+ const file = path21.join(root, "CLAUDE.md");
6455
+ let names = [];
6456
+ try {
6457
+ names = readdirSync(root);
6458
+ } catch {
6459
+ }
6460
+ if (!names.includes("CLAUDE.md")) return names.some((n) => n.toLowerCase() === "claude.md") ? "blocked" : "missing";
6461
+ let text;
6462
+ try {
6463
+ text = readFileSync(file, "utf8");
6464
+ } catch {
6465
+ return "blocked";
6466
+ }
6467
+ if (/^@AGENTS\.md\b/m.test(text)) return "ok";
6468
+ try {
6469
+ if (realpathSync(file) === realpathSync(path21.join(root, "AGENTS.md"))) return "ok";
6470
+ } catch {
6471
+ }
6472
+ return "no-import";
6473
+ }
6281
6474
  function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
6282
6475
  const rows = primitivesCatalog(packages);
6476
+ const guides = packageGuides(root, packages);
6283
6477
  const skill = read(path21.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
6284
6478
  const block = currentAgentsBlock(read(path21.join(root, agentsFile)));
6285
6479
  return {
6286
- skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
6287
- agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
6480
+ skill: skill === null ? "missing" : skill === renderSkill(rows, guides) ? "ok" : "stale",
6481
+ agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows, guides) ? "ok" : "stale",
6482
+ // Only the default AGENTS.md gets a CLAUDE.md written for it, so only then is a missing one reported.
6483
+ claude: agentsFile !== "AGENTS.md" ? "ok" : claudeState(root)
6288
6484
  };
6289
6485
  }
6290
6486
  function checkAgentGuide(ctx) {
@@ -6302,6 +6498,104 @@ function checkAgentGuide(ctx) {
6302
6498
  }[state.agents];
6303
6499
  ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
6304
6500
  }
6501
+ if (state.claude === "no-import") {
6502
+ 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" });
6503
+ }
6504
+ if (state.claude === "missing") {
6505
+ 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\`)` });
6506
+ }
6507
+ if (state.claude === "blocked") {
6508
+ 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}` });
6509
+ }
6510
+ const unlisted = unlistedGuides(ctx.root, ctx.packages);
6511
+ if (unlisted.length) {
6512
+ 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.` });
6513
+ }
6514
+ }
6515
+ var BLOCKED_FIX = "rename or replace it with a CLAUDE.md file (or remove the dangling link), then run genesis agents";
6516
+ var SETTINGS_PATH = ".claude/settings.json";
6517
+ var SUBAGENT_HOOK_COMMAND = '"$CLAUDE_PROJECT_DIR"/node_modules/.bin/genesis agents --hook subagent-start --dir "$CLAUDE_PROJECT_DIR" 2>/dev/null || true';
6518
+ var SUBAGENT_MATCHER = "Explore|Plan";
6519
+ var DENY_RULES = ["Read(./.env)", "Read(./.env.*)"];
6520
+ function subagentContext(root, packages) {
6521
+ const guides = packageGuides(root, packages);
6522
+ return [
6523
+ "This is a Genesis app. Follow these rules (the app's AGENTS.md has the full guide):",
6524
+ ...agentRules().map((r) => `- ${r}`),
6525
+ ...guides.length ? ["", "Package guides (they match the installed versions):", ...guides.map((g) => `- ${g.path}: ${g.when}`)] : []
6526
+ ].join("\n");
6527
+ }
6528
+ function subagentHookOutput(root, packages) {
6529
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: "SubagentStart", additionalContext: subagentContext(root, packages) } });
6530
+ }
6531
+ var isObject4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
6532
+ var isGenesisHook = (h) => typeof h.command === "string" && h.command.includes("genesis agents --hook");
6533
+ function checkSettingsShape(settings) {
6534
+ const fail = (msg) => {
6535
+ throw new Error(`${SETTINGS_PATH}: ${msg}; fix it by hand, then run genesis agents --hooks again.`);
6536
+ };
6537
+ if (!isObject4(settings)) fail("must be a JSON object");
6538
+ const s = settings;
6539
+ if (s.hooks !== void 0) {
6540
+ if (!isObject4(s.hooks)) fail('"hooks" must be an object');
6541
+ const start = s.hooks["SubagentStart"];
6542
+ if (start !== void 0) {
6543
+ if (!Array.isArray(start)) fail('"hooks.SubagentStart" must be a list');
6544
+ 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');
6545
+ }
6546
+ }
6547
+ if (s.permissions !== void 0) {
6548
+ if (!isObject4(s.permissions)) fail('"permissions" must be an object');
6549
+ const deny = s.permissions.deny;
6550
+ if (deny !== void 0 && (!Array.isArray(deny) || !deny.every((d) => typeof d === "string"))) fail('"permissions.deny" must be a list of strings');
6551
+ }
6552
+ }
6553
+ function mergeAgentHooks(settings) {
6554
+ checkSettingsShape(settings);
6555
+ const out = structuredClone(settings);
6556
+ const hooks = out.hooks ??= {};
6557
+ const others = (hooks["SubagentStart"] ?? []).map((e) => ({ ...e, hooks: e.hooks.filter((h) => !isGenesisHook(h)) })).filter((e) => e.hooks.length > 0);
6558
+ hooks["SubagentStart"] = [...others, { matcher: SUBAGENT_MATCHER, hooks: [{ type: "command", command: SUBAGENT_HOOK_COMMAND }] }];
6559
+ const permissions = out.permissions ??= {};
6560
+ const deny = permissions.deny ?? [];
6561
+ permissions.deny = [...deny, ...DENY_RULES.filter((r) => !deny.includes(r))];
6562
+ return out;
6563
+ }
6564
+ function writeAgentHooks(root) {
6565
+ const file = path21.join(root, SETTINGS_PATH);
6566
+ const before = existsSync(file) ? readFileSync(file, "utf8") : null;
6567
+ let current = {};
6568
+ if (before !== null) {
6569
+ try {
6570
+ current = JSON.parse(before);
6571
+ } catch {
6572
+ throw new Error(`${SETTINGS_PATH} isn't valid JSON; fix it by hand, then run genesis agents --hooks again.`);
6573
+ }
6574
+ }
6575
+ checkSettingsShape(current);
6576
+ const after = `${JSON.stringify(mergeAgentHooks(current), null, 2)}
6577
+ `;
6578
+ if (before !== null && JSON.stringify(JSON.parse(before)) === JSON.stringify(JSON.parse(after))) return [];
6579
+ mkdirSync(path21.dirname(file), { recursive: true });
6580
+ writeFileSync(file, after);
6581
+ return [SETTINGS_PATH];
6582
+ }
6583
+ function agentHooksState(root) {
6584
+ let settings;
6585
+ try {
6586
+ settings = JSON.parse(readFileSync(path21.join(root, SETTINGS_PATH), "utf8"));
6587
+ } catch {
6588
+ return "none";
6589
+ }
6590
+ const start = isObject4(settings) && isObject4(settings.hooks) ? settings.hooks["SubagentStart"] : void 0;
6591
+ 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);
6592
+ if (!commands.length) return "none";
6593
+ return commands.every((c) => c === SUBAGENT_HOOK_COMMAND) ? "ok" : "stale";
6594
+ }
6595
+ function checkAgentHooks(ctx) {
6596
+ if (agentHooksState(ctx.root) === "stale") {
6597
+ 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" });
6598
+ }
6305
6599
  }
6306
6600
 
6307
6601
  // src/blocks/templates.ts
@@ -7209,7 +7503,10 @@ function builtinChecks(config, options = {}) {
7209
7503
  { name: "studio-server-imports", check: checkStudioServerImports },
7210
7504
  { name: "removed-scope-names", check: checkRemovedScopeNames },
7211
7505
  { name: "stability-imports", check: checkStabilityImports },
7212
- { name: "agent-guide", check: checkAgentGuide },
7506
+ { name: "agent-guide", check: (ctx) => {
7507
+ checkAgentGuide(ctx);
7508
+ checkAgentHooks(ctx);
7509
+ } },
7213
7510
  { name: "overlays", check: (ctx) => checkOverlays(ctx) },
7214
7511
  { name: "lock-files", check: checkLockFiles },
7215
7512
  { name: "database-elsewhere", check: checkDatabaseHome },
@@ -7305,6 +7602,6 @@ function genesisSummary(g) {
7305
7602
  };
7306
7603
  }
7307
7604
 
7308
- export { BUILTIN_RULES, DoctorConfigError, GenesisConfigError, PackageDeclarationError, SKILL_PATH, agentGuideState, builtinChecks, catalogTable, changedSince, clearPackageRulesCache, defineDoctorPlugin, discoverPackages, findPackageDir, formatPrimitives, formatReport, genesisInstalls, genesisSummary, globToRegExp, loadConfig, loadGenesis, nativeLayouts, parseExportNames, parseRulesMarkdown, postgresContract, postgresSource, preferRules, primitivesCatalog, primitivesSummary, readGenesisConfig, readPackageExports, readReleaseManifest, renderAgentsBlock, renderSkill, routesDir, ruleNamespace, runDoctor, satisfies, sqlStatements, toJson, validateConfig, validateDeclaration, validateLinks, webRoutes, writeAgentGuide };
7605
+ export { BLOCKED_FIX, BUILTIN_RULES, CLAUDE_IMPORT, DENY_RULES, DoctorConfigError, GenesisConfigError, PackageDeclarationError, SETTINGS_PATH, SKILL_PATH, SUBAGENT_HOOK_COMMAND, agentGuideState, agentHooksState, agentRules, builtinChecks, catalogTable, changedSince, clearPackageRulesCache, defineDoctorPlugin, discoverPackages, findPackageDir, formatPrimitives, formatReport, genesisInstalls, genesisSummary, globToRegExp, loadConfig, loadGenesis, mergeAgentHooks, nativeLayouts, packageGuides, parseExportNames, parseRulesMarkdown, postgresContract, postgresSource, preferRules, primitivesCatalog, primitivesSummary, readGenesisConfig, readPackageExports, readReleaseManifest, renderAgentsBlock, renderSkill, routesDir, ruleNamespace, runDoctor, satisfies, skillDescription, sqlStatements, subagentContext, subagentHookOutput, toJson, unlistedGuides, validateConfig, validateDeclaration, validateLinks, webRoutes, writeAgentGuide, writeAgentHooks };
7309
7606
  //# sourceMappingURL=doctor.js.map
7310
7607
  //# sourceMappingURL=doctor.js.map