@marktiderman/genesis-cli 1.24.0 → 1.26.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/doctor.js CHANGED
@@ -257,7 +257,7 @@ var init_comments = __esm({
257
257
  "src/introspect/comments.ts"() {
258
258
  MARKER = "@genesis";
259
259
  TABLE_KEYS = { label: "string", labelField: "string", description: "string", noun: "string", nounPlural: "string", key: "key" };
260
- FIELD_KEYS = { label: "string", description: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
260
+ FIELD_KEYS = { label: "string", description: "string", control: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
261
261
  CommentSettingsError = class extends Error {
262
262
  };
263
263
  }
@@ -616,7 +616,8 @@ function field(column, indent) {
616
616
  const description = column.settings?.description ?? column.description;
617
617
  if (label) parts.push(`label: ${quote(label)}`);
618
618
  if (description) parts.push(`description: ${quote(description)}`);
619
- if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
619
+ if (column.settings?.control) parts.push(`control: ${quote(column.settings.control)}`);
620
+ else if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
620
621
  if (column.settings?.readonly) parts.push("readOnly: true");
621
622
  if (column.settings?.sensitive) parts.push("sensitive: true");
622
623
  return `${indent}{ ${parts.join(", ")} },`;
@@ -846,6 +847,7 @@ var KNOWN = /* @__PURE__ */ new Set([
846
847
  "forbiddenImports",
847
848
  "rules",
848
849
  "allow",
850
+ "extend",
849
851
  "patterns",
850
852
  "plugins",
851
853
  "packs",
@@ -860,7 +862,10 @@ var KNOWN = /* @__PURE__ */ new Set([
860
862
  "$comment"
861
863
  ]);
862
864
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
863
- var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
865
+ var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped", "extension-invalid"]);
866
+ var CONFIG_RULES = /* @__PURE__ */ new Set(["stale-exception", "stale-extension", "package-rule-override"]);
867
+ var EXTENSION_KEYS = /* @__PURE__ */ new Set(["rule", "file", "buildsOn", "reason", "upstream"]);
868
+ var EXTENSION_REASON_MIN = { chars: 40, words: 6 };
864
869
  var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
865
870
  var PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
866
871
  var CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
@@ -1071,6 +1076,30 @@ function validateConfig(raw, source = "config") {
1071
1076
  }
1072
1077
  });
1073
1078
  }
1079
+ if (c.extend !== void 0) {
1080
+ if (!Array.isArray(c.extend)) fail(`"extend" must be a list of { rule, file, buildsOn, reason, upstream? }`);
1081
+ const seen = /* @__PURE__ */ new Set();
1082
+ c.extend.forEach((e, i) => {
1083
+ const where2 = `extend[${i}]`;
1084
+ if (!isObject(e)) return fail(`${where2} must be an object`);
1085
+ for (const k of Object.keys(e)) if (!EXTENSION_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: ${[...EXTENSION_KEYS].join(", ")})`);
1086
+ for (const k of ["rule", "file", "buildsOn", "reason"]) if (typeof e[k] !== "string" || !e[k].trim()) fail(`${where2} needs "${k}"`);
1087
+ const { rule, file, buildsOn, reason } = e;
1088
+ 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`);
1089
+ 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)`);
1090
+ if (/[*?[\]{}]/.test(file)) fail(`${where2}.file must be one file, not a glob: each extension is reviewed on its own`);
1091
+ e.file = appPath(file, `${where2}.file`, fail);
1092
+ 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")`);
1093
+ const text = reason.trim();
1094
+ if (text.length < EXTENSION_REASON_MIN.chars || text.split(/\s+/).length < EXTENSION_REASON_MIN.words) {
1095
+ 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`);
1096
+ }
1097
+ 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`);
1098
+ const key2 = `${rule}\0${e.file}`;
1099
+ if (seen.has(key2)) fail(`${where2} extends ${rule} in ${e.file} twice`);
1100
+ seen.add(key2);
1101
+ });
1102
+ }
1074
1103
  if (c.patterns !== void 0) {
1075
1104
  if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
1076
1105
  c.patterns.forEach((p, i) => {
@@ -1764,6 +1793,9 @@ function scanFiles(root, config) {
1764
1793
  for (const pkg of local) walk3(pkg.dir);
1765
1794
  return files;
1766
1795
  }
1796
+ function withText(file, text) {
1797
+ return { ...file, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(file.ext)) };
1798
+ }
1767
1799
  function lineAt(text, index) {
1768
1800
  let line = 1;
1769
1801
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
@@ -2298,7 +2330,9 @@ function loadGenesis(root, config) {
2298
2330
  const { dir: uiDir, exports: exportNames, values, components } = pkg;
2299
2331
  const tokens = /* @__PURE__ */ new Set();
2300
2332
  const themeFiles = resolveThemeFiles(root, config, uiDir);
2301
- for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
2333
+ const themeCss = themeFiles.map((file) => readFileSync(file, "utf8"));
2334
+ for (const css of themeCss) for (const t of declaredTokens(css)) tokens.add(t);
2335
+ const colorTokens = colorRoles(themeCss);
2302
2336
  const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
2303
2337
  const rawTags = /* @__PURE__ */ new Map();
2304
2338
  for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
@@ -2314,6 +2348,8 @@ function loadGenesis(root, config) {
2314
2348
  values,
2315
2349
  components,
2316
2350
  tokens,
2351
+ colorTokens,
2352
+ ...themeParts(root) ? { themeParts: themeParts(root) } : {},
2317
2353
  rawTags,
2318
2354
  palette: loadPalette(root),
2319
2355
  companions: loadCompanions(root, config, uiPackage)
@@ -2413,6 +2449,49 @@ function parseExportNames(dts) {
2413
2449
  }
2414
2450
  return names;
2415
2451
  }
2452
+ var COLOUR_VALUE = /^(?:-?[\d.]+(?:deg)?\s+[\d.]+%\s+[\d.]+%(?:\s*\/\s*[\d.]+%?)?|#[0-9a-f]{3,8}|(?:hsla?|rgba?|oklch|oklab|lab|lch|color)\(.*\))$/i;
2453
+ function colorRoles(sheets) {
2454
+ const declared = /* @__PURE__ */ new Map();
2455
+ for (const css of sheets) {
2456
+ for (const m of css.matchAll(/(--[A-Za-z0-9_-]+)\s*:\s*([^;{}]+);/g)) {
2457
+ const list = declared.get(m[1]) ?? [];
2458
+ list.push(m[2].trim());
2459
+ declared.set(m[1], list);
2460
+ }
2461
+ }
2462
+ const roles = /* @__PURE__ */ new Set();
2463
+ for (const [name, values] of declared) if (values.some((v) => COLOUR_VALUE.test(v))) roles.add(name);
2464
+ for (let pass = 0; pass < 4; pass++) {
2465
+ for (const [name, values] of declared) {
2466
+ if (roles.has(name)) continue;
2467
+ if (values.some((v) => [...v.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)/g)].some((r) => roles.has(r[1])))) roles.add(name);
2468
+ }
2469
+ }
2470
+ return roles;
2471
+ }
2472
+ var partsCache = /* @__PURE__ */ new Map();
2473
+ function themeParts(root) {
2474
+ const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
2475
+ if (!ds) return null;
2476
+ if (partsCache.has(ds)) return partsCache.get(ds);
2477
+ let found = null;
2478
+ const dist = path21.join(ds, "dist");
2479
+ try {
2480
+ for (const name of existsSync(dist) ? readdirSync(dist) : []) {
2481
+ if (!name.endsWith(".js")) continue;
2482
+ const code = readFileSync(path21.join(dist, name), "utf8");
2483
+ const at = code.indexOf("THEME_PARTS = Object.freeze([");
2484
+ if (at === -1) continue;
2485
+ const body = code.slice(at, code.indexOf("]);", at));
2486
+ found = [...body.matchAll(/\bp\(\s*"([a-z][a-z0-9-]*)"/g)].map((m) => m[1]);
2487
+ break;
2488
+ }
2489
+ } catch {
2490
+ found = null;
2491
+ }
2492
+ partsCache.set(ds, found);
2493
+ return found;
2494
+ }
2416
2495
  function declaredTokens(css) {
2417
2496
  return [...css.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)].map((m) => m[1]);
2418
2497
  }
@@ -2761,6 +2840,10 @@ var BUILTIN_RULES = [
2761
2840
  "ratchet-skipped",
2762
2841
  "allow-grew",
2763
2842
  "rules-weakened",
2843
+ "extension-added",
2844
+ // declared extensions (extensions.ts)
2845
+ "stale-extension",
2846
+ "extension-invalid",
2764
2847
  // agent guide (primitives.ts)
2765
2848
  "agent-guide-stale",
2766
2849
  // supabase pack: contracts (contracts.ts)
@@ -2770,7 +2853,11 @@ var BUILTIN_RULES = [
2770
2853
  // an app whose database files live in another app (database.ts)
2771
2854
  "database-elsewhere",
2772
2855
  // the app's eslint config loads Genesis's lint rules (eslint-config.ts)
2773
- "genesis-eslint-config"
2856
+ "genesis-eslint-config",
2857
+ // custom views and app parts (custom-views.ts)
2858
+ "app-part-colors",
2859
+ "app-part-name",
2860
+ "custom-view-states"
2774
2861
  ];
2775
2862
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
2776
2863
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2793,7 +2880,7 @@ function checkProjectLayout(ctx) {
2793
2880
  rule: "local-primitives",
2794
2881
  file: dir,
2795
2882
  subject: dir,
2796
- message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} (or extend it upstream)`
2883
+ message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} for those, and keep the app's own components in another folder`
2797
2884
  });
2798
2885
  }
2799
2886
  }
@@ -3049,6 +3136,34 @@ function readSource(abs) {
3049
3136
  return null;
3050
3137
  }
3051
3138
  }
