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.
@@ -209,6 +209,7 @@ var SOURCE_LABEL_MAX_CHARS = 80;
209
209
  var CANCELLED_LINE = "Cancelled.";
210
210
  var BACKGROUND_REPLY_PREFIX = "started in background, pid ";
211
211
  var PLAIN_OUTPUT_ENV = Object.freeze({ NO_COLOR: "1", FORCE_COLOR: "0" });
212
+ var RUN_LABEL_PREFIX = "run.mjs:";
212
213
  var HOST_SESSION_ENV = Object.freeze({ "claude-code": "CLAUDE_CODE_SESSION_ID" });
213
214
  var NODE_MIN = "24.15.0";
214
215
  var DATA_ROOT = "~/.context-mode";
@@ -381,17 +382,34 @@ var STATS_EMPTY_LINES = Object.freeze([
381
382
  "sandbox, and only the short answer goes to the chat."
382
383
  ]);
383
384
  var STATS_KIND_LABELS = Object.freeze([
384
- ["cmd", "Tool runs"],
385
+ // D-STATS-FIX-1 (8): the first five rows are call kinds, so they add up to the calls of the scope line.
385
386
  ["index", "Content indexed"],
386
387
  ["edit", "File edits"],
387
- ["toolerr", "Errors kept"],
388
+ ["toolerr", "Issues kept"],
388
389
  ["decision", "Your decisions"],
390
+ ["cmd", "Other tool calls"],
389
391
  ["prompt", "Your prompts"]
390
392
  ]);
391
393
  var STATS_JOURNAL_HINTS = Object.freeze([
392
- "ctx_resume brings back your last task, files changed and open errors",
394
+ "ctx_resume brings back your last task, files changed and open issues",
393
395
  "after a compact or a restart; ctx_search finds indexed content by words."
394
396
  ]);
397
+ var STATS_WINDOW_TOKENS = 2e5;
398
+ var STATS_THOUSAND = 1e3;
399
+ var STATS_WHOLE_FROM = 10;
400
+ var STATS_DAYS = 7;
401
+ var STATS_TOP_OUTPUTS = 3;
402
+ var STATS_CARD_W = 19;
403
+ var STATS_DAY_BAR = 48;
404
+ var STATS_TOKEN_NOTE = " (at 4 bytes per token; a Claude context window is 200K tokens)";
405
+ var STATS_WAYS = Object.freeze([
406
+ ["sandbox", "\u2588", "sandbox run"],
407
+ ["index", "\u2593", "index + search"],
408
+ ["redirect", "\u2592", "hook sent to sandbox"],
409
+ ["replace", "\u2591", "hook cut down"]
410
+ ]);
411
+ var STATS_INDEX_TOOLS = Object.freeze(["ctx_index", "ctx_search"]);
412
+ var STATS_FOOTER_URL = "https://contextmode.ai/?utm_source=ctx_stats&utm_medium=stats&utm_content=footer";
395
413
  var PURGE_SCOPES = Object.freeze(["session", "source", "project"]);
396
414
  var PURGE_NO_SCOPE_LINE = "ctx_purge: pick one scope \u2014 session, source, or project.";
397
415
  var PURGE_MANY_SCOPES_LINE = "ctx_purge: pick only one scope \u2014 session, source, or project.";
@@ -407,7 +425,7 @@ var DECISION_OPTION_KEY = "option";
407
425
  var DECISION_LABEL_JOIN = " | ";
408
426
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
409
427
  var RELEASE_BRANCH = "release";
