context-doctor 0.32.0 → 0.33.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 +85 -695
- package/dist/autoclear.js +4 -1
- package/dist/autopilot.d.ts +20 -0
- package/dist/autopilot.js +69 -6
- package/dist/ci.js +9 -1
- package/dist/cli.js +355 -245
- package/dist/clihelp.d.ts +24 -0
- package/dist/clihelp.js +116 -0
- package/dist/compactquality.d.ts +1 -1
- package/dist/compactquality.js +3 -2
- package/dist/compactwindow.d.ts +29 -5
- package/dist/compactwindow.js +50 -18
- package/dist/diff.js +24 -2
- package/dist/doctor.d.ts +3 -2
- package/dist/doctor.js +77 -27
- package/dist/install.d.ts +25 -0
- package/dist/install.js +237 -29
- package/dist/invocation.d.ts +18 -0
- package/dist/invocation.js +49 -0
- package/dist/mcp.d.ts +5 -2
- package/dist/mcp.js +93 -299
- package/dist/mcpclient.js +45 -0
- package/dist/mcpschema.d.ts +1 -1
- package/dist/mcpschema.js +11 -8
- package/dist/optimize.d.ts +2 -0
- package/dist/optimize.js +2 -0
- package/dist/overhead.d.ts +12 -1
- package/dist/overhead.js +31 -7
- package/dist/preferences.d.ts +1 -1
- package/dist/preferences.js +5 -5
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/savings.d.ts +3 -0
- package/dist/savings.js +9 -3
- package/dist/session.d.ts +15 -0
- package/dist/session.js +43 -0
- package/dist/subagentpay.d.ts +1 -1
- package/dist/subagentpay.js +3 -2
- package/package.json +5 -8
- package/skills/context-doctor/SKILL.md +3 -3
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the CLI's argument errors and per-command help: a "did you
|
|
3
|
+
* mean" suggestion for a mistyped flag or command, and one command's lines
|
|
4
|
+
* cut out of the full help text. Kept apart from cli.ts, which runs on
|
|
5
|
+
* import, so they can be tested directly.
|
|
6
|
+
*/
|
|
7
|
+
/** Edit distance (insert, delete, substitute; each 1). */
|
|
8
|
+
export declare function levenshtein(a: string, b: string): number;
|
|
9
|
+
/**
|
|
10
|
+
* The closest candidate, when it is close enough to be a typo: within a
|
|
11
|
+
* third of the word's length (at least 2 edits), or one the word is a
|
|
12
|
+
* prefix of (`--strat` for `--strategy`).
|
|
13
|
+
*/
|
|
14
|
+
export declare function suggest(word: string, candidates: readonly string[]): string | undefined;
|
|
15
|
+
/** "Did you mean …?" or nothing. */
|
|
16
|
+
export declare function didYouMean(word: string, candidates: readonly string[]): string;
|
|
17
|
+
/** Every command the help text documents, in order. */
|
|
18
|
+
export declare function documentedCommands(help: string): string[];
|
|
19
|
+
/**
|
|
20
|
+
* One command's help, cut from the full text: its usage line(s), the options
|
|
21
|
+
* scoped to it, and its examples. Undefined when the help has no usage line
|
|
22
|
+
* for it.
|
|
23
|
+
*/
|
|
24
|
+
export declare function commandHelp(help: string, cmd: string): string | undefined;
|
package/dist/clihelp.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the CLI's argument errors and per-command help: a "did you
|
|
3
|
+
* mean" suggestion for a mistyped flag or command, and one command's lines
|
|
4
|
+
* cut out of the full help text. Kept apart from cli.ts, which runs on
|
|
5
|
+
* import, so they can be tested directly.
|
|
6
|
+
*/
|
|
7
|
+
/** Edit distance (insert, delete, substitute; each 1). */
|
|
8
|
+
export function levenshtein(a, b) {
|
|
9
|
+
if (a === b)
|
|
10
|
+
return 0;
|
|
11
|
+
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
12
|
+
for (let i = 1; i <= a.length; i++) {
|
|
13
|
+
const cur = [i];
|
|
14
|
+
for (let j = 1; j <= b.length; j++) {
|
|
15
|
+
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
16
|
+
}
|
|
17
|
+
prev = cur;
|
|
18
|
+
}
|
|
19
|
+
return prev[b.length];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The closest candidate, when it is close enough to be a typo: within a
|
|
23
|
+
* third of the word's length (at least 2 edits), or one the word is a
|
|
24
|
+
* prefix of (`--strat` for `--strategy`).
|
|
25
|
+
*/
|
|
26
|
+
export function suggest(word, candidates) {
|
|
27
|
+
let best;
|
|
28
|
+
for (const c of candidates) {
|
|
29
|
+
const d = levenshtein(word, c);
|
|
30
|
+
if (!best || d < best.d)
|
|
31
|
+
best = { c, d };
|
|
32
|
+
}
|
|
33
|
+
if (!best)
|
|
34
|
+
return undefined;
|
|
35
|
+
if (best.d <= Math.max(2, Math.floor(word.length / 3)))
|
|
36
|
+
return best.c;
|
|
37
|
+
const bare = word.replace(/^-+/, "");
|
|
38
|
+
return bare.length >= 3 ? candidates.find((c) => c.replace(/^-+/, "").startsWith(bare)) : undefined;
|
|
39
|
+
}
|
|
40
|
+
/** "Did you mean …?" or nothing. */
|
|
41
|
+
export function didYouMean(word, candidates) {
|
|
42
|
+
const s = suggest(word, candidates);
|
|
43
|
+
return s ? ` Did you mean ${s}?` : "";
|
|
44
|
+
}
|
|
45
|
+
/** Split help text into entries: a line indented 2 spaces, plus the deeper-indented lines under it. */
|
|
46
|
+
function entries(help) {
|
|
47
|
+
const out = [];
|
|
48
|
+
let section = "";
|
|
49
|
+
let cur;
|
|
50
|
+
for (const line of help.split("\n")) {
|
|
51
|
+
if (/^\S.*:\s*$/.test(line)) {
|
|
52
|
+
section = line.trim().replace(/:$/, "");
|
|
53
|
+
cur = undefined;
|
|
54
|
+
}
|
|
55
|
+
else if (/^\S/.test(line)) {
|
|
56
|
+
section = "";
|
|
57
|
+
cur = undefined;
|
|
58
|
+
}
|
|
59
|
+
else if (/^ {2}\S/.test(line)) {
|
|
60
|
+
cur = { section, lines: [line] };
|
|
61
|
+
out.push(cur);
|
|
62
|
+
}
|
|
63
|
+
else if (/^ {3,}\S/.test(line) && cur) {
|
|
64
|
+
cur.lines.push(line);
|
|
65
|
+
}
|
|
66
|
+
else if (line.trim() === "") {
|
|
67
|
+
cur = undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
/** Commands a usage line documents: ` context-doctor <cmd> …`. */
|
|
73
|
+
function usageCommand(line) {
|
|
74
|
+
return /^ {2}context-doctor\s+([a-z][\w-]*)/.exec(line)?.[1];
|
|
75
|
+
}
|
|
76
|
+
/** Does an option's text scope it to `cmd`, as in "(savings, compact-window)" or "(analyze/session)"? */
|
|
77
|
+
function optionScoped(text, cmd) {
|
|
78
|
+
for (const m of text.matchAll(/\(([^)]*)\)/g)) {
|
|
79
|
+
const names = m[1].split(/[,/]/).map((s) => s.trim().split(/\s+/)[0]);
|
|
80
|
+
if (names.includes(cmd))
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
/** Every command the help text documents, in order. */
|
|
86
|
+
export function documentedCommands(help) {
|
|
87
|
+
const seen = new Set();
|
|
88
|
+
for (const e of entries(help)) {
|
|
89
|
+
if (e.section === "Options" || e.section === "Examples")
|
|
90
|
+
continue;
|
|
91
|
+
const c = usageCommand(e.lines[0]);
|
|
92
|
+
if (c)
|
|
93
|
+
seen.add(c);
|
|
94
|
+
}
|
|
95
|
+
return [...seen];
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* One command's help, cut from the full text: its usage line(s), the options
|
|
99
|
+
* scoped to it, and its examples. Undefined when the help has no usage line
|
|
100
|
+
* for it.
|
|
101
|
+
*/
|
|
102
|
+
export function commandHelp(help, cmd) {
|
|
103
|
+
const all = entries(help);
|
|
104
|
+
const usage = all.filter((e) => e.section !== "Options" && e.section !== "Examples" && usageCommand(e.lines[0]) === cmd);
|
|
105
|
+
if (usage.length === 0)
|
|
106
|
+
return undefined;
|
|
107
|
+
const options = all.filter((e) => e.section === "Options" && optionScoped(e.lines.join(" "), cmd));
|
|
108
|
+
const examples = all.filter((e) => e.section === "Examples" && usageCommand(e.lines[0]) === cmd);
|
|
109
|
+
const out = ["Usage:", ...usage.flatMap((e) => e.lines)];
|
|
110
|
+
if (options.length)
|
|
111
|
+
out.push("", "Options:", ...options.flatMap((e) => e.lines));
|
|
112
|
+
if (examples.length)
|
|
113
|
+
out.push("", "Examples:", ...examples.flatMap((e) => e.lines));
|
|
114
|
+
out.push("", "All commands and options: context-doctor --help");
|
|
115
|
+
return out.join("\n");
|
|
116
|
+
}
|
package/dist/compactquality.d.ts
CHANGED
|
@@ -40,6 +40,6 @@ export interface CompactionQuality {
|
|
|
40
40
|
after: Signals;
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
|
-
export declare function compactionQuality(days?: number, paths?: string[]): CompactionQuality;
|
|
43
|
+
export declare function compactionQuality(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): CompactionQuality;
|
|
44
44
|
export declare function renderCompactionQuality(q: CompactionQuality, days?: number): string;
|
|
45
45
|
export {};
|
package/dist/compactquality.js
CHANGED
|
@@ -37,7 +37,7 @@ function add(s, reqs, readBefore) {
|
|
|
37
37
|
});
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
|
-
export function compactionQuality(days = 60, paths) {
|
|
40
|
+
export function compactionQuality(days = 60, paths, onProgress) {
|
|
41
41
|
const since = Date.now() - days * 86_400_000;
|
|
42
42
|
const files = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
43
43
|
const shapedAt = readLedger().filter((e) => e.ev === "precompact").map((e) => e.ts);
|
|
@@ -45,7 +45,8 @@ export function compactionQuality(days = 60, paths) {
|
|
|
45
45
|
const shaped = { compactions: 0, before: empty(), after: empty() };
|
|
46
46
|
// A forked session copies its parent's compactions (same row uuid): one compaction, counted once.
|
|
47
47
|
const countedBoundaries = new Set();
|
|
48
|
-
for (const path of files) {
|
|
48
|
+
for (const [fileIndex, path] of files.entries()) {
|
|
49
|
+
onProgress?.(fileIndex, files.length);
|
|
49
50
|
const reqs = [];
|
|
50
51
|
/** `at` is NaN when the row carries no timestamp. */
|
|
51
52
|
const boundaries = [];
|
package/dist/compactwindow.d.ts
CHANGED
|
@@ -14,14 +14,20 @@
|
|
|
14
14
|
* The trade-off is real: more compactions, each replacing history with a
|
|
15
15
|
* summary. So this measures both sides on the user's own history and changes
|
|
16
16
|
* nothing until asked. The replay uses the usage every transcript records;
|
|
17
|
-
* its baseline came within 9% of the billed figure on the author's history
|
|
18
|
-
*
|
|
17
|
+
* its baseline came within 9% of the billed figure on the author's history.
|
|
18
|
+
* Like `savings`, the replay decides each session's SHARE saved, and that
|
|
19
|
+
* share is applied to what the session was billed (its recorded usage at
|
|
20
|
+
* list price): "as now" is the same billed figure `savings` shows, over the
|
|
21
|
+
* same sessions (10+ requests in the window), so the two never disagree.
|
|
19
22
|
*/
|
|
20
23
|
export declare const MIN_WINDOW = 100000;
|
|
21
24
|
export declare const MAX_WINDOW = 1000000;
|
|
22
25
|
export interface WindowEstimate {
|
|
23
26
|
window: number;
|
|
27
|
+
/** Input billed as the sessions ran ("as now"): recorded usage at list price, as `savings` reports it. */
|
|
24
28
|
baselineUsd: number;
|
|
29
|
+
/** The replay's own model of the same baseline, from which each session's share saved is taken. */
|
|
30
|
+
replayBaselineUsd: number;
|
|
25
31
|
withWindowUsd: number;
|
|
26
32
|
savedUsd: number;
|
|
27
33
|
savedPct: number;
|
|
@@ -30,19 +36,37 @@ export interface WindowEstimate {
|
|
|
30
36
|
}
|
|
31
37
|
export interface CompactWindowReport {
|
|
32
38
|
days: number;
|
|
39
|
+
/** Sessions with 10+ requests in the period: the ones replayed (the same rule as `savings`). */
|
|
33
40
|
sessions: number;
|
|
41
|
+
/** Claude Code transcripts written in the period, replayed or not. */
|
|
42
|
+
transcripts: number;
|
|
34
43
|
/** Compactions that actually happened over the period (Claude Code's own, or /compact). */
|
|
35
44
|
actualCompactions: number;
|
|
36
45
|
estimates: WindowEstimate[];
|
|
37
46
|
/** Re-read tokens charged to each simulated compaction (0 when not measured). */
|
|
38
47
|
rereadTokens?: number;
|
|
39
48
|
}
|
|
40
|
-
export declare function estimateCompactWindows(windows: number[], days?: number, paths?: string[], rereadTokens?: number): CompactWindowReport;
|
|
49
|
+
export declare function estimateCompactWindows(windows: number[], days?: number, paths?: string[], rereadTokens?: number, onProgress?: (done: number, total: number) => void): CompactWindowReport;
|
|
50
|
+
/** "37 sessions with 10+ requests (of 85 transcripts)": what the replayed reports count, said the same way. */
|
|
51
|
+
export declare function sessionsLabel(sessions: number, transcripts: number): string;
|
|
41
52
|
export declare function settingsPath(home?: string): string;
|
|
42
53
|
/** The autoCompactWindow Claude Code will use from user settings, if set. */
|
|
43
54
|
export declare function currentCompactWindow(home?: string): number | undefined;
|
|
44
|
-
/**
|
|
45
|
-
export
|
|
55
|
+
/** What setCompactWindow did, so the CLI can say exactly that. */
|
|
56
|
+
export interface SetWindowResult {
|
|
57
|
+
/** False when the setting already was what was asked (or, for off, was never set). */
|
|
58
|
+
changed: boolean;
|
|
59
|
+
/** settings.json did not exist and was created. */
|
|
60
|
+
created: boolean;
|
|
61
|
+
/** The copy of the previous settings.json, when there was one to copy. */
|
|
62
|
+
backup?: string;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json.
|
|
66
|
+
* Nothing is written when nothing changes: `off` with no window set used to
|
|
67
|
+
* create a settings.json of `{}`. A .backup is kept when there was a file.
|
|
68
|
+
*/
|
|
69
|
+
export declare function setCompactWindow(window: number | undefined, home?: string): SetWindowResult;
|
|
46
70
|
/** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
|
|
47
71
|
export declare function parseWindow(raw: string): number | undefined;
|
|
48
72
|
export declare function renderCompactWindows(r: CompactWindowReport, current?: number): string;
|
package/dist/compactwindow.js
CHANGED
|
@@ -14,16 +14,20 @@
|
|
|
14
14
|
* The trade-off is real: more compactions, each replacing history with a
|
|
15
15
|
* summary. So this measures both sides on the user's own history and changes
|
|
16
16
|
* nothing until asked. The replay uses the usage every transcript records;
|
|
17
|
-
* its baseline came within 9% of the billed figure on the author's history
|
|
18
|
-
*
|
|
17
|
+
* its baseline came within 9% of the billed figure on the author's history.
|
|
18
|
+
* Like `savings`, the replay decides each session's SHARE saved, and that
|
|
19
|
+
* share is applied to what the session was billed (its recorded usage at
|
|
20
|
+
* list price): "as now" is the same billed figure `savings` shows, over the
|
|
21
|
+
* same sessions (10+ requests in the window), so the two never disagree.
|
|
19
22
|
*/
|
|
20
23
|
import { existsSync, readFileSync } from "node:fs";
|
|
21
24
|
import { homedir } from "node:os";
|
|
22
25
|
import { join } from "node:path";
|
|
23
26
|
import { forEachLine, listSessions, replyCounter } from "./session.js";
|
|
24
|
-
import { cacheWriteSplit, pricingFor, writeMultiplier } from "./pricing.js";
|
|
27
|
+
import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
|
|
25
28
|
import { realModel } from "./tokens.js";
|
|
26
29
|
import { readJson, writeJsonWithBackup } from "./install.js";
|
|
30
|
+
import { withInvocation } from "./invocation.js";
|
|
27
31
|
/** Claude Code compacts at about this share of the window (970k of 1M, measured). */
|
|
28
32
|
const TRIGGER_SHARE = 0.97;
|
|
29
33
|
/** Context right after a compaction: system prompt, tools and the summary (median 75,447, measured). */
|
|
@@ -80,7 +84,7 @@ function readRequests(path, runRows) {
|
|
|
80
84
|
const w = cacheWriteSplit(u);
|
|
81
85
|
writes5m += w.fiveMinute;
|
|
82
86
|
writes1h += w.oneHour;
|
|
83
|
-
reqs.push({ at, prompt, inPerM: p?.inputPerM ?? 0, readPerM: p?.cacheReadPerM ?? 0, outPerM: p?.outputPerM ?? 0, copy: seen === "copy" });
|
|
87
|
+
reqs.push({ at, prompt, inPerM: p?.inputPerM ?? 0, readPerM: p?.cacheReadPerM ?? 0, outPerM: p?.outputPerM ?? 0, copy: seen === "copy", billedUsd: p ? usageCost(u, p).promptUsd : 0 });
|
|
84
88
|
});
|
|
85
89
|
return { reqs, writeMult: writeMultiplier(writes5m, writes1h), priced };
|
|
86
90
|
}
|
|
@@ -148,14 +152,15 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25) {
|
|
|
148
152
|
}
|
|
149
153
|
return { base, sim, extra, actual };
|
|
150
154
|
}
|
|
151
|
-
export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0) {
|
|
155
|
+
export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0, onProgress) {
|
|
152
156
|
const since = Date.now() - days * 86_400_000;
|
|
153
157
|
const targets = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
154
|
-
const acc = windows.map((w) => ({ window: w,
|
|
158
|
+
const acc = windows.map((w) => ({ window: w, billed: 0, saved: 0, replayBase: 0, extra: 0 }));
|
|
155
159
|
let sessions = 0, actualCompactions = 0;
|
|
156
160
|
// Shared by every transcript of the run, so a fork's copy counts once.
|
|
157
161
|
const runRows = new Set();
|
|
158
|
-
for (const p of targets) {
|
|
162
|
+
for (const [i, p] of targets.entries()) {
|
|
163
|
+
onProgress?.(i, targets.length);
|
|
159
164
|
let parsed;
|
|
160
165
|
try {
|
|
161
166
|
parsed = readRequests(p, runRows);
|
|
@@ -163,32 +168,47 @@ export function estimateCompactWindows(windows, days = 30, paths, rereadTokens =
|
|
|
163
168
|
catch {
|
|
164
169
|
continue;
|
|
165
170
|
}
|
|
166
|
-
|
|
171
|
+
// The same sessions `savings` counts: 10+ requests of its own in the
|
|
172
|
+
// period. An unpriced session counts too, at $0, as it does there.
|
|
173
|
+
const counted = parsed.reqs.filter((r) => !("compact" in r) && r.at >= since && !r.copy);
|
|
174
|
+
if (counted.length < 10)
|
|
167
175
|
continue;
|
|
168
176
|
sessions++;
|
|
177
|
+
const billed = counted.reduce((n, r) => n + r.billedUsd, 0);
|
|
169
178
|
actualCompactions += replay(parsed.reqs, Number.MAX_SAFE_INTEGER, since, 0, parsed.writeMult).actual;
|
|
170
179
|
for (const a of acc) {
|
|
171
180
|
const r = replay(parsed.reqs, a.window, since, rereadTokens, parsed.writeMult);
|
|
172
|
-
|
|
173
|
-
|
|
181
|
+
// The replay's share saved, applied to what this session was billed.
|
|
182
|
+
const share = r.base > 0 ? (r.base - r.sim) / r.base : 0;
|
|
183
|
+
a.billed += billed;
|
|
184
|
+
a.saved += share * billed;
|
|
185
|
+
a.replayBase += r.base / 1e6;
|
|
174
186
|
a.extra += r.extra;
|
|
175
187
|
}
|
|
176
188
|
}
|
|
189
|
+
onProgress?.(targets.length, targets.length);
|
|
177
190
|
return {
|
|
178
191
|
days,
|
|
179
192
|
sessions,
|
|
193
|
+
transcripts: targets.length,
|
|
180
194
|
actualCompactions,
|
|
181
195
|
rereadTokens,
|
|
182
196
|
estimates: acc.map((a) => ({
|
|
183
197
|
window: a.window,
|
|
184
|
-
baselineUsd: a.
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
198
|
+
baselineUsd: a.billed,
|
|
199
|
+
replayBaselineUsd: a.replayBase,
|
|
200
|
+
withWindowUsd: a.billed - a.saved,
|
|
201
|
+
savedUsd: a.saved,
|
|
202
|
+
savedPct: a.billed > 0 ? a.saved / a.billed : 0,
|
|
188
203
|
compactions: a.extra,
|
|
189
204
|
})),
|
|
190
205
|
};
|
|
191
206
|
}
|
|
207
|
+
/** "37 sessions with 10+ requests (of 85 transcripts)": what the replayed reports count, said the same way. */
|
|
208
|
+
export function sessionsLabel(sessions, transcripts) {
|
|
209
|
+
const s = `${sessions} session${sessions === 1 ? "" : "s"} with 10+ requests`;
|
|
210
|
+
return transcripts > sessions ? `${s} (of ${transcripts} transcripts)` : s;
|
|
211
|
+
}
|
|
192
212
|
export function settingsPath(home = homedir()) {
|
|
193
213
|
return join(home, ".claude", "settings.json");
|
|
194
214
|
}
|
|
@@ -205,18 +225,27 @@ export function currentCompactWindow(home = homedir()) {
|
|
|
205
225
|
return undefined;
|
|
206
226
|
}
|
|
207
227
|
}
|
|
208
|
-
/**
|
|
228
|
+
/**
|
|
229
|
+
* Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json.
|
|
230
|
+
* Nothing is written when nothing changes: `off` with no window set used to
|
|
231
|
+
* create a settings.json of `{}`. A .backup is kept when there was a file.
|
|
232
|
+
*/
|
|
209
233
|
export function setCompactWindow(window, home = homedir()) {
|
|
210
234
|
if (window !== undefined && (!Number.isInteger(window) || window < MIN_WINDOW || window > MAX_WINDOW)) {
|
|
211
235
|
throw new Error(`window must be a whole number of tokens between ${MIN_WINDOW} and ${MAX_WINDOW}`);
|
|
212
236
|
}
|
|
213
237
|
const p = settingsPath(home);
|
|
238
|
+
const existed = existsSync(p);
|
|
214
239
|
const settings = readJson(p);
|
|
240
|
+
if (window === undefined ? !("autoCompactWindow" in settings) : settings.autoCompactWindow === window) {
|
|
241
|
+
return { changed: false, created: false };
|
|
242
|
+
}
|
|
215
243
|
if (window === undefined)
|
|
216
244
|
delete settings.autoCompactWindow;
|
|
217
245
|
else
|
|
218
246
|
settings.autoCompactWindow = window;
|
|
219
247
|
writeJsonWithBackup(p, settings);
|
|
248
|
+
return { changed: true, created: !existed, backup: existed ? `${p}.context-doctor.backup` : undefined };
|
|
220
249
|
}
|
|
221
250
|
/** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
|
|
222
251
|
export function parseWindow(raw) {
|
|
@@ -231,12 +260,13 @@ const k = (n) => `${Math.round(n / 1000)}k`;
|
|
|
231
260
|
export function renderCompactWindows(r, current) {
|
|
232
261
|
const lines = [];
|
|
233
262
|
lines.push("Auto-compact window: compact earlier, automatically (Claude Code's own setting)");
|
|
234
|
-
|
|
263
|
+
// Counted and said exactly as `savings` says it, so the two screens agree.
|
|
264
|
+
lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, at list prices`);
|
|
235
265
|
lines.push("─".repeat(66));
|
|
236
266
|
lines.push(`Now: ${current ? `${k(current)} (set in ~/.claude/settings.json)` : "not set: Claude Code compacts near the model's full window"}`);
|
|
237
267
|
if (r.sessions === 0) {
|
|
238
268
|
lines.push("No sessions with 10+ requests in the window to replay.");
|
|
239
|
-
return lines.join("\n");
|
|
269
|
+
return withInvocation(lines.join("\n"));
|
|
240
270
|
}
|
|
241
271
|
lines.push("");
|
|
242
272
|
lines.push(" window input cost saved compactions");
|
|
@@ -246,6 +276,8 @@ export function renderCompactWindows(r, current) {
|
|
|
246
276
|
}
|
|
247
277
|
lines.push(` as now ${usd(r.estimates[0]?.baselineUsd ?? 0).padStart(10)} ${String(r.actualCompactions).padStart(4)} (${((r.actualCompactions / r.days) * 7).toFixed(1)}/week)`);
|
|
248
278
|
lines.push("");
|
|
279
|
+
lines.push("\"as now\" is what you were billed (transcript usage at list price, as in");
|
|
280
|
+
lines.push("`context-doctor savings`); each window saves the replay's share of it.");
|
|
249
281
|
if (r.rereadTokens) {
|
|
250
282
|
lines.push(`Each simulated compaction also pays for ~${Math.round(r.rereadTokens / 100) / 10}k tokens of files read again afterwards`);
|
|
251
283
|
lines.push("(measured on your compactions: context-doctor compactions).");
|
|
@@ -253,5 +285,5 @@ export function renderCompactWindows(r, current) {
|
|
|
253
285
|
lines.push("Each compaction replaces the session's history with a summary, so a smaller");
|
|
254
286
|
lines.push("window trades detail for cost. Set one with: context-doctor compact-window 400k");
|
|
255
287
|
lines.push("Undo with: context-doctor compact-window off");
|
|
256
|
-
return lines.join("\n");
|
|
288
|
+
return withInvocation(lines.join("\n"));
|
|
257
289
|
}
|
package/dist/diff.js
CHANGED
|
@@ -22,14 +22,36 @@ import { formatUsd } from "./pricing.js";
|
|
|
22
22
|
* conversations.json and Gemini chats are .json, and read as a plain
|
|
23
23
|
* conversation they became one message of raw text. A file it finds no
|
|
24
24
|
* messages in is a plain conversation (OpenAI/Anthropic messages JSON), as in
|
|
25
|
-
* `watch`.
|
|
25
|
+
* `watch`. A saved profile (`analyze --json` output) is used as it is.
|
|
26
|
+
*
|
|
27
|
+
* Anything else is an error: a file that is not a conversation used to
|
|
28
|
+
* profile as 0 tokens, and the diff reported a 0 → 0 "comparison".
|
|
26
29
|
*/
|
|
27
30
|
function loadProfile(path, model) {
|
|
28
31
|
const session = parseSessionFile(path);
|
|
29
32
|
if (session.messageCount > 0) {
|
|
30
33
|
return profileConversation(parseConversation(session.conversationJson), model ?? session.model);
|
|
31
34
|
}
|
|
32
|
-
|
|
35
|
+
const text = readFileSync(path, "utf8");
|
|
36
|
+
const saved = savedProfile(text);
|
|
37
|
+
if (saved)
|
|
38
|
+
return saved;
|
|
39
|
+
const conversation = parseConversation(text);
|
|
40
|
+
if (conversation.parseWarning)
|
|
41
|
+
throw new Error(`${path}: ${conversation.parseWarning}`);
|
|
42
|
+
return profileConversation(conversation, model);
|
|
43
|
+
}
|
|
44
|
+
/** The JSON `analyze --json` prints, recognised by the fields every profile has. */
|
|
45
|
+
function savedProfile(text) {
|
|
46
|
+
try {
|
|
47
|
+
const p = JSON.parse(text);
|
|
48
|
+
const ok = p && typeof p === "object" && !Array.isArray(p) && typeof p.totalTokens === "number" &&
|
|
49
|
+
typeof p.messageCount === "number" && p.categories && typeof p.categories === "object" && Array.isArray(p.findings);
|
|
50
|
+
return ok ? p : undefined;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
33
55
|
}
|
|
34
56
|
function signed(n) {
|
|
35
57
|
return n === 0 ? "±0" : `${n > 0 ? "+" : "−"}${formatTokens(Math.abs(n))}`;
|
package/dist/doctor.d.ts
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* `context-doctor doctor` — self-check for a local installation.
|
|
3
3
|
*
|
|
4
4
|
* Verifies every integration point end to end and prints one ✓/✗/– line per
|
|
5
|
-
* check, so "it doesn't work" becomes a single pasteable diagnosis.
|
|
6
|
-
*
|
|
5
|
+
* check, so "it doesn't work" becomes a single pasteable diagnosis. Exits 1
|
|
6
|
+
* when any check fails (✗), so a script can tell; an app that is absent, or
|
|
7
|
+
* that nothing was installed into, is a note (–), not a failure.
|
|
7
8
|
*/
|
|
8
9
|
export declare function runDoctor(): Promise<void>;
|