context-mode 2.0.0-next.30 → 2.0.0-next.32

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/pi/index.js CHANGED
@@ -11353,6 +11353,7 @@ var SOURCE_LABEL_MAX_CHARS = 80;
11353
11353
  var CANCELLED_LINE = "Cancelled.";
11354
11354
  var BACKGROUND_REPLY_PREFIX = "started in background, pid ";
11355
11355
  var PLAIN_OUTPUT_ENV = Object.freeze({ NO_COLOR: "1", FORCE_COLOR: "0" });
11356
+ var RUN_LABEL_PREFIX = "run.mjs:";
11356
11357
  var RUN_SESSION_PREFIX = "mcp:";
11357
11358
  var HOST_SESSION_ENV = Object.freeze({ "claude-code": "CLAUDE_CODE_SESSION_ID" });
11358
11359
  var NODE_MIN = "24.15.0";
@@ -11526,17 +11527,34 @@ var STATS_EMPTY_LINES = Object.freeze([
11526
11527
  "sandbox, and only the short answer goes to the chat."
11527
11528
  ]);
11528
11529
  var STATS_KIND_LABELS = Object.freeze([
11529
- ["cmd", "Tool runs"],
11530
+ // D-STATS-FIX-1 (8): the first five rows are call kinds, so they add up to the calls of the scope line.
11530
11531
  ["index", "Content indexed"],
11531
11532
  ["edit", "File edits"],
11532
- ["toolerr", "Errors kept"],
11533
+ ["toolerr", "Issues kept"],
11533
11534
  ["decision", "Your decisions"],
11535
+ ["cmd", "Other tool calls"],
11534
11536
  ["prompt", "Your prompts"]
11535
11537
  ]);
11536
11538
  var STATS_JOURNAL_HINTS = Object.freeze([
11537
- "ctx_resume brings back your last task, files changed and open errors",
11539
+ "ctx_resume brings back your last task, files changed and open issues",
11538
11540
  "after a compact or a restart; ctx_search finds indexed content by words."
11539
11541
  ]);
11542
+ var STATS_WINDOW_TOKENS = 2e5;
11543
+ var STATS_THOUSAND = 1e3;
11544
+ var STATS_WHOLE_FROM = 10;
11545
+ var STATS_DAYS = 7;
11546
+ var STATS_TOP_OUTPUTS = 3;
11547
+ var STATS_CARD_W = 19;
11548
+ var STATS_DAY_BAR = 48;
11549
+ var STATS_TOKEN_NOTE = " (at 4 bytes per token; a Claude context window is 200K tokens)";
11550
+ var STATS_WAYS = Object.freeze([
11551
+ ["sandbox", "\u2588", "sandbox run"],
11552
+ ["index", "\u2593", "index + search"],
11553
+ ["redirect", "\u2592", "hook sent to sandbox"],
11554
+ ["replace", "\u2591", "hook cut down"]
11555
+ ]);
11556
+ var STATS_INDEX_TOOLS = Object.freeze(["ctx_index", "ctx_search"]);
11557
+ var STATS_FOOTER_URL = "https://contextmode.ai/?utm_source=ctx_stats&utm_medium=stats&utm_content=footer";
11540
11558
  var PURGE_SCOPES = Object.freeze(["session", "source", "project"]);
11541
11559
  var PURGE_NO_SCOPE_LINE = "ctx_purge: pick one scope \u2014 session, source, or project.";
11542
11560
  var PURGE_MANY_SCOPES_LINE = "ctx_purge: pick only one scope \u2014 session, source, or project.";
@@ -11552,7 +11570,7 @@ var DECISION_OPTION_KEY = "option";
11552
11570
  var DECISION_LABEL_JOIN = " | ";
11553
11571
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
11554
11572
  var RELEASE_BRANCH = "release";
