ctxmedic 0.9.0 → 0.11.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
@@ -53,6 +53,7 @@ npx ctxmedic checkup
53
53
  | `ctxmedic savings` | FinOps only: spend, run rate, cache hit ratio, savings. |
54
54
  | `ctxmedic consult [--ai]` | Interactive appointment: your priorities, budget and main tool shape the treatment plan. `--ai` asks local Ollama or your own Anthropic/OpenAI key for a second opinion. |
55
55
  | `ctxmedic history` | Health Score over time. |
56
+ | `ctxmedic rules [path]` | Every rule with its effective level and the options `ctxmedic.config.json` changed. `--json`. |
56
57
  | `ctxmedic ui` | Local Web UI on `127.0.0.1`: dashboard, diagnoses, FinOps, config graph. |
57
58
 
58
59
  Common options: `--days 30`, `--no-finops`, `--no-global`.
package/dist/index.js CHANGED
@@ -21,6 +21,7 @@ var RuleId = z.enum([
21
21
  "ERR_INVALID_SKILL",
22
22
  "CRIT_SECRET_LEAK",
23
23
  "INFO_UNSUPPORTED_SYNTAX",
24
+ "INFO_UNUSED_DISABLE",
24
25
  "FIN_BLOAT_IGNORE",
25
26
  "FIN_UNUSED_MCP",
26
27
  "FIN_MODEL_OVERKILL",
@@ -56,6 +57,8 @@ var Finding = z.object({
56
57
  severity: Severity,
57
58
  message: z.string(),
58
59
  files: z.array(z.string()).default([]),
60
+ /** 1-based line in `files[0]`, when the finding points at one line (line-level disable comments use it). */
61
+ line: z.number().int().positive().optional(),
59
62
  /** Raw lab values used by the clinical layer (token counts, ratios, $). */
60
63
  data: z.record(z.string(), z.unknown()).default({}),
61
64
  monthlySavingsUsd: z.number().nonnegative().optional(),
@@ -787,6 +790,17 @@ var finopsMeta = {
787
790
 
788
791
  // ../core/src/rules/index.ts
789
792
  var rules = [brokenLink, contextBloat, duplicates, skills, secretLeak, syntax, bloatIgnore];
793
+ var unusedDisableMeta = {
794
+ description: "Remove ctxmedic-disable comments that silence nothing",
795
+ type: "suggestion",
796
+ docs: docsUrl("INFO_UNUSED_DISABLE"),
797
+ fixable: false
798
+ };
799
+ var allRuleMeta = () => [
800
+ ...rules.map((r) => [r.id, r.meta, "config"]),
801
+ ["INFO_UNUSED_DISABLE", unusedDisableMeta, "config"],
802
+ ...Object.entries(finopsMeta).map(([id, meta2]) => [id, meta2, "session-logs"])
803
+ ];
790
804
  async function runRules(ctx2, list = rules, options = {}, off = /* @__PURE__ */ new Set()) {
791
805
  const out = [];
792
806
  for (const r of list) {
@@ -906,11 +920,36 @@ import fs6 from "fs";
906
920
  import path9 from "path";
907
921
  import picomatch2 from "picomatch";
908
922
  import { z as z5 } from "zod";
923
+
924
+ // ../core/src/presets.ts
925
+ var PRESET_NAMES = ["ctxmedic:recommended", "ctxmedic:strict"];
926
+ var PRESETS = {
927
+ // Today's defaults, spelled out so a project can say it chose them.
928
+ "ctxmedic:recommended": { rules: {} },
929
+ // Stricter thresholds, and info-only rules raised to warnings. Rules that grade their own findings
930
+ // (secrets, broken links, bloat) keep "on": forcing a severity would demote their critical findings.
931
+ "ctxmedic:strict": {
932
+ rules: {
933
+ WARN_CONTEXT_BLOAT: ["on", { tokens: 2e3 }],
934
+ WARN_DUPLICATE_RULES: ["on", { similarity: 0.6 }],
935
+ INFO_UNSUPPORTED_SYNTAX: "warning",
936
+ INFO_UNUSED_DISABLE: "warning",
937
+ FIN_CONTEXT_SNOWBALL: ["on", { steps: 25 }],
938
+ FIN_CACHE_MISS: ["on", { minHitRatio: 0.5 }],
939
+ FIN_MODEL_OVERKILL: ["on", { minSessions: 2 }]
940
+ }
941
+ }
942
+ };
943
+
944
+ // ../core/src/config.ts
909
945
  var CONFIG_FILE = "ctxmedic.config.json";
910
946
  var RuleLevel = z5.union([z5.literal("off"), z5.literal("on"), Severity]);
911
947
  var RuleEntry = z5.union([RuleLevel, z5.tuple([RuleLevel]), z5.tuple([RuleLevel, z5.record(z5.string(), z5.unknown())])]);
948
+ var Preset = z5.enum(PRESET_NAMES);
912
949
  var CtxmedicConfig = z5.object({
913
950
  $schema: z5.string().optional(),
951
+ /** Built-in presets applied in order before this file's own `rules` and `ignores`. */
952
+ extends: z5.union([Preset, z5.array(Preset)]).optional(),
914
953
  rules: z5.partialRecord(RuleId, RuleEntry).default({}),
915
954
  /** Globs over finding paths (project-relative, or `~/` for global files). */
916
955
  ignores: z5.array(z5.string()).default([])
@@ -919,6 +958,42 @@ var ConfigError = class extends Error {
919
958
  };
920
959
  var levelOf = (e) => e === void 0 ? "on" : typeof e === "string" ? e : e[0];
921
960
  var optionsOf = (e) => Array.isArray(e) && e[1] || {};
961
+ function resolveConfig(c) {
962
+ const names = c.extends === void 0 ? [] : typeof c.extends === "string" ? [c.extends] : c.extends;
963
+ const rules3 = {};
964
+ const ignores = [];
965
+ for (const layer of [...names.map((n2) => PRESETS[n2]), { rules: c.rules, ignores: c.ignores }]) {
966
+ for (const [id, entry] of Object.entries(layer.rules)) {
967
+ const before = optionsOf(rules3[id]);
968
+ rules3[id] = !Object.keys(optionsOf(entry)).length && Object.keys(before).length ? [levelOf(entry), before] : entry;
969
+ }
970
+ ignores.push(...layer.ignores ?? []);
971
+ }
972
+ return { ...c, rules: rules3, ignores };
973
+ }
974
+ var RuleInfo = z5.object({
975
+ id: RuleId,
976
+ /** "config": reads config files; "session-logs": a FIN_* detector that reads session logs. */
977
+ source: z5.enum(["config", "session-logs"]),
978
+ level: RuleLevel,
979
+ type: z5.enum(["problem", "suggestion"]),
980
+ fixable: z5.boolean(),
981
+ description: z5.string(),
982
+ docs: z5.string(),
983
+ /** Effective options, defaults included. */
984
+ options: z5.record(z5.string(), z5.unknown()),
985
+ /** Options the config set to a value other than the default. */
986
+ changed: z5.record(z5.string(), z5.unknown())
987
+ });
988
+ function describeRules(config) {
989
+ return allRuleMeta().map(([id, meta2, source]) => {
990
+ const entry = config.rules[id];
991
+ const options = meta2.options?.parse(optionsOf(entry)) ?? {};
992
+ const defaults = meta2.options?.parse({}) ?? {};
993
+ const changed = Object.fromEntries(Object.entries(options).filter(([k, v]) => JSON.stringify(v) !== JSON.stringify(defaults[k])));
994
+ return RuleInfo.parse({ id, source, level: levelOf(entry), type: meta2.type, fixable: meta2.fixable, description: meta2.description, docs: meta2.docs, options, changed });
995
+ });
996
+ }
922
997
  function loadConfig(root) {
923
998
  const file2 = path9.join(root, CONFIG_FILE);
924
999
  if (!fs6.existsSync(file2)) return CtxmedicConfig.parse({});
@@ -930,41 +1005,65 @@ function loadConfig(root) {
930
1005
  }
931
1006
  const r = CtxmedicConfig.safeParse(raw);
932
1007
  if (!r.success) throw new ConfigError(`${CONFIG_FILE}: ${z5.prettifyError(r.error)}`);
933
- for (const [id, entry] of Object.entries(r.data.rules)) {
1008
+ const config = resolveConfig(r.data);
1009
+ for (const [id, entry] of Object.entries(config.rules)) {
934
1010
  const opts = optionsOf(entry);
935
1011
  if (!Object.keys(opts).length) continue;
936
- const schema = (rules.find((x) => x.id === id)?.meta ?? finopsMeta[id])?.options;
1012
+ const schema = allRuleMeta().find(([x]) => x === id)?.[1].options;
937
1013
  if (!schema) throw new ConfigError(`${CONFIG_FILE}: rule ${id} takes no options`);
938
1014
  const o2 = schema.safeParse(opts);
939
1015
  if (!o2.success) throw new ConfigError(`${CONFIG_FILE}: rule ${id}: ${z5.prettifyError(o2.error)}`);
940
1016
  }
941
- return r.data;
1017
+ return config;
942
1018
  }
943
1019
  function configHash(c) {
944
1020
  if (!Object.keys(c.rules).length && !c.ignores.length) return "";
945
1021
  const rulesSorted = Object.fromEntries(Object.entries(c.rules).sort(([a2], [b]) => a2.localeCompare(b)));
946
1022
  return crypto2.createHash("sha256").update(JSON.stringify([rulesSorted, c.ignores])).digest("hex").slice(0, 12);
947
1023
  }
948
- var DIRECTIVE = /<!--\s*ctxmedic-disable\b([\s\S]*?)-->/g;
949
- function disabledIn(text2) {
950
- const out = /* @__PURE__ */ new Set();
951
- for (const m of text2.matchAll(DIRECTIVE)) {
952
- const ids = m[1].split("--")[0].split(/[\s,]+/).filter(Boolean);
953
- if (!ids.length) out.add("*");
954
- for (const id of ids) out.add(id);
955
- }
956
- return out;
1024
+ var DIRECTIVE = /<!--\s*ctxmedic-disable(-next-line|-line)?(?!\w|-(?!->))([\s\S]*?)-->/g;
1025
+ var lineAt = (text2, i) => text2.slice(0, i).split("\n").length;
1026
+ function directivesIn(text2) {
1027
+ return [...text2.matchAll(DIRECTIVE)].map((m) => {
1028
+ const kind = m[1] === "-next-line" ? "next-line" : m[1] === "-line" ? "line" : "file";
1029
+ const line = lineAt(text2, m.index);
1030
+ const ids = new Set(m[2].split("--")[0].split(/[\s,]+/).filter(Boolean));
1031
+ const target = kind === "line" ? line : kind === "next-line" ? lineAt(text2, m.index + m[0].length) + 1 : void 0;
1032
+ return { kind, ids, line, target };
1033
+ });
957
1034
  }
958
- function applyConfig(findings, files, config) {
1035
+ function applyConfig(findings, files, config, opts = {}) {
959
1036
  const ignored = config.ignores.length ? picomatch2(config.ignores, { dot: true }) : () => false;
960
- const disabled = new Map(files.filter((f) => f.text?.includes("ctxmedic-disable")).map((f) => [f.rel, disabledIn(f.text)]));
961
- return findings.flatMap((f) => {
962
- const level = levelOf(config.rules[f.ruleId]);
963
- if (level === "off") return [];
964
- if (f.files.length && f.files.every((p3) => ignored(p3))) return [];
965
- if (f.files.some((p3) => disabled.get(p3)?.has("*") || disabled.get(p3)?.has(f.ruleId))) return [];
966
- return [level === "on" ? f : { ...f, severity: level }];
1037
+ const comments = new Map(files.filter((f) => f.text?.includes("ctxmedic-disable")).map((f) => [f.rel, directivesIn(f.text)]));
1038
+ const used = /* @__PURE__ */ new Set();
1039
+ const level = (f) => {
1040
+ const l = levelOf(config.rules[f.ruleId]);
1041
+ if (l === "off" || f.files.length && f.files.every((p3) => ignored(p3))) return null;
1042
+ return l === "on" ? f : { ...f, severity: l };
1043
+ };
1044
+ const out = findings.flatMap((f) => {
1045
+ const kept = level(f);
1046
+ if (!kept) return [];
1047
+ const hits = f.files.flatMap(
1048
+ (p3, i) => (comments.get(p3) ?? []).filter(
1049
+ (d2) => (!d2.ids.size || d2.ids.has(f.ruleId)) && (d2.kind === "file" || i === 0 && f.line !== void 0 && d2.target === f.line)
1050
+ )
1051
+ );
1052
+ for (const d2 of hits) used.add(d2);
1053
+ return hits.length ? [] : [kept];
967
1054
  });
1055
+ if (!opts.reportUnused) return out;
1056
+ const unused = [...comments].flatMap(
1057
+ ([rel, ds]) => ds.filter((d2) => !used.has(d2)).map((d2) => ({
1058
+ ruleId: "INFO_UNUSED_DISABLE",
1059
+ severity: "info",
1060
+ message: `${rel}:${d2.line}: ctxmedic-disable${d2.kind === "file" ? "" : `-${d2.kind}`} silences nothing`,
1061
+ files: [rel],
1062
+ line: d2.line,
1063
+ data: { ids: [...d2.ids], kind: d2.kind }
1064
+ }))
1065
+ );
1066
+ return [...out, ...unused.flatMap((f) => level(f) ?? [])];
968
1067
  }
969
1068
 
970
1069
  // ../core/src/examine.ts
@@ -976,7 +1075,7 @@ async function examine(root, profiles, opts = {}) {
976
1075
  const entries = Object.entries(config.rules);
977
1076
  const off = new Set(entries.filter(([, e]) => levelOf(e) === "off").map(([id]) => id));
978
1077
  const options = Object.fromEntries(entries.map(([id, e]) => [id, optionsOf(e)]));
979
- const findings = applyConfig(await runRules({ root, files, profiles, startup }, void 0, options, off), files, config);
1078
+ const findings = applyConfig(await runRules({ root, files, profiles, startup }, void 0, options, off), files, config, { reportUnused: true });
980
1079
  const vitals2 = PatientVitals.parse({
981
1080
  root,
982
1081
  scannedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -1478,6 +1577,11 @@ var en = {
1478
1577
  prognosis: (f) => `${d(f, "harness")} reads ${(d(f, "directives") ?? []).join(", ")} as plain text: noise at best, wrong instructions at worst.`,
1479
1578
  action: () => "Move tool-specific directives into that tool's own file, or keep shared files directive-free."
1480
1579
  },
1580
+ INFO_UNUSED_DISABLE: {
1581
+ name: "Phantom Prescription",
1582
+ prognosis: (f) => `${f.files[0]}:${f.line} silences ${(d(f, "ids") ?? []).join(", ") || "every rule"}, but nothing there needed it. A stale disable hides the next real problem.`,
1583
+ action: (f) => `Delete the ctxmedic-disable comment on line ${f.line} of ${f.files[0]}.`
1584
+ },
1481
1585
  FIN_BLOAT_IGNORE: {
1482
1586
  name: "Indexing Bloat",
1483
1587
  prognosis: (f) => `${d(f, "harness")} indexes build output and lockfiles. Search results fill with junk and retrieval burns tokens.`,
@@ -1522,6 +1626,8 @@ var en = {
1522
1626
  },
1523
1627
  cli: {
1524
1628
  noBackups: "No backups in .ctxmedic/backups: nothing to restore.",
1629
+ rulesColumns: { rule: "Rule", level: "Level", type: "Type", fix: "Fix", changed: "Changed options" },
1630
+ rulesHint: (configFile) => `Levels and options come from ${configFile}. Docs: docs/rules/<RULE>.md`,
1525
1631
  restoreHint: "Undo a fix: ctxmedic restore <backup> (or latest)",
1526
1632
  restored: (id) => `Restored backup ${id}`,
1527
1633
  noAutoFix: "No auto-fix: follow the prescription by hand.",
@@ -1697,13 +1803,14 @@ var harnesses = [
1697
1803
  ];
1698
1804
 
1699
1805
  // ../clinical/src/engine.ts
1700
- var VERSION = true ? "0.9.0" : "0.0.0-dev";
1806
+ var VERSION = true ? "0.11.0" : "0.0.0-dev";
1701
1807
  var TRIAGE = { critical: "resuscitation", warning: "therapy", info: "preventive" };
1702
1808
  var ORDER = ["resuscitation", "therapy", "preventive"];
1703
1809
  var human = (k) => k.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
1704
1810
  function vitals(f) {
1705
1811
  const out = [];
1706
- if (f.files.length) out.push({ label: "Files", value: f.files.slice(0, 3).join(", ") + (f.files.length > 3 ? ` +${f.files.length - 3}` : "") });
1812
+ const shown = f.files.slice(0, 3).map((p3, i) => i === 0 && f.line ? `${p3}:${f.line}` : p3);
1813
+ if (f.files.length) out.push({ label: "Files", value: shown.join(", ") + (f.files.length > 3 ? ` +${f.files.length - 3}` : "") });
1707
1814
  for (const [k, v] of Object.entries(f.data)) {
1708
1815
  if (typeof v === "number")
1709
1816
  out.push({
@@ -2172,6 +2279,18 @@ function history(visits) {
2172
2279
  if (!visits.length) return pc.dim("No visits yet. Run `ctxmedic checkup`.");
2173
2280
  return visits.slice(-20).map((v) => `${v.at.slice(0, 16).replace("T", " ")} ${bar(v.healthScore)} ${String(v.healthScore).padStart(3)} \u{1F534}${v.counts.resuscitation} \u{1F7E1}${v.counts.therapy} \u{1F7E2}${v.counts.preventive} ${pc.dim(v.root)}${scanFlags(v)}`).join("\n");
2174
2281
  }
2282
+ function rules2(list, lang, configFile) {
2283
+ const m = messages(lang).cli;
2284
+ const c = m.rulesColumns;
2285
+ const w = Math.max(c.rule.length, ...list.map((r) => r.id.length)) + 2;
2286
+ const row = (a2, b, d2, e, f) => `${a2.padEnd(w)}${b.padEnd(10)}${d2.padEnd(12)}${e.padEnd(5)}${f}`.trimEnd();
2287
+ const lines2 = list.map((r) => {
2288
+ const changed = Object.entries(r.changed).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(" ");
2289
+ const line = row(r.id, r.level, r.type, r.fixable ? "\u2714" : "", changed);
2290
+ return r.level === "off" ? pc.dim(line) : line;
2291
+ });
2292
+ return [pc.bold(row(c.rule, c.level, c.type, c.fix, c.changed)), ...lines2, "", pc.dim(m.rulesHint(configFile))].join("\n");
2293
+ }
2175
2294
 
2176
2295
  // src/index.ts
2177
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");
@@ -2227,6 +2346,15 @@ ${m.restoreHint}`));
2227
2346
  for (const line of r.restored) console.log(pc2.dim(` ${line}`));
2228
2347
  console.log(`${r.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${m.restored(r.id)}: ${r.title}`);
2229
2348
  });
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) => {
2350
+ let list;
2351
+ try {
2352
+ list = describeRules(loadConfig(path16.resolve(dir ?? ".")));
2353
+ } catch (e) {
2354
+ fail(e);
2355
+ }
2356
+ console.log(o2.json ? JSON.stringify(list, null, 2) : rules2(list, resolveLang(o2.lang), CONFIG_FILE));
2357
+ });
2230
2358
  common(program.command("savings [path]").description("FinOps: token spend, cache hit ratio and savings prescriptions")).option("--json", "print the FinOps report as JSON").action(async (dir, o2) => {
2231
2359
  const c = ctx(dir, o2);
2232
2360
  const ex = await examine(c.root, harnesses, { global: c.global }).catch(fail);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ctxmedic",
3
- "version": "0.9.0",
3
+ "version": "0.11.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,28 @@
5
5
  "$schema": {
6
6
  "type": "string"
7
7
  },
8
+ "extends": {
9
+ "anyOf": [
10
+ {
11
+ "type": "string",
12
+ "enum": [
13
+ "ctxmedic:recommended",
14
+ "ctxmedic:strict"
15
+ ]
16
+ },
17
+ {
18
+ "type": "array",
19
+ "items": {
20
+ "type": "string",
21
+ "enum": [
22
+ "ctxmedic:recommended",
23
+ "ctxmedic:strict"
24
+ ]
25
+ }
26
+ }
27
+ ],
28
+ "description": "Built-in presets applied before this file's rules: ctxmedic:recommended, ctxmedic:strict."
29
+ },
8
30
  "rules": {
9
31
  "type": "object",
10
32
  "properties": {
@@ -265,6 +287,41 @@
265
287
  ],
266
288
  "description": "Keep build output and lockfiles out of the AI index with an ignore file. https://github.com/ponomarenko/ctxmedic/blob/main/docs/rules/FIN_BLOAT_IGNORE.md"
267
289
  },
290
+ "INFO_UNUSED_DISABLE": {
291
+ "anyOf": [
292
+ {
293
+ "$ref": "#/definitions/RuleLevel"
294
+ },
295
+ {
296
+ "type": "array",
297
+ "items": [
298
+ {
299
+ "$ref": "#/definitions/RuleLevel"
300
+ }
301
+ ],
302
+ "additionalItems": false,
303
+ "minItems": 1,
304
+ "maxItems": 1
305
+ },
306
+ {
307
+ "type": "array",
308
+ "items": [
309
+ {
310
+ "$ref": "#/definitions/RuleLevel"
311
+ },
312
+ {
313
+ "type": "object",
314
+ "properties": {},
315
+ "additionalProperties": false
316
+ }
317
+ ],
318
+ "additionalItems": false,
319
+ "minItems": 2,
320
+ "maxItems": 2
321
+ }
322
+ ],
323
+ "description": "Remove ctxmedic-disable comments that silence nothing. https://github.com/ponomarenko/ctxmedic/blob/main/docs/rules/INFO_UNUSED_DISABLE.md"
324
+ },
268
325
  "FIN_UNUSED_MCP": {
269
326
  "anyOf": [
270
327
  {