context-doctor 0.45.0 → 0.47.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 (75) hide show
  1. package/README.md +8 -3
  2. package/dist/ab.js +3 -2
  3. package/dist/autopilot.js +9 -5
  4. package/dist/blob.js +66 -12
  5. package/dist/budget.d.ts +10 -1
  6. package/dist/budget.js +37 -8
  7. package/dist/cachemisses.js +5 -3
  8. package/dist/cacheplan.js +2 -2
  9. package/dist/cachettl.js +2 -1
  10. package/dist/ci.js +2 -1
  11. package/dist/claudeplugin.d.ts +97 -0
  12. package/dist/claudeplugin.js +142 -0
  13. package/dist/cli.js +126 -39
  14. package/dist/coldresume.d.ts +6 -0
  15. package/dist/coldresume.js +7 -6
  16. package/dist/compactcost.d.ts +74 -0
  17. package/dist/compactcost.js +115 -0
  18. package/dist/compactwindow.js +5 -4
  19. package/dist/cursor.js +2 -0
  20. package/dist/doctor.js +106 -17
  21. package/dist/extract.js +4 -3
  22. package/dist/fanout.d.ts +15 -0
  23. package/dist/fanout.js +31 -10
  24. package/dist/firstfix.d.ts +43 -0
  25. package/dist/firstfix.js +80 -0
  26. package/dist/fix.d.ts +46 -2
  27. package/dist/fix.js +109 -20
  28. package/dist/hook.js +6 -2
  29. package/dist/httpguard.d.ts +13 -0
  30. package/dist/httpguard.js +22 -0
  31. package/dist/install.d.ts +21 -9
  32. package/dist/install.js +211 -40
  33. package/dist/limits.d.ts +5 -0
  34. package/dist/limits.js +26 -2
  35. package/dist/mcp.js +63 -62
  36. package/dist/missledger.js +5 -3
  37. package/dist/mod/api.d.ts +135 -0
  38. package/dist/mod/api.js +12 -0
  39. package/dist/mod/logic.d.ts +158 -0
  40. package/dist/mod/logic.js +244 -0
  41. package/dist/mod/register.d.ts +60 -0
  42. package/dist/mod/register.js +251 -0
  43. package/dist/modelids.d.ts +24 -0
  44. package/dist/modelids.js +65 -0
  45. package/dist/modelswitch.js +8 -4
  46. package/dist/modmeasure.d.ts +121 -0
  47. package/dist/modmeasure.js +310 -0
  48. package/dist/orgrates.d.ts +93 -0
  49. package/dist/orgrates.js +214 -0
  50. package/dist/overhead.js +11 -8
  51. package/dist/pack.d.ts +13 -0
  52. package/dist/pack.js +68 -3
  53. package/dist/preferences.js +2 -1
  54. package/dist/pricing.d.ts +26 -0
  55. package/dist/pricing.js +61 -7
  56. package/dist/progresssummaries.d.ts +148 -0
  57. package/dist/progresssummaries.js +248 -0
  58. package/dist/proxy.d.ts +1 -1
  59. package/dist/proxy.js +1 -1
  60. package/dist/prune.d.ts +8 -0
  61. package/dist/prune.js +11 -1
  62. package/dist/savings.js +8 -6
  63. package/dist/sessionprice.d.ts +22 -0
  64. package/dist/sessionprice.js +46 -14
  65. package/dist/spend.d.ts +46 -3
  66. package/dist/spend.js +86 -10
  67. package/dist/statusline.js +2 -2
  68. package/dist/subagentmodel.d.ts +12 -0
  69. package/dist/subagentmodel.js +17 -4
  70. package/dist/subagentpay.d.ts +15 -1
  71. package/dist/subagentpay.js +58 -25
  72. package/dist/subagents.js +4 -0
  73. package/dist/toolcwd.d.ts +14 -0
  74. package/dist/toolcwd.js +17 -0
  75. package/package.json +1 -1
