@marktiderman/genesis-cli 1.24.0 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/doctor.js CHANGED
@@ -846,6 +846,7 @@ var KNOWN = /* @__PURE__ */ new Set([
846
846
  "forbiddenImports",
847
847
  "rules",
848
848
  "allow",
849
+ "extend",
849
850
  "patterns",
850
851
  "plugins",
851
852
  "packs",
@@ -860,7 +861,10 @@ var KNOWN = /* @__PURE__ */ new Set([
860
861
  "$comment"
861
862
  ]);
862
863
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
863
- var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
864
+ var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped", "extension-invalid"]);
865
+ var CONFIG_RULES = /* @__PURE__ */ new Set(["stale-exception", "stale-extension", "package-rule-override"]);
866
+ var EXTENSION_KEYS = /* @__PURE__ */ new Set(["rule", "file", "buildsOn", "reason", "upstream"]);
867
+ var EXTENSION_REASON_MIN = { chars: 40, words: 6 };
864
868
  var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
865
869
  var PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
866
870
  var CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
@@ -1071,6 +1075,30 @@ function validateConfig(raw, source = "config") {
1071
1075
  }
1072
1076
  });
1073
1077
  }
1078
+ if (c.extend !== void 0) {
1079
+ if (!Array.isArray(c.extend)) fail(`"extend" must be a list of { rule, file, buildsOn, reason, upstream? }`);
1080
+ const seen = /* @__PURE__ */ new Set();
1081
+ c.extend.forEach((e, i) => {
1082
+ const where2 = `extend[${i}]`;
1083
+ if (!isObject(e)) return fail(`${where2} must be an object`);
1084
+ for (const k of Object.keys(e)) if (!EXTENSION_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: ${[...EXTENSION_KEYS].join(", ")})`);
1085
+ for (const k of ["rule", "file", "buildsOn", "reason"]) if (typeof e[k] !== "string" || !e[k].trim()) fail(`${where2} needs "${k}"`);
1086
+ const { rule, file, buildsOn, reason } = e;
1087
+ if (META_RULES.has(rule) || CONFIG_RULES.has(rule)) fail(`${where2} can't extend ${rule}: it is about the config, not the app's code`);
1088
+ if (!rule.includes("/")) fail(`${where2} can't extend ${rule}: only package rules declare extension points (a built-in rule's findings are fixed, or recorded as allow debt)`);
1089
+ if (/[*?[\]{}]/.test(file)) fail(`${where2}.file must be one file, not a glob: each extension is reviewed on its own`);
1090
+ e.file = appPath(file, `${where2}.file`, fail);
1091
+ if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(buildsOn)) fail(`${where2}.buildsOn must name a Genesis export, or a part of one ("FormBuilder", "ResourceView.slots")`);
1092
+ const text = reason.trim();
1093
+ if (text.length < EXTENSION_REASON_MIN.chars || text.split(/\s+/).length < EXTENSION_REASON_MIN.words) {
1094
+ fail(`${where2} (${rule}) needs a reason of at least ${EXTENSION_REASON_MIN.words} words and ${EXTENSION_REASON_MIN.chars} characters: why the rule's primitive doesn't fit this file`);
1095
+ }
1096
+ if (e.upstream !== void 0 && (typeof e.upstream !== "string" || !e.upstream.trim())) fail(`${where2}.upstream must be a link to the gap's write-up`);
1097
+ const key2 = `${rule}\0${e.file}`;
1098
+ if (seen.has(key2)) fail(`${where2} extends ${rule} in ${e.file} twice`);
1099
+ seen.add(key2);
1100
+ });
1101
+ }
1074
1102
  if (c.patterns !== void 0) {
1075
1103
  if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
1076
1104
  c.patterns.forEach((p, i) => {
@@ -1764,6 +1792,9 @@ function scanFiles(root, config) {
1764
1792
  for (const pkg of local) walk3(pkg.dir);
1765
1793
  return files;
1766
1794
  }
1795
+ function withText(file, text) {
1796
+ return { ...file, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(file.ext)) };
1797
+ }
1767
1798
  function lineAt(text, index) {
1768
1799
  let line = 1;
1769
1800
  for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
@@ -2761,6 +2792,10 @@ var BUILTIN_RULES = [
2761
2792
  "ratchet-skipped",
2762
2793
  "allow-grew",
2763
2794
  "rules-weakened",
2795
+ "extension-added",
2796
+ // declared extensions (extensions.ts)
2797
+ "stale-extension",
2798
+ "extension-invalid",
2764
2799
  // agent guide (primitives.ts)
2765
2800
  "agent-guide-stale",
2766
2801
  // supabase pack: contracts (contracts.ts)
@@ -3049,6 +3084,34 @@ function readSource(abs) {
3049
3084
  return null;
3050
3085
  }
3051
3086
  }
3087
+ var lastBlanked = null;
3088
+ function blankStrings(code) {
3089
+ if (lastBlanked?.source === code) return lastBlanked.blanked;
3090
+ const out = code.split("");
3091
+ for (let i = 0; i < code.length; i++) {
3092
+ const ch = code[i];
3093
+ if (ch !== '"' && ch !== "'" && ch !== "`") continue;
3094
+ let j = i - 1;
3095
+ while (j >= 0 && /[ \t]/.test(code[j])) j--;
3096
+ const before = j >= 0 ? code[j] : "\n";
3097
+ const word = /[\w$]/.test(before) ? /(?:^|[^\w$])(return|case|typeof|in|of|yield|await)$/.test(code.slice(Math.max(0, j - 8), j + 1)) : false;
3098
+ if (/[\w$)\]]/.test(before) && !word) continue;
3099
+ let k = i + 1;
3100
+ for (; k < code.length; k++) {
3101
+ const c = code[k];
3102
+ if (c === "\\") {
3103
+ k++;
3104
+ continue;
3105
+ }
3106
+ if (c === ch) break;
3107
+ if (c === "\n" && ch !== "`") break;
3108
+ }
3109
+ for (let x = i + 1; x < k && x < code.length; x++) if (code[x] !== "\n") out[x] = " ";
3110
+ i = k;
3111
+ }
3112
+ lastBlanked = { source: code, blanked: out.join("") };
3113
+ return lastBlanked.blanked;
3114
+ }
3052
3115
  function tagEnd(code, start) {
3053
3116
  let depth = 0;
3054
3117
  let quote2 = null;
@@ -3070,7 +3133,8 @@ function tagEnd(code, start) {
3070
3133
  }
3071
3134
  return { end: code.length, selfClosing: false };
3072
3135
  }
3073
- function openElementsAt(code, index, track) {
3136
+ function openElementsAt(source, index, track) {
3137
+ const code = blankStrings(source);
3074
3138
  const open = [];
3075
3139
  const re = /<(\/?)([A-Z][\w.]*)(?=[\s>/])/g;
3076
3140
  for (let m = re.exec(code); m && m.index < index; m = re.exec(code)) {
@@ -3922,9 +3986,9 @@ var PackageDeclarationError = class extends Error {
3922
3986
  var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
3923
3987
  var ID = /^[a-z0-9][a-z0-9-]*$/;
3924
3988
  var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
3925
- var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
3989
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly", "extensible"]);
3926
3990
  var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
3927
- var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
3991
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "inside", "pattern"]);
3928
3992
  var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
3929
3993
  var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "catalog", "primitives", "plugin", "$comment"]);
3930
3994
  var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
@@ -4033,6 +4097,9 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4033
4097
  if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
4034
4098
  if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
4035
4099
  for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
4100
+ if (raw.extensible !== void 0 && !(isStringList2(raw.extensible) && raw.extensible.every((n) => /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)))) {
4101
+ fail(`${at}.extensible must be a list of export names, or parts of one ("ResourceView.slots")`);
4102
+ }
4036
4103
  if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
