@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/vite.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
  }
@@ -2758,6 +2837,10 @@ var BUILTIN_RULES = [
2758
2837
  "ratchet-skipped",
2759
2838
  "allow-grew",
2760
2839
  "rules-weakened",
2840
+ "extension-added",
2841
+ // declared extensions (extensions.ts)
2842
+ "stale-extension",
2843
+ "extension-invalid",
2761
2844
  // agent guide (primitives.ts)
2762
2845
  "agent-guide-stale",
2763
2846
  // supabase pack: contracts (contracts.ts)
@@ -2767,7 +2850,11 @@ var BUILTIN_RULES = [
2767
2850
  // an app whose database files live in another app (database.ts)
2768
2851
  "database-elsewhere",
2769
2852
  // the app's eslint config loads Genesis's lint rules (eslint-config.ts)
2770
- "genesis-eslint-config"
2853
+ "genesis-eslint-config",
2854
+ // custom views and app parts (custom-views.ts)
2855
+ "app-part-colors",
2856
+ "app-part-name",
2857
+ "custom-view-states"
2771
2858
  ];
2772
2859
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
2773
2860
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2790,7 +2877,7 @@ function checkProjectLayout(ctx) {
2790
2877
  rule: "local-primitives",
2791
2878
  file: dir,
2792
2879
  subject: dir,
2793
- message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} (or extend it upstream)`
2880
+ message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} for those, and keep the app's own components in another folder`
2794
2881
  });
2795
2882
  }
2796
2883
  }
@@ -3046,6 +3133,34 @@ function readSource(abs) {
3046
3133
  return null;
3047
3134
  }
3048
3135
  }
3136
+ var lastBlanked = null;
3137
+ function blankStrings(code) {
3138
+ if (lastBlanked?.source === code) return lastBlanked.blanked;
3139
+ const out = code.split("");
3140
+ for (let i = 0; i < code.length; i++) {
3141
+ const ch = code[i];
3142
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
3143
+ let j = i - 1;
3144
+ while (j >= 0 && /[ \t]/.test(code[j])) j--;
3145
+ const before = j >= 0 ? code[j] : "\n";
3146
+ const word = /[\w$]/.test(before) ? /(?:^|[^\w$])(return|case|typeof|in|of|yield|await)$/.test(code.slice(Math.max(0, j - 8), j + 1)) : false;
3147
+ if (/[\w$)\]]/.test(before) && !word) continue;
3148
+ let k = i + 1;
3149
+ for (; k < code.length; k++) {
3150
+ const c = code[k];
3151
+ if (c === "\\") {
3152
+ k++;
3153
+ continue;
3154
+ }
3155
+ if (c === ch) break;
3156
+ if (c === "\n" && ch !== "`") break;
3157
+ }
3158
+ for (let x = i + 1; x < k && x < code.length; x++) if (code[x] !== "\n") out[x] = " ";
3159
+ i = k;
3160
+ }
3161
+ lastBlanked = { source: code, blanked: out.join("") };
3162
+ return lastBlanked.blanked;
3163
+ }
3049
3164
  function tagEnd(code, start) {
3050
3165
  let depth = 0;
3051
3166
  let quote2 = null;
@@ -3067,7 +3182,8 @@ function tagEnd(code, start) {
3067
3182
  }
3068
3183
  return { end: code.length, selfClosing: false };
3069
3184
  }
3070
- function openElementsAt(code, index, track) {
3185
+ function openElementsAt(source, index, track) {
3186
+ const code = blankStrings(source);
3071
3187
  const open = [];
3072
3188
  const re = /<(\/?)([A-Z][\w.]*)(?=[\s>/])/g;
3073
3189
  for (let m = re.exec(code); m && m.index < index; m = re.exec(code)) {
@@ -3919,9 +4035,9 @@ var PackageDeclarationError = class extends Error {
3919
4035
  var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
3920
4036
  var ID = /^[a-z0-9][a-z0-9-]*$/;
3921
4037
  var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
3922
- var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
4038
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly", "extensible"]);
3923
4039
  var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
3924
- var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
4040
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "inside", "pattern"]);
3925
4041
  var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
3926
4042
  var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "catalog", "primitives", "plugin", "$comment"]);
3927
4043
  var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
@@ -4030,6 +4146,9 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4030
4146
  if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
4031
4147
  if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
4032
4148
  for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
4149
+ if (raw.extensible !== void 0 && !(isStringList2(raw.extensible) && raw.extensible.every((n) => /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)))) {
4150
+ fail(`${at}.extensible must be a list of export names, or parts of one ("ResourceView.slots")`);
4151
+ }
4033
4152
  if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
