context-doctor 0.43.0 → 0.44.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 +3 -2
- package/dist/budget.d.ts +13 -3
- package/dist/budget.js +158 -40
- package/dist/cachettl.d.ts +5 -1
- package/dist/cachettl.js +10 -25
- package/dist/cli.js +6 -9
- package/dist/codexcompact.d.ts +24 -3
- package/dist/codexcompact.js +207 -41
- package/dist/compactwindow.js +2 -2
- package/dist/cursor.d.ts +10 -0
- package/dist/cursor.js +20 -0
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +45 -0
- package/dist/fanout.js +4 -2
- package/dist/fix.d.ts +8 -1
- package/dist/fix.js +59 -13
- package/dist/hook.js +45 -15
- package/dist/install.js +56 -19
- package/dist/limits.d.ts +6 -2
- package/dist/limits.js +19 -16
- package/dist/mcp.js +63 -63
- package/dist/mcpclient.js +19 -19
- package/dist/mcpschema.js +5 -9
- package/dist/overhead.d.ts +7 -2
- package/dist/overhead.js +11 -3
- package/dist/pack.js +23 -3
- package/dist/pricing.d.ts +25 -5
- package/dist/pricing.js +157 -48
- package/dist/proxy.d.ts +15 -1
- package/dist/proxy.js +33 -5
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +20 -9
- package/dist/savings.js +2 -1
- package/dist/sessionprice.d.ts +7 -1
- package/dist/sessionprice.js +79 -28
- package/dist/settingsedit.js +3 -2
- package/dist/spend.d.ts +25 -3
- package/dist/spend.js +67 -19
- package/dist/subagentmodel.js +11 -1
- package/dist/subagentpay.d.ts +17 -0
- package/dist/subagentpay.js +41 -2
- package/dist/subagents.d.ts +24 -0
- package/dist/subagents.js +82 -17
- package/dist/tooloutput.d.ts +2 -0
- package/dist/tooloutput.js +2 -0
- package/package.json +1 -1
package/dist/fix.js
CHANGED
|
@@ -39,7 +39,8 @@ import { dirname, join } from "node:path";
|
|
|
39
39
|
import { forEachLine, listSessions, isClaudeSession } from "./session.js";
|
|
40
40
|
import { pricingFor } from "./pricing.js";
|
|
41
41
|
import { contextWindowFor, realModel } from "./tokens.js";
|
|
42
|
-
import { adviseTtl, estimateCacheTtl } from "./cachettl.js";
|
|
42
|
+
import { adviseTtl, CACHE_TTL_SINCE, estimateCacheTtl } from "./cachettl.js";
|
|
43
|
+
import { compareVersions, describeInstalls } from "./modelswitch.js";
|
|
43
44
|
import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, withSettingsLock, writeAtomic } from "./settingsedit.js";
|
|
44
45
|
import { compactWindowOverrides, processEnvWhere, settingsSources, shellSet, ttlOverrides } from "./effective.js";
|
|
45
46
|
import { tilde } from "./claudedir.js";
|
|
@@ -47,8 +48,17 @@ import { applyPrune, undoPrune } from "./prune.js";
|
|
|
47
48
|
import { fallbackStateDir, readLedger } from "./ledger.js";
|
|
48
49
|
import { claudeDir } from "./claudedir.js";
|
|
49
50
|
import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
|
|
50
|
-
import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
|
|
51
|
+
import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, BASH_OUTPUT_SINCE, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
|
|
51
52
|
import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCompactSavedSince, codexConfigPath, renderCodexLimits, setTopLevelInt, topLevelValue } from "./codexcompact.js";
|
|
53
|
+
/**
|
|
54
|
+
* The Claude Code version that first reads each setting a fix writes, from
|
|
55
|
+
* its changelog (2.1.243 added promptCacheTtl and subagentPromptCacheTtl,
|
|
56
|
+
* 2.1.261 bashOutputMaxChars). CLAUDE_CODE_SUBAGENT_MODEL and
|
|
57
|
+
* ENABLE_TOOL_SEARCH are read by 2.1.62 already (the oldest binary checked;
|
|
58
|
+
* the subagent variable ahead of agent definitions there). autoCompactWindow
|
|
59
|
+
* is not in 2.1.62 and the changelog does not say when it came: not named.
|
|
60
|
+
*/
|
|
61
|
+
const SINCE = { "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE };
|
|
52
62
|
/** Below this a priced fix is not worth a setting. */
|
|
53
63
|
const MIN_USD = 1;
|
|
54
64
|
const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
@@ -143,7 +153,7 @@ export function planFixes(i) {
|
|
|
143
153
|
title: `Switch off ${names.length} unused MCP server${names.length === 1 ? "" : "s"} or skill${names.length === 1 ? "" : "s"} in this project`,
|
|
144
154
|
basis: `none used in ${i.prune.sessions} sessions of this project in ${i.days} days: ${names.slice(0, 5).join(", ")}${names.length > 5 ? ", …" : ""}`,
|
|
145
155
|
quality: "none while they stay unused; undo brings them back",
|
|
146
|
-
change:
|
|
156
|
+
change: join(i.prune.cwd, ".claude", "settings.local.json"),
|
|
147
157
|
state: "available",
|
|
148
158
|
});
|
|
149
159
|
}
|
|
@@ -212,7 +222,7 @@ export function planFixes(i) {
|
|
|
212
222
|
savedUsd: cxOffer.savedUsd,
|
|
213
223
|
savedShare: cxOffer.savedShare,
|
|
214
224
|
shareOf: "of Codex input",
|
|
215
|
-
basis: `your ${cx.requests.toLocaleString("en-US")} Codex requests replayed at a ${k(CODEX_COMPACT_LIMIT)} limit: ${(cxOffer.compactions / weeks).toFixed(1)} compactions a week instead of ${(cx.actualCompactions / weeks).toFixed(1)}, each paying a request and a ${k(5_000)}-token summary (an estimate: Codex does not record its compactions' own usage)`,
|
|
225
|
+
basis: `your ${cx.requests.toLocaleString("en-US")} Codex requests replayed at a ${k(CODEX_COMPACT_LIMIT)} limit: ${(cxOffer.compactions / weeks).toFixed(1)} compactions a week instead of ${(cx.actualCompactions / weeks).toFixed(1)}, each paying a request and a ${k(5_000)}-token summary (an estimate: Codex does not record its compactions' own usage)${cx.scope === "body_after_prefix" ? "; the limit counted as your model_auto_compact_token_limit_scope = \"body_after_prefix\" counts it: what a session added after the first request since its start or last compaction" : ""}`,
|
|
216
226
|
quality: "each compaction replaces the history with a summary: detail for money",
|
|
217
227
|
change: `${tilde(codexConfigPath())}: ${CODEX_COMPACT_KEY} = ${CODEX_COMPACT_LIMIT}`,
|
|
218
228
|
state: "available",
|
|
@@ -224,6 +234,10 @@ export function planFixes(i) {
|
|
|
224
234
|
const o = i.overrides?.[f.id];
|
|
225
235
|
if (o?.length && f.state === "available")
|
|
226
236
|
f.overriddenBy = o;
|
|
237
|
+
const since = SINCE[f.id];
|
|
238
|
+
const old = since && f.state === "available" ? (i.claudeCodeInstalls ?? []).filter((c) => compareVersions(c.version, since) < 0) : [];
|
|
239
|
+
if (old.length)
|
|
240
|
+
f.tooOld = `${describeInstalls(old)} ${old.length === 1 ? "predates" : "predate"} this setting (Claude Code ${since}+) and ${old.length === 1 ? "ignores" : "ignore"} it: update ${old.length === 1 ? "it" : "them"} for it to take effect there`;
|
|
227
241
|
}
|
|
228
242
|
const rank = (f) => (f.state === "available" ? 0 : f.state === "applied" ? 2 : 3) + (f.savedUsd === undefined ? 1 : 0);
|
|
229
243
|
return fixes.sort((a, b) => rank(a) - rank(b) || (b.savedUsd ?? 0) - (a.savedUsd ?? 0));
|
|
@@ -335,7 +349,8 @@ function applySetting(fix, home, at, extra) {
|
|
|
335
349
|
const key = KEY_PATH[fix.id];
|
|
336
350
|
const file = join(claudeDir(home), "settings.json");
|
|
337
351
|
mkdirSync(dirname(file), { recursive: true });
|
|
338
|
-
|
|
352
|
+
// The records' lock, and settings.json's own: the same file unless the records live in the state folder (a machine that had only Codex at first).
|
|
353
|
+
return withLock(lockPath(home), () => withSettingsLock(file, () => {
|
|
339
354
|
const records = loadFixRecords(home);
|
|
340
355
|
const cur = readSettings(file);
|
|
341
356
|
const now = getPath(cur.data, key);
|
|
@@ -369,7 +384,7 @@ function applySetting(fix, home, at, extra) {
|
|
|
369
384
|
};
|
|
370
385
|
writeFixRecords([...records.filter((r) => r.id !== fix.id), rec], home);
|
|
371
386
|
return [`✓ ${fix.change}`];
|
|
372
|
-
});
|
|
387
|
+
}));
|
|
373
388
|
}
|
|
374
389
|
/**
|
|
375
390
|
* Set Codex's limit at the top of config.toml, under the records' lock and
|
|
@@ -508,6 +523,9 @@ export async function applyFix(fix, deps = {}, context = {}) {
|
|
|
508
523
|
function undoSetting(r, home) {
|
|
509
524
|
const key = r.key ?? KEY_PATH[r.id];
|
|
510
525
|
const file = r.file ?? join(claudeDir(home), "settings.json");
|
|
526
|
+
return withSettingsLock(file, () => undoSettingLocked(r, key, file));
|
|
527
|
+
}
|
|
528
|
+
function undoSettingLocked(r, key, file) {
|
|
511
529
|
const name = key.join(".");
|
|
512
530
|
const cur = readSettings(file);
|
|
513
531
|
const text = cur.text ?? null;
|
|
@@ -740,6 +758,26 @@ const LABEL = {
|
|
|
740
758
|
"tool-output": "Long Bash output",
|
|
741
759
|
"codex-compact": "Codex auto-compact limit",
|
|
742
760
|
};
|
|
761
|
+
/**
|
|
762
|
+
* Priced levers that save part of the same dollars, and why: each is
|
|
763
|
+
* replayed alone on the history as billed, so applying both saves less than
|
|
764
|
+
* the two figures added. Codex's limit shares nothing with Claude Code's.
|
|
765
|
+
*/
|
|
766
|
+
const OVERLAPS = [
|
|
767
|
+
["compact-window", "cache-ttl", "compacting earlier and the main conversation's cache lifetime both change what is written to the cache"],
|
|
768
|
+
["compact-window", "tool-output", "an earlier compaction drops long Bash output sooner, so there is less left to move to a file"],
|
|
769
|
+
["compact-window", "autopilot", "compacting earlier and autopilot both take old tool output out of the context"],
|
|
770
|
+
["tool-output", "autopilot", "output moved to a file is no longer there for autopilot to clear"],
|
|
771
|
+
["tool-output", "cache-ttl", "the main conversation's cache lifetime changes how often long output is written to the cache again"],
|
|
772
|
+
["tool-output", "cache-ttl-subagents", "the subagents' cache lifetime changes how often their long output is written to the cache again"],
|
|
773
|
+
["tool-output", "subagent-model", "long output in subagents is priced at the subagents' model, which subagent-model changes"],
|
|
774
|
+
["subagent-model", "cache-ttl-subagents", "the subagents' cache is priced at their model's rates, which subagent-model changes"],
|
|
775
|
+
];
|
|
776
|
+
/** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
|
|
777
|
+
export function overlaps(fixes) {
|
|
778
|
+
const priced = new Set(fixes.filter((f) => f.savedUsd !== undefined).map((f) => f.id));
|
|
779
|
+
return OVERLAPS.filter(([a, b]) => priced.has(a) && priced.has(b)).map(([a, b, why]) => `${a} and ${b}: ${why}.`);
|
|
780
|
+
}
|
|
743
781
|
export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem, codexBilledUsd = 0) {
|
|
744
782
|
const out = [];
|
|
745
783
|
if (recordProblem)
|
|
@@ -768,10 +806,14 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
|
|
|
768
806
|
out.push(` ${d}`);
|
|
769
807
|
if (f.overriddenBy?.length)
|
|
770
808
|
out.push(` ⚠ would not take effect: ${f.overriddenBy.join("; ")}`);
|
|
809
|
+
if (f.tooOld)
|
|
810
|
+
out.push(` ⚠ ${f.tooOld}`);
|
|
771
811
|
});
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
out.push("
|
|
812
|
+
const pairs = overlaps(avail);
|
|
813
|
+
if (pairs.length) {
|
|
814
|
+
out.push(" Each figure is measured alone. Do not add them up: the levers overlap, so together they save less:");
|
|
815
|
+
for (const p of pairs)
|
|
816
|
+
out.push(` ${p}`);
|
|
775
817
|
}
|
|
776
818
|
const applied = fixes.filter((f) => f.state === "applied");
|
|
777
819
|
if (applied.length) {
|
|
@@ -810,14 +852,18 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
|
|
|
810
852
|
function noHistory(days, command) {
|
|
811
853
|
return [`No Claude Code sessions in the last ${days} days to measure yet, so no fix can be priced.`, `Use Claude Code for a while, then run this again: ${command("fix")}.`];
|
|
812
854
|
}
|
|
813
|
-
export function renderFixShare(days, billedUsd, fixes) {
|
|
855
|
+
export function renderFixShare(days, billedUsd, fixes, codexBilledUsd = 0) {
|
|
814
856
|
const avail = fixes.filter((f) => f.state === "available" && f.savedUsd !== undefined);
|
|
815
|
-
|
|
857
|
+
// As the plan's first line: Codex's input beside Claude Code's, or alone on a machine with only Codex.
|
|
858
|
+
const of = codexBilledUsd > 0 && billedUsd > 0
|
|
859
|
+
? `Claude Code and Codex (${money(billedUsd)} and ${money(codexBilledUsd)} of input at list price)`
|
|
860
|
+
: codexBilledUsd > 0 ? `Codex (${money(codexBilledUsd)} of input at list price)` : `Claude Code (${money(billedUsd)} of input at list price)`;
|
|
861
|
+
const lines = [`context-doctor fix on my last ${days} days of ${of}:`];
|
|
816
862
|
for (const f of avail)
|
|
817
863
|
lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${share(f)}`);
|
|
818
864
|
if (avail.length === 0)
|
|
819
|
-
lines.push(billedUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
|
|
820
|
-
if (avail.length
|
|
865
|
+
lines.push(billedUsd + codexBilledUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
|
|
866
|
+
if (overlaps(avail).length)
|
|
821
867
|
lines.push("Each measured alone; they overlap, so do not add them up.");
|
|
822
868
|
lines.push("Measured on my own sessions, locally: npx context-doctor fix");
|
|
823
869
|
return lines.join("\n");
|
package/dist/hook.js
CHANGED
|
@@ -114,20 +114,45 @@ function readSessionState(sessionId) {
|
|
|
114
114
|
}
|
|
115
115
|
/** Keep the directory from growing without bound as sessions come and go. */
|
|
116
116
|
const MAX_STATE_FILES = 200;
|
|
117
|
+
/**
|
|
118
|
+
* Past MAX_STATE_FILES, the sessions least recently touched go, each with
|
|
119
|
+
* all its files (named `<hash>.…`: its state, the session price's ledger and
|
|
120
|
+
* threshold markers, the subagent launch log). File by file, a live
|
|
121
|
+
* session's marker, written once when it passed $25, went first among
|
|
122
|
+
* newer files of other sessions, and the threshold was said again.
|
|
123
|
+
*/
|
|
124
|
+
function pruneStateDir(dir) {
|
|
125
|
+
const files = readdirSync(dir);
|
|
126
|
+
if (files.length <= MAX_STATE_FILES)
|
|
127
|
+
return;
|
|
128
|
+
const sessions = new Map();
|
|
129
|
+
for (const f of files) {
|
|
130
|
+
let t = 0;
|
|
131
|
+
try {
|
|
132
|
+
t = statSync(join(dir, f)).mtimeMs;
|
|
133
|
+
}
|
|
134
|
+
catch { /* gone meanwhile */ }
|
|
135
|
+
const key = f.split(".")[0];
|
|
136
|
+
const s = sessions.get(key) ?? { files: [], t: 0 };
|
|
137
|
+
s.files.push(f);
|
|
138
|
+
s.t = Math.max(s.t, t);
|
|
139
|
+
sessions.set(key, s);
|
|
140
|
+
}
|
|
141
|
+
let left = files.length;
|
|
142
|
+
for (const s of [...sessions.values()].sort((a, b) => a.t - b.t)) {
|
|
143
|
+
if (left <= MAX_STATE_FILES)
|
|
144
|
+
break;
|
|
145
|
+
for (const f of s.files)
|
|
146
|
+
rmSync(join(dir, f), { force: true });
|
|
147
|
+
left -= s.files.length;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
117
150
|
function writeSessionState(sessionId, state) {
|
|
118
151
|
const dir = stateDir();
|
|
119
152
|
mkdirSync(dir, { recursive: true });
|
|
120
153
|
writeFileSync(sessionStatePath(sessionId), JSON.stringify(state));
|
|
121
154
|
try {
|
|
122
|
-
|
|
123
|
-
if (files.length <= MAX_STATE_FILES)
|
|
124
|
-
return;
|
|
125
|
-
const byAge = files
|
|
126
|
-
.map((f) => ({ f, t: statSync(join(dir, f)).mtimeMs }))
|
|
127
|
-
.sort((a, b) => b.t - a.t)
|
|
128
|
-
.slice(MAX_STATE_FILES);
|
|
129
|
-
for (const { f } of byAge)
|
|
130
|
-
rmSync(join(dir, f), { force: true });
|
|
155
|
+
pruneStateDir(dir);
|
|
131
156
|
}
|
|
132
157
|
catch {
|
|
133
158
|
/* pruning is housekeeping, never worth failing a prompt over */
|
|
@@ -289,7 +314,7 @@ export async function runHook(app) {
|
|
|
289
314
|
// A session's own price (sessionprice.ts): once when it passes $25, $100
|
|
290
315
|
// and $500, a line to the user beside the budget's. Claimed before the
|
|
291
316
|
// rest of the hook runs, so it rides in `budgetNote` like the budget's.
|
|
292
|
-
let priceCold = false;
|
|
317
|
+
let priceCold = false, priceSaid = false;
|
|
293
318
|
if (!cursor && (input.hook_event_name === undefined || input.hook_event_name === "UserPromptSubmit" || input.hook_event_name === "BeforeAgent") && input.transcript_path && existsSync(input.transcript_path)) {
|
|
294
319
|
try {
|
|
295
320
|
const sid = input.session_id ?? input.conversation_id ?? input.transcript_path;
|
|
@@ -297,6 +322,7 @@ export async function runHook(app) {
|
|
|
297
322
|
if (p) {
|
|
298
323
|
budgetNote = [budgetNote, renderSessionPrice(p)].filter(Boolean).join("\n");
|
|
299
324
|
priceCold = p.coldUsd !== undefined;
|
|
325
|
+
priceSaid = true;
|
|
300
326
|
recordLedger({ ev: "session_price", sid: sid.slice(0, 12), usd: Math.round(p.usd * 100) / 100, ...(p.tokens !== undefined ? { tok: p.tokens } : {}), ...(p.model ? { model: p.model } : {}) });
|
|
301
327
|
}
|
|
302
328
|
}
|
|
@@ -340,11 +366,14 @@ export async function runHook(app) {
|
|
|
340
366
|
cold = undefined;
|
|
341
367
|
let cr = prev.cr;
|
|
342
368
|
if (cold && cold.lastReplyAt !== prev.cr) {
|
|
343
|
-
notes.push(renderColdResume(cold));
|
|
344
|
-
// The session price's line already said this message re-writes the cache: once is enough.
|
|
345
|
-
notice = [budgetNote, priceCold ? undefined : renderColdResumeNotice(cold)].filter(Boolean).join("\n");
|
|
346
369
|
cr = cold.lastReplyAt;
|
|
347
|
-
|
|
370
|
+
// The session price's line already told the user this message re-writes the cache and that
|
|
371
|
+
// /compact cuts it: once is enough, so neither the notice nor the model's offer goes out too.
|
|
372
|
+
if (!priceCold) {
|
|
373
|
+
notes.push(renderColdResume(cold));
|
|
374
|
+
notice = [budgetNote, renderColdResumeNotice(cold)].filter(Boolean).join("\n");
|
|
375
|
+
recordLedger({ ev: "cold_resume", sid: sessionId.slice(0, 12), tok: cold.tokens, model: cold.model });
|
|
376
|
+
}
|
|
348
377
|
}
|
|
349
378
|
const emit = (lines) => {
|
|
350
379
|
if (lines.length === 0 && !notice)
|
|
@@ -437,7 +466,8 @@ export async function runHook(app) {
|
|
|
437
466
|
if (topFinding) {
|
|
438
467
|
lines.push(`Largest recoverable waste: ${topFinding.message} (${topFinding.suggestion})`);
|
|
439
468
|
}
|
|
440
|
-
|
|
469
|
+
// Not when the session price's line just said /compact to the user: the reply would say it again.
|
|
470
|
+
if (liveTokens > threshold * 2 && !priceSaid) {
|
|
441
471
|
lines.push(cursor
|
|
442
472
|
? "If the task changes, suggest the user start a new chat from a short summary of this one."
|
|
443
473
|
: "If it fits the flow, offer the user a compaction of the older history.");
|
package/dist/install.js
CHANGED
|
@@ -250,6 +250,16 @@ function readText(path) {
|
|
|
250
250
|
return undefined;
|
|
251
251
|
}
|
|
252
252
|
}
|
|
253
|
+
/**
|
|
254
|
+
* Whether a step changed any of `paths`, by their text before it ran: a
|
|
255
|
+
* second install said "MCP server added" for every app it left exactly as
|
|
256
|
+
* it was. `said(done, kept)` picks the line's verb.
|
|
257
|
+
*/
|
|
258
|
+
function changeWatch(...paths) {
|
|
259
|
+
const before = paths.map(readText);
|
|
260
|
+
const changed = () => paths.some((p, i) => readText(p) !== before[i]);
|
|
261
|
+
return { changed, said: (done, kept = "already installed, unchanged") => (changed() ? done : kept) };
|
|
262
|
+
}
|
|
253
263
|
/**
|
|
254
264
|
* Write `data` into a JSON config the way a person would edit it: only the
|
|
255
265
|
* keys and list items that differ are changed in the text (settingsedit.ts),
|
|
@@ -606,7 +616,9 @@ function installSkillInto(skillDest, appHome) {
|
|
|
606
616
|
mkdirSync(skillDest, { recursive: true });
|
|
607
617
|
// Written whole and renamed into place: two installs at once (or Claude
|
|
608
618
|
// Code reading the skill) made Windows refuse a plain copy with EBUSY.
|
|
609
|
-
|
|
619
|
+
const skill = readFileSync(skillSource, "utf8");
|
|
620
|
+
if (readText(join(skillDest, "SKILL.md")) !== skill)
|
|
621
|
+
writeAtomic(join(skillDest, "SKILL.md"), skill);
|
|
610
622
|
if (appHome && missing.length > 0) {
|
|
611
623
|
const all = [...new Set([...createdSkillFolders(appHome), ...missing])];
|
|
612
624
|
writeAtomic(join(appHome, CREATED_MARKER), JSON.stringify({ created: all }) + "\n");
|
|
@@ -791,24 +803,28 @@ function installCodex(entry, failures) {
|
|
|
791
803
|
backupOnce(configPath);
|
|
792
804
|
writeFileSync(configPath, next);
|
|
793
805
|
}
|
|
794
|
-
console.log(`✓ Codex: MCP server added (${configPath})`);
|
|
806
|
+
console.log(`✓ Codex: MCP server ${next !== current ? "added" : "already installed, unchanged"} (${configPath})`);
|
|
795
807
|
}
|
|
796
808
|
catch (e) {
|
|
797
809
|
console.error(`✗ Codex MCP: ${e.message}`);
|
|
798
810
|
failures.push("Codex MCP");
|
|
799
811
|
}
|
|
800
812
|
try {
|
|
813
|
+
const watch = changeWatch(join(dir, "skills", "context-doctor", "SKILL.md"));
|
|
801
814
|
const skill = installSkillInto(join(dir, "skills", "context-doctor"), dir);
|
|
802
815
|
if (skill)
|
|
803
|
-
console.log(`✓ Agent Skill installed for Codex (${skill})`);
|
|
816
|
+
console.log(`✓ Agent Skill ${watch.said("installed", "already installed, up to date")} for Codex (${skill})`);
|
|
804
817
|
}
|
|
805
818
|
catch (e) {
|
|
806
819
|
console.error(`✗ Codex skill: ${e.message}`);
|
|
807
820
|
failures.push("Codex skill");
|
|
808
821
|
}
|
|
809
822
|
try {
|
|
823
|
+
const watch = changeWatch(join(dir, "hooks.json"));
|
|
810
824
|
const hook = installHookInto(join(dir, "hooks.json"), dir);
|
|
811
|
-
if (hook)
|
|
825
|
+
if (hook && !watch.changed())
|
|
826
|
+
console.log(`✓ Codex every-prompt hook already installed, unchanged (${hook})`);
|
|
827
|
+
else if (hook) {
|
|
812
828
|
console.log(`✓ Codex every-prompt hook installed (${hook})`);
|
|
813
829
|
console.log(" Codex runs a new hook only after you trust it once: open Codex, type /hooks, and trust context-doctor.");
|
|
814
830
|
}
|
|
@@ -935,12 +951,13 @@ function installCopilot(entry, failures) {
|
|
|
935
951
|
}
|
|
936
952
|
config.mcpServers = config.mcpServers ?? {};
|
|
937
953
|
const want = copilotMcpEntry(entry);
|
|
938
|
-
|
|
954
|
+
const stale = JSON.stringify(config.mcpServers["context-doctor"]) !== JSON.stringify(want);
|
|
955
|
+
if (stale) {
|
|
939
956
|
config.mcpServers["context-doctor"] = want;
|
|
940
957
|
writeJsonWithBackup(path, config);
|
|
941
958
|
}
|
|
942
959
|
mcpOk = true;
|
|
943
|
-
console.log(`✓ GitHub Copilot: MCP server added (${path})`);
|
|
960
|
+
console.log(`✓ GitHub Copilot: MCP server ${stale ? "added" : "already installed, unchanged"} (${path})`);
|
|
944
961
|
}
|
|
945
962
|
catch (e) {
|
|
946
963
|
console.error(`✗ GitHub Copilot MCP: ${e.message}`);
|
|
@@ -971,12 +988,15 @@ function installCopilot(entry, failures) {
|
|
|
971
988
|
const entries = current ?? [];
|
|
972
989
|
const want = copilotHookEntry();
|
|
973
990
|
const ours = entries.filter(isOurCopilotEntry);
|
|
974
|
-
|
|
991
|
+
const upToDate = ours.length === 1 && JSON.stringify(ours[0]) === JSON.stringify(want);
|
|
992
|
+
if (!upToDate) {
|
|
975
993
|
config.hooks[COPILOT_HOOK_EVENT] = [...entries.filter((e) => !isOurCopilotEntry(e)), want];
|
|
976
994
|
mkdirSync(dirname(path), { recursive: true });
|
|
977
995
|
writeFileSync(path, JSON.stringify(config, null, 2));
|
|
978
996
|
}
|
|
979
|
-
console.log(
|
|
997
|
+
console.log(upToDate
|
|
998
|
+
? `✓ GitHub Copilot session-start hook already installed, unchanged (${path})`
|
|
999
|
+
: `✓ GitHub Copilot session-start hook installed (${path}): each new or resumed session gets the standing context rules`);
|
|
980
1000
|
}
|
|
981
1001
|
catch (e) {
|
|
982
1002
|
console.error(`✗ GitHub Copilot hook: ${e.message}`);
|
|
@@ -1102,10 +1122,13 @@ export function runInstall(options = {}) {
|
|
|
1102
1122
|
if (config.mcpServers !== undefined && !isPlainObject(config.mcpServers))
|
|
1103
1123
|
throw new Error(`"mcpServers" in ${target.configPath} is not an object; fix it, then re-run. Nothing was changed.`);
|
|
1104
1124
|
config.mcpServers = config.mcpServers ?? {};
|
|
1105
|
-
//
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1125
|
+
// Overwrite a stale entry (re-running install is how one gets repaired); leave a current one, and its file, alone.
|
|
1126
|
+
const watch = changeWatch(target.configPath);
|
|
1127
|
+
if (JSON.stringify(config.mcpServers["context-doctor"]) !== JSON.stringify(entry)) {
|
|
1128
|
+
config.mcpServers["context-doctor"] = entry;
|
|
1129
|
+
writeJsonWithBackup(target.configPath, config);
|
|
1130
|
+
}
|
|
1131
|
+
console.log(`✓ ${target.name}: MCP server ${watch.said("added")} (${target.configPath})`);
|
|
1109
1132
|
}
|
|
1110
1133
|
catch (e) {
|
|
1111
1134
|
console.error(`✗ ${target.name}: ${e.message}`);
|
|
@@ -1113,9 +1136,10 @@ export function runInstall(options = {}) {
|
|
|
1113
1136
|
}
|
|
1114
1137
|
}
|
|
1115
1138
|
try {
|
|
1139
|
+
const watch = changeWatch(join(claudeDir(), "skills", "context-doctor", "SKILL.md"));
|
|
1116
1140
|
const skillPath = viaPlugin ? null : installSkill();
|
|
1117
1141
|
if (skillPath)
|
|
1118
|
-
console.log(`✓ Agent Skill installed for Claude Code (${skillPath})`);
|
|
1142
|
+
console.log(`✓ Agent Skill ${watch.said("installed", "already installed, up to date")} for Claude Code (${skillPath})`);
|
|
1119
1143
|
}
|
|
1120
1144
|
catch (e) {
|
|
1121
1145
|
console.error(`✗ Agent Skill: ${e.message}`);
|
|
@@ -1127,9 +1151,10 @@ export function runInstall(options = {}) {
|
|
|
1127
1151
|
// A skills folder Antigravity did not have yet is ours to remove again.
|
|
1128
1152
|
if (!existsSync(dirname(dir)))
|
|
1129
1153
|
rememberAntigravityFolder(dirname(dir));
|
|
1154
|
+
const watch = changeWatch(join(dir, "SKILL.md"));
|
|
1130
1155
|
const skillPath = installSkillInto(dir);
|
|
1131
1156
|
if (skillPath)
|
|
1132
|
-
console.log(`✓ Antigravity skill installed (${
|
|
1157
|
+
console.log(`✓ Antigravity skill ${watch.said("installed", "already installed, up to date")} (${skillPath})`);
|
|
1133
1158
|
}
|
|
1134
1159
|
catch (e) {
|
|
1135
1160
|
console.error(`✗ Antigravity skill: ${e.message}`);
|
|
@@ -1138,9 +1163,12 @@ export function runInstall(options = {}) {
|
|
|
1138
1163
|
}
|
|
1139
1164
|
}
|
|
1140
1165
|
try {
|
|
1166
|
+
const watch = changeWatch(join(claudeDir(), "settings.json"));
|
|
1141
1167
|
const hookPath = viaPlugin ? null : installHook();
|
|
1142
1168
|
if (hookPath) {
|
|
1143
|
-
console.log(
|
|
1169
|
+
console.log(watch.changed()
|
|
1170
|
+
? `✓ Claude Code every-prompt hook installed (${hookPath}) — heavy sessions get automatic hygiene guidance`
|
|
1171
|
+
: `✓ Claude Code hooks already installed, unchanged (${hookPath})`);
|
|
1144
1172
|
// npx resolves the package on every single prompt; a global install makes
|
|
1145
1173
|
// the hook a plain exec instead, which is both faster and update-proof.
|
|
1146
1174
|
if (hookUsesNpx()) {
|
|
@@ -1157,9 +1185,12 @@ export function runInstall(options = {}) {
|
|
|
1157
1185
|
if (!viaPlugin && claudeCodePresent()) {
|
|
1158
1186
|
try {
|
|
1159
1187
|
const readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv());
|
|
1188
|
+
const watch = changeWatch(join(claudeDir(), "settings.json"));
|
|
1160
1189
|
switch (installModelSwitchHook(readiness)) {
|
|
1161
1190
|
case "installed":
|
|
1162
|
-
console.log(
|
|
1191
|
+
console.log(watch.changed()
|
|
1192
|
+
? "✓ Claude Code model-switch warning installed (PreModelSwitch): before /model switches, the price of re-writing this context into the new model's cache"
|
|
1193
|
+
: "✓ Claude Code model-switch warning already installed, unchanged");
|
|
1163
1194
|
break;
|
|
1164
1195
|
case "old":
|
|
1165
1196
|
console.log(`– Claude Code model-switch warning skipped: ${describeInstalls(readiness.old)} predates PreModelSwitch (${PRE_MODEL_SWITCH_SINCE}) and would`);
|
|
@@ -1176,9 +1207,13 @@ export function runInstall(options = {}) {
|
|
|
1176
1207
|
}
|
|
1177
1208
|
}
|
|
1178
1209
|
try {
|
|
1210
|
+
const watch = changeWatch(cursorHooksPath());
|
|
1179
1211
|
const cursorHook = installCursorHook();
|
|
1180
|
-
if (cursorHook)
|
|
1181
|
-
console.log(
|
|
1212
|
+
if (cursorHook) {
|
|
1213
|
+
console.log(watch.changed()
|
|
1214
|
+
? `✓ Cursor hooks installed (${cursorHook}: after each tool call, after a failed one, at chat start) — Cursor's agent gets the same guidance in heavy sessions`
|
|
1215
|
+
: `✓ Cursor hooks already installed, unchanged (${cursorHook})`);
|
|
1216
|
+
}
|
|
1182
1217
|
}
|
|
1183
1218
|
catch (e) {
|
|
1184
1219
|
console.error(`✗ Cursor hook: ${e.message}`);
|
|
@@ -1188,9 +1223,10 @@ export function runInstall(options = {}) {
|
|
|
1188
1223
|
installCopilot(entry, failures);
|
|
1189
1224
|
if (geminiCliPresent()) {
|
|
1190
1225
|
try {
|
|
1226
|
+
const watch = changeWatch(geminiSettingsPath());
|
|
1191
1227
|
const hook = installHookInto(geminiSettingsPath(), join(homedir(), ".gemini"), "BeforeAgent");
|
|
1192
1228
|
if (hook)
|
|
1193
|
-
console.log(`✓ Gemini CLI every-prompt hook installed (${hook})`);
|
|
1229
|
+
console.log(`✓ Gemini CLI every-prompt hook ${watch.said("installed")} (${hook})`);
|
|
1194
1230
|
}
|
|
1195
1231
|
catch (e) {
|
|
1196
1232
|
console.error(`✗ Gemini CLI hook: ${e.message}`);
|
|
@@ -1425,6 +1461,7 @@ const OUR_CLAUDE_FILES = [
|
|
|
1425
1461
|
".context-doctor-subagent-costs.json",
|
|
1426
1462
|
".context-doctor-budget.json",
|
|
1427
1463
|
".context-doctor-budget-state.json",
|
|
1464
|
+
".context-doctor-budget-said.d",
|
|
1428
1465
|
];
|
|
1429
1466
|
export async function runUninstall() {
|
|
1430
1467
|
changes = 0;
|
package/dist/limits.d.ts
CHANGED
|
@@ -121,8 +121,9 @@ export interface ClaudeRequest extends UsagePoint {
|
|
|
121
121
|
* The requests of one Claude Code transcript between `since` and `until`,
|
|
122
122
|
* each reply once, its output settled on its last row. `runRows` is shared
|
|
123
123
|
* by every file of one report, so a fork's copy of its parent's replies is
|
|
124
|
-
* counted once, in the file met first (replyCounter).
|
|
125
|
-
*
|
|
124
|
+
* counted once, in the file met first (replyCounter). Replies on
|
|
125
|
+
* `<synthetic>` (isUnbilledModel) are left out. Throws when the transcript
|
|
126
|
+
* cannot be read.
|
|
126
127
|
*/
|
|
127
128
|
export declare function claudeFileUsage(file: string, since: number, until?: number, runRows?: Set<string>): ClaudeRequest[];
|
|
128
129
|
/**
|
|
@@ -134,7 +135,10 @@ export declare function claudeUsageFiles(since: number, tops?: string[]): Array<
|
|
|
134
135
|
file: string;
|
|
135
136
|
top: string;
|
|
136
137
|
subagent: boolean;
|
|
138
|
+
run?: string;
|
|
137
139
|
}>;
|
|
140
|
+
/** How long before a period a session may have been last written and still have subagents running into it. */
|
|
141
|
+
export declare const SUBAGENT_LOOKBACK_MS: number;
|
|
138
142
|
/**
|
|
139
143
|
* Every Claude Code request between `since` and `until`, main threads and
|
|
140
144
|
* subagents alike (both draw on the same limits), each reply once.
|
package/dist/limits.js
CHANGED
|
@@ -31,9 +31,9 @@ import { dirname, join } from "node:path";
|
|
|
31
31
|
import { codexDir } from "./codexdir.js";
|
|
32
32
|
import { statePath } from "./ledger.js";
|
|
33
33
|
import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
|
|
34
|
-
import {
|
|
34
|
+
import { subagentFiles } from "./subagents.js";
|
|
35
35
|
import { pick, rowsOf, slimUsage } from "./scan.js";
|
|
36
|
-
import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
|
|
36
|
+
import { isUnbilledModel, openAIUsage, pricingFor, usageCost } from "./pricing.js";
|
|
37
37
|
import { realModel } from "./tokens.js";
|
|
38
38
|
const MIN = 60_000;
|
|
39
39
|
const HOUR = 60 * MIN;
|
|
@@ -368,8 +368,9 @@ export const USAGE_ROWS = {
|
|
|
368
368
|
* The requests of one Claude Code transcript between `since` and `until`,
|
|
369
369
|
* each reply once, its output settled on its last row. `runRows` is shared
|
|
370
370
|
* by every file of one report, so a fork's copy of its parent's replies is
|
|
371
|
-
* counted once, in the file met first (replyCounter).
|
|
372
|
-
*
|
|
371
|
+
* counted once, in the file met first (replyCounter). Replies on
|
|
372
|
+
* `<synthetic>` (isUnbilledModel) are left out. Throws when the transcript
|
|
373
|
+
* cannot be read.
|
|
373
374
|
*/
|
|
374
375
|
export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
375
376
|
const out = [];
|
|
@@ -394,6 +395,9 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
|
394
395
|
if (seen !== "new")
|
|
395
396
|
return;
|
|
396
397
|
settle(e, true);
|
|
398
|
+
// A reply Claude Code made itself (an error, an interruption) never reached the API: no request, priced or not.
|
|
399
|
+
if (isUnbilledModel(m.model))
|
|
400
|
+
return;
|
|
397
401
|
const ts = Date.parse(String(e.timestamp ?? ""));
|
|
398
402
|
if (!Number.isFinite(ts) || ts < since || ts > until)
|
|
399
403
|
return;
|
|
@@ -425,22 +429,21 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
|
425
429
|
* first), each followed by its subagents'.
|
|
426
430
|
*/
|
|
427
431
|
export function claudeUsageFiles(since, tops) {
|
|
428
|
-
|
|
432
|
+
// A session last written before `since` can still have subagents (a workflow run, a background
|
|
433
|
+
// agent) writing after it: those of the sessions written in the SUBAGENT_LOOKBACK_MS before count.
|
|
434
|
+
const listed = tops ? undefined : listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since - SUBAGENT_LOOKBACK_MS);
|
|
435
|
+
const mains = tops ?? listed.map((s) => s.path);
|
|
429
436
|
const files = [];
|
|
430
|
-
for (const t of mains) {
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
if (f.endsWith(".jsonl") && statSync(join(dir, f)).mtimeMs >= since)
|
|
436
|
-
files.push({ file: join(dir, f), top: t, subagent: true });
|
|
437
|
-
}
|
|
438
|
-
catch {
|
|
439
|
-
/* no subagents */
|
|
440
|
-
}
|
|
437
|
+
for (const [i, t] of mains.entries()) {
|
|
438
|
+
if (!listed || listed[i].modifiedAt.getTime() >= since)
|
|
439
|
+
files.push({ file: t, top: t, subagent: false });
|
|
440
|
+
for (const f of subagentFiles(t, since))
|
|
441
|
+
files.push({ file: f.file, top: t, subagent: true, ...(f.run ? { run: f.run } : {}) });
|
|
441
442
|
}
|
|
442
443
|
return files;
|
|
443
444
|
}
|
|
445
|
+
/** How long before a period a session may have been last written and still have subagents running into it. */
|
|
446
|
+
export const SUBAGENT_LOOKBACK_MS = 2 * 86_400_000;
|
|
444
447
|
/**
|
|
445
448
|
* Every Claude Code request between `since` and `until`, main threads and
|
|
446
449
|
* subagents alike (both draw on the same limits), each reply once.
|