4037
4104
  const forbid = raw.forbid;
4038
4105
  for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
@@ -4045,6 +4112,7 @@ function validatePrefer(raw, where2, fail, unknownKey) {
4045
4112
  const unless = raw.unless;
4046
4113
  for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
4047
4114
  if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
4115
+ if (unless.inside !== void 0 && !(isStringList2(unless.inside) && unless.inside.every((n) => /^[A-Z][\w.]*$/.test(n)))) fail(`${at}.unless.inside must be a list of component names`);
4048
4116
  if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
4049
4117
  }
4050
4118
  return raw;
@@ -4162,6 +4230,7 @@ function compile(rule, setting, routes) {
4162
4230
  imports: (rule.forbid.imports ?? []).map(specMatcher),
4163
4231
  ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
4164
4232
  unlessRenders: new Set(rule.unless?.renders ?? []),
4233
+ unlessInside: new Set(rule.unless?.inside ?? []),
4165
4234
  ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
4166
4235
  };
4167
4236
  }
@@ -4173,10 +4242,11 @@ function messageFor(rule, found) {
4173
4242
  const docs = rule.docs ? ` See ${rule.docs}` : "";
4174
4243
  return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
4175
4244
  }
4245
+ var CHILDREN = /\{\s*(?:props\.)?children\s*\}/g;
4176
4246
  var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
4177
4247
  var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
4178
4248
  var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
