ctxmedic 0.11.0 → 0.12.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/README.md CHANGED
@@ -145,6 +145,17 @@ telemetry, no update checks.
145
145
  - The UI server (`ctxmedic ui`) listens on `127.0.0.1` only and requires a
146
146
  per-run token for writes.
147
147
 
148
+ **Plugins**
149
+ - `"plugins": ["ctxmedic-plugin-foo"]` in `ctxmedic.config.json` adds rules from
150
+ npm packages in your project's own `node_modules`. ctxmedic never installs or
151
+ downloads them.
152
+ - They load only when you pass `--plugins` (or set `CTXMEDIC_PLUGINS=1`) on that
153
+ run; a checked-in config alone never runs plugin code. Without the flag, the
154
+ report names the plugins it skipped.
155
+ - A loaded plugin runs with ctxmedic's own rights: it can read files and open
156
+ network connections, and ctxmedic does not sandbox it. Load only plugins you
157
+ trust. The report lists every loaded plugin with its version (ADR-027).
158
+
148
159
  Secrets found in configs are always masked in output. To verify that the npm
149
160
  package was built from this repo by CI, run `npm audit signatures`.
150
161
 
package/dist/index.js CHANGED
@@ -2,19 +2,19 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { spawn } from "child_process";
5
- import path16 from "path";
5
+ import path17 from "path";
6
6
  import { fileURLToPath } from "url";
7
7
  import * as p2 from "@clack/prompts";
8
8
  import { Command } from "commander";
9
9
  import pc2 from "picocolors";
10
10
 
11
11
  // ../clinical/src/schema.ts
12
- import { z as z6 } from "zod";
12
+ import { z as z7 } from "zod";
13
13
 
14
14
  // ../core/src/schema.ts
15
15
  import { z } from "zod";
16
16
  var Severity = z.enum(["critical", "warning", "info"]);