3139
+ var lastBlanked = null;
3140
+ function blankStrings(code) {
3141
+ if (lastBlanked?.source === code) return lastBlanked.blanked;
3142
+ const out = code.split("");
3143
+ for (let i = 0; i < code.length; i++) {
3144
+ const ch = code[i];
3145
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
3146
+ let j = i - 1;
3147
+ while (j >= 0 && /[ \t]/.test(code[j])) j--;
3148
+ const before = j >= 0 ? code[j] : "\n";
3149
+ const word = /[\w$]/.test(before) ? /(?:^|[^\w$])(return|case|typeof|in|of|yield|await)$/.test(code.slice(Math.max(0, j - 8), j + 1)) : false;
3150
+ if (/[\w$)\]]/.test(before) && !word) continue;
3151
+ let k = i + 1;
3152
+ for (; k < code.length; k++) {
3153
+ const c = code[k];
3154
+ if (c === "\\") {
3155
+ k++;
3156
+ continue;
3157
+ }
3158
+ if (c === ch) break;
3159
+ if (c === "\n" && ch !== "`") break;
3160
+ }
3161
+ for (let x = i + 1; x < k && x < code.length; x++) if (code[x] !== "\n") out[x] = " ";
3162
+ i = k;
3163
+ }
3164
+ lastBlanked = { source: code, blanked: out.join("") };
3165
+ return lastBlanked.blanked;
3166
+ }
3052
3167
  function tagEnd(code, start) {
3053
3168
  let depth = 0;
3054
3169
  let quote2 = null;
@@ -3070,7 +3185,8 @@ function tagEnd(code, start) {
3070
3185
  }
3071
3186
  return { end: code.length, selfClosing: false };
3072
3187
  }
