context-doctor 0.38.0 → 0.40.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 (65) hide show
  1. package/README.md +28 -19
  2. package/dist/antigravity.d.ts +44 -0
  3. package/dist/antigravity.js +80 -0
  4. package/dist/autoclear.d.ts +15 -0
  5. package/dist/autoclear.js +17 -0
  6. package/dist/autopilot.js +3 -2
  7. package/dist/cachemisses.d.ts +56 -2
  8. package/dist/cachemisses.js +252 -42
  9. package/dist/cachettl.d.ts +127 -0
  10. package/dist/cachettl.js +357 -0
  11. package/dist/claudedir.d.ts +17 -0
  12. package/dist/claudedir.js +32 -0
  13. package/dist/cli.js +303 -26
  14. package/dist/coldresume.d.ts +15 -0
  15. package/dist/coldresume.js +60 -11
  16. package/dist/compactquality.d.ts +5 -0
  17. package/dist/compactquality.js +108 -61
  18. package/dist/compactwindow.d.ts +14 -5
  19. package/dist/compactwindow.js +36 -43
  20. package/dist/doctor.d.ts +14 -0
  21. package/dist/doctor.js +94 -8
  22. package/dist/effective.d.ts +55 -0
  23. package/dist/effective.js +163 -0
  24. package/dist/experiment.js +2 -2
  25. package/dist/extract.js +4 -1
  26. package/dist/fanout.js +2 -2
  27. package/dist/fix.d.ts +176 -0
  28. package/dist/fix.js +574 -0
  29. package/dist/hook.js +2 -2
  30. package/dist/install.d.ts +27 -1
  31. package/dist/install.js +248 -37
  32. package/dist/ledger.js +2 -2
  33. package/dist/lens.d.ts +2 -0
  34. package/dist/lens.js +50 -24
  35. package/dist/limits.d.ts +10 -0
  36. package/dist/limits.js +36 -12
  37. package/dist/mcp.js +61 -61
  38. package/dist/mcpclient.js +28 -28
  39. package/dist/mcpschema.d.ts +18 -0
  40. package/dist/mcpschema.js +74 -31
  41. package/dist/missledger.d.ts +61 -0
  42. package/dist/missledger.js +198 -0
  43. package/dist/overhead.js +22 -25
  44. package/dist/profile.js +8 -8
  45. package/dist/proxy.d.ts +1 -1
  46. package/dist/proxy.js +2 -1
  47. package/dist/prune.d.ts +4 -0
  48. package/dist/prune.js +89 -49
  49. package/dist/reads.js +2 -2
  50. package/dist/recall.js +2 -1
  51. package/dist/savings.d.ts +5 -9
  52. package/dist/savings.js +217 -115
  53. package/dist/scan.d.ts +96 -0
  54. package/dist/scan.js +482 -0
  55. package/dist/session.d.ts +6 -0
  56. package/dist/session.js +16 -3
  57. package/dist/settingsedit.d.ts +72 -0
  58. package/dist/settingsedit.js +493 -0
  59. package/dist/statusline.d.ts +38 -2
  60. package/dist/statusline.js +66 -4
  61. package/dist/subagentpay.js +2 -2
  62. package/dist/tasks.js +2 -2
  63. package/dist/tokens.d.ts +5 -0
  64. package/dist/tokens.js +11 -1
  65. package/package.json +2 -2
package/dist/install.js CHANGED
@@ -6,14 +6,18 @@
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, readdirSync, readFileSync, writeFileSync, copyFileSync, rmSync } from "node:fs";
9
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, copyFileSync, rmdirSync, 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
13
  import { selfCommand, withInvocation } from "./invocation.js";
