context-doctor 0.46.0 → 0.48.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 (68) hide show
  1. package/README.md +9 -4
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +71 -28
  4. package/dist/abclaude.d.ts +167 -0
  5. package/dist/abclaude.js +511 -0
  6. package/dist/abstore.d.ts +46 -0
  7. package/dist/abstore.js +58 -0
  8. package/dist/autopilot.js +9 -5
  9. package/dist/blob.js +66 -12
  10. package/dist/budget.d.ts +8 -2
  11. package/dist/budget.js +30 -7
  12. package/dist/ci.js +2 -1
  13. package/dist/claudeplugin.d.ts +97 -0
  14. package/dist/claudeplugin.js +142 -0
  15. package/dist/cli.js +128 -36
  16. package/dist/compactcost.d.ts +74 -0
  17. package/dist/compactcost.js +115 -0
  18. package/dist/cursor.js +2 -0
  19. package/dist/doctor.js +90 -18
  20. package/dist/extract.js +4 -3
  21. package/dist/fanout.d.ts +15 -0
  22. package/dist/fanout.js +30 -9
  23. package/dist/firstfix.d.ts +43 -0
  24. package/dist/firstfix.js +80 -0
  25. package/dist/fix.d.ts +53 -4
  26. package/dist/fix.js +101 -13
  27. package/dist/httpguard.d.ts +13 -0
  28. package/dist/httpguard.js +22 -0
  29. package/dist/install.d.ts +21 -9
  30. package/dist/install.js +213 -40
  31. package/dist/limits.d.ts +5 -0
  32. package/dist/limits.js +26 -2
  33. package/dist/mcp.d.ts +4 -0
  34. package/dist/mcp.js +142 -97
  35. package/dist/mcpclient.js +73 -42
  36. package/dist/missledger.js +5 -3
  37. package/dist/mod/api.d.ts +8 -2
  38. package/dist/mod/api.js +2 -2
  39. package/dist/mod/logic.d.ts +13 -1
  40. package/dist/mod/logic.js +24 -2
  41. package/dist/mod/register.d.ts +2 -0
  42. package/dist/mod/register.js +19 -5
  43. package/dist/modelids.d.ts +62 -3
  44. package/dist/modelids.js +156 -8
  45. package/dist/modelswitch.js +8 -4
  46. package/dist/modmeasure.js +13 -1
  47. package/dist/orgrates.d.ts +18 -0
  48. package/dist/orgrates.js +51 -2
  49. package/dist/pack.d.ts +13 -0
  50. package/dist/pack.js +38 -2
  51. package/dist/preferences.js +2 -1
  52. package/dist/pricing.d.ts +8 -0
  53. package/dist/pricing.js +30 -2
  54. package/dist/progresssummaries.d.ts +148 -0
  55. package/dist/progresssummaries.js +248 -0
  56. package/dist/proxy.d.ts +1 -1
  57. package/dist/proxy.js +1 -1
  58. package/dist/prune.d.ts +8 -0
  59. package/dist/prune.js +11 -1
  60. package/dist/spend.d.ts +34 -0
  61. package/dist/spend.js +48 -4
  62. package/dist/subagentmodel.d.ts +12 -0
  63. package/dist/subagentmodel.js +17 -4
  64. package/dist/subagentpay.d.ts +8 -0
  65. package/dist/subagentpay.js +8 -1
  66. package/dist/toolcwd.d.ts +14 -0
  67. package/dist/toolcwd.js +17 -0
  68. package/package.json +6 -3
package/dist/autopilot.js CHANGED
@@ -19,6 +19,7 @@
19
19
  * backend, not an API base URL).
20
20
  */
21
21
  import { execFileSync, spawn } from "node:child_process";
22
+ import { toolCwd } from "./toolcwd.js";
22
23
  import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
23
24
  import { homedir, platform } from "node:os";
24
25
  import { dirname, join } from "node:path";
@@ -106,7 +107,7 @@ function uid() {
106
107
  return String(process.getuid?.() ?? "");
107
108
  }
