context-doctor 0.44.0 → 0.46.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 (62) hide show
  1. package/README.md +5 -2
  2. package/dist/budget.d.ts +14 -1
  3. package/dist/budget.js +50 -28
  4. package/dist/cache.js +5 -4
  5. package/dist/cachemisses.js +6 -4
  6. package/dist/cacheplan.js +2 -2
  7. package/dist/cachettl.js +8 -5
  8. package/dist/ci.js +18 -2
  9. package/dist/cli.js +27 -6
  10. package/dist/codexcompact.js +14 -7
  11. package/dist/coldresume.d.ts +6 -0
  12. package/dist/coldresume.js +20 -11
  13. package/dist/compactwindow.js +14 -8
  14. package/dist/doctor.js +26 -2
  15. package/dist/extract.d.ts +2 -2
  16. package/dist/extract.js +14 -3
  17. package/dist/fanout.js +1 -1
  18. package/dist/fix.js +14 -10
  19. package/dist/hook.js +6 -2
  20. package/dist/httpguard.d.ts +9 -1
  21. package/dist/httpguard.js +5 -4
  22. package/dist/lens.js +7 -7
  23. package/dist/limits.d.ts +14 -5
  24. package/dist/limits.js +26 -17
  25. package/dist/mcp.js +62 -62
  26. package/dist/mcpschema.js +5 -3
  27. package/dist/mod/api.d.ts +129 -0
  28. package/dist/mod/api.js +12 -0
  29. package/dist/mod/logic.d.ts +146 -0
  30. package/dist/mod/logic.js +222 -0
  31. package/dist/mod/register.d.ts +58 -0
  32. package/dist/mod/register.js +237 -0
  33. package/dist/modelids.d.ts +23 -0
  34. package/dist/modelids.js +49 -0
  35. package/dist/modmeasure.d.ts +121 -0
  36. package/dist/modmeasure.js +298 -0
  37. package/dist/orgrates.d.ts +75 -0
  38. package/dist/orgrates.js +165 -0
  39. package/dist/overhead.js +11 -8
  40. package/dist/pack.js +95 -22
  41. package/dist/pricing.d.ts +123 -6
  42. package/dist/pricing.js +236 -62
  43. package/dist/proxy.d.ts +12 -1
  44. package/dist/proxy.js +13 -1
  45. package/dist/prune.js +55 -3
  46. package/dist/savings.js +19 -10
  47. package/dist/scan.d.ts +7 -1
  48. package/dist/scan.js +19 -1
  49. package/dist/sessionprice.d.ts +25 -2
  50. package/dist/sessionprice.js +60 -20
  51. package/dist/spend.d.ts +62 -10
  52. package/dist/spend.js +255 -29
  53. package/dist/statusline.d.ts +10 -2
  54. package/dist/statusline.js +18 -9
  55. package/dist/subagentmodel.d.ts +2 -2
  56. package/dist/subagentmodel.js +31 -24
  57. package/dist/subagentpay.d.ts +7 -1
  58. package/dist/subagentpay.js +51 -25
  59. package/dist/subagents.js +15 -10
  60. package/dist/tasks.js +9 -6
  61. package/dist/tooloutput.js +14 -5
  62. package/package.json +1 -1
package/dist/mcpschema.js CHANGED
@@ -95,20 +95,22 @@ export function claudeMcpConfigs(cwd = process.cwd(), home = homedir()) {
95
95
  out.set(name, { name, scope, command: c.command, args: c.args, env: c.env, url: c.url, type: c.type });
96
96
  }
97
97
  };
98
+ let cfg;
98
99
  try {
99
- const cfg = JSON.parse(readFileSync(claudeJsonPath(home), "utf8"));
100
- addAll(cfg.mcpServers, "user");
101
- addAll(cfg.projects?.[resolve(cwd)]?.mcpServers, "project");
100
+ cfg = JSON.parse(readFileSync(claudeJsonPath(home), "utf8"));
102
101
  }
103
102
  catch {
104
103
  /* absent */
105
104
  }