4179
- function wrappersIn(file, elements, c) {
4249
+ function wrappersIn(file, elements, names, accept) {
4180
4250
  const out = /* @__PURE__ */ new Map();
4181
4251
  const decls = [...file.code.matchAll(TOP_LEVEL)];
4182
4252
  const listed = /* @__PURE__ */ new Map();
@@ -4189,12 +4259,12 @@ function wrappersIn(file, elements, c) {
4189
4259
  for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
4190
4260
  decls.forEach((d, i) => {
4191
4261
  const name = d[3];
4192
- if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
4262
+ if (!/^[A-Z]/.test(name) || names.has(name)) return;
4193
4263
  const end = decls[i + 1]?.index ?? file.code.length;
4194
- const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
4195
- if (!hit) return;
4196
- const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4197
- for (const n of names) out.set(n, hit[1]);
4264
+ const hit = elements.find((m) => m.index > d.index && m.index < end && names.has(m[1]));
4265
+ if (!hit || accept && !accept(d.index, end)) return;
4266
+ const exported = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4267
+ for (const n of exported) out.set(n, hit[1]);
4198
4268
  });
4199
4269
  return out;
4200
4270
  }
@@ -4202,6 +4272,32 @@ function runPrefer(ctx, c) {
4202
4272
  const own = c.rule.packageDir;
4203
4273
  const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
4204
4274
  const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
4275
+ const scanned = new Map(ctx.files.map((f) => [f.absolutePath, f]));
4276
+ const importedBy = /* @__PURE__ */ new Map();
4277
+ const importsOf = (file) => {
4278
+ if (!importedBy.has(file)) importedBy.set(file, localImportedNames(ctx.root, file));
4279
+ return importedBy.get(file);
4280
+ };
4281
+ const builders = /* @__PURE__ */ new Map();
4282
+ const buildersIn = (abs) => {
4283
+ if (!builders.has(abs)) {
4284
+ const target = scanned.get(abs) ?? readSource(abs);
4285
+ const code = target ? "ext" in target ? target.code : stripBlockComments(target.code, true) : "";
4286
+ const childrenInside = (start, end) => [...code.slice(start, end).matchAll(CHILDREN)].some((m) => openElementsAt(code, start + m.index, (n) => c.unlessInside.has(n)).length > 0);
4287
+ builders.set(abs, code ? wrappersIn({ code }, [...code.matchAll(ELEMENT)], c.unlessInside, childrenInside) : /* @__PURE__ */ new Map());
4288
+ }
4289
+ return builders.get(abs);
4290
+ };
4291
+ const nestedInBuilder = (file, index) => {
4292
+ if (!c.unlessInside.size) return false;
4293
+ const imported = importsOf(file);
4294
+ const isBuilder = (name) => {
4295
+ if (c.unlessInside.has(name)) return true;
4296
+ const from = name.includes(".") ? void 0 : imported.get(name);
4297
+ return from !== void 0 && buildersIn(from.file).has(from.name);
4298
+ };
4299
+ return openElementsAt(file.code, index, isBuilder).length > 0;
4300
+ };
4205
4301
  const wrappers = /* @__PURE__ */ new Map();
4206
4302
  const renderedBy = /* @__PURE__ */ new Map();
4207
4303
  for (const file of checked) {
@@ -4209,16 +4305,17 @@ function runPrefer(ctx, c) {
4209
4305
  const elements = [...file.code.matchAll(ELEMENT)];
4210
4306
  renderedBy.set(file, elements);
4211
4307
  if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
4212
- const found = wrappersIn(file, elements, c);
4308
+ const found = wrappersIn(file, elements, c.jsx);
4213
4309
  if (found.size) wrappers.set(file.absolutePath, found);
4214
4310
  }
4215
4311
  for (const file of checked) {
4216
4312
  const elements = renderedBy.get(file) ?? [];
4217
4313
  if (exempt(file, elements.map((m) => m[1]))) continue;
4218
4314
  const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
4219
- const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
4315
+ const imported = wrappers.size && elements.length ? importsOf(file) : null;
4220
4316
  for (const m of elements) {
4221
4317
  const name = m[1];
4318
+ if (nestedInBuilder(file, m.index)) continue;
4222
4319
  if (c.jsx.has(name)) {
4223
4320
  report(lineAt(file.code, m.index), name, `renders <${name}>`);
4224
4321
  continue;
@@ -4235,6 +4332,7 @@ function runPrefer(ctx, c) {
4235
4332
  if (c.pattern) {
4236
4333
  c.pattern.lastIndex = 0;
4237
4334
  for (const m of file.code.matchAll(c.pattern)) {
4335
+ if (nestedInBuilder(file, m.index)) continue;
4238
4336
  const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
4239
4337
  report(lineAt(file.code, m.index), text, `has ${text}`);
4240
4338
  }
@@ -6030,13 +6128,34 @@ function git3(root, args) {
6030
6128
  return r.status === 0 ? r.stdout : null;
6031
6129
  }
6032
6130
  function changedSince(root, base) {
6033
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6131
+ const mergeBase = mergeBaseOf2(root, base);
6034
6132
  if (!mergeBase) return null;
6035
6133
  const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
6036
6134
  const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
6037
6135
  if (committed === null || untracked === null) return null;
6038
6136
  return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
6039
6137
  }
6138
+ function originsSince(root, base) {
6139
+ const out = /* @__PURE__ */ new Map();
6140
+ const mergeBase = mergeBaseOf2(root, base);
6141
+ if (!mergeBase) return out;
6142
+ const diff = git3(root, ["diff", "-z", "-M", "--name-status", "--relative", mergeBase, "--"]);
6143
+ if (diff === null) return out;
6144
+ const parts = diff.split("\0");
6145
+ for (let i = 0; i < parts.length; ) {
6146
+ const status = parts[i++] ?? "";
6147
+ if (!status) continue;
6148
+ if (status.startsWith("R") || status.startsWith("C")) {
6149
+ const from = parts[i++];
6150
+ const to = parts[i++];
6151
+ if (status.startsWith("R")) out.set(to, from);
6152
+ } else i++;
6153
+ }
6154
+ return out;
6155
+ }
6156
+ function mergeBaseOf2(root, base) {
6157
+ return git3(root, ["merge-base", base, "HEAD"])?.trim() || null;
6158
+ }
6040
6159
  var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
6041
6160
  function showAt(dir, rev, file) {
6042
6161
  const at = `${rev}:./${file}`;
@@ -6044,7 +6163,7 @@ function showAt(dir, rev, file) {
6044
6163
  return git3(dir, ["show", at]);
6045
6164
  }
6046
6165
  function configAtBase(root, base, explicitFile) {
6047
- const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6166
+ const mergeBase = mergeBaseOf2(root, base);
6048
6167
  if (!mergeBase) return null;
6049
6168
  const candidates = explicitFile ? [{ dir: path21.dirname(explicitFile), file: path21.basename(explicitFile), explicit: true }] : [
6050
6169
  { dir: root, file: "genesis.config.json", explicit: false },
@@ -6065,7 +6184,12 @@ function configAtBase(root, base, explicitFile) {
6065
6184
  continue;
6066
6185
  }
6067
6186
  const b = objectOr(block);
6068
- return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
6187
+ return {
6188
+ allow: Array.isArray(b.allow) ? b.allow : [],
6189
+ extend: Array.isArray(b.extend) ? b.extend : [],
6190
+ rules: objectOr(b.rules),
6191
+ packageRules: objectOr(b.packageRules)
6192
+ };
6069
6193
  }
6070
6194
  return "absent";
6071
6195
  }
@@ -6079,6 +6203,16 @@ function allowGrew(allow, before, base) {
6079
6203
  message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
6080
6204
  }));
6081
6205
  }
6206
+ function extensionsAdded(extend, before, base) {
6207
+ const had = new Set(before.map((e) => `${e.rule}\0${e.file}\0${e.buildsOn}`));
6208
+ return extend.filter((e) => !had.has(`${e.rule}\0${e.file}\0${e.buildsOn}`)).map((e) => ({
6209
+ rule: "extension-added",
6210
+ level: "info",
6211
+ file: e.file,
6212
+ subject: e.rule,
6213
+ 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`
6214
+ }));
6215
+ }
6082
6216
  var RANK = { off: 0, info: 1, warn: 2, error: 3 };
6083
6217
  function rulesWeakened(config, before, base) {
6084
6218
  const out = [];
@@ -6116,14 +6250,169 @@ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
6116
6250
  "plugin-error",
6117
6251
  "build",
6118
6252
  "agent-guide-stale",
6119
- "contracts-stale"
6253
+ "contracts-stale",
6254
+ "stale-extension",
6255
+ "extension-added"
6120
6256
  ]);
6257
+ function isRatcheted(rule, config, newOnly) {
6258
+ return !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6259
+ }
6260
+ var countKey = (file, rule) => `${file}\0${rule}`;
6261
+ function countFindings(findings) {
6262
+ const counts = /* @__PURE__ */ new Map();
6263
+ for (const f of findings) counts.set(countKey(f.file, f.rule), (counts.get(countKey(f.file, f.rule)) ?? 0) + 1);
6264
+ return counts;
6265
+ }
6121
6266
  function applyRatchet(findings, options) {
6122
- const { config, newOnly, changed, base, isAppPath } = options;
6123
- const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6267
+ const { config, newOnly, changed, base, isAppPath, baseCounts, existedAtBase } = options;
6268
+ const originOf = options.originOf ?? ((f) => f);
6269
+ const counts = countFindings(findings.map((f) => ({ file: originOf(f.file), rule: f.rule })));
6124
6270
  return findings.map((f) => {
6125
- if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
6126
- return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6271
+ if (f.level === "info" || !isRatcheted(f.rule, config, newOnly) || !isAppPath(f.file)) return f;
6272
+ if (!touched(f.file, changed)) return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6273
+ const origin = originOf(f.file);
6274
+ if (!baseCounts || !existedAtBase?.(origin)) return f;
6275
+ const now = counts.get(countKey(origin, f.rule)) ?? 0;
6276
+ const was = baseCounts.get(countKey(origin, f.rule)) ?? 0;
6277
+ const where2 = origin === f.file ? "this file" : `the files from ${origin}`;
6278
+ 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)` };
6279
+ return { ...f, level: "info", message: `${f.message} (ratcheted: ${now} in ${where2}, ${was} at the merge base with ${base})` };
6280
+ });
6281
+ }
6282
+ function snapshotAtBase(root, base, files, changed, originOf = (f) => f) {
6283
+ const mergeBase = mergeBaseOf2(root, base);
6284
+ if (!mergeBase) return null;
6285
+ const out = [];
6286
+ const seen = /* @__PURE__ */ new Set();
6287
+ for (const f of files) {
6288
+ if (!changed.has(f.path)) {
6289
+ if (!seen.has(f.path)) out.push(f);
6290
+ seen.add(f.path);
6291
+ continue;
6292
+ }
6293
+ const origin = originOf(f.path);
6294
+ if (seen.has(origin)) continue;
6295
+ seen.add(origin);
6296
+ const text = showAt(root, mergeBase, origin);
6297
+ if (text === null) return null;
6298
+ if (text !== void 0) out.push(withText({ ...f, path: origin, absolutePath: path21.join(root, origin) }, text));
6299
+ }
6300
+ const cache2 = /* @__PURE__ */ new Map();
6301
+ return {
6302
+ mergeBase,
6303
+ files: out,
6304
+ existed(file) {
6305
+ if (!cache2.has(file)) cache2.set(file, git3(root, ["cat-file", "-e", `${mergeBase}:./${file}`]) !== null);
6306
+ return cache2.get(file);
6307
+ }
6308
+ };
6309
+ }
6310
+
6311
+ // src/doctor/extensions.ts
6312
+ function pointProblem(entry, packages) {
6313
+ const rule = preferRules(packages).find((r) => r.ruleId === entry.rule);
6314
+ if (!rule?.extensible?.length) return `${entry.rule} declares no extension points, so it can't be extended (debt goes in allow, and is fixed)`;
6315
+ if (!rule.extensible.includes(entry.buildsOn)) return `${entry.buildsOn} isn't one of ${entry.rule}'s extension points (${rule.extensible.join(", ")})`;
6316
+ return null;
6317
+ }
6318
+ function extensionProblem(entry, ctx) {
6319
+ const point = pointProblem(entry, ctx.packages);
6320
+ if (point) return point;
6321
+ const name = entry.buildsOn.split(".")[0];
6322
+ const replaces = preferRules(ctx.packages).find((r) => r.forbid.jsx?.includes(name));
6323
+ if (replaces) return `${name} is what ${replaces.ruleId} replaces (use ${replaces.use}); a legacy component can't be built on`;
6324
+ const flagged = ctx.raw.find((f) => f.file === entry.file && f.subject === name);
6325
+ if (flagged) return `${name} is flagged in this file by ${flagged.rule}; build on a current Genesis primitive`;
6326
+ const file = ctx.files.find((f) => f.path === entry.file);
6327
+ if (!file) return `${entry.file} isn't one of the files the doctor scans`;
6328
+ const imported = genesisNamedImports(file.code).some((i) => i.names.includes(name));
6329
+ if (!imported) return `${entry.file} doesn't import ${name} from a Genesis package; buildsOn names the extension point the file uses`;
6330
+ if (!usesPoint(blankStrings(file.code), entry.buildsOn)) {
6331
+ const prop = entry.buildsOn.split(".")[1];
6332
+ 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`;
6333
+ }
6334
+ return null;
6335
+ }
6336
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6337
+ function usesPoint(code, point) {
6338
+ const [name, prop] = point.split(".");
6339
+ const n = escape2(name);
6340
+ if (!prop) return new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])|(?<![\\w$.])${n}\\s*(?:<[^>()]*>)?\\s*\\(`).test(code);
6341
+ for (const m of code.matchAll(new RegExp(`(?<![\\w$.])<${n}(?=[\\s>/<])`, "g"))) {
6342
+ const { end } = tagEnd(code, m.index);
6343
+ if (new RegExp(`(?<![\\w$.])${escape2(prop)}\\s*=`).test(code.slice(m.index, end))) return true;
6344
+ }
6345
+ return false;
6346
+ }
6347
+ function applyExtensions(findings, ctx) {
6348
+ const entries = ctx.config.extend ?? [];
6349
+ if (!entries.length) return findings;
6350
+ const staleLevel = ctx.config.rules?.["stale-extension"];
6351
+ const covered = /* @__PURE__ */ new Set();
6352
+ const grew = /* @__PURE__ */ new Map();
6353
+ const out = [];
6354
+ 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}` });
6355
+ for (const entry of entries) {
6356
+ if (ctx.config.rules?.[entry.rule] === "off" || ctx.config.packageRules?.[entry.rule]?.level === "off") continue;
6357
+ const point = pointProblem(entry, ctx.packages);
6358
+ if (point) {
6359
+ invalid(entry, point);
6360
+ continue;
6361
+ }
6362
+ const hits = findings.filter((f) => f.rule === entry.rule && f.file === entry.file);
6363
+ if (!hits.length) {
6364
+ if (staleLevel === "off") continue;
6365
+ out.push({
6366
+ rule: "stale-extension",
6367
+ level: staleLevel ?? "warn",
6368
+ file: entry.file,
6369
+ line: 0,
6370
+ subject: entry.rule,
6371
+ message: `the extension of ${entry.rule} (building on ${entry.buildsOn}) no longer matches a finding in this file; remove it from doctor.extend`
6372
+ });
6373
+ continue;
6374
+ }
6375
+ const problem = extensionProblem(entry, ctx);
6376
+ if (problem) {
6377
+ invalid(entry, problem);
6378
+ continue;
6379
+ }
6380
+ const limit = ctx.limit?.(entry);
6381
+ if (limit !== void 0 && hits.length > limit) {
6382
+ 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)`);
6383
+ continue;
6384
+ }
6385
+ for (const h of hits) covered.add(h);
6386
+ }
6387
+ const kept = findings.filter((f) => !covered.has(f)).map((f) => grew.has(f) ? { ...f, message: grew.get(f) } : f);
6388
+ return [...kept, ...out].sort(byPlace);
6389
+ }
6390
+ var byPlace = (x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule);
6391
+ var RANK2 = { info: 0, warn: 1, error: 2 };
6392
+ function dedupeFindings(findings) {
6393
+ const groups = /* @__PURE__ */ new Map();
6394
+ const order = [];
6395
+ for (const f of findings) {
6396
+ if (f.subject === void 0 || !f.line) {
6397
+ order.push([f]);
6398
+ continue;
6399
+ }
6400
+ const key2 = `${f.file}\0${f.line}\0${f.subject}`;
6401
+ const list = groups.get(key2) ?? [];
6402
+ const group = list.find((g) => !g.some((x) => x.rule === f.rule));
6403
+ if (group) group.push(f);
6404
+ else {
6405
+ const fresh = [f];
6406
+ list.push(fresh);
6407
+ groups.set(key2, list);
6408
+ order.push(fresh);
6409
+ }
6410
+ }
6411
+ return order.map((group) => {
6412
+ if (group.length === 1) return group[0];
6413
+ const primary = group.reduce((a, b) => RANK2[b.level] > RANK2[a.level] ? b : a);
6414
+ const rules = [primary.rule, ...group.filter((g) => g !== primary).map((g) => g.rule)];
6415
+ return { ...primary, rules, message: `${primary.message} (also ${rules.slice(1).join(", ")})` };
6127
6416
  });
6128
6417
  }
6129
6418
  var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
@@ -7421,14 +7710,8 @@ async function runDoctor(options = {}) {
7421
7710
  }
7422
7711
  const raw = [];
7423
7712
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
7424
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
7425
- try {
7426
- await plugin.check(ctx);
7427
- } catch (err) {
7428
- if (err instanceof DoctorConfigError) throw err;
7429
- raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7430
- }
7431
- }
7713
+ const appChecks = [...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins];
7714
+ await runChecks(ctx, [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...appChecks]);
7432
7715
  if (options.build) {
7433
7716
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
7434
7717
  if (failure) raw.push(failure);
@@ -7438,30 +7721,57 @@ async function runDoctor(options = {}) {
7438
7721
  let changed = null;
7439
7722
  let skipped = false;
7440
7723
  const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
7441
- if (options.base && (ratchetNeeded || config.ratchet)) {
7724
+ if (options.base && (ratchetNeeded || config.ratchet || config.extend?.length)) {
7442
7725
  changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
7443
7726
  skipped ||= !changed;
7444
7727
  }
7445
7728
  const configFile = "file" in loaded ? loaded.file : null;
7446
- const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7729
+ const guarded = (config.allow?.length ?? 0) + (config.extend?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7447
7730
  let configSkipped = false;
7731
+ let baseExtend = [];
7448
7732
  if (options.base && configFile) {
7449
7733
  const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
7734
+ if (before && before !== "absent") baseExtend = before.extend;
7735
+ if (before === "absent") raw.push(...extensionsAdded(config.extend ?? [], [], options.base));
7450
7736
  if (before && before !== "absent") {
7451
7737
  raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
7452
7738
  raw.push(...rulesWeakened(config, before, options.base));
7739
+ raw.push(...extensionsAdded(config.extend ?? [], before.extend, options.base));
7453
7740
  }
7454
7741
  configSkipped = !before && guarded;
7455
7742
  }
7456
7743
  if (skipped || configSkipped) {
7457
7744
  raw.push(
7458
- configSkipped ? { rule: "ratchet-skipped", level: "error", file: "genesis config", message: `couldn't compare allow, rules and packageRules against ${options.base} (not a git repository, or the ref isn't fetched; in CI check out with fetch-depth: 0)` } : { rule: "ratchet-skipped", level: "warn", file: "genesis config", message: `couldn't compare against ${options.base} (not a git repository, or the ref isn't fetched); every rule ran at its full level` }
7745
+ configSkipped ? { rule: "ratchet-skipped", level: "error", file: "genesis config", message: `couldn't compare allow, extend, rules and packageRules against ${options.base} (not a git repository, or the ref isn't fetched; in CI check out with fetch-depth: 0)` } : { rule: "ratchet-skipped", level: "warn", file: "genesis config", message: `couldn't compare against ${options.base} (not a git repository, or the ref isn't fetched); every rule ran at its full level` }
7459
7746
  );
7460
7747
  }
7461
- let findings = applyConfig(raw, config, packageRuleIds(packages));
7748
+ const packageIds = packageRuleIds(packages);
7749
+ const extensionCtx = { config, files, packages, raw };
7750
+ const configured = applyConfig(raw, config, packageIds);
7751
+ let findings = applyExtensions(configured, extensionCtx);
7462
7752
  if (options.base && changed) {
7463
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path21.join(root, f)) });
7753
+ const isAppPath = (f) => existsSync(path21.join(root, f));
7754
+ const origins = options.changedFiles ? /* @__PURE__ */ new Map() : originsSince(root, options.base);
7755
+ const originOf = (f) => origins.get(f) ?? f;
7756
+ 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));
7757
+ 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))));
7758
+ for (const e of heldExtensions) dueRules.add(e.rule);
7759
+ const snapshot = dueRules.size ? snapshotAtBase(root, options.base, files, changed, originOf) : null;
7760
+ let baseCounts;
7761
+ if (snapshot) {
7762
+ const before = [];
7763
+ await runChecks({ ...ctx, files: snapshot.files, report: (f) => before.push(f) }, baseChecks(dueRules, packageIds, packagePlugins, () => [...builtinChecks(config, { contracts: false, figma: false }), ...appChecks]));
7764
+ baseCounts = countFindings(applyConfig(before, config, packageIds));
7765
+ if (heldExtensions.length) {
7766
+ const counts = baseCounts;
7767
+ const held = new Set(heldExtensions);
7768
+ findings = applyExtensions(configured, { ...extensionCtx, limit: (e) => held.has(e) ? counts.get(countKey(originOf(e.file), e.rule)) ?? 0 : void 0 });
7769
+ }
7770
+ }
7771
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath, originOf, ...snapshot && baseCounts ? { baseCounts, existedAtBase: snapshot.existed } : {} });
7464
7772
  }