108
109
  function run(cmd, args) {
109
- execFileSync(cmd, args, { stdio: "ignore" });
110
+ execFileSync(cmd, args, { cwd: toolCwd(), stdio: "ignore" });
110
111
  }
111
112
  function tryRun(cmd, args) {
112
113
  try {
@@ -262,7 +263,10 @@ export function restartService(home = homedir(), exec = tryRun) {
262
263
  export function startDetached(args, log) {
263
264
  mkdirSync(dirname(log), { recursive: true });
264
265
  const out = openSync(log, "a");
265
- const child = spawn(args[0], args.slice(1), { detached: true, stdio: ["ignore", out, out], windowsHide: true });
266
+ // Not the caller's folder: the every-prompt hook restarts the proxy from
267
+ // the project it runs in, and on Windows a process standing in a folder
268
+ // keeps it from being renamed or deleted for as long as the proxy lives.
269
+ const child = spawn(args[0], args.slice(1), { cwd: toolCwd(), detached: true, stdio: ["ignore", out, out], windowsHide: true });
266
270
  child.unref();
267
271
  }
268
272
  export async function health(port, timeoutMs = 800) {
@@ -324,20 +328,20 @@ async function canBind(port) {
324
328
  function listenerProcess(port) {
325
329
  try {
326
330
  if (platform() === "win32") {
327
- const net = execFileSync("netstat", ["-ano", "-p", "TCP"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
331
+ const net = execFileSync("netstat", ["-ano", "-p", "TCP"], { cwd: toolCwd(), encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
328
332
  const line = net.split(/\r?\n/).find((l) => new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+\\d+`, "i").test(l));
329
333
  const pid = Number(/LISTENING\s+(\d+)/i.exec(line ?? "")?.[1]);
330
334
  if (!(pid > 0))
331
335
  return {};
332
336
  let command;
333
337
  try {
334
- const task = execFileSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
338
+ const task = execFileSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { cwd: toolCwd(), encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
335
339
  command = /^"([^"]+)"/.exec(task.trim())?.[1];
336
340
  }
337
341
  catch { /* the pid alone */ }
338
342
  return { pid, command };
339
343
  }
340
- const out = execFileSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
344
+ const out = execFileSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], { cwd: toolCwd(), encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
341
345
  const pid = Number(/^p(\d+)/m.exec(out)?.[1]);
342
346
  return { pid: pid > 0 ? pid : undefined, command: /^c(.+)$/m.exec(out)?.[1] };
343
347
  }
package/dist/blob.js CHANGED
@@ -9,7 +9,9 @@
9
9
  * character dominating.
10
10
  */
11
11
  /** Runs of base64 alphabet long enough to be worth reporting (~375 bytes+). */
12
- const BASE64_RE = /(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g;
12
+ const MIN_RUN = 500;
13
+ /** The data: URI header a run may follow (the candidate then starts at "data:"). */
14
+ const DATA_URI_HEAD = /data:[\w/+.-]+;base64,$/;
13
15
  export const BASE64_PLACEHOLDER = "[context-doctor: base64 blob removed — use file/image APIs instead]";
14
16
  /** Distinct characters a genuine base64 payload is expected to span. */
15
17
  const MIN_DISTINCT_CHARS = 24;
@@ -19,26 +21,78 @@ function isBase64Blob(candidate) {
19
21
  // An explicit data: URI declares its own encoding — no need to guess.
20
22
  if (candidate.startsWith("data:"))
21
23
  return true;
22
- const counts = new Map();
23
- for (const ch of candidate)
24
- counts.set(ch, (counts.get(ch) ?? 0) + 1);
25
- if (counts.size < MIN_DISTINCT_CHARS)
26
- return false;
24
+ // A candidate is ASCII (the alphabet and "="): a count per character code.
25
+ const counts = new Uint32Array(128);
26
+ let distinct = 0;
27
27
  let max = 0;
28
- for (const n of counts.values())
29
- if (n > max)
30
- max = n;
28
+ for (let k = 0; k < candidate.length; k++) {
29
+ const c = candidate.charCodeAt(k) & 127;
30
+ if (counts[c]++ === 0)
31
+ distinct++;
32
+ if (counts[c] > max)
33
+ max = counts[c];
34
+ }
35
+ if (distinct < MIN_DISTINCT_CHARS)
36
+ return false;
31
37
  return max / candidate.length < MAX_SINGLE_CHAR_SHARE;
32
38
  }
39
+ /** A-Z, a-z, 0-9, + and /. */
40
+ function inAlphabet(c) {
41
+ return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 43 || c === 47;
42
+ }
43
+ /**
44
+ * The candidates, as [start, end) spans: what
45
+ * /(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g matched, found by
46
+ * a scan. That expression threw "Maximum call stack size exceeded" on a run
47
+ * past about 5.5 million characters (a 4 MB image or PDF pasted as base64),
48
+ * which ended analyze, profile_context and optimize at the very blob they
49
+ * exist to find.
50
+ */
51
+ function* candidates(text) {
52
+ const n = text.length;
53
+ let i = 0;
54
+ // Where the last candidate ended: a header cannot reuse its characters ("…xYdata" ends one).
55
+ let last = 0;
56
+ while (i < n) {
57
+ if (!inAlphabet(text.charCodeAt(i))) {
58
+ i++;
59
+ continue;
60
+ }
61
+ let j = i;
62
+ while (j < n && inAlphabet(text.charCodeAt(j)))
63
+ j++;
64
+ if (j - i < MIN_RUN) {
65
+ i = j;
66
+ continue;
67
+ }
68
+ let end = j;
69
+ while (end < n && end - j < 2 && text.charCodeAt(end) === 61)
70
+ end++; // up to two "=" of padding
71
+ const head = DATA_URI_HEAD.exec(text.slice(Math.max(last, i - 1000), i));
72
+ yield [head ? i - head[0].length : i, end];
73
+ i = last = end;
74
+ }
75
+ }
33
76
  /** True when the text carries at least one inline base64 blob. */
34
77
  export function hasBase64Blob(text) {
35
- for (const m of text.matchAll(BASE64_RE)) {
36
- if (isBase64Blob(m[0]))
78
+ for (const [s, e] of candidates(text)) {
79
+ if (isBase64Blob(text.slice(s, e)))
37
80
  return true;
38
81
  }
39
82
  return false;
40
83
  }
41
84
  /** Replace real base64 blobs with a placeholder, leaving lookalikes intact. */
42
85
  export function stripBase64Blobs(text) {
43
- return text.replace(BASE64_RE, (m) => (isBase64Blob(m) ? BASE64_PLACEHOLDER : m));
86
+ const parts = [];
87
+ let from = 0;
88
+ for (const [s, e] of candidates(text)) {
89
+ if (!isBase64Blob(text.slice(s, e)))
90
+ continue;
91
+ parts.push(text.slice(from, s), BASE64_PLACEHOLDER);
92
+ from = e;
93
+ }
94
+ if (parts.length === 0)
95
+ return text;
96
+ parts.push(text.slice(from));
97
+ return parts.join("");
44
98
  }
package/dist/budget.d.ts CHANGED
@@ -23,6 +23,7 @@
23
23
  * replies count once. Measured on the author's history: docs/spend.md.
24
24
  */
25
25
  import { type Tool } from "./spend.js";
26
+ import { type CompactTrack } from "./compactcost.js";
26
27
  export type Period = "day" | "week";
27
28
  export interface Budget {
28
29
  usd: number;
@@ -73,8 +74,12 @@ export declare function periodEnd(period: Period, now?: number): number;
73
74
  * way; `z` those priced past the day their model's price changed (index,
74
75
  * model, the day). `d` is requestCost's: each request's tier, fast mode,
75
76
  * US-only and web searches, and the output price in `r` is its own. `p`
76
- * fingerprints the organization's rates `d` was priced at (orgrates.ts;
77
- * absent at list prices): an entry priced under other rates is read again.
77
+ * fingerprints the price table `d` was priced by (pricing.ts priceTableKey)
78
+ * and the organization's rates (orgrates.ts), when set: an entry priced
79
+ * under another table or other rates is read again. `c` is where reading a
80
+ * Claude Code transcript's compactions stopped (compactcost.ts): each
81
+ * compaction's own request is in `k`/`d` too, estimated, keyed by its
82
+ * boundary's uuid.
78
83
  */
79
84
  export interface FileEntry {
80
85
  t: Tool;
@@ -90,6 +95,7 @@ export interface FileEntry {
90
95
  y?: Array<[number, string]>;
91
96
  z?: Array<[number, string, string]>;
92
97
  p?: string;
98
+ c?: CompactTrack;
93
99
  }
94
100
  /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
95
101
  export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
package/dist/budget.js CHANGED
@@ -32,10 +32,11 @@ import { claudeCodePresent, claudeDir } from "./claudedir.js";
32
32
  import { claudeFileUsage, codexSessionsRoot, rolloutFiles, SUBAGENT_LOOKBACK_MS, USAGE_ROWS } from "./limits.js";
33
33
  import { subagentFiles } from "./subagents.js";
34
34
  import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
35
- import { isUnbilledModel, priceChangedText, requestCost } from "./pricing.js";
35
+ import { isUnbilledModel, priceChangedText, priceTableKey, requestCost } from "./pricing.js";
36
36
  import { orgRates, orgRatesLine } from "./orgrates.js";
37
37
  import { anchorOf, rowsOf } from "./scan.js";
38
38
  import { realModel } from "./tokens.js";
39
+ import { isCompactionRow, isTrack, newTrack, trackCompaction } from "./compactcost.js";
39
40
  /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
40
41
  export function budgetPath() {
41
42
  return join(dirname(statePath()), ".context-doctor-budget.json");
@@ -177,6 +178,8 @@ export function periodEnd(period, now = Date.now()) {
177
178
  s.setDate(s.getDate() + (period === "week" ? 7 : 1));
178
179
  return s.getTime();
179
180
  }
181
+ /** What a ledger entry counts: 2, each Claude Code compaction's own request too (compactcost.ts). An entry counted otherwise is read again. */
182
+ const COUNTED = 2;
180
183
  /** Replies remembered per transcript, to tell a later row of one from a new reply. */
181
184
  const RECENT_REPLIES = 64;
182
185
  function readState() {
@@ -337,7 +340,10 @@ function readFile(tool, file, since, size) {
337
340
  // appended after this read, must still be known as its own (they were
338
341
  // counted again as a new request).
339
342
  const last = new Map();
343
+ // Where the compactions stand at the end (claudeFileUsage counted those before it): an append goes on from here.
344
+ const track = newTrack();
340
345
  for (const row of rowsOf(file, USAGE_ROWS)) {
346
+ trackCompaction(track, row);
341
347
  const m = row?.message;
342
348
  if (row?.type !== "assistant" || typeof m?.id !== "string")
343
349
  continue;
@@ -356,7 +362,7 @@ function readFile(tool, file, since, size) {
356
362
  const fd = openSync(file, "r");
357
363
  try {
358
364
  const o = lineStart(fd, size);
359
- return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...flags() };
365
+ return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), c: track, ...flags() };
360
366
  }
361
367
  finally {
362
368
  closeSync(fd);
@@ -419,7 +425,8 @@ function countLines(e, recent, text, since, own) {
419
425
  // Only the last replies matter (a reply's rows are written together): a whole transcript read at once stays linear.
420
426
  if (recent.length > 2 * RECENT_REPLIES)
421
427
  recent.splice(0, recent.length - RECENT_REPLIES);
422
- if (!line.includes('"usage"'))
428
+ const compaction = isCompactionRow(line);
429
+ if (!compaction && !line.includes('"usage"'))
423
430
  continue;
424
431
  let row;
425
432
  try {
@@ -428,6 +435,19 @@ function countLines(e, recent, text, since, own) {
428
435
  catch {
429
436
  continue;
430
437
  }
438
+ // A compaction's own request, estimated (compactcost.ts), as claudeFileUsage counts it.
439
+ if (!isTrack(e.c))
440
+ e.c = newTrack();
441
+ const done = trackCompaction(e.c, row);
442
+ if (done && (Number.isFinite(done.ts) ? done.ts >= since : since <= 0) && !(own !== undefined && done.sessionId !== undefined && done.sessionId !== own)) {
443
+ const index = e.k.length;
444
+ if (done.cost.changedOn)
445
+ (e.z ??= []).push([index, done.model, done.cost.changedOn]);
446
+ else if (done.cost.estimated)
447
+ (e.y ??= []).push([index, done.model]);
448
+ e.k.push(keyOf(done.uuid));
449
+ e.d.push(done.cost.totalUsd);
450
+ }
431
451
  const m = row?.message;
432
452
  if (row?.type !== "assistant" || !m?.usage)
433
453
  continue;
@@ -495,9 +515,12 @@ export function refreshEntry(tool, file, prev, since, direct = false, own) {
495
515
  catch {
496
516
  return undefined;
497
517
  }
498
- // An entry not in the shape this version writes (edited, or another version's), or priced at other rates, is read again.
518
+ // An entry not in the shape this version writes (edited, or another version's), or priced at other
519
+ // rates (the organization's, or another price table: an upgrade that corrected a price), or counted
520
+ // otherwise (COUNTED: 2 adds each compaction's own request), is read again.
499
521
  const org = orgRates()?.key;
500
- const e = wellFormed(prev) && prev.p === org ? prev : undefined;
522
+ const p = `${COUNTED}.${priceTableKey()}${org ? ` ${org}` : ""}`;
523
+ const e = wellFormed(prev) && prev.p === p ? prev : undefined;
501
524
  if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino)
502
525
  return { e, read: -1 };
503
526
  try {
@@ -517,11 +540,11 @@ export function refreshEntry(tool, file, prev, since, direct = false, own) {
517
540
  finally {
518
541
  closeSync(fd);
519
542
  }
520
- const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [], ...(org ? { p: org } : {}) };
543
+ const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [], p };
521
544
  if (readAppended(blank, file, since, own))
522
545
  return { e: { ...blank, s: s.size, m: s.mtimeMs }, read: s.size };
523
546
  }
524
- return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size), ...(org ? { p: org } : {}) }, read: s.size };
547
+ return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size), p }, read: s.size };
525
548
  }
526
549
  catch {
527
550
  return undefined;
package/dist/ci.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * Base contents come from `git show <base>:<path>`; nothing is checked out.
11
11
  */
12
12
  import { execFileSync } from "node:child_process";
13
+ import { toolCwd } from "./toolcwd.js";
13
14
  import { readFileSync, statSync } from "node:fs";
14
15
  import { join, posix } from "node:path";
15
16
  import { estimateTokens, formatTokens } from "./tokens.js";
@@ -27,7 +28,7 @@ const MEMORY_PATTERNS = [
27
28
  ];
28
29
  function git(args, cwd) {
29
30
  try {
30
- return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
31
+ return execFileSync("git", ["-C", cwd, ...args], { cwd: toolCwd(), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
31
32
  }
32
33
  catch {
33
34
  return undefined;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * The Claude Code plugin as `install`'s way into Claude Code (E1).
3
+ *
4
+ * The plugin carries everything install used to wire into Claude Code by
5
+ * hand (the MCP server, the skills, the every-prompt, compaction,
6
+ * session-start, subagent-price and model-switch hooks) plus the one thing
7
+ * install could not: the mod (limits readings and Claude Code's own session
8
+ * cost after each turn, the cold-return Compact first button,
9
+ * /context-doctor-fix). Claude Code runs mods from 2.1.286 (Desktop app),
10
+ * 2.1.287 (terminal) and 2.1.299 (VS Code).
11
+ *
12
+ * How it is switched on, verified on 2.1.321 (the Desktop app's) and 2.1.311
13
+ * (Homebrew) in a throwaway HOME: two keys in ~/.claude/settings.json,
14
+ * `extraKnownMarketplaces.context-doctor` (this repository on GitHub) and
15
+ * `enabledPlugins["context-doctor@context-doctor"]: true`. Claude Code never
16
+ * rewrites the file for them. At its next start it clones the marketplace in
17
+ * the background (known_marketplaces.json, plugins/marketplaces/), then
18
+ * downloads the enabled plugin (installed_plugins.json, plugins/cache/), and
19
+ * loads it from the next session start (or /reload-plugins); a `-p` run with
20
+ * CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1 loads it in the first session. The code
21
+ * reconciling declared marketplaces is the binary's "[reconcile]" step; the
22
+ * docs: code.claude.com/docs/en/plugins/loading ("Plugins and marketplaces
23
+ * that aren't on disk at session start"). With both keys taken out again,
24
+ * `claude plugin list` shows the downloaded copy "disabled" and no session
25
+ * loads it. `claude plugin install` does not read the declaration (it
26
+ * answers "not found in marketplace" until `marketplace add`, which
27
+ * re-serialises settings.json), so the CLI is not the way.
28
+ *
29
+ * Settings are one file for every Claude Code on the machine, so the plugin
30
+ * replaces install's own wiring only when every Claude Code found runs mods;
31
+ * with an older one present (or none found) install keeps its own wiring for
32
+ * all of them, as it does for the model-switch hook.
33
+ */
34
+ import { type ClaudeCodeInstall } from "./modelswitch.js";
35
+ /** The first Claude Code that runs a plugin's mod (the Desktop app's Code tab; the terminal from 2.1.287). */
36
+ export declare const MOD_SINCE = "2.1.286";
37
+ /** Our marketplace's name (.claude-plugin/marketplace.json) and where it lives. */
38
+ export declare const MARKETPLACE = "context-doctor";
39
+ export declare const MARKETPLACE_REPO = "KushalP1/context-doctor";
40
+ /**
41
+ * The key Claude Code enables our plugin under: "<plugin>@<marketplace>".
42
+ * A copy listed in another marketplace keeps the plugin name, so any
43
+ * "context-doctor@…" key is ours.
44
+ */
45
+ export declare const PLUGIN_KEY = "context-doctor@context-doctor";
46
+ export declare function isOurPluginKey(key: string): boolean;
47
+ /**
48
+ * The declaration install writes. autoUpdate: Claude Code refreshes it and
49
+ * updates the plugin in the background after startup when plugin.json's
50
+ * version changes (each release), as the npx-launched MCP server follows
51
+ * npm; a third-party marketplace is off by default.
52
+ */
53
+ export declare function marketplaceDeclaration(): {
54
+ source: {
55
+ source: "github";
56
+ repo: string;
57
+ };
58
+ autoUpdate: boolean;
59
+ };
60
+ /** Is this extraKnownMarketplaces entry ours: this repository on GitHub, however Claude Code has touched it since? */
61
+ export declare function isOurDeclaration(entry: unknown): boolean;
62
+ export interface ModReadiness {
63
+ /** Every Claude Code found runs mods: the plugin can stand in for install's own wiring. */
64
+ ok: boolean;
65
+ /** The ones that predate MOD_SINCE. */
66
+ old: ClaudeCodeInstall[];
67
+ installs: ClaudeCodeInstall[];
68
+ }
69
+ export declare function modReadiness(installs: ClaudeCodeInstall[]): ModReadiness;
70
+ /** What install added to settings.json for the plugin, so uninstall takes out only that. */
71
+ export interface PluginMarker {
72
+ /** install wrote extraKnownMarketplaces.context-doctor. */
73
+ marketplace: boolean;
74
+ /** install wrote enabledPlugins["context-doctor@context-doctor"]: true. */
75
+ enabled: boolean;
76
+ }
77
+ export declare function pluginMarkerPath(): string;
78
+ export declare function readPluginMarker(): PluginMarker | undefined;
79
+ /** Claude Code's plugins folder: CLAUDE_CODE_PLUGIN_CACHE_DIR, else ~/.claude/plugins. */
80
+ export declare function claudePluginsRoot(env?: NodeJS.ProcessEnv): string;
81
+ /** Is a marketplace named context-doctor registered with Claude Code (from any source)? */
82
+ export declare function marketplaceRegistered(): boolean;
83
+ /**
84
+ * How far Claude Code has got with the plugin: "installed" (downloaded, at
85
+ * `version`), "registered" (marketplace fetched, plugin not yet), or "none".
86
+ */
87
+ export declare function pluginStage(): {
88
+ stage: "installed" | "registered" | "none";
89
+ version?: string;
90
+ };
91
+ /** When the mod last wrote each ledger (ms since epoch), from the files' modification times. */
92
+ export declare function modActivity(): {
93
+ cost?: number;
94
+ limits?: number;
95
+ };
96
+ /** "3 h ago", "2 days ago". */
97
+ export declare function ago(ms: number, now?: number): string;
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The Claude Code plugin as `install`'s way into Claude Code (E1).
3
+ *
4
+ * The plugin carries everything install used to wire into Claude Code by
5
+ * hand (the MCP server, the skills, the every-prompt, compaction,
6
+ * session-start, subagent-price and model-switch hooks) plus the one thing
7
+ * install could not: the mod (limits readings and Claude Code's own session
8
+ * cost after each turn, the cold-return Compact first button,
9
+ * /context-doctor-fix). Claude Code runs mods from 2.1.286 (Desktop app),
10
+ * 2.1.287 (terminal) and 2.1.299 (VS Code).
11
+ *
12
+ * How it is switched on, verified on 2.1.321 (the Desktop app's) and 2.1.311
13
+ * (Homebrew) in a throwaway HOME: two keys in ~/.claude/settings.json,
14
+ * `extraKnownMarketplaces.context-doctor` (this repository on GitHub) and
15
+ * `enabledPlugins["context-doctor@context-doctor"]: true`. Claude Code never
16
+ * rewrites the file for them. At its next start it clones the marketplace in
17
+ * the background (known_marketplaces.json, plugins/marketplaces/), then
18
+ * downloads the enabled plugin (installed_plugins.json, plugins/cache/), and
19
+ * loads it from the next session start (or /reload-plugins); a `-p` run with
20
+ * CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1 loads it in the first session. The code
21
+ * reconciling declared marketplaces is the binary's "[reconcile]" step; the
22
+ * docs: code.claude.com/docs/en/plugins/loading ("Plugins and marketplaces
23
+ * that aren't on disk at session start"). With both keys taken out again,
24
+ * `claude plugin list` shows the downloaded copy "disabled" and no session
25
+ * loads it. `claude plugin install` does not read the declaration (it
26
+ * answers "not found in marketplace" until `marketplace add`, which
27
+ * re-serialises settings.json), so the CLI is not the way.
28
+ *
29
+ * Settings are one file for every Claude Code on the machine, so the plugin
30
+ * replaces install's own wiring only when every Claude Code found runs mods;
31
+ * with an older one present (or none found) install keeps its own wiring for
32
+ * all of them, as it does for the model-switch hook.
33
+ */
34
+ import { existsSync, readFileSync, statSync } from "node:fs";
35
+ import { dirname, join } from "node:path";
36
+ import { claudeDir } from "./claudedir.js";
37
+ import { compareVersions } from "./modelswitch.js";
38
+ import { statePath } from "./ledger.js";
39
+ /** The first Claude Code that runs a plugin's mod (the Desktop app's Code tab; the terminal from 2.1.287). */
40
+ export const MOD_SINCE = "2.1.286";
41
+ /** Our marketplace's name (.claude-plugin/marketplace.json) and where it lives. */
42
+ export const MARKETPLACE = "context-doctor";
43
+ export const MARKETPLACE_REPO = "KushalP1/context-doctor";
44
+ /**
45
+ * The key Claude Code enables our plugin under: "<plugin>@<marketplace>".
46
+ * A copy listed in another marketplace keeps the plugin name, so any
47
+ * "context-doctor@…" key is ours.
48
+ */
49
+ export const PLUGIN_KEY = `context-doctor@${MARKETPLACE}`;
50
+ export function isOurPluginKey(key) {
51
+ return key === PLUGIN_KEY || key.startsWith("context-doctor@");
52
+ }
53
+ /**
54
+ * The declaration install writes. autoUpdate: Claude Code refreshes it and
55
+ * updates the plugin in the background after startup when plugin.json's
56
+ * version changes (each release), as the npx-launched MCP server follows
57
+ * npm; a third-party marketplace is off by default.
58
+ */
59
+ export function marketplaceDeclaration() {
60
+ return { source: { source: "github", repo: MARKETPLACE_REPO }, autoUpdate: true };
61
+ }
62
+ /** Is this extraKnownMarketplaces entry ours: this repository on GitHub, however Claude Code has touched it since? */
63
+ export function isOurDeclaration(entry) {
64
+ const src = entry?.source;
65
+ return src?.source === "github" && typeof src.repo === "string" && src.repo.toLowerCase() === MARKETPLACE_REPO.toLowerCase();
66
+ }
67
+ export function modReadiness(installs) {
68
+ const old = installs.filter((i) => compareVersions(i.version, MOD_SINCE) < 0);
69
+ return { ok: installs.length > 0 && old.length === 0, old, installs };
70
+ }
71
+ export function pluginMarkerPath() {
72
+ return join(claudeDir(), ".context-doctor-plugin.json");
73
+ }
74
+ export function readPluginMarker() {
75
+ try {
76
+ const raw = JSON.parse(readFileSync(pluginMarkerPath(), "utf8"));
77
+ if (!raw || typeof raw !== "object")
78
+ return undefined;
79
+ const m = { marketplace: raw.marketplace === true, enabled: raw.enabled === true };
80
+ return m.marketplace || m.enabled ? m : undefined;
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ }
86
+ /** Claude Code's plugins folder: CLAUDE_CODE_PLUGIN_CACHE_DIR, else ~/.claude/plugins. */
87
+ export function claudePluginsRoot(env = process.env) {
88
+ return env.CLAUDE_CODE_PLUGIN_CACHE_DIR?.trim() || join(claudeDir(), "plugins");
89
+ }
90
+ function readObject(path) {
91
+ try {
92
+ const v = JSON.parse(readFileSync(path, "utf8"));
93
+ return v && typeof v === "object" && !Array.isArray(v) ? v : undefined;
94
+ }
95
+ catch {
96
+ return undefined;
97
+ }
98
+ }
99
+ /** Is a marketplace named context-doctor registered with Claude Code (from any source)? */
100
+ export function marketplaceRegistered() {
101
+ return Boolean(readObject(join(claudePluginsRoot(), "known_marketplaces.json"))?.[MARKETPLACE]);
102
+ }
103
+ /**
104
+ * How far Claude Code has got with the plugin: "installed" (downloaded, at
105
+ * `version`), "registered" (marketplace fetched, plugin not yet), or "none".
106
+ */
107
+ export function pluginStage() {
108
+ const installed = readObject(join(claudePluginsRoot(), "installed_plugins.json"))?.plugins;
109
+ if (installed && typeof installed === "object") {
110
+ for (const [key, list] of Object.entries(installed)) {
111
+ if (!isOurPluginKey(key))
112
+ continue;
113
+ const first = Array.isArray(list) ? list[0] : undefined;
114
+ return { stage: "installed", version: typeof first?.version === "string" ? first.version : undefined };
115
+ }
116
+ }
117
+ return { stage: marketplaceRegistered() ? "registered" : "none" };
118
+ }
119
+ /** When the mod last wrote each ledger (ms since epoch), from the files' modification times. */
120
+ export function modActivity() {
121
+ const at = (p) => {
122
+ try {
123
+ return existsSync(p) ? statSync(p).mtimeMs : undefined;
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ };
129
+ // modmeasure.ts costLogPath and limits.ts limitsLogPath, without loading the reports here.
130
+ const dir = dirname(statePath());
131
+ return { cost: at(join(dir, ".context-doctor-session-cost.jsonl")), limits: at(join(dir, ".context-doctor-limits.jsonl")) };
132
+ }
133
+ /** "3 h ago", "2 days ago". */
134
+ export function ago(ms, now = Date.now()) {
135
+ const min = Math.max(0, Math.round((now - ms) / 60_000));
136
+ if (min < 60)
137
+ return `${min} min ago`;
138
+ const h = Math.round(min / 60);
139
+ if (h < 48)
140
+ return `${h} h ago`;
141
+ return `${Math.round(h / 24)} days ago`;
142
+ }