context-doctor 0.32.0 → 0.34.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 (50) hide show
  1. package/README.md +84 -694
  2. package/dist/autoclear.js +4 -1
  3. package/dist/autopilot.d.ts +20 -6
  4. package/dist/autopilot.js +105 -7
  5. package/dist/cachekey.d.ts +25 -0
  6. package/dist/cachekey.js +73 -0
  7. package/dist/cacheplan.d.ts +29 -9
  8. package/dist/cacheplan.js +110 -29
  9. package/dist/ci.js +9 -1
  10. package/dist/cli.js +359 -247
  11. package/dist/clihelp.d.ts +24 -0
  12. package/dist/clihelp.js +116 -0
  13. package/dist/codexroute.d.ts +46 -0
  14. package/dist/codexroute.js +122 -0
  15. package/dist/coldresume.d.ts +62 -0
  16. package/dist/coldresume.js +85 -6
  17. package/dist/compactquality.d.ts +3 -1
  18. package/dist/compactquality.js +15 -4
  19. package/dist/compactwindow.d.ts +31 -5
  20. package/dist/compactwindow.js +80 -25
  21. package/dist/diff.js +24 -2
  22. package/dist/doctor.d.ts +8 -2
  23. package/dist/doctor.js +138 -35
  24. package/dist/hook.js +23 -4
  25. package/dist/install.d.ts +35 -0
  26. package/dist/install.js +280 -48
  27. package/dist/invocation.d.ts +18 -0
  28. package/dist/invocation.js +49 -0
  29. package/dist/ledger.d.ts +2 -0
  30. package/dist/mcp.d.ts +5 -2
  31. package/dist/mcp.js +93 -299
  32. package/dist/mcpclient.js +45 -0
  33. package/dist/mcpschema.d.ts +1 -1
  34. package/dist/mcpschema.js +11 -8
  35. package/dist/optimize.d.ts +2 -0
  36. package/dist/optimize.js +2 -0
  37. package/dist/overhead.d.ts +12 -1
  38. package/dist/overhead.js +31 -7
  39. package/dist/preferences.d.ts +1 -1
  40. package/dist/preferences.js +5 -5
  41. package/dist/proxy.d.ts +14 -1
  42. package/dist/proxy.js +45 -4
  43. package/dist/savings.d.ts +17 -1
  44. package/dist/savings.js +12 -13
  45. package/dist/session.d.ts +15 -0
  46. package/dist/session.js +43 -0
  47. package/dist/subagentpay.d.ts +1 -1
  48. package/dist/subagentpay.js +3 -2
  49. package/package.json +5 -8
  50. package/skills/context-doctor/SKILL.md +3 -3
package/dist/install.js CHANGED
@@ -6,10 +6,11 @@
6
6
  * Every config edit is a careful JSON merge with a .backup file written first.
7
7
  * `context-doctor uninstall` reverses it.
8
8
  */
9
- import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync, rmSync } from "node:fs";
9
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, copyFileSync, rmSync } from "node:fs";
10
10
  import { homedir, platform } from "node:os";
11
11
  import { delimiter, dirname, join, sep } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
