ctxmedic 0.2.3 → 0.3.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.
Files changed (3) hide show
  1. package/README.md +11 -2
  2. package/dist/index.js +240 -104
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -87,8 +87,8 @@ package from npm.
87
87
  | Code | Diagnosis | Auto-fix |
88
88
  |---|---|---|
89
89
  | `ERR_BROKEN_LINK` | Symlink Necrosis: broken, circular or absolute symlinks | relative links |
90
- | `WARN_CONTEXT_BLOAT` | Context Obesity: > 3,500 tokens loaded at session start | — |
91
- | `WARN_DUPLICATE_RULES` | Instruction Duplication: > 75% similar instruction files | hub-and-spoke `.ai/` + symlinks |
90
+ | `WARN_CONTEXT_BLOAT` | Context Obesity: > 3,500 tokens (configurable) loaded at session start | — |
91
+ | `WARN_DUPLICATE_RULES` | Instruction Duplication: > 75% (configurable) similar instruction files | hub-and-spoke `.ai/` + symlinks |
92
92
  | `ERR_INVALID_SKILL` | Skill Amnesia: bad `SKILL.md` frontmatter, names, triggers | — |
93
93
  | `CRIT_SECRET_LEAK` | Credential Hemorrhage: API keys in configs (masked in output) | — |
94
94
  | `INFO_UNSUPPORTED_SYNTAX` | Cross-Harness Allergy: `@import`, `alwaysApply`… read by tools that ignore them | — |
@@ -101,6 +101,15 @@ package from npm.
101
101
  Every fix backs up the originals to `.ctxmedic/backups/<timestamp>/` and
102
102
  refuses to touch files with uncommitted git changes unless you pass `--force`.
103
103
 
104
+ Each rule has a [docs page](docs/rules/README.md). To turn rules off, change
105
+ their severity or thresholds, or ignore paths, add `ctxmedic.config.json`:
106
+
107
+ ```json
108
+ { "rules": { "INFO_UNSUPPORTED_SYNTAX": "off", "WARN_CONTEXT_BLOAT": ["on", { "tokens": 6000 }] } }
109
+ ```
110
+
111
+ To silence a rule for one Markdown file: `<!-- ctxmedic-disable WARN_CONTEXT_BLOAT -- reason -->`.
112
+
104
113
  ## Privacy
105
114
 
106
115
  - No telemetry. No network calls, except `consult --ai`, which asks before it
package/dist/index.js CHANGED
@@ -2,14 +2,14 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { spawn } from "child_process";
5
- import path15 from "path";
5
+ import path16 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 z2 } from "zod";
12
+ import { z as z5 } from "zod";
13
13
 
14
14
  // ../core/src/schema.ts
15
15
  import { z } from "zod";
@@ -380,7 +380,7 @@ var PATTERNS = [
380
380
  ["Google API key", /\bAIza[0-9A-Za-z_-]{35}\b/g],
381
381
  ["Stripe key", /\b(?:sk|rk)_live_[A-Za-z0-9]{20,}/g]
382
382
  ];
