context-mode 2.0.0-next.34 → 2.0.0-next.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/pi/index.js CHANGED
@@ -2866,14 +2866,14 @@ var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, d
2866
2866
  inst._zod.parse = (payload, ctx) => {
2867
2867
  const input = payload.value;
2868
2868
  const left = def.left._zod.run({ value: input, issues: [] }, ctx);
2869
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
2870
- const async = left instanceof Promise || right instanceof Promise;
2869
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
2870
+ const async = left instanceof Promise || right2 instanceof Promise;
2871
2871
  if (async) {
2872
- return Promise.all([left, right]).then(([left2, right2]) => {
2873
- return handleIntersectionResults(payload, left2, right2);
2872
+ return Promise.all([left, right2]).then(([left2, right3]) => {
2873
+ return handleIntersectionResults(payload, left2, right3);
2874
2874
  });
2875
2875
  }
2876
- return handleIntersectionResults(payload, left, right);
2876
+ return handleIntersectionResults(payload, left, right2);
2877
2877
  };
2878
2878
  });
2879
2879
  function mergeValues(a, b) {
@@ -2920,16 +2920,16 @@ function mergeValues(a, b) {
2920
2920
  }
2921
2921
  return { valid: false, mergeErrorPath: [] };
2922
2922
  }
2923
- function handleIntersectionResults(result, left, right) {
2923
+ function handleIntersectionResults(result, left, right2) {
2924
2924
  if (left.issues.length) {
2925
2925
  result.issues.push(...left.issues);
2926
2926
  }
2927
- if (right.issues.length) {
2928
- result.issues.push(...right.issues);
2927
+ if (right2.issues.length) {
2928
+ result.issues.push(...right2.issues);
2929
2929
  }
2930
2930
  if (aborted(result))
2931
2931
  return result;
2932
- const merged = mergeValues(left.value, right.value);
2932
+ const merged = mergeValues(left.value, right2.value);
2933
2933
  if (!merged.valid) {
2934
2934
  throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
2935
2935
  }
@@ -8996,11 +8996,11 @@ function _discriminatedUnion(Class4, discriminator, options, params) {
8996
8996
  ...normalizeParams(params)
8997
8997
  });
8998
8998
  }
8999
- function _intersection(Class4, left, right) {
8999
+ function _intersection(Class4, left, right2) {
9000
9000
  return new Class4({
9001
9001
  type: "intersection",
9002
9002
  left,
9003
- right
9003
+ right: right2
9004
9004
  });
9005
9005
  }
9006
9006
  function _tuple(Class4, items, _paramsOrRest, _params) {
@@ -10678,11 +10678,11 @@ var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def
10678
10678
  $ZodIntersection.init(inst, def);
10679
10679
  ZodType.init(inst, def);
10680
10680
  });
10681
- function intersection(left, right) {
10681
+ function intersection(left, right2) {
10682
10682
  return new ZodIntersection({
10683
10683
  type: "intersection",
10684
10684
  left,
10685
- right
10685
+ right: right2
10686
10686
  });
10687
10687
  }
10688
10688
  var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
@@ -11570,7 +11570,7 @@ var DECISION_OPTION_KEY = "option";
11570
11570
  var DECISION_LABEL_JOIN = " | ";
11571
11571
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
11572
11572
  var RELEASE_BRANCH = "release";
11573
- var BUNDLE_SHA = true ? "e19d949bebe3a1751b6dc1a520b5ad38659fdd6f" : void 0;
11573
+ var BUNDLE_SHA = true ? "2ed67370714045804b7620af1f3af2c9eabc1713" : void 0;
11574
11574
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
11575
11575
  var DOCTOR_LABEL = Object.freeze({
11576
11576
  D1: "version",
@@ -11593,6 +11593,8 @@ var REPORT_HEADER = "| Check | Status | Detail | Fix |";
11593
11593
  var REPORT_HEADER_RULE = "|---|---|---|---|";
11594
11594
  var REPORT_COMMAND_PREFIX = "Run in a terminal: ";
11595
11595
  var ECHO_MAX_BYTES = 256;
11596
+ var LABEL_PREVIEW_BYTES = 32;
11597
+ var LABEL_PAGE_BYTES = 8192;
11596
11598
  var REPORT_SOURCE_LABEL = "ctx_doctor:report";
11597
11599
  var REPORT_REST_PREFIX = "Rows not shown here are stored in full. Read them with: ";
11598
11600
  var REPORT_POINTER = `ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(REPORT_SOURCE_LABEL)}})`;
@@ -11689,6 +11691,23 @@ function D8_HEALED_RECREATE_DETAIL(ts) {
11689
11691
  }
11690
11692
  var INTEGRITY_OK = "ok";
11691
11693
  var HEAL_BACKUP_SUFFIX = ".bak";
11694
+ var orphanList = (files) => files.map((f) => `${f.path} (${f.bytes} bytes)`).join(", ");
11695
+ var ORPHAN_DIR_PREFIX = "orphan-";
11696
+ function D8_ORPHAN_DETAIL(files) {
11697
+ return `context.db is gone, its WAL files are still here: ${orphanList(files)}`;
11698
+ }
11699
+ var D8_ORPHAN_FIX = "run ctx_doctor once; it keeps these files in a dated folder and starts a new index";
11700
+ function D8_ORPHAN_HEALED_DETAIL(dir, moved, dbPath) {
11701
+ return `moved the WAL files of the missing context.db, whole and unchanged, to ${dir}: ${orphanList(moved)}; new index at ${dbPath}; the old WAL is kept there, to restore it put the original context.db back next to it`;
11702
+ }
11703
+ var D8_ORPHAN_HEALED_FIX = "run ctx_doctor again; D8 then reads PASS";
11704
+ function D8_ORPHAN_MOVE_FAILED(detail, cause) {
11705
+ return `${detail}; moving them aside failed: ${cause}`;
11706
+ }
11707
+ var DOCTOR_TOOL_NAME = "ctx_doctor";
11708
+ function JOURNAL_SKIPPED_LINE(cause) {
11709
+ return `Journal row for this call skipped: ${cause}`;
11710
+ }
11692
11711
  function D9_INDEX_DETAIL(sources, chunks) {
11693
11712
  return `${sources} sources, ${chunks} chunks indexed`;
11694
11713
  }
@@ -12124,7 +12143,8 @@ function checkPermission(out) {
12124
12143
  var ERROR_TEXT = Object.freeze({
12125
12144
  NODE_TOO_OLD: "Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",
12126
12145
  NO_SQLITE: "node:sqlite failed to load. Fix: run ctx_doctor.",
12127
- DB_GONE: "context.db path vanished. Fix: run ctx_doctor.",
12146
+ DB_GONE: "context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",
12147
+ // D-ORPHAN-WAL-1
12128
12148
  NO_PROJECT: "Project source <kind> is missing. Fix: run ctx_doctor.",
12129
12149
  UNKNOWN_FIELD: 'Unknown field "<f>". Fix: use "queries".',
12130
12150
  TIMEOUT: "Timed out after <ms> ms. Fix: pass background: true.",
@@ -13670,8 +13690,8 @@ function jqWhitelisted(filter2) {
13670
13690
  const bar2 = s.indexOf(JQ_WHITELIST.pipeLength.charAt(0));
13671
13691
  if (bar2 < 0) return jqPath(s);
13672
13692
  const left = s.slice(0, bar2).trim();
13673
- const right = JQ_WHITELIST.pipeLength.slice(1).trim();
13674
- return (left === JQ_WHITELIST.identity || jqPath(left)) && s.slice(bar2 + 1).trim() === right;
13693
+ const right2 = JQ_WHITELIST.pipeLength.slice(1).trim();
13694
+ return (left === JQ_WHITELIST.identity || jqPath(left)) && s.slice(bar2 + 1).trim() === right2;
13675
13695
  }
13676
13696
  function isBoundedSink(c) {
13677
13697
  const name = c.argv0.toLowerCase();
@@ -14873,7 +14893,7 @@ function matchesAnyDenyPattern(text, patterns, subject = BASH_SUBJECT) {
14873
14893
  // src/prompt/_generated.ts
14874
14894
  var INSTRUCTIONS = "context-mode keeps large output out of the conversation.\n\nWhen a step counts, sums, filters or finds something in over about 20 lines of data (logs, test or build output, big JSON or CSV, long files, web pages), use ctx_execute and print only the answer, not a raw Bash or Read result.\n\nA large tool result is indexed and cut to its best-matching parts; ctx_search finds the rest. A large file's Read is denied: use offset and limit, or ctx_execute with file set. Use normal tools for small output and edits.\n";
14875
14895
  var TOOL_DESCRIPTIONS = Object.freeze({
14876
- ctx_execute: 'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nRuns code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',
14896
+ ctx_execute: 'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',
14877
14897
  ctx_batch: 'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',
14878
14898
  ctx_index: 'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',
14879
14899
  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.',
@@ -17751,6 +17771,7 @@ var PORTER_MATCH = `
17751
17771
  AND (:scope <> 'session' OR chunks.session_id = :session_id)
17752
17772
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
17753
17773
  AND (:source IS NULL OR s.label = :source)
17774
+ AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
17754
17775
  ${NOT_RAW}`;
17755
17776
  var PORTER_ORDER = `
17756
17777
  ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`;
@@ -17779,6 +17800,7 @@ WHERE chunks_tri MATCH :match
17779
17800
  AND (:scope <> 'session' OR c.session_id = :session_id)
17780
17801
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
17781
17802
  AND (:source IS NULL OR s.label = :source)
17803
+ AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
17782
17804
  ${NOT_RAW}
17783
17805
  ORDER BY bm25(chunks_tri, 1.0, ${TITLE_WEIGHT}) ASC, c.source_id DESC, c.ord ASC`;
17784
17806
  var PAGE_ROWS = `
@@ -18051,10 +18073,18 @@ function typoTerms(db, words) {
18051
18073
  });
18052
18074
  return changed ? out.map((t) => `"${t.replaceAll('"', '""')}"*`) : null;
18053
18075
  }
18054
- function ftsQuery(db, q, scope, ctx, sessionId, limit, offset, source) {
18076
+ var LABEL_SERIAL = `
18077
+ SELECT COALESCE(MAX(CAST(substr(label, length(:prefix) + 1) AS INTEGER)), 0) + 1 AS n
18078
+ FROM sources WHERE session_id = :session_id AND substr(label, 1, length(:prefix)) = :prefix`;
18079
+ function nextLabelSerial(db, sessionId, prefix) {
18080
+ const row5 = stmt(db.raw, LABEL_SERIAL).get({ session_id: sessionId, prefix });
18081
+ return Number(row5.n);
18082
+ }
18083
+ function ftsQuery(db, q, scope, ctx, sessionId, limit, offset, source, sourceIds) {
18055
18084
  const terms = searchTerms(q);
18056
18085
  if (terms.length === 0) return [];
18057
- const filter2 = { scope, session_id: sessionId, worktree: ctx.worktree, source: source ?? null };
18086
+ const ids = sourceIds === void 0 ? null : JSON.stringify(sourceIds);
18087
+ const filter2 = { scope, session_id: sessionId, worktree: ctx.worktree, source: source ?? null, ids };
18058
18088
  const rrf = scope === "project" ? { k: RRF_K } : {};
18059
18089
  const porter = (t) => stmt(db.raw, porterRankSql(scope)).all({ ...filter2, match: t.join(" OR "), all: t.join(" "), ...rrf });
18060
18090
  let pList = porter(terms);
@@ -18260,20 +18290,84 @@ function storedLabel(db, source) {
18260
18290
  const canon = pathLabel(source);
18261
18291
  return canon !== source && labelStored(db, canon) ? canon : source;
18262
18292
  }
18263
- function resolveSourceLabel(db, source) {
18293
+ function newestId(db, label2) {
18294
+ const row5 = stmt(db.raw, "SELECT id FROM sources WHERE label = ? ORDER BY id DESC LIMIT 1").get(label2);
18295
+ return row5 === void 0 ? null : Number(row5.id);
18296
+ }
18297
+ function labelOfId(db, id) {
18298
+ const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id);
18299
+ return row5 === void 0 ? null : row5.label;
18300
+ }
18301
+ function pickSource(db, source, suffix = true) {
18302
+ const named2 = storedLabel(db, source);
18264
18303
  const id = parseSourceHandle(source);
18304
+ const own4 = newestId(db, named2);
18305
+ if (own4 !== null) {
18306
+ const otherLabel = id === null || id === own4 ? null : labelOfId(db, id);
18307
+ return { label: named2, id: own4, via: "label", other: otherLabel === null || otherLabel === named2 ? null : { id, label: otherLabel } };
18308
+ }
18265
18309
  if (id !== null) {
18266
- const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id);
18267
- if (row5 !== void 0) return row5.label;
18310
+ const label2 = labelOfId(db, id);
18311
+ if (label2 !== null) return { label: label2, id, via: "handle", other: null };
18312
+ }
18313
+ if (suffix) {
18314
+ const prefix = named2 + LABEL_SUFFIX_SEP;
18315
+ const rows = stmt(db.raw, "SELECT id, label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
18316
+ for (const r of rows) {
18317
+ if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named2.length) return { label: r.label, id: Number(r.id), via: "suffix", other: null };
18318
+ }
18319
+ }
18320
+ return { label: source, id: null, via: "none", other: null };
18321
+ }
18322
+ function collisionLine(value, pick4) {
18323
+ if (pick4.other === null || pick4.id === null) return null;
18324
+ return "Source " + JSON.stringify(value) + ": used the label " + shownLabel(pick4.label, null) + " (" + sourceHandle(pick4.id) + "); handle " + sourceHandle(pick4.other.id) + " is " + shownLabel(pick4.other.label, null) + (isLongLabel(pick4.other.label) ? ", search it by its full label." : ", search it with source:" + JSON.stringify(pick4.other.label) + ".");
18325
+ }
18326
+ function labelPage(label2, offset, max) {
18327
+ const buf = Buffer.from(label2, "utf8");
18328
+ let start = Math.min(offset, buf.length);
18329
+ while (start < buf.length && (buf[start] & 192) === 128) start++;
18330
+ let end = Math.min(start + max, buf.length);
18331
+ while (end < buf.length && end > start && (buf[end] & 192) === 128) end--;
18332
+ return { text: buf.subarray(start, end).toString("utf8"), next: end < buf.length ? end : null, total: buf.length };
18333
+ }
18334
+ function groupDigits(n) {
18335
+ const s = String(Math.trunc(n));
18336
+ let out = "";
18337
+ for (let i = 0; i < s.length; i++) {
18338
+ if (i > 0 && (s.length - i) % 3 === 0) out += ",";
18339
+ out += s[i];
18268
18340
  }
18269
- const named = storedLabel(db, source);
18270
- if (labelStored(db, named)) return named;
18271
- const prefix = named + LABEL_SUFFIX_SEP;
18272
- const rows = stmt(db.raw, "SELECT label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
18273
- for (const r of rows) {
18274
- if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named.length) return r.label;
18341
+ return out;
18342
+ }
18343
+ function headBytes(s, max) {
18344
+ let out = "";
18345
+ let used = 0;
18346
+ for (const ch of s) {
18347
+ const n = Buffer.byteLength(ch, "utf8");
18348
+ if (used + n > max) break;
18349
+ out += ch;
18350
+ used += n;
18275
18351
  }
18276
- return source;
18352
+ return out;
18353
+ }
18354
+ function isLongLabel(label2) {
18355
+ return Buffer.byteLength(label2, "utf8") > ECHO_MAX_BYTES;
18356
+ }
18357
+ function labelPreview(label2) {
18358
+ return "label (" + groupDigits(Buffer.byteLength(label2, "utf8")) + " B): " + headBytes(label2, LABEL_PREVIEW_BYTES) + "\u2026";
18359
+ }
18360
+ function shownLabel(label2, id) {
18361
+ if (!isLongLabel(label2)) return label2;
18362
+ return (id === null ? "" : sourceHandle(id) + " ") + "[" + labelPreview(label2) + "]";
18363
+ }
18364
+ function indexedLabelLine(label2, id) {
18365
+ if (!isLongLabel(label2)) return "Label: " + label2;
18366
+ return "Its label (" + groupDigits(Buffer.byteLength(label2, "utf8")) + " B): " + headBytes(label2, LABEL_PREVIEW_BYTES) + "\u2026; ctx_search({queries:[], source:" + JSON.stringify(sourceHandle(id)) + "}) reads it whole.";
18367
+ }
18368
+ function sourceCardRow(db, id) {
18369
+ const row5 = stmt(db.raw, "SELECT label, bytes_total, chunk_count, kind FROM sources WHERE id = ?").get(id);
18370
+ return row5 === void 0 ? null : { label: row5.label, bytes: Number(row5.bytes_total), chunks: Number(row5.chunk_count), kind: row5.kind };
18277
18371
  }
18278
18372
  function listSessionSources(db, sessionId, limit) {
18279
18373
  const rows = stmt(db.raw, "SELECT id, label, bytes_total FROM sources WHERE session_id = ? ORDER BY id DESC LIMIT ?").all(sessionId, limit);
@@ -18850,8 +18944,8 @@ function rawEnd(src, from, name) {
18850
18944
  let k = src.indexOf("</", from);
18851
18945
  while (k >= 0) {
18852
18946
  const after = k + "</".length + name.length;
18853
- const named = src.slice(k + "</".length, after).toLowerCase() === name;
18854
- if (named && (after >= src.length || !isNameChar(src[after]))) {
18947
+ const named2 = src.slice(k + "</".length, after).toLowerCase() === name;
18948
+ if (named2 && (after >= src.length || !isNameChar(src[after]))) {
18855
18949
  const gt = src.indexOf(">", after);
18856
18950
  return gt < 0 ? src.length : gt + 1;
18857
18951
  }
@@ -18878,7 +18972,7 @@ function cutPoint(src, start, end, scratch) {
18878
18972
  const r = encoder.encodeInto(src.slice(start, limit), scratch);
18879
18973
  return { end: start + r.read, written: r.written };
18880
18974
  }
18881
- function merge2(src, blocks, join27, cap, lineCut) {
18975
+ function merge2(src, blocks, join28, cap, lineCut) {
18882
18976
  const out = [];
18883
18977
  const scratch = new Uint8Array(cap);
18884
18978
  let wide;
@@ -18888,7 +18982,7 @@ function merge2(src, blocks, join27, cap, lineCut) {
18888
18982
  out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
18889
18983
  };
18890
18984
  for (const b of blocks) {
18891
- if (cur !== void 0 && !join27) {
18985
+ if (cur !== void 0 && !join28) {
18892
18986
  emit(cur.start, cur.end, curBytes);
18893
18987
  cur = void 0;
18894
18988
  }
@@ -19086,24 +19180,24 @@ function jsonShape(text, query) {
19086
19180
  }
19087
19181
  if (outliers.size === 0 || outliers.size > SHAPE_RARE_UNITS_MAX) return null;
19088
19182
  const keyScore = rankTexts(keys, query, "any");
19089
- const named = new Set(keys.filter((_, i) => keyScore[i] > 0));
19183
+ const named2 = new Set(keys.filter((_, i) => keyScore[i] > 0));
19090
19184
  const units = [...outliers.entries()].map(([i, skewed]) => ({
19091
19185
  pos: i,
19092
19186
  rank: JSON.stringify(objs[i]),
19093
- render: (budget) => renderRow(i, objs[i], skewed, named, budget)
19187
+ render: (budget) => renderRow(i, objs[i], skewed, named2, budget)
19094
19188
  }));
19095
19189
  return { header: schemaOf(objs.length, keys) + ", " + outliers.size + " rare:", units };
19096
19190
  }
19097
- function renderRow(i, row5, skewed, named, budget) {
19191
+ function renderRow(i, row5, skewed, named2, budget) {
19098
19192
  const prefix = "[" + i + "] ";
19099
- const body = fitRow(row5, skewed, named, budget - bytes(prefix));
19193
+ const body = fitRow(row5, skewed, named2, budget - bytes(prefix));
19100
19194
  return body === null ? null : prefix + body;
19101
19195
  }
19102
- function fitRow(row5, skewed, named, budget) {
19196
+ function fitRow(row5, skewed, named2, budget) {
19103
19197
  const whole2 = JSON.stringify(row5);
19104
19198
  if (bytes(whole2) <= budget) return whole2;
19105
19199
  const own4 = Object.keys(row5);
19106
- const tier = (k) => skewed.includes(k) ? 0 : named.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
19200
+ const tier = (k) => skewed.includes(k) ? 0 : named2.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
19107
19201
  const order = [...own4].sort((a, b) => tier(a) - tier(b) || own4.indexOf(a) - own4.indexOf(b));
19108
19202
  const field = (k) => JSON.stringify(k) + ":" + JSON.stringify(row5[k]);
19109
19203
  const chosen = /* @__PURE__ */ new Set();
@@ -19125,11 +19219,11 @@ function jsonExtremes(text, query) {
19125
19219
  const parsedRows = jsonRows(text);
19126
19220
  if (parsedRows === null) return null;
19127
19221
  const { objs, keys } = parsedRows;
19128
- const named = namedKeys(keys, query);
19222
+ const named2 = namedKeys(keys, query);
19129
19223
  const picks = /* @__PURE__ */ new Map();
19130
19224
  let used = 0;
19131
19225
  for (const k of keys) {
19132
- if (!named.has(k) || used >= SHAPE_EXTREME_KEYS) continue;
19226
+ if (!named2.has(k) || used >= SHAPE_EXTREME_KEYS) continue;
19133
19227
  if (!objs.every((o) => typeof o[k] === "number" && Number.isFinite(o[k]))) continue;
19134
19228
  let hi = 0, lo = 0;
19135
19229
  for (let i = 1; i < objs.length; i++) {
@@ -19145,7 +19239,7 @@ function jsonExtremes(text, query) {
19145
19239
  const units = [...picks.entries()].map(([i, k]) => ({
19146
19240
  pos: i,
19147
19241
  rank: "",
19148
- render: (budget) => renderRow(i, objs[i], [k], named, budget)
19242
+ render: (budget) => renderRow(i, objs[i], [k], named2, budget)
19149
19243
  }));
19150
19244
  return { header: schemaOf(objs.length, keys) + ", extremes of " + [...new Set(picks.values())].join(",") + ":", units, direct: true };
19151
19245
  }
@@ -20204,8 +20298,27 @@ function sourceCount(db, scope, ctx, source) {
20204
20298
  });
20205
20299
  return Number(row5.n);
20206
20300
  }
20207
- function zeroHits(db, scope, ctx, source) {
20208
- return reply('No hits in scope "' + scope + '" across ' + sourceCount(db, scope, ctx, source) + " source(s).", false);
20301
+ function zeroHits(db, scope, ctx, source, offset = 0) {
20302
+ const n = sourceCount(db, scope, ctx, source);
20303
+ if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
20304
+ return reply('No hits in scope "' + scope + '" across ' + n + " source(s).", false);
20305
+ }
20306
+ function named(given, pick4) {
20307
+ if (given === void 0 || pick4 === null) return { arg: given, note: null };
20308
+ const arg = pick4.id !== null && isLongLabel(given) ? sourceHandle(pick4.id) : given;
20309
+ return { arg, note: collisionLine(given, pick4) };
20310
+ }
20311
+ function sourceCard(db, id, input, scope, arg) {
20312
+ const row5 = sourceCardRow(db, id);
20313
+ if (row5 === null) return null;
20314
+ const pg = labelPage(row5.label, input.offset ?? 0, LABEL_PAGE_BYTES);
20315
+ const lines = [
20316
+ "Source " + sourceHandle(id) + ": label " + groupDigits(pg.total) + " B, " + row5.chunks + " chunk(s), " + groupDigits(row5.bytes) + " B of " + row5.kind + ".",
20317
+ "Label:",
20318
+ pg.text
20319
+ ];
20320
+ if (pg.next !== null) lines.push("More: " + callText([], scope, arg, "offset:" + pg.next));
20321
+ return reply(lines.join("\n"), false);
20209
20322
  }
20210
20323
  function callText(queries, scope, source, cursor) {
20211
20324
  const src = source === void 0 ? "" : ", source:" + JSON.stringify(source);
@@ -20236,7 +20349,7 @@ WHERE label = :source
20236
20349
  AND (:scope <> 'session' OR session_id = :session_id)
20237
20350
  AND (:scope <> 'worktree' OR worktree = :worktree)
20238
20351
  ORDER BY id DESC LIMIT 1`;
20239
- function jsonRowsReply(db, input, scope, ctx) {
20352
+ function jsonRowsReply(db, input, scope, ctx, nm) {
20240
20353
  if (input.source === void 0 || input.source === DECISION_SOURCE || input.queries.length === 0) return null;
20241
20354
  const src = db.raw.prepare(JSON_SOURCE).get({ source: input.source, scope, session_id: ctx.sessionId, worktree: ctx.project.worktree });
20242
20355
  if (src === void 0 || Number(src.bytes_total) > JSON_SOURCE_MAX_BYTES) return null;
@@ -20247,25 +20360,27 @@ function jsonRowsReply(db, input, scope, ctx) {
20247
20360
  const texts = objs.map((o) => JSON.stringify(o));
20248
20361
  const offset = input.offset ?? 0;
20249
20362
  const out = [objs.length + " objects {" + keys.join(",") + "}"];
20363
+ const name = shownLabel(input.source, Number(src.id));
20250
20364
  let shown2 = 0;
20251
20365
  let more = false;
20252
20366
  for (const q of input.queries) {
20253
20367
  const scores = rankTexts(texts, q, "any");
20254
20368
  const order = objs.map((_, i) => i).filter((i) => scores[i] > 0).sort((a, b) => scores[b] - scores[a] || a - b);
20255
- const named = namedKeys(keys, q);
20369
+ const named2 = namedKeys(keys, q);
20256
20370
  out.push("Query " + JSON.stringify(q) + ":");
20257
20371
  for (const i of order.slice(offset, offset + JSON_ROWS_PAGE)) {
20258
- const row5 = fitRow(objs[i], [], named, SNIPPET_MAX_BYTES);
20372
+ const row5 = fitRow(objs[i], [], named2, SNIPPET_MAX_BYTES);
20259
20373
  if (row5 === null) continue;
20260
- out.push(input.source + " [" + i + "]: " + row5);
20374
+ out.push(name + " [" + i + "]: " + row5);
20261
20375
  shown2++;
20262
20376
  }
20263
20377
  if (order.length > offset + JSON_ROWS_PAGE) {
20264
- out.push("More: " + callText([q], scope, input.source, "offset:" + (offset + JSON_ROWS_PAGE)));
20378
+ out.push("More: " + callText([q], scope, nm.arg, "offset:" + (offset + JSON_ROWS_PAGE)));
20265
20379
  more = true;
20266
20380
  }
20267
20381
  }
20268
- return shown2 === 0 && !more ? null : reply(out.join("\n"), false);
20382
+ if (shown2 === 0 && !more) return null;
20383
+ return reply((nm.note === null ? out : [nm.note, ...out]).join("\n"), false);
20269
20384
  }
20270
20385
  var SMALL_SOURCE_SHARE = 0.5;
20271
20386
  var SOURCE_BYTES = "SELECT id, bytes_total FROM sources WHERE id IN (SELECT value FROM json_each(:ids))";
@@ -20284,23 +20399,23 @@ function replyHits(hits, size) {
20284
20399
  while (n < size && n < hits.length && hits[n].full === true) n++;
20285
20400
  return n;
20286
20401
  }
20287
- function relevance(db, given, scope, ctx) {
20402
+ function relevance(db, given, scope, ctx, nm) {
20288
20403
  const input = { ...given, queries: decisionQueries(given) };
20289
20404
  const offset = input.offset ?? 0;
20290
20405
  const size = pageSize(input);
20291
20406
  const fetched = input.queries.map((q) => page(db, q, input, scope, ctx, offset, 1));
20292
20407
  const take = fetched.map((h) => replyHits(h, size));
20293
20408
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
20294
- if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source);
20295
- const moreLine3 = (q, pos) => "More: " + callText([q], scope, input.source, "offset:" + pos);
20409
+ if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, offset);
20410
+ const moreLine3 = (q, pos) => "More: " + callText([q], scope, nm.arg, "offset:" + pos);
20296
20411
  let reserve = 0;
20297
20412
  for (const q of input.queries) reserve += bytes2(moreLine3(q, offset + size)) + 1;
20298
20413
  const total = input.source === DECISION_SOURCE ? /* @__PURE__ */ new Map() : sourceBytes(db, [...new Set(pages.flat().map((h) => h.sourceId))]);
20299
20414
  const spent = /* @__PURE__ */ new Map();
20300
- const lines = [];
20415
+ const lines = nm.note === null ? [] : [nm.note];
20301
20416
  const more = [];
20302
20417
  const shown2 = /* @__PURE__ */ new Set();
20303
- let used = 0;
20418
+ let used = nm.note === null ? 0 : bytes2(nm.note) + 1;
20304
20419
  let stopped = false;
20305
20420
  input.queries.forEach((q, qi) => {
20306
20421
  const hits = pages[qi];
@@ -20318,10 +20433,11 @@ function relevance(db, given, scope, ctx) {
20318
20433
  const hit = hits[i];
20319
20434
  const key = hit.sourceId + ":" + hit.ord;
20320
20435
  if (shown2.has(key)) {
20321
- again.set(hit.label, [...again.get(hit.label) ?? [], hit.ord]);
20436
+ const name = shownLabel(hit.label, hit.sourceId);
20437
+ again.set(name, [...again.get(name) ?? [], hit.ord]);
20322
20438
  continue;
20323
20439
  }
20324
- const line = hit.label + " #" + hit.ord + ": " + hit.snippet;
20440
+ const line = shownLabel(hit.label, hit.sourceId) + " #" + hit.ord + ": " + hit.snippet;
20325
20441
  if (used + bytes2(line) + 1 + reserve > OUTPUT_CAP) {
20326
20442
  cut = offset + i;
20327
20443
  stopped = true;
@@ -20349,23 +20465,23 @@ function relevance(db, given, scope, ctx) {
20349
20465
  const moreLines = [];
20350
20466
  const byPos = /* @__PURE__ */ new Map();
20351
20467
  for (const m of more) byPos.set(m.pos, [...byPos.get(m.pos) ?? [], m.q]);
20352
- for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, input.source, "offset:" + pos));
20468
+ for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, nm.arg, "offset:" + pos));
20353
20469
  return reply(lines.concat(moreLines).join("\n"), false);
20354
20470
  }
20355
20471
  function timelineLine(r) {
20356
20472
  const nl = r.text.indexOf("\n");
20357
20473
  const first = nl < 0 ? r.text : r.text.slice(0, nl);
20358
20474
  const seq = r.seq === null ? "" : " #" + r.seq;
20359
- return "[" + new Date(r.ts).toISOString() + "] " + r.label + seq + " " + first;
20475
+ return "[" + new Date(r.ts).toISOString() + "] " + shownLabel(r.label, r.sourceId) + seq + " " + first;
20360
20476
  }
20361
- function timeline(db, input, scope, ctx) {
20477
+ function timeline(db, input, scope, ctx, nm) {
20362
20478
  const memory = scope === "session" ? [] : readAutoMemory(ctx.project);
20363
20479
  const page2 = ftsQueryTimeline(db, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, input.after ?? null, input.source, memory);
20364
20480
  if (page2.rows.length === 0) return zeroHits(db, scope, ctx, input.source);
20365
- const moreLine3 = (ts) => "more: " + callText(input.queries, scope, input.source, 'sort:"timeline", after:' + ts);
20481
+ const moreLine3 = (ts) => "more: " + callText(input.queries, scope, nm.arg, 'sort:"timeline", after:' + ts);
20366
20482
  const reserve = bytes2(moreLine3(page2.rows[page2.rows.length - 1].ts)) + 1;
20367
- const lines = [];
20368
- let used = 0;
20483
+ const lines = nm.note === null ? [] : [nm.note];
20484
+ let used = nm.note === null ? 0 : bytes2(nm.note) + 1;
20369
20485
  let lastTs = null;
20370
20486
  let more = page2.more;
20371
20487
  let i = 0;
@@ -20401,9 +20517,16 @@ async function handler(input, ctx) {
20401
20517
  const scope = input.scope ?? "worktree";
20402
20518
  const db = await openDb(ctx.project, { readOnly: true });
20403
20519
  try {
20404
- if (input.source !== void 0 && input.source !== DECISION_SOURCE) input = { ...input, source: resolveSourceLabel(db, input.source) };
20405
- if (sort === "timeline") return timeline(db, input, scope, ctx);
20406
- return jsonRowsReply(db, input, scope, ctx) ?? relevance(db, input, scope, ctx);
20520
+ const given = input.source;
20521
+ const pick4 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given) : null;
20522
+ if (pick4 !== null) input = { ...input, source: pick4.label };
20523
+ const nm = named(given, pick4);
20524
+ if (sort === "timeline") return timeline(db, input, scope, ctx, nm);
20525
+ if (pick4 !== null && pick4.id !== null && input.queries.length === 0) {
20526
+ const card = sourceCard(db, pick4.id, input, scope, nm.arg);
20527
+ if (card !== null) return card;
20528
+ }
20529
+ return jsonRowsReply(db, input, scope, ctx, nm) ?? relevance(db, input, scope, ctx, nm);
20407
20530
  } finally {
20408
20531
  closeDb(db);
20409
20532
  }
@@ -20424,6 +20547,7 @@ var ctxBatchSchema = external_exports.object({
20424
20547
  }, { error: unknownField }).strict();
20425
20548
  var TOOL = "ctx_batch";
20426
20549
  var LABEL_PREFIX = TOOL + ":";
20550
+ var LABEL_SEP = ":";
20427
20551
  var SHELL = "shell";
20428
20552
  var SHELL_INLINE_FLAG = "-c";
20429
20553
  var MARKER = "$ ";
@@ -20491,6 +20615,7 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20491
20615
  const display = shown(chunks, ran.map((r) => r.head));
20492
20616
  const bodies = /* @__PURE__ */ new Map();
20493
20617
  const raw = /* @__PURE__ */ new Map();
20618
+ const ids = [];
20494
20619
  let total = 0;
20495
20620
  for (const c of chunks) total += c.bytes;
20496
20621
  let indexed = 0;
@@ -20511,6 +20636,7 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20511
20636
  chunkCount: group.length,
20512
20637
  createdAt: Date.now()
20513
20638
  }, group);
20639
+ ids.push(id);
20514
20640
  for (const c of group) {
20515
20641
  bodies.set(chunkKey(id, c.ord), display[c.ord]);
20516
20642
  raw.set(chunkKey(id, c.ord), c.text);
@@ -20523,25 +20649,25 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20523
20649
  for (const c of chunks) {
20524
20650
  if (queued + c.bytes > budgetBytes) {
20525
20651
  const stop2 = flush() ? "budget" : "deadline";
20526
- return { bodies, raw, indexed, total, stop: stop2 };
20652
+ return { bodies, raw, ids, indexed, total, stop: stop2 };
20527
20653
  }
20528
- if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, indexed, total, stop: "deadline" };
20654
+ if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, ids, indexed, total, stop: "deadline" };
20529
20655
  group.push(c);
20530
20656
  groupBytes += c.bytes;
20531
20657
  queued += c.bytes;
20532
20658
  }
20533
20659
  const stop = flush() ? null : "deadline";
20534
- return { bodies, raw, indexed, total, stop };
20660
+ return { bodies, raw, ids, indexed, total, stop };
20535
20661
  }
20536
20662
  function bytes3(s) {
20537
20663
  return Buffer.byteLength(s, "utf8");
20538
20664
  }
20539
- function answer(db, ctx, label2, queries, share, own4) {
20665
+ function answer(db, ctx, ownIds, queries, share, own4) {
20540
20666
  const seen = /* @__PURE__ */ new Set();
20541
20667
  const lines = [];
20542
20668
  for (const [qi, q] of queries.entries()) {
20543
20669
  if (ctx.signal.aborted) break;
20544
- let hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, label2);
20670
+ let hits = ownIds.length === 0 ? [] : ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, void 0, ownIds);
20545
20671
  if (hits.length === 0) hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0);
20546
20672
  const head = "## " + (bytes3(q) > ECHO_MAX_BYTES ? "query " + (qi + 1) : q);
20547
20673
  let used = bytes3(head) + 1;
@@ -20580,9 +20706,10 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20580
20706
  const ran = pool.results;
20581
20707
  const last2 = ran[ran.length - 1];
20582
20708
  const sandboxBytes = ran.reduce((n, r) => n + r.bytes, 0);
20583
- const label2 = LABEL_PREFIX + ctx.turn;
20584
20709
  try {
20585
20710
  const db = await openDb(ctx.project);
20711
+ const turnPrefix = LABEL_PREFIX + ctx.turn + LABEL_SEP;
20712
+ const label2 = turnPrefix + nextLabelSerial(db, ctx.sessionId, turnPrefix);
20586
20713
  let sections;
20587
20714
  let idx;
20588
20715
  const exitLine = last2.exitCode === null || last2.exitCode === 0 ? null : "exit " + last2.exitCode;
@@ -20598,7 +20725,7 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20598
20725
  notice = cut === null ? stop : cause === null ? cut : cause + " " + cut;
20599
20726
  const fixed = (exitLine === null ? 0 : bytes3(exitLine) + 1) + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
20600
20727
  const share = Math.floor((OUTPUT_CAP - fixed) / queries.length);
20601
- const answered = answer(db, ctx, label2, queries, share, idx.bodies);
20728
+ const answered = answer(db, ctx, idx.ids, queries, share, idx.bodies);
20602
20729
  sections = answered.lines;
20603
20730
  const unseen = [...idx.bodies].filter(([k, text]) => text !== "" && !answered.seen.has(k)).map(([k]) => idx.raw.get(k));
20604
20731
  const unseenBytes = unseen.reduce((n, t) => n + bytes3(t) + 1, 0);
@@ -20635,7 +20762,7 @@ var ctxBatch = Object.freeze({
20635
20762
 
20636
20763
  // src/core/tools/doctor.ts
20637
20764
  import { readdirSync as readdirSync5, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20638
- import { basename as basename4, dirname as dirname7, join as join15 } from "node:path";
20765
+ import { basename as basename5, dirname as dirname8, join as join16 } from "node:path";
20639
20766
 
20640
20767
  // src/core/ops/doctor-config.ts
20641
20768
  import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
@@ -21636,9 +21763,9 @@ var Tokenizer = class {
21636
21763
  cp = this.nextCode();
21637
21764
  }
21638
21765
  const { out } = this.parseDigits(cp, isDigit4);
21639
- const right = out;
21640
- if (minus) right.unshift(CodePoint.DASH);
21641
- const value = Number(leftMinus ? String.fromCodePoint(CodePoint.DASH, ...left, CodePoint.LATIN_SMALL_E, ...right) : String.fromCodePoint(...left, CodePoint.LATIN_SMALL_E, ...right));
21766
+ const right2 = out;
21767
+ if (minus) right2.unshift(CodePoint.DASH);
21768
+ const value = Number(leftMinus ? String.fromCodePoint(CodePoint.DASH, ...left, CodePoint.LATIN_SMALL_E, ...right2) : String.fromCodePoint(...left, CodePoint.LATIN_SMALL_E, ...right2));
21642
21769
  this.endToken("Float", "start", value);
21643
21770
  return this.back("DATA");
21644
21771
  }
@@ -23819,7 +23946,7 @@ function checkHostConfig(row5, env, worktree) {
23819
23946
  const read3 = row5.id === "pi" ? mcpFile(row5, home, env) : null;
23820
23947
  if (parts.length === 0) return read3 === null ? pass("D3") : { ...pass("D3"), detail: read3 };
23821
23948
  const detail = D3_DETAIL(parts);
23822
- const fix = parts.includes(PART_MCP) && parts.includes(PART_HOOKS) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
23949
+ const fix = parts.includes(PART_MCP) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
23823
23950
  return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, fix);
23824
23951
  }
23825
23952
  function checkV1Leftovers(agent, home, scope = {}) {
@@ -23873,7 +24000,7 @@ function configPaths(row5, env, worktree) {
23873
24000
  }
23874
24001
 
23875
24002
  // src/core/ops/doctor-db.ts
23876
- import { existsSync as existsSync7 } from "node:fs";
24003
+ import { existsSync as existsSync7, statSync as statSync5 } from "node:fs";
23877
24004
  var unknown2 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail });
23878
24005
  var pass2 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "PASS", detail });
23879
24006
  var fail3 = (detail, fixCommand) => ({ id: "D8", label: DOCTOR_LABEL.D8, status: "FAIL", detail, fixCommand });
@@ -23911,8 +24038,18 @@ function failsOnCorrupt(step) {
23911
24038
  throw err;
23912
24039
  }
23913
24040
  }
24041
+ function orphanFiles(dbPath) {
24042
+ const files = [];
24043
+ for (const suffix of [DB_WAL_SUFFIX, DB_SHM_SUFFIX]) {
24044
+ const path7 = dbPath + suffix;
24045
+ if (existsSync7(path7)) files.push({ path: path7, bytes: statSync5(path7).size });
24046
+ }
24047
+ return files.length > 0 && !existsSync7(dbPath) ? files : [];
24048
+ }
23914
24049
  async function checkDb(project) {
23915
- const clean = { schemaStale: false, integrityFailed: false };
24050
+ const clean = { schemaStale: false, integrityFailed: false, orphan: [] };
24051
+ const orphan = orphanFiles(project.dbPath);
24052
+ if (orphan.length > 0) return { row: fail3(D8_ORPHAN_DETAIL(orphan), D8_ORPHAN_FIX), schemaStale: false, integrityFailed: false, orphan };
23916
24053
  if (!existsSync7(project.dbPath)) return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
23917
24054
  const sqlite = await loadSqlite2();
23918
24055
  if (sqlite === null) return { row: unknown2("D8", D2_SQLITE_DETAIL), ...clean };
@@ -23928,11 +24065,11 @@ async function checkDb(project) {
23928
24065
  }
23929
24066
  const schemaStale = got !== null && got !== SCHEMA_VERSION;
23930
24067
  const integrityFailed = failsOnCorrupt(() => !integrityOk(db));
23931
- if (integrityFailed) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale, integrityFailed };
23932
- if (schemaStale && got !== null) return { row: fail3(D8_STALE_SCHEMA_DETAIL(got, SCHEMA_VERSION), DOCTOR_FIX_UPGRADE), schemaStale, integrityFailed };
24068
+ if (integrityFailed) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale, integrityFailed, orphan: [] };
24069
+ if (schemaStale && got !== null) return { row: fail3(D8_STALE_SCHEMA_DETAIL(got, SCHEMA_VERSION), DOCTOR_FIX_UPGRADE), schemaStale, integrityFailed, orphan: [] };
23933
24070
  return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
23934
24071
  } catch (err) {
23935
- if (isCorrupt2(err)) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true };
24072
+ if (isCorrupt2(err)) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true, orphan: [] };
23936
24073
  return { row: unknown2("D8", message2(err)), ...clean };
23937
24074
  } finally {
23938
24075
  raw?.close();
@@ -24000,7 +24137,8 @@ function fetchCause(err, timeoutMs) {
24000
24137
  const cause = err instanceof Error && err.cause instanceof Error ? err.cause : err;
24001
24138
  const code = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : "";
24002
24139
  const msg = cause instanceof Error ? cause.message : String(cause);
24003
- return D1_NPM_ERROR(code !== "" && !msg.includes(code) ? `${code} ${msg}` : msg);
24140
+ const parts = code !== "" && !msg.includes(code) ? [code, msg] : [msg];
24141
+ return D1_NPM_ERROR(parts.filter((part) => part !== "").join(" "));
24004
24142
  }
24005
24143
  async function npmLatest(url4, tag2, signal, timeoutMs) {
24006
24144
  try {
@@ -24113,9 +24251,9 @@ async function checkNode(i) {
24113
24251
  return pass3("D2", bun.length === 0 ? DOCTOR_PASS_DETAIL : bun.join(D4_REASON_JOIN));
24114
24252
  }
24115
24253
  function checkMcp(ctx) {
24116
- const named = ctx.clientInfo !== void 0 && ctx.clientInfo.name !== "";
24254
+ const named2 = ctx.clientInfo !== void 0 && ctx.clientInfo.name !== "";
24117
24255
  const versioned = ctx.protocolVersion !== void 0 && ctx.protocolVersion !== "";
24118
- return named || versioned ? pass3("D6") : unknown3("D6", D6_UNKNOWN_DETAIL);
24256
+ return named2 || versioned ? pass3("D6") : unknown3("D6", D6_UNKNOWN_DETAIL);
24119
24257
  }
24120
24258
  function piCwdInside(worktree, piCwd) {
24121
24259
  if (piCwd === void 0 || !existsSync8(piCwd)) return false;
@@ -24150,7 +24288,7 @@ import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
24150
24288
 
24151
24289
  // src/setup/spawn-bin.ts
24152
24290
  import { spawnSync } from "node:child_process";
24153
- import { accessSync as accessSync2, constants as fsc, statSync as statSync5 } from "node:fs";
24291
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync6 } from "node:fs";
24154
24292
  import path4 from "node:path";
24155
24293
  var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
24156
24294
  var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
@@ -24168,7 +24306,7 @@ function whichBin(bin, env, platform = process.platform) {
24168
24306
  const f = path4.join(dir, n);
24169
24307
  try {
24170
24308
  accessSync2(f, fsc.X_OK);
24171
- if (statSync5(f).isFile()) return f;
24309
+ if (statSync6(f).isFile()) return f;
24172
24310
  } catch {
24173
24311
  }
24174
24312
  }
@@ -24376,19 +24514,52 @@ function loadFixture(bundleDir2, agent) {
24376
24514
  }
24377
24515
  return { event: e.event, payload: e.payload };
24378
24516
  }
24379
- function payloadFor(payload, worktree) {
24380
- return worktree !== void 0 && isObject5(payload) ? { ...payload, cwd: worktree } : payload;
24381
- }
24382
- function isNativeShape(stdout, exitCode, killed, event) {
24517
+ var CWD_KEY = {
24518
+ "claude-code": "cwd",
24519
+ codex: "cwd",
24520
+ gemini: "cwd",
24521
+ qwen: "cwd",
24522
+ "copilot-cli": "cwd",
24523
+ vscode: "cwd",
24524
+ kiro: "cwd",
24525
+ zcode: "cwd",
24526
+ pi: "cwd",
24527
+ opencode: "directory"
24528
+ };
24529
+ function payloadFor(agent, payload, worktree) {
24530
+ return worktree !== void 0 && isObject5(payload) ? { ...payload, [CWD_KEY[agent]]: worktree } : payload;
24531
+ }
24532
+ var SHAPE = {
24533
+ "claude-code": "claude",
24534
+ codex: "claude",
24535
+ qwen: "claude",
24536
+ vscode: "claude",
24537
+ zcode: "claude",
24538
+ gemini: "gemini",
24539
+ "copilot-cli": "copilot",
24540
+ kiro: "text",
24541
+ pi: "text",
24542
+ opencode: "text"
24543
+ };
24544
+ var COPILOT_KEYS = ["permissionDecision", "additionalContext", "modifiedResult"];
24545
+ function isNativeShape(agent, stdout, exitCode, killed, event) {
24383
24546
  if (killed !== null || exitCode !== 0 && exitCode !== 2) return false;
24384
- if (stdout.length === 0) return true;
24547
+ if (stdout.length === 0 || SHAPE[agent] === "text") return true;
24385
24548
  let out;
24386
24549
  try {
24387
24550
  out = JSON.parse(stdout);
24388
24551
  } catch {
24389
24552
  return false;
24390
24553
  }
24391
- return isObject5(out) && isObject5(out.hookSpecificOutput) && out.hookSpecificOutput.hookEventName === event;
24554
+ if (!isObject5(out)) return false;
24555
+ switch (SHAPE[agent]) {
24556
+ case "claude":
24557
+ return isObject5(out.hookSpecificOutput) && out.hookSpecificOutput.hookEventName === event;
24558
+ case "gemini":
24559
+ return typeof out.decision === "string" || isObject5(out.hookSpecificOutput);
24560
+ default:
24561
+ return COPILOT_KEYS.some((k) => Object.hasOwn(out, k));
24562
+ }
24392
24563
  }
24393
24564
  function codexHookJournaled(db) {
24394
24565
  if (db === null) return false;
@@ -24432,9 +24603,10 @@ async function checkHookRoundTrip(i) {
24432
24603
  const fixed = i.samples === void 0 ? null : Math.max(1, i.samples);
24433
24604
  const maxPairs = fixed ?? D5_MAX_PAIRS;
24434
24605
  const minPairs = fixed ?? D5_MIN_PAIRS;
24606
+ const timeoutMs = i.timeoutMs ?? HOOK_TIMEOUT_MS;
24435
24607
  const bareMs = i.bareMs ?? (async () => {
24436
24608
  const t = performance.now();
24437
- await runProcess([process.execPath, "-e", ""], { cwd: i.bundleDir, env: i.env, signal: i.signal, timeoutMs: HOOK_TIMEOUT_MS });
24609
+ await runProcess([process.execPath, "-e", ""], { cwd: i.bundleDir, env: i.env, signal: i.signal, timeoutMs });
24438
24610
  return performance.now() - t;
24439
24611
  });
24440
24612
  const hookWalls = [];
@@ -24446,11 +24618,11 @@ async function checkHookRoundTrip(i) {
24446
24618
  cwd: i.bundleDir,
24447
24619
  env: i.env,
24448
24620
  signal: i.signal,
24449
- timeoutMs: HOOK_TIMEOUT_MS,
24450
- stdin: JSON.stringify(payloadFor(fixture.payload, i.worktree))
24621
+ timeoutMs,
24622
+ stdin: JSON.stringify(payloadFor(i.agent, fixture.payload, i.worktree))
24451
24623
  });
24452
24624
  hookWalls.push(now() - start);
24453
- if (!isNativeShape(r.stdout.toString("utf8"), r.exitCode, r.killed, fixture.event)) return row("FAIL", D5_SHAPE_DETAIL, D5_FIX);
24625
+ if (!isNativeShape(i.agent, r.stdout.toString("utf8"), r.exitCode, r.killed, fixture.event)) return row("FAIL", D5_SHAPE_DETAIL, D5_FIX);
24454
24626
  bareWalls.push(await bareMs());
24455
24627
  ms = Math.max(0, Math.round(Math.min(...hookWalls) - Math.min(...bareWalls)));
24456
24628
  if (n >= minPairs && ms <= HOOK_P95_MS) break;
@@ -24460,7 +24632,8 @@ async function checkHookRoundTrip(i) {
24460
24632
  }
24461
24633
 
24462
24634
  // src/core/ops/db-heal.ts
24463
- import { existsSync as existsSync11, rmSync as rmSync3 } from "node:fs";
24635
+ import { existsSync as existsSync11, mkdirSync as mkdirSync5, rmSync as rmSync3 } from "node:fs";
24636
+ import { basename as basename4, dirname as dirname7, join as join14 } from "node:path";
24464
24637
 
24465
24638
  // src/core/store/owners.ts
24466
24639
  import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
@@ -24572,6 +24745,39 @@ async function healD8(input) {
24572
24745
  closeDb(await openDb(project));
24573
24746
  return { ...row5, status: "FAIL", detail: D8_HEALED_RECREATE_DETAIL(ts) };
24574
24747
  }
24748
+ function utcStamp(now) {
24749
+ return now.toISOString().slice(0, 19).replaceAll("-", "").replaceAll(":", "") + "Z";
24750
+ }
24751
+ function makeOrphanDir(projectDir) {
24752
+ const base = join14(projectDir, ORPHAN_DIR_PREFIX + utcStamp(/* @__PURE__ */ new Date()));
24753
+ for (let n = 1; ; n += 1) {
24754
+ const dir = n === 1 ? base : base + "-" + String(n);
24755
+ try {
24756
+ mkdirSync5(dir);
24757
+ return dir;
24758
+ } catch (err) {
24759
+ if (err.code !== "EEXIST") throw err;
24760
+ }
24761
+ }
24762
+ }
24763
+ async function healOrphan(project, files, row5) {
24764
+ const moved = [];
24765
+ let dir = "";
24766
+ try {
24767
+ dir = makeOrphanDir(dirname7(project.dbPath));
24768
+ for (const f of files) {
24769
+ const to = join14(dir, basename4(f.path));
24770
+ renameWithRetry(f.path, to);
24771
+ moved.push({ path: to, bytes: f.bytes });
24772
+ }
24773
+ closeDb(await openDb(project));
24774
+ } catch (err) {
24775
+ const cause = err instanceof CtxError ? err.toLine() : err instanceof Error ? err.message : String(err);
24776
+ const at2 = moved.length > 0 ? D8_ORPHAN_HEALED_DETAIL(dir, moved, project.dbPath) : row5.detail;
24777
+ return { ...row5, detail: D8_ORPHAN_MOVE_FAILED(at2, cause) };
24778
+ }
24779
+ return { ...row5, status: "FAIL", detail: D8_ORPHAN_HEALED_DETAIL(dir, moved, project.dbPath), fixCommand: D8_ORPHAN_HEALED_FIX };
24780
+ }
24575
24781
 
24576
24782
  // src/core/ops/report.ts
24577
24783
  function keyIsTyped(key) {
@@ -24627,8 +24833,8 @@ function buildReportHead(input) {
24627
24833
 
24628
24834
  // src/core/ops/doctor-issue.ts
24629
24835
  import { spawnSync as spawnSync3 } from "node:child_process";
24630
- import { closeSync, existsSync as existsSync12, fstatSync, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
24631
- import { delimiter, join as join14 } from "node:path";
24836
+ import { closeSync, existsSync as existsSync12, fstatSync, mkdirSync as mkdirSync6, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
24837
+ import { delimiter, join as join15 } from "node:path";
24632
24838
  var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
24633
24839
  function tildeOf(env) {
24634
24840
  const home = homeDirOf(env);
@@ -24645,9 +24851,9 @@ function tildeOf(env) {
24645
24851
  }
24646
24852
  function maskLine(line) {
24647
24853
  const lower = line.toLowerCase();
24648
- const named = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
24854
+ const named2 = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
24649
24855
  const token = TOKEN_PREFIXES.some((p) => line.includes(p));
24650
- if (!named && !token) return line;
24856
+ if (!named2 && !token) return line;
24651
24857
  const at2 = Math.max(line.indexOf(":"), line.indexOf("="));
24652
24858
  return at2 === -1 ? DOCTOR_MASK : line.slice(0, at2 + 1) + " " + DOCTOR_MASK;
24653
24859
  }
@@ -24669,8 +24875,8 @@ function onPath(env, tool) {
24669
24875
  const out = [];
24670
24876
  for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
24671
24877
  if (dir === "") continue;
24672
- for (const n of names) if (existsSync12(join14(dir, n))) {
24673
- out.push(join14(dir, n));
24878
+ for (const n of names) if (existsSync12(join15(dir, n))) {
24879
+ out.push(join15(dir, n));
24674
24880
  break;
24675
24881
  }
24676
24882
  }
@@ -24716,8 +24922,8 @@ function agentConfig(adapter, env, worktree) {
24716
24922
  const home = homeDirOf(env);
24717
24923
  const files = configPaths(adapter, env, worktree);
24718
24924
  if (home !== null) {
24719
- if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join14(claudeDirOf(env, home), SETTINGS_FILE) });
24720
- if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join14(codexDirOf(env, home), CONFIG_TOML_FILE) });
24925
+ if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join15(claudeDirOf(env, home), SETTINGS_FILE) });
24926
+ if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join15(codexDirOf(env, home), CONFIG_TOML_FILE) });
24721
24927
  }
24722
24928
  const out = [];
24723
24929
  const seen = /* @__PURE__ */ new Set();
@@ -24800,9 +25006,9 @@ async function buildIssueBody(i) {
24800
25006
  async function writeIssueReport(i) {
24801
25007
  const tilde = tildeOf(i.env);
24802
25008
  const body = await buildIssueBody(i);
24803
- const dir = join14(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
24804
- mkdirSync5(dir, { recursive: true });
24805
- const file2 = join14(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
25009
+ const dir = join15(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
25010
+ mkdirSync6(dir, { recursive: true });
25011
+ const file2 = join15(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
24806
25012
  writeFileSync3(file2, body);
24807
25013
  const shown2 = tilde(file2);
24808
25014
  const title = issueTitle(i.adapter.id, i.rows);
@@ -24859,11 +25065,11 @@ async function hookRow(ctx, adapter, host) {
24859
25065
  }
24860
25066
  }
24861
25067
  function ownServerId(configDir, projectKey) {
24862
- const dir = join15(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
25068
+ const dir = join16(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24863
25069
  if (!existsSync13(dir)) return "";
24864
25070
  for (const name of readdirSync5(dir)) {
24865
25071
  if (!name.endsWith(OWNER_PID_EXT)) continue;
24866
- if (readFileSync13(join15(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
25072
+ if (readFileSync13(join16(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
24867
25073
  }
24868
25074
  return "";
24869
25075
  }
@@ -24872,6 +25078,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
24872
25078
  const env = host.env;
24873
25079
  const project = ctx.project;
24874
25080
  let integrityFailed = false;
25081
+ let orphan = [];
24875
25082
  const checks = {
24876
25083
  D1: () => checkVersion({ bundleSha: BUNDLE_SHA, version: bundleVersion(host.bundleDir), registryUrl: D1_REGISTRY_URL, timeoutMs: DOCTOR_GIT_TIMEOUT_MS, env: buildChildEnv(env), cwd: project.worktree, signal: ctx.signal }),
24877
25084
  D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
@@ -24884,6 +25091,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
24884
25091
  D8: async () => {
24885
25092
  const r = await checkDb(project);
24886
25093
  integrityFailed = r.integrityFailed;
25094
+ orphan = r.orphan;
24887
25095
  return r.row;
24888
25096
  },
24889
25097
  D9: () => checkIndex(project),
@@ -24892,8 +25100,13 @@ async function runDoctorChecks(ctx, adapter, host0) {
24892
25100
  };
24893
25101
  const rows = [];
24894
25102
  for (const id of DOCTOR_CHECK_ORDER) rows.push(await guard(id, checks[id]));
24895
- if (!integrityFailed) return rows;
24896
25103
  const at2 = DOCTOR_CHECK_ORDER.indexOf("D8");
25104
+ if (orphan.length > 0) {
25105
+ const files = orphan;
25106
+ rows[at2] = await guard("D8", () => healOrphan(project, files, rows[at2]));
25107
+ return rows;
25108
+ }
25109
+ if (!integrityFailed) return rows;
24897
25110
  rows[at2] = await guard("D8", () => {
24898
25111
  const configDir = resolveConfigDir(env);
24899
25112
  return healD8({ project, configDir, serverId: ownServerId(configDir, project.projectKey), row: rows[at2] });
@@ -24939,7 +25152,7 @@ async function doctorReply(ctx, host) {
24939
25152
  return { text, isError: false, sandboxBytes: bytes5 };
24940
25153
  }
24941
25154
  async function handler2(_input, ctx) {
24942
- return doctorReply(ctx, { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 });
25155
+ return doctorReply(ctx, { env: process.env, bundleDir: dirname8(process.argv[1]), piCwd: void 0 });
24943
25156
  }
24944
25157
  var ctxDoctor = Object.freeze({
24945
25158
  name: "ctx_doctor",
@@ -24953,7 +25166,7 @@ var ctxDoctor = Object.freeze({
24953
25166
  // src/core/tools/execute.ts
24954
25167
  import { existsSync as existsSync14, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "node:fs";
24955
25168
  import { tmpdir as tmpdir2 } from "node:os";
24956
- import { dirname as dirname8, join as join16, parse as parse3, resolve as resolve6 } from "node:path";
25169
+ import { dirname as dirname9, join as join17, parse as parse3, resolve as resolve6 } from "node:path";
24957
25170
 
24958
25171
  // src/core/sandbox/win-build.ts
24959
25172
  var SEPARATORS2 = ";&|(\n";
@@ -25037,7 +25250,7 @@ function schemaLine(issue4) {
25037
25250
  }
25038
25251
  function fileError(given, abs, root) {
25039
25252
  let dir = abs;
25040
- while (!existsSync14(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
25253
+ while (!existsSync14(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
25041
25254
  if (isInside(root, dir)) return null;
25042
25255
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
25043
25256
  }
@@ -25118,8 +25331,8 @@ async function handler3(raw, ctx) {
25118
25331
  if (takesDashC(input.language, runtime)) {
25119
25332
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
25120
25333
  } else {
25121
- tmpDir = mkdtempSync(join16(tmpdir2(), TMP_PREFIX));
25122
- const file2 = join16(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
25334
+ tmpDir = mkdtempSync(join17(tmpdir2(), TMP_PREFIX));
25335
+ const file2 = join17(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
25123
25336
  writeFileSync4(file2, scriptText(input.language, input.code), "utf8");
25124
25337
  argv = scriptArgv(input.language, runtime, file2);
25125
25338
  }
@@ -25154,12 +25367,12 @@ var ctxExecute = {
25154
25367
  };
25155
25368
 
25156
25369
  // src/core/tools/index.ts
25157
- import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as statSync7 } from "node:fs";
25158
- import { dirname as dirname9, extname, join as join18, relative as relative3, resolve as resolve7 } from "node:path";
25370
+ import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as statSync8 } from "node:fs";
25371
+ import { dirname as dirname10, extname, join as join19, relative as relative3, resolve as resolve7 } from "node:path";
25159
25372
 
25160
25373
  // src/core/index/walk.ts
25161
- import { readdirSync as readdirSync6, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync6 } from "node:fs";
25162
- import { join as join17 } from "node:path";
25374
+ import { readdirSync as readdirSync6, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync7 } from "node:fs";
25375
+ import { join as join18 } from "node:path";
25163
25376
  var GITIGNORE = ".gitignore";
25164
25377
  var GIT_DIR = ".git";
25165
25378
  function walkDir(root, containmentRoot) {
@@ -25168,7 +25381,7 @@ function walkDir(root, containmentRoot) {
25168
25381
  const found = [];
25169
25382
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
25170
25383
  found.sort(compareFound);
25171
- return found.map((f) => ({ absPath: f.absPath, relPath: join17(...f.dir, f.name) }));
25384
+ return found.map((f) => ({ absPath: f.absPath, relPath: join18(...f.dir, f.name) }));
25172
25385
  }
25173
25386
  function visit(abs, rel, parent, contain, seen, found) {
25174
25387
  let entries;
@@ -25177,10 +25390,10 @@ function visit(abs, rel, parent, contain, seen, found) {
25177
25390
  } catch {
25178
25391
  return;
25179
25392
  }
25180
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join17(abs, GITIGNORE), rel)) : parent;
25393
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join18(abs, GITIGNORE), rel)) : parent;
25181
25394
  for (const e of entries) {
25182
25395
  if (e.name === GIT_DIR) continue;
25183
- const path7 = join17(abs, e.name);
25396
+ const path7 = join18(abs, e.name);
25184
25397
  let isDir = e.isDirectory();
25185
25398
  let isFile = e.isFile();
25186
25399
  let target = path7;
@@ -25192,7 +25405,7 @@ function visit(abs, rel, parent, contain, seen, found) {
25192
25405
  continue;
25193
25406
  }
25194
25407
  if (!isInside(contain, resolved)) continue;
25195
- const st = statSync6(resolved);
25408
+ const st = statSync7(resolved);
25196
25409
  isDir = st.isDirectory();
25197
25410
  isFile = st.isFile();
25198
25411
  target = resolved;
@@ -29310,7 +29523,7 @@ function readUtf8(absPath) {
29310
29523
  }
29311
29524
  function missingOrOutside(given, abs, root) {
29312
29525
  let dir = abs;
29313
- while (!existsSync15(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
29526
+ while (!existsSync15(dir) && dirname10(dir) !== dir) dir = dirname10(dir);
29314
29527
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
29315
29528
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
29316
29529
  }
@@ -29318,10 +29531,10 @@ function pathItems(input, project) {
29318
29531
  const abs = resolve7(project.worktree, input.path);
29319
29532
  if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
29320
29533
  const base = relative3(project.worktree, abs);
29321
- if (statSync7(abs).isDirectory()) {
29534
+ if (statSync8(abs).isDirectory()) {
29322
29535
  return walkDir(abs, project.containmentRoot).map((f) => ({
29323
29536
  sourceKind: "path",
29324
- label: pathLabel(join18(base, f.relPath)),
29537
+ label: pathLabel(join19(base, f.relPath)),
29325
29538
  kind: kindOfPath(f.relPath),
29326
29539
  read: () => readUtf8(f.absPath)
29327
29540
  }));
@@ -29393,8 +29606,9 @@ async function handler4(input, ctx) {
29393
29606
  } finally {
29394
29607
  closeDb(db);
29395
29608
  }
29396
- const shown2 = Buffer.byteLength(from, "utf8") > ECHO_MAX_BYTES ? sourceHandle(lastId) : from;
29397
- const line = ["Indexed " + sources + " source(s), " + chunks + " chunk(s) from " + shown2 + ".", ...notes].join("\n");
29609
+ const head = "Indexed " + sources + " source(s), " + chunks + " chunk(s) from ";
29610
+ const first = sources === 1 && lastId > 0 ? head + sourceHandle(lastId) + ". " + indexedLabelLine(from, lastId) : head + shownLabel(from, null) + ".";
29611
+ const line = [first, ...notes].join("\n");
29398
29612
  return {
29399
29613
  text: capBytes(line, OUTPUT_CAP).text,
29400
29614
  isError: false,
@@ -29438,7 +29652,7 @@ function purgeScope(db, scope, input) {
29438
29652
  const raw = db.raw;
29439
29653
  if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
29440
29654
  if (scope === "source") {
29441
- const label2 = storedLabel(db, input.source);
29655
+ const label2 = pickSource(db, input.source, false).label;
29442
29656
  return deleteChunkRows(raw, { label: label2 }) + changes(raw, "DELETE FROM sources WHERE label = ?", label2);
29443
29657
  }
29444
29658
  const chunks = deleteChunkRows(raw, "all");
@@ -29637,6 +29851,9 @@ function bytes4(n) {
29637
29851
  }
29638
29852
  return v.toFixed(1) + " " + UNITS[u];
29639
29853
  }
29854
+ function right(v, width) {
29855
+ return " " + v.padStart(width - 1);
29856
+ }
29640
29857
  function pct(t) {
29641
29858
  return (t.saved * PERCENT_SCALE / Math.max(1, t.produced)).toFixed(1) + "%";
29642
29859
  }
@@ -29660,8 +29877,8 @@ function plural(n, word) {
29660
29877
  }
29661
29878
  function table2(title, rows) {
29662
29879
  const max = Math.max(0, ...rows.map((r) => r.saved));
29663
- 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);
29664
- 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())];
29880
+ const head = " " + title.padEnd(LABEL_W) + right("Calls", STATS_CALLS_W) + right("Made", NUM_W) + right("Sent", NUM_W) + right("Kept out", NUM_W) + right("%", PCT_W);
29881
+ return [head, ...rows.map((r) => (" " + label(r.name) + right(count(r.calls), STATS_CALLS_W) + right(bytes4(r.produced), NUM_W) + right(bytes4(r.returned), NUM_W) + right(bytes4(r.saved), NUM_W) + right(pct(r), PCT_W) + " " + bar(r.saved, max, STATS_ROW_BAR)).trimEnd())];
29665
29882
  }
29666
29883
  function bySaved(a, b) {
29667
29884
  return b.saved - a.saved || b.produced - a.produced || a.returned - b.returned || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
@@ -29673,14 +29890,14 @@ function joinIndex(tools) {
29673
29890
  const idx = tools.filter((t2) => STATS_INDEX_TOOLS.includes(t2.name));
29674
29891
  if (idx.length <= 1) return tools;
29675
29892
  const t = sum(idx);
29676
- const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: t.produced - t.returned };
29893
+ const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: Math.max(0, t.produced - t.returned) };
29677
29894
  return [...tools.filter((x) => !idx.includes(x)), one];
29678
29895
  }
29679
29896
  function toolRows(tools) {
29680
- const named = joinIndex(tools.map((t) => ({ ...t, saved: t.produced - t.returned }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
29681
- const zero = named.filter((t) => t.saved <= 0);
29897
+ const named2 = joinIndex(tools.map((t) => ({ ...t, saved: Math.max(0, t.produced - t.returned) }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
29898
+ const zero = named2.filter((t) => t.saved <= 0);
29682
29899
  const fold2 = zero.length > 1 ? zero : [];
29683
- const keep = named.filter((t) => !fold2.includes(t));
29900
+ const keep = named2.filter((t) => !fold2.includes(t));
29684
29901
  const room = fold2.length > 0 ? STATS_MAX_TOOL_ROWS - 1 : STATS_MAX_TOOL_ROWS;
29685
29902
  const over = keep.length > room;
29686
29903
  const shown2 = over ? keep.slice(0, STATS_MAX_TOOL_ROWS - 1) : keep;
@@ -29748,7 +29965,7 @@ function lastDays(week, allCalls) {
29748
29965
  return [
29749
29966
  head,
29750
29967
  ...card,
29751
- ...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)] : []),
29968
+ ...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) + right(bytes4(saved[i]), NUM_W)] : []),
29752
29969
  " " + STATS_WAYS.map(([, ch, name]) => `${ch} ${name}`).join(" "),
29753
29970
  ""
29754
29971
  ];
@@ -29776,8 +29993,8 @@ function report(f, sessionId, agent) {
29776
29993
  ...head,
29777
29994
  `${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
29778
29995
  ` ${bytes4(focus.produced)} became ${bytes4(focus.returned)}: ${bytes4(focus.saved)} kept out (${pct(focus)})`,
29779
- " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.produced).padStart(NUM_W),
29780
- " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.returned).padStart(NUM_W),
29996
+ " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + right(bytes4(focus.produced), NUM_W),
29997
+ " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + right(bytes4(focus.returned), NUM_W),
29781
29998
  ...focus.saved > 0 ? [windowLine(focus.saved), STATS_TOKEN_NOTE] : [],
29782
29999
  ...hookLine(f.redirected, f.replaced),
29783
30000
  "",
@@ -29791,7 +30008,7 @@ function report(f, sessionId, agent) {
29791
30008
  "",
29792
30009
  ...f.top.length > 0 ? [
29793
30010
  "Largest single outputs (made \u2192 sent to the chat)",
29794
- ...f.top.map((t) => " " + label(toolName(t.name)) + bytes4(t.produced).padStart(NUM_W) + " \u2192 " + bytes4(t.returned).padStart(NUM_W)),
30011
+ ...f.top.map((t) => " " + label(toolName(t.name)) + right(bytes4(t.produced), NUM_W) + " \u2192 " + right(bytes4(t.returned), NUM_W)),
29795
30012
  ""
29796
30013
  ] : []
29797
30014
  ];
@@ -29800,10 +30017,10 @@ function report(f, sessionId, agent) {
29800
30017
  if (!agents.has(agent)) agents.set(agent, EMPTY5);
29801
30018
  lines.push("By agent (this project)", ...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29802
30019
  const maxKind = Math.max(0, ...[...f.kinds.values()].map((k) => k.project));
29803
- lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + "Session".padStart(STATS_KIND_W) + "Project".padStart(STATS_KIND_W));
30020
+ lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + right("Session", STATS_KIND_W) + right("Project", STATS_KIND_W));
29804
30021
  for (const [kind, name] of STATS_KIND_LABELS) {
29805
30022
  const k = f.kinds.get(kind) ?? { session: 0, project: 0 };
29806
- lines.push((" " + label(name) + int2(k.session).padStart(STATS_KIND_W) + int2(k.project).padStart(STATS_KIND_W) + " " + bar(k.project, maxKind, STATS_KIND_BAR)).trimEnd());
30023
+ lines.push((" " + label(name) + right(int2(k.session), STATS_KIND_W) + right(int2(k.project), STATS_KIND_W) + " " + bar(k.project, maxKind, STATS_KIND_BAR)).trimEnd());
29807
30024
  }
29808
30025
  lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
29809
30026
  lines.push(
@@ -29820,7 +30037,14 @@ async function handler7(_input, ctx) {
29820
30037
  const db = await openDb(ctx.project, { readOnly: true });
29821
30038
  let facts;
29822
30039
  try {
29823
- facts = readFacts(db.raw, ctx.sessionId);
30040
+ db.raw.exec("BEGIN DEFERRED");
30041
+ try {
30042
+ facts = readFacts(db.raw, ctx.sessionId);
30043
+ db.raw.exec("COMMIT");
30044
+ } catch (err) {
30045
+ if (db.raw.isTransaction) db.raw.exec("ROLLBACK");
30046
+ throw err;
30047
+ }
29824
30048
  } finally {
29825
30049
  closeDb(db);
29826
30050
  }
@@ -29851,11 +30075,11 @@ var ctxStats = Object.freeze({
29851
30075
 
29852
30076
  // src/core/tools/upgrade.ts
29853
30077
  import { existsSync as existsSync21, realpathSync as realpathSync10, rmSync as rmSync9 } from "node:fs";
29854
- import { basename as basename6, dirname as dirname11, join as join24 } from "node:path";
30078
+ import { basename as basename7, dirname as dirname12, join as join25 } from "node:path";
29855
30079
 
29856
30080
  // src/core/ops/host-write.ts
29857
- import { copyFileSync, existsSync as existsSync16, mkdirSync as mkdirSync6, writeFileSync as writeFileSync5 } from "node:fs";
29858
- import { dirname as dirname10, join as join19 } from "node:path";
30081
+ import { copyFileSync, existsSync as existsSync16, mkdirSync as mkdirSync7, writeFileSync as writeFileSync5 } from "node:fs";
30082
+ import { dirname as dirname11, join as join20 } from "node:path";
29859
30083
  function defaultWrite(file2, text) {
29860
30084
  writeFileSync5(file2, text, "utf8");
29861
30085
  }
@@ -29864,14 +30088,14 @@ function hostConfigPath(agent, home, env) {
29864
30088
  if (own4 !== void 0) return ownMcpFileOf(agent, own4.file, env, home);
29865
30089
  switch (agent) {
29866
30090
  case "opencode":
29867
- return join19(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
30091
+ return join20(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29868
30092
  // D-WIN-OPENCODE-DIR-1
29869
30093
  case "pi":
29870
- return join19(piAgentDirOf(env, home), SETTINGS_FILE);
30094
+ return join20(piAgentDirOf(env, home), SETTINGS_FILE);
29871
30095
  case "copilot-cli":
29872
30096
  return null;
29873
30097
  default:
29874
- return join19(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
30098
+ return join20(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29875
30099
  }
29876
30100
  }
29877
30101
  function cell3(value) {
@@ -29884,7 +30108,7 @@ function writeWithRollback(file2, text, write2, atomic) {
29884
30108
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
29885
30109
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
29886
30110
  const had = existsSync16(file2);
29887
- mkdirSync6(dirname10(file2), { recursive: true });
30111
+ mkdirSync7(dirname11(file2), { recursive: true });
29888
30112
  if (had) copyFileSync(file2, trash);
29889
30113
  try {
29890
30114
  write2(tmp, text);
@@ -29922,7 +30146,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
29922
30146
 
29923
30147
  // src/core/ops/plugin-swap.ts
29924
30148
  import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
29925
- import { basename as basename5, join as join20, win32 as win322 } from "node:path";
30149
+ import { basename as basename6, join as join21, win32 as win322 } from "node:path";
29926
30150
  function linkTarget(path7, win) {
29927
30151
  if (!isLink(path7)) return null;
29928
30152
  const target = readlinkSync(path7);
@@ -29941,11 +30165,11 @@ function settleLinks(link, tmp, old, opts) {
29941
30165
  else renameWithRetry(old, link, opts);
29942
30166
  }
29943
30167
  function swapPluginCurrent(agentDir, sha, opts = {}) {
29944
- const next = join20(agentDir, sha);
30168
+ const next = join21(agentDir, sha);
29945
30169
  if (!existsSync17(next) || !lstatSync(next).isDirectory()) {
29946
- throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
30170
+ throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename6(agentDir), path: next });
29947
30171
  }
29948
- const link = join20(agentDir, PLUGIN_CURRENT_LINK);
30172
+ const link = join21(agentDir, PLUGIN_CURRENT_LINK);
29949
30173
  const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
29950
30174
  const old = link + PLUGIN_LINK_OLD_SUFFIX;
29951
30175
  settleLinks(link, tmp, old, opts);
@@ -29960,15 +30184,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
29960
30184
  if (before !== null) unlinkSync2(old);
29961
30185
  const keep = /* @__PURE__ */ new Set([sha]);
29962
30186
  if (before !== null) keep.add(before);
29963
- const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join20(agentDir, name));
30187
+ const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join21(agentDir, name));
29964
30188
  for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
29965
- const previous = before !== null && existsSync17(join20(agentDir, before)) ? join20(agentDir, before) : null;
30189
+ const previous = before !== null && existsSync17(join21(agentDir, before)) ? join21(agentDir, before) : null;
29966
30190
  return { current: next, previous, removed };
29967
30191
  }
29968
30192
 
29969
30193
  // src/core/ops/release-fetch.ts
29970
- import { existsSync as existsSync18, mkdirSync as mkdirSync7, rmSync as rmSync6 } from "node:fs";
29971
- import { join as join21 } from "node:path";
30194
+ import { existsSync as existsSync18, mkdirSync as mkdirSync8, rmSync as rmSync6 } from "node:fs";
30195
+ import { join as join22 } from "node:path";
29972
30196
  function failed(r) {
29973
30197
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
29974
30198
  const status = r.killed ?? String(r.exitCode);
@@ -29980,9 +30204,9 @@ async function git2(bin, args, cwd, env, signal) {
29980
30204
  return r.stdout.toString().trim();
29981
30205
  }
29982
30206
  async function fetchRelease(agent, url4, env, signal, opts = {}) {
29983
- const agentDir = join21(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
29984
- mkdirSync7(agentDir, { recursive: true });
29985
- const fetchDir = join21(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
30207
+ const agentDir = join22(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
30208
+ mkdirSync8(agentDir, { recursive: true });
30209
+ const fetchDir = join22(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29986
30210
  rmSync6(fetchDir, { recursive: true, force: true });
29987
30211
  const gitBin = findRuntime(GIT_BIN, env);
29988
30212
  if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -29990,7 +30214,7 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
29990
30214
  try {
29991
30215
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url4, fetchDir], agentDir, childEnv, signal);
29992
30216
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
29993
- const dir = join21(agentDir, sha);
30217
+ const dir = join22(agentDir, sha);
29994
30218
  if (existsSync18(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29995
30219
  else renameWithRetry(fetchDir, dir, opts);
29996
30220
  return { sha, dir };
@@ -30002,14 +30226,14 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
30002
30226
 
30003
30227
  // src/core/ops/uninstall.ts
30004
30228
  import { existsSync as existsSync19, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
30005
- import { join as join22 } from "node:path";
30229
+ import { join as join23 } from "node:path";
30006
30230
  function row2(area, before, after) {
30007
30231
  return { area, before, after };
30008
30232
  }
30009
30233
  function stopServers(configDir, projectKey) {
30010
30234
  const stopped = listLiveOwners(configDir, projectKey);
30011
- const dir = join22(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
30012
- for (const serverId of stopped) writeFileSync6(join22(dir, serverId + OWNER_STOP_EXT), "", "utf8");
30235
+ const dir = join23(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
30236
+ for (const serverId of stopped) writeFileSync6(join23(dir, serverId + OWNER_STOP_EXT), "", "utf8");
30013
30237
  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 };
30014
30238
  }
30015
30239
  function rootOrNull(adapter, env) {
@@ -30027,14 +30251,14 @@ function removeCache(adapter, env, configDir) {
30027
30251
  const root = rootOrNull(adapter, env);
30028
30252
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
30029
30253
  if (adapter.installMode === "marketplace") {
30030
- const cache = join22(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
30254
+ const cache = join23(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
30031
30255
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
30032
30256
  }
30033
30257
  rmSync7(root, { recursive: true, force: true });
30034
30258
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
30035
30259
  }
30036
30260
  case "plugin": {
30037
- const agentDir = join22(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
30261
+ const agentDir = join23(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
30038
30262
  if (!existsSync19(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
30039
30263
  rmSync7(agentDir, { recursive: true, force: true });
30040
30264
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
@@ -30080,7 +30304,7 @@ function ownEntries(agent, env) {
30080
30304
  }
30081
30305
  if (agent === "opencode") {
30082
30306
  return [{
30083
- file: join22(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
30307
+ file: join23(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
30084
30308
  // D-WIN-OPENCODE-DIR-1
30085
30309
  key: OPENCODE_PLUGIN_KEY,
30086
30310
  shown: OPENCODE_PLUGIN_KEY,
@@ -30091,7 +30315,7 @@ function ownEntries(agent, env) {
30091
30315
  if (agent === "pi") {
30092
30316
  const agentDir = piAgentDirOf(env, home);
30093
30317
  return [{
30094
- file: join22(agentDir, SETTINGS_FILE),
30318
+ file: join23(agentDir, SETTINGS_FILE),
30095
30319
  key: PI_PACKAGES_KEY,
30096
30320
  shown: PI_PACKAGES_KEY,
30097
30321
  has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
@@ -30113,12 +30337,12 @@ function removeOwnEntries(agent, env) {
30113
30337
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
30114
30338
  }
30115
30339
  function removeProjectData(configDir, projectKey) {
30116
- const projects = join22(configDir, PROJECTS_DIR_NAME);
30117
- const dir = join22(projects, projectKey);
30340
+ const projects = join23(configDir, PROJECTS_DIR_NAME);
30341
+ const dir = join23(projects, projectKey);
30118
30342
  if (!existsSync19(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
30119
30343
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
30120
30344
  for (const name of readdirSync8(dir)) {
30121
- if (name !== OWNERS_DIR_NAME) rmSync7(join22(dir, name), { recursive: true, force: true });
30345
+ if (name !== OWNERS_DIR_NAME) rmSync7(join23(dir, name), { recursive: true, force: true });
30122
30346
  }
30123
30347
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
30124
30348
  }
@@ -30126,7 +30350,7 @@ function runUninstall(input) {
30126
30350
  const configDir = resolveConfigDir(input.env);
30127
30351
  const stop = stopServers(configDir, input.project.projectKey);
30128
30352
  const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
30129
- rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join22(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
30353
+ rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join23(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
30130
30354
  return { rows, stopped: stop.stopped };
30131
30355
  }
30132
30356
 
@@ -30263,7 +30487,7 @@ function removeV1(agent, findings) {
30263
30487
  // src/core/ops/verify-sums.ts
30264
30488
  import { createHash as createHash2 } from "node:crypto";
30265
30489
  import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "node:fs";
30266
- import { join as join23 } from "node:path";
30490
+ import { join as join24 } from "node:path";
30267
30491
  function mismatch() {
30268
30492
  return new CtxError("BUNDLE_HASH_MISMATCH");
30269
30493
  }
@@ -30284,14 +30508,14 @@ function walk3(dir, prefix, out) {
30284
30508
  for (const entry of readdirSync9(dir, { withFileTypes: true })) {
30285
30509
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
30286
30510
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
30287
- const abs = join23(dir, entry.name);
30511
+ const abs = join24(dir, entry.name);
30288
30512
  if (entry.isDirectory()) walk3(abs, rel, out);
30289
30513
  else if (entry.isFile()) out.set(rel, abs);
30290
30514
  else throw mismatch();
30291
30515
  }
30292
30516
  }
30293
30517
  function verifySums(dir) {
30294
- const sumsPath = join23(dir, RELEASE_SUMS_FILE);
30518
+ const sumsPath = join24(dir, RELEASE_SUMS_FILE);
30295
30519
  const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
30296
30520
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
30297
30521
  const sums = parseSums(readFileSync17(sumsPath, "utf8"));
@@ -30315,7 +30539,7 @@ function row4(area, before, after) {
30315
30539
  return { area, before, after };
30316
30540
  }
30317
30541
  function bundleDir() {
30318
- return dirname11(process.argv[1] ?? "");
30542
+ return dirname12(process.argv[1] ?? "");
30319
30543
  }
30320
30544
  function pluginRootRow(adapter, env) {
30321
30545
  const own4 = bundleDir();
@@ -30329,12 +30553,12 @@ function pluginRootRow(adapter, env) {
30329
30553
  return root === own4 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own4)];
30330
30554
  }
30331
30555
  function isCurrent(agentDir, dir) {
30332
- const link = join24(agentDir, PLUGIN_CURRENT_LINK);
30556
+ const link = join25(agentDir, PLUGIN_CURRENT_LINK);
30333
30557
  return existsSync21(link) && realpathSync10.native(link) === realpathSync10.native(dir);
30334
30558
  }
30335
30559
  async function checkout(adapter, deps) {
30336
30560
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);
30337
- const agentDir = dirname11(fetched.dir);
30561
+ const agentDir = dirname12(fetched.dir);
30338
30562
  try {
30339
30563
  verifySums(fetched.dir);
30340
30564
  } catch (err) {
@@ -30362,7 +30586,7 @@ async function upgrade(adapter, deps, home) {
30362
30586
  return rows;
30363
30587
  } catch (err) {
30364
30588
  removal?.rollback();
30365
- if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename6(done.swap.previous));
30589
+ if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename7(done.swap.previous));
30366
30590
  throw err;
30367
30591
  }
30368
30592
  }
@@ -30451,7 +30675,7 @@ function checkCall(tool, input) {
30451
30675
  // src/entries/server.ts
30452
30676
  import { randomUUID } from "node:crypto";
30453
30677
  import { existsSync as existsSync23, realpathSync as realpathSync12, rmSync as rmSync11 } from "node:fs";
30454
- import { dirname as dirname12, join as join26 } from "node:path";
30678
+ import { dirname as dirname13, join as join27 } from "node:path";
30455
30679
  import { fileURLToPath as fileURLToPath2 } from "node:url";
30456
30680
 
30457
30681
  // node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
@@ -33325,14 +33549,14 @@ var $ZodIntersection2 = /* @__PURE__ */ $constructor2("$ZodIntersection", (inst,
33325
33549
  inst._zod.parse = (payload, ctx) => {
33326
33550
  const input = payload.value;
33327
33551
  const left = def.left._zod.run({ value: input, issues: [] }, ctx);
33328
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
33329
- const async = left instanceof Promise || right instanceof Promise;
33552
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
33553
+ const async = left instanceof Promise || right2 instanceof Promise;
33330
33554
  if (async) {
33331
- return Promise.all([left, right]).then(([left2, right2]) => {
33332
- return handleIntersectionResults2(payload, left2, right2);
33555
+ return Promise.all([left, right2]).then(([left2, right3]) => {
33556
+ return handleIntersectionResults2(payload, left2, right3);
33333
33557
  });
33334
33558
  }
33335
- return handleIntersectionResults2(payload, left, right);
33559
+ return handleIntersectionResults2(payload, left, right2);
33336
33560
  };
33337
33561
  });
33338
33562
  function mergeValues2(a, b) {
@@ -33383,7 +33607,7 @@ function mergeValues2(a, b) {
33383
33607
  }
33384
33608
  return { valid: false, mergeErrorPath: [] };
33385
33609
  }
33386
- function handleIntersectionResults2(result, left, right) {
33610
+ function handleIntersectionResults2(result, left, right2) {
33387
33611
  const unrecKeys = /* @__PURE__ */ new Map();
33388
33612
  let unrecIssue;
33389
33613
  const keyIssues = /* @__PURE__ */ new Map();
@@ -33411,7 +33635,7 @@ function handleIntersectionResults2(result, left, right) {
33411
33635
  if (!collect(iss, "l"))
33412
33636
  result.issues.push(iss);
33413
33637
  }
33414
- for (const iss of right.issues) {
33638
+ for (const iss of right2.issues) {
33415
33639
  if (!collect(iss, "r"))
33416
33640
  result.issues.push(iss);
33417
33641
  }
@@ -33425,7 +33649,7 @@ function handleIntersectionResults2(result, left, right) {
33425
33649
  result.issues.push(keyIssues.get(k));
33426
33650
  }
33427
33651
  }
33428
- const merged = mergeValues2(left.value, right.value);
33652
+ const merged = mergeValues2(left.value, right2.value);
33429
33653
  if (!merged.valid) {
33430
33654
  if (aborted2(result))
33431
33655
  return result;
@@ -33815,11 +34039,11 @@ var $ZodPipe2 = /* @__PURE__ */ $constructor2("$ZodPipe", (inst, def) => {
33815
34039
  defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);
33816
34040
  inst._zod.parse = (payload, ctx) => {
33817
34041
  if (ctx.direction === "backward") {
33818
- const right = def.out._zod.run(payload, ctx);
33819
- if (right instanceof Promise) {
33820
- return right.then((right2) => handlePipeResult2(right2, def.in, ctx));
34042
+ const right2 = def.out._zod.run(payload, ctx);
34043
+ if (right2 instanceof Promise) {
34044
+ return right2.then((right3) => handlePipeResult2(right3, def.in, ctx));
33821
34045
  }
33822
- return handlePipeResult2(right, def.in, ctx);
34046
+ return handlePipeResult2(right2, def.in, ctx);
33823
34047
  }
33824
34048
  const left = def.in._zod.run(payload, ctx);
33825
34049
  if (left instanceof Promise) {
@@ -36789,11 +37013,11 @@ var ZodIntersection2 = /* @__PURE__ */ $constructor2("ZodIntersection", (inst, d
36789
37013
  ZodType2.init(inst, def);
36790
37014
  inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params);
36791
37015
  });
36792
- function intersection2(left, right) {
37016
+ function intersection2(left, right2) {
36793
37017
  return new ZodIntersection2({
36794
37018
  type: "intersection",
36795
37019
  left,
36796
- right
37020
+ right: right2
36797
37021
  });
36798
37022
  }
36799
37023
  var ZodRecord2 = /* @__PURE__ */ $constructor2("ZodRecord", (inst, def) => {
@@ -40854,14 +41078,14 @@ var $ZodIntersection3 = /* @__PURE__ */ $constructor3("$ZodIntersection", (inst,
40854
41078
  inst._zod.parse = (payload, ctx) => {
40855
41079
  const input = payload.value;
40856
41080
  const left = def.left._zod.run({ value: input, issues: [] }, ctx);
40857
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
40858
- const async = left instanceof Promise || right instanceof Promise;
41081
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
41082
+ const async = left instanceof Promise || right2 instanceof Promise;
40859
41083
  if (async) {
40860
- return Promise.all([left, right]).then(([left2, right2]) => {
40861
- return handleIntersectionResults3(payload, left2, right2);
41084
+ return Promise.all([left, right2]).then(([left2, right3]) => {
41085
+ return handleIntersectionResults3(payload, left2, right3);
40862
41086
  });
40863
41087
  }
40864
- return handleIntersectionResults3(payload, left, right);
41088
+ return handleIntersectionResults3(payload, left, right2);
40865
41089
  };
40866
41090
  });
40867
41091
  function mergeValues3(a, b) {
@@ -40912,7 +41136,7 @@ function mergeValues3(a, b) {
40912
41136
  }
40913
41137
  return { valid: false, mergeErrorPath: [] };
40914
41138
  }
40915
- function handleIntersectionResults3(result, left, right) {
41139
+ function handleIntersectionResults3(result, left, right2) {
40916
41140
  const unrecKeys = /* @__PURE__ */ new Map();
40917
41141
  let unrecIssue;
40918
41142
  const keyIssues = /* @__PURE__ */ new Map();
@@ -40940,7 +41164,7 @@ function handleIntersectionResults3(result, left, right) {
40940
41164
  if (!collect(iss, "l"))
40941
41165
  result.issues.push(iss);
40942
41166
  }
40943
- for (const iss of right.issues) {
41167
+ for (const iss of right2.issues) {
40944
41168
  if (!collect(iss, "r"))
40945
41169
  result.issues.push(iss);
40946
41170
  }
@@ -40954,7 +41178,7 @@ function handleIntersectionResults3(result, left, right) {
40954
41178
  result.issues.push(keyIssues.get(k));
40955
41179
  }
40956
41180
  }
40957
- const merged = mergeValues3(left.value, right.value);
41181
+ const merged = mergeValues3(left.value, right2.value);
40958
41182
  if (!merged.valid) {
40959
41183
  if (aborted3(result))
40960
41184
  return result;
@@ -41344,11 +41568,11 @@ var $ZodPipe3 = /* @__PURE__ */ $constructor3("$ZodPipe", (inst, def) => {
41344
41568
  defineLazyInternal2(inst, "propValues", (zod) => zod.def.in._zod.propValues);
41345
41569
  inst._zod.parse = (payload, ctx) => {
41346
41570
  if (ctx.direction === "backward") {
41347
- const right = def.out._zod.run(payload, ctx);
41348
- if (right instanceof Promise) {
41349
- return right.then((right2) => handlePipeResult3(right2, def.in, ctx));
41571
+ const right2 = def.out._zod.run(payload, ctx);
41572
+ if (right2 instanceof Promise) {
41573
+ return right2.then((right3) => handlePipeResult3(right3, def.in, ctx));
41350
41574
  }
41351
- return handlePipeResult3(right, def.in, ctx);
41575
+ return handlePipeResult3(right2, def.in, ctx);
41352
41576
  }
41353
41577
  const left = def.in._zod.run(payload, ctx);
41354
41578
  if (left instanceof Promise) {
@@ -44404,11 +44628,11 @@ var ZodIntersection3 = /* @__PURE__ */ $constructor3("ZodIntersection", (inst, d
44404
44628
  ZodType3.init(inst, def);
44405
44629
  inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor2(inst, ctx, json2, params);
44406
44630
  });
44407
- function intersection3(left, right) {
44631
+ function intersection3(left, right2) {
44408
44632
  return new ZodIntersection3({
44409
44633
  type: "intersection",
44410
44634
  left,
44411
- right
44635
+ right: right2
44412
44636
  });
44413
44637
  }
44414
44638
  var ZodRecord3 = /* @__PURE__ */ $constructor3("ZodRecord", (inst, def) => {
@@ -58517,7 +58741,7 @@ function installExitGuard(opts) {
58517
58741
 
58518
58742
  // src/core/store/cleanup.ts
58519
58743
  import { existsSync as existsSync22, readdirSync as readdirSync10, rmSync as rmSync10 } from "node:fs";
58520
- import { join as join25 } from "node:path";
58744
+ import { join as join26 } from "node:path";
58521
58745
  function deleteSource(raw, id) {
58522
58746
  raw.prepare("DELETE FROM sources WHERE id = ?").run(id);
58523
58747
  deleteChunkRows(raw, { sourceId: id });
@@ -58573,8 +58797,8 @@ function lastAccess(raw) {
58573
58797
  return row5.t;
58574
58798
  }
58575
58799
  function sweepOne(configDir, projectKey, cutoff) {
58576
- const dir = join25(configDir, PROJECTS_DIR_NAME, projectKey);
58577
- const db = openForSweep(join25(dir, DB_FILE_NAME), projectKey);
58800
+ const dir = join26(configDir, PROJECTS_DIR_NAME, projectKey);
58801
+ const db = openForSweep(join26(dir, DB_FILE_NAME), projectKey);
58578
58802
  let dead;
58579
58803
  try {
58580
58804
  dead = withWrite(db, (h) => listLiveOwners(configDir, projectKey).length === 0 && lastAccess(h.raw) < cutoff);
@@ -58587,7 +58811,7 @@ function sweepOne(configDir, projectKey, cutoff) {
58587
58811
  function sweepDeadProjects(configDir) {
58588
58812
  let entries;
58589
58813
  try {
58590
- entries = readdirSync10(join25(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
58814
+ entries = readdirSync10(join26(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
58591
58815
  } catch (err) {
58592
58816
  if (err.code === "ENOENT") return [];
58593
58817
  throw err;
@@ -58696,7 +58920,7 @@ function workspaceCwdOf(meta3, spawnCwd, script) {
58696
58920
  const fromHost = workspaceFromMeta(meta3);
58697
58921
  if (fromHost !== void 0) return fromHost;
58698
58922
  if (script === void 0 || script === "") return spawnCwd;
58699
- return realOrSame(spawnCwd) === realOrSame(dirname12(script)) ? "" : spawnCwd;
58923
+ return realOrSame(spawnCwd) === realOrSame(dirname13(script)) ? "" : spawnCwd;
58700
58924
  }
58701
58925
  function errorReply(err) {
58702
58926
  if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0 };
@@ -58739,7 +58963,7 @@ async function startServer(argv, env) {
58739
58963
  return db;
58740
58964
  }
58741
58965
  function stopMarker(configDir, projectKey) {
58742
- return join26(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
58966
+ return join27(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
58743
58967
  }
58744
58968
  function stopRequested() {
58745
58969
  const configDir = resolveConfigDir(process.env);
@@ -58795,7 +59019,7 @@ async function startServer(argv, env) {
58795
59019
  try {
58796
59020
  await journal(resolved, ctx, tool.name, reply4);
58797
59021
  } catch (err) {
58798
- reply4 = errorReply(err);
59022
+ reply4 = tool.name === DOCTOR_TOOL_NAME ? { ...reply4, text: reply4.text + "\n" + JOURNAL_SKIPPED_LINE(errorReply(err).text) } : errorReply(err);
58799
59023
  }
58800
59024
  }
58801
59025
  }