@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/vite.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([
@@ -827,6 +846,7 @@ var KNOWN = /* @__PURE__ */ new Set([
827
846
  "forbiddenImports",
828
847
  "rules",
829
848
  "allow",
849
+ "extend",
830
850
  "patterns",
831
851
  "plugins",
832
852
  "packs",
@@ -841,14 +861,17 @@ var KNOWN = /* @__PURE__ */ new Set([
841
861
  "$comment"
842
862
  ]);
843
863
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
844
- var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
864
+ var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped", "extension-invalid"]);
865
+ var CONFIG_RULES = /* @__PURE__ */ new Set(["stale-exception", "stale-extension", "package-rule-override"]);
866
+ var EXTENSION_KEYS = /* @__PURE__ */ new Set(["rule", "file", "buildsOn", "reason", "upstream"]);
867
+ var EXTENSION_REASON_MIN = { chars: 40, words: 6 };
845
868
  var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
846
869
  var PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
847
870
  var CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
848
871
  var PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
849
872
  var PACK_KEYS = {
850
873
  native: { routerRoot: "path" },
851
- supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
874
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string", automaticBranching: "boolean" },
852
875
  packages: { base: "string" }
853
876
  };
854
877
  function appPath(v, where2, fail) {
@@ -909,6 +932,7 @@ function readGenesisConfig(root) {
909
932
  if (supabase !== true) out.supabase = supabase;
910
933
  }
911
934
  if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
935
+ if (raw.environments !== void 0) out.environments = validateEnvironments(raw.environments, file);
912
936
  return out;
913
937
  }
914
938
  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}$/;
@@ -1051,6 +1075,30 @@ function validateConfig(raw, source = "config") {
1051
1075
  }
1052
1076
  });
1053
1077
  }
