context-doctor 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +84 -694
  2. package/dist/autoclear.js +4 -1
  3. package/dist/autopilot.d.ts +20 -6
  4. package/dist/autopilot.js +105 -7
  5. package/dist/cachekey.d.ts +25 -0
  6. package/dist/cachekey.js +73 -0
  7. package/dist/cacheplan.d.ts +29 -9
  8. package/dist/cacheplan.js +110 -29
  9. package/dist/ci.js +9 -1
  10. package/dist/cli.js +359 -247
  11. package/dist/clihelp.d.ts +24 -0
  12. package/dist/clihelp.js +116 -0
  13. package/dist/codexroute.d.ts +46 -0
  14. package/dist/codexroute.js +122 -0
  15. package/dist/coldresume.d.ts +62 -0
  16. package/dist/coldresume.js +85 -6
  17. package/dist/compactquality.d.ts +3 -1
  18. package/dist/compactquality.js +15 -4
  19. package/dist/compactwindow.d.ts +31 -5
  20. package/dist/compactwindow.js +80 -25
  21. package/dist/diff.js +24 -2
  22. package/dist/doctor.d.ts +8 -2
  23. package/dist/doctor.js +138 -35
  24. package/dist/hook.js +23 -4
  25. package/dist/install.d.ts +35 -0
  26. package/dist/install.js +280 -48
  27. package/dist/invocation.d.ts +18 -0
  28. package/dist/invocation.js +49 -0
  29. package/dist/ledger.d.ts +2 -0
  30. package/dist/mcp.d.ts +5 -2
  31. package/dist/mcp.js +93 -299
  32. package/dist/mcpclient.js +45 -0
  33. package/dist/mcpschema.d.ts +1 -1
  34. package/dist/mcpschema.js +11 -8
  35. package/dist/optimize.d.ts +2 -0
  36. package/dist/optimize.js +2 -0
  37. package/dist/overhead.d.ts +12 -1
  38. package/dist/overhead.js +31 -7
  39. package/dist/preferences.d.ts +1 -1
  40. package/dist/preferences.js +5 -5
  41. package/dist/proxy.d.ts +14 -1
  42. package/dist/proxy.js +45 -4
  43. package/dist/savings.d.ts +17 -1
  44. package/dist/savings.js +12 -13
  45. package/dist/session.d.ts +15 -0
  46. package/dist/session.js +43 -0
  47. package/dist/subagentpay.d.ts +1 -1
  48. package/dist/subagentpay.js +3 -2
  49. package/package.json +5 -8
  50. package/skills/context-doctor/SKILL.md +3 -3
package/dist/doctor.js CHANGED
@@ -2,19 +2,23 @@
2
2
  * `context-doctor doctor` — self-check for a local installation.
3
3
  *
4
4
  * Verifies every integration point end to end and prints one ✓/✗/– line per
5
- * check, so "it doesn't work" becomes a single pasteable diagnosis. Always
6
- * exits 0 — absence of an app is a note, not a failure.
5
+ * check, so "it doesn't work" becomes a single pasteable diagnosis. Exits 1
6
+ * when any check fails (✗), so a script can tell; an app that is absent, or
7
+ * that nothing was installed into, is a note (–), not a failure.
7
8
  */
8
9
  import { autopilotPaths, health, installedVersion, proxyUrl, recentSurfaces } from "./autopilot.js";
9
10
  import { spawn } from "node:child_process";
10
- import { accessSync, constants as fsConstants, existsSync, mkdirSync, readFileSync } from "node:fs";
11
+ import { accessSync, constants as fsConstants, existsSync, readFileSync } from "node:fs";
11
12
  import { homedir, platform } from "node:os";
12
13
  import { dirname, join } from "node:path";
13
14
  import { fileURLToPath } from "node:url";
14
- import { ledgerPath } from "./ledger.js";
15
+ import { ledgerPath, readLedger } from "./ledger.js";
15
16
  import { loadConfig } from "./config.js";
16
- import { binOnPath, codexMcpEntry, geminiCliPresent, geminiSettingsPath, launcherNamesMissingPackage } from "./install.js";
17
+ import { codexRouting } from "./codexroute.js";
18
+ import { CURSOR_HOOK_EVENTS } from "./install.js";
19
+ import { binOnPath, claudeInstalledCopies, codexMcpEntry, geminiCliPresent, geminiSettingsPath, isEmptyStub, isOurPluginKey, launcherNamesMissingPackage } from "./install.js";
17
20
  import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