3073
- function openElementsAt(code, index, track) {
3188
+ function openElementsAt(source, index, track) {
3189
+ const code = blankStrings(source);
3074
3190
  const open = [];
3075
3191
  const re = /<(\/?)([A-Z][\w.]*)(?=[\s>/])/g;
3076
3192
  for (let m = re.exec(code); m && m.index < index; m = re.exec(code)) {
@@ -3922,9 +4038,9 @@ var PackageDeclarationError = class extends Error {
3922
4038
  var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
3923
4039
  var ID = /^[a-z0-9][a-z0-9-]*$/;
3924
4040
  var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
3925
- var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
4041
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly", "extensible"]);
3926
4042
  var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
3927
- var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
4043
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "inside", "pattern"]);
3928
4044
  var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
3929
4045
  var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "catalog", "primitives", "plugin", "$comment"]);
3930
4046
  var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
@@ -4033,6 +4149,9 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4033
4149
  if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
4034
4150
  if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
4035
4151
  for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
4152
+ if (raw.extensible !== void 0 && !(isStringList2(raw.extensible) && raw.extensible.every((n) => /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)))) {
4153
+ fail(`${at}.extensible must be a list of export names, or parts of one ("ResourceView.slots")`);
4154
+ }
4036
4155
  if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
4037
4156
  const forbid = raw.forbid;
4038
4157
  for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
@@ -4045,6 +4164,7 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4045
4164
  const unless = raw.unless;
4046
4165
  for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
4047
4166
  if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