1078
+ if (c.extend !== void 0) {
1079
+ if (!Array.isArray(c.extend)) fail(`"extend" must be a list of { rule, file, buildsOn, reason, upstream? }`);
1080
+ const seen = /* @__PURE__ */ new Set();
1081
+ c.extend.forEach((e, i) => {
1082
+ const where2 = `extend[${i}]`;
1083
+ if (!isObject(e)) return fail(`${where2} must be an object`);
1084
+ for (const k of Object.keys(e)) if (!EXTENSION_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: ${[...EXTENSION_KEYS].join(", ")})`);
1085
+ for (const k of ["rule", "file", "buildsOn", "reason"]) if (typeof e[k] !== "string" || !e[k].trim()) fail(`${where2} needs "${k}"`);
1086
+ const { rule, file, buildsOn, reason } = e;
1087
+ 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`);
1088
+ 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)`);
1089
+ if (/[*?[\]{}]/.test(file)) fail(`${where2}.file must be one file, not a glob: each extension is reviewed on its own`);
1090
+ e.file = appPath(file, `${where2}.file`, fail);
1091
+ 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")`);
1092
+ const text = reason.trim();
1093
+ if (text.length < EXTENSION_REASON_MIN.chars || text.split(/\s+/).length < EXTENSION_REASON_MIN.words) {
1094
+ 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`);
1095
+ }
1096
+ 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`);
1097
+ const key2 = `${rule}\0${e.file}`;
1098
+ if (seen.has(key2)) fail(`${where2} extends ${rule} in ${e.file} twice`);
1099
+ seen.add(key2);
1100
+ });
1101
+ }
1054
1102
  if (c.patterns !== void 0) {
1055
1103
  if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
1056
1104
  c.patterns.forEach((p, i) => {
@@ -1107,6 +1155,7 @@ function validateConfig(raw, source = "config") {
1107
1155
  if (!want) fail(`${pack}: unknown setting "${k}"`);
1108
1156
  if (want === "string" && typeof v !== "string") fail(`${pack}.${k} must be a string`);
1109
1157
  if (want === "list" && !isStringList(v)) fail(`${pack}.${k} must be a list of strings`);
1158
+ if (want === "boolean" && typeof v !== "boolean") fail(`${pack}.${k} must be true or false`);
1110
1159
  if (want === "string" && !v.trim()) fail(`${pack}.${k} must not be empty`);
1111
1160
  if (want === "path") block[k] = appPath(v, `${pack}.${k}`, fail);
1112
1161
  }
@@ -1158,7 +1207,7 @@ function globToRegExp(glob) {
1158
1207
  }
1159
1208
  function globMatcher(globs) {
1160
1209
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1161
- return (path49) => res.some((re) => re.test(path49));
1210
+ return (path50) => res.some((re) => re.test(path50));
1162
1211
  }
1163
1212
  var GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
1164
1213
  var BLOCK_ID = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
@@ -1743,6 +1792,9 @@ function scanFiles(root, config) {
1743
1792
  for (const pkg of local) walk3(pkg.dir);
1744
1793
  return files;
1745
1794
  }
1795
+ function withText(file, text) {
1796
+ return { ...file, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(file.ext)) };
1797
+ }
1746
1798
  function lineAt(text, index) {
1747
1799
  let line = 1;
1748
1800
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
@@ -2711,6 +2763,7 @@ var BUILTIN_RULES = [
2711
2763
  "migration-edited",
2712
2764
  "migration-testing-kit",
2713
2765
  "migration-view-rls",
2766
+ "exposed-schema-created-later",
2714
2767
  // packages pack
2715
2768
  "package-app-import",
2716
2769
  "package-undeclared-dependency",
@@ -2736,6 +2789,10 @@ var BUILTIN_RULES = [
2736
2789
  "ratchet-skipped",
2737
2790
  "allow-grew",
2738
2791
  "rules-weakened",
2792
+ "extension-added",
2793
+ // declared extensions (extensions.ts)
2794
+ "stale-extension",
2795
+ "extension-invalid",
2739
2796
  // agent guide (primitives.ts)
2740
2797
  "agent-guide-stale",
2741
2798
  // supabase pack: contracts (contracts.ts)
@@ -3024,6 +3081,34 @@ function readSource(abs) {
3024
3081
  return null;
3025
3082
  }
3026
3083
  }
3084
+ var lastBlanked = null;
3085
+ function blankStrings(code) {
3086
+ if (lastBlanked?.source === code) return lastBlanked.blanked;
3087
+ const out = code.split("");
3088
+ for (let i = 0; i < code.length; i++) {
3089
+ const ch = code[i];
3090
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
3091
+ let j = i - 1;
3092
+ while (j >= 0 && /[ \t]/.test(code[j])) j--;
3093
+ const before = j >= 0 ? code[j] : "\n";
3094
+ const word = /[\w$]/.test(before) ? /(?:^|[^\w$])(return|case|typeof|in|of|yield|await)$/.test(code.slice(Math.max(0, j - 8), j + 1)) : false;
3095
+ if (/[\w$)\]]/.test(before) && !word) continue;
3096
+ let k = i + 1;
3097
+ for (; k < code.length; k++) {
3098
+ const c = code[k];
3099
+ if (c === "\\") {
3100
+ k++;
3101
+ continue;
3102
+ }
3103
+ if (c === ch) break;
3104
+ if (c === "\n" && ch !== "`") break;
3105
+ }
3106
+ for (let x = i + 1; x < k && x < code.length; x++) if (code[x] !== "\n") out[x] = " ";
3107
+ i = k;
3108
+ }
3109
+ lastBlanked = { source: code, blanked: out.join("") };
3110
+ return lastBlanked.blanked;
3111
+ }
3027
3112
  function tagEnd(code, start) {
3028
3113
  let depth = 0;
3029
3114
  let quote2 = null;
@@ -3045,7 +3130,8 @@ function tagEnd(code, start) {
3045
3130
  }
3046
3131
  return { end: code.length, selfClosing: false };
3047
3132
  }
3048
- function openElementsAt(code, index, track) {
3133
+ function openElementsAt(source, index, track) {
3134
+ const code = blankStrings(source);
3049
3135
  const open = [];
3050
3136
  const re = /<(\/?)([A-Z][\w.]*)(?=[\s>/])/g;
3051
3137
  for (let m = re.exec(code); m && m.index < index; m = re.exec(code)) {
@@ -3897,9 +3983,9 @@ var PackageDeclarationError = class extends Error {
3897
3983
  var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
3898
3984
  var ID = /^[a-z0-9][a-z0-9-]*$/;
3899
3985
  var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
3900
- var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
3986
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly", "extensible"]);
3901
3987
  var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
3902
- var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
3988
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "inside", "pattern"]);
3903
3989
  var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
3904
3990
  var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "catalog", "primitives", "plugin", "$comment"]);
3905
3991
  var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
@@ -4008,6 +4094,9 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4008
4094
  if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
4009
4095
  if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
4010
4096
  for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
4097
+ if (raw.extensible !== void 0 && !(isStringList2(raw.extensible) && raw.extensible.every((n) => /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)))) {
4098
+ fail(`${at}.extensible must be a list of export names, or parts of one ("ResourceView.slots")`);
4099
+ }
4011
4100
  if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
4012
4101
  const forbid = raw.forbid;
4013
4102
  for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
@@ -4020,6 +4109,7 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4020
4109
  const unless = raw.unless;
4021
4110
  for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
4022
4111
  if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
4112
+ 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`);
4023
4113
  if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
4024
4114
  }
4025
4115
  return raw;
@@ -4134,6 +4224,7 @@ function compile(rule, setting, routes) {
4134
4224
  imports: (rule.forbid.imports ?? []).map(specMatcher),
4135
4225
  ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
4136
4226
  unlessRenders: new Set(rule.unless?.renders ?? []),
4227
+ unlessInside: new Set(rule.unless?.inside ?? []),
4137
4228
  ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
4138
4229
  };
4139
4230
  }
@@ -4145,10 +4236,11 @@ function messageFor(rule, found) {
4145
4236
  const docs = rule.docs ? ` See ${rule.docs}` : "";
4146
4237
  return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
4147
4238
  }
4239
+ var CHILDREN = /\{\s*(?:props\.)?children\s*\}/g;
4148
4240
  var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
4149
4241
  var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
4150
4242
  var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
4151
- function wrappersIn(file, elements, c) {
4243
+ function wrappersIn(file, elements, names, accept) {
4152
4244
  const out = /* @__PURE__ */ new Map();
4153
4245
  const decls = [...file.code.matchAll(TOP_LEVEL)];
4154
4246
  const listed = /* @__PURE__ */ new Map();
@@ -4161,12 +4253,12 @@ function wrappersIn(file, elements, c) {
4161
4253
  for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
4162
4254
  decls.forEach((d, i) => {
4163
4255
  const name = d[3];
4164
- if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
4256
+ if (!/^[A-Z]/.test(name) || names.has(name)) return;
4165
4257
  const end = decls[i + 1]?.index ?? file.code.length;
4166
- const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
4167
- if (!hit) return;
4168
- const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4169
- for (const n of names) out.set(n, hit[1]);
4258
+ const hit = elements.find((m) => m.index > d.index && m.index < end && names.has(m[1]));
4259
+ if (!hit || accept && !accept(d.index, end)) return;
4260
+ const exported = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4261
+ for (const n of exported) out.set(n, hit[1]);
4170
4262
  });
4171
4263
  return out;
4172
4264
  }
@@ -4174,6 +4266,32 @@ function runPrefer(ctx, c) {
4174
4266
  const own = c.rule.packageDir;
4175
4267
  const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
4176
4268
  const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
4269
+ const scanned = new Map(ctx.files.map((f) => [f.absolutePath, f]));
4270
+ const importedBy = /* @__PURE__ */ new Map();
4271
+ const importsOf = (file) => {
4272
+ if (!importedBy.has(file)) importedBy.set(file, localImportedNames(ctx.root, file));
4273
+ return importedBy.get(file);
4274
+ };
4275
+ const builders = /* @__PURE__ */ new Map();
4276
+ const buildersIn = (abs) => {
4277
+ if (!builders.has(abs)) {
4278
+ const target = scanned.get(abs) ?? readSource(abs);
4279
+ const code = target ? "ext" in target ? target.code : stripBlockComments(target.code, true) : "";
4280
+ const childrenInside = (start, end) => [...code.slice(start, end).matchAll(CHILDREN)].some((m) => openElementsAt(code, start + m.index, (n) => c.unlessInside.has(n)).length > 0);
4281
+ builders.set(abs, code ? wrappersIn({ code }, [...code.matchAll(ELEMENT)], c.unlessInside, childrenInside) : /* @__PURE__ */ new Map());
4282
+ }
4283
+ return builders.get(abs);
4284
+ };
4285
+ const nestedInBuilder = (file, index) => {
4286
+ if (!c.unlessInside.size) return false;
4287
+ const imported = importsOf(file);
4288
+ const isBuilder = (name) => {
4289
+ if (c.unlessInside.has(name)) return true;
4290
+ const from = name.includes(".") ? void 0 : imported.get(name);
4291
+ return from !== void 0 && buildersIn(from.file).has(from.name);
4292
+ };
4293
+ return openElementsAt(file.code, index, isBuilder).length > 0;
4294
+ };
4177
4295
  const wrappers = /* @__PURE__ */ new Map();
4178
4296
  const renderedBy = /* @__PURE__ */ new Map();
4179
4297
  for (const file of checked) {
@@ -4181,16 +4299,17 @@ function runPrefer(ctx, c) {
4181
4299
  const elements = [...file.code.matchAll(ELEMENT)];
4182
4300
  renderedBy.set(file, elements);
4183
4301
  if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
4184
- const found = wrappersIn(file, elements, c);
4302
+ const found = wrappersIn(file, elements, c.jsx);
4185
4303
  if (found.size) wrappers.set(file.absolutePath, found);
4186
4304
  }
4187
4305
  for (const file of checked) {
4188
4306
  const elements = renderedBy.get(file) ?? [];
4189
4307
  if (exempt(file, elements.map((m) => m[1]))) continue;
4190
4308
  const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
4191
- const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
4309
+ const imported = wrappers.size && elements.length ? importsOf(file) : null;
4192
4310
  for (const m of elements) {
4193
4311
  const name = m[1];
4312
+ if (nestedInBuilder(file, m.index)) continue;
4194
4313
  if (c.jsx.has(name)) {
4195
4314
  report(lineAt(file.code, m.index), name, `renders <${name}>`);
4196
4315
  continue;
@@ -4207,6 +4326,7 @@ function runPrefer(ctx, c) {
4207
4326
  if (c.pattern) {
4208
4327
  c.pattern.lastIndex = 0;
4209
4328
  for (const m of file.code.matchAll(c.pattern)) {
4329
+ if (nestedInBuilder(file, m.index)) continue;
4210
4330
  const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
4211
4331
  report(lineAt(file.code, m.index), text, `has ${text}`);
4212
4332
  }
@@ -4854,6 +4974,67 @@ function checkSupabasePack(ctx) {
4854
4974
  checkViewInvoker(ctx, migrations, exposed);
4855
4975
  checkDefinerSearchPath(ctx, migrations);
4856
4976
  checkTestingKit(ctx, migrations);
4977
+ checkExposedSchemasCreatedLater(ctx, dir, migrations, settings.exposedSchemas, settings.automaticBranching !== false);
4978
+ }
4979
+ var PLATFORM_SCHEMAS = /* @__PURE__ */ new Set(["public", "graphql_public", "graphql", "extensions", "storage", "auth", "realtime", "vault"]);
4980
+ function apiSchemas(toml) {
4981
+ const lines = toml.split("\n");
4982
+ const start = lines.findIndex((l) => /^\s*\[api\]\s*(?:#.*)?$/.test(l));
4983
+ if (start < 0) return null;
4984
+ let end = lines.findIndex((l, i) => i > start && /^\s*\[/.test(l));
4985
+ if (end < 0) end = lines.length;
4986
+ const bare = (l) => {
4987
+ let quoted = false;
4988
+ for (let i = 0; i < l.length; i++) {
4989
+ if (l[i] === '"' && l[i - 1] !== "\\") quoted = !quoted;
4990
+ else if (l[i] === "#" && !quoted) return l.slice(0, i);
4991
+ }
4992
+ return l;
4993
+ };
4994
+ const body = lines.slice(start + 1, end).map(bare);
4995
+ const enabled = !body.some((l) => /^\s*enabled\s*=\s*false\b/.test(l));
4996
+ const at = body.findIndex((l) => /^\s*schemas\s*=/.test(l));
4997
+ if (at < 0) return { enabled, schemas: [], line: start + 1 };
4998
+ let list = "";
4999
+ for (let i = at; i < body.length; i++) {
5000
+ list += `${body[i]}
5001
+ `;
5002
+ if (body[i].includes("]")) break;
5003
+ }
5004
+ const inner = /\[([\s\S]*?)\]/.exec(list)?.[1] ?? "";
5005
+ const schemas = [...inner.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((m) => (m[1] ?? m[2]).trim().toLowerCase()).filter(Boolean);
5006
+ return { enabled, schemas, line: start + at + 2 };
5007
+ }
5008
+ function checkExposedSchemasCreatedLater(ctx, dir, migrations, configured, branching) {
5009
+ const created = /* @__PURE__ */ new Map();
5010
+ for (const { file, statements } of migrations) {
5011
+ for (const { sql, line } of statements) {
5012
+ const m = /^create schema (?:if not exists )?"?([\w$]+)"?/.exec(sql);
5013
+ if (m && m[1] !== "authorization" && !created.has(m[1])) created.set(m[1], { file, line });
5014
+ }
5015
+ }
5016
+ const tomlFile = path21.posix.join(path21.posix.dirname(dir), "config.toml");
5017
+ const tomlText = existsSync(path21.join(ctx.root, tomlFile)) ? readFileSync(path21.join(ctx.root, tomlFile), "utf8") : null;
5018
+ const api2 = tomlText === null ? null : apiSchemas(tomlText);
5019
+ const sources = [];
5020
+ if (api2?.enabled) for (const schema of api2.schemas) sources.push({ schema, file: tomlFile, line: api2.line, where: `${tomlFile} [api] schemas` });
5021
+ for (const schema of api2?.enabled === false ? [] : configured ?? []) {
5022
+ const s = schema.toLowerCase();
5023
+ if (!sources.some((x) => x.schema === s)) sources.push({ schema: s, file: "genesis.config.json", where: "doctor.supabase.exposedSchemas" });
5024
+ }
5025
+ for (const { schema, file, line, where: where2 } of sources) {
5026
+ if (PLATFORM_SCHEMAS.has(schema)) continue;
5027
+ const by = created.get(schema);
5028
+ if (by && !branching) continue;
5029
+ ctx.report({
5030
+ rule: "exposed-schema-created-later",
5031
+ level: "warn",
5032
+ file,
5033
+ ...line ? { line } : {},
5034
+ subject: schema,
5035
+ 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`
5036
+ });
5037
+ }
4857
5038
  }
