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.
@@ -425,7 +425,7 @@ var DECISION_OPTION_KEY = "option";
425
425
  var DECISION_LABEL_JOIN = " | ";
426
426
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
427
427
  var RELEASE_BRANCH = "release";
428
- var BUNDLE_SHA = true ? "e19d949bebe3a1751b6dc1a520b5ad38659fdd6f" : void 0;
428
+ var BUNDLE_SHA = true ? "ede83923546ab97898750ef7cebe34cf82e9534c" : void 0;
429
429
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
430
430
  var DOCTOR_LABEL = Object.freeze({
431
431
  D1: "version",
@@ -448,6 +448,8 @@ var REPORT_HEADER = "| Check | Status | Detail | Fix |";
448
448
  var REPORT_HEADER_RULE = "|---|---|---|---|";
449
449
  var REPORT_COMMAND_PREFIX = "Run in a terminal: ";
450
450
  var ECHO_MAX_BYTES = 256;
451
+ var LABEL_PREVIEW_BYTES = 32;
452
+ var LABEL_PAGE_BYTES = 8192;
451
453
  var REPORT_SOURCE_LABEL = "ctx_doctor:report";
452
454
  var REPORT_REST_PREFIX = "Rows not shown here are stored in full. Read them with: ";
453
455
  var REPORT_POINTER = `ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(REPORT_SOURCE_LABEL)}})`;
@@ -544,6 +546,19 @@ function D8_HEALED_RECREATE_DETAIL(ts) {
544
546
  }
545
547
  var INTEGRITY_OK = "ok";
546
548
  var HEAL_BACKUP_SUFFIX = ".bak";
549
+ var orphanList = (files) => files.map((f) => `${f.path} (${f.bytes} bytes)`).join(", ");
550
+ var ORPHAN_DIR_PREFIX = "orphan-";
551
+ function D8_ORPHAN_DETAIL(files) {
552
+ return `context.db is gone, its WAL files are still here: ${orphanList(files)}`;
553
+ }
554
+ var D8_ORPHAN_FIX = "run ctx_doctor once; it keeps these files in a dated folder and starts a new index";
555
+ function D8_ORPHAN_HEALED_DETAIL(dir, moved, dbPath) {
556
+ 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`;
557
+ }
558
+ var D8_ORPHAN_HEALED_FIX = "run ctx_doctor again; D8 then reads PASS";
559
+ function D8_ORPHAN_MOVE_FAILED(detail, cause) {
560
+ return `${detail}; moving them aside failed: ${cause}`;
561
+ }
547
562
  function D9_INDEX_DETAIL(sources, chunks) {
548
563
  return `${sources} sources, ${chunks} chunks indexed`;
549
564
  }
@@ -921,7 +936,8 @@ var DOCTOR_LOG_TAIL_BYTES = 262144;
921
936
  var ERROR_TEXT = Object.freeze({
922
937
  NODE_TOO_OLD: "Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",
923
938
  NO_SQLITE: "node:sqlite failed to load. Fix: run ctx_doctor.",
924
- DB_GONE: "context.db path vanished. Fix: run ctx_doctor.",
939
+ 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.",
940
+ // D-ORPHAN-WAL-1
925
941
  NO_PROJECT: "Project source <kind> is missing. Fix: run ctx_doctor.",
926
942
  UNKNOWN_FIELD: 'Unknown field "<f>". Fix: use "queries".',
927
943
  TIMEOUT: "Timed out after <ms> ms. Fix: pass background: true.",
@@ -2525,8 +2541,8 @@ function jqWhitelisted(filter2) {
2525
2541
  const bar2 = s.indexOf(JQ_WHITELIST.pipeLength.charAt(0));
2526
2542
  if (bar2 < 0) return jqPath(s);
2527
2543
  const left = s.slice(0, bar2).trim();
2528
- const right = JQ_WHITELIST.pipeLength.slice(1).trim();
2529
- return (left === JQ_WHITELIST.identity || jqPath(left)) && s.slice(bar2 + 1).trim() === right;
2544
+ const right2 = JQ_WHITELIST.pipeLength.slice(1).trim();
2545
+ return (left === JQ_WHITELIST.identity || jqPath(left)) && s.slice(bar2 + 1).trim() === right2;
2530
2546
  }
2531
2547
  function isBoundedSink(c) {
2532
2548
  const name = c.argv0.toLowerCase();
@@ -3728,10 +3744,10 @@ function matchesAnyDenyPattern(text, patterns, subject = BASH_SUBJECT) {
3728
3744
  // src/prompt/_generated.ts
3729
3745
  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";
3730
3746
  var TOOL_DESCRIPTIONS = Object.freeze({
3731
- 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.',
3747
+ 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.',
3732
3748
  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.',
3733
3749
  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.',
3734
- ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',
3750
+ 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.',
3735
3751
  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.",
3736
3752
  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.",
3737
3753
  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",
@@ -6606,6 +6622,7 @@ var PORTER_MATCH = `
6606
6622
  AND (:scope <> 'session' OR chunks.session_id = :session_id)
6607
6623
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
6608
6624
  AND (:source IS NULL OR s.label = :source)
6625
+ AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
6609
6626
  ${NOT_RAW}`;
6610
6627
  var PORTER_ORDER = `
6611
6628
  ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`;
@@ -6634,6 +6651,7 @@ WHERE chunks_tri MATCH :match
6634
6651
  AND (:scope <> 'session' OR c.session_id = :session_id)
6635
6652
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
6636
6653
  AND (:source IS NULL OR s.label = :source)
6654
+ AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
6637
6655
  ${NOT_RAW}
6638
6656
  ORDER BY bm25(chunks_tri, 1.0, ${TITLE_WEIGHT}) ASC, c.source_id DESC, c.ord ASC`;
6639
6657
  var PAGE_ROWS = `
@@ -6906,10 +6924,18 @@ function typoTerms(db, words) {
6906
6924
  });
6907
6925
  return changed ? out.map((t) => `"${t.replaceAll('"', '""')}"*`) : null;
6908
6926
  }
6909
- function ftsQuery(db, q, scope, ctx, sessionId, limit, offset, source) {
6927
+ var LABEL_SERIAL = `
6928
+ SELECT COALESCE(MAX(CAST(substr(label, length(:prefix) + 1) AS INTEGER)), 0) + 1 AS n
6929
+ FROM sources WHERE session_id = :session_id AND substr(label, 1, length(:prefix)) = :prefix`;
6930
+ function nextLabelSerial(db, sessionId, prefix) {
6931
+ const row5 = stmt(db.raw, LABEL_SERIAL).get({ session_id: sessionId, prefix });
6932
+ return Number(row5.n);
6933
+ }
6934
+ function ftsQuery(db, q, scope, ctx, sessionId, limit, offset, source, sourceIds) {
6910
6935
  const terms = searchTerms(q);
6911
6936
  if (terms.length === 0) return [];
6912
- const filter2 = { scope, session_id: sessionId, worktree: ctx.worktree, source: source ?? null };
6937
+ const ids = sourceIds === void 0 ? null : JSON.stringify(sourceIds);
6938
+ const filter2 = { scope, session_id: sessionId, worktree: ctx.worktree, source: source ?? null, ids };
6913
6939
  const rrf = scope === "project" ? { k: RRF_K } : {};
6914
6940
  const porter = (t) => stmt(db.raw, porterRankSql(scope)).all({ ...filter2, match: t.join(" OR "), all: t.join(" "), ...rrf });
6915
6941
  let pList = porter(terms);
@@ -7115,20 +7141,84 @@ function storedLabel(db, source) {
7115
7141
  const canon = pathLabel(source);
7116
7142
  return canon !== source && labelStored(db, canon) ? canon : source;
7117
7143
  }
7118
- function resolveSourceLabel(db, source) {
7144
+ function newestId(db, label2) {
7145
+ const row5 = stmt(db.raw, "SELECT id FROM sources WHERE label = ? ORDER BY id DESC LIMIT 1").get(label2);
7146
+ return row5 === void 0 ? null : Number(row5.id);
7147
+ }
7148
+ function labelOfId(db, id2) {
7149
+ const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id2);
7150
+ return row5 === void 0 ? null : row5.label;
7151
+ }
7152
+ function pickSource(db, source, suffix = true) {
7153
+ const named2 = storedLabel(db, source);
7119
7154
  const id2 = parseSourceHandle(source);
7155
+ const own2 = newestId(db, named2);
7156
+ if (own2 !== null) {
7157
+ const otherLabel = id2 === null || id2 === own2 ? null : labelOfId(db, id2);
7158
+ return { label: named2, id: own2, via: "label", other: otherLabel === null || otherLabel === named2 ? null : { id: id2, label: otherLabel } };
7159
+ }
7120
7160
  if (id2 !== null) {
7121
- const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id2);
7122
- if (row5 !== void 0) return row5.label;
7161
+ const label2 = labelOfId(db, id2);
7162
+ if (label2 !== null) return { label: label2, id: id2, via: "handle", other: null };
7163
+ }
7164
+ if (suffix) {
7165
+ const prefix = named2 + LABEL_SUFFIX_SEP;
7166
+ const rows = stmt(db.raw, "SELECT id, label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
7167
+ for (const r of rows) {
7168
+ if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named2.length) return { label: r.label, id: Number(r.id), via: "suffix", other: null };
7169
+ }
7123
7170
  }
7124
- const named = storedLabel(db, source);
7125
- if (labelStored(db, named)) return named;
7126
- const prefix = named + LABEL_SUFFIX_SEP;
7127
- const rows = stmt(db.raw, "SELECT label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
7128
- for (const r of rows) {
7129
- if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named.length) return r.label;
7171
+ return { label: source, id: null, via: "none", other: null };
7172
+ }
7173
+ function collisionLine(value, pick2) {
7174
+ if (pick2.other === null || pick2.id === null) return null;
7175
+ return "Source " + JSON.stringify(value) + ": used the label " + shownLabel(pick2.label, null) + " (" + sourceHandle(pick2.id) + "); handle " + sourceHandle(pick2.other.id) + " is " + shownLabel(pick2.other.label, null) + (isLongLabel(pick2.other.label) ? ", search it by its full label." : ", search it with source:" + JSON.stringify(pick2.other.label) + ".");
7176
+ }
7177
+ function labelPage(label2, offset, max) {
7178
+ const buf = Buffer.from(label2, "utf8");
7179
+ let start = Math.min(offset, buf.length);
7180
+ while (start < buf.length && (buf[start] & 192) === 128) start++;
7181
+ let end = Math.min(start + max, buf.length);
7182
+ while (end < buf.length && end > start && (buf[end] & 192) === 128) end--;
7183
+ return { text: buf.subarray(start, end).toString("utf8"), next: end < buf.length ? end : null, total: buf.length };
7184
+ }
7185
+ function groupDigits(n) {
7186
+ const s = String(Math.trunc(n));
7187
+ let out = "";
7188
+ for (let i = 0; i < s.length; i++) {
7189
+ if (i > 0 && (s.length - i) % 3 === 0) out += ",";
7190
+ out += s[i];
7191
+ }
7192
+ return out;
7193
+ }
7194
+ function headBytes(s, max) {
7195
+ let out = "";
7196
+ let used = 0;
7197
+ for (const ch of s) {
7198
+ const n = Buffer.byteLength(ch, "utf8");
7199
+ if (used + n > max) break;
7200
+ out += ch;
7201
+ used += n;
7130
7202
  }
7131
- return source;
7203
+ return out;
7204
+ }
7205
+ function isLongLabel(label2) {
7206
+ return Buffer.byteLength(label2, "utf8") > ECHO_MAX_BYTES;
7207
+ }
7208
+ function labelPreview(label2) {
7209
+ return "label (" + groupDigits(Buffer.byteLength(label2, "utf8")) + " B): " + headBytes(label2, LABEL_PREVIEW_BYTES) + "\u2026";
7210
+ }
7211
+ function shownLabel(label2, id2) {
7212
+ if (!isLongLabel(label2)) return label2;
7213
+ return (id2 === null ? "" : sourceHandle(id2) + " ") + "[" + labelPreview(label2) + "]";
7214
+ }
7215
+ function indexedLabelLine(label2, id2) {
7216
+ if (!isLongLabel(label2)) return "Label: " + label2;
7217
+ return "Its label (" + groupDigits(Buffer.byteLength(label2, "utf8")) + " B): " + headBytes(label2, LABEL_PREVIEW_BYTES) + "\u2026; ctx_search({queries:[], source:" + JSON.stringify(sourceHandle(id2)) + "}) reads it whole.";
7218
+ }
7219
+ function sourceCardRow(db, id2) {
7220
+ const row5 = stmt(db.raw, "SELECT label, bytes_total, chunk_count, kind FROM sources WHERE id = ?").get(id2);
7221
+ return row5 === void 0 ? null : { label: row5.label, bytes: Number(row5.bytes_total), chunks: Number(row5.chunk_count), kind: row5.kind };
7132
7222
  }
7133
7223
  function listSessionSources(db, sessionId, limit) {
7134
7224
  const rows = stmt(db.raw, "SELECT id, label, bytes_total FROM sources WHERE session_id = ? ORDER BY id DESC LIMIT ?").all(sessionId, limit);
@@ -7705,8 +7795,8 @@ function rawEnd(src, from, name) {
7705
7795
  let k = src.indexOf("</", from);
7706
7796
  while (k >= 0) {
7707
7797
  const after = k + "</".length + name.length;
7708
- const named = src.slice(k + "</".length, after).toLowerCase() === name;
7709
- if (named && (after >= src.length || !isNameChar(src[after]))) {
7798
+ const named2 = src.slice(k + "</".length, after).toLowerCase() === name;
7799
+ if (named2 && (after >= src.length || !isNameChar(src[after]))) {
7710
7800
  const gt = src.indexOf(">", after);
7711
7801
  return gt < 0 ? src.length : gt + 1;
7712
7802
  }
@@ -7733,7 +7823,7 @@ function cutPoint(src, start, end, scratch) {
7733
7823
  const r = encoder.encodeInto(src.slice(start, limit), scratch);
7734
7824
  return { end: start + r.read, written: r.written };
7735
7825
  }
7736
- function merge(src, blocks, join25, cap, lineCut) {
7826
+ function merge(src, blocks, join26, cap, lineCut) {
7737
7827
  const out = [];
7738
7828
  const scratch = new Uint8Array(cap);
7739
7829
  let wide;
@@ -7743,7 +7833,7 @@ function merge(src, blocks, join25, cap, lineCut) {
7743
7833
  out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
7744
7834
  };
7745
7835
  for (const b of blocks) {
7746
- if (cur !== void 0 && !join25) {
7836
+ if (cur !== void 0 && !join26) {
7747
7837
  emit(cur.start, cur.end, curBytes);
7748
7838
  cur = void 0;
7749
7839
  }
@@ -7941,24 +8031,24 @@ function jsonShape(text, query) {
7941
8031
  }
7942
8032
  if (outliers.size === 0 || outliers.size > SHAPE_RARE_UNITS_MAX) return null;
7943
8033
  const keyScore = rankTexts(keys, query, "any");
7944
- const named = new Set(keys.filter((_, i) => keyScore[i] > 0));
8034
+ const named2 = new Set(keys.filter((_, i) => keyScore[i] > 0));
7945
8035
  const units = [...outliers.entries()].map(([i, skewed]) => ({
7946
8036
  pos: i,
7947
8037
  rank: JSON.stringify(objs[i]),
7948
- render: (budget) => renderRow(i, objs[i], skewed, named, budget)
8038
+ render: (budget) => renderRow(i, objs[i], skewed, named2, budget)
7949
8039
  }));
7950
8040
  return { header: schemaOf(objs.length, keys) + ", " + outliers.size + " rare:", units };
7951
8041
  }
7952
- function renderRow(i, row5, skewed, named, budget) {
8042
+ function renderRow(i, row5, skewed, named2, budget) {
7953
8043
  const prefix = "[" + i + "] ";
7954
- const body = fitRow(row5, skewed, named, budget - bytes(prefix));
8044
+ const body = fitRow(row5, skewed, named2, budget - bytes(prefix));
7955
8045
  return body === null ? null : prefix + body;
7956
8046
  }
7957
- function fitRow(row5, skewed, named, budget) {
8047
+ function fitRow(row5, skewed, named2, budget) {
7958
8048
  const whole2 = JSON.stringify(row5);
7959
8049
  if (bytes(whole2) <= budget) return whole2;
7960
8050
  const own2 = Object.keys(row5);
7961
- const tier = (k) => skewed.includes(k) ? 0 : named.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
8051
+ const tier = (k) => skewed.includes(k) ? 0 : named2.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
7962
8052
  const order = [...own2].sort((a, b) => tier(a) - tier(b) || own2.indexOf(a) - own2.indexOf(b));
7963
8053
  const field = (k) => JSON.stringify(k) + ":" + JSON.stringify(row5[k]);
7964
8054
  const chosen = /* @__PURE__ */ new Set();
@@ -7980,11 +8070,11 @@ function jsonExtremes(text, query) {
7980
8070
  const parsedRows = jsonRows(text);
7981
8071
  if (parsedRows === null) return null;
7982
8072
  const { objs, keys } = parsedRows;
7983
- const named = namedKeys(keys, query);
8073
+ const named2 = namedKeys(keys, query);
7984
8074
  const picks = /* @__PURE__ */ new Map();
7985
8075
  let used = 0;
7986
8076
  for (const k of keys) {
7987
- if (!named.has(k) || used >= SHAPE_EXTREME_KEYS) continue;
8077
+ if (!named2.has(k) || used >= SHAPE_EXTREME_KEYS) continue;
7988
8078
  if (!objs.every((o) => typeof o[k] === "number" && Number.isFinite(o[k]))) continue;
7989
8079
  let hi = 0, lo = 0;
7990
8080
  for (let i = 1; i < objs.length; i++) {
@@ -8000,7 +8090,7 @@ function jsonExtremes(text, query) {
8000
8090
  const units = [...picks.entries()].map(([i, k]) => ({
8001
8091
  pos: i,
8002
8092
  rank: "",
8003
- render: (budget) => renderRow(i, objs[i], [k], named, budget)
8093
+ render: (budget) => renderRow(i, objs[i], [k], named2, budget)
8004
8094
  }));
8005
8095
  return { header: schemaOf(objs.length, keys) + ", extremes of " + [...new Set(picks.values())].join(",") + ":", units, direct: true };
8006
8096
  }
@@ -11640,14 +11730,14 @@ var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, d
11640
11730
  inst._zod.parse = (payload, ctx) => {
11641
11731
  const input = payload.value;
11642
11732
  const left = def.left._zod.run({ value: input, issues: [] }, ctx);
11643
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
11644
- const async = left instanceof Promise || right instanceof Promise;
11733
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
11734
+ const async = left instanceof Promise || right2 instanceof Promise;
11645
11735
  if (async) {
11646
- return Promise.all([left, right]).then(([left2, right2]) => {
11647
- return handleIntersectionResults(payload, left2, right2);
11736
+ return Promise.all([left, right2]).then(([left2, right3]) => {
11737
+ return handleIntersectionResults(payload, left2, right3);
11648
11738
  });
11649
11739
  }
11650
- return handleIntersectionResults(payload, left, right);
11740
+ return handleIntersectionResults(payload, left, right2);
11651
11741
  };
11652
11742
  });
11653
11743
  function mergeValues(a, b) {
@@ -11694,16 +11784,16 @@ function mergeValues(a, b) {
11694
11784
  }
11695
11785
  return { valid: false, mergeErrorPath: [] };
11696
11786
  }
11697
- function handleIntersectionResults(result, left, right) {
11787
+ function handleIntersectionResults(result, left, right2) {
11698
11788
  if (left.issues.length) {
11699
11789
  result.issues.push(...left.issues);
11700
11790
  }
11701
- if (right.issues.length) {
11702
- result.issues.push(...right.issues);
11791
+ if (right2.issues.length) {
11792
+ result.issues.push(...right2.issues);
11703
11793
  }
11704
11794
  if (aborted(result))
11705
11795
  return result;
11706
- const merged = mergeValues(left.value, right.value);
11796
+ const merged = mergeValues(left.value, right2.value);
11707
11797
  if (!merged.valid) {
11708
11798
  throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
11709
11799
  }
@@ -17770,11 +17860,11 @@ function _discriminatedUnion(Class2, discriminator, options, params) {
17770
17860
  ...normalizeParams(params)
17771
17861
  });
17772
17862
  }
17773
- function _intersection(Class2, left, right) {
17863
+ function _intersection(Class2, left, right2) {
17774
17864
  return new Class2({
17775
17865
  type: "intersection",
17776
17866
  left,
17777
- right
17867
+ right: right2
17778
17868
  });
17779
17869
  }
17780
17870
  function _tuple(Class2, items, _paramsOrRest, _params) {
@@ -19452,11 +19542,11 @@ var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def
19452
19542
  $ZodIntersection.init(inst, def);
19453
19543
  ZodType.init(inst, def);
19454
19544
  });
19455
- function intersection(left, right) {
19545
+ function intersection(left, right2) {
19456
19546
  return new ZodIntersection({
19457
19547
  type: "intersection",
19458
19548
  left,
19459
- right
19549
+ right: right2
19460
19550
  });
19461
19551
  }
19462
19552
  var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
@@ -20132,17 +20222,29 @@ function runProcess(argv, o) {
20132
20222
  }
20133
20223
 
20134
20224
  // src/core/index/auto-memory.ts
20135
- import { readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
20225
+ import { readdirSync, readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
20136
20226
  import { join as join7 } from "node:path";
20137
- var CLAUDE_CODE_MEMORY_FILES = Object.freeze([
20227
+ var MEMORY_FILES = Object.freeze([
20138
20228
  Object.freeze(["CLAUDE.md"]),
20139
20229
  Object.freeze(["CLAUDE.local.md"]),
20140
- Object.freeze([".claude", "CLAUDE.md"])
20230
+ Object.freeze([".claude", "CLAUDE.md"]),
20231
+ Object.freeze(["AGENTS.md"]),
20232
+ Object.freeze(["GEMINI.md"]),
20233
+ Object.freeze(["QWEN.md"]),
20234
+ Object.freeze([".github", "copilot-instructions.md"])
20141
20235
  ]);
20236
+ var KIRO_STEERING = Object.freeze([".kiro", "steering"]);
20237
+ var MD = ".md";
20238
+ function steeringFiles(worktree) {
20239
+ try {
20240
+ return readdirSync(join7(worktree, ...KIRO_STEERING)).filter((n) => n.endsWith(MD)).sort().map((n) => [...KIRO_STEERING, n]);
20241
+ } catch {
20242
+ return [];
20243
+ }
20244
+ }
20142
20245
  function readAutoMemory(project) {
20143
- if (project.agent !== "claude-code") return [];
20144
20246
  const rows = [];
20145
- for (const segs of CLAUDE_CODE_MEMORY_FILES) {
20247
+ for (const segs of [...MEMORY_FILES, ...steeringFiles(project.worktree)]) {
20146
20248
  const path7 = join7(project.worktree, ...segs);
20147
20249
  if (!isInside(project.worktree, path7)) continue;
20148
20250
  try {
@@ -20162,6 +20264,20 @@ function readAutoMemory(project) {
20162
20264
  }
20163
20265
  return rows;
20164
20266
  }
20267
+ function memoryChunks(rows) {
20268
+ const out = [];
20269
+ rows.forEach((r, i) => {
20270
+ for (const c of chunkText(r.text, "md")) out.push({ fileNo: i + 1, label: r.label, ord: c.ord, text: c.text });
20271
+ });
20272
+ return out;
20273
+ }
20274
+ function memoryHits(chunks, q, limit) {
20275
+ if (chunks.length === 0) return [];
20276
+ const texts = chunks.map((c) => c.text);
20277
+ const any2 = rankTexts(texts, q, "any");
20278
+ const all = rankTexts(texts, q, "all");
20279
+ return chunks.map((c, i) => ({ c, s: any2[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 }));
20280
+ }
20165
20281
 
20166
20282
  // src/core/tools/search.ts
20167
20283
  function unknownField(issue2) {
@@ -20198,8 +20314,27 @@ function sourceCount(db, scope, ctx, source) {
20198
20314
  });
20199
20315
  return Number(row5.n);
20200
20316
  }
20201
- function zeroHits(db, scope, ctx, source) {
20202
- return reply('No hits in scope "' + scope + '" across ' + sourceCount(db, scope, ctx, source) + " source(s).", false);
20317
+ function zeroHits(db, scope, ctx, source, offset = 0) {
20318
+ const n = sourceCount(db, scope, ctx, source);
20319
+ if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
20320
+ return reply('No hits in scope "' + scope + '" across ' + n + " source(s).", false);
20321
+ }
20322
+ function named(given, pick2) {
20323
+ if (given === void 0 || pick2 === null) return { arg: given, note: null };
20324
+ const arg = pick2.id !== null && isLongLabel(given) ? sourceHandle(pick2.id) : given;
20325
+ return { arg, note: collisionLine(given, pick2) };
20326
+ }
20327
+ function sourceCard(db, id2, input, scope, arg) {
20328
+ const row5 = sourceCardRow(db, id2);
20329
+ if (row5 === null) return null;
20330
+ const pg = labelPage(row5.label, input.offset ?? 0, LABEL_PAGE_BYTES);
20331
+ const lines = [
20332
+ "Source " + sourceHandle(id2) + ": label " + groupDigits(pg.total) + " B, " + row5.chunks + " chunk(s), " + groupDigits(row5.bytes) + " B of " + row5.kind + ".",
20333
+ "Label:",
20334
+ pg.text
20335
+ ];
20336
+ if (pg.next !== null) lines.push("More: " + callText([], scope, arg, "offset:" + pg.next));
20337
+ return reply(lines.join("\n"), false);
20203
20338
  }
20204
20339
  function callText(queries, scope, source, cursor) {
20205
20340
  const src = source === void 0 ? "" : ", source:" + JSON.stringify(source);
@@ -20230,7 +20365,7 @@ WHERE label = :source
20230
20365
  AND (:scope <> 'session' OR session_id = :session_id)
20231
20366
  AND (:scope <> 'worktree' OR worktree = :worktree)
20232
20367
  ORDER BY id DESC LIMIT 1`;
20233
- function jsonRowsReply(db, input, scope, ctx) {
20368
+ function jsonRowsReply(db, input, scope, ctx, nm) {
20234
20369
  if (input.source === void 0 || input.source === DECISION_SOURCE || input.queries.length === 0) return null;
20235
20370
  const src = db.raw.prepare(JSON_SOURCE).get({ source: input.source, scope, session_id: ctx.sessionId, worktree: ctx.project.worktree });
20236
20371
  if (src === void 0 || Number(src.bytes_total) > JSON_SOURCE_MAX_BYTES) return null;
@@ -20241,25 +20376,27 @@ function jsonRowsReply(db, input, scope, ctx) {
20241
20376
  const texts = objs.map((o) => JSON.stringify(o));
20242
20377
  const offset = input.offset ?? 0;
20243
20378
  const out = [objs.length + " objects {" + keys.join(",") + "}"];
20379
+ const name = shownLabel(input.source, Number(src.id));
20244
20380
  let shown2 = 0;
20245
20381
  let more = false;
20246
20382
  for (const q of input.queries) {
20247
20383
  const scores = rankTexts(texts, q, "any");
20248
20384
  const order = objs.map((_, i) => i).filter((i) => scores[i] > 0).sort((a, b) => scores[b] - scores[a] || a - b);
20249
- const named = namedKeys(keys, q);
20385
+ const named2 = namedKeys(keys, q);
20250
20386
  out.push("Query " + JSON.stringify(q) + ":");
20251
20387
  for (const i of order.slice(offset, offset + JSON_ROWS_PAGE)) {
20252
- const row5 = fitRow(objs[i], [], named, SNIPPET_MAX_BYTES);
20388
+ const row5 = fitRow(objs[i], [], named2, SNIPPET_MAX_BYTES);
20253
20389
  if (row5 === null) continue;
20254
- out.push(input.source + " [" + i + "]: " + row5);
20390
+ out.push(name + " [" + i + "]: " + row5);
20255
20391
  shown2++;
20256
20392
  }
20257
20393
  if (order.length > offset + JSON_ROWS_PAGE) {
20258
- out.push("More: " + callText([q], scope, input.source, "offset:" + (offset + JSON_ROWS_PAGE)));
20394
+ out.push("More: " + callText([q], scope, nm.arg, "offset:" + (offset + JSON_ROWS_PAGE)));
20259
20395
  more = true;
20260
20396
  }
20261
20397
  }
20262
- return shown2 === 0 && !more ? null : reply(out.join("\n"), false);
20398
+ if (shown2 === 0 && !more) return null;
20399
+ return reply((nm.note === null ? out : [nm.note, ...out]).join("\n"), false);
20263
20400
  }
20264
20401
  var SMALL_SOURCE_SHARE = 0.5;
20265
20402
  var SOURCE_BYTES = "SELECT id, bytes_total FROM sources WHERE id IN (SELECT value FROM json_each(:ids))";
@@ -20278,23 +20415,49 @@ function replyHits(hits, size) {
20278
20415
  while (n < size && n < hits.length && hits[n].full === true) n++;
20279
20416
  return n;
20280
20417
  }
20281
- function relevance(db, given, scope, ctx) {
20418
+ var MEMORY_HITS = 2;
20419
+ function mergeMemory(content, memory) {
20420
+ const out = [];
20421
+ let c = 0;
20422
+ let m = 0;
20423
+ let lastMem = true;
20424
+ while (c < content.length || m < memory.length) {
20425
+ const rank = (h) => h === void 0 ? -1 : h.full === true ? 1 : 0;
20426
+ const rc = rank(content[c]);
20427
+ const rm = rank(memory[m]);
20428
+ const mem = rc < 0 || rm > rc || rm === rc && !lastMem;
20429
+ if (mem) {
20430
+ out.push(memory[m++]);
20431
+ lastMem = true;
20432
+ } else {
20433
+ out.push(content[c++]);
20434
+ lastMem = false;
20435
+ }
20436
+ }
20437
+ return out;
20438
+ }
20439
+ var contentIn = (hits, n) => hits.slice(0, n).filter((h) => h.sourceId > 0).length;
20440
+ function relevance(db, given, scope, ctx, nm) {
20282
20441
  const input = { ...given, queries: decisionQueries(given) };
20283
20442
  const offset = input.offset ?? 0;
20284
20443
  const size = pageSize(input);
20285
- const fetched = input.queries.map((q) => page(db, q, input, scope, ctx, offset, 1));
20444
+ const mem = offset === 0 && scope !== "session" && input.source === void 0 ? memoryChunks(readAutoMemory(ctx.project)) : [];
20445
+ const fetched = input.queries.map((q) => {
20446
+ const content = page(db, q, input, scope, ctx, offset, 1);
20447
+ return mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, q, MEMORY_HITS));
20448
+ });
20286
20449
  const take = fetched.map((h) => replyHits(h, size));
20287
20450
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
20288
- if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source);
20289
- const moreLine3 = (q, pos) => "More: " + callText([q], scope, input.source, "offset:" + pos);
20451
+ if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, offset);
20452
+ const moreLine3 = (q, pos) => "More: " + callText([q], scope, nm.arg, "offset:" + pos);
20290
20453
  let reserve = 0;
20291
20454
  for (const q of input.queries) reserve += bytes2(moreLine3(q, offset + size)) + 1;
20292
20455
  const total = input.source === DECISION_SOURCE ? /* @__PURE__ */ new Map() : sourceBytes(db, [...new Set(pages.flat().map((h) => h.sourceId))]);
20293
20456
  const spent = /* @__PURE__ */ new Map();
20294
- const lines = [];
20457
+ const lines = nm.note === null ? [] : [nm.note];
20295
20458
  const more = [];
20296
20459
  const shown2 = /* @__PURE__ */ new Set();
20297
- let used = 0;
20460
+ let used = nm.note === null ? 0 : bytes2(nm.note) + 1;
20298
20461
  let stopped = false;
20299
20462
  input.queries.forEach((q, qi) => {
20300
20463
  const hits = pages[qi];
@@ -20312,18 +20475,19 @@ function relevance(db, given, scope, ctx) {
20312
20475
  const hit = hits[i];
20313
20476
  const key = hit.sourceId + ":" + hit.ord;
20314
20477
  if (shown2.has(key)) {
20315
- again.set(hit.label, [...again.get(hit.label) ?? [], hit.ord]);
20478
+ const name = shownLabel(hit.label, hit.sourceId);
20479
+ again.set(name, [...again.get(name) ?? [], hit.ord]);
20316
20480
  continue;
20317
20481
  }
20318
- const line = hit.label + " #" + hit.ord + ": " + hit.snippet;
20482
+ const line = shownLabel(hit.label, hit.sourceId) + " #" + hit.ord + ": " + hit.snippet;
20319
20483
  if (used + bytes2(line) + 1 + reserve > OUTPUT_CAP) {
20320
- cut = offset + i;
20484
+ cut = offset + contentIn(hits, i);
20321
20485
  stopped = true;
20322
20486
  break;
20323
20487
  }
20324
20488
  const room = total.get(hit.sourceId);
20325
20489
  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) {
20326
- cut = offset + i;
20490
+ cut = offset + contentIn(hits, i);
20327
20491
  break;
20328
20492
  }
20329
20493
  lines.push(line);
@@ -20338,28 +20502,28 @@ function relevance(db, given, scope, ctx) {
20338
20502
  used += bytes2(line) + 1;
20339
20503
  }
20340
20504
  if (cut >= 0) more.push({ q, pos: cut });
20341
- else if (fetched[qi].length > take[qi]) more.push({ q, pos: offset + take[qi] });
20505
+ else if (contentIn(fetched[qi], fetched[qi].length) > contentIn(fetched[qi], take[qi])) more.push({ q, pos: offset + contentIn(fetched[qi], take[qi]) });
20342
20506
  });
20343
20507
  const moreLines = [];
20344
20508
  const byPos = /* @__PURE__ */ new Map();
20345
20509
  for (const m of more) byPos.set(m.pos, [...byPos.get(m.pos) ?? [], m.q]);
20346
- for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, input.source, "offset:" + pos));
20510
+ for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, nm.arg, "offset:" + pos));
20347
20511
  return reply(lines.concat(moreLines).join("\n"), false);
20348
20512
  }
20349
20513
  function timelineLine(r) {
20350
20514
  const nl = r.text.indexOf("\n");
20351
20515
  const first = nl < 0 ? r.text : r.text.slice(0, nl);
20352
20516
  const seq = r.seq === null ? "" : " #" + r.seq;
20353
- return "[" + new Date(r.ts).toISOString() + "] " + r.label + seq + " " + first;
20517
+ return "[" + new Date(r.ts).toISOString() + "] " + shownLabel(r.label, r.sourceId) + seq + " " + first;
20354
20518
  }
20355
- function timeline(db, input, scope, ctx) {
20519
+ function timeline(db, input, scope, ctx, nm) {
20356
20520
  const memory = scope === "session" ? [] : readAutoMemory(ctx.project);
20357
20521
  const page2 = ftsQueryTimeline(db, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, input.after ?? null, input.source, memory);
20358
20522
  if (page2.rows.length === 0) return zeroHits(db, scope, ctx, input.source);
20359
- const moreLine3 = (ts) => "more: " + callText(input.queries, scope, input.source, 'sort:"timeline", after:' + ts);
20523
+ const moreLine3 = (ts) => "more: " + callText(input.queries, scope, nm.arg, 'sort:"timeline", after:' + ts);
20360
20524
  const reserve = bytes2(moreLine3(page2.rows[page2.rows.length - 1].ts)) + 1;
20361
- const lines = [];
20362
- let used = 0;
20525
+ const lines = nm.note === null ? [] : [nm.note];
20526
+ let used = nm.note === null ? 0 : bytes2(nm.note) + 1;
20363
20527
  let lastTs = null;
20364
20528
  let more = page2.more;
20365
20529
  let i = 0;
@@ -20395,9 +20559,16 @@ async function handler(input, ctx) {
20395
20559
  const scope = input.scope ?? "worktree";
20396
20560
  const db = await openDb(ctx.project, { readOnly: true });
20397
20561
  try {
20398
- if (input.source !== void 0 && input.source !== DECISION_SOURCE) input = { ...input, source: resolveSourceLabel(db, input.source) };
20399
- if (sort === "timeline") return timeline(db, input, scope, ctx);
20400
- return jsonRowsReply(db, input, scope, ctx) ?? relevance(db, input, scope, ctx);
20562
+ const given = input.source;
20563
+ const pick2 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given) : null;
20564
+ if (pick2 !== null) input = { ...input, source: pick2.label };
20565
+ const nm = named(given, pick2);
20566
+ if (sort === "timeline") return timeline(db, input, scope, ctx, nm);
20567
+ if (pick2 !== null && pick2.id !== null && input.queries.length === 0) {
20568
+ const card = sourceCard(db, pick2.id, input, scope, nm.arg);
20569
+ if (card !== null) return card;
20570
+ }
20571
+ return jsonRowsReply(db, input, scope, ctx, nm) ?? relevance(db, input, scope, ctx, nm);
20401
20572
  } finally {
20402
20573
  closeDb(db);
20403
20574
  }
@@ -20418,6 +20589,7 @@ var ctxBatchSchema = external_exports.object({
20418
20589
  }, { error: unknownField }).strict();
20419
20590
  var TOOL = "ctx_batch";
20420
20591
  var LABEL_PREFIX = TOOL + ":";
20592
+ var LABEL_SEP = ":";
20421
20593
  var SHELL = "shell";
20422
20594
  var SHELL_INLINE_FLAG = "-c";
20423
20595
  var MARKER = "$ ";
@@ -20485,6 +20657,7 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20485
20657
  const display = shown(chunks, ran.map((r) => r.head));
20486
20658
  const bodies = /* @__PURE__ */ new Map();
20487
20659
  const raw = /* @__PURE__ */ new Map();
20660
+ const ids = [];
20488
20661
  let total = 0;
20489
20662
  for (const c of chunks) total += c.bytes;
20490
20663
  let indexed = 0;
@@ -20505,6 +20678,7 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20505
20678
  chunkCount: group.length,
20506
20679
  createdAt: Date.now()
20507
20680
  }, group);
20681
+ ids.push(id2);
20508
20682
  for (const c of group) {
20509
20683
  bodies.set(chunkKey(id2, c.ord), display[c.ord]);
20510
20684
  raw.set(chunkKey(id2, c.ord), c.text);
@@ -20517,25 +20691,25 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20517
20691
  for (const c of chunks) {
20518
20692
  if (queued + c.bytes > budgetBytes) {
20519
20693
  const stop2 = flush() ? "budget" : "deadline";
20520
- return { bodies, raw, indexed, total, stop: stop2 };
20694
+ return { bodies, raw, ids, indexed, total, stop: stop2 };
20521
20695
  }
20522
- if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, indexed, total, stop: "deadline" };
20696
+ if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, ids, indexed, total, stop: "deadline" };
20523
20697
  group.push(c);
20524
20698
  groupBytes += c.bytes;
20525
20699
  queued += c.bytes;
20526
20700
  }
20527
20701
  const stop = flush() ? null : "deadline";
20528
- return { bodies, raw, indexed, total, stop };
20702
+ return { bodies, raw, ids, indexed, total, stop };
20529
20703
  }
20530
20704
  function bytes3(s) {
20531
20705
  return Buffer.byteLength(s, "utf8");
20532
20706
  }
20533
- function answer(db, ctx, label2, queries, share, own2) {
20707
+ function answer(db, ctx, ownIds, queries, share, own2) {
20534
20708
  const seen = /* @__PURE__ */ new Set();
20535
20709
  const lines = [];
20536
20710
  for (const [qi, q] of queries.entries()) {
20537
20711
  if (ctx.signal.aborted) break;
20538
- let hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, label2);
20712
+ let hits = ownIds.length === 0 ? [] : ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, void 0, ownIds);
20539
20713
  if (hits.length === 0) hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0);
20540
20714
  const head = "## " + (bytes3(q) > ECHO_MAX_BYTES ? "query " + (qi + 1) : q);
20541
20715
  let used = bytes3(head) + 1;
@@ -20574,9 +20748,10 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20574
20748
  const ran = pool.results;
20575
20749
  const last2 = ran[ran.length - 1];
20576
20750
  const sandboxBytes = ran.reduce((n, r) => n + r.bytes, 0);
20577
- const label2 = LABEL_PREFIX + ctx.turn;
20578
20751
  try {
20579
20752
  const db = await openDb(ctx.project);
20753
+ const turnPrefix = LABEL_PREFIX + ctx.turn + LABEL_SEP;
20754
+ const label2 = turnPrefix + nextLabelSerial(db, ctx.sessionId, turnPrefix);
20580
20755
  let sections;
20581
20756
  let idx;
20582
20757
  const exitLine = last2.exitCode === null || last2.exitCode === 0 ? null : "exit " + last2.exitCode;
@@ -20592,7 +20767,7 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20592
20767
  notice = cut === null ? stop : cause === null ? cut : cause + " " + cut;
20593
20768
  const fixed = (exitLine === null ? 0 : bytes3(exitLine) + 1) + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
20594
20769
  const share = Math.floor((OUTPUT_CAP - fixed) / queries.length);
20595
- const answered = answer(db, ctx, label2, queries, share, idx.bodies);
20770
+ const answered = answer(db, ctx, idx.ids, queries, share, idx.bodies);
20596
20771
  sections = answered.lines;
20597
20772
  const unseen = [...idx.bodies].filter(([k, text]) => text !== "" && !answered.seen.has(k)).map(([k]) => idx.raw.get(k));
20598
20773
  const unseenBytes = unseen.reduce((n, t) => n + bytes3(t) + 1, 0);
@@ -20628,15 +20803,15 @@ var ctxBatch = Object.freeze({
20628
20803
  });
20629
20804
 
20630
20805
  // src/core/tools/doctor.ts
20631
- import { readdirSync as readdirSync5, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20632
- import { basename as basename4, dirname as dirname7, join as join15 } from "node:path";
20806
+ import { readdirSync as readdirSync6, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20807
+ import { basename as basename5, dirname as dirname8, join as join16 } from "node:path";
20633
20808
 
20634
20809
  // src/core/ops/doctor-config.ts
20635
- import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
20810
+ import { existsSync as existsSync6, readdirSync as readdirSync4 } from "node:fs";
20636
20811
  import { join as join11 } from "node:path";
20637
20812
 
20638
20813
  // src/core/ops/detect-v1.ts
20639
- import { existsSync as existsSync4, opendirSync, readdirSync, readFileSync as readFileSync7 } from "node:fs";
20814
+ import { existsSync as existsSync4, opendirSync, readdirSync as readdirSync2, readFileSync as readFileSync7 } from "node:fs";
20640
20815
  import { tmpdir } from "node:os";
20641
20816
  import { join as join9 } from "node:path";
20642
20817
 
@@ -21630,9 +21805,9 @@ var Tokenizer = class {
21630
21805
  cp = this.nextCode();
21631
21806
  }
21632
21807
  const { out } = this.parseDigits(cp, isDigit4);
21633
- const right = out;
21634
- if (minus) right.unshift(CodePoint.DASH);
21635
- const value = Number(leftMinus ? String.fromCodePoint(CodePoint.DASH, ...left, CodePoint.LATIN_SMALL_E, ...right) : String.fromCodePoint(...left, CodePoint.LATIN_SMALL_E, ...right));
21808
+ const right2 = out;
21809
+ if (minus) right2.unshift(CodePoint.DASH);
21810
+ const value = Number(leftMinus ? String.fromCodePoint(CodePoint.DASH, ...left, CodePoint.LATIN_SMALL_E, ...right2) : String.fromCodePoint(...left, CodePoint.LATIN_SMALL_E, ...right2));
21636
21811
  this.endToken("Float", "start", value);
21637
21812
  return this.back("DATA");
21638
21813
  }
@@ -23356,7 +23531,7 @@ function scanVscode(agentHome, project, out) {
23356
23531
  }
23357
23532
  function jsonFiles(dir) {
23358
23533
  try {
23359
- return readdirSync(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
23534
+ return readdirSync2(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
23360
23535
  } catch {
23361
23536
  return [];
23362
23537
  }
@@ -23482,7 +23657,7 @@ function detectV1(agent, home, scope = {}) {
23482
23657
  }
23483
23658
 
23484
23659
  // src/core/ops/plugin-root.ts
23485
- import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23660
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23486
23661
  import { dirname as dirname6, isAbsolute as isAbsolute2, join as join10, sep as sep3 } from "node:path";
23487
23662
  import { fileURLToPath } from "node:url";
23488
23663
  function missing(agent, path7) {
@@ -23582,7 +23757,7 @@ function marketplaceRoot(adapter, env, worktree) {
23582
23757
  if (ownReal !== null && cacheReal !== null && ownReal.startsWith(cacheReal + sep3) && existsSync5(join10(ownReal, SERVER_ENTRY_FILE))) return ownReal;
23583
23758
  const pattern = join10(cache, "*", PLUGIN_NAME);
23584
23759
  if (!existsSync5(cache)) throw missing(adapter.id, pattern);
23585
- const found = readdirSync2(cache).sort().map((marketplace) => join10(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync5(dir));
23760
+ const found = readdirSync3(cache).sort().map((marketplace) => join10(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync5(dir));
23586
23761
  if (found.length !== 1) throw missing(adapter.id, found.length === 0 ? pattern : found.join(", "));
23587
23762
  return found[0];
23588
23763
  }
@@ -23725,10 +23900,10 @@ function codexNativeDir(env, home) {
23725
23900
  const cache = join11(codexDir, "plugins", PLUGIN_CACHE_DIR_NAME);
23726
23901
  if (!existsSync6(cache)) return null;
23727
23902
  const found = [];
23728
- for (const market of readdirSync3(cache)) {
23903
+ for (const market of readdirSync4(cache)) {
23729
23904
  const plugin = join11(cache, market, SERVER_KEY);
23730
23905
  if (!existsSync6(plugin)) continue;
23731
- for (const version2 of readdirSync3(plugin).sort()) {
23906
+ for (const version2 of readdirSync4(plugin).sort()) {
23732
23907
  const dir = join11(plugin, version2, CODEX_PLUGIN_SUBDIR);
23733
23908
  if (existsSync6(join11(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
23734
23909
  }
@@ -23813,7 +23988,7 @@ function checkHostConfig(row5, env, worktree) {
23813
23988
  const read3 = row5.id === "pi" ? mcpFile(row5, home, env) : null;
23814
23989
  if (parts.length === 0) return read3 === null ? pass("D3") : { ...pass("D3"), detail: read3 };
23815
23990
  const detail = D3_DETAIL(parts);
23816
- const fix = parts.includes(PART_MCP) && parts.includes(PART_HOOKS) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
23991
+ const fix = parts.includes(PART_MCP) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
23817
23992
  return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, fix);
23818
23993
  }
23819
23994
  function checkV1Leftovers(agent, home, scope = {}) {
@@ -23867,7 +24042,7 @@ function configPaths(row5, env, worktree) {
23867
24042
  }
23868
24043
 
23869
24044
  // src/core/ops/doctor-db.ts
23870
- import { existsSync as existsSync7 } from "node:fs";
24045
+ import { existsSync as existsSync7, statSync as statSync5 } from "node:fs";
23871
24046
  var unknown2 = (id2, detail) => ({ id: id2, label: DOCTOR_LABEL[id2], status: "UNKNOWN", detail });
23872
24047
  var pass2 = (id2, detail) => ({ id: id2, label: DOCTOR_LABEL[id2], status: "PASS", detail });
23873
24048
  var fail3 = (detail, fixCommand) => ({ id: "D8", label: DOCTOR_LABEL.D8, status: "FAIL", detail, fixCommand });
@@ -23905,8 +24080,18 @@ function failsOnCorrupt(step) {
23905
24080
  throw err;
23906
24081
  }
23907
24082
  }
24083
+ function orphanFiles(dbPath) {
24084
+ const files = [];
24085
+ for (const suffix of [DB_WAL_SUFFIX, DB_SHM_SUFFIX]) {
24086
+ const path7 = dbPath + suffix;
24087
+ if (existsSync7(path7)) files.push({ path: path7, bytes: statSync5(path7).size });
24088
+ }
24089
+ return files.length > 0 && !existsSync7(dbPath) ? files : [];
24090
+ }
23908
24091
  async function checkDb(project) {
23909
- const clean = { schemaStale: false, integrityFailed: false };
24092
+ const clean = { schemaStale: false, integrityFailed: false, orphan: [] };
24093
+ const orphan = orphanFiles(project.dbPath);
24094
+ if (orphan.length > 0) return { row: fail3(D8_ORPHAN_DETAIL(orphan), D8_ORPHAN_FIX), schemaStale: false, integrityFailed: false, orphan };
23910
24095
  if (!existsSync7(project.dbPath)) return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
23911
24096
  const sqlite = await loadSqlite2();
23912
24097
  if (sqlite === null) return { row: unknown2("D8", D2_SQLITE_DETAIL), ...clean };
@@ -23922,11 +24107,11 @@ async function checkDb(project) {
23922
24107
  }
23923
24108
  const schemaStale = got !== null && got !== SCHEMA_VERSION;
23924
24109
  const integrityFailed = failsOnCorrupt(() => !integrityOk(db));
23925
- if (integrityFailed) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale, integrityFailed };
23926
- if (schemaStale && got !== null) return { row: fail3(D8_STALE_SCHEMA_DETAIL(got, SCHEMA_VERSION), DOCTOR_FIX_UPGRADE), schemaStale, integrityFailed };
24110
+ if (integrityFailed) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale, integrityFailed, orphan: [] };
24111
+ if (schemaStale && got !== null) return { row: fail3(D8_STALE_SCHEMA_DETAIL(got, SCHEMA_VERSION), DOCTOR_FIX_UPGRADE), schemaStale, integrityFailed, orphan: [] };
23927
24112
  return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
23928
24113
  } catch (err) {
23929
- if (isCorrupt2(err)) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true };
24114
+ if (isCorrupt2(err)) return { row: fail3(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true, orphan: [] };
23930
24115
  return { row: unknown2("D8", message2(err)), ...clean };
23931
24116
  } finally {
23932
24117
  raw?.close();
@@ -23994,7 +24179,8 @@ function fetchCause(err, timeoutMs) {
23994
24179
  const cause = err instanceof Error && err.cause instanceof Error ? err.cause : err;
23995
24180
  const code = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : "";
23996
24181
  const msg = cause instanceof Error ? cause.message : String(cause);
23997
- return D1_NPM_ERROR(code !== "" && !msg.includes(code) ? `${code} ${msg}` : msg);
24182
+ const parts = code !== "" && !msg.includes(code) ? [code, msg] : [msg];
24183
+ return D1_NPM_ERROR(parts.filter((part) => part !== "").join(" "));
23998
24184
  }
23999
24185
  async function npmLatest(url2, tag2, signal, timeoutMs) {
24000
24186
  try {
@@ -24107,9 +24293,9 @@ async function checkNode(i) {
24107
24293
  return pass3("D2", bun.length === 0 ? DOCTOR_PASS_DETAIL : bun.join(D4_REASON_JOIN));
24108
24294
  }
24109
24295
  function checkMcp(ctx) {
24110
- const named = ctx.clientInfo !== void 0 && ctx.clientInfo.name !== "";
24296
+ const named2 = ctx.clientInfo !== void 0 && ctx.clientInfo.name !== "";
24111
24297
  const versioned = ctx.protocolVersion !== void 0 && ctx.protocolVersion !== "";
24112
- return named || versioned ? pass3("D6") : unknown3("D6", D6_UNKNOWN_DETAIL);
24298
+ return named2 || versioned ? pass3("D6") : unknown3("D6", D6_UNKNOWN_DETAIL);
24113
24299
  }
24114
24300
  function piCwdInside(worktree, piCwd) {
24115
24301
  if (piCwd === void 0 || !existsSync8(piCwd)) return false;
@@ -24144,7 +24330,7 @@ import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
24144
24330
 
24145
24331
  // src/setup/spawn-bin.ts
24146
24332
  import { spawnSync } from "node:child_process";
24147
- import { accessSync as accessSync2, constants as fsc, statSync as statSync5 } from "node:fs";
24333
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync6 } from "node:fs";
24148
24334
  import path4 from "node:path";
24149
24335
  var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
24150
24336
  var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
@@ -24162,7 +24348,7 @@ function whichBin(bin, env, platform = process.platform) {
24162
24348
  const f = path4.join(dir, n);
24163
24349
  try {
24164
24350
  accessSync2(f, fsc.X_OK);
24165
- if (statSync5(f).isFile()) return f;
24351
+ if (statSync6(f).isFile()) return f;
24166
24352
  } catch {
24167
24353
  }
24168
24354
  }
@@ -24370,19 +24556,52 @@ function loadFixture(bundleDir2, agent) {
24370
24556
  }
24371
24557
  return { event: e.event, payload: e.payload };
24372
24558
  }
24373
- function payloadFor(payload, worktree) {
24374
- return worktree !== void 0 && isObject5(payload) ? { ...payload, cwd: worktree } : payload;
24375
- }
24376
- function isNativeShape(stdout, exitCode, killed, event) {
24559
+ var CWD_KEY = {
24560
+ "claude-code": "cwd",
24561
+ codex: "cwd",
24562
+ gemini: "cwd",
24563
+ qwen: "cwd",
24564
+ "copilot-cli": "cwd",
24565
+ vscode: "cwd",
24566
+ kiro: "cwd",
24567
+ zcode: "cwd",
24568
+ pi: "cwd",
24569
+ opencode: "directory"
24570
+ };
24571
+ function payloadFor(agent, payload, worktree) {
24572
+ return worktree !== void 0 && isObject5(payload) ? { ...payload, [CWD_KEY[agent]]: worktree } : payload;
24573
+ }
24574
+ var SHAPE = {
24575
+ "claude-code": "claude",
24576
+ codex: "claude",
24577
+ qwen: "claude",
24578
+ vscode: "claude",
24579
+ zcode: "claude",
24580
+ gemini: "gemini",
24581
+ "copilot-cli": "copilot",
24582
+ kiro: "text",
24583
+ pi: "text",
24584
+ opencode: "text"
24585
+ };
24586
+ var COPILOT_KEYS = ["permissionDecision", "additionalContext", "modifiedResult"];
24587
+ function isNativeShape(agent, stdout, exitCode, killed, event) {
24377
24588
  if (killed !== null || exitCode !== 0 && exitCode !== 2) return false;
24378
- if (stdout.length === 0) return true;
24589
+ if (stdout.length === 0 || SHAPE[agent] === "text") return true;
24379
24590
  let out;
24380
24591
  try {
24381
24592
  out = JSON.parse(stdout);
24382
24593
  } catch {
24383
24594
  return false;
24384
24595
  }
24385
- return isObject5(out) && isObject5(out.hookSpecificOutput) && out.hookSpecificOutput.hookEventName === event;
24596
+ if (!isObject5(out)) return false;
24597
+ switch (SHAPE[agent]) {
24598
+ case "claude":
24599
+ return isObject5(out.hookSpecificOutput) && out.hookSpecificOutput.hookEventName === event;
24600
+ case "gemini":
24601
+ return typeof out.decision === "string" || isObject5(out.hookSpecificOutput);
24602
+ default:
24603
+ return COPILOT_KEYS.some((k) => Object.hasOwn(out, k));
24604
+ }
24386
24605
  }
24387
24606
  function codexHookJournaled(db) {
24388
24607
  if (db === null) return false;
@@ -24426,9 +24645,10 @@ async function checkHookRoundTrip(i) {
24426
24645
  const fixed = i.samples === void 0 ? null : Math.max(1, i.samples);
24427
24646
  const maxPairs = fixed ?? D5_MAX_PAIRS;
24428
24647
  const minPairs = fixed ?? D5_MIN_PAIRS;
24648
+ const timeoutMs = i.timeoutMs ?? HOOK_TIMEOUT_MS;
24429
24649
  const bareMs = i.bareMs ?? (async () => {
24430
24650
  const t = performance.now();
24431
- await runProcess([process.execPath, "-e", ""], { cwd: i.bundleDir, env: i.env, signal: i.signal, timeoutMs: HOOK_TIMEOUT_MS });
24651
+ await runProcess([process.execPath, "-e", ""], { cwd: i.bundleDir, env: i.env, signal: i.signal, timeoutMs });
24432
24652
  return performance.now() - t;
24433
24653
  });
24434
24654
  const hookWalls = [];
@@ -24440,11 +24660,11 @@ async function checkHookRoundTrip(i) {
24440
24660
  cwd: i.bundleDir,
24441
24661
  env: i.env,
24442
24662
  signal: i.signal,
24443
- timeoutMs: HOOK_TIMEOUT_MS,
24444
- stdin: JSON.stringify(payloadFor(fixture.payload, i.worktree))
24663
+ timeoutMs,
24664
+ stdin: JSON.stringify(payloadFor(i.agent, fixture.payload, i.worktree))
24445
24665
  });
24446
24666
  hookWalls.push(now() - start);
24447
- if (!isNativeShape(r.stdout.toString("utf8"), r.exitCode, r.killed, fixture.event)) return row("FAIL", D5_SHAPE_DETAIL, D5_FIX);
24667
+ if (!isNativeShape(i.agent, r.stdout.toString("utf8"), r.exitCode, r.killed, fixture.event)) return row("FAIL", D5_SHAPE_DETAIL, D5_FIX);
24448
24668
  bareWalls.push(await bareMs());
24449
24669
  ms = Math.max(0, Math.round(Math.min(...hookWalls) - Math.min(...bareWalls)));
24450
24670
  if (n >= minPairs && ms <= HOOK_P95_MS) break;
@@ -24454,10 +24674,11 @@ async function checkHookRoundTrip(i) {
24454
24674
  }
24455
24675
 
24456
24676
  // src/core/ops/db-heal.ts
24457
- import { existsSync as existsSync11, rmSync as rmSync3 } from "node:fs";
24677
+ import { existsSync as existsSync11, mkdirSync as mkdirSync5, rmSync as rmSync3 } from "node:fs";
24678
+ import { basename as basename4, dirname as dirname7, join as join14 } from "node:path";
24458
24679
 
24459
24680
  // src/core/store/owners.ts
24460
- import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24681
+ import { mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24461
24682
  import { basename as basename3, join as join13 } from "node:path";
24462
24683
  function ownersDir(configDir, projectKey) {
24463
24684
  return join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
@@ -24480,7 +24701,7 @@ function listLiveOwners(configDir, projectKey) {
24480
24701
  const dir = ownersDir(configDir, projectKey);
24481
24702
  let names;
24482
24703
  try {
24483
- names = readdirSync4(dir);
24704
+ names = readdirSync5(dir);
24484
24705
  } catch (err) {
24485
24706
  if (errCode2(err) === "ENOENT") return [];
24486
24707
  throw err;
@@ -24556,6 +24777,39 @@ async function healD8(input) {
24556
24777
  closeDb(await openDb(project));
24557
24778
  return { ...row5, status: "FAIL", detail: D8_HEALED_RECREATE_DETAIL(ts) };
24558
24779
  }
24780
+ function utcStamp(now) {
24781
+ return now.toISOString().slice(0, 19).replaceAll("-", "").replaceAll(":", "") + "Z";
24782
+ }
24783
+ function makeOrphanDir(projectDir) {
24784
+ const base = join14(projectDir, ORPHAN_DIR_PREFIX + utcStamp(/* @__PURE__ */ new Date()));
24785
+ for (let n = 1; ; n += 1) {
24786
+ const dir = n === 1 ? base : base + "-" + String(n);
24787
+ try {
24788
+ mkdirSync5(dir);
24789
+ return dir;
24790
+ } catch (err) {
24791
+ if (err.code !== "EEXIST") throw err;
24792
+ }
24793
+ }
24794
+ }
24795
+ async function healOrphan(project, files, row5) {
24796
+ const moved = [];
24797
+ let dir = "";
24798
+ try {
24799
+ dir = makeOrphanDir(dirname7(project.dbPath));
24800
+ for (const f of files) {
24801
+ const to = join14(dir, basename4(f.path));
24802
+ renameWithRetry(f.path, to);
24803
+ moved.push({ path: to, bytes: f.bytes });
24804
+ }
24805
+ closeDb(await openDb(project));
24806
+ } catch (err) {
24807
+ const cause = err instanceof CtxError ? err.toLine() : err instanceof Error ? err.message : String(err);
24808
+ const at2 = moved.length > 0 ? D8_ORPHAN_HEALED_DETAIL(dir, moved, project.dbPath) : row5.detail;
24809
+ return { ...row5, detail: D8_ORPHAN_MOVE_FAILED(at2, cause) };
24810
+ }
24811
+ return { ...row5, status: "FAIL", detail: D8_ORPHAN_HEALED_DETAIL(dir, moved, project.dbPath), fixCommand: D8_ORPHAN_HEALED_FIX };
24812
+ }
24559
24813
 
24560
24814
  // src/core/ops/report.ts
24561
24815
  function keyIsTyped(key) {
@@ -24611,8 +24865,8 @@ function buildReportHead(input) {
24611
24865
 
24612
24866
  // src/core/ops/doctor-issue.ts
24613
24867
  import { spawnSync as spawnSync3 } from "node:child_process";
24614
- import { closeSync, existsSync as existsSync12, fstatSync, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
24615
- import { delimiter, join as join14 } from "node:path";
24868
+ import { closeSync, existsSync as existsSync12, fstatSync, mkdirSync as mkdirSync6, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
24869
+ import { delimiter, join as join15 } from "node:path";
24616
24870
  var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
24617
24871
  function tildeOf(env) {
24618
24872
  const home = homeDirOf(env);
@@ -24629,9 +24883,9 @@ function tildeOf(env) {
24629
24883
  }
24630
24884
  function maskLine(line) {
24631
24885
  const lower = line.toLowerCase();
24632
- const named = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
24886
+ const named2 = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
24633
24887
  const token = TOKEN_PREFIXES.some((p) => line.includes(p));
24634
- if (!named && !token) return line;
24888
+ if (!named2 && !token) return line;
24635
24889
  const at2 = Math.max(line.indexOf(":"), line.indexOf("="));
24636
24890
  return at2 === -1 ? DOCTOR_MASK : line.slice(0, at2 + 1) + " " + DOCTOR_MASK;
24637
24891
  }
@@ -24653,8 +24907,8 @@ function onPath(env, tool) {
24653
24907
  const out = [];
24654
24908
  for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
24655
24909
  if (dir === "") continue;
24656
- for (const n of names) if (existsSync12(join14(dir, n))) {
24657
- out.push(join14(dir, n));
24910
+ for (const n of names) if (existsSync12(join15(dir, n))) {
24911
+ out.push(join15(dir, n));
24658
24912
  break;
24659
24913
  }
24660
24914
  }
@@ -24700,8 +24954,8 @@ function agentConfig(adapter, env, worktree) {
24700
24954
  const home = homeDirOf(env);
24701
24955
  const files = configPaths(adapter, env, worktree);
24702
24956
  if (home !== null) {
24703
- if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join14(claudeDirOf(env, home), SETTINGS_FILE) });
24704
- if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join14(codexDirOf(env, home), CONFIG_TOML_FILE) });
24957
+ if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join15(claudeDirOf(env, home), SETTINGS_FILE) });
24958
+ if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join15(codexDirOf(env, home), CONFIG_TOML_FILE) });
24705
24959
  }
24706
24960
  const out = [];
24707
24961
  const seen = /* @__PURE__ */ new Set();
@@ -24784,9 +25038,9 @@ async function buildIssueBody(i) {
24784
25038
  async function writeIssueReport(i) {
24785
25039
  const tilde = tildeOf(i.env);
24786
25040
  const body = await buildIssueBody(i);
24787
- const dir = join14(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
24788
- mkdirSync5(dir, { recursive: true });
24789
- const file2 = join14(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
25041
+ const dir = join15(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
25042
+ mkdirSync6(dir, { recursive: true });
25043
+ const file2 = join15(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
24790
25044
  writeFileSync3(file2, body);
24791
25045
  const shown2 = tilde(file2);
24792
25046
  const title = issueTitle(i.adapter.id, i.rows);
@@ -24843,11 +25097,11 @@ async function hookRow(ctx, adapter, host) {
24843
25097
  }
24844
25098
  }
24845
25099
  function ownServerId(configDir, projectKey) {
24846
- const dir = join15(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
25100
+ const dir = join16(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24847
25101
  if (!existsSync13(dir)) return "";
24848
- for (const name of readdirSync5(dir)) {
25102
+ for (const name of readdirSync6(dir)) {
24849
25103
  if (!name.endsWith(OWNER_PID_EXT)) continue;
24850
- if (readFileSync13(join15(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
25104
+ if (readFileSync13(join16(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
24851
25105
  }
24852
25106
  return "";
24853
25107
  }
@@ -24856,6 +25110,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
24856
25110
  const env = host.env;
24857
25111
  const project = ctx.project;
24858
25112
  let integrityFailed = false;
25113
+ let orphan = [];
24859
25114
  const checks = {
24860
25115
  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 }),
24861
25116
  D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
@@ -24868,6 +25123,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
24868
25123
  D8: async () => {
24869
25124
  const r = await checkDb(project);
24870
25125
  integrityFailed = r.integrityFailed;
25126
+ orphan = r.orphan;
24871
25127
  return r.row;
24872
25128
  },
24873
25129
  D9: () => checkIndex(project),
@@ -24876,8 +25132,13 @@ async function runDoctorChecks(ctx, adapter, host0) {
24876
25132
  };
24877
25133
  const rows = [];
24878
25134
  for (const id2 of DOCTOR_CHECK_ORDER) rows.push(await guard(id2, checks[id2]));
24879
- if (!integrityFailed) return rows;
24880
25135
  const at2 = DOCTOR_CHECK_ORDER.indexOf("D8");
25136
+ if (orphan.length > 0) {
25137
+ const files = orphan;
25138
+ rows[at2] = await guard("D8", () => healOrphan(project, files, rows[at2]));
25139
+ return rows;
25140
+ }
25141
+ if (!integrityFailed) return rows;
24881
25142
  rows[at2] = await guard("D8", () => {
24882
25143
  const configDir = resolveConfigDir(env);
24883
25144
  return healD8({ project, configDir, serverId: ownServerId(configDir, project.projectKey), row: rows[at2] });
@@ -24923,7 +25184,7 @@ async function doctorReply(ctx, host) {
24923
25184
  return { text, isError: false, sandboxBytes: bytes5 };
24924
25185
  }
24925
25186
  async function handler2(_input, ctx) {
24926
- return doctorReply(ctx, { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 });
25187
+ return doctorReply(ctx, { env: process.env, bundleDir: dirname8(process.argv[1]), piCwd: void 0 });
24927
25188
  }
24928
25189
  var ctxDoctor = Object.freeze({
24929
25190
  name: "ctx_doctor",
@@ -24937,7 +25198,7 @@ var ctxDoctor = Object.freeze({
24937
25198
  // src/core/tools/execute.ts
24938
25199
  import { existsSync as existsSync14, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "node:fs";
24939
25200
  import { tmpdir as tmpdir2 } from "node:os";
24940
- import { dirname as dirname8, join as join16, parse as parse3, resolve as resolve6 } from "node:path";
25201
+ import { dirname as dirname9, join as join17, parse as parse3, resolve as resolve6 } from "node:path";
24941
25202
 
24942
25203
  // src/core/sandbox/win-build.ts
24943
25204
  var SEPARATORS2 = ";&|(\n";
@@ -25021,7 +25282,7 @@ function schemaLine(issue2) {
25021
25282
  }
25022
25283
  function fileError(given, abs, root) {
25023
25284
  let dir = abs;
25024
- while (!existsSync14(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
25285
+ while (!existsSync14(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
25025
25286
  if (isInside(root, dir)) return null;
25026
25287
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
25027
25288
  }
@@ -25102,8 +25363,8 @@ async function handler3(raw, ctx) {
25102
25363
  if (takesDashC(input.language, runtime)) {
25103
25364
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
25104
25365
  } else {
25105
- tmpDir = mkdtempSync(join16(tmpdir2(), TMP_PREFIX));
25106
- const file2 = join16(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
25366
+ tmpDir = mkdtempSync(join17(tmpdir2(), TMP_PREFIX));
25367
+ const file2 = join17(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
25107
25368
  writeFileSync4(file2, scriptText(input.language, input.code), "utf8");
25108
25369
  argv = scriptArgv(input.language, runtime, file2);
25109
25370
  }
@@ -25138,12 +25399,12 @@ var ctxExecute = {
25138
25399
  };
25139
25400
 
25140
25401
  // src/core/tools/index.ts
25141
- import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as statSync7 } from "node:fs";
25142
- import { dirname as dirname9, extname, join as join18, relative as relative3, resolve as resolve7 } from "node:path";
25402
+ import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as statSync8 } from "node:fs";
25403
+ import { dirname as dirname10, extname, join as join19, relative as relative3, resolve as resolve7 } from "node:path";
25143
25404
 
25144
25405
  // src/core/index/walk.ts
25145
- import { readdirSync as readdirSync6, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync6 } from "node:fs";
25146
- import { join as join17 } from "node:path";
25406
+ import { readdirSync as readdirSync7, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync7 } from "node:fs";
25407
+ import { join as join18 } from "node:path";
25147
25408
  var GITIGNORE = ".gitignore";
25148
25409
  var GIT_DIR = ".git";
25149
25410
  function walkDir(root, containmentRoot) {
@@ -25152,19 +25413,19 @@ function walkDir(root, containmentRoot) {
25152
25413
  const found = [];
25153
25414
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
25154
25415
  found.sort(compareFound);
25155
- return found.map((f) => ({ absPath: f.absPath, relPath: join17(...f.dir, f.name) }));
25416
+ return found.map((f) => ({ absPath: f.absPath, relPath: join18(...f.dir, f.name) }));
25156
25417
  }
25157
25418
  function visit(abs, rel, parent, contain, seen, found) {
25158
25419
  let entries;
25159
25420
  try {
25160
- entries = readdirSync6(abs, { withFileTypes: true });
25421
+ entries = readdirSync7(abs, { withFileTypes: true });
25161
25422
  } catch {
25162
25423
  return;
25163
25424
  }
25164
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join17(abs, GITIGNORE), rel)) : parent;
25425
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join18(abs, GITIGNORE), rel)) : parent;
25165
25426
  for (const e of entries) {
25166
25427
  if (e.name === GIT_DIR) continue;
25167
- const path7 = join17(abs, e.name);
25428
+ const path7 = join18(abs, e.name);
25168
25429
  let isDir = e.isDirectory();
25169
25430
  let isFile = e.isFile();
25170
25431
  let target = path7;
@@ -25176,7 +25437,7 @@ function visit(abs, rel, parent, contain, seen, found) {
25176
25437
  continue;
25177
25438
  }
25178
25439
  if (!isInside(contain, resolved)) continue;
25179
- const st = statSync6(resolved);
25440
+ const st = statSync7(resolved);
25180
25441
  isDir = st.isDirectory();
25181
25442
  isFile = st.isFile();
25182
25443
  target = resolved;
@@ -29294,7 +29555,7 @@ function readUtf8(absPath) {
29294
29555
  }
29295
29556
  function missingOrOutside(given, abs, root) {
29296
29557
  let dir = abs;
29297
- while (!existsSync15(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
29558
+ while (!existsSync15(dir) && dirname10(dir) !== dir) dir = dirname10(dir);
29298
29559
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
29299
29560
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
29300
29561
  }
@@ -29302,10 +29563,10 @@ function pathItems(input, project) {
29302
29563
  const abs = resolve7(project.worktree, input.path);
29303
29564
  if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
29304
29565
  const base = relative3(project.worktree, abs);
29305
- if (statSync7(abs).isDirectory()) {
29566
+ if (statSync8(abs).isDirectory()) {
29306
29567
  return walkDir(abs, project.containmentRoot).map((f) => ({
29307
29568
  sourceKind: "path",
29308
- label: pathLabel(join18(base, f.relPath)),
29569
+ label: pathLabel(join19(base, f.relPath)),
29309
29570
  kind: kindOfPath(f.relPath),
29310
29571
  read: () => readUtf8(f.absPath)
29311
29572
  }));
@@ -29377,8 +29638,9 @@ async function handler4(input, ctx) {
29377
29638
  } finally {
29378
29639
  closeDb(db);
29379
29640
  }
29380
- const shown2 = Buffer.byteLength(from, "utf8") > ECHO_MAX_BYTES ? sourceHandle(lastId) : from;
29381
- const line = ["Indexed " + sources + " source(s), " + chunks + " chunk(s) from " + shown2 + ".", ...notes].join("\n");
29641
+ const head = "Indexed " + sources + " source(s), " + chunks + " chunk(s) from ";
29642
+ const first = sources === 1 && lastId > 0 ? head + sourceHandle(lastId) + ". " + indexedLabelLine(from, lastId) : head + shownLabel(from, null) + ".";
29643
+ const line = [first, ...notes].join("\n");
29382
29644
  return {
29383
29645
  text: capBytes(line, OUTPUT_CAP).text,
29384
29646
  isError: false,
@@ -29422,7 +29684,7 @@ function purgeScope(db, scope, input) {
29422
29684
  const raw = db.raw;
29423
29685
  if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
29424
29686
  if (scope === "source") {
29425
- const label2 = storedLabel(db, input.source);
29687
+ const label2 = pickSource(db, input.source, false).label;
29426
29688
  return deleteChunkRows(raw, { label: label2 }) + changes(raw, "DELETE FROM sources WHERE label = ?", label2);
29427
29689
  }
29428
29690
  const chunks = deleteChunkRows(raw, "all");
@@ -29621,6 +29883,9 @@ function bytes4(n) {
29621
29883
  }
29622
29884
  return v.toFixed(1) + " " + UNITS[u];
29623
29885
  }
29886
+ function right(v, width) {
29887
+ return " " + v.padStart(width - 1);
29888
+ }
29624
29889
  function pct(t) {
29625
29890
  return (t.saved * PERCENT_SCALE / Math.max(1, t.produced)).toFixed(1) + "%";
29626
29891
  }
@@ -29644,8 +29909,8 @@ function plural(n, word) {
29644
29909
  }
29645
29910
  function table2(title, rows) {
29646
29911
  const max = Math.max(0, ...rows.map((r) => r.saved));
29647
- const head = " " + title.padEnd(LABEL_W) + "Calls".padStart(STATS_CALLS_W) + "Made".padStart(NUM_W) + "Sent".padStart(NUM_W) + "Kept out".padStart(NUM_W) + "%".padStart(PCT_W);
29648
- return [head, ...rows.map((r) => (" " + label(r.name) + count(r.calls).padStart(STATS_CALLS_W) + bytes4(r.produced).padStart(NUM_W) + bytes4(r.returned).padStart(NUM_W) + bytes4(r.saved).padStart(NUM_W) + pct(r).padStart(PCT_W) + " " + bar(r.saved, max, STATS_ROW_BAR)).trimEnd())];
29912
+ 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);
29913
+ 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())];
29649
29914
  }
29650
29915
  function bySaved(a, b) {
29651
29916
  return b.saved - a.saved || b.produced - a.produced || a.returned - b.returned || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
@@ -29657,14 +29922,14 @@ function joinIndex(tools) {
29657
29922
  const idx = tools.filter((t2) => STATS_INDEX_TOOLS.includes(t2.name));
29658
29923
  if (idx.length <= 1) return tools;
29659
29924
  const t = sum(idx);
29660
- const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: t.produced - t.returned };
29925
+ const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: Math.max(0, t.produced - t.returned) };
29661
29926
  return [...tools.filter((x) => !idx.includes(x)), one];
29662
29927
  }
29663
29928
  function toolRows(tools) {
29664
- const named = joinIndex(tools.map((t) => ({ ...t, saved: t.produced - t.returned }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
29665
- const zero = named.filter((t) => t.saved <= 0);
29929
+ const named2 = joinIndex(tools.map((t) => ({ ...t, saved: Math.max(0, t.produced - t.returned) }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
29930
+ const zero = named2.filter((t) => t.saved <= 0);
29666
29931
  const fold2 = zero.length > 1 ? zero : [];
29667
- const keep = named.filter((t) => !fold2.includes(t));
29932
+ const keep = named2.filter((t) => !fold2.includes(t));
29668
29933
  const room = fold2.length > 0 ? STATS_MAX_TOOL_ROWS - 1 : STATS_MAX_TOOL_ROWS;
29669
29934
  const over = keep.length > room;
29670
29935
  const shown2 = over ? keep.slice(0, STATS_MAX_TOOL_ROWS - 1) : keep;
@@ -29732,7 +29997,7 @@ function lastDays(week, allCalls) {
29732
29997
  return [
29733
29998
  head,
29734
29999
  ...card,
29735
- ...week.flatMap((d, i) => saved[i] > 0 ? [" " + mmdd(d.day) + " " + stack(STATS_WAYS.map(([w]) => d.ways[w]), max, STATS_DAY_BAR).padEnd(STATS_DAY_BAR) + bytes4(saved[i]).padStart(NUM_W)] : []),
30000
+ ...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)] : []),
29736
30001
  " " + STATS_WAYS.map(([, ch, name]) => `${ch} ${name}`).join(" "),
29737
30002
  ""
29738
30003
  ];
@@ -29760,8 +30025,8 @@ function report(f, sessionId, agent) {
29760
30025
  ...head,
29761
30026
  `${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
29762
30027
  ` ${bytes4(focus.produced)} became ${bytes4(focus.returned)}: ${bytes4(focus.saved)} kept out (${pct(focus)})`,
29763
- " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.produced).padStart(NUM_W),
29764
- " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.returned).padStart(NUM_W),
30028
+ " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + right(bytes4(focus.produced), NUM_W),
30029
+ " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + right(bytes4(focus.returned), NUM_W),
29765
30030
  ...focus.saved > 0 ? [windowLine(focus.saved), STATS_TOKEN_NOTE] : [],
29766
30031
  ...hookLine(f.redirected, f.replaced),
29767
30032
  "",
@@ -29775,7 +30040,7 @@ function report(f, sessionId, agent) {
29775
30040
  "",
29776
30041
  ...f.top.length > 0 ? [
29777
30042
  "Largest single outputs (made \u2192 sent to the chat)",
29778
- ...f.top.map((t) => " " + label(toolName(t.name)) + bytes4(t.produced).padStart(NUM_W) + " \u2192 " + bytes4(t.returned).padStart(NUM_W)),
30043
+ ...f.top.map((t) => " " + label(toolName(t.name)) + right(bytes4(t.produced), NUM_W) + " \u2192 " + right(bytes4(t.returned), NUM_W)),
29779
30044
  ""
29780
30045
  ] : []
29781
30046
  ];
@@ -29784,10 +30049,10 @@ function report(f, sessionId, agent) {
29784
30049
  if (!agents.has(agent)) agents.set(agent, EMPTY5);
29785
30050
  lines.push("By agent (this project)", ...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29786
30051
  const maxKind = Math.max(0, ...[...f.kinds.values()].map((k) => k.project));
29787
- lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + "Session".padStart(STATS_KIND_W) + "Project".padStart(STATS_KIND_W));
30052
+ lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + right("Session", STATS_KIND_W) + right("Project", STATS_KIND_W));
29788
30053
  for (const [kind, name] of STATS_KIND_LABELS) {
29789
30054
  const k = f.kinds.get(kind) ?? { session: 0, project: 0 };
29790
- 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());
30055
+ 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());
29791
30056
  }
29792
30057
  lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
29793
30058
  lines.push(
@@ -29804,7 +30069,14 @@ async function handler7(_input, ctx) {
29804
30069
  const db = await openDb(ctx.project, { readOnly: true });
29805
30070
  let facts;
29806
30071
  try {
29807
- facts = readFacts(db.raw, ctx.sessionId);
30072
+ db.raw.exec("BEGIN DEFERRED");
30073
+ try {
30074
+ facts = readFacts(db.raw, ctx.sessionId);
30075
+ db.raw.exec("COMMIT");
30076
+ } catch (err) {
30077
+ if (db.raw.isTransaction) db.raw.exec("ROLLBACK");
30078
+ throw err;
30079
+ }
29808
30080
  } finally {
29809
30081
  closeDb(db);
29810
30082
  }
@@ -29835,11 +30107,11 @@ var ctxStats = Object.freeze({
29835
30107
 
29836
30108
  // src/core/tools/upgrade.ts
29837
30109
  import { existsSync as existsSync21, realpathSync as realpathSync10, rmSync as rmSync9 } from "node:fs";
29838
- import { basename as basename6, dirname as dirname11, join as join24 } from "node:path";
30110
+ import { basename as basename7, dirname as dirname12, join as join25 } from "node:path";
29839
30111
 
29840
30112
  // src/core/ops/host-write.ts
29841
- import { copyFileSync, existsSync as existsSync16, mkdirSync as mkdirSync6, writeFileSync as writeFileSync5 } from "node:fs";
29842
- import { dirname as dirname10, join as join19 } from "node:path";
30113
+ import { copyFileSync, existsSync as existsSync16, mkdirSync as mkdirSync7, writeFileSync as writeFileSync5 } from "node:fs";
30114
+ import { dirname as dirname11, join as join20 } from "node:path";
29843
30115
  function defaultWrite(file2, text) {
29844
30116
  writeFileSync5(file2, text, "utf8");
29845
30117
  }
@@ -29848,14 +30120,14 @@ function hostConfigPath(agent, home, env) {
29848
30120
  if (own2 !== void 0) return ownMcpFileOf(agent, own2.file, env, home);
29849
30121
  switch (agent) {
29850
30122
  case "opencode":
29851
- return join19(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
30123
+ return join20(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29852
30124
  // D-WIN-OPENCODE-DIR-1
29853
30125
  case "pi":
29854
- return join19(piAgentDirOf(env, home), SETTINGS_FILE);
30126
+ return join20(piAgentDirOf(env, home), SETTINGS_FILE);
29855
30127
  case "copilot-cli":
29856
30128
  return null;
29857
30129
  default:
29858
- return join19(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
30130
+ return join20(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29859
30131
  }
29860
30132
  }
29861
30133
  function cell3(value) {
@@ -29868,7 +30140,7 @@ function writeWithRollback(file2, text, write2, atomic) {
29868
30140
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
29869
30141
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
29870
30142
  const had = existsSync16(file2);
29871
- mkdirSync6(dirname10(file2), { recursive: true });
30143
+ mkdirSync7(dirname11(file2), { recursive: true });
29872
30144
  if (had) copyFileSync(file2, trash);
29873
30145
  try {
29874
30146
  write2(tmp, text);
@@ -29905,8 +30177,8 @@ function regenerateHostConfig(row5, home, opts = {}) {
29905
30177
  }
29906
30178
 
29907
30179
  // src/core/ops/plugin-swap.ts
29908
- import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
29909
- import { basename as basename5, join as join20, win32 as win322 } from "node:path";
30180
+ import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync8, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
30181
+ import { basename as basename6, join as join21, win32 as win322 } from "node:path";
29910
30182
  function linkTarget(path7, win) {
29911
30183
  if (!isLink(path7)) return null;
29912
30184
  const target = readlinkSync(path7);
@@ -29916,7 +30188,7 @@ function isLink(path7) {
29916
30188
  return lstatSync(path7, { throwIfNoEntry: false })?.isSymbolicLink() === true;
29917
30189
  }
29918
30190
  function generations(agentDir) {
29919
- 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();
30191
+ 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();
29920
30192
  }
29921
30193
  function settleLinks(link, tmp, old, opts) {
29922
30194
  if (isLink(tmp)) unlinkSync2(tmp);
@@ -29925,11 +30197,11 @@ function settleLinks(link, tmp, old, opts) {
29925
30197
  else renameWithRetry(old, link, opts);
29926
30198
  }
29927
30199
  function swapPluginCurrent(agentDir, sha, opts = {}) {
29928
- const next = join20(agentDir, sha);
30200
+ const next = join21(agentDir, sha);
29929
30201
  if (!existsSync17(next) || !lstatSync(next).isDirectory()) {
29930
- throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
30202
+ throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename6(agentDir), path: next });
29931
30203
  }
29932
- const link = join20(agentDir, PLUGIN_CURRENT_LINK);
30204
+ const link = join21(agentDir, PLUGIN_CURRENT_LINK);
29933
30205
  const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
29934
30206
  const old = link + PLUGIN_LINK_OLD_SUFFIX;
29935
30207
  settleLinks(link, tmp, old, opts);
@@ -29944,15 +30216,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
29944
30216
  if (before !== null) unlinkSync2(old);
29945
30217
  const keep = /* @__PURE__ */ new Set([sha]);
29946
30218
  if (before !== null) keep.add(before);
29947
- const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join20(agentDir, name));
30219
+ const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join21(agentDir, name));
29948
30220
  for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
29949
- const previous = before !== null && existsSync17(join20(agentDir, before)) ? join20(agentDir, before) : null;
30221
+ const previous = before !== null && existsSync17(join21(agentDir, before)) ? join21(agentDir, before) : null;
29950
30222
  return { current: next, previous, removed };
29951
30223
  }
29952
30224
 
29953
30225
  // src/core/ops/release-fetch.ts
29954
- import { existsSync as existsSync18, mkdirSync as mkdirSync7, rmSync as rmSync6 } from "node:fs";
29955
- import { join as join21 } from "node:path";
30226
+ import { existsSync as existsSync18, mkdirSync as mkdirSync8, rmSync as rmSync6 } from "node:fs";
30227
+ import { join as join22 } from "node:path";
29956
30228
  function failed(r) {
29957
30229
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
29958
30230
  const status = r.killed ?? String(r.exitCode);
@@ -29964,9 +30236,9 @@ async function git2(bin, args, cwd, env, signal) {
29964
30236
  return r.stdout.toString().trim();
29965
30237
  }
29966
30238
  async function fetchRelease(agent, url2, env, signal, opts = {}) {
29967
- const agentDir = join21(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
29968
- mkdirSync7(agentDir, { recursive: true });
29969
- const fetchDir = join21(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
30239
+ const agentDir = join22(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
30240
+ mkdirSync8(agentDir, { recursive: true });
30241
+ const fetchDir = join22(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29970
30242
  rmSync6(fetchDir, { recursive: true, force: true });
29971
30243
  const gitBin = findRuntime(GIT_BIN, env);
29972
30244
  if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -29974,7 +30246,7 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
29974
30246
  try {
29975
30247
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url2, fetchDir], agentDir, childEnv, signal);
29976
30248
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
29977
- const dir = join21(agentDir, sha);
30249
+ const dir = join22(agentDir, sha);
29978
30250
  if (existsSync18(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29979
30251
  else renameWithRetry(fetchDir, dir, opts);
29980
30252
  return { sha, dir };
@@ -29985,15 +30257,15 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
29985
30257
  }
29986
30258
 
29987
30259
  // src/core/ops/uninstall.ts
29988
- import { existsSync as existsSync19, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
29989
- import { join as join22 } from "node:path";
30260
+ import { existsSync as existsSync19, readdirSync as readdirSync9, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
30261
+ import { join as join23 } from "node:path";
29990
30262
  function row2(area, before, after) {
29991
30263
  return { area, before, after };
29992
30264
  }
29993
30265
  function stopServers(configDir, projectKey) {
29994
30266
  const stopped = listLiveOwners(configDir, projectKey);
29995
- const dir = join22(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
29996
- for (const serverId of stopped) writeFileSync6(join22(dir, serverId + OWNER_STOP_EXT), "", "utf8");
30267
+ const dir = join23(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
30268
+ for (const serverId of stopped) writeFileSync6(join23(dir, serverId + OWNER_STOP_EXT), "", "utf8");
29997
30269
  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 };
29998
30270
  }
29999
30271
  function rootOrNull(adapter, env) {
@@ -30011,14 +30283,14 @@ function removeCache(adapter, env, configDir) {
30011
30283
  const root = rootOrNull(adapter, env);
30012
30284
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
30013
30285
  if (adapter.installMode === "marketplace") {
30014
- const cache = join22(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
30286
+ const cache = join23(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
30015
30287
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
30016
30288
  }
30017
30289
  rmSync7(root, { recursive: true, force: true });
30018
30290
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
30019
30291
  }
30020
30292
  case "plugin": {
30021
- const agentDir = join22(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
30293
+ const agentDir = join23(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
30022
30294
  if (!existsSync19(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
30023
30295
  rmSync7(agentDir, { recursive: true, force: true });
30024
30296
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
@@ -30064,7 +30336,7 @@ function ownEntries(agent, env) {
30064
30336
  }
30065
30337
  if (agent === "opencode") {
30066
30338
  return [{
30067
- file: join22(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
30339
+ file: join23(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
30068
30340
  // D-WIN-OPENCODE-DIR-1
30069
30341
  key: OPENCODE_PLUGIN_KEY,
30070
30342
  shown: OPENCODE_PLUGIN_KEY,
@@ -30075,7 +30347,7 @@ function ownEntries(agent, env) {
30075
30347
  if (agent === "pi") {
30076
30348
  const agentDir = piAgentDirOf(env, home);
30077
30349
  return [{
30078
- file: join22(agentDir, SETTINGS_FILE),
30350
+ file: join23(agentDir, SETTINGS_FILE),
30079
30351
  key: PI_PACKAGES_KEY,
30080
30352
  shown: PI_PACKAGES_KEY,
30081
30353
  has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
@@ -30097,12 +30369,12 @@ function removeOwnEntries(agent, env) {
30097
30369
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
30098
30370
  }
30099
30371
  function removeProjectData(configDir, projectKey) {
30100
- const projects = join22(configDir, PROJECTS_DIR_NAME);
30101
- const dir = join22(projects, projectKey);
30372
+ const projects = join23(configDir, PROJECTS_DIR_NAME);
30373
+ const dir = join23(projects, projectKey);
30102
30374
  if (!existsSync19(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
30103
30375
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
30104
- for (const name of readdirSync8(dir)) {
30105
- if (name !== OWNERS_DIR_NAME) rmSync7(join22(dir, name), { recursive: true, force: true });
30376
+ for (const name of readdirSync9(dir)) {
30377
+ if (name !== OWNERS_DIR_NAME) rmSync7(join23(dir, name), { recursive: true, force: true });
30106
30378
  }
30107
30379
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
30108
30380
  }
@@ -30110,7 +30382,7 @@ function runUninstall(input) {
30110
30382
  const configDir = resolveConfigDir(input.env);
30111
30383
  const stop = stopServers(configDir, input.project.projectKey);
30112
30384
  const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
30113
- rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join22(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
30385
+ rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join23(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
30114
30386
  return { rows, stopped: stop.stopped };
30115
30387
  }
30116
30388
 
@@ -30246,8 +30518,8 @@ function removeV1(agent, findings) {
30246
30518
 
30247
30519
  // src/core/ops/verify-sums.ts
30248
30520
  import { createHash as createHash2 } from "node:crypto";
30249
- import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "node:fs";
30250
- import { join as join23 } from "node:path";
30521
+ import { lstatSync as lstatSync2, readdirSync as readdirSync10, readFileSync as readFileSync17 } from "node:fs";
30522
+ import { join as join24 } from "node:path";
30251
30523
  function mismatch() {
30252
30524
  return new CtxError("BUNDLE_HASH_MISMATCH");
30253
30525
  }
@@ -30265,17 +30537,17 @@ function parseSums(text) {
30265
30537
  return sums;
30266
30538
  }
30267
30539
  function walk3(dir, prefix, out) {
30268
- for (const entry of readdirSync9(dir, { withFileTypes: true })) {
30540
+ for (const entry of readdirSync10(dir, { withFileTypes: true })) {
30269
30541
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
30270
30542
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
30271
- const abs = join23(dir, entry.name);
30543
+ const abs = join24(dir, entry.name);
30272
30544
  if (entry.isDirectory()) walk3(abs, rel, out);
30273
30545
  else if (entry.isFile()) out.set(rel, abs);
30274
30546
  else throw mismatch();
30275
30547
  }
30276
30548
  }
30277
30549
  function verifySums(dir) {
30278
- const sumsPath = join23(dir, RELEASE_SUMS_FILE);
30550
+ const sumsPath = join24(dir, RELEASE_SUMS_FILE);
30279
30551
  const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
30280
30552
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
30281
30553
  const sums = parseSums(readFileSync17(sumsPath, "utf8"));
@@ -30299,7 +30571,7 @@ function row4(area, before, after) {
30299
30571
  return { area, before, after };
30300
30572
  }
30301
30573
  function bundleDir() {
30302
- return dirname11(process.argv[1] ?? "");
30574
+ return dirname12(process.argv[1] ?? "");
30303
30575
  }
30304
30576
  function pluginRootRow(adapter, env) {
30305
30577
  const own2 = bundleDir();
@@ -30313,12 +30585,12 @@ function pluginRootRow(adapter, env) {
30313
30585
  return root === own2 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own2)];
30314
30586
  }
30315
30587
  function isCurrent(agentDir, dir) {
30316
- const link = join24(agentDir, PLUGIN_CURRENT_LINK);
30588
+ const link = join25(agentDir, PLUGIN_CURRENT_LINK);
30317
30589
  return existsSync21(link) && realpathSync10.native(link) === realpathSync10.native(dir);
30318
30590
  }
30319
30591
  async function checkout(adapter, deps) {
30320
30592
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);
30321
- const agentDir = dirname11(fetched.dir);
30593
+ const agentDir = dirname12(fetched.dir);
30322
30594
  try {
30323
30595
  verifySums(fetched.dir);
30324
30596
  } catch (err) {
@@ -30346,7 +30618,7 @@ async function upgrade(adapter, deps, home) {
30346
30618
  return rows;
30347
30619
  } catch (err) {
30348
30620
  removal?.rollback();
30349
- if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename6(done.swap.previous));
30621
+ if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename7(done.swap.previous));
30350
30622
  throw err;
30351
30623
  }
30352
30624
  }