context-doctor 0.46.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 (61) hide show
  1. package/README.md +7 -4
  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 +8 -2
  6. package/dist/budget.js +30 -7
  7. package/dist/ci.js +2 -1
  8. package/dist/claudeplugin.d.ts +97 -0
  9. package/dist/claudeplugin.js +142 -0
  10. package/dist/cli.js +109 -36
  11. package/dist/compactcost.d.ts +74 -0
  12. package/dist/compactcost.js +115 -0
  13. package/dist/cursor.js +2 -0
  14. package/dist/doctor.js +90 -18
  15. package/dist/extract.js +4 -3
  16. package/dist/fanout.d.ts +15 -0
  17. package/dist/fanout.js +30 -9
  18. package/dist/firstfix.d.ts +43 -0
  19. package/dist/firstfix.js +80 -0
  20. package/dist/fix.d.ts +46 -2
  21. package/dist/fix.js +95 -10
  22. package/dist/httpguard.d.ts +13 -0
  23. package/dist/httpguard.js +22 -0
  24. package/dist/install.d.ts +21 -9
  25. package/dist/install.js +211 -40
  26. package/dist/limits.d.ts +5 -0
  27. package/dist/limits.js +26 -2
  28. package/dist/mcp.js +60 -59
  29. package/dist/missledger.js +5 -3
  30. package/dist/mod/api.d.ts +8 -2
  31. package/dist/mod/api.js +2 -2
  32. package/dist/mod/logic.d.ts +13 -1
  33. package/dist/mod/logic.js +24 -2
  34. package/dist/mod/register.d.ts +2 -0
  35. package/dist/mod/register.js +19 -5
  36. package/dist/modelids.d.ts +4 -3
  37. package/dist/modelids.js +23 -7
  38. package/dist/modelswitch.js +8 -4
  39. package/dist/modmeasure.js +13 -1
  40. package/dist/orgrates.d.ts +18 -0
  41. package/dist/orgrates.js +51 -2
  42. package/dist/pack.d.ts +13 -0
  43. package/dist/pack.js +38 -2
  44. package/dist/preferences.js +2 -1
  45. package/dist/pricing.d.ts +8 -0
  46. package/dist/pricing.js +16 -0
  47. package/dist/progresssummaries.d.ts +148 -0
  48. package/dist/progresssummaries.js +248 -0
  49. package/dist/proxy.d.ts +1 -1
  50. package/dist/proxy.js +1 -1
  51. package/dist/prune.d.ts +8 -0
  52. package/dist/prune.js +11 -1
  53. package/dist/spend.d.ts +34 -0
  54. package/dist/spend.js +48 -4
  55. package/dist/subagentmodel.d.ts +12 -0
  56. package/dist/subagentmodel.js +17 -4
  57. package/dist/subagentpay.d.ts +8 -0
  58. package/dist/subagentpay.js +8 -1
  59. package/dist/toolcwd.d.ts +14 -0
  60. package/dist/toolcwd.js +17 -0
  61. package/package.json +1 -1
package/dist/fix.js CHANGED
@@ -27,7 +27,10 @@
27
27
  * ran on before against as billed (the same token counts: an estimate);
28
28
  * - long Bash output: the results moved to a file that the cap before left
29
29
  * inline, priced at the requests that re-read them no more (an estimate:
30
- * a file the model opens again is not counted).
30
+ * a file the model opens again is not counted);
31
+ * - subagent progress summaries: the summaries Claude Code would have
32
+ * written for the background subagents since (2.1.318+, which read the
33
+ * variable), estimated as `spend` estimates them (progresssummaries.ts).
31
34
  *
32
35
  * The subagents' model is the one lever with a quality cost `fix` cannot
33
36
  * measure: it is offered with that said, applied only when named (never by
@@ -40,16 +43,17 @@ import { forEachLine, listSessions, isClaudeSession } from "./session.js";
40
43
  import { rateCard, ratesAt } from "./pricing.js";
41
44
  import { priceBasis } from "./orgrates.js";
42
45
  import { contextWindowFor, realModel } from "./tokens.js";
43
- import { adviseTtl, CACHE_TTL_SINCE, estimateCacheTtl } from "./cachettl.js";
46
+ import { adviseTtl, CACHE_TTL_SINCE, estimateCacheTtl, subagentTranscripts } from "./cachettl.js";
44
47
  import { compareVersions, describeInstalls } from "./modelswitch.js";
45
48
  import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, withSettingsLock, writeAtomic } from "./settingsedit.js";
46
- import { compactWindowOverrides, processEnvWhere, settingsSources, shellSet, ttlOverrides } from "./effective.js";
49
+ import { compactWindowOverrides, effectiveEnv, processEnvWhere, settingsSources, shellSet, ttlOverrides, underClaudeCode } from "./effective.js";
47
50
  import { tilde } from "./claudedir.js";
48
51
  import { applyPrune, undoPrune } from "./prune.js";
49
52
  import { fallbackStateDir, readLedger } from "./ledger.js";
50
53
  import { claudeDir } from "./claudedir.js";
51
54
  import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
52
55
  import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, BASH_OUTPUT_SINCE, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
56
+ import { disablesSummaries, estimateProgressSummaries, hostName, PROGRESS_SUMMARIES_ENV, PROGRESS_SUMMARIES_OFF, PROGRESS_SUMMARIES_SINCE } from "./progresssummaries.js";
53
57
  import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCompactSavedSince, codexConfigPath, renderCodexLimits, setTopLevelInt, topLevelValue } from "./codexcompact.js";
54
58
  /**
55
59
  * The Claude Code version that first reads each setting a fix writes, from
@@ -59,14 +63,14 @@ import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCom
59
63
  * the subagent variable ahead of agent definitions there). autoCompactWindow
60
64
  * is not in 2.1.62 and the changelog does not say when it came: not named.
61
65
  */
