context-doctor 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +28 -19
  2. package/dist/antigravity.d.ts +44 -0
  3. package/dist/antigravity.js +80 -0
  4. package/dist/autoclear.d.ts +15 -0
  5. package/dist/autoclear.js +17 -0
  6. package/dist/autopilot.js +3 -2
  7. package/dist/cachemisses.d.ts +56 -2
  8. package/dist/cachemisses.js +252 -42
  9. package/dist/cachettl.d.ts +127 -0
  10. package/dist/cachettl.js +357 -0
  11. package/dist/claudedir.d.ts +17 -0
  12. package/dist/claudedir.js +32 -0
  13. package/dist/cli.js +303 -26
  14. package/dist/coldresume.d.ts +15 -0
  15. package/dist/coldresume.js +60 -11
  16. package/dist/compactquality.d.ts +5 -0
  17. package/dist/compactquality.js +108 -61
  18. package/dist/compactwindow.d.ts +14 -5
  19. package/dist/compactwindow.js +36 -43
  20. package/dist/doctor.d.ts +14 -0
  21. package/dist/doctor.js +94 -8
  22. package/dist/effective.d.ts +55 -0
  23. package/dist/effective.js +163 -0
  24. package/dist/experiment.js +2 -2
  25. package/dist/extract.js +4 -1
  26. package/dist/fanout.js +2 -2
  27. package/dist/fix.d.ts +176 -0
  28. package/dist/fix.js +574 -0
  29. package/dist/hook.js +2 -2
  30. package/dist/install.d.ts +27 -1
  31. package/dist/install.js +248 -37
  32. package/dist/ledger.js +2 -2
  33. package/dist/lens.d.ts +2 -0
  34. package/dist/lens.js +50 -24
  35. package/dist/limits.d.ts +10 -0
  36. package/dist/limits.js +36 -12
  37. package/dist/mcp.js +61 -61
  38. package/dist/mcpclient.js +28 -28
  39. package/dist/mcpschema.d.ts +18 -0
  40. package/dist/mcpschema.js +74 -31
  41. package/dist/missledger.d.ts +61 -0
  42. package/dist/missledger.js +198 -0
  43. package/dist/overhead.js +22 -25
  44. package/dist/profile.js +8 -8
  45. package/dist/proxy.d.ts +1 -1
  46. package/dist/proxy.js +2 -1
  47. package/dist/prune.d.ts +4 -0
  48. package/dist/prune.js +89 -49
  49. package/dist/reads.js +2 -2
  50. package/dist/recall.js +2 -1
  51. package/dist/savings.d.ts +5 -9
  52. package/dist/savings.js +217 -115
  53. package/dist/scan.d.ts +96 -0
  54. package/dist/scan.js +482 -0
  55. package/dist/session.d.ts +6 -0
  56. package/dist/session.js +16 -3
  57. package/dist/settingsedit.d.ts +72 -0
  58. package/dist/settingsedit.js +493 -0
  59. package/dist/statusline.d.ts +38 -2
  60. package/dist/statusline.js +66 -4
  61. package/dist/subagentpay.js +2 -2
  62. package/dist/tasks.js +2 -2
  63. package/dist/tokens.d.ts +5 -0
  64. package/dist/tokens.js +11 -1
  65. package/package.json +2 -2
@@ -15,13 +15,93 @@
15
15
  * Compactions shaped by context-doctor's PreCompact hook are reported apart,
16
16
  * so its effect can be seen as it accumulates.
17
17
  */
18
- import { forEachLine, listSessions, queuedUserPrompt } from "./session.js";
18
+ import { listSessions, queuedUserPrompt, isClaudeSession } from "./session.js";
19
+ import { rowsOf } from "./scan.js";
19
20
  import { readLedger } from "./ledger.js";
20
21
  import { estimateTokens, formatTokens } from "./tokens.js";
21
22
  import { isIdleCompactNotice } from "./coldresume.js";
22
23
  const WINDOW = 15;