@@ -0,0 +1,115 @@
1
+ /**
2
+ * A compaction's own request, estimated: the one request of a session that no
3
+ * transcript row carries usage for.
4
+ *
5
+ * Compacting sends the whole conversation once more with an instruction to
6
+ * summarize it, and the answer is the summary the session restarts from.
7
+ * Claude Code bills it and counts it in its own cost (the mods API says the
8
+ * session's cost ledger holds it), but writes only a `compact_boundary` row
9
+ * (`compactMetadata.preTokens`: the context it read) and the summary as a user
10
+ * row (`isCompactSummary`): no usage (2.1.321). So `spend`, the budget and a
11
+ * session's price left every compaction out, and the mod's comparison with
12
+ * Claude Code's own cost showed the gap.
13
+ *
14
+ * Estimated from what the transcript does record, at the model of the reply
15
+ * before it (rateCard, as every request: the organization's rates, the day's
16
+ * price, its fast mode and US-only):
17
+ * - the context it read, `preTokens`: at the cache-read rate when the cache
18
+ * the last reply left was still alive (an automatic compaction mid-turn,
19
+ * Claude Code's idle compaction before expiry), else written again at the
20
+ * session's lifetime (a /compact after the cache went cold);
21
+ * - its output, the summary: the summary row's text, in tokens.
22
+ * Not counted: the request's own instruction (a few hundred tokens) and any
23
+ * thinking it did. The next request's re-write of the new context is in that
24
+ * request's own usage, as before.
25
+ */
26
+ import { requestCost } from "./pricing.js";
27
+ import { textOf } from "./session.js";
28
+ import { realModel, tokensForLength } from "./tokens.js";
29
+ const HOUR_MS = 3_600_000;
30
+ const FIVE_MIN_MS = 300_000;
31
+ /** The summary's output when no summary row follows the boundary: compactwindow.ts's measured figure. */
32
+ export const SUMMARY_TOKENS_UNSEEN = 20_000;
33
+ export const newTrack = () => ({ t: {} });
34
+ /** A ledger's kept state, when it is one this version wrote. */
35
+ export function isTrack(v) {
36
+ return Boolean(v) && typeof v === "object" && Boolean(v.t) && typeof v.t === "object";
37
+ }
38
+ /** The rows a reader must hand on: replies with usage, compaction boundaries, summary rows. */
39
+ export function isCompactionRow(line) {
40
+ return line.includes('"compact_boundary"') || line.includes('"isCompactSummary"');
41
+ }
42
+ const thread = (e) => (e?.isSidechain === true ? "1" : "0");
43
+ function priced(st, summaryTokens) {
44
+ const p = st.p;
45
+ st.p = undefined;
46
+ if (!p)
47
+ return undefined;
48
+ const th = st.t[p.th];
49
+ if (!th?.m || !(p.pre > 0))
50
+ return undefined;
51
+ const ttl = th.ttl ?? HOUR_MS;
52
+ const warm = th.at !== undefined && p.at - th.at <= ttl;
53
+ const usage = warm
54
+ ? { input_tokens: 0, cache_read_input_tokens: p.pre, cache_creation_input_tokens: 0, output_tokens: summaryTokens, ...th.b }
55
+ : { input_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: p.pre, cache_creation: ttl >= HOUR_MS ? { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: p.pre } : { ephemeral_5m_input_tokens: p.pre, ephemeral_1h_input_tokens: 0 }, output_tokens: summaryTokens, ...th.b };
56
+ const cost = requestCost(th.m, usage, p.at);
57
+ if (!cost)
58
+ return undefined;
59
+ return { ...(p.u ? { uuid: p.u } : {}), ...(p.s ? { sessionId: p.s } : {}), sidechain: p.th === "1", ts: p.at, model: th.m, usage, cost, warm };
60
+ }
61
+ /**
62
+ * Feed one parsed row; a compaction's request when this row completes one
63
+ * (its summary row, or a reply that came with no summary row between). A
64
+ * boundary still waiting for its summary at the end of what was read is kept
65
+ * in `st` and priced when the summary is read.
66
+ */
67
+ export function trackCompaction(st, e) {
68
+ if (!e || typeof e !== "object")
69
+ return undefined;
70
+ if (e.type === "system" && e.subtype === "compact_boundary") {
71
+ // A boundary right after another (no summary between): the first is priced as unseen.
72
+ const before = st.p ? priced(st, SUMMARY_TOKENS_UNSEEN) : undefined;
73
+ const at = Date.parse(String(e.timestamp ?? ""));
74
+ const pre = Number(e.compactMetadata?.preTokens);
75
+ if (Number.isFinite(at) && Number.isFinite(pre) && pre > 0) {
76
+ st.p = { at, pre, th: thread(e), ...(typeof e.uuid === "string" ? { u: e.uuid } : {}), ...(typeof e.sessionId === "string" ? { s: e.sessionId } : {}) };
77
+ }
78
+ return before;
79
+ }
80
+ if (e.type === "user" && e.isCompactSummary === true) {
81
+ if (!st.p)
82
+ return undefined;
83
+ const length = typeof e.n === "number" ? e.n : textOf(e.message?.content).length;
84
+ const model = st.t[st.p.th]?.m;
85
+ return priced(st, Math.max(1, tokensForLength(length, false, model)));
86
+ }
87
+ if (e.type === "assistant" && e.message?.usage) {
88
+ const done = st.p && st.p.th === thread(e) ? priced(st, SUMMARY_TOKENS_UNSEEN) : undefined;
89
+ const model = realModel(e.message.model);
90
+ if (!model)
91
+ return done;
92
+ const u = e.message.usage;
93
+ const th = (st.t[thread(e)] ??= {});
94
+ th.m = model;
95
+ const at = Date.parse(String(e.timestamp ?? ""));
96
+ if (Number.isFinite(at))
97
+ th.at = at;
98
+ const split = u.cache_creation;
99
+ if (split && (split.ephemeral_1h_input_tokens ?? 0) > 0)
100
+ th.ttl = HOUR_MS;
101
+ else if (split && (split.ephemeral_5m_input_tokens ?? 0) > 0)
102
+ th.ttl = FIVE_MIN_MS;
103
+ const b = { ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { inference_geo: "us" } : {}) };
104
+ if (Object.keys(b).length)
105
+ th.b = b;
106
+ else
107
+ delete th.b;
108
+ return done;
109
+ }
110
+ return undefined;
111
+ }
112
+ /** A summary row as an extractor keeps it: its length, not its text. */
113
+ export function slimSummary(e) {
114
+ return { type: "user", isCompactSummary: true, n: textOf(e?.message?.content).length, ...(e?.isSidechain === true ? { isSidechain: true } : {}) };
115
+ }
@@ -22,7 +22,8 @@
22
22
  */
