@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/index.js CHANGED
@@ -258,7 +258,7 @@ var init_comments = __esm({
258
258
  "src/introspect/comments.ts"() {
259
259
  MARKER = "@genesis";
260
260
  TABLE_KEYS = { label: "string", labelField: "string", description: "string", noun: "string", nounPlural: "string", key: "key" };
261
- FIELD_KEYS = { label: "string", description: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
261
+ FIELD_KEYS = { label: "string", description: "string", control: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
262
262
  CommentSettingsError = class extends Error {
263
263
  };
264
264
  }
@@ -617,7 +617,8 @@ function field(column, indent) {
617
617
  const description = column.settings?.description ?? column.description;
618
618
  if (label) parts.push(`label: ${quote(label)}`);
619
619
  if (description) parts.push(`description: ${quote(description)}`);
620
- if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
620
+ if (column.settings?.control) parts.push(`control: ${quote(column.settings.control)}`);
621
+ else if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
621
622
  if (column.settings?.readonly) parts.push("readOnly: true");
622
623
  if (column.settings?.sensitive) parts.push("sensitive: true");
623
624
  return `${indent}{ ${parts.join(", ")} },`;
@@ -1534,6 +1535,7 @@ var KNOWN = /* @__PURE__ */ new Set([
1534
1535
  "forbiddenImports",
1535
1536
  "rules",
1536
1537
  "allow",
1538
+ "extend",
1537
1539
  "patterns",
1538
1540
  "plugins",
1539
1541
  "packs",
@@ -1548,7 +1550,10 @@ var KNOWN = /* @__PURE__ */ new Set([
1548
1550
  "$comment"
1549
1551
  ]);
1550
1552
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
1551
- var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
1553
+ var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped", "extension-invalid"]);
1554
+ var CONFIG_RULES = /* @__PURE__ */ new Set(["stale-exception", "stale-extension", "package-rule-override"]);
1555
+ var EXTENSION_KEYS = /* @__PURE__ */ new Set(["rule", "file", "buildsOn", "reason", "upstream"]);
1556
+ var EXTENSION_REASON_MIN = { chars: 40, words: 6 };
1552
1557
  var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
1553
1558
  var PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
1554
1559
  var CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
@@ -1759,6 +1764,30 @@ function validateConfig(raw, source = "config") {
1759
1764
  }
1760
1765
  });
1761
1766
  }
1767
+ if (c.extend !== void 0) {
1768
+ if (!Array.isArray(c.extend)) fail(`"extend" must be a list of { rule, file, buildsOn, reason, upstream? }`);
1769
+ const seen = /* @__PURE__ */ new Set();
1770
+ c.extend.forEach((e, i) => {
1771
+ const where2 = `extend[${i}]`;
1772
+ if (!isObject(e)) return fail(`${where2} must be an object`);
1773
+ for (const k of Object.keys(e)) if (!EXTENSION_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: ${[...EXTENSION_KEYS].join(", ")})`);
1774
+ for (const k of ["rule", "file", "buildsOn", "reason"]) if (typeof e[k] !== "string" || !e[k].trim()) fail(`${where2} needs "${k}"`);
1775
+ const { rule, file, buildsOn, reason } = e;
1776
+ 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`);
1777
+ 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)`);
1778
+ if (/[*?[\]{}]/.test(file)) fail(`${where2}.file must be one file, not a glob: each extension is reviewed on its own`);
1779
+ e.file = appPath(file, `${where2}.file`, fail);
1780
+ 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")`);
1781
+ const text = reason.trim();
1782
+ if (text.length < EXTENSION_REASON_MIN.chars || text.split(/\s+/).length < EXTENSION_REASON_MIN.words) {
1783
+ 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`);
1784
+ }
1785
+ 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`);
1786
+ const key2 = `${rule}\0${e.file}`;
1787
+ if (seen.has(key2)) fail(`${where2} extends ${rule} in ${e.file} twice`);
1788
+ seen.add(key2);
1789
+ });
1790
+ }
1762
1791
  if (c.patterns !== void 0) {
1763
1792
  if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
1764
1793
  c.patterns.forEach((p, i) => {
@@ -2452,6 +2481,9 @@ function scanFiles(root, config) {
2452
2481
  for (const pkg of local) walk3(pkg.dir);
2453
2482
  return files;
2454
2483
  }
2484
+ function withText(file, text) {
2485
+ return { ...file, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(file.ext)) };
2486
+ }
2455
2487
  function lineAt(text, index) {
2456
2488
  let line = 1;
2457
2489
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
@@ -2986,7 +3018,9 @@ function loadGenesis(root, config) {
2986
3018
  const { dir: uiDir, exports: exportNames, values, components } = pkg;
2987
3019
  const tokens = /* @__PURE__ */ new Set();
2988
3020
  const themeFiles = resolveThemeFiles(root, config, uiDir);
2989
- for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
3021
+ const themeCss = themeFiles.map((file) => readFileSync(file, "utf8"));
3022
+ for (const css of themeCss) for (const t of declaredTokens(css)) tokens.add(t);
3023
+ const colorTokens = colorRoles(themeCss);
2990
3024
  const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
2991
3025
  const rawTags = /* @__PURE__ */ new Map();
2992
3026
  for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
@@ -3002,6 +3036,8 @@ function loadGenesis(root, config) {
3002
3036
  values,
3003
3037
  components,
3004
3038
  tokens,
3039
+ colorTokens,
3040
+ ...themeParts(root) ? { themeParts: themeParts(root) } : {},
3005
3041
  rawTags,
3006
3042
  palette: loadPalette(root),
3007
3043
  companions: loadCompanions(root, config, uiPackage)
@@ -3101,6 +3137,49 @@ function parseExportNames(dts) {
3101
3137
  }
3102
3138
  return names;
3103
3139
  }
3140
+ 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;
3141
+ function colorRoles(sheets) {
3142
+ const declared = /* @__PURE__ */ new Map();
3143
+ for (const css of sheets) {
3144
+ for (const m of css.matchAll(/(--[A-Za-z0-9_-]+)\s*:\s*([^;{}]+);/g)) {
3145
+ const list = declared.get(m[1]) ?? [];
3146
+ list.push(m[2].trim());
3147
+ declared.set(m[1], list);
3148
+ }
3149
+ }
3150
+ const roles = /* @__PURE__ */ new Set();
3151
+ for (const [name, values] of declared) if (values.some((v) => COLOUR_VALUE.test(v))) roles.add(name);
3152
+ for (let pass = 0; pass < 4; pass++) {
3153
+ for (const [name, values] of declared) {
3154
+ if (roles.has(name)) continue;
3155
+ if (values.some((v) => [...v.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)/g)].some((r) => roles.has(r[1])))) roles.add(name);
3156
+ }
3157
+ }
3158
+ return roles;
3159
+ }
3160
+ var partsCache = /* @__PURE__ */ new Map();
3161
+ function themeParts(root) {
3162
+ const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
3163
+ if (!ds) return null;
3164
+ if (partsCache.has(ds)) return partsCache.get(ds);
3165
+ let found = null;
3166
+ const dist = path21.join(ds, "dist");
3167
+ try {
3168
+ for (const name of existsSync(dist) ? readdirSync(dist) : []) {
3169
+ if (!name.endsWith(".js")) continue;
3170
+ const code = readFileSync(path21.join(dist, name), "utf8");
3171
+ const at = code.indexOf("THEME_PARTS = Object.freeze([");
3172
+ if (at === -1) continue;
3173
+ const body = code.slice(at, code.indexOf("]);", at));
3174
+ found = [...body.matchAll(/\bp\(\s*"([a-z][a-z0-9-]*)"/g)].map((m) => m[1]);
3175
+ break;
3176
+ }
3177
+ } catch {
3178
+ found = null;
3179
+ }
3180
+ partsCache.set(ds, found);
3181
+ return found;
3182
+ }
3104
3183
  function declaredTokens(css) {
3105
3184
  return [...css.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)].map((m) => m[1]);
3106
3185
  }
@@ -3449,6 +3528,10 @@ var BUILTIN_RULES = [
3449
3528
  "ratchet-skipped",
3450
3529
  "allow-grew",
3451
3530
  "rules-weakened",
3531
+ "extension-added",
3532
+ // declared extensions (extensions.ts)
3533
+ "stale-extension",
3534
+ "extension-invalid",
3452
3535
  // agent guide (primitives.ts)
3453
3536
  "agent-guide-stale",
3454
3537
  // supabase pack: contracts (contracts.ts)
@@ -3458,7 +3541,11 @@ var BUILTIN_RULES = [
3458
3541
  // an app whose database files live in another app (database.ts)
3459
3542
  "database-elsewhere",
3460
3543
  // the app's eslint config loads Genesis's lint rules (eslint-config.ts)
3461
- "genesis-eslint-config"
3544
+ "genesis-eslint-config",
3545
+ // custom views and app parts (custom-views.ts)
3546
+ "app-part-colors",
3547
+ "app-part-name",
3548
+ "custom-view-states"
3462
3549
  ];
3463
3550
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
3464
3551
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -3481,7 +3568,7 @@ function checkProjectLayout(ctx) {
3481
3568
  rule: "local-primitives",
3482
3569
  file: dir,
3483
3570
  subject: dir,
3484
- message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} (or extend it upstream)`
3571
+ message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} for those, and keep the app's own components in another folder`
3485
3572
  });
3486
3573
  }
3487
3574
  }