+ import { selfCommand, withInvocation } from "./invocation.js";
13
14
  function claudeDesktopConfigPath() {
14
15
  switch (platform()) {
15
16
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -98,6 +99,62 @@ export function launcherNamesMissingPackage(entry) {
98
99
  return false;
99
100
  return rest.find((w) => !w.startsWith("-")) === "context-doctor-mcp";
100
101
  }
102
+ /**
103
+ * The Claude Code plugin's key in enabledPlugins: "<plugin>@<marketplace>".
104
+ * Our marketplace (.claude-plugin/marketplace.json) is named context-doctor
105
+ * and lists one plugin, context-doctor, so the official key is
106
+ * "context-doctor@context-doctor"; a copy listed in another marketplace keeps
107
+ * the plugin name, so any "context-doctor@…" key is ours.
108
+ */
109
+ export const PLUGIN_KEY = "context-doctor@context-doctor";
110
+ export function isOurPluginKey(key) {
111
+ return key === PLUGIN_KEY || key.startsWith("context-doctor@");
112
+ }
113
+ /**
114
+ * Is the context-doctor plugin switched on in the user's Claude Code
115
+ * settings? The plugin brings its own MCP server, skills and hooks, so
116
+ * `install` adding them as well makes Claude Code load the server's
117
+ * instructions and tools twice.
118
+ */
119
+ export function claudePluginEnabled(home = homedir()) {
120
+ try {
121
+ const plugins = readJson(join(home, ".claude", "settings.json")).enabledPlugins ?? {};
122
+ return Object.entries(plugins).some(([key, on]) => isOurPluginKey(key) && on === true);
123
+ }
124
+ catch {
125
+ return false; // an unreadable settings.json is reported by the hook step
126
+ }
127
+ }
128
+ /** What `install` put into Claude Code that the plugin also provides, by name. */
129
+ export function claudeInstalledCopies(home = homedir()) {
130
+ const found = [];
131
+ try {
132
+ if (readJson(join(home, ".claude.json")).mcpServers?.["context-doctor"])
133
+ found.push("MCP server in ~/.claude.json");
134
+ }
135
+ catch { /* unreadable: not ours to judge here */ }
136
+ try {
137
+ const hooks = readJson(join(home, ".claude", "settings.json")).hooks ?? {};
138
+ if (["UserPromptSubmit", "PreCompact", "SessionStart"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
139
+ found.push("hooks in ~/.claude/settings.json");
140
+ }
141
+ catch { /* unreadable */ }
142
+ if (existsSync(join(home, ".claude", "skills", "context-doctor", "SKILL.md")))
143
+ found.push("skill in ~/.claude/skills/context-doctor");
144
+ return found;
145
+ }
146
+ /**
147
+ * A config that configures nothing: `{}`, or only empty `mcpServers` /
148
+ * `hooks` containers (plus `extraKeys`, e.g. the `version` install writes
149
+ * into Cursor's hooks.json). It is what install's own writes leave once our
150
+ * entries are gone, and to an app it is the same as no file at all.
151
+ */
152
+ export function isEmptyStub(config, extraKeys = []) {
153
+ if (!config || typeof config !== "object" || Array.isArray(config))
154
+ return false;
155
+ const empty = (v) => v !== null && typeof v === "object" && Object.keys(v).length === 0;
156
+ return Object.entries(config).every(([k, v]) => ((k === "mcpServers" || k === "hooks") && empty(v)) || extraKeys.includes(k));
157
+ }
101
158
  export function readJson(path) {
102
159
  if (!existsSync(path))
103
160
  return {};
@@ -218,8 +275,8 @@ function uninstallStatusLine() {
218
275
  const current = settings.statusLine?.command;
219
276
  if (current && isOurStatusLine(current)) {
220
277
  delete settings.statusLine;
221
- writeJsonWithBackup(settingsPath, settings);
222
- console.log("✓ Claude Code status line removed");
278
+ writeUninstalled(settingsPath, settings);
279
+ done("✓ Claude Code status line removed");
223
280
  }
224
281
  }
225
282
  /** True when the hook had to fall back to npx — worth telling the user. */
@@ -249,9 +306,12 @@ function isOurHookEntry(entry) {
249
306
  function installHook() {
250
307
  const settings = join(homedir(), ".claude", "settings.json");
251
308
  const path = installHookInto(settings, join(homedir(), ".claude"));
252
- // The same command also answers PreCompact: what each compaction's summary must keep.
253
- if (path)
309
+ // The same command also answers PreCompact (what each compaction's summary
310
+ // must keep) and SessionStart (Claude Code's verdict on a resumed cache).
311
+ if (path) {
254
312
  installHookInto(settings, join(homedir(), ".claude"), "PreCompact");
313
+ installHookInto(settings, join(homedir(), ".claude"), "SessionStart");
314
+ }
255
315
  return path;
256
316
  }
257
317
  /**
@@ -293,6 +353,7 @@ function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit") {
293
353
  function uninstallHook() {
294
354
  uninstallHookFrom(join(homedir(), ".claude", "settings.json"), "Claude Code every-prompt hook");
295
355
  uninstallHookFrom(join(homedir(), ".claude", "settings.json"), "Claude Code compaction hook", "PreCompact");
356
+ uninstallHookFrom(join(homedir(), ".claude", "settings.json"), "Claude Code session-start hook", "SessionStart");
296
357
  uninstallHookFrom(join(homedir(), ".codex", "hooks.json"), "Codex every-prompt hook");
297
358
  uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent");
298
359
  uninstallCursorHook();
@@ -308,7 +369,16 @@ function uninstallHook() {
308
369
  export function cursorHooksPath() {
309
370
  return join(homedir(), ".cursor", "hooks.json");
310
371
  }
311
- const isOurCursorEntry = (e) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(String(e?.command ?? ""));
372
+ export const isOurCursorEntry = (e) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(String(e?.command ?? ""));
373
+ /**
374
+ * Cursor's events whose `additional_context` can reach its agent: after a
375
+ * tool call, after a failed one, and at the start of a chat. Cursor 3.18's
376
+ * agent runtime attaches the first two to the tool result (Cursor confirmed
377
+ * postToolUseFailure delivery in 3.17.8); before 3.17 it dropped postToolUse
378
+ * output (staff-confirmed, March 2026). sessionStart is the documented way
379
+ * to add context to a chat's start, and serves a resumed heavy chat.
380
+ */
381
+ export const CURSOR_HOOK_EVENTS = ["postToolUse", "postToolUseFailure", "sessionStart"];
312
382
  export function installCursorHook() {
313
383
  if (!existsSync(join(homedir(), ".cursor")))
314
384
  return null;
@@ -316,13 +386,18 @@ export function installCursorHook() {
316
386
  const config = readJson(path);
317
387
  config.version = config.version ?? 1;
318
388
  config.hooks = config.hooks ?? {};
319
- const entries = config.hooks.postToolUse ?? [];
320
389
  const want = hookCommand();
321
- const ours = entries.filter(isOurCursorEntry);
322
- if (ours.length === 1 && ours[0].command === want)
323
- return path; // already correct
324
- config.hooks.postToolUse = [...entries.filter((e) => !isOurCursorEntry(e)), { command: want, timeout: 10 }];
325
- writeJsonWithBackup(path, config);
390
+ let changed = false;
391
+ for (const event of CURSOR_HOOK_EVENTS) {
392
+ const entries = config.hooks[event] ?? [];
393
+ const ours = entries.filter(isOurCursorEntry);
394
+ if (ours.length === 1 && ours[0].command === want)
395
+ continue; // already correct
396
+ config.hooks[event] = [...entries.filter((e) => !isOurCursorEntry(e)), { command: want, timeout: 10 }];
397
+ changed = true;
398
+ }
399
+ if (changed)
400
+ writeJsonWithBackup(path, config);
326
401
  return path;
327
402
  }
328
403
  function uninstallCursorHook() {
@@ -330,18 +405,24 @@ function uninstallCursorHook() {
330
405
  if (!existsSync(path))
331
406
  return;
332
407
  const config = readJson(path);
333
- const entries = config.hooks?.postToolUse;
334
- if (!entries)
335
- return;
336
- const filtered = entries.filter((e) => !isOurCursorEntry(e));
337
- if (filtered.length === entries.length)
408
+ let removed = false;
409
+ for (const event of CURSOR_HOOK_EVENTS) {
410
+ const entries = config.hooks?.[event];
411
+ if (!entries)
412
+ continue;
413
+ const filtered = entries.filter((e) => !isOurCursorEntry(e));
414
+ if (filtered.length === entries.length)
415
+ continue;
416
+ removed = true;
417
+ if (filtered.length === 0)
418
+ delete config.hooks[event];
419
+ else
420
+ config.hooks[event] = filtered;
421
+ }
422
+ if (!removed)
338
423
  return;
339
- if (filtered.length === 0)
340
- delete config.hooks.postToolUse;
341
- else
342
- config.hooks.postToolUse = filtered;
343
- writeJsonWithBackup(path, config);
344
- console.log("✓ Cursor after-tool-call hook removed");
424
+ writeUninstalled(path, config, ["version"]);
425
+ done("✓ Cursor hooks removed");
345
426
  }
346
427
  function uninstallHookFrom(settingsPath, label, event = "UserPromptSubmit") {
347
428
  if (!existsSync(settingsPath))
@@ -355,8 +436,8 @@ function uninstallHookFrom(settingsPath, label, event = "UserPromptSubmit") {
355
436
  settings.hooks[event] = filtered;
356
437
  if (filtered.length === 0)
357
438
  delete settings.hooks[event];
358
- writeJsonWithBackup(settingsPath, settings);
359
- console.log(`✓ ${label} removed`);
439
+ writeUninstalled(settingsPath, settings);
440
+ done(`✓ ${label} removed`);
360
441
  }
361
442
  }
362
443
  function installSkill() {
@@ -559,20 +640,31 @@ function uninstallCodex() {
559
640
  const current = readFileSync(configPath, "utf8");
560
641
  const next = removeCodexMcpTable(current);
561
642
  if (next !== current) {
562
- backupOnce(configPath);
563
- writeFileSync(configPath, next);
564
- console.log("✓ Codex: MCP server removed");
643
+ // A config.toml install created and that now holds nothing goes too.
644
+ const backup = configPath + BACKUP_SUFFIX;
645
+ let created = !existsSync(backup);
646
+ if (!created) {
647
+ try {
648
+ const before = readFileSync(backup, "utf8");
649
+ created = before !== removeCodexMcpTable(before) && removeCodexMcpTable(before).trim() === "";
650
+ }
651
+ catch { /* unreadable backup: the file was the user's */ }
652
+ }
653
+ if (created && next.trim() === "") {
654
+ rmSync(configPath);
655
+ deletedStubs.push(configPath);
656
+ }
657
+ else {
658
+ writeFileSync(configPath, next);
659
+ }
660
+ done("✓ Codex: MCP server removed");
565
661
  }
566
662
  }
567
663
  }
568
664
  catch (e) {
569
665
  console.error(`✗ Codex MCP: ${e.message}`);
570
666
  }
571
- const skillDir = join(dir, "skills", "context-doctor");
572
- if (existsSync(skillDir)) {
573
- rmSync(skillDir, { recursive: true });
574
- console.log("✓ Codex skill removed");
575
- }
667
+ removeSkill(join(dir, "skills", "context-doctor"), "Codex skill");
576
668
  }
577
669
  /**
578
670
  * Install into every detected app.
@@ -594,7 +686,22 @@ export function runInstall(options = {}) {
594
686
  return { failures: [] };
595
687
  }
596
688
  const failures = [];
689
+ // The plugin already gives Claude Code the server, skill and hooks; a
690
+ // second copy of each makes every session load the instructions and the
691
+ // tools twice. Claude Code is skipped; the other apps are not.
692
+ const viaPlugin = claudePluginEnabled();
693
+ if (viaPlugin) {
694
+ console.log("– Claude Code: skipped the MCP server, skill and hooks. The context-doctor plugin is enabled and");
695
+ console.log(" provides them already; installing them as well would load its instructions and tools twice.");
696
+ const copies = claudeInstalledCopies();
697
+ if (copies.length > 0) {
698
+ console.log(` An earlier install is still in place (${copies.join(", ")}): \`${selfCommand("uninstall")}\``);
699
+ console.log(` removes it, then \`${selfCommand("install")}\` wires the other apps again.`);
700
+ }
701
+ }
597
702
  for (const target of found) {
703
+ if (viaPlugin && target.name === "Claude Code")
704
+ continue;
598
705
  try {
599
706
  const config = readJson(target.configPath);
600
707
  config.mcpServers = config.mcpServers ?? {};
@@ -609,7 +716,7 @@ export function runInstall(options = {}) {
609
716
  }
610
717
  }
611
718
  try {
612
- const skillPath = installSkill();
719
+ const skillPath = viaPlugin ? null : installSkill();
613
720
  if (skillPath)
614
721
  console.log(`✓ Agent Skill installed for Claude Code (${skillPath})`);
615
722
  }
@@ -618,7 +725,7 @@ export function runInstall(options = {}) {
618
725
  failures.push("Agent Skill");
619
726
  }
620
727
  try {
621
- const hookPath = installHook();
728
+ const hookPath = viaPlugin ? null : installHook();
622
729
  if (hookPath) {
623
730
  console.log(`✓ Claude Code every-prompt hook installed (${hookPath}) — heavy sessions get automatic hygiene guidance`);
624
731
  // npx resolves the package on every single prompt; a global install makes
@@ -637,7 +744,7 @@ export function runInstall(options = {}) {
637
744
  try {
638
745
  const cursorHook = installCursorHook();
639
746
  if (cursorHook)
640
- console.log(`✓ Cursor after-tool-call hook installed (${cursorHook}) — Cursor's agent gets the same guidance in heavy sessions`);
747
+ console.log(`✓ Cursor hooks installed (${cursorHook}: after each tool call, after a failed one, at chat start) — Cursor's agent gets the same guidance in heavy sessions`);
641
748
  }
642
749
  catch (e) {
643
750
  console.error(`✗ Cursor hook: ${e.message}`);
@@ -684,9 +791,9 @@ export function runInstall(options = {}) {
684
791
  else {
685
792
  console.log("\nDone. Restart the apps to pick up the new tools, then try:");
686
793
  console.log(' "What\'s eating my context?" — or paste a conversation and ask for a profile.');
687
- console.log("See what it is worth on your own sessions: context-doctor savings");
794
+ console.log(`See what it is worth on your own sessions: ${selfCommand("savings")}`);
688
795
  console.log("Chat apps (Claude Desktop, claude.ai, ChatGPT, phones) have no hook. To make the rules standing there:");
689
- console.log(" context-doctor instructions --copy then paste into the app's preferences (it tells you where).");
796
+ console.log(` ${selfCommand("instructions --copy")} then paste into the app's preferences (it tells you where).`);
690
797
  }
691
798
  return { failures };
692
799
  }
@@ -721,7 +828,7 @@ async function uninstallAutopilot() {
721
828
  console.log(line);
722
829
  }
723
830
  catch (e) {
724
- console.error(`✗ Autopilot: ${e.message} (run: context-doctor autopilot off)`);
831
+ console.error(withInvocation(`✗ Autopilot: ${e.message} (run: context-doctor autopilot off)`));
725
832
  return;
726
833
  }
727
834
  // `off` restores only what a readable config describes. A damaged one
@@ -740,6 +847,112 @@ async function uninstallAutopilot() {
740
847
  console.error(`✗ Autopilot: ${e.message}`);
741
848
  }
742
849
  }
850
+ // -- Uninstall: take out exactly what install put in.
851
+ const BACKUP_SUFFIX = ".context-doctor.backup";
852
+ /** What this uninstall run changed, and the stub files it deleted. */
853
+ let changes = 0;
854
+ let deletedStubs = [];
855
+ /** Print one thing uninstall did, and count it. */
856
+ function done(line) {
857
+ changes++;
858
+ console.log(line);
859
+ }
860
+ /** A JSON config with our entries taken out, the way uninstall takes them out. */
861
+ function withoutOurs(config) {
862
+ const c = structuredClone(config);
863
+ if (c.mcpServers && typeof c.mcpServers === "object")
864
+ delete c.mcpServers["context-doctor"];
865
+ if (c.hooks && typeof c.hooks === "object") {
866
+ for (const [event, list] of Object.entries(c.hooks)) {
867
+ if (!Array.isArray(list))
868
+ continue;
869
+ const kept = list.filter((e) => !isOurHookEntry(e) && !isOurCursorEntry(e));
870
+ if (kept.length > 0)
871
+ c.hooks[event] = kept;
872
+ else
873
+ delete c.hooks[event];
874
+ }
875
+ }
876
+ if (typeof c.statusLine?.command === "string" && isOurStatusLine(c.statusLine.command))
877
+ delete c.statusLine;
878
+ return c;
879
+ }
880
+ /**
881
+ * The file as it was before install, as far as its backup can tell:
882
+ * `created` when install made the file (no backup was needed), or when the
883
+ * backup is only an earlier install's own write (install run twice);
884
+ * `before` is the backup without our entries.
885
+ */
886
+ function installOrigin(path, extraKeys) {
887
+ const backup = path + BACKUP_SUFFIX;
888
+ if (!existsSync(backup))
889
+ return { created: true, before: {} };
890
+ try {
891
+ const raw = JSON.parse(readFileSync(backup, "utf8"));
892
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
893
+ return { created: false, before: {} };
894
+ const before = withoutOurs(raw);
895
+ const hadOurs = JSON.stringify(before) !== JSON.stringify(raw);
896
+ return { created: hadOurs && isEmptyStub(before, extraKeys), before };
897
+ }
898
+ catch {
899
+ return { created: false, before: {} }; // unreadable backup: the file was the user's
900
+ }
901
+ }
902
+ /**
903
+ * Write a config with our entries removed. Containers install added
904
+ * (`mcpServers`, `hooks`, Cursor's `version`) go once empty, unless the file
905
+ * had them before install; a file install created that now configures
906
+ * nothing is deleted rather than left as `{"mcpServers":{}}`. No backup is
907
+ * written: the one install made of the user's original is kept as it is.
908
+ */
909
+ function writeUninstalled(path, config, extraKeys = []) {
910
+ const { created, before } = installOrigin(path, extraKeys);
911
+ for (const key of ["mcpServers", "hooks"]) {
912
+ const v = config[key];
913
+ if (v && typeof v === "object" && Object.keys(v).length === 0 && !(key in before))
914
+ delete config[key];
915
+ }
916
+ if (!("hooks" in config))
917
+ for (const key of extraKeys)
918
+ if (!(key in before))
919
+ delete config[key];
920
+ if (created && isEmptyStub(config, extraKeys)) {
921
+ rmSync(path);
922
+ deletedStubs.push(path);
923
+ return;
924
+ }
925
+ writeFileSync(path, JSON.stringify(config, null, 2));
926
+ }
927
+ /** Remove the SKILL.md install copied, and its folder once nothing else is in it. */
928
+ function removeSkill(dir, label) {
929
+ const file = join(dir, "SKILL.md");
930
+ if (!existsSync(file))
931
+ return;
932
+ rmSync(file);
933
+ try {
934
+ if (readdirSync(dir).length === 0)
935
+ rmSync(dir, { recursive: true });
936
+ }
937
+ catch { /* already gone */ }
938
+ done(`✓ ${label} removed`);
939
+ }
940
+ /** Every config file install or autopilot may write. */
941
+ function configPaths() {
942
+ return [
943
+ ...targets().map((t) => t.configPath),
944
+ join(homedir(), ".claude", "settings.json"),
945
+ cursorHooksPath(),
946
+ join(codexDir(), "config.toml"),
947
+ join(codexDir(), "hooks.json"),
948
+ geminiSettingsPath(),
949
+ ].filter((p, i, all) => all.indexOf(p) === i);
950
+ }
951
+ /** "~/..." for a path under the home directory. */
952
+ function tilde(p) {
953
+ const home = homedir();
954
+ return p.startsWith(home) ? "~" + p.slice(home.length) : p;
955
+ }
743
956
  /** Everything of ours under ~/.claude besides configs: state, ledger, autopilot bookkeeping. */
744
957
  const OUR_CLAUDE_FILES = [
745
958
  ".context-doctor-hook-state.json",
@@ -752,8 +965,18 @@ const OUR_CLAUDE_FILES = [
752
965
  ".context-doctor-proxy-restart",
753
966
  ];
754
967
  export async function runUninstall() {
968
+ changes = 0;
969
+ deletedStubs = [];
970
+ // Uninstall writes no backups: each .context-doctor.backup already holds
971
+ // the user's file from before install, and overwriting it with the
972
+ // installed state (as every write here used to) lost that original.
973
+ for (const p of configPaths())
974
+ backedUp.add(p);
755
975
  // First: if anything below fails, Claude Code must still reach the API.
976
+ const hadAutopilot = existsSync(join(homedir(), ".claude", ".context-doctor-autopilot.json"));
756
977
  await uninstallAutopilot();
978
+ if (hadAutopilot)
979
+ changes++;
757
980
  for (const target of targets().filter((t) => t.detect())) {
758
981
  try {
759
982
  if (!existsSync(target.configPath))
@@ -761,19 +984,15 @@ export async function runUninstall() {
761
984
  const config = readJson(target.configPath);
762
985
  if (config.mcpServers?.["context-doctor"]) {
763
986
  delete config.mcpServers["context-doctor"];
764
- writeJsonWithBackup(target.configPath, config);
765
- console.log(`✓ ${target.name}: MCP server removed`);
987
+ writeUninstalled(target.configPath, config);
988
+ done(`✓ ${target.name}: MCP server removed`);
766
989
  }
767
990
  }
768
991
  catch (e) {
769
992
  console.error(`✗ ${target.name}: ${e.message}`);
770
993
  }
771
994
  }
772
- const skillDir = join(homedir(), ".claude", "skills", "context-doctor");
773
- if (existsSync(skillDir)) {
774
- rmSync(skillDir, { recursive: true });
775
- console.log("✓ Agent Skill removed");
776
- }
995
+ removeSkill(join(homedir(), ".claude", "skills", "context-doctor"), "Agent Skill");
777
996
  uninstallHook();
778
997
  uninstallStatusLine();
779
998
  uninstallCodex();
@@ -783,8 +1002,21 @@ export async function runUninstall() {
783
1002
  const p = join(homedir(), ".claude", file);
784
1003
  if (existsSync(p)) {
785
1004
  rmSync(p, { recursive: true, force: true });
786
- console.log(`✓ Removed ${file}`);
1005
+ done(`✓ Removed ${file}`);
787
1006
  }
788
1007
  }
789
- console.log("Done.");
1008
+ if (deletedStubs.length > 0) {
1009
+ console.log(`✓ Deleted ${deletedStubs.length === 1 ? "a file" : "files"} install had created, now empty: ${deletedStubs.map(tilde).join(", ")}`);
1010
+ }
1011
+ const backups = configPaths().map((p) => p + BACKUP_SUFFIX).filter((b) => existsSync(b));
1012
+ if (changes === 0)
1013
+ console.log("Nothing of context-doctor's was installed.");
1014
+ else
1015
+ console.log("Done.");
1016
+ if (backups.length > 0) {
1017
+ console.log("Backups install made of your configs, from before it changed them, are kept:");
1018
+ for (const b of backups)
1019
+ console.log(` ${tilde(b)}`);
1020
+ console.log("Delete them once you no longer need them.");
1021
+ }
790
1022
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * How the user started this process, so the next steps we print can be
3
+ * typed as they are. Someone who ran `npx context-doctor savings` has no
4
+ * `context-doctor` on PATH: a hint saying `context-doctor autopilot on` is
5
+ * "command not found" for them.
6
+ */
7
+ /** Started through npx (or `npm exec`): npm says so, or the script sits in npx's cache. */
8
+ export declare function launchedViaNpx(env?: NodeJS.ProcessEnv, script?: string): boolean;
9
+ /** Should follow-up commands be spelled `npx context-doctor …`? */
10
+ export declare function needsNpx(env?: NodeJS.ProcessEnv, script?: string): boolean;
11
+ /** A follow-up command as the user should type it: `npx context-doctor <rest>` after an npx run. */
12
+ export declare function selfCommand(rest: string, env?: NodeJS.ProcessEnv, script?: string): string;
13
+ /**
14
+ * Rewrite the `context-doctor <command>` hints in printed text for the way
15
+ * this process was started. Autopilot runs as a background service, which
16
+ * cannot point into npx's cache, so from npx its hint is a global install.
17
+ */
18
+ export declare function withInvocation(text: string, env?: NodeJS.ProcessEnv, script?: string): string;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * How the user started this process, so the next steps we print can be
3
+ * typed as they are. Someone who ran `npx context-doctor savings` has no
4
+ * `context-doctor` on PATH: a hint saying `context-doctor autopilot on` is
5
+ * "command not found" for them.
6
+ */
7
+ import { existsSync } from "node:fs";
8
+ import { platform } from "node:os";
9
+ import { delimiter, join } from "node:path";
10
+ /** Started through npx (or `npm exec`): npm says so, or the script sits in npx's cache. */
11
+ export function launchedViaNpx(env = process.env, script = process.argv[1] ?? "") {
12
+ return env.npm_command === "exec" || /[\\/]_npx[\\/]/.test(script);
13
+ }
14
+ /**
15
+ * A `context-doctor` the user's own shell will find: on PATH, outside npx's
16
+ * cache and outside a project's node_modules/.bin (which npm puts on PATH
17
+ * only while it runs a command).
18
+ */
19
+ function installedBinary(env) {
20
+ const exts = platform() === "win32" ? [".cmd", ".exe", ""] : [""];
21
+ for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
22
+ if (!dir || /[\\/]_npx[\\/]|[\\/]node_modules[\\/]\.bin\b|[\\/]\.npm[\\/]|[\\/]npm-cache[\\/]/i.test(dir + "/"))
23
+ continue;
24
+ if (exts.some((e) => existsSync(join(dir, "context-doctor" + e))))
25
+ return true;
26
+ }
27
+ return false;
28
+ }
29
+ /** Should follow-up commands be spelled `npx context-doctor …`? */
30
+ export function needsNpx(env = process.env, script) {
31
+ return launchedViaNpx(env, script) && !installedBinary(env);
32
+ }
33
+ /** A follow-up command as the user should type it: `npx context-doctor <rest>` after an npx run. */
34
+ export function selfCommand(rest, env = process.env, script) {
35
+ return `${needsNpx(env, script) ? "npx context-doctor" : "context-doctor"} ${rest}`;
36
+ }
37
+ const SUBCOMMANDS = "install|uninstall|autopilot|init|compact-window|compactions|doctor|savings|instructions|session|overhead|report|subagents|tasks|reads|--help";
38
+ /**
39
+ * Rewrite the `context-doctor <command>` hints in printed text for the way
40
+ * this process was started. Autopilot runs as a background service, which
41
+ * cannot point into npx's cache, so from npx its hint is a global install.
42
+ */
43
+ export function withInvocation(text, env = process.env, script) {
44
+ if (!needsNpx(env, script))
45
+ return text;
46
+ return text
47
+ .replace(/(?<![\w/@.-])context-doctor autopilot on\b/g, "npm i -g context-doctor && context-doctor autopilot on")
48
+ .replace(new RegExp(`(?<![\\w/@.-]|npx |-g |&& )context-doctor (?=(?:${SUBCOMMANDS})\\b)`, "g"), "npx context-doctor ");
49
+ }
package/dist/ledger.d.ts CHANGED
@@ -26,6 +26,8 @@ export interface LedgerEntry {
26
26
  requests?: number;
27
27
  saved?: number;
28
28
  model?: string;
29
+ /** The Cursor version that ran the hook (its input's cursor_version), for `doctor`. */
30
+ cv?: string;
29
31
  /** rollup only: sums carried forward from entries rotation removed. */
30
32
  carried?: CarriedTotals;
31
33
  }
package/dist/mcp.d.ts CHANGED
@@ -2,11 +2,14 @@
2
2
  /**
3
3
  * context-doctor MCP server (stdio).
4
4
  *
5
- * Plug into Claude Desktop, ChatGPT desktop (developer mode), Cursor, or any
6
- * MCP client:
5
+ * Plug into Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI or any MCP
6
+ * client that launches a local command:
7
7
  *
8
8
  * { "mcpServers": { "context-doctor": { "command": "npx", "args": ["-y", "context-doctor", "mcp"] } } }
9
9
  *
10
+ * ChatGPT launches nothing locally: it connects only to a URL (a developer-mode
11
+ * connector), which `--http` serves (see the transport dispatch at the end).
12
+ *
10
13
  * Tools:
11
14
  * profile_context — analyze a conversation/prompt, report token breakdown + findings
12
15
  * optimize_context — apply safe strategies, return the slimmed conversation