context-doctor 0.35.1 → 0.37.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.
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Guards for the MCP server's --http mode, kept apart from mcp.ts (which
3
+ * starts a server on import) so they can be tested directly.
4
+ *
5
+ * A server on 127.0.0.1 is still reachable from a browser: a page can POST to
6
+ * it (a cross-origin "simple" request needs no preflight), and with DNS
7
+ * rebinding a page on attacker.example can even make the browser treat the
8
+ * server as same-origin. A QA pass did exactly that: a foreign origin saved
9
+ * 101 handoffs through --store-handoffs, evicted the user's own and planted
10
+ * handoff://latest. So every /mcp request is checked:
11
+ *
12
+ * - Host must name this server: localhost, 127.0.0.1, [::1], the --host it
13
+ * was given, or a name in --allowed-hosts (a tunnel's host name, say).
14
+ * `--allowed-hosts '*'` turns the check off, explicitly.
15
+ * - Origin, when a browser sends one, must be a loopback origin, one whose
16
+ * host is allowed above, or one in --allowed-origins. ChatGPT's own
17
+ * origins are allowed by default; requests without an Origin (servers,
18
+ * CLIs, ChatGPT's connector backend) are not affected.
19
+ * - The body is read here, capped (10 MB, else 413), and parsed (else 400),
20
+ * then handed to the transport, so no request can make the server buffer
21
+ * an unbounded body.
22
+ */
23
+ export const HTTP_LIMITS = { bodyBytes: 10 * 1024 * 1024, bodyMs: 30_000 };
24
+ /** Origins a browser may call from without being listed: ChatGPT's. */
25
+ export const DEFAULT_ALLOWED_ORIGINS = ["https://chatgpt.com", "https://chat.openai.com"];
26
+ const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "::1"];
27
+ function list(value) {
28
+ return (value ?? "").split(",").map((x) => x.trim()).filter(Boolean);
29
+ }
30
+ /** A Host header's or URL's host name: lowercase, no port, no brackets, no trailing dot. */
31
+ export function hostName(hostHeader) {
32
+ let h = hostHeader.trim().toLowerCase();
33
+ if (h.startsWith("["))
34
+ h = h.slice(1, h.indexOf("]") > 0 ? h.indexOf("]") : undefined);
35
+ else if (h.split(":").length === 2)
36
+ h = h.split(":")[0];
37
+ return h.replace(/\.$/, "");
38
+ }
39
+ /**
40
+ * The guard for a server bound to `bindHost`, from --allowed-hosts and
41
+ * --allowed-origins (comma lists) and the CONTEXT_DOCTOR_ALLOWED_HOSTS and
42
+ * CONTEXT_DOCTOR_ALLOWED_ORIGINS environment variables.
43
+ */
44
+ export function makeGuard(bindHost, allowedHosts, allowedOrigins, env = process.env) {
45
+ const extra = [...list(allowedHosts), ...list(env.CONTEXT_DOCTOR_ALLOWED_HOSTS)];
46
+ const origins = new Set([...DEFAULT_ALLOWED_ORIGINS, ...list(allowedOrigins), ...list(env.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map((o) => o.toLowerCase().replace(/\/+$/, "")));
47
+ if (extra.includes("*"))
48
+ return { hosts: "*", origins };
49
+ const bind = hostName(bindHost);
50
+ const hosts = new Set([...LOOPBACK_HOSTS, ...extra.map(hostName)]);
51
+ // A specific bind address or name is one the server answers to; a wildcard is not a name.
52
+ if (bind && bind !== "0.0.0.0" && bind !== "::")
53
+ hosts.add(bind);
54
+ return { hosts, origins };
55
+ }
56
+ /** Why this request may not reach /mcp, or undefined when it may. */
57
+ export function refusal(guard, headers) {
58
+ if (guard.hosts !== "*") {
59
+ const host = hostName(String(headers.host ?? ""));
60
+ if (!host)
61
+ return "the request has no Host header";
62
+ if (!guard.hosts.has(host)) {
63
+ return `Host "${host}" is not one this server answers to. Behind a tunnel or under a host name, start it with --allowed-hosts ${host}`;
64
+ }
65
+ }
66
+ const origin = headers.origin;
67
+ if (origin !== undefined) {
68
+ const o = String(origin).toLowerCase().replace(/\/+$/, "");
69
+ if (guard.origins.has(o))
70
+ return undefined;
71
+ let url;
72
+ try {
73
+ url = new URL(o);
74
+ }
75
+ catch {
76
+ return `Origin "${o}" is not allowed`;
77
+ }
78
+ const h = hostName(url.host);
79
+ const ok = LOOPBACK_HOSTS.includes(h) || (guard.hosts !== "*" && guard.hosts.has(h));
80
+ if (!ok)
81
+ return `Origin "${o}" is not allowed. To let a web page call this server, start it with --allowed-origins ${o}`;
82
+ }
83
+ return undefined;
84
+ }
85
+ /**
86
+ * The request body as JSON, at most `limit` bytes and within `ms` (a client
87
+ * that declares more than it sends must not hold a request open); otherwise
88
+ * the status and reason to answer with.
89
+ */
90
+ export function readJsonBody(req, limit = HTTP_LIMITS.bodyBytes, ms = HTTP_LIMITS.bodyMs) {
91
+ return new Promise((resolve) => {
92
+ let done = false;
93
+ const timer = setTimeout(() => {
94
+ if (done)
95
+ return;
96
+ done = true;
97
+ resolve({ status: 408, code: -32600, message: `the request body did not arrive within ${Math.round(ms / 1000)} s` });
98
+ }, ms);
99
+ const settle = (r) => {
100
+ clearTimeout(timer);
101
+ resolve(r);
102
+ };
103
+ const tooLarge = { status: 413, code: -32600, message: `request body over ${Math.round(limit / 1024 / 1024)} MB` };
104
+ const declared = Number(req.headers["content-length"]);
105
+ if (Number.isFinite(declared) && declared > limit) {
106
+ req.resume();
107
+ return settle(tooLarge);
108
+ }
109
+ const parts = [];
110
+ let size = 0;
111
+ req.on("data", (d) => {
112
+ if (done)
113
+ return;
114
+ size += d.length;
115
+ if (size > limit) {
116
+ done = true;
117
+ parts.length = 0;
118
+ req.resume();
119
+ return settle(tooLarge);
120
+ }
121
+ parts.push(d);
122
+ });
123
+ req.on("end", () => {
124
+ if (done)
125
+ return;
126
+ done = true;
127
+ try {
128
+ settle({ value: JSON.parse(Buffer.concat(parts).toString("utf8")) });
129
+ }
130
+ catch {
131
+ settle({ status: 400, code: -32700, message: "Parse error: the body is not JSON" });
132
+ }
133
+ });
134
+ req.on("error", () => {
135
+ if (done)
136
+ return;
137
+ done = true;
138
+ settle({ status: 400, code: -32700, message: "the request body could not be read" });
139
+ });
140
+ });
141
+ }
package/dist/index.d.ts CHANGED
@@ -40,3 +40,5 @@ export * from "./compactquality.js";
40
40
  export * from "./precompact.js";
41
41
  export * from "./cachemisses.js";
42
42
  export * from "./modelswitch.js";
43
+ export * from "./ab.js";
44
+ export * from "./abtasks.js";
package/dist/index.js CHANGED
@@ -35,3 +35,5 @@ export * from "./compactquality.js";
35
35
  export * from "./precompact.js";
36
36
  export * from "./cachemisses.js";
37
37
  export * from "./modelswitch.js";
38
+ export * from "./ab.js";
39
+ export * from "./abtasks.js";
package/dist/install.d.ts CHANGED
@@ -137,6 +137,22 @@ export declare function codexMcpEntry(toml: string): {
137
137
  command?: string;
138
138
  args: string[];
139
139
  } | undefined;
140
+ /** Copilot is here: its home exists, its CLI is on PATH, or VS Code (which ships Copilot) is installed. */
141
+ export declare function copilotPresent(): boolean;
142
+ /**
143
+ * The hook entry. `command` is the cross-platform field both harnesses read
144
+ * (Copilot copies it to bash and powershell). PowerShell runs a quoted path
145
+ * only after `&`, so a quoted global binary gets its own powershell line.
146
+ */
147
+ export declare function copilotHookEntry(): Record<string, unknown>;
148
+ /** A JSON value that is an object (not an array, null or a scalar). */
149
+ export declare function isPlainObject(v: unknown): v is Record<string, any>;
150
+ /**
151
+ * readJson, refusing anything but an object: `[1]` or `"x"` read fine as
152
+ * JSON, and fields set on them vanish when the file is written back, so
153
+ * install reported ✓ over a file it had left as it was.
154
+ */
155
+ export declare function readJsonObject(path: string): Record<string, any>;
140
156
  /** Outcome of an install run, so the CLI can set a truthful exit code. */
141
157
  export interface InstallResult {
142
158
  /** Detected targets that could not be configured, with the reason. */
package/dist/install.js CHANGED
@@ -12,6 +12,7 @@ import { delimiter, dirname, join, sep } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { selfCommand, withInvocation } from "./invocation.js";
14
14
  import { claudeCodeInstalls, describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
15
+ import { COPILOT_HOOK_EVENT, copilotHome, copilotHookFilePath, copilotMcpConfigPath, isOurCopilotEntry, vsCodePresent } from "./copilot.js";
15
16
  function claudeDesktopConfigPath() {
16
17
  switch (platform()) {
17
18
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -701,6 +702,170 @@ function uninstallCodex() {
701
702
  }
702
703
  removeSkill(join(dir, "skills", "context-doctor"), "Codex skill");
703
704
  }
705
+ // -- GitHub Copilot: the Copilot CLI, the GitHub Copilot app, and VS Code's
706
+ // agent sessions (see copilot.ts for what was verified and where). Two files:
707
+ // the MCP server in ~/.copilot/mcp-config.json, and a hook file of our own,
708
+ // ~/.copilot/hooks/context-doctor.json, whose sessionStart adds the standing
709
+ // context rules to each new session. No size check: no Copilot hook that can
710
+ // add context is given a transcript to measure.
711
+ /** Copilot is here: its home exists, its CLI is on PATH, or VS Code (which ships Copilot) is installed. */
712
+ export function copilotPresent() {
713
+ return existsSync(copilotHome()) || binOnPath("copilot") !== null || vsCodePresent();
714
+ }
715
+ /** The MCP entry in Copilot's portable format. */
716
+ function copilotMcpEntry(entry) {
717
+ return { type: "local", command: entry.command, args: entry.args, tools: ["*"] };
718
+ }
719
+ /**
720
+ * The hook entry. `command` is the cross-platform field both harnesses read
721
+ * (Copilot copies it to bash and powershell). PowerShell runs a quoted path
722
+ * only after `&`, so a quoted global binary gets its own powershell line.
723
+ */
724
+ export function copilotHookEntry() {
725
+ const command = cliCommand("hook copilot");
726
+ return { type: "command", command, ...(command.startsWith('"') ? { powershell: `& ${command}` } : {}), timeoutSec: 10 };
727
+ }
728
+ /** A JSON value that is an object (not an array, null or a scalar). */
729
+ export function isPlainObject(v) {
730
+ return v !== null && typeof v === "object" && !Array.isArray(v);
731
+ }
732
+ /**
733
+ * readJson, refusing anything but an object: `[1]` or `"x"` read fine as
734
+ * JSON, and fields set on them vanish when the file is written back, so
735
+ * install reported ✓ over a file it had left as it was.
736
+ */
737
+ export function readJsonObject(path) {
738
+ const config = readJson(path);
739
+ if (!isPlainObject(config))
740
+ throw new Error(`${path} is not a JSON object; fix or remove it, then re-run. Nothing was changed.`);
741
+ return config;
742
+ }
743
+ /**
744
+ * Folders install created in Copilot's home, recorded in a marker there so
745
+ * uninstall removes only those (a ~/.copilot that was already there, even
746
+ * empty, is the user's): "" for the home itself, "hooks" for its hooks folder.
747
+ */
748
+ const COPILOT_MARKER = ".context-doctor-created.json";
749
+ function copilotCreated() {
750
+ try {
751
+ const raw = JSON.parse(readFileSync(join(copilotHome(), COPILOT_MARKER), "utf8"));
752
+ return Array.isArray(raw?.created) ? raw.created.filter((d) => d === "" || d === "hooks") : [];
753
+ }
754
+ catch {
755
+ return [];
756
+ }
757
+ }
758
+ function installCopilot(entry, failures) {
759
+ if (!copilotPresent())
760
+ return;
761
+ const home = copilotHome();
762
+ const created = ["", "hooks"].filter((d) => !existsSync(join(home, d)));
763
+ const remember = () => {
764
+ const made = created.filter((d) => existsSync(join(home, d)));
765
+ if (made.length === 0)
766
+ return;
767
+ const all = [...new Set([...copilotCreated(), ...made])];
768
+ writeFileSync(join(home, COPILOT_MARKER), JSON.stringify({ created: all }) + "\n");
769
+ };
770
+ let mcpOk = false;
771
+ try {
772
+ const path = copilotMcpConfigPath();
773
+ const config = readJsonObject(path);
774
+ if (config.mcpServers !== undefined && !isPlainObject(config.mcpServers)) {
775
+ throw new Error(`"mcpServers" in ${path} is not an object; fix it, then re-run. Nothing was changed.`);
776
+ }
777
+ config.mcpServers = config.mcpServers ?? {};
778
+ const want = copilotMcpEntry(entry);
779
+ if (JSON.stringify(config.mcpServers["context-doctor"]) !== JSON.stringify(want)) {
780
+ config.mcpServers["context-doctor"] = want;
781
+ writeJsonWithBackup(path, config);
782
+ }
783
+ mcpOk = true;
784
+ console.log(`✓ GitHub Copilot: MCP server added (${path})`);
785
+ }
786
+ catch (e) {
787
+ console.error(`✗ GitHub Copilot MCP: ${e.message}`);
788
+ failures.push("GitHub Copilot MCP");
789
+ }
790
+ // The hook's rules name the MCP tools: without the server they would
791
+ // point the model at tools that are not there, so no hook without it.
792
+ if (!mcpOk) {
793
+ console.log("– GitHub Copilot session-start hook not written: its rules name the MCP tools, which could not be added. Fix the file above and re-run install.");
794
+ remember();
795
+ return;
796
+ }
797
+ try {
798
+ const path = copilotHookFilePath();
799
+ // The file is ours, so it is never backed up; entries someone added to it are kept.
800
+ const config = readJsonObject(path);
801
+ if (config.version !== undefined && config.version !== 1) {
802
+ throw new Error(`${path} says "version": ${JSON.stringify(config.version)}; Copilot loads hooks only from version 1 files. Set it to 1 or delete the file, then re-run.`);
803
+ }
804
+ if (config.hooks !== undefined && !isPlainObject(config.hooks))
805
+ throw new Error(`"hooks" in ${path} is not an object; fix it or delete the file, then re-run. Nothing was changed.`);
806
+ const current = config.hooks?.[COPILOT_HOOK_EVENT];
807
+ if (current !== undefined && !Array.isArray(current)) {
808
+ throw new Error(`"hooks.${COPILOT_HOOK_EVENT}" in ${path} is not a list; fix it or delete the file, then re-run. Nothing was changed.`);
809
+ }
810
+ config.version = 1;
811
+ config.hooks = config.hooks ?? {};
812
+ const entries = current ?? [];
813
+ const want = copilotHookEntry();
814
+ const ours = entries.filter(isOurCopilotEntry);
815
+ if (!(ours.length === 1 && JSON.stringify(ours[0]) === JSON.stringify(want))) {
816
+ config.hooks[COPILOT_HOOK_EVENT] = [...entries.filter((e) => !isOurCopilotEntry(e)), want];
817
+ mkdirSync(dirname(path), { recursive: true });
818
+ writeFileSync(path, JSON.stringify(config, null, 2));
819
+ }
820
+ console.log(`✓ GitHub Copilot session-start hook installed (${path}): each new or resumed session gets the standing context rules`);
821
+ }
822
+ catch (e) {
823
+ console.error(`✗ GitHub Copilot hook: ${e.message}`);
824
+ failures.push("GitHub Copilot hook");
825
+ }
826
+ remember();
827
+ }
828
+ function uninstallCopilotMcp() {
829
+ const mcp = copilotMcpConfigPath();
830
+ if (!existsSync(mcp))
831
+ return;
832
+ const config = readJson(mcp);
833
+ if (isPlainObject(config) && isPlainObject(config.mcpServers) && config.mcpServers["context-doctor"]) {
834
+ delete config.mcpServers["context-doctor"];
835
+ writeUninstalled(mcp, config);
836
+ done("✓ GitHub Copilot: MCP server removed");
837
+ }
838
+ }
839
+ function uninstallCopilotHook() {
840
+ const hookFile = copilotHookFilePath();
841
+ if (!existsSync(hookFile))
842
+ return;
843
+ const config = readJson(hookFile);
844
+ const entries = isPlainObject(config) && isPlainObject(config.hooks) && Array.isArray(config.hooks[COPILOT_HOOK_EVENT]) ? config.hooks[COPILOT_HOOK_EVENT] : undefined;
845
+ const kept = entries?.filter((e) => !isOurCopilotEntry(e));
846
+ if (entries && kept && kept.length !== entries.length) {
847
+ if (kept.length > 0)
848
+ config.hooks[COPILOT_HOOK_EVENT] = kept;
849
+ else
850
+ delete config.hooks[COPILOT_HOOK_EVENT];
851
+ if (isEmptyStub(config, ["version"]))
852
+ rmSync(hookFile);
853
+ else
854
+ writeFileSync(hookFile, JSON.stringify(config, null, 2));
855
+ done("✓ GitHub Copilot session-start hook removed");
856
+ }
857
+ }
858
+ /** The folders install created (from its marker), once nothing is left in them. */
859
+ function uninstallCopilotFolders() {
860
+ const home = copilotHome();
861
+ const created = copilotCreated();
862
+ rmSync(join(home, COPILOT_MARKER), { force: true });
863
+ for (const d of ["hooks", ""].filter((x) => created.includes(x))) {
864
+ const dir = join(home, d);
865
+ if (existsSync(dir) && readdirSync(dir).length === 0)
866
+ rmSync(dir, { recursive: true });
867
+ }
868
+ }
704
869
  /**
705
870
  * Install into every detected app.
706
871
  *
@@ -714,8 +879,8 @@ function uninstallCodex() {
714
879
  export function runInstall(options = {}) {
715
880
  const entry = serverEntry();
716
881
  const found = targets().filter((t) => t.detect());
717
- if (found.length === 0 && !existsSync(codexDir())) {
718
- console.log("No supported AI apps detected (Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI).");
882
+ if (found.length === 0 && !existsSync(codexDir()) && !copilotPresent()) {
883
+ console.log("No supported AI apps detected (Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, GitHub Copilot).");
719
884
  console.log("Manual setup — add to your app's MCP config:");
720
885
  console.log(JSON.stringify({ mcpServers: { "context-doctor": entry } }, null, 2));
721
886
  return { failures: [] };
@@ -738,7 +903,9 @@ export function runInstall(options = {}) {
738
903
  if (viaPlugin && target.name === "Claude Code")
739
904
  continue;
740
905
  try {
741
- const config = readJson(target.configPath);
906
+ const config = readJsonObject(target.configPath);
907
+ if (config.mcpServers !== undefined && !isPlainObject(config.mcpServers))
908
+ throw new Error(`"mcpServers" in ${target.configPath} is not an object; fix it, then re-run. Nothing was changed.`);
742
909
  config.mcpServers = config.mcpServers ?? {};
743
910
  // Always overwrite: re-running install is how a stale entry gets repaired.
744
911
  config.mcpServers["context-doctor"] = entry;
@@ -807,6 +974,7 @@ export function runInstall(options = {}) {
807
974
  failures.push("Cursor hook");
808
975
  }
809
976
  installCodex(entry, failures);
977
+ installCopilot(entry, failures);
810
978
  if (geminiCliPresent()) {
811
979
  try {
812
980
  const hook = installHookInto(geminiSettingsPath(), join(homedir(), ".gemini"), "BeforeAgent");
@@ -1002,6 +1170,7 @@ function configPaths() {
1002
1170
  join(codexDir(), "config.toml"),
1003
1171
  join(codexDir(), "hooks.json"),
1004
1172
  geminiSettingsPath(),
1173
+ copilotMcpConfigPath(),
1005
1174
  ].filter((p, i, all) => all.indexOf(p) === i);
1006
1175
  }
1007
1176
  /** "~/..." for a path under the home directory. */
@@ -1069,6 +1238,10 @@ export async function runUninstall() {
1069
1238
  uninstallHook(attempt);
1070
1239
  attempt("Claude Code status line", () => uninstallStatusLine());
1071
1240
  attempt("Codex", () => uninstallCodex());
1241
+ // One step per file: a malformed mcp-config.json must not keep the hook file installed.
1242
+ attempt(`GitHub Copilot MCP server (${tilde(copilotMcpConfigPath())})`, () => uninstallCopilotMcp());
1243
+ attempt(`GitHub Copilot hook (${tilde(copilotHookFilePath())})`, () => uninstallCopilotHook());
1244
+ attempt("GitHub Copilot folders", () => uninstallCopilotFolders());
1072
1245
  // Remove our bookkeeping files too — uninstall means gone. The hook's
1073
1246
  // per-session state is a directory, one small file per session.
1074
1247
  for (const file of OUR_CLAUDE_FILES) {
package/dist/ledger.d.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  * optimize — an optimization was applied {ev: "optimize", src: "cli"|"mcp", saved, model?}
10
10
  * proxy — proxy savings checkpoint {ev: "proxy", saved, usd?, requests?}
11
11
  * rollup — totals folded in on rotation {ev: "rollup", ...carried sums}
12
+ * session_rules — a Copilot session start got the standing rules {ev: "session_rules", app}
12
13
  *
13
14
  * The ledger is capped, and everything it feeds is a LIFETIME total. Simply
14
15
  * dropping old lines made those totals go backwards — measured: 1,692,000
@@ -17,7 +18,7 @@
17
18
  */
18
19
  export interface LedgerEntry {
19
20
  ts: number;
20
- ev?: "check" | "optimize" | "proxy" | "rollup" | "cold_resume" | "precompact";
21
+ ev?: "check" | "optimize" | "proxy" | "rollup" | "cold_resume" | "precompact" | "session_rules";
21
22
  sid?: string;
22
23
  tok?: number;
23
24
  warn?: boolean;
@@ -28,6 +29,8 @@ export interface LedgerEntry {
28
29
  model?: string;
29
30
  /** The Cursor version that ran the hook (its input's cursor_version), for `doctor`. */
30
31
  cv?: string;
32
+ /** session_rules only: the app whose session start got the standing rules ("copilot"). */
33
+ app?: string;
31
34
  /** rollup only: sums carried forward from entries rotation removed. */
32
35
  carried?: CarriedTotals;
33
36
  }
@@ -54,5 +57,7 @@ export interface CarriedTotals {
54
57
  export declare function foldTotals(entries: LedgerEntry[]): CarriedTotals;
55
58
  export declare function statePath(): string;
56
59
  export declare function ledgerPath(): string;
60
+ /** Longest string field kept in a ledger entry (a model name, a session id). */
61
+ export declare const LEDGER_STRING_MAX = 100;
57
62
  export declare function recordLedger(entry: Omit<LedgerEntry, "ts">): void;
58
63
  export declare function readLedger(): LedgerEntry[];
package/dist/ledger.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * optimize — an optimization was applied {ev: "optimize", src: "cli"|"mcp", saved, model?}
10
10
  * proxy — proxy savings checkpoint {ev: "proxy", saved, usd?, requests?}
11
11
  * rollup — totals folded in on rotation {ev: "rollup", ...carried sums}
12
+ * session_rules — a Copilot session start got the standing rules {ev: "session_rules", app}
12
13
  *
13
14
  * The ledger is capped, and everything it feeds is a LIFETIME total. Simply
14
15
  * dropping old lines made those totals go backwards — measured: 1,692,000
@@ -83,16 +84,32 @@ export function statePath() {
83
84
  export function ledgerPath() {
84
85
  return join(dirname(statePath()), ".context-doctor-ledger.jsonl");
85
86
  }
87
+ /** Longest string field kept in a ledger entry (a model name, a session id). */
88
+ export const LEDGER_STRING_MAX = 100;
89
+ /** On rotation: what is kept, by bytes and by entries; longer lines are folded, not kept. */
90
+ const LEDGER_ROTATE_AT = 256 * 1024;
91
+ const LEDGER_KEEP_BYTES = 128 * 1024;
92
+ const LEDGER_KEEP_LINES = 500;
93
+ const LEDGER_LINE_MAX = 4 * 1024;
94
+ /** A string field as the ledger keeps it: no control characters, at most LEDGER_STRING_MAX. */
95
+ function cap(v) {
96
+ if (typeof v !== "string")
97
+ return undefined;
98
+ // eslint-disable-next-line no-control-regex
99
+ const clean = v.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
100
+ return clean.length > LEDGER_STRING_MAX ? clean.slice(0, LEDGER_STRING_MAX) : clean;
101
+ }
86
102
  export function recordLedger(entry) {
87
103
  const path = ledgerPath();
88
104
  try {
89
105
  // Claude-Desktop-only machines have no ~/.claude — create it so their
90
106
  // optimize events count in `context-doctor report` too.
91
107
  mkdirSync(dirname(path), { recursive: true });
92
- // Cap growth: past ~256KB keep the most recent 500 entries — but fold the
93
- // dropped ones into a rollup first, or every lifetime total in the reports
94
- // silently shrinks the moment a heavy user crosses the cap.
95
- if (existsSync(path) && statSync(path).size > 256 * 1024) {
108
+ // Cap growth by bytes, not lines: past 256KB keep the newest entries that
109
+ // fit 128KB (at most 500), and fold the rest into a rollup first, or every
110
+ // lifetime total in the reports silently shrinks the moment a heavy user
111
+ // crosses the cap. A line too long to be a real entry is folded, never kept.
112
+ if (existsSync(path) && statSync(path).size > LEDGER_ROTATE_AT) {
96
113
  const lines = readFileSync(path, "utf8").trimEnd().split("\n");
97
114
  const parse = (line) => {
98
115
  try {
@@ -102,13 +119,34 @@ export function recordLedger(entry) {
102
119
  return [];
103
120
  }
104
121
  };
105
- const kept = lines.slice(-500);
106
- const dropped = lines.slice(0, -500).flatMap(parse);
122
+ const keptAt = new Set();
123
+ let bytes = 0;
124
+ for (let i = lines.length - 1; i >= 0 && keptAt.size < LEDGER_KEEP_LINES; i--) {
125
+ const n = Buffer.byteLength(lines[i]) + 1;
126
+ if (n > LEDGER_LINE_MAX)
127
+ continue;
128
+ if (bytes + n > LEDGER_KEEP_BYTES)
129
+ break;
130
+ keptAt.add(i);
131
+ bytes += n;
132
+ }
133
+ const kept = lines.filter((_, i) => keptAt.has(i));
134
+ const dropped = lines.filter((_, i) => !keptAt.has(i)).flatMap(parse);
107
135
  const carried = foldTotals(dropped);
108
136
  const rollup = { ts: Date.now(), ev: "rollup", carried };
109
137
  writeFileSync(path, [JSON.stringify(rollup), ...kept].join("\n") + "\n");
110
138
  }
111
- appendFileSync(path, JSON.stringify({ ts: Date.now(), ...entry }) + "\n");
139
+ const clean = { ...entry };
140
+ for (const k of ["model", "sid", "cv", "app"]) {
141
+ if (k in clean) {
142
+ const v = cap(clean[k]);
143
+ if (v === undefined)
144
+ delete clean[k];
145
+ else
146
+ clean[k] = v;
147
+ }
148
+ }
149
+ appendFileSync(path, JSON.stringify({ ts: Date.now(), ...clean }) + "\n");
112
150
  }
113
151
  catch {
114
152
  /* best-effort */
package/dist/mcp.d.ts CHANGED
@@ -15,5 +15,7 @@
15
15
  * optimize_context — apply safe strategies, return the slimmed conversation
16
16
  * context_best_practices — curated checklist for a given provider/use case
17
17
  * pack_context — only the chunks of big files a question needs, within a token budget
18
+ * save_handoff — store a handoff brief the next chat starts from (a chat's history cannot be cut)
19
+ * Prompts: context_checkup, handoff, ask_file. Resources (stdio): handoff://latest, handoff://<id>.
18
20
  */
19
21
  export {};