@@ -3737,6 +3824,34 @@ function readSource(abs) {
3737
3824
  return null;
3738
3825
  }
3739
3826
  }
3827
+ var lastBlanked = null;
3828
+ function blankStrings(code) {
3829
+ if (lastBlanked?.source === code) return lastBlanked.blanked;
3830
+ const out = code.split("");
3831
+ for (let i = 0; i < code.length; i++) {
3832
+ const ch = code[i];
3833
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
3834
+ let j = i - 1;
3835
+ while (j >= 0 && /[ \t]/.test(code[j])) j--;
3836
+ const before = j >= 0 ? code[j] : "\n";
3837
+ const word = /[\w$]/.test(before) ? /(?:^|[^\w$])(return|case|typeof|in|of|yield|await)$/.test(code.slice(Math.max(0, j - 8), j + 1)) : false;
3838
+ if (/[\w$)\]]/.test(before) && !word) continue;
3839
+ let k = i + 1;
3840
+ for (; k < code.length; k++) {
3841
+ const c = code[k];
3842
+ if (c === "\\") {
3843
+ k++;
3844
+ continue;
3845
+ }
3846
+ if (c === ch) break;
3847
+ if (c === "\n" && ch !== "`") break;
3848
+ }
3849
+ for (let x = i + 1; x < k && x < code.length; x++) if (code[x] !== "\n") out[x] = " ";
3850
+ i = k;
3851
+ }
3852
+ lastBlanked = { source: code, blanked: out.join("") };
3853
+ return lastBlanked.blanked;
3854
+ }
3740
3855
  function tagEnd(code, start) {
3741
3856
  let depth = 0;
3742
3857
  let quote2 = null;
@@ -3758,7 +3873,8 @@ function tagEnd(code, start) {
3758
3873
  }
3759
3874
  return { end: code.length, selfClosing: false };
3760
3875
  }
