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

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 ? "a65cd5ad387fe1dc95f9320783843d566440d57c" : 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,20 +455,25 @@ 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";
444
462
  function D1_PREFIX(version2, sha) {
445
463
  return `${version2 ?? "bundle"} (${sha.slice(0, D1_SHORT_SHA_LEN)})`;
446
464
  }
447
- var D1_GIT_PASS = "latest on the release branch";
448
- function D1_NPM_PASS(tag2) {
449
- return `latest ${tag2} on npm`;
465
+ var D1_SOURCE_NPM = "npm";
466
+ var D1_SOURCE_TAGS = "GitHub tags";
467
+ function D1_LATEST_PASS(tag2, source) {
468
+ return `latest ${tag2} on ${source}`;
469
+ }
470
+ function D1_LATEST_UPDATE(tag2, source, latest) {
471
+ return `${D1_UPDATE_DETAIL}, ${tag2} on ${source} is ${latest}`;
450
472
  }
451
- function D1_NPM_UPDATE(tag2, latest) {
452
- return `${D1_UPDATE_DETAIL}, ${tag2} on npm is ${latest}`;
473
+ function D1_LATEST_AHEAD(tag2, source, latest) {
474
+ return `ahead of ${tag2} on ${source} (${latest})`;
453
475
  }
476
+ var D1_NO_VERSION = "no version in package.json";
454
477
  var D1_LATEST_UNKNOWN = "latest unknown";
455
478
  var D1_GIT_MISSING = "git not found on PATH";
456
479
  function D1_GIT_EXIT(code, stderrLine) {
@@ -461,7 +484,9 @@ function D1_GIT_TIMEOUT(ms) {
461
484
  }
462
485
  var D1_GIT_CANCEL = "git stopped by cancel";
463
486
  var D1_GIT_NO_START = "git did not start";
464
- var D1_GIT_NO_SHA = "git answered no sha";
487
+ function D1_GIT_NO_TAG(tag2) {
488
+ return `git answered no ${tag2} tag`;
489
+ }
465
490
  function D1_NPM_TIMEOUT(ms) {
466
491
  return `npm registry timed out after ${ms} ms`;
467
492
  }
@@ -475,7 +500,10 @@ function D1_NPM_NO_TAG(tag2) {
475
500
  return `npm registry answered no ${tag2} version`;
476
501
  }
477
502
  var D1_CAUSE_JOIN = "; ";
478
- var D1_GIT_CHECK_FIX = `git ls-remote ${RELEASE_REPO_URL} ${RELEASE_BRANCH}`;
503
+ var GIT_LS_REMOTE_TAG_ARGS = Object.freeze(["--tags", "--refs"]);
504
+ var RELEASE_TAG_PATTERN = "v*";
505
+ var RELEASE_TAG_REF_PREFIX = "refs/tags/v";
506
+ var D1_GIT_CHECK_FIX = `git ls-remote --tags --refs ${RELEASE_REPO_URL} "${RELEASE_TAG_PATTERN}"`;
479
507
  var D1_NPM_CHECK_FIX = "npm view context-mode dist-tags";
480
508
  var D1_REGISTRY_URL = "https://registry.npmjs.org/-/package/context-mode/dist-tags";
481
509
  var D1_PRERELEASE_SEP = "-";
@@ -767,7 +795,7 @@ var V1_REASON = Object.freeze({
767
795
  dataDir: "old context-mode data dir <agent home>/context-mode/",
768
796
  dataDirShared: "old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",
769
797
  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"
798
+ tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep"
771
799
  });
772
800
  var UPGRADE_REPORT_ONLY_REASONS = Object.freeze([V1_REASON.statusLine, V1_REASON.vscodeMcp, V1_REASON.dataDirShared, V1_REASON.tmpFile, V1_REASON.kiroSteering]);
773
801
  var PLUGIN_ID = SERVER_KEY;
@@ -809,6 +837,85 @@ var REPORT_ENV_PREFIX = "env.";
809
837
  var REPORT_ENV_ENUMS = Object.freeze({
810
838
  NODE_ENV: Object.freeze(["development", "production", "test"])
811
839
  });
840
+ var DOCTOR_ENV_PREFIX = "Environment: ";
841
+ var DOCTOR_DOCS_URL = "https://contextmode.ai/docs/engine/doctor";
842
+ var DOCTOR_DOCS_ANCHOR = "checks";
843
+ function DOCTOR_DOCS_LINK(check2) {
844
+ return `${DOCTOR_DOCS_URL}?utm_source=ctx_doctor&utm_medium=doctor&utm_content=${check2}#${DOCTOR_DOCS_ANCHOR}`;
845
+ }
846
+ var DOCTOR_DOCS_LABEL = "Docs: ";
847
+ function D3_NO_SETUP_FIX(agent) {
848
+ return `context-mode setup --agents ${agent}`;
849
+ }
850
+ function D5_FIXTURE_FILE_ABSENT(file2) {
851
+ return `hook fixture ${file2} is absent: the round trip needs it`;
852
+ }
853
+ function D5_FIXTURE_PARSE(file2, cause) {
854
+ return `the hook fixture file ${file2} failed to parse: ${cause}`;
855
+ }
856
+ function D5_FIXTURE_AGENT_ABSENT(file2, keys) {
857
+ return `the hook fixture file ${file2} records payloads for ${keys.join(", ") || "zero agents"} only`;
858
+ }
859
+ var DOCTOR_REPORTS_DIR = "reports";
860
+ var DOCTOR_REPORT_FILE_PREFIX = "doctor-";
861
+ var DOCTOR_REPORT_LINE = "Report file: ";
862
+ var DOCTOR_GH_LINE = "File it: ";
863
+ var DOCTOR_URL_LINE = "Or open: ";
864
+ var DOCTOR_GH_NEXT = " --";
865
+ var DOCTOR_NOTE_PREFIXES = Object.freeze([
866
+ DOCTOR_ENV_PREFIX,
867
+ DOCTOR_DOCS_LABEL,
868
+ DOCTOR_REPORT_LINE,
869
+ DOCTOR_GH_LINE,
870
+ DOCTOR_GH_NEXT.trim(),
871
+ DOCTOR_URL_LINE
872
+ ]);
873
+ var ISSUE_REPO_SLUG = "mksglu/context-mode";
874
+ var ISSUE_FORM_FILE = "agent-report.yml";
875
+ var ISSUE_URL_MAX = 8e3;
876
+ var ISSUE_FORM_HEADINGS = Object.freeze([
877
+ "Summary",
878
+ "ctx-report",
879
+ "What happened",
880
+ "Hook errors",
881
+ "Journal rows",
882
+ "Agent config",
883
+ "Expected",
884
+ "Steps",
885
+ "Environment"
886
+ ]);
887
+ var DOCTOR_HOOK_LOG_LINES = 50;
888
+ var DOCTOR_JOURNAL_ROWS = 30;
889
+ var DOCTOR_CONFIG_LINES = 40;
890
+ var DOCTOR_ENV_NAMES = Object.freeze([
891
+ "CODEX_HOME",
892
+ "CLAUDE_CONFIG_DIR",
893
+ "CLAUDE_PLUGIN_ROOT",
894
+ "COPILOT_HOME",
895
+ "KIRO_HOME",
896
+ "OPENCODE_CONFIG_DIR",
897
+ "PI_CODING_AGENT_DIR",
898
+ "XDG_CONFIG_HOME",
899
+ "SHELL"
900
+ ]);
901
+ var DOCTOR_PATH_TOOLS = Object.freeze(["node", "git", "sh"]);
902
+ var DOCTOR_SECRET_WORDS = Object.freeze(["token", "secret", "password", "apikey", "api_key", "authorization", "bearer"]);
903
+ var DOCTOR_MASK = "<masked>";
904
+ var NATIVE_INSTALL = Object.freeze({
905
+ "claude-code": ["claude plugin marketplace add mksglu/context-mode#release", "claude plugin install context-mode@context-mode"],
906
+ codex: ["codex plugin marketplace add mksglu/context-mode@release", "codex plugin add context-mode@context-mode"],
907
+ gemini: ["gemini extensions install https://github.com/mksglu/context-mode --ref release"],
908
+ qwen: ["qwen extensions install https://github.com/mksglu/context-mode:context-mode --ref release"],
909
+ opencode: ["opencode plugin add context-mode@next"],
910
+ pi: ["pi install npm:context-mode@next"],
911
+ "copilot-cli": ["npm i -g context-mode@next", "context-mode setup --agents copilot-cli"],
912
+ vscode: ["npm i -g context-mode@next", "context-mode setup --agents vscode"],
913
+ kiro: ["npm i -g context-mode@next", "context-mode setup --agents kiro"],
914
+ zcode: ["npm i -g context-mode@next", "context-mode setup --agents zcode"]
915
+ });
916
+ var ISSUE_FORM_URL = `https://github.com/${ISSUE_REPO_SLUG}/issues/new?template=${ISSUE_FORM_FILE}`;
917
+ var DOCTOR_GIT_VERSION_TIMEOUT_MS = 5e3;
918
+ var DOCTOR_LOG_TAIL_BYTES = 262144;
812
919
 
813
920
  // src/core/contracts/errors.ts
814
921
  var ERROR_TEXT = Object.freeze({
@@ -1212,8 +1319,8 @@ function decode5(raw) {
1212
1319
  if (event === "SessionStart" && typeof raw.source === "string" && COPILOT_SOURCES[raw.source] !== void 0) ev.source = COPILOT_SOURCES[raw.source];
1213
1320
  if (event === "UserPromptSubmit" && typeof raw.prompt === "string") ev.prompt = raw.prompt;
1214
1321
  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]) };
1322
+ const toolName2 = String(raw[k.tool] ?? "");
1323
+ const tool = { name: toolName2, canonicalName: canonicalName3(toolName2), input: readArgs(raw[k.args]) };
1217
1324
  ev.tool = tool;
1218
1325
  }
1219
1326
  if (event === "PostToolUse") ev.result = readResult3(raw[k.result], native.casing, native.failure);
@@ -1327,9 +1434,9 @@ function decodeCamel(p, name) {
1327
1434
  if (event === "SessionStart" && typeof p.source === "string" && SESSION_SOURCES[p.source] !== void 0) ev.source = SESSION_SOURCES[p.source];
1328
1435
  if (event === "UserPromptSubmit" && typeof p.prompt === "string") ev.prompt = p.prompt;
1329
1436
  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)) };
1437
+ const toolName2 = String(p.toolName ?? "");
1438
+ const canonical = canonicalName4(toolName2);
1439
+ ev.tool = { name: toolName2, canonicalName: canonical, input: policyInput(toolName2, canonical, readArgs2(p.toolArgs)) };
1333
1440
  }
1334
1441
  if (event === "PostToolUse") ev.result = readCamelResult(p.toolResult);
1335
1442
  return ev;
@@ -2180,10 +2287,10 @@ function lexSpan(st, from, inParen, depth, out, bodies) {
2180
2287
  }