4858
5039
  function checkTestingKit(ctx, migrations) {
4859
5040
  for (const { file, statements } of migrations) {
@@ -5941,13 +6122,34 @@ function git3(root, args) {
5941
6122
  return r.status === 0 ? r.stdout : null;
5942
6123
  }
5943
6124
  function changedSince(root, base) {
5944
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6125
+ const mergeBase = mergeBaseOf2(root, base);
5945
6126
  if (!mergeBase) return null;
5946
6127
  const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
5947
6128
  const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
5948
6129
  if (committed === null || untracked === null) return null;
5949
6130
  return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
5950
6131
  }
6132
+ function originsSince(root, base) {
6133
+ const out = /* @__PURE__ */ new Map();
6134
+ const mergeBase = mergeBaseOf2(root, base);
6135
+ if (!mergeBase) return out;
6136
+ const diff = git3(root, ["diff", "-z", "-M", "--name-status", "--relative", mergeBase, "--"]);
6137
+ if (diff === null) return out;
6138
+ const parts = diff.split("\0");
6139
+ for (let i = 0; i < parts.length; ) {
6140
+ const status = parts[i++] ?? "";
6141
+ if (!status) continue;
6142
+ if (status.startsWith("R") || status.startsWith("C")) {
6143
+ const from = parts[i++];
6144
+ const to = parts[i++];
6145
+ if (status.startsWith("R")) out.set(to, from);
6146
+ } else i++;
6147
+ }
6148
+ return out;
6149
+ }
6150
+ function mergeBaseOf2(root, base) {
6151
+ return git3(root, ["merge-base", base, "HEAD"])?.trim() || null;
6152
+ }
5951
6153
  var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
5952
6154
  function showAt(dir, rev, file) {
5953
6155
  const at = `${rev}:./${file}`;
@@ -5955,7 +6157,7 @@ function showAt(dir, rev, file) {
5955
6157
  return git3(dir, ["show", at]);
5956
6158
  }
5957
6159
  function configAtBase(root, base, explicitFile) {
5958
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6160
+ const mergeBase = mergeBaseOf2(root, base);
5959
6161
  if (!mergeBase) return null;
5960
6162
  const candidates = explicitFile ? [{ dir: path21.dirname(explicitFile), file: path21.basename(explicitFile), explicit: true }] : [
5961
6163
  { dir: root, file: "genesis.config.json", explicit: false },
@@ -5976,7 +6178,12 @@ function configAtBase(root, base, explicitFile) {
5976
6178
  continue;
5977
6179
  }
5978
6180
  const b = objectOr(block);
5979
- return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
6181
+ return {
6182
+ allow: Array.isArray(b.allow) ? b.allow : [],
6183
+ extend: Array.isArray(b.extend) ? b.extend : [],
6184
+ rules: objectOr(b.rules),
6185
+ packageRules: objectOr(b.packageRules)
6186
+ };
5980
6187
  }
5981
6188
  return "absent";
5982
6189
  }
@@ -5990,6 +6197,16 @@ function allowGrew(allow, before, base) {
5990
6197
  message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
5991
6198
  }));
5992
6199
  }
