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

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 ? "ede83923546ab97898750ef7cebe34cf82e9534c" : 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,10 +14893,10 @@ 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
- 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.',
14899
+ ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. 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.',
14880
14900
  ctx_resume: "Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",
14881
14901
  ctx_stats: "Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",
14882
14902
  ctx_doctor: "Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",
@@ -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
+ }
18268
18319
  }
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;
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];
18340
+ }
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
  }
@@ -20138,17 +20232,29 @@ function runProcess(argv, o) {
20138
20232
  }
20139
20233
 
20140
20234
  // src/core/index/auto-memory.ts
20141
- import { readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
20235
+ import { readdirSync, readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
20142
20236
  import { join as join7 } from "node:path";
20143
- var CLAUDE_CODE_MEMORY_FILES = Object.freeze([
20237
+ var MEMORY_FILES = Object.freeze([
20144
20238
  Object.freeze(["CLAUDE.md"]),
20145
20239
  Object.freeze(["CLAUDE.local.md"]),
20146
- Object.freeze([".claude", "CLAUDE.md"])
20240
+ Object.freeze([".claude", "CLAUDE.md"]),
20241
+ Object.freeze(["AGENTS.md"]),
20242
+ Object.freeze(["GEMINI.md"]),
20243
+ Object.freeze(["QWEN.md"]),
20244
+ Object.freeze([".github", "copilot-instructions.md"])
20147
20245
  ]);
20246
+ var KIRO_STEERING = Object.freeze([".kiro", "steering"]);
20247
+ var MD = ".md";
20248
+ function steeringFiles(worktree) {
20249
+ try {
20250
+ return readdirSync(join7(worktree, ...KIRO_STEERING)).filter((n) => n.endsWith(MD)).sort().map((n) => [...KIRO_STEERING, n]);
20251
+ } catch {
20252
+ return [];
20253
+ }
20254
+ }
20148
20255
  function readAutoMemory(project) {
20149
- if (project.agent !== "claude-code") return [];
20150
20256
  const rows = [];
20151
- for (const segs of CLAUDE_CODE_MEMORY_FILES) {
20257
+ for (const segs of [...MEMORY_FILES, ...steeringFiles(project.worktree)]) {
20152
20258
  const path7 = join7(project.worktree, ...segs);
20153
20259
  if (!isInside(project.worktree, path7)) continue;
20154
20260
  try {
@@ -20168,6 +20274,20 @@ function readAutoMemory(project) {
20168
20274
  }
20169
20275
  return rows;
20170
20276
  }
20277
+ function memoryChunks(rows) {
20278
+ const out = [];
20279
+ rows.forEach((r, i) => {
20280
+ for (const c of chunkText(r.text, "md")) out.push({ fileNo: i + 1, label: r.label, ord: c.ord, text: c.text });
20281
+ });
20282
+ return out;
20283
+ }
20284
+ function memoryHits(chunks, q, limit) {
20285
+ if (chunks.length === 0) return [];
20286
+ const texts = chunks.map((c) => c.text);
20287
+ const any3 = rankTexts(texts, q, "any");
20288
+ const all = rankTexts(texts, q, "all");
20289
+ return chunks.map((c, i) => ({ c, s: any3[i], full: all[i] > 0 })).filter((e) => e.s > 0).sort((a, b) => Number(b.full) - Number(a.full) || b.s - a.s || a.c.fileNo - b.c.fileNo || a.c.ord - b.c.ord).slice(0, limit).map((e) => ({ sourceId: -e.c.fileNo, label: "memory " + e.c.label, ord: e.c.ord, snippet: highlight(e.c.text, q, SNIPPET_MAX_BYTES), score: e.s, full: e.full }));
20290
+ }
20171
20291
 
20172
20292
  // src/core/tools/search.ts
20173
20293
  function unknownField(issue4) {
@@ -20204,8 +20324,27 @@ function sourceCount(db, scope, ctx, source) {
20204
20324
  });
20205
20325
  return Number(row5.n);
20206
20326
  }
20207
- function zeroHits(db, scope, ctx, source) {
20208
- return reply('No hits in scope "' + scope + '" across ' + sourceCount(db, scope, ctx, source) + " source(s).", false);
20327
+ function zeroHits(db, scope, ctx, source, offset = 0) {
20328
+ const n = sourceCount(db, scope, ctx, source);
20329
+ if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
20330
+ return reply('No hits in scope "' + scope + '" across ' + n + " source(s).", false);
20331
+ }
20332
+ function named(given, pick4) {
20333
+ if (given === void 0 || pick4 === null) return { arg: given, note: null };
20334
+ const arg = pick4.id !== null && isLongLabel(given) ? sourceHandle(pick4.id) : given;
20335
+ return { arg, note: collisionLine(given, pick4) };
20336
+ }
20337
+ function sourceCard(db, id, input, scope, arg) {
20338
+ const row5 = sourceCardRow(db, id);
20339
+ if (row5 === null) return null;
20340
+ const pg = labelPage(row5.label, input.offset ?? 0, LABEL_PAGE_BYTES);
20341
+ const lines = [
20342
+ "Source " + sourceHandle(id) + ": label " + groupDigits(pg.total) + " B, " + row5.chunks + " chunk(s), " + groupDigits(row5.bytes) + " B of " + row5.kind + ".",
20343
+ "Label:",
20344
+ pg.text
20345
+ ];
20346
+ if (pg.next !== null) lines.push("More: " + callText([], scope, arg, "offset:" + pg.next));
20347
+ return reply(lines.join("\n"), false);
20209
20348
  }
20210
20349
  function callText(queries, scope, source, cursor) {
20211
20350
  const src = source === void 0 ? "" : ", source:" + JSON.stringify(source);
@@ -20236,7 +20375,7 @@ WHERE label = :source
20236
20375
  AND (:scope <> 'session' OR session_id = :session_id)
20237
20376
  AND (:scope <> 'worktree' OR worktree = :worktree)
20238
20377
  ORDER BY id DESC LIMIT 1`;
20239
- function jsonRowsReply(db, input, scope, ctx) {
20378
+ function jsonRowsReply(db, input, scope, ctx, nm) {
20240
20379
  if (input.source === void 0 || input.source === DECISION_SOURCE || input.queries.length === 0) return null;
20241
20380
  const src = db.raw.prepare(JSON_SOURCE).get({ source: input.source, scope, session_id: ctx.sessionId, worktree: ctx.project.worktree });
20242
20381
  if (src === void 0 || Number(src.bytes_total) > JSON_SOURCE_MAX_BYTES) return null;
@@ -20247,25 +20386,27 @@ function jsonRowsReply(db, input, scope, ctx) {
20247
20386
  const texts = objs.map((o) => JSON.stringify(o));
20248
20387
  const offset = input.offset ?? 0;
20249
20388
  const out = [objs.length + " objects {" + keys.join(",") + "}"];
20389
+ const name = shownLabel(input.source, Number(src.id));
20250
20390
  let shown2 = 0;
20251
20391
  let more = false;
20252
20392
  for (const q of input.queries) {
20253
20393
  const scores = rankTexts(texts, q, "any");
20254
20394
  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);
20395
+ const named2 = namedKeys(keys, q);
20256
20396
  out.push("Query " + JSON.stringify(q) + ":");
20257
20397
  for (const i of order.slice(offset, offset + JSON_ROWS_PAGE)) {
20258
- const row5 = fitRow(objs[i], [], named, SNIPPET_MAX_BYTES);
20398
+ const row5 = fitRow(objs[i], [], named2, SNIPPET_MAX_BYTES);
20259
20399
  if (row5 === null) continue;
20260
- out.push(input.source + " [" + i + "]: " + row5);
20400
+ out.push(name + " [" + i + "]: " + row5);
20261
20401
  shown2++;
20262
20402
  }
20263
20403
  if (order.length > offset + JSON_ROWS_PAGE) {
20264
- out.push("More: " + callText([q], scope, input.source, "offset:" + (offset + JSON_ROWS_PAGE)));
20404
+ out.push("More: " + callText([q], scope, nm.arg, "offset:" + (offset + JSON_ROWS_PAGE)));
20265
20405
  more = true;
20266
20406
  }
20267
20407
  }
20268
- return shown2 === 0 && !more ? null : reply(out.join("\n"), false);
20408
+ if (shown2 === 0 && !more) return null;
20409
+ return reply((nm.note === null ? out : [nm.note, ...out]).join("\n"), false);
20269
20410
  }
20270
20411
  var SMALL_SOURCE_SHARE = 0.5;
20271
20412
  var SOURCE_BYTES = "SELECT id, bytes_total FROM sources WHERE id IN (SELECT value FROM json_each(:ids))";
@@ -20284,23 +20425,49 @@ function replyHits(hits, size) {
20284
20425
  while (n < size && n < hits.length && hits[n].full === true) n++;
20285
20426
  return n;
20286
20427
  }
20287
- function relevance(db, given, scope, ctx) {
20428
+ var MEMORY_HITS = 2;
20429
+ function mergeMemory(content, memory) {
20430
+ const out = [];
20431
+ let c = 0;
20432
+ let m = 0;
20433
+ let lastMem = true;
20434
+ while (c < content.length || m < memory.length) {
20435
+ const rank = (h) => h === void 0 ? -1 : h.full === true ? 1 : 0;
20436
+ const rc = rank(content[c]);
20437
+ const rm = rank(memory[m]);
20438
+ const mem = rc < 0 || rm > rc || rm === rc && !lastMem;
20439
+ if (mem) {
20440
+ out.push(memory[m++]);
20441
+ lastMem = true;
20442
+ } else {
20443
+ out.push(content[c++]);
20444
+ lastMem = false;
20445
+ }
20446
+ }
20447
+ return out;
20448
+ }
20449
+ var contentIn = (hits, n) => hits.slice(0, n).filter((h) => h.sourceId > 0).length;
20450
+ function relevance(db, given, scope, ctx, nm) {
20288
20451
  const input = { ...given, queries: decisionQueries(given) };
20289
20452
  const offset = input.offset ?? 0;
20290
20453
  const size = pageSize(input);
20291
- const fetched = input.queries.map((q) => page(db, q, input, scope, ctx, offset, 1));
20454
+ const mem = offset === 0 && scope !== "session" && input.source === void 0 ? memoryChunks(readAutoMemory(ctx.project)) : [];
20455
+ const fetched = input.queries.map((q) => {
20456
+ const content = page(db, q, input, scope, ctx, offset, 1);
20457
+ return mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, q, MEMORY_HITS));
20458
+ });
20292
20459
  const take = fetched.map((h) => replyHits(h, size));
20293
20460
  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);
20461
+ if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, offset);
20462
+ const moreLine3 = (q, pos) => "More: " + callText([q], scope, nm.arg, "offset:" + pos);
20296
20463
  let reserve = 0;
20297
20464
  for (const q of input.queries) reserve += bytes2(moreLine3(q, offset + size)) + 1;
20298
20465
  const total = input.source === DECISION_SOURCE ? /* @__PURE__ */ new Map() : sourceBytes(db, [...new Set(pages.flat().map((h) => h.sourceId))]);
20299
20466
  const spent = /* @__PURE__ */ new Map();
20300
- const lines = [];
20467
+ const lines = nm.note === null ? [] : [nm.note];
20301
20468
  const more = [];
20302
20469
  const shown2 = /* @__PURE__ */ new Set();
20303
- let used = 0;
20470
+ let used = nm.note === null ? 0 : bytes2(nm.note) + 1;
20304
20471
  let stopped = false;
20305
20472
  input.queries.forEach((q, qi) => {
20306
20473
  const hits = pages[qi];
@@ -20318,18 +20485,19 @@ function relevance(db, given, scope, ctx) {
20318
20485
  const hit = hits[i];
20319
20486
  const key = hit.sourceId + ":" + hit.ord;
20320
20487
  if (shown2.has(key)) {
20321
- again.set(hit.label, [...again.get(hit.label) ?? [], hit.ord]);
20488
+ const name = shownLabel(hit.label, hit.sourceId);
20489
+ again.set(name, [...again.get(name) ?? [], hit.ord]);
20322
20490
  continue;
20323
20491
  }
20324
- const line = hit.label + " #" + hit.ord + ": " + hit.snippet;
20492
+ const line = shownLabel(hit.label, hit.sourceId) + " #" + hit.ord + ": " + hit.snippet;
20325
20493
  if (used + bytes2(line) + 1 + reserve > OUTPUT_CAP) {
20326
- cut = offset + i;
20494
+ cut = offset + contentIn(hits, i);
20327
20495
  stopped = true;
20328
20496
  break;
20329
20497
  }
20330
20498
  const room = total.get(hit.sourceId);
20331
20499
  if (room !== void 0 && mine.has(hit.sourceId) && (spent.get(hit.sourceId) ?? 0) + bytes2(line) + 1 > room * SMALL_SOURCE_SHARE * (qi + 1) / input.queries.length) {
20332
- cut = offset + i;
20500
+ cut = offset + contentIn(hits, i);
20333
20501
  break;
20334
20502
  }
20335
20503
  lines.push(line);
@@ -20344,28 +20512,28 @@ function relevance(db, given, scope, ctx) {
20344
20512
  used += bytes2(line) + 1;
20345
20513
  }
20346
20514
  if (cut >= 0) more.push({ q, pos: cut });
20347
- else if (fetched[qi].length > take[qi]) more.push({ q, pos: offset + take[qi] });
20515
+ else if (contentIn(fetched[qi], fetched[qi].length) > contentIn(fetched[qi], take[qi])) more.push({ q, pos: offset + contentIn(fetched[qi], take[qi]) });
20348
20516
  });
20349
20517
  const moreLines = [];
20350
20518
  const byPos = /* @__PURE__ */ new Map();
20351
20519
  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));
20520
+ for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, nm.arg, "offset:" + pos));
20353
20521
  return reply(lines.concat(moreLines).join("\n"), false);
20354
20522
  }
20355
20523
  function timelineLine(r) {
20356
20524
  const nl = r.text.indexOf("\n");
20357
20525
  const first = nl < 0 ? r.text : r.text.slice(0, nl);
20358
20526
  const seq = r.seq === null ? "" : " #" + r.seq;
20359
- return "[" + new Date(r.ts).toISOString() + "] " + r.label + seq + " " + first;
20527
+ return "[" + new Date(r.ts).toISOString() + "] " + shownLabel(r.label, r.sourceId) + seq + " " + first;
20360
20528
  }
20361
- function timeline(db, input, scope, ctx) {
20529
+ function timeline(db, input, scope, ctx, nm) {
20362
20530
  const memory = scope === "session" ? [] : readAutoMemory(ctx.project);
20363
20531
  const page2 = ftsQueryTimeline(db, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, input.after ?? null, input.source, memory);
20364
20532
  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);
20533
+ const moreLine3 = (ts) => "more: " + callText(input.queries, scope, nm.arg, 'sort:"timeline", after:' + ts);
20366
20534
  const reserve = bytes2(moreLine3(page2.rows[page2.rows.length - 1].ts)) + 1;
20367
- const lines = [];
20368
- let used = 0;
20535
+ const lines = nm.note === null ? [] : [nm.note];
20536
+ let used = nm.note === null ? 0 : bytes2(nm.note) + 1;
20369
20537
  let lastTs = null;
20370
20538
  let more = page2.more;
20371
20539
  let i = 0;
@@ -20401,9 +20569,16 @@ async function handler(input, ctx) {
20401
20569
  const scope = input.scope ?? "worktree";
20402
20570
  const db = await openDb(ctx.project, { readOnly: true });
20403
20571
  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);
20572
+ const given = input.source;
20573
+ const pick4 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given) : null;
20574
+ if (pick4 !== null) input = { ...input, source: pick4.label };
20575
+ const nm = named(given, pick4);
20576
+ if (sort === "timeline") return timeline(db, input, scope, ctx, nm);
20577
+ if (pick4 !== null && pick4.id !== null && input.queries.length === 0) {
20578
+ const card = sourceCard(db, pick4.id, input, scope, nm.arg);
20579
+ if (card !== null) return card;
20580
+ }
20581
+ return jsonRowsReply(db, input, scope, ctx, nm) ?? relevance(db, input, scope, ctx, nm);
20407
20582
  } finally {
20408
20583
  closeDb(db);
20409
20584
  }
@@ -20424,6 +20599,7 @@ var ctxBatchSchema = external_exports.object({
20424
20599
  }, { error: unknownField }).strict();
20425
20600
  var TOOL = "ctx_batch";
20426
20601
  var LABEL_PREFIX = TOOL + ":";
20602
+ var LABEL_SEP = ":";
20427
20603
  var SHELL = "shell";
20428
20604
  var SHELL_INLINE_FLAG = "-c";
20429
20605
  var MARKER = "$ ";
@@ -20491,6 +20667,7 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20491
20667
  const display = shown(chunks, ran.map((r) => r.head));
20492
20668
  const bodies = /* @__PURE__ */ new Map();
20493
20669
  const raw = /* @__PURE__ */ new Map();
20670
+ const ids = [];
20494
20671
  let total = 0;
20495
20672
  for (const c of chunks) total += c.bytes;
20496
20673
  let indexed = 0;
@@ -20511,6 +20688,7 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20511
20688
  chunkCount: group.length,
20512
20689
  createdAt: Date.now()
20513
20690
  }, group);
20691
+ ids.push(id);
20514
20692
  for (const c of group) {
20515
20693
  bodies.set(chunkKey(id, c.ord), display[c.ord]);
20516
20694
  raw.set(chunkKey(id, c.ord), c.text);
@@ -20523,25 +20701,25 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20523
20701
  for (const c of chunks) {
20524
20702
  if (queued + c.bytes > budgetBytes) {
20525
20703
  const stop2 = flush() ? "budget" : "deadline";
20526
- return { bodies, raw, indexed, total, stop: stop2 };
20704
+ return { bodies, raw, ids, indexed, total, stop: stop2 };
20527
20705
  }
20528
- if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, indexed, total, stop: "deadline" };
20706
+ if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, ids, indexed, total, stop: "deadline" };
20529
20707
  group.push(c);
20530
20708
  groupBytes += c.bytes;
20531
20709
  queued += c.bytes;
20532
20710
  }
20533
20711
  const stop = flush() ? null : "deadline";
20534
- return { bodies, raw, indexed, total, stop };
20712
+ return { bodies, raw, ids, indexed, total, stop };
20535
20713
  }
20536
20714
  function bytes3(s) {
20537
20715
  return Buffer.byteLength(s, "utf8");
20538
20716
  }
20539
- function answer(db, ctx, label2, queries, share, own4) {
20717
+ function answer(db, ctx, ownIds, queries, share, own4) {
20540
20718
  const seen = /* @__PURE__ */ new Set();
20541
20719
  const lines = [];
20542
20720
  for (const [qi, q] of queries.entries()) {
20543
20721
  if (ctx.signal.aborted) break;
20544
- let hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, label2);
20722
+ let hits = ownIds.length === 0 ? [] : ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, void 0, ownIds);
20545
20723
  if (hits.length === 0) hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0);
20546
20724
  const head = "## " + (bytes3(q) > ECHO_MAX_BYTES ? "query " + (qi + 1) : q);
20547
20725
  let used = bytes3(head) + 1;
@@ -20580,9 +20758,10 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20580
20758
  const ran = pool.results;
20581
20759
  const last2 = ran[ran.length - 1];
20582
20760
  const sandboxBytes = ran.reduce((n, r) => n + r.bytes, 0);
20583
- const label2 = LABEL_PREFIX + ctx.turn;
20584
20761
  try {
20585
20762
  const db = await openDb(ctx.project);
20763
+ const turnPrefix = LABEL_PREFIX + ctx.turn + LABEL_SEP;
20764
+ const label2 = turnPrefix + nextLabelSerial(db, ctx.sessionId, turnPrefix);
20586
20765
  let sections;
20587
20766
  let idx;
20588
20767
  const exitLine = last2.exitCode === null || last2.exitCode === 0 ? null : "exit " + last2.exitCode;
@@ -20598,7 +20777,7 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20598
20777
  notice = cut === null ? stop : cause === null ? cut : cause + " " + cut;
20599
20778
  const fixed = (exitLine === null ? 0 : bytes3(exitLine) + 1) + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
20600
20779
  const share = Math.floor((OUTPUT_CAP - fixed) / queries.length);
20601
- const answered = answer(db, ctx, label2, queries, share, idx.bodies);
20780
+ const answered = answer(db, ctx, idx.ids, queries, share, idx.bodies);
20602
20781
  sections = answered.lines;
20603
20782
  const unseen = [...idx.bodies].filter(([k, text]) => text !== "" && !answered.seen.has(k)).map(([k]) => idx.raw.get(k));
20604
20783
  const unseenBytes = unseen.reduce((n, t) => n + bytes3(t) + 1, 0);
@@ -20634,15 +20813,15 @@ var ctxBatch = Object.freeze({
20634
20813
  });
20635
20814
 
20636
20815
  // src/core/tools/doctor.ts
20637
- 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";
20816
+ import { readdirSync as readdirSync6, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20817
+ import { basename as basename5, dirname as dirname8, join as join16 } from "node:path";
20639
20818
 
20640
20819
  // src/core/ops/doctor-config.ts
20641
- import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
20820
+ import { existsSync as existsSync6, readdirSync as readdirSync4 } from "node:fs";
20642
20821
  import { join as join11 } from "node:path";
20643
20822
 
20644
20823
  // src/core/ops/detect-v1.ts
20645
- import { existsSync as existsSync4, opendirSync, readdirSync, readFileSync as readFileSync7 } from "node:fs";
20824
+ import { existsSync as existsSync4, opendirSync, readdirSync as readdirSync2, readFileSync as readFileSync7 } from "node:fs";
20646
20825
  import { tmpdir } from "node:os";
20647
20826
  import { join as join9 } from "node:path";
20648
20827
 
@@ -21636,9 +21815,9 @@ var Tokenizer = class {
21636
21815
  cp = this.nextCode();
21637
21816
  }
21638
21817
  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));
21818
+ const right2 = out;
21819
+ if (minus) right2.unshift(CodePoint.DASH);
21820
+ const value = Number(leftMinus ? String.fromCodePoint(CodePoint.DASH, ...left, CodePoint.LATIN_SMALL_E, ...right2) : String.fromCodePoint(...left, CodePoint.LATIN_SMALL_E, ...right2));
21642
21821
  this.endToken("Float", "start", value);
21643
21822
  return this.back("DATA");
21644
21823
  }
@@ -23362,7 +23541,7 @@ function scanVscode(agentHome, project, out) {
23362
23541
  }
23363
23542
  function jsonFiles(dir) {
23364
23543
  try {
23365
- return readdirSync(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
23544
+ return readdirSync2(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
23366
23545
  } catch {
23367
23546
  return [];
23368
23547
  }
@@ -23488,7 +23667,7 @@ function detectV1(agent, home, scope = {}) {
23488
23667
  }
23489
23668
 
23490
23669
  // src/core/ops/plugin-root.ts
23491
- import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23670
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23492
23671
  import { dirname as dirname6, isAbsolute as isAbsolute2, join as join10, sep as sep3 } from "node:path";
23493
23672
  import { fileURLToPath } from "node:url";
23494
23673
  function missing(agent, path7) {
@@ -23588,7 +23767,7 @@ function marketplaceRoot(adapter, env, worktree) {
23588
23767
  if (ownReal !== null && cacheReal !== null && ownReal.startsWith(cacheReal + sep3) && existsSync5(join10(ownReal, SERVER_ENTRY_FILE))) return ownReal;
23589
23768
  const pattern = join10(cache, "*", PLUGIN_NAME);
23590
23769
  if (!existsSync5(cache)) throw missing(adapter.id, pattern);
23591
- const found = readdirSync2(cache).sort().map((marketplace) => join10(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync5(dir));
23770
+ const found = readdirSync3(cache).sort().map((marketplace) => join10(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync5(dir));
23592
23771
  if (found.length !== 1) throw missing(adapter.id, found.length === 0 ? pattern : found.join(", "));
23593
23772
  return found[0];
23594
23773
  }
@@ -23731,10 +23910,10 @@ function codexNativeDir(env, home) {
23731
23910
  const cache = join11(codexDir, "plugins", PLUGIN_CACHE_DIR_NAME);
23732
23911
  if (!existsSync6(cache)) return null;
23733
23912
  const found = [];
23734
- for (const market of readdirSync3(cache)) {
23913
+ for (const market of readdirSync4(cache)) {
23735
23914
  const plugin = join11(cache, market, SERVER_KEY);
23736
23915
  if (!existsSync6(plugin)) continue;
23737
- for (const version4 of readdirSync3(plugin).sort()) {
23916
+ for (const version4 of readdirSync4(plugin).sort()) {
23738
23917
  const dir = join11(plugin, version4, CODEX_PLUGIN_SUBDIR);
23739
23918
  if (existsSync6(join11(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
23740
23919
  }
@@ -23819,7 +23998,7 @@ function checkHostConfig(row5, env, worktree) {
23819
23998
  const read3 = row5.id === "pi" ? mcpFile(row5, home, env) : null;
23820
23999
  if (parts.length === 0) return read3 === null ? pass("D3") : { ...pass("D3"), detail: read3 };
23821
24000
  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;
24001
+ const fix = parts.includes(PART_MCP) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
23823
24002
  return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, fix);
23824
24003
  }
23825
24004
  function checkV1Leftovers(agent, home, scope = {}) {
@@ -23873,7 +24052,7 @@ function configPaths(row5, env, worktree) {
23873
24052
  }
23874
24053
 
23875
24054
  // src/core/ops/doctor-db.ts
23876
- import { existsSync as existsSync7 } from "node:fs";
24055
+ import { existsSync as existsSync7, statSync as statSync5 } from "node:fs";
23877
24056
  var unknown2 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail });
23878
24057
  var pass2 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "PASS", detail });
23879
24058
  var fail3 = (detail, fixCommand) => ({ id: "D8", label: DOCTOR_LABEL.D8, status: "FAIL", detail, fixCommand });
@@ -23911,8 +24090,18 @@ function failsOnCorrupt(step) {
23911
24090
  throw err;
23912
24091
  }
23913
24092
  }
24093
+ function orphanFiles(dbPath) {
24094
+ const files = [];
24095
+ for (const suffix of [DB_WAL_SUFFIX, DB_SHM_SUFFIX]) {
24096
+ const path7 = dbPath + suffix;
24097
+ if (existsSync7(path7)) files.push({ path: path7, bytes: statSync5(path7).size });
24098
+ }
24099
+ return files.length > 0 && !existsSync7(dbPath) ? files : [];
24100
+ }
23914
24101
  async function checkDb(project) {
23915
- const clean = { schemaStale: false, integrityFailed: false };
24102
+ const clean = { schemaStale: false, integrityFailed: false, orphan: [] };
24103
+ const orphan = orphanFiles(project.dbPath);
24104
+ if (orphan.length > 0) return { row: fail3(D8_ORPHAN_DETAIL(orphan), D8_ORPHAN_FIX), schemaStale: false, integrityFailed: false, orphan };
23916
24105
  if (!existsSync7(project.dbPath)) return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
23917
24106
  const sqlite = await loadSqlite2();
23918
24107
  if (sqlite === null) return { row: unknown2("D8", D2_SQLITE_DETAIL), ...clean };
@@ -23928,11 +24117,11 @@ async function checkDb(project) {
23928
24117
  }
23929
24118
  const schemaStale = got !== null && got !== SCHEMA_VERSION;
23930
24119
  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 };
24120
+ if (integrityFailed) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale, integrityFailed, orphan: [] };
24121
+ if (schemaStale && got !== null) return { row: fail3(D8_STALE_SCHEMA_DETAIL(got, SCHEMA_VERSION), DOCTOR_FIX_UPGRADE), schemaStale, integrityFailed, orphan: [] };
23933
24122
  return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
23934
24123
  } catch (err) {
23935
- if (isCorrupt2(err)) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true };
24124
+ if (isCorrupt2(err)) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true, orphan: [] };
23936
24125
  return { row: unknown2("D8", message2(err)), ...clean };
23937
24126
  } finally {
23938
24127
  raw?.close();
@@ -24000,7 +24189,8 @@ function fetchCause(err, timeoutMs) {
24000
24189
  const cause = err instanceof Error && err.cause instanceof Error ? err.cause : err;
24001
24190
  const code = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : "";
24002
24191
  const msg = cause instanceof Error ? cause.message : String(cause);
24003
- return D1_NPM_ERROR(code !== "" && !msg.includes(code) ? `${code} ${msg}` : msg);
24192
+ const parts = code !== "" && !msg.includes(code) ? [code, msg] : [msg];
24193
+ return D1_NPM_ERROR(parts.filter((part) => part !== "").join(" "));
24004
24194
  }
24005
24195
  async function npmLatest(url4, tag2, signal, timeoutMs) {
24006
24196
  try {
@@ -24113,9 +24303,9 @@ async function checkNode(i) {
24113
24303
  return pass3("D2", bun.length === 0 ? DOCTOR_PASS_DETAIL : bun.join(D4_REASON_JOIN));
24114
24304
  }
24115
24305
  function checkMcp(ctx) {
24116
- const named = ctx.clientInfo !== void 0 && ctx.clientInfo.name !== "";
24306
+ const named2 = ctx.clientInfo !== void 0 && ctx.clientInfo.name !== "";
24117
24307
  const versioned = ctx.protocolVersion !== void 0 && ctx.protocolVersion !== "";
24118
- return named || versioned ? pass3("D6") : unknown3("D6", D6_UNKNOWN_DETAIL);
24308
+ return named2 || versioned ? pass3("D6") : unknown3("D6", D6_UNKNOWN_DETAIL);
24119
24309
  }
24120
24310
  function piCwdInside(worktree, piCwd) {
24121
24311
  if (piCwd === void 0 || !existsSync8(piCwd)) return false;
@@ -24150,7 +24340,7 @@ import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
24150
24340
 
24151
24341
  // src/setup/spawn-bin.ts
24152
24342
  import { spawnSync } from "node:child_process";
24153
- import { accessSync as accessSync2, constants as fsc, statSync as statSync5 } from "node:fs";
24343
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync6 } from "node:fs";
24154
24344
  import path4 from "node:path";
24155
24345
  var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
24156
24346
  var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
@@ -24168,7 +24358,7 @@ function whichBin(bin, env, platform = process.platform) {
24168
24358
  const f = path4.join(dir, n);
24169
24359
  try {
24170
24360
  accessSync2(f, fsc.X_OK);
24171
- if (statSync5(f).isFile()) return f;
24361
+ if (statSync6(f).isFile()) return f;
24172
24362
  } catch {
24173
24363
  }
24174
24364
  }
@@ -24376,19 +24566,52 @@ function loadFixture(bundleDir2, agent) {
24376
24566
  }
24377
24567
  return { event: e.event, payload: e.payload };
24378
24568
  }
24379
- function payloadFor(payload, worktree) {
24380
- return worktree !== void 0 && isObject5(payload) ? { ...payload, cwd: worktree } : payload;
24381
- }
24382
- function isNativeShape(stdout, exitCode, killed, event) {
24569
+ var CWD_KEY = {
24570
+ "claude-code": "cwd",
24571
+ codex: "cwd",
24572
+ gemini: "cwd",
24573
+ qwen: "cwd",
24574
+ "copilot-cli": "cwd",
24575
+ vscode: "cwd",
24576
+ kiro: "cwd",
24577
+ zcode: "cwd",
24578
+ pi: "cwd",
24579
+ opencode: "directory"
24580
+ };
24581
+ function payloadFor(agent, payload, worktree) {
24582
+ return worktree !== void 0 && isObject5(payload) ? { ...payload, [CWD_KEY[agent]]: worktree } : payload;
24583
+ }
24584
+ var SHAPE = {
24585
+ "claude-code": "claude",
24586
+ codex: "claude",
24587
+ qwen: "claude",
24588
+ vscode: "claude",
24589
+ zcode: "claude",
24590
+ gemini: "gemini",
24591
+ "copilot-cli": "copilot",
24592
+ kiro: "text",
24593
+ pi: "text",
24594
+ opencode: "text"
24595
+ };
24596
+ var COPILOT_KEYS = ["permissionDecision", "additionalContext", "modifiedResult"];
24597
+ function isNativeShape(agent, stdout, exitCode, killed, event) {
24383
24598
  if (killed !== null || exitCode !== 0 && exitCode !== 2) return false;
24384
- if (stdout.length === 0) return true;
24599
+ if (stdout.length === 0 || SHAPE[agent] === "text") return true;
24385
24600
  let out;
24386
24601
  try {
24387
24602
  out = JSON.parse(stdout);
24388
24603
  } catch {
24389
24604
  return false;
24390
24605
  }
24391
- return isObject5(out) && isObject5(out.hookSpecificOutput) && out.hookSpecificOutput.hookEventName === event;
24606
+ if (!isObject5(out)) return false;
24607
+ switch (SHAPE[agent]) {
24608
+ case "claude":
24609
+ return isObject5(out.hookSpecificOutput) && out.hookSpecificOutput.hookEventName === event;
24610
+ case "gemini":
24611
+ return typeof out.decision === "string" || isObject5(out.hookSpecificOutput);
24612
+ default:
24613
+ return COPILOT_KEYS.some((k) => Object.hasOwn(out, k));
24614
+ }
24392
24615
  }
24393
24616
  function codexHookJournaled(db) {
24394
24617
  if (db === null) return false;
@@ -24432,9 +24655,10 @@ async function checkHookRoundTrip(i) {
24432
24655
  const fixed = i.samples === void 0 ? null : Math.max(1, i.samples);
24433
24656
  const maxPairs = fixed ?? D5_MAX_PAIRS;
24434
24657
  const minPairs = fixed ?? D5_MIN_PAIRS;
24658
+ const timeoutMs = i.timeoutMs ?? HOOK_TIMEOUT_MS;
24435
24659
  const bareMs = i.bareMs ?? (async () => {
24436
24660
  const t = performance.now();
24437
- await runProcess([process.execPath, "-e", ""], { cwd: i.bundleDir, env: i.env, signal: i.signal, timeoutMs: HOOK_TIMEOUT_MS });
24661
+ await runProcess([process.execPath, "-e", ""], { cwd: i.bundleDir, env: i.env, signal: i.signal, timeoutMs });
24438
24662
  return performance.now() - t;
24439
24663
  });
24440
24664
  const hookWalls = [];
@@ -24446,11 +24670,11 @@ async function checkHookRoundTrip(i) {
24446
24670
  cwd: i.bundleDir,
24447
24671
  env: i.env,
24448
24672
  signal: i.signal,
24449
- timeoutMs: HOOK_TIMEOUT_MS,
24450
- stdin: JSON.stringify(payloadFor(fixture.payload, i.worktree))
24673
+ timeoutMs,
24674
+ stdin: JSON.stringify(payloadFor(i.agent, fixture.payload, i.worktree))
24451
24675
  });
24452
24676
  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);
24677
+ if (!isNativeShape(i.agent, r.stdout.toString("utf8"), r.exitCode, r.killed, fixture.event)) return row("FAIL", D5_SHAPE_DETAIL, D5_FIX);
24454
24678
  bareWalls.push(await bareMs());
24455
24679
  ms = Math.max(0, Math.round(Math.min(...hookWalls) - Math.min(...bareWalls)));
24456
24680
  if (n >= minPairs && ms <= HOOK_P95_MS) break;
@@ -24460,10 +24684,11 @@ async function checkHookRoundTrip(i) {
24460
24684
  }
24461
24685
 
24462
24686
  // src/core/ops/db-heal.ts
24463
- import { existsSync as existsSync11, rmSync as rmSync3 } from "node:fs";
24687
+ import { existsSync as existsSync11, mkdirSync as mkdirSync5, rmSync as rmSync3 } from "node:fs";
24688
+ import { basename as basename4, dirname as dirname7, join as join14 } from "node:path";
24464
24689
 
24465
24690
  // src/core/store/owners.ts
24466
- import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24691
+ import { mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24467
24692
  import { basename as basename3, join as join13 } from "node:path";
24468
24693
  function ownersDir(configDir, projectKey) {
24469
24694
  return join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
@@ -24496,7 +24721,7 @@ function listLiveOwners(configDir, projectKey) {
24496
24721
  const dir = ownersDir(configDir, projectKey);
24497
24722
  let names;
24498
24723
  try {
24499
- names = readdirSync4(dir);
24724
+ names = readdirSync5(dir);
24500
24725
  } catch (err) {
24501
24726
  if (errCode2(err) === "ENOENT") return [];
24502
24727
  throw err;
@@ -24572,6 +24797,39 @@ async function healD8(input) {
24572
24797
  closeDb(await openDb(project));
24573
24798
  return { ...row5, status: "FAIL", detail: D8_HEALED_RECREATE_DETAIL(ts) };
24574
24799
  }
24800
+ function utcStamp(now) {
24801
+ return now.toISOString().slice(0, 19).replaceAll("-", "").replaceAll(":", "") + "Z";
24802
+ }
24803
+ function makeOrphanDir(projectDir) {
24804
+ const base = join14(projectDir, ORPHAN_DIR_PREFIX + utcStamp(/* @__PURE__ */ new Date()));
24805
+ for (let n = 1; ; n += 1) {
24806
+ const dir = n === 1 ? base : base + "-" + String(n);
24807
+ try {
24808
+ mkdirSync5(dir);
24809
+ return dir;
24810
+ } catch (err) {
24811
+ if (err.code !== "EEXIST") throw err;
24812
+ }
24813
+ }
24814
+ }
24815
+ async function healOrphan(project, files, row5) {
24816
+ const moved = [];
24817
+ let dir = "";
24818
+ try {
24819
+ dir = makeOrphanDir(dirname7(project.dbPath));
24820
+ for (const f of files) {
24821
+ const to = join14(dir, basename4(f.path));
24822
+ renameWithRetry(f.path, to);
24823
+ moved.push({ path: to, bytes: f.bytes });
24824
+ }
24825
+ closeDb(await openDb(project));
24826
+ } catch (err) {
24827
+ const cause = err instanceof CtxError ? err.toLine() : err instanceof Error ? err.message : String(err);
24828
+ const at2 = moved.length > 0 ? D8_ORPHAN_HEALED_DETAIL(dir, moved, project.dbPath) : row5.detail;
24829
+ return { ...row5, detail: D8_ORPHAN_MOVE_FAILED(at2, cause) };
24830
+ }
24831
+ return { ...row5, status: "FAIL", detail: D8_ORPHAN_HEALED_DETAIL(dir, moved, project.dbPath), fixCommand: D8_ORPHAN_HEALED_FIX };
24832
+ }
24575
24833
 
24576
24834
  // src/core/ops/report.ts
24577
24835
  function keyIsTyped(key) {
@@ -24627,8 +24885,8 @@ function buildReportHead(input) {
24627
24885
 
24628
24886
  // src/core/ops/doctor-issue.ts
24629
24887
  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";
24888
+ import { closeSync, existsSync as existsSync12, fstatSync, mkdirSync as mkdirSync6, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
24889
+ import { delimiter, join as join15 } from "node:path";
24632
24890
  var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
24633
24891
  function tildeOf(env) {
24634
24892
  const home = homeDirOf(env);
@@ -24645,9 +24903,9 @@ function tildeOf(env) {
24645
24903
  }
24646
24904
  function maskLine(line) {
24647
24905
  const lower = line.toLowerCase();
24648
- const named = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
24906
+ const named2 = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
24649
24907
  const token = TOKEN_PREFIXES.some((p) => line.includes(p));
24650
- if (!named && !token) return line;
24908
+ if (!named2 && !token) return line;
24651
24909
  const at2 = Math.max(line.indexOf(":"), line.indexOf("="));
24652
24910
  return at2 === -1 ? DOCTOR_MASK : line.slice(0, at2 + 1) + " " + DOCTOR_MASK;
24653
24911
  }
@@ -24669,8 +24927,8 @@ function onPath(env, tool) {
24669
24927
  const out = [];
24670
24928
  for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
24671
24929
  if (dir === "") continue;
24672
- for (const n of names) if (existsSync12(join14(dir, n))) {
24673
- out.push(join14(dir, n));
24930
+ for (const n of names) if (existsSync12(join15(dir, n))) {
24931
+ out.push(join15(dir, n));
24674
24932
  break;
24675
24933
  }
24676
24934
  }
@@ -24716,8 +24974,8 @@ function agentConfig(adapter, env, worktree) {
24716
24974
  const home = homeDirOf(env);
24717
24975
  const files = configPaths(adapter, env, worktree);
24718
24976
  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) });
24977
+ if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join15(claudeDirOf(env, home), SETTINGS_FILE) });
24978
+ if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join15(codexDirOf(env, home), CONFIG_TOML_FILE) });
24721
24979
  }
24722
24980
  const out = [];
24723
24981
  const seen = /* @__PURE__ */ new Set();
@@ -24800,9 +25058,9 @@ async function buildIssueBody(i) {
24800
25058
  async function writeIssueReport(i) {
24801
25059
  const tilde = tildeOf(i.env);
24802
25060
  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`);
25061
+ const dir = join15(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
25062
+ mkdirSync6(dir, { recursive: true });
25063
+ const file2 = join15(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
24806
25064
  writeFileSync3(file2, body);
24807
25065
  const shown2 = tilde(file2);
24808
25066
  const title = issueTitle(i.adapter.id, i.rows);
@@ -24859,11 +25117,11 @@ async function hookRow(ctx, adapter, host) {
24859
25117
  }
24860
25118
  }
24861
25119
  function ownServerId(configDir, projectKey) {
24862
- const dir = join15(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
25120
+ const dir = join16(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24863
25121
  if (!existsSync13(dir)) return "";
24864
- for (const name of readdirSync5(dir)) {
25122
+ for (const name of readdirSync6(dir)) {
24865
25123
  if (!name.endsWith(OWNER_PID_EXT)) continue;
24866
- if (readFileSync13(join15(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
25124
+ if (readFileSync13(join16(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
24867
25125
  }
24868
25126
  return "";
24869
25127
  }
@@ -24872,6 +25130,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
24872
25130
  const env = host.env;
24873
25131
  const project = ctx.project;
24874
25132
  let integrityFailed = false;
25133
+ let orphan = [];
24875
25134
  const checks = {
24876
25135
  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
25136
  D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
@@ -24884,6 +25143,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
24884
25143
  D8: async () => {
24885
25144
  const r = await checkDb(project);
24886
25145
  integrityFailed = r.integrityFailed;
25146
+ orphan = r.orphan;
24887
25147
  return r.row;
24888
25148
  },
24889
25149
  D9: () => checkIndex(project),
@@ -24892,8 +25152,13 @@ async function runDoctorChecks(ctx, adapter, host0) {
24892
25152
  };
24893
25153
  const rows = [];
24894
25154
  for (const id of DOCTOR_CHECK_ORDER) rows.push(await guard(id, checks[id]));
24895
- if (!integrityFailed) return rows;
24896
25155
  const at2 = DOCTOR_CHECK_ORDER.indexOf("D8");
25156
+ if (orphan.length > 0) {
25157
+ const files = orphan;
25158
+ rows[at2] = await guard("D8", () => healOrphan(project, files, rows[at2]));
25159
+ return rows;
25160
+ }
25161
+ if (!integrityFailed) return rows;
24897
25162
  rows[at2] = await guard("D8", () => {
24898
25163
  const configDir = resolveConfigDir(env);
24899
25164
  return healD8({ project, configDir, serverId: ownServerId(configDir, project.projectKey), row: rows[at2] });
@@ -24939,7 +25204,7 @@ async function doctorReply(ctx, host) {
24939
25204
  return { text, isError: false, sandboxBytes: bytes5 };
24940
25205
  }
24941
25206
  async function handler2(_input, ctx) {
24942
- return doctorReply(ctx, { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 });
25207
+ return doctorReply(ctx, { env: process.env, bundleDir: dirname8(process.argv[1]), piCwd: void 0 });
24943
25208
  }
24944
25209
  var ctxDoctor = Object.freeze({
24945
25210
  name: "ctx_doctor",
@@ -24953,7 +25218,7 @@ var ctxDoctor = Object.freeze({
24953
25218
  // src/core/tools/execute.ts
24954
25219
  import { existsSync as existsSync14, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "node:fs";
24955
25220
  import { tmpdir as tmpdir2 } from "node:os";
24956
- import { dirname as dirname8, join as join16, parse as parse3, resolve as resolve6 } from "node:path";
25221
+ import { dirname as dirname9, join as join17, parse as parse3, resolve as resolve6 } from "node:path";
24957
25222
 
24958
25223
  // src/core/sandbox/win-build.ts
24959
25224
  var SEPARATORS2 = ";&|(\n";
@@ -25037,7 +25302,7 @@ function schemaLine(issue4) {
25037
25302
  }
25038
25303
  function fileError(given, abs, root) {
25039
25304
  let dir = abs;
25040
- while (!existsSync14(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
25305
+ while (!existsSync14(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
25041
25306
  if (isInside(root, dir)) return null;
25042
25307
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
25043
25308
  }
@@ -25118,8 +25383,8 @@ async function handler3(raw, ctx) {
25118
25383
  if (takesDashC(input.language, runtime)) {
25119
25384
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
25120
25385
  } else {
25121
- tmpDir = mkdtempSync(join16(tmpdir2(), TMP_PREFIX));
25122
- const file2 = join16(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
25386
+ tmpDir = mkdtempSync(join17(tmpdir2(), TMP_PREFIX));
25387
+ const file2 = join17(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
25123
25388
  writeFileSync4(file2, scriptText(input.language, input.code), "utf8");
25124
25389
  argv = scriptArgv(input.language, runtime, file2);
25125
25390
  }
@@ -25154,12 +25419,12 @@ var ctxExecute = {
25154
25419
  };
25155
25420
 
25156
25421
  // 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";
25422
+ import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as statSync8 } from "node:fs";
25423
+ import { dirname as dirname10, extname, join as join19, relative as relative3, resolve as resolve7 } from "node:path";
25159
25424
 
25160
25425
  // 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";
25426
+ import { readdirSync as readdirSync7, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync7 } from "node:fs";
25427
+ import { join as join18 } from "node:path";
25163
25428
  var GITIGNORE = ".gitignore";
25164
25429
  var GIT_DIR = ".git";
25165
25430
  function walkDir(root, containmentRoot) {
@@ -25168,19 +25433,19 @@ function walkDir(root, containmentRoot) {
25168
25433
  const found = [];
25169
25434
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
25170
25435
  found.sort(compareFound);
25171
- return found.map((f) => ({ absPath: f.absPath, relPath: join17(...f.dir, f.name) }));
25436
+ return found.map((f) => ({ absPath: f.absPath, relPath: join18(...f.dir, f.name) }));
25172
25437
  }
25173
25438
  function visit(abs, rel, parent, contain, seen, found) {
25174
25439
  let entries;
25175
25440
  try {
25176
- entries = readdirSync6(abs, { withFileTypes: true });
25441
+ entries = readdirSync7(abs, { withFileTypes: true });
25177
25442
  } catch {
25178
25443
  return;
25179
25444
  }
25180
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join17(abs, GITIGNORE), rel)) : parent;
25445
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join18(abs, GITIGNORE), rel)) : parent;
25181
25446
  for (const e of entries) {
25182
25447
  if (e.name === GIT_DIR) continue;
25183
- const path7 = join17(abs, e.name);
25448
+ const path7 = join18(abs, e.name);
25184
25449
  let isDir = e.isDirectory();
25185
25450
  let isFile = e.isFile();
25186
25451
  let target = path7;
@@ -25192,7 +25457,7 @@ function visit(abs, rel, parent, contain, seen, found) {
25192
25457
  continue;
25193
25458
  }
25194
25459
  if (!isInside(contain, resolved)) continue;
25195
- const st = statSync6(resolved);
25460
+ const st = statSync7(resolved);
25196
25461
  isDir = st.isDirectory();
25197
25462
  isFile = st.isFile();
25198
25463
  target = resolved;
@@ -29310,7 +29575,7 @@ function readUtf8(absPath) {
29310
29575
  }
29311
29576
  function missingOrOutside(given, abs, root) {
29312
29577
  let dir = abs;
29313
- while (!existsSync15(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
29578
+ while (!existsSync15(dir) && dirname10(dir) !== dir) dir = dirname10(dir);
29314
29579
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
29315
29580
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
29316
29581
  }
@@ -29318,10 +29583,10 @@ function pathItems(input, project) {
29318
29583
  const abs = resolve7(project.worktree, input.path);
29319
29584
  if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
29320
29585
  const base = relative3(project.worktree, abs);
29321
- if (statSync7(abs).isDirectory()) {
29586
+ if (statSync8(abs).isDirectory()) {
29322
29587
  return walkDir(abs, project.containmentRoot).map((f) => ({
29323
29588
  sourceKind: "path",
29324
- label: pathLabel(join18(base, f.relPath)),
29589
+ label: pathLabel(join19(base, f.relPath)),
29325
29590
  kind: kindOfPath(f.relPath),
29326
29591
  read: () => readUtf8(f.absPath)
29327
29592
  }));
@@ -29393,8 +29658,9 @@ async function handler4(input, ctx) {
29393
29658
  } finally {
29394
29659
  closeDb(db);
29395
29660
  }
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");
29661
+ const head = "Indexed " + sources + " source(s), " + chunks + " chunk(s) from ";
29662
+ const first = sources === 1 && lastId > 0 ? head + sourceHandle(lastId) + ". " + indexedLabelLine(from, lastId) : head + shownLabel(from, null) + ".";
29663
+ const line = [first, ...notes].join("\n");
29398
29664
  return {
29399
29665
  text: capBytes(line, OUTPUT_CAP).text,
29400
29666
  isError: false,
@@ -29438,7 +29704,7 @@ function purgeScope(db, scope, input) {
29438
29704
  const raw = db.raw;
29439
29705
  if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
29440
29706
  if (scope === "source") {
29441
- const label2 = storedLabel(db, input.source);
29707
+ const label2 = pickSource(db, input.source, false).label;
29442
29708
  return deleteChunkRows(raw, { label: label2 }) + changes(raw, "DELETE FROM sources WHERE label = ?", label2);
29443
29709
  }
29444
29710
  const chunks = deleteChunkRows(raw, "all");
@@ -29637,6 +29903,9 @@ function bytes4(n) {
29637
29903
  }
29638
29904
  return v.toFixed(1) + " " + UNITS[u];
29639
29905
  }
29906
+ function right(v, width) {
29907
+ return " " + v.padStart(width - 1);
29908
+ }
29640
29909
  function pct(t) {
29641
29910
  return (t.saved * PERCENT_SCALE / Math.max(1, t.produced)).toFixed(1) + "%";
29642
29911
  }
@@ -29660,8 +29929,8 @@ function plural(n, word) {
29660
29929
  }
29661
29930
  function table2(title, rows) {
29662
29931
  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())];
29932
+ 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);
29933
+ 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
29934
  }
29666
29935
  function bySaved(a, b) {
29667
29936
  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 +29942,14 @@ function joinIndex(tools) {
29673
29942
  const idx = tools.filter((t2) => STATS_INDEX_TOOLS.includes(t2.name));
29674
29943
  if (idx.length <= 1) return tools;
29675
29944
  const t = sum(idx);
29676
- const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: t.produced - t.returned };
29945
+ const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: Math.max(0, t.produced - t.returned) };
29677
29946
  return [...tools.filter((x) => !idx.includes(x)), one];
29678
29947
  }
29679
29948
  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);
29949
+ const named2 = joinIndex(tools.map((t) => ({ ...t, saved: Math.max(0, t.produced - t.returned) }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
29950
+ const zero = named2.filter((t) => t.saved <= 0);
29682
29951
  const fold2 = zero.length > 1 ? zero : [];
29683
- const keep = named.filter((t) => !fold2.includes(t));
29952
+ const keep = named2.filter((t) => !fold2.includes(t));
29684
29953
  const room = fold2.length > 0 ? STATS_MAX_TOOL_ROWS - 1 : STATS_MAX_TOOL_ROWS;
29685
29954
  const over = keep.length > room;
29686
29955
  const shown2 = over ? keep.slice(0, STATS_MAX_TOOL_ROWS - 1) : keep;
@@ -29748,7 +30017,7 @@ function lastDays(week, allCalls) {
29748
30017
  return [
29749
30018
  head,
29750
30019
  ...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)] : []),
30020
+ ...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
30021
  " " + STATS_WAYS.map(([, ch, name]) => `${ch} ${name}`).join(" "),
29753
30022
  ""
29754
30023
  ];
@@ -29776,8 +30045,8 @@ function report(f, sessionId, agent) {
29776
30045
  ...head,
29777
30046
  `${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
29778
30047
  ` ${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),
30048
+ " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + right(bytes4(focus.produced), NUM_W),
30049
+ " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + right(bytes4(focus.returned), NUM_W),
29781
30050
  ...focus.saved > 0 ? [windowLine(focus.saved), STATS_TOKEN_NOTE] : [],
29782
30051
  ...hookLine(f.redirected, f.replaced),
29783
30052
  "",
@@ -29791,7 +30060,7 @@ function report(f, sessionId, agent) {
29791
30060
  "",
29792
30061
  ...f.top.length > 0 ? [
29793
30062
  "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)),
30063
+ ...f.top.map((t) => " " + label(toolName(t.name)) + right(bytes4(t.produced), NUM_W) + " \u2192 " + right(bytes4(t.returned), NUM_W)),
29795
30064
  ""
29796
30065
  ] : []
29797
30066
  ];
@@ -29800,10 +30069,10 @@ function report(f, sessionId, agent) {
29800
30069
  if (!agents.has(agent)) agents.set(agent, EMPTY5);
29801
30070
  lines.push("By agent (this project)", ...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29802
30071
  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));
30072
+ lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + right("Session", STATS_KIND_W) + right("Project", STATS_KIND_W));
29804
30073
  for (const [kind, name] of STATS_KIND_LABELS) {
29805
30074
  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());
30075
+ 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
30076
  }
29808
30077
  lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
29809
30078
  lines.push(
@@ -29820,7 +30089,14 @@ async function handler7(_input, ctx) {
29820
30089
  const db = await openDb(ctx.project, { readOnly: true });
29821
30090
  let facts;
29822
30091
  try {
29823
- facts = readFacts(db.raw, ctx.sessionId);
30092
+ db.raw.exec("BEGIN DEFERRED");
30093
+ try {
30094
+ facts = readFacts(db.raw, ctx.sessionId);
30095
+ db.raw.exec("COMMIT");
30096
+ } catch (err) {
30097
+ if (db.raw.isTransaction) db.raw.exec("ROLLBACK");
30098
+ throw err;
30099
+ }
29824
30100
  } finally {
29825
30101
  closeDb(db);
29826
30102
  }
@@ -29851,11 +30127,11 @@ var ctxStats = Object.freeze({
29851
30127
 
29852
30128
  // src/core/tools/upgrade.ts
29853
30129
  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";
30130
+ import { basename as basename7, dirname as dirname12, join as join25 } from "node:path";
29855
30131
 
29856
30132
  // 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";
30133
+ import { copyFileSync, existsSync as existsSync16, mkdirSync as mkdirSync7, writeFileSync as writeFileSync5 } from "node:fs";
30134
+ import { dirname as dirname11, join as join20 } from "node:path";
29859
30135
  function defaultWrite(file2, text) {
29860
30136
  writeFileSync5(file2, text, "utf8");
29861
30137
  }
@@ -29864,14 +30140,14 @@ function hostConfigPath(agent, home, env) {
29864
30140
  if (own4 !== void 0) return ownMcpFileOf(agent, own4.file, env, home);
29865
30141
  switch (agent) {
29866
30142
  case "opencode":
29867
- return join19(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
30143
+ return join20(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29868
30144
  // D-WIN-OPENCODE-DIR-1
29869
30145
  case "pi":
29870
- return join19(piAgentDirOf(env, home), SETTINGS_FILE);
30146
+ return join20(piAgentDirOf(env, home), SETTINGS_FILE);
29871
30147
  case "copilot-cli":
29872
30148
  return null;
29873
30149
  default:
29874
- return join19(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
30150
+ return join20(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29875
30151
  }
29876
30152
  }
29877
30153
  function cell3(value) {
@@ -29884,7 +30160,7 @@ function writeWithRollback(file2, text, write2, atomic) {
29884
30160
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
29885
30161
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
29886
30162
  const had = existsSync16(file2);
29887
- mkdirSync6(dirname10(file2), { recursive: true });
30163
+ mkdirSync7(dirname11(file2), { recursive: true });
29888
30164
  if (had) copyFileSync(file2, trash);
29889
30165
  try {
29890
30166
  write2(tmp, text);
@@ -29921,8 +30197,8 @@ function regenerateHostConfig(row5, home, opts = {}) {
29921
30197
  }
29922
30198
 
29923
30199
  // src/core/ops/plugin-swap.ts
29924
- 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";
30200
+ import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync8, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
30201
+ import { basename as basename6, join as join21, win32 as win322 } from "node:path";
29926
30202
  function linkTarget(path7, win) {
29927
30203
  if (!isLink(path7)) return null;
29928
30204
  const target = readlinkSync(path7);
@@ -29932,7 +30208,7 @@ function isLink(path7) {
29932
30208
  return lstatSync(path7, { throwIfNoEntry: false })?.isSymbolicLink() === true;
29933
30209
  }
29934
30210
  function generations(agentDir) {
29935
- return readdirSync7(agentDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).filter((name) => !name.startsWith(UPGRADE_FETCH_DIR_PREFIX) && !name.endsWith(UPGRADE_TRASH_SUFFIX)).sort();
30211
+ return readdirSync8(agentDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).filter((name) => !name.startsWith(UPGRADE_FETCH_DIR_PREFIX) && !name.endsWith(UPGRADE_TRASH_SUFFIX)).sort();
29936
30212
  }
29937
30213
  function settleLinks(link, tmp, old, opts) {
29938
30214
  if (isLink(tmp)) unlinkSync2(tmp);
@@ -29941,11 +30217,11 @@ function settleLinks(link, tmp, old, opts) {
29941
30217
  else renameWithRetry(old, link, opts);
29942
30218
  }
29943
30219
  function swapPluginCurrent(agentDir, sha, opts = {}) {
29944
- const next = join20(agentDir, sha);
30220
+ const next = join21(agentDir, sha);
29945
30221
  if (!existsSync17(next) || !lstatSync(next).isDirectory()) {
29946
- throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
30222
+ throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename6(agentDir), path: next });
29947
30223
  }
29948
- const link = join20(agentDir, PLUGIN_CURRENT_LINK);
30224
+ const link = join21(agentDir, PLUGIN_CURRENT_LINK);
29949
30225
  const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
29950
30226
  const old = link + PLUGIN_LINK_OLD_SUFFIX;
29951
30227
  settleLinks(link, tmp, old, opts);
@@ -29960,15 +30236,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
29960
30236
  if (before !== null) unlinkSync2(old);
29961
30237
  const keep = /* @__PURE__ */ new Set([sha]);
29962
30238
  if (before !== null) keep.add(before);
29963
- const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join20(agentDir, name));
30239
+ const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join21(agentDir, name));
29964
30240
  for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
29965
- const previous = before !== null && existsSync17(join20(agentDir, before)) ? join20(agentDir, before) : null;
30241
+ const previous = before !== null && existsSync17(join21(agentDir, before)) ? join21(agentDir, before) : null;
29966
30242
  return { current: next, previous, removed };
29967
30243
  }
29968
30244
 
29969
30245
  // 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";
30246
+ import { existsSync as existsSync18, mkdirSync as mkdirSync8, rmSync as rmSync6 } from "node:fs";
30247
+ import { join as join22 } from "node:path";
29972
30248
  function failed(r) {
29973
30249
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
29974
30250
  const status = r.killed ?? String(r.exitCode);
@@ -29980,9 +30256,9 @@ async function git2(bin, args, cwd, env, signal) {
29980
30256
  return r.stdout.toString().trim();
29981
30257
  }
29982
30258
  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);
30259
+ const agentDir = join22(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
30260
+ mkdirSync8(agentDir, { recursive: true });
30261
+ const fetchDir = join22(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29986
30262
  rmSync6(fetchDir, { recursive: true, force: true });
29987
30263
  const gitBin = findRuntime(GIT_BIN, env);
29988
30264
  if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -29990,7 +30266,7 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
29990
30266
  try {
29991
30267
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url4, fetchDir], agentDir, childEnv, signal);
29992
30268
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
29993
- const dir = join21(agentDir, sha);
30269
+ const dir = join22(agentDir, sha);
29994
30270
  if (existsSync18(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29995
30271
  else renameWithRetry(fetchDir, dir, opts);
29996
30272
  return { sha, dir };
@@ -30001,15 +30277,15 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
30001
30277
  }
30002
30278
 
30003
30279
  // src/core/ops/uninstall.ts
30004
- import { existsSync as existsSync19, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
30005
- import { join as join22 } from "node:path";
30280
+ import { existsSync as existsSync19, readdirSync as readdirSync9, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
30281
+ import { join as join23 } from "node:path";
30006
30282
  function row2(area, before, after) {
30007
30283
  return { area, before, after };
30008
30284
  }
30009
30285
  function stopServers(configDir, projectKey) {
30010
30286
  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");
30287
+ const dir = join23(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
30288
+ for (const serverId of stopped) writeFileSync6(join23(dir, serverId + OWNER_STOP_EXT), "", "utf8");
30013
30289
  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
30290
  }
30015
30291
  function rootOrNull(adapter, env) {
@@ -30027,14 +30303,14 @@ function removeCache(adapter, env, configDir) {
30027
30303
  const root = rootOrNull(adapter, env);
30028
30304
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
30029
30305
  if (adapter.installMode === "marketplace") {
30030
- const cache = join22(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
30306
+ const cache = join23(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
30031
30307
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
30032
30308
  }
30033
30309
  rmSync7(root, { recursive: true, force: true });
30034
30310
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
30035
30311
  }
30036
30312
  case "plugin": {
30037
- const agentDir = join22(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
30313
+ const agentDir = join23(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
30038
30314
  if (!existsSync19(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
30039
30315
  rmSync7(agentDir, { recursive: true, force: true });
30040
30316
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
@@ -30080,7 +30356,7 @@ function ownEntries(agent, env) {
30080
30356
  }
30081
30357
  if (agent === "opencode") {
30082
30358
  return [{
30083
- file: join22(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
30359
+ file: join23(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
30084
30360
  // D-WIN-OPENCODE-DIR-1
30085
30361
  key: OPENCODE_PLUGIN_KEY,
30086
30362
  shown: OPENCODE_PLUGIN_KEY,
@@ -30091,7 +30367,7 @@ function ownEntries(agent, env) {
30091
30367
  if (agent === "pi") {
30092
30368
  const agentDir = piAgentDirOf(env, home);
30093
30369
  return [{
30094
- file: join22(agentDir, SETTINGS_FILE),
30370
+ file: join23(agentDir, SETTINGS_FILE),
30095
30371
  key: PI_PACKAGES_KEY,
30096
30372
  shown: PI_PACKAGES_KEY,
30097
30373
  has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
@@ -30113,12 +30389,12 @@ function removeOwnEntries(agent, env) {
30113
30389
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
30114
30390
  }
30115
30391
  function removeProjectData(configDir, projectKey) {
30116
- const projects = join22(configDir, PROJECTS_DIR_NAME);
30117
- const dir = join22(projects, projectKey);
30392
+ const projects = join23(configDir, PROJECTS_DIR_NAME);
30393
+ const dir = join23(projects, projectKey);
30118
30394
  if (!existsSync19(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
30119
30395
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
30120
- for (const name of readdirSync8(dir)) {
30121
- if (name !== OWNERS_DIR_NAME) rmSync7(join22(dir, name), { recursive: true, force: true });
30396
+ for (const name of readdirSync9(dir)) {
30397
+ if (name !== OWNERS_DIR_NAME) rmSync7(join23(dir, name), { recursive: true, force: true });
30122
30398
  }
30123
30399
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
30124
30400
  }
@@ -30126,7 +30402,7 @@ function runUninstall(input) {
30126
30402
  const configDir = resolveConfigDir(input.env);
30127
30403
  const stop = stopServers(configDir, input.project.projectKey);
30128
30404
  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));
30405
+ 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
30406
  return { rows, stopped: stop.stopped };
30131
30407
  }
30132
30408
 
@@ -30262,8 +30538,8 @@ function removeV1(agent, findings) {
30262
30538
 
30263
30539
  // src/core/ops/verify-sums.ts
30264
30540
  import { createHash as createHash2 } from "node:crypto";
30265
- import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "node:fs";
30266
- import { join as join23 } from "node:path";
30541
+ import { lstatSync as lstatSync2, readdirSync as readdirSync10, readFileSync as readFileSync17 } from "node:fs";
30542
+ import { join as join24 } from "node:path";
30267
30543
  function mismatch() {
30268
30544
  return new CtxError("BUNDLE_HASH_MISMATCH");
30269
30545
  }
@@ -30281,17 +30557,17 @@ function parseSums(text) {
30281
30557
  return sums;
30282
30558
  }
30283
30559
  function walk3(dir, prefix, out) {
30284
- for (const entry of readdirSync9(dir, { withFileTypes: true })) {
30560
+ for (const entry of readdirSync10(dir, { withFileTypes: true })) {
30285
30561
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
30286
30562
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
30287
- const abs = join23(dir, entry.name);
30563
+ const abs = join24(dir, entry.name);
30288
30564
  if (entry.isDirectory()) walk3(abs, rel, out);
30289
30565
  else if (entry.isFile()) out.set(rel, abs);
30290
30566
  else throw mismatch();
30291
30567
  }
30292
30568
  }
30293
30569
  function verifySums(dir) {
30294
- const sumsPath = join23(dir, RELEASE_SUMS_FILE);
30570
+ const sumsPath = join24(dir, RELEASE_SUMS_FILE);
30295
30571
  const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
30296
30572
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
30297
30573
  const sums = parseSums(readFileSync17(sumsPath, "utf8"));
@@ -30315,7 +30591,7 @@ function row4(area, before, after) {
30315
30591
  return { area, before, after };
30316
30592
  }
30317
30593
  function bundleDir() {
30318
- return dirname11(process.argv[1] ?? "");
30594
+ return dirname12(process.argv[1] ?? "");
30319
30595
  }
30320
30596
  function pluginRootRow(adapter, env) {
30321
30597
  const own4 = bundleDir();
@@ -30329,12 +30605,12 @@ function pluginRootRow(adapter, env) {
30329
30605
  return root === own4 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own4)];
30330
30606
  }
30331
30607
  function isCurrent(agentDir, dir) {
30332
- const link = join24(agentDir, PLUGIN_CURRENT_LINK);
30608
+ const link = join25(agentDir, PLUGIN_CURRENT_LINK);
30333
30609
  return existsSync21(link) && realpathSync10.native(link) === realpathSync10.native(dir);
30334
30610
  }
30335
30611
  async function checkout(adapter, deps) {
30336
30612
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);
30337
- const agentDir = dirname11(fetched.dir);
30613
+ const agentDir = dirname12(fetched.dir);
30338
30614
  try {
30339
30615
  verifySums(fetched.dir);
30340
30616
  } catch (err) {
@@ -30362,7 +30638,7 @@ async function upgrade(adapter, deps, home) {
30362
30638
  return rows;
30363
30639
  } catch (err) {
30364
30640
  removal?.rollback();
30365
- if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename6(done.swap.previous));
30641
+ if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename7(done.swap.previous));
30366
30642
  throw err;
30367
30643
  }
30368
30644
  }
@@ -30451,7 +30727,7 @@ function checkCall(tool, input) {
30451
30727
  // src/entries/server.ts
30452
30728
  import { randomUUID } from "node:crypto";
30453
30729
  import { existsSync as existsSync23, realpathSync as realpathSync12, rmSync as rmSync11 } from "node:fs";
30454
- import { dirname as dirname12, join as join26 } from "node:path";
30730
+ import { dirname as dirname13, join as join27 } from "node:path";
30455
30731
  import { fileURLToPath as fileURLToPath2 } from "node:url";
30456
30732
 
30457
30733
  // node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
@@ -33325,14 +33601,14 @@ var $ZodIntersection2 = /* @__PURE__ */ $constructor2("$ZodIntersection", (inst,
33325
33601
  inst._zod.parse = (payload, ctx) => {
33326
33602
  const input = payload.value;
33327
33603
  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;
33604
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
33605
+ const async = left instanceof Promise || right2 instanceof Promise;
33330
33606
  if (async) {
33331
- return Promise.all([left, right]).then(([left2, right2]) => {
33332
- return handleIntersectionResults2(payload, left2, right2);
33607
+ return Promise.all([left, right2]).then(([left2, right3]) => {
33608
+ return handleIntersectionResults2(payload, left2, right3);
33333
33609
  });
33334
33610
  }
33335
- return handleIntersectionResults2(payload, left, right);
33611
+ return handleIntersectionResults2(payload, left, right2);
33336
33612
  };
33337
33613
  });
33338
33614
  function mergeValues2(a, b) {
@@ -33383,7 +33659,7 @@ function mergeValues2(a, b) {
33383
33659
  }
33384
33660
  return { valid: false, mergeErrorPath: [] };
33385
33661
  }
33386
- function handleIntersectionResults2(result, left, right) {
33662
+ function handleIntersectionResults2(result, left, right2) {
33387
33663
  const unrecKeys = /* @__PURE__ */ new Map();
33388
33664
  let unrecIssue;
33389
33665
  const keyIssues = /* @__PURE__ */ new Map();
@@ -33411,7 +33687,7 @@ function handleIntersectionResults2(result, left, right) {
33411
33687
  if (!collect(iss, "l"))
33412
33688
  result.issues.push(iss);
33413
33689
  }
33414
- for (const iss of right.issues) {
33690
+ for (const iss of right2.issues) {
33415
33691
  if (!collect(iss, "r"))
33416
33692
  result.issues.push(iss);
33417
33693
  }
@@ -33425,7 +33701,7 @@ function handleIntersectionResults2(result, left, right) {
33425
33701
  result.issues.push(keyIssues.get(k));
33426
33702
  }
33427
33703
  }
33428
- const merged = mergeValues2(left.value, right.value);
33704
+ const merged = mergeValues2(left.value, right2.value);
33429
33705
  if (!merged.valid) {
33430
33706
  if (aborted2(result))
33431
33707
  return result;
@@ -33815,11 +34091,11 @@ var $ZodPipe2 = /* @__PURE__ */ $constructor2("$ZodPipe", (inst, def) => {
33815
34091
  defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);
33816
34092
  inst._zod.parse = (payload, ctx) => {
33817
34093
  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));
34094
+ const right2 = def.out._zod.run(payload, ctx);
34095
+ if (right2 instanceof Promise) {
34096
+ return right2.then((right3) => handlePipeResult2(right3, def.in, ctx));
33821
34097
  }
33822
- return handlePipeResult2(right, def.in, ctx);
34098
+ return handlePipeResult2(right2, def.in, ctx);
33823
34099
  }
33824
34100
  const left = def.in._zod.run(payload, ctx);
33825
34101
  if (left instanceof Promise) {
@@ -36789,11 +37065,11 @@ var ZodIntersection2 = /* @__PURE__ */ $constructor2("ZodIntersection", (inst, d
36789
37065
  ZodType2.init(inst, def);
36790
37066
  inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params);
36791
37067
  });
36792
- function intersection2(left, right) {
37068
+ function intersection2(left, right2) {
36793
37069
  return new ZodIntersection2({
36794
37070
  type: "intersection",
36795
37071
  left,
36796
- right
37072
+ right: right2
36797
37073
  });
36798
37074
  }
36799
37075
  var ZodRecord2 = /* @__PURE__ */ $constructor2("ZodRecord", (inst, def) => {
@@ -40854,14 +41130,14 @@ var $ZodIntersection3 = /* @__PURE__ */ $constructor3("$ZodIntersection", (inst,
40854
41130
  inst._zod.parse = (payload, ctx) => {
40855
41131
  const input = payload.value;
40856
41132
  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;
41133
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
41134
+ const async = left instanceof Promise || right2 instanceof Promise;
40859
41135
  if (async) {
40860
- return Promise.all([left, right]).then(([left2, right2]) => {
40861
- return handleIntersectionResults3(payload, left2, right2);
41136
+ return Promise.all([left, right2]).then(([left2, right3]) => {
41137
+ return handleIntersectionResults3(payload, left2, right3);
40862
41138
  });
40863
41139
  }
40864
- return handleIntersectionResults3(payload, left, right);
41140
+ return handleIntersectionResults3(payload, left, right2);
40865
41141
  };
40866
41142
  });
40867
41143
  function mergeValues3(a, b) {
@@ -40912,7 +41188,7 @@ function mergeValues3(a, b) {
40912
41188
  }
40913
41189
  return { valid: false, mergeErrorPath: [] };
40914
41190
  }
40915
- function handleIntersectionResults3(result, left, right) {
41191
+ function handleIntersectionResults3(result, left, right2) {
40916
41192
  const unrecKeys = /* @__PURE__ */ new Map();
40917
41193
  let unrecIssue;
40918
41194
  const keyIssues = /* @__PURE__ */ new Map();
@@ -40940,7 +41216,7 @@ function handleIntersectionResults3(result, left, right) {
40940
41216
  if (!collect(iss, "l"))
40941
41217
  result.issues.push(iss);
40942
41218
  }
40943
- for (const iss of right.issues) {
41219
+ for (const iss of right2.issues) {
40944
41220
  if (!collect(iss, "r"))
40945
41221
  result.issues.push(iss);
40946
41222
  }
@@ -40954,7 +41230,7 @@ function handleIntersectionResults3(result, left, right) {
40954
41230
  result.issues.push(keyIssues.get(k));
40955
41231
  }
40956
41232
  }
40957
- const merged = mergeValues3(left.value, right.value);
41233
+ const merged = mergeValues3(left.value, right2.value);
40958
41234
  if (!merged.valid) {
40959
41235
  if (aborted3(result))
40960
41236
  return result;
@@ -41344,11 +41620,11 @@ var $ZodPipe3 = /* @__PURE__ */ $constructor3("$ZodPipe", (inst, def) => {
41344
41620
  defineLazyInternal2(inst, "propValues", (zod) => zod.def.in._zod.propValues);
41345
41621
  inst._zod.parse = (payload, ctx) => {
41346
41622
  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));
41623
+ const right2 = def.out._zod.run(payload, ctx);
41624
+ if (right2 instanceof Promise) {
41625
+ return right2.then((right3) => handlePipeResult3(right3, def.in, ctx));
41350
41626
  }
41351
- return handlePipeResult3(right, def.in, ctx);
41627
+ return handlePipeResult3(right2, def.in, ctx);
41352
41628
  }
41353
41629
  const left = def.in._zod.run(payload, ctx);
41354
41630
  if (left instanceof Promise) {
@@ -44404,11 +44680,11 @@ var ZodIntersection3 = /* @__PURE__ */ $constructor3("ZodIntersection", (inst, d
44404
44680
  ZodType3.init(inst, def);
44405
44681
  inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor2(inst, ctx, json2, params);
44406
44682
  });
44407
- function intersection3(left, right) {
44683
+ function intersection3(left, right2) {
44408
44684
  return new ZodIntersection3({
44409
44685
  type: "intersection",
44410
44686
  left,
44411
- right
44687
+ right: right2
44412
44688
  });
44413
44689
  }
44414
44690
  var ZodRecord3 = /* @__PURE__ */ $constructor3("ZodRecord", (inst, def) => {
@@ -58516,8 +58792,8 @@ function installExitGuard(opts) {
58516
58792
  }
58517
58793
 
58518
58794
  // src/core/store/cleanup.ts
58519
- import { existsSync as existsSync22, readdirSync as readdirSync10, rmSync as rmSync10 } from "node:fs";
58520
- import { join as join25 } from "node:path";
58795
+ import { existsSync as existsSync22, readdirSync as readdirSync11, rmSync as rmSync10 } from "node:fs";
58796
+ import { join as join26 } from "node:path";
58521
58797
  function deleteSource(raw, id) {
58522
58798
  raw.prepare("DELETE FROM sources WHERE id = ?").run(id);
58523
58799
  deleteChunkRows(raw, { sourceId: id });
@@ -58573,8 +58849,8 @@ function lastAccess(raw) {
58573
58849
  return row5.t;
58574
58850
  }
58575
58851
  function sweepOne(configDir, projectKey, cutoff) {
58576
- const dir = join25(configDir, PROJECTS_DIR_NAME, projectKey);
58577
- const db = openForSweep(join25(dir, DB_FILE_NAME), projectKey);
58852
+ const dir = join26(configDir, PROJECTS_DIR_NAME, projectKey);
58853
+ const db = openForSweep(join26(dir, DB_FILE_NAME), projectKey);
58578
58854
  let dead;
58579
58855
  try {
58580
58856
  dead = withWrite(db, (h) => listLiveOwners(configDir, projectKey).length === 0 && lastAccess(h.raw) < cutoff);
@@ -58587,7 +58863,7 @@ function sweepOne(configDir, projectKey, cutoff) {
58587
58863
  function sweepDeadProjects(configDir) {
58588
58864
  let entries;
58589
58865
  try {
58590
- entries = readdirSync10(join25(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
58866
+ entries = readdirSync11(join26(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
58591
58867
  } catch (err) {
58592
58868
  if (err.code === "ENOENT") return [];
58593
58869
  throw err;
@@ -58696,7 +58972,7 @@ function workspaceCwdOf(meta3, spawnCwd, script) {
58696
58972
  const fromHost = workspaceFromMeta(meta3);
58697
58973
  if (fromHost !== void 0) return fromHost;
58698
58974
  if (script === void 0 || script === "") return spawnCwd;
58699
- return realOrSame(spawnCwd) === realOrSame(dirname12(script)) ? "" : spawnCwd;
58975
+ return realOrSame(spawnCwd) === realOrSame(dirname13(script)) ? "" : spawnCwd;
58700
58976
  }
58701
58977
  function errorReply(err) {
58702
58978
  if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0 };
@@ -58739,7 +59015,7 @@ async function startServer(argv, env) {
58739
59015
  return db;
58740
59016
  }
58741
59017
  function stopMarker(configDir, projectKey) {
58742
- return join26(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
59018
+ return join27(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
58743
59019
  }
58744
59020
  function stopRequested() {
58745
59021
  const configDir = resolveConfigDir(process.env);
@@ -58795,7 +59071,7 @@ async function startServer(argv, env) {
58795
59071
  try {
58796
59072
  await journal(resolved, ctx, tool.name, reply4);
58797
59073
  } catch (err) {
58798
- reply4 = errorReply(err);
59074
+ reply4 = tool.name === DOCTOR_TOOL_NAME ? { ...reply4, text: reply4.text + "\n" + JOURNAL_SKIPPED_LINE(errorReply(err).text) } : errorReply(err);
58799
59075
  }
58800
59076
  }
58801
59077
  }