23
24
  const CORRECTION = /^(no\b|nope\b|wrong\b|that'?s (not|wrong)|not what i|you forgot|i (said|told you|asked)|revert\b|undo\b|stop\b|again\??$|why did you)/i;
24
25
  const empty = () => ({ requests: 0, rereads: 0, rereadTokens: 0, reads: 0, calls: 0, errors: 0, userMsgs: 0, corrections: 0 });
26
+ export const QUALITY_ROWS = {
27
+ id: "quality.1",
28
+ init: () => ({ reads: {} }),
29
+ line(_raw, row, out, st) {
30
+ let e;
31
+ try {
32
+ e = row();
33
+ }
34
+ catch {
35
+ return;
36
+ }
37
+ if (!e || e.isSidechain)
38
+ return;
39
+ if (e.type === "system" && e.subtype === "compact_boundary") {
40
+ out.push({ k: "b", ...(typeof e.uuid === "string" ? { uuid: e.uuid } : {}), ...(e.timestamp !== undefined ? { ts: e.timestamp } : {}) });
41
+ return;
42
+ }
43
+ if (isIdleCompactNotice(e)) {
44
+ out.push({ k: "i" });
45
+ return;
46
+ }
47
+ // Typed while the agent worked: a user message recorded only as an
48
+ // attachment, and the likeliest moment for a "no, stop" to arrive.
49
+ const queued = queuedUserPrompt(e);
50
+ if (queued !== undefined) {
51
+ const text = typeof queued === "string" ? queued : queued.map((b) => (typeof b?.text === "string" ? b.text : "")).join(" ");
52
+ out.push({ k: "u", corr: CORRECTION.test(text.trim()) ? 1 : 0 });
53
+ return;
54
+ }
55
+ const c = e.message?.content;
56
+ if (e.type === "assistant") {
57
+ // A request starts at a reply with usage whose id differs from the last request's.
58
+ const n = e.message?.id !== st.lastId && e.message?.usage;
59
+ if (n)
60
+ st.lastId = e.message.id;
61
+ let calls = 0;
62
+ const reads = [];
63
+ if (Array.isArray(c)) {
64
+ for (const b of c) {
65
+ if (b?.type !== "tool_use")
66
+ continue;
67
+ calls++;
68
+ if (b.name === "Read" && typeof b.input?.file_path === "string") {
69
+ reads.push([b.id, b.input.file_path]);
70
+ st.reads[String(b.id)] = 1;
71
+ }
72
+ }
73
+ }
74
+ if (n)
75
+ out.push({ k: "a", n: 1, ...(e.timestamp !== undefined ? { ts: e.timestamp } : {}), calls, reads });
76
+ else if (calls)
77
+ out.push({ k: "a", calls, reads });
78
+ }
79
+ else if (e.type === "user") {
80
+ if (typeof c === "string" && !e.isMeta && !e.isCompactSummary) {
81
+ out.push({ k: "u", corr: CORRECTION.test(c.trim()) ? 1 : 0 });
82
+ }
83
+ else if (Array.isArray(c)) {
84
+ let err = 0;
85
+ const r = [];
86
+ for (const b of c) {
87
+ if (b?.type !== "tool_result")
88
+ continue;
89
+ if (b.is_error) {
90
+ err++;
91
+ continue;
92
+ }
93
+ // Only a Read's result is ever counted: the rest are not sized.
94
+ if (!st.reads[String(b.tool_use_id)])
95
+ continue;
96
+ const text = typeof b.content === "string" ? b.content : JSON.stringify(b.content ?? "");
97
+ r.push([b.tool_use_id, estimateTokens(text, "claude-opus-5")]);
98
+ }
99
+ if (err || r.length)
100
+ out.push({ k: "t", err, r });
101
+ }
102
+ }
103
+ },
104
+ };
25
105
  function add(s, reqs, readBefore) {
26
106
  for (const r of reqs) {
27
107
  s.requests++;
@@ -40,7 +120,7 @@ function add(s, reqs, readBefore) {
40
120
  }
41
121
  export function compactionQuality(days = 60, paths, onProgress) {
42
122
  const since = Date.now() - days * 86_400_000;
43
- const files = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
123
+ const files = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
44
124
  const shapedAt = readLedger().filter((e) => e.ev === "precompact").map((e) => e.ts);
45
125
  const q = { compactions: 0, idle: 0, extraRereadTokensPerCompaction: 0, sessions: 0, before: empty(), after: empty() };
46
126
  const shaped = { compactions: 0, before: empty(), after: empty() };
@@ -54,8 +134,7 @@ export function compactionQuality(days = 60, paths, onProgress) {
54
134
  let cur;
55
135
  // User messages between a compaction and the next request belong to the "after" side.
56
136
  let pendingUser = 0, pendingCorrections = 0;
57
- const userMessage = (text) => {
58
- const corr = CORRECTION.test(text.trim()) ? 1 : 0;
137
+ const userMessage = (corr) => {
59
138
  if (cur) {
60
139
  cur.userMsgs++;
61
140
  cur.corrections += corr;
@@ -66,79 +145,47 @@ export function compactionQuality(days = 60, paths, onProgress) {
66
145
  }
67
146
  };
68
147
  const readIds = new Map();
69
- let lastId;
70
- forEachLine(path, (line) => {
71
- let e;
72
- try {
73
- e = JSON.parse(line);
74
- }
75
- catch {
76
- return;
77
- }
78
- if (!e || e.isSidechain)
79
- return;
80
- const at = Date.parse(e.timestamp);
81
- if (e.type === "system" && e.subtype === "compact_boundary") {
82
- const copy = typeof e.uuid === "string" && countedBoundaries.has(e.uuid);
83
- if (typeof e.uuid === "string")
84
- countedBoundaries.add(e.uuid);
148
+ for (const r of rowsOf(path, QUALITY_ROWS)) {
149
+ if (r.k === "b") {
150
+ const copy = r.uuid !== undefined && countedBoundaries.has(r.uuid);
151
+ if (r.uuid !== undefined)
152
+ countedBoundaries.add(r.uuid);
85
153
  if (!copy)
86
- boundaries.push({ index: reqs.length, at });
154
+ boundaries.push({ index: reqs.length, at: Date.parse(r.ts) });
87
155
  cur = undefined;
88
- return;
89
156
  }
90
- // Claude Code's idle compaction writes this right after its boundary.
91
- if (isIdleCompactNotice(e)) {
157
+ else if (r.k === "i") {
158
+ // Claude Code's idle compaction writes this right after its boundary.
92
159
  const last = boundaries[boundaries.length - 1];
93
160
  if (last && last.index === reqs.length)
94
161
  last.idle = true;
95
- return;
96
162
  }
97
- // Typed while the agent worked: a user message recorded only as an
98
- // attachment, and the likeliest moment for a "no, stop" to arrive.
99
- const queued = queuedUserPrompt(e);
100
- if (queued !== undefined) {
101
- userMessage(typeof queued === "string" ? queued : queued.map((b) => (typeof b?.text === "string" ? b.text : "")).join(" "));
102
- return;
163
+ else if (r.k === "u") {
164
+ userMessage(r.corr);
103
165
  }
104
- const c = e.message?.content;
105
- if (e.type === "assistant") {
106
- if (e.message?.id !== lastId && e.message?.usage) {
107
- lastId = e.message.id;
108
- cur = { at, reads: [], readTokens: [], calls: 0, errors: 0, userMsgs: pendingUser, corrections: pendingCorrections };
166
+ else if (r.k === "a") {
167
+ if (r.n) {
168
+ cur = { at: Date.parse(r.ts), reads: [], readTokens: [], calls: 0, errors: 0, userMsgs: pendingUser, corrections: pendingCorrections };
109
169
  pendingUser = pendingCorrections = 0;
110
170
  reqs.push(cur);
111
171
  }
112
- if (cur && Array.isArray(c)) {
113
- for (const b of c) {
114
- if (b?.type !== "tool_use")
115
- continue;
116
- cur.calls++;
117
- if (b.name === "Read" && typeof b.input?.file_path === "string")
118
- readIds.set(b.id, b.input.file_path);
119
- }
172
+ if (cur) {
173
+ cur.calls += r.calls;
174
+ for (const [id, file] of r.reads)
175
+ readIds.set(id, file);
120
176
  }
121
177
  }
122
- else if (e.type === "user") {
123
- if (typeof c === "string" && !e.isMeta && !e.isCompactSummary) {
124
- userMessage(c);
125
- }
126
- else if (cur && Array.isArray(c)) {
127
- for (const b of c) {
128
- if (b?.type !== "tool_result")
129
- continue;
130
- if (b.is_error)
131
- cur.errors++;
132
- const p = readIds.get(b.tool_use_id);
133
- if (p && !b.is_error) {
134
- cur.reads.push(p);
135
- const text = typeof b.content === "string" ? b.content : JSON.stringify(b.content ?? "");
136
- cur.readTokens.push(estimateTokens(text, "claude-opus-5"));
137
- }
178
+ else if (cur) {
179
+ cur.errors += r.err;
180
+ for (const [id, tokens] of r.r) {
181
+ const p = readIds.get(id);
182
+ if (p) {
183
+ cur.reads.push(p);
184
+ cur.readTokens.push(tokens);
138
185
  }
139
186
  }
140
187
  }
141
- });
188
+ }
142
189
  let counted = false;
143
190
  for (const b of boundaries) {
144
191
  // Each compaction by its own time: a session touched in the window
@@ -52,8 +52,14 @@ export declare function estimateCompactWindows(windows: number[], days?: number,
52
52
  /** "37 sessions with 10+ requests (of 85 transcripts)": what the replayed reports count, said the same way. */
53
53
  export declare function sessionsLabel(sessions: number, transcripts: number): string;
54
54
  export declare function settingsPath(home?: string): string;
55
- /** The autoCompactWindow Claude Code will use from user settings, if set. */
56
- export declare function currentCompactWindow(home?: string): number | undefined;
55
+ /**
56
+ * The auto-compact window Claude Code will use, when it is a number: managed,
57
+ * project and user settings merged, CLAUDE_CODE_AUTO_COMPACT_WINDOW first
58
+ * (CLAUDE_CONFIG_DIR honoured). Undefined when none is set or it is "auto".
59
+ */
60
+ export declare function currentCompactWindow(home?: string, env?: NodeJS.ProcessEnv, cwd?: string): number | undefined;
61
+ /** What keeps a user-level autoCompactWindow from taking effect: environment, project or managed settings, per-model windows. */
62
+ export declare function compactWindowBlockers(home?: string, env?: NodeJS.ProcessEnv, cwd?: string): string[];
57
63
  /** What setCompactWindow did, so the CLI can say exactly that. */
58
64
  export interface SetWindowResult {
59
65
  /** False when the setting already was what was asked (or, for off, was never set). */
@@ -62,11 +68,14 @@ export interface SetWindowResult {
62
68
  created: boolean;
63
69
  /** The copy of the previous settings.json, when there was one to copy. */
64
70
  backup?: string;
71
+ /** The value before, as written (undefined: not set). */
72
+ previous?: unknown;
65
73
  }
66
74
  /**
67
- * Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json.
68
- * Nothing is written when nothing changes: `off` with no window set used to
69
- * create a settings.json of `{}`. A .backup is kept when there was a file.
75
+ * Set (or with undefined, remove) autoCompactWindow in the user's
76
+ * settings.json, editing only that key. Nothing is written when nothing
77
+ * changes: `off` with no window set used to create a settings.json of `{}`.
78
+ * A .backup is kept when there was a file.
70
79
  */
71
80
  export declare function setCompactWindow(window: number | undefined, home?: string): SetWindowResult;
72
81
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
@@ -20,15 +20,17 @@
20
20
  * list price): "as now" is the same billed figure `savings` shows, over the
21
21
  * same sessions (10+ requests in the window), so the two never disagree.
22
22
  */
23
- import { existsSync, readFileSync } from "node:fs";
24
- import { homedir } from "node:os";
25
23
  import { join } from "node:path";
26
- import { forEachLine, listSessions, replyCounter } from "./session.js";
24
+ import { listSessions, replyCounter, isClaudeSession } from "./session.js";
27
25
  import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
28
26
  import { realModel } from "./tokens.js";
29
- import { readJson, writeJsonWithBackup } from "./install.js";
27
+ import { backupOnce } from "./install.js";
28
+ import { ABSENT, readSettings, setJsonPath, writeAtomic } from "./settingsedit.js";
29
+ import { compactWindowOverrides, effectiveCompactWindow, settingsSources } from "./effective.js";
30
30
  import { withInvocation } from "./invocation.js";
31
- import { idleCompactMinTokens, isIdleCompactNotice } from "./coldresume.js";
31
+ import { idleCompactMinTokens, isIdleCompactNotice, REQUEST_ROWS } from "./coldresume.js";
32
+ import { rowsOf } from "./scan.js";
33
+ import { claudeDir } from "./claudedir.js";
32
34
  /** Claude Code compacts at about this share of the window (970k of 1M, measured). */
33
35
  const TRIGGER_SHARE = 0.97;
34
36
  /** Context right after a compaction: system prompt, tools and the summary (median 75,447, measured). */
@@ -50,14 +52,7 @@ function readRequests(path, runRows) {
50
52
  const reqs = [];
51
53
  let model, writes5m = 0, writes1h = 0, priced = false;
52
54
  const sighting = replyCounter(runRows);
53
- forEachLine(path, (line) => {
54
- let e;
55
- try {
56
- e = JSON.parse(line);
57
- }
58
- catch {
59
- return;
60
- }
55
+ rowsOf(path, REQUEST_ROWS).forEach((e) => {
61
56
  if (!e || e.isSidechain)
62
57
  return;
63
58
  if (e.type === "system" && e.subtype === "compact_boundary") {
@@ -174,7 +169,7 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
174
169
  }
175
170
  export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0, onProgress) {
176
171
  const since = Date.now() - days * 86_400_000;
177
- const targets = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
172
+ const targets = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
178
173
  const acc = windows.map((w) => ({ window: w, billed: 0, saved: 0, replayBase: 0, extra: 0 }));
179
174
  let sessions = 0, actualCompactions = 0, idleCompactions = 0;
180
175
  // Shared by every transcript of the run, so a fork's copy counts once.
@@ -232,43 +227,41 @@ export function sessionsLabel(sessions, transcripts) {
232
227
  const s = `${sessions} session${sessions === 1 ? "" : "s"} with 10+ requests`;
233
228
  return transcripts > sessions ? `${s} (of ${transcripts} transcripts)` : s;
234
229
  }
235
- export function settingsPath(home = homedir()) {
236
- return join(home, ".claude", "settings.json");
230
+ export function settingsPath(home) {
231
+ return join(claudeDir(home), "settings.json");
237
232
  }
238
- /** The autoCompactWindow Claude Code will use from user settings, if set. */
239
- export function currentCompactWindow(home = homedir()) {
240
- const p = settingsPath(home);
241
- if (!existsSync(p))
242
- return undefined;
243
- try {
244
- const v = JSON.parse(readFileSync(p, "utf8"))?.autoCompactWindow;
245
- return typeof v === "number" && Number.isFinite(v) ? v : undefined;
246
- }
247
- catch {
248
- return undefined;
249
- }
233
+ /**
234
+ * The auto-compact window Claude Code will use, when it is a number: managed,
235
+ * project and user settings merged, CLAUDE_CODE_AUTO_COMPACT_WINDOW first
236
+ * (CLAUDE_CONFIG_DIR honoured). Undefined when none is set or it is "auto".
237
+ */
238
+ export function currentCompactWindow(home, env = process.env, cwd = process.cwd()) {
239
+ const v = effectiveCompactWindow(settingsSources({ home, cwd, env }), env).value;
240
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
241
+ }
242
+ /** What keeps a user-level autoCompactWindow from taking effect: environment, project or managed settings, per-model windows. */
243
+ export function compactWindowBlockers(home, env = process.env, cwd = process.cwd()) {
244
+ return compactWindowOverrides(settingsSources({ home, cwd, env }), env);
250
245
  }
251
246
  /**
252
- * Set (or with undefined, remove) autoCompactWindow in ~/.claude/settings.json.
253
- * Nothing is written when nothing changes: `off` with no window set used to
254
- * create a settings.json of `{}`. A .backup is kept when there was a file.
247
+ * Set (or with undefined, remove) autoCompactWindow in the user's
248
+ * settings.json, editing only that key. Nothing is written when nothing
249
+ * changes: `off` with no window set used to create a settings.json of `{}`.
250
+ * A .backup is kept when there was a file.
255
251
  */
256
- export function setCompactWindow(window, home = homedir()) {
252
+ export function setCompactWindow(window, home) {
257
253
  if (window !== undefined && (!Number.isInteger(window) || window < MIN_WINDOW || window > MAX_WINDOW)) {
258
254
  throw new Error(`window must be a whole number of tokens between ${MIN_WINDOW} and ${MAX_WINDOW}`);
259
255
  }
260
256
  const p = settingsPath(home);
261
- const existed = existsSync(p);
262
- const settings = readJson(p);
263
- if (window === undefined ? !("autoCompactWindow" in settings) : settings.autoCompactWindow === window) {
264
- return { changed: false, created: false };
265
- }
266
- if (window === undefined)
267
- delete settings.autoCompactWindow;
268
- else
269
- settings.autoCompactWindow = window;
270
- writeJsonWithBackup(p, settings);
271
- return { changed: true, created: !existed, backup: existed ? `${p}.context-doctor.backup` : undefined };
257
+ const cur = readSettings(p);
258
+ const previous = cur.data.autoCompactWindow;
259
+ if (window === undefined ? previous === undefined : previous === window)
260
+ return { changed: false, created: false, ...(previous !== undefined ? { previous } : {}) };
261
+ const next = setJsonPath(cur.text, ["autoCompactWindow"], window === undefined ? ABSENT : window);
262
+ backupOnce(p);
263
+ writeAtomic(p, next);
264
+ return { changed: true, created: cur.text === undefined, backup: cur.text !== undefined ? `${p}.context-doctor.backup` : undefined, previous };
272
265
  }
273
266
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
274
267
  export function parseWindow(raw) {
package/dist/doctor.d.ts CHANGED
@@ -11,6 +11,20 @@ interface Check {
11
11
  status: "ok" | "warn" | "fail" | "skip";
12
12
  detail: string;
13
13
  }
14
+ /**
15
+ * Installed copies of the Agent Skill against the SKILL.md this version
16
+ * ships. Install copies the file once and nothing updates it, so after an
17
+ * upgrade the model kept reading the old instructions under a ✓. A copy
18
+ * that differs is out of date or was edited by hand; either way install
19
+ * replaces it with the current one. Line ends are not a difference.
20
+ */
21
+ export declare function skillCheck(label: string, files: string[], okDetail?: string): Check;
22
+ /**
23
+ * The prompt cache lifetime (`cache-ttl`), only when one is set: the value,
24
+ * an environment variable that overrides it, and a Claude Code too old to
25
+ * read it (it ignores the key; nothing else in the file is affected).
26
+ */
27
+ export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): Check | undefined;
14
28
  /**
15
29
  * Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
16
30
  * Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
package/dist/doctor.js CHANGED
@@ -16,12 +16,16 @@ 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, claudeCodeInstallsFromEnv, claudeInstalledCopies, codexMcpEntry, copilotPresent, geminiCliPresent, geminiSettingsPath, isEmptyStub, isOurPluginKey, launcherNamesMissingPackage } from "./install.js";
19
+ import { CACHE_TTL_SINCE, currentTtl, ttlUnsupported } from "./cachettl.js";
20
+ import { allowsComments, binOnPath, claudeCodeInstallsFromEnv, claudeInstalledCopies, codexMcpEntry, copilotPresent, geminiCliPresent, geminiSettingsPath, isEmptyStub, isOurPluginKey, launcherNamesMissingPackage, shippedSkillPath } from "./install.js";
21
+ import { parseSettingsText } from "./settingsedit.js";
22
+ import { antigravityMcpConfigPath, antigravityPresent, antigravitySkillDirs } from "./antigravity.js";
20
23
  import { COPILOT_HOOK_EVENT, copilotHookFilePath, copilotLegacyConfigPath, copilotMcpConfigPath, copilotSettingsPath, isOurCopilotEntry, vsCodeUserDirs } from "./copilot.js";
21
24
  import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
22
25
  import { withInvocation } from "./invocation.js";
23
26
  import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
24
27
  import { describeCosts, subagentCostsPath } from "./fanout.js";
28
+ import { claudeDir, claudeJsonPath } from "./claudedir.js";
25
29
  function claudeDesktopConfigPath() {
26
30
  switch (platform()) {
27
31
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -40,6 +44,32 @@ function missingPackageCheck(label) {
40
44
  ? { label, status: "warn", detail: "MCP entry runs `npx context-doctor-mcp`, which starts only through your global install (no npm package has that name) — re-run: context-doctor install" }
41
45
  : { label, status: "fail", detail: "MCP entry runs `npx context-doctor-mcp`, a package that does not exist on npm, so the server never starts — re-run: context-doctor install" };
42
46
  }
47
+ /**
48
+ * Antigravity (app, IDE, CLI): the MCP server in its mcp_config.json, not
49
+ * switched off there, and the skill. Its hooks are not installed: the
50
+ * transcript they point at has no documented format (see antigravity.ts).
51
+ */
52
+ function antigravityChecks() {
53
+ if (!antigravityPresent())
54
+ return [{ label: "Antigravity", status: "skip", detail: "not detected" }];
55
+ const path = antigravityMcpConfigPath();
56
+ const mcp = existsSync(path) ? checkMcpEntry("Antigravity MCP", path) : { label: "Antigravity MCP", status: "skip", detail: NOT_INSTALLED };
57
+ let disabled = false;
58
+ try {
59
+ disabled = readConfig(path)?.mcpServers?.["context-doctor"]?.disabled === true;
60
+ }
61
+ catch {
62
+ /* checkMcpEntry reported it */
63
+ }
64
+ const out = [disabled ? { label: "Antigravity MCP", status: "warn", detail: `"disabled": true for context-doctor in ${tilde(path)}: Antigravity does not start it` } : mcp];
65
+ if (mcp.status === "ok") {
66
+ const skills = antigravitySkillDirs().filter((d) => existsSync(join(d, "SKILL.md")));
67
+ out.push(skills.length > 0
68
+ ? skillCheck("Antigravity skill", skills.map((d) => join(d, "SKILL.md")), `in ${skills.map(tilde).join(", ")}; no hooks (Antigravity's transcript format is undocumented)`)
69
+ : { label: "Antigravity skill", status: "warn", detail: "not installed — re-run: context-doctor install" });
70
+ }
71
+ return out;
72
+ }
43
73
  /** The "not installed" note shared by every app whose config has nothing in it. */
44
74
  const NOT_INSTALLED = "not installed (no config, or an empty one)";
45
75
  /**
@@ -51,9 +81,40 @@ const NOT_INSTALLED = "not installed (no config, or an empty one)";
51
81
  function readConfig(path, extraKeys = []) {
52
82
  if (!existsSync(path))
53
83
  return undefined;
54
- const config = JSON.parse(readFileSync(path, "utf8"));
84
+ const text = readFileSync(path, "utf8");
85
+ if (text.trim() === "")
86
+ return undefined; // Antigravity creates its MCP file empty
87
+ const config = parseSettingsText(text, allowsComments(path));
55
88
  return isEmptyStub(config, extraKeys) ? undefined : config;
56
89
  }
90
+ /**
91
+ * Installed copies of the Agent Skill against the SKILL.md this version
92
+ * ships. Install copies the file once and nothing updates it, so after an
93
+ * upgrade the model kept reading the old instructions under a ✓. A copy
94
+ * that differs is out of date or was edited by hand; either way install
95
+ * replaces it with the current one. Line ends are not a difference.
96
+ */
97
+ export function skillCheck(label, files, okDetail = files.map(tilde).join(", ")) {
98
+ let shipped;
99
+ try {
100
+ shipped = readFileSync(shippedSkillPath(), "utf8").replace(/\r\n/g, "\n");
101
+ }
102
+ catch {
103
+ /* no shipped copy to compare with (a bare build) */
104
+ }
105
+ const differs = files.filter((f) => {
106
+ try {
107
+ return shipped !== undefined && readFileSync(f, "utf8").replace(/\r\n/g, "\n") !== shipped;
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ });
113
+ if (differs.length > 0) {
114
+ return { label, status: "warn", detail: `${differs.map(tilde).join(", ")} differs from the skill this version ships (out of date, or edited by hand) — re-run \`context-doctor install\` to replace it with the current one` };
115
+ }
116
+ return { label, status: "ok", detail: okDetail };
117
+ }
57
118
  function checkMcpEntry(appName, configPath, plugin = false) {
58
119
  const viaPlugin = { label: appName, status: "ok", detail: "MCP server provided by the context-doctor plugin" };
59
120
  try {
@@ -114,7 +175,7 @@ function hookBinaryMissing(command) {
114
175
  */
115
176
  function claudeSettingsLayers() {
116
177
  const paths = [
117
- join(homedir(), ".claude", "settings.json"),
178
+ join(claudeDir(), "settings.json"),
118
179
  join(process.cwd(), ".claude", "settings.json"),
119
180
  join(process.cwd(), ".claude", "settings.local.json"),
120
181
  ];
@@ -201,6 +262,24 @@ function modelSwitchCheck(settings, plugin) {
201
262
  return { label, status: "skip", detail: `not installed: no Claude Code version found to check (needs ${PRE_MODEL_SWITCH_SINCE})` };
202
263
  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" };
203
264
  }
265
+ /**
266
+ * The prompt cache lifetime (`cache-ttl`), only when one is set: the value,
267
+ * an environment variable that overrides it, and a Claude Code too old to
268
+ * read it (it ignores the key; nothing else in the file is affected).
269
+ */
270
+ export function cacheTtlCheck(home = homedir(), env = process.env) {
271
+ const cur = currentTtl(home, env);
272
+ if (!cur.main && !cur.subagents)
273
+ return undefined;
274
+ const label = "Prompt cache lifetime";
275
+ const set = [cur.main && `main conversation ${cur.main}`, cur.subagents && `subagents ${cur.subagents}`].filter(Boolean).join(", ");
276
+ if (cur.overrides.length)
277
+ return { label, status: "warn", detail: `${set} in ~/.claude/settings.json, but ${cur.overrides.join(", ")} overrides it` };
278
+ const old = ttlUnsupported(claudeCodeInstallsFromEnv());
279
+ if (old.length)
280
+ return { label, status: "warn", detail: `${set}; ${describeInstalls(old)} predates the setting (${CACHE_TTL_SINCE}) and ignores it` };
281
+ return { label, status: "ok", detail: `${set} (context-doctor cache-ttl; off removes it)` };
282
+ }
204
283
  /**
205
284
  * Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
206
285
  * Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
@@ -375,7 +454,7 @@ export async function runDoctor() {
375
454
  checks.push({ label: "Desktop chat tool use", status: "ok", detail: describeDesktopUsage(desktop, recentSurfaces(7).get("claude-desktop") ?? 0) });
376
455
  const layers = claudeSettingsLayers();
377
456
  const plugin = pluginEnabled(layers);
378
- const claudeMcp = checkMcpEntry("Claude Code", join(homedir(), ".claude.json"), plugin);
457
+ const claudeMcp = checkMcpEntry("Claude Code", claudeJsonPath(), plugin);
379
458
  const cursorMcp = checkMcpEntry("Cursor", join(homedir(), ".cursor", "mcp.json"));
380
459
  checks.push(claudeMcp, cursorMcp);
381
460
  // A missing hook is an issue only for an app that is there to hook: when
@@ -386,8 +465,8 @@ export async function runDoctor() {
386
465
  : { label, status: "fail", detail: "not registered — run: context-doctor install" };
387
466
  // Hook registration. ~/.claude without a settings.json is Claude Code with
388
467
  // no hook registered, not Claude Code absent.
389
- const settingsPath = join(homedir(), ".claude", "settings.json");
390
- if (existsSync(settingsPath) || existsSync(join(homedir(), ".claude"))) {
468
+ const settingsPath = join(claudeDir(), "settings.json");
469
+ if (existsSync(settingsPath) || existsSync(claudeDir())) {
391
470
  try {
392
471
  const settings = readConfig(settingsPath) ?? {};
393
472
  const entries = settings.hooks?.UserPromptSubmit ?? [];
@@ -424,6 +503,9 @@ export async function runDoctor() {
424
503
  checks.push(fanoutCheck(settings, plugin));
425
504
  }
426
505
  checks.push(modelSwitchCheck(settings, plugin));
506
+ const ttl = cacheTtlCheck();
507
+ if (ttl)
508
+ checks.push(ttl);
427
509
  }
428
510
  catch (e) {
429
511
  checks.push({ label: "Every-prompt hook", status: "fail", detail: `settings.json unreadable (${e.message})` });
@@ -459,6 +541,9 @@ export async function runDoctor() {
459
541
  ? missingPackageCheck("Codex MCP")
460
542
  : { label: "Codex MCP", status: "ok", detail: "wired in ~/.codex/config.toml" };
461
543
  checks.push(codexMcp);
544
+ const codexSkill = join(codexHome, "skills", "context-doctor", "SKILL.md");
545
+ if (existsSync(codexSkill))
546
+ checks.push(skillCheck("Codex skill", [codexSkill]));
462
547
  try {
463
548
  const hooksPath = join(codexHome, "hooks.json");
464
549
  const hooks = readConfig(hooksPath) ?? {};
@@ -527,6 +612,7 @@ export async function runDoctor() {
527
612
  else {
528
613
  checks.push({ label: "Gemini CLI", status: "skip", detail: "not detected" });
529
614
  }
615
+ checks.push(...antigravityChecks());
530
616
  checks.push(devinCheck());
531
617
  // GitHub Copilot (CLI, app, VS Code): MCP in ~/.copilot/mcp-config.json,
532
618
  // the sessionStart hook in a hook file of our own.
@@ -605,9 +691,9 @@ export async function runDoctor() {
605
691
  }
606
692
  }
607
693
  // Skill
608
- const skillPath = join(homedir(), ".claude", "skills", "context-doctor", "SKILL.md");
694
+ const skillPath = join(claudeDir(), "skills", "context-doctor", "SKILL.md");
609
695
  checks.push(existsSync(skillPath)
610
- ? { label: "Agent Skill", status: "ok", detail: skillPath }
696
+ ? skillCheck("Agent Skill", [skillPath])
611
697
  : { label: "Agent Skill", status: "skip", detail: "not installed (run context-doctor install on a Claude Code machine)" });
612
698
  // Ledger writable. Tested without writing an entry: recordLedger swallows
613
699
  // errors (so this could never fail), and the entry it wrote counted as a
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The value Claude Code will actually use for a setting `fix` writes, and
3
+ * what would override the user-level value `fix` writes.
4
+ *
5
+ * Claude Code merges settings from several files, highest first: managed
6
+ * (policy) settings, the project's `.claude/settings.local.json`, its
7
+ * `.claude/settings.json`, then the user's `settings.json` (in
8
+ * CLAUDE_CONFIG_DIR when set). Read from the 2.1.309 binary:
9
+ * - the prompt cache lifetime: FORCE_PROMPT_CACHING_5M wins, then
10
+ * CLAUDE_CODE_PROMPT_CACHE_TTL (CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL for
11
+ * subagents), then the merged `promptCacheTtl` / `subagentPromptCacheTtl`,
12
+ * then an agent's own frontmatter, then ENABLE_PROMPT_CACHING_1H; and
13
+ * CLAUDE_CODE_MESSAGES_PROMPT_CACHE_TTL=5m turns the main conversation's
14
+ * 1 hour into 5 minutes;
15
+ * - the auto-compact window: CLAUDE_CODE_AUTO_COMPACT_WINDOW, else, from the
16
+ * highest file down, `modelSettings.<model>.autoCompactWindow` (what
17
+ * /autocompact writes) before that file's `autoCompactWindow` ("auto"
18
+ * meaning the model's own window).
19
+ * Environment variables count from the process and from every settings
20
+ * file's `env` block (Claude Code applies those at start).
21
+ */
22
+ export type SourceName = "managed" | "project local" | "project" | "user";
23
+ export interface SettingsSource {
24
+ name: SourceName;
25
+ path: string;
26
+ settings: Record<string, any>;
27
+ }
28
+ /** Managed (policy) settings files: CLAUDE_CODE_MANAGED_SETTINGS_PATH, else the platform's place and its drop-in folder. */
29
+ export declare function managedSettingsPaths(env?: NodeJS.ProcessEnv): string[];
30
+ /** The settings files that apply in `cwd`, highest precedence first; unreadable ones are skipped. */
31
+ export declare function settingsSources(opts?: {
32
+ home?: string;
33
+ cwd?: string;
34
+ env?: NodeJS.ProcessEnv;
35
+ }): SettingsSource[];
36
+ /** An environment variable as Claude Code sees it: a settings file's `env` (highest first), else the process. */
37
+ export declare function effectiveEnv(name: string, sources: SettingsSource[], env?: NodeJS.ProcessEnv): {
38
+ value: string;
39
+ where: string;
40
+ } | undefined;
41
+ export interface Effective<T> {
42
+ value?: T;
43
+ /** Where the value comes from, for messages. */
44
+ where?: string;
45
+ /** The value comes from the user's settings.json (what fix and cache-ttl write). */
46
+ fromUser: boolean;
47
+ }
48
+ /** The prompt cache lifetime Claude Code will use, as far as settings and environment decide it. */
49
+ export declare function effectiveTtl(kind: "main" | "subagents", sources: SettingsSource[], env?: NodeJS.ProcessEnv): Effective<string>;
50
+ /** What keeps a user-level promptCacheTtl / subagentPromptCacheTtl from taking effect. */
51
+ export declare function ttlOverrides(kind: "main" | "subagents", sources: SettingsSource[], env?: NodeJS.ProcessEnv): string[];
52
+ /** The auto-compact window Claude Code will use (for `model`, when given). */
53
+ export declare function effectiveCompactWindow(sources: SettingsSource[], env?: NodeJS.ProcessEnv, model?: string): Effective<number | string>;
54
+ /** What keeps a user-level autoCompactWindow from taking effect (everywhere, or for some models). */
55
+ export declare function compactWindowOverrides(sources: SettingsSource[], env?: NodeJS.ProcessEnv): string[];