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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.mjs CHANGED
@@ -8,7 +8,7 @@ var __export = (target, all) => {
8
8
  // src/entries/server.ts
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { existsSync as existsSync23, realpathSync as realpathSync12, rmSync as rmSync11 } from "node:fs";
11
- import { dirname as dirname11, join as join23 } from "node:path";
11
+ import { dirname as dirname12, join as join24 } from "node:path";
12
12
  import { fileURLToPath as fileURLToPath2 } from "node:url";
13
13
 
14
14
  // node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
@@ -2882,14 +2882,14 @@ var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, d
2882
2882
  inst._zod.parse = (payload, ctx) => {
2883
2883
  const input = payload.value;
2884
2884
  const left = def.left._zod.run({ value: input, issues: [] }, ctx);
2885
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
2886
- const async = left instanceof Promise || right instanceof Promise;
2885
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
2886
+ const async = left instanceof Promise || right2 instanceof Promise;
2887
2887
  if (async) {
2888
- return Promise.all([left, right]).then(([left2, right2]) => {
2889
- return handleIntersectionResults(payload, left2, right2);
2888
+ return Promise.all([left, right2]).then(([left2, right3]) => {
2889
+ return handleIntersectionResults(payload, left2, right3);
2890
2890
  });
2891
2891
  }
2892
- return handleIntersectionResults(payload, left, right);
2892
+ return handleIntersectionResults(payload, left, right2);
2893
2893
  };
2894
2894
  });
2895
2895
  function mergeValues(a, b) {
@@ -2940,7 +2940,7 @@ function mergeValues(a, b) {
2940
2940
  }
2941
2941
  return { valid: false, mergeErrorPath: [] };
2942
2942
  }
2943
- function handleIntersectionResults(result, left, right) {
2943
+ function handleIntersectionResults(result, left, right2) {
2944
2944
  const unrecKeys = /* @__PURE__ */ new Map();
2945
2945
  let unrecIssue;
2946
2946
  const keyIssues = /* @__PURE__ */ new Map();
@@ -2968,7 +2968,7 @@ function handleIntersectionResults(result, left, right) {
2968
2968
  if (!collect(iss, "l"))
2969
2969
  result.issues.push(iss);
2970
2970
  }
2971
- for (const iss of right.issues) {
2971
+ for (const iss of right2.issues) {
2972
2972
  if (!collect(iss, "r"))
2973
2973
  result.issues.push(iss);
2974
2974
  }
@@ -2982,7 +2982,7 @@ function handleIntersectionResults(result, left, right) {
2982
2982
  result.issues.push(keyIssues.get(k));
2983
2983
  }
2984
2984
  }
2985
- const merged = mergeValues(left.value, right.value);
2985
+ const merged = mergeValues(left.value, right2.value);
2986
2986
  if (!merged.valid) {
2987
2987
  if (aborted(result))
2988
2988
  return result;
@@ -3372,11 +3372,11 @@ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
3372
3372
  defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);
3373
3373
  inst._zod.parse = (payload, ctx) => {
3374
3374
  if (ctx.direction === "backward") {
3375
- const right = def.out._zod.run(payload, ctx);
3376
- if (right instanceof Promise) {
3377
- return right.then((right2) => handlePipeResult(right2, def.in, ctx));
3375
+ const right2 = def.out._zod.run(payload, ctx);
3376
+ if (right2 instanceof Promise) {
3377
+ return right2.then((right3) => handlePipeResult(right3, def.in, ctx));
3378
3378
  }
3379
- return handlePipeResult(right, def.in, ctx);
3379
+ return handlePipeResult(right2, def.in, ctx);
3380
3380
  }
3381
3381
  const left = def.in._zod.run(payload, ctx);
3382
3382
  if (left instanceof Promise) {
@@ -6346,11 +6346,11 @@ var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def
6346
6346
  ZodType.init(inst, def);
6347
6347
  inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params);
6348
6348
  });
6349
- function intersection(left, right) {
6349
+ function intersection(left, right2) {
6350
6350
  return new ZodIntersection({
6351
6351
  type: "intersection",
6352
6352
  left,
6353
- right
6353
+ right: right2
6354
6354
  });
6355
6355
  }
6356
6356
  var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
@@ -10411,14 +10411,14 @@ var $ZodIntersection2 = /* @__PURE__ */ $constructor2("$ZodIntersection", (inst,
10411
10411
  inst._zod.parse = (payload, ctx) => {
10412
10412
  const input = payload.value;
10413
10413
  const left = def.left._zod.run({ value: input, issues: [] }, ctx);
10414
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
10415
- const async = left instanceof Promise || right instanceof Promise;
10414
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
10415
+ const async = left instanceof Promise || right2 instanceof Promise;
10416
10416
  if (async) {
10417
- return Promise.all([left, right]).then(([left2, right2]) => {
10418
- return handleIntersectionResults2(payload, left2, right2);
10417
+ return Promise.all([left, right2]).then(([left2, right3]) => {
10418
+ return handleIntersectionResults2(payload, left2, right3);
10419
10419
  });
10420
10420
  }
10421
- return handleIntersectionResults2(payload, left, right);
10421
+ return handleIntersectionResults2(payload, left, right2);
10422
10422
  };
10423
10423
  });
10424
10424
  function mergeValues2(a, b) {
@@ -10469,7 +10469,7 @@ function mergeValues2(a, b) {
10469
10469
  }
10470
10470
  return { valid: false, mergeErrorPath: [] };
10471
10471
  }
10472
- function handleIntersectionResults2(result, left, right) {
10472
+ function handleIntersectionResults2(result, left, right2) {
10473
10473
  const unrecKeys = /* @__PURE__ */ new Map();
10474
10474
  let unrecIssue;
10475
10475
  const keyIssues = /* @__PURE__ */ new Map();
@@ -10497,7 +10497,7 @@ function handleIntersectionResults2(result, left, right) {
10497
10497
  if (!collect(iss, "l"))
10498
10498
  result.issues.push(iss);
10499
10499
  }
10500
- for (const iss of right.issues) {
10500
+ for (const iss of right2.issues) {
10501
10501
  if (!collect(iss, "r"))
10502
10502
  result.issues.push(iss);
10503
10503
  }
@@ -10511,7 +10511,7 @@ function handleIntersectionResults2(result, left, right) {
10511
10511
  result.issues.push(keyIssues.get(k));
10512
10512
  }
10513
10513
  }
10514
- const merged = mergeValues2(left.value, right.value);
10514
+ const merged = mergeValues2(left.value, right2.value);
10515
10515
  if (!merged.valid) {
10516
10516
  if (aborted2(result))
10517
10517
  return result;
@@ -10901,11 +10901,11 @@ var $ZodPipe2 = /* @__PURE__ */ $constructor2("$ZodPipe", (inst, def) => {
10901
10901
  defineLazyInternal2(inst, "propValues", (zod) => zod.def.in._zod.propValues);
10902
10902
  inst._zod.parse = (payload, ctx) => {
10903
10903
  if (ctx.direction === "backward") {
10904
- const right = def.out._zod.run(payload, ctx);
10905
- if (right instanceof Promise) {
10906
- return right.then((right2) => handlePipeResult2(right2, def.in, ctx));
10904
+ const right2 = def.out._zod.run(payload, ctx);
10905
+ if (right2 instanceof Promise) {
10906
+ return right2.then((right3) => handlePipeResult2(right3, def.in, ctx));
10907
10907
  }
10908
- return handlePipeResult2(right, def.in, ctx);
10908
+ return handlePipeResult2(right2, def.in, ctx);
10909
10909
  }
10910
10910
  const left = def.in._zod.run(payload, ctx);
10911
10911
  if (left instanceof Promise) {
@@ -13961,11 +13961,11 @@ var ZodIntersection2 = /* @__PURE__ */ $constructor2("ZodIntersection", (inst, d
13961
13961
  ZodType2.init(inst, def);
13962
13962
  inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor2(inst, ctx, json2, params);
13963
13963
  });
13964
- function intersection2(left, right) {
13964
+ function intersection2(left, right2) {
13965
13965
  return new ZodIntersection2({
13966
13966
  type: "intersection",
13967
13967
  left,
13968
- right
13968
+ right: right2
13969
13969
  });
13970
13970
  }
13971
13971
  var ZodRecord2 = /* @__PURE__ */ $constructor2("ZodRecord", (inst, def) => {
@@ -28405,7 +28405,7 @@ var DECISION_SOURCE = "decision";
28405
28405
  var DECISION_USER_LABEL = "decision (user)";
28406
28406
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
28407
28407
  var RELEASE_BRANCH = "release";
28408
- var BUNDLE_SHA = true ? "e19d949bebe3a1751b6dc1a520b5ad38659fdd6f" : void 0;
28408
+ var BUNDLE_SHA = true ? "2ed67370714045804b7620af1f3af2c9eabc1713" : void 0;
28409
28409
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
28410
28410
  var DOCTOR_LABEL = Object.freeze({
28411
28411
  D1: "version",
@@ -28428,6 +28428,8 @@ var REPORT_HEADER = "| Check | Status | Detail | Fix |";
28428
28428
  var REPORT_HEADER_RULE = "|---|---|---|---|";
28429
28429
  var REPORT_COMMAND_PREFIX = "Run in a terminal: ";
28430
28430
  var ECHO_MAX_BYTES = 256;
28431
+ var LABEL_PREVIEW_BYTES = 32;
28432
+ var LABEL_PAGE_BYTES = 8192;
28431
28433
  var REPORT_SOURCE_LABEL = "ctx_doctor:report";
28432
28434
  var REPORT_REST_PREFIX = "Rows not shown here are stored in full. Read them with: ";
28433
28435
  var REPORT_POINTER = `ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(REPORT_SOURCE_LABEL)}})`;
@@ -28524,6 +28526,23 @@ function D8_HEALED_RECREATE_DETAIL(ts) {
28524
28526
  }
28525
28527
  var INTEGRITY_OK = "ok";
28526
28528
  var HEAL_BACKUP_SUFFIX = ".bak";
28529
+ var orphanList = (files) => files.map((f) => `${f.path} (${f.bytes} bytes)`).join(", ");
28530
+ var ORPHAN_DIR_PREFIX = "orphan-";
28531
+ function D8_ORPHAN_DETAIL(files) {
28532
+ return `context.db is gone, its WAL files are still here: ${orphanList(files)}`;
28533
+ }
28534
+ var D8_ORPHAN_FIX = "run ctx_doctor once; it keeps these files in a dated folder and starts a new index";
28535
+ function D8_ORPHAN_HEALED_DETAIL(dir, moved, dbPath) {
28536
+ 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`;
28537
+ }
28538
+ var D8_ORPHAN_HEALED_FIX = "run ctx_doctor again; D8 then reads PASS";
28539
+ function D8_ORPHAN_MOVE_FAILED(detail, cause) {
28540
+ return `${detail}; moving them aside failed: ${cause}`;
28541
+ }
28542
+ var DOCTOR_TOOL_NAME = "ctx_doctor";
28543
+ function JOURNAL_SKIPPED_LINE(cause) {
28544
+ return `Journal row for this call skipped: ${cause}`;
28545
+ }
28527
28546
  function D9_INDEX_DETAIL(sources, chunks) {
28528
28547
  return `${sources} sources, ${chunks} chunks indexed`;
28529
28548
  }
@@ -28901,7 +28920,8 @@ var DOCTOR_LOG_TAIL_BYTES = 262144;
28901
28920
  var ERROR_TEXT = Object.freeze({
28902
28921
  NODE_TOO_OLD: "Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",
28903
28922
  NO_SQLITE: "node:sqlite failed to load. Fix: run ctx_doctor.",
28904
- DB_GONE: "context.db path vanished. Fix: run ctx_doctor.",
28923
+ 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.",
28924
+ // D-ORPHAN-WAL-1
28905
28925
  NO_PROJECT: "Project source <kind> is missing. Fix: run ctx_doctor.",
28906
28926
  UNKNOWN_FIELD: 'Unknown field "<f>". Fix: use "queries".',
28907
28927
  TIMEOUT: "Timed out after <ms> ms. Fix: pass background: true.",
@@ -31626,6 +31646,7 @@ var PORTER_MATCH = `
31626
31646
  AND (:scope <> 'session' OR chunks.session_id = :session_id)
31627
31647
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
31628
31648
  AND (:source IS NULL OR s.label = :source)
31649
+ AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
31629
31650
  ${NOT_RAW}`;
31630
31651
  var PORTER_ORDER = `
31631
31652
  ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`;
@@ -31654,6 +31675,7 @@ WHERE chunks_tri MATCH :match
31654
31675
  AND (:scope <> 'session' OR c.session_id = :session_id)
31655
31676
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
31656
31677
  AND (:source IS NULL OR s.label = :source)
31678
+ AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
31657
31679
  ${NOT_RAW}
31658
31680
  ORDER BY bm25(chunks_tri, 1.0, ${TITLE_WEIGHT}) ASC, c.source_id DESC, c.ord ASC`;
31659
31681
  var PAGE_ROWS = `
@@ -31914,10 +31936,18 @@ function typoTerms(db, words) {
31914
31936
  });
31915
31937
  return changed ? out.map((t) => `"${t.replaceAll('"', '""')}"*`) : null;
31916
31938
  }
31917
- function ftsQuery(db, q, scope, ctx, sessionId, limit, offset, source) {
31939
+ var LABEL_SERIAL = `
31940
+ SELECT COALESCE(MAX(CAST(substr(label, length(:prefix) + 1) AS INTEGER)), 0) + 1 AS n
31941
+ FROM sources WHERE session_id = :session_id AND substr(label, 1, length(:prefix)) = :prefix`;
31942
+ function nextLabelSerial(db, sessionId, prefix) {
31943
+ const row5 = stmt(db.raw, LABEL_SERIAL).get({ session_id: sessionId, prefix });
31944
+ return Number(row5.n);
31945
+ }
31946
+ function ftsQuery(db, q, scope, ctx, sessionId, limit, offset, source, sourceIds) {
31918
31947
  const terms = searchTerms(q);
31919
31948
  if (terms.length === 0) return [];
31920
- const filter2 = { scope, session_id: sessionId, worktree: ctx.worktree, source: source ?? null };
31949
+ const ids = sourceIds === void 0 ? null : JSON.stringify(sourceIds);
31950
+ const filter2 = { scope, session_id: sessionId, worktree: ctx.worktree, source: source ?? null, ids };
31921
31951
  const rrf = scope === "project" ? { k: RRF_K } : {};
31922
31952
  const porter = (t) => stmt(db.raw, porterRankSql(scope)).all({ ...filter2, match: t.join(" OR "), all: t.join(" "), ...rrf });
31923
31953
  let pList = porter(terms);
@@ -32123,20 +32153,84 @@ function storedLabel(db, source) {
32123
32153
  const canon = pathLabel(source);
32124
32154
  return canon !== source && labelStored(db, canon) ? canon : source;
32125
32155
  }
32126
- function resolveSourceLabel(db, source) {
32156
+ function newestId(db, label2) {
32157
+ const row5 = stmt(db.raw, "SELECT id FROM sources WHERE label = ? ORDER BY id DESC LIMIT 1").get(label2);
32158
+ return row5 === void 0 ? null : Number(row5.id);
32159
+ }
32160
+ function labelOfId(db, id) {
32161
+ const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id);
32162
+ return row5 === void 0 ? null : row5.label;
32163
+ }
32164
+ function pickSource(db, source, suffix = true) {
32165
+ const named2 = storedLabel(db, source);
32127
32166
  const id = parseSourceHandle(source);
32167
+ const own4 = newestId(db, named2);
32168
+ if (own4 !== null) {
32169
+ const otherLabel = id === null || id === own4 ? null : labelOfId(db, id);
32170
+ return { label: named2, id: own4, via: "label", other: otherLabel === null || otherLabel === named2 ? null : { id, label: otherLabel } };
32171
+ }
32128
32172
  if (id !== null) {
32129
- const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id);
32130
- if (row5 !== void 0) return row5.label;
32173
+ const label2 = labelOfId(db, id);
32174
+ if (label2 !== null) return { label: label2, id, via: "handle", other: null };
32175
+ }
32176
+ if (suffix) {
32177
+ const prefix = named2 + LABEL_SUFFIX_SEP;
32178
+ const rows = stmt(db.raw, "SELECT id, label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
32179
+ for (const r of rows) {
32180
+ if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named2.length) return { label: r.label, id: Number(r.id), via: "suffix", other: null };
32181
+ }
32182
+ }
32183
+ return { label: source, id: null, via: "none", other: null };
32184
+ }
32185
+ function collisionLine(value, pick4) {
32186
+ if (pick4.other === null || pick4.id === null) return null;
32187
+ return "Source " + JSON.stringify(value) + ": used the label " + shownLabel(pick4.label, null) + " (" + sourceHandle(pick4.id) + "); handle " + sourceHandle(pick4.other.id) + " is " + shownLabel(pick4.other.label, null) + (isLongLabel(pick4.other.label) ? ", search it by its full label." : ", search it with source:" + JSON.stringify(pick4.other.label) + ".");
32188
+ }
32189
+ function labelPage(label2, offset, max) {
32190
+ const buf = Buffer.from(label2, "utf8");
32191
+ let start = Math.min(offset, buf.length);
32192
+ while (start < buf.length && (buf[start] & 192) === 128) start++;
32193
+ let end = Math.min(start + max, buf.length);
32194
+ while (end < buf.length && end > start && (buf[end] & 192) === 128) end--;
32195
+ return { text: buf.subarray(start, end).toString("utf8"), next: end < buf.length ? end : null, total: buf.length };
32196
+ }
32197
+ function groupDigits(n) {
32198
+ const s = String(Math.trunc(n));
32199
+ let out = "";
32200
+ for (let i = 0; i < s.length; i++) {
32201
+ if (i > 0 && (s.length - i) % 3 === 0) out += ",";
32202
+ out += s[i];
32131
32203
  }
32132
- const named = storedLabel(db, source);
32133
- if (labelStored(db, named)) return named;
32134
- const prefix = named + LABEL_SUFFIX_SEP;
32135
- const rows = stmt(db.raw, "SELECT label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
32136
- for (const r of rows) {
32137
- if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named.length) return r.label;
32204
+ return out;
32205
+ }
32206
+ function headBytes(s, max) {
32207
+ let out = "";
32208
+ let used = 0;
32209
+ for (const ch of s) {
32210
+ const n = Buffer.byteLength(ch, "utf8");
32211
+ if (used + n > max) break;
32212
+ out += ch;
32213
+ used += n;
32138
32214
  }
32139
- return source;
32215
+ return out;
32216
+ }
32217
+ function isLongLabel(label2) {
32218
+ return Buffer.byteLength(label2, "utf8") > ECHO_MAX_BYTES;
32219
+ }
32220
+ function labelPreview(label2) {
32221
+ return "label (" + groupDigits(Buffer.byteLength(label2, "utf8")) + " B): " + headBytes(label2, LABEL_PREVIEW_BYTES) + "\u2026";
32222
+ }
32223
+ function shownLabel(label2, id) {
32224
+ if (!isLongLabel(label2)) return label2;
32225
+ return (id === null ? "" : sourceHandle(id) + " ") + "[" + labelPreview(label2) + "]";
32226
+ }
32227
+ function indexedLabelLine(label2, id) {
32228
+ if (!isLongLabel(label2)) return "Label: " + label2;
32229
+ return "Its label (" + groupDigits(Buffer.byteLength(label2, "utf8")) + " B): " + headBytes(label2, LABEL_PREVIEW_BYTES) + "\u2026; ctx_search({queries:[], source:" + JSON.stringify(sourceHandle(id)) + "}) reads it whole.";
32230
+ }
32231
+ function sourceCardRow(db, id) {
32232
+ const row5 = stmt(db.raw, "SELECT label, bytes_total, chunk_count, kind FROM sources WHERE id = ?").get(id);
32233
+ return row5 === void 0 ? null : { label: row5.label, bytes: Number(row5.bytes_total), chunks: Number(row5.chunk_count), kind: row5.kind };
32140
32234
  }
32141
32235
  function listSessionSources(db, sessionId, limit) {
32142
32236
  const rows = stmt(db.raw, "SELECT id, label, bytes_total FROM sources WHERE session_id = ? ORDER BY id DESC LIMIT ?").all(sessionId, limit);
@@ -35160,14 +35254,14 @@ var $ZodIntersection3 = /* @__PURE__ */ $constructor3("$ZodIntersection", (inst,
35160
35254
  inst._zod.parse = (payload, ctx) => {
35161
35255
  const input = payload.value;
35162
35256
  const left = def.left._zod.run({ value: input, issues: [] }, ctx);
35163
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
35164
- const async = left instanceof Promise || right instanceof Promise;
35257
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
35258
+ const async = left instanceof Promise || right2 instanceof Promise;
35165
35259
  if (async) {
35166
- return Promise.all([left, right]).then(([left2, right2]) => {
35167
- return handleIntersectionResults3(payload, left2, right2);
35260
+ return Promise.all([left, right2]).then(([left2, right3]) => {
35261
+ return handleIntersectionResults3(payload, left2, right3);
35168
35262
  });
35169
35263
  }
35170
- return handleIntersectionResults3(payload, left, right);
35264
+ return handleIntersectionResults3(payload, left, right2);
35171
35265
  };
35172
35266
  });
35173
35267
  function mergeValues3(a, b) {
@@ -35214,16 +35308,16 @@ function mergeValues3(a, b) {
35214
35308
  }
35215
35309
  return { valid: false, mergeErrorPath: [] };
35216
35310
  }
35217
- function handleIntersectionResults3(result, left, right) {
35311
+ function handleIntersectionResults3(result, left, right2) {
35218
35312
  if (left.issues.length) {
35219
35313
  result.issues.push(...left.issues);
35220
35314
  }
35221
- if (right.issues.length) {
35222
- result.issues.push(...right.issues);
35315
+ if (right2.issues.length) {
35316
+ result.issues.push(...right2.issues);
35223
35317
  }
35224
35318
  if (aborted3(result))
35225
35319
  return result;
35226
- const merged = mergeValues3(left.value, right.value);
35320
+ const merged = mergeValues3(left.value, right2.value);
35227
35321
  if (!merged.valid) {
35228
35322
  throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
35229
35323
  }
@@ -41290,11 +41384,11 @@ function _discriminatedUnion(Class4, discriminator, options, params) {
41290
41384
  ...normalizeParams3(params)
41291
41385
  });
41292
41386
  }
41293
- function _intersection(Class4, left, right) {
41387
+ function _intersection(Class4, left, right2) {
41294
41388
  return new Class4({
41295
41389
  type: "intersection",
41296
41390
  left,
41297
- right
41391
+ right: right2
41298
41392
  });
41299
41393
  }
41300
41394
  function _tuple(Class4, items, _paramsOrRest, _params) {
@@ -42972,11 +43066,11 @@ var ZodIntersection3 = /* @__PURE__ */ $constructor3("ZodIntersection", (inst, d
42972
43066
  $ZodIntersection3.init(inst, def);
42973
43067
  ZodType3.init(inst, def);
42974
43068
  });
42975
- function intersection3(left, right) {
43069
+ function intersection3(left, right2) {
42976
43070
  return new ZodIntersection3({
42977
43071
  type: "intersection",
42978
43072
  left,
42979
- right
43073
+ right: right2
42980
43074
  });
42981
43075
  }
42982
43076
  var ZodTuple = /* @__PURE__ */ $constructor3("ZodTuple", (inst, def) => {
@@ -43441,7 +43535,7 @@ config3(en_default3());
43441
43535
  // src/prompt/_generated.ts
43442
43536
  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";
43443
43537
  var TOOL_DESCRIPTIONS = Object.freeze({
43444
- 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.',
43538
+ 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.',
43445
43539
  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.',
43446
43540
  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.',
43447
43541
  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.',
@@ -43702,8 +43796,8 @@ function rawEnd(src, from, name) {
43702
43796
  let k = src.indexOf("</", from);
43703
43797
  while (k >= 0) {
43704
43798
  const after = k + "</".length + name.length;
43705
- const named = src.slice(k + "</".length, after).toLowerCase() === name;
43706
- if (named && (after >= src.length || !isNameChar(src[after]))) {
43799
+ const named2 = src.slice(k + "</".length, after).toLowerCase() === name;
43800
+ if (named2 && (after >= src.length || !isNameChar(src[after]))) {
43707
43801
  const gt = src.indexOf(">", after);
43708
43802
  return gt < 0 ? src.length : gt + 1;
43709
43803
  }
@@ -43730,7 +43824,7 @@ function cutPoint(src, start, end, scratch) {
43730
43824
  const r = encoder.encodeInto(src.slice(start, limit), scratch);
43731
43825
  return { end: start + r.read, written: r.written };
43732
43826
  }
43733
- function merge4(src, blocks, join24, cap, lineCut) {
43827
+ function merge4(src, blocks, join25, cap, lineCut) {
43734
43828
  const out = [];
43735
43829
  const scratch = new Uint8Array(cap);
43736
43830
  let wide;
@@ -43740,7 +43834,7 @@ function merge4(src, blocks, join24, cap, lineCut) {
43740
43834
  out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
43741
43835
  };
43742
43836
  for (const b of blocks) {
43743
- if (cur !== void 0 && !join24) {
43837
+ if (cur !== void 0 && !join25) {
43744
43838
  emit(cur.start, cur.end, curBytes);
43745
43839
  cur = void 0;
43746
43840
  }
@@ -44071,11 +44165,11 @@ function jsonRows(text) {
44071
44165
  }
44072
44166
  return { objs, keys };
44073
44167
  }
44074
- function fitRow(row5, skewed, named, budget) {
44168
+ function fitRow(row5, skewed, named2, budget) {
44075
44169
  const whole2 = JSON.stringify(row5);
44076
44170
  if (bytes(whole2) <= budget) return whole2;
44077
44171
  const own4 = Object.keys(row5);
44078
- const tier = (k) => skewed.includes(k) ? 0 : named.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
44172
+ const tier = (k) => skewed.includes(k) ? 0 : named2.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
44079
44173
  const order = [...own4].sort((a, b) => tier(a) - tier(b) || own4.indexOf(a) - own4.indexOf(b));
44080
44174
  const field = (k) => JSON.stringify(k) + ":" + JSON.stringify(row5[k]);
44081
44175
  const chosen = /* @__PURE__ */ new Set();
@@ -44129,8 +44223,27 @@ function sourceCount(db, scope, ctx, source) {
44129
44223
  });
44130
44224
  return Number(row5.n);
44131
44225
  }
44132
- function zeroHits(db, scope, ctx, source) {
44133
- return reply('No hits in scope "' + scope + '" across ' + sourceCount(db, scope, ctx, source) + " source(s).", false);
44226
+ function zeroHits(db, scope, ctx, source, offset = 0) {
44227
+ const n = sourceCount(db, scope, ctx, source);
44228
+ if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
44229
+ return reply('No hits in scope "' + scope + '" across ' + n + " source(s).", false);
44230
+ }
44231
+ function named(given, pick4) {
44232
+ if (given === void 0 || pick4 === null) return { arg: given, note: null };
44233
+ const arg = pick4.id !== null && isLongLabel(given) ? sourceHandle(pick4.id) : given;
44234
+ return { arg, note: collisionLine(given, pick4) };
44235
+ }
44236
+ function sourceCard(db, id, input, scope, arg) {
44237
+ const row5 = sourceCardRow(db, id);
44238
+ if (row5 === null) return null;
44239
+ const pg = labelPage(row5.label, input.offset ?? 0, LABEL_PAGE_BYTES);
44240
+ const lines = [
44241
+ "Source " + sourceHandle(id) + ": label " + groupDigits(pg.total) + " B, " + row5.chunks + " chunk(s), " + groupDigits(row5.bytes) + " B of " + row5.kind + ".",
44242
+ "Label:",
44243
+ pg.text
44244
+ ];
44245
+ if (pg.next !== null) lines.push("More: " + callText([], scope, arg, "offset:" + pg.next));
44246
+ return reply(lines.join("\n"), false);
44134
44247
  }
44135
44248
  function callText(queries, scope, source, cursor) {
44136
44249
  const src = source === void 0 ? "" : ", source:" + JSON.stringify(source);
@@ -44161,7 +44274,7 @@ WHERE label = :source
44161
44274
  AND (:scope <> 'session' OR session_id = :session_id)
44162
44275
  AND (:scope <> 'worktree' OR worktree = :worktree)
44163
44276
  ORDER BY id DESC LIMIT 1`;
44164
- function jsonRowsReply(db, input, scope, ctx) {
44277
+ function jsonRowsReply(db, input, scope, ctx, nm) {
44165
44278
  if (input.source === void 0 || input.source === DECISION_SOURCE || input.queries.length === 0) return null;
44166
44279
  const src = db.raw.prepare(JSON_SOURCE).get({ source: input.source, scope, session_id: ctx.sessionId, worktree: ctx.project.worktree });
44167
44280
  if (src === void 0 || Number(src.bytes_total) > JSON_SOURCE_MAX_BYTES) return null;
@@ -44172,25 +44285,27 @@ function jsonRowsReply(db, input, scope, ctx) {
44172
44285
  const texts = objs.map((o) => JSON.stringify(o));
44173
44286
  const offset = input.offset ?? 0;
44174
44287
  const out = [objs.length + " objects {" + keys.join(",") + "}"];
44288
+ const name = shownLabel(input.source, Number(src.id));
44175
44289
  let shown2 = 0;
44176
44290
  let more = false;
44177
44291
  for (const q of input.queries) {
44178
44292
  const scores = rankTexts(texts, q, "any");
44179
44293
  const order = objs.map((_, i) => i).filter((i) => scores[i] > 0).sort((a, b) => scores[b] - scores[a] || a - b);
44180
- const named = namedKeys(keys, q);
44294
+ const named2 = namedKeys(keys, q);
44181
44295
  out.push("Query " + JSON.stringify(q) + ":");
44182
44296
  for (const i of order.slice(offset, offset + JSON_ROWS_PAGE)) {
44183
- const row5 = fitRow(objs[i], [], named, SNIPPET_MAX_BYTES);
44297
+ const row5 = fitRow(objs[i], [], named2, SNIPPET_MAX_BYTES);
44184
44298
  if (row5 === null) continue;
44185
- out.push(input.source + " [" + i + "]: " + row5);
44299
+ out.push(name + " [" + i + "]: " + row5);
44186
44300
  shown2++;
44187
44301
  }
44188
44302
  if (order.length > offset + JSON_ROWS_PAGE) {
44189
- out.push("More: " + callText([q], scope, input.source, "offset:" + (offset + JSON_ROWS_PAGE)));
44303
+ out.push("More: " + callText([q], scope, nm.arg, "offset:" + (offset + JSON_ROWS_PAGE)));
44190
44304
  more = true;
44191
44305
  }
44192
44306
  }
44193
- return shown2 === 0 && !more ? null : reply(out.join("\n"), false);
44307
+ if (shown2 === 0 && !more) return null;
44308
+ return reply((nm.note === null ? out : [nm.note, ...out]).join("\n"), false);
44194
44309
  }
44195
44310
  var SMALL_SOURCE_SHARE = 0.5;
44196
44311
  var SOURCE_BYTES = "SELECT id, bytes_total FROM sources WHERE id IN (SELECT value FROM json_each(:ids))";
@@ -44209,23 +44324,23 @@ function replyHits(hits, size) {
44209
44324
  while (n < size && n < hits.length && hits[n].full === true) n++;
44210
44325
  return n;
44211
44326
  }
44212
- function relevance(db, given, scope, ctx) {
44327
+ function relevance(db, given, scope, ctx, nm) {
44213
44328
  const input = { ...given, queries: decisionQueries(given) };
44214
44329
  const offset = input.offset ?? 0;
44215
44330
  const size = pageSize(input);
44216
44331
  const fetched = input.queries.map((q) => page(db, q, input, scope, ctx, offset, 1));
44217
44332
  const take = fetched.map((h) => replyHits(h, size));
44218
44333
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
44219
- if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source);
44220
- const moreLine3 = (q, pos) => "More: " + callText([q], scope, input.source, "offset:" + pos);
44334
+ if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, offset);
44335
+ const moreLine3 = (q, pos) => "More: " + callText([q], scope, nm.arg, "offset:" + pos);
44221
44336
  let reserve = 0;
44222
44337
  for (const q of input.queries) reserve += bytes2(moreLine3(q, offset + size)) + 1;
44223
44338
  const total = input.source === DECISION_SOURCE ? /* @__PURE__ */ new Map() : sourceBytes(db, [...new Set(pages.flat().map((h) => h.sourceId))]);
44224
44339
  const spent = /* @__PURE__ */ new Map();
44225
- const lines = [];
44340
+ const lines = nm.note === null ? [] : [nm.note];
44226
44341
  const more = [];
44227
44342
  const shown2 = /* @__PURE__ */ new Set();
44228
- let used = 0;
44343
+ let used = nm.note === null ? 0 : bytes2(nm.note) + 1;
44229
44344
  let stopped = false;
44230
44345
  input.queries.forEach((q, qi) => {
44231
44346
  const hits = pages[qi];
@@ -44243,10 +44358,11 @@ function relevance(db, given, scope, ctx) {
44243
44358
  const hit = hits[i];
44244
44359
  const key = hit.sourceId + ":" + hit.ord;
44245
44360
  if (shown2.has(key)) {
44246
- again.set(hit.label, [...again.get(hit.label) ?? [], hit.ord]);
44361
+ const name = shownLabel(hit.label, hit.sourceId);
44362
+ again.set(name, [...again.get(name) ?? [], hit.ord]);
44247
44363
  continue;
44248
44364
  }
44249
- const line = hit.label + " #" + hit.ord + ": " + hit.snippet;
44365
+ const line = shownLabel(hit.label, hit.sourceId) + " #" + hit.ord + ": " + hit.snippet;
44250
44366
  if (used + bytes2(line) + 1 + reserve > OUTPUT_CAP) {
44251
44367
  cut = offset + i;
44252
44368
  stopped = true;
@@ -44274,23 +44390,23 @@ function relevance(db, given, scope, ctx) {
44274
44390
  const moreLines = [];
44275
44391
  const byPos = /* @__PURE__ */ new Map();
44276
44392
  for (const m of more) byPos.set(m.pos, [...byPos.get(m.pos) ?? [], m.q]);
44277
- for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, input.source, "offset:" + pos));
44393
+ for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, nm.arg, "offset:" + pos));
44278
44394
  return reply(lines.concat(moreLines).join("\n"), false);
44279
44395
  }
44280
44396
  function timelineLine(r) {
44281
44397
  const nl = r.text.indexOf("\n");
44282
44398
  const first = nl < 0 ? r.text : r.text.slice(0, nl);
44283
44399
  const seq = r.seq === null ? "" : " #" + r.seq;
44284
- return "[" + new Date(r.ts).toISOString() + "] " + r.label + seq + " " + first;
44400
+ return "[" + new Date(r.ts).toISOString() + "] " + shownLabel(r.label, r.sourceId) + seq + " " + first;
44285
44401
  }
44286
- function timeline(db, input, scope, ctx) {
44402
+ function timeline(db, input, scope, ctx, nm) {
44287
44403
  const memory = scope === "session" ? [] : readAutoMemory(ctx.project);
44288
44404
  const page2 = ftsQueryTimeline(db, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, input.after ?? null, input.source, memory);
44289
44405
  if (page2.rows.length === 0) return zeroHits(db, scope, ctx, input.source);
44290
- const moreLine3 = (ts) => "more: " + callText(input.queries, scope, input.source, 'sort:"timeline", after:' + ts);
44406
+ const moreLine3 = (ts) => "more: " + callText(input.queries, scope, nm.arg, 'sort:"timeline", after:' + ts);
44291
44407
  const reserve = bytes2(moreLine3(page2.rows[page2.rows.length - 1].ts)) + 1;
44292
- const lines = [];
44293
- let used = 0;
44408
+ const lines = nm.note === null ? [] : [nm.note];
44409
+ let used = nm.note === null ? 0 : bytes2(nm.note) + 1;
44294
44410
  let lastTs = null;
44295
44411
  let more = page2.more;
44296
44412
  let i = 0;
@@ -44326,9 +44442,16 @@ async function handler(input, ctx) {
44326
44442
  const scope = input.scope ?? "worktree";
44327
44443
  const db = await openDb(ctx.project, { readOnly: true });
44328
44444
  try {
44329
- if (input.source !== void 0 && input.source !== DECISION_SOURCE) input = { ...input, source: resolveSourceLabel(db, input.source) };
44330
- if (sort === "timeline") return timeline(db, input, scope, ctx);
44331
- return jsonRowsReply(db, input, scope, ctx) ?? relevance(db, input, scope, ctx);
44445
+ const given = input.source;
44446
+ const pick4 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given) : null;
44447
+ if (pick4 !== null) input = { ...input, source: pick4.label };
44448
+ const nm = named(given, pick4);
44449
+ if (sort === "timeline") return timeline(db, input, scope, ctx, nm);
44450
+ if (pick4 !== null && pick4.id !== null && input.queries.length === 0) {
44451
+ const card = sourceCard(db, pick4.id, input, scope, nm.arg);
44452
+ if (card !== null) return card;
44453
+ }
44454
+ return jsonRowsReply(db, input, scope, ctx, nm) ?? relevance(db, input, scope, ctx, nm);
44332
44455
  } finally {
44333
44456
  closeDb(db);
44334
44457
  }
@@ -44349,6 +44472,7 @@ var ctxBatchSchema = external_exports.object({
44349
44472
  }, { error: unknownField }).strict();
44350
44473
  var TOOL = "ctx_batch";
44351
44474
  var LABEL_PREFIX = TOOL + ":";
44475
+ var LABEL_SEP = ":";
44352
44476
  var SHELL = "shell";
44353
44477
  var SHELL_INLINE_FLAG = "-c";
44354
44478
  var MARKER = "$ ";
@@ -44416,6 +44540,7 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
44416
44540
  const display = shown(chunks, ran.map((r) => r.head));
44417
44541
  const bodies = /* @__PURE__ */ new Map();
44418
44542
  const raw = /* @__PURE__ */ new Map();
44543
+ const ids = [];
44419
44544
  let total = 0;
44420
44545
  for (const c of chunks) total += c.bytes;
44421
44546
  let indexed = 0;
@@ -44436,6 +44561,7 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
44436
44561
  chunkCount: group.length,
44437
44562
  createdAt: Date.now()
44438
44563
  }, group);
44564
+ ids.push(id);
44439
44565
  for (const c of group) {
44440
44566
  bodies.set(chunkKey(id, c.ord), display[c.ord]);
44441
44567
  raw.set(chunkKey(id, c.ord), c.text);
@@ -44448,25 +44574,25 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
44448
44574
  for (const c of chunks) {
44449
44575
  if (queued + c.bytes > budgetBytes) {
44450
44576
  const stop2 = flush() ? "budget" : "deadline";
44451
- return { bodies, raw, indexed, total, stop: stop2 };
44577
+ return { bodies, raw, ids, indexed, total, stop: stop2 };
44452
44578
  }
44453
- if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, indexed, total, stop: "deadline" };
44579
+ if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, ids, indexed, total, stop: "deadline" };
44454
44580
  group.push(c);
44455
44581
  groupBytes += c.bytes;
44456
44582
  queued += c.bytes;
44457
44583
  }
44458
44584
  const stop = flush() ? null : "deadline";
44459
- return { bodies, raw, indexed, total, stop };
44585
+ return { bodies, raw, ids, indexed, total, stop };
44460
44586
  }
44461
44587
  function bytes3(s) {
44462
44588
  return Buffer.byteLength(s, "utf8");
44463
44589
  }
44464
- function answer(db, ctx, label2, queries, share, own4) {
44590
+ function answer(db, ctx, ownIds, queries, share, own4) {
44465
44591
  const seen = /* @__PURE__ */ new Set();
44466
44592
  const lines = [];
44467
44593
  for (const [qi, q] of queries.entries()) {
44468
44594
  if (ctx.signal.aborted) break;
44469
- let hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, label2);
44595
+ let hits = ownIds.length === 0 ? [] : ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, void 0, ownIds);
44470
44596
  if (hits.length === 0) hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0);
44471
44597
  const head = "## " + (bytes3(q) > ECHO_MAX_BYTES ? "query " + (qi + 1) : q);
44472
44598
  let used = bytes3(head) + 1;
@@ -44505,9 +44631,10 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
44505
44631
  const ran = pool.results;
44506
44632
  const last2 = ran[ran.length - 1];
44507
44633
  const sandboxBytes = ran.reduce((n, r) => n + r.bytes, 0);
44508
- const label2 = LABEL_PREFIX + ctx.turn;
44509
44634
  try {
44510
44635
  const db = await openDb(ctx.project);
44636
+ const turnPrefix = LABEL_PREFIX + ctx.turn + LABEL_SEP;
44637
+ const label2 = turnPrefix + nextLabelSerial(db, ctx.sessionId, turnPrefix);
44511
44638
  let sections;
44512
44639
  let idx;
44513
44640
  const exitLine = last2.exitCode === null || last2.exitCode === 0 ? null : "exit " + last2.exitCode;
@@ -44523,7 +44650,7 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
44523
44650
  notice = cut === null ? stop : cause === null ? cut : cause + " " + cut;
44524
44651
  const fixed = (exitLine === null ? 0 : bytes3(exitLine) + 1) + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
44525
44652
  const share = Math.floor((OUTPUT_CAP - fixed) / queries.length);
44526
- const answered = answer(db, ctx, label2, queries, share, idx.bodies);
44653
+ const answered = answer(db, ctx, idx.ids, queries, share, idx.bodies);
44527
44654
  sections = answered.lines;
44528
44655
  const unseen = [...idx.bodies].filter(([k, text]) => text !== "" && !answered.seen.has(k)).map(([k]) => idx.raw.get(k));
44529
44656
  const unseenBytes = unseen.reduce((n, t) => n + bytes3(t) + 1, 0);
@@ -44560,7 +44687,7 @@ var ctxBatch = Object.freeze({
44560
44687
 
44561
44688
  // src/core/tools/doctor.ts
44562
44689
  import { readdirSync as readdirSync6, readFileSync as readFileSync10, existsSync as existsSync14 } from "node:fs";
44563
- import { basename as basename4, dirname as dirname6, join as join13 } from "node:path";
44690
+ import { basename as basename5, dirname as dirname7, join as join14 } from "node:path";
44564
44691
 
44565
44692
  // src/adapters/claude-code.ts
44566
44693
  var TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__";
@@ -46447,9 +46574,9 @@ var Tokenizer = class {
46447
46574
  cp = this.nextCode();
46448
46575
  }
46449
46576
  const { out } = this.parseDigits(cp, isDigit);
46450
- const right = out;
46451
- if (minus) right.unshift(CodePoint.DASH);
46452
- const value = Number(leftMinus ? String.fromCodePoint(CodePoint.DASH, ...left, CodePoint.LATIN_SMALL_E, ...right) : String.fromCodePoint(...left, CodePoint.LATIN_SMALL_E, ...right));
46577
+ const right2 = out;
46578
+ if (minus) right2.unshift(CodePoint.DASH);
46579
+ const value = Number(leftMinus ? String.fromCodePoint(CodePoint.DASH, ...left, CodePoint.LATIN_SMALL_E, ...right2) : String.fromCodePoint(...left, CodePoint.LATIN_SMALL_E, ...right2));
46453
46580
  this.endToken("Float", "start", value);
46454
46581
  return this.back("DATA");
46455
46582
  }
@@ -48653,7 +48780,7 @@ function checkHostConfig(row5, env, worktree) {
48653
48780
  const read = row5.id === "pi" ? mcpFile(row5, home, env) : null;
48654
48781
  if (parts.length === 0) return read === null ? pass("D3") : { ...pass("D3"), detail: read };
48655
48782
  const detail = D3_DETAIL(parts);
48656
- const fix = parts.includes(PART_MCP) && parts.includes(PART_HOOKS) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
48783
+ const fix = parts.includes(PART_MCP) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
48657
48784
  return fail("D3", read === null ? detail : detail + D4_REASON_JOIN + read, fix);
48658
48785
  }
48659
48786
  function checkV1Leftovers(agent, home, scope = {}) {
@@ -48707,7 +48834,7 @@ function configPaths(row5, env, worktree) {
48707
48834
  }
48708
48835
 
48709
48836
  // src/core/ops/doctor-db.ts
48710
- import { existsSync as existsSync8 } from "node:fs";
48837
+ import { existsSync as existsSync8, statSync as statSync4 } from "node:fs";
48711
48838
  var unknown4 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail });
48712
48839
  var pass2 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "PASS", detail });
48713
48840
  var fail2 = (detail, fixCommand) => ({ id: "D8", label: DOCTOR_LABEL.D8, status: "FAIL", detail, fixCommand });
@@ -48745,8 +48872,18 @@ function failsOnCorrupt(step) {
48745
48872
  throw err;
48746
48873
  }
48747
48874
  }
48875
+ function orphanFiles(dbPath) {
48876
+ const files = [];
48877
+ for (const suffix of [DB_WAL_SUFFIX, DB_SHM_SUFFIX]) {
48878
+ const path7 = dbPath + suffix;
48879
+ if (existsSync8(path7)) files.push({ path: path7, bytes: statSync4(path7).size });
48880
+ }
48881
+ return files.length > 0 && !existsSync8(dbPath) ? files : [];
48882
+ }
48748
48883
  async function checkDb(project) {
48749
- const clean = { schemaStale: false, integrityFailed: false };
48884
+ const clean = { schemaStale: false, integrityFailed: false, orphan: [] };
48885
+ const orphan = orphanFiles(project.dbPath);
48886
+ if (orphan.length > 0) return { row: fail2(D8_ORPHAN_DETAIL(orphan), D8_ORPHAN_FIX), schemaStale: false, integrityFailed: false, orphan };
48750
48887
  if (!existsSync8(project.dbPath)) return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
48751
48888
  const sqlite = await loadSqlite2();
48752
48889
  if (sqlite === null) return { row: unknown4("D8", D2_SQLITE_DETAIL), ...clean };
@@ -48762,11 +48899,11 @@ async function checkDb(project) {
48762
48899
  }
48763
48900
  const schemaStale = got !== null && got !== SCHEMA_VERSION;
48764
48901
  const integrityFailed = failsOnCorrupt(() => !integrityOk(db));
48765
- if (integrityFailed) return { row: fail2(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale, integrityFailed };
48766
- if (schemaStale && got !== null) return { row: fail2(D8_STALE_SCHEMA_DETAIL(got, SCHEMA_VERSION), DOCTOR_FIX_UPGRADE), schemaStale, integrityFailed };
48902
+ if (integrityFailed) return { row: fail2(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale, integrityFailed, orphan: [] };
48903
+ if (schemaStale && got !== null) return { row: fail2(D8_STALE_SCHEMA_DETAIL(got, SCHEMA_VERSION), DOCTOR_FIX_UPGRADE), schemaStale, integrityFailed, orphan: [] };
48767
48904
  return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
48768
48905
  } catch (err) {
48769
- if (isCorrupt2(err)) return { row: fail2(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true };
48906
+ if (isCorrupt2(err)) return { row: fail2(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true, orphan: [] };
48770
48907
  return { row: unknown4("D8", message(err)), ...clean };
48771
48908
  } finally {
48772
48909
  raw?.close();
@@ -48834,7 +48971,8 @@ function fetchCause(err, timeoutMs) {
48834
48971
  const cause = err instanceof Error && err.cause instanceof Error ? err.cause : err;
48835
48972
  const code = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : "";
48836
48973
  const msg = cause instanceof Error ? cause.message : String(cause);
48837
- return D1_NPM_ERROR(code !== "" && !msg.includes(code) ? `${code} ${msg}` : msg);
48974
+ const parts = code !== "" && !msg.includes(code) ? [code, msg] : [msg];
48975
+ return D1_NPM_ERROR(parts.filter((part) => part !== "").join(" "));
48838
48976
  }
48839
48977
  async function npmLatest(url4, tag, signal, timeoutMs) {
48840
48978
  try {
@@ -48947,9 +49085,9 @@ async function checkNode(i) {
48947
49085
  return pass3("D2", bun.length === 0 ? DOCTOR_PASS_DETAIL : bun.join(D4_REASON_JOIN));
48948
49086
  }
48949
49087
  function checkMcp(ctx) {
48950
- const named = ctx.clientInfo !== void 0 && ctx.clientInfo.name !== "";
49088
+ const named2 = ctx.clientInfo !== void 0 && ctx.clientInfo.name !== "";
48951
49089
  const versioned = ctx.protocolVersion !== void 0 && ctx.protocolVersion !== "";
48952
- return named || versioned ? pass3("D6") : unknown5("D6", D6_UNKNOWN_DETAIL);
49090
+ return named2 || versioned ? pass3("D6") : unknown5("D6", D6_UNKNOWN_DETAIL);
48953
49091
  }
48954
49092
  function piCwdInside(worktree, piCwd) {
48955
49093
  if (piCwd === void 0 || !existsSync9(piCwd)) return false;
@@ -48984,7 +49122,7 @@ import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
48984
49122
 
48985
49123
  // src/setup/spawn-bin.ts
48986
49124
  import { spawnSync } from "node:child_process";
48987
- import { accessSync as accessSync2, constants as fsc, statSync as statSync4 } from "node:fs";
49125
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync5 } from "node:fs";
48988
49126
  import path4 from "node:path";
48989
49127
  var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
48990
49128
  var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
@@ -49002,7 +49140,7 @@ function whichBin(bin, env, platform = process.platform) {
49002
49140
  const f = path4.join(dir, n);
49003
49141
  try {
49004
49142
  accessSync2(f, fsc.X_OK);
49005
- if (statSync4(f).isFile()) return f;
49143
+ if (statSync5(f).isFile()) return f;
49006
49144
  } catch {
49007
49145
  }
49008
49146
  }
@@ -49210,19 +49348,52 @@ function loadFixture(bundleDir2, agent) {
49210
49348
  }
49211
49349
  return { event: e.event, payload: e.payload };
49212
49350
  }
49213
- function payloadFor(payload, worktree) {
49214
- return worktree !== void 0 && isObject5(payload) ? { ...payload, cwd: worktree } : payload;
49215
- }
49216
- function isNativeShape(stdout, exitCode, killed, event) {
49351
+ var CWD_KEY = {
49352
+ "claude-code": "cwd",
49353
+ codex: "cwd",
49354
+ gemini: "cwd",
49355
+ qwen: "cwd",
49356
+ "copilot-cli": "cwd",
49357
+ vscode: "cwd",
49358
+ kiro: "cwd",
49359
+ zcode: "cwd",
49360
+ pi: "cwd",
49361
+ opencode: "directory"
49362
+ };
49363
+ function payloadFor(agent, payload, worktree) {
49364
+ return worktree !== void 0 && isObject5(payload) ? { ...payload, [CWD_KEY[agent]]: worktree } : payload;
49365
+ }
49366
+ var SHAPE = {
49367
+ "claude-code": "claude",
49368
+ codex: "claude",
49369
+ qwen: "claude",
49370
+ vscode: "claude",
49371
+ zcode: "claude",
49372
+ gemini: "gemini",
49373
+ "copilot-cli": "copilot",
49374
+ kiro: "text",
49375
+ pi: "text",
49376
+ opencode: "text"
49377
+ };
49378
+ var COPILOT_KEYS = ["permissionDecision", "additionalContext", "modifiedResult"];
49379
+ function isNativeShape(agent, stdout, exitCode, killed, event) {
49217
49380
  if (killed !== null || exitCode !== 0 && exitCode !== 2) return false;
49218
- if (stdout.length === 0) return true;
49381
+ if (stdout.length === 0 || SHAPE[agent] === "text") return true;
49219
49382
  let out;
49220
49383
  try {
49221
49384
  out = JSON.parse(stdout);
49222
49385
  } catch {
49223
49386
  return false;
49224
49387
  }
49225
- return isObject5(out) && isObject5(out.hookSpecificOutput) && out.hookSpecificOutput.hookEventName === event;
49388
+ if (!isObject5(out)) return false;
49389
+ switch (SHAPE[agent]) {
49390
+ case "claude":
49391
+ return isObject5(out.hookSpecificOutput) && out.hookSpecificOutput.hookEventName === event;
49392
+ case "gemini":
49393
+ return typeof out.decision === "string" || isObject5(out.hookSpecificOutput);
49394
+ default:
49395
+ return COPILOT_KEYS.some((k) => Object.hasOwn(out, k));
49396
+ }
49226
49397
  }
49227
49398
  function codexHookJournaled(db) {
49228
49399
  if (db === null) return false;
@@ -49266,9 +49437,10 @@ async function checkHookRoundTrip(i) {
49266
49437
  const fixed = i.samples === void 0 ? null : Math.max(1, i.samples);
49267
49438
  const maxPairs = fixed ?? D5_MAX_PAIRS;
49268
49439
  const minPairs = fixed ?? D5_MIN_PAIRS;
49440
+ const timeoutMs = i.timeoutMs ?? HOOK_TIMEOUT_MS;
49269
49441
  const bareMs = i.bareMs ?? (async () => {
49270
49442
  const t = performance.now();
49271
- await runProcess([process.execPath, "-e", ""], { cwd: i.bundleDir, env: i.env, signal: i.signal, timeoutMs: HOOK_TIMEOUT_MS });
49443
+ await runProcess([process.execPath, "-e", ""], { cwd: i.bundleDir, env: i.env, signal: i.signal, timeoutMs });
49272
49444
  return performance.now() - t;
49273
49445
  });
49274
49446
  const hookWalls = [];
@@ -49280,11 +49452,11 @@ async function checkHookRoundTrip(i) {
49280
49452
  cwd: i.bundleDir,
49281
49453
  env: i.env,
49282
49454
  signal: i.signal,
49283
- timeoutMs: HOOK_TIMEOUT_MS,
49284
- stdin: JSON.stringify(payloadFor(fixture.payload, i.worktree))
49455
+ timeoutMs,
49456
+ stdin: JSON.stringify(payloadFor(i.agent, fixture.payload, i.worktree))
49285
49457
  });
49286
49458
  hookWalls.push(now() - start);
49287
- if (!isNativeShape(r.stdout.toString("utf8"), r.exitCode, r.killed, fixture.event)) return row("FAIL", D5_SHAPE_DETAIL, D5_FIX);
49459
+ if (!isNativeShape(i.agent, r.stdout.toString("utf8"), r.exitCode, r.killed, fixture.event)) return row("FAIL", D5_SHAPE_DETAIL, D5_FIX);
49288
49460
  bareWalls.push(await bareMs());
49289
49461
  ms = Math.max(0, Math.round(Math.min(...hookWalls) - Math.min(...bareWalls)));
49290
49462
  if (n >= minPairs && ms <= HOOK_P95_MS) break;
@@ -49331,7 +49503,8 @@ function lastHookError(env) {
49331
49503
  }
49332
49504
 
49333
49505
  // src/core/ops/db-heal.ts
49334
- import { existsSync as existsSync12, rmSync as rmSync4 } from "node:fs";
49506
+ import { existsSync as existsSync12, mkdirSync as mkdirSync5, rmSync as rmSync4 } from "node:fs";
49507
+ import { basename as basename4, dirname as dirname6, join as join12 } from "node:path";
49335
49508
  function integrityOk2(rows) {
49336
49509
  return rows.length === 1 && rows[0].integrity_check === INTEGRITY_OK;
49337
49510
  }
@@ -49384,6 +49557,39 @@ async function healD8(input) {
49384
49557
  closeDb(await openDb(project));
49385
49558
  return { ...row5, status: "FAIL", detail: D8_HEALED_RECREATE_DETAIL(ts) };
49386
49559
  }
49560
+ function utcStamp(now) {
49561
+ return now.toISOString().slice(0, 19).replaceAll("-", "").replaceAll(":", "") + "Z";
49562
+ }
49563
+ function makeOrphanDir(projectDir) {
49564
+ const base = join12(projectDir, ORPHAN_DIR_PREFIX + utcStamp(/* @__PURE__ */ new Date()));
49565
+ for (let n = 1; ; n += 1) {
49566
+ const dir = n === 1 ? base : base + "-" + String(n);
49567
+ try {
49568
+ mkdirSync5(dir);
49569
+ return dir;
49570
+ } catch (err) {
49571
+ if (err.code !== "EEXIST") throw err;
49572
+ }
49573
+ }
49574
+ }
49575
+ async function healOrphan(project, files, row5) {
49576
+ const moved = [];
49577
+ let dir = "";
49578
+ try {
49579
+ dir = makeOrphanDir(dirname6(project.dbPath));
49580
+ for (const f of files) {
49581
+ const to = join12(dir, basename4(f.path));
49582
+ renameWithRetry(f.path, to);
49583
+ moved.push({ path: to, bytes: f.bytes });
49584
+ }
49585
+ closeDb(await openDb(project));
49586
+ } catch (err) {
49587
+ const cause = err instanceof CtxError ? err.toLine() : err instanceof Error ? err.message : String(err);
49588
+ const at = moved.length > 0 ? D8_ORPHAN_HEALED_DETAIL(dir, moved, project.dbPath) : row5.detail;
49589
+ return { ...row5, detail: D8_ORPHAN_MOVE_FAILED(at, cause) };
49590
+ }
49591
+ return { ...row5, status: "FAIL", detail: D8_ORPHAN_HEALED_DETAIL(dir, moved, project.dbPath), fixCommand: D8_ORPHAN_HEALED_FIX };
49592
+ }
49387
49593
 
49388
49594
  // src/core/ops/report.ts
49389
49595
  function keyIsTyped(key) {
@@ -49439,8 +49645,8 @@ function buildReportHead(input) {
49439
49645
 
49440
49646
  // src/core/ops/doctor-issue.ts
49441
49647
  import { spawnSync as spawnSync3 } from "node:child_process";
49442
- import { closeSync, existsSync as existsSync13, fstatSync, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync9, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
49443
- import { delimiter, join as join12 } from "node:path";
49648
+ import { closeSync, existsSync as existsSync13, fstatSync, mkdirSync as mkdirSync6, openSync, readFileSync as readFileSync9, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
49649
+ import { delimiter, join as join13 } from "node:path";
49444
49650
  var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
49445
49651
  function tildeOf(env) {
49446
49652
  const home = homeDirOf(env);
@@ -49457,9 +49663,9 @@ function tildeOf(env) {
49457
49663
  }
49458
49664
  function maskLine(line) {
49459
49665
  const lower = line.toLowerCase();
49460
- const named = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
49666
+ const named2 = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
49461
49667
  const token = TOKEN_PREFIXES.some((p) => line.includes(p));
49462
- if (!named && !token) return line;
49668
+ if (!named2 && !token) return line;
49463
49669
  const at = Math.max(line.indexOf(":"), line.indexOf("="));
49464
49670
  return at === -1 ? DOCTOR_MASK : line.slice(0, at + 1) + " " + DOCTOR_MASK;
49465
49671
  }
@@ -49481,8 +49687,8 @@ function onPath(env, tool) {
49481
49687
  const out = [];
49482
49688
  for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
49483
49689
  if (dir === "") continue;
49484
- for (const n of names) if (existsSync13(join12(dir, n))) {
49485
- out.push(join12(dir, n));
49690
+ for (const n of names) if (existsSync13(join13(dir, n))) {
49691
+ out.push(join13(dir, n));
49486
49692
  break;
49487
49693
  }
49488
49694
  }
@@ -49528,8 +49734,8 @@ function agentConfig(adapter, env, worktree) {
49528
49734
  const home = homeDirOf(env);
49529
49735
  const files = configPaths(adapter, env, worktree);
49530
49736
  if (home !== null) {
49531
- if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join12(claudeDirOf(env, home), SETTINGS_FILE) });
49532
- if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join12(codexDirOf(env, home), CONFIG_TOML_FILE) });
49737
+ if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join13(claudeDirOf(env, home), SETTINGS_FILE) });
49738
+ if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join13(codexDirOf(env, home), CONFIG_TOML_FILE) });
49533
49739
  }
49534
49740
  const out = [];
49535
49741
  const seen = /* @__PURE__ */ new Set();
@@ -49612,9 +49818,9 @@ async function buildIssueBody(i) {
49612
49818
  async function writeIssueReport(i) {
49613
49819
  const tilde = tildeOf(i.env);
49614
49820
  const body = await buildIssueBody(i);
49615
- const dir = join12(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
49616
- mkdirSync5(dir, { recursive: true });
49617
- const file2 = join12(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
49821
+ const dir = join13(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
49822
+ mkdirSync6(dir, { recursive: true });
49823
+ const file2 = join13(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
49618
49824
  writeFileSync3(file2, body);
49619
49825
  const shown2 = tilde(file2);
49620
49826
  const title = issueTitle(i.adapter.id, i.rows);
@@ -49690,11 +49896,11 @@ async function hookRow(ctx, adapter, host) {
49690
49896
  }
49691
49897
  }
49692
49898
  function ownServerId(configDir, projectKey) {
49693
- const dir = join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
49899
+ const dir = join14(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
49694
49900
  if (!existsSync14(dir)) return "";
49695
49901
  for (const name of readdirSync6(dir)) {
49696
49902
  if (!name.endsWith(OWNER_PID_EXT)) continue;
49697
- if (readFileSync10(join13(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
49903
+ if (readFileSync10(join14(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
49698
49904
  }
49699
49905
  return "";
49700
49906
  }
@@ -49703,6 +49909,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
49703
49909
  const env = host.env;
49704
49910
  const project = ctx.project;
49705
49911
  let integrityFailed = false;
49912
+ let orphan = [];
49706
49913
  const checks = {
49707
49914
  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 }),
49708
49915
  D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
@@ -49715,6 +49922,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
49715
49922
  D8: async () => {
49716
49923
  const r = await checkDb(project);
49717
49924
  integrityFailed = r.integrityFailed;
49925
+ orphan = r.orphan;
49718
49926
  return r.row;
49719
49927
  },
49720
49928
  D9: () => checkIndex(project),
@@ -49723,8 +49931,13 @@ async function runDoctorChecks(ctx, adapter, host0) {
49723
49931
  };
49724
49932
  const rows = [];
49725
49933
  for (const id of DOCTOR_CHECK_ORDER) rows.push(await guard(id, checks[id]));
49726
- if (!integrityFailed) return rows;
49727
49934
  const at = DOCTOR_CHECK_ORDER.indexOf("D8");
49935
+ if (orphan.length > 0) {
49936
+ const files = orphan;
49937
+ rows[at] = await guard("D8", () => healOrphan(project, files, rows[at]));
49938
+ return rows;
49939
+ }
49940
+ if (!integrityFailed) return rows;
49728
49941
  rows[at] = await guard("D8", () => {
49729
49942
  const configDir = resolveConfigDir(env);
49730
49943
  return healD8({ project, configDir, serverId: ownServerId(configDir, project.projectKey), row: rows[at] });
@@ -49770,7 +49983,7 @@ async function doctorReply(ctx, host) {
49770
49983
  return { text, isError: false, sandboxBytes: bytes5 };
49771
49984
  }
49772
49985
  async function handler2(_input, ctx) {
49773
- return doctorReply(ctx, { env: process.env, bundleDir: dirname6(process.argv[1]), piCwd: void 0 });
49986
+ return doctorReply(ctx, { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 });
49774
49987
  }
49775
49988
  var ctxDoctor = Object.freeze({
49776
49989
  name: "ctx_doctor",
@@ -49784,7 +49997,7 @@ var ctxDoctor = Object.freeze({
49784
49997
  // src/core/tools/execute.ts
49785
49998
  import { existsSync as existsSync15, mkdtempSync, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "node:fs";
49786
49999
  import { tmpdir as tmpdir2 } from "node:os";
49787
- import { dirname as dirname7, join as join14, parse as parse5, resolve as resolve4 } from "node:path";
50000
+ import { dirname as dirname8, join as join15, parse as parse5, resolve as resolve4 } from "node:path";
49788
50001
 
49789
50002
  // src/core/index/select.ts
49790
50003
  var READ_CHUNKS = "SELECT ord, body FROM chunks WHERE source_id = ?";
@@ -49907,7 +50120,7 @@ function schemaLine(issue4) {
49907
50120
  }
49908
50121
  function fileError(given, abs, root) {
49909
50122
  let dir = abs;
49910
- while (!existsSync15(dir) && dirname7(dir) !== dir) dir = dirname7(dir);
50123
+ while (!existsSync15(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
49911
50124
  if (isInside(root, dir)) return null;
49912
50125
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
49913
50126
  }
@@ -49988,8 +50201,8 @@ async function handler3(raw, ctx) {
49988
50201
  if (takesDashC(input.language, runtime)) {
49989
50202
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
49990
50203
  } else {
49991
- tmpDir = mkdtempSync(join14(tmpdir2(), TMP_PREFIX));
49992
- const file2 = join14(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
50204
+ tmpDir = mkdtempSync(join15(tmpdir2(), TMP_PREFIX));
50205
+ const file2 = join15(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
49993
50206
  writeFileSync4(file2, scriptText(input.language, input.code), "utf8");
49994
50207
  argv = scriptArgv(input.language, runtime, file2);
49995
50208
  }
@@ -50024,12 +50237,12 @@ var ctxExecute = {
50024
50237
  };
50025
50238
 
50026
50239
  // src/core/tools/index.ts
50027
- import { existsSync as existsSync16, readFileSync as readFileSync12, statSync as statSync6 } from "node:fs";
50028
- import { dirname as dirname8, extname, join as join16, relative as relative2, resolve as resolve5 } from "node:path";
50240
+ import { existsSync as existsSync16, readFileSync as readFileSync12, statSync as statSync7 } from "node:fs";
50241
+ import { dirname as dirname9, extname, join as join17, relative as relative2, resolve as resolve5 } from "node:path";
50029
50242
 
50030
50243
  // src/core/index/walk.ts
50031
- import { readdirSync as readdirSync7, readFileSync as readFileSync11, realpathSync as realpathSync9, statSync as statSync5 } from "node:fs";
50032
- import { join as join15 } from "node:path";
50244
+ import { readdirSync as readdirSync7, readFileSync as readFileSync11, realpathSync as realpathSync9, statSync as statSync6 } from "node:fs";
50245
+ import { join as join16 } from "node:path";
50033
50246
  var GITIGNORE = ".gitignore";
50034
50247
  var GIT_DIR = ".git";
50035
50248
  function walkDir(root, containmentRoot) {
@@ -50038,7 +50251,7 @@ function walkDir(root, containmentRoot) {
50038
50251
  const found = [];
50039
50252
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
50040
50253
  found.sort(compareFound);
50041
- return found.map((f) => ({ absPath: f.absPath, relPath: join15(...f.dir, f.name) }));
50254
+ return found.map((f) => ({ absPath: f.absPath, relPath: join16(...f.dir, f.name) }));
50042
50255
  }
50043
50256
  function visit(abs, rel, parent, contain, seen, found) {
50044
50257
  let entries;
@@ -50047,10 +50260,10 @@ function visit(abs, rel, parent, contain, seen, found) {
50047
50260
  } catch {
50048
50261
  return;
50049
50262
  }
50050
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join15(abs, GITIGNORE), rel)) : parent;
50263
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join16(abs, GITIGNORE), rel)) : parent;
50051
50264
  for (const e of entries) {
50052
50265
  if (e.name === GIT_DIR) continue;
50053
- const path7 = join15(abs, e.name);
50266
+ const path7 = join16(abs, e.name);
50054
50267
  let isDir = e.isDirectory();
50055
50268
  let isFile = e.isFile();
50056
50269
  let target = path7;
@@ -50062,7 +50275,7 @@ function visit(abs, rel, parent, contain, seen, found) {
50062
50275
  continue;
50063
50276
  }
50064
50277
  if (!isInside(contain, resolved)) continue;
50065
- const st = statSync5(resolved);
50278
+ const st = statSync6(resolved);
50066
50279
  isDir = st.isDirectory();
50067
50280
  isFile = st.isFile();
50068
50281
  target = resolved;
@@ -54180,7 +54393,7 @@ function readUtf8(absPath) {
54180
54393
  }
54181
54394
  function missingOrOutside(given, abs, root) {
54182
54395
  let dir = abs;
54183
- while (!existsSync16(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
54396
+ while (!existsSync16(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
54184
54397
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
54185
54398
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
54186
54399
  }
@@ -54188,10 +54401,10 @@ function pathItems(input, project) {
54188
54401
  const abs = resolve5(project.worktree, input.path);
54189
54402
  if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
54190
54403
  const base = relative2(project.worktree, abs);
54191
- if (statSync6(abs).isDirectory()) {
54404
+ if (statSync7(abs).isDirectory()) {
54192
54405
  return walkDir(abs, project.containmentRoot).map((f) => ({
54193
54406
  sourceKind: "path",
54194
- label: pathLabel(join16(base, f.relPath)),
54407
+ label: pathLabel(join17(base, f.relPath)),
54195
54408
  kind: kindOfPath(f.relPath),
54196
54409
  read: () => readUtf8(f.absPath)
54197
54410
  }));
@@ -54263,8 +54476,9 @@ async function handler4(input, ctx) {
54263
54476
  } finally {
54264
54477
  closeDb(db);
54265
54478
  }
54266
- const shown2 = Buffer.byteLength(from, "utf8") > ECHO_MAX_BYTES ? sourceHandle(lastId) : from;
54267
- const line = ["Indexed " + sources + " source(s), " + chunks + " chunk(s) from " + shown2 + ".", ...notes].join("\n");
54479
+ const head = "Indexed " + sources + " source(s), " + chunks + " chunk(s) from ";
54480
+ const first = sources === 1 && lastId > 0 ? head + sourceHandle(lastId) + ". " + indexedLabelLine(from, lastId) : head + shownLabel(from, null) + ".";
54481
+ const line = [first, ...notes].join("\n");
54268
54482
  return {
54269
54483
  text: capBytes(line, OUTPUT_CAP).text,
54270
54484
  isError: false,
@@ -54308,7 +54522,7 @@ function purgeScope(db, scope, input) {
54308
54522
  const raw = db.raw;
54309
54523
  if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
54310
54524
  if (scope === "source") {
54311
- const label2 = storedLabel(db, input.source);
54525
+ const label2 = pickSource(db, input.source, false).label;
54312
54526
  return deleteChunkRows(raw, { label: label2 }) + changes(raw, "DELETE FROM sources WHERE label = ?", label2);
54313
54527
  }
54314
54528
  const chunks = deleteChunkRows(raw, "all");
@@ -54772,6 +54986,9 @@ function bytes4(n) {
54772
54986
  }
54773
54987
  return v.toFixed(1) + " " + UNITS[u];
54774
54988
  }
54989
+ function right(v, width) {
54990
+ return " " + v.padStart(width - 1);
54991
+ }
54775
54992
  function pct(t) {
54776
54993
  return (t.saved * PERCENT_SCALE / Math.max(1, t.produced)).toFixed(1) + "%";
54777
54994
  }
@@ -54795,8 +55012,8 @@ function plural(n, word) {
54795
55012
  }
54796
55013
  function table2(title, rows) {
54797
55014
  const max = Math.max(0, ...rows.map((r) => r.saved));
54798
- 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);
54799
- 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())];
55015
+ 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);
55016
+ 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())];
54800
55017
  }
54801
55018
  function bySaved(a, b) {
54802
55019
  return b.saved - a.saved || b.produced - a.produced || a.returned - b.returned || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
@@ -54808,14 +55025,14 @@ function joinIndex(tools) {
54808
55025
  const idx = tools.filter((t2) => STATS_INDEX_TOOLS.includes(t2.name));
54809
55026
  if (idx.length <= 1) return tools;
54810
55027
  const t = sum(idx);
54811
- const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: t.produced - t.returned };
55028
+ const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: Math.max(0, t.produced - t.returned) };
54812
55029
  return [...tools.filter((x) => !idx.includes(x)), one];
54813
55030
  }
54814
55031
  function toolRows(tools) {
54815
- const named = joinIndex(tools.map((t) => ({ ...t, saved: t.produced - t.returned }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
54816
- const zero = named.filter((t) => t.saved <= 0);
55032
+ const named2 = joinIndex(tools.map((t) => ({ ...t, saved: Math.max(0, t.produced - t.returned) }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
55033
+ const zero = named2.filter((t) => t.saved <= 0);
54817
55034
  const fold = zero.length > 1 ? zero : [];
54818
- const keep = named.filter((t) => !fold.includes(t));
55035
+ const keep = named2.filter((t) => !fold.includes(t));
54819
55036
  const room = fold.length > 0 ? STATS_MAX_TOOL_ROWS - 1 : STATS_MAX_TOOL_ROWS;
54820
55037
  const over = keep.length > room;
54821
55038
  const shown2 = over ? keep.slice(0, STATS_MAX_TOOL_ROWS - 1) : keep;
@@ -54883,7 +55100,7 @@ function lastDays(week, allCalls) {
54883
55100
  return [
54884
55101
  head,
54885
55102
  ...card,
54886
- ...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)] : []),
55103
+ ...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)] : []),
54887
55104
  " " + STATS_WAYS.map(([, ch, name]) => `${ch} ${name}`).join(" "),
54888
55105
  ""
54889
55106
  ];
@@ -54911,8 +55128,8 @@ function report(f, sessionId, agent) {
54911
55128
  ...head,
54912
55129
  `${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
54913
55130
  ` ${bytes4(focus.produced)} became ${bytes4(focus.returned)}: ${bytes4(focus.saved)} kept out (${pct(focus)})`,
54914
- " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.produced).padStart(NUM_W),
54915
- " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.returned).padStart(NUM_W),
55131
+ " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + right(bytes4(focus.produced), NUM_W),
55132
+ " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + right(bytes4(focus.returned), NUM_W),
54916
55133
  ...focus.saved > 0 ? [windowLine(focus.saved), STATS_TOKEN_NOTE] : [],
54917
55134
  ...hookLine(f.redirected, f.replaced),
54918
55135
  "",
@@ -54926,7 +55143,7 @@ function report(f, sessionId, agent) {
54926
55143
  "",
54927
55144
  ...f.top.length > 0 ? [
54928
55145
  "Largest single outputs (made \u2192 sent to the chat)",
54929
- ...f.top.map((t) => " " + label(toolName(t.name)) + bytes4(t.produced).padStart(NUM_W) + " \u2192 " + bytes4(t.returned).padStart(NUM_W)),
55146
+ ...f.top.map((t) => " " + label(toolName(t.name)) + right(bytes4(t.produced), NUM_W) + " \u2192 " + right(bytes4(t.returned), NUM_W)),
54930
55147
  ""
54931
55148
  ] : []
54932
55149
  ];
@@ -54935,10 +55152,10 @@ function report(f, sessionId, agent) {
54935
55152
  if (!agents.has(agent)) agents.set(agent, EMPTY3);
54936
55153
  lines.push("By agent (this project)", ...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
54937
55154
  const maxKind = Math.max(0, ...[...f.kinds.values()].map((k) => k.project));
54938
- lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + "Session".padStart(STATS_KIND_W) + "Project".padStart(STATS_KIND_W));
55155
+ lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + right("Session", STATS_KIND_W) + right("Project", STATS_KIND_W));
54939
55156
  for (const [kind, name] of STATS_KIND_LABELS) {
54940
55157
  const k = f.kinds.get(kind) ?? { session: 0, project: 0 };
54941
- lines.push((" " + label(name) + int4(k.session).padStart(STATS_KIND_W) + int4(k.project).padStart(STATS_KIND_W) + " " + bar(k.project, maxKind, STATS_KIND_BAR)).trimEnd());
55158
+ lines.push((" " + label(name) + right(int4(k.session), STATS_KIND_W) + right(int4(k.project), STATS_KIND_W) + " " + bar(k.project, maxKind, STATS_KIND_BAR)).trimEnd());
54942
55159
  }
54943
55160
  lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
54944
55161
  lines.push(
@@ -54955,7 +55172,14 @@ async function handler7(_input, ctx) {
54955
55172
  const db = await openDb(ctx.project, { readOnly: true });
54956
55173
  let facts;
54957
55174
  try {
54958
- facts = readFacts(db.raw, ctx.sessionId);
55175
+ db.raw.exec("BEGIN DEFERRED");
55176
+ try {
55177
+ facts = readFacts(db.raw, ctx.sessionId);
55178
+ db.raw.exec("COMMIT");
55179
+ } catch (err) {
55180
+ if (db.raw.isTransaction) db.raw.exec("ROLLBACK");
55181
+ throw err;
55182
+ }
54959
55183
  } finally {
54960
55184
  closeDb(db);
54961
55185
  }
@@ -54986,11 +55210,11 @@ var ctxStats = Object.freeze({
54986
55210
 
54987
55211
  // src/core/tools/upgrade.ts
54988
55212
  import { existsSync as existsSync22, realpathSync as realpathSync10, rmSync as rmSync10 } from "node:fs";
54989
- import { basename as basename6, dirname as dirname10, join as join22 } from "node:path";
55213
+ import { basename as basename7, dirname as dirname11, join as join23 } from "node:path";
54990
55214
 
54991
55215
  // src/core/ops/host-write.ts
54992
- import { copyFileSync, existsSync as existsSync17, mkdirSync as mkdirSync6, writeFileSync as writeFileSync5 } from "node:fs";
54993
- import { dirname as dirname9, join as join17 } from "node:path";
55216
+ import { copyFileSync, existsSync as existsSync17, mkdirSync as mkdirSync7, writeFileSync as writeFileSync5 } from "node:fs";
55217
+ import { dirname as dirname10, join as join18 } from "node:path";
54994
55218
  function defaultWrite(file2, text) {
54995
55219
  writeFileSync5(file2, text, "utf8");
54996
55220
  }
@@ -54999,14 +55223,14 @@ function hostConfigPath(agent, home, env) {
54999
55223
  if (own4 !== void 0) return ownMcpFileOf(agent, own4.file, env, home);
55000
55224
  switch (agent) {
55001
55225
  case "opencode":
55002
- return join17(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
55226
+ return join18(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
55003
55227
  // D-WIN-OPENCODE-DIR-1
55004
55228
  case "pi":
55005
- return join17(piAgentDirOf(env, home), SETTINGS_FILE);
55229
+ return join18(piAgentDirOf(env, home), SETTINGS_FILE);
55006
55230
  case "copilot-cli":
55007
55231
  return null;
55008
55232
  default:
55009
- return join17(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
55233
+ return join18(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
55010
55234
  }
55011
55235
  }
55012
55236
  function cell3(value) {
@@ -55019,7 +55243,7 @@ function writeWithRollback(file2, text, write, atomic) {
55019
55243
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
55020
55244
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
55021
55245
  const had = existsSync17(file2);
55022
- mkdirSync6(dirname9(file2), { recursive: true });
55246
+ mkdirSync7(dirname10(file2), { recursive: true });
55023
55247
  if (had) copyFileSync(file2, trash);
55024
55248
  try {
55025
55249
  write(tmp, text);
@@ -55057,7 +55281,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
55057
55281
 
55058
55282
  // src/core/ops/plugin-swap.ts
55059
55283
  import { existsSync as existsSync18, lstatSync, readdirSync as readdirSync8, readlinkSync, rmSync as rmSync6, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
55060
- import { basename as basename5, join as join18, win32 as win322 } from "node:path";
55284
+ import { basename as basename6, join as join19, win32 as win322 } from "node:path";
55061
55285
  function linkTarget(path7, win) {
55062
55286
  if (!isLink(path7)) return null;
55063
55287
  const target = readlinkSync(path7);
@@ -55076,11 +55300,11 @@ function settleLinks(link, tmp, old, opts) {
55076
55300
  else renameWithRetry(old, link, opts);
55077
55301
  }
55078
55302
  function swapPluginCurrent(agentDir, sha, opts = {}) {
55079
- const next = join18(agentDir, sha);
55303
+ const next = join19(agentDir, sha);
55080
55304
  if (!existsSync18(next) || !lstatSync(next).isDirectory()) {
55081
- throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
55305
+ throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename6(agentDir), path: next });
55082
55306
  }
55083
- const link = join18(agentDir, PLUGIN_CURRENT_LINK);
55307
+ const link = join19(agentDir, PLUGIN_CURRENT_LINK);
55084
55308
  const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
55085
55309
  const old = link + PLUGIN_LINK_OLD_SUFFIX;
55086
55310
  settleLinks(link, tmp, old, opts);
@@ -55095,15 +55319,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
55095
55319
  if (before !== null) unlinkSync2(old);
55096
55320
  const keep = /* @__PURE__ */ new Set([sha]);
55097
55321
  if (before !== null) keep.add(before);
55098
- const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join18(agentDir, name));
55322
+ const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join19(agentDir, name));
55099
55323
  for (const dir of removed) rmSync6(dir, { recursive: true, force: true });
55100
- const previous = before !== null && existsSync18(join18(agentDir, before)) ? join18(agentDir, before) : null;
55324
+ const previous = before !== null && existsSync18(join19(agentDir, before)) ? join19(agentDir, before) : null;
55101
55325
  return { current: next, previous, removed };
55102
55326
  }
55103
55327
 
55104
55328
  // src/core/ops/release-fetch.ts
55105
- import { existsSync as existsSync19, mkdirSync as mkdirSync7, rmSync as rmSync7 } from "node:fs";
55106
- import { join as join19 } from "node:path";
55329
+ import { existsSync as existsSync19, mkdirSync as mkdirSync8, rmSync as rmSync7 } from "node:fs";
55330
+ import { join as join20 } from "node:path";
55107
55331
  function failed(r) {
55108
55332
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
55109
55333
  const status = r.killed ?? String(r.exitCode);
@@ -55115,9 +55339,9 @@ async function git2(bin, args, cwd, env, signal) {
55115
55339
  return r.stdout.toString().trim();
55116
55340
  }
55117
55341
  async function fetchRelease(agent, url4, env, signal, opts = {}) {
55118
- const agentDir = join19(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
55119
- mkdirSync7(agentDir, { recursive: true });
55120
- const fetchDir = join19(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
55342
+ const agentDir = join20(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
55343
+ mkdirSync8(agentDir, { recursive: true });
55344
+ const fetchDir = join20(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
55121
55345
  rmSync7(fetchDir, { recursive: true, force: true });
55122
55346
  const gitBin = findRuntime(GIT_BIN, env);
55123
55347
  if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -55125,7 +55349,7 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
55125
55349
  try {
55126
55350
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url4, fetchDir], agentDir, childEnv, signal);
55127
55351
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
55128
- const dir = join19(agentDir, sha);
55352
+ const dir = join20(agentDir, sha);
55129
55353
  if (existsSync19(dir)) rmSync7(fetchDir, { recursive: true, force: true });
55130
55354
  else renameWithRetry(fetchDir, dir, opts);
55131
55355
  return { sha, dir };
@@ -55137,14 +55361,14 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
55137
55361
 
55138
55362
  // src/core/ops/uninstall.ts
55139
55363
  import { existsSync as existsSync20, readdirSync as readdirSync9, rmSync as rmSync8, writeFileSync as writeFileSync6 } from "node:fs";
55140
- import { join as join20 } from "node:path";
55364
+ import { join as join21 } from "node:path";
55141
55365
  function row2(area, before, after) {
55142
55366
  return { area, before, after };
55143
55367
  }
55144
55368
  function stopServers(configDir, projectKey) {
55145
55369
  const stopped = listLiveOwners(configDir, projectKey);
55146
- const dir = join20(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
55147
- for (const serverId of stopped) writeFileSync6(join20(dir, serverId + OWNER_STOP_EXT), "", "utf8");
55370
+ const dir = join21(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
55371
+ for (const serverId of stopped) writeFileSync6(join21(dir, serverId + OWNER_STOP_EXT), "", "utf8");
55148
55372
  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 };
55149
55373
  }
55150
55374
  function rootOrNull(adapter, env) {
@@ -55162,14 +55386,14 @@ function removeCache(adapter, env, configDir) {
55162
55386
  const root = rootOrNull(adapter, env);
55163
55387
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
55164
55388
  if (adapter.installMode === "marketplace") {
55165
- const cache = join20(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
55389
+ const cache = join21(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
55166
55390
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
55167
55391
  }
55168
55392
  rmSync8(root, { recursive: true, force: true });
55169
55393
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
55170
55394
  }
55171
55395
  case "plugin": {
55172
- const agentDir = join20(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
55396
+ const agentDir = join21(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
55173
55397
  if (!existsSync20(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
55174
55398
  rmSync8(agentDir, { recursive: true, force: true });
55175
55399
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
@@ -55215,7 +55439,7 @@ function ownEntries(agent, env) {
55215
55439
  }
55216
55440
  if (agent === "opencode") {
55217
55441
  return [{
55218
- file: join20(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
55442
+ file: join21(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
55219
55443
  // D-WIN-OPENCODE-DIR-1
55220
55444
  key: OPENCODE_PLUGIN_KEY,
55221
55445
  shown: OPENCODE_PLUGIN_KEY,
@@ -55226,7 +55450,7 @@ function ownEntries(agent, env) {
55226
55450
  if (agent === "pi") {
55227
55451
  const agentDir = piAgentDirOf(env, home);
55228
55452
  return [{
55229
- file: join20(agentDir, SETTINGS_FILE),
55453
+ file: join21(agentDir, SETTINGS_FILE),
55230
55454
  key: PI_PACKAGES_KEY,
55231
55455
  shown: PI_PACKAGES_KEY,
55232
55456
  has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
@@ -55248,12 +55472,12 @@ function removeOwnEntries(agent, env) {
55248
55472
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
55249
55473
  }
55250
55474
  function removeProjectData(configDir, projectKey) {
55251
- const projects = join20(configDir, PROJECTS_DIR_NAME);
55252
- const dir = join20(projects, projectKey);
55475
+ const projects = join21(configDir, PROJECTS_DIR_NAME);
55476
+ const dir = join21(projects, projectKey);
55253
55477
  if (!existsSync20(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
55254
55478
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
55255
55479
  for (const name of readdirSync9(dir)) {
55256
- if (name !== OWNERS_DIR_NAME) rmSync8(join20(dir, name), { recursive: true, force: true });
55480
+ if (name !== OWNERS_DIR_NAME) rmSync8(join21(dir, name), { recursive: true, force: true });
55257
55481
  }
55258
55482
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
55259
55483
  }
@@ -55261,7 +55485,7 @@ function runUninstall(input) {
55261
55485
  const configDir = resolveConfigDir(input.env);
55262
55486
  const stop = stopServers(configDir, input.project.projectKey);
55263
55487
  const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
55264
- rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join20(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
55488
+ rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join21(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
55265
55489
  return { rows, stopped: stop.stopped };
55266
55490
  }
55267
55491
 
@@ -55398,7 +55622,7 @@ function removeV1(agent, findings) {
55398
55622
  // src/core/ops/verify-sums.ts
55399
55623
  import { createHash as createHash2 } from "node:crypto";
55400
55624
  import { lstatSync as lstatSync2, readdirSync as readdirSync10, readFileSync as readFileSync14 } from "node:fs";
55401
- import { join as join21 } from "node:path";
55625
+ import { join as join22 } from "node:path";
55402
55626
  function mismatch() {
55403
55627
  return new CtxError("BUNDLE_HASH_MISMATCH");
55404
55628
  }
@@ -55419,14 +55643,14 @@ function walk2(dir, prefix, out) {
55419
55643
  for (const entry of readdirSync10(dir, { withFileTypes: true })) {
55420
55644
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
55421
55645
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
55422
- const abs = join21(dir, entry.name);
55646
+ const abs = join22(dir, entry.name);
55423
55647
  if (entry.isDirectory()) walk2(abs, rel, out);
55424
55648
  else if (entry.isFile()) out.set(rel, abs);
55425
55649
  else throw mismatch();
55426
55650
  }
55427
55651
  }
55428
55652
  function verifySums(dir) {
55429
- const sumsPath = join21(dir, RELEASE_SUMS_FILE);
55653
+ const sumsPath = join22(dir, RELEASE_SUMS_FILE);
55430
55654
  const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
55431
55655
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
55432
55656
  const sums = parseSums(readFileSync14(sumsPath, "utf8"));
@@ -55450,7 +55674,7 @@ function row4(area, before, after) {
55450
55674
  return { area, before, after };
55451
55675
  }
55452
55676
  function bundleDir() {
55453
- return dirname10(process.argv[1] ?? "");
55677
+ return dirname11(process.argv[1] ?? "");
55454
55678
  }
55455
55679
  function pluginRootRow(adapter, env) {
55456
55680
  const own4 = bundleDir();
@@ -55464,12 +55688,12 @@ function pluginRootRow(adapter, env) {
55464
55688
  return root === own4 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own4)];
55465
55689
  }
55466
55690
  function isCurrent(agentDir, dir) {
55467
- const link = join22(agentDir, PLUGIN_CURRENT_LINK);
55691
+ const link = join23(agentDir, PLUGIN_CURRENT_LINK);
55468
55692
  return existsSync22(link) && realpathSync10.native(link) === realpathSync10.native(dir);
55469
55693
  }
55470
55694
  async function checkout(adapter, deps) {
55471
55695
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);
55472
- const agentDir = dirname10(fetched.dir);
55696
+ const agentDir = dirname11(fetched.dir);
55473
55697
  try {
55474
55698
  verifySums(fetched.dir);
55475
55699
  } catch (err) {
@@ -55497,7 +55721,7 @@ async function upgrade(adapter, deps, home) {
55497
55721
  return rows;
55498
55722
  } catch (err) {
55499
55723
  removal?.rollback();
55500
- if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename6(done.swap.previous));
55724
+ if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename7(done.swap.previous));
55501
55725
  throw err;
55502
55726
  }
55503
55727
  }
@@ -55674,7 +55898,7 @@ function workspaceCwdOf(meta3, spawnCwd, script) {
55674
55898
  const fromHost = workspaceFromMeta(meta3);
55675
55899
  if (fromHost !== void 0) return fromHost;
55676
55900
  if (script === void 0 || script === "") return spawnCwd;
55677
- return realOrSame(spawnCwd) === realOrSame(dirname11(script)) ? "" : spawnCwd;
55901
+ return realOrSame(spawnCwd) === realOrSame(dirname12(script)) ? "" : spawnCwd;
55678
55902
  }
55679
55903
  function errorReply(err) {
55680
55904
  if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0 };
@@ -55717,7 +55941,7 @@ async function startServer(argv, env) {
55717
55941
  return db;
55718
55942
  }
55719
55943
  function stopMarker(configDir, projectKey) {
55720
- return join23(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
55944
+ return join24(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
55721
55945
  }
55722
55946
  function stopRequested() {
55723
55947
  const configDir = resolveConfigDir(process.env);
@@ -55773,7 +55997,7 @@ async function startServer(argv, env) {
55773
55997
  try {
55774
55998
  await journal(resolved, ctx, tool.name, reply4);
55775
55999
  } catch (err) {
55776
- reply4 = errorReply(err);
56000
+ reply4 = tool.name === DOCTOR_TOOL_NAME ? { ...reply4, text: reply4.text + "\n" + JOURNAL_SKIPPED_LINE(errorReply(err).text) } : errorReply(err);
55777
56001
  }
55778
56002
  }
55779
56003
  }