23
23
  import { join } from "node:path";
24
24
  import { listSessions, replyCounter, isClaudeSession } from "./session.js";
25
- import { cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
25
+ import { cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier, writePerM } from "./pricing.js";
26
+ import { priceBasis } from "./orgrates.js";
26
27
  import { realModel } from "./tokens.js";
27
28
  import { backupOnce } from "./install.js";
28
29
  import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
@@ -138,7 +139,7 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
138
139
  const rates = (ctx) => (r.card ? ratesAt(r.card, ctx) : UNPRICED);
139
140
  const cost = (ctx, prev) => {
140
141
  const p = rates(ctx);
141
- const write = writeMult * p.inputPerM;
142
+ const write = writePerM(p, writeMult);
142
143
  if (cold)
143
144
  return write * ctx;
144
145
  const fresh = prev === undefined || ctx < prev ? ctx : ctx - prev;
@@ -157,7 +158,7 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
157
158
  if (ctx >= TRIGGER_SHARE * window) {
158
159
  const p = rates(ctx);
159
160
  if (counted) {
160
- sim += p.cacheReadPerM * ctx + p.outputPerM * SUMMARY_OUTPUT + writeMult * p.inputPerM * reread;
161
+ sim += p.cacheReadPerM * ctx + p.outputPerM * SUMMARY_OUTPUT + writePerM(p, writeMult) * reread;
161
162
  extra++;
162
163
  }
163
164
  removed = r.prompt - AFTER_COMPACT - reread;
@@ -285,7 +286,7 @@ export function renderCompactWindows(r, current, limitLines) {
285
286
  const lines = [];
286
287
  lines.push("Auto-compact window: compact earlier, automatically (Claude Code's own setting)");
287
288
  // Counted and said exactly as `savings` says it, so the two screens agree.
288
- lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, at list prices`);
289
+ lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, ${priceBasis()}`);
289
290
  lines.push("─".repeat(66));
290
291
  lines.push(`Now: ${current ? `${k(current)} (set in ${tilde(settingsPath())})` : "not set: Claude Code compacts near the model's full window"}`);
291
292
  if (r.sessions === 0) {
package/dist/cursor.js CHANGED
@@ -12,6 +12,7 @@
12
12
  * say so plainly instead of failing obscurely.
13
13
  */
14
14
  import { execFileSync } from "node:child_process";
15
+ import { toolCwd } from "./toolcwd.js";
15
16
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
16
17
  import { createRequire } from "node:module";
17
18
  import { homedir, platform } from "node:os";
@@ -127,6 +128,7 @@ export function queryRows(dbPath, sql) {
127
128
  }
128
129
  // Fallback: the sqlite3 CLI, if the user has it.
129
130
  const cli = (target) => execFileSync("sqlite3", ["-readonly", "-json", target, sql], {
131
+ cwd: toolCwd(),
130
132
  encoding: "utf8",
131
133
  maxBuffer: 512 * 1024 * 1024,
132
134
  stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs
package/dist/doctor.js CHANGED
@@ -13,6 +13,8 @@ import { homedir, platform } from "node:os";
13
13
  import { dirname, join } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { ledgerPath, readLedger } from "./ledger.js";
16
+ import { costCheck } from "./modmeasure.js";
17
+ import { ago, MOD_SINCE, modActivity, modReadiness, PLUGIN_KEY, pluginStage, readPluginMarker } from "./claudeplugin.js";
16
18
  import { loadConfig } from "./config.js";
17
19
  import { codexRouting } from "./codexroute.js";
18
20
  import { CURSOR_HOOK_EVENTS } from "./install.js";
@@ -31,6 +33,7 @@ import { periodSpend, readBudget } from "./budget.js";
31
33
  import { sessionPriceThresholds } from "./sessionprice.js";
32
34
  import { claudeSpend, codexSpend } from "./spend.js";
33
35
  import { hasKnownPrice, isUnbilledModel, priceChangedText } from "./pricing.js";
36
+ import { managedSourcesLine, orgRatesLine } from "./orgrates.js";
34
37
  function claudeDesktopConfigPath() {
35
38
  switch (platform()) {
36
39
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -178,6 +181,23 @@ function hookBinaryMissing(command) {
178
181
  * Claude Code's settings files, lowest precedence first: user, project,
179
182
  * local. A later file's value for a key wins, as in Claude Code itself.
180
183
  */
184
+ /**
185
+ * A hooks event's entries, whatever the file holds there. A config written
186
+ * by hand can hold an object, a string or a null where a list belongs; the
187
+ * app ignores it, and doctor must not stop at it (it printed "settings.json
188
+ * unreadable (entries.map is not a function)").
189
+ */
190
+ function hookEntries(v) {
191
+ return Array.isArray(v) ? v.filter(isObject) : [];
192
+ }
193
+ /** The first command of a Claude Code-shaped hook entry ({ hooks: [{ command }] }), or "". */
194
+ function firstCommand(e) {
195
+ const h = Array.isArray(e.hooks) ? e.hooks[0] : undefined;
196
+ return isObject(h) && typeof h.command === "string" ? h.command : "";
197
+ }
198
+ function isObject(v) {
199
+ return v !== null && typeof v === "object" && !Array.isArray(v);
200
+ }
181
201
  function claudeSettingsLayers() {
182
202
  const paths = [
183
203
  join(claudeDir(), "settings.json"),
@@ -186,7 +206,9 @@ function claudeSettingsLayers() {
186
206
  ];
187
207
  return [...new Set(paths)].flatMap((p) => {
188
208
  try {
189
- return existsSync(p) ? [JSON.parse(readFileSync(p, "utf8"))] : [];
209
+ const v = existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : undefined;
210
+ // A file holding null, an array or a number is no settings at all (Claude Code ignores it).
211
+ return isObject(v) ? [v] : [];
190
212
  }
191
213
  catch {
192
214
  return []; // an unreadable user settings.json is reported by the hook check
@@ -203,13 +225,62 @@ function claudeSettingsLayers() {
203
225
  function pluginEnabled(layers) {
204
226
  const state = new Map();
205
227
  for (const s of layers) {
206
- for (const [key, on] of Object.entries((s.enabledPlugins ?? {}))) {
228
+ for (const [key, on] of Object.entries(isObject(s.enabledPlugins) ? s.enabledPlugins : {})) {
207
229
  if (isOurPluginKey(key))
208
230
  state.set(key, on === true);
209
231
  }
210
232
  }
211
233
  return [...state.values()].some(Boolean);
212
234
  }
235
+ /** A mod reading older than this is no longer "recording". */
236
+ const MOD_FRESH_MS = 24 * 3600_000;
237
+ /**
238
+ * Which way Claude Code gets context-doctor (claudeplugin.ts): the plugin,
239
+ * and how far Claude Code has got with it, or install's own wiring and why;
240
+ * then whether the mod is recording, from when it last wrote its ledgers.
241
+ */
242
+ function claudeRouteChecks(layers, plugin, now = Date.now()) {
243
+ const readiness = modReadiness(claudeCodeInstallsFromEnv());
244
+ const userOff = layers.some((s) => isObject(s.enabledPlugins) && s.enabledPlugins[PLUGIN_KEY] === false);
245
+ if (!plugin) {
246
+ const why = userOff
247
+ ? "the context-doctor plugin is turned off in your settings"
248
+ : readiness.ok
249
+ ? `every Claude Code here runs mods (${describeInstalls(readiness.installs)}): run context-doctor install to move to the plugin and its mod`
250
+ : readiness.old.length > 0
251
+ ? `${describeInstalls(readiness.old)} predates mods (${MOD_SINCE}), and every Claude Code here reads the same settings`
252
+ : `no Claude Code version found to check (the plugin's mod needs ${MOD_SINCE} or later)`;
253
+ const mod = { label: "Mod", status: readiness.ok && !userOff ? "warn" : "skip", detail: `not running: ${why}` };
254
+ // Nothing of ours in Claude Code at all is the hook check's failure, above.
255
+ return claudeInstalledCopies().length > 0 ? [{ label: "Claude Code route", status: "ok", detail: "install's own MCP server, skill and hooks, not the plugin" }, mod] : [mod];
256
+ }
257
+ const by = readPluginMarker() ? "enabled by install" : "enabled in your settings";
258
+ const st = pluginStage();
259
+ const route = st.stage === "installed"
260
+ ? { label: "Claude Code route", status: "ok", detail: `the context-doctor plugin (${by}), downloaded${st.version ? ` (${st.version})` : ""}: its MCP server, skills, hooks and mod` }
261
+ : {
262
+ label: "Claude Code route",
263
+ status: "warn",
264
+ detail: `the context-doctor plugin (${by}), ${st.stage === "registered" ? "its marketplace fetched but the plugin not downloaded yet" : "not fetched yet"}: Claude Code does that in the background at its next start and loads it from the session after (or at once: /reload-plugins)`,
265
+ };
266
+ let mod;
267
+ const act = modActivity();
268
+ const limits = act.limits ? `; limits ledger written ${ago(act.limits, now)}` : "; no limit reading yet (Claude Code hands them over on Pro and Max plans)";
269
+ if (process.env.CONTEXT_DOCTOR_NO_MOD === "1") {
270
+ mod = { label: "Mod", status: "skip", detail: "off: CONTEXT_DOCTOR_NO_MOD=1" };
271
+ }
272
+ else if (act.cost && now - act.cost < MOD_FRESH_MS) {
273
+ mod = { label: "Mod", status: "ok", detail: `recording: last measured ${ago(act.cost, now)} (~/.claude/.context-doctor-session-cost.jsonl)${limits}` };
274
+ }
275
+ else if (act.cost) {
276
+ mod = { label: "Mod", status: "warn", detail: `last measured ${ago(act.cost, now)}: no session that loaded the plugin since, or the mod stopped${limits}` };
277
+ }
278
+ else {
279
+ const old = readiness.old.length > 0 ? `; ${describeInstalls(readiness.old)} predates mods and never will` : "";
280
+ mod = { label: "Mod", status: "warn", detail: `has not measured yet: it records after each turn of a session that loaded the plugin (Claude Code ${MOD_SINCE}+ in the Desktop app, 2.1.287+ in a terminal)${old}` };
281
+ }
282
+ return [route, mod];
283
+ }
213
284
  /** "headroom (pid 4242)", or "another program". */
214
285
  function occupantName(o) {
215
286
  return `${o.name ?? "another program"}${o.pid ? ` (pid ${o.pid})` : ""}`;
@@ -221,8 +292,7 @@ function occupantName(o) {
221
292
  */
222
293
  function fanoutCheck(settings, plugin) {
223
294
  const label = "Subagent price";
224
- const entries = Array.isArray(settings.hooks?.PreToolUse) ? settings.hooks.PreToolUse : [];
225
- const ours = entries.find((e) => /context-doctor|cli\.js"?\s+hook/.test(e.hooks?.[0]?.command ?? ""));
295
+ const ours = hookEntries(settings.hooks?.PreToolUse).find((e) => /context-doctor|cli\.js"?\s+hook/.test(firstCommand(e)));
226
296
  let costs;
227
297
  try {
228
298
  costs = JSON.parse(readFileSync(subagentCostsPath(), "utf8"));
@@ -244,8 +314,7 @@ function fanoutCheck(settings, plugin) {
244
314
  */
245
315
  function modelSwitchCheck(settings, plugin) {
246
316
  const label = "Model-switch warning";
247
- const entries = settings.hooks?.PreModelSwitch ?? [];
248
- const ours = entries.some((e) => /context-doctor|cli\.js"?\s+hook/.test(e.hooks?.[0]?.command ?? ""));
317
+ const ours = hookEntries(settings.hooks?.PreModelSwitch).some((e) => /context-doctor|cli\.js"?\s+hook/.test(firstCommand(e)));
249
318
  const readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv());
250
319
  if (Array.isArray(settings.hooks?.PreModelSwitch) && readiness.old.length > 0) {
251
320
  return {
@@ -533,8 +602,7 @@ export async function runDoctor() {
533
602
  if (existsSync(settingsPath) || claudeCodePresent()) {
534
603
  try {
535
604
  const settings = readConfig(settingsPath) ?? {};
536
- const entries = settings.hooks?.UserPromptSubmit ?? [];
537
- const ours = entries.map((e) => e.hooks?.[0]?.command ?? "").find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
605
+ const ours = hookEntries(settings.hooks?.UserPromptSubmit).map(firstCommand).find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
538
606
  if (hooksDisabled(layers)) {
539
607
  // Registered or not, nothing runs: say that first, it is the fix.
540
608
  checks.push({
@@ -559,8 +627,7 @@ export async function runDoctor() {
559
627
  checks.push(missing
560
628
  ? { label: "Every-prompt hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` }
561
629
  : { label: "Every-prompt hook", status: "ok", detail: "registered in ~/.claude/settings.json; command resolves" });
562
- const pre = settings.hooks?.PreCompact ?? [];
563
- const preOurs = plugin || pre.some((e) => /context-doctor|cli\.js"?\s+hook/.test(e.hooks?.[0]?.command ?? ""));
630
+ const preOurs = plugin || hookEntries(settings.hooks?.PreCompact).some((e) => /context-doctor|cli\.js"?\s+hook/.test(firstCommand(e)));
564
631
  checks.push(preOurs
565
632
  ? { label: "Compaction hook", status: "ok", detail: "PreCompact: each compaction's summary keeps the session's files, open tasks, your instructions and failing commands" }
566
633
  : { label: "Compaction hook", status: "warn", detail: "not registered: compactions use generic instructions; run context-doctor install" });
@@ -586,9 +653,11 @@ export async function runDoctor() {
586
653
  label: "Plugin + install",
587
654
  status: "warn",
588
655
  detail: `the context-doctor plugin is enabled and \`install\` also wired Claude Code (${copies.join(", ")}), so its instructions and tools load twice. ` +
589
- "Keep one: `context-doctor uninstall` removes the installed copy (then `context-doctor install` re-wires other apps and skips Claude Code while the plugin is on), or disable the plugin",
656
+ "Run `context-doctor install`: it takes its own copies out while the plugin is on. Or disable the plugin",
590
657
  });
591
658
  }
659
+ if (claudeCodePresent())
660
+ checks.push(...claudeRouteChecks(layers, plugin));
592
661
  // Codex (OpenAI): MCP table in config.toml, hook in hooks.json, skill.
593
662
  const codexHome = codexDir();
594
663
  if (existsSync(codexHome)) {
@@ -611,8 +680,7 @@ export async function runDoctor() {
611
680
  try {
612
681
  const hooksPath = join(codexHome, "hooks.json");
613
682
  const hooks = readConfig(hooksPath) ?? {};
614
- const entries = hooks.hooks?.UserPromptSubmit ?? [];
615
- const ours = entries.map((e) => e.hooks?.[0]?.command ?? "").find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
683
+ const ours = hookEntries(hooks.hooks?.UserPromptSubmit).map(firstCommand).find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
616
684
  if (!ours) {
617
685
  checks.push(missingHook("Codex hook", codexMcp));
618
686
  }
@@ -658,8 +726,7 @@ export async function runDoctor() {
658
726
  ? missingPackageCheck("Gemini CLI MCP")
659
727
  : { label: "Gemini CLI MCP", status: "ok", detail: "wired in ~/.gemini/settings.json" };
660
728
  checks.push(geminiMcp);
661
- const entries = settings.hooks?.BeforeAgent ?? [];
662
- const ours = entries.map((e) => e.hooks?.[0]?.command ?? "").find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
729
+ const ours = hookEntries(settings.hooks?.BeforeAgent).map(firstCommand).find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
663
730
  const missing = ours ? hookBinaryMissing(ours) : undefined;
664
731
  checks.push(!ours
665
732
  ? missingHook("Gemini CLI hook", geminiMcp)
@@ -710,7 +777,7 @@ export async function runDoctor() {
710
777
  const hooksPath = join(homedir(), ".cursor", "hooks.json");
711
778
  try {
712
779
  const hooks = readConfig(hooksPath, ["version"]) ?? {};
713
- const oursIn = (event) => (hooks.hooks?.[event] ?? []).map((e) => e.command ?? "").find((c) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(c));
780
+ const oursIn = (event) => hookEntries(hooks.hooks?.[event]).map((e) => (typeof e.command === "string" ? e.command : "")).find((c) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(c));
714
781
  const ours = oursIn("postToolUse");
715
782
  const missing = ours ? hookBinaryMissing(ours) : undefined;
716
783
  const fallbacks = CURSOR_HOOK_EVENTS.filter((e) => !oursIn(e));
@@ -754,11 +821,23 @@ export async function runDoctor() {
754
821
  /* settings.json unreadable is already reported by the hook check */
755
822
  }
756
823
  }
824
+ // The plugin's mod: our session price against Claude Code's own cost, where it measured any.
825
+ try {
826
+ const c = costCheck();
827
+ if (c)
828
+ checks.push(c);
829
+ }
830
+ catch {
831
+ /* an unreadable ledger is no finding */
832
+ }
757
833
  // Skill
758
834
  const skillPath = join(claudeDir(), "skills", "context-doctor", "SKILL.md");
759
835
  checks.push(existsSync(skillPath)
760
836
  ? skillCheck("Agent Skill", [skillPath])
761
- : { label: "Agent Skill", status: "skip", detail: "not installed (run context-doctor install on a Claude Code machine)" });
837
+ : plugin
838
+ // The plugin carries the skill, and install skips it while the plugin is on: "run install" sent people round in a circle.
839
+ ? { label: "Agent Skill", status: "ok", detail: "provided by the context-doctor plugin" }
840
+ : { label: "Agent Skill", status: "skip", detail: "not installed (run context-doctor install on a Claude Code machine)" });
762
841
  // Ledger writable. Tested without writing an entry: recordLedger swallows
763
842
  // errors (so this could never fail), and the entry it wrote counted as a
764
843
  // hook check in every report.
@@ -827,6 +906,16 @@ export async function runDoctor() {
827
906
  if (c)
828
907
  checks.push(c);
829
908
  }
909
+ // Contracted rates in managed settings: every report prices Claude at them, as Claude Code does.
910
+ {
911
+ const org = orgRatesLine();
912
+ if (org)
913
+ checks.push({ label: "Prices", status: "ok", detail: org });
914
+ // Server-managed settings or an MDM profile come before the files in Claude Code, and alone: rates context-doctor cannot see.
915
+ const ahead = managedSourcesLine();
916
+ if (ahead)
917
+ checks.push({ label: "Prices", status: "warn", detail: ahead });
918
+ }
830
919
  checks.push(await checkMcpHandshake());
831
920
  // Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
832
921
  // dead proxy or a settings file pointing elsewhere is a real problem.
package/dist/extract.js CHANGED
@@ -22,11 +22,12 @@ import { execFile, spawnSync } from "node:child_process";
22
22
  import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
23
23
  import { tmpdir } from "node:os";
24
24
  import { dirname, extname, join, resolve } from "node:path";
25
+ import { toolCwd } from "./toolcwd.js";
25
26
  export const EXTRACTABLE = new Set([".pdf", ".docx", ".doc", ".rtf", ".odt", ".pptx"]);
26
27
  const RUN = { encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024 * 1024 };
27
28
  function run(cmd, args) {
28
29
  try {
29
- const r = spawnSync(cmd, args, RUN);
30
+ const r = spawnSync(cmd, args, { ...RUN, cwd: toolCwd() });
30
31
  return r.status === 0 && typeof r.stdout === "string" && r.stdout.trim() ? r.stdout : undefined;
31
32
  }
32
33
  catch {
@@ -47,7 +48,7 @@ function pdftotext(path) {
47
48
  return direct;
48
49
  const out = join(mkdtempSync(join(tmpdir(), "cd-pdf-")), "out.txt");
49
50
  try {
50
- spawnSync("pdftotext", [path, out], RUN);
51
+ spawnSync("pdftotext", [path, out], { ...RUN, cwd: toolCwd() });
51
52
  const text = existsSync(out) ? readFileSync(out, "utf8") : "";
52
53
  return text.trim() ? text : undefined;
53
54
  }
@@ -157,7 +158,7 @@ function runAsync(cmd, args, end) {
157
158
  finish({ timedOut: monotonicNow() >= end - 50 });
158
159
  }, timeout);
159
160
  try {
160
- child = execFile(cmd, args, { encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => {
161
+ child = execFile(cmd, args, { cwd: toolCwd(), encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => {
161
162
  // Only the clock says the budget ran out: a child killed for another
162
163
  // reason (seen on Windows runners, well inside a 60 s budget) is a
163
164
  // failed tool, and the next one is tried.
package/dist/fanout.d.ts CHANGED
@@ -28,6 +28,12 @@ export interface CostStat {
28
28
  p90: number;
29
29
  /** The model most of these ran on. */
30
30
  model?: string;
31
+ /**
32
+ * Their tokens, summed, as [uncached input, cache reads, cache writes,
33
+ * output, requests]: what another model's price of them is worked out
34
+ * from, rate by rate (absent in a cache written before it was kept).
35
+ */
36
+ tok?: [number, number, number, number, number];
31
37
  }
32
38
  export interface SubagentCosts {
33
39
  computedAt: number;
@@ -41,6 +47,15 @@ export interface SubagentCosts {
41
47
  byModel: Record<string, CostStat>;
42
48
  }
43
49
  export declare function subagentCostsPath(): string;
50
+ /**
51
+ * What runs like `s` cost on `to` against `from`: their own tokens priced
52
+ * at each model's rates (rateCard: its tier for their average prompt, the
53
+ * organization's rates), each category at its own rate. Fable 5.2 reads at
54
+ * 2.5% of its input and Sonnet 5.5 at 5%: by the input price alone a
55
+ * read-heavy run on Sonnet came out at half its price. The input ratio only
56
+ * for a stat kept without its tokens.
57
+ */
58
+ export declare function priceRatio(from: string | undefined, to: string | undefined, s?: CostStat): number;
44
59
  /**
45
60
  * Each subagent's bill in the last `days`, newest transcripts first, by
46
61
  * type and model. `limit` and `budgetMs` bound the work when the hook has
package/dist/fanout.js CHANGED
@@ -26,7 +26,7 @@ import { basename, dirname, join } from "node:path";
26
26
  import { statePath } from "./ledger.js";
27
27
  import { listSessions, isClaudeSession } from "./session.js";
28
28
  import { scanSubagent } from "./subagentpay.js";
29
- import { formatUsd, pricingFor } from "./pricing.js";
29
+ import { formatUsd, pricingFor, rateCard, ratesAt, usageCost } from "./pricing.js";
30
30
  import { tailUsage } from "./statusline.js";
31
31
  /** The subagent tool, by its current name and its pre-2.1.63 alias. */
32
32
  export const FANOUT_MATCHER = "Agent|Task";
@@ -42,13 +42,38 @@ function stat(costs) {
42
42
  for (const c of costs)
43
43
  if (c.model)
44
44
  models.set(c.model, (models.get(c.model) ?? 0) + 1);
45
+ const tok = costs.every((c) => c.tok) ? costs.reduce((t, c) => t.map((v, i) => v + c.tok[i]), [0, 0, 0, 0, 0]) : undefined;
45
46
  return {
46
47
  n: s.length,
47
48
  median: s[Math.floor(s.length / 2)],
48
49
  p90: s[Math.min(s.length - 1, Math.floor(s.length * 0.9))],
49
50
  model: [...models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0],
51
+ ...(tok ? { tok } : {}),
50
52
  };
51
53
  }
54
+ /**
55
+ * What runs like `s` cost on `to` against `from`: their own tokens priced
56
+ * at each model's rates (rateCard: its tier for their average prompt, the
57
+ * organization's rates), each category at its own rate. Fable 5.2 reads at
58
+ * 2.5% of its input and Sonnet 5.5 at 5%: by the input price alone a
59
+ * read-heavy run on Sonnet came out at half its price. The input ratio only
60
+ * for a stat kept without its tokens.
61
+ */
62
+ export function priceRatio(from, to, s) {
63
+ if (!from || !to || from === to)
64
+ return 1;
65
+ if (s?.tok && s.tok[4] > 0) {
66
+ const [input, read, write, output, requests] = s.tok;
67
+ const u = { input_tokens: input, cache_read_input_tokens: read, cache_creation_input_tokens: write, output_tokens: output };
68
+ const prompt = (input + read + write) / requests;
69
+ const at = (m) => { const c = rateCard(m); return c ? usageCost(u, ratesAt(c, prompt)).totalUsd : undefined; };
70
+ const a = at(from), b = at(to);
71
+ if (a !== undefined && b !== undefined && a > 0)
72
+ return b / a;
73
+ }
74
+ const a = pricingFor(from), b = pricingFor(to);
75
+ return a && b && a.inputPerM > 0 ? b.inputPerM / a.inputPerM : 1;
76
+ }
52
77
  /**
53
78
  * Each subagent's bill in the last `days`, newest transcripts first, by
54
79
  * type and model. `limit` and `budgetMs` bound the work when the hook has
@@ -96,7 +121,7 @@ export function measureSubagentCosts(days = 30, opts = {}) {
96
121
  type = String(JSON.parse(readFileSync(f.meta, "utf8"))?.agentType ?? "unknown").slice(0, 60);
97
122
  }
98
123
  catch { /* older Claude Code: no meta */ }
99
- runs.push({ type, model: s.model, usd: s.costUsd });
124
+ runs.push({ type, model: s.model, usd: s.costUsd, tok: [s.tokens.input, s.tokens.read, s.tokens.write, s.tokens.output, s.steps] });
100
125
  }
101
126
  catch { /* unreadable */ }
102
127
  }
@@ -150,7 +175,7 @@ const ALIAS = {
150
175
  sonnet: { family: /sonnet/i, fallback: "claude-sonnet-5-5" },
151
176
  opus: { family: /opus/i, fallback: "claude-opus-5-5" },
152
177
  haiku: { family: /haiku/i, fallback: "claude-haiku-5-5" },
153
- fable: { family: /fable|mythos/i, fallback: "claude-fable-5-1" },
178
+ fable: { family: /fable|mythos/i, fallback: "claude-fable-5-2" },
154
179
  };
155
180
  function aliasModel(alias, costs) {
156
181
  const a = ALIAS[alias.toLowerCase()];
@@ -192,23 +217,19 @@ export function estimateSubagent(costs, type, modelAlias, parentModel) {
192
217
  // inherits the parent's model (general-purpose and Explore ran on several
193
218
  // families on the author's history: they follow the parent).
194
219
  const model = (modelAlias ? aliasModel(modelAlias, costs) : undefined) ?? pinnedModel(costs, type) ?? parentModel ?? (byType && byType.n >= MIN_RUNS ? byType.model : undefined);
195
- const scale = (from, to) => {
196
- const a = pricingFor(from), b = pricingFor(to);
197
- return a && b && a.inputPerM > 0 ? b.inputPerM / a.inputPerM : 1;
198
- };
199
220
  let base, factor = 1;
200
221
  const exact = model ? costs.byTypeModel[`${type}|${model}`] : undefined;
201
222
  if (exact && exact.n >= MIN_RUNS)
202
223
  base = exact;
203
224
  else if (byType && byType.n >= MIN_RUNS) {
204
225
  base = byType;
205
- factor = scale(byType.model, model ?? byType.model);
226
+ factor = priceRatio(byType.model, model ?? byType.model, byType);
206
227
  }
207
228
  else if (model && costs.byModel[model]?.n >= MIN_RUNS)
208
229
  base = costs.byModel[model];
209
230
  else if (costs.all && costs.all.n >= MIN_RUNS) {
210
231
  base = costs.all;
211
- factor = scale(costs.all.model, model ?? costs.all.model);
232
+ factor = priceRatio(costs.all.model, model ?? costs.all.model, costs.all);
212
233
  }
213
234
  if (!base)
214
235
  return undefined;
@@ -219,7 +240,7 @@ export function estimateSubagent(costs, type, modelAlias, parentModel) {
219
240
  const measured = costs.byTypeModel[`${type}|${sonnet}`];
220
241
  est.cheaper = measured && measured.n >= MIN_RUNS
221
242
  ? { model: sonnet, median: measured.median, measured: true }
222
- : { model: sonnet, median: est.median * scale(est.model, sonnet), measured: false };
243
+ : { model: sonnet, median: est.median * priceRatio(est.model, sonnet, base), measured: false };
223
244
  if (!(est.cheaper.median < est.median))
224
245
  delete est.cheaper;
225
246
  }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * What a bare `context-doctor` shows in a terminal with Claude Code history:
3
+ * the plan, not the report, and one question.
4
+ *
5
+ * `fix` lists every lever with how it was measured, what it costs in quality
6
+ * and what it writes: 30 to 50 lines and a question per lever. The author,
7
+ * who wrote every lever, applied none of them that way. So the first screen
8
+ * splits `fix`'s own plan (the same replays, one scan) in two:
9
+ * - the fixes whose quality line is "none" (`Fix.qualityFree`: the model
10
+ * sees the same content, or the same content moved where it can open it,
11
+ * on the same model), one line each with one total and ONE y/N question
12
+ * that applies them all through `applyFix`, as `fix --apply <ids>` does;
13
+ * - the ones that trade something (compacting earlier, autopilot clearing
14
+ * output, the subagents' model, Codex's limit), one line each with their
15
+ * dollars and the command that applies each, after reading it in `fix`.
16
+ * Nothing is written without a `y` typed in a terminal.
17
+ */
18
+ import { type Fix } from "./fix.js";
19
+ export interface FirstSplit {
20
+ /** Offered under the one question: available and quality-free, in the plan's order. */
21
+ free: Fix[];
22
+ /** Available, with a quality cost (or one not measured): pointed at `fix`. */
23
+ other: Fix[];
24
+ /** Applied before (by `fix` or by hand). */
25
+ applied: Fix[];
26
+ }
27
+ export declare function splitFirstFixes(fixes: Fix[]): FirstSplit;
28
+ export interface FirstScreen {
29
+ days: number;
30
+ billedUsd: number;
31
+ codexBilledUsd?: number;
32
+ fixes: Fix[];
33
+ /** `context-doctor <rest>`, or `npx context-doctor <rest>` (invocation.ts). */
34
+ command: (rest: string) => string;
35
+ /** The record of applied fixes is damaged: `fix` refuses to apply, so nothing is asked. */
36
+ recordProblem?: string;
37
+ /** The question follows (stdin and stdout are a terminal); otherwise the last line says how to apply them. */
38
+ ask: boolean;
39
+ }
40
+ /** The screen, everything but the question itself (under 25 lines whatever the plan). */
41
+ export declare function renderFirstScreen(s: FirstScreen): string;
42
+ /** The one question, for the quality-free fixes together. */
43
+ export declare function firstQuestion(n: number, command: (rest: string) => string): string;