3761
- function openElementsAt(code, index, track) {
3876
+ function openElementsAt(source, index, track) {
3877
+ const code = blankStrings(source);
3762
3878
  const open = [];
3763
3879
  const re = /<(\/?)([A-Z][\w.]*)(?=[\s>/])/g;
3764
3880
  for (let m = re.exec(code); m && m.index < index; m = re.exec(code)) {
@@ -4610,9 +4726,9 @@ var PackageDeclarationError = class extends Error {
4610
4726
  var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
4611
4727
  var ID = /^[a-z0-9][a-z0-9-]*$/;
4612
4728
  var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
4613
- var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
4729
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly", "extensible"]);
4614
4730
  var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
4615
- var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
4731
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "inside", "pattern"]);
4616
4732
  var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
4617
4733
  var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "catalog", "primitives", "plugin", "$comment"]);
4618
4734
  var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
@@ -4721,6 +4837,9 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4721
4837
  if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
4722
4838
  if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
4723
4839
  for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
4840
+ if (raw.extensible !== void 0 && !(isStringList2(raw.extensible) && raw.extensible.every((n) => /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)))) {
4841
+ fail(`${at}.extensible must be a list of export names, or parts of one ("ResourceView.slots")`);
4842
+ }
4724
4843
  if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
4725
4844
  const forbid = raw.forbid;
4726
4845
  for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
@@ -4733,6 +4852,7 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4733
4852
  const unless = raw.unless;
4734
4853
  for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
4735
4854
  if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