410
- var BUNDLE_SHA = true ? "dd54e208f8debb1c4601659ee632ada9a3612e45" : void 0;
428
+ var BUNDLE_SHA = true ? "feb8de116956b3d3eff56c7d5ed2d840483d0cd4" : void 0;
411
429
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
412
430
  var DOCTOR_LABEL = Object.freeze({
413
431
  D1: "version",
@@ -437,7 +455,7 @@ function DOCTOR_FAIL_LINE(host, check2, cause, command) {
437
455
  return `FAIL ${host}: ${check2} \u2014 ${cause}. Fix: ${command}`;
438
456
  }
439
457
  var DOCTOR_FIX_UPGRADE = "run ctx_upgrade";
440
- var D1_DEV_BUILD_DETAIL = "dev build";
458
+ var D1_DEV_BUILD_DETAIL = "dev build: source checkout; release builds stamp the sha";
441
459
  var D1_UPDATE_DETAIL = "update available";
442
460
  var D1_SHORT_SHA_LEN = 7;
443
461
  var D1_PACKAGE_FILE = "package.json";
@@ -767,7 +785,7 @@ var V1_REASON = Object.freeze({
767
785
  dataDir: "old context-mode data dir <agent home>/context-mode/",
768
786
  dataDirShared: "old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",
769
787
  dataRoot: "old context-mode content under ~/.context-mode/",
770
- tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, no action needed"
788
+ tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep"
771
789
  });
772
790
  var UPGRADE_REPORT_ONLY_REASONS = Object.freeze([V1_REASON.statusLine, V1_REASON.vscodeMcp, V1_REASON.dataDirShared, V1_REASON.tmpFile, V1_REASON.kiroSteering]);
773
791
  var PLUGIN_ID = SERVER_KEY;
@@ -809,6 +827,85 @@ var REPORT_ENV_PREFIX = "env.";
809
827
  var REPORT_ENV_ENUMS = Object.freeze({
810
828
  NODE_ENV: Object.freeze(["development", "production", "test"])
811
829
  });
830
+ var DOCTOR_ENV_PREFIX = "Environment: ";
831
+ var DOCTOR_DOCS_URL = "https://contextmode.ai/docs/engine/doctor";
832
+ var DOCTOR_DOCS_ANCHOR = "checks";
833
+ function DOCTOR_DOCS_LINK(check2) {
834
+ return `${DOCTOR_DOCS_URL}?utm_source=ctx_doctor&utm_medium=doctor&utm_content=${check2}#${DOCTOR_DOCS_ANCHOR}`;
835
+ }
836
+ var DOCTOR_DOCS_LABEL = "Docs: ";
837
+ function D3_NO_SETUP_FIX(agent) {
838
+ return `context-mode setup --agents ${agent}`;
839
+ }
840
+ function D5_FIXTURE_FILE_ABSENT(file2) {
841
+ return `hook fixture ${file2} is absent: the round trip needs it`;
842
+ }
843
+ function D5_FIXTURE_PARSE(file2, cause) {
844
+ return `the hook fixture file ${file2} failed to parse: ${cause}`;
845
+ }
846
+ function D5_FIXTURE_AGENT_ABSENT(file2, keys) {
847
+ return `the hook fixture file ${file2} records payloads for ${keys.join(", ") || "zero agents"} only`;
848
+ }
849
+ var DOCTOR_REPORTS_DIR = "reports";
850
+ var DOCTOR_REPORT_FILE_PREFIX = "doctor-";
851
+ var DOCTOR_REPORT_LINE = "Report file: ";
852
+ var DOCTOR_GH_LINE = "File it: ";
853
+ var DOCTOR_URL_LINE = "Or open: ";
854
+ var DOCTOR_GH_NEXT = " --";
855
+ var DOCTOR_NOTE_PREFIXES = Object.freeze([
856
+ DOCTOR_ENV_PREFIX,
857
+ DOCTOR_DOCS_LABEL,
858
+ DOCTOR_REPORT_LINE,
859
+ DOCTOR_GH_LINE,
860
+ DOCTOR_GH_NEXT.trim(),
861
+ DOCTOR_URL_LINE
862
+ ]);
863
+ var ISSUE_REPO_SLUG = "mksglu/context-mode";
864
+ var ISSUE_FORM_FILE = "agent-report.yml";
865
+ var ISSUE_URL_MAX = 8e3;
866
+ var ISSUE_FORM_HEADINGS = Object.freeze([
867
+ "Summary",
868
+ "ctx-report",
869
+ "What happened",
870
+ "Hook errors",
871
+ "Journal rows",
872
+ "Agent config",
873
+ "Expected",
874
+ "Steps",
875
+ "Environment"
876
+ ]);
877
+ var DOCTOR_HOOK_LOG_LINES = 50;
878
+ var DOCTOR_JOURNAL_ROWS = 30;
879
+ var DOCTOR_CONFIG_LINES = 40;
880
+ var DOCTOR_ENV_NAMES = Object.freeze([
881
+ "CODEX_HOME",
882
+ "CLAUDE_CONFIG_DIR",
883
+ "CLAUDE_PLUGIN_ROOT",
884
+ "COPILOT_HOME",
885
+ "KIRO_HOME",
886
+ "OPENCODE_CONFIG_DIR",
887
+ "PI_CODING_AGENT_DIR",
888
+ "XDG_CONFIG_HOME",
889
+ "SHELL"
890
+ ]);
891
+ var DOCTOR_PATH_TOOLS = Object.freeze(["node", "git", "sh"]);
892
+ var DOCTOR_SECRET_WORDS = Object.freeze(["token", "secret", "password", "apikey", "api_key", "authorization", "bearer"]);
893
+ var DOCTOR_MASK = "<masked>";
894
+ var NATIVE_INSTALL = Object.freeze({
895
+ "claude-code": ["claude plugin marketplace add mksglu/context-mode#release", "claude plugin install context-mode@context-mode"],
896
+ codex: ["codex plugin marketplace add mksglu/context-mode@release", "codex plugin add context-mode@context-mode"],
897
+ gemini: ["gemini extensions install https://github.com/mksglu/context-mode --ref release"],
898
+ qwen: ["qwen extensions install https://github.com/mksglu/context-mode:context-mode --ref release"],
899
+ opencode: ["opencode plugin add context-mode@next"],
900
+ pi: ["pi install npm:context-mode@next"],
901
+ "copilot-cli": ["npm i -g context-mode@next", "context-mode setup --agents copilot-cli"],
902
+ vscode: ["npm i -g context-mode@next", "context-mode setup --agents vscode"],
903
+ kiro: ["npm i -g context-mode@next", "context-mode setup --agents kiro"],
904
+ zcode: ["npm i -g context-mode@next", "context-mode setup --agents zcode"]
905
+ });
906
+ var ISSUE_FORM_URL = `https://github.com/${ISSUE_REPO_SLUG}/issues/new?template=${ISSUE_FORM_FILE}`;
907
+ var DOCTOR_GIT_VERSION_TIMEOUT_MS = 5e3;
908
+ var DOCTOR_LOG_TAIL_BYTES = 262144;
812
909
 
813
910
  // src/core/contracts/errors.ts
814
911
  var ERROR_TEXT = Object.freeze({
@@ -1212,8 +1309,8 @@ function decode5(raw) {
1212
1309
  if (event === "SessionStart" && typeof raw.source === "string" && COPILOT_SOURCES[raw.source] !== void 0) ev.source = COPILOT_SOURCES[raw.source];
1213
1310
  if (event === "UserPromptSubmit" && typeof raw.prompt === "string") ev.prompt = raw.prompt;
1214
1311
  if (event === "PreToolUse" || event === "PostToolUse") {
1215
- const toolName = String(raw[k.tool] ?? "");
1216
- const tool = { name: toolName, canonicalName: canonicalName3(toolName), input: readArgs(raw[k.args]) };
1312
+ const toolName2 = String(raw[k.tool] ?? "");
1313
+ const tool = { name: toolName2, canonicalName: canonicalName3(toolName2), input: readArgs(raw[k.args]) };
1217
1314
  ev.tool = tool;
1218
1315
  }
1219
1316
  if (event === "PostToolUse") ev.result = readResult3(raw[k.result], native.casing, native.failure);
@@ -1327,9 +1424,9 @@ function decodeCamel(p, name) {
1327
1424
  if (event === "SessionStart" && typeof p.source === "string" && SESSION_SOURCES[p.source] !== void 0) ev.source = SESSION_SOURCES[p.source];
1328
1425
  if (event === "UserPromptSubmit" && typeof p.prompt === "string") ev.prompt = p.prompt;
1329
1426
  if (event === "PreToolUse" || event === "PostToolUse") {
1330
- const toolName = String(p.toolName ?? "");
1331
- const canonical = canonicalName4(toolName);
1332
- ev.tool = { name: toolName, canonicalName: canonical, input: policyInput(toolName, canonical, readArgs2(p.toolArgs)) };
1427
+ const toolName2 = String(p.toolName ?? "");
1428
+ const canonical = canonicalName4(toolName2);
1429
+ ev.tool = { name: toolName2, canonicalName: canonical, input: policyInput(toolName2, canonical, readArgs2(p.toolArgs)) };
1333
1430
  }
1334
1431
  if (event === "PostToolUse") ev.result = readCamelResult(p.toolResult);
1335
1432
  return ev;
@@ -2180,10 +2277,10 @@ function lexSpan(st, from, inParen, depth, out, bodies) {
2180
2277
  }
2181
2278
  function scan(cmd) {
2182
2279
  const st = { s: cmd, n: cmd.length, end: "complete" };
2183
- const tokens = [];
2280
+ const tokens2 = [];
2184
2281
  const heredocBodies = [];
2185
- lexSpan(st, 0, false, 0, tokens, heredocBodies);
2186
- return { tokens, heredocBodies, end: st.end };
2282
+ lexSpan(st, 0, false, 0, tokens2, heredocBodies);
2283
+ return { tokens: tokens2, heredocBodies, end: st.end };
2187
2284
  }
2188
2285
  function dequote(word) {
2189
2286
  let out = "";
@@ -3627,7 +3724,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
3627
3724
  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.',
3628
3725
  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.",
3629
3726
  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.",
3630
- 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.",
3727
+ 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",
3631
3728
  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.",
3632
3729
  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.'
3633
3730
  });
@@ -4140,8 +4237,8 @@ function firstLine(file2) {
4140
4237
  return line === "" ? null : line;
4141
4238
  }
4142
4239
  function git(dir, args) {
4143
- const { spawnSync: spawnSync3 } = process.getBuiltinModule("node:child_process");
4144
- const r = spawnSync3("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
4240
+ const { spawnSync: spawnSync4 } = process.getBuiltinModule("node:child_process");
4241
+ const r = spawnSync4("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
4145
4242
  if (r.error !== void 0 || r.status !== 0) throw new CtxError("NO_GIT_DIR", { path: dir });
4146
4243
  return r.stdout.split("\n").filter((l) => l !== "");
4147
4244
  }
@@ -6719,8 +6816,8 @@ function trigramMatch(q) {
6719
6816
  const words = blankTokens(q);
6720
6817
  const kept = words.filter((w) => !STOPWORDS.has(w.toLowerCase()));
6721
6818
  const parts = new Set((kept.length > 0 ? kept : words).filter((w) => [...w].length >= 3));
6722
- const whole = words.join(" ");
6723
- if (words.length > 1 && [...whole].length >= 3) parts.add(whole);
6819
+ const whole2 = words.join(" ");
6820
+ if (words.length > 1 && [...whole2].length >= 3) parts.add(whole2);
6724
6821
  return [...parts].map((w) => `"${w.replaceAll('"', '""')}"`).join(" OR ");
6725
6822
  }
6726
6823
  function editDistance(a, b, max) {
@@ -7067,15 +7164,15 @@ function indentOf(line) {
7067
7164
  }
7068
7165
  function buildUnits(text) {
7069
7166
  const lines = text.split("\n");
7070
- const stack = [];
7167
+ const stack2 = [];
7071
7168
  const out = [];
7072
7169
  for (let i = 0; i < lines.length; i++) {
7073
7170
  const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
7074
7171
  const indent = indentOf(line);
7075
7172
  if (indent === line.length) continue;
7076
- while (stack.length > 0 && stack[stack.length - 1].indent >= indent) stack.pop();
7077
- out.push({ ord: i, body: [...stack.map((s) => s.line), line].join("\n") });
7078
- stack.push({ indent, line });
7173
+ while (stack2.length > 0 && stack2[stack2.length - 1].indent >= indent) stack2.pop();
7174
+ out.push({ ord: i, body: [...stack2.map((s) => s.line), line].join("\n") });
7175
+ stack2.push({ indent, line });
7079
7176
  }
7080
7177
  return out;
7081
7178
  }
@@ -7377,7 +7474,7 @@ function chunkText(text, kind, maxBytes = MAX_CHUNK_BYTES) {
7377
7474
  }
7378
7475
  function mdChunks(src, cap, lineCut) {
7379
7476
  const out = [];
7380
- const stack = [];
7477
+ const stack2 = [];
7381
7478
  let title = "";
7382
7479
  let run = [];
7383
7480
  const push2 = (text, bytes5) => {
@@ -7391,9 +7488,9 @@ function mdChunks(src, cap, lineCut) {
7391
7488
  for (const b of lineBlocks(src, true)) {
7392
7489
  if (b.heading !== void 0) {
7393
7490
  flush();
7394
- while (stack.length > 0 && stack[stack.length - 1].level >= b.heading.level) stack.pop();
7395
- stack.push(b.heading);
7396
- title = stack.map((h) => h.text).join(" > ");
7491
+ while (stack2.length > 0 && stack2[stack2.length - 1].level >= b.heading.level) stack2.pop();
7492
+ stack2.push(b.heading);
7493
+ title = stack2.map((h) => h.text).join(" > ");
7397
7494
  }
7398
7495
  if (b.fence !== void 0 && utf8Bytes(src.slice(b.start, b.end)) > cap) {
7399
7496
  const pieces = fencePieces(src, b, b.fence, cap);
@@ -7626,7 +7723,7 @@ function cutPoint(src, start, end, scratch) {
7626
7723
  const r = encoder.encodeInto(src.slice(start, limit), scratch);
7627
7724
  return { end: start + r.read, written: r.written };
7628
7725
  }
7629
- function merge(src, blocks, join24, cap, lineCut) {
7726
+ function merge(src, blocks, join25, cap, lineCut) {
7630
7727
  const out = [];
7631
7728
  const scratch = new Uint8Array(cap);
7632
7729
  let wide;
@@ -7636,7 +7733,7 @@ function merge(src, blocks, join24, cap, lineCut) {
7636
7733
  out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
7637
7734
  };
7638
7735
  for (const b of blocks) {
7639
- if (cur !== void 0 && !join24) {
7736
+ if (cur !== void 0 && !join25) {
7640
7737
  emit(cur.start, cur.end, curBytes);
7641
7738
  cur = void 0;
7642
7739
  }
@@ -7848,8 +7945,8 @@ function renderRow(i, row5, skewed, named, budget) {
7848
7945
  return body === null ? null : prefix + body;
7849
7946
  }
7850
7947
  function fitRow(row5, skewed, named, budget) {
7851
- const whole = JSON.stringify(row5);
7852
- if (bytes(whole) <= budget) return whole;
7948
+ const whole2 = JSON.stringify(row5);
7949
+ if (bytes(whole2) <= budget) return whole2;
7853
7950
  const own2 = Object.keys(row5);
7854
7951
  const tier = (k) => skewed.includes(k) ? 0 : named.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
7855
7952
  const order = [...own2].sort((a, b) => tier(a) - tier(b) || own2.indexOf(a) - own2.indexOf(b));
@@ -19854,9 +19951,9 @@ import { accessSync, constants as fsConstants, statSync as statSync3 } from "nod
19854
19951
  import path from "node:path";
19855
19952
 
19856
19953
  // src/core/sandbox/path-entries.ts
19857
- function pathEntries(value, platform = process.platform, delimiter = platform === "win32" ? ";" : ":") {
19954
+ function pathEntries(value, platform = process.platform, delimiter2 = platform === "win32" ? ";" : ":") {
19858
19955
  const win = platform === "win32";
19859
- return value.split(delimiter).map((e) => win && e.length >= 2 && e.startsWith('"') && e.endsWith('"') ? e.slice(1, -1) : e).filter(Boolean);
19956
+ return value.split(delimiter2).map((e) => win && e.length >= 2 && e.startsWith('"') && e.endsWith('"') ? e.slice(1, -1) : e).filter(Boolean);
19860
19957
  }
19861
19958
 
19862
19959
  // src/core/sandbox/runtimes.ts
@@ -20521,8 +20618,8 @@ var ctxBatch = Object.freeze({
20521
20618
  });
20522
20619
 
20523
20620
  // src/core/tools/doctor.ts
20524
- import { readdirSync as readdirSync5, readFileSync as readFileSync12, existsSync as existsSync12 } from "node:fs";
20525
- import { basename as basename4, dirname as dirname7, join as join14 } from "node:path";
20621
+ import { readdirSync as readdirSync5, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20622
+ import { basename as basename4, dirname as dirname7, join as join15 } from "node:path";
20526
20623
 
20527
20624
  // src/core/ops/doctor-config.ts
20528
20625
  import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
@@ -22974,8 +23071,8 @@ function setTomlText(text, path7, value) {
22974
23071
  if (sameValue(cur, value)) return text;
22975
23072
  const inline = doc.keys.find((k) => k.inline && k.full.length < path7.length && under(path7, k.full));
22976
23073
  if (inline !== void 0) {
22977
- const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
22978
- return replaceToml(text, doc, inline.full, whole);
23074
+ const whole2 = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
23075
+ return replaceToml(text, doc, inline.full, whole2);
22979
23076
  }
22980
23077
  if (isPlainObject3(cur) && isPlainObject3(value)) {
22981
23078
  const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
@@ -23654,14 +23751,18 @@ function mcpWrong(row5, home, env, worktree) {
23654
23751
  return true;
23655
23752
  }
23656
23753
  }
23754
+ function hookFile(row5, spec, home, env, worktree) {
23755
+ const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
23756
+ const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23757
+ 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);
23758
+ return file2;
23759
+ }
23657
23760
  function hookParts(row5, home, env, worktree) {
23658
23761
  const spec = HOOK_HOST_FILE[row5.id];
23659
23762
  if (spec === null) return [];
23660
23763
  let block;
23661
23764
  try {
23662
- const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
23663
- const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23664
- 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);
23765
+ const file2 = hookFile(row5, spec, home, env, worktree);
23665
23766
  block = hostConfigValueAt(readParsed(row5.id, file2).value, spec.key);
23666
23767
  if (row5.id === "codex") {
23667
23768
  const config2 = readParsed(row5.id, join11(codexDirOf(env, home), CONFIG_TOML_FILE)).value;
@@ -23702,12 +23803,15 @@ function checkHostConfig(row5, env, worktree) {
23702
23803
  const read3 = row5.id === "pi" ? mcpFile(row5, home, env) : null;
23703
23804
  if (parts.length === 0) return read3 === null ? pass("D3") : { ...pass("D3"), detail: read3 };
23704
23805
  const detail = D3_DETAIL(parts);
23705
- return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, DOCTOR_FIX_UPGRADE);
23806
+ const fix = parts.includes(PART_MCP) && parts.includes(PART_HOOKS) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
23807
+ return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, fix);
23706
23808
  }
23707
23809
  function checkV1Leftovers(agent, home, scope = {}) {
23708
23810
  const findings = detectV1(agent, home, scope);
23709
23811
  if (findings.length === 0) return pass("D4");
23710
- return fail2("D4", findings.map((f) => f.reason).join(D4_REASON_JOIN), DOCTOR_FIX_UPGRADE);
23812
+ const detail = findings.map((f) => f.reason).join(D4_REASON_JOIN);
23813
+ if (findings.every((f) => f.reason === V1_REASON.tmpFile)) return { ...pass("D4"), detail };
23814
+ return fail2("D4", detail, DOCTOR_FIX_UPGRADE);
23711
23815
  }
23712
23816
  function parsedOrNull(agent, file2, jsonc) {
23713
23817
  try {
@@ -23726,6 +23830,31 @@ function checkDoubleFire(agent, worktree) {
23726
23830
  const useClaudeHooks = isObject4(vscode) && vscode[VSCODE_CLAUDE_HOOKS_SETTING] === true;
23727
23831
  return hooksOn && useClaudeHooks ? fail2("D5b", D5B_DETAIL, D5B_FIX) : pass("D5b");
23728
23832
  }
23833
+ function configPaths(row5, env, worktree) {
23834
+ const home = homeDirOf(env);
23835
+ if (home === null) return [];
23836
+ const out = [];
23837
+ const mcp = mcpFile(row5, home, env);
23838
+ if (mcp !== null) out.push({ label: "MCP entry", path: mcp });
23839
+ const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23840
+ if (native !== null) out.push({ label: "Codex plugin MCP", path: join11(native, CODEX_PLUGIN_MCP_FILE) });
23841
+ const spec = HOOK_HOST_FILE[row5.id];
23842
+ if (spec !== null) {
23843
+ try {
23844
+ out.push({ label: "hook entries", path: hookFile(row5, spec, home, env, worktree) });
23845
+ } catch (err) {
23846
+ out.push({ label: "hook entries", path: err instanceof Error ? err.message : String(err) });
23847
+ }
23848
+ }
23849
+ if (spec !== null && spec.root === "plugin" || row5.installMode === "marketplace" || row5.installMode === "plugin") {
23850
+ try {
23851
+ out.push({ label: "plugin root", path: resolvePluginRoot(row5, env, worktree) });
23852
+ } catch (err) {
23853
+ out.push({ label: "plugin root", path: err instanceof Error ? err.message : String(err) });
23854
+ }
23855
+ }
23856
+ return out.filter((e, i) => out.findIndex((o) => o.path === e.path) === i);
23857
+ }
23729
23858
 
23730
23859
  // src/core/ops/doctor-db.ts
23731
23860
  import { existsSync as existsSync7 } from "node:fs";
@@ -24175,16 +24304,19 @@ function isObject5(v) {
24175
24304
  }
24176
24305
  function loadFixture(bundleDir2, agent) {
24177
24306
  const file2 = path6.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
24178
- if (!existsSync10(file2)) return null;
24307
+ if (!existsSync10(file2)) return { cause: D5_FIXTURE_FILE_ABSENT(file2) };
24179
24308
  let all;
24180
24309
  try {
24181
24310
  all = JSON.parse(hostText(readFileSync10(file2, "utf8")));
24182
- } catch {
24183
- return null;
24311
+ } catch (err) {
24312
+ return { cause: D5_FIXTURE_PARSE(file2, err instanceof Error ? err.message : String(err)) };
24184
24313
  }
24185
- if (!isObject5(all) || !Object.hasOwn(all, agent)) return null;
24314
+ if (!isObject5(all)) return { cause: D5_FIXTURE_PARSE(file2, "top level is not an object") };
24315
+ if (!Object.hasOwn(all, agent)) return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": " + D5_FIXTURE_AGENT_ABSENT(file2, Object.keys(all)) };
24186
24316
  const e = all[agent];
24187
- if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload")) return null;
24317
+ if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload")) {
24318
+ return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": the entry lacks an event name or a payload" };
24319
+ }
24188
24320
  return { event: e.event, payload: e.payload };
24189
24321
  }
24190
24322
  function payloadFor(payload, worktree) {
@@ -24238,7 +24370,7 @@ async function checkHookRoundTrip(i) {
24238
24370
  return row("UNKNOWN", D5_CODEX_UNTRUSTED_DETAIL);
24239
24371
  }
24240
24372
  const fixture = loadFixture(i.bundleDir, i.agent);
24241
- if (fixture === null) return row("UNKNOWN", D5_NO_FIXTURE_DETAIL(i.agent));
24373
+ if ("cause" in fixture) return row("UNKNOWN", fixture.cause);
24242
24374
  const now = i.now ?? (() => performance.now());
24243
24375
  const fixed = i.samples === void 0 ? null : Math.max(1, i.samples);
24244
24376
  const maxPairs = fixed ?? D5_MAX_PAIRS;
@@ -24390,8 +24522,13 @@ function envLine(key, value) {
24390
24522
  const typedValue = allowed !== void 0 && allowed.includes(value) ? value : REPORT_INVALID;
24391
24523
  return REPORT_ENV_PREFIX + typedKey + ": " + typedValue;
24392
24524
  }
24525
+ function fixCell(agent, row5) {
24526
+ if (row5.status === "PASS") return "";
24527
+ if (row5.status === "FAIL") return DOCTOR_FAIL_LINE(agent, row5.id, row5.detail, row5.fixCommand ?? "");
24528
+ return row5.fixCommand === void 0 ? "" : "Fix: " + row5.fixCommand;
24529
+ }
24393
24530
  function rowLine(agent, row5) {
24394
- const fix = row5.status === "FAIL" ? DOCTOR_FAIL_LINE(agent, row5.id, row5.detail, row5.fixCommand ?? "") : "";
24531
+ const fix = fixCell(agent, row5);
24395
24532
  return "| " + [row5.id + " " + row5.label, row5.status, row5.detail, fix].join(" | ") + " |";
24396
24533
  }
24397
24534
  function buildReport(input) {
@@ -24421,6 +24558,196 @@ function buildReportHead(input) {
24421
24558
  return lines.concat(tail).join("\n");
24422
24559
  }
24423
24560
 
24561
+ // src/core/ops/doctor-issue.ts
24562
+ import { spawnSync as spawnSync3 } from "node:child_process";
24563
+ import { closeSync, existsSync as existsSync12, fstatSync, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
24564
+ import { delimiter, join as join14 } from "node:path";
24565
+ var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
24566
+ function tildeOf(env) {
24567
+ const home = homeDirOf(env);
24568
+ if (home === null || home === "") return (t) => t;
24569
+ const homes = [home];
24570
+ try {
24571
+ const real2 = realpathSync8.native(home);
24572
+ if (real2 !== home) homes.push(real2);
24573
+ } catch {
24574
+ }
24575
+ homes.sort((a, b) => b.length - a.length);
24576
+ const slash = (rest) => rest.replace(/^[^\s"'`|)>,;]*/, (run) => run.replace(/\\/g, "/"));
24577
+ return (t) => homes.reduce((acc, h) => acc.split(h).map((piece, n) => n === 0 ? piece : slash(piece)).join("~"), t);
24578
+ }
24579
+ function maskLine(line) {
24580
+ const lower = line.toLowerCase();
24581
+ const named = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
24582
+ const token = TOKEN_PREFIXES.some((p) => line.includes(p));
24583
+ if (!named && !token) return line;
24584
+ const at2 = Math.max(line.indexOf(":"), line.indexOf("="));
24585
+ return at2 === -1 ? DOCTOR_MASK : line.slice(0, at2 + 1) + " " + DOCTOR_MASK;
24586
+ }
24587
+ function environmentLine(ctx, adapter, env, version2) {
24588
+ const sha = BUNDLE_SHA === void 0 ? "dev build" : BUNDLE_SHA.slice(0, 7);
24589
+ const client = ctx.clientInfo;
24590
+ const agent = client === void 0 ? adapter.id : client.name === adapter.id ? `${adapter.id} ${client.version}` : `${adapter.id} ${client.version} (client ${client.name})`;
24591
+ const shell = env.SHELL ?? env.ComSpec ?? "sh";
24592
+ return `${DOCTOR_ENV_PREFIX}context-mode ${version2 ?? "source checkout"} (${sha}), agent ${agent}
24593
+ ${DOCTOR_ENV_PREFIX}${process.platform}-${process.arch}, Node ${process.version}, shell ${shell}`;
24594
+ }
24595
+ function gitVersion(env) {
24596
+ const r = spawnSync3("git", ["--version"], { env, encoding: "utf8", timeout: DOCTOR_GIT_VERSION_TIMEOUT_MS, windowsHide: true });
24597
+ if (r.status === 0) return `${r.stdout}`.trim();
24598
+ return `git --version: ${r.error ? r.error.message : `exit ${r.status}`}`;
24599
+ }
24600
+ function onPath(env, tool) {
24601
+ const names = process.platform === "win32" ? [tool + EXE_SUFFIX, tool + ".cmd", tool] : [tool];
24602
+ const out = [];
24603
+ for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
24604
+ if (dir === "") continue;
24605
+ for (const n of names) if (existsSync12(join14(dir, n))) {
24606
+ out.push(join14(dir, n));
24607
+ break;
24608
+ }
24609
+ }
24610
+ return out;
24611
+ }
24612
+ function hookLogTail(env) {
24613
+ const file2 = hookLogPath(env);
24614
+ if (file2 === "" || !existsSync12(file2)) return [`(${file2 || "hook-errors.log"} holds zero lines)`];
24615
+ try {
24616
+ const fd = openSync(file2, "r");
24617
+ try {
24618
+ const size = fstatSync(fd).size;
24619
+ const start = Math.max(0, size - DOCTOR_LOG_TAIL_BYTES);
24620
+ const buf = Buffer.alloc(size - start);
24621
+ readSync(fd, buf, 0, buf.length, start);
24622
+ const lines = buf.toString("utf8").split("\n").filter((l) => l.trim() !== "");
24623
+ if (start > 0) lines.shift();
24624
+ return lines.slice(-DOCTOR_HOOK_LOG_LINES).map(maskLine);
24625
+ } finally {
24626
+ closeSync(fd);
24627
+ }
24628
+ } catch (err) {
24629
+ return [`hook-errors.log read: ${err instanceof Error ? err.message : String(err)}`];
24630
+ }
24631
+ }
24632
+ async function journalRows(ctx) {
24633
+ const head = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
24634
+ if (!existsSync12(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
24635
+ try {
24636
+ const db = await openDb(ctx.project, { readOnly: true });
24637
+ try {
24638
+ 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();
24639
+ const cell5 = (v) => v === null || v === void 0 ? "" : String(v);
24640
+ 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)} |`));
24641
+ } finally {
24642
+ closeDb(db);
24643
+ }
24644
+ } catch (err) {
24645
+ return [`journal read: ${err instanceof Error ? err.message : String(err)}`];
24646
+ }
24647
+ }
24648
+ function agentConfig(adapter, env, worktree) {
24649
+ const home = homeDirOf(env);
24650
+ const files = configPaths(adapter, env, worktree);
24651
+ if (home !== null) {
24652
+ if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join14(claudeDirOf(env, home), SETTINGS_FILE) });
24653
+ if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join14(codexDirOf(env, home), CONFIG_TOML_FILE) });
24654
+ }
24655
+ const out = [];
24656
+ const seen = /* @__PURE__ */ new Set();
24657
+ for (const f of files) {
24658
+ if (seen.has(f.path)) continue;
24659
+ seen.add(f.path);
24660
+ if (!existsSync12(f.path)) {
24661
+ out.push(`${f.label}: ${f.path} (absent)`);
24662
+ continue;
24663
+ }
24664
+ let text = "";
24665
+ try {
24666
+ text = readFileSync12(f.path, "utf8");
24667
+ } catch (err) {
24668
+ out.push(`${f.label}: ${f.path} (read: ${err instanceof Error ? err.message : String(err)})`);
24669
+ continue;
24670
+ }
24671
+ const hit = text.split("\n").filter((l) => l.includes("context-mode") || l.includes("hook.mjs") || adapter.id === "codex" && l.includes("trust"));
24672
+ out.push(`${f.label}: ${f.path} (${hit.length} matching lines)`);
24673
+ for (const l of hit.slice(0, DOCTOR_CONFIG_LINES)) out.push(" " + maskLine(l.trimEnd()));
24674
+ }
24675
+ return out;
24676
+ }
24677
+ function failing(rows) {
24678
+ return rows.filter((r) => r.status === "FAIL");
24679
+ }
24680
+ function issueTitle(agent, rows) {
24681
+ return `ctx_doctor ${agent}: ${failing(rows).map((r) => `${r.id} ${r.label}`).join(", ")} FAIL`;
24682
+ }
24683
+ function summaryOf(agent, rows) {
24684
+ const f = failing(rows)[0];
24685
+ return f === void 0 ? `ctx_doctor ${agent}` : `${f.id} ${f.label} FAIL on ${agent}: ${f.detail}`;
24686
+ }
24687
+ async function buildIssueBody(i) {
24688
+ const tilde = tildeOf(i.env);
24689
+ const agent = i.adapter.id;
24690
+ const install = NATIVE_INSTALL[agent] ?? [];
24691
+ const failRows = i.rows.filter((r) => r.status !== "PASS");
24692
+ const envNames = DOCTOR_ENV_NAMES.map((n) => i.env[n] === void 0 ? `${n} (unset)` : `${n}=${i.env[n]}`);
24693
+ const pathTools = DOCTOR_PATH_TOOLS.map((t) => `PATH holds ${t}: ${onPath(i.env, t).join(", ") || "(absent)"}`);
24694
+ const sections = {
24695
+ "Summary": [summaryOf(agent, i.rows)],
24696
+ "ctx-report": [i.table],
24697
+ "What happened": [
24698
+ "Rows that need a look:",
24699
+ ...failRows.map((r) => `- ${r.id} ${r.label} ${r.status}: ${r.detail}${r.fixCommand ? ` (Fix: ${r.fixCommand})` : ""}`),
24700
+ "Error code and text: <the agent fills this in: the exact error the user saw>"
24701
+ ],
24702
+ "Hook errors": ["hook-errors.log, last " + DOCTOR_HOOK_LOG_LINES + " lines (UTC):", "```", ...hookLogTail(i.env), "```"],
24703
+ "Journal rows": ["events, newest first, last " + DOCTOR_JOURNAL_ROWS + " (bodies stay local):", ...await journalRows(i.ctx)],
24704
+ "Agent config": agentConfig(i.adapter, i.env, i.ctx.project.worktree),
24705
+ "Expected": ["Expected: <the agent fills this in: what should happen, with the byte count>"],
24706
+ "Steps": [
24707
+ "Reproduced: <yes (2 of 2) or 1 of 2>",
24708
+ "Prompt or command: <the agent fills this in: the exact prompt or command>",
24709
+ "Actual: <the agent fills this in: what context-mode did, with the byte count>",
24710
+ "Repro script (fresh HOME, native install for " + agent + "):",
24711
+ "```sh",
24712
+ 'export HOME="$(mktemp -d)"',
24713
+ 'cd "$HOME"',
24714
+ ...install,
24715
+ "<the command or prompt above>",
24716
+ "```"
24717
+ ],
24718
+ "Environment": [
24719
+ i.envLine,
24720
+ `context-mode bundle: ${i.bundleDir}`,
24721
+ `Install route: ${install.join(" && ")}`,
24722
+ `git: ${gitVersion(i.env)}`,
24723
+ ...pathTools,
24724
+ ...envNames,
24725
+ `Project: ${i.ctx.project.worktree} (key ${i.ctx.project.projectKey})`,
24726
+ "Filed by: <your agent name, version, model id>"
24727
+ ]
24728
+ };
24729
+ const out = [];
24730
+ for (const h of ISSUE_FORM_HEADINGS) out.push(`### ${h}`, "", ...sections[h] ?? [], "");
24731
+ return tilde(out.join("\n"));
24732
+ }
24733
+ async function writeIssueReport(i) {
24734
+ const tilde = tildeOf(i.env);
24735
+ const body = await buildIssueBody(i);
24736
+ const dir = join14(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
24737
+ mkdirSync5(dir, { recursive: true });
24738
+ const file2 = join14(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
24739
+ writeFileSync3(file2, body);
24740
+ const shown2 = tilde(file2);
24741
+ const title = issueTitle(i.adapter.id, i.rows);
24742
+ const gh = [`gh issue create --repo ${ISSUE_REPO_SLUG} --label bug \\`, `${DOCTOR_GH_NEXT}title ${JSON.stringify(title)} \\`, `${DOCTOR_GH_NEXT}body-file ${shown2}`];
24743
+ 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))];
24744
+ }
24745
+ function formUrl(title, summary) {
24746
+ const base = `${ISSUE_FORM_URL}&title=${encodeURIComponent(title)}`;
24747
+ const full = `${base}&summary=${encodeURIComponent(summary)}`;
24748
+ return full.length < ISSUE_URL_MAX ? full : base;
24749
+ }
24750
+
24424
24751
  // src/core/tools/doctor.ts
24425
24752
  var ctxDoctorSchema = external_exports.object({}).strict();
24426
24753
  function lineOf2(err) {
@@ -24435,7 +24762,7 @@ async function guard(id2, run) {
24435
24762
  }
24436
24763
  }
24437
24764
  async function codexDb(ctx, adapter) {
24438
- if (adapter.id !== "codex" || !existsSync12(ctx.project.dbPath)) return null;
24765
+ if (adapter.id !== "codex" || !existsSync13(ctx.project.dbPath)) return null;
24439
24766
  try {
24440
24767
  return await openDb(ctx.project, { readOnly: true });
24441
24768
  } catch {
@@ -24465,11 +24792,11 @@ async function hookRow(ctx, adapter, host) {
24465
24792
  }
24466
24793
  }
24467
24794
  function ownServerId(configDir, projectKey) {
24468
- const dir = join14(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24469
- if (!existsSync12(dir)) return "";
24795
+ const dir = join15(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24796
+ if (!existsSync13(dir)) return "";
24470
24797
  for (const name of readdirSync5(dir)) {
24471
24798
  if (!name.endsWith(OWNER_PID_EXT)) continue;
24472
- if (readFileSync12(join14(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
24799
+ if (readFileSync13(join15(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
24473
24800
  }
24474
24801
  return "";
24475
24802
  }
@@ -24514,24 +24841,39 @@ function reportEnv(env) {
24514
24841
  }
24515
24842
  return out;
24516
24843
  }
24517
- async function handler2(_input, ctx) {
24844
+ async function doctorReply(ctx, host) {
24518
24845
  const adapter = getAdapter(ctx.project.agent);
24519
- const host = { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 };
24520
24846
  const rows = await runDoctorChecks(ctx, adapter, host);
24521
- const command = `context-mode ${rows.some((r) => r.status === "FAIL") ? "setup" : "doctor"} --agents ${adapter.id}`;
24522
- const input = { agent: adapter.id, rows, env: reportEnv(process.env), command };
24523
- const whole = buildReport(input);
24524
- const bytes5 = Buffer.byteLength(whole, "utf8");
24525
- if (bytes5 <= REPORT_CAP) return { text: whole, isError: false, sandboxBytes: bytes5 };
24847
+ const failed2 = rows.some((r) => r.status === "FAIL");
24848
+ const command = `context-mode ${failed2 ? "setup" : "doctor"} --agents ${adapter.id}`;
24849
+ const input = { agent: adapter.id, rows, env: reportEnv(host.env), command };
24850
+ const envLine2 = environmentLine(ctx, adapter, host.env, bundleVersion(host.bundleDir));
24851
+ const table3 = buildReport(input);
24852
+ let notes = [];
24853
+ if (failed2) {
24854
+ try {
24855
+ notes = await writeIssueReport({ ctx, adapter, env: host.env, bundleDir: host.bundleDir, rows, envLine: envLine2, table: table3 });
24856
+ } catch (err) {
24857
+ notes = [`Report file: ${lineOf2(err)}`];
24858
+ }
24859
+ }
24860
+ const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
24861
+ const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
24862
+ const whole2 = [envLine2, table3, ...docs, ...notes].join("\n");
24863
+ const bytes5 = Buffer.byteLength(whole2, "utf8");
24864
+ if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
24526
24865
  const db = await openDb(ctx.project);
24527
24866
  try {
24528
- indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole, "text");
24867
+ indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
24529
24868
  } finally {
24530
24869
  closeDb(db);
24531
24870
  }
24532
- const text = buildReportHead(input);
24871
+ const text = [envLine2, buildReportHead(input), ...docs, ...notes].join("\n");
24533
24872
  return { text, isError: false, sandboxBytes: bytes5 };
24534
24873
  }
24874
+ async function handler2(_input, ctx) {
24875
+ return doctorReply(ctx, { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 });
24876
+ }
24535
24877
  var ctxDoctor = Object.freeze({
24536
24878
  name: "ctx_doctor",
24537
24879
  schema: ctxDoctorSchema,
@@ -24542,9 +24884,9 @@ var ctxDoctor = Object.freeze({
24542
24884
  });
24543
24885
 
24544
24886
  // src/core/tools/execute.ts
24545
- import { existsSync as existsSync13, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
24887
+ import { existsSync as existsSync14, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "node:fs";
24546
24888
  import { tmpdir as tmpdir2 } from "node:os";
24547
- import { dirname as dirname8, join as join15, parse as parse3, resolve as resolve6 } from "node:path";
24889
+ import { dirname as dirname8, join as join16, parse as parse3, resolve as resolve6 } from "node:path";
24548
24890
 
24549
24891
  // src/core/sandbox/win-build.ts
24550
24892
  var SEPARATORS2 = ";&|(\n";
@@ -24628,7 +24970,7 @@ function schemaLine(issue2) {
24628
24970
  }
24629
24971
  function fileError(given, abs, root) {
24630
24972
  let dir = abs;
24631
- while (!existsSync13(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
24973
+ while (!existsSync14(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
24632
24974
  if (isInside(root, dir)) return null;
24633
24975
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
24634
24976
  }
@@ -24709,9 +25051,9 @@ async function handler3(raw, ctx) {
24709
25051
  if (takesDashC(input.language, runtime)) {
24710
25052
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
24711
25053
  } else {
24712
- tmpDir = mkdtempSync(join15(tmpdir2(), TMP_PREFIX));
24713
- const file2 = join15(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
24714
- writeFileSync3(file2, scriptText(input.language, input.code), "utf8");
25054
+ tmpDir = mkdtempSync(join16(tmpdir2(), TMP_PREFIX));
25055
+ const file2 = join16(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
25056
+ writeFileSync4(file2, scriptText(input.language, input.code), "utf8");
24715
25057
  argv = scriptArgv(input.language, runtime, file2);
24716
25058
  }
24717
25059
  if (input.background === true) {
@@ -24745,21 +25087,21 @@ var ctxExecute = {
24745
25087
  };
24746
25088
 
24747
25089
  // src/core/tools/index.ts
24748
- import { existsSync as existsSync14, readFileSync as readFileSync14, statSync as statSync7 } from "node:fs";
24749
- import { dirname as dirname9, extname, join as join17, relative as relative3, resolve as resolve7 } from "node:path";
25090
+ import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as statSync7 } from "node:fs";
25091
+ import { dirname as dirname9, extname, join as join18, relative as relative3, resolve as resolve7 } from "node:path";
24750
25092
 
24751
25093
  // src/core/index/walk.ts
24752
- import { readdirSync as readdirSync6, readFileSync as readFileSync13, realpathSync as realpathSync8, statSync as statSync6 } from "node:fs";
24753
- import { join as join16 } from "node:path";
25094
+ import { readdirSync as readdirSync6, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync6 } from "node:fs";
25095
+ import { join as join17 } from "node:path";
24754
25096
  var GITIGNORE = ".gitignore";
24755
25097
  var GIT_DIR = ".git";
24756
25098
  function walkDir(root, containmentRoot) {
24757
- const real2 = realpathSync8(root);
25099
+ const real2 = realpathSync9(root);
24758
25100
  if (!isInside(containmentRoot, real2)) throw new CtxError("OUTSIDE_ROOT", { p: root, root: containmentRoot });
24759
25101
  const found = [];
24760
25102
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
24761
25103
  found.sort(compareFound);
24762
- return found.map((f) => ({ absPath: f.absPath, relPath: join16(...f.dir, f.name) }));
25104
+ return found.map((f) => ({ absPath: f.absPath, relPath: join17(...f.dir, f.name) }));
24763
25105
  }
24764
25106
  function visit(abs, rel, parent, contain, seen, found) {
24765
25107
  let entries;
@@ -24768,17 +25110,17 @@ function visit(abs, rel, parent, contain, seen, found) {
24768
25110
  } catch {
24769
25111
  return;
24770
25112
  }
24771
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join16(abs, GITIGNORE), rel)) : parent;
25113
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join17(abs, GITIGNORE), rel)) : parent;
24772
25114
  for (const e of entries) {
24773
25115
  if (e.name === GIT_DIR) continue;
24774
- const path7 = join16(abs, e.name);
25116
+ const path7 = join17(abs, e.name);
24775
25117
  let isDir = e.isDirectory();
24776
25118
  let isFile = e.isFile();
24777
25119
  let target = path7;
24778
25120
  if (e.isSymbolicLink()) {
24779
25121
  let resolved;
24780
25122
  try {
24781
- resolved = realpathSync8(path7);
25123
+ resolved = realpathSync9(path7);
24782
25124
  } catch {
24783
25125
  continue;
24784
25126
  }
@@ -24793,7 +25135,7 @@ function visit(abs, rel, parent, contain, seen, found) {
24793
25135
  if (isFile) {
24794
25136
  found.push({ dir: rel, name: e.name, absPath: path7 });
24795
25137
  } else if (isDir) {
24796
- const key = e.isSymbolicLink() ? target : realpathSync8(path7);
25138
+ const key = e.isSymbolicLink() ? target : realpathSync9(path7);
24797
25139
  if (seen.has(key)) continue;
24798
25140
  seen.add(key);
24799
25141
  visit(path7, segs, rules, contain, seen, found);
@@ -24811,7 +25153,7 @@ function compareFound(a, b) {
24811
25153
  function readRules(file2, base) {
24812
25154
  let body;
24813
25155
  try {
24814
- body = readFileSync13(file2, "utf8");
25156
+ body = readFileSync14(file2, "utf8");
24815
25157
  } catch {
24816
25158
  return [];
24817
25159
  }
@@ -28894,14 +29236,14 @@ function kindOfType(contentType) {
28894
29236
  }
28895
29237
  function readUtf8(absPath) {
28896
29238
  try {
28897
- return utf8.decode(readFileSync14(absPath));
29239
+ return utf8.decode(readFileSync15(absPath));
28898
29240
  } catch {
28899
29241
  return void 0;
28900
29242
  }
28901
29243
  }
28902
29244
  function missingOrOutside(given, abs, root) {
28903
29245
  let dir = abs;
28904
- while (!existsSync14(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
29246
+ while (!existsSync15(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
28905
29247
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
28906
29248
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
28907
29249
  }
@@ -28912,7 +29254,7 @@ function pathItems(input, project) {
28912
29254
  if (statSync7(abs).isDirectory()) {
28913
29255
  return walkDir(abs, project.containmentRoot).map((f) => ({
28914
29256
  sourceKind: "path",
28915
- label: pathLabel(join17(base, f.relPath)),
29257
+ label: pathLabel(join18(base, f.relPath)),
28916
29258
  kind: kindOfPath(f.relPath),
28917
29259
  read: () => readUtf8(f.absPath)
28918
29260
  }));
@@ -29119,6 +29461,43 @@ var KINDS = "SELECT kind, COALESCE(SUM(session_id = ?), 0) AS s, COUNT(*) AS p F
29119
29461
  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}`;
29120
29462
  var SPAN = "SELECT COALESCE(MAX(created_at) - MIN(created_at), 0) AS span FROM events WHERE session_id = ? AND kind <> 'cost'";
29121
29463
  var SOURCES = "SELECT COUNT(*) AS n, COALESCE(SUM(chunk_count), 0) AS chunks, COALESCE(SUM(bytes_total), 0) AS bytes FROM sources";
29464
+ var HOST = "tool NOT LIKE 'ctx\\_%' ESCAPE '\\'";
29465
+ var REPLACED = `SELECT COUNT(*) AS n FROM events WHERE ${CALLS} AND ${HOST} AND returned_bytes < sandbox_bytes`;
29466
+ var RUNS = "FROM sources WHERE substr(label, 1, ?) = ?";
29467
+ var REDIRECTED = `SELECT COUNT(*) AS n, COALESCE(MAX(created_ts), 0) AS last ${RUNS}`;
29468
+ var LAST = `SELECT COALESCE(MAX(created_at), 0) AS last FROM events WHERE ${CALLS}`;
29469
+ 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`;
29470
+ 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`;
29471
+ 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}`;
29472
+ function wayOf(tool) {
29473
+ if (STATS_INDEX_TOOLS.includes(tool)) return "index";
29474
+ return tool.startsWith("ctx_") ? "sandbox" : "replace";
29475
+ }
29476
+ function readWeek(raw, lastMs) {
29477
+ const last2 = Math.floor(lastMs / MS_PER_DAY);
29478
+ const first = last2 - STATS_DAYS + 1;
29479
+ const days = Array.from({ length: STATS_DAYS }, (_, i) => ({
29480
+ day: first + i,
29481
+ calls: 0,
29482
+ ways: { sandbox: 0, index: 0, redirect: 0, replace: 0 }
29483
+ }));
29484
+ const net = /* @__PURE__ */ new Map();
29485
+ for (const r of raw.prepare(WEEK).all(first * MS_PER_DAY)) {
29486
+ const d = days[Number(r.day) - first];
29487
+ if (d === void 0) continue;
29488
+ d.calls += Number(r.calls);
29489
+ const key = `${d.day}:${wayOf(String(r.tool))}`;
29490
+ net.set(key, (net.get(key) ?? 0) + Number(r.produced) - Number(r.returned));
29491
+ }
29492
+ for (const d of days) for (const [way] of STATS_WAYS) d.ways[way] = Math.max(0, net.get(`${d.day}:${way}`) ?? 0);
29493
+ for (const r of raw.prepare(WEEK_RUNS).all(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX, first * MS_PER_DAY)) {
29494
+ const d = days[Number(r.day) - first];
29495
+ if (d === void 0) continue;
29496
+ d.calls += Number(r.calls);
29497
+ d.ways.redirect += Number(r.saved);
29498
+ }
29499
+ return days;
29500
+ }
29122
29501
  var EMPTY5 = Object.freeze({ calls: 0, produced: 0, returned: 0, saved: 0 });
29123
29502
  function totals(r) {
29124
29503
  const produced = Number(r.produced);
@@ -29133,6 +29512,8 @@ function readFacts(raw, sessionId) {
29133
29512
  const meta = raw.prepare(META).get();
29134
29513
  const span2 = Number(raw.prepare(SPAN).get(sessionId).span);
29135
29514
  const src = raw.prepare(SOURCES).get();
29515
+ const runs = raw.prepare(REDIRECTED).get(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX);
29516
+ const last2 = Math.max(Number(raw.prepare(LAST).get().last), Number(runs.last));
29136
29517
  const pages = raw.prepare("PRAGMA page_count").get();
29137
29518
  const size = raw.prepare("PRAGMA page_size").get();
29138
29519
  return {
@@ -29144,7 +29525,11 @@ function readFacts(raw, sessionId) {
29144
29525
  agents: Number(meta.agents),
29145
29526
  days: Number(meta.days),
29146
29527
  sources: { count: Number(src.n), chunks: Number(src.chunks), bytes: Number(src.bytes) },
29147
- dbBytes: Number(pages.page_count) * Number(size.page_size)
29528
+ dbBytes: Number(pages.page_count) * Number(size.page_size),
29529
+ top: raw.prepare(TOP).all().map((r) => ({ name: String(r.tool), ...totals(r) })),
29530
+ replaced: Number(raw.prepare(REPLACED).get().n),
29531
+ redirected: Number(runs.n),
29532
+ week: readWeek(raw, last2)
29148
29533
  };
29149
29534
  }
29150
29535
  function sum(groups) {
@@ -29175,6 +29560,7 @@ function count(n) {
29175
29560
  return n < STATS_MILLION ? int2(n) : (n / STATS_MILLION).toFixed(1) + "M";
29176
29561
  }
29177
29562
  function bytes4(n) {
29563
+ if (n < 0) return "-" + bytes4(-n);
29178
29564
  if (n < STATS_KIB) return int2(n) + " B";
29179
29565
  let v = n / STATS_KIB;
29180
29566
  let u = 0;
@@ -29207,17 +29593,105 @@ function plural(n, word) {
29207
29593
  }
29208
29594
  function table2(title, rows) {
29209
29595
  const max = Math.max(0, ...rows.map((r) => r.saved));
29210
- 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);
29596
+ 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);
29211
29597
  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())];
29212
29598
  }
29213
29599
  function bySaved(a, b) {
29214
29600
  return b.saved - a.saved || b.produced - a.produced || a.returned - b.returned || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
29215
29601
  }
29602
+ function toolName(tool) {
29603
+ return tool.startsWith("ctx_") ? tool : "hook " + tool;
29604
+ }
29605
+ function joinIndex(tools) {
29606
+ const idx = tools.filter((t2) => STATS_INDEX_TOOLS.includes(t2.name));
29607
+ if (idx.length <= 1) return tools;
29608
+ const t = sum(idx);
29609
+ const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: t.produced - t.returned };
29610
+ return [...tools.filter((x) => !idx.includes(x)), one];
29611
+ }
29216
29612
  function toolRows(tools) {
29217
- const named = tools.map((t) => ({ ...t, name: t.name.startsWith("ctx_") ? t.name : "hook " + t.name })).sort(bySaved);
29218
- if (named.length <= STATS_MAX_TOOL_ROWS) return named;
29219
- const rest = named.slice(STATS_MAX_TOOL_ROWS - 1);
29220
- return [...named.slice(0, STATS_MAX_TOOL_ROWS - 1), { name: `other (${rest.length} tools)`, ...sum(rest) }];
29613
+ const named = joinIndex(tools.map((t) => ({ ...t, saved: t.produced - t.returned }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
29614
+ const zero = named.filter((t) => t.saved <= 0);
29615
+ const fold2 = zero.length > 1 ? zero : [];
29616
+ const keep = named.filter((t) => !fold2.includes(t));
29617
+ const room = fold2.length > 0 ? STATS_MAX_TOOL_ROWS - 1 : STATS_MAX_TOOL_ROWS;
29618
+ const over = keep.length > room;
29619
+ const shown2 = over ? keep.slice(0, STATS_MAX_TOOL_ROWS - 1) : keep;
29620
+ const rest = over ? [...keep.slice(STATS_MAX_TOOL_ROWS - 1), ...fold2] : fold2;
29621
+ return rest.length === 0 ? shown2 : [...shown2, { name: `other (${plural(rest.length, "tool")})`, ...sum(rest) }];
29622
+ }
29623
+ var TOKEN_UNITS = ["K", "M", "B", "T"];
29624
+ function whole(v) {
29625
+ return v >= STATS_WHOLE_FROM ? int2(v) : v.toFixed(1);
29626
+ }
29627
+ function tokens(n) {
29628
+ if (n < STATS_THOUSAND) return int2(n);
29629
+ let v = n / STATS_THOUSAND;
29630
+ let u = 0;
29631
+ while (v >= STATS_THOUSAND && u < TOKEN_UNITS.length - 1) {
29632
+ v /= STATS_THOUSAND;
29633
+ u++;
29634
+ }
29635
+ return whole(v) + TOKEN_UNITS[u];
29636
+ }
29637
+ function windowLine(saved) {
29638
+ const t = saved / STATS_BYTES_PER_TOKEN;
29639
+ const share = t / STATS_WINDOW_TOKENS;
29640
+ const win = `a ${tokens(STATS_WINDOW_TOKENS)} window`;
29641
+ const head = ` about ${tokens(t)} tokens kept out`;
29642
+ if (share >= 1) return `${head}, ${whole(share)} times ${win}`;
29643
+ const p = share * PERCENT_SCALE;
29644
+ return p * STATS_WHOLE_FROM < 1 ? head : `${head}, ${whole(p)}% of ${win}`;
29645
+ }
29646
+ function ymd(day) {
29647
+ return new Date(day * MS_PER_DAY).toISOString().slice(0, "yyyy-mm-dd".length);
29648
+ }
29649
+ function mmdd(day) {
29650
+ return ymd(day).slice("yyyy-".length);
29651
+ }
29652
+ function stack(parts, max, width) {
29653
+ let total = 0;
29654
+ let at2 = 0;
29655
+ let out = "";
29656
+ parts.forEach((v, i) => {
29657
+ total += v;
29658
+ const end = max <= 0 ? 0 : Math.round(total / max * width);
29659
+ if (end > at2) {
29660
+ out += STATS_WAYS[i][1].repeat(end - at2);
29661
+ at2 = end;
29662
+ }
29663
+ });
29664
+ if (out === "" && total > 0) out = STATS_WAYS[parts.indexOf(Math.max(...parts))][1];
29665
+ return out;
29666
+ }
29667
+ function cards(cells) {
29668
+ return (" " + cells.map((c) => c.padEnd(STATS_CARD_W)).join("")).trimEnd();
29669
+ }
29670
+ function lastDays(week, allCalls) {
29671
+ const saved = week.map((d) => STATS_WAYS.reduce((t, [w]) => t + d.ways[w], 0));
29672
+ const all = saved.reduce((a, b) => a + b, 0);
29673
+ const calls = week.reduce((a, d) => a + d.calls, 0);
29674
+ const max = Math.max(0, ...saved);
29675
+ const head = `Last ${STATS_DAYS} days of use \xB7 ${ymd(week[0].day)} to ${ymd(week[week.length - 1].day)}`;
29676
+ const card = calls < allCalls ? [
29677
+ cards(["Kept out", "Tokens kept out", "Calls", "Kept out per call"]),
29678
+ cards([bytes4(all), "about " + tokens(all / STATS_BYTES_PER_TOKEN), count(calls), bytes4(calls > 0 ? all / calls : 0)]),
29679
+ ""
29680
+ ] : [];
29681
+ return [
29682
+ head,
29683
+ ...card,
29684
+ ...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)] : []),
29685
+ " " + STATS_WAYS.map(([, ch, name]) => `${ch} ${name}`).join(" "),
29686
+ ""
29687
+ ];
29688
+ }
29689
+ function hookLine(redirected, replaced) {
29690
+ const all = redirected + replaced;
29691
+ if (all === 0) return [];
29692
+ const parts = [...redirected > 0 ? [`${int2(redirected)} sent to the sandbox`] : [], ...replaced > 0 ? [`${int2(replaced)} cut down`] : []];
29693
+ const what = plural(all, "large output");
29694
+ return [parts.length === 1 ? ` Project hooks: ${what} ${parts[0].replace(/^[\d,]+ /, "")}` : ` Project hooks: ${what} kept out \xB7 ${parts.join(", ")}`];
29221
29695
  }
29222
29696
  function fit(line) {
29223
29697
  const chars = [...line];
@@ -29234,20 +29708,30 @@ function report(f, sessionId, agent) {
29234
29708
  const lines = [
29235
29709
  ...head,
29236
29710
  `${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
29711
+ ` ${bytes4(focus.produced)} became ${bytes4(focus.returned)}: ${bytes4(focus.saved)} kept out (${pct(focus)})`,
29237
29712
  " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.produced).padStart(NUM_W),
29238
29713
  " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.returned).padStart(NUM_W),
29239
- ` ${bytes4(focus.saved)} saved (${pct(focus)}) \xB7 about ${int2(focus.saved / STATS_BYTES_PER_TOKEN)} tokens kept out of the chat`,
29714
+ ...focus.saved > 0 ? [windowLine(focus.saved), STATS_TOKEN_NOTE] : [],
29715
+ ...hookLine(f.redirected, f.replaced),
29240
29716
  "",
29241
- ...table2("Scope", [{ name: "session", ...session }, { name: "project", ...project }, { name: "all-time", ...project }]),
29717
+ ...lastDays(f.week, project.calls + f.redirected),
29718
+ // D-STATS-FIX-1 (5): one DB per project holds every session of it, so project and all-time are one row.
29719
+ "By scope",
29720
+ ...table2("Scope", [{ name: "session", ...session }, { name: "project (all-time)", ...project }]),
29242
29721
  "",
29243
- "Where the savings came from (this project)",
29722
+ "By tool (this project)",
29244
29723
  ...table2("Tool", toolRows(f.tools)),
29245
- ""
29724
+ "",
29725
+ ...f.top.length > 0 ? [
29726
+ "Largest single outputs (made \u2192 sent to the chat)",
29727
+ ...f.top.map((t) => " " + label(toolName(t.name)) + bytes4(t.produced).padStart(NUM_W) + " \u2192 " + bytes4(t.returned).padStart(NUM_W)),
29728
+ ""
29729
+ ] : []
29246
29730
  ];
29247
29731
  const agents = /* @__PURE__ */ new Map();
29248
29732
  for (const g of f.groups) agents.set(g.agent, sum([agents.get(g.agent) ?? EMPTY5, g]));
29249
29733
  if (!agents.has(agent)) agents.set(agent, EMPTY5);
29250
- lines.push(...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29734
+ lines.push("By agent (this project)", ...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29251
29735
  const maxKind = Math.max(0, ...[...f.kinds.values()].map((k) => k.project));
29252
29736
  lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + "Session".padStart(STATS_KIND_W) + "Project".padStart(STATS_KIND_W));
29253
29737
  for (const [kind, name] of STATS_KIND_LABELS) {
@@ -29256,9 +29740,12 @@ function report(f, sessionId, agent) {
29256
29740
  }
29257
29741
  lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
29258
29742
  lines.push(
29259
- " " + "Indexed sources".padEnd(LABEL_W) + `${int2(f.sources.count)} \xB7 ${plural(f.sources.chunks, "chunk")} \xB7 ${bytes4(f.sources.bytes)} of content`,
29743
+ " " + "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")}`,
29260
29744
  " " + "Database file".padEnd(LABEL_W) + bytes4(f.dbBytes),
29261
- " " + "Sessions".padEnd(LABEL_W) + `${int2(f.sessions)} \xB7 agents ${int2(f.agents)} \xB7 active days ${int2(f.days)}`
29745
+ " " + "Sessions".padEnd(LABEL_W) + `${int2(f.sessions)} \xB7 agents ${int2(f.agents)} \xB7 active days ${int2(f.days)}`,
29746
+ "",
29747
+ STATS_FOOTER_URL,
29748
+ "github.com/" + ISSUE_REPO_SLUG
29262
29749
  );
29263
29750
  return lines.map(fit).join("\n");
29264
29751
  }
@@ -29296,28 +29783,28 @@ var ctxStats = Object.freeze({
29296
29783
  });
29297
29784
 
29298
29785
  // src/core/tools/upgrade.ts
29299
- import { existsSync as existsSync20, realpathSync as realpathSync9, rmSync as rmSync9 } from "node:fs";
29300
- import { basename as basename6, dirname as dirname11, join as join23 } from "node:path";
29786
+ import { existsSync as existsSync21, realpathSync as realpathSync10, rmSync as rmSync9 } from "node:fs";
29787
+ import { basename as basename6, dirname as dirname11, join as join24 } from "node:path";
29301
29788
 
29302
29789
  // src/core/ops/host-write.ts
29303
- import { copyFileSync, existsSync as existsSync15, mkdirSync as mkdirSync5, writeFileSync as writeFileSync4 } from "node:fs";
29304
- import { dirname as dirname10, join as join18 } from "node:path";
29790
+ import { copyFileSync, existsSync as existsSync16, mkdirSync as mkdirSync6, writeFileSync as writeFileSync5 } from "node:fs";
29791
+ import { dirname as dirname10, join as join19 } from "node:path";
29305
29792
  function defaultWrite(file2, text) {
29306
- writeFileSync4(file2, text, "utf8");
29793
+ writeFileSync5(file2, text, "utf8");
29307
29794
  }
29308
29795
  function hostConfigPath(agent, home, env) {
29309
29796
  const own2 = OWN_MCP_ENTRY[agent];
29310
29797
  if (own2 !== void 0) return ownMcpFileOf(agent, own2.file, env, home);
29311
29798
  switch (agent) {
29312
29799
  case "opencode":
29313
- return join18(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29800
+ return join19(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29314
29801
  // D-WIN-OPENCODE-DIR-1
29315
29802
  case "pi":
29316
- return join18(piAgentDirOf(env, home), SETTINGS_FILE);
29803
+ return join19(piAgentDirOf(env, home), SETTINGS_FILE);
29317
29804
  case "copilot-cli":
29318
29805
  return null;
29319
29806
  default:
29320
- return join18(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29807
+ return join19(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29321
29808
  }
29322
29809
  }
29323
29810
  function cell3(value) {
@@ -29329,8 +29816,8 @@ function toRow(file2, edit) {
29329
29816
  function writeWithRollback(file2, text, write2, atomic) {
29330
29817
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
29331
29818
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
29332
- const had = existsSync15(file2);
29333
- mkdirSync5(dirname10(file2), { recursive: true });
29819
+ const had = existsSync16(file2);
29820
+ mkdirSync6(dirname10(file2), { recursive: true });
29334
29821
  if (had) copyFileSync(file2, trash);
29335
29822
  try {
29336
29823
  write2(tmp, text);
@@ -29359,7 +29846,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
29359
29846
  if (requested === null) return [];
29360
29847
  const current = readHostConfig(row5.id, requested);
29361
29848
  const result = mergeOwnEntries(row5.id, current.text, current.format, row5);
29362
- const exists = existsSync15(current.path);
29849
+ const exists = existsSync16(current.path);
29363
29850
  if (exists && result.text === current.text) return [];
29364
29851
  const text = result.text === "" && current.format !== "toml" ? JSON.stringify({}) : result.text;
29365
29852
  writeWithRollback(current.path, current.layout === void 0 ? text : withLayout(text, current.layout), opts.write ?? defaultWrite, opts.atomic ?? {});
@@ -29367,8 +29854,8 @@ function regenerateHostConfig(row5, home, opts = {}) {
29367
29854
  }
29368
29855
 
29369
29856
  // src/core/ops/plugin-swap.ts
29370
- import { existsSync as existsSync16, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
29371
- import { basename as basename5, join as join19, win32 as win322 } from "node:path";
29857
+ import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
29858
+ import { basename as basename5, join as join20, win32 as win322 } from "node:path";
29372
29859
  function linkTarget(path7, win) {
29373
29860
  if (!isLink(path7)) return null;
29374
29861
  const target = readlinkSync(path7);
@@ -29387,11 +29874,11 @@ function settleLinks(link, tmp, old, opts) {
29387
29874
  else renameWithRetry(old, link, opts);
29388
29875
  }
29389
29876
  function swapPluginCurrent(agentDir, sha, opts = {}) {
29390
- const next = join19(agentDir, sha);
29391
- if (!existsSync16(next) || !lstatSync(next).isDirectory()) {
29877
+ const next = join20(agentDir, sha);
29878
+ if (!existsSync17(next) || !lstatSync(next).isDirectory()) {
29392
29879
  throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
29393
29880
  }
29394
- const link = join19(agentDir, PLUGIN_CURRENT_LINK);
29881
+ const link = join20(agentDir, PLUGIN_CURRENT_LINK);
29395
29882
  const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
29396
29883
  const old = link + PLUGIN_LINK_OLD_SUFFIX;
29397
29884
  settleLinks(link, tmp, old, opts);
@@ -29406,15 +29893,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
29406
29893
  if (before !== null) unlinkSync2(old);
29407
29894
  const keep = /* @__PURE__ */ new Set([sha]);
29408
29895
  if (before !== null) keep.add(before);
29409
- const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join19(agentDir, name));
29896
+ const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join20(agentDir, name));
29410
29897
  for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
29411
- const previous = before !== null && existsSync16(join19(agentDir, before)) ? join19(agentDir, before) : null;
29898
+ const previous = before !== null && existsSync17(join20(agentDir, before)) ? join20(agentDir, before) : null;
29412
29899
  return { current: next, previous, removed };
29413
29900
  }
29414
29901
 
29415
29902
  // src/core/ops/release-fetch.ts
29416
- import { existsSync as existsSync17, mkdirSync as mkdirSync6, rmSync as rmSync6 } from "node:fs";
29417
- import { join as join20 } from "node:path";
29903
+ import { existsSync as existsSync18, mkdirSync as mkdirSync7, rmSync as rmSync6 } from "node:fs";
29904
+ import { join as join21 } from "node:path";
29418
29905
  function failed(r) {
29419
29906
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
29420
29907
  const status = r.killed ?? String(r.exitCode);
@@ -29426,9 +29913,9 @@ async function git2(bin, args, cwd, env, signal) {
29426
29913
  return r.stdout.toString().trim();
29427
29914
  }
29428
29915
  async function fetchRelease(agent, url2, env, signal, opts = {}) {
29429
- const agentDir = join20(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
29430
- mkdirSync6(agentDir, { recursive: true });
29431
- const fetchDir = join20(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29916
+ const agentDir = join21(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
29917
+ mkdirSync7(agentDir, { recursive: true });
29918
+ const fetchDir = join21(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29432
29919
  rmSync6(fetchDir, { recursive: true, force: true });
29433
29920
  const gitBin = findRuntime(GIT_BIN, env);
29434
29921
  if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -29436,8 +29923,8 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
29436
29923
  try {
29437
29924
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url2, fetchDir], agentDir, childEnv, signal);
29438
29925
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
29439
- const dir = join20(agentDir, sha);
29440
- if (existsSync17(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29926
+ const dir = join21(agentDir, sha);
29927
+ if (existsSync18(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29441
29928
  else renameWithRetry(fetchDir, dir, opts);
29442
29929
  return { sha, dir };
29443
29930
  } catch (e) {
@@ -29447,15 +29934,15 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
29447
29934
  }
29448
29935
 
29449
29936
  // src/core/ops/uninstall.ts
29450
- import { existsSync as existsSync18, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "node:fs";
29451
- import { join as join21 } from "node:path";
29937
+ import { existsSync as existsSync19, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
29938
+ import { join as join22 } from "node:path";
29452
29939
  function row2(area, before, after) {
29453
29940
  return { area, before, after };
29454
29941
  }
29455
29942
  function stopServers(configDir, projectKey) {
29456
29943
  const stopped = listLiveOwners(configDir, projectKey);
29457
- const dir = join21(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
29458
- for (const serverId of stopped) writeFileSync5(join21(dir, serverId + OWNER_STOP_EXT), "", "utf8");
29944
+ const dir = join22(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
29945
+ for (const serverId of stopped) writeFileSync6(join22(dir, serverId + OWNER_STOP_EXT), "", "utf8");
29459
29946
  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 };
29460
29947
  }
29461
29948
  function rootOrNull(adapter, env) {
@@ -29473,15 +29960,15 @@ function removeCache(adapter, env, configDir) {
29473
29960
  const root = rootOrNull(adapter, env);
29474
29961
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29475
29962
  if (adapter.installMode === "marketplace") {
29476
- const cache = join21(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
29963
+ const cache = join22(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
29477
29964
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
29478
29965
  }
29479
29966
  rmSync7(root, { recursive: true, force: true });
29480
29967
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
29481
29968
  }
29482
29969
  case "plugin": {
29483
- const agentDir = join21(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
29484
- if (!existsSync18(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29970
+ const agentDir = join22(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
29971
+ if (!existsSync19(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29485
29972
  rmSync7(agentDir, { recursive: true, force: true });
29486
29973
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
29487
29974
  }
@@ -29526,7 +30013,7 @@ function ownEntries(agent, env) {
29526
30013
  }
29527
30014
  if (agent === "opencode") {
29528
30015
  return [{
29529
- file: join21(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
30016
+ file: join22(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
29530
30017
  // D-WIN-OPENCODE-DIR-1
29531
30018
  key: OPENCODE_PLUGIN_KEY,
29532
30019
  shown: OPENCODE_PLUGIN_KEY,
@@ -29537,7 +30024,7 @@ function ownEntries(agent, env) {
29537
30024
  if (agent === "pi") {
29538
30025
  const agentDir = piAgentDirOf(env, home);
29539
30026
  return [{
29540
- file: join21(agentDir, SETTINGS_FILE),
30027
+ file: join22(agentDir, SETTINGS_FILE),
29541
30028
  key: PI_PACKAGES_KEY,
29542
30029
  shown: PI_PACKAGES_KEY,
29543
30030
  has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
@@ -29559,12 +30046,12 @@ function removeOwnEntries(agent, env) {
29559
30046
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
29560
30047
  }
29561
30048
  function removeProjectData(configDir, projectKey) {
29562
- const projects = join21(configDir, PROJECTS_DIR_NAME);
29563
- const dir = join21(projects, projectKey);
29564
- if (!existsSync18(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
30049
+ const projects = join22(configDir, PROJECTS_DIR_NAME);
30050
+ const dir = join22(projects, projectKey);
30051
+ if (!existsSync19(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
29565
30052
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
29566
30053
  for (const name of readdirSync8(dir)) {
29567
- if (name !== OWNERS_DIR_NAME) rmSync7(join21(dir, name), { recursive: true, force: true });
30054
+ if (name !== OWNERS_DIR_NAME) rmSync7(join22(dir, name), { recursive: true, force: true });
29568
30055
  }
29569
30056
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
29570
30057
  }
@@ -29572,12 +30059,12 @@ function runUninstall(input) {
29572
30059
  const configDir = resolveConfigDir(input.env);
29573
30060
  const stop = stopServers(configDir, input.project.projectKey);
29574
30061
  const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
29575
- rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join21(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
30062
+ rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join22(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
29576
30063
  return { rows, stopped: stop.stopped };
29577
30064
  }
29578
30065
 
29579
30066
  // src/core/ops/v1-remove.ts
29580
- import { copyFileSync as copyFileSync2, existsSync as existsSync19, readFileSync as readFileSync15, rmSync as rmSync8 } from "node:fs";
30067
+ import { copyFileSync as copyFileSync2, existsSync as existsSync20, readFileSync as readFileSync16, rmSync as rmSync8 } from "node:fs";
29581
30068
  var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
29582
30069
  var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
29583
30070
  var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
@@ -29621,8 +30108,8 @@ function locate(doc, path7) {
29621
30108
  return null;
29622
30109
  }
29623
30110
  function stripJsonEntries(agent, file2, findings, kept, undo) {
29624
- const layout = hostLayout(readFileSync15(file2, "utf8"));
29625
- const text = hostText(readFileSync15(file2, "utf8"));
30111
+ const layout = hostLayout(readFileSync16(file2, "utf8"));
30112
+ const text = hostText(readFileSync16(file2, "utf8"));
29626
30113
  const doc = parseHostConfig(agent, file2, text, "jsonc");
29627
30114
  const hit = /* @__PURE__ */ new Set();
29628
30115
  const byContainer = /* @__PURE__ */ new Map();
@@ -29658,19 +30145,19 @@ function removeV1(agent, findings) {
29658
30145
  for (const f of findings) {
29659
30146
  if (UPGRADE_REPORT_ONLY_REASONS.includes(f.reason)) done.set(f, UPGRADE_REPORT_ONLY);
29660
30147
  else if (f.path === "") {
29661
- if (existsSync19(f.file)) {
30148
+ if (existsSync20(f.file)) {
29662
30149
  moveAside(f.file, undo);
29663
30150
  done.set(f, UPGRADE_REMOVED);
29664
30151
  } else done.set(f, UPGRADE_NOT_FOUND);
29665
30152
  } else entries.set(f.file, [...entries.get(f.file) ?? [], f]);
29666
30153
  }
29667
30154
  for (const [file2, list4] of entries) {
29668
- if (!existsSync19(file2)) {
30155
+ if (!existsSync20(file2)) {
29669
30156
  for (const f of list4) done.set(f, UPGRADE_NOT_FOUND);
29670
30157
  continue;
29671
30158
  }
29672
30159
  if (file2.endsWith(TOML_EXT)) {
29673
- const rawToml = readFileSync15(file2, "utf8");
30160
+ const rawToml = readFileSync16(file2, "utf8");
29674
30161
  const tomlLayout = hostLayout(rawToml);
29675
30162
  let text = hostText(rawToml);
29676
30163
  for (const f of list4) {
@@ -29698,7 +30185,7 @@ function removeV1(agent, findings) {
29698
30185
  },
29699
30186
  rollback() {
29700
30187
  for (const u of undo.splice(0).reverse()) {
29701
- if (!existsSync19(u.trash)) continue;
30188
+ if (!existsSync20(u.trash)) continue;
29702
30189
  rmSync8(u.target, { recursive: true, force: true });
29703
30190
  renameWithRetry(u.trash, u.target);
29704
30191
  }
@@ -29708,8 +30195,8 @@ function removeV1(agent, findings) {
29708
30195
 
29709
30196
  // src/core/ops/verify-sums.ts
29710
30197
  import { createHash as createHash2 } from "node:crypto";
29711
- import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync16 } from "node:fs";
29712
- import { join as join22 } from "node:path";
30198
+ import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "node:fs";
30199
+ import { join as join23 } from "node:path";
29713
30200
  function mismatch() {
29714
30201
  return new CtxError("BUNDLE_HASH_MISMATCH");
29715
30202
  }
@@ -29730,24 +30217,24 @@ function walk3(dir, prefix, out) {
29730
30217
  for (const entry of readdirSync9(dir, { withFileTypes: true })) {
29731
30218
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
29732
30219
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
29733
- const abs = join22(dir, entry.name);
30220
+ const abs = join23(dir, entry.name);
29734
30221
  if (entry.isDirectory()) walk3(abs, rel, out);
29735
30222
  else if (entry.isFile()) out.set(rel, abs);
29736
30223
  else throw mismatch();
29737
30224
  }
29738
30225
  }
29739
30226
  function verifySums(dir) {
29740
- const sumsPath = join22(dir, RELEASE_SUMS_FILE);
30227
+ const sumsPath = join23(dir, RELEASE_SUMS_FILE);
29741
30228
  const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
29742
30229
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
29743
- const sums = parseSums(readFileSync16(sumsPath, "utf8"));
30230
+ const sums = parseSums(readFileSync17(sumsPath, "utf8"));
29744
30231
  const files = /* @__PURE__ */ new Map();
29745
30232
  walk3(dir, "", files);
29746
30233
  if (files.size !== sums.size) throw mismatch();
29747
30234
  for (const [rel, abs] of files) {
29748
30235
  const want = sums.get(rel);
29749
30236
  if (want === void 0) throw mismatch();
29750
- const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync16(abs)).digest(HASH_ENCODING);
30237
+ const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync17(abs)).digest(HASH_ENCODING);
29751
30238
  if (got !== want) throw mismatch();
29752
30239
  }
29753
30240
  }
@@ -29775,8 +30262,8 @@ function pluginRootRow(adapter, env) {
29775
30262
  return root === own2 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own2)];
29776
30263
  }
29777
30264
  function isCurrent(agentDir, dir) {
29778
- const link = join23(agentDir, PLUGIN_CURRENT_LINK);
29779
- return existsSync20(link) && realpathSync9.native(link) === realpathSync9.native(dir);
30265
+ const link = join24(agentDir, PLUGIN_CURRENT_LINK);
30266
+ return existsSync21(link) && realpathSync10.native(link) === realpathSync10.native(dir);
29780
30267
  }
29781
30268
  async function checkout(adapter, deps) {
29782
30269
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);