2181
2288
  function scan(cmd) {
2182
2289
  const st = { s: cmd, n: cmd.length, end: "complete" };
2183
- const tokens = [];
2290
+ const tokens2 = [];
2184
2291
  const heredocBodies = [];
2185
- lexSpan(st, 0, false, 0, tokens, heredocBodies);
2186
- return { tokens, heredocBodies, end: st.end };
2292
+ lexSpan(st, 0, false, 0, tokens2, heredocBodies);
2293
+ return { tokens: tokens2, heredocBodies, end: st.end };
2187
2294
  }
2188
2295
  function dequote(word) {
2189
2296
  let out = "";
@@ -3627,7 +3734,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
3627
3734
  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
3735
  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
3736
  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.",
3737
+ 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
3738
  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
3739
  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
3740
  });
@@ -4140,8 +4247,8 @@ function firstLine(file2) {
4140
4247
  return line === "" ? null : line;
4141
4248
  }
4142
4249
  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 });
4250
+ const { spawnSync: spawnSync4 } = process.getBuiltinModule("node:child_process");
4251
+ const r = spawnSync4("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
4145
4252
  if (r.error !== void 0 || r.status !== 0) throw new CtxError("NO_GIT_DIR", { path: dir });
4146
4253
  return r.stdout.split("\n").filter((l) => l !== "");
4147
4254
  }
@@ -6719,8 +6826,8 @@ function trigramMatch(q) {
6719
6826
  const words = blankTokens(q);
6720
6827
  const kept = words.filter((w) => !STOPWORDS.has(w.toLowerCase()));
6721
6828
  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);
6829
+ const whole2 = words.join(" ");
6830
+ if (words.length > 1 && [...whole2].length >= 3) parts.add(whole2);
6724
6831
  return [...parts].map((w) => `"${w.replaceAll('"', '""')}"`).join(" OR ");
6725
6832
  }
6726
6833
  function editDistance(a, b, max) {
@@ -7067,15 +7174,15 @@ function indentOf(line) {
7067
7174
  }
7068
7175
  function buildUnits(text) {
7069
7176
  const lines = text.split("\n");
7070
- const stack = [];
7177
+ const stack2 = [];
7071
7178
  const out = [];
7072
7179
  for (let i = 0; i < lines.length; i++) {
7073
7180
  const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
7074
7181
  const indent = indentOf(line);
7075
7182
  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 });
7183
+ while (stack2.length > 0 && stack2[stack2.length - 1].indent >= indent) stack2.pop();
7184
+ out.push({ ord: i, body: [...stack2.map((s) => s.line), line].join("\n") });
7185
+ stack2.push({ indent, line });
7079
7186
  }
7080
7187
  return out;
7081
7188
  }
@@ -7377,7 +7484,7 @@ function chunkText(text, kind, maxBytes = MAX_CHUNK_BYTES) {
7377
7484
  }