4167
+ 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`);
4048
4168
  if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
4049
4169
  }
4050
4170
  return raw;
@@ -4162,6 +4282,7 @@ function compile(rule, setting, routes) {
4162
4282
  imports: (rule.forbid.imports ?? []).map(specMatcher),
4163
4283
  ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
4164
4284
  unlessRenders: new Set(rule.unless?.renders ?? []),
4285
+ unlessInside: new Set(rule.unless?.inside ?? []),
4165
4286
  ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
4166
4287
  };
4167
4288
  }
@@ -4173,10 +4294,11 @@ function messageFor(rule, found) {
4173
4294
  const docs = rule.docs ? ` See ${rule.docs}` : "";
4174
4295
  return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
4175
4296
  }
4297
+ var CHILDREN = /\{\s*(?:props\.)?children\s*\}/g;
4176
4298
  var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
4177
4299
  var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
4178
4300
  var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
4179
- function wrappersIn(file, elements, c) {
4301
+ function wrappersIn(file, elements, names, accept) {
4180
4302
  const out = /* @__PURE__ */ new Map();
4181
4303
  const decls = [...file.code.matchAll(TOP_LEVEL)];
4182
4304
  const listed = /* @__PURE__ */ new Map();
@@ -4189,12 +4311,12 @@ function wrappersIn(file, elements, c) {
4189
4311
  for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
4190
4312
  decls.forEach((d, i) => {
4191
4313
  const name = d[3];
4192
- if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
4314
+ if (!/^[A-Z]/.test(name) || names.has(name)) return;
4193
4315
  const end = decls[i + 1]?.index ?? file.code.length;
4194
- const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
4195
- if (!hit) return;
4196
- const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4197
- for (const n of names) out.set(n, hit[1]);
4316
+ const hit = elements.find((m) => m.index > d.index && m.index < end && names.has(m[1]));
4317
+ if (!hit || accept && !accept(d.index, end)) return;
4318
+ const exported = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4319
+ for (const n of exported) out.set(n, hit[1]);
4198
4320
  });
4199
4321
  return out;
4200
4322
  }
@@ -4202,6 +4324,32 @@ function runPrefer(ctx, c) {
4202
4324
  const own = c.rule.packageDir;
4203
4325
  const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
4204
4326
  const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
4327
+ const scanned = new Map(ctx.files.map((f) => [f.absolutePath, f]));
4328
+ const importedBy = /* @__PURE__ */ new Map();
4329
+ const importsOf = (file) => {
4330
+ if (!importedBy.has(file)) importedBy.set(file, localImportedNames(ctx.root, file));
4331
+ return importedBy.get(file);
4332
+ };
4333
+ const builders = /* @__PURE__ */ new Map();
4334
+ const buildersIn = (abs) => {
4335
+ if (!builders.has(abs)) {
4336
+ const target = scanned.get(abs) ?? readSource(abs);
4337
+ const code = target ? "ext" in target ? target.code : stripBlockComments(target.code, true) : "";
4338
+ const childrenInside = (start, end) => [...code.slice(start, end).matchAll(CHILDREN)].some((m) => openElementsAt(code, start + m.index, (n) => c.unlessInside.has(n)).length > 0);
4339
+ builders.set(abs, code ? wrappersIn({ code }, [...code.matchAll(ELEMENT)], c.unlessInside, childrenInside) : /* @__PURE__ */ new Map());
4340
+ }
4341
+ return builders.get(abs);
4342
+ };
4343
+ const nestedInBuilder = (file, index) => {
4344
+ if (!c.unlessInside.size) return false;
4345
+ const imported = importsOf(file);
4346
+ const isBuilder = (name) => {
4347
+ if (c.unlessInside.has(name)) return true;
4348
+ const from = name.includes(".") ? void 0 : imported.get(name);
4349
+ return from !== void 0 && buildersIn(from.file).has(from.name);
4350
+ };
4351
+ return openElementsAt(file.code, index, isBuilder).length > 0;
4352
+ };
4205
4353
  const wrappers = /* @__PURE__ */ new Map();
4206
4354
  const renderedBy = /* @__PURE__ */ new Map();
4207
4355
  for (const file of checked) {
@@ -4209,16 +4357,17 @@ function runPrefer(ctx, c) {
4209
4357
  const elements = [...file.code.matchAll(ELEMENT)];
4210
4358
  renderedBy.set(file, elements);
4211
4359
  if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
4212
- const found = wrappersIn(file, elements, c);
4360
+ const found = wrappersIn(file, elements, c.jsx);
4213
4361
  if (found.size) wrappers.set(file.absolutePath, found);
4214
4362
  }
4215
4363
  for (const file of checked) {
4216
4364
  const elements = renderedBy.get(file) ?? [];
4217
4365
  if (exempt(file, elements.map((m) => m[1]))) continue;
4218
4366
  const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
4219
- const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
4367
+ const imported = wrappers.size && elements.length ? importsOf(file) : null;
4220
4368
  for (const m of elements) {
4221
4369
  const name = m[1];
4370
+ if (nestedInBuilder(file, m.index)) continue;
4222
4371
  if (c.jsx.has(name)) {
4223
4372
  report(lineAt(file.code, m.index), name, `renders <${name}>`);
4224
4373
  continue;
@@ -4235,6 +4384,7 @@ function runPrefer(ctx, c) {
4235
4384
  if (c.pattern) {
4236
4385
  c.pattern.lastIndex = 0;
4237
4386
  for (const m of file.code.matchAll(c.pattern)) {
4387
+ if (nestedInBuilder(file, m.index)) continue;
4238
4388
  const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
4239
4389
  report(lineAt(file.code, m.index), text, `has ${text}`);
4240
4390
  }
@@ -5919,6 +6069,73 @@ function checkRemovedScopeNames(ctx) {
5919
6069
  }
5920
6070
  }
5921
6071
  }
6072
+
6073
+ // src/doctor/custom-views.ts
6074
+ var JSX_EXTS4 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
6075
+ var CUSTOM_VIEW = /<CustomView\b|\buseCustomView\s*[<(]/;
6076
+ var APP_PART = /data-slot\s*=\s*\{?\s*["'`]app-/;
6077
+ var COLOUR_KEY = /\b(color|background(?:Color)?|border(?:Top|Right|Bottom|Left|Block|Inline)?(?:Color)?|outline(?:Color)?|textDecorationColor|caretColor|accentColor|fill|stroke|columnRuleColor|boxShadow)\s*:\s*(["'`])([^"'`]*)\2/g;
6078
+ var COLOUR_UTILITY = /(?<![\w-])(?:bg|text|border(?:-[xytrbls])?|ring|ring-offset|fill|stroke|from|to|via|outline|divide|decoration|shadow|accent|caret|placeholder)-\[([^\]]*var\(--[^\]]*)\]/g;
6079
+ var VARIABLE = /var\(\s*(--[A-Za-z0-9_-]+)/g;
6080
+ function checkAppParts(ctx) {
6081
+ const roles = ctx.genesis.colorTokens;
6082
+ const genesisParts = new Set(ctx.genesis.themeParts ?? []);
6083
+ const overlays = markedOverlays(ctx);
6084
+ for (const file of ctx.files) {
6085
+ if (!JSX_EXTS4.has(file.ext) && file.ext !== ".ts" && file.ext !== ".js") continue;
6086
+ if (insideOverlayOf(overlays, file, ctx.genesis.uiPackage)) continue;
6087
+ const code = file.code;
6088
+ if (JSX_EXTS4.has(file.ext)) {
6089
+ for (const m of code.matchAll(/\bdata-slot\s*=\s*(?:\{\s*)?["'`]([^"'`$]+)["'`]/g)) {
6090
+ const name = m[1];
6091
+ if (name.startsWith("app-")) continue;
6092
+ const clash = genesisParts.has(name);
6093
+ ctx.report({
6094
+ rule: "app-part-name",
6095
+ level: "warn",
6096
+ file: file.path,
6097
+ line: lineAt(code, m.index ?? 0),
6098
+ subject: name,
6099
+ message: clash ? `marks an app element data-slot="${name}", which is a Genesis part (THEME_PARTS): every app style's rules for it would hit this element too. Name the app's own part "app-${name}"` : `marks an app element data-slot="${name}"; name the app's own part "app-${name}", so it never collides with a Genesis part (docs/adr/0018-app-brands-styles-themes.md)`
6100
+ });
6101
+ }
6102
+ }
6103
+ if (roles && roles.size && (CUSTOM_VIEW.test(code) || APP_PART.test(code))) {
6104
+ const seen = /* @__PURE__ */ new Set();
6105
+ const check = (value, at) => {
6106
+ for (const v of value.matchAll(VARIABLE)) {
6107
+ const name = v[1];
6108
+ if (roles.has(name)) continue;
6109
+ const line = lineAt(code, at);
6110
+ if (seen.has(`${line}:${name}`)) continue;
6111
+ seen.add(`${line}:${name}`);
6112
+ ctx.report({
6113
+ rule: "app-part-colors",
6114
+ level: "warn",
6115
+ file: file.path,
6116
+ line,
6117
+ subject: name,
6118
+ message: `colours a custom view or app part with ${name}, which isn't a colour role; take colours from roles only (hsl(var(--primary)), bg-primary, text-muted-foreground) so the app brand and dark mode reach it`
6119
+ });
6120
+ }
6121
+ };
6122
+ for (const m of code.matchAll(COLOUR_KEY)) check(m[3], m.index ?? 0);
6123
+ for (const m of code.matchAll(COLOUR_UTILITY)) check(m[1], m.index ?? 0);
6124
+ }
6125
+ if (JSX_EXTS4.has(file.ext) && CUSTOM_VIEW.test(code)) {
6126
+ for (const m of code.matchAll(/\bstatus\s*[!=]={1,2}\s*["'`](loading|empty|error)["'`]/g)) {
6127
+ ctx.report({
6128
+ rule: "custom-view-states",
6129
+ level: "warn",
6130
+ file: file.path,
6131
+ line: lineAt(code, m.index ?? 0),
6132
+ subject: m[1],
6133
+ message: `draws a custom view's own ${m[1]} state; <CustomView> draws loading, empty and error in the app's style (pass its loading, empty or error prop to replace one) (docs/adr/0019-custom-views.md)`
6134
+ });
6135
+ }
6136
+ }
6137
+ }
6138
+ }
5922
6139
  var SCRIPT_EXTS6 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
5923
6140
  var DECLARATION = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*\n(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:function|const|let|class|interface|type|enum|namespace)\s+([A-Za-z_$][\w$]*)/g;
5924
6141
  var REEXPORT = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*\nexport\s+(?:type\s+)?\{([^}]*)\}/g;
@@ -6030,13 +6247,34 @@ function git3(root, args) {
6030
6247
  return r.status === 0 ? r.stdout : null;
6031
6248
  }
6032
6249
  function changedSince(root, base) {
6033
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6250
+ const mergeBase = mergeBaseOf2(root, base);
6034
6251
  if (!mergeBase) return null;
6035
6252
  const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
6036
6253
  const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
6037
6254
  if (committed === null || untracked === null) return null;
6038
6255
  return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
6039
6256
  }
6257
+ function originsSince(root, base) {
6258
+ const out = /* @__PURE__ */ new Map();
6259
+ const mergeBase = mergeBaseOf2(root, base);
6260
+ if (!mergeBase) return out;
6261
+ const diff = git3(root, ["diff", "-z", "-M", "--name-status", "--relative", mergeBase, "--"]);
6262
+ if (diff === null) return out;
6263
+ const parts = diff.split("\0");
6264
+ for (let i = 0; i < parts.length; ) {
6265
+ const status = parts[i++] ?? "";
6266
+ if (!status) continue;
6267
+ if (status.startsWith("R") || status.startsWith("C")) {
6268
+ const from = parts[i++];
6269
+ const to = parts[i++];
6270
+ if (status.startsWith("R")) out.set(to, from);
6271
+ } else i++;
6272
+ }
6273
+ return out;
6274
+ }
6275
+ function mergeBaseOf2(root, base) {
6276
+ return git3(root, ["merge-base", base, "HEAD"])?.trim() || null;
6277
+ }
6040
6278
  var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
6041
6279
  function showAt(dir, rev, file) {
6042
6280
  const at = `${rev}:./${file}`;
@@ -6044,7 +6282,7 @@ function showAt(dir, rev, file) {
6044
6282
  return git3(dir, ["show", at]);
6045
6283
  }
6046
6284
  function configAtBase(root, base, explicitFile) {
6047
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6285
+ const mergeBase = mergeBaseOf2(root, base);
6048
6286
  if (!mergeBase) return null;
6049
6287
  const candidates = explicitFile ? [{ dir: path21.dirname(explicitFile), file: path21.basename(explicitFile), explicit: true }] : [
6050
6288
  { dir: root, file: "genesis.config.json", explicit: false },
@@ -6065,7 +6303,12 @@ function configAtBase(root, base, explicitFile) {
6065
6303
  continue;
6066
6304
  }
6067
6305
  const b = objectOr(block);
6068
- return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
6306
+ return {
6307
+ allow: Array.isArray(b.allow) ? b.allow : [],
6308
+ extend: Array.isArray(b.extend) ? b.extend : [],
6309
+ rules: objectOr(b.rules),
6310
+ packageRules: objectOr(b.packageRules)
6311
+ };
6069
6312
  }
6070
6313
  return "absent";
6071
6314
  }
@@ -6079,6 +6322,16 @@ function allowGrew(allow, before, base) {
6079
6322
  message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
6080
6323
  }));
6081
6324
  }
6325
+ function extensionsAdded(extend, before, base) {
6326
+ const had = new Set(before.map((e) => `${e.rule}\0${e.file}\0${e.buildsOn}`));
6327
+ return extend.filter((e) => !had.has(`${e.rule}\0${e.file}\0${e.buildsOn}`)).map((e) => ({
6328
+ rule: "extension-added",
6329
+ level: "info",
6330
+ file: e.file,
6331
+ subject: e.rule,
6332
+ 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`
6333
+ }));
6334
+ }
6082
6335
  var RANK = { off: 0, info: 1, warn: 2, error: 3 };
6083
6336
  function rulesWeakened(config, before, base) {
6084
6337
  const out = [];
@@ -6116,14 +6369,169 @@ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
6116
6369
  "plugin-error",
6117
6370
  "build",
6118
6371
  "agent-guide-stale",
6119
- "contracts-stale"
6372
+ "contracts-stale",
6373
+ "stale-extension",
6374
+ "extension-added"
6120
6375
  ]);
6376
+ function isRatcheted(rule, config, newOnly) {
6377
+ return !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6378
+ }
6379
+ var countKey = (file, rule) => `${file}\0${rule}`;
6380
+ function countFindings(findings) {
6381
+ const counts = /* @__PURE__ */ new Map();
6382
+ for (const f of findings) counts.set(countKey(f.file, f.rule), (counts.get(countKey(f.file, f.rule)) ?? 0) + 1);
6383
+ return counts;
6384
+ }
6121
6385
  function applyRatchet(findings, options) {
6122
- const { config, newOnly, changed, base, isAppPath } = options;
6123
- const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6386
+ const { config, newOnly, changed, base, isAppPath, baseCounts, existedAtBase } = options;
6387
+ const originOf = options.originOf ?? ((f) => f);
6388
+ const counts = countFindings(findings.map((f) => ({ file: originOf(f.file), rule: f.rule })));
6124
6389
  return findings.map((f) => {
6125
- if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
6126
- return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6390
+ if (f.level === "info" || !isRatcheted(f.rule, config, newOnly) || !isAppPath(f.file)) return f;
6391
+ if (!touched(f.file, changed)) return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6392
+ const origin = originOf(f.file);
6393
+ if (!baseCounts || !existedAtBase?.(origin)) return f;
6394
+ const now = counts.get(countKey(origin, f.rule)) ?? 0;
6395
+ const was = baseCounts.get(countKey(origin, f.rule)) ?? 0;
6396
+ const where2 = origin === f.file ? "this file" : `the files from ${origin}`;
6397
+ 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)` };
6398
+ return { ...f, level: "info", message: `${f.message} (ratcheted: ${now} in ${where2}, ${was} at the merge base with ${base})` };
6399
+ });
6400
+ }
6401
+ function snapshotAtBase(root, base, files, changed, originOf = (f) => f) {
6402
+ const mergeBase = mergeBaseOf2(root, base);
6403
+ if (!mergeBase) return null;
6404
+ const out = [];
6405
+ const seen = /* @__PURE__ */ new Set();
6406
+ for (const f of files) {
6407
+ if (!changed.has(f.path)) {
6408
+ if (!seen.has(f.path)) out.push(f);
6409
+ seen.add(f.path);
6410
+ continue;
6411
+ }
6412
+ const origin = originOf(f.path);
6413
+ if (seen.has(origin)) continue;
6414
+ seen.add(origin);
6415
+ const text = showAt(root, mergeBase, origin);
6416
+ if (text === null) return null;
6417
+ if (text !== void 0) out.push(withText({ ...f, path: origin, absolutePath: path21.join(root, origin) }, text));
6418
+ }
6419
+ const cache2 = /* @__PURE__ */ new Map();
6420
+ return {
6421
+ mergeBase,
6422
+ files: out,
6423
+ existed(file) {
6424
+ if (!cache2.has(file)) cache2.set(file, git3(root, ["cat-file", "-e", `${mergeBase}:./${file}`]) !== null);
6425
+ return cache2.get(file);
6426
+ }
6427
+ };
6428
+ }
6429
+
6430
+ // src/doctor/extensions.ts
6431
+ function pointProblem(entry, packages) {
6432
+ const rule = preferRules(packages).find((r) => r.ruleId === entry.rule);
6433
+ if (!rule?.extensible?.length) return `${entry.rule} declares no extension points, so it can't be extended (debt goes in allow, and is fixed)`;
6434
+ if (!rule.extensible.includes(entry.buildsOn)) return `${entry.buildsOn} isn't one of ${entry.rule}'s extension points (${rule.extensible.join(", ")})`;
6435
+ return null;
6436
+ }
6437
+ function extensionProblem(entry, ctx) {
6438
+ const point = pointProblem(entry, ctx.packages);
6439
+ if (point) return point;
6440
+ const name = entry.buildsOn.split(".")[0];
6441
+ const replaces = preferRules(ctx.packages).find((r) => r.forbid.jsx?.includes(name));
6442
+ if (replaces) return `${name} is what ${replaces.ruleId} replaces (use ${replaces.use}); a legacy component can't be built on`;
6443
+ const flagged = ctx.raw.find((f) => f.file === entry.file && f.subject === name);
6444
+ if (flagged) return `${name} is flagged in this file by ${flagged.rule}; build on a current Genesis primitive`;
6445
+ const file = ctx.files.find((f) => f.path === entry.file);
6446
+ if (!file) return `${entry.file} isn't one of the files the doctor scans`;
6447
+ const imported = genesisNamedImports(file.code).some((i) => i.names.includes(name));
6448
+ if (!imported) return `${entry.file} doesn't import ${name} from a Genesis package; buildsOn names the extension point the file uses`;
6449
+ if (!usesPoint(blankStrings(file.code), entry.buildsOn)) {
6450
+ const prop = entry.buildsOn.split(".")[1];
6451
+ 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`;
6452
+ }
6453
+ return null;
6454
+ }
6455
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6456
+ function usesPoint(code, point) {
6457
+ const [name, prop] = point.split(".");
6458
+ const n = escape2(name);
6459
+ if (!prop) return new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])|(?<![\\w$.])${n}\\s*(?:<[^>()]*>)?\\s*\\(`).test(code);
6460
+ for (const m of code.matchAll(new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])`, "g"))) {
6461
+ const { end } = tagEnd(code, m.index);
6462
+ if (new RegExp(`(?<![\\w$.])${escape2(prop)}\\s*=`).test(code.slice(m.index, end))) return true;
6463
+ }
6464
+ return false;
6465
+ }
6466
+ function applyExtensions(findings, ctx) {
6467
+ const entries = ctx.config.extend ?? [];
6468
+ if (!entries.length) return findings;
6469
+ const staleLevel = ctx.config.rules?.["stale-extension"];
6470
+ const covered = /* @__PURE__ */ new Set();
6471
+ const grew = /* @__PURE__ */ new Map();
6472
+ const out = [];
6473
+ 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}` });
6474
+ for (const entry of entries) {
6475
+ if (ctx.config.rules?.[entry.rule] === "off" || ctx.config.packageRules?.[entry.rule]?.level === "off") continue;
6476
+ const point = pointProblem(entry, ctx.packages);
6477
+ if (point) {
6478
+ invalid(entry, point);
6479
+ continue;
6480
+ }
6481
+ const hits = findings.filter((f) => f.rule === entry.rule && f.file === entry.file);
6482
+ if (!hits.length) {
6483
+ if (staleLevel === "off") continue;
6484
+ out.push({
6485
+ rule: "stale-extension",
6486
+ level: staleLevel ?? "warn",
6487
+ file: entry.file,
6488
+ line: 0,
6489
+ subject: entry.rule,
6490
+ message: `the extension of ${entry.rule} (building on ${entry.buildsOn}) no longer matches a finding in this file; remove it from doctor.extend`
6491
+ });
6492
+ continue;
6493
+ }
6494
+ const problem = extensionProblem(entry, ctx);
6495
+ if (problem) {
6496
+ invalid(entry, problem);
6497
+ continue;
6498
+ }
6499
+ const limit = ctx.limit?.(entry);
6500
+ if (limit !== void 0 && hits.length > limit) {
6501
+ 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)`);
6502
+ continue;
6503
+ }
6504
+ for (const h of hits) covered.add(h);
6505
+ }
6506
+ const kept = findings.filter((f) => !covered.has(f)).map((f) => grew.has(f) ? { ...f, message: grew.get(f) } : f);
6507
+ return [...kept, ...out].sort(byPlace);
6508
+ }
6509
+ var byPlace = (x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule);
6510
+ var RANK2 = { info: 0, warn: 1, error: 2 };
6511
+ function dedupeFindings(findings) {
6512
+ const groups = /* @__PURE__ */ new Map();
6513
+ const order = [];
6514
+ for (const f of findings) {
6515
+ if (f.subject === void 0 || !f.line) {
6516
+ order.push([f]);
6517
+ continue;
6518
+ }
6519
+ const key2 = `${f.file}\0${f.line}\0${f.subject}`;
6520
+ const list = groups.get(key2) ?? [];
6521
+ const group = list.find((g) => !g.some((x) => x.rule === f.rule));
6522
+ if (group) group.push(f);
6523
+ else {
6524
+ const fresh = [f];
6525
+ list.push(fresh);
6526
+ groups.set(key2, list);
6527
+ order.push(fresh);
6528
+ }
6529
+ }
6530
+ return order.map((group) => {
6531
+ if (group.length === 1) return group[0];
6532
+ const primary = group.reduce((a, b) => RANK2[b.level] > RANK2[a.level] ? b : a);
6533
+ const rules = [primary.rule, ...group.filter((g) => g !== primary).map((g) => g.rule)];
6534
+ return { ...primary, rules, message: `${primary.message} (also ${rules.slice(1).join(", ")})` };
6127
6535
  });
6128
6536
  }
6129
6537
  var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
@@ -6210,7 +6618,7 @@ function pathTaken(file) {
6210
6618
  var CORE = [
6211
6619
  {
6212
6620
  need: "anything, before building it",
6213
- use: 'search what exists: `genesis features find <term>`, this catalog, and the "Available but unused" list in `genesis doctor --verbose`',
6621
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the "Available but unused" list in `genesis doctor --verbose`. Check the install is current first (`genesis upgrade --dry-run`): an old one hides pieces that exist',
6214
6622
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6215
6623
  from: "genesis-cli"
6216
6624
  },
@@ -6235,9 +6643,15 @@ var CORE = [
6235
6643
  rule: "raw-color",
6236
6644
  from: "genesis-cli"
6237
6645
  },
6646
+ {
6647
+ need: "a Genesis piece that is close but doesn't quite fit",
6648
+ use: "extend it: a prop, a variant, a slot, or your own component that wraps it; never a parallel copy beside it",
6649
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6650
+ from: "genesis-cli"
6651
+ },
6238
6652
  {
6239
6653
  need: "something no primitive covers",
6240
- use: "write the gap up for Genesis (an issue or a proposal) first, then invent in the app, on Genesis primitives",
6654
+ use: "invent it in the app, on Genesis tokens and primitives; Genesis asks for no write-up first. You may add it to `docs/genesis-upstream.md` (`genesis upstream`) if you think Genesis should have it",
6241
6655
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6242
6656
  from: "genesis-cli"
6243
6657
  }
@@ -6290,10 +6704,12 @@ var AGENTS_START = "<!-- genesis-primitives:start -->";
6290
6704
  var AGENTS_END = "<!-- genesis-primitives:end -->";
6291
6705
  var RULES = [
6292
6706
  `Use the Genesis primitive for the need first: reuse, then extend, then invent (G1 to G6 in ${GENESIS_DOCS}/FRAMEWORK.md).`,
6707
+ "Before deciding Genesis lacks a piece, look at all of it (the catalog below, `genesis features find <term>`) and check the installed packages are current (`genesis upgrade --dry-run`). An old install hides pieces that exist; upgrade before building around a gap that is already closed.",
6293
6708
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
6294
6709
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
6295
6710
  "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.",
6296
- "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
6711
+ "When a Genesis piece is close and does the same job, extend it: a prop, a variant, a slot, or your own component that wraps it. Never build a parallel copy beside it.",
6712
+ "When no Genesis piece does the job, invent it in the app: your own screens and components, on Genesis tokens and primitives. Genesis asks for no write-up or approval first (your app's own design review still applies); you may add it to `docs/genesis-upstream.md` if you think Genesis should have it.",
6297
6713
  "Run `genesis doctor` before you finish; it enforces these rules."
6298
6714
  ];
6299
6715
  function skillDescription(text) {
@@ -7421,14 +7837,8 @@ async function runDoctor(options = {}) {
7421
7837
  }
7422
7838
  const raw = [];
7423
7839
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
7424
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
7425
- try {
7426
- await plugin.check(ctx);
7427
- } catch (err) {
7428
- if (err instanceof DoctorConfigError) throw err;
7429
- raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7430
- }
7431
- }
7840
+ const appChecks = [...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins];
7841
+ await runChecks(ctx, [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...appChecks]);
7432
7842
  if (options.build) {
7433
7843
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
7434
7844
  if (failure) raw.push(failure);
@@ -7438,30 +7848,57 @@ async function runDoctor(options = {}) {
7438
7848
  let changed = null;
7439
7849
  let skipped = false;
7440
7850
  const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
7441
- if (options.base && (ratchetNeeded || config.ratchet)) {
7851
+ if (options.base && (ratchetNeeded || config.ratchet || config.extend?.length)) {
7442
7852
  changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
7443
7853
  skipped ||= !changed;
7444
7854
  }
7445
7855
  const configFile = "file" in loaded ? loaded.file : null;
7446
- const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7856
+ const guarded = (config.allow?.length ?? 0) + (config.extend?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7447
7857
  let configSkipped = false;
7858
+ let baseExtend = [];
7448
7859
  if (options.base && configFile) {
7449
7860
  const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
7861
+ if (before && before !== "absent") baseExtend = before.extend;
7862
+ if (before === "absent") raw.push(...extensionsAdded(config.extend ?? [], [], options.base));
7450
7863
  if (before && before !== "absent") {
7451
7864
  raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
7452
7865
  raw.push(...rulesWeakened(config, before, options.base));
7866
+ raw.push(...extensionsAdded(config.extend ?? [], before.extend, options.base));
7453
7867
  }
7454
7868
  configSkipped = !before && guarded;
7455
7869
  }
7456
7870
  if (skipped || configSkipped) {
7457
7871
  raw.push(
7458
- 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` }
7872
+ 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` }
7459
7873
  );
7460
7874
  }
7461
- let findings = applyConfig(raw, config, packageRuleIds(packages));
7875
+ const packageIds = packageRuleIds(packages);
7876
+ const extensionCtx = { config, files, packages, raw };
7877
+ const configured = applyConfig(raw, config, packageIds);
7878
+ let findings = applyExtensions(configured, extensionCtx);
7462
7879
  if (options.base && changed) {
7463
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path21.join(root, f)) });
7880
+ const isAppPath = (f) => existsSync(path21.join(root, f));
7881
+ const origins = options.changedFiles ? /* @__PURE__ */ new Map() : originsSince(root, options.base);
7882
+ const originOf = (f) => origins.get(f) ?? f;
7883
+ 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));
7884
+ 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))));
7885
+ for (const e of heldExtensions) dueRules.add(e.rule);
7886
+ const snapshot = dueRules.size ? snapshotAtBase(root, options.base, files, changed, originOf) : null;
7887
+ let baseCounts;
7888
+ if (snapshot) {
7889
+ const before = [];
7890
+ await runChecks({ ...ctx, files: snapshot.files, report: (f) => before.push(f) }, baseChecks(dueRules, packageIds, packagePlugins, () => [...builtinChecks(config, { contracts: false, figma: false }), ...appChecks]));
7891
+ baseCounts = countFindings(applyConfig(before, config, packageIds));
7892
+ if (heldExtensions.length) {
7893
+ const counts = baseCounts;
7894
+ const held = new Set(heldExtensions);
7895
+ findings = applyExtensions(configured, { ...extensionCtx, limit: (e) => held.has(e) ? counts.get(countKey(originOf(e.file), e.rule)) ?? 0 : void 0 });
7896
+ }
7897
+ }
7898
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath, originOf, ...snapshot && baseCounts ? { baseCounts, existedAtBase: snapshot.existed } : {} });
7464
7899
  }
7900
+ findings = dedupeFindings(findings);
7901
+ const extensionsNew = (config.extend ?? []).filter((e) => findings.some((f) => f.rule === "extension-added" && f.file === e.file && f.subject === e.rule));
7465
7902
  const errors = findings.filter((f) => f.level === "error").length;
7466
7903
  const warnings = findings.filter((f) => f.level === "warn").length;
7467
7904
  const infos = findings.length - errors - warnings;
@@ -7475,9 +7912,24 @@ async function runDoctor(options = {}) {
7475
7912
  primitives: primitivesSummary(packages),
7476
7913
  errors,
7477
7914
  warnings,
7478
- infos
7915
+ infos,
7916
+ ...extensionsNew.length ? { extensionsAdded: extensionsNew } : {}
7479
7917
  };
7480
7918
  }
7919
+ function baseChecks(rules, preferIds, packagePlugins, all) {
7920
+ if ([...rules].every((r) => preferIds.has(r))) return packagePlugins.filter((p) => p.name === "package-rules");
7921
+ return all();
7922
+ }
7923
+ async function runChecks(ctx, checks) {
7924
+ for (const plugin of checks) {
7925
+ try {
7926
+ await plugin.check(ctx);
7927
+ } catch (err) {
7928
+ if (err instanceof DoctorConfigError) throw err;
7929
+ ctx.report({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7930
+ }
7931
+ }
7932
+ }
7481
7933
  function builtinChecks(config, options = {}) {
7482
7934
  const packs = {
7483
7935
  native: { name: "native", check: checkNativePack },
@@ -7502,6 +7954,7 @@ function builtinChecks(config, options = {}) {
7502
7954
  { name: "resource-view-trees", check: checkTreeViews },
7503
7955
  { name: "studio-server-imports", check: checkStudioServerImports },
7504
7956
  { name: "removed-scope-names", check: checkRemovedScopeNames },
7957
+ { name: "app-parts", check: checkAppParts },
7505
7958
  { name: "stability-imports", check: checkStabilityImports },
7506
7959
  { name: "agent-guide", check: (ctx) => {
7507
7960
  checkAgentGuide(ctx);
@@ -7571,10 +8024,14 @@ function formatReport(result, options = {}) {
7571
8024
  `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"}`
7572
8025
  ];