14
14
  import { claudeCodeInstalls, describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
15
15
  import { FANOUT_MATCHER } from "./fanout.js";
16
+ import { antigravityAllSkillDirs, antigravityMcpConfigPath, antigravityPresent, antigravitySkillDirs } from "./antigravity.js";
16
17
  import { COPILOT_HOOK_EVENT, copilotHome, copilotHookFilePath, copilotMcpConfigPath, isOurCopilotEntry, vsCodePresent } from "./copilot.js";
18
+ import { claudeDir, claudeJsonPath } from "./claudedir.js";
19
+ import { scanCacheDir } from "./scan.js";
20
+ import { editJsonText, parseSettingsText, sameJson } from "./settingsedit.js";
17
21
  function claudeDesktopConfigPath() {
18
22
  switch (platform()) {
19
23
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -23,13 +27,15 @@ function claudeDesktopConfigPath() {
23
27
  }
24
28
  function targets() {
25
29
  const desktop = claudeDesktopConfigPath();
26
- const claudeCode = join(homedir(), ".claude.json");
30
+ const claudeCode = claudeJsonPath();
27
31
  const cursor = join(homedir(), ".cursor", "mcp.json");
28
32
  return [
29
33
  { name: "Claude Desktop", configPath: desktop, detect: () => existsSync(dirname(desktop)) },
30
- { name: "Claude Code", configPath: claudeCode, detect: () => existsSync(claudeCode) || existsSync(join(homedir(), ".claude")) },
34
+ { name: "Claude Code", configPath: claudeCode, detect: () => existsSync(claudeCode) || existsSync(claudeDir()) },
31
35
  { name: "Cursor", configPath: cursor, detect: () => existsSync(join(homedir(), ".cursor")) },
32
36
  { name: "Gemini CLI", configPath: geminiSettingsPath(), detect: geminiCliPresent },
37
+ // Antigravity's MCP file has Claude Desktop's shape (see antigravity.ts).
38
+ { name: "Antigravity", configPath: antigravityMcpConfigPath(), detect: antigravityPresent },
33
39
  ];
34
40
  }
35
41
  // -- Gemini CLI: MCP servers and hooks both live in ~/.gemini/settings.json,
@@ -39,6 +45,14 @@ function targets() {
39
45
  export function geminiSettingsPath() {
40
46
  return join(homedir(), ".gemini", "settings.json");
41
47
  }
48
+ /**
49
+ * Gemini CLI reads its settings.json through strip-json-comments
50
+ * (packages/cli/src/config/settings.ts), so `//` and block comments are
51
+ * valid there: read past them, and keep them when editing.
52
+ */
53
+ export function allowsComments(path) {
54
+ return path === geminiSettingsPath();
55
+ }
42
56
  export function geminiCliPresent() {
43
57
  return existsSync(geminiSettingsPath()) || existsSync(join(homedir(), ".gemini", "tmp")) || binOnPath("gemini") !== null;
44
58
  }
@@ -121,7 +135,7 @@ export function isOurPluginKey(key) {
121
135
  */
122
136
  export function claudePluginEnabled(home = homedir()) {
123
137
  try {
124
- const plugins = readJson(join(home, ".claude", "settings.json")).enabledPlugins ?? {};
138
+ const plugins = readJson(join(claudeDir(home), "settings.json")).enabledPlugins ?? {};
125
139
  return Object.entries(plugins).some(([key, on]) => isOurPluginKey(key) && on === true);
126
140
  }
127
141
  catch {
@@ -132,17 +146,17 @@ export function claudePluginEnabled(home = homedir()) {
132
146
  export function claudeInstalledCopies(home = homedir()) {
133
147
  const found = [];
134
148
  try {
135
- if (readJson(join(home, ".claude.json")).mcpServers?.["context-doctor"])
149
+ if (readJson(claudeJsonPath(home)).mcpServers?.["context-doctor"])
136
150
  found.push("MCP server in ~/.claude.json");
137
151
  }
138
152
  catch { /* unreadable: not ours to judge here */ }
139
153
  try {
140
- const hooks = readJson(join(home, ".claude", "settings.json")).hooks ?? {};
154
+ const hooks = readJson(join(claudeDir(home), "settings.json")).hooks ?? {};
141
155
  if (["UserPromptSubmit", "PreCompact", "SessionStart", "PreModelSwitch", "PreToolUse"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
142
156
  found.push("hooks in ~/.claude/settings.json");
143
157
  }
144
158
  catch { /* unreadable */ }
145
- if (existsSync(join(home, ".claude", "skills", "context-doctor", "SKILL.md")))
159
+ if (existsSync(join(claudeDir(home), "skills", "context-doctor", "SKILL.md")))
146
160
  found.push("skill in ~/.claude/skills/context-doctor");
147
161
  return found;
148
162
  }
@@ -162,7 +176,12 @@ export function readJson(path) {
162
176
  if (!existsSync(path))
163
177
  return {};
164
178
  try {
165
- return JSON.parse(readFileSync(path, "utf8"));
179
+ const text = readFileSync(path, "utf8");
180
+ // An empty file configures nothing, like an absent one: Antigravity
181
+ // creates its mcp_config.json empty.
182
+ if (text.replace(/^\ufeff/, "").trim() === "")
183
+ return {};
184
+ return parseSettingsText(text, allowsComments(path));
166
185
  }
167
186
  catch (e) {
168
187
  throw new Error(`${path} exists but is not valid JSON — fix or remove it first (${e.message})`);
@@ -177,18 +196,70 @@ export function readJson(path) {
177
196
  * before the run even finished. The first write of a run keeps the original.
178
197
  */
179
198
  const backedUp = new Set();
180
- /** Copy `path` to its .context-doctor.backup, once per run. */
199
+ /**
200
+ * Does the file already hold an entry of ours (an earlier install's write)?
201
+ * JSON configs by the same test uninstall uses; Codex's TOML by its table.
202
+ */
203
+ function holdsOurs(path) {
204
+ let text;
205
+ try {
206
+ text = readFileSync(path, "utf8");
207
+ }
208
+ catch {
209
+ return false;
210
+ }
211
+ if (path.endsWith(".toml"))
212
+ return codexMcpEntry(text) !== undefined;
213
+ try {
214
+ const raw = parseSettingsText(text, allowsComments(path));
215
+ return isPlainObject(raw) && JSON.stringify(withoutOurs(raw)) !== JSON.stringify(raw);
216
+ }
217
+ catch {
218
+ return false;
219
+ }
220
+ }
221
+ /**
222
+ * Copy `path` to its .context-doctor.backup, once per run, and never over a
223
+ * backup with a copy of our own write. A second install (a new process, so
224
+ * `backedUp` is empty again) used to copy the file install had already
225
+ * changed over the user's original: uninstall then read that backup as
226
+ * "install made this file" and deleted an empty `{}` or empty config the
227
+ * user had (Antigravity's, with the app's link to it left dangling). A file
228
+ * that holds our entry while a backup exists is an earlier install's write;
229
+ * the backup from that install stays. A file without our entry (the user's,
230
+ * after an uninstall) is backed up afresh.
231
+ */
181
232
  export function backupOnce(path) {
182
233
  if (backedUp.has(path))
183
234
  return;
184
235
  backedUp.add(path);
185
- if (existsSync(path))
186
- copyFileSync(path, path + ".context-doctor.backup");
236
+ if (!existsSync(path))
237
+ return;
238
+ const backup = path + ".context-doctor.backup";
239
+ if (existsSync(backup) && holdsOurs(path))
240
+ return;
241
+ copyFileSync(path, backup);
242
+ }
243
+ function readText(path) {
244
+ try {
245
+ return readFileSync(path, "utf8");
246
+ }
247
+ catch {
248
+ return undefined;
249
+ }
187
250
  }
251
+ /**
252
+ * Write `data` into a JSON config the way a person would edit it: only the
253
+ * keys and list items that differ are changed in the text (settingsedit.ts),
254
+ * so indentation, one-line objects, minified files, CRLF, escapes, number
255
+ * spelling and (Gemini CLI) comments stay as they were, and uninstall's
256
+ * removal of the same entries gives the file back byte for byte.
257
+ * Re-serialising the whole file used to expand a minified or inline config.
258
+ */
188
259
  export function writeJsonWithBackup(path, data) {
189
260
  mkdirSync(dirname(path), { recursive: true });
190
261
  backupOnce(path);
191
- writeFileSync(path, JSON.stringify(data, null, 2));
262
+ writeFileSync(path, editJsonText(readText(path), data, allowsComments(path)));
192
263
  }
193
264
  /**
194
265
  * Find an executable on PATH without shelling out (works on Windows too).
@@ -253,8 +324,8 @@ function cliCommand(subcommand) {
253
324
  * ours. Returns what happened so install can print the truth.
254
325
  */
255
326
  export function installStatusLine() {
256
- const settingsPath = join(homedir(), ".claude", "settings.json");
257
- if (!existsSync(join(homedir(), ".claude")))
327
+ const settingsPath = join(claudeDir(), "settings.json");
328
+ if (!existsSync(claudeDir()))
258
329
  return "no-claude-code";
259
330
  const settings = readJson(settingsPath);
260
331
  const want = cliCommand("statusline");
@@ -271,7 +342,7 @@ function isOurStatusLine(command) {
271
342
  return /context-doctor|cli\.js"?\s+statusline\s*$/.test(command);
272
343
  }
273
344
  function uninstallStatusLine() {
274
- const settingsPath = join(homedir(), ".claude", "settings.json");
345
+ const settingsPath = join(claudeDir(), "settings.json");
275
346
  if (!existsSync(settingsPath))
276
347
  return;
277
348
  const settings = readJson(settingsPath);
@@ -307,17 +378,17 @@ function isOurHookEntry(entry) {
307
378
  * Claude Code query gets a context-size check. Idempotent.
308
379
  */
309
380
  function installHook() {
310
- const settings = join(homedir(), ".claude", "settings.json");
311
- const path = installHookInto(settings, join(homedir(), ".claude"));
381
+ const settings = join(claudeDir(), "settings.json");
382
+ const path = installHookInto(settings, claudeDir());
312
383
  // The same command also answers PreCompact (what each compaction's summary
313
384
  // must keep) and SessionStart (Claude Code's verdict on a resumed cache).
314
385
  if (path) {
315
- installHookInto(settings, join(homedir(), ".claude"), "PreCompact");
316
- installHookInto(settings, join(homedir(), ".claude"), "SessionStart");
386
+ installHookInto(settings, claudeDir(), "PreCompact");
387
+ installHookInto(settings, claudeDir(), "SessionStart");
317
388
  // Before a subagent starts: its price. PreToolUse is in every Claude Code
318
389
  // with hooks (2.1.62's event list has it), so no version guard is needed,
319
390
  // and a timeout never blocks the call. "Task" is the tool's name before 2.1.63.
320
- installHookInto(settings, join(homedir(), ".claude"), "PreToolUse", { matcher: FANOUT_MATCHER, timeout: 10 });
391
+ installHookInto(settings, claudeDir(), "PreToolUse", { matcher: FANOUT_MATCHER, timeout: 10 });
321
392
  }
322
393
  return path;
323
394
  }
@@ -363,7 +434,7 @@ function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit", opts
363
434
  }
364
435
  /** Each hook removal on its own: a malformed file for one app must not leave the others installed. */
365
436
  function uninstallHook(attempt) {
366
- const claude = join(homedir(), ".claude", "settings.json");
437
+ const claude = join(claudeDir(), "settings.json");
367
438
  attempt("Claude Code every-prompt hook", () => uninstallHookFrom(claude, "Claude Code every-prompt hook"));
368
439
  attempt("Claude Code compaction hook", () => uninstallHookFrom(claude, "Claude Code compaction hook", "PreCompact"));
369
440
  attempt("Claude Code session-start hook", () => uninstallHookFrom(claude, "Claude Code session-start hook", "SessionStart"));
@@ -447,7 +518,7 @@ function uninstallCursorHook() {
447
518
  * earlier install wrote is taken out again.
448
519
  */
449
520
  export function installModelSwitchHook(readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv())) {
450
- const dir = join(homedir(), ".claude");
521
+ const dir = claudeDir();
451
522
  if (!existsSync(dir))
452
523
  return "no-claude-code";
453
524
  const settingsPath = join(dir, "settings.json");
@@ -487,19 +558,63 @@ function uninstallHookFrom(settingsPath, label, event = "UserPromptSubmit") {
487
558
  }
488
559
  }
489
560
  function installSkill() {
490
- return installSkillInto(join(homedir(), ".claude", "skills", "context-doctor"));
561
+ // Only where Claude Code is: making ~/.claude makes it look installed.
562
+ if (!existsSync(claudeDir()) && !existsSync(claudeJsonPath()))
563
+ return null;
564
+ return installSkillInto(join(claudeDir(), "skills", "context-doctor"), claudeDir());
491
565
  }
492
- /** Agent Skills are one format across Claude Code and Codex; only the home differs. */
493
- function installSkillInto(skillDest) {
494
- const selfDir = dirname(fileURLToPath(import.meta.url));
566
+ /** The SKILL.md this package ships, the one install copies. */
567
+ export function shippedSkillPath() {
495
568
  // dist/install.js → package root is one level up; skills/ ships in the package.
496
- const skillSource = join(selfDir, "..", "skills", "context-doctor", "SKILL.md");
569
+ return join(dirname(fileURLToPath(import.meta.url)), "..", "skills", "context-doctor", "SKILL.md");
570
+ }
571
+ /**
572
+ * Agent Skills are one format across Claude Code and Codex; only the home
573
+ * differs. With `appHome`, the folders this makes there (the skills folder,
574
+ * and for Claude Code the home itself) are recorded, so uninstall can take
575
+ * them out again once empty; a folder that was already there is the user's.
576
+ */
577
+ function installSkillInto(skillDest, appHome) {
578
+ const skillSource = shippedSkillPath();
497
579
  if (!existsSync(skillSource))
498
580
  return null;
581
+ const missing = appHome ? skillFolders(appHome).filter((d) => !existsSync(d)) : [];
499
582
  mkdirSync(skillDest, { recursive: true });
500
583
  copyFileSync(skillSource, join(skillDest, "SKILL.md"));
584
+ if (appHome && missing.length > 0) {
585
+ const all = [...new Set([...createdSkillFolders(appHome), ...missing])];
586
+ writeFileSync(join(appHome, CREATED_MARKER), JSON.stringify({ created: all }) + "\n");
587
+ }
501
588
  return join(skillDest, "SKILL.md");
502
589
  }
590
+ /** The marker naming the folders install created in an app's home (Claude Code's, Codex's). */
591
+ const CREATED_MARKER = ".context-doctor-created.json";
592
+ /** The only folders a skill install can create, deepest first: a marker naming anything else is ignored. */
593
+ function skillFolders(appHome) {
594
+ return [join(appHome, "skills", "context-doctor"), join(appHome, "skills"), appHome];
595
+ }
596
+ function createdSkillFolders(appHome) {
597
+ try {
598
+ const raw = JSON.parse(readFileSync(join(appHome, CREATED_MARKER), "utf8"));
599
+ const allowed = skillFolders(appHome);
600
+ return Array.isArray(raw?.created) ? raw.created.filter((d) => typeof d === "string" && allowed.includes(d)) : [];
601
+ }
602
+ catch {
603
+ return [];
604
+ }
605
+ }
606
+ /** The folders install created for the skill, once nothing is left in them; then the marker. */
607
+ function removeSkillFolders(appHome) {
608
+ const marker = join(appHome, CREATED_MARKER);
609
+ if (!existsSync(marker))
610
+ return;
611
+ const created = createdSkillFolders(appHome);
612
+ rmSync(marker, { force: true });
613
+ for (const dir of skillFolders(appHome).filter((d) => created.includes(d))) {
614
+ if (existsSync(dir) && readdirSync(dir).length === 0)
615
+ rmSync(dir, { recursive: true });
616
+ }
617
+ }
503
618
  // -- Codex (OpenAI's agent: the Codex tab in ChatGPT.app, the IDE extension, the CLI)
504
619
  //
505
620
  // Codex supports the same three integration points as Claude Code, in almost
@@ -656,7 +771,7 @@ function installCodex(entry, failures) {
656
771
  failures.push("Codex MCP");
657
772
  }
658
773
  try {
659
- const skill = installSkillInto(join(dir, "skills", "context-doctor"));
774
+ const skill = installSkillInto(join(dir, "skills", "context-doctor"), dir);
660
775
  if (skill)
661
776
  console.log(`✓ Agent Skill installed for Codex (${skill})`);
662
777
  }
@@ -696,10 +811,16 @@ function uninstallCodex() {
696
811
  }
697
812
  catch { /* unreadable backup: the file was the user's */ }
698
813
  }
814
+ // The file from before install when only its final newline differs:
815
+ // install had to add one to a file that ended without it.
816
+ const original = readText(backup);
699
817
  if (created && next.trim() === "") {
700
818
  rmSync(configPath);
701
819
  deletedStubs.push(configPath);
702
820
  }
821
+ else if (original !== undefined && codexMcpEntry(original) === undefined && original.trimEnd() === next.trimEnd()) {
822
+ writeFileSync(configPath, original);
823
+ }
703
824
  else {
704
825
  writeFileSync(configPath, next);
705
826
  }
@@ -711,6 +832,7 @@ function uninstallCodex() {
711
832
  console.error(`✗ Codex MCP: ${e.message}`);
712
833
  }
713
834
  removeSkill(join(dir, "skills", "context-doctor"), "Codex skill");
835
+ removeSkillFolders(dir);
714
836
  }
715
837
  // -- GitHub Copilot: the Copilot CLI, the GitHub Copilot app, and VS Code's
716
838
  // agent sessions (see copilot.ts for what was verified and where). Two files:
@@ -876,6 +998,38 @@ function uninstallCopilotFolders() {
876
998
  rmSync(dir, { recursive: true });
877
999
  }
878
1000
  }
1001
+ /**
1002
+ * Folders install created under ~/.gemini for Antigravity (skills folders,
1003
+ * and the shared config folder on a CLI-only install), recorded
1004
+ * in a marker there (as for Copilot) so uninstall removes only those, once
1005
+ * empty: a skills folder that was already there is the user's.
1006
+ */
1007
+ const ANTIGRAVITY_MARKER = ".context-doctor-created.json";
1008
+ function antigravityCreated() {
1009
+ try {
1010
+ const raw = JSON.parse(readFileSync(join(homedir(), ".gemini", ANTIGRAVITY_MARKER), "utf8"));
1011
+ const allowed = new Set([...antigravityAllSkillDirs().map((d) => dirname(d)), dirname(antigravityMcpConfigPath())]);
1012
+ return Array.isArray(raw?.created) ? raw.created.filter((d) => typeof d === "string" && allowed.has(d)) : [];
1013
+ }
1014
+ catch {
1015
+ return [];
1016
+ }
1017
+ }
1018
+ function rememberAntigravityFolder(dir) {
1019
+ const all = [...new Set([...antigravityCreated(), dir])];
1020
+ mkdirSync(join(homedir(), ".gemini"), { recursive: true });
1021
+ writeFileSync(join(homedir(), ".gemini", ANTIGRAVITY_MARKER), JSON.stringify({ created: all }) + "\n");
1022
+ }
1023
+ function uninstallAntigravityFolders() {
1024
+ const marker = join(homedir(), ".gemini", ANTIGRAVITY_MARKER);
1025
+ if (!existsSync(marker))
1026
+ return;
1027
+ // Deepest first: config/skills before config.
1028
+ for (const dir of antigravityCreated().sort((a, b) => b.length - a.length))
1029
+ if (existsSync(dir) && readdirSync(dir).length === 0)
1030
+ rmSync(dir, { recursive: true });
1031
+ rmSync(marker, { force: true });
1032
+ }
879
1033
  /**
880
1034
  * Install into every detected app.
881
1035
  *
@@ -890,7 +1044,7 @@ export function runInstall(options = {}) {
890
1044
  const entry = serverEntry();
891
1045
  const found = targets().filter((t) => t.detect());
892
1046
  if (found.length === 0 && !existsSync(codexDir()) && !copilotPresent()) {
893
- console.log("No supported AI apps detected (Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, GitHub Copilot).");
1047
+ console.log("No supported AI apps detected (Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, GitHub Copilot, Antigravity).");
894
1048
  console.log("Manual setup — add to your app's MCP config:");
895
1049
  console.log(JSON.stringify({ mcpServers: { "context-doctor": entry } }, null, 2));
896
1050
  return { failures: [] };
@@ -913,6 +1067,10 @@ export function runInstall(options = {}) {
913
1067
  if (viaPlugin && target.name === "Claude Code")
914
1068
  continue;
915
1069
  try {
1070
+ // A CLI-only Antigravity has no ~/.gemini/config yet: the folder the
1071
+ // MCP file needs is ours to remove again once uninstall empties it.
1072
+ if (target.name === "Antigravity" && !existsSync(dirname(target.configPath)))
1073
+ rememberAntigravityFolder(dirname(target.configPath));
916
1074
  const config = readJsonObject(target.configPath);
917
1075
  if (config.mcpServers !== undefined && !isPlainObject(config.mcpServers))
918
1076
  throw new Error(`"mcpServers" in ${target.configPath} is not an object; fix it, then re-run. Nothing was changed.`);
@@ -936,6 +1094,22 @@ export function runInstall(options = {}) {
936
1094
  console.error(`✗ Agent Skill: ${e.message}`);
937
1095
  failures.push("Agent Skill");
938
1096
  }
1097
+ if (antigravityPresent()) {
1098
+ for (const dir of antigravitySkillDirs()) {
1099
+ try {
1100
+ // A skills folder Antigravity did not have yet is ours to remove again.
1101
+ if (!existsSync(dirname(dir)))
1102
+ rememberAntigravityFolder(dirname(dir));
1103
+ const skillPath = installSkillInto(dir);
1104
+ if (skillPath)
1105
+ console.log(`✓ Antigravity skill installed (${tilde(skillPath)})`);
1106
+ }
1107
+ catch (e) {
1108
+ console.error(`✗ Antigravity skill: ${e.message}`);
1109
+ failures.push("Antigravity skill");
1110
+ }
1111
+ }
1112
+ }
939
1113
  try {
940
1114
  const hookPath = viaPlugin ? null : installHook();
941
1115
  if (hookPath) {
@@ -953,7 +1127,7 @@ export function runInstall(options = {}) {
953
1127
  console.error(`✗ Claude Code every-prompt hook: ${e.message}`);
954
1128
  failures.push("Claude Code hook");
955
1129
  }
956
- if (!viaPlugin && existsSync(join(homedir(), ".claude"))) {
1130
+ if (!viaPlugin && existsSync(claudeDir())) {
957
1131
  try {
958
1132
  const readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv());
959
1133
  switch (installModelSwitchHook(readiness)) {
@@ -1122,7 +1296,10 @@ function installOrigin(path, extraKeys) {
1122
1296
  if (!existsSync(backup))
1123
1297
  return { created: true, before: {} };
1124
1298
  try {
1125
- const raw = JSON.parse(readFileSync(backup, "utf8"));
1299
+ const text = readFileSync(backup, "utf8");
1300
+ if (text.trim() === "")
1301
+ return { created: false, before: {}, empty: true };
1302
+ const raw = parseSettingsText(text, allowsComments(path));
1126
1303
  if (!raw || typeof raw !== "object" || Array.isArray(raw))
1127
1304
  return { created: false, before: {} };
1128
1305
  const before = withoutOurs(raw);
@@ -1141,7 +1318,7 @@ function installOrigin(path, extraKeys) {
1141
1318
  * written: the one install made of the user's original is kept as it is.
1142
1319
  */
1143
1320
  function writeUninstalled(path, config, extraKeys = []) {
1144
- const { created, before } = installOrigin(path, extraKeys);
1321
+ const { created, before, empty } = installOrigin(path, extraKeys);
1145
1322
  for (const key of ["mcpServers", "hooks"]) {
1146
1323
  const v = config[key];
1147
1324
  if (v && typeof v === "object" && Object.keys(v).length === 0 && !(key in before))
@@ -1156,7 +1333,23 @@ function writeUninstalled(path, config, extraKeys = []) {
1156
1333
  deletedStubs.push(path);
1157
1334
  return;
1158
1335
  }
1159
- writeFileSync(path, JSON.stringify(config, null, 2));
1336
+ // An empty file before install is an empty file again, not "{}".
1337
+ if (empty && isEmptyStub(config, extraKeys)) {
1338
+ writeFileSync(path, "");
1339
+ return;
1340
+ }
1341
+ // Exactly the file from before install when that is what is left (also
1342
+ // for a file an older version re-serialised); else our entries are taken
1343
+ // out of the text, everything else as it is now.
1344
+ const backup = readText(path + BACKUP_SUFFIX);
1345
+ try {
1346
+ if (backup?.trim() && sameJson(parseSettingsText(backup, allowsComments(path)), config)) {
1347
+ writeFileSync(path, backup);
1348
+ return;
1349
+ }
1350
+ }
1351
+ catch { /* an unreadable backup: edit the file as it is */ }
1352
+ writeFileSync(path, editJsonText(readText(path), config, allowsComments(path)));
1160
1353
  }
1161
1354
  /** Remove the SKILL.md install copied, and its folder once nothing else is in it. */
1162
1355
  function removeSkill(dir, label) {
@@ -1175,7 +1368,7 @@ function removeSkill(dir, label) {
1175
1368
  function configPaths() {
1176
1369
  return [
1177
1370
  ...targets().map((t) => t.configPath),
1178
- join(homedir(), ".claude", "settings.json"),
1371
+ join(claudeDir(), "settings.json"),
1179
1372
  cursorHooksPath(),
1180
1373
  join(codexDir(), "config.toml"),
1181
1374
  join(codexDir(), "hooks.json"),
@@ -1199,6 +1392,7 @@ const OUR_CLAUDE_FILES = [
1199
1392
  ".context-doctor-proxy.log",
1200
1393
  ".context-doctor-proxy-restart",
1201
1394
  ".context-doctor-limits.jsonl",
1395
+ ".context-doctor-misses.jsonl",
1202
1396
  ".context-doctor-subagent-costs.json",
1203
1397
  ];
1204
1398
  export async function runUninstall() {
@@ -1224,7 +1418,7 @@ export async function runUninstall() {
1224
1418
  }
1225
1419
  };
1226
1420
  // First: if anything below fails, Claude Code must still reach the API.
1227
- const hadAutopilot = existsSync(join(homedir(), ".claude", ".context-doctor-autopilot.json"));
1421
+ const hadAutopilot = existsSync(join(claudeDir(), ".context-doctor-autopilot.json"));
1228
1422
  try {
1229
1423
  await uninstallAutopilot();
1230
1424
  if (hadAutopilot)
@@ -1246,7 +1440,10 @@ export async function runUninstall() {
1246
1440
  }
1247
1441
  });
1248
1442
  }
1249
- attempt("Agent Skill", () => removeSkill(join(homedir(), ".claude", "skills", "context-doctor"), "Agent Skill"));
1443
+ attempt("Agent Skill", () => removeSkill(join(claudeDir(), "skills", "context-doctor"), "Agent Skill"));
1444
+ for (const dir of antigravityAllSkillDirs())
1445
+ attempt(`Antigravity skill (${tilde(dir)})`, () => removeSkill(dir, "Antigravity skill"));
1446
+ attempt("Antigravity folders", () => uninstallAntigravityFolders());
1250
1447
  uninstallHook(attempt);
1251
1448
  attempt("Claude Code status line", () => uninstallStatusLine());
1252
1449
  attempt("Codex", () => uninstallCodex());
@@ -1257,7 +1454,7 @@ export async function runUninstall() {
1257
1454
  // Remove our bookkeeping files too — uninstall means gone. The hook's
1258
1455
  // per-session state is a directory, one small file per session.
1259
1456
  for (const file of OUR_CLAUDE_FILES) {
1260
- const p = join(homedir(), ".claude", file);
1457
+ const p = join(claudeDir(), file);
1261
1458
  attempt(file, () => {
1262
1459
  if (existsSync(p)) {
1263
1460
  rmSync(p, { recursive: true, force: true });
@@ -1265,6 +1462,20 @@ export async function runUninstall() {
1265
1462
  }
1266
1463
  });
1267
1464
  }
1465
+ // The reports' transcript cache (scan.ts): records taken from your transcripts, rebuilt by the next report.
1466
+ attempt("transcript cache", () => {
1467
+ const dir = join(scanCacheDir(), "transcripts");
1468
+ if (existsSync(dir)) {
1469
+ rmSync(dir, { recursive: true, force: true });
1470
+ done(`✓ Removed the transcript cache (${tilde(dir)})`);
1471
+ }
1472
+ try {
1473
+ rmdirSync(scanCacheDir());
1474
+ }
1475
+ catch { /* not empty (someone else's files too), or never made */ }
1476
+ });
1477
+ // Last: the folders install made for the skill, now empty.
1478
+ attempt("Claude Code skill folders", () => removeSkillFolders(claudeDir()));
1268
1479
  if (deletedStubs.length > 0) {
1269
1480
  console.log(`✓ Deleted ${deletedStubs.length === 1 ? "a file" : "files"} install had created, now empty: ${deletedStubs.map(tilde).join(", ")}`);
1270
1481
  }
package/dist/ledger.js CHANGED
@@ -17,8 +17,8 @@
17
17
  * what it drops into a single rollup entry instead of discarding it.
18
18
  */
19
19
  import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
20
- import { homedir } from "node:os";
21
20
  import { dirname, join } from "node:path";
21
+ import { claudeDir } from "./claudedir.js";
22
22
  const EMPTY_CARRIED = {
23
23
  optimizeSaved: 0, optimizeUsd: 0, proxySaved: 0, proxyUsd: 0,
24
24
  proxyRequests: 0, checks: 0, warnings: 0, shrinkage: 0,
@@ -79,7 +79,7 @@ export function foldTotals(entries) {
79
79
  return out;
80
80
  }
81
81
  export function statePath() {
82
- return process.env.CONTEXT_DOCTOR_HOOK_STATE ?? join(homedir(), ".claude", ".context-doctor-hook-state.json");
82
+ return process.env.CONTEXT_DOCTOR_HOOK_STATE ?? join(claudeDir(), ".context-doctor-hook-state.json");
83
83
  }
84
84
  export function ledgerPath() {
85
85
  return join(dirname(statePath()), ".context-doctor-ledger.jsonl");
package/dist/lens.d.ts CHANGED
@@ -14,6 +14,7 @@
14
14
  * Each repeat is a whole request that re-reads the context; it is priced
15
15
  * at that request's billed cost.
16
16
  */
17
+ import { type Extractor } from "./scan.js";
17
18
  export interface ModelOutput {
18
19
  model: string;
19
20
  requests: number;
@@ -42,6 +43,7 @@ export interface Lens {
42
43
  polls: PollStats;
43
44
  totalUsd: number;
44
45
  }
46
+ export declare const LENS_ROWS: Extractor<null>;
45
47
  /** One session transcript (Claude Code or Codex). */
46
48
  export declare function sessionLens(path: string, since?: number): Lens;
47
49
  /** Every Claude Code (and, unless `claudeOnly`, Codex) session touched in the last `days`. */