11555
- var BUNDLE_SHA = true ? "dd54e208f8debb1c4601659ee632ada9a3612e45" : void 0;
11573
+ var BUNDLE_SHA = true ? "feb8de116956b3d3eff56c7d5ed2d840483d0cd4" : void 0;
11556
11574
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
11557
11575
  var DOCTOR_LABEL = Object.freeze({
11558
11576
  D1: "version",
@@ -11582,7 +11600,7 @@ function DOCTOR_FAIL_LINE(host, check2, cause, command) {
11582
11600
  return `FAIL ${host}: ${check2} \u2014 ${cause}. Fix: ${command}`;
11583
11601
  }
11584
11602
  var DOCTOR_FIX_UPGRADE = "run ctx_upgrade";
11585
- var D1_DEV_BUILD_DETAIL = "dev build";
11603
+ var D1_DEV_BUILD_DETAIL = "dev build: source checkout; release builds stamp the sha";
11586
11604
  var D1_UPDATE_DETAIL = "update available";
11587
11605
  var D1_SHORT_SHA_LEN = 7;
11588
11606
  var D1_PACKAGE_FILE = "package.json";
@@ -11913,7 +11931,7 @@ var V1_REASON = Object.freeze({
11913
11931
  dataDir: "old context-mode data dir <agent home>/context-mode/",
11914
11932
  dataDirShared: "old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",
11915
11933
  dataRoot: "old context-mode content under ~/.context-mode/",
11916
- tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, no action needed"
11934
+ tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep"
11917
11935
  });
11918
11936
  var UPGRADE_REPORT_ONLY_REASONS = Object.freeze([V1_REASON.statusLine, V1_REASON.vscodeMcp, V1_REASON.dataDirShared, V1_REASON.tmpFile, V1_REASON.kiroSteering]);
11919
11937
  var PLUGIN_NAME = SERVER_KEY;
@@ -11954,6 +11972,85 @@ var REPORT_ENV_PREFIX = "env.";
11954
11972
  var REPORT_ENV_ENUMS = Object.freeze({
11955
11973
  NODE_ENV: Object.freeze(["development", "production", "test"])
11956
11974
  });
11975
+ var DOCTOR_ENV_PREFIX = "Environment: ";
11976
+ var DOCTOR_DOCS_URL = "https://contextmode.ai/docs/engine/doctor";
11977
+ var DOCTOR_DOCS_ANCHOR = "checks";
11978
+ function DOCTOR_DOCS_LINK(check2) {
11979
+ return `${DOCTOR_DOCS_URL}?utm_source=ctx_doctor&utm_medium=doctor&utm_content=${check2}#${DOCTOR_DOCS_ANCHOR}`;
11980
+ }
11981
+ var DOCTOR_DOCS_LABEL = "Docs: ";
11982
+ function D3_NO_SETUP_FIX(agent) {
11983
+ return `context-mode setup --agents ${agent}`;
11984
+ }
11985
+ function D5_FIXTURE_FILE_ABSENT(file2) {
11986
+ return `hook fixture ${file2} is absent: the round trip needs it`;
11987
+ }
11988
+ function D5_FIXTURE_PARSE(file2, cause) {
11989
+ return `the hook fixture file ${file2} failed to parse: ${cause}`;
11990
+ }
11991
+ function D5_FIXTURE_AGENT_ABSENT(file2, keys) {
11992
+ return `the hook fixture file ${file2} records payloads for ${keys.join(", ") || "zero agents"} only`;
11993
+ }
11994
+ var DOCTOR_REPORTS_DIR = "reports";
11995
+ var DOCTOR_REPORT_FILE_PREFIX = "doctor-";
11996
+ var DOCTOR_REPORT_LINE = "Report file: ";
11997
+ var DOCTOR_GH_LINE = "File it: ";
11998
+ var DOCTOR_URL_LINE = "Or open: ";
11999
+ var DOCTOR_GH_NEXT = " --";
12000
+ var DOCTOR_NOTE_PREFIXES = Object.freeze([
12001
+ DOCTOR_ENV_PREFIX,
12002
+ DOCTOR_DOCS_LABEL,
12003
+ DOCTOR_REPORT_LINE,
12004
+ DOCTOR_GH_LINE,
12005
+ DOCTOR_GH_NEXT.trim(),
12006
+ DOCTOR_URL_LINE
12007
+ ]);
12008
+ var ISSUE_REPO_SLUG = "mksglu/context-mode";
12009
+ var ISSUE_FORM_FILE = "agent-report.yml";
12010
+ var ISSUE_URL_MAX = 8e3;
12011
+ var ISSUE_FORM_HEADINGS = Object.freeze([
12012
+ "Summary",
12013
+ "ctx-report",
12014
+ "What happened",
12015
+ "Hook errors",
12016
+ "Journal rows",
12017
+ "Agent config",
12018
+ "Expected",
12019
+ "Steps",
12020
+ "Environment"
12021
+ ]);
12022
+ var DOCTOR_HOOK_LOG_LINES = 50;
12023
+ var DOCTOR_JOURNAL_ROWS = 30;
12024
+ var DOCTOR_CONFIG_LINES = 40;
12025
+ var DOCTOR_ENV_NAMES = Object.freeze([
12026
+ "CODEX_HOME",
12027
+ "CLAUDE_CONFIG_DIR",
12028
+ "CLAUDE_PLUGIN_ROOT",
12029
+ "COPILOT_HOME",
12030
+ "KIRO_HOME",
12031
+ "OPENCODE_CONFIG_DIR",
12032
+ "PI_CODING_AGENT_DIR",
12033
+ "XDG_CONFIG_HOME",
12034
+ "SHELL"
12035
+ ]);
12036
+ var DOCTOR_PATH_TOOLS = Object.freeze(["node", "git", "sh"]);
12037
+ var DOCTOR_SECRET_WORDS = Object.freeze(["token", "secret", "password", "apikey", "api_key", "authorization", "bearer"]);
12038
+ var DOCTOR_MASK = "<masked>";
12039
+ var NATIVE_INSTALL = Object.freeze({
12040
+ "claude-code": ["claude plugin marketplace add mksglu/context-mode#release", "claude plugin install context-mode@context-mode"],
12041
+ codex: ["codex plugin marketplace add mksglu/context-mode@release", "codex plugin add context-mode@context-mode"],
12042
+ gemini: ["gemini extensions install https://github.com/mksglu/context-mode --ref release"],
12043
+ qwen: ["qwen extensions install https://github.com/mksglu/context-mode:context-mode --ref release"],
12044
+ opencode: ["opencode plugin add context-mode@next"],
12045
+ pi: ["pi install npm:context-mode@next"],
12046
+ "copilot-cli": ["npm i -g context-mode@next", "context-mode setup --agents copilot-cli"],
12047
+ vscode: ["npm i -g context-mode@next", "context-mode setup --agents vscode"],
12048
+ kiro: ["npm i -g context-mode@next", "context-mode setup --agents kiro"],
12049
+ zcode: ["npm i -g context-mode@next", "context-mode setup --agents zcode"]
12050
+ });
12051
+ var ISSUE_FORM_URL = `https://github.com/${ISSUE_REPO_SLUG}/issues/new?template=${ISSUE_FORM_FILE}`;
12052
+ var DOCTOR_GIT_VERSION_TIMEOUT_MS = 5e3;
12053
+ var DOCTOR_LOG_TAIL_BYTES = 262144;
11957
12054
 
11958
12055
  // src/adapters/pi.ts
11959
12056
  var TOOL_NAME_PREFIX = "";
@@ -12415,8 +12512,8 @@ function decode6(raw) {
12415
12512
  if (event === "SessionStart" && typeof raw.source === "string" && COPILOT_SOURCES[raw.source] !== void 0) ev.source = COPILOT_SOURCES[raw.source];
12416
12513
  if (event === "UserPromptSubmit" && typeof raw.prompt === "string") ev.prompt = raw.prompt;
12417
12514
  if (event === "PreToolUse" || event === "PostToolUse") {
12418
- const toolName = String(raw[k.tool] ?? "");
12419
- const tool = { name: toolName, canonicalName: canonicalName3(toolName), input: readArgs(raw[k.args]) };
12515
+ const toolName2 = String(raw[k.tool] ?? "");
12516
+ const tool = { name: toolName2, canonicalName: canonicalName3(toolName2), input: readArgs(raw[k.args]) };
12420
12517
  ev.tool = tool;
12421
12518
  }
12422
12519
  if (event === "PostToolUse") ev.result = readResult4(raw[k.result], native.casing, native.failure);
@@ -12530,9 +12627,9 @@ function decodeCamel(p, name) {
12530
12627
  if (event === "SessionStart" && typeof p.source === "string" && SESSION_SOURCES[p.source] !== void 0) ev.source = SESSION_SOURCES[p.source];
12531
12628
  if (event === "UserPromptSubmit" && typeof p.prompt === "string") ev.prompt = p.prompt;
12532
12629
  if (event === "PreToolUse" || event === "PostToolUse") {
12533
- const toolName = String(p.toolName ?? "");
12534
- const canonical = canonicalName4(toolName);
12535
- ev.tool = { name: toolName, canonicalName: canonical, input: policyInput(toolName, canonical, readArgs2(p.toolArgs)) };
12630
+ const toolName2 = String(p.toolName ?? "");
12631
+ const canonical = canonicalName4(toolName2);
12632
+ ev.tool = { name: toolName2, canonicalName: canonical, input: policyInput(toolName2, canonical, readArgs2(p.toolArgs)) };
12536
12633
  }
12537
12634
  if (event === "PostToolUse") ev.result = readCamelResult(p.toolResult);
12538
12635
  return ev;
@@ -13325,10 +13422,10 @@ function lexSpan(st, from, inParen, depth, out, bodies) {
13325
13422
  }
13326
13423
  function scan(cmd) {
13327
13424
  const st = { s: cmd, n: cmd.length, end: "complete" };
13328
- const tokens = [];
13425
+ const tokens2 = [];
13329
13426
  const heredocBodies = [];
13330
- lexSpan(st, 0, false, 0, tokens, heredocBodies);
13331
- return { tokens, heredocBodies, end: st.end };
13427
+ lexSpan(st, 0, false, 0, tokens2, heredocBodies);
13428
+ return { tokens: tokens2, heredocBodies, end: st.end };
13332
13429
  }
13333
13430
  function dequote(word) {
13334
13431
  let out = "";
@@ -14772,7 +14869,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
14772
14869
  ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',
14773
14870
  ctx_resume: "Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",
14774
14871
  ctx_stats: "Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",
14775
- ctx_doctor: "Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause and the fix in one line. It changes nothing. Use it when the user asks whether context-mode works, or after a context-mode error.",
14872
+ ctx_doctor: "Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",
14776
14873
  ctx_upgrade: "Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",
14777
14874
  ctx_purge: 'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'
14778
14875
  });
@@ -15285,8 +15382,8 @@ function firstLine(file2) {
15285
15382
  return line === "" ? null : line;
15286
15383
  }
15287
15384
  function git(dir, args) {
15288
- const { spawnSync: spawnSync3 } = process.getBuiltinModule("node:child_process");
15289
- const r = spawnSync3("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
15385
+ const { spawnSync: spawnSync4 } = process.getBuiltinModule("node:child_process");
15386
+ const r = spawnSync4("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
15290
15387
  if (r.error !== void 0 || r.status !== 0) throw new CtxError("NO_GIT_DIR", { path: dir });
15291
15388
  return r.stdout.split("\n").filter((l) => l !== "");
15292
15389
  }
@@ -17864,8 +17961,8 @@ function trigramMatch(q) {
17864
17961
  const words = blankTokens(q);
17865
17962
  const kept = words.filter((w) => !STOPWORDS.has(w.toLowerCase()));
17866
17963
  const parts = new Set((kept.length > 0 ? kept : words).filter((w) => [...w].length >= 3));
17867
- const whole = words.join(" ");
17868
- if (words.length > 1 && [...whole].length >= 3) parts.add(whole);
17964
+ const whole2 = words.join(" ");
17965
+ if (words.length > 1 && [...whole2].length >= 3) parts.add(whole2);
17869
17966
  return [...parts].map((w) => `"${w.replaceAll('"', '""')}"`).join(" OR ");
17870
17967
  }
17871
17968
  function editDistance(a, b, max) {
@@ -18212,15 +18309,15 @@ function indentOf(line) {
18212
18309
  }
18213
18310
  function buildUnits(text) {
18214
18311
  const lines = text.split("\n");
18215
- const stack = [];
18312
+ const stack2 = [];
18216
18313
  const out = [];
18217
18314
  for (let i = 0; i < lines.length; i++) {
18218
18315
  const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
18219
18316
  const indent = indentOf(line);
18220
18317
  if (indent === line.length) continue;
18221
- while (stack.length > 0 && stack[stack.length - 1].indent >= indent) stack.pop();
18222
- out.push({ ord: i, body: [...stack.map((s) => s.line), line].join("\n") });
18223
- stack.push({ indent, line });
18318
+ while (stack2.length > 0 && stack2[stack2.length - 1].indent >= indent) stack2.pop();
18319
+ out.push({ ord: i, body: [...stack2.map((s) => s.line), line].join("\n") });
18320
+ stack2.push({ indent, line });
18224
18321
  }
18225
18322
  return out;
18226
18323
  }
@@ -18522,7 +18619,7 @@ function chunkText(text, kind, maxBytes = MAX_CHUNK_BYTES) {
18522
18619
  }
18523
18620
  function mdChunks(src, cap, lineCut) {
18524
18621
  const out = [];
18525
- const stack = [];
18622
+ const stack2 = [];
18526
18623
  let title = "";
18527
18624
  let run = [];
18528
18625
  const push2 = (text, bytes5) => {
@@ -18536,9 +18633,9 @@ function mdChunks(src, cap, lineCut) {
18536
18633
  for (const b of lineBlocks(src, true)) {
18537
18634
  if (b.heading !== void 0) {
18538
18635
  flush();
18539
- while (stack.length > 0 && stack[stack.length - 1].level >= b.heading.level) stack.pop();
18540
- stack.push(b.heading);
18541
- title = stack.map((h) => h.text).join(" > ");
18636
+ while (stack2.length > 0 && stack2[stack2.length - 1].level >= b.heading.level) stack2.pop();
18637
+ stack2.push(b.heading);
18638
+ title = stack2.map((h) => h.text).join(" > ");
18542
18639
  }
18543
18640
  if (b.fence !== void 0 && utf8Bytes(src.slice(b.start, b.end)) > cap) {
18544
18641
  const pieces = fencePieces(src, b, b.fence, cap);
@@ -18771,7 +18868,7 @@ function cutPoint(src, start, end, scratch) {
18771
18868
  const r = encoder.encodeInto(src.slice(start, limit), scratch);
18772
18869
  return { end: start + r.read, written: r.written };
18773
18870
  }
18774
- function merge2(src, blocks, join26, cap, lineCut) {
18871
+ function merge2(src, blocks, join27, cap, lineCut) {
18775
18872
  const out = [];
18776
18873
  const scratch = new Uint8Array(cap);
18777
18874
  let wide;
@@ -18781,7 +18878,7 @@ function merge2(src, blocks, join26, cap, lineCut) {
18781
18878
  out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
18782
18879
  };
18783
18880
  for (const b of blocks) {
18784
- if (cur !== void 0 && !join26) {
18881
+ if (cur !== void 0 && !join27) {
18785
18882
  emit(cur.start, cur.end, curBytes);
18786
18883
  cur = void 0;
18787
18884
  }
@@ -18993,8 +19090,8 @@ function renderRow(i, row5, skewed, named, budget) {
18993
19090
  return body === null ? null : prefix + body;
18994
19091
  }
18995
19092
  function fitRow(row5, skewed, named, budget) {
18996
- const whole = JSON.stringify(row5);
18997
- if (bytes(whole) <= budget) return whole;
19093
+ const whole2 = JSON.stringify(row5);
19094
+ if (bytes(whole2) <= budget) return whole2;
18998
19095
  const own4 = Object.keys(row5);
18999
19096
  const tier = (k) => skewed.includes(k) ? 0 : named.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
19000
19097
  const order = [...own4].sort((a, b) => tier(a) - tier(b) || own4.indexOf(a) - own4.indexOf(b));
@@ -19860,9 +19957,9 @@ import { accessSync, constants as fsConstants, statSync as statSync3 } from "nod
19860
19957
  import path from "node:path";
19861
19958
 
19862
19959
  // src/core/sandbox/path-entries.ts
19863
- function pathEntries(value, platform = process.platform, delimiter = platform === "win32" ? ";" : ":") {
19960
+ function pathEntries(value, platform = process.platform, delimiter2 = platform === "win32" ? ";" : ":") {
19864
19961
  const win = platform === "win32";
19865
- return value.split(delimiter).map((e) => win && e.length >= 2 && e.startsWith('"') && e.endsWith('"') ? e.slice(1, -1) : e).filter(Boolean);
19962
+ return value.split(delimiter2).map((e) => win && e.length >= 2 && e.startsWith('"') && e.endsWith('"') ? e.slice(1, -1) : e).filter(Boolean);
19866
19963
  }
19867
19964
 
19868
19965
  // src/core/sandbox/runtimes.ts
@@ -20527,8 +20624,8 @@ var ctxBatch = Object.freeze({
20527
20624
  });
20528
20625
 
20529
20626
  // src/core/tools/doctor.ts
20530
- import { readdirSync as readdirSync5, readFileSync as readFileSync12, existsSync as existsSync12 } from "node:fs";
20531
- import { basename as basename4, dirname as dirname7, join as join14 } from "node:path";
20627
+ import { readdirSync as readdirSync5, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20628
+ import { basename as basename4, dirname as dirname7, join as join15 } from "node:path";
20532
20629
 
20533
20630
  // src/core/ops/doctor-config.ts
20534
20631
  import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
@@ -22980,8 +23077,8 @@ function setTomlText(text, path7, value) {
22980
23077
  if (sameValue(cur, value)) return text;
22981
23078
  const inline = doc.keys.find((k) => k.inline && k.full.length < path7.length && under(path7, k.full));
22982
23079
  if (inline !== void 0) {
22983
- const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
22984
- return replaceToml(text, doc, inline.full, whole);
23080
+ const whole2 = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
23081
+ return replaceToml(text, doc, inline.full, whole2);
22985
23082
  }
22986
23083
  if (isPlainObject3(cur) && isPlainObject3(value)) {
22987
23084
  const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
@@ -23660,14 +23757,18 @@ function mcpWrong(row5, home, env, worktree) {
23660
23757
  return true;
23661
23758
  }
23662
23759
  }
23760
+ function hookFile(row5, spec, home, env, worktree) {
23761
+ const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
23762
+ const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23763
+ const file2 = native !== null ? join11(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join11(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join11(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join11(kiroDirOf(env, home), ...spec.file.slice(1)) : join11(root, ...spec.file);
23764
+ return file2;
23765
+ }
23663
23766
  function hookParts(row5, home, env, worktree) {
23664
23767
  const spec = HOOK_HOST_FILE[row5.id];
23665
23768
  if (spec === null) return [];
23666
23769
  let block;
23667
23770
  try {
23668
- const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
23669
- const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23670
- const file2 = native !== null ? join11(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join11(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join11(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join11(kiroDirOf(env, home), ...spec.file.slice(1)) : join11(root, ...spec.file);
23771
+ const file2 = hookFile(row5, spec, home, env, worktree);
23671
23772
  block = hostConfigValueAt(readParsed(row5.id, file2).value, spec.key);
23672
23773
  if (row5.id === "codex") {
23673
23774
  const config4 = readParsed(row5.id, join11(codexDirOf(env, home), CONFIG_TOML_FILE)).value;
@@ -23708,12 +23809,15 @@ function checkHostConfig(row5, env, worktree) {
23708
23809
  const read3 = row5.id === "pi" ? mcpFile(row5, home, env) : null;
23709
23810
  if (parts.length === 0) return read3 === null ? pass("D3") : { ...pass("D3"), detail: read3 };
23710
23811
  const detail = D3_DETAIL(parts);
23711
- return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, DOCTOR_FIX_UPGRADE);
23812
+ const fix = parts.includes(PART_MCP) && parts.includes(PART_HOOKS) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
23813
+ return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, fix);
23712
23814
  }
23713
23815
  function checkV1Leftovers(agent, home, scope = {}) {
23714
23816
  const findings = detectV1(agent, home, scope);
23715
23817
  if (findings.length === 0) return pass("D4");
23716
- return fail2("D4", findings.map((f) => f.reason).join(D4_REASON_JOIN), DOCTOR_FIX_UPGRADE);
23818
+ const detail = findings.map((f) => f.reason).join(D4_REASON_JOIN);
23819
+ if (findings.every((f) => f.reason === V1_REASON.tmpFile)) return { ...pass("D4"), detail };
23820
+ return fail2("D4", detail, DOCTOR_FIX_UPGRADE);
23717
23821
  }
23718
23822
  function parsedOrNull(agent, file2, jsonc) {
23719
23823
  try {
@@ -23732,6 +23836,31 @@ function checkDoubleFire(agent, worktree) {
23732
23836
  const useClaudeHooks = isObject4(vscode) && vscode[VSCODE_CLAUDE_HOOKS_SETTING] === true;
23733
23837
  return hooksOn && useClaudeHooks ? fail2("D5b", D5B_DETAIL, D5B_FIX) : pass("D5b");
23734
23838
  }
23839
+ function configPaths(row5, env, worktree) {
23840
+ const home = homeDirOf(env);
23841
+ if (home === null) return [];
23842
+ const out = [];
23843
+ const mcp = mcpFile(row5, home, env);
23844
+ if (mcp !== null) out.push({ label: "MCP entry", path: mcp });
23845
+ const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23846
+ if (native !== null) out.push({ label: "Codex plugin MCP", path: join11(native, CODEX_PLUGIN_MCP_FILE) });
23847
+ const spec = HOOK_HOST_FILE[row5.id];
23848
+ if (spec !== null) {
23849
+ try {
23850
+ out.push({ label: "hook entries", path: hookFile(row5, spec, home, env, worktree) });
23851
+ } catch (err) {
23852
+ out.push({ label: "hook entries", path: err instanceof Error ? err.message : String(err) });
23853
+ }
23854
+ }
23855
+ if (spec !== null && spec.root === "plugin" || row5.installMode === "marketplace" || row5.installMode === "plugin") {
23856
+ try {
23857
+ out.push({ label: "plugin root", path: resolvePluginRoot(row5, env, worktree) });
23858
+ } catch (err) {
23859
+ out.push({ label: "plugin root", path: err instanceof Error ? err.message : String(err) });
23860
+ }
23861
+ }
23862
+ return out.filter((e, i) => out.findIndex((o) => o.path === e.path) === i);
23863
+ }
23735
23864
 
23736
23865
  // src/core/ops/doctor-db.ts
23737
23866
  import { existsSync as existsSync7 } from "node:fs";
@@ -24181,16 +24310,19 @@ function isObject5(v) {
24181
24310
  }
24182
24311
  function loadFixture(bundleDir2, agent) {
24183
24312
  const file2 = path6.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
24184
- if (!existsSync10(file2)) return null;
24313
+ if (!existsSync10(file2)) return { cause: D5_FIXTURE_FILE_ABSENT(file2) };
24185
24314
  let all;
24186
24315
  try {
24187
24316
  all = JSON.parse(hostText(readFileSync10(file2, "utf8")));
24188
- } catch {
24189
- return null;
24317
+ } catch (err) {
24318
+ return { cause: D5_FIXTURE_PARSE(file2, err instanceof Error ? err.message : String(err)) };
24190
24319
  }
24191
- if (!isObject5(all) || !Object.hasOwn(all, agent)) return null;
24320
+ if (!isObject5(all)) return { cause: D5_FIXTURE_PARSE(file2, "top level is not an object") };
24321
+ if (!Object.hasOwn(all, agent)) return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": " + D5_FIXTURE_AGENT_ABSENT(file2, Object.keys(all)) };
24192
24322
  const e = all[agent];
24193
- if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload")) return null;
24323
+ if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload")) {
24324
+ return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": the entry lacks an event name or a payload" };
24325
+ }
24194
24326
  return { event: e.event, payload: e.payload };
24195
24327
  }
24196
24328
  function payloadFor(payload, worktree) {
@@ -24244,7 +24376,7 @@ async function checkHookRoundTrip(i) {
24244
24376
  return row("UNKNOWN", D5_CODEX_UNTRUSTED_DETAIL);
24245
24377
  }
24246
24378
  const fixture = loadFixture(i.bundleDir, i.agent);
24247
- if (fixture === null) return row("UNKNOWN", D5_NO_FIXTURE_DETAIL(i.agent));
24379
+ if ("cause" in fixture) return row("UNKNOWN", fixture.cause);
24248
24380
  const now = i.now ?? (() => performance.now());
24249
24381
  const fixed = i.samples === void 0 ? null : Math.max(1, i.samples);
24250
24382
  const maxPairs = fixed ?? D5_MAX_PAIRS;
@@ -24406,8 +24538,13 @@ function envLine(key, value) {
24406
24538
  const typedValue = allowed !== void 0 && allowed.includes(value) ? value : REPORT_INVALID;
24407
24539
  return REPORT_ENV_PREFIX + typedKey + ": " + typedValue;
24408
24540
  }
24541
+ function fixCell(agent, row5) {
24542
+ if (row5.status === "PASS") return "";
24543
+ if (row5.status === "FAIL") return DOCTOR_FAIL_LINE(agent, row5.id, row5.detail, row5.fixCommand ?? "");
24544
+ return row5.fixCommand === void 0 ? "" : "Fix: " + row5.fixCommand;
24545
+ }
24409
24546
  function rowLine(agent, row5) {
24410
- const fix = row5.status === "FAIL" ? DOCTOR_FAIL_LINE(agent, row5.id, row5.detail, row5.fixCommand ?? "") : "";
24547
+ const fix = fixCell(agent, row5);
24411
24548
  return "| " + [row5.id + " " + row5.label, row5.status, row5.detail, fix].join(" | ") + " |";
24412
24549
  }
24413
24550
  function buildReport(input) {
@@ -24437,6 +24574,196 @@ function buildReportHead(input) {
24437
24574
  return lines.concat(tail).join("\n");
24438
24575
  }
24439
24576
 
24577
+ // src/core/ops/doctor-issue.ts
24578
+ import { spawnSync as spawnSync3 } from "node:child_process";
24579
+ import { closeSync, existsSync as existsSync12, fstatSync, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
24580
+ import { delimiter, join as join14 } from "node:path";
24581
+ var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
24582
+ function tildeOf(env) {
24583
+ const home = homeDirOf(env);
24584
+ if (home === null || home === "") return (t) => t;
24585
+ const homes = [home];
24586
+ try {
24587
+ const real2 = realpathSync8.native(home);
24588
+ if (real2 !== home) homes.push(real2);
24589
+ } catch {
24590
+ }
24591
+ homes.sort((a, b) => b.length - a.length);
24592
+ const slash = (rest) => rest.replace(/^[^\s"'`|)>,;]*/, (run) => run.replace(/\\/g, "/"));
24593
+ return (t) => homes.reduce((acc, h) => acc.split(h).map((piece, n) => n === 0 ? piece : slash(piece)).join("~"), t);
24594
+ }
24595
+ function maskLine(line) {
24596
+ const lower = line.toLowerCase();
24597
+ const named = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
24598
+ const token = TOKEN_PREFIXES.some((p) => line.includes(p));
24599
+ if (!named && !token) return line;
24600
+ const at2 = Math.max(line.indexOf(":"), line.indexOf("="));
24601
+ return at2 === -1 ? DOCTOR_MASK : line.slice(0, at2 + 1) + " " + DOCTOR_MASK;
24602
+ }
24603
+ function environmentLine(ctx, adapter, env, version4) {
24604
+ const sha = BUNDLE_SHA === void 0 ? "dev build" : BUNDLE_SHA.slice(0, 7);
24605
+ const client = ctx.clientInfo;
24606
+ const agent = client === void 0 ? adapter.id : client.name === adapter.id ? `${adapter.id} ${client.version}` : `${adapter.id} ${client.version} (client ${client.name})`;
24607
+ const shell = env.SHELL ?? env.ComSpec ?? "sh";
24608
+ return `${DOCTOR_ENV_PREFIX}context-mode ${version4 ?? "source checkout"} (${sha}), agent ${agent}
24609
+ ${DOCTOR_ENV_PREFIX}${process.platform}-${process.arch}, Node ${process.version}, shell ${shell}`;
24610
+ }
24611
+ function gitVersion(env) {
24612
+ const r = spawnSync3("git", ["--version"], { env, encoding: "utf8", timeout: DOCTOR_GIT_VERSION_TIMEOUT_MS, windowsHide: true });
24613
+ if (r.status === 0) return `${r.stdout}`.trim();
24614
+ return `git --version: ${r.error ? r.error.message : `exit ${r.status}`}`;
24615
+ }
24616
+ function onPath(env, tool) {
24617
+ const names = process.platform === "win32" ? [tool + EXE_SUFFIX, tool + ".cmd", tool] : [tool];
24618
+ const out = [];
24619
+ for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
24620
+ if (dir === "") continue;
24621
+ for (const n of names) if (existsSync12(join14(dir, n))) {
24622
+ out.push(join14(dir, n));
24623
+ break;
24624
+ }
24625
+ }
24626
+ return out;
24627
+ }
24628
+ function hookLogTail(env) {
24629
+ const file2 = hookLogPath(env);
24630
+ if (file2 === "" || !existsSync12(file2)) return [`(${file2 || "hook-errors.log"} holds zero lines)`];
24631
+ try {
24632
+ const fd = openSync(file2, "r");
24633
+ try {
24634
+ const size = fstatSync(fd).size;
24635
+ const start = Math.max(0, size - DOCTOR_LOG_TAIL_BYTES);
24636
+ const buf = Buffer.alloc(size - start);
24637
+ readSync(fd, buf, 0, buf.length, start);
24638
+ const lines = buf.toString("utf8").split("\n").filter((l) => l.trim() !== "");
24639
+ if (start > 0) lines.shift();
24640
+ return lines.slice(-DOCTOR_HOOK_LOG_LINES).map(maskLine);
24641
+ } finally {
24642
+ closeSync(fd);
24643
+ }
24644
+ } catch (err) {
24645
+ return [`hook-errors.log read: ${err instanceof Error ? err.message : String(err)}`];
24646
+ }
24647
+ }
24648
+ async function journalRows(ctx) {
24649
+ const head = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
24650
+ if (!existsSync12(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
24651
+ try {
24652
+ const db = await openDb(ctx.project, { readOnly: true });
24653
+ try {
24654
+ const rows = db.raw.prepare(`SELECT kind, tool, bytes, ok, exit_code, created_at FROM events ORDER BY seq DESC LIMIT ${DOCTOR_JOURNAL_ROWS}`).all();
24655
+ const cell5 = (v) => v === null || v === void 0 ? "" : String(v);
24656
+ return head.concat(rows.map((r) => `| ${cell5(r.kind)} | ${cell5(r.tool)} | ${cell5(r.bytes)} | ${cell5(r.ok)} | ${cell5(r.exit_code)} | ${typeof r.created_at === "number" ? new Date(r.created_at).toISOString() : cell5(r.created_at)} |`));
24657
+ } finally {
24658
+ closeDb(db);
24659
+ }
24660
+ } catch (err) {
24661
+ return [`journal read: ${err instanceof Error ? err.message : String(err)}`];
24662
+ }
24663
+ }
24664
+ function agentConfig(adapter, env, worktree) {
24665
+ const home = homeDirOf(env);
24666
+ const files = configPaths(adapter, env, worktree);
24667
+ if (home !== null) {
24668
+ if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join14(claudeDirOf(env, home), SETTINGS_FILE) });
24669
+ if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join14(codexDirOf(env, home), CONFIG_TOML_FILE) });
24670
+ }
24671
+ const out = [];
24672
+ const seen = /* @__PURE__ */ new Set();
24673
+ for (const f of files) {
24674
+ if (seen.has(f.path)) continue;
24675
+ seen.add(f.path);
24676
+ if (!existsSync12(f.path)) {
24677
+ out.push(`${f.label}: ${f.path} (absent)`);
24678
+ continue;
24679
+ }
24680
+ let text = "";
24681
+ try {
24682
+ text = readFileSync12(f.path, "utf8");
24683
+ } catch (err) {
24684
+ out.push(`${f.label}: ${f.path} (read: ${err instanceof Error ? err.message : String(err)})`);
24685
+ continue;
24686
+ }
24687
+ const hit = text.split("\n").filter((l) => l.includes("context-mode") || l.includes("hook.mjs") || adapter.id === "codex" && l.includes("trust"));
24688
+ out.push(`${f.label}: ${f.path} (${hit.length} matching lines)`);
24689
+ for (const l of hit.slice(0, DOCTOR_CONFIG_LINES)) out.push(" " + maskLine(l.trimEnd()));
24690
+ }
24691
+ return out;
24692
+ }
24693
+ function failing(rows) {
24694
+ return rows.filter((r) => r.status === "FAIL");
24695
+ }
24696
+ function issueTitle(agent, rows) {
24697
+ return `ctx_doctor ${agent}: ${failing(rows).map((r) => `${r.id} ${r.label}`).join(", ")} FAIL`;
24698
+ }
24699
+ function summaryOf(agent, rows) {
24700
+ const f = failing(rows)[0];
24701
+ return f === void 0 ? `ctx_doctor ${agent}` : `${f.id} ${f.label} FAIL on ${agent}: ${f.detail}`;
24702
+ }
24703
+ async function buildIssueBody(i) {
24704
+ const tilde = tildeOf(i.env);
24705
+ const agent = i.adapter.id;
24706
+ const install = NATIVE_INSTALL[agent] ?? [];
24707
+ const failRows = i.rows.filter((r) => r.status !== "PASS");
24708
+ const envNames = DOCTOR_ENV_NAMES.map((n) => i.env[n] === void 0 ? `${n} (unset)` : `${n}=${i.env[n]}`);
24709
+ const pathTools = DOCTOR_PATH_TOOLS.map((t) => `PATH holds ${t}: ${onPath(i.env, t).join(", ") || "(absent)"}`);
24710
+ const sections = {
24711
+ "Summary": [summaryOf(agent, i.rows)],
24712
+ "ctx-report": [i.table],
24713
+ "What happened": [
24714
+ "Rows that need a look:",
24715
+ ...failRows.map((r) => `- ${r.id} ${r.label} ${r.status}: ${r.detail}${r.fixCommand ? ` (Fix: ${r.fixCommand})` : ""}`),
24716
+ "Error code and text: <the agent fills this in: the exact error the user saw>"
24717
+ ],
24718
+ "Hook errors": ["hook-errors.log, last " + DOCTOR_HOOK_LOG_LINES + " lines (UTC):", "```", ...hookLogTail(i.env), "```"],
24719
+ "Journal rows": ["events, newest first, last " + DOCTOR_JOURNAL_ROWS + " (bodies stay local):", ...await journalRows(i.ctx)],
24720
+ "Agent config": agentConfig(i.adapter, i.env, i.ctx.project.worktree),
24721
+ "Expected": ["Expected: <the agent fills this in: what should happen, with the byte count>"],
24722
+ "Steps": [
24723
+ "Reproduced: <yes (2 of 2) or 1 of 2>",
24724
+ "Prompt or command: <the agent fills this in: the exact prompt or command>",
24725
+ "Actual: <the agent fills this in: what context-mode did, with the byte count>",
24726
+ "Repro script (fresh HOME, native install for " + agent + "):",
24727
+ "```sh",
24728
+ 'export HOME="$(mktemp -d)"',
24729
+ 'cd "$HOME"',
24730
+ ...install,
24731
+ "<the command or prompt above>",
24732
+ "```"
24733
+ ],
24734
+ "Environment": [
24735
+ i.envLine,
24736
+ `context-mode bundle: ${i.bundleDir}`,
24737
+ `Install route: ${install.join(" && ")}`,
24738
+ `git: ${gitVersion(i.env)}`,
24739
+ ...pathTools,
24740
+ ...envNames,
24741
+ `Project: ${i.ctx.project.worktree} (key ${i.ctx.project.projectKey})`,
24742
+ "Filed by: <your agent name, version, model id>"
24743
+ ]
24744
+ };
24745
+ const out = [];
24746
+ for (const h of ISSUE_FORM_HEADINGS) out.push(`### ${h}`, "", ...sections[h] ?? [], "");
24747
+ return tilde(out.join("\n"));
24748
+ }
24749
+ async function writeIssueReport(i) {
24750
+ const tilde = tildeOf(i.env);
24751
+ const body = await buildIssueBody(i);
24752
+ const dir = join14(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
24753
+ mkdirSync5(dir, { recursive: true });
24754
+ const file2 = join14(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
24755
+ writeFileSync3(file2, body);
24756
+ const shown2 = tilde(file2);
24757
+ const title = issueTitle(i.adapter.id, i.rows);
24758
+ const gh = [`gh issue create --repo ${ISSUE_REPO_SLUG} --label bug \\`, `${DOCTOR_GH_NEXT}title ${JSON.stringify(title)} \\`, `${DOCTOR_GH_NEXT}body-file ${shown2}`];
24759
+ return [DOCTOR_REPORT_LINE + shown2, DOCTOR_GH_LINE + gh[0], gh[1], gh[2], DOCTOR_URL_LINE + formUrl(title, summaryOf(i.adapter.id, i.rows))];
24760
+ }
24761
+ function formUrl(title, summary) {
24762
+ const base = `${ISSUE_FORM_URL}&title=${encodeURIComponent(title)}`;
24763
+ const full = `${base}&summary=${encodeURIComponent(summary)}`;
24764
+ return full.length < ISSUE_URL_MAX ? full : base;
24765
+ }
24766
+
24440
24767
  // src/core/tools/doctor.ts
24441
24768
  var ctxDoctorSchema = external_exports.object({}).strict();
24442
24769
  function lineOf2(err) {
@@ -24451,7 +24778,7 @@ async function guard(id, run) {
24451
24778
  }
24452
24779
  }
24453
24780
  async function codexDb(ctx, adapter) {
24454
- if (adapter.id !== "codex" || !existsSync12(ctx.project.dbPath)) return null;
24781
+ if (adapter.id !== "codex" || !existsSync13(ctx.project.dbPath)) return null;
24455
24782
  try {
24456
24783
  return await openDb(ctx.project, { readOnly: true });
24457
24784
  } catch {
@@ -24481,11 +24808,11 @@ async function hookRow(ctx, adapter, host) {
24481
24808
  }
24482
24809
  }
24483
24810
  function ownServerId(configDir, projectKey) {
24484
- const dir = join14(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24485
- if (!existsSync12(dir)) return "";
24811
+ const dir = join15(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24812
+ if (!existsSync13(dir)) return "";
24486
24813
  for (const name of readdirSync5(dir)) {
24487
24814
  if (!name.endsWith(OWNER_PID_EXT)) continue;
24488
- if (readFileSync12(join14(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
24815
+ if (readFileSync13(join15(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
24489
24816
  }
24490
24817
  return "";
24491
24818
  }
@@ -24530,24 +24857,39 @@ function reportEnv(env) {
24530
24857
  }
24531
24858
  return out;
24532
24859
  }
24533
- async function handler2(_input, ctx) {
24860
+ async function doctorReply(ctx, host) {
24534
24861
  const adapter = getAdapter(ctx.project.agent);
24535
- const host = { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 };
24536
24862
  const rows = await runDoctorChecks(ctx, adapter, host);
24537
- const command = `context-mode ${rows.some((r) => r.status === "FAIL") ? "setup" : "doctor"} --agents ${adapter.id}`;
24538
- const input = { agent: adapter.id, rows, env: reportEnv(process.env), command };
24539
- const whole = buildReport(input);
24540
- const bytes5 = Buffer.byteLength(whole, "utf8");
24541
- if (bytes5 <= REPORT_CAP) return { text: whole, isError: false, sandboxBytes: bytes5 };
24863
+ const failed2 = rows.some((r) => r.status === "FAIL");
24864
+ const command = `context-mode ${failed2 ? "setup" : "doctor"} --agents ${adapter.id}`;
24865
+ const input = { agent: adapter.id, rows, env: reportEnv(host.env), command };
24866
+ const envLine2 = environmentLine(ctx, adapter, host.env, bundleVersion(host.bundleDir));
24867
+ const table3 = buildReport(input);
24868
+ let notes = [];
24869
+ if (failed2) {
24870
+ try {
24871
+ notes = await writeIssueReport({ ctx, adapter, env: host.env, bundleDir: host.bundleDir, rows, envLine: envLine2, table: table3 });
24872
+ } catch (err) {
24873
+ notes = [`Report file: ${lineOf2(err)}`];
24874
+ }
24875
+ }
24876
+ const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
24877
+ const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
24878
+ const whole2 = [envLine2, table3, ...docs, ...notes].join("\n");
24879
+ const bytes5 = Buffer.byteLength(whole2, "utf8");
24880
+ if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
24542
24881
  const db = await openDb(ctx.project);
24543
24882
  try {
24544
- indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole, "text");
24883
+ indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
24545
24884
  } finally {
24546
24885
  closeDb(db);
24547
24886
  }
24548
- const text = buildReportHead(input);
24887
+ const text = [envLine2, buildReportHead(input), ...docs, ...notes].join("\n");
24549
24888
  return { text, isError: false, sandboxBytes: bytes5 };
24550
24889
  }
24890
+ async function handler2(_input, ctx) {
24891
+ return doctorReply(ctx, { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 });
24892
+ }
24551
24893
  var ctxDoctor = Object.freeze({
24552
24894
  name: "ctx_doctor",
24553
24895
  schema: ctxDoctorSchema,
@@ -24558,9 +24900,9 @@ var ctxDoctor = Object.freeze({
24558
24900
  });
24559
24901
 
24560
24902
  // src/core/tools/execute.ts
24561
- import { existsSync as existsSync13, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
24903
+ import { existsSync as existsSync14, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "node:fs";
24562
24904
  import { tmpdir as tmpdir2 } from "node:os";
24563
- import { dirname as dirname8, join as join15, parse as parse3, resolve as resolve6 } from "node:path";
24905
+ import { dirname as dirname8, join as join16, parse as parse3, resolve as resolve6 } from "node:path";
24564
24906
 
24565
24907
  // src/core/sandbox/win-build.ts
24566
24908
  var SEPARATORS2 = ";&|(\n";
@@ -24644,7 +24986,7 @@ function schemaLine(issue4) {
24644
24986
  }
24645
24987
  function fileError(given, abs, root) {
24646
24988
  let dir = abs;
24647
- while (!existsSync13(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
24989
+ while (!existsSync14(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
24648
24990
  if (isInside(root, dir)) return null;
24649
24991
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
24650
24992
  }
@@ -24725,9 +25067,9 @@ async function handler3(raw, ctx) {
24725
25067
  if (takesDashC(input.language, runtime)) {
24726
25068
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
24727
25069
  } else {
24728
- tmpDir = mkdtempSync(join15(tmpdir2(), TMP_PREFIX));
24729
- const file2 = join15(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
24730
- writeFileSync3(file2, scriptText(input.language, input.code), "utf8");
25070
+ tmpDir = mkdtempSync(join16(tmpdir2(), TMP_PREFIX));
25071
+ const file2 = join16(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
25072
+ writeFileSync4(file2, scriptText(input.language, input.code), "utf8");
24731
25073
  argv = scriptArgv(input.language, runtime, file2);
24732
25074
  }
24733
25075
  if (input.background === true) {
@@ -24761,21 +25103,21 @@ var ctxExecute = {
24761
25103
  };
24762
25104
 
24763
25105
  // src/core/tools/index.ts
24764
- import { existsSync as existsSync14, readFileSync as readFileSync14, statSync as statSync7 } from "node:fs";
24765
- import { dirname as dirname9, extname, join as join17, relative as relative3, resolve as resolve7 } from "node:path";
25106
+ import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as statSync7 } from "node:fs";
25107
+ import { dirname as dirname9, extname, join as join18, relative as relative3, resolve as resolve7 } from "node:path";
24766
25108
 
24767
25109
  // src/core/index/walk.ts
24768
- import { readdirSync as readdirSync6, readFileSync as readFileSync13, realpathSync as realpathSync8, statSync as statSync6 } from "node:fs";
24769
- import { join as join16 } from "node:path";
25110
+ import { readdirSync as readdirSync6, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync6 } from "node:fs";
25111
+ import { join as join17 } from "node:path";
24770
25112
  var GITIGNORE = ".gitignore";
24771
25113
  var GIT_DIR = ".git";
24772
25114
  function walkDir(root, containmentRoot) {
24773
- const real2 = realpathSync8(root);
25115
+ const real2 = realpathSync9(root);
24774
25116
  if (!isInside(containmentRoot, real2)) throw new CtxError("OUTSIDE_ROOT", { p: root, root: containmentRoot });
24775
25117
  const found = [];
24776
25118
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
24777
25119
  found.sort(compareFound);
24778
- return found.map((f) => ({ absPath: f.absPath, relPath: join16(...f.dir, f.name) }));
25120
+ return found.map((f) => ({ absPath: f.absPath, relPath: join17(...f.dir, f.name) }));
24779
25121
  }
24780
25122
  function visit(abs, rel, parent, contain, seen, found) {
24781
25123
  let entries;
@@ -24784,17 +25126,17 @@ function visit(abs, rel, parent, contain, seen, found) {
24784
25126
  } catch {
24785
25127
  return;
24786
25128
  }
24787
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join16(abs, GITIGNORE), rel)) : parent;
25129
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join17(abs, GITIGNORE), rel)) : parent;
24788
25130
  for (const e of entries) {
24789
25131
  if (e.name === GIT_DIR) continue;
24790
- const path7 = join16(abs, e.name);
25132
+ const path7 = join17(abs, e.name);
24791
25133
  let isDir = e.isDirectory();
24792
25134
  let isFile = e.isFile();
24793
25135
  let target = path7;
24794
25136
  if (e.isSymbolicLink()) {
24795
25137
  let resolved;
24796
25138
  try {
24797
- resolved = realpathSync8(path7);
25139
+ resolved = realpathSync9(path7);
24798
25140
  } catch {
24799
25141
  continue;
24800
25142
  }
@@ -24809,7 +25151,7 @@ function visit(abs, rel, parent, contain, seen, found) {
24809
25151
  if (isFile) {
24810
25152
  found.push({ dir: rel, name: e.name, absPath: path7 });
24811
25153
  } else if (isDir) {
24812
- const key = e.isSymbolicLink() ? target : realpathSync8(path7);
25154
+ const key = e.isSymbolicLink() ? target : realpathSync9(path7);
24813
25155
  if (seen.has(key)) continue;
24814
25156
  seen.add(key);
24815
25157
  visit(path7, segs, rules, contain, seen, found);
@@ -24827,7 +25169,7 @@ function compareFound(a, b) {
24827
25169
  function readRules(file2, base) {
24828
25170
  let body;
24829
25171
  try {
24830
- body = readFileSync13(file2, "utf8");
25172
+ body = readFileSync14(file2, "utf8");
24831
25173
  } catch {
24832
25174
  return [];
24833
25175
  }
@@ -28910,14 +29252,14 @@ function kindOfType(contentType) {
28910
29252
  }
28911
29253
  function readUtf8(absPath) {
28912
29254
  try {
28913
- return utf8.decode(readFileSync14(absPath));
29255
+ return utf8.decode(readFileSync15(absPath));
28914
29256
  } catch {
28915
29257
  return void 0;
28916
29258
  }
28917
29259
  }
28918
29260
  function missingOrOutside(given, abs, root) {
28919
29261
  let dir = abs;
28920
- while (!existsSync14(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
29262
+ while (!existsSync15(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
28921
29263
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
28922
29264
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
28923
29265
  }
@@ -28928,7 +29270,7 @@ function pathItems(input, project) {
28928
29270
  if (statSync7(abs).isDirectory()) {
28929
29271
  return walkDir(abs, project.containmentRoot).map((f) => ({
28930
29272
  sourceKind: "path",
28931
- label: pathLabel(join17(base, f.relPath)),
29273
+ label: pathLabel(join18(base, f.relPath)),
28932
29274
  kind: kindOfPath(f.relPath),
28933
29275
  read: () => readUtf8(f.absPath)
28934
29276
  }));
@@ -29135,6 +29477,43 @@ var KINDS = "SELECT kind, COALESCE(SUM(session_id = ?), 0) AS s, COUNT(*) AS p F
29135
29477
  var META = `SELECT COUNT(DISTINCT session_id) AS sessions, COUNT(DISTINCT agent) AS agents, COUNT(DISTINCT created_at / ${MS_PER_DAY}) AS days FROM events WHERE ${CALLS}`;
29136
29478
  var SPAN = "SELECT COALESCE(MAX(created_at) - MIN(created_at), 0) AS span FROM events WHERE session_id = ? AND kind <> 'cost'";
29137
29479
  var SOURCES = "SELECT COUNT(*) AS n, COALESCE(SUM(chunk_count), 0) AS chunks, COALESCE(SUM(bytes_total), 0) AS bytes FROM sources";
29480
+ var HOST = "tool NOT LIKE 'ctx\\_%' ESCAPE '\\'";
29481
+ var REPLACED = `SELECT COUNT(*) AS n FROM events WHERE ${CALLS} AND ${HOST} AND returned_bytes < sandbox_bytes`;
29482
+ var RUNS = "FROM sources WHERE substr(label, 1, ?) = ?";
29483
+ var REDIRECTED = `SELECT COUNT(*) AS n, COALESCE(MAX(created_ts), 0) AS last ${RUNS}`;
29484
+ var LAST = `SELECT COALESCE(MAX(created_at), 0) AS last FROM events WHERE ${CALLS}`;
29485
+ var WEEK = `SELECT created_at / ${MS_PER_DAY} AS day, tool, COUNT(*) AS calls, COALESCE(SUM(sandbox_bytes), 0) AS produced, COALESCE(SUM(returned_bytes), 0) AS returned FROM events WHERE ${CALLS} AND created_at >= ? GROUP BY day, tool`;
29486
+ var WEEK_RUNS = `SELECT created_ts / ${MS_PER_DAY} AS day, COUNT(*) AS calls, COALESCE(SUM(MAX(0, bytes_total - ${OUTPUT_CAP})), 0) AS saved ${RUNS} AND created_ts >= ? GROUP BY day`;
29487
+ var TOP = `SELECT tool, 1 AS calls, sandbox_bytes AS produced, returned_bytes AS returned FROM events WHERE ${CALLS} AND sandbox_bytes > 0 ORDER BY sandbox_bytes DESC, seq ASC LIMIT ${STATS_TOP_OUTPUTS}`;
29488
+ function wayOf(tool) {
29489
+ if (STATS_INDEX_TOOLS.includes(tool)) return "index";
29490
+ return tool.startsWith("ctx_") ? "sandbox" : "replace";
29491
+ }
29492
+ function readWeek(raw, lastMs) {
29493
+ const last2 = Math.floor(lastMs / MS_PER_DAY);
29494
+ const first = last2 - STATS_DAYS + 1;
29495
+ const days = Array.from({ length: STATS_DAYS }, (_, i) => ({
29496
+ day: first + i,
29497
+ calls: 0,
29498
+ ways: { sandbox: 0, index: 0, redirect: 0, replace: 0 }
29499
+ }));
29500
+ const net = /* @__PURE__ */ new Map();
29501
+ for (const r of raw.prepare(WEEK).all(first * MS_PER_DAY)) {
29502
+ const d = days[Number(r.day) - first];
29503
+ if (d === void 0) continue;
29504
+ d.calls += Number(r.calls);
29505
+ const key = `${d.day}:${wayOf(String(r.tool))}`;
29506
+ net.set(key, (net.get(key) ?? 0) + Number(r.produced) - Number(r.returned));
29507
+ }
29508
+ for (const d of days) for (const [way] of STATS_WAYS) d.ways[way] = Math.max(0, net.get(`${d.day}:${way}`) ?? 0);
29509
+ for (const r of raw.prepare(WEEK_RUNS).all(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX, first * MS_PER_DAY)) {
29510
+ const d = days[Number(r.day) - first];
29511
+ if (d === void 0) continue;
29512
+ d.calls += Number(r.calls);
29513
+ d.ways.redirect += Number(r.saved);
29514
+ }
29515
+ return days;
29516
+ }
29138
29517
  var EMPTY5 = Object.freeze({ calls: 0, produced: 0, returned: 0, saved: 0 });
29139
29518
  function totals(r) {
29140
29519
  const produced = Number(r.produced);
@@ -29149,6 +29528,8 @@ function readFacts(raw, sessionId) {
29149
29528
  const meta3 = raw.prepare(META).get();
29150
29529
  const span2 = Number(raw.prepare(SPAN).get(sessionId).span);
29151
29530
  const src = raw.prepare(SOURCES).get();
29531
+ const runs = raw.prepare(REDIRECTED).get(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX);
29532
+ const last2 = Math.max(Number(raw.prepare(LAST).get().last), Number(runs.last));
29152
29533
  const pages = raw.prepare("PRAGMA page_count").get();
29153
29534
  const size = raw.prepare("PRAGMA page_size").get();
29154
29535
  return {
@@ -29160,7 +29541,11 @@ function readFacts(raw, sessionId) {
29160
29541
  agents: Number(meta3.agents),
29161
29542
  days: Number(meta3.days),
29162
29543
  sources: { count: Number(src.n), chunks: Number(src.chunks), bytes: Number(src.bytes) },
29163
- dbBytes: Number(pages.page_count) * Number(size.page_size)
29544
+ dbBytes: Number(pages.page_count) * Number(size.page_size),
29545
+ top: raw.prepare(TOP).all().map((r) => ({ name: String(r.tool), ...totals(r) })),
29546
+ replaced: Number(raw.prepare(REPLACED).get().n),
29547
+ redirected: Number(runs.n),
29548
+ week: readWeek(raw, last2)
29164
29549
  };
29165
29550
  }
29166
29551
  function sum(groups) {
@@ -29191,6 +29576,7 @@ function count(n) {
29191
29576
  return n < STATS_MILLION ? int2(n) : (n / STATS_MILLION).toFixed(1) + "M";
29192
29577
  }
29193
29578
  function bytes4(n) {
29579
+ if (n < 0) return "-" + bytes4(-n);
29194
29580
  if (n < STATS_KIB) return int2(n) + " B";
29195
29581
  let v = n / STATS_KIB;
29196
29582
  let u = 0;
@@ -29223,17 +29609,105 @@ function plural(n, word) {
29223
29609
  }
29224
29610
  function table2(title, rows) {
29225
29611
  const max = Math.max(0, ...rows.map((r) => r.saved));
29226
- const head = " " + title.padEnd(LABEL_W) + "Calls".padStart(STATS_CALLS_W) + "Produced".padStart(NUM_W) + "Returned".padStart(NUM_W) + "Saved".padStart(NUM_W) + "%".padStart(PCT_W);
29612
+ const head = " " + title.padEnd(LABEL_W) + "Calls".padStart(STATS_CALLS_W) + "Made".padStart(NUM_W) + "Sent".padStart(NUM_W) + "Kept out".padStart(NUM_W) + "%".padStart(PCT_W);
29227
29613
  return [head, ...rows.map((r) => (" " + label(r.name) + count(r.calls).padStart(STATS_CALLS_W) + bytes4(r.produced).padStart(NUM_W) + bytes4(r.returned).padStart(NUM_W) + bytes4(r.saved).padStart(NUM_W) + pct(r).padStart(PCT_W) + " " + bar(r.saved, max, STATS_ROW_BAR)).trimEnd())];
29228
29614
  }
29229
29615
  function bySaved(a, b) {
29230
29616
  return b.saved - a.saved || b.produced - a.produced || a.returned - b.returned || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
29231
29617
  }
29618
+ function toolName(tool) {
29619
+ return tool.startsWith("ctx_") ? tool : "hook " + tool;
29620
+ }
29621
+ function joinIndex(tools) {
29622
+ const idx = tools.filter((t2) => STATS_INDEX_TOOLS.includes(t2.name));
29623
+ if (idx.length <= 1) return tools;
29624
+ const t = sum(idx);
29625
+ const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: t.produced - t.returned };
29626
+ return [...tools.filter((x) => !idx.includes(x)), one];
29627
+ }
29232
29628
  function toolRows(tools) {
29233
- const named = tools.map((t) => ({ ...t, name: t.name.startsWith("ctx_") ? t.name : "hook " + t.name })).sort(bySaved);
29234
- if (named.length <= STATS_MAX_TOOL_ROWS) return named;
29235
- const rest = named.slice(STATS_MAX_TOOL_ROWS - 1);
29236
- return [...named.slice(0, STATS_MAX_TOOL_ROWS - 1), { name: `other (${rest.length} tools)`, ...sum(rest) }];
29629
+ const named = joinIndex(tools.map((t) => ({ ...t, saved: t.produced - t.returned }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
29630
+ const zero = named.filter((t) => t.saved <= 0);
29631
+ const fold2 = zero.length > 1 ? zero : [];
29632
+ const keep = named.filter((t) => !fold2.includes(t));
29633
+ const room = fold2.length > 0 ? STATS_MAX_TOOL_ROWS - 1 : STATS_MAX_TOOL_ROWS;
29634
+ const over = keep.length > room;
29635
+ const shown2 = over ? keep.slice(0, STATS_MAX_TOOL_ROWS - 1) : keep;
29636
+ const rest = over ? [...keep.slice(STATS_MAX_TOOL_ROWS - 1), ...fold2] : fold2;
29637
+ return rest.length === 0 ? shown2 : [...shown2, { name: `other (${plural(rest.length, "tool")})`, ...sum(rest) }];
29638
+ }
29639
+ var TOKEN_UNITS = ["K", "M", "B", "T"];
29640
+ function whole(v) {
29641
+ return v >= STATS_WHOLE_FROM ? int2(v) : v.toFixed(1);
29642
+ }
29643
+ function tokens(n) {
29644
+ if (n < STATS_THOUSAND) return int2(n);
29645
+ let v = n / STATS_THOUSAND;
29646
+ let u = 0;
29647
+ while (v >= STATS_THOUSAND && u < TOKEN_UNITS.length - 1) {
29648
+ v /= STATS_THOUSAND;
29649
+ u++;
29650
+ }
29651
+ return whole(v) + TOKEN_UNITS[u];
29652
+ }
29653
+ function windowLine(saved) {
29654
+ const t = saved / STATS_BYTES_PER_TOKEN;
29655
+ const share = t / STATS_WINDOW_TOKENS;
29656
+ const win = `a ${tokens(STATS_WINDOW_TOKENS)} window`;
29657
+ const head = ` about ${tokens(t)} tokens kept out`;
29658
+ if (share >= 1) return `${head}, ${whole(share)} times ${win}`;
29659
+ const p = share * PERCENT_SCALE;
29660
+ return p * STATS_WHOLE_FROM < 1 ? head : `${head}, ${whole(p)}% of ${win}`;
29661
+ }
29662
+ function ymd(day) {
29663
+ return new Date(day * MS_PER_DAY).toISOString().slice(0, "yyyy-mm-dd".length);
29664
+ }
29665
+ function mmdd(day) {
29666
+ return ymd(day).slice("yyyy-".length);
29667
+ }
29668
+ function stack(parts, max, width) {
29669
+ let total = 0;
29670
+ let at2 = 0;
29671
+ let out = "";
29672
+ parts.forEach((v, i) => {
29673
+ total += v;
29674
+ const end = max <= 0 ? 0 : Math.round(total / max * width);
29675
+ if (end > at2) {
29676
+ out += STATS_WAYS[i][1].repeat(end - at2);
29677
+ at2 = end;
29678
+ }
29679
+ });
29680
+ if (out === "" && total > 0) out = STATS_WAYS[parts.indexOf(Math.max(...parts))][1];
29681
+ return out;
29682
+ }
29683
+ function cards(cells) {
29684
+ return (" " + cells.map((c) => c.padEnd(STATS_CARD_W)).join("")).trimEnd();
29685
+ }
29686
+ function lastDays(week, allCalls) {
29687
+ const saved = week.map((d) => STATS_WAYS.reduce((t, [w]) => t + d.ways[w], 0));
29688
+ const all = saved.reduce((a, b) => a + b, 0);
29689
+ const calls = week.reduce((a, d) => a + d.calls, 0);
29690
+ const max = Math.max(0, ...saved);
29691
+ const head = `Last ${STATS_DAYS} days of use \xB7 ${ymd(week[0].day)} to ${ymd(week[week.length - 1].day)}`;
29692
+ const card = calls < allCalls ? [
29693
+ cards(["Kept out", "Tokens kept out", "Calls", "Kept out per call"]),
29694
+ cards([bytes4(all), "about " + tokens(all / STATS_BYTES_PER_TOKEN), count(calls), bytes4(calls > 0 ? all / calls : 0)]),
29695
+ ""
29696
+ ] : [];
29697
+ return [
29698
+ head,
29699
+ ...card,
29700
+ ...week.flatMap((d, i) => saved[i] > 0 ? [" " + mmdd(d.day) + " " + stack(STATS_WAYS.map(([w]) => d.ways[w]), max, STATS_DAY_BAR).padEnd(STATS_DAY_BAR) + bytes4(saved[i]).padStart(NUM_W)] : []),
29701
+ " " + STATS_WAYS.map(([, ch, name]) => `${ch} ${name}`).join(" "),
29702
+ ""
29703
+ ];
29704
+ }
29705
+ function hookLine(redirected, replaced) {
29706
+ const all = redirected + replaced;
29707
+ if (all === 0) return [];
29708
+ const parts = [...redirected > 0 ? [`${int2(redirected)} sent to the sandbox`] : [], ...replaced > 0 ? [`${int2(replaced)} cut down`] : []];
29709
+ const what = plural(all, "large output");
29710
+ return [parts.length === 1 ? ` Project hooks: ${what} ${parts[0].replace(/^[\d,]+ /, "")}` : ` Project hooks: ${what} kept out \xB7 ${parts.join(", ")}`];
29237
29711
  }
29238
29712
  function fit(line) {
29239
29713
  const chars = [...line];
@@ -29250,20 +29724,30 @@ function report(f, sessionId, agent) {
29250
29724
  const lines = [
29251
29725
  ...head,
29252
29726
  `${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
29727
+ ` ${bytes4(focus.produced)} became ${bytes4(focus.returned)}: ${bytes4(focus.saved)} kept out (${pct(focus)})`,
29253
29728
  " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.produced).padStart(NUM_W),
29254
29729
  " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.returned).padStart(NUM_W),
29255
- ` ${bytes4(focus.saved)} saved (${pct(focus)}) \xB7 about ${int2(focus.saved / STATS_BYTES_PER_TOKEN)} tokens kept out of the chat`,
29730
+ ...focus.saved > 0 ? [windowLine(focus.saved), STATS_TOKEN_NOTE] : [],
29731
+ ...hookLine(f.redirected, f.replaced),
29256
29732
  "",
29257
- ...table2("Scope", [{ name: "session", ...session }, { name: "project", ...project }, { name: "all-time", ...project }]),
29733
+ ...lastDays(f.week, project.calls + f.redirected),
29734
+ // D-STATS-FIX-1 (5): one DB per project holds every session of it, so project and all-time are one row.
29735
+ "By scope",
29736
+ ...table2("Scope", [{ name: "session", ...session }, { name: "project (all-time)", ...project }]),
29258
29737
  "",
29259
- "Where the savings came from (this project)",
29738
+ "By tool (this project)",
29260
29739
  ...table2("Tool", toolRows(f.tools)),
29261
- ""
29740
+ "",
29741
+ ...f.top.length > 0 ? [
29742
+ "Largest single outputs (made \u2192 sent to the chat)",
29743
+ ...f.top.map((t) => " " + label(toolName(t.name)) + bytes4(t.produced).padStart(NUM_W) + " \u2192 " + bytes4(t.returned).padStart(NUM_W)),
29744
+ ""
29745
+ ] : []
29262
29746
  ];
29263
29747
  const agents = /* @__PURE__ */ new Map();
29264
29748
  for (const g of f.groups) agents.set(g.agent, sum([agents.get(g.agent) ?? EMPTY5, g]));
29265
29749
  if (!agents.has(agent)) agents.set(agent, EMPTY5);
29266
- lines.push(...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29750
+ lines.push("By agent (this project)", ...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29267
29751
  const maxKind = Math.max(0, ...[...f.kinds.values()].map((k) => k.project));
29268
29752
  lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + "Session".padStart(STATS_KIND_W) + "Project".padStart(STATS_KIND_W));
29269
29753
  for (const [kind, name] of STATS_KIND_LABELS) {
@@ -29272,9 +29756,12 @@ function report(f, sessionId, agent) {
29272
29756
  }
29273
29757
  lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
29274
29758
  lines.push(
29275
- " " + "Indexed sources".padEnd(LABEL_W) + `${int2(f.sources.count)} \xB7 ${plural(f.sources.chunks, "chunk")} \xB7 ${bytes4(f.sources.bytes)} of content`,
29759
+ " " + "Index and search".padEnd(LABEL_W) + `${plural(f.sources.count, "source")} \xB7 ${plural(f.sources.chunks, "chunk")} \xB7 ${bytes4(f.sources.bytes)} \xB7 ${plural(f.tools.find((t) => t.name === "ctx_search")?.calls ?? 0, "ctx_search call")}`,
29276
29760
  " " + "Database file".padEnd(LABEL_W) + bytes4(f.dbBytes),
29277
- " " + "Sessions".padEnd(LABEL_W) + `${int2(f.sessions)} \xB7 agents ${int2(f.agents)} \xB7 active days ${int2(f.days)}`
29761
+ " " + "Sessions".padEnd(LABEL_W) + `${int2(f.sessions)} \xB7 agents ${int2(f.agents)} \xB7 active days ${int2(f.days)}`,
29762
+ "",
29763
+ STATS_FOOTER_URL,
29764
+ "github.com/" + ISSUE_REPO_SLUG
29278
29765
  );
29279
29766
  return lines.map(fit).join("\n");
29280
29767
  }
@@ -29312,28 +29799,28 @@ var ctxStats = Object.freeze({
29312
29799
  });
29313
29800
 
29314
29801
  // src/core/tools/upgrade.ts
29315
- import { existsSync as existsSync20, realpathSync as realpathSync9, rmSync as rmSync9 } from "node:fs";
29316
- import { basename as basename6, dirname as dirname11, join as join23 } from "node:path";
29802
+ import { existsSync as existsSync21, realpathSync as realpathSync10, rmSync as rmSync9 } from "node:fs";
29803
+ import { basename as basename6, dirname as dirname11, join as join24 } from "node:path";
29317
29804
 
29318
29805
  // src/core/ops/host-write.ts
29319
- import { copyFileSync, existsSync as existsSync15, mkdirSync as mkdirSync5, writeFileSync as writeFileSync4 } from "node:fs";
29320
- import { dirname as dirname10, join as join18 } from "node:path";
29806
+ import { copyFileSync, existsSync as existsSync16, mkdirSync as mkdirSync6, writeFileSync as writeFileSync5 } from "node:fs";
29807
+ import { dirname as dirname10, join as join19 } from "node:path";
29321
29808
  function defaultWrite(file2, text) {
29322
- writeFileSync4(file2, text, "utf8");
29809
+ writeFileSync5(file2, text, "utf8");
29323
29810
  }
29324
29811
  function hostConfigPath(agent, home, env) {
29325
29812
  const own4 = OWN_MCP_ENTRY[agent];
29326
29813
  if (own4 !== void 0) return ownMcpFileOf(agent, own4.file, env, home);
29327
29814
  switch (agent) {
29328
29815
  case "opencode":
29329
- return join18(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29816
+ return join19(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29330
29817
  // D-WIN-OPENCODE-DIR-1
29331
29818
  case "pi":
29332
- return join18(piAgentDirOf(env, home), SETTINGS_FILE);
29819
+ return join19(piAgentDirOf(env, home), SETTINGS_FILE);
29333
29820
  case "copilot-cli":
29334
29821
  return null;
29335
29822
  default:
29336
- return join18(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29823
+ return join19(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29337
29824
  }
29338
29825
  }
29339
29826
  function cell3(value) {
@@ -29345,8 +29832,8 @@ function toRow(file2, edit) {
29345
29832
  function writeWithRollback(file2, text, write2, atomic) {
29346
29833
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
29347
29834
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
29348
- const had = existsSync15(file2);
29349
- mkdirSync5(dirname10(file2), { recursive: true });
29835
+ const had = existsSync16(file2);
29836
+ mkdirSync6(dirname10(file2), { recursive: true });
29350
29837
  if (had) copyFileSync(file2, trash);
29351
29838
  try {
29352
29839
  write2(tmp, text);
@@ -29375,7 +29862,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
29375
29862
  if (requested === null) return [];
29376
29863
  const current = readHostConfig(row5.id, requested);
29377
29864
  const result = mergeOwnEntries(row5.id, current.text, current.format, row5);
29378
- const exists = existsSync15(current.path);
29865
+ const exists = existsSync16(current.path);
29379
29866
  if (exists && result.text === current.text) return [];
29380
29867
  const text = result.text === "" && current.format !== "toml" ? JSON.stringify({}) : result.text;
29381
29868
  writeWithRollback(current.path, current.layout === void 0 ? text : withLayout(text, current.layout), opts.write ?? defaultWrite, opts.atomic ?? {});
@@ -29383,8 +29870,8 @@ function regenerateHostConfig(row5, home, opts = {}) {
29383
29870
  }
29384
29871
 
29385
29872
  // src/core/ops/plugin-swap.ts
29386
- import { existsSync as existsSync16, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
29387
- import { basename as basename5, join as join19, win32 as win322 } from "node:path";
29873
+ import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
29874
+ import { basename as basename5, join as join20, win32 as win322 } from "node:path";
29388
29875
  function linkTarget(path7, win) {
29389
29876
  if (!isLink(path7)) return null;
29390
29877
  const target = readlinkSync(path7);
@@ -29403,11 +29890,11 @@ function settleLinks(link, tmp, old, opts) {
29403
29890
  else renameWithRetry(old, link, opts);
29404
29891
  }
29405
29892
  function swapPluginCurrent(agentDir, sha, opts = {}) {
29406
- const next = join19(agentDir, sha);
29407
- if (!existsSync16(next) || !lstatSync(next).isDirectory()) {
29893
+ const next = join20(agentDir, sha);
29894
+ if (!existsSync17(next) || !lstatSync(next).isDirectory()) {
29408
29895
  throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
29409
29896
  }
29410
- const link = join19(agentDir, PLUGIN_CURRENT_LINK);
29897
+ const link = join20(agentDir, PLUGIN_CURRENT_LINK);
29411
29898
  const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
29412
29899
  const old = link + PLUGIN_LINK_OLD_SUFFIX;
29413
29900
  settleLinks(link, tmp, old, opts);
@@ -29422,15 +29909,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
29422
29909
  if (before !== null) unlinkSync2(old);
29423
29910
  const keep = /* @__PURE__ */ new Set([sha]);
29424
29911
  if (before !== null) keep.add(before);
29425
- const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join19(agentDir, name));
29912
+ const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join20(agentDir, name));
29426
29913
  for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
29427
- const previous = before !== null && existsSync16(join19(agentDir, before)) ? join19(agentDir, before) : null;
29914
+ const previous = before !== null && existsSync17(join20(agentDir, before)) ? join20(agentDir, before) : null;
29428
29915
  return { current: next, previous, removed };
29429
29916
  }
29430
29917
 
29431
29918
  // src/core/ops/release-fetch.ts
29432
- import { existsSync as existsSync17, mkdirSync as mkdirSync6, rmSync as rmSync6 } from "node:fs";
29433
- import { join as join20 } from "node:path";
29919
+ import { existsSync as existsSync18, mkdirSync as mkdirSync7, rmSync as rmSync6 } from "node:fs";
29920
+ import { join as join21 } from "node:path";
29434
29921
  function failed(r) {
29435
29922
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
29436
29923
  const status = r.killed ?? String(r.exitCode);
@@ -29442,9 +29929,9 @@ async function git2(bin, args, cwd, env, signal) {
29442
29929
  return r.stdout.toString().trim();
29443
29930
  }
29444
29931
  async function fetchRelease(agent, url4, env, signal, opts = {}) {
29445
- const agentDir = join20(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
29446
- mkdirSync6(agentDir, { recursive: true });
29447
- const fetchDir = join20(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29932
+ const agentDir = join21(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
29933
+ mkdirSync7(agentDir, { recursive: true });
29934
+ const fetchDir = join21(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29448
29935
  rmSync6(fetchDir, { recursive: true, force: true });
29449
29936
  const gitBin = findRuntime(GIT_BIN, env);
29450
29937
  if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -29452,8 +29939,8 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
29452
29939
  try {
29453
29940
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url4, fetchDir], agentDir, childEnv, signal);
29454
29941
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
29455
- const dir = join20(agentDir, sha);
29456
- if (existsSync17(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29942
+ const dir = join21(agentDir, sha);
29943
+ if (existsSync18(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29457
29944
  else renameWithRetry(fetchDir, dir, opts);
29458
29945
  return { sha, dir };
29459
29946
  } catch (e) {
@@ -29463,15 +29950,15 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
29463
29950
  }
29464
29951
 
29465
29952
  // src/core/ops/uninstall.ts
29466
- import { existsSync as existsSync18, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "node:fs";
29467
- import { join as join21 } from "node:path";
29953
+ import { existsSync as existsSync19, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
29954
+ import { join as join22 } from "node:path";
29468
29955
  function row2(area, before, after) {
29469
29956
  return { area, before, after };
29470
29957
  }
29471
29958
  function stopServers(configDir, projectKey) {
29472
29959
  const stopped = listLiveOwners(configDir, projectKey);
29473
- const dir = join21(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
29474
- for (const serverId of stopped) writeFileSync5(join21(dir, serverId + OWNER_STOP_EXT), "", "utf8");
29960
+ const dir = join22(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
29961
+ for (const serverId of stopped) writeFileSync6(join22(dir, serverId + OWNER_STOP_EXT), "", "utf8");
29475
29962
  return stopped.length === 0 ? { row: row2(UPGRADE_SERVER_AREA, "", UPGRADE_NOT_FOUND), stopped } : { row: row2(UPGRADE_SERVER_AREA, UPGRADE_SERVER_RUNNING, UPGRADE_SERVER_STOPPED), stopped };
29476
29963
  }
29477
29964
  function rootOrNull(adapter, env) {
@@ -29489,15 +29976,15 @@ function removeCache(adapter, env, configDir) {
29489
29976
  const root = rootOrNull(adapter, env);
29490
29977
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29491
29978
  if (adapter.installMode === "marketplace") {
29492
- const cache = join21(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
29979
+ const cache = join22(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
29493
29980
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
29494
29981
  }
29495
29982
  rmSync7(root, { recursive: true, force: true });
29496
29983
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
29497
29984
  }
29498
29985
  case "plugin": {
29499
- const agentDir = join21(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
29500
- if (!existsSync18(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29986
+ const agentDir = join22(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
29987
+ if (!existsSync19(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29501
29988
  rmSync7(agentDir, { recursive: true, force: true });
29502
29989
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
29503
29990
  }
@@ -29542,7 +30029,7 @@ function ownEntries(agent, env) {
29542
30029
  }
29543
30030
  if (agent === "opencode") {
29544
30031
  return [{
29545
- file: join21(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
30032
+ file: join22(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
29546
30033
  // D-WIN-OPENCODE-DIR-1
29547
30034
  key: OPENCODE_PLUGIN_KEY,
29548
30035
  shown: OPENCODE_PLUGIN_KEY,
@@ -29553,7 +30040,7 @@ function ownEntries(agent, env) {
29553
30040
  if (agent === "pi") {
29554
30041
  const agentDir = piAgentDirOf(env, home);
29555
30042
  return [{
29556
- file: join21(agentDir, SETTINGS_FILE),
30043
+ file: join22(agentDir, SETTINGS_FILE),
29557
30044
  key: PI_PACKAGES_KEY,
29558
30045
  shown: PI_PACKAGES_KEY,
29559
30046
  has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
@@ -29575,12 +30062,12 @@ function removeOwnEntries(agent, env) {
29575
30062
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
29576
30063
  }
29577
30064
  function removeProjectData(configDir, projectKey) {
29578
- const projects = join21(configDir, PROJECTS_DIR_NAME);
29579
- const dir = join21(projects, projectKey);
29580
- if (!existsSync18(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
30065
+ const projects = join22(configDir, PROJECTS_DIR_NAME);
30066
+ const dir = join22(projects, projectKey);
30067
+ if (!existsSync19(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
29581
30068
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
29582
30069
  for (const name of readdirSync8(dir)) {
29583
- if (name !== OWNERS_DIR_NAME) rmSync7(join21(dir, name), { recursive: true, force: true });
30070
+ if (name !== OWNERS_DIR_NAME) rmSync7(join22(dir, name), { recursive: true, force: true });
29584
30071
  }
29585
30072
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
29586
30073
  }
@@ -29588,12 +30075,12 @@ function runUninstall(input) {
29588
30075
  const configDir = resolveConfigDir(input.env);
29589
30076
  const stop = stopServers(configDir, input.project.projectKey);
29590
30077
  const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
29591
- rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join21(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
30078
+ rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join22(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
29592
30079
  return { rows, stopped: stop.stopped };
29593
30080
  }
29594
30081
 
29595
30082
  // src/core/ops/v1-remove.ts
29596
- import { copyFileSync as copyFileSync2, existsSync as existsSync19, readFileSync as readFileSync15, rmSync as rmSync8 } from "node:fs";
30083
+ import { copyFileSync as copyFileSync2, existsSync as existsSync20, readFileSync as readFileSync16, rmSync as rmSync8 } from "node:fs";
29597
30084
  var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
29598
30085
  var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
29599
30086
  var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
@@ -29637,8 +30124,8 @@ function locate(doc, path7) {
29637
30124
  return null;
29638
30125
  }
29639
30126
  function stripJsonEntries(agent, file2, findings, kept, undo) {
29640
- const layout = hostLayout(readFileSync15(file2, "utf8"));
29641
- const text = hostText(readFileSync15(file2, "utf8"));
30127
+ const layout = hostLayout(readFileSync16(file2, "utf8"));
30128
+ const text = hostText(readFileSync16(file2, "utf8"));
29642
30129
  const doc = parseHostConfig(agent, file2, text, "jsonc");
29643
30130
  const hit = /* @__PURE__ */ new Set();
29644
30131
  const byContainer = /* @__PURE__ */ new Map();
@@ -29674,19 +30161,19 @@ function removeV1(agent, findings) {
29674
30161
  for (const f of findings) {
29675
30162
  if (UPGRADE_REPORT_ONLY_REASONS.includes(f.reason)) done.set(f, UPGRADE_REPORT_ONLY);
29676
30163
  else if (f.path === "") {
29677
- if (existsSync19(f.file)) {
30164
+ if (existsSync20(f.file)) {
29678
30165
  moveAside(f.file, undo);
29679
30166
  done.set(f, UPGRADE_REMOVED);
29680
30167
  } else done.set(f, UPGRADE_NOT_FOUND);
29681
30168
  } else entries.set(f.file, [...entries.get(f.file) ?? [], f]);
29682
30169
  }
29683
30170
  for (const [file2, list4] of entries) {
29684
- if (!existsSync19(file2)) {
30171
+ if (!existsSync20(file2)) {
29685
30172
  for (const f of list4) done.set(f, UPGRADE_NOT_FOUND);
29686
30173
  continue;
29687
30174
  }
29688
30175
  if (file2.endsWith(TOML_EXT)) {
29689
- const rawToml = readFileSync15(file2, "utf8");
30176
+ const rawToml = readFileSync16(file2, "utf8");
29690
30177
  const tomlLayout = hostLayout(rawToml);
29691
30178
  let text = hostText(rawToml);
29692
30179
  for (const f of list4) {
@@ -29714,7 +30201,7 @@ function removeV1(agent, findings) {
29714
30201
  },
29715
30202
  rollback() {
29716
30203
  for (const u of undo.splice(0).reverse()) {
29717
- if (!existsSync19(u.trash)) continue;
30204
+ if (!existsSync20(u.trash)) continue;
29718
30205
  rmSync8(u.target, { recursive: true, force: true });
29719
30206
  renameWithRetry(u.trash, u.target);
29720
30207
  }
@@ -29724,8 +30211,8 @@ function removeV1(agent, findings) {
29724
30211
 
29725
30212
  // src/core/ops/verify-sums.ts
29726
30213
  import { createHash as createHash2 } from "node:crypto";
29727
- import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync16 } from "node:fs";
29728
- import { join as join22 } from "node:path";
30214
+ import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "node:fs";
30215
+ import { join as join23 } from "node:path";
29729
30216
  function mismatch() {
29730
30217
  return new CtxError("BUNDLE_HASH_MISMATCH");
29731
30218
  }
@@ -29746,24 +30233,24 @@ function walk3(dir, prefix, out) {
29746
30233
  for (const entry of readdirSync9(dir, { withFileTypes: true })) {
29747
30234
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
29748
30235
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
29749
- const abs = join22(dir, entry.name);
30236
+ const abs = join23(dir, entry.name);
29750
30237
  if (entry.isDirectory()) walk3(abs, rel, out);
29751
30238
  else if (entry.isFile()) out.set(rel, abs);
29752
30239
  else throw mismatch();
29753
30240
  }
29754
30241
  }
29755
30242
  function verifySums(dir) {
29756
- const sumsPath = join22(dir, RELEASE_SUMS_FILE);
30243
+ const sumsPath = join23(dir, RELEASE_SUMS_FILE);
29757
30244
  const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
29758
30245
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
29759
- const sums = parseSums(readFileSync16(sumsPath, "utf8"));
30246
+ const sums = parseSums(readFileSync17(sumsPath, "utf8"));
29760
30247
  const files = /* @__PURE__ */ new Map();
29761
30248
  walk3(dir, "", files);
29762
30249
  if (files.size !== sums.size) throw mismatch();
29763
30250
  for (const [rel, abs] of files) {
29764
30251
  const want = sums.get(rel);
29765
30252
  if (want === void 0) throw mismatch();
29766
- const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync16(abs)).digest(HASH_ENCODING);
30253
+ const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync17(abs)).digest(HASH_ENCODING);
29767
30254
  if (got !== want) throw mismatch();
29768
30255
  }
29769
30256
  }
@@ -29791,8 +30278,8 @@ function pluginRootRow(adapter, env) {
29791
30278
  return root === own4 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own4)];
29792
30279
  }
29793
30280
  function isCurrent(agentDir, dir) {
29794
- const link = join23(agentDir, PLUGIN_CURRENT_LINK);
29795
- return existsSync20(link) && realpathSync9.native(link) === realpathSync9.native(dir);
30281
+ const link = join24(agentDir, PLUGIN_CURRENT_LINK);
30282
+ return existsSync21(link) && realpathSync10.native(link) === realpathSync10.native(dir);
29796
30283
  }
29797
30284
  async function checkout(adapter, deps) {
29798
30285
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);
@@ -29912,8 +30399,8 @@ function checkCall(tool, input) {
29912
30399
 
29913
30400
  // src/entries/server.ts
29914
30401
  import { randomUUID } from "node:crypto";
29915
- import { existsSync as existsSync22, realpathSync as realpathSync11, rmSync as rmSync11 } from "node:fs";
29916
- import { dirname as dirname12, join as join25 } from "node:path";
30402
+ import { existsSync as existsSync23, realpathSync as realpathSync12, rmSync as rmSync11 } from "node:fs";
30403
+ import { dirname as dirname12, join as join26 } from "node:path";
29917
30404
  import { fileURLToPath as fileURLToPath2 } from "node:url";
29918
30405
 
29919
30406
  // node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
@@ -33392,17 +33879,17 @@ var recursive = /* @__PURE__ */ new WeakMap();
33392
33879
  var NONE3 = 0;
33393
33880
  var ASSUMED = 1;
33394
33881
  var PROVEN = 2;
33395
- function isRecursive(inst, stack, resolve8) {
33882
+ function isRecursive(inst, stack2, resolve8) {
33396
33883
  const cached4 = recursive.get(inst);
33397
33884
  if (cached4 !== void 0)
33398
33885
  return cached4 ? PROVEN : NONE3;
33399
- if (stack.has(inst))
33886
+ if (stack2.has(inst))
33400
33887
  return PROVEN;
33401
- stack.add(inst);
33888
+ stack2.add(inst);
33402
33889
  let result = NONE3;
33403
33890
  const check2 = (child) => {
33404
33891
  if (result !== PROVEN && child?._zod) {
33405
- const answer2 = isRecursive(child, stack, resolve8);
33892
+ const answer2 = isRecursive(child, stack2, resolve8);
33406
33893
  if (answer2 > result)
33407
33894
  result = answer2;
33408
33895
  }
@@ -33413,7 +33900,7 @@ function isRecursive(inst, stack, resolve8) {
33413
33900
  const desc = Object.getOwnPropertyDescriptor(sh, key);
33414
33901
  if (spread && !desc.enumerable)
33415
33902
  continue;
33416
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve8) : NONE3;
33903
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack2, resolve8) : NONE3;
33417
33904
  if (child > answer2)
33418
33905
  answer2 = child;
33419
33906
  }
@@ -33478,7 +33965,7 @@ function isRecursive(inst, stack, resolve8) {
33478
33965
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
33479
33966
  case "lazy": {
33480
33967
  const inner = def._cachedInner ?? (resolve8 ? inst._zod.innerType : void 0);
33481
- merge5(inner ? isRecursive(inner, stack, false) : ASSUMED);
33968
+ merge5(inner ? isRecursive(inner, stack2, false) : ASSUMED);
33482
33969
  break;
33483
33970
  }
33484
33971
  // a leaf by choice: `parts` are regex fragments, not data positions
@@ -33521,7 +34008,7 @@ function isRecursive(inst, stack, resolve8) {
33521
34008
  }
33522
34009
  }
33523
34010
  }
33524
- stack.delete(inst);
34011
+ stack2.delete(inst);
33525
34012
  return settle(inst, result);
33526
34013
  }
33527
34014
  function settle(inst, answer2) {
@@ -40921,17 +41408,17 @@ var recursive2 = /* @__PURE__ */ new WeakMap();
40921
41408
  var NONE4 = 0;
40922
41409
  var ASSUMED2 = 1;
40923
41410
  var PROVEN2 = 2;
40924
- function isRecursive2(inst, stack, resolve8) {
41411
+ function isRecursive2(inst, stack2, resolve8) {
40925
41412
  const cached4 = recursive2.get(inst);
40926
41413
  if (cached4 !== void 0)
40927
41414
  return cached4 ? PROVEN2 : NONE4;
40928
- if (stack.has(inst))
41415
+ if (stack2.has(inst))
40929
41416
  return PROVEN2;
40930
- stack.add(inst);
41417
+ stack2.add(inst);
40931
41418
  let result = NONE4;
40932
41419
  const check2 = (child) => {
40933
41420
  if (result !== PROVEN2 && child?._zod) {
40934
- const answer2 = isRecursive2(child, stack, resolve8);
41421
+ const answer2 = isRecursive2(child, stack2, resolve8);
40935
41422
  if (answer2 > result)
40936
41423
  result = answer2;
40937
41424
  }
@@ -40942,7 +41429,7 @@ function isRecursive2(inst, stack, resolve8) {
40942
41429
  const desc = Object.getOwnPropertyDescriptor(sh, key);
40943
41430
  if (spread && !desc.enumerable)
40944
41431
  continue;
40945
- const child = desc.get ? ASSUMED2 : desc.value?._zod ? isRecursive2(desc.value, stack, resolve8) : NONE4;
41432
+ const child = desc.get ? ASSUMED2 : desc.value?._zod ? isRecursive2(desc.value, stack2, resolve8) : NONE4;
40946
41433
  if (child > answer2)
40947
41434
  answer2 = child;
40948
41435
  }
@@ -41007,7 +41494,7 @@ function isRecursive2(inst, stack, resolve8) {
41007
41494
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
41008
41495
  case "lazy": {
41009
41496
  const inner = def._cachedInner ?? (resolve8 ? inst._zod.innerType : void 0);
41010
- merge5(inner ? isRecursive2(inner, stack, false) : ASSUMED2);
41497
+ merge5(inner ? isRecursive2(inner, stack2, false) : ASSUMED2);
41011
41498
  break;
41012
41499
  }
41013
41500
  // a leaf by choice: `parts` are regex fragments, not data positions
@@ -41050,7 +41537,7 @@ function isRecursive2(inst, stack, resolve8) {
41050
41537
  }
41051
41538
  }
41052
41539
  }
41053
- stack.delete(inst);
41540
+ stack2.delete(inst);
41054
41541
  return settle2(inst, result);
41055
41542
  }
41056
41543
  function settle2(inst, answer2) {
@@ -56814,19 +57301,19 @@ function discoverAdvertisedCapabilities(capabilities) {
56814
57301
  }
56815
57302
  function toolInputElementCount(value, max) {
56816
57303
  let count2 = 0;
56817
- const stack = [value];
56818
- while (stack.length > 0) {
56819
- const node3 = stack.pop();
57304
+ const stack2 = [value];
57305
+ while (stack2.length > 0) {
57306
+ const node3 = stack2.pop();
56820
57307
  if (node3 === null || typeof node3 !== "object") continue;
56821
57308
  if (Array.isArray(node3)) for (const child of node3) {
56822
57309
  if (++count2 > max) return count2;
56823
- if (child !== null && typeof child === "object") stack.push(child);
57310
+ if (child !== null && typeof child === "object") stack2.push(child);
56824
57311
  }
56825
57312
  else for (const key in node3) {
56826
57313
  if (!Object.prototype.hasOwnProperty.call(node3, key)) continue;
56827
57314
  if (++count2 > max) return count2;
56828
57315
  const child = node3[key];
56829
- if (child !== null && typeof child === "object") stack.push(child);
57316
+ if (child !== null && typeof child === "object") stack2.push(child);
56830
57317
  }
56831
57318
  }
56832
57319
  return count2;
@@ -56902,9 +57389,9 @@ var McpServer = class {
56902
57389
  resolveScopeChallenge = (context) => {
56903
57390
  switch (context.request.method) {
56904
57391
  case "tools/call": {
56905
- const toolName = context.request.params?.name;
56906
- if (typeof toolName !== "string") return;
56907
- const tool = this._registeredTools[toolName];
57392
+ const toolName2 = context.request.params?.name;
57393
+ if (typeof toolName2 !== "string") return;
57394
+ const tool = this._registeredTools[toolName2];
56908
57395
  if (tool === void 0 || !tool.enabled) return;
56909
57396
  return tool.scopeChallenge?.(context);
56910
57397
  }
@@ -56988,23 +57475,23 @@ var McpServer = class {
56988
57475
  /**
56989
57476
  * Validates tool input arguments against the tool's input schema.
56990
57477
  */
56991
- async validateToolInput(tool, args, toolName) {
56992
- if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
57478
+ async validateToolInput(tool, args, toolName2) {
57479
+ if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for tool ${toolName2}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
56993
57480
  if (!tool.inputSchema) return;
56994
57481
  const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {});
56995
- if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`);
57482
+ if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName2}: ${parseResult.error}`);
56996
57483
  return parseResult.data;
56997
57484
  }
56998
57485
  /**
56999
57486
  * Validates tool output against the tool's output schema.
57000
57487
  */
57001
- async validateToolOutput(tool, result, toolName) {
57488
+ async validateToolOutput(tool, result, toolName2) {
57002
57489
  if (!tool.outputSchema) return;
57003
57490
  if (isInputRequiredResult(result)) return;
57004
57491
  if (result.isError) return;
57005
- if (result.structuredContent === void 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
57492
+ if (result.structuredContent === void 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName2} has an output schema but no structured content was provided`);
57006
57493
  const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent);
57007
- if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`);
57494
+ if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName2}: ${parseResult.error}`);
57008
57495
  }
57009
57496
  /**
57010
57497
  * Executes a tool handler.
@@ -57978,8 +58465,8 @@ function installExitGuard(opts) {
57978
58465
  }
57979
58466
 
57980
58467
  // src/core/store/cleanup.ts
57981
- import { existsSync as existsSync21, readdirSync as readdirSync10, rmSync as rmSync10 } from "node:fs";
57982
- import { join as join24 } from "node:path";
58468
+ import { existsSync as existsSync22, readdirSync as readdirSync10, rmSync as rmSync10 } from "node:fs";
58469
+ import { join as join25 } from "node:path";
57983
58470
  function deleteSource(raw, id) {
57984
58471
  raw.prepare("DELETE FROM sources WHERE id = ?").run(id);
57985
58472
  deleteChunkRows(raw, { sourceId: id });
@@ -58014,7 +58501,7 @@ function userVersion(raw) {
58014
58501
  return raw.prepare("PRAGMA user_version").get().user_version;
58015
58502
  }
58016
58503
  function openForSweep(dbPath, projectKey) {
58017
- if (!existsSync21(dbPath) && (existsSync21(dbPath + DB_WAL_SUFFIX) || existsSync21(dbPath + DB_SHM_SUFFIX))) {
58504
+ if (!existsSync22(dbPath) && (existsSync22(dbPath + DB_WAL_SUFFIX) || existsSync22(dbPath + DB_SHM_SUFFIX))) {
58018
58505
  throw new CtxError("DB_GONE");
58019
58506
  }
58020
58507
  const sqlite = process.getBuiltinModule("node:sqlite");
@@ -58035,8 +58522,8 @@ function lastAccess(raw) {
58035
58522
  return row5.t;
58036
58523
  }
58037
58524
  function sweepOne(configDir, projectKey, cutoff) {
58038
- const dir = join24(configDir, PROJECTS_DIR_NAME, projectKey);
58039
- const db = openForSweep(join24(dir, DB_FILE_NAME), projectKey);
58525
+ const dir = join25(configDir, PROJECTS_DIR_NAME, projectKey);
58526
+ const db = openForSweep(join25(dir, DB_FILE_NAME), projectKey);
58040
58527
  let dead;
58041
58528
  try {
58042
58529
  dead = withWrite(db, (h) => listLiveOwners(configDir, projectKey).length === 0 && lastAccess(h.raw) < cutoff);
@@ -58049,7 +58536,7 @@ function sweepOne(configDir, projectKey, cutoff) {
58049
58536
  function sweepDeadProjects(configDir) {
58050
58537
  let entries;
58051
58538
  try {
58052
- entries = readdirSync10(join24(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
58539
+ entries = readdirSync10(join25(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
58053
58540
  } catch (err) {
58054
58541
  if (err.code === "ENOENT") return [];
58055
58542
  throw err;
@@ -58068,12 +58555,12 @@ function sweepDeadProjects(configDir) {
58068
58555
  }
58069
58556
 
58070
58557
  // src/entries/is-entry.ts
58071
- import { realpathSync as realpathSync10 } from "node:fs";
58558
+ import { realpathSync as realpathSync11 } from "node:fs";
58072
58559
  function isEntry(main, argv1, self) {
58073
58560
  if (main !== void 0) return main;
58074
58561
  if (argv1 === void 0 || argv1 === "") return false;
58075
58562
  try {
58076
- return realpathSync10(argv1) === realpathSync10(self);
58563
+ return realpathSync11(argv1) === realpathSync11(self);
58077
58564
  } catch {
58078
58565
  return false;
58079
58566
  }
@@ -58149,7 +58636,7 @@ function workspaceFromMeta(meta3) {
58149
58636
  }
58150
58637
  function realOrSame(p) {
58151
58638
  try {
58152
- return realpathSync11.native(p);
58639
+ return realpathSync12.native(p);
58153
58640
  } catch {
58154
58641
  return p;
58155
58642
  }
@@ -58197,15 +58684,15 @@ async function startServer(argv, env) {
58197
58684
  opening.catch(() => pending.delete(project.dbPath));
58198
58685
  }
58199
58686
  const db = await opening;
58200
- if (!existsSync22(db.path)) throw new CtxError("DB_GONE");
58687
+ if (!existsSync23(db.path)) throw new CtxError("DB_GONE");
58201
58688
  return db;
58202
58689
  }
58203
58690
  function stopMarker(configDir, projectKey) {
58204
- return join25(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
58691
+ return join26(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
58205
58692
  }
58206
58693
  function stopRequested() {
58207
58694
  const configDir = resolveConfigDir(process.env);
58208
- return held.some((db) => existsSync22(stopMarker(configDir, db.projectKey)));
58695
+ return held.some((db) => existsSync23(stopMarker(configDir, db.projectKey)));
58209
58696
  }
58210
58697
  async function journal(project, ctx, name, reply4) {
58211
58698
  const db = await ownDb(project);