7573
8026
  for (const f of result.findings) {
7574
- lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
8027
+ lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${(f.rules ?? [f.rule]).join(", ")}] ${f.message}`);
7575
8028
  }
7576
8029
  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)`);
7577
8030
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
8031
+ if (result.extensionsAdded?.length) {
8032
+ lines.push(`Extensions added on this branch (${result.extensionsAdded.length}); the pull request's review accepts each:`);
8033
+ for (const e of result.extensionsAdded) lines.push(` ${e.file} [${e.rule}] builds on ${e.buildsOn}: ${e.reason}${e.upstream ? ` (upstream: ${e.upstream})` : ""}`);
8034
+ }
7578
8035
  const info = result.infos ? `, ${result.infos} info` : "";
7579
8036
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
7580
8037
  return lines.join("\n");
@@ -7588,7 +8045,8 @@ function toJson(result) {
7588
8045
  infos: result.infos,
7589
8046
  findings: result.findings,
7590
8047
  unused: result.unused,
7591
- primitives: result.primitives
8048
+ primitives: result.primitives,
8049
+ ...result.extensionsAdded ? { extensionsAdded: result.extensionsAdded } : {}
7592
8050
  };
7593
8051
  }
7594
8052
  function genesisSummary(g) {
@@ -7602,6 +8060,6 @@ function genesisSummary(g) {
7602
8060
  };
7603
8061
  }
7604
8062
 
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 };
8063
+ export { BLOCKED_FIX, BUILTIN_RULES, CLAUDE_IMPORT, DENY_RULES, DoctorConfigError, GenesisConfigError, PackageDeclarationError, SETTINGS_PATH, SKILL_PATH, SUBAGENT_HOOK_COMMAND, agentGuideState, agentHooksState, agentRules, applyExtensions, builtinChecks, catalogTable, changedSince, clearPackageRulesCache, dedupeFindings, defineDoctorPlugin, discoverPackages, extensionProblem, 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 };
7606
8064
  //# sourceMappingURL=doctor.js.map
7607
8065
  //# sourceMappingURL=doctor.js.map