6200
+ function extensionsAdded(extend, before, base) {
6201
+ const had = new Set(before.map((e) => `${e.rule}\0${e.file}\0${e.buildsOn}`));
6202
+ return extend.filter((e) => !had.has(`${e.rule}\0${e.file}\0${e.buildsOn}`)).map((e) => ({
6203
+ rule: "extension-added",
6204
+ level: "info",
6205
+ file: e.file,
6206
+ subject: e.rule,
6207
+ 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`
6208
+ }));
6209
+ }
5993
6210
  var RANK = { off: 0, info: 1, warn: 2, error: 3 };
5994
6211
  function rulesWeakened(config, before, base) {
5995
6212
  const out = [];
@@ -6027,14 +6244,169 @@ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
6027
6244
  "plugin-error",
6028
6245
  "build",
6029
6246
  "agent-guide-stale",
6030
- "contracts-stale"
6247
+ "contracts-stale",
6248
+ "stale-extension",
6249
+ "extension-added"
6031
6250
  ]);
6251
+ function isRatcheted(rule, config, newOnly) {
6252
+ return !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6253
+ }
6254
+ var countKey = (file, rule) => `${file}\0${rule}`;
6255
+ function countFindings(findings) {
6256
+ const counts = /* @__PURE__ */ new Map();
6257
+ for (const f of findings) counts.set(countKey(f.file, f.rule), (counts.get(countKey(f.file, f.rule)) ?? 0) + 1);
6258
+ return counts;
6259
+ }
6032
6260
  function applyRatchet(findings, options) {
6033
- const { config, newOnly, changed, base, isAppPath } = options;
6034
- const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6261
+ const { config, newOnly, changed, base, isAppPath, baseCounts, existedAtBase } = options;
6262
+ const originOf = options.originOf ?? ((f) => f);
6263
+ const counts = countFindings(findings.map((f) => ({ file: originOf(f.file), rule: f.rule })));
6035
6264
  return findings.map((f) => {
6036
- if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
6037
- return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6265
+ if (f.level === "info" || !isRatcheted(f.rule, config, newOnly) || !isAppPath(f.file)) return f;
6266
+ if (!touched(f.file, changed)) return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6267
+ const origin = originOf(f.file);
6268
+ if (!baseCounts || !existedAtBase?.(origin)) return f;
6269
+ const now = counts.get(countKey(origin, f.rule)) ?? 0;
6270
+ const was = baseCounts.get(countKey(origin, f.rule)) ?? 0;
6271
+ const where2 = origin === f.file ? "this file" : `the files from ${origin}`;
6272
+ 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)` };
6273
+ return { ...f, level: "info", message: `${f.message} (ratcheted: ${now} in ${where2}, ${was} at the merge base with ${base})` };
6274
+ });
6275
+ }
6276
+ function snapshotAtBase(root, base, files, changed, originOf = (f) => f) {
6277
+ const mergeBase = mergeBaseOf2(root, base);
6278
+ if (!mergeBase) return null;
6279
+ const out = [];
6280
+ const seen = /* @__PURE__ */ new Set();
6281
+ for (const f of files) {
6282
+ if (!changed.has(f.path)) {
6283
+ if (!seen.has(f.path)) out.push(f);
6284
+ seen.add(f.path);
6285
+ continue;
6286
+ }
6287
+ const origin = originOf(f.path);
6288
+ if (seen.has(origin)) continue;
6289
+ seen.add(origin);
6290
+ const text = showAt(root, mergeBase, origin);
6291
+ if (text === null) return null;
6292
+ if (text !== void 0) out.push(withText({ ...f, path: origin, absolutePath: path21.join(root, origin) }, text));
6293
+ }
6294
+ const cache2 = /* @__PURE__ */ new Map();
6295
+ return {
6296
+ mergeBase,
6297
+ files: out,
6298
+ existed(file) {
6299
+ if (!cache2.has(file)) cache2.set(file, git3(root, ["cat-file", "-e", `${mergeBase}:./${file}`]) !== null);
6300
+ return cache2.get(file);
6301
+ }
6302
+ };
6303
+ }
6304
+
6305
+ // src/doctor/extensions.ts
6306
+ function pointProblem(entry, packages) {
6307
+ const rule = preferRules(packages).find((r) => r.ruleId === entry.rule);
6308
+ if (!rule?.extensible?.length) return `${entry.rule} declares no extension points, so it can't be extended (debt goes in allow, and is fixed)`;
6309
+ if (!rule.extensible.includes(entry.buildsOn)) return `${entry.buildsOn} isn't one of ${entry.rule}'s extension points (${rule.extensible.join(", ")})`;
6310
+ return null;
6311
+ }
6312
+ function extensionProblem(entry, ctx) {
6313
+ const point = pointProblem(entry, ctx.packages);
6314
+ if (point) return point;
6315
+ const name = entry.buildsOn.split(".")[0];
6316
+ const replaces = preferRules(ctx.packages).find((r) => r.forbid.jsx?.includes(name));
6317
+ if (replaces) return `${name} is what ${replaces.ruleId} replaces (use ${replaces.use}); a legacy component can't be built on`;
6318
+ const flagged = ctx.raw.find((f) => f.file === entry.file && f.subject === name);
6319
+ if (flagged) return `${name} is flagged in this file by ${flagged.rule}; build on a current Genesis primitive`;
6320
+ const file = ctx.files.find((f) => f.path === entry.file);
6321
+ if (!file) return `${entry.file} isn't one of the files the doctor scans`;
6322
+ const imported = genesisNamedImports(file.code).some((i) => i.names.includes(name));
6323
+ if (!imported) return `${entry.file} doesn't import ${name} from a Genesis package; buildsOn names the extension point the file uses`;
6324
+ if (!usesPoint(blankStrings(file.code), entry.buildsOn)) {
6325
+ const prop = entry.buildsOn.split(".")[1];
6326
+ 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`;
6327
+ }
6328
+ return null;
6329
+ }
6330
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6331
+ function usesPoint(code, point) {
6332
+ const [name, prop] = point.split(".");
6333
+ const n = escape2(name);
6334
+ if (!prop) return new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])|(?<![\\w$.])${n}\\s*(?:<[^>()]*>)?\\s*\\(`).test(code);
6335
+ for (const m of code.matchAll(new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])`, "g"))) {
6336
+ const { end } = tagEnd(code, m.index);
6337
+ if (new RegExp(`(?<![\\w$.])${escape2(prop)}\\s*=`).test(code.slice(m.index, end))) return true;
6338
+ }
6339
+ return false;
6340
+ }
6341
+ function applyExtensions(findings, ctx) {
6342
+ const entries = ctx.config.extend ?? [];
6343
+ if (!entries.length) return findings;
6344
+ const staleLevel = ctx.config.rules?.["stale-extension"];
6345
+ const covered = /* @__PURE__ */ new Set();
6346
+ const grew = /* @__PURE__ */ new Map();
6347
+ const out = [];
6348
+ 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}` });
6349
+ for (const entry of entries) {
6350
+ if (ctx.config.rules?.[entry.rule] === "off" || ctx.config.packageRules?.[entry.rule]?.level === "off") continue;
6351
+ const point = pointProblem(entry, ctx.packages);
6352
+ if (point) {
6353
+ invalid(entry, point);
6354
+ continue;
6355
+ }
6356
+ const hits = findings.filter((f) => f.rule === entry.rule && f.file === entry.file);
6357
+ if (!hits.length) {
6358
+ if (staleLevel === "off") continue;
6359
+ out.push({
6360
+ rule: "stale-extension",
6361
+ level: staleLevel ?? "warn",
6362
+ file: entry.file,
6363
+ line: 0,
6364
+ subject: entry.rule,
6365
+ message: `the extension of ${entry.rule} (building on ${entry.buildsOn}) no longer matches a finding in this file; remove it from doctor.extend`
6366
+ });
6367
+ continue;
6368
+ }
6369
+ const problem = extensionProblem(entry, ctx);
6370
+ if (problem) {
6371
+ invalid(entry, problem);
6372
+ continue;
6373
+ }
6374
+ const limit = ctx.limit?.(entry);
6375
+ if (limit !== void 0 && hits.length > limit) {
6376
+ 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)`);
6377
+ continue;
6378
+ }
6379
+ for (const h of hits) covered.add(h);
6380
+ }
6381
+ const kept = findings.filter((f) => !covered.has(f)).map((f) => grew.has(f) ? { ...f, message: grew.get(f) } : f);
6382
+ return [...kept, ...out].sort(byPlace);
6383
+ }
6384
+ var byPlace = (x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule);
6385
+ var RANK2 = { info: 0, warn: 1, error: 2 };
6386
+ function dedupeFindings(findings) {
6387
+ const groups = /* @__PURE__ */ new Map();
6388
+ const order = [];
6389
+ for (const f of findings) {
6390
+ if (f.subject === void 0 || !f.line) {
6391
+ order.push([f]);
6392
+ continue;
6393
+ }
6394
+ const key2 = `${f.file}\0${f.line}\0${f.subject}`;
6395
+ const list = groups.get(key2) ?? [];
6396
+ const group = list.find((g) => !g.some((x) => x.rule === f.rule));
6397
+ if (group) group.push(f);
6398
+ else {
6399
+ const fresh = [f];
6400
+ list.push(fresh);
6401
+ groups.set(key2, list);
6402
+ order.push(fresh);
6403
+ }
6404
+ }
6405
+ return order.map((group) => {
6406
+ if (group.length === 1) return group[0];
6407
+ const primary = group.reduce((a, b) => RANK2[b.level] > RANK2[a.level] ? b : a);
6408
+ const rules = [primary.rule, ...group.filter((g) => g !== primary).map((g) => g.rule)];
6409
+ return { ...primary, rules, message: `${primary.message} (also ${rules.slice(1).join(", ")})` };
6038
6410
  });
6039
6411
  }
6040
6412
  var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
@@ -6104,6 +6476,7 @@ async function checkContracts(ctx, read2 = postgresContract) {
6104
6476
  }
6105
6477
  }
6106
6478
  var GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
6479
+ var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
6107
6480
  var CORE = [
6108
6481
  {
6109
6482
  need: "anything, before building it",
@@ -6176,14 +6549,79 @@ var SKILL_PATH = ".claude/skills/genesis/SKILL.md";
6176
6549
  var AGENTS_START = "<!-- genesis-primitives:start -->";
6177
6550
  var AGENTS_END = "<!-- genesis-primitives:end -->";
6178
6551
  var RULES = [
6179
- "Use the Genesis primitive for the need first: reuse, then extend, then invent (docs/FRAMEWORK.md, G1 to G6).",
6552
+ `Use the Genesis primitive for the need first: reuse, then extend, then invent (G1 to G6 in ${GENESIS_DOCS}/FRAMEWORK.md).`,
6180
6553
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
6181
6554
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
6182
6555
  "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.",
6183
6556
  "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
6184
6557
  "Run `genesis doctor` before you finish; it enforces these rules."
6185
6558
  ];
6186
- function renderSkill(rows) {
6559
+ function skillDescription(text) {
6560
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1];
6561
+ if (!fm) return "";
6562
+ const lines = fm.split(/\r?\n/);
6563
+ const i = lines.findIndex((l) => /^description:/.test(l));
6564
+ if (i < 0) return "";
6565
+ const first = lines[i].replace(/^description:\s*/, "").trim();
6566
+ if (first && !/^[>|][+-]?$/.test(first)) return first.replace(/^["']|["']$/g, "");
6567
+ const more = [];
6568
+ for (const l of lines.slice(i + 1)) {
6569
+ if (!/^\s+\S/.test(l)) break;
6570
+ more.push(l.trim());
6571
+ }
6572
+ return more.join(" ");
6573
+ }
6574
+ var GUIDE_SEARCH_LEVELS = 4;
6575
+ function stableGuidePath(root, p) {
6576
+ const real2 = (f) => {
6577
+ try {
6578
+ return realpathSync(f);
6579
+ } catch {
6580
+ return null;
6581
+ }
6582
+ };
6583
+ const want = real2(p.dir);
6584
+ for (let dir = root, level = 0; level <= GUIDE_SEARCH_LEVELS; level++) {
6585
+ const found = path21.join(dir, "node_modules", p.name);
6586
+ if (existsSync(found)) {
6587
+ const file = path21.join(found, "SKILL.md");
6588
+ return want !== null && real2(found) === want && existsSync(file) ? file : null;
6589
+ }
6590
+ if (existsSync(path21.join(dir, ".git")) || existsSync(path21.join(dir, "pnpm-workspace.yaml"))) return null;
6591
+ const up = path21.dirname(dir);
6592
+ if (up === dir) return null;
6593
+ dir = up;
6594
+ }
6595
+ return null;
6596
+ }
6597
+ function packageGuides(root, packages) {
6598
+ const guides = [];
6599
+ for (const p of packages) {
6600
+ const stable = p.local ? path21.join(p.dir, "SKILL.md") : stableGuidePath(root, p);
6601
+ const text = stable === null ? null : read(stable);
6602
+ if (stable === null || text === null) continue;
6603
+ const description = skillDescription(text);
6604
+ const at = description.indexOf("Load before");
6605
+ guides.push({ package: p.name, path: path21.relative(root, stable).split(path21.sep).join("/"), when: at >= 0 ? description.slice(at) : description });
6606
+ }
6607
+ return guides.sort((a, b) => a.package.localeCompare(b.package));
6608
+ }
6609
+ function unlistedGuides(root, packages) {
6610
+ const listed = new Set(packageGuides(root, packages).map((g) => g.package));
6611
+ return packages.filter((p) => !p.local && !listed.has(p.name) && existsSync(path21.join(p.dir, "SKILL.md"))).map((p) => p.name).sort();
6612
+ }
6613
+ function guidesSection(guides) {
6614
+ if (!guides.length) return [];
6615
+ return [
6616
+ "### Package guides (they match the installed versions)",
6617
+ "",
6618
+ "Before using a package's primitives, read its guide:",
6619
+ "",
6620
+ ...guides.map((g) => `- \`${g.path}\` (${g.package}): ${g.when}`),
6621
+ ""
6622
+ ];
6623
+ }
6624
+ function renderSkill(rows, guides = []) {
6187
6625
  return [
6188
6626
  "---",
6189
6627
  "name: genesis",
@@ -6196,6 +6634,7 @@ function renderSkill(rows) {
6196
6634
  "",
6197
6635
  ...RULES.map((r) => `- ${r}`),
6198
6636
  "",
6637
+ ...guidesSection(guides),
6199
6638
  "## What to use for each need",
6200
6639
  "",
6201
6640
  catalogTable(rows, { docs: true }),
@@ -6204,7 +6643,7 @@ function renderSkill(rows) {
6204
6643
  ""
6205
6644
  ].join("\n");
6206
6645
  }
6207
- function renderAgentsBlock(rows) {
6646
+ function renderAgentsBlock(rows, guides = []) {
6208
6647
  return [
6209
6648
  AGENTS_START,
6210
6649
  "## Building with Genesis",
@@ -6215,6 +6654,7 @@ function renderAgentsBlock(rows) {
6215
6654
  "",
6216
6655
  ...RULES.map((r) => `- ${r}`),
6217
6656
  "",
6657
+ ...guidesSection(guides),
6218
6658
  catalogTable(rows),
6219
6659
  AGENTS_END
6220
6660
  ].join("\n");
@@ -6233,14 +6673,37 @@ function currentAgentsBlock(agents) {
6233
6673
  if (span === "broken") return "broken";
6234
6674
  return agents.slice(span.start, span.end).replace(/\r\n/g, "\n");
6235
6675
  }
6236
- var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
6676
+ function claudeState(root) {
6677
+ const file = path21.join(root, "CLAUDE.md");
6678
+ let names = [];
6679
+ try {
6680
+ names = readdirSync(root);
6681
+ } catch {
6682
+ }
6683
+ if (!names.includes("CLAUDE.md")) return names.some((n) => n.toLowerCase() === "claude.md") ? "blocked" : "missing";
6684
+ let text;
6685
+ try {
6686
+ text = readFileSync(file, "utf8");
6687
+ } catch {
6688
+ return "blocked";
6689
+ }
6690
+ if (/^@AGENTS\.md\b/m.test(text)) return "ok";
6691
+ try {
6692
+ if (realpathSync(file) === realpathSync(path21.join(root, "AGENTS.md"))) return "ok";
6693
+ } catch {
6694
+ }
6695
+ return "no-import";
6696
+ }
6237
6697
  function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
6238
6698
  const rows = primitivesCatalog(packages);
6699
+ const guides = packageGuides(root, packages);
6239
6700
  const skill = read(path21.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
6240
6701
  const block = currentAgentsBlock(read(path21.join(root, agentsFile)));
6241
6702
  return {
6242
- skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
6243
- agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
6703
+ skill: skill === null ? "missing" : skill === renderSkill(rows, guides) ? "ok" : "stale",
6704
+ agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows, guides) ? "ok" : "stale",
6705
+ // Only the default AGENTS.md gets a CLAUDE.md written for it, so only then is a missing one reported.
6706
+ claude: agentsFile !== "AGENTS.md" ? "ok" : claudeState(root)
6244
6707
  };
6245
6708
  }
6246
6709
  function checkAgentGuide(ctx) {
@@ -6258,6 +6721,41 @@ function checkAgentGuide(ctx) {
6258
6721
  }[state.agents];
6259
6722
  ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
6260
6723
  }
6724
+ if (state.claude === "no-import") {
6725
+ 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" });
6726
+ }
6727
+ if (state.claude === "missing") {
6728
+ 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\`)` });
6729
+ }
6730
+ if (state.claude === "blocked") {
6731
+ 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}` });
6732
+ }
6733
+ const unlisted = unlistedGuides(ctx.root, ctx.packages);
6734
+ if (unlisted.length) {
6735
+ 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.` });
6736
+ }
6737
+ }
6738
+ var BLOCKED_FIX = "rename or replace it with a CLAUDE.md file (or remove the dangling link), then run genesis agents";
6739
+ var SETTINGS_PATH = ".claude/settings.json";
6740
+ var SUBAGENT_HOOK_COMMAND = '"$CLAUDE_PROJECT_DIR"/node_modules/.bin/genesis agents --hook subagent-start --dir "$CLAUDE_PROJECT_DIR" 2>/dev/null || true';
6741
+ var isObject4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
6742
+ var isGenesisHook = (h) => typeof h.command === "string" && h.command.includes("genesis agents --hook");
6743
+ function agentHooksState(root) {
6744
+ let settings;
6745
+ try {
6746
+ settings = JSON.parse(readFileSync(path21.join(root, SETTINGS_PATH), "utf8"));
6747
+ } catch {
6748
+ return "none";
6749
+ }
6750
+ const start = isObject4(settings) && isObject4(settings.hooks) ? settings.hooks["SubagentStart"] : void 0;
6751
+ 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);
6752
+ if (!commands.length) return "none";
6753
+ return commands.every((c) => c === SUBAGENT_HOOK_COMMAND) ? "ok" : "stale";
6754
+ }
6755
+ function checkAgentHooks(ctx) {
6756
+ if (agentHooksState(ctx.root) === "stale") {
6757
+ 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" });
6758
+ }
6261
6759
  }
