context-doctor 0.33.0 → 0.35.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.
- package/README.md +13 -10
- package/dist/autoclear.d.ts +5 -2
- package/dist/autoclear.js +57 -19
- package/dist/autopilot.d.ts +0 -6
- package/dist/autopilot.js +37 -2
- package/dist/cachekey.d.ts +25 -0
- package/dist/cachekey.js +73 -0
- package/dist/cachemisses.d.ts +88 -0
- package/dist/cachemisses.js +325 -0
- package/dist/cacheplan.d.ts +30 -10
- package/dist/cacheplan.js +157 -32
- package/dist/cli.js +68 -19
- package/dist/codexroute.d.ts +46 -0
- package/dist/codexroute.js +122 -0
- package/dist/coldresume.d.ts +62 -0
- package/dist/coldresume.js +85 -6
- package/dist/compactquality.d.ts +2 -0
- package/dist/compactquality.js +21 -3
- package/dist/compactwindow.d.ts +2 -0
- package/dist/compactwindow.js +30 -7
- package/dist/config.d.ts +11 -0
- package/dist/config.js +117 -4
- package/dist/dashboard.js +15 -1
- package/dist/doctor.d.ts +23 -0
- package/dist/doctor.js +133 -10
- package/dist/hook.d.ts +18 -0
- package/dist/hook.js +58 -8
- package/dist/impact.js +32 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +25 -0
- package/dist/install.js +148 -45
- package/dist/ledger.d.ts +2 -0
- package/dist/mcp.js +56 -53
- package/dist/modelswitch.d.ts +76 -0
- package/dist/modelswitch.js +184 -0
- package/dist/optimize.js +40 -6
- package/dist/pack.d.ts +32 -3
- package/dist/pack.js +176 -24
- package/dist/parse.d.ts +3 -1
- package/dist/parse.js +123 -3
- package/dist/pricing.js +8 -0
- package/dist/profile.js +60 -17
- package/dist/proxy.d.ts +22 -1
- package/dist/proxy.js +89 -12
- package/dist/report.js +8 -2
- package/dist/savings.d.ts +15 -2
- package/dist/savings.js +9 -11
- package/dist/session.js +19 -3
- package/dist/sketch.d.ts +2 -0
- package/dist/sketch.js +10 -1
- package/dist/tokens.js +20 -9
- package/dist/wrap.js +27 -5
- package/package.json +1 -1
package/dist/config.js
CHANGED
|
@@ -96,15 +96,128 @@ export function validateConfig(config, path) {
|
|
|
96
96
|
const value = c[key];
|
|
97
97
|
if (value === undefined)
|
|
98
98
|
continue;
|
|
99
|
-
if (
|
|
99
|
+
if (!isPositiveInt(value)) {
|
|
100
100
|
warnings.push(`${where(key)} must be a positive whole number, got ${JSON.stringify(value)} — ignored`);
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
|
-
if (c.
|
|
104
|
-
warnings.push(`${where("
|
|
103
|
+
if (c.model !== undefined && (typeof c.model !== "string" || !c.model.trim())) {
|
|
104
|
+
warnings.push(`${where("model")} must be a model name, got ${JSON.stringify(c.model)} — ignored`);
|
|
105
105
|
}
|
|
106
|
+
if (c.routes !== undefined) {
|
|
107
|
+
if (!Array.isArray(c.routes)) {
|
|
108
|
+
warnings.push(`${where("routes")} must be an array — ignored`);
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
warnings.push(...validateRoutes(c.routes, path));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return warnings;
|
|
115
|
+
}
|
|
116
|
+
/** Warnings for the entries of a `routes` array (rc file or `proxy --config`). */
|
|
117
|
+
export function validateRoutes(routes, path) {
|
|
118
|
+
const warnings = [];
|
|
119
|
+
routes.forEach((r, i) => {
|
|
120
|
+
const at = `${path}: routes[${i}]`;
|
|
121
|
+
if (!r || typeof r !== "object" || Array.isArray(r)) {
|
|
122
|
+
warnings.push(`${at} must be an object — ignored`);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const route = r;
|
|
126
|
+
if (typeof route.modelPrefix !== "string") {
|
|
127
|
+
warnings.push(`${at}.modelPrefix must be a string — route ignored`);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (route.strategies !== undefined) {
|
|
131
|
+
if (!Array.isArray(route.strategies))
|
|
132
|
+
warnings.push(`${at}.strategies must be an array — ignored`);
|
|
133
|
+
else
|
|
134
|
+
for (const id of route.strategies) {
|
|
135
|
+
if (!KNOWN_STRATEGIES.has(String(id)))
|
|
136
|
+
warnings.push(`${at}.strategies: "${id}" is not a strategy — ignored`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
for (const key of ["keepRecent", "maxToolResultTokens"]) {
|
|
140
|
+
const value = route[key];
|
|
141
|
+
if (value !== undefined && !isPositiveInt(value)) {
|
|
142
|
+
warnings.push(`${at}.${key} must be a positive whole number, got ${JSON.stringify(value)} — ignored`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
});
|
|
106
146
|
return warnings;
|
|
107
147
|
}
|
|
148
|
+
function isPositiveInt(value) {
|
|
149
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0;
|
|
150
|
+
}
|
|
151
|
+
/** Valid strategy ids from a raw value; undefined when it is not an array or nothing valid is left. */
|
|
152
|
+
function validStrategies(value) {
|
|
153
|
+
if (!Array.isArray(value))
|
|
154
|
+
return undefined;
|
|
155
|
+
// An explicit empty list is a choice (no strategies); a list whose every
|
|
156
|
+
// entry is a typo is not, and falls back to the defaults like a missing one.
|
|
157
|
+
if (value.length === 0)
|
|
158
|
+
return [];
|
|
159
|
+
const kept = value.filter((id) => KNOWN_STRATEGIES.has(String(id)));
|
|
160
|
+
return kept.length > 0 ? kept : undefined;
|
|
161
|
+
}
|
|
162
|
+
/** The valid routes of a raw `routes` value, each with only its valid settings. */
|
|
163
|
+
export function sanitizeRoutes(value) {
|
|
164
|
+
if (!Array.isArray(value))
|
|
165
|
+
return undefined;
|
|
166
|
+
const routes = [];
|
|
167
|
+
for (const r of value) {
|
|
168
|
+
if (!r || typeof r !== "object" || Array.isArray(r))
|
|
169
|
+
continue;
|
|
170
|
+
const route = r;
|
|
171
|
+
if (typeof route.modelPrefix !== "string")
|
|
172
|
+
continue;
|
|
173
|
+
const out = { modelPrefix: route.modelPrefix };
|
|
174
|
+
const strategies = validStrategies(route.strategies);
|
|
175
|
+
if (strategies)
|
|
176
|
+
out.strategies = strategies;
|
|
177
|
+
if (isPositiveInt(route.keepRecent))
|
|
178
|
+
out.keepRecent = route.keepRecent;
|
|
179
|
+
if (isPositiveInt(route.maxToolResultTokens))
|
|
180
|
+
out.maxToolResultTokens = route.maxToolResultTokens;
|
|
181
|
+
routes.push(out);
|
|
182
|
+
}
|
|
183
|
+
return routes;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The settings of a parsed rc file that are actually in effect: exactly the
|
|
187
|
+
* values validateConfig does not call ignored. Returning the raw object, as
|
|
188
|
+
* this once did, warned that `keepRecent: -5` was ignored and then applied
|
|
189
|
+
* it, which cut the live tool result in `optimize` and the proxy.
|
|
190
|
+
*/
|
|
191
|
+
export function sanitizeConfig(config) {
|
|
192
|
+
if (!config || typeof config !== "object" || Array.isArray(config))
|
|
193
|
+
return {};
|
|
194
|
+
const c = config;
|
|
195
|
+
const out = {};
|
|
196
|
+
if (c.budget && typeof c.budget === "object" && !Array.isArray(c.budget)) {
|
|
197
|
+
const budget = {};
|
|
198
|
+
for (const [key, value] of Object.entries(c.budget)) {
|
|
199
|
+
if (!KNOWN_BUDGET_KEYS.has(key))
|
|
200
|
+
continue;
|
|
201
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
|
|
202
|
+
continue;
|
|
203
|
+
budget[key] = value;
|
|
204
|
+
}
|
|
205
|
+
out.budget = budget;
|
|
206
|
+
}
|
|
207
|
+
const strategies = validStrategies(c.strategies);
|
|
208
|
+
if (strategies)
|
|
209
|
+
out.strategies = strategies;
|
|
210
|
+
for (const key of ["keepRecent", "maxToolResultTokens", "trimBoundaryStep"]) {
|
|
211
|
+
if (isPositiveInt(c[key]))
|
|
212
|
+
out[key] = c[key];
|
|
213
|
+
}
|
|
214
|
+
const routes = sanitizeRoutes(c.routes);
|
|
215
|
+
if (routes)
|
|
216
|
+
out.routes = routes;
|
|
217
|
+
if (typeof c.model === "string" && c.model.trim())
|
|
218
|
+
out.model = c.model;
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
108
221
|
export function loadConfig(startDir = process.cwd(), onWarn) {
|
|
109
222
|
for (const path of candidatePaths(startDir)) {
|
|
110
223
|
if (!existsSync(path))
|
|
@@ -116,7 +229,7 @@ export function loadConfig(startDir = process.cwd(), onWarn) {
|
|
|
116
229
|
const warnings = validateConfig(parsed, path);
|
|
117
230
|
for (const warning of warnings)
|
|
118
231
|
onWarn?.(warning);
|
|
119
|
-
return { config: parsed, path, warnings };
|
|
232
|
+
return { config: sanitizeConfig(parsed), path, warnings };
|
|
120
233
|
}
|
|
121
234
|
onWarn?.(`${path}: expected a JSON object — ignoring`);
|
|
122
235
|
return { config: {}, path, error: "expected a JSON object" };
|
package/dist/dashboard.js
CHANGED
|
@@ -154,9 +154,23 @@ export function startDashboard(opts = {}) {
|
|
|
154
154
|
res.end(`dashboard error: ${e.message}`);
|
|
155
155
|
}
|
|
156
156
|
});
|
|
157
|
+
// A busy port used to surface as an unhandled 'error' event: a stack
|
|
158
|
+
// trace, and nothing about what to do. Say it, and exit 1 (nothing else
|
|
159
|
+
// keeps the process alive once the server is gone).
|
|
160
|
+
server.on("error", (e) => {
|
|
161
|
+
const reason = e.code === "EADDRINUSE"
|
|
162
|
+
? `port ${port} is already in use (a dashboard may already be running: open http://127.0.0.1:${port}). Pass --port <n> to use another.`
|
|
163
|
+
: e.code === "EACCES"
|
|
164
|
+
? `not allowed to listen on port ${port}. Pass --port <n> above 1024.`
|
|
165
|
+
: e.message;
|
|
166
|
+
console.error(`context-doctor dashboard: ${reason}`);
|
|
167
|
+
process.exitCode = 1;
|
|
168
|
+
server.close();
|
|
169
|
+
});
|
|
157
170
|
// Loopback only: this page exposes local usage data.
|
|
158
171
|
server.listen(port, "127.0.0.1", () => {
|
|
159
|
-
|
|
172
|
+
const bound = server.address()?.port ?? port;
|
|
173
|
+
console.error(`context-doctor dashboard on http://127.0.0.1:${bound}`);
|
|
160
174
|
});
|
|
161
175
|
return server;
|
|
162
176
|
}
|
package/dist/doctor.d.ts
CHANGED
|
@@ -6,4 +6,27 @@
|
|
|
6
6
|
* when any check fails (✗), so a script can tell; an app that is absent, or
|
|
7
7
|
* that nothing was installed into, is a note (–), not a failure.
|
|
8
8
|
*/
|
|
9
|
+
interface Check {
|
|
10
|
+
label: string;
|
|
11
|
+
status: "ok" | "warn" | "fail" | "skip";
|
|
12
|
+
detail: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
|
|
16
|
+
* Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
|
|
17
|
+
* ~/.claude/settings.json in Claude Code's format while its
|
|
18
|
+
* `read_config_from.claude` is on (the default), with session_id and
|
|
19
|
+
* prompt_id but no transcript_path in the input; the desktop app's Cascade
|
|
20
|
+
* hooks (~/.codeium/windsurf/hooks.json) pass a transcript only to
|
|
21
|
+
* post_cascade_response_with_transcript. So in Devin our hook runs (CLI) or
|
|
22
|
+
* does not (Desktop) and has no transcript to measure either way: say that,
|
|
23
|
+
* rather than nothing or a false "ok".
|
|
24
|
+
*/
|
|
25
|
+
export declare function devinCheck(home?: string): Check;
|
|
9
26
|
export declare function runDoctor(): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* The Cursor version here: the newest one that ran the hook (its input
|
|
29
|
+
* carries cursor_version, on every platform), else the macOS app bundle.
|
|
30
|
+
*/
|
|
31
|
+
export declare function cursorVersion(): string | undefined;
|
|
32
|
+
export {};
|
package/dist/doctor.js
CHANGED
|
@@ -12,11 +12,14 @@ import { accessSync, constants as fsConstants, existsSync, readFileSync } from "
|
|
|
12
12
|
import { homedir, platform } from "node:os";
|
|
13
13
|
import { dirname, join } from "node:path";
|
|
14
14
|
import { fileURLToPath } from "node:url";
|
|
15
|
-
import { ledgerPath } from "./ledger.js";
|
|
15
|
+
import { ledgerPath, readLedger } from "./ledger.js";
|
|
16
16
|
import { loadConfig } from "./config.js";
|
|
17
|
-
import {
|
|
17
|
+
import { codexRouting } from "./codexroute.js";
|
|
18
|
+
import { CURSOR_HOOK_EVENTS } from "./install.js";
|
|
19
|
+
import { binOnPath, claudeCodeInstallsFromEnv, claudeInstalledCopies, codexMcpEntry, geminiCliPresent, geminiSettingsPath, isEmptyStub, isOurPluginKey, launcherNamesMissingPackage } from "./install.js";
|
|
18
20
|
import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
|
|
19
21
|
import { withInvocation } from "./invocation.js";
|
|
22
|
+
import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
|
|
20
23
|
function claudeDesktopConfigPath() {
|
|
21
24
|
switch (platform()) {
|
|
22
25
|
case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
@@ -139,6 +142,73 @@ function pluginEnabled(layers) {
|
|
|
139
142
|
}
|
|
140
143
|
return [...state.values()].some(Boolean);
|
|
141
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* The model-switch warning (PreModelSwitch). Its entry in settings.json is a
|
|
147
|
+
* failure next to a Claude Code older than the event: that version skips the
|
|
148
|
+
* whole file, every other setting and hook with it.
|
|
149
|
+
*/
|
|
150
|
+
function modelSwitchCheck(settings, plugin) {
|
|
151
|
+
const label = "Model-switch warning";
|
|
152
|
+
const entries = settings.hooks?.PreModelSwitch ?? [];
|
|
153
|
+
const ours = entries.some((e) => /context-doctor|cli\.js"?\s+hook/.test(e.hooks?.[0]?.command ?? ""));
|
|
154
|
+
const readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv());
|
|
155
|
+
if (Array.isArray(settings.hooks?.PreModelSwitch) && readiness.old.length > 0) {
|
|
156
|
+
return {
|
|
157
|
+
label,
|
|
158
|
+
status: "fail",
|
|
159
|
+
detail: `~/.claude/settings.json has a PreModelSwitch hook${ours ? "" : " (not ours)"}, and ${describeInstalls(readiness.old)} predates that event (${PRE_MODEL_SWITCH_SINCE}): it skips the whole file, every setting and hook in it. Update that Claude Code, or ${ours ? "run context-doctor install (it takes ours out)" : "remove the entry"}`,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
if (ours)
|
|
163
|
+
return { label, status: "ok", detail: "PreModelSwitch: before a model switch, the price of re-writing the context into the new model's cache" };
|
|
164
|
+
if (plugin) {
|
|
165
|
+
return readiness.old.length > 0
|
|
166
|
+
? { label, status: "skip", detail: `the plugin carries it, but ${describeInstalls(readiness.old)} predates PreModelSwitch (${PRE_MODEL_SWITCH_SINCE}) and drops it` }
|
|
167
|
+
: { label, status: "ok", detail: "PreModelSwitch: provided by the context-doctor plugin" };
|
|
168
|
+
}
|
|
169
|
+
if (readiness.old.length > 0)
|
|
170
|
+
return { label, status: "skip", detail: `not installed: ${describeInstalls(readiness.old)} predates PreModelSwitch (${PRE_MODEL_SWITCH_SINCE}); update it, then run context-doctor install` };
|
|
171
|
+
if (!readiness.ok)
|
|
172
|
+
return { label, status: "skip", detail: `not installed: no Claude Code version found to check (needs ${PRE_MODEL_SWITCH_SINCE})` };
|
|
173
|
+
return { label, status: "warn", detail: "not registered: model switches re-write the whole context into the new model's cache unannounced; run context-doctor install" };
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
|
|
177
|
+
* Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
|
|
178
|
+
* ~/.claude/settings.json in Claude Code's format while its
|
|
179
|
+
* `read_config_from.claude` is on (the default), with session_id and
|
|
180
|
+
* prompt_id but no transcript_path in the input; the desktop app's Cascade
|
|
181
|
+
* hooks (~/.codeium/windsurf/hooks.json) pass a transcript only to
|
|
182
|
+
* post_cascade_response_with_transcript. So in Devin our hook runs (CLI) or
|
|
183
|
+
* does not (Desktop) and has no transcript to measure either way: say that,
|
|
184
|
+
* rather than nothing or a false "ok".
|
|
185
|
+
*/
|
|
186
|
+
export function devinCheck(home = homedir()) {
|
|
187
|
+
const label = "Devin";
|
|
188
|
+
const app = [join("/Applications", "Devin.app"), join(home, "Applications", "Devin.app"), join(home, "Library", "Application Support", "Devin"), join(home, ".devin")].find((p) => existsSync(p));
|
|
189
|
+
const cliConfig = join(home, ".config", "devin", "config.json");
|
|
190
|
+
const cli = binOnPath("devin") || existsSync(join(home, ".local", "bin", "devin")) || existsSync(cliConfig);
|
|
191
|
+
if (!app && !cli)
|
|
192
|
+
return { label, status: "skip", detail: "not detected (Devin CLI or Devin Desktop)" };
|
|
193
|
+
const parts = [];
|
|
194
|
+
if (cli) {
|
|
195
|
+
let readsClaude = true;
|
|
196
|
+
try {
|
|
197
|
+
const config = JSON.parse(readFileSync(cliConfig, "utf8"));
|
|
198
|
+
if (config?.read_config_from?.claude === false)
|
|
199
|
+
readsClaude = false;
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
/* no config: the default, which reads ~/.claude */
|
|
203
|
+
}
|
|
204
|
+
parts.push(readsClaude
|
|
205
|
+
? "Devin CLI runs the hooks in ~/.claude/settings.json (read_config_from.claude, on by default), so the every-prompt hook runs there too, but Devin gives hooks no transcript path, so it stays silent"
|
|
206
|
+
: "Devin CLI found with read_config_from.claude off: it runs none of the hooks in ~/.claude/settings.json");
|
|
207
|
+
}
|
|
208
|
+
if (app)
|
|
209
|
+
parts.push(`Devin Desktop found (${app.replace(home, "~")}): its Cascade hooks pass a transcript to one event only, after a response, too late to steer it`);
|
|
210
|
+
return { label, status: "skip", detail: `${parts.join("; ")}. Not supported yet; the MCP tools work in any MCP client` };
|
|
211
|
+
}
|
|
142
212
|
/** Claude Code's disableAllHooks: when true, no hook of anyone's runs. */
|
|
143
213
|
function hooksDisabled(layers) {
|
|
144
214
|
return layers.reduce((off, s) => (typeof s.disableAllHooks === "boolean" ? s.disableAllHooks : off), false);
|
|
@@ -234,6 +304,7 @@ export async function runDoctor() {
|
|
|
234
304
|
? { label: "Compaction hook", status: "ok", detail: "PreCompact: each compaction's summary keeps the session's files, open tasks, your instructions and failing commands" }
|
|
235
305
|
: { label: "Compaction hook", status: "warn", detail: "not registered: compactions use generic instructions; run context-doctor install" });
|
|
236
306
|
}
|
|
307
|
+
checks.push(modelSwitchCheck(settings, plugin));
|
|
237
308
|
}
|
|
238
309
|
catch (e) {
|
|
239
310
|
checks.push({ label: "Every-prompt hook", status: "fail", detail: `settings.json unreadable (${e.message})` });
|
|
@@ -287,6 +358,19 @@ export async function runDoctor() {
|
|
|
287
358
|
catch (e) {
|
|
288
359
|
checks.push({ label: "Codex hook", status: "fail", detail: `~/.codex/hooks.json unreadable (${e.message})` });
|
|
289
360
|
}
|
|
361
|
+
// Autopilot reaches Codex through openai_base_url (OPENAI_BASE_URL no
|
|
362
|
+
// longer routes it), and only on an API key.
|
|
363
|
+
const route = codexRouting(homedir());
|
|
364
|
+
const local = route.baseUrl && /^http:\/\/(127\.0\.0\.1|localhost):\d+\/v1\/?$/.test(route.baseUrl);
|
|
365
|
+
if (local && route.auth !== "apikey") {
|
|
366
|
+
checks.push({ label: "Codex autopilot", status: "warn", detail: `openai_base_url points at ${route.baseUrl} while Codex signs in ${route.auth === "chatgpt" ? "with ChatGPT" : "without an API key"}: autopilot routes Codex only on an API key (the proxy relays ChatGPT traffic unedited meanwhile); remove the line from ~/.codex/config.toml` });
|
|
367
|
+
}
|
|
368
|
+
else if (local) {
|
|
369
|
+
checks.push({ label: "Codex autopilot", status: "ok", detail: `Codex (API key) sends its requests through ${route.baseUrl}` });
|
|
370
|
+
}
|
|
371
|
+
else if (process.env.OPENAI_BASE_URL && route.auth === "apikey") {
|
|
372
|
+
checks.push({ label: "Codex autopilot", status: "warn", detail: "OPENAI_BASE_URL is set, but Codex no longer reads it: `context-doctor autopilot on` sets openai_base_url in ~/.codex/config.toml" });
|
|
373
|
+
}
|
|
290
374
|
}
|
|
291
375
|
else {
|
|
292
376
|
checks.push({ label: "Codex", status: "skip", detail: "not detected (ChatGPT's Codex agent, IDE extension or CLI)" });
|
|
@@ -324,19 +408,33 @@ export async function runDoctor() {
|
|
|
324
408
|
else {
|
|
325
409
|
checks.push({ label: "Gemini CLI", status: "skip", detail: "not detected" });
|
|
326
410
|
}
|
|
327
|
-
|
|
328
|
-
//
|
|
411
|
+
checks.push(devinCheck());
|
|
412
|
+
// Cursor: its agent gets the guidance through native hooks (the Claude
|
|
413
|
+
// Code hook it also runs cannot add context there). Whether the text then
|
|
414
|
+
// reaches the model depends on the Cursor version, and Cursor logs only
|
|
415
|
+
// that the hook ran, so this says what is known rather than "✓".
|
|
329
416
|
if (existsSync(join(homedir(), ".cursor"))) {
|
|
330
417
|
const hooksPath = join(homedir(), ".cursor", "hooks.json");
|
|
331
418
|
try {
|
|
332
419
|
const hooks = readConfig(hooksPath, ["version"]) ?? {};
|
|
333
|
-
const
|
|
420
|
+
const oursIn = (event) => (hooks.hooks?.[event] ?? []).map((e) => e.command ?? "").find((c) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(c));
|
|
421
|
+
const ours = oursIn("postToolUse");
|
|
334
422
|
const missing = ours ? hookBinaryMissing(ours) : undefined;
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
423
|
+
const fallbacks = CURSOR_HOOK_EVENTS.filter((e) => !oursIn(e));
|
|
424
|
+
if (!ours)
|
|
425
|
+
checks.push(missingHook("Cursor hook", cursorMcp));
|
|
426
|
+
else if (missing)
|
|
427
|
+
checks.push({ label: "Cursor hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` });
|
|
428
|
+
else {
|
|
429
|
+
const v = cursorVersion();
|
|
430
|
+
const delivered = v ? versionAtLeast(v, 3, 17) : undefined;
|
|
431
|
+
const where = `registered in ~/.cursor/hooks.json for ${CURSOR_HOOK_EVENTS.filter((e) => oursIn(e)).join(", ")}`;
|
|
432
|
+
checks.push(delivered === false
|
|
433
|
+
? { label: "Cursor hook", status: "warn", detail: `${where}, but Cursor ${v} drops hook additional_context before the model (confirmed by Cursor staff, March 2026; reported through 3.10): update Cursor to 3.17 or later; until then the MCP tools are the way in` }
|
|
434
|
+
: fallbacks.length
|
|
435
|
+
? { label: "Cursor hook", status: "warn", detail: `${where}; re-run context-doctor install to add ${fallbacks.join(" and ")} (the fallbacks Cursor 3.17+ delivers)` }
|
|
436
|
+
: { label: "Cursor hook", status: "ok", detail: `${where}. ${v ? `Cursor ${v}` : "Cursor 3.17 and later"} attaches their additional_context to the tool result; Cursor does not log what the model saw: in a long chat, ask its agent what context-doctor said` });
|
|
437
|
+
}
|
|
340
438
|
}
|
|
341
439
|
catch (e) {
|
|
342
440
|
checks.push({ label: "Cursor hook", status: "fail", detail: `~/.cursor/hooks.json unreadable (${e.message})` });
|
|
@@ -485,3 +583,28 @@ export async function runDoctor() {
|
|
|
485
583
|
? `No problems; ${warns.length} note(s) marked ! above.`
|
|
486
584
|
: "All good.");
|
|
487
585
|
}
|
|
586
|
+
/** "3.18.25" >= major.minor. */
|
|
587
|
+
function versionAtLeast(v, major, minor) {
|
|
588
|
+
const m = /^(\d+)\.(\d+)/.exec(v);
|
|
589
|
+
if (!m)
|
|
590
|
+
return true;
|
|
591
|
+
return Number(m[1]) > major || (Number(m[1]) === major && Number(m[2]) >= minor);
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* The Cursor version here: the newest one that ran the hook (its input
|
|
595
|
+
* carries cursor_version, on every platform), else the macOS app bundle.
|
|
596
|
+
*/
|
|
597
|
+
export function cursorVersion() {
|
|
598
|
+
const fromLedger = readLedger().reverse().find((e) => typeof e.cv === "string")?.cv;
|
|
599
|
+
if (fromLedger)
|
|
600
|
+
return fromLedger;
|
|
601
|
+
for (const plist of ["/Applications/Cursor.app/Contents/Info.plist", join(homedir(), "Applications", "Cursor.app", "Contents", "Info.plist")]) {
|
|
602
|
+
try {
|
|
603
|
+
const m = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(readFileSync(plist, "utf8"));
|
|
604
|
+
if (m)
|
|
605
|
+
return m[1];
|
|
606
|
+
}
|
|
607
|
+
catch { /* not there */ }
|
|
608
|
+
}
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
package/dist/hook.d.ts
CHANGED
|
@@ -11,4 +11,22 @@
|
|
|
11
11
|
* Registered by `context-doctor install` under hooks.UserPromptSubmit in
|
|
12
12
|
* ~/.claude/settings.json; removed by `context-doctor uninstall`.
|
|
13
13
|
*/
|
|
14
|
+
/** The hook input fields this module reads, as their types: anything else is dropped. */
|
|
15
|
+
export interface HookInput {
|
|
16
|
+
session_id?: string;
|
|
17
|
+
transcript_path?: string;
|
|
18
|
+
cwd?: string;
|
|
19
|
+
hook_event_name?: string;
|
|
20
|
+
conversation_id?: string;
|
|
21
|
+
model?: string;
|
|
22
|
+
workspace_roots?: string[];
|
|
23
|
+
cursor_version?: string;
|
|
24
|
+
[key: string]: unknown;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Hook input with the string fields checked. A number or object where a path
|
|
28
|
+
* belongs reached fs.existsSync, which on current Node prints a
|
|
29
|
+
* DeprecationWarning into the user's session (and will throw on a later one).
|
|
30
|
+
*/
|
|
31
|
+
export declare function hookInput(raw: unknown): HookInput;
|
|
14
32
|
export declare function runHook(): Promise<void>;
|
package/dist/hook.js
CHANGED
|
@@ -21,9 +21,10 @@ import { profileConversation } from "./profile.js";
|
|
|
21
21
|
import { parseSessionFile } from "./session.js";
|
|
22
22
|
import { formatTokens, CHARS_PER_TOKEN, LARGEST_WINDOW } from "./tokens.js";
|
|
23
23
|
import { ensureProxyUp } from "./autopilot.js";
|
|
24
|
-
import { detectColdResume, renderColdResume, renderColdResumeNotice, sessionWriteMultiplier } from "./coldresume.js";
|
|
24
|
+
import { autoCompactsAt, detectColdResume, renderColdResume, renderColdResumeNotice, resumeVerdict, sessionWriteMultiplier, withResumeVerdict } from "./coldresume.js";
|
|
25
25
|
import { formatUsd, pricingFor } from "./pricing.js";
|
|
26
26
|
import { checkBudget, loadConfig } from "./config.js";
|
|
27
|
+
import { modelSwitchMessage } from "./modelswitch.js";
|
|
27
28
|
import { compactFacts, compactInstructions } from "./precompact.js";
|
|
28
29
|
/** Default nudge threshold; a project budget or env var can lower/raise it. */
|
|
29
30
|
const DEFAULT_WARN_TOKENS = 80_000;
|
|
@@ -134,15 +135,35 @@ async function readStdin() {
|
|
|
134
135
|
chunks.push(chunk);
|
|
135
136
|
return Buffer.concat(chunks).toString("utf8");
|
|
136
137
|
}
|
|
137
|
-
function settingsHasOurHook() {
|
|
138
|
+
function settingsHasOurHook(event = "UserPromptSubmit") {
|
|
138
139
|
try {
|
|
139
|
-
|
|
140
|
+
// Per event: a settings.json that has our prompt hook but not our
|
|
141
|
+
// PreModelSwitch one (install skips it next to an older Claude Code)
|
|
142
|
+
// must not silence the plugin's copy of the event it lacks.
|
|
143
|
+
const hooks = JSON.parse(readFileSync(join(homedir(), ".claude", "settings.json"), "utf8"))?.hooks?.[event || "UserPromptSubmit"];
|
|
140
144
|
return JSON.stringify(hooks ?? "").includes("context-doctor");
|
|
141
145
|
}
|
|
142
146
|
catch {
|
|
143
147
|
return false;
|
|
144
148
|
}
|
|
145
149
|
}
|
|
150
|
+
/**
|
|
151
|
+
* Hook input with the string fields checked. A number or object where a path
|
|
152
|
+
* belongs reached fs.existsSync, which on current Node prints a
|
|
153
|
+
* DeprecationWarning into the user's session (and will throw on a later one).
|
|
154
|
+
*/
|
|
155
|
+
export function hookInput(raw) {
|
|
156
|
+
const obj = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
157
|
+
const out = { ...obj };
|
|
158
|
+
for (const key of ["session_id", "transcript_path", "cwd", "hook_event_name", "conversation_id", "model", "cursor_version"]) {
|
|
159
|
+
if (typeof obj[key] !== "string" || obj[key] === "")
|
|
160
|
+
delete out[key];
|
|
161
|
+
}
|
|
162
|
+
out.workspace_roots = Array.isArray(obj.workspace_roots) ? obj.workspace_roots.filter((r) => typeof r === "string") : undefined;
|
|
163
|
+
if (out.workspace_roots === undefined)
|
|
164
|
+
delete out.workspace_roots;
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
146
167
|
export async function runHook() {
|
|
147
168
|
// A hook must never break the user's prompt: any failure exits silently.
|
|
148
169
|
try {
|
|
@@ -152,12 +173,31 @@ export async function runHook() {
|
|
|
152
173
|
const heal = ensureProxyUp().catch(() => undefined);
|
|
153
174
|
// Installed both ways (plugin and `context-doctor install`)? The plugin
|
|
154
175
|
// copy stays silent so the model is told once, not twice.
|
|
155
|
-
|
|
176
|
+
const input = hookInput(JSON.parse(await readStdin()));
|
|
177
|
+
if (process.env.CLAUDE_PLUGIN_ROOT && settingsHasOurHook(input.hook_event_name)) {
|
|
156
178
|
await heal;
|
|
157
179
|
return;
|
|
158
180
|
}
|
|
159
|
-
const input = JSON.parse(await readStdin());
|
|
160
181
|
await heal;
|
|
182
|
+
// Before a model switch: what re-writing this context into the new
|
|
183
|
+
// model's cache costs, shown to the user. Never blocks (no decision, exit
|
|
184
|
+
// 0); a hook that failed or timed out here would block the switch, so
|
|
185
|
+
// this path only reads the transcript's tail.
|
|
186
|
+
if (input.hook_event_name === "PreModelSwitch") {
|
|
187
|
+
const message = modelSwitchMessage(input);
|
|
188
|
+
if (message)
|
|
189
|
+
process.stdout.write(JSON.stringify({ systemMessage: message }) + "\n");
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
// A resumed session: Claude Code says whether its cache expired and what
|
|
193
|
+
// re-caching costs. Kept for the first prompt, which decides the offer
|
|
194
|
+
// (an offer before any message would come before the rebuild it prices).
|
|
195
|
+
if (input.hook_event_name === "SessionStart") {
|
|
196
|
+
const verdict = resumeVerdict(input);
|
|
197
|
+
if (verdict && input.session_id)
|
|
198
|
+
writeSessionState(input.session_id, { ...readSessionState(input.session_id), rv: verdict });
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
161
201
|
// Before a compaction: tell the summary what this session cannot lose.
|
|
162
202
|
// Claude Code adds a PreCompact hook's plain-text output to the
|
|
163
203
|
// compaction's instructions (auto and manual alike).
|
|
@@ -178,7 +218,9 @@ export async function runHook() {
|
|
|
178
218
|
// Cursor marks every hook input with cursor_version; any of its events but
|
|
179
219
|
// postToolUse would only spend the once-per-growth warning on output Cursor
|
|
180
220
|
// drops.
|
|
181
|
-
|
|
221
|
+
// postToolUseFailure and sessionStart carry additional_context too: the
|
|
222
|
+
// first serves a chat whose tool calls fail, the second a resumed heavy chat.
|
|
223
|
+
const cursor = input.hook_event_name === "postToolUse" || input.hook_event_name === "postToolUseFailure" || input.hook_event_name === "sessionStart";
|
|
182
224
|
if (input.hook_event_name === "beforeSubmitPrompt" || (input.cursor_version && !cursor))
|
|
183
225
|
return;
|
|
184
226
|
const transcriptPath = input.transcript_path;
|
|
@@ -202,7 +244,15 @@ export async function runHook() {
|
|
|
202
244
|
// Once per idle period; the tail read is ~1 ms and only on large files.
|
|
203
245
|
const notes = [];
|
|
204
246
|
let notice;
|
|
205
|
-
|
|
247
|
+
// Silent when Claude Code compacts this very prompt itself (the context
|
|
248
|
+
// is past its auto-compact window, e.g. one set smaller since): an offer
|
|
249
|
+
// would arrive after the compaction it proposes. Below the window the
|
|
250
|
+
// note tells the model to stay quiet if a compaction came first (seen
|
|
251
|
+
// once in 516 cold returns: a 964k session compacted, then the reply
|
|
252
|
+
// offered /compact on the fresh summary).
|
|
253
|
+
let cold = withResumeVerdict(detectColdResume(transcriptPath), prev.rv);
|
|
254
|
+
if (cold && cold.tokens >= (autoCompactsAt(cold.model ?? input.model) ?? Infinity))
|
|
255
|
+
cold = undefined;
|
|
206
256
|
let cr = prev.cr;
|
|
207
257
|
if (cold && cold.lastReplyAt !== prev.cr) {
|
|
208
258
|
notes.push(renderColdResume(cold));
|
|
@@ -253,7 +303,7 @@ export async function runHook() {
|
|
|
253
303
|
// warning needed 1.4x a size the session no longer had (seen: warned at
|
|
254
304
|
// 843k, compacted, then regrew to 809k without a word).
|
|
255
305
|
writeSessionState(sessionId, { t: shouldWarn ? liveTokens : Math.min(prev.t, liveTokens), b: sizeBytes, cr });
|
|
256
|
-
recordLedger({ ev: "check", sid: sessionId.slice(0, 12), tok: liveTokens, warn: shouldWarn });
|
|
306
|
+
recordLedger({ ev: "check", sid: sessionId.slice(0, 12), tok: liveTokens, warn: shouldWarn, ...(input.cursor_version ? { cv: input.cursor_version } : {}) });
|
|
257
307
|
if (!shouldWarn) {
|
|
258
308
|
emit(notes);
|
|
259
309
|
return;
|
package/dist/impact.js
CHANGED
|
@@ -15,6 +15,20 @@ import { profileConversation } from "./profile.js";
|
|
|
15
15
|
import { formatTokens } from "./tokens.js";
|
|
16
16
|
import { formatUsd, inputCostUsd, pricingFor } from "./pricing.js";
|
|
17
17
|
import { coldResumeFollowThrough } from "./coldresume.js";
|
|
18
|
+
/**
|
|
19
|
+
* The dollar figure for `tokens`, of which only `priced` have a model with a
|
|
20
|
+
* known price. Pricing the whole total at the priced part's rate, or showing
|
|
21
|
+
* the priced part's dollars beside the whole total unlabeled, overstated it.
|
|
22
|
+
*/
|
|
23
|
+
function pricedNote(usd, priced, tokens) {
|
|
24
|
+
if (tokens <= 0)
|
|
25
|
+
return "";
|
|
26
|
+
if (priced <= 0 || usd <= 0)
|
|
27
|
+
return " (no known price for these models)";
|
|
28
|
+
if (priced >= tokens)
|
|
29
|
+
return ` ≈ ${formatUsd(usd)}`;
|
|
30
|
+
return ` ≈ ${formatUsd(usd)} on the ${formatTokens(priced)} with a known price; ${formatTokens(tokens - priced)} unpriced`;
|
|
31
|
+
}
|
|
18
32
|
/** Sessions larger than this are skipped in the report (keeps it snappy). */
|
|
19
33
|
const MAX_SESSION_BYTES = 30 * 1024 * 1024;
|
|
20
34
|
/**
|
|
@@ -105,12 +119,16 @@ export async function buildImpactReport(proxyPort = 8787) {
|
|
|
105
119
|
const optimizeSaved = optimizes.reduce((s, e) => s + (e.saved ?? 0), 0) + carried.optimizeSaved;
|
|
106
120
|
const savedByFamily = new Map();
|
|
107
121
|
let optimizeUsd = 0;
|
|
122
|
+
/** The part of optimizeSaved whose model has a known price: the dollars cover only this. */
|
|
123
|
+
let optimizePriced = 0;
|
|
108
124
|
for (const e of optimizes) {
|
|
109
125
|
const family = /claude/i.test(e.model ?? "") ? "claude" : /gpt|^o\d/i.test(e.model ?? "") ? "gpt" : "other";
|
|
110
126
|
savedByFamily.set(family, (savedByFamily.get(family) ?? 0) + (e.saved ?? 0));
|
|
111
127
|
const pricing = pricingFor(e.model);
|
|
112
|
-
if (pricing && e.saved)
|
|
128
|
+
if (pricing && e.saved) {
|
|
113
129
|
optimizeUsd += inputCostUsd(e.saved, pricing);
|
|
130
|
+
optimizePriced += e.saved;
|
|
131
|
+
}
|
|
114
132
|
}
|
|
115
133
|
const proxy = await fetchProxyStats(proxyPort);
|
|
116
134
|
// Persisted checkpoints cover earlier runs AND the live one's past minutes;
|
|
@@ -141,7 +159,7 @@ export async function buildImpactReport(proxyPort = 8787) {
|
|
|
141
159
|
.join(", ");
|
|
142
160
|
lines.push(` · optimizations applied via CLI/chat tools (exact): ${formatTokens(optimizeSaved)} over ${optimizes.length} run(s)` +
|
|
143
161
|
(familyNote ? ` [${familyNote}]` : "") +
|
|
144
|
-
(optimizeUsd
|
|
162
|
+
pricedNote(optimizeUsd, optimizePriced, optimizeSaved));
|
|
145
163
|
lines.push("");
|
|
146
164
|
lines.push(`Sessions that got smaller after a hygiene warning: ${formatTokens(totalReduction)} tokens`);
|
|
147
165
|
lines.push(" (mostly compaction, by you or Claude Code; not counted above, because a warning");
|
|
@@ -182,6 +200,8 @@ export async function buildImpactReport(proxyPort = 8787) {
|
|
|
182
200
|
let totalTokens = 0;
|
|
183
201
|
let totalWaste = 0;
|
|
184
202
|
let totalWasteUsd = 0;
|
|
203
|
+
/** Recoverable tokens in sessions whose model has a known price: the dollars cover only these. */
|
|
204
|
+
let pricedWaste = 0;
|
|
185
205
|
for (const s of sessions) {
|
|
186
206
|
try {
|
|
187
207
|
const parsed = parseSessionFile(s.path);
|
|
@@ -193,8 +213,10 @@ export async function buildImpactReport(proxyPort = 8787) {
|
|
|
193
213
|
// Claude Code sessions run on the prompt cache, so recoverable tokens
|
|
194
214
|
// cost the cached rate on each message, not the full input rate.
|
|
195
215
|
const pr = pricingFor(p.model);
|
|
196
|
-
if (p.cost && pr)
|
|
216
|
+
if (p.cost && pr) {
|
|
197
217
|
totalWasteUsd += p.cost.savingsPerCallUsd * (pr.cacheReadPerM / pr.inputPerM);
|
|
218
|
+
pricedWaste += p.totalEstSavings;
|
|
219
|
+
}
|
|
198
220
|
const wastePct = p.totalTokens > 0 ? Math.round((p.totalEstSavings / p.totalTokens) * 100) : 0;
|
|
199
221
|
// Ledger sids are the session UUID's first 12 chars (= filename prefix).
|
|
200
222
|
const sid = (s.path.split(/[\\/]/).pop() ?? "").slice(0, 12);
|
|
@@ -210,7 +232,13 @@ export async function buildImpactReport(proxyPort = 8787) {
|
|
|
210
232
|
}
|
|
211
233
|
lines.push("");
|
|
212
234
|
lines.push(`Across these sessions: ~${formatTokens(totalTokens)} tokens held; ~${formatTokens(totalWaste)} still recoverable` +
|
|
213
|
-
(totalWasteUsd > 0
|
|
235
|
+
(totalWasteUsd > 0
|
|
236
|
+
? pricedWaste < totalWaste
|
|
237
|
+
? ` (≈ ${formatUsd(totalWasteUsd)} of input per message on the ~${formatTokens(pricedWaste)} with a known price; ~${formatTokens(totalWaste - pricedWaste)} unpriced)`
|
|
238
|
+
: ` (≈ ${formatUsd(totalWasteUsd)} of input per message sent in them)`
|
|
239
|
+
: totalWaste > 0
|
|
240
|
+
? " (no known price for these models)"
|
|
241
|
+
: ""));
|
|
214
242
|
}
|
|
215
243
|
lines.push("");
|
|
216
244
|
lines.push("What no report can show: tokens Claude AVOIDED adding thanks to the standing");
|
package/dist/index.d.ts
CHANGED