4855
+ 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`);
4736
4856
  if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
4737
4857
  }
4738
4858
  return raw;
@@ -4847,6 +4967,7 @@ function compile(rule, setting, routes) {
4847
4967
  imports: (rule.forbid.imports ?? []).map(specMatcher),
4848
4968
  ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
4849
4969
  unlessRenders: new Set(rule.unless?.renders ?? []),
4970
+ unlessInside: new Set(rule.unless?.inside ?? []),
4850
4971
  ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
4851
4972
  };
4852
4973
  }
@@ -4858,10 +4979,11 @@ function messageFor(rule, found) {
4858
4979
  const docs = rule.docs ? ` See ${rule.docs}` : "";
4859
4980
  return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
4860
4981
  }
4982
+ var CHILDREN = /\{\s*(?:props\.)?children\s*\}/g;
4861
4983
  var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
4862
4984
  var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
4863
4985
  var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
4864
- function wrappersIn(file, elements, c) {
4986
+ function wrappersIn(file, elements, names, accept) {
4865
4987
  const out = /* @__PURE__ */ new Map();
4866
4988
  const decls = [...file.code.matchAll(TOP_LEVEL)];
4867
4989
  const listed = /* @__PURE__ */ new Map();
@@ -4874,12 +4996,12 @@ function wrappersIn(file, elements, c) {
4874
4996
  for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
4875
4997
  decls.forEach((d, i) => {
4876
4998
  const name = d[3];
4877
- if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
4999
+ if (!/^[A-Z]/.test(name) || names.has(name)) return;
4878
5000
  const end = decls[i + 1]?.index ?? file.code.length;
4879
- const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
4880
- if (!hit) return;
4881
- const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4882
- for (const n of names) out.set(n, hit[1]);
5001
+ const hit = elements.find((m) => m.index > d.index && m.index < end && names.has(m[1]));
5002
+ if (!hit || accept && !accept(d.index, end)) return;
5003
+ const exported = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
5004
+ for (const n of exported) out.set(n, hit[1]);
4883
5005
  });
4884
5006
  return out;
4885
5007
  }
@@ -4887,6 +5009,32 @@ function runPrefer(ctx, c) {
4887
5009
  const own = c.rule.packageDir;
4888
5010
  const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
4889
5011
  const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
5012
+ const scanned = new Map(ctx.files.map((f) => [f.absolutePath, f]));
5013
+ const importedBy = /* @__PURE__ */ new Map();
5014
+ const importsOf = (file) => {
5015
+ if (!importedBy.has(file)) importedBy.set(file, localImportedNames(ctx.root, file));
5016
+ return importedBy.get(file);
5017
+ };
5018
+ const builders = /* @__PURE__ */ new Map();
5019
+ const buildersIn = (abs) => {
5020
+ if (!builders.has(abs)) {
5021
+ const target = scanned.get(abs) ?? readSource(abs);
5022
+ const code = target ? "ext" in target ? target.code : stripBlockComments(target.code, true) : "";
5023
+ const childrenInside = (start, end) => [...code.slice(start, end).matchAll(CHILDREN)].some((m) => openElementsAt(code, start + m.index, (n) => c.unlessInside.has(n)).length > 0);
5024
+ builders.set(abs, code ? wrappersIn({ code }, [...code.matchAll(ELEMENT)], c.unlessInside, childrenInside) : /* @__PURE__ */ new Map());
5025
+ }
5026
+ return builders.get(abs);
5027
+ };
5028
+ const nestedInBuilder = (file, index) => {
5029
+ if (!c.unlessInside.size) return false;
5030
+ const imported = importsOf(file);
5031
+ const isBuilder = (name) => {
5032
+ if (c.unlessInside.has(name)) return true;
5033
+ const from = name.includes(".") ? void 0 : imported.get(name);
5034
+ return from !== void 0 && buildersIn(from.file).has(from.name);
5035
+ };
5036
+ return openElementsAt(file.code, index, isBuilder).length > 0;
5037
+ };
4890
5038
  const wrappers = /* @__PURE__ */ new Map();
4891
5039
  const renderedBy = /* @__PURE__ */ new Map();
4892
5040
  for (const file of checked) {
@@ -4894,16 +5042,17 @@ function runPrefer(ctx, c) {
4894
5042
  const elements = [...file.code.matchAll(ELEMENT)];
4895
5043
  renderedBy.set(file, elements);
4896
5044
  if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
4897
- const found = wrappersIn(file, elements, c);
5045
+ const found = wrappersIn(file, elements, c.jsx);
4898
5046
  if (found.size) wrappers.set(file.absolutePath, found);
4899
5047
  }
4900
5048
  for (const file of checked) {
4901
5049
  const elements = renderedBy.get(file) ?? [];
4902
5050
  if (exempt(file, elements.map((m) => m[1]))) continue;
4903
5051
  const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
4904
- const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
5052
+ const imported = wrappers.size && elements.length ? importsOf(file) : null;
4905
5053
  for (const m of elements) {
4906
5054
  const name = m[1];
5055
+ if (nestedInBuilder(file, m.index)) continue;
4907
5056
  if (c.jsx.has(name)) {
4908
5057
  report(lineAt(file.code, m.index), name, `renders <${name}>`);
4909
5058
  continue;
@@ -4920,6 +5069,7 @@ function runPrefer(ctx, c) {
4920
5069
  if (c.pattern) {
4921
5070
  c.pattern.lastIndex = 0;
4922
5071
  for (const m of file.code.matchAll(c.pattern)) {
5072
+ if (nestedInBuilder(file, m.index)) continue;
4923
5073
  const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
4924
5074
  report(lineAt(file.code, m.index), text, `has ${text}`);
4925
5075
  }
@@ -6604,6 +6754,73 @@ function checkRemovedScopeNames(ctx) {
6604
6754
  }
6605
6755
  }
6606
6756
  }
6757
+
6758
+ // src/doctor/custom-views.ts
6759
+ var JSX_EXTS4 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
6760
+ var CUSTOM_VIEW = /<CustomView\b|\buseCustomView\s*[<(]/;
6761
+ var APP_PART = /data-slot\s*=\s*\{?\s*["'`]app-/;
6762
+ 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;
6763
+ 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;
6764
+ var VARIABLE = /var\(\s*(--[A-Za-z0-9_-]+)/g;
6765
+ function checkAppParts(ctx) {
6766
+ const roles = ctx.genesis.colorTokens;
6767
+ const genesisParts = new Set(ctx.genesis.themeParts ?? []);
6768
+ const overlays = markedOverlays(ctx);
6769
+ for (const file of ctx.files) {
6770
+ if (!JSX_EXTS4.has(file.ext) && file.ext !== ".ts" && file.ext !== ".js") continue;
6771
+ if (insideOverlayOf(overlays, file, ctx.genesis.uiPackage)) continue;
6772
+ const code = file.code;
6773
+ if (JSX_EXTS4.has(file.ext)) {
6774
+ for (const m of code.matchAll(/\bdata-slot\s*=\s*(?:\{\s*)?["'`]([^"'`$]+)["'`]/g)) {
6775
+ const name = m[1];
6776
+ if (name.startsWith("app-")) continue;
6777
+ const clash = genesisParts.has(name);
6778
+ ctx.report({
6779
+ rule: "app-part-name",
6780
+ level: "warn",
6781
+ file: file.path,
6782
+ line: lineAt(code, m.index ?? 0),
6783
+ subject: name,
6784
+ 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)`
6785
+ });
6786
+ }
6787
+ }
6788
+ if (roles && roles.size && (CUSTOM_VIEW.test(code) || APP_PART.test(code))) {
6789
+ const seen = /* @__PURE__ */ new Set();
6790
+ const check = (value, at) => {
6791
+ for (const v of value.matchAll(VARIABLE)) {
6792
+ const name = v[1];
6793
+ if (roles.has(name)) continue;
6794
+ const line = lineAt(code, at);
6795
+ if (seen.has(`${line}:${name}`)) continue;
6796
+ seen.add(`${line}:${name}`);
6797
+ ctx.report({
6798
+ rule: "app-part-colors",
6799
+ level: "warn",
6800
+ file: file.path,
6801
+ line,
6802
+ subject: name,
6803
+ 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`
6804
+ });
6805
+ }
6806
+ };
6807
+ for (const m of code.matchAll(COLOUR_KEY)) check(m[3], m.index ?? 0);
6808
+ for (const m of code.matchAll(COLOUR_UTILITY)) check(m[1], m.index ?? 0);
6809
+ }
6810
+ if (JSX_EXTS4.has(file.ext) && CUSTOM_VIEW.test(code)) {
6811
+ for (const m of code.matchAll(/\bstatus\s*[!=]={1,2}\s*["'`](loading|empty|error)["'`]/g)) {
6812
+ ctx.report({
6813
+ rule: "custom-view-states",
6814
+ level: "warn",
6815
+ file: file.path,
6816
+ line: lineAt(code, m.index ?? 0),
6817
+ subject: m[1],
6818
+ 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)`
6819
+ });
6820
+ }
6821
+ }
6822
+ }
6823
+ }
6607
6824
  var SCRIPT_EXTS6 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
6608
6825
  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;
6609
6826
  var REEXPORT = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*\nexport\s+(?:type\s+)?\{([^}]*)\}/g;
@@ -6715,13 +6932,34 @@ function git3(root, args) {
6715
6932
  return r.status === 0 ? r.stdout : null;
6716
6933
  }
6717
6934
  function changedSince(root, base) {
6718
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6935
+ const mergeBase = mergeBaseOf2(root, base);
6719
6936
  if (!mergeBase) return null;
6720
6937
  const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
6721
6938
  const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
6722
6939
  if (committed === null || untracked === null) return null;
6723
6940
  return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
6724
6941
  }
6942
+ function originsSince(root, base) {
6943
+ const out = /* @__PURE__ */ new Map();
6944
+ const mergeBase = mergeBaseOf2(root, base);
6945
+ if (!mergeBase) return out;
6946
+ const diff = git3(root, ["diff", "-z", "-M", "--name-status", "--relative", mergeBase, "--"]);
6947
+ if (diff === null) return out;
6948
+ const parts = diff.split("\0");
6949
+ for (let i = 0; i < parts.length; ) {
6950
+ const status = parts[i++] ?? "";
6951
+ if (!status) continue;
6952
+ if (status.startsWith("R") || status.startsWith("C")) {
6953
+ const from = parts[i++];
6954
+ const to = parts[i++];
6955
+ if (status.startsWith("R")) out.set(to, from);
6956
+ } else i++;
6957
+ }
6958
+ return out;
6959
+ }
6960
+ function mergeBaseOf2(root, base) {
6961
+ return git3(root, ["merge-base", base, "HEAD"])?.trim() || null;
6962
+ }
6725
6963
  var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
6726
6964
  function showAt(dir, rev, file) {
6727
6965
  const at = `${rev}:./${file}`;
@@ -6729,7 +6967,7 @@ function showAt(dir, rev, file) {
6729
6967
  return git3(dir, ["show", at]);
6730
6968
  }
6731
6969
  function configAtBase(root, base, explicitFile) {
6732
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6970
+ const mergeBase = mergeBaseOf2(root, base);
6733
6971
  if (!mergeBase) return null;
6734
6972
  const candidates = explicitFile ? [{ dir: path21.dirname(explicitFile), file: path21.basename(explicitFile), explicit: true }] : [
6735
6973
  { dir: root, file: "genesis.config.json", explicit: false },
@@ -6750,7 +6988,12 @@ function configAtBase(root, base, explicitFile) {
6750
6988
  continue;
6751
6989
  }
6752
6990
  const b = objectOr(block);
6753
- return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
6991
+ return {
6992
+ allow: Array.isArray(b.allow) ? b.allow : [],
6993
+ extend: Array.isArray(b.extend) ? b.extend : [],
6994
+ rules: objectOr(b.rules),
6995
+ packageRules: objectOr(b.packageRules)
6996
+ };
6754
6997
  }
6755
6998
  return "absent";
6756
6999
  }
@@ -6764,6 +7007,16 @@ function allowGrew(allow, before, base) {
6764
7007
  message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
6765
7008
  }));
6766
7009
  }
7010
+ function extensionsAdded(extend, before, base) {
7011
+ const had = new Set(before.map((e) => `${e.rule}\0${e.file}\0${e.buildsOn}`));
7012
+ return extend.filter((e) => !had.has(`${e.rule}\0${e.file}\0${e.buildsOn}`)).map((e) => ({
7013
+ rule: "extension-added",
7014
+ level: "info",
7015
+ file: e.file,
7016
+ subject: e.rule,
7017
+ 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`
7018
+ }));
7019
+ }
6767
7020
  var RANK = { off: 0, info: 1, warn: 2, error: 3 };
6768
7021
  function rulesWeakened(config, before, base) {
6769
7022
  const out = [];
@@ -6801,14 +7054,169 @@ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
6801
7054
  "plugin-error",
6802
7055
  "build",
6803
7056
  "agent-guide-stale",
6804
- "contracts-stale"
7057
+ "contracts-stale",
7058
+ "stale-extension",
7059
+ "extension-added"
6805
7060
  ]);
7061
+ function isRatcheted(rule, config, newOnly) {
7062
+ return !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
7063
+ }
7064
+ var countKey = (file, rule) => `${file}\0${rule}`;
7065
+ function countFindings(findings) {
7066
+ const counts = /* @__PURE__ */ new Map();
7067
+ for (const f of findings) counts.set(countKey(f.file, f.rule), (counts.get(countKey(f.file, f.rule)) ?? 0) + 1);
7068
+ return counts;
7069
+ }
6806
7070
  function applyRatchet(findings, options) {
6807
- const { config, newOnly, changed, base, isAppPath } = options;
6808
- const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
7071
+ const { config, newOnly, changed, base, isAppPath, baseCounts, existedAtBase } = options;
7072
+ const originOf = options.originOf ?? ((f) => f);
7073
+ const counts = countFindings(findings.map((f) => ({ file: originOf(f.file), rule: f.rule })));
6809
7074
  return findings.map((f) => {
6810
- if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
6811
- return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
7075
+ if (f.level === "info" || !isRatcheted(f.rule, config, newOnly) || !isAppPath(f.file)) return f;
7076
+ if (!touched(f.file, changed)) return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
7077
+ const origin = originOf(f.file);
7078
+ if (!baseCounts || !existedAtBase?.(origin)) return f;
7079
+ const now = counts.get(countKey(origin, f.rule)) ?? 0;
7080
+ const was = baseCounts.get(countKey(origin, f.rule)) ?? 0;
7081
+ const where2 = origin === f.file ? "this file" : `the files from ${origin}`;
7082
+ 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)` };
7083
+ return { ...f, level: "info", message: `${f.message} (ratcheted: ${now} in ${where2}, ${was} at the merge base with ${base})` };
7084
+ });
7085
+ }
7086
+ function snapshotAtBase(root, base, files, changed, originOf = (f) => f) {
7087
+ const mergeBase = mergeBaseOf2(root, base);
7088
+ if (!mergeBase) return null;
7089
+ const out = [];
7090
+ const seen = /* @__PURE__ */ new Set();
7091
+ for (const f of files) {
7092
+ if (!changed.has(f.path)) {
7093
+ if (!seen.has(f.path)) out.push(f);
7094
+ seen.add(f.path);
7095
+ continue;
7096
+ }
7097
+ const origin = originOf(f.path);
7098
+ if (seen.has(origin)) continue;
7099
+ seen.add(origin);
7100
+ const text = showAt(root, mergeBase, origin);
7101
+ if (text === null) return null;
7102
+ if (text !== void 0) out.push(withText({ ...f, path: origin, absolutePath: path21.join(root, origin) }, text));
7103
+ }
7104
+ const cache2 = /* @__PURE__ */ new Map();
7105
+ return {
7106
+ mergeBase,
7107
+ files: out,
7108
+ existed(file) {
7109
+ if (!cache2.has(file)) cache2.set(file, git3(root, ["cat-file", "-e", `${mergeBase}:./${file}`]) !== null);
7110
+ return cache2.get(file);
7111
+ }
7112
+ };
7113
+ }
7114
+
7115
+ // src/doctor/extensions.ts
7116
+ function pointProblem(entry, packages) {
7117
+ const rule = preferRules(packages).find((r) => r.ruleId === entry.rule);
7118
+ if (!rule?.extensible?.length) return `${entry.rule} declares no extension points, so it can't be extended (debt goes in allow, and is fixed)`;
7119
+ if (!rule.extensible.includes(entry.buildsOn)) return `${entry.buildsOn} isn't one of ${entry.rule}'s extension points (${rule.extensible.join(", ")})`;
7120
+ return null;
7121
+ }
7122
+ function extensionProblem(entry, ctx) {
7123
+ const point = pointProblem(entry, ctx.packages);
7124
+ if (point) return point;
7125
+ const name = entry.buildsOn.split(".")[0];
7126
+ const replaces = preferRules(ctx.packages).find((r) => r.forbid.jsx?.includes(name));
7127
+ if (replaces) return `${name} is what ${replaces.ruleId} replaces (use ${replaces.use}); a legacy component can't be built on`;
7128
+ const flagged = ctx.raw.find((f) => f.file === entry.file && f.subject === name);
7129
+ if (flagged) return `${name} is flagged in this file by ${flagged.rule}; build on a current Genesis primitive`;
7130
+ const file = ctx.files.find((f) => f.path === entry.file);
7131
+ if (!file) return `${entry.file} isn't one of the files the doctor scans`;
7132
+ const imported = genesisNamedImports(file.code).some((i) => i.names.includes(name));
7133
+ if (!imported) return `${entry.file} doesn't import ${name} from a Genesis package; buildsOn names the extension point the file uses`;
7134
+ if (!usesPoint(blankStrings(file.code), entry.buildsOn)) {
7135
+ const prop = entry.buildsOn.split(".")[1];
7136
+ 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`;
7137
+ }
7138
+ return null;
7139
+ }
7140
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7141
+ function usesPoint(code, point) {
7142
+ const [name, prop] = point.split(".");
7143
+ const n = escape2(name);
7144
+ if (!prop) return new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])|(?<![\\w$.])${n}\\s*(?:<[^>()]*>)?\\s*\\(`).test(code);
7145
+ for (const m of code.matchAll(new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])`, "g"))) {
7146
+ const { end } = tagEnd(code, m.index);
7147
+ if (new RegExp(`(?<![\\w$.])${escape2(prop)}\\s*=`).test(code.slice(m.index, end))) return true;
7148
+ }
7149
+ return false;
7150
+ }
7151
+ function applyExtensions(findings, ctx) {
7152
+ const entries = ctx.config.extend ?? [];
7153
+ if (!entries.length) return findings;
7154
+ const staleLevel = ctx.config.rules?.["stale-extension"];
7155
+ const covered = /* @__PURE__ */ new Set();
7156
+ const grew = /* @__PURE__ */ new Map();
7157
+ const out = [];
7158
+ 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}` });
7159
+ for (const entry of entries) {
7160
+ if (ctx.config.rules?.[entry.rule] === "off" || ctx.config.packageRules?.[entry.rule]?.level === "off") continue;
7161
+ const point = pointProblem(entry, ctx.packages);
7162
+ if (point) {
7163
+ invalid(entry, point);
7164
+ continue;
7165
+ }
7166
+ const hits = findings.filter((f) => f.rule === entry.rule && f.file === entry.file);
7167
+ if (!hits.length) {
7168
+ if (staleLevel === "off") continue;
7169
+ out.push({
7170
+ rule: "stale-extension",
7171
+ level: staleLevel ?? "warn",
7172
+ file: entry.file,
7173
+ line: 0,
7174
+ subject: entry.rule,
7175
+ message: `the extension of ${entry.rule} (building on ${entry.buildsOn}) no longer matches a finding in this file; remove it from doctor.extend`
7176
+ });
7177
+ continue;
7178
+ }
7179
+ const problem = extensionProblem(entry, ctx);
7180
+ if (problem) {
7181
+ invalid(entry, problem);
7182
+ continue;
7183
+ }
7184
+ const limit = ctx.limit?.(entry);
7185
+ if (limit !== void 0 && hits.length > limit) {
7186
+ 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)`);
7187
+ continue;
7188
+ }
7189
+ for (const h of hits) covered.add(h);
7190
+ }
7191
+ const kept = findings.filter((f) => !covered.has(f)).map((f) => grew.has(f) ? { ...f, message: grew.get(f) } : f);
7192
+ return [...kept, ...out].sort(byPlace);
7193
+ }
7194
+ var byPlace = (x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule);
7195
+ var RANK2 = { info: 0, warn: 1, error: 2 };
7196
+ function dedupeFindings(findings) {
7197
+ const groups = /* @__PURE__ */ new Map();
7198
+ const order = [];
7199
+ for (const f of findings) {
7200
+ if (f.subject === void 0 || !f.line) {
7201
+ order.push([f]);
7202
+ continue;
7203
+ }
7204
+ const key2 = `${f.file}\0${f.line}\0${f.subject}`;
7205
+ const list = groups.get(key2) ?? [];
7206
+ const group = list.find((g) => !g.some((x) => x.rule === f.rule));
7207
+ if (group) group.push(f);
7208
+ else {
7209
+ const fresh = [f];
7210
+ list.push(fresh);
7211
+ groups.set(key2, list);
7212
+ order.push(fresh);
7213
+ }
7214
+ }
7215
+ return order.map((group) => {
7216
+ if (group.length === 1) return group[0];
7217
+ const primary = group.reduce((a, b) => RANK2[b.level] > RANK2[a.level] ? b : a);
7218
+ const rules = [primary.rule, ...group.filter((g) => g !== primary).map((g) => g.rule)];
7219
+ return { ...primary, rules, message: `${primary.message} (also ${rules.slice(1).join(", ")})` };
6812
7220
  });
6813
7221
  }
6814
7222
  var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
@@ -6882,7 +7290,7 @@ var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
6882
7290
  var CORE = [
6883
7291
  {
6884
7292
  need: "anything, before building it",
6885
- use: 'search what exists: `genesis features find <term>`, this catalog, and the "Available but unused" list in `genesis doctor --verbose`',
7293
+ 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',
6886
7294
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6887
7295
  from: "genesis-cli"
6888
7296
  },
@@ -6907,9 +7315,15 @@ var CORE = [
6907
7315
  rule: "raw-color",
6908
7316
  from: "genesis-cli"
6909
7317
  },
7318
+ {
7319
+ need: "a Genesis piece that is close but doesn't quite fit",
7320
+ use: "extend it: a prop, a variant, a slot, or your own component that wraps it; never a parallel copy beside it",
7321
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
7322
+ from: "genesis-cli"
7323
+ },
6910
7324
  {
6911
7325
  need: "something no primitive covers",
6912
- use: "write the gap up for Genesis (an issue or a proposal) first, then invent in the app, on Genesis primitives",
7326
+ 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",
6913
7327
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6914
7328
  from: "genesis-cli"
6915
7329
  }
@@ -6952,10 +7366,12 @@ var AGENTS_START = "<!-- genesis-primitives:start -->";
6952
7366
  var AGENTS_END = "<!-- genesis-primitives:end -->";
6953
7367
  var RULES = [
6954
7368
  `Use the Genesis primitive for the need first: reuse, then extend, then invent (G1 to G6 in ${GENESIS_DOCS}/FRAMEWORK.md).`,
7369
+ "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.",
6955
7370
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
6956
7371
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
6957
7372
  "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.",
6958
- "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
7373
+ "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.",
7374
+ "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.",
6959
7375
  "Run `genesis doctor` before you finish; it enforces these rules."
6960
7376
  ];
6961
7377
  function skillDescription(text) {
@@ -8002,14 +8418,8 @@ async function runDoctor(options = {}) {
8002
8418
  }
8003
8419
  const raw = [];
8004
8420
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
8005
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
8006
- try {
8007
- await plugin.check(ctx);
8008
- } catch (err) {
8009
- if (err instanceof DoctorConfigError) throw err;
8010
- raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
8011
- }
8012
- }
8421
+ const appChecks = [...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins];
8422
+ await runChecks(ctx, [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...appChecks]);
8013
8423
  if (options.build) {
8014
8424
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
8015
8425
  if (failure) raw.push(failure);
@@ -8019,30 +8429,57 @@ async function runDoctor(options = {}) {
8019
8429
  let changed = null;
8020
8430
  let skipped = false;
8021
8431
  const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
8022
- if (options.base && (ratchetNeeded || config.ratchet)) {
8432
+ if (options.base && (ratchetNeeded || config.ratchet || config.extend?.length)) {
8023
8433
  changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
8024
8434
  skipped ||= !changed;
8025
8435
  }
8026
8436
  const configFile = "file" in loaded ? loaded.file : null;
8027
- const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
8437
+ const guarded = (config.allow?.length ?? 0) + (config.extend?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
8028
8438
  let configSkipped = false;
8439
+ let baseExtend = [];
8029
8440
  if (options.base && configFile) {
8030
8441
  const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
8442
+ if (before && before !== "absent") baseExtend = before.extend;
8443
+ if (before === "absent") raw.push(...extensionsAdded(config.extend ?? [], [], options.base));
8031
8444
  if (before && before !== "absent") {
8032
8445
  raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
8033
8446
  raw.push(...rulesWeakened(config, before, options.base));
8447
+ raw.push(...extensionsAdded(config.extend ?? [], before.extend, options.base));
8034
8448
  }
8035
8449
  configSkipped = !before && guarded;
8036
8450
  }
8037
8451
  if (skipped || configSkipped) {
8038
8452
  raw.push(
8039
- 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` }
8453
+ 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` }
8040
8454
  );
8041
8455
  }
8042
- let findings = applyConfig(raw, config, packageRuleIds(packages));
8456
+ const packageIds = packageRuleIds(packages);
8457
+ const extensionCtx = { config, files, packages, raw };
8458
+ const configured = applyConfig(raw, config, packageIds);
8459
+ let findings = applyExtensions(configured, extensionCtx);
8043
8460
  if (options.base && changed) {
8044
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path21.join(root, f)) });
8461
+ const isAppPath = (f) => existsSync(path21.join(root, f));
8462
+ const origins = options.changedFiles ? /* @__PURE__ */ new Map() : originsSince(root, options.base);
8463
+ const originOf = (f) => origins.get(f) ?? f;
8464
+ 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));
8465
+ 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))));
8466
+ for (const e of heldExtensions) dueRules.add(e.rule);
8467
+ const snapshot = dueRules.size ? snapshotAtBase(root, options.base, files, changed, originOf) : null;
8468
+ let baseCounts;
8469
+ if (snapshot) {
8470
+ const before = [];
8471
+ await runChecks({ ...ctx, files: snapshot.files, report: (f) => before.push(f) }, baseChecks(dueRules, packageIds, packagePlugins, () => [...builtinChecks(config, { contracts: false, figma: false }), ...appChecks]));
8472
+ baseCounts = countFindings(applyConfig(before, config, packageIds));
8473
+ if (heldExtensions.length) {
8474
+ const counts = baseCounts;
8475
+ const held = new Set(heldExtensions);
8476
+ findings = applyExtensions(configured, { ...extensionCtx, limit: (e) => held.has(e) ? counts.get(countKey(originOf(e.file), e.rule)) ?? 0 : void 0 });
8477
+ }
8478
+ }
8479
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath, originOf, ...snapshot && baseCounts ? { baseCounts, existedAtBase: snapshot.existed } : {} });
8045
8480
  }
8481
+ findings = dedupeFindings(findings);
8482
+ const extensionsNew = (config.extend ?? []).filter((e) => findings.some((f) => f.rule === "extension-added" && f.file === e.file && f.subject === e.rule));
8046
8483
  const errors = findings.filter((f) => f.level === "error").length;
8047
8484
  const warnings = findings.filter((f) => f.level === "warn").length;
8048
8485
  const infos = findings.length - errors - warnings;
@@ -8056,9 +8493,24 @@ async function runDoctor(options = {}) {
8056
8493
  primitives: primitivesSummary(packages),
8057
8494
  errors,
8058
8495
  warnings,
8059
- infos
8496
+ infos,
8497
+ ...extensionsNew.length ? { extensionsAdded: extensionsNew } : {}
8060
8498
  };
8061
8499
  }
8500
+ function baseChecks(rules, preferIds, packagePlugins, all) {
8501
+ if ([...rules].every((r) => preferIds.has(r))) return packagePlugins.filter((p) => p.name === "package-rules");
8502
+ return all();
8503
+ }
8504
+ async function runChecks(ctx, checks) {
8505
+ for (const plugin of checks) {
8506
+ try {
8507
+ await plugin.check(ctx);
8508
+ } catch (err) {
8509
+ if (err instanceof DoctorConfigError) throw err;
8510
+ ctx.report({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
8511
+ }
8512
+ }
8513
+ }
8062
8514
  function builtinChecks(config, options = {}) {
8063
8515
  const packs = {
8064
8516
  native: { name: "native", check: checkNativePack },
@@ -8083,6 +8535,7 @@ function builtinChecks(config, options = {}) {
8083
8535
  { name: "resource-view-trees", check: checkTreeViews },
8084
8536
  { name: "studio-server-imports", check: checkStudioServerImports },
8085
8537
  { name: "removed-scope-names", check: checkRemovedScopeNames },
8538
+ { name: "app-parts", check: checkAppParts },
8086
8539
  { name: "stability-imports", check: checkStabilityImports },
8087
8540
  { name: "agent-guide", check: (ctx) => {
8088
8541
  checkAgentGuide(ctx);
@@ -8152,10 +8605,14 @@ function formatReport(result, options = {}) {
8152
8605
  `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"}`
8153
8606
  ];
8154
8607
  for (const f of result.findings) {
8155
- lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
8608
+ lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${(f.rules ?? [f.rule]).join(", ")}] ${f.message}`);
8156
8609
  }
8157
8610
  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)`);
8158
8611
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
8612
+ if (result.extensionsAdded?.length) {
8613
+ lines.push(`Extensions added on this branch (${result.extensionsAdded.length}); the pull request's review accepts each:`);
8614
+ for (const e of result.extensionsAdded) lines.push(` ${e.file} [${e.rule}] builds on ${e.buildsOn}: ${e.reason}${e.upstream ? ` (upstream: ${e.upstream})` : ""}`);
8615
+ }
8159
8616
  const info = result.infos ? `, ${result.infos} info` : "";
8160
8617
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
8161
8618
  return lines.join("\n");