383
- var GENERIC = /["']?([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))["']?\s*[:=]\s*["']([^"'\s$]{16,})["']/gi;
383
+ var GENERIC = /(?<![A-Za-z0-9_-])["']?([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))["']?\s*[:=]\s*["']([^"'\s$]{16,})["']/gi;
384
384
  var mask = (s) => s.length <= 8 ? "****" : `${s.slice(0, 6)}\u2026${s.slice(-2)} (${s.length} chars)`;
385
385
  function entropy(s) {
386
386
  const freq = /* @__PURE__ */ new Map();
@@ -413,6 +413,13 @@ function redactSecrets(text2) {
413
413
  // ../core/src/rules/bloatIgnore.ts
414
414
  import fs3 from "fs";
415
415
  import path5 from "path";
416
+
417
+ // ../core/src/rules/types.ts
418
+ var docsUrl = (id) => `https://github.com/ponomarenko/ctxmedic/blob/main/docs/rules/${id}.md`;
419
+ var BLOAT_TOKENS = 3500;
420
+ var DUPLICATE_SIMILARITY = 0.75;
421
+
422
+ // ../core/src/rules/bloatIgnore.ts
416
423
  var HEAVY = [
417
424
  "node_modules/",
418
425
  "dist/",
@@ -437,6 +444,12 @@ var HEAVY = [
437
444
  ];
438
445
  var bloatIgnore = {
439
446
  id: "FIN_BLOAT_IGNORE",
447
+ meta: {
448
+ description: "Keep build output and lockfiles out of the AI index with an ignore file",
449
+ type: "suggestion",
450
+ docs: docsUrl("FIN_BLOAT_IGNORE"),
451
+ fixable: true
452
+ },
440
453
  check: ({ root, files, profiles }) => {
441
454
  const out = [];
442
455
  for (const h of profiles) {
@@ -473,6 +486,12 @@ ${HEAVY.join("\n")}
473
486
  import path6 from "path";
474
487
  var brokenLink = {
475
488
  id: "ERR_BROKEN_LINK",
489
+ meta: {
490
+ description: "Symlinked configs must point to an existing target, without loops or absolute paths",
491
+ type: "problem",
492
+ docs: docsUrl("ERR_BROKEN_LINK"),
493
+ fixable: true
494
+ },
476
495
  check: ({ files }) => files.flatMap((f) => {
477
496
  if (f.broken || f.loop)
478
497
  return [
@@ -502,22 +521,27 @@ var brokenLink = {
502
521
  })
503
522
  };
504
523
 
505
- // ../core/src/rules/types.ts
506
- var BLOAT_TOKENS = 3500;
507
- var DUPLICATE_SIMILARITY = 0.75;
508
-
509
524
  // ../core/src/rules/contextBloat.ts
525
+ import { z as z2 } from "zod";
526
+ var Options = z2.object({ tokens: z2.number().int().positive().default(BLOAT_TOKENS) });
510
527
  var contextBloat = {
511
528
  id: "WARN_CONTEXT_BLOAT",
512
- check: ({ startup, profiles }) => Object.entries(startup).filter(([, l]) => l.tokens > BLOAT_TOKENS).map(([id, l]) => {
529
+ meta: {
530
+ description: "Limit the tokens a harness loads at session start",
531
+ type: "suggestion",
532
+ docs: docsUrl("WARN_CONTEXT_BLOAT"),
533
+ fixable: false,
534
+ options: Options
535
+ },
536
+ check: ({ startup, profiles }, { tokens: threshold }) => Object.entries(startup).filter(([, l]) => l.tokens > threshold).map(([id, l]) => {
513
537
  const top = [...l.files].sort((a2, b) => b.tokens - a2.tokens).slice(0, 5);
514
538
  const limit = profiles.find((p3) => p3.id === id)?.contextLimit ?? 2e5;
515
539
  return {
516
540
  ruleId: "WARN_CONTEXT_BLOAT",
517
- severity: l.tokens > BLOAT_TOKENS * 3 ? "critical" : "warning",
518
- message: `${id} loads ${l.tokens.toLocaleString("en")} tokens at session start (threshold ${BLOAT_TOKENS.toLocaleString("en")})`,
541
+ severity: l.tokens > threshold * 3 ? "critical" : "warning",
542
+ message: `${id} loads ${l.tokens.toLocaleString("en")} tokens at session start (threshold ${threshold.toLocaleString("en")})`,
519
543
  files: top.map((f) => f.rel),
520
- data: { harness: id, tokens: l.tokens, threshold: BLOAT_TOKENS, contextShare: l.tokens / limit, top }
544
+ data: { harness: id, tokens: l.tokens, threshold, contextShare: l.tokens / limit, top }
521
545
  };
522
546
  })
523
547
  };
@@ -525,6 +549,8 @@ var contextBloat = {
525
549
  // ../core/src/rules/duplicates.ts
526
550
  import fs4 from "fs";
527
551
  import path7 from "path";
552
+ import { z as z3 } from "zod";
553
+ var Options2 = z3.object({ similarity: z3.number().gt(0).lt(1).default(DUPLICATE_SIMILARITY) });
528
554
  var norm = (text2) => new Set(
529
555
  text2.split("\n").map((l) => l.toLowerCase().replace(/\s+/g, " ").trim()).filter((l) => l.length >= 8)
530
556
  );
@@ -560,7 +586,14 @@ ${extra.join("\n")}
560
586
  }
561
587
  var duplicates = {
562
588
  id: "WARN_DUPLICATE_RULES",
563
- check: ({ root, files }) => {
589
+ meta: {
590
+ description: "Do not keep near-identical instruction files for different harnesses",
591
+ type: "suggestion",
592
+ docs: docsUrl("WARN_DUPLICATE_RULES"),
593
+ fixable: true,
594
+ options: Options2
595
+ },
596
+ check: ({ root, files }, { similarity: threshold }) => {
564
597
  const docs = files.filter((f) => f.role === "instructions" && f.text && !f.broken);
565
598
  const out = [];
566
599
  const seen = /* @__PURE__ */ new Set();
@@ -573,7 +606,7 @@ var duplicates = {
573
606
  if (seen.has(key)) continue;
574
607
  seen.add(key);
575
608
  const sim = similarity(a2.text, b.text);
576
- if (sim <= DUPLICATE_SIMILARITY) continue;
609
+ if (sim <= threshold) continue;
577
610
  const ops = a2.scope === "project" && b.scope === "project" && !a2.isSymlink && !b.isSymlink ? hubFix(root, a2, b) : [];
578
611
  out.push({
579
612
  ruleId: "WARN_DUPLICATE_RULES",
@@ -591,6 +624,12 @@ var duplicates = {
591
624
  // ../core/src/rules/secretLeak.ts
592
625
  var secretLeak = {
593
626
  id: "CRIT_SECRET_LEAK",
627
+ meta: {
628
+ description: "Do not store secrets in plain text in AI configs",
629
+ type: "problem",
630
+ docs: docsUrl("CRIT_SECRET_LEAK"),
631
+ fixable: false
632
+ },
594
633
  check: ({ files }) => files.flatMap((f) => {
595
634
  if (!f.text) return [];
596
635
  const hits = findSecrets(f.text);
@@ -614,6 +653,12 @@ var NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
614
653
  var TRIGGER = /\b(use|when|whenever|triggers?|invoke)\b/i;
615
654
  var skills = {
616
655
  id: "ERR_INVALID_SKILL",
656
+ meta: {
657
+ description: "Skills need valid frontmatter, a unique name and a description with a trigger",
658
+ type: "problem",
659
+ docs: docsUrl("ERR_INVALID_SKILL"),
660
+ fixable: false
661
+ },
617
662
  check: ({ files }) => {
618
663
  const out = [];
619
664
  const names = /* @__PURE__ */ new Map();
@@ -664,6 +709,12 @@ function directives(text2) {
664
709
  }
665
710
  var syntax = {
666
711
  id: "INFO_UNSUPPORTED_SYNTAX",
712
+ meta: {
713
+ description: "Flag directives a harness does not understand",
714
+ type: "suggestion",
715
+ docs: docsUrl("INFO_UNSUPPORTED_SYNTAX"),
716
+ fixable: false
717
+ },
667
718
  check: ({ files, profiles }) => {
668
719
  const out = [];
669
720
  for (const f of files) {
@@ -689,9 +740,13 @@ var syntax = {
689
740
 
690
741
  // ../core/src/rules/index.ts
691
742
  var rules = [brokenLink, contextBloat, duplicates, skills, secretLeak, syntax, bloatIgnore];
692
- async function runRules(ctx2, list = rules) {
743
+ async function runRules(ctx2, list = rules, options = {}, off = /* @__PURE__ */ new Set()) {
693
744
  const out = [];
694
- for (const r of list) for (const f of await r.check(ctx2)) out.push(Finding.parse(f));
745
+ for (const r of list) {
746
+ if (off.has(r.id)) continue;
747
+ const opts = r.meta.options ? r.meta.options.parse(options[r.id] ?? {}) : {};
748
+ for (const f of await r.check(ctx2, opts)) out.push(Finding.parse(f));
749
+ }
695
750
  return out;
696
751
  }
697
752
 
@@ -796,12 +851,85 @@ async function restoreBackup(idIn, opts) {
796
851
  }
797
852
 
798
853
  // ../core/src/examine.ts
854
+ import path10 from "path";
855
+
856
+ // ../core/src/config.ts
857
+ import crypto2 from "crypto";
858
+ import fs6 from "fs";
799
859
  import path9 from "path";
860
+ import picomatch2 from "picomatch";
861
+ import { z as z4 } from "zod";
862
+ var CONFIG_FILE = "ctxmedic.config.json";
863
+ var RuleLevel = z4.union([z4.literal("off"), z4.literal("on"), Severity]);
864
+ var RuleEntry = z4.union([RuleLevel, z4.tuple([RuleLevel]), z4.tuple([RuleLevel, z4.record(z4.string(), z4.unknown())])]);
865
+ var CtxmedicConfig = z4.object({
866
+ $schema: z4.string().optional(),
867
+ rules: z4.partialRecord(RuleId, RuleEntry).default({}),
868
+ /** Globs over finding paths (project-relative, or `~/` for global files). */
869
+ ignores: z4.array(z4.string()).default([])
870
+ });
871
+ var ConfigError = class extends Error {
872
+ };
873
+ var levelOf = (e) => e === void 0 ? "on" : typeof e === "string" ? e : e[0];
874
+ var optionsOf = (e) => Array.isArray(e) && e[1] || {};
875
+ function loadConfig(root) {
876
+ const file2 = path9.join(root, CONFIG_FILE);
877
+ if (!fs6.existsSync(file2)) return CtxmedicConfig.parse({});
878
+ let raw;
879
+ try {
880
+ raw = JSON.parse(fs6.readFileSync(file2, "utf8"));
881
+ } catch (e) {
882
+ throw new ConfigError(`${CONFIG_FILE}: ${e.message}`);
883
+ }
884
+ const r = CtxmedicConfig.safeParse(raw);
885
+ if (!r.success) throw new ConfigError(`${CONFIG_FILE}: ${z4.prettifyError(r.error)}`);
886
+ for (const [id, entry] of Object.entries(r.data.rules)) {
887
+ const opts = optionsOf(entry);
888
+ if (!Object.keys(opts).length) continue;
889
+ const schema = rules.find((x) => x.id === id)?.meta.options;
890
+ if (!schema) throw new ConfigError(`${CONFIG_FILE}: rule ${id} takes no options`);
891
+ const o2 = schema.safeParse(opts);
892
+ if (!o2.success) throw new ConfigError(`${CONFIG_FILE}: rule ${id}: ${z4.prettifyError(o2.error)}`);
893
+ }
894
+ return r.data;
895
+ }
896
+ function configHash(c) {
897
+ if (!Object.keys(c.rules).length && !c.ignores.length) return "";
898
+ const rulesSorted = Object.fromEntries(Object.entries(c.rules).sort(([a2], [b]) => a2.localeCompare(b)));
899
+ return crypto2.createHash("sha256").update(JSON.stringify([rulesSorted, c.ignores])).digest("hex").slice(0, 12);
900
+ }
901
+ var DIRECTIVE = /<!--\s*ctxmedic-disable\b([\s\S]*?)-->/g;
902
+ function disabledIn(text2) {
903
+ const out = /* @__PURE__ */ new Set();
904
+ for (const m of text2.matchAll(DIRECTIVE)) {
905
+ const ids = m[1].split("--")[0].split(/[\s,]+/).filter(Boolean);
906
+ if (!ids.length) out.add("*");
907
+ for (const id of ids) out.add(id);
908
+ }
909
+ return out;
910
+ }
911
+ function applyConfig(findings, files, config) {
912
+ const ignored = config.ignores.length ? picomatch2(config.ignores, { dot: true }) : () => false;
913
+ const disabled = new Map(files.filter((f) => f.text?.includes("ctxmedic-disable")).map((f) => [f.rel, disabledIn(f.text)]));
914
+ return findings.flatMap((f) => {
915
+ const level = levelOf(config.rules[f.ruleId]);
916
+ if (level === "off") return [];
917
+ if (f.files.length && f.files.every((p3) => ignored(p3))) return [];
918
+ if (f.files.some((p3) => disabled.get(p3)?.has("*") || disabled.get(p3)?.has(f.ruleId))) return [];
919
+ return [level === "on" ? f : { ...f, severity: level }];
920
+ });
921
+ }
922
+
923
+ // ../core/src/examine.ts
800
924
  async function examine(root, profiles, opts = {}) {
801
- root = path9.resolve(root);
925
+ root = path10.resolve(root);
926
+ const config = loadConfig(root);
802
927
  const files = await scan(root, profiles, opts);
803
928
  const startup = startupLoad(files, profiles);
804
- const findings = await runRules({ root, files, profiles, startup });
929
+ const entries = Object.entries(config.rules);
930
+ const off = new Set(entries.filter(([, e]) => levelOf(e) === "off").map(([id]) => id));
931
+ const options = Object.fromEntries(entries.map(([id, e]) => [id, optionsOf(e)]));
932
+ const findings = applyConfig(await runRules({ root, files, profiles, startup }, void 0, options, off), files, config);
805
933
  const vitals2 = PatientVitals.parse({
806
934
  root,
807
935
  scannedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -809,81 +937,87 @@ async function examine(root, profiles, opts = {}) {
809
937
  harnesses: detectedHarnesses(files),
810
938
  startupTokens: Object.fromEntries(Object.entries(startup).map(([k, v]) => [k, v.tokens]))
811
939
  });
812
- return { vitals: vitals2, files, startup, findings };
940
+ return { vitals: vitals2, files, startup, findings, config };
813
941
  }
814
942
 
815
943
  // ../clinical/src/schema.ts
816
- var Lang = z2.enum(["en"]);
817
- var Triage = z2.enum(["resuscitation", "therapy", "preventive"]);
818
- var PrescriptionRx = z2.object({
819
- id: z2.string().regex(/^RX-\d{2,}$/),
820
- action: z2.string(),
821
- command: z2.string().optional(),
822
- autoFix: z2.boolean(),
823
- healthGain: z2.number().nonnegative(),
824
- monthlySavingsUsd: z2.number().nonnegative().optional()
944
+ var Lang = z5.enum(["en"]);
945
+ var Triage = z5.enum(["resuscitation", "therapy", "preventive"]);
946
+ var PrescriptionRx = z5.object({
947
+ id: z5.string().regex(/^RX-\d{2,}$/),
948
+ action: z5.string(),
949
+ command: z5.string().optional(),
950
+ autoFix: z5.boolean(),
951
+ healthGain: z5.number().nonnegative(),
952
+ monthlySavingsUsd: z5.number().nonnegative().optional()
825
953
  });
826
- var ClinicalDiagnosis = z2.object({
954
+ var ClinicalDiagnosis = z5.object({
827
955
  code: RuleId,
828
956
  triage: Triage,
829
- diagnosis: z2.string(),
830
- summary: z2.string(),
831
- vitals: z2.array(z2.object({ label: z2.string(), value: z2.string() })),
832
- prognosis: z2.string(),
957
+ diagnosis: z5.string(),
958
+ summary: z5.string(),
959
+ vitals: z5.array(z5.object({ label: z5.string(), value: z5.string() })),
960
+ prognosis: z5.string(),
833
961
  rx: PrescriptionRx,
834
- files: z2.array(z2.string()),
962
+ files: z5.array(z5.string()),
835
963
  finding: Finding
836
964
  });
837
- var Counts = z2.object({ resuscitation: z2.number(), therapy: z2.number(), preventive: z2.number() });
838
- var Anamnesis = z2.object({
839
- priority: z2.enum(["economy", "balanced", "quality"]).default("balanced"),
840
- primaryHarness: z2.string().optional(),
841
- monthlyBudgetUsd: z2.number().nonnegative().optional()
965
+ var Counts = z5.object({ resuscitation: z5.number(), therapy: z5.number(), preventive: z5.number() });
966
+ var Anamnesis = z5.object({
967
+ priority: z5.enum(["economy", "balanced", "quality"]).default("balanced"),
968
+ primaryHarness: z5.string().optional(),
969
+ monthlyBudgetUsd: z5.number().nonnegative().optional()
842
970
  });
843
- var ScanSettings = z2.object({ global: z2.boolean(), finops: z2.boolean(), days: z2.number() });
844
- var DEFAULT_SCAN = { global: true, finops: true, days: 30 };
845
- var Visit = z2.object({
846
- at: z2.string(),
847
- root: z2.string(),
971
+ var ScanSettings = z5.object({
972
+ global: z5.boolean(),
973
+ finops: z5.boolean(),
974
+ days: z5.number(),
975
+ /** `configHash` of ctxmedic.config.json; "" without one, and in history written before v0.3. */
976
+ config: z5.string().default("")
977
+ });
978
+ var DEFAULT_SCAN = { global: true, finops: true, days: 30, config: "" };
979
+ var Visit = z5.object({
980
+ at: z5.string(),
981
+ root: z5.string(),
848
982
  /** Missing in history written by v0.1.0: those runs are assumed to use the defaults. */
849
983
  scan: ScanSettings.default(DEFAULT_SCAN),
850
- healthScore: z2.number(),
984
+ healthScore: z5.number(),
851
985
  counts: Counts,
852
- monthlySpendUsd: z2.number().optional(),
853
- potentialMonthlySavingsUsd: z2.number()
986
+ monthlySpendUsd: z5.number().optional(),
987
+ potentialMonthlySavingsUsd: z5.number()
854
988
  });
855
- var ClinicalReport = z2.object({
856
- tool: z2.literal("ctxmedic"),
857
- version: z2.string(),
989
+ var ClinicalReport = z5.object({
990
+ tool: z5.literal("ctxmedic"),
991
+ version: z5.string(),
858
992
  lang: Lang,
859
- generatedAt: z2.string(),
993
+ generatedAt: z5.string(),
860
994
  patient: PatientVitals,
861
- healthScore: z2.number().min(0).max(100),
995
+ healthScore: z5.number().min(0).max(100),
862
996
  previous: Visit.nullable(),
863
- opinion: z2.string(),
997
+ opinion: z5.string(),
864
998
  counts: Counts,
865
- diagnoses: z2.array(ClinicalDiagnosis),
999
+ diagnoses: z5.array(ClinicalDiagnosis),
866
1000
  finops: FinOpsReport.nullable(),
867
- potentialMonthlySavingsUsd: z2.number()
1001
+ potentialMonthlySavingsUsd: z5.number()
868
1002
  });
869
1003
 
870
1004
  // ../finops/src/cache.ts
871
- import fs6 from "fs";
872
- import path10 from "path";
873
- var file = () => path10.join(stateDir(), "cache.json");
1005
+ import fs7 from "fs";
1006
+ import path11 from "path";
1007
+ var file = () => path11.join(stateDir(), "cache.json");
874
1008
  function loadCache() {
875
1009
  try {
876
- const c = JSON.parse(fs6.readFileSync(file(), "utf8"));
1010
+ const c = JSON.parse(fs7.readFileSync(file(), "utf8"));
877
1011
  if (c?.v === 3 && c.files) return c;
878
1012
  } catch {
879
1013
  }
880
1014
  return { v: 3, files: {} };
881
1015
  }
882
1016
  function saveCache(c) {
883
- fs6.mkdirSync(stateDir(), { recursive: true });
1017
+ fs7.mkdirSync(stateDir(), { recursive: true });
884
1018
  const tmp = file() + ".tmp";
885
- fs6.writeFileSync(tmp, JSON.stringify(c));
886
- fs6.renameSync(tmp, file());
1019
+ fs7.writeFileSync(tmp, JSON.stringify(c));
1020
+ fs7.renameSync(tmp, file());
887
1021
  }
888
1022
  async function cachedParse(paths, parse, cache) {
889
1023
  const stats = [];
@@ -891,7 +1025,7 @@ async function cachedParse(paths, parse, cache) {
891
1025
  for (const p3 of paths) {
892
1026
  let st;
893
1027
  try {
894
- st = fs6.statSync(p3);
1028
+ st = fs7.statSync(p3);
895
1029
  } catch {
896
1030
  continue;
897
1031
  }
@@ -909,7 +1043,7 @@ async function cachedParse(paths, parse, cache) {
909
1043
  }
910
1044
 
911
1045
  // ../finops/src/detectors.ts
912
- import path11 from "path";
1046
+ import path12 from "path";
913
1047
 
914
1048
  // ../finops/src/pricing.ts
915
1049
  var PRICING_AS_OF = "2026-11-03";
@@ -1046,7 +1180,7 @@ function contextSnowball({ sessions, days }) {
1046
1180
  ruleId: "FIN_CONTEXT_SNOWBALL",
1047
1181
  severity: sev(usd3),
1048
1182
  message: `${bad.length} session(s) ran >${SNOWBALL_STEPS} steps with 100k+ context and no /clear or /compact`,
1049
- files: bad.slice(0, 5).map((s) => `session ${path11.basename(s.file, ".jsonl")}`),
1183
+ files: bad.slice(0, 5).map((s) => `session ${path12.basename(s.file, ".jsonl")}`),
1050
1184
  data: { sessions: bad.length, worstSteps: worst.steps, worstMaxContext: worst.maxContext, days },
1051
1185
  monthlySavingsUsd: round(usd3)
1052
1186
  }
@@ -1080,8 +1214,8 @@ function cacheMiss({ sessions, days }) {
1080
1214
  var detectors = [unusedMcp, modelOverkill, contextSnowball, cacheMiss];
1081
1215
 
1082
1216
  // ../finops/src/parsers.ts
1083
- import fs7 from "fs";
1084
- import path12 from "path";
1217
+ import fs8 from "fs";
1218
+ import path13 from "path";
1085
1219
  import readline from "readline";
1086
1220
  var SNOWBALL_CONTEXT = 1e5;
1087
1221
  var HEALTHY_CONTEXT = 4e4;
@@ -1112,7 +1246,7 @@ function schemas(s, defs) {
1112
1246
  for (const [name, d2] of Object.entries(defs)) s.mcpSchemaTokens[name] = Math.max(s.mcpSchemaTokens[name] ?? 0, countTokens(JSON.stringify(d2)));
1113
1247
  }
1114
1248
  async function* lines(file2) {
1115
- const rl = readline.createInterface({ input: fs7.createReadStream(file2), crlfDelay: Infinity });
1249
+ const rl = readline.createInterface({ input: fs8.createReadStream(file2), crlfDelay: Infinity });
1116
1250
  for await (const line of rl) {
1117
1251
  if (!line) continue;
1118
1252
  try {
@@ -1191,7 +1325,7 @@ async function parseCursor(file2) {
1191
1325
  for (const c of Array.isArray(content) ? content : []) if (c?.type === "tool_use" || c?.type === "tool-call") mcp(s, c.name ?? c.toolName);
1192
1326
  }
1193
1327
  if (!s.end) {
1194
- const t2 = fs7.statSync(file2).mtime.toISOString();
1328
+ const t2 = fs8.statSync(file2).mtime.toISOString();
1195
1329
  s.start ??= t2;
1196
1330
  s.end = t2;
1197
1331
  }
@@ -1217,7 +1351,7 @@ async function loadSessions(days, now = /* @__PURE__ */ new Date()) {
1217
1351
  const since = new Date(now.getTime() - days * 864e5).toISOString();
1218
1352
  return all.filter((s) => (s.end ?? "") >= since);
1219
1353
  }
1220
- function buildReport(sessions, { days = 30, root, files }) {
1354
+ function buildReport(sessions, { days = 30, root, files, config }) {
1221
1355
  const byModel = /* @__PURE__ */ new Map();
1222
1356
  const byHarness = {};
1223
1357
  const mcpCalls = {};
@@ -1245,7 +1379,8 @@ function buildReport(sessions, { days = 30, root, files }) {
1245
1379
  read += u.cacheRead;
1246
1380
  }
1247
1381
  }
1248
- const findings = detectors.flatMap((d2) => d2({ sessions, days, files, root }));
1382
+ const raw = detectors.flatMap((d2) => d2({ sessions, days, files, root }));
1383
+ const findings = config ? applyConfig(raw, files, config) : raw;
1249
1384
  return FinOpsReport.parse({
1250
1385
  periodDays: days,
1251
1386
  sessions: sessions.length,
@@ -1281,7 +1416,7 @@ var en = {
1281
1416
  WARN_CONTEXT_BLOAT: {
1282
1417
  name: "Context Obesity",
1283
1418
  prognosis: (f) => `${n(d(f, "tokens"))} tokens ride along with every request. Rules in the middle get "lost in the middle", attention drifts and the bill grows with each turn.`,
1284
- action: () => "Move rarely-needed sections into skills or path-scoped rules; keep the always-on core under 3,500 tokens."
1419
+ action: (f) => `Move rarely-needed sections into skills or path-scoped rules; keep the always-on core under ${n(d(f, "threshold"))} tokens.`
1285
1420
  },
1286
1421
  WARN_DUPLICATE_RULES: {
1287
1422
  name: "Instruction Duplication Syndrome",
@@ -1398,24 +1533,24 @@ function healthGain(findings, f) {
1398
1533
  }
1399
1534
 
1400
1535
  // ../clinical/src/store.ts
1401
- import fs8 from "fs";
1402
- import path13 from "path";
1536
+ import fs9 from "fs";
1537
+ import path14 from "path";
1403
1538
  var MAX_VISITS = 200;
1404
- var historyFile = () => path13.join(stateDir(), "history.json");
1405
- var profileFile = () => path13.join(stateDir(), "profile.json");
1539
+ var historyFile = () => path14.join(stateDir(), "history.json");
1540
+ var profileFile = () => path14.join(stateDir(), "profile.json");
1406
1541
  function readJson(file2) {
1407
1542
  try {
1408
- return JSON.parse(fs8.readFileSync(file2, "utf8"));
1543
+ return JSON.parse(fs9.readFileSync(file2, "utf8"));
1409
1544
  } catch {
1410
1545
  return void 0;
1411
1546
  }
1412
1547
  }
1413
1548
  function writeJson(file2, v) {
1414
- fs8.mkdirSync(path13.dirname(file2), { recursive: true });
1415
- fs8.writeFileSync(file2 + ".tmp", JSON.stringify(v, null, 2));
1416
- fs8.renameSync(file2 + ".tmp", file2);
1549
+ fs9.mkdirSync(path14.dirname(file2), { recursive: true });
1550
+ fs9.writeFileSync(file2 + ".tmp", JSON.stringify(v, null, 2));
1551
+ fs9.renameSync(file2 + ".tmp", file2);
1417
1552
  }
1418
- var sameScan = (a2, b) => a2.global === b.global && a2.finops === b.finops && (!a2.finops || a2.days === b.days);
1553
+ var sameScan = (a2, b) => a2.global === b.global && a2.finops === b.finops && (!a2.finops || a2.days === b.days) && a2.config === b.config;
1419
1554
  function loadHistory(root, scan2) {
1420
1555
  const raw = readJson(historyFile());
1421
1556
  const visits = Array.isArray(raw) ? raw.flatMap((v) => {
@@ -1517,7 +1652,7 @@ var harnesses = [
1517
1652
  ];
1518
1653
 
1519
1654
  // ../clinical/src/engine.ts
1520
- var VERSION = true ? "0.2.3" : "0.0.0-dev";
1655
+ var VERSION = true ? "0.3.0" : "0.0.0-dev";
1521
1656
  var TRIAGE = { critical: "resuscitation", warning: "therapy", info: "preventive" };
1522
1657
  var ORDER = ["resuscitation", "therapy", "preventive"];
1523
1658
  var human = (k) => k.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
@@ -1573,19 +1708,20 @@ function diagnose(findings, lang, anamnesis = Anamnesis.parse({})) {
1573
1708
  var scanSettings = (opts) => ({
1574
1709
  global: opts.global !== false,
1575
1710
  finops: opts.finops !== false,
1576
- days: opts.days ?? 30
1711
+ days: opts.days ?? 30,
1712
+ config: opts.config ?? ""
1577
1713
  });
1578
1714
  async function checkup(opts) {
1579
1715
  const ex = await examine(opts.root, harnesses, { global: opts.global });
1580
1716
  let finops = null;
1581
- if (opts.finops !== false) finops = await analyze({ root: ex.vitals.root, files: ex.files, days: opts.days ?? 30 });
1717
+ if (opts.finops !== false) finops = await analyze({ root: ex.vitals.root, files: ex.files, days: opts.days ?? 30, config: ex.config });
1582
1718
  const findings = [...ex.findings, ...finops?.findings ?? []];
1583
1719
  const diagnoses = diagnose(findings, opts.lang, loadAnamnesis());
1584
1720
  const score = healthScore(findings);
1585
1721
  const counts = { resuscitation: 0, therapy: 0, preventive: 0 };
1586
1722
  for (const d2 of diagnoses) counts[d2.triage]++;
1587
1723
  const savings = findings.reduce((n2, f) => n2 + (f.monthlySavingsUsd ?? 0), 0);
1588
- const scan2 = scanSettings(opts);
1724
+ const scan2 = scanSettings({ ...opts, config: configHash(ex.config) });
1589
1725
  const previous = loadHistory(ex.vitals.root, scan2).at(-1) ?? null;
1590
1726
  const report2 = ClinicalReport.parse({
1591
1727
  tool: "ctxmedic",
@@ -1694,15 +1830,15 @@ async function askAi(provider, prompt) {
1694
1830
  }
1695
1831
 
1696
1832
  // ../server/src/index.ts
1697
- import crypto2 from "crypto";
1698
- import fs9 from "fs";
1699
- import path14 from "path";
1833
+ import crypto3 from "crypto";
1834
+ import fs10 from "fs";
1835
+ import path15 from "path";
1700
1836
  import { serve } from "@hono/node-server";
1701
1837
  import { serveStatic } from "@hono/node-server/serve-static";
1702
1838
  import { Hono } from "hono";
1703
1839
  function createApp(opts) {
1704
1840
  const app = new Hono();
1705
- const root = path14.resolve(opts.root);
1841
+ const root = path15.resolve(opts.root);
1706
1842
  app.use("/api/*", async (c, next) => {
1707
1843
  c.header("cache-control", "no-store");
1708
1844
  if (c.req.method !== "GET" && c.req.header("x-ctxmedic-token") !== opts.token) return c.json({ error: "invalid session token" }, 403);
@@ -1712,7 +1848,7 @@ function createApp(opts) {
1712
1848
  const lang = c.req.query("lang") ? resolveLang(c.req.query("lang")) : opts.lang;
1713
1849
  return c.json(await checkup({ root, lang, days: opts.days, record: c.req.query("record") === "1" }));
1714
1850
  });
1715
- app.get("/api/history", (c) => c.json(loadHistory(root, scanSettings({ days: opts.days }))));
1851
+ app.get("/api/history", (c) => c.json(loadHistory(root, scanSettings({ days: opts.days, config: configHash(loadConfig(root)) }))));
1716
1852
  app.get("/api/graph", async (c) => {
1717
1853
  const ex = await examine(root, harnesses);
1718
1854
  const nodes = [
@@ -1723,7 +1859,7 @@ function createApp(opts) {
1723
1859
  for (const f of ex.files) {
1724
1860
  for (const h of f.harnesses) edges.push({ source: `h:${h}`, target: f.path, kind: "loads" });
1725
1861
  if (f.isSymlink && f.realpath) {
1726
- if (!nodes.some((n2) => n2.id === f.realpath)) nodes.push({ id: f.realpath, kind: "target", label: path14.relative(root, f.realpath), tokens: f.tokens, broken: false, scope: f.scope });
1862
+ 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 });
1727
1863
  edges.push({ source: f.path, target: f.realpath, kind: "symlink" });
1728
1864
  }
1729
1865
  }
@@ -1742,15 +1878,15 @@ function createApp(opts) {
1742
1878
  return c.json({ error: e.message }, e instanceof FixRefusedError ? 409 : 500);
1743
1879
  }
1744
1880
  });
1745
- if (opts.publicDir && fs9.existsSync(path14.join(opts.publicDir, "index.html"))) {
1746
- const rel = path14.relative(process.cwd(), opts.publicDir) || ".";
1881
+ if (opts.publicDir && fs10.existsSync(path15.join(opts.publicDir, "index.html"))) {
1882
+ const rel = path15.relative(process.cwd(), opts.publicDir) || ".";
1747
1883
  app.use("/*", serveStatic({ root: rel }));
1748
- app.get("*", serveStatic({ path: path14.join(rel, "index.html") }));
1884
+ app.get("*", serveStatic({ path: path15.join(rel, "index.html") }));
1749
1885
  } else app.get("/", (c) => c.text("ctxmedic UI is not built. Run `pnpm build` in the repository."));
1750
1886
  return app;
1751
1887
  }
1752
1888
  async function startServer(opts) {
1753
- const token = crypto2.randomBytes(16).toString("hex");
1889
+ const token = crypto3.randomBytes(16).toString("hex");
1754
1890
  const app = createApp({ ...opts, token });
1755
1891
  return new Promise((resolve) => {
1756
1892
  const server2 = serve(
@@ -1827,7 +1963,7 @@ function report(r) {
1827
1963
  return [header(r), ...r.diagnoses.map((d2) => card(d2, r.lang) + "\n"), r.finops ? finopsSummary(r.finops, r.lang) : ""].join("\n");
1828
1964
  }
1829
1965
  var scanFlags = ({ scan: s }) => {
1830
- const f = [!s.global && "--no-global", !s.finops && "--no-finops", s.finops && s.days !== DEFAULT_SCAN.days && `--days ${s.days}`].filter(Boolean);
1966
+ const f = [!s.global && "--no-global", !s.finops && "--no-finops", s.finops && s.days !== DEFAULT_SCAN.days && `--days ${s.days}`, s.config && `config ${s.config}`].filter(Boolean);
1831
1967
  return f.length ? pc.yellow(` ${f.join(" ")}`) : "";
1832
1968
  };
1833
1969
  function history(visits) {
@@ -1838,14 +1974,14 @@ function history(visits) {
1838
1974
  // src/index.ts
1839
1975
  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");
1840
1976
  var ctx = (dir, o2) => ({
1841
- root: path15.resolve(dir ?? "."),
1977
+ root: path16.resolve(dir ?? "."),
1842
1978
  lang: resolveLang(o2.lang),
1843
1979
  days: Math.max(1, Number.parseInt(o2.days, 10) || 30),
1844
1980
  finops: o2.finops,
1845
1981
  global: o2.global
1846
1982
  });
1847
1983
  function fail(e) {
1848
- console.error(pc2.red(`\u2716 ${e instanceof FixRefusedError ? e.message : e.stack ?? e}`));
1984
+ console.error(pc2.red(`\u2716 ${e instanceof FixRefusedError || e instanceof ConfigError ? e.message : e.stack ?? e}`));
1849
1985
  process.exit(2);
1850
1986
  }
1851
1987
  var program = new Command().name("ctxmedic").description("The context medic for your AI coding setup: checkup, treat, savings.").version(VERSION);
@@ -1865,18 +2001,18 @@ common(program.command("treat [rx]").description("apply a prescription (e.g. RX-
1865
2001
  const m = messages(c.lang).cli;
1866
2002
  if (manual.length === picked.length) return console.log(pc2.yellow(m.noAutoFix));
1867
2003
  const plans = picked.flatMap((d2) => d2.finding.fix ? [d2.finding.fix] : []);
1868
- for (const plan of plans) for (const op of plan.ops) console.log(pc2.dim(` ${op.kind === "write" ? "write " : "symlink"} ${path15.relative(c.root, op.path)}${op.kind === "symlink" ? ` \u2192 ${op.target}` : ""}`));
2004
+ 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}` : ""}`));
1869
2005
  if (!o2.dryRun && !o2.yes) {
1870
2006
  const ok = await p2.confirm({ message: m.confirmApply });
1871
2007
  if (p2.isCancel(ok) || !ok) return p2.cancel(m.cancelled);
1872
2008
  }
1873
2009
  for (const plan of plans) {
1874
2010
  const res = await applyFix(plan, { root: c.root, dryRun: o2.dryRun, force: o2.force, global: false }).catch(fail);
1875
- console.log(`${o2.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${plan.title}${res.dryRun ? "" : pc2.dim(` backup: ${path15.relative(c.root, res.backupDir)}`)}`);
2011
+ console.log(`${o2.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${plan.title}${res.dryRun ? "" : pc2.dim(` backup: ${path16.relative(c.root, res.backupDir)}`)}`);
1876
2012
  }
1877
2013
  });
1878
2014
  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) => {
1879
- const root = path15.resolve(".");
2015
+ const root = path16.resolve(".");
1880
2016
  const m = messages(resolveLang(o2.lang)).cli;
1881
2017
  if (!id) {
1882
2018
  const all = await listBackups(root);
@@ -1891,8 +2027,8 @@ ${m.restoreHint}`));
1891
2027
  });
1892
2028
  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) => {
1893
2029
  const c = ctx(dir, o2);
1894
- const ex = await examine(c.root, harnesses, { global: c.global });
1895
- const f = await analyze({ root: c.root, files: ex.files, days: c.days }).catch(fail);
2030
+ const ex = await examine(c.root, harnesses, { global: c.global }).catch(fail);
2031
+ const f = await analyze({ root: c.root, files: ex.files, days: c.days, config: ex.config }).catch(fail);
1896
2032
  if (o2.json) return console.log(JSON.stringify(f, null, 2));
1897
2033
  console.log("\n" + finopsSummary(f, c.lang) + "\n");
1898
2034
  const r = await checkup({ ...c, record: false });
@@ -1950,10 +2086,10 @@ common(program.command("consult [path]").description("interactive appointment: a
1950
2086
  }
1951
2087
  p2.outro(m.goodbye);
1952
2088
  });
1953
- 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 : path15.resolve(dir ?? ".")))));
2089
+ 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 ?? ".")))));
1954
2090
  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) => {
1955
2091
  const c = ctx(dir, o2);
1956
- const publicDir = path15.join(path15.dirname(fileURLToPath(import.meta.url)), "..", "public");
2092
+ const publicDir = path16.join(path16.dirname(fileURLToPath(import.meta.url)), "..", "public");
1957
2093
  const { url } = await startServer({ root: c.root, lang: c.lang, days: c.days, port: Number(o2.port), publicDir }).catch(fail);
1958
2094
  console.log(`${pc2.bold("\u{1FA7A} ctxmedic UI")} ${pc2.cyan(url)}
1959
2095
  ${pc2.dim("Ctrl+C to stop. Listening on 127.0.0.1 only.")}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ctxmedic",
3
- "version": "0.2.3",
3
+ "version": "0.3.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",