62
- const SINCE = { "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE };
66
+ const SINCE = { "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE, "progress-summaries": PROGRESS_SUMMARIES_SINCE };
63
67
  /** Below this a priced fix is not worth a setting. */
64
68
  const MIN_USD = 1;
65
- const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
69
+ export const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
66
70
  const pct = (x) => `${Math.round(x * 100)}%`;
67
71
  const k = (n) => `${Math.round(n / 1000)}k`;
68
72
  /** " (48%)", or " (37% of subagents)" for a share of something else. */
69
- const share = (f) => (f.savedShare !== undefined ? ` (${pct(f.savedShare)}${f.shareOf ? ` ${f.shareOf}` : ""})` : "");
73
+ export const share = (f) => (f.savedShare !== undefined ? ` (${pct(f.savedShare)}${f.shareOf ? ` ${f.shareOf}` : ""})` : "");
70
74
  export function planFixes(i) {
71
75
  const fixes = [];
72
76
  const where = tilde(join(claudeDir(), "settings.json"));
@@ -105,6 +109,7 @@ export function planFixes(i) {
105
109
  savedShare: a.savedShare,
106
110
  basis: `the same ${r.requests.toLocaleString("en-US")} requests priced at each lifetime (${pct(r.oneHourShare)} of writes at 1 hour as billed${a.ttl === "1h" && r.keptWarmAt1h ? `; ${r.keptWarmAt1h} cold re-writes kept warm` : ""})`,
107
111
  quality: "none: the same content is sent; only the price of keeping it cached changes",
112
+ qualityFree: true,
108
113
  change: `${where}: ${key} = "${a.ttl}" (Claude Code 2.1.243+)`,
109
114
  state: "available",
110
115
  value: a.ttl,
@@ -142,6 +147,7 @@ export function planFixes(i) {
142
147
  title: "MCP tool search back on",
143
148
  basis: `ENABLE_TOOL_SEARCH=${i.toolSearchOff} loads every tool definition of your ${i.mcpServers} MCP server${i.mcpServers === 1 ? "" : "s"} into every request; with search on Claude Code loads one when it is needed (Anthropic: ~77k tokens to ~8.7k on a large set, tool choice more accurate, not less)`,
144
149
  quality: "none expected: Anthropic measured better tool choice with search on (Opus 4.5: 79.5% to 88.1%)",
150
+ qualityFree: true,
145
151
  change: `${where}: env.ENABLE_TOOL_SEARCH = "auto"`,
146
152
  state: "available",
147
153
  value: "auto",
@@ -154,6 +160,7 @@ export function planFixes(i) {
154
160
  title: `Switch off ${names.length} unused MCP server${names.length === 1 ? "" : "s"} or skill${names.length === 1 ? "" : "s"} in this project`,
155
161
  basis: `none used in ${i.prune.sessions} sessions of this project in ${i.days} days: ${names.slice(0, 5).join(", ")}${names.length > 5 ? ", …" : ""}`,
156
162
  quality: "none while they stay unused; undo brings them back",
163
+ qualityFree: true,
157
164
  change: join(i.prune.cwd, ".claude", "settings.local.json"),
158
165
  state: "available",
159
166
  });
@@ -204,6 +211,8 @@ export function planFixes(i) {
204
211
  shareOf: "of input, subagents included",
205
212
  basis: `${best.moved.toLocaleString("en-US")} of ${best.results.toLocaleString("en-US")} Bash results were longer; the tokens past a 2,000-character preview priced at each later request that re-read them until a compaction (cache reads, one write); an estimate: a file the model opens again costs about ${money(each)} a time and is not counted, and the saving covers it opening up to ${pct(breakEven(best))} of them`,
206
213
  quality: "long output goes to a file the model can still open; it sees the first 2,000 characters and the path, as it already does past 30,000",
214
+ // Nothing is lost, only moved (in `--apply all` for the same reason).
215
+ qualityFree: true,
207
216
  change: `${where}: ${BASH_OUTPUT_KEY} = ${best.cap} (Claude Code 2.1.261+)`,
208
217
  state: "available",
209
218
  value: best.cap,
@@ -231,6 +240,33 @@ export function planFixes(i) {
231
240
  detail: renderCodexLimits(cx, CODEX_COMPACT_LIMIT),
232
241
  });
233
242
  }
243
+ const ps = i.progressSummaries;
244
+ const psSet = i.progressSummariesSet;
245
+ if (psSet) {
246
+ const off = disablesSummaries(psSet.value);
247
+ const less = !off && ps && ps.notesUsd >= MIN_USD ? ` (turning them off would have saved about ${money(ps.notesUsd)})` : "";
248
+ fixes.push({ id: "progress-summaries", title: "Subagent progress summaries", basis: "set", quality: "", change: `env.${PROGRESS_SUMMARIES_ENV}`, state: off ? "applied" : "not-here", note: `${PROGRESS_SUMMARIES_ENV}=${psSet.value} in ${psSet.where}${off ? "" : `: left as you set it${less}`}`, value: psSet.value });
249
+ }
250
+ else if (ps && ps.summarized > 0 && ps.notesUsd >= MIN_USD) {
251
+ const billed = i.subagentModel?.billedUsd ?? 0;
252
+ fixes.push({
253
+ id: "progress-summaries",
254
+ title: "Subagent progress summaries off",
255
+ savedUsd: ps.notesUsd,
256
+ savedShare: billed > 0 ? ps.notesUsd / billed : undefined,
257
+ shareOf: "of subagents",
258
+ basis: `${ps.calls.toLocaleString("en-US")} summaries for ${ps.summarized} background subagent${ps.summarized === 1 ? "" : "s"}, one each 30 s while one ran and its transcript changed; no transcript records them, so an estimate: ~1,850 tokens of notes each (what Anthropic serves since November 2026), ${money(ps.forkUsd)} if each sent the whole context, as before`,
259
+ quality: "none to the work: a summary never enters the subagent's context; you lose the 3-5 word progress line on a running subagent's task row",
260
+ qualityFree: true,
261
+ change: `${where}: env.${PROGRESS_SUMMARIES_ENV} = "${PROGRESS_SUMMARIES_OFF}" (Claude Code ${PROGRESS_SUMMARIES_SINCE}+)`,
262
+ state: "available",
263
+ value: PROGRESS_SUMMARIES_OFF,
264
+ });
265
+ }
266
+ else if (ps && ps.summarized === 0 && (ps.none.host ?? 0) > 0) {
267
+ const n = ps.none.host;
268
+ fixes.push({ id: "progress-summaries", title: "Subagent progress summaries", basis: "", quality: "", change: "", state: "not-here", note: `your ${n} background subagent${n === 1 ? "" : "s"} ran in ${ps.hosts.map(hostName).join(" and ")}, where Claude Code writes no progress summaries: nothing to turn off` });
269
+ }
234
270
  for (const f of fixes) {
235
271
  const o = i.overrides?.[f.id];
236
272
  if (o?.length && f.state === "available")
@@ -306,9 +342,12 @@ const KEY_PATH = {
306
342
  "tool-search": ["env", "ENABLE_TOOL_SEARCH"],
307
343
  "subagent-model": ["env", SUBAGENT_MODEL_ENV],
308
344
  "tool-output": [BASH_OUTPUT_KEY],
345
+ "progress-summaries": ["env", PROGRESS_SUMMARIES_ENV],
309
346
  };
310
347
  /** Fixes that never overwrite a value already there: the user set it. */
311
- const YOURS = new Set(["subagent-model", "tool-output"]);
348
+ const YOURS = new Set(["subagent-model", "tool-output", "progress-summaries"]);
349
+ /** The environment variable a settings fix writes, when the shell's own value is the user's too. */
350
+ const SHELL_ENV = { "subagent-model": SUBAGENT_MODEL_ENV, "progress-summaries": PROGRESS_SUMMARIES_ENV };
312
351
  /** Fixes with a quality cost not measured here: applied only when named, never by `--apply all`. */
313
352
  const NAMED_ONLY = new Set(["subagent-model"]);
314
353
  /** What would keep this fix's value from taking effect, as Claude Code merges settings. */
@@ -339,6 +378,10 @@ export function fixOverrides(id, deps = {}) {
339
378
  out.push(`${SUBAGENT_MODEL_ENV}=${s.settings.env[SUBAGENT_MODEL_ENV]} in ${tilde(s.path)} env`);
340
379
  return out;
341
380
  }
381
+ if (id === "progress-summaries") {
382
+ // A project's, local or managed env is applied over the user's: a value there that does not turn them off wins.
383
+ return sources.filter((s) => s.name !== "user" && s.settings.env?.[PROGRESS_SUMMARIES_ENV] !== undefined && s.settings.env[PROGRESS_SUMMARIES_ENV] !== null && !disablesSummaries(s.settings.env[PROGRESS_SUMMARIES_ENV])).map((s) => `${PROGRESS_SUMMARIES_ENV}=${s.settings.env[PROGRESS_SUMMARIES_ENV]} in ${tilde(s.path)} env`);
384
+ }
342
385
  if (id === "tool-output") {
343
386
  // Merged settings: a project's or managed value wins over the user's (BASH_MAX_OUTPUT_LENGTH does not: the setting replaces it).
344
387
  return sources.filter((s) => s.name !== "user" && s.settings[BASH_OUTPUT_KEY] !== undefined).map((s) => `${BASH_OUTPUT_KEY} ${JSON.stringify(s.settings[BASH_OUTPUT_KEY])} in ${tilde(s.path)}`);
@@ -476,9 +519,10 @@ export async function applyFix(fix, deps = {}, context = {}) {
476
519
  // The environment Claude Code starts in is the user's too: a value there is theirs (settings.json would override it).
477
520
  // Not a value Claude Code copied from a settings file into the session this runs in, nor fix's own left from before an undo.
478
521
  const env = deps.env ?? process.env;
479
- const shell = fix.id === "subagent-model" && shellSet(SUBAGENT_MODEL_ENV, settingsSources({ home: deps.home, cwd: deps.cwd, env }), env, String(fix.value)) ? env[SUBAGENT_MODEL_ENV] : undefined;
480
- if (shell)
481
- return { ok: false, lines: [`✗ ${fix.id}: ${processEnvWhere(SUBAGENT_MODEL_ENV, shell, env)}, a value you set: left as it is. Nothing was changed.`] };
522
+ const name = SHELL_ENV[fix.id];
523
+ const shell = name && shellSet(name, settingsSources({ home: deps.home, cwd: deps.cwd, env }), env, String(fix.value)) ? env[name] : undefined;
524
+ if (name && shell)
525
+ return { ok: false, lines: [`✗ ${fix.id}: ${processEnvWhere(name, shell, env)}, a value you set: left as it is. Nothing was changed.`] };
482
526
  const lines = applySetting(fix, home, at, { oneHourShareBefore: context.oneHourShare, modelsBefore: context.modelsBefore });
483
527
  const over = fixOverrides(fix.id, deps);
484
528
  if (over.length)
@@ -634,6 +678,41 @@ export async function undoFixes(ids, deps = {}) {
634
678
  }
635
679
  return lines;
636
680
  }
681
+ // -- What each applied fix saved since ------------------------------------------------
682
+ /**
683
+ * Where CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES is set, as Claude Code
684
+ * sees it: the highest settings file whose env names it (managed, local,
685
+ * project, user: each applied over the one before and over the shell), else
686
+ * the shell's own value. A project's or managed value that keeps them is not
687
+ * the user's (fixOverrides names it); the user's own one is never
688
+ * overwritten. `offSince`: when fix turned them off (its record).
689
+ * `forkGateOff`: CLAUDE_CODE_FORK_SUBAGENT off, which in a terminal session
690
+ * also keeps ordinary background subagents from getting summaries.
691
+ */
692
+ export function progressSummariesState(deps = {}) {
693
+ const env = deps.env ?? process.env;
694
+ const sources = settingsSources({ home: deps.home, cwd: deps.cwd, env });
695
+ const fork = effectiveEnv("CLAUDE_CODE_FORK_SUBAGENT", sources, env);
696
+ const forkGateOff = !!fork && ["0", "false", "no", "off"].includes(fork.value.trim().toLowerCase());
697
+ const rec = readFixRecords(deps.home).find((r) => r.id === "progress-summaries");
698
+ const off = (value, where) => ({ set: { value, where }, ...(disablesSummaries(value) && rec ? { offSince: rec.at } : {}), forkGateOff });
699
+ for (const s of sources) {
700
+ const v = s.settings.env?.[PROGRESS_SUMMARIES_ENV];
701
+ if (v === undefined || v === null || String(v).trim() === "")
702
+ continue;
703
+ if (disablesSummaries(v) || s.name === "user")
704
+ return off(String(v), `${tilde(s.path)} env`);
705
+ return { forkGateOff };
706
+ }
707
+ // The shell's value, unless it is fix's own copied into a session started before an undo.
708
+ if (shellSet(PROGRESS_SUMMARIES_ENV, sources, env, PROGRESS_SUMMARIES_OFF))
709
+ return off(env[PROGRESS_SUMMARIES_ENV], underClaudeCode(env) ? "this Claude Code session's environment" : "the environment");
710
+ return { forkGateOff };
711
+ }
712
+ /** The summaries fix's variable stopped since `at`: the background subagents on Claude Code 2.1.318+ since, estimated as if it were not set. */
713
+ export function progressSummariesSavedSince(at, subagentPaths, forkGateOff = false) {
714
+ return estimateProgressSummaries(subagentPaths ?? subagentTranscripts(at), { since: at, minVersion: PROGRESS_SUMMARIES_SINCE, forkGateOff });
715
+ }
637
716
  /**
638
717
  * Compactions since `since` that came before the old window, priced: every
639
718
  * later request in that session re-read less context, until the session
@@ -738,6 +817,10 @@ export function savedSince(records, opts = {}) {
738
817
  const s = toolOutputSavedSince(r.at, typeof r.previous === "number" ? r.previous : BASH_OUTPUT_DEFAULT, paths);
739
818
  out.push({ id: r.id, at: r.at, savedUsd: s.moved ? s.savedUsd : undefined, detail: s.moved ? `estimated: ${s.moved.toLocaleString("en-US")} Bash results moved to a file that were inline before, priced at the requests that would have re-read them; files the model opened again not counted` : "no Bash output over the cap since" });
740
819
  }
820
+ else if (r.id === "progress-summaries") {
821
+ const s = progressSummariesSavedSince(r.at, opts.subagentPaths);
822
+ out.push({ id: r.id, at: r.at, savedUsd: s.summarized ? s.notesUsd : undefined, detail: s.summarized ? `estimated: ${s.calls.toLocaleString("en-US")} summaries it stopped for ${s.summarized} background subagent${s.summarized === 1 ? "" : "s"} on Claude Code ${PROGRESS_SUMMARIES_SINCE}+, as notes (${money(s.forkUsd)} at the whole context)` : "no background subagent in a terminal session since" });
823
+ }
741
824
  else if (r.id === "autopilot") {
742
825
  const ledger = opts.ledger ?? readLedger();
743
826
  const ev = ledger.filter((e) => e.ev === "proxy" && e.ts >= r.at);
@@ -761,6 +844,7 @@ const LABEL = {
761
844
  "subagent-model": "Subagent model",
762
845
  "tool-output": "Long Bash output",
763
846
  "codex-compact": "Codex auto-compact limit",
847
+ "progress-summaries": "Subagent progress summaries",
764
848
  };
765
849
  /**
766
850
  * Priced levers that save part of the same dollars, and why: each is
@@ -776,6 +860,7 @@ const OVERLAPS = [
776
860
  ["tool-output", "cache-ttl-subagents", "the subagents' cache lifetime changes how often their long output is written to the cache again"],
777
861
  ["tool-output", "subagent-model", "long output in subagents is priced at the subagents' model, which subagent-model changes"],
778
862
  ["subagent-model", "cache-ttl-subagents", "the subagents' cache is priced at their model's rates, which subagent-model changes"],
863
+ ["progress-summaries", "subagent-model", "the progress summaries run on the subagents' model, which subagent-model changes"],
779
864
  ];
780
865
  /** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
781
866
  export function overlaps(fixes) {
@@ -48,6 +48,19 @@ export declare function hostName(hostHeader: string): string;
48
48
  export declare function makeGuard(bindHost: string, allowedHosts?: string, allowedOrigins?: string, env?: NodeJS.ProcessEnv, opts?: {
49
49
  ipLiterals?: boolean;
50
50
  }): HttpGuard;
51
+ /**
52
+ * What to say when the --http server listens beyond this machine: it has no
53
+ * sign-in, so anyone who can reach the address can call its tools (and,
54
+ * with --store-handoffs, save handoffs on this machine). On a host or behind
55
+ * a tunnel for ChatGPT that is the point, so it is said, not refused, as the
56
+ * proxy says it. Undefined on a loopback address.
57
+ */
58
+ export declare function exposureWarning(host: string, storeHandoffs?: boolean): string | undefined;
59
+ /**
60
+ * The --port value: a port number, 0 for one the system picks, or the
61
+ * default when absent or not a port (0 used to fall back to 8808).
62
+ */
63
+ export declare function portArg(raw: string | undefined, fallback?: number): number;
51
64
  /** Why this request may not reach /mcp, or undefined when it may. */
52
65
  export declare function refusal(guard: HttpGuard, headers: IncomingMessage["headers"]): string | undefined;
53
66
  /**
package/dist/httpguard.js CHANGED
@@ -54,6 +54,28 @@ export function makeGuard(bindHost, allowedHosts, allowedOrigins, env = process.
54
54
  hosts.add(bind);
55
55
  return { hosts, origins, ipLiterals: opts.ipLiterals };
56
56
  }
57
+ /**
58
+ * What to say when the --http server listens beyond this machine: it has no
59
+ * sign-in, so anyone who can reach the address can call its tools (and,
60
+ * with --store-handoffs, save handoffs on this machine). On a host or behind
61
+ * a tunnel for ChatGPT that is the point, so it is said, not refused, as the
62
+ * proxy says it. Undefined on a loopback address.
63
+ */
64
+ export function exposureWarning(host, storeHandoffs = false) {
65
+ const h = hostName(host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
66
+ if (h === "localhost" || h === "::1" || /^127\.\d+\.\d+\.\d+$/.test(h) || /^::ffff:127\./.test(h))
67
+ return undefined;
68
+ return (`WARNING: listening on ${host}, beyond this machine, with no sign-in: anyone who can reach it can call its tools${storeHandoffs ? " and save handoffs here (--store-handoffs)" : ""}.\n` +
69
+ "Put it behind your tunnel's or reverse proxy's authentication unless only you can reach this address.");
70
+ }
71
+ /**
72
+ * The --port value: a port number, 0 for one the system picks, or the
73
+ * default when absent or not a port (0 used to fall back to 8808).
74
+ */
75
+ export function portArg(raw, fallback = 8808) {
76
+ const n = Number(raw);
77
+ return raw !== undefined && raw.trim() !== "" && Number.isInteger(n) && n >= 0 && n <= 65535 ? n : fallback;
78
+ }
57
79
  /** Why this request may not reach /mcp, or undefined when it may. */
58
80
  export function refusal(guard, headers) {
59
81
  if (guard.hosts !== "*") {
package/dist/install.d.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * `context-doctor uninstall` reverses it.
8
8
  */
9
9
  import { type ClaudeCodeInstall, type ModelSwitchReadiness } from "./modelswitch.js";
10
+ import { type ModReadiness } from "./claudeplugin.js";
10
11
  export declare function geminiSettingsPath(): string;
11
12
  /**
12
13
  * Gemini CLI reads its settings.json through strip-json-comments
@@ -45,15 +46,7 @@ export declare function launcherNamesMissingPackage(entry: {
45
46
  command?: unknown;
46
47
  args?: unknown;
47
48
  } | undefined): boolean;
48
- /**
49
- * The Claude Code plugin's key in enabledPlugins: "<plugin>@<marketplace>".
50
- * Our marketplace (.claude-plugin/marketplace.json) is named context-doctor
51
- * and lists one plugin, context-doctor, so the official key is
52
- * "context-doctor@context-doctor"; a copy listed in another marketplace keeps
53
- * the plugin name, so any "context-doctor@…" key is ours.
54
- */
55
- export declare const PLUGIN_KEY = "context-doctor@context-doctor";
56
- export declare function isOurPluginKey(key: string): boolean;
49
+ export { PLUGIN_KEY, isOurPluginKey } from "./claudeplugin.js";
57
50
  /**
58
51
  * Is the context-doctor plugin switched on in the user's Claude Code
59
52
  * settings? The plugin brings its own MCP server, skills and hooks, so
@@ -63,6 +56,25 @@ export declare function isOurPluginKey(key: string): boolean;
63
56
  export declare function claudePluginEnabled(home?: string): boolean;
64
57
  /** What `install` put into Claude Code that the plugin also provides, by name. */
65
58
  export declare function claudeInstalledCopies(home?: string): string[];
59
+ /**
60
+ * How install serves Claude Code this run (claudeplugin.ts has the why):
61
+ * through the plugin (`ours`: the keys are install's to write and to take
62
+ * out again; otherwise the user enabled it), or with install's own MCP
63
+ * server, skill and hooks: the plugin turned off by the user ("off"), a
64
+ * Claude Code here that predates mods ("old"), or no version found
65
+ * ("unknown"). Settings are shared by every Claude Code on the machine, so
66
+ * one route serves them all.
67
+ */
68
+ export type ClaudeCodeRoute = {
69
+ via: "plugin";
70
+ ours: boolean;
71
+ readiness: ModReadiness;
72
+ } | {
73
+ via: "hooks";
74
+ why: "off" | "old" | "unknown";
75
+ readiness: ModReadiness;
76
+ };
77
+ export declare function claudeCodeRoute(readiness?: ModReadiness): ClaudeCodeRoute;
66
78
  /**
67
79
  * A config that configures nothing: `{}`, or only empty `mcpServers` /
68
80
  * `hooks` containers (plus `extraKeys`, e.g. the `version` install writes
package/dist/install.js CHANGED
@@ -19,6 +19,7 @@ import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
19
19
  import { fallbackStateDir } from "./ledger.js";
20
20
  import { codexDir as codexHomeDir } from "./codexdir.js";
21
21
  import { scanCacheDir } from "./scan.js";
22
+ import { isOurDeclaration, isOurPluginKey, MARKETPLACE, marketplaceDeclaration, marketplaceRegistered, MOD_SINCE, modReadiness, PLUGIN_KEY, pluginMarkerPath, pluginStage, readPluginMarker } from "./claudeplugin.js";
22
23
  import { editJsonText, parseSettingsText, sameJson, withSettingsLock, writeAtomic } from "./settingsedit.js";
23
24
  function claudeDesktopConfigPath() {
24
25
  switch (platform()) {
@@ -118,17 +119,8 @@ export function launcherNamesMissingPackage(entry) {
118
119
  return false;
119
120
  return rest.find((w) => !w.startsWith("-")) === "context-doctor-mcp";
120
121
  }
121
- /**
122
- * The Claude Code plugin's key in enabledPlugins: "<plugin>@<marketplace>".
123
- * Our marketplace (.claude-plugin/marketplace.json) is named context-doctor
124
- * and lists one plugin, context-doctor, so the official key is
125
- * "context-doctor@context-doctor"; a copy listed in another marketplace keeps
126
- * the plugin name, so any "context-doctor@…" key is ours.
127
- */
128
- export const PLUGIN_KEY = "context-doctor@context-doctor";
129
- export function isOurPluginKey(key) {
130
- return key === PLUGIN_KEY || key.startsWith("context-doctor@");
131
- }
122
+ // The plugin's key lives in claudeplugin.ts with the rest of the plugin path.
123
+ export { PLUGIN_KEY, isOurPluginKey } from "./claudeplugin.js";
132
124
  /**
133
125
  * Is the context-doctor plugin switched on in the user's Claude Code
134
126
  * settings? The plugin brings its own MCP server, skills and hooks, so
@@ -162,6 +154,116 @@ export function claudeInstalledCopies(home = homedir()) {
162
154
  found.push("skill in ~/.claude/skills/context-doctor");
163
155
  return found;
164
156
  }
157
+ export function claudeCodeRoute(readiness = modReadiness(claudeCodeInstallsFromEnv())) {
158
+ let enabled = {};
159
+ try {
160
+ const e = readJson(join(claudeDir(), "settings.json")).enabledPlugins;
161
+ if (isPlainObject(e))
162
+ enabled = e;
163
+ }
164
+ catch { /* unreadable: the step that writes it reports that */ }
165
+ const on = Object.entries(enabled).some(([key, v]) => isOurPluginKey(key) && v === true);
166
+ if (on && !readPluginMarker())
167
+ return { via: "plugin", ours: false, readiness };
168
+ // Turned off by hand (install never writes false): the user's call stands.
169
+ if (enabled[PLUGIN_KEY] === false)
170
+ return { via: "hooks", why: "off", readiness };
171
+ if (readiness.ok)
172
+ return { via: "plugin", ours: true, readiness };
173
+ return { via: "hooks", why: readiness.old.length > 0 ? "old" : "unknown", readiness };
174
+ }
175
+ /**
176
+ * Switch the plugin on in ~/.claude/settings.json: this repository as a
177
+ * marketplace and the plugin enabled, each key only if it is not there
178
+ * already, written key by key under the settings lock (so uninstall gives
179
+ * the file back byte for byte), and what was added recorded in the marker.
180
+ * Returns whether the file changed.
181
+ */
182
+ function enablePlugin() {
183
+ const path = join(claudeDir(), "settings.json");
184
+ return settingsUpdate(path, () => {
185
+ const settings = readJson(path);
186
+ for (const key of ["extraKnownMarketplaces", "enabledPlugins"]) {
187
+ if (settings[key] !== undefined && !isPlainObject(settings[key]))
188
+ throw new Error(`"${key}" in ${path} is not an object; fix it, then re-run. Nothing was changed.`);
189
+ }
190
+ const marker = readPluginMarker() ?? { marketplace: false, enabled: false };
191
+ let changed = false;
192
+ // Declared already (either spelling), or a marketplace of that name Claude
193
+ // Code already knows (added with /plugin, perhaps from a local checkout):
194
+ // declaring this repository over it would move it to GitHub.
195
+ const declared = [settings.extraKnownMarketplaces, settings.additionalMarketplaces].some((m) => isPlainObject(m) && m[MARKETPLACE] !== undefined);
196
+ if (!declared && !marketplaceRegistered()) {
197
+ settings.extraKnownMarketplaces = { ...(settings.extraKnownMarketplaces ?? {}), [MARKETPLACE]: marketplaceDeclaration() };
198
+ marker.marketplace = true;
199
+ changed = true;
200
+ }
201
+ if (settings.enabledPlugins?.[PLUGIN_KEY] !== true) {
202
+ settings.enabledPlugins = { ...(settings.enabledPlugins ?? {}), [PLUGIN_KEY]: true };
203
+ marker.enabled = true;
204
+ changed = true;
205
+ }
206
+ if (!changed)
207
+ return false;
208
+ // The record first: from here on a later install's backup step and
209
+ // uninstall see these keys as install's, not the user's.
210
+ writeAtomic(pluginMarkerPath(), JSON.stringify(marker) + "\n");
211
+ writeJsonWithBackup(path, settings);
212
+ return true;
213
+ });
214
+ }
215
+ /**
216
+ * Take out the plugin keys install wrote (each only if it still says what
217
+ * install wrote), then the marker. Returns whether settings.json changed.
218
+ */
219
+ function disablePlugin() {
220
+ const marker = readPluginMarker();
221
+ let changed = false;
222
+ const path = join(claudeDir(), "settings.json");
223
+ if (marker && existsSync(path)) {
224
+ settingsUpdate(path, () => {
225
+ const settings = readJson(path);
226
+ if (dropOurPluginKeys(settings, marker)) {
227
+ writeUninstalled(path, settings);
228
+ changed = true;
229
+ }
230
+ });
231
+ }
232
+ rmSync(pluginMarkerPath(), { force: true });
233
+ return changed;
234
+ }
235
+ /** Install's own Claude Code hooks, by event, with the name each step prints. */
236
+ const CLAUDE_HOOKS = [
237
+ ["UserPromptSubmit", "Claude Code every-prompt hook"],
238
+ ["PreCompact", "Claude Code compaction hook"],
239
+ ["SessionStart", "Claude Code session-start hook"],
240
+ ["PreModelSwitch", "Claude Code model-switch warning"],
241
+ ["PreToolUse", "Claude Code subagent price"],
242
+ ];
243
+ /** Remove our MCP server from one app's config, as uninstall does. */
244
+ function removeMcpEntry(name, configPath) {
245
+ if (!existsSync(configPath))
246
+ return;
247
+ const config = readJson(configPath);
248
+ if (config.mcpServers?.["context-doctor"]) {
249
+ delete config.mcpServers["context-doctor"];
250
+ writeUninstalled(configPath, config);
251
+ done(`✓ ${name}: MCP server removed`);
252
+ }
253
+ }
254
+ /**
255
+ * Install's own Claude Code wiring out (the MCP server in ~/.claude.json,
256
+ * the skill, the hooks), each step on its own, as uninstall takes them out:
257
+ * beside the plugin each would run twice.
258
+ */
259
+ function removeClaudeCodeCopies(attempt) {
260
+ const settings = join(claudeDir(), "settings.json");
261
+ for (const [event, label] of CLAUDE_HOOKS)
262
+ attempt(label, () => uninstallHookFrom(settings, label, event));
263
+ attempt("Claude Code", () => removeMcpEntry("Claude Code", claudeJsonPath()));
264
+ attempt("Agent Skill", () => removeSkill(join(claudeDir(), "skills", "context-doctor"), "Agent Skill"));
265
+ attempt("Claude Code skill folders", () => removeSkillFolders(claudeDir()));
266
+ }
165
267
  /**
166
268
  * A config that configures nothing: `{}`, or only empty `mcpServers` /
167
269
  * `hooks` containers (plus `extraKeys`, e.g. the `version` install writes
@@ -466,11 +568,8 @@ function addHookEntry(settingsPath, event, opts) {
466
568
  /** Each hook removal on its own: a malformed file for one app must not leave the others installed. */
467
569
  function uninstallHook(attempt) {
468
570
  const claude = join(claudeDir(), "settings.json");
469
- attempt("Claude Code every-prompt hook", () => uninstallHookFrom(claude, "Claude Code every-prompt hook"));
470
- attempt("Claude Code compaction hook", () => uninstallHookFrom(claude, "Claude Code compaction hook", "PreCompact"));
471
- attempt("Claude Code session-start hook", () => uninstallHookFrom(claude, "Claude Code session-start hook", "SessionStart"));
472
- attempt("Claude Code model-switch warning", () => uninstallHookFrom(claude, "Claude Code model-switch warning", "PreModelSwitch"));
473
- attempt("Claude Code subagent price", () => uninstallHookFrom(claude, "Claude Code subagent price", "PreToolUse"));
571
+ for (const [event, label] of CLAUDE_HOOKS)
572
+ attempt(label, () => uninstallHookFrom(claude, label, event));
474
573
  attempt("Codex every-prompt hook", () => uninstallHookFrom(join(codexDir(), "hooks.json"), "Codex every-prompt hook"));
475
574
  attempt("Gemini CLI every-prompt hook", () => uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent"));
476
575
  attempt("Cursor hooks", () => uninstallCursorHook());
@@ -1077,6 +1176,49 @@ function uninstallAntigravityFolders() {
1077
1176
  rmSync(dir, { recursive: true });
1078
1177
  rmSync(marker, { force: true });
1079
1178
  }
1179
+ /**
1180
+ * Claude Code's half of install for the route chosen: the plugin switched
1181
+ * on (or found on) and install's own copies taken out, or the plugin keys
1182
+ * install wrote taken out again before its own wiring goes in. Says which,
1183
+ * and what each Claude Code here gets.
1184
+ */
1185
+ function routeClaudeCode(route, attempt) {
1186
+ const settingsPath = join(claudeDir(), "settings.json");
1187
+ if (route.via === "plugin" && !route.ours) {
1188
+ console.log("– Claude Code: skipped the MCP server, skill and hooks. The context-doctor plugin is enabled and");
1189
+ console.log(" provides them already (and, on Claude Code 2.1.286+, its mod); installing them as well would load its instructions and tools twice.");
1190
+ }
1191
+ else if (route.via === "plugin") {
1192
+ const changed = enablePlugin();
1193
+ console.log(changed
1194
+ ? `✓ Claude Code: the context-doctor plugin enabled (${tilde(settingsPath)}: extraKnownMarketplaces, enabledPlugins), in place of install's own MCP server, skill and hooks`
1195
+ : "✓ Claude Code: the context-doctor plugin already enabled, unchanged");
1196
+ console.log(` ${describeInstalls(route.readiness.installs)} ${route.readiness.installs.length === 1 ? "runs" : "run"} its mod: limit readings and Claude Code's own session cost after each turn,`);
1197
+ console.log(" the Compact first button on a cold return, /context-doctor-fix; and the MCP server, skills and hooks install used to add itself.");
1198
+ if (pluginStage().stage !== "installed") {
1199
+ console.log(" Claude Code downloads it in the background at its next start and loads it from the session after (or at once: /reload-plugins).");
1200
+ }
1201
+ }
1202
+ else {
1203
+ if (readPluginMarker()) {
1204
+ if (disablePlugin())
1205
+ console.log("– Claude Code: the context-doctor plugin install had enabled is turned off again (its keys removed from settings.json).");
1206
+ }
1207
+ const why = route.why === "off"
1208
+ ? "the context-doctor plugin is turned off in your settings (enabledPlugins); turn it on in /plugin for its mod, and install leaves Claude Code to it"
1209
+ : route.why === "old"
1210
+ ? `${describeInstalls(route.readiness.old)} predates mods (${MOD_SINCE}), and every Claude Code here reads the same settings; update or remove it, then run install again for the plugin and its mod`
1211
+ : `no Claude Code version found to check (the plugin's mod needs ${MOD_SINCE} or later)`;
1212
+ console.log(`– Claude Code: install's own MCP server, skill and hooks, not the plugin: ${why}.`);
1213
+ return;
1214
+ }
1215
+ // Beside the plugin, install's own copies would run twice: out they go, as uninstall takes them out.
1216
+ const copies = claudeInstalledCopies();
1217
+ if (copies.length > 0) {
1218
+ console.log(` Taking out install's own copies (${copies.join(", ")}), which would load twice beside the plugin:`);
1219
+ removeClaudeCodeCopies(attempt);
1220
+ }
1221
+ }
1080
1222
  /**
1081
1223
  * Install into every detected app.
1082
1224
  *
@@ -1097,19 +1239,23 @@ export function runInstall(options = {}) {
1097
1239
  return { failures: [] };
1098
1240
  }
1099
1241
  const failures = [];
1100
- // The plugin already gives Claude Code the server, skill and hooks; a
1101
- // second copy of each makes every session load the instructions and the
1102
- // tools twice. Claude Code is skipped; the other apps are not.
1103
- const viaPlugin = claudePluginEnabled();
1104
- if (viaPlugin) {
1105
- console.log("– Claude Code: skipped the MCP server, skill and hooks. The context-doctor plugin is enabled and");
1106
- console.log(" provides them already; installing them as well would load its instructions and tools twice.");
1107
- const copies = claudeInstalledCopies();
1108
- if (copies.length > 0) {
1109
- console.log(` An earlier install is still in place (${copies.join(", ")}): \`${selfCommand("uninstall")}\``);
1110
- console.log(` removes it, then \`${selfCommand("install")}\` wires the other apps again.`);
1242
+ const attempt = (label, fn) => {
1243
+ try {
1244
+ fn();
1111
1245
  }
1112
- }
1246
+ catch (e) {
1247
+ console.error(`✗ ${label}: ${e.message}`);
1248
+ failures.push(label);
1249
+ }
1250
+ };
1251
+ // Claude Code through the plugin (claudeplugin.ts) when it runs mods, or
1252
+ // with install's own MCP server, skill and hooks. Never both: a second
1253
+ // copy of each makes every session load the instructions and the tools
1254
+ // twice. The other apps are wired either way.
1255
+ const route = claudeCodePresent() ? claudeCodeRoute() : undefined;
1256
+ const viaPlugin = route?.via === "plugin";
1257
+ if (route)
1258
+ attempt("Claude Code plugin", () => routeClaudeCode(route, attempt));
1113
1259
  for (const target of found) {
1114
1260
  if (viaPlugin && target.name === "Claude Code")
1115
1261
  continue;
@@ -1348,8 +1494,29 @@ function withoutOurs(config) {
1348
1494
  }
1349
1495
  if (typeof c.statusLine?.command === "string" && isOurStatusLine(c.statusLine.command))
1350
1496
  delete c.statusLine;
1497
+ // The plugin keys count as ours only where install wrote them (its marker
1498
+ // says so): an enabledPlugins entry the user made is theirs.
1499
+ const marker = readPluginMarker();
1500
+ if (marker)
1501
+ dropOurPluginKeys(c, marker);
1351
1502
  return c;
1352
1503
  }
1504
+ /**
1505
+ * Take the plugin keys install wrote out of a settings object, each only if
1506
+ * it still says what install wrote. Returns whether anything went.
1507
+ */
1508
+ function dropOurPluginKeys(c, marker) {
1509
+ let dropped = false;
1510
+ if (marker.enabled && isPlainObject(c.enabledPlugins) && c.enabledPlugins[PLUGIN_KEY] === true) {
1511
+ delete c.enabledPlugins[PLUGIN_KEY];
1512
+ dropped = true;
1513
+ }
1514
+ if (marker.marketplace && isPlainObject(c.extraKnownMarketplaces) && isOurDeclaration(c.extraKnownMarketplaces[MARKETPLACE])) {
1515
+ delete c.extraKnownMarketplaces[MARKETPLACE];
1516
+ dropped = true;
1517
+ }
1518
+ return dropped;
1519
+ }
1353
1520
  /**
1354
1521
  * The file as it was before install, as far as its backup can tell:
1355
1522
  * `created` when install made the file (no backup was needed), or when the
@@ -1384,7 +1551,8 @@ function installOrigin(path, extraKeys) {
1384
1551
  */
1385
1552
  function writeUninstalled(path, config, extraKeys = []) {
1386
1553
  const { created, before, empty } = installOrigin(path, extraKeys);
1387
- for (const key of ["mcpServers", "hooks"]) {
1554
+ // The plugin's containers too (settings.json): install made them when the file had none.
1555
+ for (const key of ["mcpServers", "hooks", "enabledPlugins", "extraKnownMarketplaces"]) {
1388
1556
  const v = config[key];
1389
1557
  if (v && typeof v === "object" && Object.keys(v).length === 0 && !(key in before))
1390
1558
  delete config[key];
@@ -1457,6 +1625,7 @@ const OUR_CLAUDE_FILES = [
1457
1625
  ".context-doctor-proxy.log",
1458
1626
  ".context-doctor-proxy-restart",
1459
1627
  ".context-doctor-limits.jsonl",
1628
+ ".context-doctor-session-cost.jsonl",
1460
1629
  ".context-doctor-misses.jsonl",
1461
1630
  ".context-doctor-subagent-costs.json",
1462
1631
  ".context-doctor-budget.json",
@@ -1500,17 +1669,19 @@ export async function runUninstall() {
1500
1669
  console.error(`✗ autopilot: ${e.message}`);
1501
1670
  }
1502
1671
  for (const target of targets().filter((t) => t.detect())) {
1503
- attempt(target.name, () => {
1504
- if (!existsSync(target.configPath))
1505
- return;
1506
- const config = readJson(target.configPath);
1507
- if (config.mcpServers?.["context-doctor"]) {
1508
- delete config.mcpServers["context-doctor"];
1509
- writeUninstalled(target.configPath, config);
1510
- done(`✓ ${target.name}: MCP server removed`);
1511
- }
1512
- });
1513
- }
1672
+ attempt(target.name, () => removeMcpEntry(target.name, target.configPath));
1673
+ }
1674
+ // The plugin keys install wrote; a plugin the user enabled stays theirs.
1675
+ attempt("Claude Code plugin", () => {
1676
+ if (disablePlugin()) {
1677
+ done("✓ Claude Code: the context-doctor plugin turned off (the keys install added to ~/.claude/settings.json removed)");
1678
+ if (pluginStage().stage !== "none")
1679
+ console.log(" Claude Code keeps its downloaded copy, disabled, under ~/.claude/plugins; `claude plugin uninstall context-doctor@context-doctor` deletes it.");
1680
+ }
1681
+ else if (claudePluginEnabled()) {
1682
+ console.log("– Claude Code: the context-doctor plugin stays enabled: you turned it on, not install (turn it off in /plugin).");
1683
+ }
1684
+ });
1514
1685
  attempt("Agent Skill", () => removeSkill(join(claudeDir(), "skills", "context-doctor"), "Agent Skill"));
1515
1686
  for (const dir of antigravityAllSkillDirs())
1516
1687
  attempt(`Antigravity skill (${tilde(dir)})`, () => removeSkill(dir, "Antigravity skill"));