21
+ import { withInvocation } from "./invocation.js";
18
22
  function claudeDesktopConfigPath() {
19
23
  switch (platform()) {
20
24
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -33,12 +37,27 @@ function missingPackageCheck(label) {
33
37
  ? { label, status: "warn", detail: "MCP entry runs `npx context-doctor-mcp`, which starts only through your global install (no npm package has that name) — re-run: context-doctor install" }
34
38
  : { label, status: "fail", detail: "MCP entry runs `npx context-doctor-mcp`, a package that does not exist on npm, so the server never starts — re-run: context-doctor install" };
35
39
  }
40
+ /** The "not installed" note shared by every app whose config has nothing in it. */
41
+ const NOT_INSTALLED = "not installed (no config, or an empty one)";
42
+ /**
43
+ * Read a JSON config for a check: undefined when it is absent or an empty
44
+ * stub (`{}`, `{"mcpServers":{}}`, `{"hooks":{}}`), which configure nothing
45
+ * and are what install leaves behind once our entries are removed. Both
46
+ * mean "not installed" for every app alike. Throws on invalid JSON.
47
+ */
48
+ function readConfig(path, extraKeys = []) {
49
+ if (!existsSync(path))
50
+ return undefined;
51
+ const config = JSON.parse(readFileSync(path, "utf8"));
52
+ return isEmptyStub(config, extraKeys) ? undefined : config;
53
+ }
36
54
  function checkMcpEntry(appName, configPath, plugin = false) {
37
55
  const viaPlugin = { label: appName, status: "ok", detail: "MCP server provided by the context-doctor plugin" };
38
- if (!existsSync(configPath))
39
- return plugin ? viaPlugin : { label: appName, status: "skip", detail: "app not detected (config file absent)" };
40
56
  try {
41
- const config = JSON.parse(readFileSync(configPath, "utf8"));
57
+ const config = readConfig(configPath);
58
+ if (!config) {
59
+ return plugin ? viaPlugin : { label: appName, status: "skip", detail: existsSync(configPath) ? NOT_INSTALLED : "app not detected (config file absent)" };
60
+ }
42
61
  const entry = config.mcpServers?.["context-doctor"];
43
62
  if (!entry && plugin)
44
63
  return viaPlugin;
@@ -116,7 +135,7 @@ function pluginEnabled(layers) {
116
135
  const state = new Map();
117
136
  for (const s of layers) {
118
137
  for (const [key, on] of Object.entries((s.enabledPlugins ?? {}))) {
119
- if (key.startsWith("context-doctor@"))
138
+ if (isOurPluginKey(key))
120
139
  state.set(key, on === true);
121
140
  }
122
141
  }
@@ -171,14 +190,21 @@ export async function runDoctor() {
171
190
  checks.push({ label: "Desktop chat tool use", status: "ok", detail: describeDesktopUsage(desktop, recentSurfaces(7).get("claude-desktop") ?? 0) });
172
191
  const layers = claudeSettingsLayers();
173
192
  const plugin = pluginEnabled(layers);
174
- checks.push(checkMcpEntry("Claude Code", join(homedir(), ".claude.json"), plugin));
175
- checks.push(checkMcpEntry("Cursor", join(homedir(), ".cursor", "mcp.json")));
193
+ const claudeMcp = checkMcpEntry("Claude Code", join(homedir(), ".claude.json"), plugin);
194
+ const cursorMcp = checkMcpEntry("Cursor", join(homedir(), ".cursor", "mcp.json"));
195
+ checks.push(claudeMcp, cursorMcp);
196
+ // A missing hook is an issue only for an app that is there to hook: when
197
+ // the app's own MCP check says it is absent or holds nothing of ours, the
198
+ // hook is "not installed" too, not a failure.
199
+ const missingHook = (label, app) => app.status === "skip"
200
+ ? { label, status: "skip", detail: "not installed (nor is the MCP server, above)" }
201
+ : { label, status: "fail", detail: "not registered — run: context-doctor install" };
176
202
  // Hook registration. ~/.claude without a settings.json is Claude Code with
177
203
  // no hook registered, not Claude Code absent.
178
204
  const settingsPath = join(homedir(), ".claude", "settings.json");
179
205
  if (existsSync(settingsPath) || existsSync(join(homedir(), ".claude"))) {
180
206
  try {
181
- const settings = existsSync(settingsPath) ? JSON.parse(readFileSync(settingsPath, "utf8")) : {};
207
+ const settings = readConfig(settingsPath) ?? {};
182
208
  const entries = settings.hooks?.UserPromptSubmit ?? [];
183
209
  const ours = entries.map((e) => e.hooks?.[0]?.command ?? "").find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
184
210
  if (hooksDisabled(layers)) {
@@ -194,7 +220,7 @@ export async function runDoctor() {
194
220
  checks.push({ label: "Compaction hook", status: "ok", detail: "PreCompact: provided by the context-doctor plugin" });
195
221
  }
196
222
  else if (!ours) {
197
- checks.push({ label: "Every-prompt hook", status: "fail", detail: "not registered — run: context-doctor install" });
223
+ checks.push(missingHook("Every-prompt hook", claudeMcp));
198
224
  }
199
225
  else {
200
226
  // "Registered" is not "working": a hook whose binary has been deleted
@@ -218,6 +244,17 @@ export async function runDoctor() {
218
244
  else {
219
245
  checks.push({ label: "Every-prompt hook", status: "skip", detail: "Claude Code not detected" });
220
246
  }
247
+ // Plugin AND install: Claude Code then starts our MCP server twice (its
248
+ // instructions and tools load twice) and runs the hook twice.
249
+ const copies = plugin ? claudeInstalledCopies() : [];
250
+ if (copies.length > 0) {
251
+ checks.push({
252
+ label: "Plugin + install",
253
+ status: "warn",
254
+ detail: `the context-doctor plugin is enabled and \`install\` also wired Claude Code (${copies.join(", ")}), so its instructions and tools load twice. ` +
255
+ "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",
256
+ });
257
+ }
221
258
  // Codex (OpenAI): MCP table in config.toml, hook in hooks.json, skill.
222
259
  const codexHome = join(homedir(), ".codex");
223
260
  if (existsSync(codexHome)) {
@@ -225,18 +262,22 @@ export async function runDoctor() {
225
262
  // Parsed rather than searched for one exact header: a quoted key or a
226
263
  // trailing comment is the same table to Codex.
227
264
  const codexEntry = codexMcpEntry(toml);
228
- checks.push(!codexEntry
229
- ? { label: "Codex MCP", status: "fail", detail: "Codex detected but not wired — run: context-doctor install" }
265
+ // An absent or empty config.toml is "not installed", as for every other app.
266
+ const codexMcp = !codexEntry
267
+ ? toml.trim() === ""
268
+ ? { label: "Codex MCP", status: "skip", detail: NOT_INSTALLED }
269
+ : { label: "Codex MCP", status: "fail", detail: "Codex detected but not wired — run: context-doctor install" }
230
270
  : launcherNamesMissingPackage(codexEntry)
231
271
  ? missingPackageCheck("Codex MCP")
232
- : { label: "Codex MCP", status: "ok", detail: "wired in ~/.codex/config.toml" });
272
+ : { label: "Codex MCP", status: "ok", detail: "wired in ~/.codex/config.toml" };
273
+ checks.push(codexMcp);
233
274
  try {
234
275
  const hooksPath = join(codexHome, "hooks.json");
235
- const hooks = existsSync(hooksPath) ? JSON.parse(readFileSync(hooksPath, "utf8")) : {};
276
+ const hooks = readConfig(hooksPath) ?? {};
236
277
  const entries = hooks.hooks?.UserPromptSubmit ?? [];
237
278
  const ours = entries.map((e) => e.hooks?.[0]?.command ?? "").find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
238
279
  if (!ours) {
239
- checks.push({ label: "Codex hook", status: "fail", detail: "not registered — run: context-doctor install" });
280
+ checks.push(missingHook("Codex hook", codexMcp));
240
281
  }
241
282
  else {
242
283
  const missing = hookBinaryMissing(ours);
@@ -248,6 +289,19 @@ export async function runDoctor() {
248
289
  catch (e) {
249
290
  checks.push({ label: "Codex hook", status: "fail", detail: `~/.codex/hooks.json unreadable (${e.message})` });
250
291
  }
292
+ // Autopilot reaches Codex through openai_base_url (OPENAI_BASE_URL no
293
+ // longer routes it), and only on an API key.
294
+ const route = codexRouting(homedir());
295
+ const local = route.baseUrl && /^http:\/\/(127\.0\.0\.1|localhost):\d+\/v1\/?$/.test(route.baseUrl);
296
+ if (local && route.auth !== "apikey") {
297
+ checks.push({ label: "Codex autopilot", status: "warn", detail: `openai_base_url points at ${route.baseUrl} while Codex signs in ${route.auth === "chatgpt" ? "with ChatGPT" : "without an API key"}: autopilot routes Codex only on an API key (the proxy relays ChatGPT traffic unedited meanwhile); remove the line from ~/.codex/config.toml` });
298
+ }
299
+ else if (local) {
300
+ checks.push({ label: "Codex autopilot", status: "ok", detail: `Codex (API key) sends its requests through ${route.baseUrl}` });
301
+ }
302
+ else if (process.env.OPENAI_BASE_URL && route.auth === "apikey") {
303
+ checks.push({ label: "Codex autopilot", status: "warn", detail: "OPENAI_BASE_URL is set, but Codex no longer reads it: `context-doctor autopilot on` sets openai_base_url in ~/.codex/config.toml" });
304
+ }
251
305
  }
252
306
  else {
253
307
  checks.push({ label: "Codex", status: "skip", detail: "not detected (ChatGPT's Codex agent, IDE extension or CLI)" });
@@ -256,18 +310,22 @@ export async function runDoctor() {
256
310
  if (geminiCliPresent()) {
257
311
  try {
258
312
  const path = geminiSettingsPath();
259
- const settings = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {};
313
+ const read = readConfig(path);
314
+ const settings = read ?? {};
260
315
  const geminiEntry = settings.mcpServers?.["context-doctor"];
261
- checks.push(!geminiEntry
262
- ? { label: "Gemini CLI MCP", status: "fail", detail: "Gemini CLI detected but not wired — run: context-doctor install" }
316
+ const geminiMcp = !geminiEntry
317
+ ? read === undefined
318
+ ? { label: "Gemini CLI MCP", status: "skip", detail: NOT_INSTALLED }
319
+ : { label: "Gemini CLI MCP", status: "fail", detail: "Gemini CLI detected but not wired — run: context-doctor install" }
263
320
  : launcherNamesMissingPackage(geminiEntry)
264
321
  ? missingPackageCheck("Gemini CLI MCP")
265
- : { label: "Gemini CLI MCP", status: "ok", detail: "wired in ~/.gemini/settings.json" });
322
+ : { label: "Gemini CLI MCP", status: "ok", detail: "wired in ~/.gemini/settings.json" };
323
+ checks.push(geminiMcp);
266
324
  const entries = settings.hooks?.BeforeAgent ?? [];
267
325
  const ours = entries.map((e) => e.hooks?.[0]?.command ?? "").find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
268
326
  const missing = ours ? hookBinaryMissing(ours) : undefined;
269
327
  checks.push(!ours
270
- ? { label: "Gemini CLI hook", status: "fail", detail: "not registered — run: context-doctor install" }
328
+ ? missingHook("Gemini CLI hook", geminiMcp)
271
329
  : missing
272
330
  ? { label: "Gemini CLI hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` }
273
331
  : settings.hooksConfig?.enabled === false
@@ -281,19 +339,32 @@ export async function runDoctor() {
281
339
  else {
282
340
  checks.push({ label: "Gemini CLI", status: "skip", detail: "not detected" });
283
341
  }
284
- // Cursor: its agent gets the guidance through a native postToolUse hook
285
- // (the Claude Code hook it also runs cannot add context there).
342
+ // Cursor: its agent gets the guidance through native hooks (the Claude
343
+ // Code hook it also runs cannot add context there). Whether the text then
344
+ // reaches the model depends on the Cursor version, and Cursor logs only
345
+ // that the hook ran, so this says what is known rather than "✓".
286
346
  if (existsSync(join(homedir(), ".cursor"))) {
287
347
  const hooksPath = join(homedir(), ".cursor", "hooks.json");
288
348
  try {
289
- const hooks = existsSync(hooksPath) ? JSON.parse(readFileSync(hooksPath, "utf8")) : {};
290
- const ours = (hooks.hooks?.postToolUse ?? []).map((e) => e.command ?? "").find((c) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(c));
349
+ const hooks = readConfig(hooksPath, ["version"]) ?? {};
350
+ const oursIn = (event) => (hooks.hooks?.[event] ?? []).map((e) => e.command ?? "").find((c) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(c));
351
+ const ours = oursIn("postToolUse");
291
352
  const missing = ours ? hookBinaryMissing(ours) : undefined;
292
- checks.push(!ours
293
- ? { label: "Cursor hook", status: "fail", detail: "not registered — run: context-doctor install" }
294
- : missing
295
- ? { label: "Cursor hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` }
296
- : { label: "Cursor hook", status: "ok", detail: "registered in ~/.cursor/hooks.json (after each tool call in heavy chats)" });
353
+ const fallbacks = CURSOR_HOOK_EVENTS.filter((e) => !oursIn(e));
354
+ if (!ours)
355
+ checks.push(missingHook("Cursor hook", cursorMcp));
356
+ else if (missing)
357
+ checks.push({ label: "Cursor hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` });
358
+ else {
359
+ const v = cursorVersion();
360
+ const delivered = v ? versionAtLeast(v, 3, 17) : undefined;
361
+ const where = `registered in ~/.cursor/hooks.json for ${CURSOR_HOOK_EVENTS.filter((e) => oursIn(e)).join(", ")}`;
362
+ checks.push(delivered === false
363
+ ? { label: "Cursor hook", status: "warn", detail: `${where}, but Cursor ${v} drops hook additional_context before the model (confirmed by Cursor staff, March 2026; reported through 3.10): update Cursor to 3.17 or later; until then the MCP tools are the way in` }
364
+ : fallbacks.length
365
+ ? { label: "Cursor hook", status: "warn", detail: `${where}; re-run context-doctor install to add ${fallbacks.join(" and ")} (the fallbacks Cursor 3.17+ delivers)` }
366
+ : { label: "Cursor hook", status: "ok", detail: `${where}. ${v ? `Cursor ${v}` : "Cursor 3.17 and later"} attaches their additional_context to the tool result; Cursor does not log what the model saw: in a long chat, ask its agent what context-doctor said` });
367
+ }
297
368
  }
298
369
  catch (e) {
299
370
  checks.push({ label: "Cursor hook", status: "fail", detail: `~/.cursor/hooks.json unreadable (${e.message})` });
@@ -328,10 +399,14 @@ export async function runDoctor() {
328
399
  // Ledger writable. Tested without writing an entry: recordLedger swallows
329
400
  // errors (so this could never fail), and the entry it wrote counted as a
330
401
  // hook check in every report.
402
+ // Nor by creating its directory: doctor making ~/.claude on a machine
403
+ // without Claude Code made the next install and doctor see Claude Code.
331
404
  try {
332
405
  const lp = ledgerPath();
333
- mkdirSync(dirname(lp), { recursive: true });
334
- accessSync(existsSync(lp) ? lp : dirname(lp), fsConstants.W_OK);
406
+ let dir = dirname(lp);
407
+ while (!existsSync(dir) && dirname(dir) !== dir)
408
+ dir = dirname(dir);
409
+ accessSync(existsSync(lp) ? lp : dir, fsConstants.W_OK);
335
410
  checks.push({ label: "Ledger", status: "ok", detail: `writable at ${lp}` });
336
411
  }
337
412
  catch {
@@ -423,11 +498,14 @@ export async function runDoctor() {
423
498
  const mark = { ok: "✓", warn: "!", fail: "✗", skip: "–" };
424
499
  console.log("CONTEXT DOCTOR — self-check");
425
500
  console.log("═".repeat(56));
501
+ // Fix hints name `context-doctor <command>`; after an npx run, `npx context-doctor <command>`.
426
502
  for (const c of checks) {
427
- console.log(`${mark[c.status]} ${c.label.padEnd(22)} ${c.detail}`);
503
+ console.log(withInvocation(`${mark[c.status]} ${c.label.padEnd(22)} ${c.detail}`));
428
504
  }
429
505
  const fails = checks.filter((c) => c.status === "fail");
430
506
  const warns = checks.filter((c) => c.status === "warn");
507
+ if (fails.length > 0)
508
+ process.exitCode = 1;
431
509
  console.log("");
432
510
  console.log(fails.length > 0
433
511
  ? `${fails.length} issue(s) found — fixes suggested above.`
@@ -435,3 +513,28 @@ export async function runDoctor() {
435
513
  ? `No problems; ${warns.length} note(s) marked ! above.`
436
514
  : "All good.");
437
515
  }
516
+ /** "3.18.25" >= major.minor. */
517
+ function versionAtLeast(v, major, minor) {
518
+ const m = /^(\d+)\.(\d+)/.exec(v);
519
+ if (!m)
520
+ return true;
521
+ return Number(m[1]) > major || (Number(m[1]) === major && Number(m[2]) >= minor);
522
+ }
523
+ /**
524
+ * The Cursor version here: the newest one that ran the hook (its input
525
+ * carries cursor_version, on every platform), else the macOS app bundle.
526
+ */
527
+ export function cursorVersion() {
528
+ const fromLedger = readLedger().reverse().find((e) => typeof e.cv === "string")?.cv;
529
+ if (fromLedger)
530
+ return fromLedger;
531
+ for (const plist of ["/Applications/Cursor.app/Contents/Info.plist", join(homedir(), "Applications", "Cursor.app", "Contents", "Info.plist")]) {
532
+ try {
533
+ const m = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(readFileSync(plist, "utf8"));
534
+ if (m)
535
+ return m[1];
536
+ }
537
+ catch { /* not there */ }
538
+ }
539
+ return undefined;
540
+ }
package/dist/hook.js CHANGED
@@ -21,7 +21,7 @@ import { profileConversation } from "./profile.js";
21
21
  import { parseSessionFile } from "./session.js";
22
22
  import { formatTokens, CHARS_PER_TOKEN, LARGEST_WINDOW } from "./tokens.js";
23
23
  import { ensureProxyUp } from "./autopilot.js";
24
- import { detectColdResume, renderColdResume, renderColdResumeNotice, sessionWriteMultiplier } from "./coldresume.js";
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
27
  import { compactFacts, compactInstructions } from "./precompact.js";
@@ -158,6 +158,15 @@ export async function runHook() {
158
158
  }
159
159
  const input = JSON.parse(await readStdin());
160
160
  await heal;
161
+ // A resumed session: Claude Code says whether its cache expired and what
162
+ // re-caching costs. Kept for the first prompt, which decides the offer
163
+ // (an offer before any message would come before the rebuild it prices).
164
+ if (input.hook_event_name === "SessionStart") {
165
+ const verdict = resumeVerdict(input);
166
+ if (verdict && input.session_id)
167
+ writeSessionState(input.session_id, { ...readSessionState(input.session_id), rv: verdict });
168
+ return;
169
+ }
161
170
  // Before a compaction: tell the summary what this session cannot lose.
162
171
  // Claude Code adds a PreCompact hook's plain-text output to the
163
172
  // compaction's instructions (auto and manual alike).
@@ -178,7 +187,9 @@ export async function runHook() {
178
187
  // Cursor marks every hook input with cursor_version; any of its events but
179
188
  // postToolUse would only spend the once-per-growth warning on output Cursor
180
189
  // drops.
181
- const cursor = input.hook_event_name === "postToolUse";
190
+ // postToolUseFailure and sessionStart carry additional_context too: the
191
+ // first serves a chat whose tool calls fail, the second a resumed heavy chat.
192
+ const cursor = input.hook_event_name === "postToolUse" || input.hook_event_name === "postToolUseFailure" || input.hook_event_name === "sessionStart";
182
193
  if (input.hook_event_name === "beforeSubmitPrompt" || (input.cursor_version && !cursor))
183
194
  return;
184
195
  const transcriptPath = input.transcript_path;
@@ -202,7 +213,15 @@ export async function runHook() {
202
213
  // Once per idle period; the tail read is ~1 ms and only on large files.
203
214
  const notes = [];
204
215
  let notice;
205
- const cold = detectColdResume(transcriptPath);
216
+ // Silent when Claude Code compacts this very prompt itself (the context
217
+ // is past its auto-compact window, e.g. one set smaller since): an offer
218
+ // would arrive after the compaction it proposes. Below the window the
219
+ // note tells the model to stay quiet if a compaction came first (seen
220
+ // once in 516 cold returns: a 964k session compacted, then the reply
221
+ // offered /compact on the fresh summary).
222
+ let cold = withResumeVerdict(detectColdResume(transcriptPath), prev.rv);
223
+ if (cold && cold.tokens >= (autoCompactsAt(cold.model ?? input.model) ?? Infinity))
224
+ cold = undefined;
206
225
  let cr = prev.cr;
207
226
  if (cold && cold.lastReplyAt !== prev.cr) {
208
227
  notes.push(renderColdResume(cold));
@@ -253,7 +272,7 @@ export async function runHook() {
253
272
  // warning needed 1.4x a size the session no longer had (seen: warned at
254
273
  // 843k, compacted, then regrew to 809k without a word).
255
274
  writeSessionState(sessionId, { t: shouldWarn ? liveTokens : Math.min(prev.t, liveTokens), b: sizeBytes, cr });
256
- recordLedger({ ev: "check", sid: sessionId.slice(0, 12), tok: liveTokens, warn: shouldWarn });
275
+ recordLedger({ ev: "check", sid: sessionId.slice(0, 12), tok: liveTokens, warn: shouldWarn, ...(input.cursor_version ? { cv: input.cursor_version } : {}) });
257
276
  if (!shouldWarn) {
258
277
  emit(notes);
259
278
  return;
package/dist/install.d.ts CHANGED
@@ -38,6 +38,31 @@ export declare function launcherNamesMissingPackage(entry: {
38
38
  command?: unknown;
39
39
  args?: unknown;
40
40
  } | undefined): boolean;
41
+ /**
42
+ * The Claude Code plugin's key in enabledPlugins: "<plugin>@<marketplace>".
43
+ * Our marketplace (.claude-plugin/marketplace.json) is named context-doctor
44
+ * and lists one plugin, context-doctor, so the official key is
45
+ * "context-doctor@context-doctor"; a copy listed in another marketplace keeps
46
+ * the plugin name, so any "context-doctor@…" key is ours.
47
+ */
48
+ export declare const PLUGIN_KEY = "context-doctor@context-doctor";
49
+ export declare function isOurPluginKey(key: string): boolean;
50
+ /**
51
+ * Is the context-doctor plugin switched on in the user's Claude Code
52
+ * settings? The plugin brings its own MCP server, skills and hooks, so
53
+ * `install` adding them as well makes Claude Code load the server's
54
+ * instructions and tools twice.
55
+ */
56
+ export declare function claudePluginEnabled(home?: string): boolean;
57
+ /** What `install` put into Claude Code that the plugin also provides, by name. */
58
+ export declare function claudeInstalledCopies(home?: string): string[];
59
+ /**
60
+ * A config that configures nothing: `{}`, or only empty `mcpServers` /
61
+ * `hooks` containers (plus `extraKeys`, e.g. the `version` install writes
62
+ * into Cursor's hooks.json). It is what install's own writes leave once our
63
+ * entries are gone, and to an app it is the same as no file at all.
64
+ */
65
+ export declare function isEmptyStub(config: unknown, extraKeys?: string[]): boolean;
41
66
  export declare function readJson(path: string): Record<string, any>;
42
67
  /** Copy `path` to its .context-doctor.backup, once per run. */
43
68
  export declare function backupOnce(path: string): void;
@@ -66,6 +91,16 @@ export declare function installStatusLine(): "installed" | "already" | "kept-for
66
91
  * tool call, which the hook's stat-only fast path and regrowth gate make cheap.
67
92
  */
68
93
  export declare function cursorHooksPath(): string;
94
+ export declare const isOurCursorEntry: (e: unknown) => boolean;
95
+ /**
96
+ * Cursor's events whose `additional_context` can reach its agent: after a
97
+ * tool call, after a failed one, and at the start of a chat. Cursor 3.18's
98
+ * agent runtime attaches the first two to the tool result (Cursor confirmed
99
+ * postToolUseFailure delivery in 3.17.8); before 3.17 it dropped postToolUse
100
+ * output (staff-confirmed, March 2026). sessionStart is the documented way
101
+ * to add context to a chat's start, and serves a resumed heavy chat.
102
+ */
103
+ export declare const CURSOR_HOOK_EVENTS: readonly ["postToolUse", "postToolUseFailure", "sessionStart"];
69
104
  export declare function installCursorHook(): string | null;
70
105
  export declare function codexDir(): string;
71
106
  /**