105
+ // A name in several scopes is Claude Code's local one, then the .mcp.json one, then the user's.
106
+ addAll(cfg?.mcpServers, "user");
106
107
  try {
107
108
  addAll(JSON.parse(readFileSync(join(cwd, ".mcp.json"), "utf8")).mcpServers, ".mcp.json");
108
109
  }
109
110
  catch {
110
111
  /* absent */
111
112
  }
113
+ addAll(cfg?.projects?.[resolve(cwd)]?.mcpServers, "project");
112
114
  return [...out.values()].sort((a, b) => a.name.localeCompare(b.name));
113
115
  }
114
116
  export const MCP_ROWS = {
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The part of Claude Code's mods API the context-doctor mod uses, typed here
3
+ * so the mod compiles with the rest of the package (the engine's own
4
+ * declarations, `claude-code`, exist only inside a mod folder Claude Code
5
+ * writes types into). Each name and shape below was read from the
6
+ * declarations Claude Code 2.1.321 writes (`claude-code.d.ts`): `$.process.run`,
7
+ * `$.session.{id,model,compact}`, `$.ui.{open,resolve,invalidate,toast}`,
8
+ * `$.command.register`, `$.clock.{now,every}`, `$.env.get`, `$.plugin.root`,
9
+ * and the events `session.start`, `session.measure`, `command.run`,
10
+ * `ui.render`. A subset, structurally compatible: no runtime code.
11
+ */
12
+ export type Surface = "terminal" | "desktop" | "vscode" | "mobile";
13
+ export interface RateLimit {
14
+ kind: string;
15
+ percentUsed: number;
16
+ resetsAt?: string;
17
+ }
18
+ export interface MeasureEvent {
19
+ context: {
20
+ tokens?: number;
21
+ window: number;
22
+ percent?: number;
23
+ };
24
+ rateLimits: RateLimit[];
25
+ cost?: {
26
+ usd: number;
27
+ };
28
+ changed: string[];
29
+ }
30
+ export interface RunResult {
31
+ exitCode: number;
32
+ stdout: string;
33
+ stderr: string;
34
+ }
35
+ export type Element = unknown;
36
+ export type Ctor = (props: Record<string, unknown>) => Element;
37
+ export interface RenderEvent {
38
+ component: string;
39
+ surface: Surface;
40
+ requestId?: string;
41
+ props: {
42
+ hasSurvey?: boolean;
43
+ isWorking?: boolean;
44
+ isCollapsed?: boolean;
45
+ bodyColumns?: number;
46
+ title?: string;
47
+ isFocused?: boolean;
48
+ };
49
+ }
50
+ export interface Engine {
51
+ plugin: {
52
+ name: string;
53
+ root: string;
54
+ };
55
+ process: {
56
+ run: (argv: readonly string[], init?: {
57
+ cwd?: string;
58
+ env?: Record<string, string>;
59
+ stdin?: string;
60
+ timeoutMs?: number;
61
+ }) => Promise<RunResult>;
62
+ };
63
+ session: {
64
+ id: () => Promise<string>;
65
+ model: () => Promise<string>;
66
+ cwd: () => Promise<string>;
67
+ compact: (input?: {
68
+ instructions?: string;
69
+ }) => Promise<{
70
+ skip?: string;
71
+ }>;
72
+ };
73
+ ui: {
74
+ open: (pane: {
75
+ id: string;
76
+ title?: string;
77
+ }) => Promise<{
78
+ isPlaced: boolean;
79
+ }>;
80
+ /** The engine's is generic per surface (each has its own table); the mod passes the render event it got. */
81
+ resolve: (e: any) => Record<"Box" | "Text" | "Button", Ctor>;
82
+ invalidate: (event: "ui.render") => void;
83
+ toast: (text: string, options?: {
84
+ timeoutMs?: number;
85
+ }) => void;
86
+ };
87
+ command: {
88
+ register: (spec: {
89
+ name: string;
90
+ description: string;
91
+ }) => Promise<unknown>;
92
+ };
93
+ clock: {
94
+ now: () => Promise<number>;
95
+ every: (ms: number, fn: () => void) => {
96
+ cancel: () => void;
97
+ };
98
+ };
99
+ env: {
100
+ get: (name: string) => Promise<string | undefined>;
101
+ };
102
+ }
103
+ export type Next<E, R> = (e: E) => Promise<R>;
104
+ export type Hook<E, R> = ($: Engine, e: E, next: Next<E, R>) => R | Promise<R>;
105
+ /** `on(event, matcher?, hook)`: the overloads the mod uses. */
106
+ export interface On {
107
+ (event: "session.start", hook: Hook<{
108
+ cwd: string;
109
+ surface: Surface | null;
110
+ isInteractive: boolean;
111
+ }, {
112
+ cwd: string;
113
+ }>): unknown;
114
+ (event: "session.measure", hook: Hook<MeasureEvent, {
115
+ changed: string[];
116
+ }>): unknown;
117
+ (event: "command.run", matcher: {
118
+ command: string;
119
+ }, hook: Hook<{
120
+ command: string;
121
+ args?: string;
122
+ }, {
123
+ text: string;
124
+ }>): unknown;
125
+ (event: "ui.render", matcher: {
126
+ component: string;
127
+ requestId?: string;
128
+ }, hook: Hook<RenderEvent, Element>): unknown;
129
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The part of Claude Code's mods API the context-doctor mod uses, typed here
3
+ * so the mod compiles with the rest of the package (the engine's own
4
+ * declarations, `claude-code`, exist only inside a mod folder Claude Code
5
+ * writes types into). Each name and shape below was read from the
6
+ * declarations Claude Code 2.1.321 writes (`claude-code.d.ts`): `$.process.run`,
7
+ * `$.session.{id,model,compact}`, `$.ui.{open,resolve,invalidate,toast}`,
8
+ * `$.command.register`, `$.clock.{now,every}`, `$.env.get`, `$.plugin.root`,
9
+ * and the events `session.start`, `session.measure`, `command.run`,
10
+ * `ui.render`. A subset, structurally compatible: no runtime code.
11
+ */
12
+ export {};
@@ -0,0 +1,146 @@
1
+ /**
2
+ * What the context-doctor mod shows and runs, as plain functions.
3
+ *
4
+ * The mod (register.ts) runs inside Claude Code's mods runtime, which has no
5
+ * Node: no fs, no child_process, no imports of the rest of context-doctor.
6
+ * So everything it decides is here, with no imports at all, and the measuring
7
+ * and the writing are done by the CLI it runs (`context-doctor mod measure`,
8
+ * `fix --apply`, `fix undo`), the same code as in a terminal. The node test
9
+ * suite exercises these functions directly.
10
+ */
11
+ /** What `context-doctor mod measure` prints after a turn: the band's inputs. */
12
+ export interface BandData {
13
+ /** When it was measured, ms. */
14
+ at: number;
15
+ /** context-doctor's price of the session so far, subagents included. */
16
+ usd?: number;
17
+ /** Claude Code's own cost of the session so far (`session.measure`'s `cost.usd`). */
18
+ ccUsd?: number;
19
+ /** The main conversation's context at its last reply, and its model. */
20
+ tokens?: number;
21
+ model?: string;
22
+ /** When that reply was written, ms, and how long the cache it left lives. */
23
+ lastReplyAt?: number;
24
+ ttlMs?: number;
25
+ /** Past the cache's lifetime by this much, a return counts as cold (coldresume.ts). */
26
+ coldMarginMs?: number;
27
+ /** What the next message pays to write the context again once the cache is cold. */
28
+ rewriteUsd?: number;
29
+ /** What each later message pays to re-read it, and what it would after a compaction. */
30
+ perMessageUsd?: number;
31
+ afterCompactPerMessageUsd?: number;
32
+ /** The context Claude Code compacts at by itself: no offer at or past it. */
33
+ autoCompactAt?: number;
34
+ /** Below this context, a cold return is cheap: no offer. */
35
+ coldMinTokens: number;
36
+ /** Session price thresholds in force (CONTEXT_DOCTOR_SESSION_PRICE), ascending. */
37
+ thresholds: number[];
38
+ }
39
+ export type Surface = "terminal" | "desktop" | "vscode" | "mobile" | string;
40
+ /** One band, or none. `key` names what Hide hides, so the next state shows again. */
41
+ export type Band = {
42
+ kind: "none";
43
+ } | {
44
+ kind: "warm" | "expired" | "price";
45
+ key: string;
46
+ text: string;
47
+ } | {
48
+ kind: "cold";
49
+ key: string;
50
+ text: string;
51
+ compact: string;
52
+ };
53
+ /** The band shows within this long of the cache going cold. */
54
+ export declare const WARN_BEFORE_MS: number;
55
+ /** "$0.42", "$3.10", "$112", "$1,240". */
56
+ export declare function money(n: number): string;
57
+ /** "820", "45k", "520k", "1.2M". */
58
+ export declare function tokens(n: number): string;
59
+ /** "3 min", "1h 20m", "2 days". */
60
+ export declare function duration(ms: number): string;
61
+ /** The highest session price threshold `usd` has passed, or undefined. */
62
+ export declare function passedThreshold(usd: number | undefined, thresholds: number[]): number | undefined;
63
+ /** The session's price as the band says it, with Claude Code's own figure beside ours when both are known. */
64
+ export declare function priceText(d: Pick<BandData, "usd" | "ccUsd">): string | undefined;
65
+ export interface BandOptions {
66
+ /** Keys the person hid this session. */
67
+ hidden?: ReadonlySet<string>;
68
+ /** CONTEXT_DOCTOR_MOD_BAND=always: show the cache clock and the price at all times, not only when they pay. */
69
+ always?: boolean;
70
+ }
71
+ /**
72
+ * The band above the prompt at `now`. Quiet unless it pays (the cache about
73
+ * to go cold, or gone cold, on a context worth caring about; the session
74
+ * past a price threshold), except with `always`. The terminal has the
75
+ * status line for the clock and the price, so there the band shows only the
76
+ * cold return, the one thing with a button. Nothing on mobile.
77
+ */
78
+ export declare function band(d: BandData | undefined, now: number, surface: Surface, opts?: BandOptions): Band;
79
+ /** A lever as `context-doctor fix --json` prints it (the fields the pane reads). */
80
+ export interface PlanFix {
81
+ id: string;
82
+ title: string;
83
+ savedUsd?: number;
84
+ savedShare?: number;
85
+ shareOf?: string;
86
+ basis?: string;
87
+ quality?: string;
88
+ change?: string;
89
+ state: "available" | "applied" | "not-here";
90
+ note?: string;
91
+ overriddenBy?: string[];
92
+ tooOld?: string;
93
+ }
94
+ export interface PlanJson {
95
+ days: number;
96
+ billedUsd: number;
97
+ fixes: PlanFix[];
98
+ since?: Array<{
99
+ id: string;
100
+ at: number;
101
+ savedUsd?: number;
102
+ detail?: string;
103
+ }>;
104
+ recordProblem?: string;
105
+ }
106
+ /** One row of the pane: what it says, and which buttons it has. */
107
+ export interface PaneRow {
108
+ id: string;
109
+ head: string;
110
+ lines: string[];
111
+ /** The subagents' model: a model change, said on the row and on its button. */
112
+ modelChange: boolean;
113
+ apply?: string;
114
+ undo?: string;
115
+ }
116
+ /** The lever that changes which model runs: never applied by `--apply all`, and marked as such here. */
117
+ export declare const MODEL_CHANGE = "subagent-model";
118
+ /** Parse `fix --json`'s output; undefined when it is not a plan. */
119
+ export declare function parsePlan(stdout: string): PlanJson | undefined;
120
+ /**
121
+ * The pane's rows: every lever the plan names, available ones first (the
122
+ * plan's own order), each with Apply when it is available and Undo when
123
+ * `fix` applied it (it is in the record, which is what `fix undo` reverts).
124
+ */
125
+ export declare function paneRows(plan: PlanJson): PaneRow[];
126
+ /**
127
+ * The rows after presses made since the plan was measured: an applied lever
128
+ * offers Undo, an undone one nothing until the plan is measured again (its
129
+ * figures are the old plan's). Measuring takes a while, so a press does not
130
+ * re-measure by itself; the pane offers Refresh.
131
+ */
132
+ export declare function withPresses(rows: PaneRow[], presses: ReadonlyMap<string, "applied" | "undone">): PaneRow[];
133
+ /** A lever id the CLI accepts: letters, digits and hyphens (never an option, never a path). */
134
+ export declare function isFixId(id: string): boolean;
135
+ /** The command a button runs: the CLI's own, so the files it writes are the CLI's. */
136
+ export declare function fixArgv(node: string, cli: string, op: "plan" | "apply" | "undo", id?: string): string[];
137
+ /** What `fix --apply <id> --json` did, from its `applied` list; the text form's lines otherwise. */
138
+ export declare function applyOutcome(stdout: string, stderr: string, exitCode: number): {
139
+ ok: boolean;
140
+ lines: string[];
141
+ };
142
+ /** The CLI's lines, without the plan it prints first: what the press did. */
143
+ export declare function outcome(stdout: string, stderr: string, exitCode: number): {
144
+ ok: boolean;
145
+ lines: string[];
146
+ };
@@ -0,0 +1,222 @@
1
+ /**
2
+ * What the context-doctor mod shows and runs, as plain functions.
3
+ *
4
+ * The mod (register.ts) runs inside Claude Code's mods runtime, which has no
5
+ * Node: no fs, no child_process, no imports of the rest of context-doctor.
6
+ * So everything it decides is here, with no imports at all, and the measuring
7
+ * and the writing are done by the CLI it runs (`context-doctor mod measure`,
8
+ * `fix --apply`, `fix undo`), the same code as in a terminal. The node test
9
+ * suite exercises these functions directly.
10
+ */
11
+ /** The band shows within this long of the cache going cold. */
12
+ export const WARN_BEFORE_MS = 5 * 60_000;
13
+ const MIN = 60_000;
14
+ /** "$0.42", "$3.10", "$112", "$1,240". */
15
+ export function money(n) {
16
+ if (!Number.isFinite(n))
17
+ return "$0.00";
18
+ if (n >= 100)
19
+ return `$${Math.round(n).toLocaleString("en-US")}`;
20
+ if (n >= 0.01 || n === 0)
21
+ return `$${n.toFixed(2)}`;
22
+ return "<$0.01";
23
+ }
24
+ /** "820", "45k", "520k", "1.2M". */
25
+ export function tokens(n) {
26
+ if (!Number.isFinite(n) || n < 0)
27
+ return "0";
28
+ if (n < 1000)
29
+ return String(Math.round(n));
30
+ if (n < 999_500)
31
+ return `${Math.round(n / 1000)}k`;
32
+ return `${(n / 1e6).toFixed(1)}M`;
33
+ }
34
+ /** "3 min", "1h 20m", "2 days". */
35
+ export function duration(ms) {
36
+ const m = Math.max(1, Math.round(ms / MIN));
37
+ if (m < 60)
38
+ return `${m} min`;
39
+ if (m < 48 * 60)
40
+ return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;
41
+ return `${Math.round(m / 1440)} days`;
42
+ }
43
+ /** The highest session price threshold `usd` has passed, or undefined. */
44
+ export function passedThreshold(usd, thresholds) {
45
+ if (usd === undefined || !Number.isFinite(usd))
46
+ return undefined;
47
+ const passed = thresholds.filter((t) => usd >= t);
48
+ return passed[passed.length - 1];
49
+ }
50
+ /** The session's price as the band says it, with Claude Code's own figure beside ours when both are known. */
51
+ export function priceText(d) {
52
+ if (d.usd !== undefined && d.ccUsd !== undefined)
53
+ return `session ${money(d.usd)} (Claude Code: ${money(d.ccUsd)})`;
54
+ if (d.usd !== undefined)
55
+ return `session ${money(d.usd)}`;
56
+ if (d.ccUsd !== undefined)
57
+ return `session ${money(d.ccUsd)} (Claude Code's figure)`;
58
+ return undefined;
59
+ }
60
+ /**
61
+ * The band above the prompt at `now`. Quiet unless it pays (the cache about
62
+ * to go cold, or gone cold, on a context worth caring about; the session
63
+ * past a price threshold), except with `always`. The terminal has the
64
+ * status line for the clock and the price, so there the band shows only the
65
+ * cold return, the one thing with a button. Nothing on mobile.
66
+ */
67
+ export function band(d, now, surface, opts = {}) {
68
+ if (!d || surface === "mobile")
69
+ return { kind: "none" };
70
+ const hidden = opts.hidden ?? new Set();
71
+ const show = (b) => (hidden.has(b.key) ? { kind: "none" } : b);
72
+ const terminal = surface === "terminal";
73
+ const price = priceText(d);
74
+ const big = d.tokens !== undefined && d.tokens >= d.coldMinTokens;
75
+ const known = d.tokens !== undefined && d.lastReplyAt !== undefined && d.ttlMs !== undefined;
76
+ if (known) {
77
+ const expiresAt = d.lastReplyAt + d.ttlMs;
78
+ const coldAt = expiresAt + (d.coldMarginMs ?? 0);
79
+ const rewrite = `${tokens(d.tokens)} tokens${d.rewriteUsd !== undefined ? ` (~${money(d.rewriteUsd)})` : ""}`;
80
+ const tail = price && !terminal ? ` · ${price}` : "";
81
+ // The return the cold-resume offer is about: past the cache's life by the margin, big enough, and not about to be compacted by Claude Code anyway.
82
+ if (now >= coldAt && big && d.tokens < (d.autoCompactAt ?? Infinity)) {
83
+ const each = d.perMessageUsd !== undefined && d.afterCompactPerMessageUsd !== undefined
84
+ ? `each later message re-reads ~${money(d.perMessageUsd)} of context now, ~${money(d.afterCompactPerMessageUsd)} after`
85
+ : `each later message re-reads ${tokens(d.tokens)} tokens now, far fewer after`;
86
+ return show({
87
+ kind: "cold",
88
+ key: `cold:${d.lastReplyAt}`,
89
+ text: `context-doctor: idle ${duration(now - d.lastReplyAt)}, the cache expired: your next message re-writes ${rewrite}${tail}`,
90
+ compact: `Compact first: ${each}`,
91
+ });
92
+ }
93
+ if (terminal)
94
+ return { kind: "none" };
95
+ if (now >= expiresAt && (big || opts.always)) {
96
+ return show({ kind: "expired", key: `expired:${d.lastReplyAt}`, text: `context-doctor: the cache expired, so your next message re-writes ${rewrite}${tail}` });
97
+ }
98
+ if (now < expiresAt && (opts.always || (big && expiresAt - now <= WARN_BEFORE_MS))) {
99
+ return show({ kind: "warm", key: `warm:${d.lastReplyAt}`, text: `context-doctor: cache warm for ${duration(expiresAt - now)}, then your next message re-writes ${rewrite}${tail}` });
100
+ }
101
+ }
102
+ if (terminal)
103
+ return { kind: "none" };
104
+ const usd = d.usd ?? d.ccUsd;
105
+ const t = passedThreshold(usd, d.thresholds);
106
+ if (price && (t !== undefined || opts.always)) {
107
+ return show({ kind: "price", key: `price:${t ?? 0}`, text: `context-doctor: ${price}` });
108
+ }
109
+ return { kind: "none" };
110
+ }
111
+ /** The lever that changes which model runs: never applied by `--apply all`, and marked as such here. */
112
+ export const MODEL_CHANGE = "subagent-model";
113
+ /** Parse `fix --json`'s output; undefined when it is not a plan. */
114
+ export function parsePlan(stdout) {
115
+ try {
116
+ const j = JSON.parse(stdout);
117
+ if (!j || typeof j !== "object" || !Array.isArray(j.fixes))
118
+ return undefined;
119
+ return j;
120
+ }
121
+ catch {
122
+ return undefined;
123
+ }
124
+ }
125
+ /**
126
+ * The pane's rows: every lever the plan names, available ones first (the
127
+ * plan's own order), each with Apply when it is available and Undo when
128
+ * `fix` applied it (it is in the record, which is what `fix undo` reverts).
129
+ */
130
+ export function paneRows(plan) {
131
+ const applied = new Set((plan.since ?? []).map((s) => s.id));
132
+ const rows = [];
133
+ for (const f of plan.fixes) {
134
+ const modelChange = f.id === MODEL_CHANGE;
135
+ const saved = f.savedUsd !== undefined ? `${money(f.savedUsd)}${f.savedShare !== undefined ? ` (${Math.round(f.savedShare * 100)}%${f.shareOf ? ` ${f.shareOf}` : ""})` : ""}` : "not priced";
136
+ const lines = [];
137
+ if (f.state === "available") {
138
+ if (modelChange)
139
+ lines.push("Model change: subagents run on another model. Its quality cost is not measured here.");
140
+ if (f.quality)
141
+ lines.push(`quality: ${f.quality}`);
142
+ if (f.change)
143
+ lines.push(`changes: ${f.change}`);
144
+ if (f.overriddenBy?.length)
145
+ lines.push(`would not take effect: ${f.overriddenBy.join("; ")}`);
146
+ if (f.tooOld)
147
+ lines.push(f.tooOld);
148
+ }
149
+ else if (f.note) {
150
+ lines.push(f.note);
151
+ }
152
+ const s = plan.since?.find((x) => x.id === f.id);
153
+ if (s?.savedUsd !== undefined)
154
+ lines.push(`${s.savedUsd >= 0 ? "saved" : "cost"} ${money(Math.abs(s.savedUsd))} since it was applied`);
155
+ rows.push({
156
+ id: f.id,
157
+ head: f.state === "available" ? `${f.title} · ${saved} in ${plan.days} days` : `${f.title}${f.state === "applied" ? " · applied" : " · not here"}`,
158
+ lines,
159
+ modelChange,
160
+ ...(f.state === "available" ? { apply: modelChange ? "Apply (model change)" : "Apply" } : {}),
161
+ ...(applied.has(f.id) ? { undo: "Undo" } : {}),
162
+ });
163
+ }
164
+ // A fix applied by `fix` that the plan no longer lists (its setting changed since): still undoable.
165
+ for (const s of plan.since ?? []) {
166
+ if (rows.some((r) => r.id === s.id))
167
+ continue;
168
+ rows.push({ id: s.id, head: `${s.id} · applied`, lines: s.detail ? [s.detail] : [], modelChange: s.id === MODEL_CHANGE, undo: "Undo" });
169
+ }
170
+ return rows;
171
+ }
172
+ /**
173
+ * The rows after presses made since the plan was measured: an applied lever
174
+ * offers Undo, an undone one nothing until the plan is measured again (its
175
+ * figures are the old plan's). Measuring takes a while, so a press does not
176
+ * re-measure by itself; the pane offers Refresh.
177
+ */
178
+ export function withPresses(rows, presses) {
179
+ return rows.map((r) => {
180
+ const p = presses.get(r.id);
181
+ if (p === "applied")
182
+ return { ...r, head: r.head.replace(/ · [^·]* in \d+ days$/, "") + " · applied just now", apply: undefined, undo: "Undo" };
183
+ if (p === "undone")
184
+ return { ...r, head: r.head.replace(/ · applied$/, "") + " · undone just now", lines: ["Refresh to measure it again."], apply: undefined, undo: undefined };
185
+ return r;
186
+ });
187
+ }
188
+ /** A lever id the CLI accepts: letters, digits and hyphens (never an option, never a path). */
189
+ export function isFixId(id) {
190
+ return /^[a-z][a-z0-9-]{0,40}$/.test(id);
191
+ }
192
+ /** The command a button runs: the CLI's own, so the files it writes are the CLI's. */
193
+ export function fixArgv(node, cli, op, id) {
194
+ if (op === "plan")
195
+ return [node, cli, "fix", "--json"];
196
+ if (!id || !isFixId(id))
197
+ throw new Error(`not a fix id: ${id}`);
198
+ // `--json` only changes what is printed (the lines of what it did, without the plan): the same applyFix writes the same files.
199
+ return op === "apply" ? [node, cli, "fix", "--apply", id, "--json"] : [node, cli, "fix", "undo", id];
200
+ }
201
+ /** What `fix --apply <id> --json` did, from its `applied` list; the text form's lines otherwise. */
202
+ export function applyOutcome(stdout, stderr, exitCode) {
203
+ try {
204
+ const j = JSON.parse(stdout);
205
+ const a = Array.isArray(j?.applied) ? j.applied : [];
206
+ if (a.length) {
207
+ const lines = a.flatMap((x) => (Array.isArray(x?.lines) ? x.lines.filter((l) => typeof l === "string") : [])).map((l) => l.trim()).filter(Boolean);
208
+ return { ok: exitCode === 0 && a.every((x) => x?.ok === true), lines: lines.slice(0, 8) };
209
+ }
210
+ }
211
+ catch { /* not JSON: read it as text */ }
212
+ return outcome(stdout, stderr, exitCode);
213
+ }
214
+ /** The CLI's lines, without the plan it prints first: what the press did. */
215
+ export function outcome(stdout, stderr, exitCode) {
216
+ const text = stdout.replace(/\r\n/g, "\n");
217
+ // `fix --apply` prints the plan, a blank line, then what it did; `fix undo` only what it did.
218
+ const marks = text.split("\n").filter((l) => /^\s*(✓|✗|–|⚠|New |Nothing |[a-z-]+: )/.test(l));
219
+ const lines = (marks.length ? marks : text.split("\n").filter((l) => l.trim()).slice(-3)).map((l) => l.trim());
220
+ const err = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
221
+ return { ok: exitCode === 0, lines: [...lines, ...(exitCode === 0 ? [] : err.slice(-3))].slice(0, 8) };
222
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * context-doctor's mod: the status line's measurements and `fix`'s plan where
3
+ * the status line never runs (Claude Code's Desktop app, the VS Code
4
+ * extension), and in the terminal too.
5
+ *
6
+ * Shipped inside the plugin: hooks/hooks.json names this file under
7
+ * `modules`. Claude Code runs mods from 2.1.287 (terminal), 2.1.286 (the
8
+ * Desktop app's Code tab) and 2.1.299 (VS Code); an older one never loads
9
+ * it and keeps the rest of the plugin.
10
+ *
11
+ * - After each turn (`session.measure`) it runs `context-doctor mod measure`
12
+ * with Claude Code's rate-limit windows and session cost: the CLI keeps
13
+ * them (the limits ledger; Claude Code's cost beside ours) and answers
14
+ * with the band's figures.
15
+ * - A band above the prompt, only when it pays: the cache about to go cold
16
+ * or gone cold on a big context (with the re-write's price), the session
17
+ * past a price threshold. On a cold return a "Compact first" button calls
18
+ * `$.session.compact()`, between turns, on the press alone.
19
+ * - `/context-doctor-fix` opens a pane with `fix`'s plan and an Apply / Undo
20
+ * button per lever. Each press runs the CLI's own `fix --apply <id>` /
21
+ * `fix undo <id>`: the same lock, backup and record as in a terminal.
22
+ *
23
+ * Nothing happens without a press: no auto-compaction, no auto-apply. The
24
+ * mod writes no file itself; the CLI writes ours. Off: CONTEXT_DOCTOR_NO_MOD=1.
25
+ *
26
+ * The mods runtime has no Node, so this file imports only ./logic.js (no
27
+ * imports of its own) and reaches everything else through `$`. Claude Code
28
+ * reads which calls a module makes from its source: `$` is passed only to
29
+ * functions declared at the top of this file.
30
+ */
31
+ import { type BandData, type PlanJson } from "./logic.js";
32
+ import type { On } from "./api.js";
33
+ export declare const COMMAND = "context-doctor-fix";
34
+ export declare const PANE = "context-doctor-fix";
35
+ /** The mod's state for this load (a reload starts it over; the next turn measures again). */
36
+ interface State {
37
+ off: boolean;
38
+ always: boolean;
39
+ data?: BandData;
40
+ hidden: Set<string>;
41
+ drawn: string;
42
+ compacting: boolean;
43
+ plan?: PlanJson;
44
+ planError?: string;
45
+ loading: boolean;
46
+ /** A press in flight ("apply:<id>"): never two at once. */
47
+ busy?: string;
48
+ last?: {
49
+ id: string;
50
+ ok: boolean;
51
+ lines: string[];
52
+ };
53
+ presses: Map<string, "applied" | "undone">;
54
+ }
55
+ /** For tests: the state the hooks share. */
56
+ export declare const state: () => State;
57
+ export declare function register(on: On): void;
58
+ export {};