7378
7485
  function mdChunks(src, cap, lineCut) {
7379
7486
  const out = [];
7380
- const stack = [];
7487
+ const stack2 = [];
7381
7488
  let title = "";
7382
7489
  let run = [];
7383
7490
  const push2 = (text, bytes5) => {
@@ -7391,9 +7498,9 @@ function mdChunks(src, cap, lineCut) {
7391
7498
  for (const b of lineBlocks(src, true)) {
7392
7499
  if (b.heading !== void 0) {
7393
7500
  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(" > ");
7501
+ while (stack2.length > 0 && stack2[stack2.length - 1].level >= b.heading.level) stack2.pop();
7502
+ stack2.push(b.heading);
7503
+ title = stack2.map((h) => h.text).join(" > ");
7397
7504
  }
7398
7505
  if (b.fence !== void 0 && utf8Bytes(src.slice(b.start, b.end)) > cap) {
7399
7506
  const pieces = fencePieces(src, b, b.fence, cap);
@@ -7626,7 +7733,7 @@ function cutPoint(src, start, end, scratch) {
7626
7733
  const r = encoder.encodeInto(src.slice(start, limit), scratch);
7627
7734
  return { end: start + r.read, written: r.written };
7628
7735
  }
7629
- function merge(src, blocks, join24, cap, lineCut) {
7736
+ function merge(src, blocks, join25, cap, lineCut) {
7630
7737
  const out = [];
7631
7738
  const scratch = new Uint8Array(cap);
7632
7739
  let wide;
@@ -7636,7 +7743,7 @@ function merge(src, blocks, join24, cap, lineCut) {
7636
7743
  out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
7637
7744
  };
7638
7745
  for (const b of blocks) {
7639
- if (cur !== void 0 && !join24) {
7746
+ if (cur !== void 0 && !join25) {
7640
7747
  emit(cur.start, cur.end, curBytes);
7641
7748
  cur = void 0;
7642
7749
  }
@@ -7848,8 +7955,8 @@ function renderRow(i, row5, skewed, named, budget) {
7848
7955
  return body === null ? null : prefix + body;
7849
7956
  }
7850
7957
  function fitRow(row5, skewed, named, budget) {
7851
- const whole = JSON.stringify(row5);
7852
- if (bytes(whole) <= budget) return whole;
7958
+ const whole2 = JSON.stringify(row5);
7959
+ if (bytes(whole2) <= budget) return whole2;
7853
7960
  const own2 = Object.keys(row5);
7854
7961
  const tier = (k) => skewed.includes(k) ? 0 : named.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
7855
7962
  const order = [...own2].sort((a, b) => tier(a) - tier(b) || own2.indexOf(a) - own2.indexOf(b));
@@ -8504,14 +8611,14 @@ function exitCodeOf(text) {
8504
8611
  const first = nl < 0 ? text : text.slice(0, nl);
8505
8612
  if (!first.startsWith(EXIT_CODE_LINE_PREFIX)) return null;
8506
8613
  let n = 0;
8507
- let digits = 0;
8614
+ let digits2 = 0;
8508
8615
  for (const ch of first.slice(EXIT_CODE_LINE_PREFIX.length)) {
8509
8616
  const d = ch.charCodeAt(0) - DIGIT_0;
8510
8617
  if (d < 0 || d > 9) break;
8511
8618
  n = n * 10 + d;
8512
- digits++;
8619
+ digits2++;
8513
8620
  }
8514
- return digits === 0 ? null : n;
8621
+ return digits2 === 0 ? null : n;
8515
8622
  }
8516
8623
  function pathOf(input) {
8517
8624
  for (const k of EDIT_PATH_KEYS) if (typeof input[k] === "string") return input[k];
@@ -19854,9 +19961,9 @@ import { accessSync, constants as fsConstants, statSync as statSync3 } from "nod
19854
19961
  import path from "node:path";
19855
19962
 
19856
19963
  // src/core/sandbox/path-entries.ts
19857
- function pathEntries(value, platform = process.platform, delimiter = platform === "win32" ? ";" : ":") {
19964
+ function pathEntries(value, platform = process.platform, delimiter2 = platform === "win32" ? ";" : ":") {
19858
19965
  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);
19966
+ return value.split(delimiter2).map((e) => win && e.length >= 2 && e.startsWith('"') && e.endsWith('"') ? e.slice(1, -1) : e).filter(Boolean);
19860
19967
  }
19861
19968
 
19862
19969
  // src/core/sandbox/runtimes.ts
@@ -20521,8 +20628,8 @@ var ctxBatch = Object.freeze({
20521
20628
  });
20522
20629
 
20523
20630
  // 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";
20631
+ import { readdirSync as readdirSync5, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20632
+ import { basename as basename4, dirname as dirname7, join as join15 } from "node:path";
20526
20633
 
20527
20634
  // src/core/ops/doctor-config.ts
20528
20635
  import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
@@ -21378,9 +21485,9 @@ var Tokenizer = class {
21378
21485
  }
21379
21486
  NUMBER(cp) {
21380
21487
  const start = this.text[this.tokenStart];
21381
- const sign = start === "+" ? CodePoint.PLUS_SIGN : start === "-" ? CodePoint.DASH : CodePoint.NULL;
21488
+ const sign2 = start === "+" ? CodePoint.PLUS_SIGN : start === "-" ? CodePoint.DASH : CodePoint.NULL;
21382
21489
  if (cp === CodePoint.DIGIT_0) {
21383
- if (sign === CodePoint.NULL) {
21490
+ if (sign2 === CodePoint.NULL) {
21384
21491
  const startPos = this.codePointIterator.start;
21385
21492
  const nextCp$1 = this.nextCode();
21386
21493
  if (isDigit4(nextCp$1)) {
@@ -21419,19 +21526,19 @@ var Tokenizer = class {
21419
21526
  }
21420
21527
  cp = this.nextCode();
21421
21528
  if (cp === CodePoint.LATIN_SMALL_X || cp === CodePoint.LATIN_SMALL_O || cp === CodePoint.LATIN_SMALL_B) {
21422
- if (sign !== CodePoint.NULL) return this.reportParseError("unexpected-char");
21529
+ if (sign2 !== CodePoint.NULL) return this.reportParseError("unexpected-char");
21423
21530
  return cp === CodePoint.LATIN_SMALL_X ? "HEX" : cp === CodePoint.LATIN_SMALL_O ? "OCTAL" : "BINARY";
21424
21531
  }
21425
21532
  if (cp === CodePoint.LATIN_SMALL_E || cp === CodePoint.LATIN_CAPITAL_E) {
21426
21533
  this.data = {
21427
- minus: sign === CodePoint.DASH,
21534
+ minus: sign2 === CodePoint.DASH,
21428
21535
  left: [CodePoint.DIGIT_0]
21429
21536
  };
21430
21537
  return "EXPONENT_RIGHT";
21431
21538
  }
21432
21539
  if (cp === CodePoint.DOT) {
21433
21540
  this.data = {
21434
- minus: sign === CodePoint.DASH,
21541
+ minus: sign2 === CodePoint.DASH,
21435
21542
  absInt: [CodePoint.DIGIT_0]
21436
21543
  };
21437
21544
  return "FRACTIONAL_RIGHT";
@@ -21440,7 +21547,7 @@ var Tokenizer = class {
21440
21547
  return this.back("DATA");
21441
21548
  }
21442
21549
  const { out, nextCp, hasUnderscore } = this.parseDigits(cp, isDigit4);
21443
- if (nextCp === CodePoint.DASH && sign === CodePoint.NULL && !hasUnderscore && out.length === 4) {
21550
+ if (nextCp === CodePoint.DASH && sign2 === CodePoint.NULL && !hasUnderscore && out.length === 4) {
21444
21551
  this.data = {
21445
21552
  hasDate: true,
21446
21553
  year: Number(String.fromCodePoint(...out)),
@@ -21452,7 +21559,7 @@ var Tokenizer = class {
21452
21559
  };
21453
21560
  return "DATE_MONTH";
21454
21561
  }
21455
- if (nextCp === CodePoint.COLON && sign === CodePoint.NULL && !hasUnderscore && out.length === 2) {
21562
+ if (nextCp === CodePoint.COLON && sign2 === CodePoint.NULL && !hasUnderscore && out.length === 2) {
21456
21563
  this.data = {
21457
21564
  hasDate: false,
21458
21565
  year: 0,
@@ -21466,19 +21573,19 @@ var Tokenizer = class {
21466
21573
  }
21467
21574
  if (nextCp === CodePoint.LATIN_SMALL_E || nextCp === CodePoint.LATIN_CAPITAL_E) {
21468
21575
  this.data = {
21469
- minus: sign === CodePoint.DASH,
21576
+ minus: sign2 === CodePoint.DASH,
21470
21577
  left: out
21471
21578
  };
21472
21579
  return "EXPONENT_RIGHT";
21473
21580
  }
21474
21581
  if (nextCp === CodePoint.DOT) {
21475
21582
  this.data = {
21476
- minus: sign === CodePoint.DASH,
21583
+ minus: sign2 === CodePoint.DASH,
21477
21584
  absInt: out
21478
21585
  };
21479
21586
  return "FRACTIONAL_RIGHT";
21480
21587
  }
21481
- this.endToken("Integer", "start", sign === CodePoint.DASH ? String.fromCodePoint(CodePoint.DASH, ...out) : String.fromCodePoint(...out), 10);
21588
+ this.endToken("Integer", "start", sign2 === CodePoint.DASH ? String.fromCodePoint(CodePoint.DASH, ...out) : String.fromCodePoint(...out), 10);
21482
21589
  return this.back("DATA");
21483
21590
  }
21484
21591
  HEX(cp) {
@@ -22974,8 +23081,8 @@ function setTomlText(text, path7, value) {
22974
23081
  if (sameValue(cur, value)) return text;
22975
23082
  const inline = doc.keys.find((k) => k.inline && k.full.length < path7.length && under(path7, k.full));
22976
23083
  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);
23084
+ const whole2 = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
23085
+ return replaceToml(text, doc, inline.full, whole2);
22979
23086
  }
22980
23087
  if (isPlainObject3(cur) && isPlainObject3(value)) {
22981
23088
  const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
@@ -23654,14 +23761,18 @@ function mcpWrong(row5, home, env, worktree) {
23654
23761
  return true;
23655
23762
  }
23656
23763
  }
23764
+ function hookFile(row5, spec, home, env, worktree) {
23765
+ const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
23766
+ const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23767
+ 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);
23768
+ return file2;
23769
+ }
23657
23770
  function hookParts(row5, home, env, worktree) {
23658
23771
  const spec = HOOK_HOST_FILE[row5.id];
23659
23772
  if (spec === null) return [];
23660
23773
  let block;
23661
23774
  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);
23775
+ const file2 = hookFile(row5, spec, home, env, worktree);
23665
23776
  block = hostConfigValueAt(readParsed(row5.id, file2).value, spec.key);
23666
23777
  if (row5.id === "codex") {
23667
23778
  const config2 = readParsed(row5.id, join11(codexDirOf(env, home), CONFIG_TOML_FILE)).value;
@@ -23702,12 +23813,15 @@ function checkHostConfig(row5, env, worktree) {
23702
23813
  const read3 = row5.id === "pi" ? mcpFile(row5, home, env) : null;
23703
23814
  if (parts.length === 0) return read3 === null ? pass("D3") : { ...pass("D3"), detail: read3 };
23704
23815
  const detail = D3_DETAIL(parts);
23705
- return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, DOCTOR_FIX_UPGRADE);
23816
+ const fix = parts.includes(PART_MCP) && parts.includes(PART_HOOKS) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
23817
+ return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, fix);
23706
23818
  }
23707
23819
  function checkV1Leftovers(agent, home, scope = {}) {
23708
23820
  const findings = detectV1(agent, home, scope);
23709
23821
  if (findings.length === 0) return pass("D4");
23710
- return fail2("D4", findings.map((f) => f.reason).join(D4_REASON_JOIN), DOCTOR_FIX_UPGRADE);
23822
+ const detail = findings.map((f) => f.reason).join(D4_REASON_JOIN);
23823
+ if (findings.every((f) => f.reason === V1_REASON.tmpFile)) return { ...pass("D4"), detail };
23824
+ return fail2("D4", detail, DOCTOR_FIX_UPGRADE);
23711
23825
  }
23712
23826
  function parsedOrNull(agent, file2, jsonc) {
23713
23827
  try {
@@ -23726,6 +23840,31 @@ function checkDoubleFire(agent, worktree) {
23726
23840
  const useClaudeHooks = isObject4(vscode) && vscode[VSCODE_CLAUDE_HOOKS_SETTING] === true;
23727
23841
  return hooksOn && useClaudeHooks ? fail2("D5b", D5B_DETAIL, D5B_FIX) : pass("D5b");
23728
23842
  }
23843
+ function configPaths(row5, env, worktree) {
23844
+ const home = homeDirOf(env);
23845
+ if (home === null) return [];
23846
+ const out = [];
23847
+ const mcp = mcpFile(row5, home, env);
23848
+ if (mcp !== null) out.push({ label: "MCP entry", path: mcp });
23849
+ const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23850
+ if (native !== null) out.push({ label: "Codex plugin MCP", path: join11(native, CODEX_PLUGIN_MCP_FILE) });
23851
+ const spec = HOOK_HOST_FILE[row5.id];
23852
+ if (spec !== null) {
23853
+ try {
23854
+ out.push({ label: "hook entries", path: hookFile(row5, spec, home, env, worktree) });
23855
+ } catch (err) {
23856
+ out.push({ label: "hook entries", path: err instanceof Error ? err.message : String(err) });
23857
+ }
23858
+ }
23859
+ if (spec !== null && spec.root === "plugin" || row5.installMode === "marketplace" || row5.installMode === "plugin") {
23860
+ try {
23861
+ out.push({ label: "plugin root", path: resolvePluginRoot(row5, env, worktree) });
23862
+ } catch (err) {
23863
+ out.push({ label: "plugin root", path: err instanceof Error ? err.message : String(err) });
23864
+ }
23865
+ }
23866
+ return out.filter((e, i) => out.findIndex((o) => o.path === e.path) === i);
23867
+ }
23729
23868
 
23730
23869
  // src/core/ops/doctor-db.ts
23731
23870
  import { existsSync as existsSync7 } from "node:fs";
@@ -23868,35 +24007,76 @@ async function npmLatest(url2, tag2, signal, timeoutMs) {
23868
24007
  return { ok: false, cause: fetchCause(err, timeoutMs) };
23869
24008
  }
23870
24009
  }
24010
+ function digits(s) {
24011
+ if (s === "") return false;
24012
+ for (const ch of s) if (ch < "0" || ch > "9") return false;
24013
+ return true;
24014
+ }
24015
+ function parseVersion(v) {
24016
+ const at2 = v.indexOf(D1_PRERELEASE_SEP);
24017
+ const core = (at2 < 0 ? v : v.slice(0, at2)).split(NODE_VERSION_SEP);
24018
+ if (core.length !== 3 || !core.every(digits)) return null;
24019
+ const nums = [Number(core[0]), Number(core[1]), Number(core[2])];
24020
+ if (at2 < 0) return { core: nums, pre: [] };
24021
+ const pre = v.slice(at2 + 1).split(NODE_VERSION_SEP);
24022
+ if (pre[0] === "" || digits(pre[0]) || pre.length > 2) return null;
24023
+ if (pre.length === 1) return { core: nums, pre: [pre[0]] };
24024
+ return digits(pre[1]) ? { core: nums, pre: [pre[0], Number(pre[1])] } : null;
24025
+ }
24026
+ function sign(n) {
24027
+ return n < 0 ? -1 : n > 0 ? 1 : 0;
24028
+ }
24029
+ function compareVersions(a, b) {
24030
+ const x = parseVersion(a);
24031
+ const y = parseVersion(b);
24032
+ if (x === null || y === null) return null;
24033
+ for (let k = 0; k < 3; k++) if (x.core[k] !== y.core[k]) return sign(x.core[k] - y.core[k]);
24034
+ if (x.pre.length === 0 || y.pre.length === 0) return sign(y.pre.length - x.pre.length);
24035
+ if (x.pre[0] !== y.pre[0]) return x.pre[0] < y.pre[0] ? -1 : 1;
24036
+ return sign((x.pre[1] ?? -1) - (y.pre[1] ?? -1));
24037
+ }
24038
+ function highestTag(stdout, tag2) {
24039
+ let best;
24040
+ for (const line of stdout.split("\n")) {
24041
+ const [sha, ref] = line.trim().split(LS_REMOTE_FIELD_SEP);
24042
+ if (sha === void 0 || sha.length !== GIT_SHA_HEX_LEN || ref === void 0 || !ref.startsWith(RELEASE_TAG_REF_PREFIX)) continue;
24043
+ const v = ref.slice(RELEASE_TAG_REF_PREFIX.length);
24044
+ if (parseVersion(v) === null || channelOf(v) !== tag2) continue;
24045
+ if (best === void 0 || compareVersions(v, best) === 1) best = v;
24046
+ }
24047
+ return best;
24048
+ }
24049
+ function versionRow(head, installed, tag2, source, latest, tail) {
24050
+ const cmp = compareVersions(installed, latest) ?? (installed === latest ? 0 : -1);
24051
+ if (cmp === 0) return pass3("D1", head + D1_LATEST_PASS(tag2, source) + tail);
24052
+ if (cmp > 0) return pass3("D1", head + D1_LATEST_AHEAD(tag2, source, latest) + tail);
24053
+ return fail4("D1", head + D1_LATEST_UPDATE(tag2, source, latest) + tail, DOCTOR_FIX_UPGRADE);
24054
+ }
23871
24055
  async function checkVersion(i) {
23872
24056
  if (i.bundleSha === void 0) return unknown3("D1", D1_DEV_BUILD_DETAIL);
23873
24057
  const head = D1_PREFIX(i.version, i.bundleSha) + ": ";
24058
+ if (i.version === void 0) return unknown3("D1", head + D1_LATEST_UNKNOWN + ", " + D1_NO_VERSION, D1_NPM_CHECK_FIX);
24059
+ const tag2 = channelOf(i.version);
23874
24060
  const git3 = findRuntime(GIT_BIN, i.env);
24061
+ const npm = await npmLatest(i.registryUrl, tag2, i.signal, i.timeoutMs);
24062
+ if (npm.ok) return versionRow(head, i.version, tag2, D1_SOURCE_NPM, npm.version, "");
23875
24063
  let cause = D1_GIT_MISSING;
23876
24064
  if (git3 !== null) {
23877
- const r = await runProcess([git3, GIT_LS_REMOTE, RELEASE_REPO_URL, RELEASE_BRANCH], {
24065
+ const r = await runProcess([git3, GIT_LS_REMOTE, ...GIT_LS_REMOTE_TAG_ARGS, RELEASE_REPO_URL, RELEASE_TAG_PATTERN], {
23878
24066
  cwd: i.cwd,
23879
24067
  env: { ...i.env, ...GIT_NO_PROMPT_ENV },
23880
24068
  signal: i.signal,
23881
24069
  timeoutMs: i.timeoutMs
23882
24070
  });
23883
24071
  if (r.exitCode === 0 && r.killed === null) {
23884
- const latest = r.stdout.toString("utf8").split(LS_REMOTE_FIELD_SEP)[0];
23885
- if (latest.length === GIT_SHA_HEX_LEN) {
23886
- return latest === i.bundleSha ? pass3("D1", head + D1_GIT_PASS) : fail4("D1", head + D1_UPDATE_DETAIL, DOCTOR_FIX_UPGRADE);
23887
- }
23888
- cause = D1_GIT_NO_SHA;
24072
+ const latest = highestTag(r.stdout.toString("utf8"), tag2);
24073
+ if (latest !== void 0) return versionRow(head, i.version, tag2, D1_SOURCE_TAGS, latest, D1_CAUSE_JOIN + npm.cause);
24074
+ cause = D1_GIT_NO_TAG(tag2);
23889
24075
  } else {
23890
24076
  cause = gitCause(r, i.timeoutMs);
23891
24077
  }
23892
24078
  }
23893
- const handFix = git3 === null ? D1_NPM_CHECK_FIX : D1_GIT_CHECK_FIX;
23894
- if (i.version === void 0) return unknown3("D1", head + D1_LATEST_UNKNOWN + ", " + cause, handFix);
23895
- const tag2 = channelOf(i.version);
23896
- const npm = await npmLatest(i.registryUrl, tag2, i.signal, i.timeoutMs);
23897
- if (!npm.ok) return unknown3("D1", head + D1_LATEST_UNKNOWN + ", " + cause + D1_CAUSE_JOIN + npm.cause, handFix);
23898
- if (npm.version === i.version) return pass3("D1", head + D1_NPM_PASS(tag2) + D1_CAUSE_JOIN + cause);
23899
- return fail4("D1", head + D1_NPM_UPDATE(tag2, npm.version) + D1_CAUSE_JOIN + cause, DOCTOR_FIX_UPGRADE);
24079
+ return unknown3("D1", head + D1_LATEST_UNKNOWN + ", " + npm.cause + D1_CAUSE_JOIN + cause, git3 === null ? D1_NPM_CHECK_FIX : D1_GIT_CHECK_FIX);
23900
24080
  }
23901
24081
  function numbers(v) {
23902
24082
  const bare2 = v.startsWith(NODE_VERSION_PREFIX) ? v.slice(NODE_VERSION_PREFIX.length) : v;
@@ -24175,16 +24355,19 @@ function isObject5(v) {
24175
24355
  }
24176
24356
  function loadFixture(bundleDir2, agent) {
24177
24357
  const file2 = path6.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
24178
- if (!existsSync10(file2)) return null;
24358
+ if (!existsSync10(file2)) return { cause: D5_FIXTURE_FILE_ABSENT(file2) };
24179
24359
  let all;
24180
24360
  try {
24181
24361
  all = JSON.parse(hostText(readFileSync10(file2, "utf8")));
24182
- } catch {
24183
- return null;
24362
+ } catch (err) {
24363
+ return { cause: D5_FIXTURE_PARSE(file2, err instanceof Error ? err.message : String(err)) };
24184
24364
  }
24185
- if (!isObject5(all) || !Object.hasOwn(all, agent)) return null;
24365
+ if (!isObject5(all)) return { cause: D5_FIXTURE_PARSE(file2, "top level is not an object") };
24366
+ if (!Object.hasOwn(all, agent)) return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": " + D5_FIXTURE_AGENT_ABSENT(file2, Object.keys(all)) };
24186
24367
  const e = all[agent];
24187
- if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload")) return null;
24368
+ if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload")) {
24369
+ return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": the entry lacks an event name or a payload" };
24370
+ }
24188
24371
  return { event: e.event, payload: e.payload };
24189
24372
  }
24190
24373
  function payloadFor(payload, worktree) {
@@ -24238,7 +24421,7 @@ async function checkHookRoundTrip(i) {
24238
24421
  return row("UNKNOWN", D5_CODEX_UNTRUSTED_DETAIL);
24239
24422
  }
24240
24423
  const fixture = loadFixture(i.bundleDir, i.agent);
24241
- if (fixture === null) return row("UNKNOWN", D5_NO_FIXTURE_DETAIL(i.agent));
24424
+ if ("cause" in fixture) return row("UNKNOWN", fixture.cause);
24242
24425
  const now = i.now ?? (() => performance.now());
24243
24426
  const fixed = i.samples === void 0 ? null : Math.max(1, i.samples);
24244
24427
  const maxPairs = fixed ?? D5_MAX_PAIRS;
@@ -24390,8 +24573,13 @@ function envLine(key, value) {
24390
24573
  const typedValue = allowed !== void 0 && allowed.includes(value) ? value : REPORT_INVALID;
24391
24574
  return REPORT_ENV_PREFIX + typedKey + ": " + typedValue;
24392
24575
  }
24576
+ function fixCell(agent, row5) {
24577
+ if (row5.status === "PASS") return "";
24578
+ if (row5.status === "FAIL") return DOCTOR_FAIL_LINE(agent, row5.id, row5.detail, row5.fixCommand ?? "");
24579
+ return row5.fixCommand === void 0 ? "" : "Fix: " + row5.fixCommand;
24580
+ }
24393
24581
  function rowLine(agent, row5) {
24394
- const fix = row5.status === "FAIL" ? DOCTOR_FAIL_LINE(agent, row5.id, row5.detail, row5.fixCommand ?? "") : "";
24582
+ const fix = fixCell(agent, row5);
24395
24583
  return "| " + [row5.id + " " + row5.label, row5.status, row5.detail, fix].join(" | ") + " |";
24396
24584
  }
24397
24585
  function buildReport(input) {
@@ -24421,6 +24609,196 @@ function buildReportHead(input) {
24421
24609
  return lines.concat(tail).join("\n");
24422
24610
  }
24423
24611
 
24612
+ // src/core/ops/doctor-issue.ts
24613
+ import { spawnSync as spawnSync3 } from "node:child_process";
24614
+ import { closeSync, existsSync as existsSync12, fstatSync, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
24615
+ import { delimiter, join as join14 } from "node:path";
24616
+ var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
24617
+ function tildeOf(env) {
24618
+ const home = homeDirOf(env);
24619
+ if (home === null || home === "") return (t) => t;
24620
+ const homes = [home];
24621
+ try {
24622
+ const real2 = realpathSync8.native(home);
24623
+ if (real2 !== home) homes.push(real2);
24624
+ } catch {
24625
+ }
24626
+ homes.sort((a, b) => b.length - a.length);
24627
+ const slash = (rest) => rest.replace(/^[^\s"'`|)>,;]*/, (run) => run.replace(/\\/g, "/"));
24628
+ return (t) => homes.reduce((acc, h) => acc.split(h).map((piece, n) => n === 0 ? piece : slash(piece)).join("~"), t);
24629
+ }
24630
+ function maskLine(line) {
24631
+ const lower = line.toLowerCase();
24632
+ const named = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
24633
+ const token = TOKEN_PREFIXES.some((p) => line.includes(p));
24634
+ if (!named && !token) return line;
24635
+ const at2 = Math.max(line.indexOf(":"), line.indexOf("="));
24636
+ return at2 === -1 ? DOCTOR_MASK : line.slice(0, at2 + 1) + " " + DOCTOR_MASK;
24637
+ }
24638
+ function environmentLine(ctx, adapter, env, version2) {
24639
+ const sha = BUNDLE_SHA === void 0 ? "dev build" : BUNDLE_SHA.slice(0, 7);
24640
+ const client = ctx.clientInfo;
24641
+ const agent = client === void 0 ? adapter.id : client.name === adapter.id ? `${adapter.id} ${client.version}` : `${adapter.id} ${client.version} (client ${client.name})`;
24642
+ const shell = env.SHELL ?? env.ComSpec ?? "sh";
24643
+ return `${DOCTOR_ENV_PREFIX}context-mode ${version2 ?? "source checkout"} (${sha}), agent ${agent}
24644
+ ${DOCTOR_ENV_PREFIX}${process.platform}-${process.arch}, Node ${process.version}, shell ${shell}`;
24645
+ }
24646
+ function gitVersion(env) {
24647
+ const r = spawnSync3("git", ["--version"], { env, encoding: "utf8", timeout: DOCTOR_GIT_VERSION_TIMEOUT_MS, windowsHide: true });
24648
+ if (r.status === 0) return `${r.stdout}`.trim();
24649
+ return `git --version: ${r.error ? r.error.message : `exit ${r.status}`}`;
24650
+ }
24651
+ function onPath(env, tool) {
24652
+ const names = process.platform === "win32" ? [tool + EXE_SUFFIX, tool + ".cmd", tool] : [tool];
24653
+ const out = [];
24654
+ for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
24655
+ if (dir === "") continue;
24656
+ for (const n of names) if (existsSync12(join14(dir, n))) {
24657
+ out.push(join14(dir, n));
24658
+ break;
24659
+ }
24660
+ }
24661
+ return out;
24662
+ }
24663
+ function hookLogTail(env) {
24664
+ const file2 = hookLogPath(env);
24665
+ if (file2 === "" || !existsSync12(file2)) return [`(${file2 || "hook-errors.log"} holds zero lines)`];
24666
+ try {
24667
+ const fd = openSync(file2, "r");
24668
+ try {
24669
+ const size = fstatSync(fd).size;
24670
+ const start = Math.max(0, size - DOCTOR_LOG_TAIL_BYTES);
24671
+ const buf = Buffer.alloc(size - start);
24672
+ readSync(fd, buf, 0, buf.length, start);
24673
+ const lines = buf.toString("utf8").split("\n").filter((l) => l.trim() !== "");
24674
+ if (start > 0) lines.shift();
24675
+ return lines.slice(-DOCTOR_HOOK_LOG_LINES).map(maskLine);
24676
+ } finally {
24677
+ closeSync(fd);
24678
+ }
24679
+ } catch (err) {
24680
+ return [`hook-errors.log read: ${err instanceof Error ? err.message : String(err)}`];
24681
+ }
24682
+ }
24683
+ async function journalRows(ctx) {
24684
+ const head = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
24685
+ if (!existsSync12(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
24686
+ try {
24687
+ const db = await openDb(ctx.project, { readOnly: true });
24688
+ try {
24689
+ 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();
24690
+ const cell5 = (v) => v === null || v === void 0 ? "" : String(v);
24691
+ 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)} |`));
24692
+ } finally {
24693
+ closeDb(db);
24694
+ }
24695
+ } catch (err) {
24696
+ return [`journal read: ${err instanceof Error ? err.message : String(err)}`];
24697
+ }
24698
+ }
24699
+ function agentConfig(adapter, env, worktree) {
24700
+ const home = homeDirOf(env);
24701
+ const files = configPaths(adapter, env, worktree);
24702
+ if (home !== null) {
24703
+ if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join14(claudeDirOf(env, home), SETTINGS_FILE) });
24704
+ if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join14(codexDirOf(env, home), CONFIG_TOML_FILE) });
24705
+ }
24706
+ const out = [];
24707
+ const seen = /* @__PURE__ */ new Set();
24708
+ for (const f of files) {
24709
+ if (seen.has(f.path)) continue;
24710
+ seen.add(f.path);
24711
+ if (!existsSync12(f.path)) {
24712
+ out.push(`${f.label}: ${f.path} (absent)`);
24713
+ continue;
24714
+ }
24715
+ let text = "";
24716
+ try {
24717
+ text = readFileSync12(f.path, "utf8");
24718
+ } catch (err) {
24719
+ out.push(`${f.label}: ${f.path} (read: ${err instanceof Error ? err.message : String(err)})`);
24720
+ continue;
24721
+ }
24722
+ const hit = text.split("\n").filter((l) => l.includes("context-mode") || l.includes("hook.mjs") || adapter.id === "codex" && l.includes("trust"));
24723
+ out.push(`${f.label}: ${f.path} (${hit.length} matching lines)`);
24724
+ for (const l of hit.slice(0, DOCTOR_CONFIG_LINES)) out.push(" " + maskLine(l.trimEnd()));
24725
+ }
24726
+ return out;
24727
+ }
24728
+ function failing(rows) {
24729
+ return rows.filter((r) => r.status === "FAIL");
24730
+ }
24731
+ function issueTitle(agent, rows) {
24732
+ return `ctx_doctor ${agent}: ${failing(rows).map((r) => `${r.id} ${r.label}`).join(", ")} FAIL`;
24733
+ }
24734
+ function summaryOf(agent, rows) {
24735
+ const f = failing(rows)[0];
24736
+ return f === void 0 ? `ctx_doctor ${agent}` : `${f.id} ${f.label} FAIL on ${agent}: ${f.detail}`;
24737
+ }
24738
+ async function buildIssueBody(i) {
24739
+ const tilde = tildeOf(i.env);
24740
+ const agent = i.adapter.id;
24741
+ const install = NATIVE_INSTALL[agent] ?? [];
24742
+ const failRows = i.rows.filter((r) => r.status !== "PASS");
24743
+ const envNames = DOCTOR_ENV_NAMES.map((n) => i.env[n] === void 0 ? `${n} (unset)` : `${n}=${i.env[n]}`);
24744
+ const pathTools = DOCTOR_PATH_TOOLS.map((t) => `PATH holds ${t}: ${onPath(i.env, t).join(", ") || "(absent)"}`);
24745
+ const sections = {
24746
+ "Summary": [summaryOf(agent, i.rows)],
24747
+ "ctx-report": [i.table],
24748
+ "What happened": [
24749
+ "Rows that need a look:",
24750
+ ...failRows.map((r) => `- ${r.id} ${r.label} ${r.status}: ${r.detail}${r.fixCommand ? ` (Fix: ${r.fixCommand})` : ""}`),
24751
+ "Error code and text: <the agent fills this in: the exact error the user saw>"
24752
+ ],
24753
+ "Hook errors": ["hook-errors.log, last " + DOCTOR_HOOK_LOG_LINES + " lines (UTC):", "```", ...hookLogTail(i.env), "```"],
24754
+ "Journal rows": ["events, newest first, last " + DOCTOR_JOURNAL_ROWS + " (bodies stay local):", ...await journalRows(i.ctx)],
24755
+ "Agent config": agentConfig(i.adapter, i.env, i.ctx.project.worktree),
24756
+ "Expected": ["Expected: <the agent fills this in: what should happen, with the byte count>"],
24757
+ "Steps": [
24758
+ "Reproduced: <yes (2 of 2) or 1 of 2>",
24759
+ "Prompt or command: <the agent fills this in: the exact prompt or command>",
24760
+ "Actual: <the agent fills this in: what context-mode did, with the byte count>",
24761
+ "Repro script (fresh HOME, native install for " + agent + "):",
24762
+ "```sh",
24763
+ 'export HOME="$(mktemp -d)"',
24764
+ 'cd "$HOME"',
24765
+ ...install,
24766
+ "<the command or prompt above>",
24767
+ "```"
24768
+ ],
24769
+ "Environment": [
24770
+ i.envLine,
24771
+ `context-mode bundle: ${i.bundleDir}`,
24772
+ `Install route: ${install.join(" && ")}`,
24773
+ `git: ${gitVersion(i.env)}`,
24774
+ ...pathTools,
24775
+ ...envNames,
24776
+ `Project: ${i.ctx.project.worktree} (key ${i.ctx.project.projectKey})`,
24777
+ "Filed by: <your agent name, version, model id>"
24778
+ ]
24779
+ };
24780
+ const out = [];
24781
+ for (const h of ISSUE_FORM_HEADINGS) out.push(`### ${h}`, "", ...sections[h] ?? [], "");
24782
+ return tilde(out.join("\n"));
24783
+ }
24784
+ async function writeIssueReport(i) {
24785
+ const tilde = tildeOf(i.env);
24786
+ const body = await buildIssueBody(i);
24787
+ const dir = join14(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
24788
+ mkdirSync5(dir, { recursive: true });
24789
+ const file2 = join14(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
24790
+ writeFileSync3(file2, body);
24791
+ const shown2 = tilde(file2);
24792
+ const title = issueTitle(i.adapter.id, i.rows);
24793
+ const gh = [`gh issue create --repo ${ISSUE_REPO_SLUG} --label bug \\`, `${DOCTOR_GH_NEXT}title ${JSON.stringify(title)} \\`, `${DOCTOR_GH_NEXT}body-file ${shown2}`];
24794
+ 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))];
24795
+ }
24796
+ function formUrl(title, summary) {
24797
+ const base = `${ISSUE_FORM_URL}&title=${encodeURIComponent(title)}`;
24798
+ const full = `${base}&summary=${encodeURIComponent(summary)}`;
24799
+ return full.length < ISSUE_URL_MAX ? full : base;
24800
+ }
24801
+
24424
24802
  // src/core/tools/doctor.ts
24425
24803
  var ctxDoctorSchema = external_exports.object({}).strict();
24426
24804
  function lineOf2(err) {
@@ -24435,7 +24813,7 @@ async function guard(id2, run) {
24435
24813
  }
24436
24814
  }
24437
24815
  async function codexDb(ctx, adapter) {
24438
- if (adapter.id !== "codex" || !existsSync12(ctx.project.dbPath)) return null;
24816
+ if (adapter.id !== "codex" || !existsSync13(ctx.project.dbPath)) return null;
24439
24817
  try {
24440
24818
  return await openDb(ctx.project, { readOnly: true });
24441
24819
  } catch {
@@ -24465,11 +24843,11 @@ async function hookRow(ctx, adapter, host) {
24465
24843
  }
24466
24844
  }
24467
24845
  function ownServerId(configDir, projectKey) {
24468
- const dir = join14(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24469
- if (!existsSync12(dir)) return "";
24846
+ const dir = join15(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24847
+ if (!existsSync13(dir)) return "";
24470
24848
  for (const name of readdirSync5(dir)) {
24471
24849
  if (!name.endsWith(OWNER_PID_EXT)) continue;
24472
- if (readFileSync12(join14(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
24850
+ if (readFileSync13(join15(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
24473
24851
  }
24474
24852
  return "";
24475
24853
  }
@@ -24514,24 +24892,39 @@ function reportEnv(env) {
24514
24892
  }
24515
24893
  return out;
24516
24894
  }
24517
- async function handler2(_input, ctx) {
24895
+ async function doctorReply(ctx, host) {
24518
24896
  const adapter = getAdapter(ctx.project.agent);
24519
- const host = { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 };
24520
24897
  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 };
24898
+ const failed2 = rows.some((r) => r.status === "FAIL");
24899
+ const command = `context-mode ${failed2 ? "setup" : "doctor"} --agents ${adapter.id}`;
24900
+ const input = { agent: adapter.id, rows, env: reportEnv(host.env), command };
24901
+ const envLine2 = environmentLine(ctx, adapter, host.env, bundleVersion(host.bundleDir));
24902
+ const table3 = buildReport(input);
24903
+ let notes = [];
24904
+ if (failed2) {
24905
+ try {
24906
+ notes = await writeIssueReport({ ctx, adapter, env: host.env, bundleDir: host.bundleDir, rows, envLine: envLine2, table: table3 });
24907
+ } catch (err) {
24908
+ notes = [`Report file: ${lineOf2(err)}`];
24909
+ }
24910
+ }
24911
+ const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
24912
+ const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
24913
+ const whole2 = [envLine2, table3, ...docs, ...notes].join("\n");
24914
+ const bytes5 = Buffer.byteLength(whole2, "utf8");
24915
+ if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
24526
24916
  const db = await openDb(ctx.project);
24527
24917
  try {
24528
- indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole, "text");
24918
+ indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
24529
24919
  } finally {
24530
24920
  closeDb(db);
24531
24921
  }
24532
- const text = buildReportHead(input);
24922
+ const text = [envLine2, buildReportHead(input), ...docs, ...notes].join("\n");
24533
24923
  return { text, isError: false, sandboxBytes: bytes5 };
24534
24924
  }
24925
+ async function handler2(_input, ctx) {
24926
+ return doctorReply(ctx, { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 });
24927
+ }
24535
24928
  var ctxDoctor = Object.freeze({
24536
24929
  name: "ctx_doctor",
24537
24930
  schema: ctxDoctorSchema,
@@ -24542,9 +24935,9 @@ var ctxDoctor = Object.freeze({
24542
24935
  });
24543
24936
 
24544
24937
  // src/core/tools/execute.ts
24545
- import { existsSync as existsSync13, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
24938
+ import { existsSync as existsSync14, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "node:fs";
24546
24939
  import { tmpdir as tmpdir2 } from "node:os";
24547
- import { dirname as dirname8, join as join15, parse as parse3, resolve as resolve6 } from "node:path";
24940
+ import { dirname as dirname8, join as join16, parse as parse3, resolve as resolve6 } from "node:path";
24548
24941
 
24549
24942
  // src/core/sandbox/win-build.ts
24550
24943
  var SEPARATORS2 = ";&|(\n";
@@ -24628,7 +25021,7 @@ function schemaLine(issue2) {
24628
25021
  }
24629
25022
  function fileError(given, abs, root) {
24630
25023
  let dir = abs;
24631
- while (!existsSync13(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
25024
+ while (!existsSync14(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
24632
25025
  if (isInside(root, dir)) return null;
24633
25026
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
24634
25027
  }
@@ -24709,9 +25102,9 @@ async function handler3(raw, ctx) {
24709
25102
  if (takesDashC(input.language, runtime)) {
24710
25103
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
24711
25104
  } 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");
25105
+ tmpDir = mkdtempSync(join16(tmpdir2(), TMP_PREFIX));
25106
+ const file2 = join16(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
25107
+ writeFileSync4(file2, scriptText(input.language, input.code), "utf8");
24715
25108
  argv = scriptArgv(input.language, runtime, file2);
24716
25109
  }
24717
25110
  if (input.background === true) {
@@ -24745,21 +25138,21 @@ var ctxExecute = {
24745
25138
  };
24746
25139
 
24747
25140
  // 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";
25141
+ import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as statSync7 } from "node:fs";
25142
+ import { dirname as dirname9, extname, join as join18, relative as relative3, resolve as resolve7 } from "node:path";
24750
25143
 
24751
25144
  // 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";
25145
+ import { readdirSync as readdirSync6, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync6 } from "node:fs";
25146
+ import { join as join17 } from "node:path";
24754
25147
  var GITIGNORE = ".gitignore";
24755
25148
  var GIT_DIR = ".git";
24756
25149
  function walkDir(root, containmentRoot) {
24757
- const real2 = realpathSync8(root);
25150
+ const real2 = realpathSync9(root);
24758
25151
  if (!isInside(containmentRoot, real2)) throw new CtxError("OUTSIDE_ROOT", { p: root, root: containmentRoot });
24759
25152
  const found = [];
24760
25153
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
24761
25154
  found.sort(compareFound);
24762
- return found.map((f) => ({ absPath: f.absPath, relPath: join16(...f.dir, f.name) }));
25155
+ return found.map((f) => ({ absPath: f.absPath, relPath: join17(...f.dir, f.name) }));
24763
25156
  }
24764
25157
  function visit(abs, rel, parent, contain, seen, found) {
24765
25158
  let entries;
@@ -24768,17 +25161,17 @@ function visit(abs, rel, parent, contain, seen, found) {
24768
25161
  } catch {
24769
25162
  return;
24770
25163
  }
24771
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join16(abs, GITIGNORE), rel)) : parent;
25164
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join17(abs, GITIGNORE), rel)) : parent;
24772
25165
  for (const e of entries) {
24773
25166
  if (e.name === GIT_DIR) continue;
24774
- const path7 = join16(abs, e.name);
25167
+ const path7 = join17(abs, e.name);
24775
25168
  let isDir = e.isDirectory();
24776
25169
  let isFile = e.isFile();
24777
25170
  let target = path7;
24778
25171
  if (e.isSymbolicLink()) {
24779
25172
  let resolved;
24780
25173
  try {
24781
- resolved = realpathSync8(path7);
25174
+ resolved = realpathSync9(path7);
24782
25175
  } catch {
24783
25176
  continue;
24784
25177
  }
@@ -24793,7 +25186,7 @@ function visit(abs, rel, parent, contain, seen, found) {
24793
25186
  if (isFile) {
24794
25187
  found.push({ dir: rel, name: e.name, absPath: path7 });
24795
25188
  } else if (isDir) {
24796
- const key = e.isSymbolicLink() ? target : realpathSync8(path7);
25189
+ const key = e.isSymbolicLink() ? target : realpathSync9(path7);
24797
25190
  if (seen.has(key)) continue;
24798
25191
  seen.add(key);
24799
25192
  visit(path7, segs, rules, contain, seen, found);
@@ -24811,7 +25204,7 @@ function compareFound(a, b) {
24811
25204
  function readRules(file2, base) {
24812
25205
  let body;
24813
25206
  try {
24814
- body = readFileSync13(file2, "utf8");
25207
+ body = readFileSync14(file2, "utf8");
24815
25208
  } catch {
24816
25209
  return [];
24817
25210
  }
@@ -28894,14 +29287,14 @@ function kindOfType(contentType) {
28894
29287
  }
28895
29288
  function readUtf8(absPath) {
28896
29289
  try {
28897
- return utf8.decode(readFileSync14(absPath));
29290
+ return utf8.decode(readFileSync15(absPath));
28898
29291
  } catch {
28899
29292
  return void 0;
28900
29293
  }
28901
29294
  }
28902
29295
  function missingOrOutside(given, abs, root) {
28903
29296
  let dir = abs;
28904
- while (!existsSync14(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
29297
+ while (!existsSync15(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
28905
29298
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
28906
29299
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
28907
29300
  }
@@ -28912,7 +29305,7 @@ function pathItems(input, project) {
28912
29305
  if (statSync7(abs).isDirectory()) {
28913
29306
  return walkDir(abs, project.containmentRoot).map((f) => ({
28914
29307
  sourceKind: "path",
28915
- label: pathLabel(join17(base, f.relPath)),
29308
+ label: pathLabel(join18(base, f.relPath)),
28916
29309
  kind: kindOfPath(f.relPath),
28917
29310
  read: () => readUtf8(f.absPath)
28918
29311
  }));
@@ -29119,6 +29512,43 @@ var KINDS = "SELECT kind, COALESCE(SUM(session_id = ?), 0) AS s, COUNT(*) AS p F
29119
29512
  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
29513
  var SPAN = "SELECT COALESCE(MAX(created_at) - MIN(created_at), 0) AS span FROM events WHERE session_id = ? AND kind <> 'cost'";
29121
29514
  var SOURCES = "SELECT COUNT(*) AS n, COALESCE(SUM(chunk_count), 0) AS chunks, COALESCE(SUM(bytes_total), 0) AS bytes FROM sources";
29515
+ var HOST = "tool NOT LIKE 'ctx\\_%' ESCAPE '\\'";
29516
+ var REPLACED = `SELECT COUNT(*) AS n FROM events WHERE ${CALLS} AND ${HOST} AND returned_bytes < sandbox_bytes`;
29517
+ var RUNS = "FROM sources WHERE substr(label, 1, ?) = ?";
29518
+ var REDIRECTED = `SELECT COUNT(*) AS n, COALESCE(MAX(created_ts), 0) AS last ${RUNS}`;
29519
+ var LAST = `SELECT COALESCE(MAX(created_at), 0) AS last FROM events WHERE ${CALLS}`;
29520
+ 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`;
29521
+ 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`;
29522
+ 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}`;
29523
+ function wayOf(tool) {
29524
+ if (STATS_INDEX_TOOLS.includes(tool)) return "index";
29525
+ return tool.startsWith("ctx_") ? "sandbox" : "replace";
29526
+ }
29527
+ function readWeek(raw, lastMs) {
29528
+ const last2 = Math.floor(lastMs / MS_PER_DAY);
29529
+ const first = last2 - STATS_DAYS + 1;
29530
+ const days = Array.from({ length: STATS_DAYS }, (_, i) => ({
29531
+ day: first + i,
29532
+ calls: 0,
29533
+ ways: { sandbox: 0, index: 0, redirect: 0, replace: 0 }
29534
+ }));
29535
+ const net = /* @__PURE__ */ new Map();
29536
+ for (const r of raw.prepare(WEEK).all(first * MS_PER_DAY)) {
29537
+ const d = days[Number(r.day) - first];
29538
+ if (d === void 0) continue;
29539
+ d.calls += Number(r.calls);
29540
+ const key = `${d.day}:${wayOf(String(r.tool))}`;
29541
+ net.set(key, (net.get(key) ?? 0) + Number(r.produced) - Number(r.returned));
29542
+ }
29543
+ for (const d of days) for (const [way] of STATS_WAYS) d.ways[way] = Math.max(0, net.get(`${d.day}:${way}`) ?? 0);
29544
+ for (const r of raw.prepare(WEEK_RUNS).all(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX, first * MS_PER_DAY)) {
29545
+ const d = days[Number(r.day) - first];
29546
+ if (d === void 0) continue;
29547
+ d.calls += Number(r.calls);
29548
+ d.ways.redirect += Number(r.saved);
29549
+ }
29550
+ return days;
29551
+ }
29122
29552
  var EMPTY5 = Object.freeze({ calls: 0, produced: 0, returned: 0, saved: 0 });
29123
29553
  function totals(r) {
29124
29554
  const produced = Number(r.produced);
@@ -29133,6 +29563,8 @@ function readFacts(raw, sessionId) {
29133
29563
  const meta = raw.prepare(META).get();
29134
29564
  const span2 = Number(raw.prepare(SPAN).get(sessionId).span);
29135
29565
  const src = raw.prepare(SOURCES).get();
29566
+ const runs = raw.prepare(REDIRECTED).get(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX);
29567
+ const last2 = Math.max(Number(raw.prepare(LAST).get().last), Number(runs.last));
29136
29568
  const pages = raw.prepare("PRAGMA page_count").get();
29137
29569
  const size = raw.prepare("PRAGMA page_size").get();
29138
29570
  return {
@@ -29144,7 +29576,11 @@ function readFacts(raw, sessionId) {
29144
29576
  agents: Number(meta.agents),
29145
29577
  days: Number(meta.days),
29146
29578
  sources: { count: Number(src.n), chunks: Number(src.chunks), bytes: Number(src.bytes) },
29147
- dbBytes: Number(pages.page_count) * Number(size.page_size)
29579
+ dbBytes: Number(pages.page_count) * Number(size.page_size),
29580
+ top: raw.prepare(TOP).all().map((r) => ({ name: String(r.tool), ...totals(r) })),
29581
+ replaced: Number(raw.prepare(REPLACED).get().n),
29582
+ redirected: Number(runs.n),
29583
+ week: readWeek(raw, last2)
29148
29584
  };
29149
29585
  }
29150
29586
  function sum(groups) {
@@ -29175,6 +29611,7 @@ function count(n) {
29175
29611
  return n < STATS_MILLION ? int2(n) : (n / STATS_MILLION).toFixed(1) + "M";
29176
29612
  }
29177
29613
  function bytes4(n) {
29614
+ if (n < 0) return "-" + bytes4(-n);
29178
29615
  if (n < STATS_KIB) return int2(n) + " B";
29179
29616
  let v = n / STATS_KIB;
29180
29617
  let u = 0;
@@ -29207,17 +29644,105 @@ function plural(n, word) {
29207
29644
  }
29208
29645
  function table2(title, rows) {
29209
29646
  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);
29647
+ 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
29648
  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
29649
  }
29213
29650
  function bySaved(a, b) {
29214
29651
  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
29652
  }
29653
+ function toolName(tool) {
29654
+ return tool.startsWith("ctx_") ? tool : "hook " + tool;
29655
+ }
29656
+ function joinIndex(tools) {
29657
+ const idx = tools.filter((t2) => STATS_INDEX_TOOLS.includes(t2.name));
29658
+ if (idx.length <= 1) return tools;
29659
+ const t = sum(idx);
29660
+ const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: t.produced - t.returned };
29661
+ return [...tools.filter((x) => !idx.includes(x)), one];
29662
+ }
29216
29663
  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) }];
29664
+ const named = joinIndex(tools.map((t) => ({ ...t, saved: t.produced - t.returned }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
29665
+ const zero = named.filter((t) => t.saved <= 0);
29666
+ const fold2 = zero.length > 1 ? zero : [];
29667
+ const keep = named.filter((t) => !fold2.includes(t));
29668
+ const room = fold2.length > 0 ? STATS_MAX_TOOL_ROWS - 1 : STATS_MAX_TOOL_ROWS;
29669
+ const over = keep.length > room;
29670
+ const shown2 = over ? keep.slice(0, STATS_MAX_TOOL_ROWS - 1) : keep;
29671
+ const rest = over ? [...keep.slice(STATS_MAX_TOOL_ROWS - 1), ...fold2] : fold2;
29672
+ return rest.length === 0 ? shown2 : [...shown2, { name: `other (${plural(rest.length, "tool")})`, ...sum(rest) }];
29673
+ }
29674
+ var TOKEN_UNITS = ["K", "M", "B", "T"];
29675
+ function whole(v) {
29676
+ return v >= STATS_WHOLE_FROM ? int2(v) : v.toFixed(1);
29677
+ }
29678
+ function tokens(n) {
29679
+ if (n < STATS_THOUSAND) return int2(n);
29680
+ let v = n / STATS_THOUSAND;
29681
+ let u = 0;
29682
+ while (v >= STATS_THOUSAND && u < TOKEN_UNITS.length - 1) {
29683
+ v /= STATS_THOUSAND;
29684
+ u++;
29685
+ }
29686
+ return whole(v) + TOKEN_UNITS[u];
29687
+ }
29688
+ function windowLine(saved) {
29689
+ const t = saved / STATS_BYTES_PER_TOKEN;
29690
+ const share = t / STATS_WINDOW_TOKENS;
29691
+ const win = `a ${tokens(STATS_WINDOW_TOKENS)} window`;
29692
+ const head = ` about ${tokens(t)} tokens kept out`;
29693
+ if (share >= 1) return `${head}, ${whole(share)} times ${win}`;
29694
+ const p = share * PERCENT_SCALE;
29695
+ return p * STATS_WHOLE_FROM < 1 ? head : `${head}, ${whole(p)}% of ${win}`;
29696
+ }
29697
+ function ymd(day) {
29698
+ return new Date(day * MS_PER_DAY).toISOString().slice(0, "yyyy-mm-dd".length);
29699
+ }
29700
+ function mmdd(day) {
29701
+ return ymd(day).slice("yyyy-".length);
29702
+ }
29703
+ function stack(parts, max, width) {
29704
+ let total = 0;
29705
+ let at2 = 0;
29706
+ let out = "";
29707
+ parts.forEach((v, i) => {
29708
+ total += v;
29709
+ const end = max <= 0 ? 0 : Math.round(total / max * width);
29710
+ if (end > at2) {
29711
+ out += STATS_WAYS[i][1].repeat(end - at2);
29712
+ at2 = end;
29713
+ }
29714
+ });
29715
+ if (out === "" && total > 0) out = STATS_WAYS[parts.indexOf(Math.max(...parts))][1];
29716
+ return out;
29717
+ }
29718
+ function cards(cells) {
29719
+ return (" " + cells.map((c) => c.padEnd(STATS_CARD_W)).join("")).trimEnd();
29720
+ }
29721
+ function lastDays(week, allCalls) {
29722
+ const saved = week.map((d) => STATS_WAYS.reduce((t, [w]) => t + d.ways[w], 0));
29723
+ const all = saved.reduce((a, b) => a + b, 0);
29724
+ const calls = week.reduce((a, d) => a + d.calls, 0);
29725
+ const max = Math.max(0, ...saved);
29726
+ const head = `Last ${STATS_DAYS} days of use \xB7 ${ymd(week[0].day)} to ${ymd(week[week.length - 1].day)}`;
29727
+ const card = calls < allCalls ? [
29728
+ cards(["Kept out", "Tokens kept out", "Calls", "Kept out per call"]),
29729
+ cards([bytes4(all), "about " + tokens(all / STATS_BYTES_PER_TOKEN), count(calls), bytes4(calls > 0 ? all / calls : 0)]),
29730
+ ""
29731
+ ] : [];
29732
+ return [
29733
+ head,
29734
+ ...card,
29735
+ ...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)] : []),
29736
+ " " + STATS_WAYS.map(([, ch, name]) => `${ch} ${name}`).join(" "),
29737
+ ""
29738
+ ];
29739
+ }
29740
+ function hookLine(redirected, replaced) {
29741
+ const all = redirected + replaced;
29742
+ if (all === 0) return [];
29743
+ const parts = [...redirected > 0 ? [`${int2(redirected)} sent to the sandbox`] : [], ...replaced > 0 ? [`${int2(replaced)} cut down`] : []];
29744
+ const what = plural(all, "large output");
29745
+ return [parts.length === 1 ? ` Project hooks: ${what} ${parts[0].replace(/^[\d,]+ /, "")}` : ` Project hooks: ${what} kept out \xB7 ${parts.join(", ")}`];
29221
29746
  }
29222
29747
  function fit(line) {
29223
29748
  const chars = [...line];
@@ -29234,20 +29759,30 @@ function report(f, sessionId, agent) {
29234
29759
  const lines = [
29235
29760
  ...head,
29236
29761
  `${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
29762
+ ` ${bytes4(focus.produced)} became ${bytes4(focus.returned)}: ${bytes4(focus.saved)} kept out (${pct(focus)})`,
29237
29763
  " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.produced).padStart(NUM_W),
29238
29764
  " " + "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`,
29765
+ ...focus.saved > 0 ? [windowLine(focus.saved), STATS_TOKEN_NOTE] : [],
29766
+ ...hookLine(f.redirected, f.replaced),
29240
29767
  "",
29241
- ...table2("Scope", [{ name: "session", ...session }, { name: "project", ...project }, { name: "all-time", ...project }]),
29768
+ ...lastDays(f.week, project.calls + f.redirected),
29769
+ // D-STATS-FIX-1 (5): one DB per project holds every session of it, so project and all-time are one row.
29770
+ "By scope",
29771
+ ...table2("Scope", [{ name: "session", ...session }, { name: "project (all-time)", ...project }]),
29242
29772
  "",
29243
- "Where the savings came from (this project)",
29773
+ "By tool (this project)",
29244
29774
  ...table2("Tool", toolRows(f.tools)),
29245
- ""
29775
+ "",
29776
+ ...f.top.length > 0 ? [
29777
+ "Largest single outputs (made \u2192 sent to the chat)",
29778
+ ...f.top.map((t) => " " + label(toolName(t.name)) + bytes4(t.produced).padStart(NUM_W) + " \u2192 " + bytes4(t.returned).padStart(NUM_W)),
29779
+ ""
29780
+ ] : []
29246
29781
  ];
29247
29782
  const agents = /* @__PURE__ */ new Map();
29248
29783
  for (const g of f.groups) agents.set(g.agent, sum([agents.get(g.agent) ?? EMPTY5, g]));
29249
29784
  if (!agents.has(agent)) agents.set(agent, EMPTY5);
29250
- lines.push(...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29785
+ lines.push("By agent (this project)", ...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29251
29786
  const maxKind = Math.max(0, ...[...f.kinds.values()].map((k) => k.project));
29252
29787
  lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + "Session".padStart(STATS_KIND_W) + "Project".padStart(STATS_KIND_W));
29253
29788
  for (const [kind, name] of STATS_KIND_LABELS) {
@@ -29256,9 +29791,12 @@ function report(f, sessionId, agent) {
29256
29791
  }
29257
29792
  lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
29258
29793
  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`,
29794
+ " " + "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
29795
  " " + "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)}`
29796
+ " " + "Sessions".padEnd(LABEL_W) + `${int2(f.sessions)} \xB7 agents ${int2(f.agents)} \xB7 active days ${int2(f.days)}`,
29797
+ "",
29798
+ STATS_FOOTER_URL,
29799
+ "github.com/" + ISSUE_REPO_SLUG
29262
29800
  );
29263
29801
  return lines.map(fit).join("\n");
29264
29802
  }
@@ -29296,28 +29834,28 @@ var ctxStats = Object.freeze({
29296
29834
  });
29297
29835
 
29298
29836
  // 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";
29837
+ import { existsSync as existsSync21, realpathSync as realpathSync10, rmSync as rmSync9 } from "node:fs";
29838
+ import { basename as basename6, dirname as dirname11, join as join24 } from "node:path";
29301
29839
 
29302
29840
  // 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";
29841
+ import { copyFileSync, existsSync as existsSync16, mkdirSync as mkdirSync6, writeFileSync as writeFileSync5 } from "node:fs";
29842
+ import { dirname as dirname10, join as join19 } from "node:path";
29305
29843
  function defaultWrite(file2, text) {
29306
- writeFileSync4(file2, text, "utf8");
29844
+ writeFileSync5(file2, text, "utf8");
29307
29845
  }
29308
29846
  function hostConfigPath(agent, home, env) {
29309
29847
  const own2 = OWN_MCP_ENTRY[agent];
29310
29848
  if (own2 !== void 0) return ownMcpFileOf(agent, own2.file, env, home);
29311
29849
  switch (agent) {
29312
29850
  case "opencode":
29313
- return join18(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29851
+ return join19(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29314
29852
  // D-WIN-OPENCODE-DIR-1
29315
29853
  case "pi":
29316
- return join18(piAgentDirOf(env, home), SETTINGS_FILE);
29854
+ return join19(piAgentDirOf(env, home), SETTINGS_FILE);
29317
29855
  case "copilot-cli":
29318
29856
  return null;
29319
29857
  default:
29320
- return join18(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29858
+ return join19(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29321
29859
  }
29322
29860
  }
29323
29861
  function cell3(value) {
@@ -29329,8 +29867,8 @@ function toRow(file2, edit) {
29329
29867
  function writeWithRollback(file2, text, write2, atomic) {
29330
29868
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
29331
29869
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
29332
- const had = existsSync15(file2);
29333
- mkdirSync5(dirname10(file2), { recursive: true });
29870
+ const had = existsSync16(file2);
29871
+ mkdirSync6(dirname10(file2), { recursive: true });
29334
29872
  if (had) copyFileSync(file2, trash);
29335
29873
  try {
29336
29874
  write2(tmp, text);
@@ -29359,7 +29897,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
29359
29897
  if (requested === null) return [];
29360
29898
  const current = readHostConfig(row5.id, requested);
29361
29899
  const result = mergeOwnEntries(row5.id, current.text, current.format, row5);
29362
- const exists = existsSync15(current.path);
29900
+ const exists = existsSync16(current.path);
29363
29901
  if (exists && result.text === current.text) return [];
29364
29902
  const text = result.text === "" && current.format !== "toml" ? JSON.stringify({}) : result.text;
29365
29903
  writeWithRollback(current.path, current.layout === void 0 ? text : withLayout(text, current.layout), opts.write ?? defaultWrite, opts.atomic ?? {});
@@ -29367,8 +29905,8 @@ function regenerateHostConfig(row5, home, opts = {}) {
29367
29905
  }
29368
29906
 
29369
29907
  // 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";
29908
+ import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
29909
+ import { basename as basename5, join as join20, win32 as win322 } from "node:path";
29372
29910
  function linkTarget(path7, win) {
29373
29911
  if (!isLink(path7)) return null;
29374
29912
  const target = readlinkSync(path7);
@@ -29387,11 +29925,11 @@ function settleLinks(link, tmp, old, opts) {
29387
29925
  else renameWithRetry(old, link, opts);
29388
29926
  }
29389
29927
  function swapPluginCurrent(agentDir, sha, opts = {}) {
29390
- const next = join19(agentDir, sha);
29391
- if (!existsSync16(next) || !lstatSync(next).isDirectory()) {
29928
+ const next = join20(agentDir, sha);
29929
+ if (!existsSync17(next) || !lstatSync(next).isDirectory()) {
29392
29930
  throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
29393
29931
  }
29394
- const link = join19(agentDir, PLUGIN_CURRENT_LINK);
29932
+ const link = join20(agentDir, PLUGIN_CURRENT_LINK);
29395
29933
  const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
29396
29934
  const old = link + PLUGIN_LINK_OLD_SUFFIX;
29397
29935
  settleLinks(link, tmp, old, opts);
@@ -29406,15 +29944,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
29406
29944
  if (before !== null) unlinkSync2(old);
29407
29945
  const keep = /* @__PURE__ */ new Set([sha]);
29408
29946
  if (before !== null) keep.add(before);
29409
- const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join19(agentDir, name));
29947
+ const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join20(agentDir, name));
29410
29948
  for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
29411
- const previous = before !== null && existsSync16(join19(agentDir, before)) ? join19(agentDir, before) : null;
29949
+ const previous = before !== null && existsSync17(join20(agentDir, before)) ? join20(agentDir, before) : null;
29412
29950
  return { current: next, previous, removed };
29413
29951
  }
29414
29952
 
29415
29953
  // 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";
29954
+ import { existsSync as existsSync18, mkdirSync as mkdirSync7, rmSync as rmSync6 } from "node:fs";
29955
+ import { join as join21 } from "node:path";
29418
29956
  function failed(r) {
29419
29957
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
29420
29958
  const status = r.killed ?? String(r.exitCode);
@@ -29426,9 +29964,9 @@ async function git2(bin, args, cwd, env, signal) {
29426
29964
  return r.stdout.toString().trim();
29427
29965
  }
29428
29966
  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);
29967
+ const agentDir = join21(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
29968
+ mkdirSync7(agentDir, { recursive: true });
29969
+ const fetchDir = join21(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29432
29970
  rmSync6(fetchDir, { recursive: true, force: true });
29433
29971
  const gitBin = findRuntime(GIT_BIN, env);
29434
29972
  if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -29436,8 +29974,8 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
29436
29974
  try {
29437
29975
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url2, fetchDir], agentDir, childEnv, signal);
29438
29976
  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 });
29977
+ const dir = join21(agentDir, sha);
29978
+ if (existsSync18(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29441
29979
  else renameWithRetry(fetchDir, dir, opts);
29442
29980
  return { sha, dir };
29443
29981
  } catch (e) {
@@ -29447,15 +29985,15 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
29447
29985
  }
29448
29986
 
29449
29987
  // 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";
29988
+ import { existsSync as existsSync19, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
29989
+ import { join as join22 } from "node:path";
29452
29990
  function row2(area, before, after) {
29453
29991
  return { area, before, after };
29454
29992
  }
29455
29993
  function stopServers(configDir, projectKey) {
29456
29994
  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");
29995
+ const dir = join22(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
29996
+ for (const serverId of stopped) writeFileSync6(join22(dir, serverId + OWNER_STOP_EXT), "", "utf8");
29459
29997
  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
29998
  }
29461
29999
  function rootOrNull(adapter, env) {
@@ -29473,15 +30011,15 @@ function removeCache(adapter, env, configDir) {
29473
30011
  const root = rootOrNull(adapter, env);
29474
30012
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29475
30013
  if (adapter.installMode === "marketplace") {
29476
- const cache = join21(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
30014
+ const cache = join22(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
29477
30015
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
29478
30016
  }
29479
30017
  rmSync7(root, { recursive: true, force: true });
29480
30018
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
29481
30019
  }
29482
30020
  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);
30021
+ const agentDir = join22(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
30022
+ if (!existsSync19(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29485
30023
  rmSync7(agentDir, { recursive: true, force: true });
29486
30024
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
29487
30025
  }
@@ -29526,7 +30064,7 @@ function ownEntries(agent, env) {
29526
30064
  }
29527
30065
  if (agent === "opencode") {
29528
30066
  return [{
29529
- file: join21(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
30067
+ file: join22(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
29530
30068
  // D-WIN-OPENCODE-DIR-1
29531
30069
  key: OPENCODE_PLUGIN_KEY,
29532
30070
  shown: OPENCODE_PLUGIN_KEY,
@@ -29537,7 +30075,7 @@ function ownEntries(agent, env) {
29537
30075
  if (agent === "pi") {
29538
30076
  const agentDir = piAgentDirOf(env, home);
29539
30077
  return [{
29540
- file: join21(agentDir, SETTINGS_FILE),
30078
+ file: join22(agentDir, SETTINGS_FILE),
29541
30079
  key: PI_PACKAGES_KEY,
29542
30080
  shown: PI_PACKAGES_KEY,
29543
30081
  has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
@@ -29559,12 +30097,12 @@ function removeOwnEntries(agent, env) {
29559
30097
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
29560
30098
  }
29561
30099
  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);
30100
+ const projects = join22(configDir, PROJECTS_DIR_NAME);
30101
+ const dir = join22(projects, projectKey);
30102
+ if (!existsSync19(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
29565
30103
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
29566
30104
  for (const name of readdirSync8(dir)) {
29567
- if (name !== OWNERS_DIR_NAME) rmSync7(join21(dir, name), { recursive: true, force: true });
30105
+ if (name !== OWNERS_DIR_NAME) rmSync7(join22(dir, name), { recursive: true, force: true });
29568
30106
  }
29569
30107
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
29570
30108
  }
@@ -29572,12 +30110,12 @@ function runUninstall(input) {
29572
30110
  const configDir = resolveConfigDir(input.env);
29573
30111
  const stop = stopServers(configDir, input.project.projectKey);
29574
30112
  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));
30113
+ 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
30114
  return { rows, stopped: stop.stopped };
29577
30115
  }
29578
30116
 
29579
30117
  // src/core/ops/v1-remove.ts
29580
- import { copyFileSync as copyFileSync2, existsSync as existsSync19, readFileSync as readFileSync15, rmSync as rmSync8 } from "node:fs";
30118
+ import { copyFileSync as copyFileSync2, existsSync as existsSync20, readFileSync as readFileSync16, rmSync as rmSync8 } from "node:fs";
29581
30119
  var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
29582
30120
  var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
29583
30121
  var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
@@ -29621,8 +30159,8 @@ function locate(doc, path7) {
29621
30159
  return null;
29622
30160
  }
29623
30161
  function stripJsonEntries(agent, file2, findings, kept, undo) {
29624
- const layout = hostLayout(readFileSync15(file2, "utf8"));
29625
- const text = hostText(readFileSync15(file2, "utf8"));
30162
+ const layout = hostLayout(readFileSync16(file2, "utf8"));
30163
+ const text = hostText(readFileSync16(file2, "utf8"));
29626
30164
  const doc = parseHostConfig(agent, file2, text, "jsonc");
29627
30165
  const hit = /* @__PURE__ */ new Set();
29628
30166
  const byContainer = /* @__PURE__ */ new Map();
@@ -29658,19 +30196,19 @@ function removeV1(agent, findings) {
29658
30196
  for (const f of findings) {
29659
30197
  if (UPGRADE_REPORT_ONLY_REASONS.includes(f.reason)) done.set(f, UPGRADE_REPORT_ONLY);
29660
30198
  else if (f.path === "") {
29661
- if (existsSync19(f.file)) {
30199
+ if (existsSync20(f.file)) {
29662
30200
  moveAside(f.file, undo);
29663
30201
  done.set(f, UPGRADE_REMOVED);
29664
30202
  } else done.set(f, UPGRADE_NOT_FOUND);
29665
30203
  } else entries.set(f.file, [...entries.get(f.file) ?? [], f]);
29666
30204
  }
29667
30205
  for (const [file2, list4] of entries) {
29668
- if (!existsSync19(file2)) {
30206
+ if (!existsSync20(file2)) {
29669
30207
  for (const f of list4) done.set(f, UPGRADE_NOT_FOUND);
29670
30208
  continue;
29671
30209
  }
29672
30210
  if (file2.endsWith(TOML_EXT)) {
29673
- const rawToml = readFileSync15(file2, "utf8");
30211
+ const rawToml = readFileSync16(file2, "utf8");
29674
30212
  const tomlLayout = hostLayout(rawToml);
29675
30213
  let text = hostText(rawToml);
29676
30214
  for (const f of list4) {
@@ -29698,7 +30236,7 @@ function removeV1(agent, findings) {
29698
30236
  },
29699
30237
  rollback() {
29700
30238
  for (const u of undo.splice(0).reverse()) {
29701
- if (!existsSync19(u.trash)) continue;
30239
+ if (!existsSync20(u.trash)) continue;
29702
30240
  rmSync8(u.target, { recursive: true, force: true });
29703
30241
  renameWithRetry(u.trash, u.target);
29704
30242
  }
@@ -29708,8 +30246,8 @@ function removeV1(agent, findings) {
29708
30246
 
29709
30247
  // src/core/ops/verify-sums.ts
29710
30248
  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";
30249
+ import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "node:fs";
30250
+ import { join as join23 } from "node:path";
29713
30251
  function mismatch() {
29714
30252
  return new CtxError("BUNDLE_HASH_MISMATCH");
29715
30253
  }
@@ -29730,24 +30268,24 @@ function walk3(dir, prefix, out) {
29730
30268
  for (const entry of readdirSync9(dir, { withFileTypes: true })) {
29731
30269
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
29732
30270
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
29733
- const abs = join22(dir, entry.name);
30271
+ const abs = join23(dir, entry.name);
29734
30272
  if (entry.isDirectory()) walk3(abs, rel, out);
29735
30273
  else if (entry.isFile()) out.set(rel, abs);
29736
30274
  else throw mismatch();
29737
30275
  }
29738
30276
  }
29739
30277
  function verifySums(dir) {
29740
- const sumsPath = join22(dir, RELEASE_SUMS_FILE);
30278
+ const sumsPath = join23(dir, RELEASE_SUMS_FILE);
29741
30279
  const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
29742
30280
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
29743
- const sums = parseSums(readFileSync16(sumsPath, "utf8"));
30281
+ const sums = parseSums(readFileSync17(sumsPath, "utf8"));
29744
30282
  const files = /* @__PURE__ */ new Map();
29745
30283
  walk3(dir, "", files);
29746
30284
  if (files.size !== sums.size) throw mismatch();
29747
30285
  for (const [rel, abs] of files) {
29748
30286
  const want = sums.get(rel);
29749
30287
  if (want === void 0) throw mismatch();
29750
- const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync16(abs)).digest(HASH_ENCODING);
30288
+ const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync17(abs)).digest(HASH_ENCODING);
29751
30289
  if (got !== want) throw mismatch();
29752
30290
  }
29753
30291
  }
@@ -29775,8 +30313,8 @@ function pluginRootRow(adapter, env) {
29775
30313
  return root === own2 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own2)];
29776
30314
  }
29777
30315
  function isCurrent(agentDir, dir) {
29778
- const link = join23(agentDir, PLUGIN_CURRENT_LINK);
29779
- return existsSync20(link) && realpathSync9.native(link) === realpathSync9.native(dir);
30316
+ const link = join24(agentDir, PLUGIN_CURRENT_LINK);
30317
+ return existsSync21(link) && realpathSync10.native(link) === realpathSync10.native(dir);
29780
30318
  }
29781
30319
  async function checkout(adapter, deps) {
29782
30320
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);