ctxmedic 0.1.0 → 0.2.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 +39 -1
  2. package/dist/index.js +318 -203
  3. package/package.json +15 -4
package/README.md CHANGED
@@ -1,6 +1,13 @@
1
1
  # ctxmedic
2
2
 
3
- > The context medic for your AI coding setup.
3
+ [![npm](https://img.shields.io/npm/v/ctxmedic)](https://www.npmjs.com/package/ctxmedic)
4
+ [![downloads](https://img.shields.io/npm/dm/ctxmedic)](https://www.npmjs.com/package/ctxmedic)
5
+ [![CI](https://github.com/ponomarenko/ctxmedic/actions/workflows/ci.yml/badge.svg)](https://github.com/ponomarenko/ctxmedic/actions/workflows/ci.yml)
6
+ [![node](https://img.shields.io/node/v/ctxmedic)](https://www.npmjs.com/package/ctxmedic)
7
+ [![license](https://img.shields.io/badge/license-FSL--1.1--MIT-blue)](https://github.com/ponomarenko/ctxmedic/blob/main/LICENSE)
8
+
9
+ > The context medic for your AI coding setup: a linter, auto-fixer and
10
+ > token-cost analyzer for `CLAUDE.md`, `AGENTS.md`, Cursor rules, skills and MCP configs.
4
11
 
5
12
  ctxmedic examines the AI configuration of a project like a doctor examines a
6
13
  patient. It reads your `CLAUDE.md`, `AGENTS.md`, Cursor/Windsurf/Copilot/Cline
@@ -11,6 +18,11 @@ save tokens and money.
11
18
  Works with Claude Code, Cursor, Windsurf, Codex CLI, OpenCode, GitHub Copilot
12
19
  and Cline. 100% local: nothing leaves your machine.
13
20
 
21
+ **Why:** AI coding tools load your rules, skills and MCP tool schemas into every
22
+ request. Bloated or duplicated `CLAUDE.md` files, broken links, leaked secrets and
23
+ long sessions without `/compact` quietly cost tokens, money and answer quality.
24
+ ctxmedic finds them, explains them, and fixes them safely.
25
+
14
26
  ```bash
15
27
  npx ctxmedic checkup
16
28
  ```
@@ -36,6 +48,7 @@ npx ctxmedic checkup
36
48
  |---|---|
37
49
  | `ctxmedic checkup [path]` | Full examination. `--json` for machines, exit code 1 on 🔴 findings (CI gate). |
38
50
  | `ctxmedic treat RX-01` | Apply one prescription. `--all`, `--dry-run`, `--force`, `-y`. |
51
+ | `ctxmedic restore [backup\|latest]` | Undo a fix from `.ctxmedic/backups`. No argument lists backups. `--dry-run`, `--force`. |
39
52
  | `ctxmedic savings` | FinOps only: spend, run rate, cache hit ratio, savings. |
40
53
  | `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. |
41
54
  | `ctxmedic history` | Health Score over time. |
@@ -43,6 +56,31 @@ npx ctxmedic checkup
43
56
 
44
57
  Common options: `--days 30`, `--no-finops`, `--no-global`.
45
58
 
59
+ ## GitHub Action
60
+
61
+ Gate pull requests on the health of your AI configs. The action runs
62
+ `ctxmedic checkup --no-global --no-finops`, writes the cards to the job summary,
63
+ annotates the files, and fails the job on 🔴 findings.
64
+
65
+ ```yaml
66
+ # .github/workflows/ctxmedic.yml
67
+ name: ctxmedic
68
+ on: pull_request
69
+ jobs:
70
+ checkup:
71
+ runs-on: ubuntu-latest
72
+ steps:
73
+ - uses: actions/checkout@v4
74
+ - uses: ponomarenko/ctxmedic@main # pin a release tag once one includes the action
75
+ with:
76
+ fail-on: critical # or "warning" to fail on 🟡 too
77
+ # path: . # project folder
78
+ # version: 0.1.0 # ctxmedic version from npm (default: latest)
79
+ ```
80
+
81
+ Nothing leaves the runner: no telemetry, no network calls besides installing the
82
+ package from npm.
83
+
46
84
  ## Diagnoses
47
85
 
48
86
  | Code | Diagnosis | Auto-fix |
package/dist/index.js CHANGED
@@ -32,6 +32,25 @@ var FixOp = z.discriminatedUnion("kind", [
32
32
  z.object({ kind: z.literal("symlink"), path: z.string(), target: z.string() })
33
33
  ]);
34
34
  var FixPlan = z.object({ title: z.string(), ops: z.array(FixOp).min(1) });
35
+ var FixAfter = z.discriminatedUnion("kind", [
36
+ z.object({ kind: z.literal("write"), sha256: z.string() }),
37
+ z.object({ kind: z.literal("symlink"), target: z.string() })
38
+ ]);
39
+ var BackupManifest = z.object({
40
+ title: z.string(),
41
+ createdAt: z.string(),
42
+ entries: z.array(
43
+ z.object({
44
+ path: z.string(),
45
+ existed: z.boolean(),
46
+ /** Copy of the original, relative to the backup folder. */
47
+ backup: z.string().optional(),
48
+ /** Original symlink target. */
49
+ symlink: z.string().optional(),
50
+ after: FixAfter.optional()
51
+ })
52
+ )
53
+ });
35
54
  var Finding = z.object({
36
55
  ruleId: RuleId,
37
56
  severity: Severity,
@@ -676,46 +695,52 @@ async function runRules(ctx2, list = rules) {
676
695
  }
677
696
 
678
697
  // ../core/src/fix.ts
698
+ import crypto from "crypto";
679
699
  import fs5 from "fs/promises";
680
700
  import path8 from "path";
681
701
  var FixRefusedError = class extends Error {
682
702
  };
683
703
  var stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
704
+ var sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex");
705
+ var outside = (root, p3) => {
706
+ const rel = path8.relative(root, p3);
707
+ return rel.startsWith("..") || path8.isAbsolute(rel);
708
+ };
709
+ var backupsDir = (root) => path8.join(path8.resolve(root), ".ctxmedic", "backups");
684
710
  async function applyFix(planIn, opts) {
685
711
  const plan = FixPlan.parse(planIn);
686
712
  const root = path8.resolve(opts.root);
687
713
  const targets = plan.ops.map((o2) => path8.resolve(o2.path));
688
714
  for (const t2 of targets)
689
- if (path8.relative(root, t2).startsWith("..") && !opts.global)
715
+ if (outside(root, t2) && !opts.global)
690
716
  throw new FixRefusedError(`refusing to modify ${t2}: outside ${root} (use --global)`);
691
717
  if (!opts.force) {
692
- const dirty = dirtyFiles(root, targets.filter((t2) => !path8.relative(root, t2).startsWith("..")));
718
+ const dirty = dirtyFiles(root, targets.filter((t2) => !outside(root, t2)));
693
719
  if (dirty.length) throw new FixRefusedError(`uncommitted changes in ${dirty.join(", ")}; commit them or use --force`);
694
720
  }
695
- const backupDir = path8.join(root, ".ctxmedic", "backups", stamp());
721
+ const backupDir = path8.join(backupsDir(root), stamp());
696
722
  const describe = plan.ops.map((o2) => o2.kind === "write" ? `write ${o2.path}` : `symlink ${o2.path} -> ${o2.target}`);
697
723
  if (opts.dryRun) return { backupDir, applied: describe, dryRun: true };
698
- const manifest = {
699
- title: plan.title,
700
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
701
- entries: []
702
- };
724
+ const after = new Map(
725
+ plan.ops.map((o2) => [path8.resolve(o2.path), o2.kind === "write" ? { kind: "write", sha256: sha256(o2.content) } : { kind: "symlink", target: o2.target }])
726
+ );
727
+ const manifest = { title: plan.title, createdAt: (/* @__PURE__ */ new Date()).toISOString(), entries: [] };
703
728
  await fs5.mkdir(backupDir, { recursive: true });
704
- for (const t2 of targets) {
705
- const rel = path8.relative(root, t2).startsWith("..") ? path8.join("_outside", t2) : path8.relative(root, t2);
729
+ for (const t2 of new Set(targets)) {
730
+ const rel = outside(root, t2) ? path8.join("_outside", t2) : path8.relative(root, t2);
706
731
  let st;
707
732
  try {
708
733
  st = await fs5.lstat(t2);
709
734
  } catch {
710
- manifest.entries.push({ path: t2, existed: false });
735
+ manifest.entries.push({ path: t2, existed: false, after: after.get(t2) });
711
736
  continue;
712
737
  }
713
- if (st.isSymbolicLink()) manifest.entries.push({ path: t2, existed: true, symlink: await fs5.readlink(t2) });
738
+ if (st.isSymbolicLink()) manifest.entries.push({ path: t2, existed: true, symlink: await fs5.readlink(t2), after: after.get(t2) });
714
739
  else {
715
740
  const dest = path8.join(backupDir, rel);
716
741
  await fs5.mkdir(path8.dirname(dest), { recursive: true });
717
742
  await fs5.copyFile(t2, dest);
718
- manifest.entries.push({ path: t2, existed: true, backup: rel });
743
+ manifest.entries.push({ path: t2, existed: true, backup: rel, after: after.get(t2) });
719
744
  }
720
745
  }
721
746
  await fs5.writeFile(path8.join(backupDir, "manifest.json"), JSON.stringify(manifest, null, 2));
@@ -727,6 +752,47 @@ async function applyFix(planIn, opts) {
727
752
  }
728
753
  return { backupDir, applied: describe, dryRun: false };
729
754
  }
755
+ async function listBackups(root) {
756
+ const ids = await fs5.readdir(backupsDir(root)).catch(() => []);
757
+ const out = [];
758
+ for (const id of ids) {
759
+ const m = await readManifest(root, id).catch(() => null);
760
+ if (m) out.push({ id, title: m.title, createdAt: m.createdAt });
761
+ }
762
+ return out.sort((a2, b) => b.createdAt.localeCompare(a2.createdAt) || b.id.localeCompare(a2.id));
763
+ }
764
+ var readManifest = async (root, id) => BackupManifest.parse(JSON.parse(await fs5.readFile(path8.join(backupsDir(root), id, "manifest.json"), "utf8")));
765
+ async function unchanged(p3, after) {
766
+ const st = await fs5.lstat(p3).catch(() => null);
767
+ if (!st) return false;
768
+ if (after.kind === "symlink") return st.isSymbolicLink() && await fs5.readlink(p3) === after.target;
769
+ return st.isFile() && sha256(await fs5.readFile(p3)) === after.sha256;
770
+ }
771
+ async function restoreBackup(idIn, opts) {
772
+ const root = path8.resolve(opts.root);
773
+ const all = await listBackups(root);
774
+ const info = idIn === "latest" ? all[0] : all.find((b) => b.id === idIn);
775
+ if (!info) throw new FixRefusedError(all.length ? `backup ${idIn} not found; run \`ctxmedic restore\` to list backups` : "no backups to restore");
776
+ const dir = path8.join(backupsDir(root), info.id);
777
+ const manifest = await readManifest(root, info.id);
778
+ for (const e of manifest.entries) {
779
+ if (outside(root, e.path)) throw new FixRefusedError(`refusing to restore ${e.path}: outside ${root}`);
780
+ if (e.backup && outside(dir, path8.resolve(dir, e.backup))) throw new FixRefusedError(`invalid backup entry ${e.backup}`);
781
+ if (opts.force) continue;
782
+ if (!e.after) throw new FixRefusedError(`backup ${info.id} does not record what the fix wrote; use --force to restore anyway`);
783
+ if (!await unchanged(e.path, e.after)) throw new FixRefusedError(`${path8.relative(root, e.path)} changed after the fix; use --force to overwrite it`);
784
+ }
785
+ const restored = manifest.entries.map((e) => `${e.existed ? "restore" : "remove "} ${path8.relative(root, e.path)}`);
786
+ if (opts.dryRun) return { id: info.id, title: info.title, restored, dryRun: true };
787
+ for (const e of manifest.entries) {
788
+ await fs5.rm(e.path, { force: true });
789
+ if (!e.existed) continue;
790
+ await fs5.mkdir(path8.dirname(e.path), { recursive: true });
791
+ if (e.symlink !== void 0) await fs5.symlink(e.symlink, e.path);
792
+ else if (e.backup) await fs5.copyFile(path8.join(dir, e.backup), e.path);
793
+ }
794
+ return { id: info.id, title: info.title, restored, dryRun: false };
795
+ }
730
796
 
731
797
  // ../core/src/examine.ts
732
798
  import path9 from "path";
@@ -773,9 +839,13 @@ var Anamnesis = z2.object({
773
839
  primaryHarness: z2.string().optional(),
774
840
  monthlyBudgetUsd: z2.number().nonnegative().optional()
775
841
  });
842
+ var ScanSettings = z2.object({ global: z2.boolean(), finops: z2.boolean(), days: z2.number() });
843
+ var DEFAULT_SCAN = { global: true, finops: true, days: 30 };
776
844
  var Visit = z2.object({
777
845
  at: z2.string(),
778
846
  root: z2.string(),
847
+ /** Missing in history written by v0.1.0: those runs are assumed to use the defaults. */
848
+ scan: ScanSettings.default(DEFAULT_SCAN),
779
849
  healthScore: z2.number(),
780
850
  counts: Counts,
781
851
  monthlySpendUsd: z2.number().optional(),
@@ -796,187 +866,23 @@ var ClinicalReport = z2.object({
796
866
  potentialMonthlySavingsUsd: z2.number()
797
867
  });
798
868
 
799
- // ../clinical/src/i18n.ts
800
- var d = (f, k) => f.data[k];
801
- var n = (x) => Number(x ?? 0).toLocaleString("en");
802
- var usd = (x) => `$${Number(x ?? 0).toFixed(2)}`;
803
- var pct = (x) => `${Math.round(Number(x ?? 0) * 100)}%`;
804
- var en = {
805
- cards: {
806
- ERR_BROKEN_LINK: {
807
- name: "Symlink Necrosis",
808
- prognosis: (f) => d(f, "absolute") ? "Works on this machine only. Teammates and CI silently lose these instructions." : "The agent silently loses these instructions and runs without them. You will see it ignore rules you think are active.",
809
- action: (f) => f.fix ? "Rewrite the link as a relative symlink." : `Restore the target or delete the dead link: ${f.files[0]}`
810
- },
811
- WARN_CONTEXT_BLOAT: {
812
- name: "Context Obesity",
813
- 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.`,
814
- action: () => "Move rarely-needed sections into skills or path-scoped rules; keep the always-on core under 3,500 tokens."
815
- },
816
- WARN_DUPLICATE_RULES: {
817
- name: "Instruction Duplication Syndrome",
818
- prognosis: (f) => `${n(d(f, "wastedTokens"))} duplicated tokens. The copies drift apart and the agents get contradictory orders.`,
819
- action: (f) => f.fix ? `Merge into ${d(f, "hub")} (hub) and symlink every tool's file to it (spokes).` : "Keep one canonical file and symlink the others to it."
820
- },
821
- ERR_INVALID_SKILL: {
822
- name: "Skill Amnesia",
823
- prognosis: () => "The harness cannot discover or trigger this skill reliably. It costs tokens and never helps.",
824
- action: (f) => `Fix the SKILL.md frontmatter: ${d(f, "problem")}.`
825
- },
826
- CRIT_SECRET_LEAK: {
827
- name: "Credential Hemorrhage",
828
- prognosis: (f) => d(f, "exposed") ? "One `git add .` away from a public leak. Leaked keys are found by scanners within minutes." : "Plain-text keys in config files end up in backups, screenshots and support bundles.",
829
- action: () => "Rotate the key now, then reference it through an environment variable (`${VAR}`) and git-ignore the file."
830
- },
831
- INFO_UNSUPPORTED_SYNTAX: {
832
- name: "Cross-Harness Allergy",
833
- prognosis: (f) => `${d(f, "harness")} reads ${(d(f, "directives") ?? []).join(", ")} as plain text: noise at best, wrong instructions at worst.`,
834
- action: () => "Move tool-specific directives into that tool's own file, or keep shared files directive-free."
835
- },
836
- FIN_BLOAT_IGNORE: {
837
- name: "Indexing Bloat",
838
- prognosis: (f) => `${d(f, "harness")} indexes build output and lockfiles. Search results fill with junk and retrieval burns tokens.`,
839
- action: (f) => `Create ${d(f, "ignoreFile")} with the standard exclusions.`
840
- },
841
- FIN_UNUSED_MCP: {
842
- name: "Toxic MCP Syndrome",
843
- prognosis: (f) => `~${n(d(f, "schemaTokens"))} tokens of tool schemas in every request for a server nobody calls.`,
844
- action: (f) => d(f, "scope") === "global" ? `Move "${d(f, "server")}" from the global config into the project-level MCP config of the projects that need it.` : `Remove "${d(f, "server")}" from ${f.files[0]} or disable it until needed.`
845
- },
846
- FIN_MODEL_OVERKILL: {
847
- name: "Model Overkill",
848
- prognosis: (f) => `${d(f, "sessions")} trivial sessions paid frontier prices (${usd(d(f, "costUsd"))} in ${d(f, "days")} days).`,
849
- action: (f) => `Route one-shot tasks, routine skills and subagents to ${d(f, "suggested")} (set \`model:\` in the skill/agent frontmatter).`
850
- },
851
- FIN_CONTEXT_SNOWBALL: {
852
- name: "Context Snowball",
853
- prognosis: (f) => `Worst case: ${d(f, "worstSteps")} steps, peak context ${n(d(f, "worstMaxContext"))} tokens. Each step re-reads the whole history; quality drops as it grows.`,
854
- action: () => "Run /compact at task milestones and /clear between unrelated tasks; enable auto-compact."
855
- },
856
- FIN_CACHE_MISS: {
857
- name: "Prompt Cache Thrashing",
858
- prognosis: (f) => `Cache hit ratio ${pct(d(f, "cacheHitRatio"))}: you pay full price for context the provider could serve at ~10%.`,
859
- action: () => "Keep instructions static: no dates, branch names or random IDs at the top; avoid switching models mid-session."
860
- }
861
- },
862
- ui: {
863
- triage: { resuscitation: "\u{1F534} Resuscitation", therapy: "\u{1F7E1} Therapy", preventive: "\u{1F7E2} Preventive" },
864
- labs: "Vitals",
865
- prognosis: "Prognosis",
866
- health: "Health Score",
867
- savings: "Potential savings",
868
- perMonth: "/mo",
869
- healthy: "No complaints. The patient is healthy.",
870
- opinion: (s) => s >= 90 ? "Excellent condition. Only preventive care needed." : s >= 70 ? "Stable, but a few conditions need therapy." : s >= 40 ? "The patient needs treatment soon." : "Critical condition. Start with the red cards right now.",
871
- since: (x) => x === 0 ? "unchanged since the last visit" : x > 0 ? `+${x} since the last visit` : `${x} since the last visit`,
872
- manual: "manual treatment",
873
- noLogs: "No session logs found: FinOps analysis skipped.",
874
- spend: "Spend",
875
- runRate: "run rate"
876
- },
877
- cli: {
878
- noAutoFix: "No auto-fix: follow the prescription by hand.",
879
- confirmApply: "Apply? (originals are backed up to .ctxmedic/backups)",
880
- consultTitle: "\u{1FA7A} ctxmedic consultation",
881
- askPriority: "What matters most to you?",
882
- priority: { economy: "Saving tokens and money", balanced: "Balanced", quality: "Maximum answer quality" },
883
- askHarness: "Your main AI tool?",
884
- askBudget: "Monthly AI budget in $ (empty = no limit)",
885
- enterNumber: "Enter a number",
886
- examining: "Examining the patient",
887
- treatmentPlan: "Treatment plan",
888
- overBudget: (x) => `Over budget by $${x.toFixed(2)}/mo`,
889
- withinBudget: "Within budget",
890
- noAiProvider: "No Ollama, ANTHROPIC_API_KEY or OPENAI_API_KEY: AI review skipped.",
891
- confirmSend: (chars, provider) => `Send ${chars.toLocaleString("en")} characters of your instructions (secrets redacted) to ${provider}?`,
892
- nothingSent: "Nothing was sent.",
893
- consulting: (provider) => `Consulting ${provider}`,
894
- secondOpinion: "Second opinion",
895
- goodbye: "Get well soon! Follow-up: ctxmedic checkup",
896
- cancelled: "Cancelled"
897
- }
898
- };
899
- var catalogs = { en };
900
- var messages = (lang) => catalogs[lang];
901
- var cards = (lang) => catalogs[lang].cards;
902
- var t = (lang) => catalogs[lang].ui;
903
- var resolveLang = (x) => {
904
- const r = Lang.safeParse((x ?? process.env.CTXMEDIC_LANG ?? "en").slice(0, 2).toLowerCase());
905
- return r.success ? r.data : "en";
906
- };
907
-
908
- // ../clinical/src/score.ts
909
- var PENALTY = { critical: 25, warning: 8, info: 2 };
910
- function healthScore(findings) {
911
- const byRule = /* @__PURE__ */ new Map();
912
- for (const f of findings) {
913
- const p3 = PENALTY[f.severity];
914
- const e = byRule.get(f.ruleId) ?? { sum: 0, max: 0 };
915
- e.sum += p3;
916
- e.max = Math.max(e.max, p3);
917
- byRule.set(f.ruleId, e);
918
- }
919
- let total = 0;
920
- for (const e of byRule.values()) total += Math.min(e.sum, e.max * 2);
921
- return Math.max(0, Math.min(100, 100 - total));
922
- }
923
- function healthGain(findings, f) {
924
- return healthScore(findings.filter((x) => x !== f)) - healthScore(findings);
925
- }
926
-
927
- // ../clinical/src/store.ts
869
+ // ../finops/src/cache.ts
928
870
  import fs6 from "fs";
929
871
  import path10 from "path";
930
- var MAX_VISITS = 200;
931
- var historyFile = () => path10.join(stateDir(), "history.json");
932
- var profileFile = () => path10.join(stateDir(), "profile.json");
933
- function readJson(file2) {
934
- try {
935
- return JSON.parse(fs6.readFileSync(file2, "utf8"));
936
- } catch {
937
- return void 0;
938
- }
939
- }
940
- function writeJson(file2, v) {
941
- fs6.mkdirSync(path10.dirname(file2), { recursive: true });
942
- fs6.writeFileSync(file2 + ".tmp", JSON.stringify(v, null, 2));
943
- fs6.renameSync(file2 + ".tmp", file2);
944
- }
945
- function loadHistory(root) {
946
- const raw = readJson(historyFile());
947
- const visits = Array.isArray(raw) ? raw.flatMap((v) => {
948
- const r = Visit.safeParse(v);
949
- return r.success ? [r.data] : [];
950
- }) : [];
951
- return root ? visits.filter((v) => v.root === root) : visits;
952
- }
953
- function recordVisit(v) {
954
- writeJson(historyFile(), [...loadHistory(), Visit.parse(v)].slice(-MAX_VISITS));
955
- }
956
- function loadAnamnesis() {
957
- return Anamnesis.safeParse(readJson(profileFile())).data ?? Anamnesis.parse({});
958
- }
959
- function saveAnamnesis(a2) {
960
- writeJson(profileFile(), Anamnesis.parse(a2));
961
- }
962
-
963
- // ../finops/src/cache.ts
964
- import fs7 from "fs";
965
- import path11 from "path";
966
- var file = () => path11.join(stateDir(), "cache.json");
872
+ var file = () => path10.join(stateDir(), "cache.json");
967
873
  function loadCache() {
968
874
  try {
969
- const c = JSON.parse(fs7.readFileSync(file(), "utf8"));
970
- if (c?.v === 2 && c.files) return c;
875
+ const c = JSON.parse(fs6.readFileSync(file(), "utf8"));
876
+ if (c?.v === 3 && c.files) return c;
971
877
  } catch {
972
878
  }
973
- return { v: 2, files: {} };
879
+ return { v: 3, files: {} };
974
880
  }
975
881
  function saveCache(c) {
976
- fs7.mkdirSync(stateDir(), { recursive: true });
882
+ fs6.mkdirSync(stateDir(), { recursive: true });
977
883
  const tmp = file() + ".tmp";
978
- fs7.writeFileSync(tmp, JSON.stringify(c));
979
- fs7.renameSync(tmp, file());
884
+ fs6.writeFileSync(tmp, JSON.stringify(c));
885
+ fs6.renameSync(tmp, file());
980
886
  }
981
887
  async function cachedParse(paths, parse, cache) {
982
888
  const stats = [];
@@ -984,7 +890,7 @@ async function cachedParse(paths, parse, cache) {
984
890
  for (const p3 of paths) {
985
891
  let st;
986
892
  try {
987
- st = fs7.statSync(p3);
893
+ st = fs6.statSync(p3);
988
894
  } catch {
989
895
  continue;
990
896
  }
@@ -1002,7 +908,7 @@ async function cachedParse(paths, parse, cache) {
1002
908
  }
1003
909
 
1004
910
  // ../finops/src/detectors.ts
1005
- import path12 from "path";
911
+ import path11 from "path";
1006
912
 
1007
913
  // ../finops/src/pricing.ts
1008
914
  var PRICING_AS_OF = "2026-11-03";
@@ -1082,14 +988,16 @@ function unusedMcp({ sessions, days, files, root }) {
1082
988
  const model = dominant(hs) ?? "claude-sonnet-5-5";
1083
989
  const idle = Object.keys(mcpServers(f.path, f.text, root)).filter((name) => !calls[name] && !calls[name.replace(/[^\w]/g, "_")]);
1084
990
  if (!idle.length) continue;
1085
- const schemaTokens = MCP_SCHEMA_TOKENS * idle.length;
991
+ const measured = idle.map((name) => Math.max(0, ...hs.map((s) => s.mcpSchemaTokens?.[name] ?? s.mcpSchemaTokens?.[name.replace(/[^\w]/g, "_")] ?? 0)) || null);
992
+ const schemaTokens = measured.reduce((n2, t2) => n2 + (t2 ?? MCP_SCHEMA_TOKENS), 0);
993
+ const estimated = measured.some((t2) => t2 === null);
1086
994
  const usd3 = monthly(schemaTokens * steps * priceOf(model).price.cacheRead / 1e6, days);
1087
995
  out.push({
1088
996
  ruleId: "FIN_UNUSED_MCP",
1089
997
  severity: sev(usd3),
1090
998
  message: `${idle.length} MCP server(s) in ${f.rel} were called 0 times in ${days} days across ${steps.toLocaleString("en")} requests: ${idle.join(", ")}`,
1091
999
  files: [f.rel],
1092
- data: { server: idle.join(", "), harness: hid, scope: f.scope, steps, schemaTokens, days },
1000
+ data: { server: idle.join(", "), harness: hid, scope: f.scope, steps, schemaTokens, estimated, days },
1093
1001
  monthlySavingsUsd: round(usd3)
1094
1002
  });
1095
1003
  }
@@ -1137,7 +1045,7 @@ function contextSnowball({ sessions, days }) {
1137
1045
  ruleId: "FIN_CONTEXT_SNOWBALL",
1138
1046
  severity: sev(usd3),
1139
1047
  message: `${bad.length} session(s) ran >${SNOWBALL_STEPS} steps with 100k+ context and no /clear or /compact`,
1140
- files: bad.slice(0, 5).map((s) => `session ${path12.basename(s.file, ".jsonl")}`),
1048
+ files: bad.slice(0, 5).map((s) => `session ${path11.basename(s.file, ".jsonl")}`),
1141
1049
  data: { sessions: bad.length, worstSteps: worst.steps, worstMaxContext: worst.maxContext, days },
1142
1050
  monthlySavingsUsd: round(usd3)
1143
1051
  }
@@ -1171,14 +1079,14 @@ function cacheMiss({ sessions, days }) {
1171
1079
  var detectors = [unusedMcp, modelOverkill, contextSnowball, cacheMiss];
1172
1080
 
1173
1081
  // ../finops/src/parsers.ts
1174
- import fs8 from "fs";
1175
- import path13 from "path";
1082
+ import fs7 from "fs";
1083
+ import path12 from "path";
1176
1084
  import readline from "readline";
1177
1085
  var SNOWBALL_CONTEXT = 1e5;
1178
1086
  var HEALTHY_CONTEXT = 4e4;
1179
1087
  var MCP = /^mcp__(.+?)(?:__|$)/;
1180
1088
  function blank(file2, harness) {
1181
- return { file: file2, harness, steps: 0, models: {}, mcpCalls: {}, compactions: 0, maxContext: 0, heavySteps: 0, heavyExcessTokens: 0 };
1089
+ return { file: file2, harness, steps: 0, models: {}, mcpCalls: {}, mcpSchemaTokens: {}, compactions: 0, maxContext: 0, heavySteps: 0, heavyExcessTokens: 0 };
1182
1090
  }
1183
1091
  function addStep(s, model, u) {
1184
1092
  const m = s.models[model] ??= { steps: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, costUsd: 0 };
@@ -1198,8 +1106,12 @@ var mcp = (s, name) => {
1198
1106
  if (m) s.mcpCalls[m[1]] = (s.mcpCalls[m[1]] ?? 0) + 1;
1199
1107
  return Boolean(m);
1200
1108
  };
1109
+ var server = (name) => typeof name === "string" ? MCP.exec(name)?.[1] : void 0;
1110
+ function schemas(s, defs) {
1111
+ for (const [name, d2] of Object.entries(defs)) s.mcpSchemaTokens[name] = Math.max(s.mcpSchemaTokens[name] ?? 0, countTokens(JSON.stringify(d2)));
1112
+ }
1201
1113
  async function* lines(file2) {
1202
- const rl = readline.createInterface({ input: fs8.createReadStream(file2), crlfDelay: Infinity });
1114
+ const rl = readline.createInterface({ input: fs7.createReadStream(file2), crlfDelay: Infinity });
1203
1115
  for await (const line of rl) {
1204
1116
  if (!line) continue;
1205
1117
  try {
@@ -1219,6 +1131,14 @@ async function parseClaude(file2) {
1219
1131
  for await (const l of lines(file2)) {
1220
1132
  stamp2(s, l.timestamp);
1221
1133
  if (l.type === "system" && l.subtype === "compact_boundary" || l.isCompactSummary) s.compactions++;
1134
+ if (l.type === "api-request-shape" && Array.isArray(l.shape?.tools)) {
1135
+ const defs = {};
1136
+ for (const t2 of l.shape.tools) {
1137
+ const name = server(t2?.name);
1138
+ if (name) (defs[name] ??= []).push(t2);
1139
+ }
1140
+ schemas(s, defs);
1141
+ }
1222
1142
  if (l.type !== "assistant" || !l.message?.usage) continue;
1223
1143
  const msg = l.message;
1224
1144
  if (msg.model === "<synthetic>") continue;
@@ -1244,6 +1164,8 @@ async function parseCodex(file2) {
1244
1164
  const p3 = l.payload ?? {};
1245
1165
  if (l.type === "turn_context" && typeof p3.model === "string") model = p3.model;
1246
1166
  else if (l.type === "compacted") s.compactions++;
1167
+ else if (l.type === "response_item" && p3.type === "additional_tools" && Array.isArray(p3.tools))
1168
+ schemas(s, Object.fromEntries(p3.tools.flatMap((ns) => ns?.type === "namespace" && server(ns.name) ? [[server(ns.name), ns.tools ?? []]] : [])));
1247
1169
  else if (l.type === "response_item" && /function_call|custom_tool_call|mcp_tool_call/.test(p3.type ?? "")) mcp(s, p3.namespace) || mcp(s, p3.name);
1248
1170
  else if (l.type === "event_msg" && p3.type === "token_count" && p3.info?.last_token_usage) {
1249
1171
  const total = p3.info.total_token_usage?.total_tokens ?? -2;
@@ -1268,7 +1190,7 @@ async function parseCursor(file2) {
1268
1190
  for (const c of Array.isArray(content) ? content : []) if (c?.type === "tool_use" || c?.type === "tool-call") mcp(s, c.name ?? c.toolName);
1269
1191
  }
1270
1192
  if (!s.end) {
1271
- const t2 = fs8.statSync(file2).mtime.toISOString();
1193
+ const t2 = fs7.statSync(file2).mtime.toISOString();
1272
1194
  s.start ??= t2;
1273
1195
  s.end = t2;
1274
1196
  }
@@ -1343,6 +1265,174 @@ async function analyze(opts) {
1343
1265
  return buildReport(await loadSessions(days, opts.now), { ...opts, days });
1344
1266
  }
1345
1267
 
1268
+ // ../clinical/src/i18n.ts
1269
+ var d = (f, k) => f.data[k];
1270
+ var n = (x) => Number(x ?? 0).toLocaleString("en");
1271
+ var usd = (x) => `$${Number(x ?? 0).toFixed(2)}`;
1272
+ var pct = (x) => `${Math.round(Number(x ?? 0) * 100)}%`;
1273
+ var en = {
1274
+ cards: {
1275
+ ERR_BROKEN_LINK: {
1276
+ name: "Symlink Necrosis",
1277
+ prognosis: (f) => d(f, "absolute") ? "Works on this machine only. Teammates and CI silently lose these instructions." : "The agent silently loses these instructions and runs without them. You will see it ignore rules you think are active.",
1278
+ action: (f) => f.fix ? "Rewrite the link as a relative symlink." : `Restore the target or delete the dead link: ${f.files[0]}`
1279
+ },
1280
+ WARN_CONTEXT_BLOAT: {
1281
+ name: "Context Obesity",
1282
+ 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.`,
1283
+ action: () => "Move rarely-needed sections into skills or path-scoped rules; keep the always-on core under 3,500 tokens."
1284
+ },
1285
+ WARN_DUPLICATE_RULES: {
1286
+ name: "Instruction Duplication Syndrome",
1287
+ prognosis: (f) => `${n(d(f, "wastedTokens"))} duplicated tokens. The copies drift apart and the agents get contradictory orders.`,
1288
+ action: (f) => f.fix ? `Merge into ${d(f, "hub")} (hub) and symlink every tool's file to it (spokes).` : "Keep one canonical file and symlink the others to it."
1289
+ },
1290
+ ERR_INVALID_SKILL: {
1291
+ name: "Skill Amnesia",
1292
+ prognosis: () => "The harness cannot discover or trigger this skill reliably. It costs tokens and never helps.",
1293
+ action: (f) => `Fix the SKILL.md frontmatter: ${d(f, "problem")}.`
1294
+ },
1295
+ CRIT_SECRET_LEAK: {
1296
+ name: "Credential Hemorrhage",
1297
+ prognosis: (f) => d(f, "exposed") ? "One `git add .` away from a public leak. Leaked keys are found by scanners within minutes." : "Plain-text keys in config files end up in backups, screenshots and support bundles.",
1298
+ action: () => "Rotate the key now, then reference it through an environment variable (`${VAR}`) and git-ignore the file."
1299
+ },
1300
+ INFO_UNSUPPORTED_SYNTAX: {
1301
+ name: "Cross-Harness Allergy",
1302
+ prognosis: (f) => `${d(f, "harness")} reads ${(d(f, "directives") ?? []).join(", ")} as plain text: noise at best, wrong instructions at worst.`,
1303
+ action: () => "Move tool-specific directives into that tool's own file, or keep shared files directive-free."
1304
+ },
1305
+ FIN_BLOAT_IGNORE: {
1306
+ name: "Indexing Bloat",
1307
+ prognosis: (f) => `${d(f, "harness")} indexes build output and lockfiles. Search results fill with junk and retrieval burns tokens.`,
1308
+ action: (f) => `Create ${d(f, "ignoreFile")} with the standard exclusions.`
1309
+ },
1310
+ FIN_UNUSED_MCP: {
1311
+ name: "Toxic MCP Syndrome",
1312
+ prognosis: (f) => `${n(d(f, "schemaTokens"))} tokens of tool schemas (${d(f, "estimated") === false ? "measured from session logs" : `estimated at ${n(MCP_SCHEMA_TOKENS)} per server`}) in every request for a server nobody calls.`,
1313
+ action: (f) => d(f, "scope") === "global" ? `Move "${d(f, "server")}" from the global config into the project-level MCP config of the projects that need it.` : `Remove "${d(f, "server")}" from ${f.files[0]} or disable it until needed.`
1314
+ },
1315
+ FIN_MODEL_OVERKILL: {
1316
+ name: "Model Overkill",
1317
+ prognosis: (f) => `${d(f, "sessions")} trivial sessions paid frontier prices (${usd(d(f, "costUsd"))} in ${d(f, "days")} days).`,
1318
+ action: (f) => `Route one-shot tasks, routine skills and subagents to ${d(f, "suggested")} (set \`model:\` in the skill/agent frontmatter).`
1319
+ },
1320
+ FIN_CONTEXT_SNOWBALL: {
1321
+ name: "Context Snowball",
1322
+ prognosis: (f) => `Worst case: ${d(f, "worstSteps")} steps, peak context ${n(d(f, "worstMaxContext"))} tokens. Each step re-reads the whole history; quality drops as it grows.`,
1323
+ action: () => "Run /compact at task milestones and /clear between unrelated tasks; enable auto-compact."
1324
+ },
1325
+ FIN_CACHE_MISS: {
1326
+ name: "Prompt Cache Thrashing",
1327
+ prognosis: (f) => `Cache hit ratio ${pct(d(f, "cacheHitRatio"))}: you pay full price for context the provider could serve at ~10%.`,
1328
+ action: () => "Keep instructions static: no dates, branch names or random IDs at the top; avoid switching models mid-session."
1329
+ }
1330
+ },
1331
+ ui: {
1332
+ triage: { resuscitation: "\u{1F534} Resuscitation", therapy: "\u{1F7E1} Therapy", preventive: "\u{1F7E2} Preventive" },
1333
+ labs: "Vitals",
1334
+ prognosis: "Prognosis",
1335
+ health: "Health Score",
1336
+ savings: "Potential savings",
1337
+ perMonth: "/mo",
1338
+ healthy: "No complaints. The patient is healthy.",
1339
+ opinion: (s) => s >= 90 ? "Excellent condition. Only preventive care needed." : s >= 70 ? "Stable, but a few conditions need therapy." : s >= 40 ? "The patient needs treatment soon." : "Critical condition. Start with the red cards right now.",
1340
+ since: (x) => x === 0 ? "unchanged since the last visit" : x > 0 ? `+${x} since the last visit` : `${x} since the last visit`,
1341
+ manual: "manual treatment",
1342
+ noLogs: "No session logs found: FinOps analysis skipped.",
1343
+ spend: "Spend",
1344
+ runRate: "run rate"
1345
+ },
1346
+ cli: {
1347
+ noBackups: "No backups in .ctxmedic/backups: nothing to restore.",
1348
+ restoreHint: "Undo a fix: ctxmedic restore <backup> (or latest)",
1349
+ restored: (id) => `Restored backup ${id}`,
1350
+ noAutoFix: "No auto-fix: follow the prescription by hand.",
1351
+ confirmApply: "Apply? (originals are backed up to .ctxmedic/backups)",
1352
+ consultTitle: "\u{1FA7A} ctxmedic consultation",
1353
+ askPriority: "What matters most to you?",
1354
+ priority: { economy: "Saving tokens and money", balanced: "Balanced", quality: "Maximum answer quality" },
1355
+ askHarness: "Your main AI tool?",
1356
+ askBudget: "Monthly AI budget in $ (empty = no limit)",
1357
+ enterNumber: "Enter a number",
1358
+ examining: "Examining the patient",
1359
+ treatmentPlan: "Treatment plan",
1360
+ overBudget: (x) => `Over budget by $${x.toFixed(2)}/mo`,
1361
+ withinBudget: "Within budget",
1362
+ noAiProvider: "No Ollama, ANTHROPIC_API_KEY or OPENAI_API_KEY: AI review skipped.",
1363
+ confirmSend: (chars, provider) => `Send ${chars.toLocaleString("en")} characters of your instructions (secrets redacted) to ${provider}?`,
1364
+ nothingSent: "Nothing was sent.",
1365
+ consulting: (provider) => `Consulting ${provider}`,
1366
+ secondOpinion: "Second opinion",
1367
+ goodbye: "Get well soon! Follow-up: ctxmedic checkup",
1368
+ cancelled: "Cancelled"
1369
+ }
1370
+ };
1371
+ var catalogs = { en };
1372
+ var messages = (lang) => catalogs[lang];
1373
+ var cards = (lang) => catalogs[lang].cards;
1374
+ var t = (lang) => catalogs[lang].ui;
1375
+ var resolveLang = (x) => {
1376
+ const r = Lang.safeParse((x ?? process.env.CTXMEDIC_LANG ?? "en").slice(0, 2).toLowerCase());
1377
+ return r.success ? r.data : "en";
1378
+ };
1379
+
1380
+ // ../clinical/src/score.ts
1381
+ var PENALTY = { critical: 25, warning: 8, info: 2 };
1382
+ function healthScore(findings) {
1383
+ const byRule = /* @__PURE__ */ new Map();
1384
+ for (const f of findings) {
1385
+ const p3 = PENALTY[f.severity];
1386
+ const e = byRule.get(f.ruleId) ?? { sum: 0, max: 0 };
1387
+ e.sum += p3;
1388
+ e.max = Math.max(e.max, p3);
1389
+ byRule.set(f.ruleId, e);
1390
+ }
1391
+ let total = 0;
1392
+ for (const e of byRule.values()) total += Math.min(e.sum, e.max * 2);
1393
+ return Math.max(0, Math.min(100, 100 - total));
1394
+ }
1395
+ function healthGain(findings, f) {
1396
+ return healthScore(findings.filter((x) => x !== f)) - healthScore(findings);
1397
+ }
1398
+
1399
+ // ../clinical/src/store.ts
1400
+ import fs8 from "fs";
1401
+ import path13 from "path";
1402
+ var MAX_VISITS = 200;
1403
+ var historyFile = () => path13.join(stateDir(), "history.json");
1404
+ var profileFile = () => path13.join(stateDir(), "profile.json");
1405
+ function readJson(file2) {
1406
+ try {
1407
+ return JSON.parse(fs8.readFileSync(file2, "utf8"));
1408
+ } catch {
1409
+ return void 0;
1410
+ }
1411
+ }
1412
+ function writeJson(file2, v) {
1413
+ fs8.mkdirSync(path13.dirname(file2), { recursive: true });
1414
+ fs8.writeFileSync(file2 + ".tmp", JSON.stringify(v, null, 2));
1415
+ fs8.renameSync(file2 + ".tmp", file2);
1416
+ }
1417
+ var sameScan = (a2, b) => a2.global === b.global && a2.finops === b.finops && (!a2.finops || a2.days === b.days);
1418
+ function loadHistory(root, scan2) {
1419
+ const raw = readJson(historyFile());
1420
+ const visits = Array.isArray(raw) ? raw.flatMap((v) => {
1421
+ const r = Visit.safeParse(v);
1422
+ return r.success ? [r.data] : [];
1423
+ }) : [];
1424
+ return visits.filter((v) => (!root || v.root === root) && (!scan2 || sameScan(v.scan, scan2)));
1425
+ }
1426
+ function recordVisit(v) {
1427
+ writeJson(historyFile(), [...loadHistory(), Visit.parse(v)].slice(-MAX_VISITS));
1428
+ }
1429
+ function loadAnamnesis() {
1430
+ return Anamnesis.safeParse(readJson(profileFile())).data ?? Anamnesis.parse({});
1431
+ }
1432
+ function saveAnamnesis(a2) {
1433
+ writeJson(profileFile(), Anamnesis.parse(a2));
1434
+ }
1435
+
1346
1436
  // ../harnesses/src/index.ts
1347
1437
  var p = (x) => HarnessProfile.parse(x);
1348
1438
  var harnesses = [
@@ -1426,7 +1516,7 @@ var harnesses = [
1426
1516
  ];
1427
1517
 
1428
1518
  // ../clinical/src/engine.ts
1429
- var VERSION = true ? "0.1.0" : "0.0.0-dev";
1519
+ var VERSION = true ? "0.2.0" : "0.0.0-dev";
1430
1520
  var TRIAGE = { critical: "resuscitation", warning: "therapy", info: "preventive" };
1431
1521
  var ORDER = ["resuscitation", "therapy", "preventive"];
1432
1522
  var human = (k) => k.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
@@ -1479,6 +1569,11 @@ function diagnose(findings, lang, anamnesis = Anamnesis.parse({})) {
1479
1569
  };
1480
1570
  });
1481
1571
  }
1572
+ var scanSettings = (opts) => ({
1573
+ global: opts.global !== false,
1574
+ finops: opts.finops !== false,
1575
+ days: opts.days ?? 30
1576
+ });
1482
1577
  async function checkup(opts) {
1483
1578
  const ex = await examine(opts.root, harnesses, { global: opts.global });
1484
1579
  let finops = null;
@@ -1489,7 +1584,8 @@ async function checkup(opts) {
1489
1584
  const counts = { resuscitation: 0, therapy: 0, preventive: 0 };
1490
1585
  for (const d2 of diagnoses) counts[d2.triage]++;
1491
1586
  const savings = findings.reduce((n2, f) => n2 + (f.monthlySavingsUsd ?? 0), 0);
1492
- const previous = loadHistory(ex.vitals.root).at(-1) ?? null;
1587
+ const scan2 = scanSettings(opts);
1588
+ const previous = loadHistory(ex.vitals.root, scan2).at(-1) ?? null;
1493
1589
  const report2 = ClinicalReport.parse({
1494
1590
  tool: "ctxmedic",
1495
1591
  version: VERSION,
@@ -1508,6 +1604,7 @@ async function checkup(opts) {
1508
1604
  recordVisit({
1509
1605
  at: report2.generatedAt,
1510
1606
  root: ex.vitals.root,
1607
+ scan: scan2,
1511
1608
  healthScore: score,
1512
1609
  counts,
1513
1610
  monthlySpendUsd: finops?.monthlyRunRateUsd,
@@ -1596,7 +1693,7 @@ async function askAi(provider, prompt) {
1596
1693
  }
1597
1694
 
1598
1695
  // ../server/src/index.ts
1599
- import crypto from "crypto";
1696
+ import crypto2 from "crypto";
1600
1697
  import fs9 from "fs";
1601
1698
  import path14 from "path";
1602
1699
  import { serve } from "@hono/node-server";
@@ -1614,7 +1711,7 @@ function createApp(opts) {
1614
1711
  const lang = c.req.query("lang") ? resolveLang(c.req.query("lang")) : opts.lang;
1615
1712
  return c.json(await checkup({ root, lang, days: opts.days, record: c.req.query("record") === "1" }));
1616
1713
  });
1617
- app.get("/api/history", (c) => c.json(loadHistory(root)));
1714
+ app.get("/api/history", (c) => c.json(loadHistory(root, scanSettings({ days: opts.days }))));
1618
1715
  app.get("/api/graph", async (c) => {
1619
1716
  const ex = await examine(root, harnesses);
1620
1717
  const nodes = [
@@ -1652,12 +1749,12 @@ function createApp(opts) {
1652
1749
  return app;
1653
1750
  }
1654
1751
  async function startServer(opts) {
1655
- const token = crypto.randomBytes(16).toString("hex");
1752
+ const token = crypto2.randomBytes(16).toString("hex");
1656
1753
  const app = createApp({ ...opts, token });
1657
1754
  return new Promise((resolve) => {
1658
- const server = serve(
1755
+ const server2 = serve(
1659
1756
  { fetch: app.fetch, hostname: "127.0.0.1", port: opts.port ?? 7337 },
1660
- (info) => resolve({ url: `http://127.0.0.1:${info.port}/#token=${token}`, close: () => server.close() })
1757
+ (info) => resolve({ url: `http://127.0.0.1:${info.port}/#token=${token}`, close: () => server2.close() })
1661
1758
  );
1662
1759
  });
1663
1760
  }
@@ -1728,9 +1825,13 @@ function header(r) {
1728
1825
  function report(r) {
1729
1826
  return [header(r), ...r.diagnoses.map((d2) => card(d2, r.lang) + "\n"), r.finops ? finopsSummary(r.finops, r.lang) : ""].join("\n");
1730
1827
  }
1828
+ var scanFlags = ({ scan: s }) => {
1829
+ const f = [!s.global && "--no-global", !s.finops && "--no-finops", s.finops && s.days !== DEFAULT_SCAN.days && `--days ${s.days}`].filter(Boolean);
1830
+ return f.length ? pc.yellow(` ${f.join(" ")}`) : "";
1831
+ };
1731
1832
  function history(visits) {
1732
1833
  if (!visits.length) return pc.dim("No visits yet. Run `ctxmedic checkup`.");
1733
- 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)}`).join("\n");
1834
+ 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");
1734
1835
  }
1735
1836
 
1736
1837
  // src/index.ts
@@ -1773,6 +1874,20 @@ common(program.command("treat [rx]").description("apply a prescription (e.g. RX-
1773
1874
  console.log(`${o2.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${plan.title}${res.dryRun ? "" : pc2.dim(` backup: ${path15.relative(c.root, res.backupDir)}`)}`);
1774
1875
  }
1775
1876
  });
1877
+ 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) => {
1878
+ const root = path15.resolve(".");
1879
+ const m = messages(resolveLang(o2.lang)).cli;
1880
+ if (!id) {
1881
+ const all = await listBackups(root);
1882
+ if (!all.length) return console.log(m.noBackups);
1883
+ for (const b of all) console.log(`${pc2.cyan(b.id)} ${b.title}`);
1884
+ return console.log(pc2.dim(`
1885
+ ${m.restoreHint}`));
1886
+ }
1887
+ const r = await restoreBackup(id, { root, dryRun: o2.dryRun, force: o2.force }).catch(fail);
1888
+ for (const line of r.restored) console.log(pc2.dim(` ${line}`));
1889
+ console.log(`${r.dryRun ? pc2.yellow("dry-run") : pc2.green("\u2714")} ${m.restored(r.id)}: ${r.title}`);
1890
+ });
1776
1891
  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) => {
1777
1892
  const c = ctx(dir, o2);
1778
1893
  const ex = await examine(c.root, harnesses, { global: c.global });
package/package.json CHANGED
@@ -1,27 +1,38 @@
1
1
  {
2
2
  "name": "ctxmedic",
3
- "version": "0.1.0",
3
+ "version": "0.2.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",
7
- "author": "Vitalii Ponomarenko <https://github.com/ponomarenko>",
7
+ "author": "Vitalii Ponomarenko (https://github.com/ponomarenko)",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/ponomarenko/ctxmedic.git",
11
11
  "directory": "packages/cli"
12
12
  },
13
- "homepage": "https://github.com/ponomarenko/ctxmedic",
13
+ "homepage": "https://github.com/ponomarenko/ctxmedic#readme",
14
14
  "bugs": "https://github.com/ponomarenko/ctxmedic/issues",
15
15
  "keywords": [
16
16
  "ai",
17
+ "llm",
18
+ "claude",
17
19
  "claude-code",
20
+ "claude-md",
21
+ "agents-md",
18
22
  "cursor",
23
+ "cursor-rules",
19
24
  "windsurf",
20
25
  "codex",
26
+ "opencode",
27
+ "copilot",
28
+ "cline",
21
29
  "mcp",
30
+ "context-engineering",
22
31
  "linter",
32
+ "cli",
23
33
  "finops",
24
34
  "tokens",
35
+ "token-cost",
25
36
  "agents"
26
37
  ],
27
38
  "bin": {
@@ -39,7 +50,7 @@
39
50
  },
40
51
  "dependencies": {
41
52
  "@clack/prompts": "^0.9.1",
42
- "@hono/node-server": "^1.13.7",
53
+ "@hono/node-server": "^2.1.6",
43
54
  "commander": "^12.1.0",
44
55
  "hono": "^4.6.14",
45
56
  "js-tiktoken": "^1.0.16",