6262
6760
 
6263
6761
  // src/blocks/templates.ts
@@ -7083,14 +7581,8 @@ async function runDoctor(options = {}) {
7083
7581
  }
7084
7582
  const raw = [];
7085
7583
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
7086
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
7087
- try {
7088
- await plugin.check(ctx);
7089
- } catch (err) {
7090
- if (err instanceof DoctorConfigError) throw err;
7091
- raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7092
- }
7093
- }
7584
+ const appChecks = [...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins];
7585
+ await runChecks(ctx, [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...appChecks]);
7094
7586
  if (options.build) {
7095
7587
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
7096
7588
  if (failure) raw.push(failure);
@@ -7100,30 +7592,57 @@ async function runDoctor(options = {}) {
7100
7592
  let changed = null;
7101
7593
  let skipped = false;
7102
7594
  const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
7103
- if (options.base && (ratchetNeeded || config.ratchet)) {
7595
+ if (options.base && (ratchetNeeded || config.ratchet || config.extend?.length)) {
7104
7596
  changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
7105
7597
  skipped ||= !changed;
7106
7598
  }
7107
7599
  const configFile = "file" in loaded ? loaded.file : null;
7108
- const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7600
+ const guarded = (config.allow?.length ?? 0) + (config.extend?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7109
7601
  let configSkipped = false;
7602
+ let baseExtend = [];
7110
7603
  if (options.base && configFile) {
7111
7604
  const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
7605
+ if (before && before !== "absent") baseExtend = before.extend;
7606
+ if (before === "absent") raw.push(...extensionsAdded(config.extend ?? [], [], options.base));
7112
7607
  if (before && before !== "absent") {
7113
7608
  raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
7114
7609
  raw.push(...rulesWeakened(config, before, options.base));
7610
+ raw.push(...extensionsAdded(config.extend ?? [], before.extend, options.base));
7115
7611
  }
7116
7612
  configSkipped = !before && guarded;
7117
7613
  }
7118
7614
  if (skipped || configSkipped) {
7119
7615
  raw.push(
7120
- 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` }
7616
+ 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` }
7121
7617
  );
7122
7618
  }
7123
- let findings = applyConfig(raw, config, packageRuleIds(packages));
7619
+ const packageIds = packageRuleIds(packages);
7620
+ const extensionCtx = { config, files, packages, raw };
7621
+ const configured = applyConfig(raw, config, packageIds);
7622
+ let findings = applyExtensions(configured, extensionCtx);
7124
7623
  if (options.base && changed) {
7125
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path21.join(root, f)) });
7624
+ const isAppPath = (f) => existsSync(path21.join(root, f));
7625
+ const origins = options.changedFiles ? /* @__PURE__ */ new Map() : originsSince(root, options.base);
7626
+ const originOf = (f) => origins.get(f) ?? f;
7627
+ 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));
7628
+ 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))));
7629
+ for (const e of heldExtensions) dueRules.add(e.rule);
7630
+ const snapshot = dueRules.size ? snapshotAtBase(root, options.base, files, changed, originOf) : null;
7631
+ let baseCounts;
7632
+ if (snapshot) {
7633
+ const before = [];
7634
+ await runChecks({ ...ctx, files: snapshot.files, report: (f) => before.push(f) }, baseChecks(dueRules, packageIds, packagePlugins, () => [...builtinChecks(config, { contracts: false, figma: false }), ...appChecks]));
7635
+ baseCounts = countFindings(applyConfig(before, config, packageIds));
7636
+ if (heldExtensions.length) {
7637
+ const counts = baseCounts;
7638
+ const held = new Set(heldExtensions);
7639
+ findings = applyExtensions(configured, { ...extensionCtx, limit: (e) => held.has(e) ? counts.get(countKey(originOf(e.file), e.rule)) ?? 0 : void 0 });
7640
+ }
7641
+ }
7642
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath, originOf, ...snapshot && baseCounts ? { baseCounts, existedAtBase: snapshot.existed } : {} });
7126
7643
  }