4034
4153
  const forbid = raw.forbid;
4035
4154
  for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
@@ -4042,6 +4161,7 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4042
4161
  const unless = raw.unless;
4043
4162
  for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
4044
4163
  if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
4164
+ 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`);
4045
4165
  if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
4046
4166
  }
4047
4167
  return raw;
@@ -4156,6 +4276,7 @@ function compile(rule, setting, routes) {
4156
4276
  imports: (rule.forbid.imports ?? []).map(specMatcher),
4157
4277
  ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
4158
4278
  unlessRenders: new Set(rule.unless?.renders ?? []),
4279
+ unlessInside: new Set(rule.unless?.inside ?? []),
4159
4280
  ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
4160
4281
  };
4161
4282
  }
@@ -4167,10 +4288,11 @@ function messageFor(rule, found) {
4167
4288
  const docs = rule.docs ? ` See ${rule.docs}` : "";
4168
4289
  return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
4169
4290
  }
4291
+ var CHILDREN = /\{\s*(?:props\.)?children\s*\}/g;
4170
4292
  var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
4171
4293
  var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
4172
4294
  var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
4173
- function wrappersIn(file, elements, c) {
4295
+ function wrappersIn(file, elements, names, accept) {
4174
4296
  const out = /* @__PURE__ */ new Map();
4175
4297
  const decls = [...file.code.matchAll(TOP_LEVEL)];
4176
4298
  const listed = /* @__PURE__ */ new Map();
@@ -4183,12 +4305,12 @@ function wrappersIn(file, elements, c) {
4183
4305
  for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
4184
4306
  decls.forEach((d, i) => {
4185
4307
  const name = d[3];
4186
- if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
4308
+ if (!/^[A-Z]/.test(name) || names.has(name)) return;
4187
4309
  const end = decls[i + 1]?.index ?? file.code.length;
4188
- const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
4189
- if (!hit) return;
4190
- const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4191
- for (const n of names) out.set(n, hit[1]);
4310
+ const hit = elements.find((m) => m.index > d.index && m.index < end && names.has(m[1]));
4311
+ if (!hit || accept && !accept(d.index, end)) return;
4312
+ const exported = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4313
+ for (const n of exported) out.set(n, hit[1]);
4192
4314
  });
4193
4315
  return out;
4194
4316
  }
@@ -4196,6 +4318,32 @@ function runPrefer(ctx, c) {
4196
4318
  const own = c.rule.packageDir;
4197
4319
  const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
4198
4320
  const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
4321
+ const scanned = new Map(ctx.files.map((f) => [f.absolutePath, f]));
4322
+ const importedBy = /* @__PURE__ */ new Map();
4323
+ const importsOf = (file) => {
4324
+ if (!importedBy.has(file)) importedBy.set(file, localImportedNames(ctx.root, file));
4325
+ return importedBy.get(file);
4326
+ };
4327
+ const builders = /* @__PURE__ */ new Map();
4328
+ const buildersIn = (abs) => {
4329
+ if (!builders.has(abs)) {
4330
+ const target = scanned.get(abs) ?? readSource(abs);
4331
+ const code = target ? "ext" in target ? target.code : stripBlockComments(target.code, true) : "";
4332
+ const childrenInside = (start, end) => [...code.slice(start, end).matchAll(CHILDREN)].some((m) => openElementsAt(code, start + m.index, (n) => c.unlessInside.has(n)).length > 0);
4333
+ builders.set(abs, code ? wrappersIn({ code }, [...code.matchAll(ELEMENT)], c.unlessInside, childrenInside) : /* @__PURE__ */ new Map());
4334
+ }
4335
+ return builders.get(abs);
4336
+ };
4337
+ const nestedInBuilder = (file, index) => {
4338
+ if (!c.unlessInside.size) return false;
4339
+ const imported = importsOf(file);
4340
+ const isBuilder = (name) => {
4341
+ if (c.unlessInside.has(name)) return true;
4342
+ const from = name.includes(".") ? void 0 : imported.get(name);
4343
+ return from !== void 0 && buildersIn(from.file).has(from.name);
4344
+ };
4345
+ return openElementsAt(file.code, index, isBuilder).length > 0;
4346
+ };
4199
4347
  const wrappers = /* @__PURE__ */ new Map();
4200
4348
  const renderedBy = /* @__PURE__ */ new Map();
4201
4349
  for (const file of checked) {
@@ -4203,16 +4351,17 @@ function runPrefer(ctx, c) {
4203
4351
  const elements = [...file.code.matchAll(ELEMENT)];
4204
4352
  renderedBy.set(file, elements);
4205
4353
  if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
4206
- const found = wrappersIn(file, elements, c);
4354
+ const found = wrappersIn(file, elements, c.jsx);
4207
4355
  if (found.size) wrappers.set(file.absolutePath, found);
4208
4356
  }
4209
4357
  for (const file of checked) {
4210
4358
  const elements = renderedBy.get(file) ?? [];
4211
4359
  if (exempt(file, elements.map((m) => m[1]))) continue;
4212
4360
  const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
4213
- const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
4361
+ const imported = wrappers.size && elements.length ? importsOf(file) : null;
4214
4362
  for (const m of elements) {
4215
4363
  const name = m[1];
4364
+ if (nestedInBuilder(file, m.index)) continue;
4216
4365
  if (c.jsx.has(name)) {
4217
4366
  report(lineAt(file.code, m.index), name, `renders <${name}>`);
4218
4367
  continue;
@@ -4229,6 +4378,7 @@ function runPrefer(ctx, c) {
4229
4378
  if (c.pattern) {
4230
4379
  c.pattern.lastIndex = 0;
4231
4380
  for (const m of file.code.matchAll(c.pattern)) {
4381
+ if (nestedInBuilder(file, m.index)) continue;
4232
4382
  const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
4233
4383
  report(lineAt(file.code, m.index), text, `has ${text}`);
4234
4384
  }
@@ -5913,6 +6063,73 @@ function checkRemovedScopeNames(ctx) {
5913
6063
  }
5914
6064
  }
5915
6065
  }
6066
+
6067
+ // src/doctor/custom-views.ts
6068
+ var JSX_EXTS4 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
6069
+ var CUSTOM_VIEW = /<CustomView\b|\buseCustomView\s*[<(]/;
6070
+ var APP_PART = /data-slot\s*=\s*\{?\s*["'`]app-/;
6071
+ 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;
6072
+ 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;
6073
+ var VARIABLE = /var\(\s*(--[A-Za-z0-9_-]+)/g;
6074
+ function checkAppParts(ctx) {
6075
+ const roles = ctx.genesis.colorTokens;
6076
+ const genesisParts = new Set(ctx.genesis.themeParts ?? []);
6077
+ const overlays = markedOverlays(ctx);
6078
+ for (const file of ctx.files) {
6079
+ if (!JSX_EXTS4.has(file.ext) && file.ext !== ".ts" && file.ext !== ".js") continue;
6080
+ if (insideOverlayOf(overlays, file, ctx.genesis.uiPackage)) continue;
6081
+ const code = file.code;
6082
+ if (JSX_EXTS4.has(file.ext)) {
6083
+ for (const m of code.matchAll(/\bdata-slot\s*=\s*(?:\{\s*)?["'`]([^"'`$]+)["'`]/g)) {
6084
+ const name = m[1];
6085
+ if (name.startsWith("app-")) continue;
6086
+ const clash = genesisParts.has(name);
6087
+ ctx.report({
6088
+ rule: "app-part-name",
6089
+ level: "warn",
6090
+ file: file.path,
6091
+ line: lineAt(code, m.index ?? 0),
6092
+ subject: name,
6093
+ 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)`
6094
+ });
6095
+ }
6096
+ }
6097
+ if (roles && roles.size && (CUSTOM_VIEW.test(code) || APP_PART.test(code))) {
6098
+ const seen = /* @__PURE__ */ new Set();
6099
+ const check = (value, at) => {
6100
+ for (const v of value.matchAll(VARIABLE)) {
6101
+ const name = v[1];
6102
+ if (roles.has(name)) continue;
6103
+ const line = lineAt(code, at);
6104
+ if (seen.has(`${line}:${name}`)) continue;
6105
+ seen.add(`${line}:${name}`);
6106
+ ctx.report({
6107
+ rule: "app-part-colors",
6108
+ level: "warn",
6109
+ file: file.path,
6110
+ line,
6111
+ subject: name,
6112
+ 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`
6113
+ });
6114
+ }
6115
+ };
6116
+ for (const m of code.matchAll(COLOUR_KEY)) check(m[3], m.index ?? 0);
6117
+ for (const m of code.matchAll(COLOUR_UTILITY)) check(m[1], m.index ?? 0);
6118
+ }
6119
+ if (JSX_EXTS4.has(file.ext) && CUSTOM_VIEW.test(code)) {
6120
+ for (const m of code.matchAll(/\bstatus\s*[!=]={1,2}\s*["'`](loading|empty|error)["'`]/g)) {
6121
+ ctx.report({
6122
+ rule: "custom-view-states",
6123
+ level: "warn",
6124
+ file: file.path,
6125
+ line: lineAt(code, m.index ?? 0),
6126
+ subject: m[1],
6127
+ 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)`
6128
+ });
6129
+ }
6130
+ }
6131
+ }
6132
+ }
5916
6133
  var SCRIPT_EXTS6 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
5917
6134
  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;
5918
6135
  var REEXPORT = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*\nexport\s+(?:type\s+)?\{([^}]*)\}/g;
@@ -6024,13 +6241,34 @@ function git3(root, args) {
6024
6241
  return r.status === 0 ? r.stdout : null;
6025
6242
  }
6026
6243
  function changedSince(root, base) {
6027
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6244
+ const mergeBase = mergeBaseOf2(root, base);
6028
6245
  if (!mergeBase) return null;
6029
6246
  const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
6030
6247
  const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
6031
6248
  if (committed === null || untracked === null) return null;
6032
6249
  return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
6033
6250
  }
6251
+ function originsSince(root, base) {
6252
+ const out = /* @__PURE__ */ new Map();
6253
+ const mergeBase = mergeBaseOf2(root, base);
6254
+ if (!mergeBase) return out;
6255
+ const diff = git3(root, ["diff", "-z", "-M", "--name-status", "--relative", mergeBase, "--"]);
6256
+ if (diff === null) return out;
6257
+ const parts = diff.split("\0");
6258
+ for (let i = 0; i < parts.length; ) {
6259
+ const status = parts[i++] ?? "";
6260
+ if (!status) continue;
6261
+ if (status.startsWith("R") || status.startsWith("C")) {
6262
+ const from = parts[i++];
6263
+ const to = parts[i++];
6264
+ if (status.startsWith("R")) out.set(to, from);
6265
+ } else i++;
6266
+ }
6267
+ return out;
6268
+ }
6269
+ function mergeBaseOf2(root, base) {
6270
+ return git3(root, ["merge-base", base, "HEAD"])?.trim() || null;
6271
+ }
6034
6272
  var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
6035
6273
  function showAt(dir, rev, file) {
6036
6274
  const at = `${rev}:./${file}`;
@@ -6038,7 +6276,7 @@ function showAt(dir, rev, file) {
6038
6276
  return git3(dir, ["show", at]);
6039
6277
  }
6040
6278
  function configAtBase(root, base, explicitFile) {
6041
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6279
+ const mergeBase = mergeBaseOf2(root, base);
6042
6280
  if (!mergeBase) return null;
6043
6281
  const candidates = explicitFile ? [{ dir: path21.dirname(explicitFile), file: path21.basename(explicitFile), explicit: true }] : [
6044
6282
  { dir: root, file: "genesis.config.json", explicit: false },
@@ -6059,7 +6297,12 @@ function configAtBase(root, base, explicitFile) {
6059
6297
  continue;
6060
6298
  }
6061
6299
  const b = objectOr(block);
6062
- return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
6300
+ return {
6301
+ allow: Array.isArray(b.allow) ? b.allow : [],
6302
+ extend: Array.isArray(b.extend) ? b.extend : [],
6303
+ rules: objectOr(b.rules),
6304
+ packageRules: objectOr(b.packageRules)
6305
+ };
6063
6306
  }
6064
6307
  return "absent";
6065
6308
  }
@@ -6073,6 +6316,16 @@ function allowGrew(allow, before, base) {
6073
6316
  message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
6074
6317
  }));
6075
6318
  }
6319
+ function extensionsAdded(extend, before, base) {
6320
+ const had = new Set(before.map((e) => `${e.rule}\0${e.file}\0${e.buildsOn}`));
6321
+ return extend.filter((e) => !had.has(`${e.rule}\0${e.file}\0${e.buildsOn}`)).map((e) => ({
6322
+ rule: "extension-added",
6323
+ level: "info",
6324
+ file: e.file,
6325
+ subject: e.rule,
6326
+ 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`
6327
+ }));
6328
+ }
6076
6329
  var RANK = { off: 0, info: 1, warn: 2, error: 3 };
6077
6330
  function rulesWeakened(config, before, base) {
6078
6331
  const out = [];
@@ -6110,14 +6363,169 @@ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
6110
6363
  "plugin-error",
6111
6364
  "build",
6112
6365
  "agent-guide-stale",
6113
- "contracts-stale"
6366
+ "contracts-stale",
6367
+ "stale-extension",
6368
+ "extension-added"
6114
6369
  ]);
6370
+ function isRatcheted(rule, config, newOnly) {
6371
+ return !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6372
+ }
6373
+ var countKey = (file, rule) => `${file}\0${rule}`;
6374
+ function countFindings(findings) {
6375
+ const counts = /* @__PURE__ */ new Map();
6376
+ for (const f of findings) counts.set(countKey(f.file, f.rule), (counts.get(countKey(f.file, f.rule)) ?? 0) + 1);
6377
+ return counts;
6378
+ }
6115
6379
  function applyRatchet(findings, options) {
6116
- const { config, newOnly, changed, base, isAppPath } = options;
6117
- const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6380
+ const { config, newOnly, changed, base, isAppPath, baseCounts, existedAtBase } = options;
6381
+ const originOf = options.originOf ?? ((f) => f);
6382
+ const counts = countFindings(findings.map((f) => ({ file: originOf(f.file), rule: f.rule })));
6118
6383
  return findings.map((f) => {
6119
- if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
6120
- return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6384
+ if (f.level === "info" || !isRatcheted(f.rule, config, newOnly) || !isAppPath(f.file)) return f;
6385
+ if (!touched(f.file, changed)) return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6386
+ const origin = originOf(f.file);
6387
+ if (!baseCounts || !existedAtBase?.(origin)) return f;
6388
+ const now = counts.get(countKey(origin, f.rule)) ?? 0;
6389
+ const was = baseCounts.get(countKey(origin, f.rule)) ?? 0;
6390
+ const where2 = origin === f.file ? "this file" : `the files from ${origin}`;
6391
+ 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)` };
6392
+ return { ...f, level: "info", message: `${f.message} (ratcheted: ${now} in ${where2}, ${was} at the merge base with ${base})` };
6393
+ });
6394
+ }
6395
+ function snapshotAtBase(root, base, files, changed, originOf = (f) => f) {
6396
+ const mergeBase = mergeBaseOf2(root, base);
6397
+ if (!mergeBase) return null;
6398
+ const out = [];
6399
+ const seen = /* @__PURE__ */ new Set();
6400
+ for (const f of files) {
6401
+ if (!changed.has(f.path)) {
6402
+ if (!seen.has(f.path)) out.push(f);
6403
+ seen.add(f.path);
6404
+ continue;
6405
+ }
6406
+ const origin = originOf(f.path);
6407
+ if (seen.has(origin)) continue;
6408
+ seen.add(origin);
6409
+ const text = showAt(root, mergeBase, origin);
6410
+ if (text === null) return null;
6411
+ if (text !== void 0) out.push(withText({ ...f, path: origin, absolutePath: path21.join(root, origin) }, text));
6412
+ }
6413
+ const cache2 = /* @__PURE__ */ new Map();
6414
+ return {
6415
+ mergeBase,
6416
+ files: out,
6417
+ existed(file) {
6418
+ if (!cache2.has(file)) cache2.set(file, git3(root, ["cat-file", "-e", `${mergeBase}:./${file}`]) !== null);
6419
+ return cache2.get(file);
6420
+ }
6421
+ };
6422
+ }
6423
+
6424
+ // src/doctor/extensions.ts
6425
+ function pointProblem(entry, packages) {
6426
+ const rule = preferRules(packages).find((r) => r.ruleId === entry.rule);
6427
+ if (!rule?.extensible?.length) return `${entry.rule} declares no extension points, so it can't be extended (debt goes in allow, and is fixed)`;
6428
+ if (!rule.extensible.includes(entry.buildsOn)) return `${entry.buildsOn} isn't one of ${entry.rule}'s extension points (${rule.extensible.join(", ")})`;
6429
+ return null;
6430
+ }
6431
+ function extensionProblem(entry, ctx) {
6432
+ const point = pointProblem(entry, ctx.packages);
6433
+ if (point) return point;
6434
+ const name = entry.buildsOn.split(".")[0];
6435
+ const replaces = preferRules(ctx.packages).find((r) => r.forbid.jsx?.includes(name));
6436
+ if (replaces) return `${name} is what ${replaces.ruleId} replaces (use ${replaces.use}); a legacy component can't be built on`;
6437
+ const flagged = ctx.raw.find((f) => f.file === entry.file && f.subject === name);
6438
+ if (flagged) return `${name} is flagged in this file by ${flagged.rule}; build on a current Genesis primitive`;
6439
+ const file = ctx.files.find((f) => f.path === entry.file);
6440
+ if (!file) return `${entry.file} isn't one of the files the doctor scans`;
6441
+ const imported = genesisNamedImports(file.code).some((i) => i.names.includes(name));
6442
+ if (!imported) return `${entry.file} doesn't import ${name} from a Genesis package; buildsOn names the extension point the file uses`;
6443
+ if (!usesPoint(blankStrings(file.code), entry.buildsOn)) {
6444
+ const prop = entry.buildsOn.split(".")[1];
6445
+ 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`;
6446
+ }
6447
+ return null;
6448
+ }
6449
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6450
+ function usesPoint(code, point) {
6451
+ const [name, prop] = point.split(".");
6452
+ const n = escape2(name);
6453
+ if (!prop) return new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])|(?<![\\w$.])${n}\\s*(?:<[^>()]*>)?\\s*\\(`).test(code);
6454
+ for (const m of code.matchAll(new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])`, "g"))) {
6455
+ const { end } = tagEnd(code, m.index);
6456
+ if (new RegExp(`(?<![\\w$.])${escape2(prop)}\\s*=`).test(code.slice(m.index, end))) return true;
6457
+ }
6458
+ return false;
6459
+ }
6460
+ function applyExtensions(findings, ctx) {
6461
+ const entries = ctx.config.extend ?? [];
6462
+ if (!entries.length) return findings;
6463
+ const staleLevel = ctx.config.rules?.["stale-extension"];
6464
+ const covered = /* @__PURE__ */ new Set();
6465
+ const grew = /* @__PURE__ */ new Map();
6466
+ const out = [];
6467
+ 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}` });
6468
+ for (const entry of entries) {
6469
+ if (ctx.config.rules?.[entry.rule] === "off" || ctx.config.packageRules?.[entry.rule]?.level === "off") continue;
6470
+ const point = pointProblem(entry, ctx.packages);
6471
+ if (point) {
6472
+ invalid(entry, point);
6473
+ continue;
6474
+ }
6475
+ const hits = findings.filter((f) => f.rule === entry.rule && f.file === entry.file);
6476
+ if (!hits.length) {
6477
+ if (staleLevel === "off") continue;
6478
+ out.push({
6479
+ rule: "stale-extension",
6480
+ level: staleLevel ?? "warn",
6481
+ file: entry.file,
6482
+ line: 0,
6483
+ subject: entry.rule,
6484
+ message: `the extension of ${entry.rule} (building on ${entry.buildsOn}) no longer matches a finding in this file; remove it from doctor.extend`
6485
+ });
6486
+ continue;
6487
+ }
6488
+ const problem = extensionProblem(entry, ctx);
6489
+ if (problem) {
6490
+ invalid(entry, problem);
6491
+ continue;
6492
+ }
6493
+ const limit = ctx.limit?.(entry);
6494
+ if (limit !== void 0 && hits.length > limit) {
6495
+ 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)`);
6496
+ continue;
6497
+ }
6498
+ for (const h of hits) covered.add(h);
6499
+ }
6500
+ const kept = findings.filter((f) => !covered.has(f)).map((f) => grew.has(f) ? { ...f, message: grew.get(f) } : f);
6501
+ return [...kept, ...out].sort(byPlace);
6502
+ }
6503
+ var byPlace = (x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule);
6504
+ var RANK2 = { info: 0, warn: 1, error: 2 };
6505
+ function dedupeFindings(findings) {
6506
+ const groups = /* @__PURE__ */ new Map();
6507
+ const order = [];
6508
+ for (const f of findings) {
6509
+ if (f.subject === void 0 || !f.line) {
6510
+ order.push([f]);
6511
+ continue;
6512
+ }
6513
+ const key2 = `${f.file}\0${f.line}\0${f.subject}`;
6514
+ const list = groups.get(key2) ?? [];
6515
+ const group = list.find((g) => !g.some((x) => x.rule === f.rule));
6516
+ if (group) group.push(f);
6517
+ else {
6518
+ const fresh = [f];
6519
+ list.push(fresh);
6520
+ groups.set(key2, list);
6521
+ order.push(fresh);
6522
+ }
6523
+ }
6524
+ return order.map((group) => {
6525
+ if (group.length === 1) return group[0];
6526
+ const primary = group.reduce((a, b) => RANK2[b.level] > RANK2[a.level] ? b : a);
6527
+ const rules = [primary.rule, ...group.filter((g) => g !== primary).map((g) => g.rule)];
6528
+ return { ...primary, rules, message: `${primary.message} (also ${rules.slice(1).join(", ")})` };
6121
6529
  });
6122
6530
  }
6123
6531
  var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
@@ -6191,7 +6599,7 @@ var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
6191
6599
  var CORE = [
6192
6600
  {
6193
6601
  need: "anything, before building it",
6194
- use: 'search what exists: `genesis features find <term>`, this catalog, and the "Available but unused" list in `genesis doctor --verbose`',
6602
+ 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',
6195
6603
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6196
6604
  from: "genesis-cli"
6197
6605
  },
@@ -6216,9 +6624,15 @@ var CORE = [
6216
6624
  rule: "raw-color",
6217
6625
  from: "genesis-cli"
6218
6626
  },
6627
+ {
6628
+ need: "a Genesis piece that is close but doesn't quite fit",
6629
+ use: "extend it: a prop, a variant, a slot, or your own component that wraps it; never a parallel copy beside it",
6630
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6631
+ from: "genesis-cli"
6632
+ },
6219
6633
  {
6220
6634
  need: "something no primitive covers",
6221
- use: "write the gap up for Genesis (an issue or a proposal) first, then invent in the app, on Genesis primitives",
6635
+ 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",
6222
6636
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6223
6637
  from: "genesis-cli"
6224
6638
  }
@@ -6261,10 +6675,12 @@ var AGENTS_START = "<!-- genesis-primitives:start -->";
6261
6675
  var AGENTS_END = "<!-- genesis-primitives:end -->";
6262
6676
  var RULES = [
6263
6677
  `Use the Genesis primitive for the need first: reuse, then extend, then invent (G1 to G6 in ${GENESIS_DOCS}/FRAMEWORK.md).`,
6678
+ "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.",
6264
6679
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
6265
6680
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
6266
6681
  "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.",
6267
- "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
6682
+ "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.",
6683
+ "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.",
6268
6684
  "Run `genesis doctor` before you finish; it enforces these rules."
6269
6685
  ];
6270
6686
  function skillDescription(text) {
@@ -7292,14 +7708,8 @@ async function runDoctor(options = {}) {
7292
7708
  }
7293
7709
  const raw = [];
7294
7710
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
7295
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
7296
- try {
7297
- await plugin.check(ctx);
7298
- } catch (err) {
7299
- if (err instanceof DoctorConfigError) throw err;
7300
- raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7301
- }
7302
- }
7711
+ const appChecks = [...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins];
7712
+ await runChecks(ctx, [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...appChecks]);
7303
7713
  if (options.build) {
7304
7714
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
7305
7715
  if (failure) raw.push(failure);
@@ -7309,30 +7719,57 @@ async function runDoctor(options = {}) {
7309
7719
  let changed = null;
7310
7720
  let skipped = false;
7311
7721
  const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
7312
- if (options.base && (ratchetNeeded || config.ratchet)) {
7722
+ if (options.base && (ratchetNeeded || config.ratchet || config.extend?.length)) {
7313
7723
  changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
7314
7724
  skipped ||= !changed;
7315
7725
  }
7316
7726
  const configFile = "file" in loaded ? loaded.file : null;
7317
- const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7727
+ const guarded = (config.allow?.length ?? 0) + (config.extend?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7318
7728
  let configSkipped = false;
7729
+ let baseExtend = [];
7319
7730
  if (options.base && configFile) {
7320
7731
  const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
7732
+ if (before && before !== "absent") baseExtend = before.extend;
7733
+ if (before === "absent") raw.push(...extensionsAdded(config.extend ?? [], [], options.base));
7321
7734
  if (before && before !== "absent") {
7322
7735
  raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
7323
7736
  raw.push(...rulesWeakened(config, before, options.base));
7737
+ raw.push(...extensionsAdded(config.extend ?? [], before.extend, options.base));
7324
7738
  }
7325
7739
  configSkipped = !before && guarded;
7326
7740
  }
7327
7741
  if (skipped || configSkipped) {
7328
7742
  raw.push(
7329
- 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` }
7743
+ 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` }
7330
7744
  );
7331
7745
  }
7332
- let findings = applyConfig(raw, config, packageRuleIds(packages));
7746
+ const packageIds = packageRuleIds(packages);
7747
+ const extensionCtx = { config, files, packages, raw };
7748
+ const configured = applyConfig(raw, config, packageIds);
7749
+ let findings = applyExtensions(configured, extensionCtx);
7333
7750
  if (options.base && changed) {
7334
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path21.join(root, f)) });
7751
+ const isAppPath = (f) => existsSync(path21.join(root, f));
7752
+ const origins = options.changedFiles ? /* @__PURE__ */ new Map() : originsSince(root, options.base);
7753
+ const originOf = (f) => origins.get(f) ?? f;
7754
+ 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));
7755
+ 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))));
7756
+ for (const e of heldExtensions) dueRules.add(e.rule);
7757
+ const snapshot = dueRules.size ? snapshotAtBase(root, options.base, files, changed, originOf) : null;
7758
+ let baseCounts;
7759
+ if (snapshot) {
7760
+ const before = [];
7761
+ await runChecks({ ...ctx, files: snapshot.files, report: (f) => before.push(f) }, baseChecks(dueRules, packageIds, packagePlugins, () => [...builtinChecks(config, { contracts: false, figma: false }), ...appChecks]));
7762
+ baseCounts = countFindings(applyConfig(before, config, packageIds));
7763
+ if (heldExtensions.length) {
7764
+ const counts = baseCounts;
7765
+ const held = new Set(heldExtensions);
7766
+ findings = applyExtensions(configured, { ...extensionCtx, limit: (e) => held.has(e) ? counts.get(countKey(originOf(e.file), e.rule)) ?? 0 : void 0 });
7767
+ }
7768
+ }
7769
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath, originOf, ...snapshot && baseCounts ? { baseCounts, existedAtBase: snapshot.existed } : {} });
7335
7770
  }
7771
+ findings = dedupeFindings(findings);
7772
+ const extensionsNew = (config.extend ?? []).filter((e) => findings.some((f) => f.rule === "extension-added" && f.file === e.file && f.subject === e.rule));
7336
7773
  const errors = findings.filter((f) => f.level === "error").length;
7337
7774
  const warnings = findings.filter((f) => f.level === "warn").length;
7338
7775
  const infos = findings.length - errors - warnings;
@@ -7346,9 +7783,24 @@ async function runDoctor(options = {}) {
7346
7783
  primitives: primitivesSummary(packages),
7347
7784
  errors,
7348
7785
  warnings,
7349
- infos
7786
+ infos,
7787
+ ...extensionsNew.length ? { extensionsAdded: extensionsNew } : {}
7350
7788
  };
7351
7789
  }
7790
+ function baseChecks(rules, preferIds, packagePlugins, all) {
7791
+ if ([...rules].every((r) => preferIds.has(r))) return packagePlugins.filter((p) => p.name === "package-rules");
7792
+ return all();
7793
+ }
7794
+ async function runChecks(ctx, checks) {
7795
+ for (const plugin of checks) {
7796
+ try {
7797
+ await plugin.check(ctx);
7798
+ } catch (err) {
7799
+ if (err instanceof DoctorConfigError) throw err;
7800
+ ctx.report({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7801
+ }
7802
+ }
7803
+ }
7352
7804
  function builtinChecks(config, options = {}) {
7353
7805
  const packs = {
7354
7806
  native: { name: "native", check: checkNativePack },
@@ -7373,6 +7825,7 @@ function builtinChecks(config, options = {}) {
7373
7825
  { name: "resource-view-trees", check: checkTreeViews },
7374
7826
  { name: "studio-server-imports", check: checkStudioServerImports },
7375
7827
  { name: "removed-scope-names", check: checkRemovedScopeNames },
7828
+ { name: "app-parts", check: checkAppParts },
7376
7829
  { name: "stability-imports", check: checkStabilityImports },
7377
7830
  { name: "agent-guide", check: (ctx) => {
7378
7831
  checkAgentGuide(ctx);
@@ -7442,17 +7895,21 @@ function formatReport(result, options = {}) {
7442
7895
  `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"}`
7443
7896
  ];
7444
7897
  for (const f of result.findings) {
7445
- lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
7898
+ lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${(f.rules ?? [f.rule]).join(", ")}] ${f.message}`);
7446
7899
  }
7447
7900
  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)`);
7448
7901
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
7902
+ if (result.extensionsAdded?.length) {
7903
+ lines.push(`Extensions added on this branch (${result.extensionsAdded.length}); the pull request's review accepts each:`);
7904
+ for (const e of result.extensionsAdded) lines.push(` ${e.file} [${e.rule}] builds on ${e.buildsOn}: ${e.reason}${e.upstream ? ` (upstream: ${e.upstream})` : ""}`);
7905
+ }
7449
7906
  const info = result.infos ? `, ${result.infos} info` : "";
7450
7907
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
7451
7908
  return lines.join("\n");
7452
7909
  }
7453
7910
 
7454
7911
  // src/vite.ts
7455
- 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");
7912
+ 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");
7456
7913
  function genesisDoctor(options = {}) {
7457
7914
  let root = options.root ?? process.cwd();
7458
7915
  return [