context-doctor 0.34.0 → 0.35.1
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 +5 -2
- package/dist/autoclear.d.ts +5 -2
- package/dist/autoclear.js +57 -19
- package/dist/cachemisses.d.ts +88 -0
- package/dist/cachemisses.js +325 -0
- package/dist/cacheplan.d.ts +1 -1
- package/dist/cacheplan.js +47 -3
- package/dist/cli.js +63 -16
- package/dist/compactquality.js +9 -1
- package/dist/config.d.ts +11 -0
- package/dist/config.js +117 -4
- package/dist/dashboard.js +15 -1
- package/dist/doctor.d.ts +18 -0
- package/dist/doctor.js +71 -1
- package/dist/hook.d.ts +18 -0
- package/dist/hook.js +35 -4
- package/dist/impact.js +32 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +15 -0
- package/dist/install.js +105 -26
- package/dist/mcp.js +52 -49
- 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 +9 -1
- package/dist/proxy.js +45 -9
- package/dist/report.js +8 -2
- package/dist/savings.d.ts +1 -1
- package/dist/savings.js +6 -1
- 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/cacheplan.js
CHANGED
|
@@ -149,10 +149,54 @@ function positions(blocks) {
|
|
|
149
149
|
});
|
|
150
150
|
return out;
|
|
151
151
|
}
|
|
152
|
+
/** Gemini text in a request: the text of every part (attachments as a nominal size). */
|
|
153
|
+
function geminiTokens(req, model) {
|
|
154
|
+
const parts = [];
|
|
155
|
+
const sys = req.systemInstruction ?? req.system_instruction;
|
|
156
|
+
if (typeof sys === "string")
|
|
157
|
+
parts.push({ text: sys });
|
|
158
|
+
else if (Array.isArray(sys?.parts))
|
|
159
|
+
parts.push(...sys.parts);
|
|
160
|
+
for (const c of Array.isArray(req.contents) ? req.contents : [])
|
|
161
|
+
if (Array.isArray(c?.parts))
|
|
162
|
+
parts.push(...c.parts);
|
|
163
|
+
let n = req.tools ? estimateTokens(JSON.stringify(req.tools), model) : 0;
|
|
164
|
+
for (const p of parts) {
|
|
165
|
+
if (typeof p?.text === "string")
|
|
166
|
+
n += estimateTokens(p.text, model);
|
|
167
|
+
else if (p?.inlineData || p?.fileData)
|
|
168
|
+
n += 258; // nominal: a small image on Gemini 2.x; tiling and Gemini 3's media_resolution change it
|
|
169
|
+
else
|
|
170
|
+
n += estimateTokens(JSON.stringify(p ?? ""), model);
|
|
171
|
+
}
|
|
172
|
+
return n;
|
|
173
|
+
}
|
|
174
|
+
/** Smallest prefix Gemini caches implicitly (Gemini API caching docs, Oct 2026: 4,096 for Gemini 3; Vertex lists up to 6,144 for some). */
|
|
175
|
+
const GEMINI_CACHE_MINIMUM = 4096;
|
|
152
176
|
export function planCache(request, calls = 10, modelOverride, opts = {}) {
|
|
153
|
-
|
|
177
|
+
// A copy: apply() places breakpoints on the request it returns, and the
|
|
178
|
+
// caller's own object (the library takes one) must come back as it was.
|
|
179
|
+
const req = (typeof request === "string" ? JSON.parse(request) : structuredClone(request));
|
|
180
|
+
if (!req || typeof req !== "object" || Array.isArray(req))
|
|
181
|
+
throw new Error("expected a request object ({model, messages, …})");
|
|
154
182
|
const model = modelOverride ?? (typeof req.model === "string" ? req.model : undefined);
|
|
155
183
|
const notes = [];
|
|
184
|
+
// Gemini: `contents`, or a gemini model. Read as Anthropic it was ~0 tokens
|
|
185
|
+
// with breakpoints Gemini has no field for.
|
|
186
|
+
if (Array.isArray(req.contents) || /gemini/i.test(model ?? "")) {
|
|
187
|
+
const total = geminiTokens(req, model);
|
|
188
|
+
notes.push(`Gemini caches implicitly (on by default from Gemini 2.5): a request whose prefix matches an earlier one and is at least ~${formatTokens(GEMINI_CACHE_MINIMUM)} tokens (Gemini 3 on the Gemini API; Vertex lists up to 6,144 for some models) bills that prefix at the cached rate, about 10% of input. There are no markers to place.`, "What you control is order: keep systemInstruction, tools and shared documents first and byte-identical between calls, and put the per-call question last.", "For a guaranteed discount on a large prefix reused for a while, create an explicit cache (cachedContents.create; default TTL 60 minutes, storage billed per hour) and pass its name as `cachedContent` in each request.");
|
|
189
|
+
if (typeof req.cachedContent === "string" || typeof req.cached_content === "string") {
|
|
190
|
+
notes.push("This request already uses an explicit cache (cachedContent): its cached part bills at the cached rate.");
|
|
191
|
+
}
|
|
192
|
+
else if (total < GEMINI_CACHE_MINIMUM) {
|
|
193
|
+
notes.push(`The whole request is ~${formatTokens(total)} tokens, under the implicit-caching minimum: caching cannot help until it grows.`);
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
plan: { provider: "gemini", model, totalTokens: total, minCacheable: GEMINI_CACHE_MINIMUM, existing: [], plan: [], cachedTokens: 0, calls, notes },
|
|
197
|
+
apply: () => req,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
156
200
|
const isOpenAI = Array.isArray(req.input) || (Array.isArray(req.messages) && req.messages.some((m) => m?.role === "system" || m?.role === "developer" || m?.role === "tool"));
|
|
157
201
|
if (isOpenAI || /gpt|^o\d/i.test(model ?? "")) {
|
|
158
202
|
const text = JSON.stringify(req.tools ?? "") + JSON.stringify(req.messages ?? req.input ?? "");
|
|
@@ -269,8 +313,8 @@ export function planCache(request, calls = 10, modelOverride, opts = {}) {
|
|
|
269
313
|
}
|
|
270
314
|
export function renderCachePlan(p) {
|
|
271
315
|
const out = ["CACHE PLAN", "═".repeat(56)];
|
|
272
|
-
out.push(`${p.provider === "openai" ? "OpenAI" : "Anthropic"} request${p.model ? ` for ${p.model}` : ""}: ~${formatTokens(p.totalTokens)} tokens.`);
|
|
273
|
-
if (p.provider === "openai") {
|
|
316
|
+
out.push(`${p.provider === "openai" ? "OpenAI" : p.provider === "gemini" ? "Gemini" : "Anthropic"} request${p.model ? ` for ${p.model}` : ""}: ~${formatTokens(p.totalTokens)} tokens.`);
|
|
317
|
+
if (p.provider === "openai" || p.provider === "gemini") {
|
|
274
318
|
out.push("", ...p.notes.map((n) => `• ${n}`));
|
|
275
319
|
return out.join("\n");
|
|
276
320
|
}
|
package/dist/cli.js
CHANGED
|
@@ -39,7 +39,7 @@ import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
|
|
|
39
39
|
import { runWatch } from "./watch.js";
|
|
40
40
|
import { exactTokenCount } from "./exact.js";
|
|
41
41
|
import { modelFamily, recordCalibration } from "./calibration.js";
|
|
42
|
-
import { checkBudget, loadConfig } from "./config.js";
|
|
42
|
+
import { checkBudget, loadConfig, sanitizeRoutes, validateRoutes } from "./config.js";
|
|
43
43
|
import { startDashboard } from "./dashboard.js";
|
|
44
44
|
import { listCursorChats, parseCursorChat } from "./cursor.js";
|
|
45
45
|
import { analyzeCacheUsage, renderCacheReport } from "./cache.js";
|
|
@@ -51,6 +51,7 @@ import { ciReport, renderCiMarkdown, renderCiText } from "./ci.js";
|
|
|
51
51
|
import { renderReads, repeatedReads } from "./reads.js";
|
|
52
52
|
import { costPerTask, renderTasks } from "./tasks.js";
|
|
53
53
|
import { planCache, renderCachePlan } from "./cacheplan.js";
|
|
54
|
+
import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses } from "./cachemisses.js";
|
|
54
55
|
import { renderPayback, subagentPayback } from "./subagentpay.js";
|
|
55
56
|
import { compactionQuality, renderCompactionQuality } from "./compactquality.js";
|
|
56
57
|
const HELP = `context-doctor — profile and optimize LLM context windows
|
|
@@ -91,6 +92,9 @@ Measure:
|
|
|
91
92
|
cost, and whether a CLAUDE.md summary or pack pays
|
|
92
93
|
context-doctor compactions [--days n] Do sessions work worse right after compacting? Re-reads,
|
|
93
94
|
tool errors and your corrections, before vs after
|
|
95
|
+
context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
|
|
96
|
+
still warm: priced, by model and context size, with
|
|
97
|
+
the cause where the transcript shows one
|
|
94
98
|
context-doctor accuracy Measure the token heuristic against the API's own
|
|
95
99
|
counts recorded in your transcripts (--limit n)
|
|
96
100
|
context-doctor diff <before> <after> Compare two profiles: what moved, which findings
|
|
@@ -183,12 +187,15 @@ Options:
|
|
|
183
187
|
--max-tool-tokens <n> (optimize) Token budget for trimmed tool results (default 300)
|
|
184
188
|
--limit <n> (accuracy, session --list, reads, tasks, subagents) How many to sample
|
|
185
189
|
or list
|
|
186
|
-
--days <n> (savings, compact-window, overhead, reads, tasks, subagents, compactions
|
|
190
|
+
--days <n> (savings, compact-window, overhead, reads, tasks, subagents, compactions,
|
|
191
|
+
cache-misses)
|
|
187
192
|
Days of history to read (default 30; compactions 60)
|
|
188
193
|
-q, --query <text> (pack) The question to rank chunks against
|
|
189
194
|
--max-tokens <n> (pack) Token budget (default 4000); (ci) fail over this many tokens
|
|
190
195
|
--chunk-tokens <n> (pack) Largest chunk, in tokens (default 400)
|
|
191
196
|
--ids <a#2,b#5> (pack) Return these chunks by id
|
|
197
|
+
--include-secrets (pack) Also pack .env, .npmrc, private keys and other credential files,
|
|
198
|
+
and paths under ~/.ssh, ~/.aws and similar (skipped by default)
|
|
192
199
|
--min-tokens <n> (overhead split) Smallest section to move, in tokens (default 400)
|
|
193
200
|
--requests-per-day <n> (ci --markdown) Price the change at this many requests a day
|
|
194
201
|
--check <cmd> (experiment) Command whose exit code is the pass/fail for each arm
|
|
@@ -251,7 +258,7 @@ function usageError(message) {
|
|
|
251
258
|
const COMMANDS = [
|
|
252
259
|
"analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
|
|
253
260
|
"instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
|
|
254
|
-
"experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "subagents", "tasks",
|
|
261
|
+
"experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "subagents", "tasks",
|
|
255
262
|
"reads", "pack", "watch", "help", "version",
|
|
256
263
|
];
|
|
257
264
|
/** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
|
|
@@ -299,6 +306,7 @@ const FLAGS = [
|
|
|
299
306
|
{ names: ["--explicit"], set: (a) => { a.explicit = true; } },
|
|
300
307
|
{ names: ["--semantic"], set: (a) => { a.semantic = a.semantic || true; } },
|
|
301
308
|
{ names: ["--embed-model"], value: "text", set: (a, v) => { a.semantic = v; } },
|
|
309
|
+
{ names: ["--include-secrets"], set: (a) => { a.includeSecrets = true; } },
|
|
302
310
|
{ names: ["--base"], value: "text", set: (a, v) => { a.base = v; } },
|
|
303
311
|
{ names: ["--markdown"], set: (a) => { a.markdown = true; } },
|
|
304
312
|
{ names: ["--max-increase"], value: "number", num: { min: 0, integer: true }, set: (a, v) => { a.maxIncrease = v; } },
|
|
@@ -398,9 +406,15 @@ function applyBudgetGate(overBudget, failOverBudget) {
|
|
|
398
406
|
}
|
|
399
407
|
}
|
|
400
408
|
function readInput(file) {
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
409
|
+
return stripBom(readFileSync(file === "-" ? 0 : file, "utf8"));
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* A UTF-8 byte-order mark (Windows editors, PowerShell's Out-File) is not
|
|
413
|
+
* part of the text: left in, JSON.parse rejects the file and a valid
|
|
414
|
+
* conversation was reported as not being one.
|
|
415
|
+
*/
|
|
416
|
+
function stripBom(text) {
|
|
417
|
+
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
404
418
|
}
|
|
405
419
|
/** The installed package's version, read from its package.json so it cannot drift. */
|
|
406
420
|
function packageVersion() {
|
|
@@ -639,7 +653,15 @@ async function main() {
|
|
|
639
653
|
console.error(`Could not read session: ${e.message}`);
|
|
640
654
|
process.exit(1);
|
|
641
655
|
}
|
|
642
|
-
const
|
|
656
|
+
const sessionConversation = parseConversation(parsed.conversationJson);
|
|
657
|
+
// A file that is not a transcript parses to no messages. It used to print
|
|
658
|
+
// the warning inside a normal report and exit 0; analyze exits 1 for the
|
|
659
|
+
// same thing, and a script cannot tell a profile from a non-file otherwise.
|
|
660
|
+
if (sessionConversation.parseWarning) {
|
|
661
|
+
usageError(`Could not profile ${path} as a session: no conversation messages in it. ` +
|
|
662
|
+
"session reads Claude Code, Codex and Gemini CLI transcripts and ChatGPT exports; for a conversation JSON or a prompt, use analyze.");
|
|
663
|
+
}
|
|
664
|
+
const profile = profileConversation(sessionConversation, args.model ?? parsed.model);
|
|
643
665
|
if (args.json) {
|
|
644
666
|
console.log(JSON.stringify({ session: { path: parsed.path, title: parsed.title, ...(picked ? { picked: picked.how } : {}), toolTimings: parsed.toolTimings ?? [], subagents: subagentReport(path) }, profile }, null, 2));
|
|
645
667
|
// --json is what CI pipes, so the gate must hold here too (as it does for
|
|
@@ -711,9 +733,14 @@ async function main() {
|
|
|
711
733
|
const cwLine = cwReport.sessions > 0 && est
|
|
712
734
|
? { window: est.window, savedUsd: est.savedUsd, compactionsPerWeek: (est.compactions / cwReport.days) * 7, nowPerWeek: (cwReport.actualCompactions / cwReport.days) * 7, isCurrent: setWindow !== undefined }
|
|
713
735
|
: undefined;
|
|
736
|
+
const checking = progressLine("Checking for cache misses");
|
|
737
|
+
const misses = cacheMisses(args.days ?? 30, undefined, checking.tick);
|
|
738
|
+
checking.clear();
|
|
714
739
|
const on = existsSync(autopilotPaths().config);
|
|
715
|
-
if (args.json)
|
|
716
|
-
|
|
740
|
+
if (args.json) {
|
|
741
|
+
const { largest: _largest, ...missSummary } = misses;
|
|
742
|
+
console.log(JSON.stringify({ ...report, cacheMisses: missSummary }, null, 2));
|
|
743
|
+
}
|
|
717
744
|
else if (args.share) {
|
|
718
745
|
const text = renderShare(report);
|
|
719
746
|
console.log(text);
|
|
@@ -721,7 +748,7 @@ async function main() {
|
|
|
721
748
|
console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
|
|
722
749
|
}
|
|
723
750
|
else {
|
|
724
|
-
console.log(renderSavings(report, on, cwLine));
|
|
751
|
+
console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined));
|
|
725
752
|
if (!args.command)
|
|
726
753
|
console.log(`\nAll commands: ${selfCommand("--help")}`);
|
|
727
754
|
}
|
|
@@ -818,7 +845,14 @@ async function main() {
|
|
|
818
845
|
let routes = loadedRc.config.routes;
|
|
819
846
|
if (args.config) {
|
|
820
847
|
try {
|
|
821
|
-
|
|
848
|
+
const raw = JSON.parse(readFileSync(args.config, "utf8")).routes;
|
|
849
|
+
// The same rule as the rc file: a value the warning calls ignored is not applied.
|
|
850
|
+
if (raw !== undefined && !Array.isArray(raw))
|
|
851
|
+
console.error(`context-doctor: ${args.config}: routes must be an array — ignored`);
|
|
852
|
+
else if (Array.isArray(raw))
|
|
853
|
+
for (const w of validateRoutes(raw, args.config))
|
|
854
|
+
console.error(`context-doctor: ${w}`);
|
|
855
|
+
routes = sanitizeRoutes(raw);
|
|
822
856
|
}
|
|
823
857
|
catch (e) {
|
|
824
858
|
console.error(`Could not read --config ${args.config}: ${e.message}`);
|
|
@@ -826,7 +860,7 @@ async function main() {
|
|
|
826
860
|
}
|
|
827
861
|
}
|
|
828
862
|
startProxy({
|
|
829
|
-
routes
|
|
863
|
+
routes,
|
|
830
864
|
port: args.port,
|
|
831
865
|
host: args.host,
|
|
832
866
|
token: args.token ?? process.env.CONTEXT_DOCTOR_PROXY_TOKEN,
|
|
@@ -843,6 +877,13 @@ async function main() {
|
|
|
843
877
|
});
|
|
844
878
|
return; // server keeps the process alive
|
|
845
879
|
}
|
|
880
|
+
if (args.command === "cache-misses") {
|
|
881
|
+
const reading = progressLine("Reading your Claude Code transcripts");
|
|
882
|
+
const report = cacheMisses(args.days ?? 30, undefined, reading.tick);
|
|
883
|
+
reading.clear();
|
|
884
|
+
console.log(args.json ? JSON.stringify(report, null, 2) : renderCacheMisses(report));
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
846
887
|
if (args.command === "compactions") {
|
|
847
888
|
const days = args.days ?? 60;
|
|
848
889
|
const q = compactionQuality(days);
|
|
@@ -873,7 +914,9 @@ async function main() {
|
|
|
873
914
|
console.log(args.json ? JSON.stringify(result.plan, null, 2) : renderCachePlan(result.plan));
|
|
874
915
|
if (args.out) {
|
|
875
916
|
writeFileSync(args.out, JSON.stringify(result.apply(), null, 2));
|
|
876
|
-
console.error(
|
|
917
|
+
console.error(result.plan.plan.length
|
|
918
|
+
? `context-doctor: request with the planned breakpoints written to ${args.out}`
|
|
919
|
+
: `context-doctor: nothing to place; the request was written unchanged to ${args.out}`);
|
|
877
920
|
}
|
|
878
921
|
return;
|
|
879
922
|
}
|
|
@@ -945,9 +988,13 @@ async function main() {
|
|
|
945
988
|
console.error('usage: context-doctor pack <files|dirs...> --query "<question>" [--max-tokens 4000] [--ids a#2,b#5] [--json]');
|
|
946
989
|
process.exit(1);
|
|
947
990
|
}
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
991
|
+
// "-" is stdin, read once beside any other paths (it used to drop them silently).
|
|
992
|
+
const files = paths.filter((p) => p !== "-");
|
|
993
|
+
const { sources, skipped } = files.length
|
|
994
|
+
? readSources(files, { includeSecrets: args.includeSecrets, secretsHint: " (--include-secrets packs it)" })
|
|
995
|
+
: { sources: [], skipped: [] };
|
|
996
|
+
if (paths.includes("-"))
|
|
997
|
+
sources.unshift({ name: "stdin", text: stripBom(readFileSync(0, "utf8")) });
|
|
951
998
|
for (const s of skipped)
|
|
952
999
|
console.error(`context-doctor: skipped ${s}`);
|
|
953
1000
|
if (sources.length === 0)
|
package/dist/compactquality.js
CHANGED
|
@@ -202,8 +202,16 @@ export function renderCompactionQuality(q, days = 60) {
|
|
|
202
202
|
// Rounded: an average below 1k otherwise printed as "~237.46428571428572".
|
|
203
203
|
out.push(`Compacting forgets files: each compaction is followed by ~${formatTokens(Math.round(q.extraRereadTokensPerCompaction))} tokens of extra re-reads. compact-window charges that to every compaction it simulates.`);
|
|
204
204
|
}
|
|
205
|
+
// "No higher" only when neither went up: 0% before and 4.8% after is under
|
|
206
|
+
// the margin for "worse", and it is still higher, so it is said as such.
|
|
207
|
+
const higher = [
|
|
208
|
+
a.error - b.error > 0.0005 ? `tool errors ${pct(b.error)} → ${pct(a.error)}` : "",
|
|
209
|
+
a.correction - b.correction > 0.0005 ? `corrections ${pct(b.correction)} → ${pct(a.correction)}` : "",
|
|
210
|
+
].filter(Boolean);
|
|
205
211
|
out.push(worse
|
|
206
212
|
? "Sessions also work worse after compacting (more tool errors or corrections): compact less often, and let the PreCompact hook tell each summary what to keep."
|
|
207
|
-
:
|
|
213
|
+
: higher.length === 0
|
|
214
|
+
? "No sign of worse work after compacting: tool errors and corrections are no higher. The cost of compacting here is tokens, not quality."
|
|
215
|
+
: `Little sign of worse work after compacting: ${higher.join(" and ")}, up by less than the margin counted as worse here (3 points for errors, 5 for corrections). The cost of compacting here is mostly tokens.`);
|
|
208
216
|
return out.join("\n");
|
|
209
217
|
}
|
package/dist/config.d.ts
CHANGED
|
@@ -60,6 +60,17 @@ export interface LoadedConfig {
|
|
|
60
60
|
* doing nothing is the worst available behaviour.
|
|
61
61
|
*/
|
|
62
62
|
export declare function validateConfig(config: unknown, path: string): string[];
|
|
63
|
+
/** Warnings for the entries of a `routes` array (rc file or `proxy --config`). */
|
|
64
|
+
export declare function validateRoutes(routes: unknown[], path: string): string[];
|
|
65
|
+
/** The valid routes of a raw `routes` value, each with only its valid settings. */
|
|
66
|
+
export declare function sanitizeRoutes(value: unknown): ContextDoctorConfig["routes"];
|
|
67
|
+
/**
|
|
68
|
+
* The settings of a parsed rc file that are actually in effect: exactly the
|
|
69
|
+
* values validateConfig does not call ignored. Returning the raw object, as
|
|
70
|
+
* this once did, warned that `keepRecent: -5` was ignored and then applied
|
|
71
|
+
* it, which cut the live tool result in `optimize` and the proxy.
|
|
72
|
+
*/
|
|
73
|
+
export declare function sanitizeConfig(config: unknown): ContextDoctorConfig;
|
|
63
74
|
export declare function loadConfig(startDir?: string, onWarn?: (msg: string) => void): LoadedConfig;
|
|
64
75
|
export interface BudgetVerdict {
|
|
65
76
|
/** True when any configured limit is exceeded. */
|
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,9 +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>;
|
|
10
27
|
/**
|
|
11
28
|
* The Cursor version here: the newest one that ran the hook (its input
|
|
12
29
|
* carries cursor_version, on every platform), else the macOS app bundle.
|
|
13
30
|
*/
|
|
14
31
|
export declare function cursorVersion(): string | undefined;
|
|
32
|
+
export {};
|
package/dist/doctor.js
CHANGED
|
@@ -16,9 +16,10 @@ import { ledgerPath, readLedger } from "./ledger.js";
|
|
|
16
16
|
import { loadConfig } from "./config.js";
|
|
17
17
|
import { codexRouting } from "./codexroute.js";
|
|
18
18
|
import { CURSOR_HOOK_EVENTS } from "./install.js";
|
|
19
|
-
import { binOnPath, claudeInstalledCopies, codexMcpEntry, geminiCliPresent, geminiSettingsPath, isEmptyStub, isOurPluginKey, launcherNamesMissingPackage } from "./install.js";
|
|
19
|
+
import { binOnPath, claudeCodeInstallsFromEnv, claudeInstalledCopies, codexMcpEntry, geminiCliPresent, geminiSettingsPath, isEmptyStub, isOurPluginKey, launcherNamesMissingPackage } from "./install.js";
|
|
20
20
|
import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
|
|
21
21
|
import { withInvocation } from "./invocation.js";
|
|
22
|
+
import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
|
|
22
23
|
function claudeDesktopConfigPath() {
|
|
23
24
|
switch (platform()) {
|
|
24
25
|
case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
@@ -141,6 +142,73 @@ function pluginEnabled(layers) {
|
|
|
141
142
|
}
|
|
142
143
|
return [...state.values()].some(Boolean);
|
|
143
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
|
+
}
|
|
144
212
|
/** Claude Code's disableAllHooks: when true, no hook of anyone's runs. */
|
|
145
213
|
function hooksDisabled(layers) {
|
|
146
214
|
return layers.reduce((off, s) => (typeof s.disableAllHooks === "boolean" ? s.disableAllHooks : off), false);
|
|
@@ -236,6 +304,7 @@ export async function runDoctor() {
|
|
|
236
304
|
? { label: "Compaction hook", status: "ok", detail: "PreCompact: each compaction's summary keeps the session's files, open tasks, your instructions and failing commands" }
|
|
237
305
|
: { label: "Compaction hook", status: "warn", detail: "not registered: compactions use generic instructions; run context-doctor install" });
|
|
238
306
|
}
|
|
307
|
+
checks.push(modelSwitchCheck(settings, plugin));
|
|
239
308
|
}
|
|
240
309
|
catch (e) {
|
|
241
310
|
checks.push({ label: "Every-prompt hook", status: "fail", detail: `settings.json unreadable (${e.message})` });
|
|
@@ -339,6 +408,7 @@ export async function runDoctor() {
|
|
|
339
408
|
else {
|
|
340
409
|
checks.push({ label: "Gemini CLI", status: "skip", detail: "not detected" });
|
|
341
410
|
}
|
|
411
|
+
checks.push(devinCheck());
|
|
342
412
|
// Cursor: its agent gets the guidance through native hooks (the Claude
|
|
343
413
|
// Code hook it also runs cannot add context there). Whether the text then
|
|
344
414
|
// reaches the model depends on the Cursor version, and Cursor logs only
|
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>;
|