7644
+ findings = dedupeFindings(findings);
7645
+ const extensionsNew = (config.extend ?? []).filter((e) => findings.some((f) => f.rule === "extension-added" && f.file === e.file && f.subject === e.rule));
7127
7646
  const errors = findings.filter((f) => f.level === "error").length;
7128
7647
  const warnings = findings.filter((f) => f.level === "warn").length;
7129
7648
  const infos = findings.length - errors - warnings;
@@ -7137,9 +7656,24 @@ async function runDoctor(options = {}) {
7137
7656
  primitives: primitivesSummary(packages),
7138
7657
  errors,
7139
7658
  warnings,
7140
- infos
7659
+ infos,
7660
+ ...extensionsNew.length ? { extensionsAdded: extensionsNew } : {}
7141
7661
  };
7142
7662
  }
7663
+ function baseChecks(rules, preferIds, packagePlugins, all) {
7664
+ if ([...rules].every((r) => preferIds.has(r))) return packagePlugins.filter((p) => p.name === "package-rules");
7665
+ return all();
7666
+ }
7667
+ async function runChecks(ctx, checks) {
7668
+ for (const plugin of checks) {
7669
+ try {
7670
+ await plugin.check(ctx);
7671
+ } catch (err) {
7672
+ if (err instanceof DoctorConfigError) throw err;
7673
+ ctx.report({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7674
+ }
7675
+ }
7676
+ }
7143
7677
  function builtinChecks(config, options = {}) {
7144
7678
  const packs = {
7145
7679
  native: { name: "native", check: checkNativePack },
@@ -7165,7 +7699,10 @@ function builtinChecks(config, options = {}) {
7165
7699
  { name: "studio-server-imports", check: checkStudioServerImports },
7166
7700
  { name: "removed-scope-names", check: checkRemovedScopeNames },
7167
7701
  { name: "stability-imports", check: checkStabilityImports },
7168
- { name: "agent-guide", check: checkAgentGuide },
7702
+ { name: "agent-guide", check: (ctx) => {
7703
+ checkAgentGuide(ctx);
7704
+ checkAgentHooks(ctx);
7705
+ } },
7169
7706
  { name: "overlays", check: (ctx) => checkOverlays(ctx) },
7170
7707
  { name: "lock-files", check: checkLockFiles },
7171
7708
  { name: "database-elsewhere", check: checkDatabaseHome },
@@ -7230,17 +7767,21 @@ function formatReport(result, options = {}) {
7230
7767
  `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"}`
7231
7768
  ];
7232
7769
  for (const f of result.findings) {
7233
- lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
7770
+ lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${(f.rules ?? [f.rule]).join(", ")}] ${f.message}`);
7234
7771
  }
7235
7772
  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)`);
7236
7773
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
7774
+ if (result.extensionsAdded?.length) {
7775
+ lines.push(`Extensions added on this branch (${result.extensionsAdded.length}); the pull request's review accepts each:`);
7776
+ for (const e of result.extensionsAdded) lines.push(` ${e.file} [${e.rule}] builds on ${e.buildsOn}: ${e.reason}${e.upstream ? ` (upstream: ${e.upstream})` : ""}`);
7777
+ }
7237
7778
  const info = result.infos ? `, ${result.infos} info` : "";
7238
7779
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
7239
7780
  return lines.join("\n");
7240
7781
  }
7241
7782
 
7242
7783
  // src/vite.ts
7243
- var formatProblems = (result, withWarnings = false) => result.findings.filter((f) => f.level === "error" || withWarnings && f.level === "warn").map((f) => `${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`).join("\n");
7784
+ var formatProblems = (result, withWarnings = false) => result.findings.filter((f) => f.level === "error" || withWarnings && f.level === "warn").map((f) => `${f.file}${f.line ? `:${f.line}` : ""} [${(f.rules ?? [f.rule]).join(", ")}] ${f.message}`).join("\n");
7244
7785
  function genesisDoctor(options = {}) {
7245
7786
  let root = options.root ?? process.cwd();
7246
7787
  return [