context-doctor 0.34.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hook.js CHANGED
@@ -24,6 +24,7 @@ import { ensureProxyUp } from "./autopilot.js";
24
24
  import { autoCompactsAt, detectColdResume, renderColdResume, renderColdResumeNotice, resumeVerdict, sessionWriteMultiplier, withResumeVerdict } from "./coldresume.js";
25
25
  import { formatUsd, pricingFor } from "./pricing.js";
26
26
  import { checkBudget, loadConfig } from "./config.js";
27
+ import { modelSwitchMessage } from "./modelswitch.js";
27
28
  import { compactFacts, compactInstructions } from "./precompact.js";
28
29
  /** Default nudge threshold; a project budget or env var can lower/raise it. */
29
30
  const DEFAULT_WARN_TOKENS = 80_000;
@@ -134,15 +135,35 @@ async function readStdin() {
134
135
  chunks.push(chunk);
135
136
  return Buffer.concat(chunks).toString("utf8");
136
137
  }
137
- function settingsHasOurHook() {
138
+ function settingsHasOurHook(event = "UserPromptSubmit") {
138
139
  try {
139
- const hooks = JSON.parse(readFileSync(join(homedir(), ".claude", "settings.json"), "utf8"))?.hooks?.UserPromptSubmit;
140
+ // Per event: a settings.json that has our prompt hook but not our
141
+ // PreModelSwitch one (install skips it next to an older Claude Code)
142
+ // must not silence the plugin's copy of the event it lacks.
143
+ const hooks = JSON.parse(readFileSync(join(homedir(), ".claude", "settings.json"), "utf8"))?.hooks?.[event || "UserPromptSubmit"];
140
144
  return JSON.stringify(hooks ?? "").includes("context-doctor");
141
145
  }
142
146
  catch {
143
147
  return false;
144
148
  }
145
149
  }
150
+ /**
151
+ * Hook input with the string fields checked. A number or object where a path
152
+ * belongs reached fs.existsSync, which on current Node prints a
153
+ * DeprecationWarning into the user's session (and will throw on a later one).
154
+ */
155
+ export function hookInput(raw) {
156
+ const obj = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
157
+ const out = { ...obj };
158
+ for (const key of ["session_id", "transcript_path", "cwd", "hook_event_name", "conversation_id", "model", "cursor_version"]) {
159
+ if (typeof obj[key] !== "string" || obj[key] === "")
160
+ delete out[key];
161
+ }
162
+ out.workspace_roots = Array.isArray(obj.workspace_roots) ? obj.workspace_roots.filter((r) => typeof r === "string") : undefined;
163
+ if (out.workspace_roots === undefined)
164
+ delete out.workspace_roots;
165
+ return out;
166
+ }
146
167
  export async function runHook() {
147
168
  // A hook must never break the user's prompt: any failure exits silently.
148
169
  try {
@@ -152,12 +173,22 @@ export async function runHook() {
152
173
  const heal = ensureProxyUp().catch(() => undefined);
153
174
  // Installed both ways (plugin and `context-doctor install`)? The plugin
154
175
  // copy stays silent so the model is told once, not twice.
155
- if (process.env.CLAUDE_PLUGIN_ROOT && settingsHasOurHook()) {
176
+ const input = hookInput(JSON.parse(await readStdin()));
177
+ if (process.env.CLAUDE_PLUGIN_ROOT && settingsHasOurHook(input.hook_event_name)) {
156
178
  await heal;
157
179
  return;
158
180
  }
159
- const input = JSON.parse(await readStdin());
160
181
  await heal;
182
+ // Before a model switch: what re-writing this context into the new
183
+ // model's cache costs, shown to the user. Never blocks (no decision, exit
184
+ // 0); a hook that failed or timed out here would block the switch, so
185
+ // this path only reads the transcript's tail.
186
+ if (input.hook_event_name === "PreModelSwitch") {
187
+ const message = modelSwitchMessage(input);
188
+ if (message)
189
+ process.stdout.write(JSON.stringify({ systemMessage: message }) + "\n");
190
+ return;
191
+ }
161
192
  // A resumed session: Claude Code says whether its cache expired and what
162
193
  // re-caching costs. Kept for the first prompt, which decides the offer
163
194
  // (an offer before any message would come before the rebuild it prices).
package/dist/impact.js CHANGED
@@ -15,6 +15,20 @@ import { profileConversation } from "./profile.js";
15
15
  import { formatTokens } from "./tokens.js";
16
16
  import { formatUsd, inputCostUsd, pricingFor } from "./pricing.js";
17
17
  import { coldResumeFollowThrough } from "./coldresume.js";
18
+ /**
19
+ * The dollar figure for `tokens`, of which only `priced` have a model with a
20
+ * known price. Pricing the whole total at the priced part's rate, or showing
21
+ * the priced part's dollars beside the whole total unlabeled, overstated it.
22
+ */
23
+ function pricedNote(usd, priced, tokens) {
24
+ if (tokens <= 0)
25
+ return "";
26
+ if (priced <= 0 || usd <= 0)
27
+ return " (no known price for these models)";
28
+ if (priced >= tokens)
29
+ return ` ≈ ${formatUsd(usd)}`;
30
+ return ` ≈ ${formatUsd(usd)} on the ${formatTokens(priced)} with a known price; ${formatTokens(tokens - priced)} unpriced`;
31
+ }
18
32
  /** Sessions larger than this are skipped in the report (keeps it snappy). */
19
33
  const MAX_SESSION_BYTES = 30 * 1024 * 1024;
20
34
  /**
@@ -105,12 +119,16 @@ export async function buildImpactReport(proxyPort = 8787) {
105
119
  const optimizeSaved = optimizes.reduce((s, e) => s + (e.saved ?? 0), 0) + carried.optimizeSaved;
106
120
  const savedByFamily = new Map();
107
121
  let optimizeUsd = 0;
122
+ /** The part of optimizeSaved whose model has a known price: the dollars cover only this. */
123
+ let optimizePriced = 0;
108
124
  for (const e of optimizes) {
109
125
  const family = /claude/i.test(e.model ?? "") ? "claude" : /gpt|^o\d/i.test(e.model ?? "") ? "gpt" : "other";
110
126
  savedByFamily.set(family, (savedByFamily.get(family) ?? 0) + (e.saved ?? 0));
111
127
  const pricing = pricingFor(e.model);
112
- if (pricing && e.saved)
128
+ if (pricing && e.saved) {
113
129
  optimizeUsd += inputCostUsd(e.saved, pricing);
130
+ optimizePriced += e.saved;
131
+ }
114
132
  }
115
133
  const proxy = await fetchProxyStats(proxyPort);
116
134
  // Persisted checkpoints cover earlier runs AND the live one's past minutes;
@@ -141,7 +159,7 @@ export async function buildImpactReport(proxyPort = 8787) {
141
159
  .join(", ");
142
160
  lines.push(` · optimizations applied via CLI/chat tools (exact): ${formatTokens(optimizeSaved)} over ${optimizes.length} run(s)` +
143
161
  (familyNote ? ` [${familyNote}]` : "") +
144
- (optimizeUsd > 0 ? ` ≈ ${formatUsd(optimizeUsd)}` : ""));
162
+ pricedNote(optimizeUsd, optimizePriced, optimizeSaved));
145
163
  lines.push("");
146
164
  lines.push(`Sessions that got smaller after a hygiene warning: ${formatTokens(totalReduction)} tokens`);
147
165
  lines.push(" (mostly compaction, by you or Claude Code; not counted above, because a warning");
@@ -182,6 +200,8 @@ export async function buildImpactReport(proxyPort = 8787) {
182
200
  let totalTokens = 0;
183
201
  let totalWaste = 0;
184
202
  let totalWasteUsd = 0;
203
+ /** Recoverable tokens in sessions whose model has a known price: the dollars cover only these. */
204
+ let pricedWaste = 0;
185
205
  for (const s of sessions) {
186
206
  try {
187
207
  const parsed = parseSessionFile(s.path);
@@ -193,8 +213,10 @@ export async function buildImpactReport(proxyPort = 8787) {
193
213
  // Claude Code sessions run on the prompt cache, so recoverable tokens
194
214
  // cost the cached rate on each message, not the full input rate.
195
215
  const pr = pricingFor(p.model);
196
- if (p.cost && pr)
216
+ if (p.cost && pr) {
197
217
  totalWasteUsd += p.cost.savingsPerCallUsd * (pr.cacheReadPerM / pr.inputPerM);
218
+ pricedWaste += p.totalEstSavings;
219
+ }
198
220
  const wastePct = p.totalTokens > 0 ? Math.round((p.totalEstSavings / p.totalTokens) * 100) : 0;
199
221
  // Ledger sids are the session UUID's first 12 chars (= filename prefix).
200
222
  const sid = (s.path.split(/[\\/]/).pop() ?? "").slice(0, 12);
@@ -210,7 +232,13 @@ export async function buildImpactReport(proxyPort = 8787) {
210
232
  }
211
233
  lines.push("");
212
234
  lines.push(`Across these sessions: ~${formatTokens(totalTokens)} tokens held; ~${formatTokens(totalWaste)} still recoverable` +
213
- (totalWasteUsd > 0 ? ` (≈ ${formatUsd(totalWasteUsd)} of input per message sent in them)` : ""));
235
+ (totalWasteUsd > 0
236
+ ? pricedWaste < totalWaste
237
+ ? ` (≈ ${formatUsd(totalWasteUsd)} of input per message on the ~${formatTokens(pricedWaste)} with a known price; ~${formatTokens(totalWaste - pricedWaste)} unpriced)`
238
+ : ` (≈ ${formatUsd(totalWasteUsd)} of input per message sent in them)`
239
+ : totalWaste > 0
240
+ ? " (no known price for these models)"
241
+ : ""));
214
242
  }
215
243
  lines.push("");
216
244
  lines.push("What no report can show: tokens Claude AVOIDED adding thanks to the standing");
package/dist/index.d.ts CHANGED
@@ -38,3 +38,5 @@ export * from "./cacheplan.js";
38
38
  export * from "./subagentpay.js";
39
39
  export * from "./compactquality.js";
40
40
  export * from "./precompact.js";
41
+ export * from "./cachemisses.js";
42
+ export * from "./modelswitch.js";
package/dist/index.js CHANGED
@@ -33,3 +33,5 @@ export * from "./cacheplan.js";
33
33
  export * from "./subagentpay.js";
34
34
  export * from "./compactquality.js";
35
35
  export * from "./precompact.js";
36
+ export * from "./cachemisses.js";
37
+ export * from "./modelswitch.js";
package/dist/install.d.ts CHANGED
@@ -6,6 +6,7 @@
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 { type ClaudeCodeInstall, type ModelSwitchReadiness } from "./modelswitch.js";
9
10
  export declare function geminiSettingsPath(): string;
10
11
  export declare function geminiCliPresent(): boolean;
11
12
  /**
@@ -102,6 +103,20 @@ export declare const isOurCursorEntry: (e: unknown) => boolean;
102
103
  */
103
104
  export declare const CURSOR_HOOK_EVENTS: readonly ["postToolUse", "postToolUseFailure", "sessionStart"];
104
105
  export declare function installCursorHook(): string | null;
106
+ /**
107
+ * The model-switch warning (PreModelSwitch) goes into ~/.claude/settings.json
108
+ * only when every Claude Code found here runs that event: an older one skips
109
+ * the WHOLE file over an event it does not know (measured on 2.1.62: none of
110
+ * the user's settings or hooks ran). With an older one present, an entry an
111
+ * earlier install wrote is taken out again.
112
+ */
113
+ export declare function installModelSwitchHook(readiness?: ModelSwitchReadiness): "installed" | "old" | "unknown" | "no-claude-code";
114
+ /**
115
+ * The Claude Code versions to plan for: CONTEXT_DOCTOR_CLAUDE_CODE_VERSIONS
116
+ * ("2.1.299,2.1.62") when detection cannot see an install, else what
117
+ * claudeCodeInstalls finds.
118
+ */
119
+ export declare function claudeCodeInstallsFromEnv(): ClaudeCodeInstall[];
105
120
  export declare function codexDir(): string;
106
121
  /**
107
122
  * Add or replace our [mcp_servers.context-doctor] table in config.toml without
package/dist/install.js CHANGED
@@ -11,6 +11,7 @@ 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
+ import { claudeCodeInstalls, describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
14
15
  function claudeDesktopConfigPath() {
15
16
  switch (platform()) {
16
17
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -135,7 +136,7 @@ export function claudeInstalledCopies(home = homedir()) {
135
136
  catch { /* unreadable: not ours to judge here */ }
136
137
  try {
137
138
  const hooks = readJson(join(home, ".claude", "settings.json")).hooks ?? {};
138
- if (["UserPromptSubmit", "PreCompact", "SessionStart"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
139
+ if (["UserPromptSubmit", "PreCompact", "SessionStart", "PreModelSwitch"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
139
140
  found.push("hooks in ~/.claude/settings.json");
140
141
  }
141
142
  catch { /* unreadable */ }
@@ -350,13 +351,16 @@ function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit") {
350
351
  writeJsonWithBackup(settingsPath, settings);
351
352
  return settingsPath;
352
353
  }
353
- function uninstallHook() {
354
- uninstallHookFrom(join(homedir(), ".claude", "settings.json"), "Claude Code every-prompt hook");
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");
357
- uninstallHookFrom(join(homedir(), ".codex", "hooks.json"), "Codex every-prompt hook");
358
- uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent");
359
- uninstallCursorHook();
354
+ /** Each hook removal on its own: a malformed file for one app must not leave the others installed. */
355
+ function uninstallHook(attempt) {
356
+ const claude = join(homedir(), ".claude", "settings.json");
357
+ attempt("Claude Code every-prompt hook", () => uninstallHookFrom(claude, "Claude Code every-prompt hook"));
358
+ attempt("Claude Code compaction hook", () => uninstallHookFrom(claude, "Claude Code compaction hook", "PreCompact"));
359
+ attempt("Claude Code session-start hook", () => uninstallHookFrom(claude, "Claude Code session-start hook", "SessionStart"));
360
+ attempt("Claude Code model-switch warning", () => uninstallHookFrom(claude, "Claude Code model-switch warning", "PreModelSwitch"));
361
+ attempt("Codex every-prompt hook", () => uninstallHookFrom(join(homedir(), ".codex", "hooks.json"), "Codex every-prompt hook"));
362
+ attempt("Gemini CLI every-prompt hook", () => uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent"));
363
+ attempt("Cursor hooks", () => uninstallCursorHook());
360
364
  }
361
365
  /**
362
366
  * Cursor runs Claude Code's UserPromptSubmit hook as its own
@@ -424,6 +428,37 @@ function uninstallCursorHook() {
424
428
  writeUninstalled(path, config, ["version"]);
425
429
  done("✓ Cursor hooks removed");
426
430
  }
431
+ /**
432
+ * The model-switch warning (PreModelSwitch) goes into ~/.claude/settings.json
433
+ * only when every Claude Code found here runs that event: an older one skips
434
+ * the WHOLE file over an event it does not know (measured on 2.1.62: none of
435
+ * the user's settings or hooks ran). With an older one present, an entry an
436
+ * earlier install wrote is taken out again.
437
+ */
438
+ export function installModelSwitchHook(readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv())) {
439
+ const dir = join(homedir(), ".claude");
440
+ if (!existsSync(dir))
441
+ return "no-claude-code";
442
+ const settingsPath = join(dir, "settings.json");
443
+ if (readiness.ok) {
444
+ installHookInto(settingsPath, dir, "PreModelSwitch");
445
+ return "installed";
446
+ }
447
+ uninstallHookFrom(settingsPath, "Claude Code model-switch warning (an older Claude Code here would skip the whole file)", "PreModelSwitch");
448
+ return readiness.old.length > 0 ? "old" : "unknown";
449
+ }
450
+ /**
451
+ * The Claude Code versions to plan for: CONTEXT_DOCTOR_CLAUDE_CODE_VERSIONS
452
+ * ("2.1.299,2.1.62") when detection cannot see an install, else what
453
+ * claudeCodeInstalls finds.
454
+ */
455
+ export function claudeCodeInstallsFromEnv() {
456
+ const forced = process.env.CONTEXT_DOCTOR_CLAUDE_CODE_VERSIONS;
457
+ if (forced !== undefined) {
458
+ return forced.split(",").map((v) => v.trim()).filter((v) => /^\d+\.\d+\.\d+$/.test(v)).map((version) => ({ path: "CONTEXT_DOCTOR_CLAUDE_CODE_VERSIONS", version, source: "cli" }));
459
+ }
460
+ return claudeCodeInstalls();
461
+ }
427
462
  function uninstallHookFrom(settingsPath, label, event = "UserPromptSubmit") {
428
463
  if (!existsSync(settingsPath))
429
464
  return;
@@ -741,6 +776,27 @@ export function runInstall(options = {}) {
741
776
  console.error(`✗ Claude Code every-prompt hook: ${e.message}`);
742
777
  failures.push("Claude Code hook");
743
778
  }
779
+ if (!viaPlugin && existsSync(join(homedir(), ".claude"))) {
780
+ try {
781
+ const readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv());
782
+ switch (installModelSwitchHook(readiness)) {
783
+ case "installed":
784
+ console.log("✓ Claude Code model-switch warning installed (PreModelSwitch): before /model switches, the price of re-writing this context into the new model's cache");
785
+ break;
786
+ case "old":
787
+ console.log(`– Claude Code model-switch warning skipped: ${describeInstalls(readiness.old)} predates PreModelSwitch (${PRE_MODEL_SWITCH_SINCE}) and would`);
788
+ console.log(" ignore your whole ~/.claude/settings.json with it. Update or remove it, then run install again.");
789
+ break;
790
+ case "unknown":
791
+ console.log(`– Claude Code model-switch warning skipped: no Claude Code version found to check (it needs ${PRE_MODEL_SWITCH_SINCE} or later).`);
792
+ break;
793
+ }
794
+ }
795
+ catch (e) {
796
+ console.error(`✗ Claude Code model-switch warning: ${e.message}`);
797
+ failures.push("Claude Code model-switch warning");
798
+ }
799
+ }
744
800
  try {
745
801
  const cursorHook = installCursorHook();
746
802
  if (cursorHook)
@@ -972,44 +1028,67 @@ export async function runUninstall() {
972
1028
  // installed state (as every write here used to) lost that original.
973
1029
  for (const p of configPaths())
974
1030
  backedUp.add(p);
1031
+ // Every step stands alone. A malformed ~/.gemini/settings.json used to
1032
+ // throw out of the whole uninstall midway, leaving everything after it
1033
+ // (status line, Codex, bookkeeping files) installed; now that one target
1034
+ // is reported and the rest still go.
1035
+ const failures = [];
1036
+ const attempt = (label, fn) => {
1037
+ try {
1038
+ fn();
1039
+ }
1040
+ catch (e) {
1041
+ failures.push(label);
1042
+ console.error(`✗ ${label}: ${e.message}`);
1043
+ }
1044
+ };
975
1045
  // First: if anything below fails, Claude Code must still reach the API.
976
1046
  const hadAutopilot = existsSync(join(homedir(), ".claude", ".context-doctor-autopilot.json"));
977
- await uninstallAutopilot();
978
- if (hadAutopilot)
979
- changes++;
1047
+ try {
1048
+ await uninstallAutopilot();
1049
+ if (hadAutopilot)
1050
+ changes++;
1051
+ }
1052
+ catch (e) {
1053
+ failures.push("autopilot");
1054
+ console.error(`✗ autopilot: ${e.message}`);
1055
+ }
980
1056
  for (const target of targets().filter((t) => t.detect())) {
981
- try {
1057
+ attempt(target.name, () => {
982
1058
  if (!existsSync(target.configPath))
983
- continue;
1059
+ return;
984
1060
  const config = readJson(target.configPath);
985
1061
  if (config.mcpServers?.["context-doctor"]) {
986
1062
  delete config.mcpServers["context-doctor"];
987
1063
  writeUninstalled(target.configPath, config);
988
1064
  done(`✓ ${target.name}: MCP server removed`);
989
1065
  }
990
- }
991
- catch (e) {
992
- console.error(`✗ ${target.name}: ${e.message}`);
993
- }
1066
+ });
994
1067
  }
995
- removeSkill(join(homedir(), ".claude", "skills", "context-doctor"), "Agent Skill");
996
- uninstallHook();
997
- uninstallStatusLine();
998
- uninstallCodex();
1068
+ attempt("Agent Skill", () => removeSkill(join(homedir(), ".claude", "skills", "context-doctor"), "Agent Skill"));
1069
+ uninstallHook(attempt);
1070
+ attempt("Claude Code status line", () => uninstallStatusLine());
1071
+ attempt("Codex", () => uninstallCodex());
999
1072
  // Remove our bookkeeping files too — uninstall means gone. The hook's
1000
1073
  // per-session state is a directory, one small file per session.
1001
1074
  for (const file of OUR_CLAUDE_FILES) {
1002
1075
  const p = join(homedir(), ".claude", file);
1003
- if (existsSync(p)) {
1004
- rmSync(p, { recursive: true, force: true });
1005
- done(`✓ Removed ${file}`);
1006
- }
1076
+ attempt(file, () => {
1077
+ if (existsSync(p)) {
1078
+ rmSync(p, { recursive: true, force: true });
1079
+ done(`✓ Removed ${file}`);
1080
+ }
1081
+ });
1007
1082
  }
1008
1083
  if (deletedStubs.length > 0) {
1009
1084
  console.log(`✓ Deleted ${deletedStubs.length === 1 ? "a file" : "files"} install had created, now empty: ${deletedStubs.map(tilde).join(", ")}`);
1010
1085
  }
1011
1086
  const backups = configPaths().map((p) => p + BACKUP_SUFFIX).filter((b) => existsSync(b));
1012
- if (changes === 0)
1087
+ if (failures.length > 0) {
1088
+ console.error(`Not removed: ${failures.join(", ")} (see above). Everything else was${changes === 0 ? " checked" : " removed"}; fix those files and run uninstall again.`);
1089
+ process.exitCode = 1;
1090
+ }
1091
+ else if (changes === 0)
1013
1092
  console.log("Nothing of context-doctor's was installed.");
1014
1093
  else
1015
1094
  console.log("Done.");