17
- var RuleId = z.enum([
17
+ var BuiltinRuleId = z.enum([
18
18
  "ERR_BROKEN_LINK",
19
19
  "WARN_CONTEXT_BLOAT",
20
20
  "WARN_DUPLICATE_RULES",
@@ -28,6 +28,9 @@ var RuleId = z.enum([
28
28
  "FIN_CONTEXT_SNOWBALL",
29
29
  "FIN_CACHE_MISS"
30
30
  ]);
31
+ var EXTERNAL_RULE_ID = /^[a-z][a-z0-9-]*\/[A-Z][A-Z0-9_]*$/;
32
+ var ExternalRuleId = z.string().regex(EXTERNAL_RULE_ID, "external rule ids look like plugin/RULE_NAME").transform((s) => s);
33
+ var RuleId = z.union([BuiltinRuleId, ExternalRuleId]);
31
34
  var FixOp = z.discriminatedUnion("kind", [
32
35
  z.object({ kind: z.literal("write"), path: z.string(), content: z.string() }),
33
36
  z.object({ kind: z.literal("symlink"), path: z.string(), target: z.string() })
@@ -145,6 +148,12 @@ var ConfigGraph = z.object({
145
148
  nodes: z.array(GraphNode),
146
149
  edges: z.array(z.object({ source: z.string(), target: z.string(), kind: z.enum(["loads", "symlink", "duplicate"]) }))
147
150
  });
151
+ var PluginInfo = z.object({
152
+ name: z.string(),
153
+ version: z.string().optional(),
154
+ loaded: z.boolean(),
155
+ rules: z.array(RuleId)
156
+ });
148
157
 
149
158
  // ../core/src/paths.ts
150
159
  import os from "os";
@@ -796,8 +805,8 @@ var unusedDisableMeta = {
796
805
  docs: docsUrl("INFO_UNUSED_DISABLE"),
797
806
  fixable: false
798
807
  };
799
- var allRuleMeta = () => [
800
- ...rules.map((r) => [r.id, r.meta, "config"]),
808
+ var allRuleMeta = (extraRules = []) => [
809
+ ...[...rules, ...extraRules].map((r) => [r.id, r.meta, "config"]),
801
810
  ["INFO_UNUSED_DISABLE", unusedDisableMeta, "config"],
802
811
  ...Object.entries(finopsMeta).map(([id, meta2]) => [id, meta2, "session-logs"])
803
812
  ];
@@ -952,7 +961,9 @@ var CtxmedicConfig = z5.object({
952
961
  extends: z5.union([Preset, z5.array(Preset)]).optional(),
953
962
  rules: z5.partialRecord(RuleId, RuleEntry).default({}),
954
963
  /** Globs over finding paths (project-relative, or `~/` for global files). */
955
- ignores: z5.array(z5.string()).default([])
964
+ ignores: z5.array(z5.string()).default([]),
965
+ /** npm packages in the project's node_modules that add rules; loaded only with `--plugins` (ADR-027). */
966
+ plugins: z5.array(z5.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/, "an npm package name")).default([])
956
967
  });
957
968
  var ConfigError = class extends Error {
958
969
  };
@@ -985,8 +996,8 @@ var RuleInfo = z5.object({
985
996
  /** Options the config set to a value other than the default. */
986
997
  changed: z5.record(z5.string(), z5.unknown())
987
998
  });
988
- function describeRules(config) {
989
- return allRuleMeta().map(([id, meta2, source]) => {
999
+ function describeRules(config, extraRules = []) {
1000
+ return allRuleMeta(extraRules).map(([id, meta2, source]) => {
990
1001
  const entry = config.rules[id];
991
1002
  const options = meta2.options?.parse(optionsOf(entry)) ?? {};
992
1003
  const defaults = meta2.options?.parse({}) ?? {};
@@ -994,7 +1005,7 @@ function describeRules(config) {
994
1005
  return RuleInfo.parse({ id, source, level: levelOf(entry), type: meta2.type, fixable: meta2.fixable, description: meta2.description, docs: meta2.docs, options, changed });
995
1006
  });
996
1007
  }
997
- function loadConfig(root) {
1008
+ function loadConfig(root, extraRules = []) {
998
1009
  const file2 = path9.join(root, CONFIG_FILE);
999
1010
  if (!fs6.existsSync(file2)) return CtxmedicConfig.parse({});
1000
1011
  let raw;
@@ -1009,7 +1020,9 @@ function loadConfig(root) {
1009
1020
  for (const [id, entry] of Object.entries(config.rules)) {
1010
1021
  const opts = optionsOf(entry);
1011
1022
  if (!Object.keys(opts).length) continue;
1012
- const schema = allRuleMeta().find(([x]) => x === id)?.[1].options;
1023
+ const known = allRuleMeta(extraRules).find(([x]) => x === id);
1024
+ if (!known && id.includes("/")) continue;
1025
+ const schema = known?.[1].options;
1013
1026
  if (!schema) throw new ConfigError(`${CONFIG_FILE}: rule ${id} takes no options`);
1014
1027
  const o2 = schema.safeParse(opts);
1015
1028
  if (!o2.success) throw new ConfigError(`${CONFIG_FILE}: rule ${id}: ${z5.prettifyError(o2.error)}`);
@@ -1069,13 +1082,14 @@ function applyConfig(findings, files, config, opts = {}) {
1069
1082
  // ../core/src/examine.ts
1070
1083
  async function examine(root, profiles, opts = {}) {
1071
1084
  root = path10.resolve(root);
1072
- const config = loadConfig(root);
1085
+ const extraRules = opts.extraRules ?? [];
1086
+ const config = loadConfig(root, extraRules);
1073
1087
  const files = await scan(root, profiles, opts);
1074
1088
  const startup = startupLoad(files, profiles);
1075
1089
  const entries = Object.entries(config.rules);
1076
1090
  const off = new Set(entries.filter(([, e]) => levelOf(e) === "off").map(([id]) => id));
1077
1091
  const options = Object.fromEntries(entries.map(([id, e]) => [id, optionsOf(e)]));
1078
- const findings = applyConfig(await runRules({ root, files, profiles, startup }, void 0, options, off), files, config, { reportUnused: true });
1092
+ const findings = applyConfig(await runRules({ root, files, profiles, startup }, [...rules, ...extraRules], options, off), files, config, { reportUnused: true });
1079
1093
  const vitals2 = PatientVitals.parse({
1080
1094
  root,
1081
1095
  scannedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -1086,84 +1100,131 @@ async function examine(root, profiles, opts = {}) {
1086
1100
  return { vitals: vitals2, files, startup, findings, config };
1087
1101
  }
1088
1102
 
1103
+ // ../core/src/plugins.ts
1104
+ import fs7 from "fs";
1105
+ import path11 from "path";
1106
+ import { pathToFileURL } from "url";
1107
+ import { z as z6 } from "zod";
1108
+ var fn = z6.custom((v) => typeof v === "function", "a function");
1109
+ var PluginRule = z6.object({
1110
+ id: z6.string().regex(EXTERNAL_RULE_ID, "a namespaced id like plugin/RULE_NAME"),
1111
+ meta: z6.object({
1112
+ description: z6.string().min(1),
1113
+ type: z6.enum(["problem", "suggestion"]),
1114
+ docs: z6.string(),
1115
+ fixable: z6.boolean(),
1116
+ options: z6.custom((v) => v === void 0 || typeof v?.safeParse === "function", "a zod schema").optional(),
1117
+ card: z6.object({ name: z6.string(), prognosis: fn, action: fn }).optional()
1118
+ }),
1119
+ check: fn
1120
+ });
1121
+ var PluginModule = z6.object({ namespace: z6.string().regex(/^[a-z][a-z0-9-]*$/), rules: z6.array(PluginRule) });
1122
+ function entryOf(dir, pkg) {
1123
+ const pick = (e) => typeof e === "string" ? e : e && typeof e === "object" ? pick(e.import ?? e.default ?? e.node) : void 0;
1124
+ const ex = pkg.exports;
1125
+ const dot = typeof ex === "string" || ex && !Object.keys(ex).some((k) => k.startsWith(".")) ? ex : ex?.["."];
1126
+ return path11.resolve(dir, pick(dot) ?? pkg.module ?? pkg.main ?? "index.js");
1127
+ }
1128
+ async function loadPlugins(root, names) {
1129
+ const out = [];
1130
+ for (const name of names) {
1131
+ const dir = path11.join(path11.resolve(root), "node_modules", name);
1132
+ const pkgFile = path11.join(dir, "package.json");
1133
+ if (!fs7.existsSync(pkgFile)) throw new ConfigError(`plugin ${name} is not installed in ${path11.join(root, "node_modules")}`);
1134
+ const pkg = JSON.parse(fs7.readFileSync(pkgFile, "utf8"));
1135
+ const entry = entryOf(dir, pkg);
1136
+ if (path11.relative(dir, entry).startsWith("..")) throw new ConfigError(`plugin ${name}: its entry point is outside the package`);
1137
+ const mod = await import(pathToFileURL(entry).href);
1138
+ const parsed = PluginModule.safeParse(mod.default ?? mod);
1139
+ if (!parsed.success) throw new ConfigError(`plugin ${name}: ${z6.prettifyError(parsed.error)}`);
1140
+ const { namespace, rules: rules3 } = parsed.data;
1141
+ const foreign = rules3.find((r) => !r.id.startsWith(`${namespace}/`));
1142
+ if (foreign) throw new ConfigError(`plugin ${name}: rule ${foreign.id} is outside its namespace ${namespace}/`);
1143
+ out.push({ name, version: pkg.version, rules: (mod.default ?? mod).rules });
1144
+ }
1145
+ return out;
1146
+ }
1147
+
1089
1148
  // ../clinical/src/schema.ts
1090
- var Lang = z6.enum(["en"]);
1091
- var Triage = z6.enum(["resuscitation", "therapy", "preventive"]);
1092
- var PrescriptionRx = z6.object({
1093
- id: z6.string().regex(/^RX-\d{2,}$/),
1094
- action: z6.string(),
1095
- command: z6.string().optional(),
1096
- autoFix: z6.boolean(),
1097
- healthGain: z6.number().nonnegative(),
1098
- monthlySavingsUsd: z6.number().nonnegative().optional()
1149
+ var Lang = z7.enum(["en"]);
1150
+ var Triage = z7.enum(["resuscitation", "therapy", "preventive"]);
1151
+ var PrescriptionRx = z7.object({
1152
+ id: z7.string().regex(/^RX-\d{2,}$/),
1153
+ action: z7.string(),
1154
+ command: z7.string().optional(),
1155
+ autoFix: z7.boolean(),
1156
+ healthGain: z7.number().nonnegative(),
1157
+ monthlySavingsUsd: z7.number().nonnegative().optional()
1099
1158
  });
1100
- var ClinicalDiagnosis = z6.object({
1159
+ var ClinicalDiagnosis = z7.object({
1101
1160
  code: RuleId,
1102
1161
  triage: Triage,
1103
- diagnosis: z6.string(),
1104
- summary: z6.string(),
1105
- vitals: z6.array(z6.object({ label: z6.string(), value: z6.string() })),
1106
- prognosis: z6.string(),
1162
+ diagnosis: z7.string(),
1163
+ summary: z7.string(),
1164
+ vitals: z7.array(z7.object({ label: z7.string(), value: z7.string() })),
1165
+ prognosis: z7.string(),
1107
1166
  rx: PrescriptionRx,
1108
- files: z6.array(z6.string()),
1167
+ files: z7.array(z7.string()),
1109
1168
  finding: Finding
1110
1169
  });
1111
- var Counts = z6.object({ resuscitation: z6.number(), therapy: z6.number(), preventive: z6.number() });
1112
- var Anamnesis = z6.object({
1113
- priority: z6.enum(["economy", "balanced", "quality"]).default("balanced"),
1114
- primaryHarness: z6.string().optional(),
1115
- monthlyBudgetUsd: z6.number().nonnegative().optional()
1170
+ var Counts = z7.object({ resuscitation: z7.number(), therapy: z7.number(), preventive: z7.number() });
1171
+ var Anamnesis = z7.object({
1172
+ priority: z7.enum(["economy", "balanced", "quality"]).default("balanced"),
1173
+ primaryHarness: z7.string().optional(),
1174
+ monthlyBudgetUsd: z7.number().nonnegative().optional()
1116
1175
  });
1117
- var ScanSettings = z6.object({
1118
- global: z6.boolean(),
1119
- finops: z6.boolean(),
1120
- days: z6.number(),
1176
+ var ScanSettings = z7.object({
1177
+ global: z7.boolean(),
1178
+ finops: z7.boolean(),
1179
+ days: z7.number(),
1121
1180
  /** `configHash` of ctxmedic.config.json; "" without one, and in history written before v0.3. */
1122
- config: z6.string().default("")
1181
+ config: z7.string().default("")
1123
1182
  });
1124
1183
  var DEFAULT_SCAN = { global: true, finops: true, days: 30, config: "" };
1125
- var Visit = z6.object({
1126
- at: z6.string(),
1127
- root: z6.string(),
1184
+ var Visit = z7.object({
1185
+ at: z7.string(),
1186
+ root: z7.string(),
1128
1187
  /** Missing in history written by v0.1.0: those runs are assumed to use the defaults. */
1129
1188
  scan: ScanSettings.default(DEFAULT_SCAN),
1130
- healthScore: z6.number(),
1189
+ healthScore: z7.number(),
1131
1190
  counts: Counts,
1132
- monthlySpendUsd: z6.number().optional(),
1133
- potentialMonthlySavingsUsd: z6.number()
1191
+ monthlySpendUsd: z7.number().optional(),
1192
+ potentialMonthlySavingsUsd: z7.number()
1134
1193
  });
1135
- var ClinicalReport = z6.object({
1136
- tool: z6.literal("ctxmedic"),
1137
- version: z6.string(),
1194
+ var ClinicalReport = z7.object({
1195
+ tool: z7.literal("ctxmedic"),
1196
+ version: z7.string(),
1138
1197
  lang: Lang,
1139
- generatedAt: z6.string(),
1198
+ generatedAt: z7.string(),
1140
1199
  patient: PatientVitals,
1141
- healthScore: z6.number().min(0).max(100),
1200
+ healthScore: z7.number().min(0).max(100),
1142
1201
  previous: Visit.nullable(),
1143
- opinion: z6.string(),
1202
+ opinion: z7.string(),
1144
1203
  counts: Counts,
1145
- diagnoses: z6.array(ClinicalDiagnosis),
1204
+ diagnoses: z7.array(ClinicalDiagnosis),
1146
1205
  finops: FinOpsReport.nullable(),
1147
- potentialMonthlySavingsUsd: z6.number()
1206
+ potentialMonthlySavingsUsd: z7.number(),
1207
+ /** Plugins listed in the config and whether this run loaded them (ADR-027). */
1208
+ plugins: z7.array(PluginInfo).default([])
1148
1209
  });
1149
1210
 
1150
1211
  // ../finops/src/cache.ts
1151
- import fs7 from "fs";
1152
- import path11 from "path";
1153
- var file = () => path11.join(stateDir(), "cache.json");
1212
+ import fs8 from "fs";
1213
+ import path12 from "path";
1214
+ var file = () => path12.join(stateDir(), "cache.json");
1154
1215
  function loadCache() {
1155
1216
  try {
1156
- const c = JSON.parse(fs7.readFileSync(file(), "utf8"));
1217
+ const c = JSON.parse(fs8.readFileSync(file(), "utf8"));
1157
1218
  if (c?.v === 3 && c.files) return c;
1158
1219
  } catch {
1159
1220
  }
1160
1221
  return { v: 3, files: {} };
1161
1222
  }
1162
1223
  function saveCache(c) {
1163
- fs7.mkdirSync(stateDir(), { recursive: true });
1224
+ fs8.mkdirSync(stateDir(), { recursive: true });
1164
1225
  const tmp = file() + ".tmp";
1165
- fs7.writeFileSync(tmp, JSON.stringify(c));
1166
- fs7.renameSync(tmp, file());
1226
+ fs8.writeFileSync(tmp, JSON.stringify(c));
1227
+ fs8.renameSync(tmp, file());
1167
1228
  }
1168
1229
  async function cachedParse(paths, parse, cache) {
1169
1230
  const stats = [];
@@ -1171,7 +1232,7 @@ async function cachedParse(paths, parse, cache) {
1171
1232
  for (const p3 of paths) {
1172
1233
  let st;
1173
1234
  try {
1174
- st = fs7.statSync(p3);
1235
+ st = fs8.statSync(p3);
1175
1236
  } catch {
1176
1237
  continue;
1177
1238
  }
@@ -1189,7 +1250,7 @@ async function cachedParse(paths, parse, cache) {
1189
1250
  }
1190
1251
 
1191
1252
  // ../finops/src/detectors.ts
1192
- import path12 from "path";
1253
+ import path13 from "path";
1193
1254
 
1194
1255
  // ../finops/src/pricing.ts
1195
1256
  var PRICING_AS_OF = "2026-11-03";
@@ -1319,7 +1380,7 @@ var contextSnowball = detector("FIN_CONTEXT_SNOWBALL", ({ sessions, days }, { st
1319
1380
  ruleId: "FIN_CONTEXT_SNOWBALL",
1320
1381
  severity: sev(usd3),
1321
1382
  message: `${bad.length} session(s) ran >${steps} steps with 100k+ context and no /clear or /compact`,
1322
- files: bad.slice(0, 5).map((s) => `session ${path12.basename(s.file, ".jsonl")}`),
1383
+ files: bad.slice(0, 5).map((s) => `session ${path13.basename(s.file, ".jsonl")}`),
1323
1384
  data: { sessions: bad.length, worstSteps: worst.steps, worstMaxContext: worst.maxContext, days },
1324
1385
  monthlySavingsUsd: round(usd3)
1325
1386
  }
@@ -1353,8 +1414,8 @@ var cacheMiss = detector("FIN_CACHE_MISS", ({ sessions, days }, { minHitRatio, t
1353
1414
  var detectors = [unusedMcp, modelOverkill, contextSnowball, cacheMiss];
1354
1415
 
1355
1416
  // ../finops/src/parsers.ts
1356
- import fs8 from "fs";
1357
- import path13 from "path";
1417
+ import fs9 from "fs";
1418
+ import path14 from "path";
1358
1419
  import readline from "readline";
1359
1420
  var SNOWBALL_CONTEXT = 1e5;
1360
1421
  var HEALTHY_CONTEXT = 4e4;
@@ -1385,7 +1446,7 @@ function schemas(s, defs) {
1385
1446
  for (const [name, d2] of Object.entries(defs)) s.mcpSchemaTokens[name] = Math.max(s.mcpSchemaTokens[name] ?? 0, countTokens(JSON.stringify(d2)));
1386
1447
  }
1387
1448
  async function* lines(file2) {
1388
- const rl = readline.createInterface({ input: fs8.createReadStream(file2), crlfDelay: Infinity });
1449
+ const rl = readline.createInterface({ input: fs9.createReadStream(file2), crlfDelay: Infinity });
1389
1450
  for await (const line of rl) {
1390
1451
  if (!line) continue;
1391
1452
  try {
@@ -1464,7 +1525,7 @@ async function parseCursor(file2) {
1464
1525
  for (const c of Array.isArray(content) ? content : []) if (c?.type === "tool_use" || c?.type === "tool-call") mcp(s, c.name ?? c.toolName);
1465
1526
  }
1466
1527
  if (!s.end) {
1467
- const t2 = fs8.statSync(file2).mtime.toISOString();
1528
+ const t2 = fs9.statSync(file2).mtime.toISOString();
1468
1529
  s.start ??= t2;
1469
1530
  s.end = t2;
1470
1531
  }
@@ -1608,6 +1669,10 @@ var en = {
1608
1669
  action: () => "Keep instructions static: no dates, branch names or random IDs at the top; avoid switching models mid-session."
1609
1670
  }
1610
1671
  },
1672
+ externalCard: {
1673
+ prognosis: (description) => `Reported by a rule from outside ctxmedic: ${description}.`,
1674
+ action: (docs) => docs ? `See the rule's docs: ${docs}` : "See the docs of the plugin that provides this rule."
1675
+ },
1611
1676
  ui: {
1612
1677
  triage: { resuscitation: "\u{1F534} Resuscitation", therapy: "\u{1F7E1} Therapy", preventive: "\u{1F7E2} Preventive" },
1613
1678
  labs: "Vitals",
@@ -1622,7 +1687,9 @@ var en = {
1622
1687
  noLogs: "No session logs found: FinOps analysis skipped.",
1623
1688
  spend: "Spend",
1624
1689
  runRate: "run rate",
1625
- estimatedPrice: "\u2248 model not in the price table: estimated at Sonnet-class rates"
1690
+ estimatedPrice: "\u2248 model not in the price table: estimated at Sonnet-class rates",
1691
+ pluginsLoaded: (list) => `plugins: ${list}`,
1692
+ pluginsSkipped: (names) => `plugins not loaded: ${names}. Run with --plugins to load them (their code runs with ctxmedic's rights).`
1626
1693
  },
1627
1694
  cli: {
1628
1695
  noBackups: "No backups in .ctxmedic/backups: nothing to restore.",
@@ -1684,22 +1751,22 @@ function healthGain(findings, f) {
1684
1751
  }
1685
1752
 
1686
1753
  // ../clinical/src/store.ts
1687
- import fs9 from "fs";
1688
- import path14 from "path";
1754
+ import fs10 from "fs";
1755
+ import path15 from "path";
1689
1756
  var MAX_VISITS = 200;
1690
- var historyFile = () => path14.join(stateDir(), "history.json");
1691
- var profileFile = () => path14.join(stateDir(), "profile.json");
1757
+ var historyFile = () => path15.join(stateDir(), "history.json");
1758
+ var profileFile = () => path15.join(stateDir(), "profile.json");
1692
1759
  function readJson(file2) {
1693
1760
  try {
1694
- return JSON.parse(fs9.readFileSync(file2, "utf8"));
1761
+ return JSON.parse(fs10.readFileSync(file2, "utf8"));
1695
1762
  } catch {
1696
1763
  return void 0;
1697
1764
  }
1698
1765
  }
1699
1766
  function writeJson(file2, v) {
1700
- fs9.mkdirSync(path14.dirname(file2), { recursive: true });
1701
- fs9.writeFileSync(file2 + ".tmp", JSON.stringify(v, null, 2));
1702
- fs9.renameSync(file2 + ".tmp", file2);
1767
+ fs10.mkdirSync(path15.dirname(file2), { recursive: true });
1768
+ fs10.writeFileSync(file2 + ".tmp", JSON.stringify(v, null, 2));
1769
+ fs10.renameSync(file2 + ".tmp", file2);
1703
1770
  }
1704
1771
  var sameScan = (a2, b) => a2.global === b.global && a2.finops === b.finops && (!a2.finops || a2.days === b.days) && a2.config === b.config;
1705
1772
  function loadHistory(root, scan2) {
@@ -1803,7 +1870,7 @@ var harnesses = [
1803
1870
  ];
1804
1871
 
1805
1872
  // ../clinical/src/engine.ts
1806
- var VERSION = true ? "0.11.0" : "0.0.0-dev";
1873
+ var VERSION = true ? "0.12.0" : "0.0.0-dev";
1807
1874
  var TRIAGE = { critical: "resuscitation", warning: "therapy", info: "preventive" };
1808
1875
  var ORDER = ["resuscitation", "therapy", "preventive"];
1809
1876
  var human = (k) => k.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
@@ -1824,8 +1891,15 @@ function vitals(f) {
1824
1891
  if (f.monthlySavingsUsd) out.push({ label: "Savings", value: `$${f.monthlySavingsUsd.toFixed(2)}/mo` });
1825
1892
  return out;
1826
1893
  }
1827
- function diagnose(findings, lang, anamnesis = Anamnesis.parse({})) {
1894
+ function diagnose(findings, lang, anamnesis = Anamnesis.parse({}), extraRules = []) {
1828
1895
  const cat = cards(lang);
1896
+ const cardFor = (f) => {
1897
+ if (cat[f.ruleId]) return cat[f.ruleId];
1898
+ const meta2 = extraRules.find((r) => r.id === f.ruleId)?.meta;
1899
+ if (meta2?.card) return meta2.card;
1900
+ const ext = messages(lang).externalCard;
1901
+ return { name: f.ruleId, prognosis: () => ext.prognosis(meta2?.description ?? f.message), action: () => ext.action(meta2?.docs) };
1902
+ };
1829
1903
  const weight = (f) => {
1830
1904
  const gain = healthGain(findings, f);
1831
1905
  const usd3 = f.monthlySavingsUsd ?? 0;
@@ -1836,7 +1910,7 @@ function diagnose(findings, lang, anamnesis = Anamnesis.parse({})) {
1836
1910
  );
1837
1911
  return sorted.map((f, i) => {
1838
1912
  const id = `RX-${String(i + 1).padStart(2, "0")}`;
1839
- const card2 = cat[f.ruleId];
1913
+ const card2 = cardFor(f);
1840
1914
  return {
1841
1915
  code: f.ruleId,
1842
1916
  triage: TRIAGE[f.severity],
@@ -1864,11 +1938,18 @@ var scanSettings = (opts) => ({
1864
1938
  config: opts.config ?? ""
1865
1939
  });
1866
1940
  async function checkup(opts) {
1867
- const ex = await examine(opts.root, harnesses, { global: opts.global });
1941
+ const listed = loadConfig(opts.root).plugins;
1942
+ const loaded = opts.plugins ? await loadPlugins(opts.root, listed) : [];
1943
+ const extraRules = [...opts.extraRules ?? [], ...loaded.flatMap((p3) => p3.rules)];
1944
+ const plugins2 = listed.map((name) => {
1945
+ const p3 = loaded.find((x) => x.name === name);
1946
+ return { name, version: p3?.version, loaded: Boolean(p3), rules: p3?.rules.map((r) => r.id) ?? [] };
1947
+ });
1948
+ const ex = await examine(opts.root, harnesses, { global: opts.global, extraRules });
1868
1949
  let finops = null;
1869
1950
  if (opts.finops !== false) finops = await analyze({ root: ex.vitals.root, files: ex.files, days: opts.days ?? 30, config: ex.config });
1870
1951
  const findings = [...ex.findings, ...finops?.findings ?? []];
1871
- const diagnoses = diagnose(findings, opts.lang, loadAnamnesis());
1952
+ const diagnoses = diagnose(findings, opts.lang, loadAnamnesis(), extraRules);
1872
1953
  const score = healthScore(findings);
1873
1954
  const counts = { resuscitation: 0, therapy: 0, preventive: 0 };
1874
1955
  for (const d2 of diagnoses) counts[d2.triage]++;
@@ -1887,7 +1968,8 @@ async function checkup(opts) {
1887
1968
  counts,
1888
1969
  diagnoses,
1889
1970
  finops,
1890
- potentialMonthlySavingsUsd: Math.round(savings * 100) / 100
1971
+ potentialMonthlySavingsUsd: Math.round(savings * 100) / 100,
1972
+ plugins: plugins2
1891
1973
  });
1892
1974
  if (opts.record !== false)
1893
1975
  recordVisit({
@@ -2049,8 +2131,8 @@ async function askAnthropic(prompt, onProgress) {
2049
2131
 
2050
2132
  // ../server/src/index.ts
2051
2133
  import crypto3 from "crypto";
2052
- import fs10 from "fs";
2053
- import path15 from "path";
2134
+ import fs11 from "fs";
2135
+ import path16 from "path";
2054
2136
  import { serve } from "@hono/node-server";
2055
2137
  import { serveStatic } from "@hono/node-server/serve-static";
2056
2138
  import { Hono } from "hono";
@@ -2070,14 +2152,14 @@ function configWatcher(root) {
2070
2152
  if (!subs.size) return;
2071
2153
  const dirs = /* @__PURE__ */ new Map();
2072
2154
  for (const f of ex.files) {
2073
- const dir = path15.dirname(f.path);
2074
- if (dirs.get(dir) !== null) dirs.set(dir, (dirs.get(dir) ?? /* @__PURE__ */ new Set()).add(path15.basename(f.path)));
2075
- if (f.role === "skill") dirs.set(path15.dirname(dir), null);
2155
+ const dir = path16.dirname(f.path);
2156
+ if (dirs.get(dir) !== null) dirs.set(dir, (dirs.get(dir) ?? /* @__PURE__ */ new Set()).add(path16.basename(f.path)));
2157
+ if (f.role === "skill") dirs.set(path16.dirname(dir), null);
2076
2158
  }
2077
2159
  const sig = (p3, isDir) => {
2078
2160
  try {
2079
- if (isDir) return fs10.readdirSync(p3).sort().join("/");
2080
- const st = fs10.statSync(p3);
2161
+ if (isDir) return fs11.readdirSync(p3).sort().join("/");
2162
+ const st = fs11.statSync(p3);
2081
2163
  return `${st.mtimeMs}:${st.size}`;
2082
2164
  } catch {
2083
2165
  return "gone";
@@ -2086,10 +2168,10 @@ function configWatcher(root) {
2086
2168
  const seen = /* @__PURE__ */ new Map();
2087
2169
  for (const [dir, names] of dirs) {
2088
2170
  if (!names) seen.set(dir, sig(dir, true));
2089
- else for (const n2 of names) seen.set(path15.join(dir, n2), sig(path15.join(dir, n2), false));
2171
+ else for (const n2 of names) seen.set(path16.join(dir, n2), sig(path16.join(dir, n2), false));
2090
2172
  }
2091
2173
  const onEvent = (dir, names, name) => {
2092
- const p3 = names ? name && names.has(name) ? path15.join(dir, name) : null : dir;
2174
+ const p3 = names ? name && names.has(name) ? path16.join(dir, name) : null : dir;
2093
2175
  if (!p3) return;
2094
2176
  const now = sig(p3, !names);
2095
2177
  if (now === seen.get(p3)) return;
@@ -2098,7 +2180,7 @@ function configWatcher(root) {
2098
2180
  };
2099
2181
  for (const [dir, names] of dirs) {
2100
2182
  try {
2101
- const w = fs10.watch(dir, (_, name) => onEvent(dir, names, name === null ? null : String(name)));
2183
+ const w = fs11.watch(dir, (_, name) => onEvent(dir, names, name === null ? null : String(name)));
2102
2184
  w.unref();
2103
2185
  watchers.push(w);
2104
2186
  } catch {
@@ -2113,13 +2195,13 @@ function configWatcher(root) {
2113
2195
  }, 300);
2114
2196
  };
2115
2197
  return {
2116
- subscribe(fn) {
2117
- subs.add(fn);
2198
+ subscribe(fn2) {
2199
+ subs.add(fn2);
2118
2200
  if (subs.size === 1) ready = watch();
2119
2201
  return {
2120
2202
  ready,
2121
2203
  off: () => {
2122
- subs.delete(fn);
2204
+ subs.delete(fn2);
2123
2205
  if (!subs.size) {
2124
2206
  clearTimeout(timer);
2125
2207
  close();
@@ -2131,7 +2213,7 @@ function configWatcher(root) {
2131
2213
  }
2132
2214
  function createApp(opts) {
2133
2215
  const app = new Hono();
2134
- const root = path15.resolve(opts.root);
2216
+ const root = path16.resolve(opts.root);
2135
2217
  app.use("/api/*", async (c, next) => {
2136
2218
  c.header("cache-control", "no-store");
2137
2219
  if (c.req.method !== "GET" && c.req.header("x-ctxmedic-token") !== opts.token) return c.json({ error: "invalid session token" }, 403);
@@ -2153,7 +2235,7 @@ function createApp(opts) {
2153
2235
  );
2154
2236
  app.get("/api/checkup", async (c) => {
2155
2237
  const lang = c.req.query("lang") ? resolveLang(c.req.query("lang")) : opts.lang;
2156
- return c.json(await checkup({ root, lang, days: opts.days, record: c.req.query("record") === "1" }));
2238
+ return c.json(await checkup({ root, lang, days: opts.days, plugins: opts.plugins, record: c.req.query("record") === "1" }));
2157
2239
  });
2158
2240
  app.get("/api/history", (c) => c.json(loadHistory(root, scanSettings({ days: opts.days, config: configHash(loadConfig(root)) }))));
2159
2241
  app.get("/api/graph", async (c) => {
@@ -2166,7 +2248,7 @@ function createApp(opts) {
2166
2248
  for (const f of ex.files) {
2167
2249
  for (const h of f.harnesses) edges.push({ source: `h:${h}`, target: f.path, kind: "loads" });
2168
2250
  if (f.isSymlink && f.realpath) {
2169
- if (!nodes.some((n2) => n2.id === f.realpath)) nodes.push({ id: f.realpath, kind: "target", label: path15.relative(root, f.realpath), tokens: f.tokens, broken: false, scope: f.scope });
2251
+ if (!nodes.some((n2) => n2.id === f.realpath)) nodes.push({ id: f.realpath, kind: "target", label: path16.relative(root, f.realpath), tokens: f.tokens, broken: false, scope: f.scope });
2170
2252
  edges.push({ source: f.path, target: f.realpath, kind: "symlink" });
2171
2253
  }
2172
2254
  }
@@ -2179,16 +2261,16 @@ function createApp(opts) {
2179
2261
  app.post("/api/treat/:rx", async (c) => {
2180
2262
  const dryRun = c.req.query("dryRun") === "1";
2181
2263
  try {
2182
- const r = await treat(c.req.param("rx"), { root, lang: opts.lang, days: opts.days, dryRun });
2264
+ const r = await treat(c.req.param("rx"), { root, lang: opts.lang, days: opts.days, plugins: opts.plugins, dryRun });
2183
2265
  return c.json({ rx: r.diagnosis.rx.id, applied: r.result?.applied ?? [], backupDir: r.result?.backupDir, dryRun, manual: r.manual });
2184
2266
  } catch (e) {
2185
2267
  return c.json({ error: e.message }, e instanceof FixRefusedError ? 409 : 500);
2186
2268
  }
2187
2269
  });
2188
- if (opts.publicDir && fs10.existsSync(path15.join(opts.publicDir, "index.html"))) {
2189
- const rel = path15.relative(process.cwd(), opts.publicDir) || ".";
2270
+ if (opts.publicDir && fs11.existsSync(path16.join(opts.publicDir, "index.html"))) {
2271
+ const rel = path16.relative(process.cwd(), opts.publicDir) || ".";
2190
2272
  app.use("/*", serveStatic({ root: rel }));
2191
- app.get("*", serveStatic({ path: path15.join(rel, "index.html") }));
2273
+ app.get("*", serveStatic({ path: path16.join(rel, "index.html") }));
2192
2274
  } else app.get("/", (c) => c.text("ctxmedic UI is not built. Run `pnpm build` in the repository."));
2193
2275
  return app;
2194
2276
  }
@@ -2253,6 +2335,12 @@ function finopsSummary(f, lang) {
2253
2335
  estimated ? pc.dim(` ${tx.estimatedPrice}`) : ""
2254
2336
  ].filter(Boolean).join("\n");
2255
2337
  }
2338
+ function plugins(r) {
2339
+ const tx = t(r.lang);
2340
+ const loaded = r.plugins.filter((p3) => p3.loaded).map((p3) => `${p3.name}${p3.version ? `@${p3.version}` : ""}`);
2341
+ const skipped = r.plugins.filter((p3) => !p3.loaded).map((p3) => p3.name);
2342
+ return [loaded.length ? pc.dim(` ${tx.pluginsLoaded(loaded.join(", "))}`) : "", skipped.length ? pc.yellow(` ${tx.pluginsSkipped(skipped.join(", "))}`) : ""].filter(Boolean);
2343
+ }
2256
2344
  function header(r) {
2257
2345
  const tx = t(r.lang);
2258
2346
  const delta = r.previous ? r.healthScore - r.previous.healthScore : null;
@@ -2264,6 +2352,7 @@ function header(r) {
2264
2352
  "",
2265
2353
  ` ${tx.health}: ${bar(r.healthScore)} ${pc.bold(String(r.healthScore))}/100${trend}`,
2266
2354
  ` ${pc.italic(r.opinion)}`,
2355
+ ...plugins(r),
2267
2356
  ` ${tx.triage.resuscitation} ${r.counts.resuscitation} ${tx.triage.therapy} ${r.counts.therapy} ${tx.triage.preventive} ${r.counts.preventive}` + (r.potentialMonthlySavingsUsd ? ` \xB7 ${tx.savings}: ${pc.green(pc.bold(usd2(r.potentialMonthlySavingsUsd) + tx.perMonth))}` : ""),
2268
2357
  ""
2269
2358
  ].join("\n");
@@ -2293,13 +2382,15 @@ function rules2(list, lang, configFile) {
2293
2382
  }
2294
2383
 
2295
2384
  // src/index.ts
2296
- var common = (cmd) => cmd.option("--lang <lang>", "interface language (only en for now)").option("--days <n>", "how many days of session logs to analyze", "30").option("--no-finops", "skip session-log (cost) analysis").option("--no-global", "skip global configs in the home directory");
2385
+ var common = (cmd) => cmd.option("--lang <lang>", "interface language (only en for now)").option("--days <n>", "how many days of session logs to analyze", "30").option("--no-finops", "skip session-log (cost) analysis").option("--no-global", "skip global configs in the home directory").option("--plugins", "load the plugins listed in ctxmedic.config.json (runs their code; or CTXMEDIC_PLUGINS=1)");
2386
+ var pluginsAllowed = (o2) => Boolean(o2.plugins) || process.env.CTXMEDIC_PLUGINS === "1";
2297
2387
  var ctx = (dir, o2) => ({
2298
- root: path16.resolve(dir ?? "."),
2388
+ root: path17.resolve(dir ?? "."),
2299
2389
  lang: resolveLang(o2.lang),
2300
2390
  days: Math.max(1, Number.parseInt(o2.days, 10) || 30),
2301
2391
  finops: o2.finops,
2302
- global: o2.global
2392
+ global: o2.global,
2393
+ plugins: pluginsAllowed(o2)
2303
2394
  });
2304
2395
  function fail(e) {
2305
2396
  console.error(pc2.red(`\u2716 ${e instanceof FixRefusedError || e instanceof ConfigError ? e.message : e.stack ?? e}`));
@@ -2322,18 +2413,18 @@ common(program.command("treat [rx]").description("apply a prescription (e.g. RX-
2322
2413
  const m = messages(c.lang).cli;
2323
2414
  if (manual.length === picked.length) return console.log(pc2.yellow(m.noAutoFix));
2324
2415
  const plans = picked.flatMap((d2) => d2.finding.fix ? [d2.finding.fix] : []);
2325
- for (const plan of plans) for (const op of plan.ops) console.log(pc2.dim(` ${op.kind === "write" ? "write " : "symlink"} ${path16.relative(c.root, op.path)}${op.kind === "symlink" ? ` \u2192 ${op.target}` : ""}`));
2416
+ for (const plan of plans) for (const op of plan.ops) console.log(pc2.dim(` ${op.kind === "write" ? "write " : "symlink"} ${path17.relative(c.root, op.path)}${op.kind === "symlink" ? ` \u2192 ${op.target}` : ""}`));
2326
2417
  if (!o2.dryRun && !o2.yes) {
2327
2418
  const ok = await p2.confirm({ message: m.confirmApply });
2328
2419
  if (p2.isCancel(ok) || !ok) return p2.cancel(m.cancelled);
2329
2420
  }
2330
2421
  for (const plan of plans) {
2331
2422
  const res = await applyFix(plan, { root: c.root, dryRun: o2.dryRun, force: o2.force, global: false }).catch(fail);
2332
- console.log(`${o2.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${plan.title}${res.dryRun ? "" : pc2.dim(` backup: ${path16.relative(c.root, res.backupDir)}`)}`);
2423
+ console.log(`${o2.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${plan.title}${res.dryRun ? "" : pc2.dim(` backup: ${path17.relative(c.root, res.backupDir)}`)}`);
2333
2424
  }
2334
2425
  });
2335
2426
  program.command("restore [backup]").description("undo a fix: list backups, or restore one by id (or latest)").option("--lang <lang>", "interface language (only en for now)").option("--dry-run", "show what would change without writing").option("--force", "restore even if files changed after the fix").action(async (id, o2) => {
2336
- const root = path16.resolve(".");
2427
+ const root = path17.resolve(".");
2337
2428
  const m = messages(resolveLang(o2.lang)).cli;
2338
2429
  if (!id) {
2339
2430
  const all = await listBackups(root);
@@ -2346,10 +2437,12 @@ ${m.restoreHint}`));
2346
2437
  for (const line of r.restored) console.log(pc2.dim(` ${line}`));
2347
2438
  console.log(`${r.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${m.restored(r.id)}: ${r.title}`);
2348
2439
  });
2349
- program.command("rules [path]").description("list rules with their effective level and options from ctxmedic.config.json").option("--lang <lang>", "interface language (only en for now)").option("--json", "print the rules as JSON").action((dir, o2) => {
2440
+ program.command("rules [path]").description("list rules with their effective level and options from ctxmedic.config.json").option("--lang <lang>", "interface language (only en for now)").option("--json", "print the rules as JSON").option("--plugins", "also list rules from the plugins in ctxmedic.config.json (runs their code)").action(async (dir, o2) => {
2441
+ const root = path17.resolve(dir ?? ".");
2350
2442
  let list;
2351
2443
  try {
2352
- list = describeRules(loadConfig(path16.resolve(dir ?? ".")));
2444
+ const extra = pluginsAllowed(o2) ? (await loadPlugins(root, loadConfig(root).plugins)).flatMap((p3) => p3.rules) : [];
2445
+ list = describeRules(loadConfig(root, extra), extra);
2353
2446
  } catch (e) {
2354
2447
  fail(e);
2355
2448
  }
@@ -2423,11 +2516,11 @@ common(program.command("consult [path]").description("interactive appointment: a
2423
2516
  }
2424
2517
  p2.outro(m.goodbye);
2425
2518
  });
2426
- program.command("history [path]").description("Health Score history for a project (or all with --all)").option("--all", "show every project").action((dir, o2) => console.log(history(loadHistory(o2.all ? void 0 : path16.resolve(dir ?? ".")))));
2519
+ program.command("history [path]").description("Health Score history for a project (or all with --all)").option("--all", "show every project").action((dir, o2) => console.log(history(loadHistory(o2.all ? void 0 : path17.resolve(dir ?? ".")))));
2427
2520
  common(program.command("ui [path]").description("open the local Web UI (127.0.0.1 only)")).option("--port <n>", "port", "7337").option("--no-open", "do not open the browser").action(async (dir, o2) => {
2428
2521
  const c = ctx(dir, o2);
2429
- const publicDir = path16.join(path16.dirname(fileURLToPath(import.meta.url)), "..", "public");
2430
- const { url } = await startServer({ root: c.root, lang: c.lang, days: c.days, port: Number(o2.port), publicDir }).catch(fail);
2522
+ const publicDir = path17.join(path17.dirname(fileURLToPath(import.meta.url)), "..", "public");
2523
+ const { url } = await startServer({ root: c.root, lang: c.lang, days: c.days, plugins: c.plugins, port: Number(o2.port), publicDir }).catch(fail);
2431
2524
  console.log(`${pc2.bold("\u{1FA7A} ctxmedic UI")} ${pc2.cyan(url)}
2432
2525
  ${pc2.dim("Ctrl+C to stop. Listening on 127.0.0.1 only.")}`);
2433
2526
  if (o2.open) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ctxmedic",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "The context medic for your AI coding setup: checkup, treat, savings for Claude Code, Cursor, Windsurf, Codex CLI, OpenCode, Cline and Copilot.",
5
5
  "type": "module",
6
6
  "license": "FSL-1.1-MIT",
package/schema.json CHANGED
@@ -5,6 +5,13 @@
5
5
  "$schema": {
6
6
  "type": "string"
7
7
  },
8
+ "plugins": {
9
+ "type": "array",
10
+ "items": {
11
+ "type": "string"
12
+ },
13
+ "description": "npm packages in node_modules that add rules. They run only with --plugins (their code can do anything ctxmedic can)."
14
+ },
8
15
  "extends": {
9
16
  "anyOf": [
10
17
  {
@@ -512,7 +519,40 @@
512
519
  }
513
520
  },
514
521
  "additionalProperties": false,
515
- "description": "Rule levels and options: \"off\", \"on\", a severity, or [level, options]."
522
+ "description": "Rule levels and options: \"off\", \"on\", a severity, or [level, options].",
523
+ "patternProperties": {
524
+ "^[a-z][a-z0-9-]*\\/[A-Z][A-Z0-9_]*$": {
525
+ "description": "A rule from a plugin: plugin/RULE_NAME.",
526
+ "anyOf": [
527
+ {
528
+ "$ref": "#/definitions/RuleLevel"
529
+ },
530
+ {
531
+ "type": "array",
532
+ "items": [
533
+ {
534
+ "$ref": "#/definitions/RuleLevel"
535
+ }
536
+ ],
537
+ "minItems": 1,
538
+ "maxItems": 1
539
+ },
540
+ {
541
+ "type": "array",
542
+ "items": [
543
+ {
544
+ "$ref": "#/definitions/RuleLevel"
545
+ },
546
+ {
547
+ "type": "object"
548
+ }
549
+ ],
550
+ "minItems": 2,
551
+ "maxItems": 2
552
+ }
553
+ ]
554
+ }
555
+ }
516
556
  },
517
557
  "ignores": {
518
558
  "type": "array",