7773
+ findings = dedupeFindings(findings);
7774
+ const extensionsNew = (config.extend ?? []).filter((e) => findings.some((f) => f.rule === "extension-added" && f.file === e.file && f.subject === e.rule));
7465
7775
  const errors = findings.filter((f) => f.level === "error").length;
7466
7776
  const warnings = findings.filter((f) => f.level === "warn").length;
7467
7777
  const infos = findings.length - errors - warnings;
@@ -7475,9 +7785,24 @@ async function runDoctor(options = {}) {
7475
7785
  primitives: primitivesSummary(packages),
7476
7786
  errors,
7477
7787
  warnings,
7478
- infos
7788
+ infos,
7789
+ ...extensionsNew.length ? { extensionsAdded: extensionsNew } : {}
7479
7790
  };
7480
7791
  }
7792
+ function baseChecks(rules, preferIds, packagePlugins, all) {
7793
+ if ([...rules].every((r) => preferIds.has(r))) return packagePlugins.filter((p) => p.name === "package-rules");
7794
+ return all();
7795
+ }
7796
+ async function runChecks(ctx, checks) {
7797
+ for (const plugin of checks) {
7798
+ try {
7799
+ await plugin.check(ctx);
7800
+ } catch (err) {
7801
+ if (err instanceof DoctorConfigError) throw err;
7802
+ ctx.report({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7803
+ }
7804
+ }
7805
+ }
7481
7806
  function builtinChecks(config, options = {}) {
7482
7807
  const packs = {
7483
7808
  native: { name: "native", check: checkNativePack },
@@ -7571,10 +7896,14 @@ function formatReport(result, options = {}) {
7571
7896
  `Genesis doctor: ${g.uiPackage}@${g.uiVersion}, ${g.components.length} components, ${g.tokens.size} tokens, ${result.ruleCount} app rules; raw tags checked: ${[...g.rawTags.keys()].join(", ") || "none"}`
7572
7897
  ];
7573
7898
  for (const f of result.findings) {
7574
- lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
7899
+ lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${(f.rules ?? [f.rule]).join(", ")}] ${f.message}`);
7575
7900
  }
7576
7901
  lines.push(options.verbose ? `Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}` : `Available but unused: ${result.unused.length} (genesis doctor --verbose lists them)`);
7577
7902
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
7903
+ if (result.extensionsAdded?.length) {
7904
+ lines.push(`Extensions added on this branch (${result.extensionsAdded.length}); the pull request's review accepts each:`);
7905
+ for (const e of result.extensionsAdded) lines.push(` ${e.file} [${e.rule}] builds on ${e.buildsOn}: ${e.reason}${e.upstream ? ` (upstream: ${e.upstream})` : ""}`);
7906
+ }
7578
7907
  const info = result.infos ? `, ${result.infos} info` : "";
7579
7908
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
7580
7909
  return lines.join("\n");
@@ -7588,7 +7917,8 @@ function toJson(result) {
7588
7917
  infos: result.infos,
7589
7918
  findings: result.findings,
7590
7919
  unused: result.unused,
7591
- primitives: result.primitives
7920
+ primitives: result.primitives,
7921
+ ...result.extensionsAdded ? { extensionsAdded: result.extensionsAdded } : {}
7592
7922
  };
7593
7923
  }
7594
7924
  function genesisSummary(g) {
@@ -7602,6 +7932,6 @@ function genesisSummary(g) {
7602
7932
  };
7603
7933
  }
7604
7934
 
7605
- export { BLOCKED_FIX, BUILTIN_RULES, CLAUDE_IMPORT, DENY_RULES, DoctorConfigError, GenesisConfigError, PackageDeclarationError, SETTINGS_PATH, SKILL_PATH, SUBAGENT_HOOK_COMMAND, agentGuideState, agentHooksState, agentRules, builtinChecks, catalogTable, changedSince, clearPackageRulesCache, defineDoctorPlugin, discoverPackages, findPackageDir, formatPrimitives, formatReport, genesisInstalls, genesisSummary, globToRegExp, loadConfig, loadGenesis, mergeAgentHooks, nativeLayouts, packageGuides, parseExportNames, parseRulesMarkdown, postgresContract, postgresSource, preferRules, primitivesCatalog, primitivesSummary, readGenesisConfig, readPackageExports, readReleaseManifest, renderAgentsBlock, renderSkill, routesDir, ruleNamespace, runDoctor, satisfies, skillDescription, sqlStatements, subagentContext, subagentHookOutput, toJson, unlistedGuides, validateConfig, validateDeclaration, validateLinks, webRoutes, writeAgentGuide, writeAgentHooks };
7935
+ export { BLOCKED_FIX, BUILTIN_RULES, CLAUDE_IMPORT, DENY_RULES, DoctorConfigError, GenesisConfigError, PackageDeclarationError, SETTINGS_PATH, SKILL_PATH, SUBAGENT_HOOK_COMMAND, agentGuideState, agentHooksState, agentRules, applyExtensions, builtinChecks, catalogTable, changedSince, clearPackageRulesCache, dedupeFindings, defineDoctorPlugin, discoverPackages, extensionProblem, findPackageDir, formatPrimitives, formatReport, genesisInstalls, genesisSummary, globToRegExp, loadConfig, loadGenesis, mergeAgentHooks, nativeLayouts, packageGuides, parseExportNames, parseRulesMarkdown, postgresContract, postgresSource, preferRules, primitivesCatalog, primitivesSummary, readGenesisConfig, readPackageExports, readReleaseManifest, renderAgentsBlock, renderSkill, routesDir, ruleNamespace, runDoctor, satisfies, skillDescription, sqlStatements, subagentContext, subagentHookOutput, toJson, unlistedGuides, validateConfig, validateDeclaration, validateLinks, webRoutes, writeAgentGuide, writeAgentHooks };
7606
7936
  //# sourceMappingURL=doctor.js.map
7607
7937
  //# sourceMappingURL=doctor.js.map