context-mode 2.2.1 → 2.2.3

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.
@@ -23,16 +23,11 @@ var POINTER_MIN = 640;
23
23
  var STATE_CLOSE_TAG = "</context_mode_state>";
24
24
  var INDEX_WRITE_CHUNK = 1048576;
25
25
  var SYNC_INDEX_MAX_BYTES = 65536;
26
- var REPLACE_TRIGGER_BYTES_DEFAULT = 4096;
26
+ var REPLACE_TRIGGER_BYTES = 4096;
27
27
  var REPLACE_TRIGGER_ENV = "CTX_REPLACE_TRIGGER_BYTES";
28
- function readReplaceTrigger(raw) {
29
- if (raw === void 0 || raw.trim() === "") return REPLACE_TRIGGER_BYTES_DEFAULT;
30
- const n = Number(raw);
31
- return Number.isSafeInteger(n) && n > 0 ? n : REPLACE_TRIGGER_BYTES_DEFAULT;
32
- }
33
- var REPLACE_TRIGGER_BYTES = readReplaceTrigger(process.env[REPLACE_TRIGGER_ENV]);
34
28
  var RANGE_READ_TOOLS = Object.freeze(["Read", "view"]);
35
29
  var READ_RANGE_KEYS = Object.freeze(["offset", "limit", "view_range"]);
30
+ var SKILL_LOAD_TOOLS = Object.freeze(["Skill"]);
36
31
  var REPLACE_RETURN_BYTES = 96;
37
32
  var SHAPE_RETURN_BYTES = 256;
38
33
  var REPLACE_CHUNK_BYTES = 48;
@@ -46,6 +41,9 @@ function SUBAGENT_HANDLE_LINE(handle, bytes5, read3) {
46
41
  function SEARCH_TWIN_LINE(searchPath, handle, terms, projectDir) {
47
42
  return " Or run: node " + shellWord(searchPath) + " " + handle + " " + shellWord(terms) + " " + shellWord(projectDir);
48
43
  }
44
+ function PERSISTED_FILE_LINE(file2) {
45
+ return " The whole output is also in " + JSON.stringify(file2) + "; Read it with offset and limit.";
46
+ }
49
47
  function shellWord(s) {
50
48
  return "'" + s.split("'").join("'\\''") + "'";
51
49
  }
@@ -200,6 +198,10 @@ var KILL_GRACE_MS = 1e3;
200
198
  var PIPE_EOF_GRACE_MS = 250;
201
199
  var PIPE_DRAIN_MAX_MS = 2e3;
202
200
  var DB_TIMEOUT_MS = 5e3;
201
+ var HOOK_BUSY_MS = 250;
202
+ var HOOK_SPOOL_DIR = "pending";
203
+ var SPOOL_CLAIM_STALE_MS = 3e4;
204
+ var SPOOL_DRAIN_MS = 1e3;
203
205
  var DB_WAL_SUFFIX = "-wal";
204
206
  var DB_SHM_SUFFIX = "-shm";
205
207
  var DB_TMP_SUFFIX = ".tmp";
@@ -215,7 +217,7 @@ var HOOK_TIMEOUT_MS = 5e3;
215
217
  var IN_PROCESS_TIMEOUT_MS = 0;
216
218
  var MS_PER_DAY = 864e5;
217
219
  var PROJECT_KEY_HEX_LEN = 16;
218
- var SCHEMA_VERSION = 6;
220
+ var SCHEMA_VERSION = 7;
219
221
  var RETENTION_SIZE_CAP_BYTES = 524288e3;
220
222
  var PROJECTS_DIR_NAME = "projects";
221
223
  var DB_FILE_NAME = "context.db";
@@ -240,6 +242,7 @@ var RUN_LABEL_PREFIX = "run.mjs:";
240
242
  var SEARCH_WRAPPER_FILE = "search.mjs";
241
243
  var RUN_WRAPPER_AGENT = "claude-code";
242
244
  var HOST_SESSION_ENV = Object.freeze({ "claude-code": "CLAUDE_CODE_SESSION_ID" });
245
+ var HOST_SESSION_META = Object.freeze({ zcode: "session_id" });
243
246
  var NODE_MIN = "24.15.0";
244
247
  var DATA_ROOT = "~/.context-mode";
245
248
  var DATA_DIR_ENV = "CONTEXT_MODE_DATA_DIR";
@@ -264,6 +267,7 @@ var FRONTMATTER_FENCE = "---";
264
267
  var FRONTMATTER_TOOLS_KEY = "tools";
265
268
  var FRONTMATTER_DISALLOWED_KEY = "disallowedTools";
266
269
  var MCP_SERVER_TOOL_PREFIX = "mcp__";
270
+ var PLUGIN_CALL_ID_PREFIX = "toolu_plugin_";
267
271
  var MCP_NAME_JOIN = "__";
268
272
  var GEMINI_MCP_PREFIX = "mcp_";
269
273
  var GEMINI_NAME_EXTRA_CHARS = "_-.:";
@@ -389,6 +393,8 @@ var RECALL_BUDGET_BYTES = 2048;
389
393
  var RECALL_MIN_SCORE = 5;
390
394
  var RECALL_MAX_ROWS = 340;
391
395
  var COMPACTED_META_PREFIX = "compacted:";
396
+ var BET_META_PREFIX = "bet:";
397
+ var LOSTBET_META_PREFIX = "lostbet:";
392
398
  var RECALL_UNITS_SEEN_META_PREFIX = "recall_units_seen:";
393
399
  var UNITS_ANCESTOR_FACTOR = 8;
394
400
  var RECALL_QUERY_MAX_TERMS = 64;
@@ -485,7 +491,7 @@ var DECISION_ANSWERS_KEY = "answers";
485
491
  var DECISION_OPTION_KEY = "option";
486
492
  var DECISION_LABEL_JOIN = " | ";
487
493
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
488
- var BUNDLE_SHA = true ? "1fce537096e8e2b7d1924c2b5ff2b83287f157ee" : void 0;
494
+ var BUNDLE_SHA = true ? "f41c429ae530a3fec5bda3c12a8ecdc2a5f14ada" : void 0;
489
495
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
490
496
  var DOCTOR_LABEL = Object.freeze({
491
497
  D1: "version",
@@ -596,6 +602,10 @@ function D7_DETAIL(got) {
596
602
  return `resolved project source ${got} does not match the host's actual cwd`;
597
603
  }
598
604
  var D7_FIX = "restart the agent in the correct directory";
605
+ function D7_NO_PROJECT_DETAIL(kind) {
606
+ return `Project source ${kind} is missing`;
607
+ }
608
+ var DOCTOR_NEEDS_PROJECT_DETAIL = "runs once the project resolves; D7 names the project source";
599
609
  function D8_STALE_SCHEMA_DETAIL(got, want) {
600
610
  return `stale schema (v${got}, expected v${want})`;
601
611
  }
@@ -921,6 +931,7 @@ var OMP_CONTENT_INFO = "OMP keeps tool output in content; context-mode writes it
921
931
  var OMP_PRINT_MODE_INFO = "Print mode sends no prompt event. Use omp or omp --mode rpc to keep prompts.";
922
932
  var OMP_SCRIPTS_INFO = "Add < /dev/null in scripts.";
923
933
  var OMP_IMPORT_INFO = (claude, mcp) => `OMP also imports context-mode from ${claude}. To run it once, add "context-mode" to disabledServers in ${mcp}.`;
934
+ var REPLACE_TRIGGER_RETIRED_INFO = (where) => `${REPLACE_TRIGGER_ENV} in ${where} is no longer read: context-mode stores every tool output over ${REPLACE_TRIGGER_BYTES} B whole and ctx_search reads it back. You can remove that line from ${where}.`;
924
935
  var PI_CURRENT_MAJOR = 2;
925
936
  var V1_OPENCODE_PLUGIN_SPEC = "context-mode";
926
937
  var V1_TMP_PREFIX = "context-mode-";
@@ -940,6 +951,10 @@ var OPENCODE_CONFIG_DIR_ENV = "OPENCODE_CONFIG_DIR";
940
951
  var APPDATA_ENV = "APPDATA";
941
952
  var VSCODE_USER_DIR_SEGMENTS = Object.freeze(["Code", "User"]);
942
953
  var XDG_CONFIG_HOME_ENV = "XDG_CONFIG_HOME";
954
+ var XDG_DATA_HOME_ENV = "XDG_DATA_HOME";
955
+ var PI_CONFIG_DIR_ENV = "PI_CONFIG_DIR";
956
+ var OMP_APP_DIR = "omp";
957
+ var OMP_PLUGINS_DIR = "plugins";
943
958
  var CONFIG_TOML_FILE = "config.toml";
944
959
  var CONFIG_JSON_FILE = "config.json";
945
960
  var ZCODE_CLI_DIR = "cli";
@@ -1155,7 +1170,8 @@ var OPENCODE_EVENTS = {
1155
1170
  var SHELL_TOOL_NAME = "bash";
1156
1171
  var READ_TOOL_NAME = "read";
1157
1172
  var SHELL_TOOL_NAMES = Object.freeze([SHELL_TOOL_NAME, "shell"]);
1158
- var NATIVE_TO_CANONICAL = { webfetch: "WebFetch", [READ_TOOL_NAME]: "Read", ...Object.fromEntries(SHELL_TOOL_NAMES.map((n) => [n, "Bash"])) };
1173
+ var SKILL_TOOL_NAME = "skill";
1174
+ var NATIVE_TO_CANONICAL = { webfetch: "WebFetch", [READ_TOOL_NAME]: "Read", [SKILL_TOOL_NAME]: "Skill", ...Object.fromEntries(SHELL_TOOL_NAMES.map((n) => [n, "Bash"])) };
1159
1175
  function toCanonicalTool(name) {
1160
1176
  if (name.startsWith(OWN_WIRE_PREFIX)) return name.slice(OWN_WIRE_PREFIX.length);
1161
1177
  return Object.prototype.hasOwnProperty.call(NATIVE_TO_CANONICAL, name) ? NATIVE_TO_CANONICAL[name] : name;
@@ -1220,7 +1236,8 @@ var ERROR_TEXT = Object.freeze({
1220
1236
  NO_RUNTIME: "No <lang> runtime on PATH. Fix: install it or pick another language.",
1221
1237
  FETCH_FAILED: "Fetch failed: <code>. Fix: check the URL or proxy.",
1222
1238
  SSRF: "Blocked private address <host>. Fix: use a public URL.",
1223
- OUTSIDE_ROOT: "Path <p> is outside the project. Fix: use a path inside <root>.",
1239
+ OUTSIDE_ROOT: "Path <p> is outside the project and the folders added to this session. Fix: use a path inside <root>, or add its folder to the session (Claude Code /add-dir, Codex --add-dir).",
1240
+ // #1398 D-1398-HOST-ROOTS-1
1224
1241
  INVALID_ARGS: "Invalid argument <field>. Fix: <action>.",
1225
1242
  ONE_OF_INPUT: "Pass exactly one of <names>. Fix: drop the extra field.",
1226
1243
  SPAWN_FAILED: "Failed to start the process: <detail>. Fix: check the command and PATH.",
@@ -1278,7 +1295,7 @@ var CtxError = class extends Error {
1278
1295
  };
1279
1296
 
1280
1297
  // src/core/hooks/dispatch.ts
1281
- import { dirname as dirname4, join as join8, relative as relative3, resolve as resolve8, sep as sep3 } from "node:path";
1298
+ import { dirname as dirname4, join as join9, relative as relative3, resolve as resolve8, sep as sep3 } from "node:path";
1282
1299
 
1283
1300
  // src/core/contracts/agents.ts
1284
1301
  var AGENT_IDS = ["claude-code", "codex", "gemini", "qwen", "copilot-cli", "vscode", "kiro", "zcode", "pi", "opencode", "omp"];
@@ -1289,6 +1306,7 @@ var SHELL_TOOL_NAMES2 = Object.freeze(["Bash", "PowerShell"]);
1289
1306
  var POWERSHELL_TOOL = "PowerShell";
1290
1307
  var SHELL_CANONICAL = "Bash";
1291
1308
  var CLAUDE_SHAPE_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse"];
1309
+ var FAILURE_EVENT = "PostToolUseFailure";
1292
1310
  var MCP_PREFIX = "mcp__";
1293
1311
  var MCP_SEP = "__";
1294
1312
  var CLAUDE_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
@@ -1462,7 +1480,14 @@ function requireFields(raw) {
1462
1480
  }
1463
1481
  function decode2(raw) {
1464
1482
  requireFields(raw);
1465
- const ev = decodeClaudeShape(raw, "claude-code", TOOL_NAME_PREFIX2, CLAUDE_SOURCES);
1483
+ const failure = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT;
1484
+ const payload = failure ? { ...raw, hook_event_name: "PostToolUse" } : raw;
1485
+ const ev = decodeClaudeShape(payload, "claude-code", TOOL_NAME_PREFIX2, CLAUDE_SOURCES);
1486
+ if (failure) {
1487
+ const error40 = raw.error;
1488
+ const text = typeof error40 === "string" ? error40 : error40 === void 0 ? "" : JSON.stringify(error40);
1489
+ ev.result = { isError: true, bytes: Buffer.byteLength(text), text, keep: true };
1490
+ }
1466
1491
  if (ev.tool !== void 0 && ev.tool.name === POWERSHELL_TOOL) ev.tool.canonicalName = SHELL_CANONICAL;
1467
1492
  if (ev.cwd === "") ev.cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd();
1468
1493
  if (ev.event === "PostToolUse" && ev.tool !== void 0 && ev.tool.callId === void 0) {
@@ -1641,9 +1666,9 @@ var NATIVE_TO_CANONICAL3 = {
1641
1666
  grep_search: "Grep",
1642
1667
  web_fetch: "WebFetch"
1643
1668
  };
1644
- var FAILURE_EVENT = "PostToolUseFailure";
1669
+ var FAILURE_EVENT2 = "PostToolUseFailure";
1645
1670
  function decode5(raw) {
1646
- const failure = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT;
1671
+ const failure = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT2;
1647
1672
  const payload = failure ? { ...raw, hook_event_name: "PostToolUse" } : raw;
1648
1673
  const ev = decodeClaudeShape(payload, "qwen", TOOL_NAME_PREFIX5, QWEN_SOURCES);
1649
1674
  if (ev.tool !== void 0 && Object.hasOwn(NATIVE_TO_CANONICAL3, ev.tool.name)) ev.tool.canonicalName = NATIVE_TO_CANONICAL3[ev.tool.name];
@@ -1963,12 +1988,12 @@ var TOOL_NAME_PREFIX9 = "mcp__context-mode__";
1963
1988
  var PLUGIN_TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__";
1964
1989
  var ZCODE_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
1965
1990
  var TWINS = { hook_event_name: "hookEventName", session_id: "sessionId" };
1966
- var FAILURE_EVENT2 = "PostToolUseFailure";
1991
+ var FAILURE_EVENT3 = "PostToolUseFailure";
1967
1992
  function decode9(raw) {
1968
1993
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("zcode: hook payload is not a JSON object");
1969
1994
  const p = { ...raw };
1970
1995
  for (const [snake, camel] of Object.entries(TWINS)) if (p[snake] === void 0) p[snake] = p[camel];
1971
- const failure = p.hook_event_name === FAILURE_EVENT2;
1996
+ const failure = p.hook_event_name === FAILURE_EVENT3;
1972
1997
  if (failure) p.hook_event_name = "PostToolUse";
1973
1998
  const toolName2 = typeof p.tool_name === "string" ? p.tool_name : "";
1974
1999
  const prefix = toolName2.startsWith(PLUGIN_TOOL_NAME_PREFIX) ? PLUGIN_TOOL_NAME_PREFIX : TOOL_NAME_PREFIX9;
@@ -3711,6 +3736,24 @@ function piAgentDirOf(env, home) {
3711
3736
  const dir = env[PI_AGENT_DIR_ENV];
3712
3737
  return dir !== void 0 && dir !== "" ? dir : join(home, ...AGENT_HOME_DIR.pi, PI_AGENT_DIR);
3713
3738
  }
3739
+ function ompConfigRootOf(env, home) {
3740
+ const dir = env[PI_CONFIG_DIR_ENV];
3741
+ return dir !== void 0 && dir !== "" ? join(home, dir) : join(home, ...AGENT_HOME_DIR.omp);
3742
+ }
3743
+ function ompAgentDirOf(env, home) {
3744
+ return join(ompConfigRootOf(env, home), PI_AGENT_DIR);
3745
+ }
3746
+ function ompPluginsDirOf(env, home, platform = process.platform) {
3747
+ const root = ompConfigRootOf(env, home);
3748
+ const xdg = env[XDG_DATA_HOME_ENV];
3749
+ const agent = env[PI_AGENT_DIR_ENV];
3750
+ const defaultAgent = agent === void 0 || agent === "" || resolve2(agent) === join(root, PI_AGENT_DIR);
3751
+ if ((platform === "linux" || platform === "darwin") && defaultAgent && xdg !== void 0 && xdg !== "") {
3752
+ const app = join(xdg, OMP_APP_DIR);
3753
+ if (existsSync(app)) return join(app, OMP_PLUGINS_DIR);
3754
+ }
3755
+ return join(root, OMP_PLUGINS_DIR);
3756
+ }
3714
3757
  function vscodeUserDirOf(env, home, platform = process.platform) {
3715
3758
  const set3 = (v) => v !== void 0 && v !== "";
3716
3759
  const p = platform === "win32" ? win32 : posix;
@@ -4262,7 +4305,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
4262
4305
  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.',
4263
4306
  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.',
4264
4307
  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.',
4265
- ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',
4308
+ ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. Set `source` with queries `[""]` to read that source whole, in order, a full page per call; `More:` gives the next `offset`. When nothing matches, the reply states the scope and how many sources are indexed.',
4266
4309
  ctx_resume: "Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",
4267
4310
  ctx_stats: "Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",
4268
4311
  ctx_doctor: "Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",
@@ -4310,6 +4353,10 @@ function isInside(root, p) {
4310
4353
  }
4311
4354
  return true;
4312
4355
  }
4356
+ function allowedRootOf(containmentRoot, hostRoots, p) {
4357
+ if (isInside(containmentRoot, p)) return containmentRoot;
4358
+ return hostRoots?.find((r) => isInside(r, p));
4359
+ }
4313
4360
  var rootReal = /* @__PURE__ */ new Map();
4314
4361
  function realRoot(root) {
4315
4362
  const hit = rootReal.get(root);
@@ -4738,7 +4785,7 @@ function dumpTarget(name, args) {
4738
4785
  }
4739
4786
 
4740
4787
  // src/core/project/resolve.ts
4741
- import { basename as basename2, dirname as dirname3, join as join6, resolve as resolve6 } from "node:path";
4788
+ import { basename as basename2, dirname as dirname3, isAbsolute as isAbsolute3, join as join6, resolve as resolve6 } from "node:path";
4742
4789
 
4743
4790
  // src/core/project/sha256.ts
4744
4791
  var K = new Uint32Array([
@@ -4893,12 +4940,7 @@ function dirOf(kind, src) {
4893
4940
  }
4894
4941
  }
4895
4942
  function gitDirs(dir) {
4896
- let cur;
4897
- try {
4898
- cur = realpathSync3.native(dir);
4899
- } catch {
4900
- throw new CtxError("NO_GIT_DIR", { path: dir });
4901
- }
4943
+ let cur = nearestRealDir(dir);
4902
4944
  const start = cur;
4903
4945
  for (; ; ) {
4904
4946
  const gitDir = gitDirAt(join6(cur, GIT_DIR_NAME));
@@ -4911,6 +4953,18 @@ function gitDirs(dir) {
4911
4953
  cur = up;
4912
4954
  }
4913
4955
  }
4956
+ function nearestRealDir(dir) {
4957
+ const walk3 = isAbsolute3(dir);
4958
+ for (let d = walk3 ? resolve6(dir) : dir; ; ) {
4959
+ try {
4960
+ return realpathSync3.native(d);
4961
+ } catch {
4962
+ const up = dirname3(d);
4963
+ if (!walk3 || up === d) throw new CtxError("NO_GIT_DIR", { path: dir });
4964
+ d = up;
4965
+ }
4966
+ }
4967
+ }
4914
4968
  function gitDirAt(dotGit) {
4915
4969
  let gitDir;
4916
4970
  try {
@@ -4973,7 +5027,7 @@ function resolveProject(agent, src) {
4973
5027
  },
4974
5028
  worktree,
4975
5029
  get containmentRoot() {
4976
- root ??= plain ?? containmentRootOf(dir, commonDir);
5030
+ root ??= plain ?? containmentRootOf(worktree, commonDir);
4977
5031
  return root;
4978
5032
  },
4979
5033
  agent,
@@ -5083,13 +5137,22 @@ CREATE VIRTUAL TABLE line_units USING fts5(
5083
5137
  var DDL_V6 = `
5084
5138
  UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
5085
5139
  `;
5140
+ var DDL_V7 = `
5141
+ ALTER TABLE sources ADD COLUMN unit_lo INTEGER;
5142
+ ALTER TABLE sources ADD COLUMN unit_hi INTEGER;
5143
+ CREATE INDEX IF NOT EXISTS idx_sources_session ON sources(session_id, id);
5144
+ UPDATE sources SET unit_lo = g.lo, unit_hi = g.hi
5145
+ FROM (SELECT source_id, MIN(rowid) AS lo, MAX(rowid) AS hi FROM line_units GROUP BY source_id) AS g
5146
+ WHERE g.source_id = sources.id;
5147
+ `;
5086
5148
  var MIGRATIONS = [
5087
5149
  { version: 1, sql: DDL },
5088
5150
  { version: 2, sql: DDL_V2 },
5089
5151
  { version: 3, sql: DDL_V3 },
5090
5152
  { version: 4, sql: DDL_V4 },
5091
5153
  { version: 5, sql: DDL_V5 },
5092
- { version: 6, sql: DDL_V6 }
5154
+ { version: 6, sql: DDL_V6 },
5155
+ { version: 7, sql: DDL_V7 }
5093
5156
  ];
5094
5157
  function applyMigrations(db, fromVersion) {
5095
5158
  if (fromVersion === SCHEMA_VERSION2) return;
@@ -5156,26 +5219,26 @@ function errCode(err) {
5156
5219
  return err.code ?? "";
5157
5220
  }
5158
5221
  function publishWithoutLink(tmp, path8) {
5159
- const claim = path8 + DB_PUBLISH_CLAIM_SUFFIX;
5222
+ const claim2 = path8 + DB_PUBLISH_CLAIM_SUFFIX;
5160
5223
  const start = Date.now();
5161
5224
  for (; ; ) {
5162
5225
  if (existsSync3(path8)) return;
5163
5226
  try {
5164
- mkdirSync2(claim);
5227
+ mkdirSync2(claim2);
5165
5228
  } catch (err) {
5166
5229
  if (!DB_CLAIM_BUSY_CODES.includes(errCode(err))) throw err;
5167
5230
  if (Date.now() - start < DB_TIMEOUT_MS) {
5168
5231
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, DB_PUBLISH_POLL_MS);
5169
5232
  continue;
5170
5233
  }
5171
- const held = statSync3(claim, { throwIfNoEntry: false });
5172
- if (held !== void 0 && held.mtimeMs < start) rmSync(claim, { recursive: true, force: true });
5173
- throw new Error(`context.db was not published within ${DB_TIMEOUT_MS} ms: ${claim} was held; open again`);
5234
+ const held = statSync3(claim2, { throwIfNoEntry: false });
5235
+ if (held !== void 0 && held.mtimeMs < start) rmSync(claim2, { recursive: true, force: true });
5236
+ throw new Error(`context.db was not published within ${DB_TIMEOUT_MS} ms: ${claim2} was held; open again`);
5174
5237
  }
5175
5238
  try {
5176
5239
  if (!existsSync3(path8)) renameSync(tmp, path8);
5177
5240
  } finally {
5178
- rmSync(claim, { recursive: true, force: true });
5241
+ rmSync(claim2, { recursive: true, force: true });
5179
5242
  }
5180
5243
  return;
5181
5244
  }
@@ -5289,14 +5352,59 @@ function metaTake(db, key) {
5289
5352
  });
5290
5353
  }
5291
5354
 
5355
+ // src/core/store/lost-bet.ts
5356
+ function lostKey(sessionId, key) {
5357
+ return LOSTBET_META_PREFIX + sessionId + ":" + key;
5358
+ }
5359
+ function isLostBet(db, sessionId, key) {
5360
+ return sessionId !== "" && metaGet(db, lostKey(sessionId, key)) !== null;
5361
+ }
5362
+ function markLostBet(db, sessionId, key, reason, source) {
5363
+ if (sessionId === "" || key === "") return;
5364
+ try {
5365
+ metaSet(db, lostKey(sessionId, key), JSON.stringify({ at: Date.now(), reason, source }));
5366
+ } catch {
5367
+ }
5368
+ }
5369
+ function hasBet(db, sessionId, key) {
5370
+ return sessionId !== "" && metaGet(db, BET_META_PREFIX + sessionId + ":" + key) !== null;
5371
+ }
5372
+ function noteBet(db, sessionId, key, source) {
5373
+ if (sessionId === "" || key === "") return;
5374
+ try {
5375
+ metaSet(db, BET_META_PREFIX + sessionId + ":" + key, source);
5376
+ } catch {
5377
+ }
5378
+ }
5379
+ function clearLostBets(db, sessionId) {
5380
+ if (sessionId === "") return;
5381
+ const lo = LOSTBET_META_PREFIX + sessionId + ":";
5382
+ const hi = LOSTBET_META_PREFIX + sessionId + ";";
5383
+ const run = (h) => {
5384
+ h.raw.prepare("DELETE FROM meta WHERE key >= ? AND key < ?").run(lo, hi);
5385
+ };
5386
+ if (db.raw.isTransaction) run(db);
5387
+ else withWrite(db, run);
5388
+ }
5389
+ function betKeyOfLabel(label2) {
5390
+ if (label2.startsWith(SUBAGENT_SOURCE_PREFIX)) return null;
5391
+ const hash = label2.lastIndexOf("#");
5392
+ if (hash <= 0) return null;
5393
+ const stem = label2.slice(0, hash);
5394
+ const colon = stem.indexOf(":");
5395
+ if (colon <= 0) return null;
5396
+ if (colon + 1 < stem.length || stem.startsWith(MCP_SERVER_TOOL_PREFIX)) return stem;
5397
+ return null;
5398
+ }
5399
+
5292
5400
  // src/core/journal/append.ts
5293
5401
  var COLUMNS = "events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
5294
5402
  var INSERT_SQL = "INSERT INTO " + COLUMNS;
5295
5403
  var INSERT_COST_SQL = "INSERT OR IGNORE INTO " + COLUMNS;
5296
5404
  var COST_SEQ_SQL = "SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";
5297
- function appendEvent(db, row5) {
5405
+ function appendEvent(db, row5, at2) {
5298
5406
  return withWrite(db, (h) => {
5299
- const now = Date.now();
5407
+ const now = at2 ?? Date.now();
5300
5408
  const isCost = row5.kind === "cost";
5301
5409
  const res = h.raw.prepare(isCost ? INSERT_COST_SQL : INSERT_SQL).run(
5302
5410
  row5.session_id,
@@ -7402,18 +7510,6 @@ function reserveSource(db, src, chunks) {
7402
7510
  return Number(row5.id);
7403
7511
  });
7404
7512
  }
7405
- function finishReserved(db, id2, src, chunks, units) {
7406
- try {
7407
- insertChunks(db, id2, src, chunks);
7408
- insertUnits(db, id2, src.sessionId, units);
7409
- } catch (err) {
7410
- withWrite(db, (h) => {
7411
- deleteChunkRows(h.raw, { sourceId: id2 });
7412
- h.raw.prepare("DELETE FROM sources WHERE id = ?").run(id2);
7413
- });
7414
- throw err;
7415
- }
7416
- }
7417
7513
  function insertChunks(db, id2, src, chunks) {
7418
7514
  const batches = [];
7419
7515
  let batch = [];
@@ -7444,11 +7540,13 @@ function deleteChunkRows(raw, scope) {
7444
7540
  if (scope === "all") {
7445
7541
  raw.exec("INSERT INTO chunks_tri(chunks_tri) VALUES ('delete-all')");
7446
7542
  raw.exec("DELETE FROM line_units");
7543
+ raw.exec("UPDATE sources SET unit_lo = NULL, unit_hi = NULL WHERE unit_lo IS NOT NULL");
7447
7544
  return Number(raw.prepare("DELETE FROM chunks").run().changes);
7448
7545
  }
7449
- const [where, arg] = "sourceId" in scope ? ["source_id = ?", scope.sourceId] : ["source_id IN (SELECT id FROM sources WHERE label = ?)", scope.label];
7546
+ const [where, arg, own2] = "sourceId" in scope ? ["source_id = ?", scope.sourceId, "id = ?"] : ["source_id IN (SELECT id FROM sources WHERE label = ?)", scope.label, "label = ?"];
7450
7547
  raw.prepare(TRI_DELETE + " WHERE " + where).run(arg);
7451
7548
  raw.prepare("DELETE FROM line_units WHERE " + where).run(arg);
7549
+ raw.prepare("UPDATE sources SET unit_lo = NULL, unit_hi = NULL WHERE " + own2).run(arg);
7452
7550
  return Number(raw.prepare("DELETE FROM chunks WHERE " + where).run(arg).changes);
7453
7551
  }
7454
7552
  function toMatch(q) {
@@ -7852,43 +7950,53 @@ function parseSourceHandle(s) {
7852
7950
  function pathLabel(p) {
7853
7951
  return p.includes("\\") ? p.split("\\").join("/") : p;
7854
7952
  }
7855
- function labelStored(db, label2) {
7856
- return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label2) !== void 0;
7953
+ var EVERY_ROW = { scope: "project", sessionId: "", worktree: "" };
7954
+ var IN_SCOPE = "(:scope <> 'session' OR session_id = :session_id) AND (:scope <> 'worktree' OR worktree = :worktree)";
7955
+ var scopeArgs = (w) => ({ scope: w.scope, session_id: w.sessionId, worktree: w.worktree });
7956
+ function labelStored(db, label2, w) {
7957
+ return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = :label AND " + IN_SCOPE + " LIMIT 1").get({ label: label2, ...scopeArgs(w) }) !== void 0;
7857
7958
  }
7858
- function storedLabel(db, source) {
7859
- if (labelStored(db, source)) return source;
7959
+ function storedLabel(db, source, w = EVERY_ROW) {
7960
+ if (labelStored(db, source, w)) return source;
7860
7961
  const canon = pathLabel(source);
7861
- return canon !== source && labelStored(db, canon) ? canon : source;
7962
+ return canon !== source && labelStored(db, canon, w) ? canon : source;
7862
7963
  }
7863
- function newestId(db, label2) {
7864
- const row5 = stmt(db.raw, "SELECT id FROM sources WHERE label = ? ORDER BY id DESC LIMIT 1").get(label2);
7964
+ function newestId(db, label2, w) {
7965
+ const row5 = stmt(db.raw, "SELECT id FROM sources WHERE label = :label AND " + IN_SCOPE + " ORDER BY id DESC LIMIT 1").get({ label: label2, ...scopeArgs(w) });
7865
7966
  return row5 === void 0 ? null : Number(row5.id);
7866
7967
  }
7867
- function labelOfId(db, id2) {
7868
- const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id2);
7968
+ function labelOfId(db, id2, w) {
7969
+ const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = :id AND " + IN_SCOPE).get({ id: id2, ...scopeArgs(w) });
7869
7970
  return row5 === void 0 ? null : row5.label;
7870
7971
  }
7871
- function pickSource(db, source, suffix = true) {
7872
- const named2 = storedLabel(db, source);
7972
+ function pickIn(db, source, suffix, w) {
7973
+ const named2 = storedLabel(db, source, w);
7873
7974
  const id2 = parseSourceHandle(source);
7874
- const own2 = newestId(db, named2);
7975
+ const own2 = newestId(db, named2, w);
7875
7976
  if (own2 !== null) {
7876
- const otherLabel = id2 === null || id2 === own2 ? null : labelOfId(db, id2);
7977
+ const otherLabel = id2 === null || id2 === own2 ? null : labelOfId(db, id2, EVERY_ROW);
7877
7978
  return { label: named2, id: own2, via: "label", other: otherLabel === null || otherLabel === named2 ? null : { id: id2, label: otherLabel } };
7878
7979
  }
7879
7980
  if (id2 !== null) {
7880
- const label2 = labelOfId(db, id2);
7981
+ const label2 = labelOfId(db, id2, w);
7881
7982
  if (label2 !== null) return { label: label2, id: id2, via: "handle", other: null };
7882
7983
  }
7883
7984
  if (suffix) {
7884
7985
  const prefix = named2 + LABEL_SUFFIX_SEP;
7885
- const rows = stmt(db.raw, "SELECT id, label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
7986
+ const rows = stmt(db.raw, "SELECT id, label FROM sources WHERE substr(label, 1, :n) = :prefix AND " + IN_SCOPE + " ORDER BY id DESC").all({ n: prefix.length, prefix, ...scopeArgs(w) });
7886
7987
  for (const r of rows) {
7887
7988
  if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named2.length) return { label: r.label, id: Number(r.id), via: "suffix", other: null };
7888
7989
  }
7889
7990
  }
7890
7991
  return { label: source, id: null, via: "none", other: null };
7891
7992
  }
7993
+ function pickSource(db, source, suffix = true, w = EVERY_ROW) {
7994
+ if (w.scope !== "project") {
7995
+ const here = pickIn(db, source, suffix, w);
7996
+ if (here.via !== "none") return here;
7997
+ }
7998
+ return pickIn(db, source, suffix, EVERY_ROW);
7999
+ }
7892
8000
  function collisionLine(value, pick2) {
7893
8001
  if (pick2.other === null || pick2.id === null) return null;
7894
8002
  return "Source " + JSON.stringify(value) + ": used the label " + shownLabel(pick2.label, null) + " (" + sourceHandle(pick2.id) + "); handle " + sourceHandle(pick2.other.id) + " is " + shownLabel(pick2.other.label, null) + (isLongLabel(pick2.other.label) ? ", search it by its full label." : ", search it with source:" + JSON.stringify(pick2.other.label) + ".");
@@ -7955,10 +8063,15 @@ function insertUnits(db, sourceId, sessionId, units) {
7955
8063
  const from = start;
7956
8064
  withWrite(db, (h) => {
7957
8065
  const ins = h.raw.prepare("INSERT INTO line_units(body, source_id, session_id, ord) VALUES (?, ?, ?, ?)");
8066
+ let lo = Number.MAX_SAFE_INTEGER;
8067
+ let hi = 0;
7958
8068
  for (let i = from; i < end; i++) {
7959
8069
  const u = units[i];
7960
- ins.run(u.body, sourceId, sessionId, u.ord);
8070
+ const rid = Number(ins.run(u.body, sourceId, sessionId, u.ord).lastInsertRowid);
8071
+ if (rid < lo) lo = rid;
8072
+ if (rid > hi) hi = rid;
7961
8073
  }
8074
+ h.raw.prepare("UPDATE sources SET unit_lo = min(coalesce(unit_lo, ?), ?), unit_hi = max(coalesce(unit_hi, ?), ?) WHERE id = ?").run(lo, lo, hi, hi, sourceId);
7962
8075
  });
7963
8076
  start = end;
7964
8077
  }
@@ -7990,48 +8103,25 @@ function readMaxSourceId(db) {
7990
8103
  function queryUnits(db, sessionId, q, limit, maxSourceId = Number.MAX_SAFE_INTEGER) {
7991
8104
  const match = searchTerms(q).join(" OR ");
7992
8105
  if (match === "" || sessionId === "") return [];
7993
- const rows = db.raw.prepare(
7994
- "SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? AND s.id <= ? ORDER BY bm25(line_units) LIMIT ?"
7995
- ).all(match, sessionId, maxSourceId, limit);
8106
+ const span2 = stmt(
8107
+ db.raw,
8108
+ "SELECT MIN(unit_lo) AS lo, MAX(unit_hi) AS hi FROM sources WHERE session_id = ? AND id <= ? AND unit_lo IS NOT NULL"
8109
+ ).get(sessionId, maxSourceId);
8110
+ if (span2 === void 0 || span2.lo === null || span2.hi === null) return [];
8111
+ const rows = stmt(
8112
+ db.raw,
8113
+ "SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.rowid BETWEEN ? AND ? AND u.session_id = ? AND s.id <= ? ORDER BY bm25(line_units) LIMIT ?"
8114
+ ).all(match, span2.lo, span2.hi, sessionId, maxSourceId, limit);
7996
8115
  return rows.map((r) => ({ sourceId: Number(r.source_id), ord: Number(r.ord), label: r.label, body: r.body, score: r.score }));
7997
8116
  }
7998
8117
 
7999
- // src/core/index/units.ts
8000
- function indentOf(line) {
8001
- let n = 0;
8002
- while (n < line.length && (line[n] === " " || line[n] === " ")) n++;
8003
- return n;
8004
- }
8005
- function buildUnits(text) {
8006
- const lines = text.split("\n");
8007
- const stack2 = [];
8008
- const out = [];
8009
- let left = UNITS_ANCESTOR_FACTOR * Buffer.byteLength(text, "utf8");
8010
- for (let i = 0; i < lines.length; i++) {
8011
- const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
8012
- const indent = indentOf(line);
8013
- if (indent === line.length) continue;
8014
- while (stack2.length > 0 && stack2[stack2.length - 1].indent >= indent) stack2.pop();
8015
- const bytes5 = Buffer.byteLength(line, "utf8");
8016
- let size = bytes5;
8017
- let from = stack2.length;
8018
- while (from > 0) {
8019
- const add = stack2[from - 1].bytes + 1;
8020
- if (size + add > RECALL_BUDGET_BYTES || size - bytes5 + add > left) break;
8021
- size += add;
8022
- from--;
8023
- }
8024
- left -= size - bytes5;
8025
- out.push({ ord: i, body: [...stack2.slice(from).map((s) => s.line), line].join("\n") });
8026
- stack2.push({ indent, line, bytes: bytes5 });
8027
- }
8028
- return out;
8029
- }
8030
-
8031
8118
  // src/core/compaction/candidates.ts
8032
8119
  function firstLine2(body) {
8033
- const nl = body.indexOf("\n");
8034
- return (nl < 0 ? body : body.slice(0, nl)).replaceAll("\r", " ");
8120
+ const i = body.length - body.trimStart().length;
8121
+ if (i === body.length) return "";
8122
+ const start = i === 0 ? 0 : body.lastIndexOf("\n", i) + 1;
8123
+ const nl = body.indexOf("\n", i);
8124
+ return (start === 0 && nl < 0 ? body : body.slice(start, nl < 0 ? body.length : nl)).replaceAll("\r", " ");
8035
8125
  }
8036
8126
  function make(section, row5, text, repeatCount, query) {
8037
8127
  const bytes5 = Buffer.byteLength(text, "utf8");
@@ -8574,7 +8664,7 @@ function cutPoint(src, start, end, scratch) {
8574
8664
  const r = encoder.encodeInto(src.slice(start, limit), scratch);
8575
8665
  return { end: start + r.read, written: r.written };
8576
8666
  }
8577
- function merge(src, blocks, join27, cap, lineCut) {
8667
+ function merge(src, blocks, join28, cap, lineCut) {
8578
8668
  const out = [];
8579
8669
  const scratch = new Uint8Array(cap);
8580
8670
  let wide;
@@ -8584,7 +8674,7 @@ function merge(src, blocks, join27, cap, lineCut) {
8584
8674
  out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
8585
8675
  };
8586
8676
  for (const b of blocks) {
8587
- if (cur !== void 0 && !join27) {
8677
+ if (cur !== void 0 && !join28) {
8588
8678
  emit(cur.start, cur.end, curBytes);
8589
8679
  cur = void 0;
8590
8680
  }
@@ -8905,37 +8995,255 @@ function lineShape(text) {
8905
8995
  return { header, units };
8906
8996
  }
8907
8997
 
8908
- // src/core/index/text.ts
8909
- function storeText(db, project, sessionId, sourceKind, label2, text, kind, chunks = chunkText(text, kind)) {
8910
- const sourceId = ftsInsert(db, {
8911
- projectKey: project.projectKey,
8912
- sessionId,
8913
- worktree: project.worktree,
8914
- agent: project.agent,
8915
- kind: sourceKind,
8916
- label: label2,
8917
- bytes: Buffer.byteLength(text, "utf8"),
8918
- chunkCount: chunks.length,
8919
- createdAt: Date.now()
8920
- }, chunks);
8921
- return { sourceId, chunks: chunks.length };
8998
+ // src/core/hooks/spool.ts
8999
+ import { join as join7 } from "node:path";
9000
+
9001
+ // src/core/index/units.ts
9002
+ function indentOf(line) {
9003
+ let n = 0;
9004
+ while (n < line.length && (line[n] === " " || line[n] === " ")) n++;
9005
+ return n;
8922
9006
  }
8923
- function indexText(db, ctx, sessionId, source, text, kind, chunks) {
8924
- return storeText(db, ctx, sessionId, "content", source, text, kind, chunks);
9007
+ function buildUnits(text) {
9008
+ const lines = text.split("\n");
9009
+ const stack2 = [];
9010
+ const out = [];
9011
+ let left = UNITS_ANCESTOR_FACTOR * Buffer.byteLength(text, "utf8");
9012
+ for (let i = 0; i < lines.length; i++) {
9013
+ const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
9014
+ const indent = indentOf(line);
9015
+ if (indent === line.length) continue;
9016
+ while (stack2.length > 0 && stack2[stack2.length - 1].indent >= indent) stack2.pop();
9017
+ const bytes5 = Buffer.byteLength(line, "utf8");
9018
+ let size = bytes5;
9019
+ let from = stack2.length;
9020
+ while (from > 0) {
9021
+ const add = stack2[from - 1].bytes + 1;
9022
+ if (size + add > RECALL_BUDGET_BYTES || size - bytes5 + add > left) break;
9023
+ size += add;
9024
+ from--;
9025
+ }
9026
+ left -= size - bytes5;
9027
+ out.push({ ord: i, body: [...stack2.slice(from).map((s) => s.line), line].join("\n") });
9028
+ stack2.push({ indent, line, bytes: bytes5 });
9029
+ }
9030
+ return out;
8925
9031
  }
8926
9032
 
8927
- // src/core/hooks/detached.ts
8928
- async function write(project, row5) {
9033
+ // src/core/hooks/spool.ts
9034
+ var { mkdirSync: mkdirSync3, readdirSync: readdirSync3, readFileSync: readFileSync5, renameSync: renameSync2, statSync: statSync4, unlinkSync, utimesSync, writeFileSync } = process.getBuiltinModule("node:fs");
9035
+ var SEEN_TAG = ".seen";
9036
+ var OP_SUFFIX = ".json";
9037
+ var CLAIM_SUFFIX = ".claim";
9038
+ var TMP_SUFFIX = ".tmp";
9039
+ var BAD_SUFFIX = ".bad";
9040
+ var NAME_TIME_DIGITS = 15;
9041
+ var NAME_SEQ_DIGITS = 6;
9042
+ var nameSeq = 0;
9043
+ function isBusy(err) {
9044
+ const code = err?.errcode;
9045
+ return typeof code === "number" && (code & SQLITE_PRIMARY_CODE_MASK) === SQLITE_BUSY_CODE;
9046
+ }
9047
+ function message(err) {
9048
+ return err instanceof Error ? err.message : String(err);
9049
+ }
9050
+ async function hookDb(project) {
9051
+ const db = await openDb(project);
9052
+ db.raw.exec("PRAGMA busy_timeout = " + String(HOOK_BUSY_MS));
9053
+ return db;
9054
+ }
9055
+ function spoolDir(project) {
9056
+ return join7(project.projectDir, HOOK_SPOOL_DIR);
9057
+ }
9058
+ function spool(project, op) {
9059
+ const dir = spoolDir(project);
9060
+ mkdirSync3(dir, { recursive: true });
9061
+ const name = String(Date.now()).padStart(NAME_TIME_DIGITS, "0") + "-" + String(process.pid) + "-" + String(nameSeq++).padStart(NAME_SEQ_DIGITS, "0");
9062
+ const tmp = join7(dir, name + TMP_SUFFIX);
9063
+ writeFileSync(tmp, JSON.stringify(op));
9064
+ renameSync2(tmp, join7(dir, name + (op.t === "seen" ? SEEN_TAG : "") + OP_SUFFIX));
9065
+ }
9066
+ function runOp(db, op, chunks, cur) {
9067
+ if (op.t === "row") {
9068
+ appendEvent(db, op.row, op.at);
9069
+ return null;
9070
+ }
9071
+ if (op.t === "seen") {
9072
+ withWrite(db, (h) => {
9073
+ const have = parseList(metaGet(h, op.key));
9074
+ const add = op.add.filter((v) => !have.includes(v));
9075
+ if (add.length > 0) metaSet(h, op.key, JSON.stringify([...have, ...add]));
9076
+ });
9077
+ return null;
9078
+ }
9079
+ const c = chunks ?? chunkText(op.text, "text", op.max);
9080
+ let id2 = op.id;
9081
+ if (id2 === null) {
9082
+ id2 = reserveSource(db, op.src, c);
9083
+ cur.op = { ...op, id: id2 };
9084
+ } else if (chunks === void 0) {
9085
+ const sid = id2;
9086
+ const gone = withWrite(db, (h) => {
9087
+ if (h.raw.prepare("SELECT 1 AS x FROM sources WHERE id = ?").get(sid) === void 0) return true;
9088
+ deleteChunkRows(h.raw, { sourceId: sid });
9089
+ return false;
9090
+ });
9091
+ if (gone) return null;
9092
+ }
9093
+ try {
9094
+ insertChunks(db, id2, op.src, c);
9095
+ if (op.units) insertUnits(db, id2, op.src.sessionId, buildUnits(op.text));
9096
+ } catch (err) {
9097
+ if (isBusy(err)) throw err;
9098
+ const sid = id2;
9099
+ withWrite(db, (h) => {
9100
+ deleteChunkRows(h.raw, { sourceId: sid });
9101
+ h.raw.prepare("DELETE FROM sources WHERE id = ?").run(sid);
9102
+ });
9103
+ throw err;
9104
+ }
9105
+ return id2;
9106
+ }
9107
+ function parseList(value) {
9108
+ if (value === null) return [];
9109
+ try {
9110
+ const v = JSON.parse(value);
9111
+ return Array.isArray(v) ? v.filter((x) => typeof x === "number" || typeof x === "string") : [];
9112
+ } catch {
9113
+ return [];
9114
+ }
9115
+ }
9116
+ function readSeen(project, db, key) {
9117
+ const out = [];
9118
+ const dir = spoolDir(project);
9119
+ let names = [];
9120
+ try {
9121
+ names = readdirSync3(dir);
9122
+ } catch {
9123
+ }
9124
+ for (const name of names) {
9125
+ const base = name.endsWith(CLAIM_SUFFIX) ? name.slice(0, -CLAIM_SUFFIX.length) : name;
9126
+ if (!base.endsWith(SEEN_TAG + OP_SUFFIX)) continue;
9127
+ let op = null;
9128
+ for (const n of [name, base + CLAIM_SUFFIX, base]) {
9129
+ try {
9130
+ op = JSON.parse(readFileSync5(join7(dir, n), "utf8"));
9131
+ break;
9132
+ } catch {
9133
+ }
9134
+ }
9135
+ if (op !== null && op.t === "seen" && op.key === key) out.push(...op.add);
9136
+ }
9137
+ for (const v of parseList(metaGet(db, key))) if (!out.includes(v)) out.push(v);
9138
+ return out;
9139
+ }
9140
+ var busyUntil = 0;
9141
+ function writeOrSpool(project, db, op, chunks) {
9142
+ const cur = { op };
8929
9143
  try {
8930
- const db = await openDb(project);
8931
- appendEvent(db, row5);
9144
+ return runOp(db, op, chunks, cur);
8932
9145
  } catch (err) {
8933
- const message3 = err instanceof Error ? err.message : String(err);
8934
- process.stderr.write("hooks: journal write failed: " + message3 + "\n");
9146
+ if (!isBusy(err)) throw err;
9147
+ busyUntil = Date.now() + HOOK_BUSY_MS;
9148
+ spool(project, cur.op);
9149
+ return cur.op.t === "src" ? cur.op.id : null;
9150
+ }
9151
+ }
9152
+ function writeDetached(project, op, what, chunks) {
9153
+ void (async () => {
9154
+ try {
9155
+ const db = await hookDb(project);
9156
+ if (Date.now() < busyUntil) {
9157
+ spool(project, op);
9158
+ } else if (drain(project, db)) {
9159
+ busyUntil = Date.now() + HOOK_BUSY_MS;
9160
+ spool(project, op);
9161
+ } else {
9162
+ writeOrSpool(project, db, op, chunks);
9163
+ }
9164
+ } catch (err) {
9165
+ try {
9166
+ if (!isBusy(err)) throw err;
9167
+ busyUntil = Date.now() + HOOK_BUSY_MS;
9168
+ spool(project, op);
9169
+ } catch (e) {
9170
+ process.stderr.write("hooks: " + what + " write failed: " + message(e) + "\n");
9171
+ }
9172
+ }
9173
+ })();
9174
+ }
9175
+ function claim(dir, name) {
9176
+ let base = name;
9177
+ if (name.endsWith(OP_SUFFIX + CLAIM_SUFFIX)) {
9178
+ const path8 = join7(dir, name);
9179
+ try {
9180
+ if (Date.now() - statSync4(path8).mtimeMs < SPOOL_CLAIM_STALE_MS) return null;
9181
+ base = name.slice(0, -CLAIM_SUFFIX.length);
9182
+ renameSync2(path8, join7(dir, base));
9183
+ } catch {
9184
+ return null;
9185
+ }
9186
+ } else if (!name.endsWith(OP_SUFFIX)) {
9187
+ return null;
9188
+ }
9189
+ const claimed = join7(dir, base + CLAIM_SUFFIX);
9190
+ try {
9191
+ renameSync2(join7(dir, base), claimed);
9192
+ const now = /* @__PURE__ */ new Date();
9193
+ utimesSync(claimed, now, now);
9194
+ return claimed;
9195
+ } catch {
9196
+ return null;
9197
+ }
9198
+ }
9199
+ function drain(project, db) {
9200
+ const dir = spoolDir(project);
9201
+ let names;
9202
+ try {
9203
+ names = readdirSync3(dir);
9204
+ } catch {
9205
+ return false;
9206
+ }
9207
+ const start = Date.now();
9208
+ for (const name of names.sort()) {
9209
+ if (Date.now() - start > SPOOL_DRAIN_MS) return false;
9210
+ const claimed = claim(dir, name);
9211
+ if (claimed === null) continue;
9212
+ const base = claimed.slice(0, -CLAIM_SUFFIX.length);
9213
+ let op;
9214
+ try {
9215
+ op = JSON.parse(readFileSync5(claimed, "utf8"));
9216
+ } catch (err) {
9217
+ process.stderr.write("hooks: pending write unreadable: " + message(err) + "\n");
9218
+ renameSync2(claimed, base + BAD_SUFFIX);
9219
+ continue;
9220
+ }
9221
+ const cur = { op };
9222
+ try {
9223
+ runOp(db, op, void 0, cur);
9224
+ } catch (err) {
9225
+ if (isBusy(err)) {
9226
+ if (cur.op === op) {
9227
+ renameSync2(claimed, base);
9228
+ } else {
9229
+ writeFileSync(base + TMP_SUFFIX, JSON.stringify(cur.op));
9230
+ renameSync2(base + TMP_SUFFIX, base);
9231
+ unlinkSync(claimed);
9232
+ }
9233
+ return true;
9234
+ }
9235
+ process.stderr.write("hooks: pending write failed: " + message(err) + "\n");
9236
+ renameSync2(claimed, base + BAD_SUFFIX);
9237
+ continue;
9238
+ }
9239
+ unlinkSync(claimed);
8935
9240
  }
9241
+ return false;
8936
9242
  }
9243
+
9244
+ // src/core/hooks/detached.ts
8937
9245
  function appendDetached(project, sessionId, row5) {
8938
- void write(project, row5);
9246
+ writeDetached(project, { t: "row", row: row5, at: Date.now() }, "journal");
8939
9247
  }
8940
9248
 
8941
9249
  // src/core/hooks/handle-query.ts
@@ -9026,7 +9334,7 @@ function shouldHint(db, sessionId, onceKey, everyN) {
9026
9334
  }
9027
9335
 
9028
9336
  // src/core/hooks/fallback.ts
9029
- import { join as join7, resolve as resolve7 } from "node:path";
9337
+ import { join as join8, resolve as resolve7 } from "node:path";
9030
9338
  var fs = process.getBuiltinModule("node:fs");
9031
9339
  function isRec(v) {
9032
9340
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -9054,9 +9362,9 @@ function homeOf(env) {
9054
9362
  }
9055
9363
  function hookLogPath(env) {
9056
9364
  const dir = env[DATA_DIR_ENV];
9057
- if (dir !== void 0 && dir !== "") return join7(dataRootOf(env, ""), HOOK_ERROR_LOG_FILE);
9365
+ if (dir !== void 0 && dir !== "") return join8(dataRootOf(env, ""), HOOK_ERROR_LOG_FILE);
9058
9366
  const home = homeOf(env);
9059
- return home === "" ? "" : join7(dataRootOf(env, home), HOOK_ERROR_LOG_FILE);
9367
+ return home === "" ? "" : join8(dataRootOf(env, home), HOOK_ERROR_LOG_FILE);
9060
9368
  }
9061
9369
  function errorLabel(err) {
9062
9370
  const code = isRec(err) ? err.code : void 0;
@@ -9067,7 +9375,7 @@ function logHookError(env, agent, stage, err) {
9067
9375
  try {
9068
9376
  const file2 = hookLogPath(env);
9069
9377
  if (file2 === "") return;
9070
- fs.mkdirSync(join7(file2, ".."), { recursive: true });
9378
+ fs.mkdirSync(join8(file2, ".."), { recursive: true });
9071
9379
  const line = JSON.stringify({
9072
9380
  ts: (/* @__PURE__ */ new Date()).toISOString(),
9073
9381
  agent,
@@ -9181,14 +9489,14 @@ function failureOutput(agent, raw, err, cwdFallback = "") {
9181
9489
  var { read: read2, writeSync } = process.getBuiltinModule("node:fs");
9182
9490
 
9183
9491
  // src/core/hooks/dispatch.ts
9184
- var { lstatSync: lstatSync2, readFileSync: readFileSync5 } = process.getBuiltinModule("node:fs");
9492
+ var { lstatSync: lstatSync2, readFileSync: readFileSync6 } = process.getBuiltinModule("node:fs");
9185
9493
  var ALLOW2 = { kind: "allow" };
9186
9494
  var EMPTY5 = { stdout: "", exitCode: 0 };
9187
9495
  var DIGIT_0 = 48;
9188
9496
  function isAgentId(s) {
9189
9497
  return AGENT_IDS.includes(s);
9190
9498
  }
9191
- function message(err) {
9499
+ function message2(err) {
9192
9500
  return err instanceof Error ? err.message : String(err);
9193
9501
  }
9194
9502
  function str2(v) {
@@ -9202,7 +9510,7 @@ async function handleHook(agent, raw, env) {
9202
9510
  const row5 = getAdapter(agent);
9203
9511
  const report2 = (stage, err, line) => {
9204
9512
  logHookError(env, agent, stage, err);
9205
- process.stderr.write(line ?? "hooks: " + stage + " failed: " + message(err) + "\n");
9513
+ process.stderr.write(line ?? "hooks: " + stage + " failed: " + message2(err) + "\n");
9206
9514
  };
9207
9515
  const fail7 = (stage, err, line) => {
9208
9516
  report2(stage, err, line);
@@ -9228,7 +9536,7 @@ async function handleHook(agent, raw, env) {
9228
9536
  const argv = agent === "vscode" ? [WORKSPACE_FOLDER_FLAG, ev.cwd] : process.argv;
9229
9537
  project = resolveProject(agent, { env, argv, cwd: ev.cwd, piCwd: getAdapter(agent).projectSource === "pi:ctx.cwd" ? ev.cwd : void 0 });
9230
9538
  } catch (err) {
9231
- return fail7("project", err, "hooks: no project: " + String(err.code ?? "ERROR") + " " + message(err) + "\n");
9539
+ return fail7("project", err, "hooks: no project: " + String(err.code ?? "ERROR") + " " + message2(err) + "\n");
9232
9540
  }
9233
9541
  let decision;
9234
9542
  const settle = {};
@@ -9273,14 +9581,15 @@ function compactText(db, ev, row5) {
9273
9581
  return renderState(readSessionEvents(db, ev.sessionId), ev.turn ?? 0, void 0, row5.toolNamePrefix);
9274
9582
  }
9275
9583
  async function sessionStart(ev, row5, project) {
9276
- if (ev.source === "compact" && hasRecall(row5)) markCompacted(await openDb(project), ev.sessionId);
9584
+ if (ev.source === "compact" && hasRecall(row5)) markCompacted(await hookDb(project), ev.sessionId);
9585
+ if (ev.source === "compact") endLostBets(await hookDb(project), ev.sessionId);
9277
9586
  if (ev.source === "compact" && row5.compactDelivery === "sessionstart") {
9278
- const db2 = await openDb(project);
9587
+ const db2 = await hookDb(project);
9279
9588
  const onceKey = COMPACT_STATE_KEY + ":" + lastSessionSeq(db2, ev.sessionId);
9280
9589
  if (!shouldHint(db2, ev.sessionId, onceKey)) return ALLOW2;
9281
9590
  return { kind: "hint", text: compactText(db2, ev, row5), onceKey };
9282
9591
  }
9283
- const db = await openDb(project);
9592
+ const db = await hookDb(project);
9284
9593
  if (row5.compactDelivery === "opencode-cache" && metaTake(db, PENDING_COMPACT_META_PREFIX + ev.sessionId) !== null) {
9285
9594
  return { kind: "hint", text: compactText(db, ev, row5), onceKey: PENDING_COMPACT_KEY };
9286
9595
  }
@@ -9308,7 +9617,7 @@ async function userPromptSubmit(ev, row5, project) {
9308
9617
  });
9309
9618
  echoDetached(ev, project, body);
9310
9619
  if (row5.compactDelivery === "pending-flag") {
9311
- const db = await openDb(project);
9620
+ const db = await hookDb(project);
9312
9621
  if (metaTake(db, PENDING_COMPACT_META_PREFIX + ev.sessionId) !== null) {
9313
9622
  return { kind: "hint", text: compactText(db, ev, row5), onceKey: PENDING_COMPACT_KEY };
9314
9623
  }
@@ -9318,7 +9627,7 @@ async function userPromptSubmit(ev, row5, project) {
9318
9627
  }
9319
9628
  async function firstTurnResume(ev, row5, project) {
9320
9629
  if (row5.eventMap.SessionStart !== void 0 || ev.sessionId === "") return null;
9321
- const db = await openDb(project);
9630
+ const db = await hookDb(project);
9322
9631
  if (hasSessionRows(db, ev.sessionId)) return null;
9323
9632
  if (!shouldHint(db, ev.sessionId, RESUME_HINT_KEY)) return null;
9324
9633
  if (!hasAgentRows(db, project.worktree, ev.agent)) return null;
@@ -9342,40 +9651,22 @@ function compactBoundary(value) {
9342
9651
  return all;
9343
9652
  }
9344
9653
  }
9345
- function seenSeqs(value) {
9346
- if (value === null) return [];
9347
- try {
9348
- const v = JSON.parse(value);
9349
- return Array.isArray(v) ? v.filter((n) => typeof n === "number") : [];
9350
- } catch {
9351
- return [];
9352
- }
9353
- }
9354
- function seenUnitKeys(value) {
9355
- if (value === null) return [];
9356
- try {
9357
- const v = JSON.parse(value);
9358
- return Array.isArray(v) ? v.filter((k) => typeof k === "string") : [];
9359
- } catch {
9360
- return [];
9361
- }
9362
- }
9363
9654
  async function recall(ev, row5, project, prompt) {
9364
9655
  if (!hasRecall(row5) || ev.sessionId === "") return ALLOW2;
9365
- const db = await openDb(project);
9656
+ const db = await hookDb(project);
9366
9657
  const compacted = metaGet(db, COMPACTED_META_PREFIX + ev.sessionId);
9367
9658
  if (compacted === null) return ALLOW2;
9368
9659
  const boundary = compactBoundary(compacted);
9369
9660
  const seenKey = RECALL_SEEN_META_PREFIX + ev.sessionId;
9370
- const seen = seenSeqs(metaGet(db, seenKey));
9661
+ const seen = readSeen(project, db, seenKey).filter((n) => typeof n === "number");
9371
9662
  const unitsKey = RECALL_UNITS_SEEN_META_PREFIX + ev.sessionId;
9372
- const seenUnits = seenUnitKeys(metaGet(db, unitsKey));
9663
+ const seenUnits = readSeen(project, db, unitsKey).filter((k) => typeof k === "string");
9373
9664
  const units = queryUnits(db, ev.sessionId, recallQueryText(prompt), RECALL_UNIT_CANDIDATES, boundary.source);
9374
9665
  const rows = readRecallRows(db, ev.sessionId, project.worktree, RECALL_MAX_ROWS, boundary.seq);
9375
9666
  const picked = pickRecall(rows, prompt, new Set(seen), units, new Set(seenUnits));
9376
9667
  if (picked.text === "") return ALLOW2;
9377
- if (picked.seqs.length > 0) metaSet(db, seenKey, JSON.stringify([...seen, ...picked.seqs]));
9378
- if (picked.units !== void 0) metaSet(db, unitsKey, JSON.stringify([...seenUnits, ...picked.units]));
9668
+ if (picked.seqs.length > 0) writeDetached(project, { t: "seen", key: seenKey, add: picked.seqs }, "recall");
9669
+ if (picked.units !== void 0) writeDetached(project, { t: "seen", key: unitsKey, add: picked.units }, "recall");
9379
9670
  return { kind: "hint", text: picked.text, onceKey: RECALL_KEY };
9380
9671
  }
9381
9672
  function optionsKey(sessionId) {
@@ -9395,7 +9686,7 @@ function readOptions(value) {
9395
9686
  function echoDetached(ev, project, prompt) {
9396
9687
  if (ev.sessionId === "") return;
9397
9688
  const key = optionsKey(ev.sessionId);
9398
- void openDb(project).then((db) => {
9689
+ void hookDb(project).then((db) => {
9399
9690
  if (metaGet(db, key) === null) return;
9400
9691
  const taken = metaTake(db, key);
9401
9692
  const offered = taken === null ? null : readOptions(taken);
@@ -9403,12 +9694,12 @@ function echoDetached(ev, project, prompt) {
9403
9694
  const part = optionEchoDecision(prompt, offered.labels, offered.seq);
9404
9695
  if (part !== null) writeDecisions(db, ev, project, [part]);
9405
9696
  }).catch((err) => {
9406
- process.stderr.write("hooks: decision write failed: " + message(err) + "\n");
9697
+ process.stderr.write("hooks: decision write failed: " + message2(err) + "\n");
9407
9698
  });
9408
9699
  }
9409
9700
  function writeDecisions(db, ev, project, parts) {
9410
9701
  for (const part of parts) {
9411
- appendEvent(db, {
9702
+ writeOrSpool(project, db, { t: "row", at: Date.now(), row: {
9412
9703
  session_id: ev.sessionId,
9413
9704
  worktree: project.worktree,
9414
9705
  agent: ev.agent,
@@ -9423,22 +9714,22 @@ function writeDecisions(db, ev, project, parts) {
9423
9714
  turn: ev.turn ?? 0,
9424
9715
  sandbox_bytes: 0,
9425
9716
  returned_bytes: 0
9426
- });
9427
- indexText(db, project, ev.sessionId, DECISION_SOURCE, part.body, "text");
9717
+ } });
9718
+ writeOrSpool(project, db, { t: "src", id: null, src: sourceRowOf(project, ev.sessionId, DECISION_SOURCE), text: part.body, max: MAX_CHUNK_BYTES, units: false });
9428
9719
  }
9429
9720
  }
9430
9721
  function askDetached(ev, project, tool, text) {
9431
9722
  const parts = answerDecisions(text);
9432
9723
  const labels = parts.length === 0 ? askOptionLabels(tool.input) : [];
9433
9724
  if (parts.length === 0 && labels.length === 0) return;
9434
- void openDb(project).then((db) => {
9725
+ void hookDb(project).then((db) => {
9435
9726
  if (parts.length > 0) return writeDecisions(db, ev, project, parts);
9436
9727
  const prompts = readSessionEvents(db, ev.sessionId, "prompt");
9437
9728
  const last2 = prompts[prompts.length - 1];
9438
9729
  if (last2 === void 0 || ev.sessionId === "") return;
9439
9730
  metaSet(db, optionsKey(ev.sessionId), JSON.stringify({ seq: last2.seq, labels }));
9440
9731
  }).catch((err) => {
9441
- process.stderr.write("hooks: decision write failed: " + message(err) + "\n");
9732
+ process.stderr.write("hooks: decision write failed: " + message2(err) + "\n");
9442
9733
  });
9443
9734
  }
9444
9735
  function toolSetSources(ev, project, env) {
@@ -9474,7 +9765,7 @@ function caseB(ev, row5, d0, userDeny) {
9474
9765
  if (tool === void 0 || !isShell(tool, row5) || isUserPolicyDeny(d0.reason, row5)) return d0;
9475
9766
  const command = tool.input.command;
9476
9767
  if (typeof command !== "string") return d0;
9477
- const wrapper = '"' + join8(dirname4(process.argv[1] ?? ""), RUN_WRAPPER_FILE) + '"';
9768
+ const wrapper = '"' + join9(dirname4(process.argv[1] ?? ""), RUN_WRAPPER_FILE) + '"';
9478
9769
  const rewritten = [RUN_WRAPPER_NODE, wrapper, b64(command), b64(JSON.stringify(userDeny ?? [])), b64(str2(tool.input.description))].join(" ");
9479
9770
  return { kind: "deny", reason: SUBAGENT_RUN_DENY, rewritten };
9480
9771
  }
@@ -9515,7 +9806,8 @@ async function postToolUse(ev, row5, project, env, settle) {
9515
9806
  const tool = ev.tool;
9516
9807
  if (tool === void 0 || tool.canonicalName.startsWith(OWN_TOOL_PREFIX)) return ALLOW2;
9517
9808
  const result = ev.result ?? { isError: false, bytes: 0 };
9518
- const text = wholeOutput(result, ev.sessionId, env);
9809
+ const whole2 = wholeOutput(result, ev.sessionId, env);
9810
+ const text = whole2.text;
9519
9811
  if (result.persistedPath !== void 0) result.bytes = Buffer.byteLength(text);
9520
9812
  if (tool.canonicalName === DECISION_TOOL) askDetached(ev, project, tool, text);
9521
9813
  const kind = journalKind(tool, row5, result.isError);
@@ -9542,7 +9834,7 @@ async function postToolUse(ev, row5, project, env, settle) {
9542
9834
  };
9543
9835
  let decision;
9544
9836
  try {
9545
- decision = await postReplace(ev, row5, project, env, tool, result, text);
9837
+ decision = await postReplace(ev, row5, project, env, tool, result, text, whole2.file);
9546
9838
  } catch (err) {
9547
9839
  journal(result.bytes);
9548
9840
  throw err;
@@ -9556,19 +9848,25 @@ function ownRead(ev, tool, env) {
9556
9848
  const p = READ_PATH_KEYS.map((k) => tool.input[k]).find((v) => typeof v === "string" && v !== "");
9557
9849
  return p !== void 0 && isOwnFile(ev.agent, ev.cwd, p, env);
9558
9850
  }
9559
- async function postReplace(ev, row5, project, env, tool, result, text) {
9851
+ async function postReplace(ev, row5, project, env, tool, result, text, persistedFile) {
9852
+ if (boundedRead(tool)) {
9853
+ await rangedAfterBet(ev, row5, project, tool);
9854
+ return ALLOW2;
9855
+ }
9560
9856
  if (result.bytes <= REPLACE_TRIGGER_BYTES) return ALLOW2;
9561
- if (boundedRead(tool)) return ALLOW2;
9562
9857
  if (ompRangedRead(ev, tool)) return ALLOW2;
9563
9858
  if (ownRead(ev, tool, env)) return ALLOW2;
9859
+ if (SKILL_LOAD_TOOLS.includes(tool.canonicalName)) return ALLOW2;
9564
9860
  if (result.keep === true) return ALLOW2;
9565
9861
  if (!hasReplace(row5)) return ALLOW2;
9566
9862
  let label2;
9567
9863
  let caller = { ctx: true, shell: true, read: false };
9864
+ let canRead = true;
9568
9865
  if (isSubagentCall(ev)) {
9569
9866
  const set3 = toolSetForAgentType(ev, toolSetSources(ev, project, env));
9570
9867
  const subCase = pickSubagentCase(ev, set3);
9571
9868
  const has3 = (names) => set3 !== null && names.some((n) => set3.includes(n));
9869
+ canRead = has3(row5.nativeTools.read ?? []);
9572
9870
  caller = {
9573
9871
  ctx: subCase === "A",
9574
9872
  shell: has3(row5.nativeTools.shell),
@@ -9581,29 +9879,53 @@ async function postReplace(ev, row5, project, env, tool, result, text) {
9581
9879
  }
9582
9880
  const intent = [tool.input.description, tool.input.command, tool.input.file_path, tool.input.pattern, tool.input.url, tool.name].map(str2).find((v) => v.trim() !== "") ?? tool.canonicalName;
9583
9881
  const chunks = chunkText(text, "text", REPLACE_CHUNK_BYTES);
9584
- const db = await openDb(project);
9882
+ const db = await hookDb(project);
9883
+ const betOn = betKey(ev, tool);
9884
+ if (result.bytes <= OUTPUT_CAP && betOn !== "" && isLostBet(db, ev.sessionId, betOn)) return ALLOW2;
9885
+ const op = { t: "src", id: null, src: sourceRowOf(project, ev.sessionId, label2), text, max: REPLACE_CHUNK_BYTES, units: true };
9585
9886
  let sourceId;
9586
9887
  if (result.bytes <= SYNC_INDEX_MAX_BYTES) {
9587
- sourceId = indexText(db, project, ev.sessionId, label2, text, "text", chunks).sourceId;
9588
- insertUnits(db, sourceId, ev.sessionId, buildUnits(text));
9888
+ sourceId = writeOrSpool(project, db, op, chunks);
9589
9889
  } else {
9590
- sourceId = reserveSource(db, sourceRowOf(project, ev.sessionId, label2), chunks);
9591
- indexDetached(project, ev.sessionId, sourceId, label2, text, chunks);
9890
+ sourceId = reserveOrSpool(project, db, op, chunks);
9891
+ if (sourceId !== null) indexDetached(project, { ...op, id: sourceId }, chunks);
9592
9892
  }
9593
- const handle = sourceHandle(sourceId);
9893
+ if (pluginMcpCall(tool)) return ALLOW2;
9894
+ const handle = sourceId === null ? label2 : sourceHandle(sourceId);
9895
+ if (RANGE_READ_TOOLS.includes(tool.canonicalName) && betOn !== "" && !hasBet(db, ev.sessionId, betOn)) noteBet(db, ev.sessionId, betOn, handle);
9594
9896
  const prompt = await lastPrompt(project, ev.sessionId);
9595
9897
  const rankQuery = prompt.trim() === "" ? void 0 : intent + " " + prompt;
9596
9898
  const handleLine = caller.ctx ? REPLACE_HANDLE_LINE(intent, handle, result.bytes, row5.toolNamePrefix, askedWords(intent, prompt, text)) : SUBAGENT_HANDLE_LINE(handle, result.bytes, caller.read);
9597
9899
  const budget = replaceBudget(handleLine, moreLine2(intent, label2));
9598
- const pointer = handleLine + (caller.shell && ev.agent === RUN_WRAPPER_AGENT ? searchTwin(handle, intent, project) : "");
9900
+ const pointer = handleLine + (caller.shell && ev.agent === RUN_WRAPPER_AGENT && sourceId !== null ? searchTwin(handle, intent, project) : "") + (persistedFile !== void 0 && canRead ? PERSISTED_FILE_LINE(persistedFile) : "");
9599
9901
  const digest = shapeDigest(text, rankQuery ?? intent, SHAPE_RETURN_BYTES);
9600
9902
  if (digest !== null) return { kind: "replace", output: replaceOutput(digest, pointer) };
9601
9903
  const selected = selectChunksInMemory(chunks, intent, budget, label2, rankQuery);
9602
9904
  return { kind: "replace", output: selected.more !== null ? replaceOutput(selected.text, pointer) : selected.text };
9603
9905
  }
9906
+ function betKey(ev, tool) {
9907
+ if (RANGE_READ_TOOLS.includes(tool.canonicalName)) {
9908
+ const p = READ_PATH_KEYS.map((k) => tool.input[k]).find((v) => typeof v === "string" && v !== "");
9909
+ return p === void 0 ? "" : tool.canonicalName + ":" + resolve8(ev.cwd, p);
9910
+ }
9911
+ return betKeyOfLabel(mainLabel(tool, ev)) ?? "";
9912
+ }
9913
+ async function rangedAfterBet(ev, row5, project, tool) {
9914
+ if (ev.sessionId === "" || !hasReplace(row5)) return;
9915
+ const key = betKey(ev, tool);
9916
+ if (key === "") return;
9917
+ try {
9918
+ const db = await hookDb(project);
9919
+ if (hasBet(db, ev.sessionId, key) && !isLostBet(db, ev.sessionId, key)) markLostBet(db, ev.sessionId, key, "ranged-read", tool.callId ?? "");
9920
+ } catch {
9921
+ }
9922
+ }
9923
+ function pluginMcpCall(tool) {
9924
+ return tool.callId !== void 0 && tool.callId.startsWith(PLUGIN_CALL_ID_PREFIX) && tool.name.startsWith(MCP_SERVER_TOOL_PREFIX);
9925
+ }
9604
9926
  function searchTwin(handle, intent, project) {
9605
9927
  const terms = Buffer.byteLength(intent, "utf8") > ECHO_MAX_BYTES ? "" : intent;
9606
- return SEARCH_TWIN_LINE(join8(dirname4(process.argv[1] ?? ""), SEARCH_WRAPPER_FILE), handle, terms, project.worktree);
9928
+ return SEARCH_TWIN_LINE(join9(dirname4(process.argv[1] ?? ""), SEARCH_WRAPPER_FILE), handle, terms, project.worktree);
9607
9929
  }
9608
9930
  function boundedRead(tool) {
9609
9931
  return RANGE_READ_TOOLS.includes(tool.canonicalName) && READ_RANGE_KEYS.some((k) => tool.input[k] !== void 0 && tool.input[k] !== null);
@@ -9663,7 +9985,7 @@ function replaceBudget(handleLine, more) {
9663
9985
  }
9664
9986
  function hostToolResult(file2, sessionId, env) {
9665
9987
  if (sessionId === "" || sessionId.includes(sep3) || sessionId.includes("/")) return false;
9666
- const projects = join8(claudeDirOf(env, homeDirOf(env) ?? ""), PROJECTS_DIR_NAME);
9988
+ const projects = join9(claudeDirOf(env, homeDirOf(env) ?? ""), PROJECTS_DIR_NAME);
9667
9989
  const steps = relative3(projects, resolve8(file2)).split(sep3);
9668
9990
  if (steps.length !== 4 || steps.includes("..") || steps.includes("")) return false;
9669
9991
  if (steps[1] !== sessionId || steps[2] !== CLAUDE_TOOL_RESULTS_DIR_NAME) return false;
@@ -9672,20 +9994,20 @@ function hostToolResult(file2, sessionId, env) {
9672
9994
  }
9673
9995
  function wholeOutput(result, sessionId, env) {
9674
9996
  const head2 = result.text ?? "";
9675
- if (result.persistedPath === void 0) return head2;
9997
+ if (result.persistedPath === void 0) return { text: head2 };
9676
9998
  try {
9677
9999
  if (!hostToolResult(result.persistedPath, sessionId, env)) {
9678
10000
  logHookError(env, "claude-code", "persisted-output", new Error("persisted output path is outside this session's tool-results dir or too large; kept the head"));
9679
- return head2;
10001
+ return { text: head2 };
9680
10002
  }
9681
- return readFileSync5(result.persistedPath, "utf8");
10003
+ return { text: readFileSync6(result.persistedPath, "utf8"), file: result.persistedPath };
9682
10004
  } catch {
9683
- return head2;
10005
+ return { text: head2 };
9684
10006
  }
9685
10007
  }
9686
10008
  async function lastPrompt(project, sessionId) {
9687
10009
  try {
9688
- return readLastPrompt(await openDb(project), sessionId);
10010
+ return readLastPrompt(await hookDb(project), sessionId);
9689
10011
  } catch {
9690
10012
  return "";
9691
10013
  }
@@ -9696,22 +10018,34 @@ function mainLabel(tool, ev) {
9696
10018
  const head2 = (tool.canonicalName + ":" + (nl < 0 ? cmd : cmd.slice(0, nl))).slice(0, SOURCE_LABEL_MAX_CHARS);
9697
10019
  return head2 + "#" + (tool.callId ?? String(ev.turn ?? 0));
9698
10020
  }
9699
- function indexDetached(project, sessionId, sourceId, label2, text, chunks) {
9700
- void openDb(project).then((db) => {
9701
- finishReserved(db, sourceId, sourceRowOf(project, sessionId, label2), chunks, buildUnits(text));
9702
- }).catch((err) => {
9703
- process.stderr.write("hooks: index write failed: " + message(err) + "\n");
9704
- });
10021
+ function indexDetached(project, op, chunks) {
10022
+ writeDetached(project, op, "index", chunks);
10023
+ }
10024
+ function reserveOrSpool(project, db, op, chunks) {
10025
+ try {
10026
+ return reserveSource(db, op.src, chunks);
10027
+ } catch (err) {
10028
+ if (!isBusy(err)) throw err;
10029
+ spool(project, op);
10030
+ return null;
10031
+ }
9705
10032
  }
9706
10033
  function sourceRowOf(project, sessionId, label2) {
9707
10034
  return { sessionId, worktree: project.worktree, agent: project.agent, kind: "content", label: label2, createdAt: Date.now() };
9708
10035
  }
9709
10036
  async function preCompact(ev, row5, project) {
9710
- const db = await openDb(project);
10037
+ const db = await hookDb(project);
9711
10038
  metaSet(db, PENDING_COMPACT_META_PREFIX + ev.sessionId, PENDING_COMPACT_FLAG);
9712
10039
  if (hasRecall(row5)) markCompacted(db, ev.sessionId);
10040
+ endLostBets(db, ev.sessionId);
9713
10041
  return ALLOW2;
9714
10042
  }
10043
+ function endLostBets(db, sessionId) {
10044
+ try {
10045
+ clearLostBets(db, sessionId);
10046
+ } catch {
10047
+ }
10048
+ }
9715
10049
  function usage(ev, project) {
9716
10050
  appendDetached(project, ev.sessionId, {
9717
10051
  session_id: ev.sessionId,
@@ -10733,14 +11067,14 @@ function prefixIssues(path8, issues) {
10733
11067
  return iss;
10734
11068
  });
10735
11069
  }
10736
- function unwrapMessage(message3) {
10737
- return typeof message3 === "string" ? message3 : message3?.message;
11070
+ function unwrapMessage(message4) {
11071
+ return typeof message4 === "string" ? message4 : message4?.message;
10738
11072
  }
10739
11073
  function finalizeIssue(iss, ctx, config2) {
10740
11074
  const full = { ...iss, path: iss.path ?? [] };
10741
11075
  if (!iss.message) {
10742
- const message3 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
10743
- full.message = message3;
11076
+ const message4 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
11077
+ full.message = message4;
10744
11078
  }
10745
11079
  delete full.inst;
10746
11080
  delete full.continue;
@@ -20928,7 +21262,7 @@ function buildChildEnv(parent, extra) {
20928
21262
  }
20929
21263
 
20930
21264
  // src/core/sandbox/runtimes.ts
20931
- import { accessSync, constants as fsConstants, statSync as statSync4 } from "node:fs";
21265
+ import { accessSync, constants as fsConstants, statSync as statSync5 } from "node:fs";
20932
21266
  import path from "node:path";
20933
21267
 
20934
21268
  // src/core/sandbox/path-entries.ts
@@ -20973,7 +21307,7 @@ function fileNames(name, pathExt) {
20973
21307
  function probe(full) {
20974
21308
  let st;
20975
21309
  try {
20976
- st = statSync4(full, { throwIfNoEntry: false });
21310
+ st = statSync5(full, { throwIfNoEntry: false });
20977
21311
  } catch {
20978
21312
  return "unreadable";
20979
21313
  }
@@ -21168,8 +21502,8 @@ function runProcess(argv, o) {
21168
21502
  }
21169
21503
 
21170
21504
  // src/core/index/auto-memory.ts
21171
- import { readdirSync as readdirSync3, readFileSync as readFileSync6, statSync as statSync5 } from "node:fs";
21172
- import { join as join9 } from "node:path";
21505
+ import { readdirSync as readdirSync4, readFileSync as readFileSync7, statSync as statSync6 } from "node:fs";
21506
+ import { join as join10 } from "node:path";
21173
21507
  var MEMORY_FILES = Object.freeze([
21174
21508
  Object.freeze(["CLAUDE.md"]),
21175
21509
  Object.freeze(["CLAUDE.local.md"]),
@@ -21183,7 +21517,7 @@ var KIRO_STEERING = Object.freeze([".kiro", "steering"]);
21183
21517
  var MD = ".md";
21184
21518
  function steeringFiles(worktree) {
21185
21519
  try {
21186
- return readdirSync3(join9(worktree, ...KIRO_STEERING)).filter((n) => n.endsWith(MD)).sort().map((n) => [...KIRO_STEERING, n]);
21520
+ return readdirSync4(join10(worktree, ...KIRO_STEERING)).filter((n) => n.endsWith(MD)).sort().map((n) => [...KIRO_STEERING, n]);
21187
21521
  } catch {
21188
21522
  return [];
21189
21523
  }
@@ -21191,10 +21525,10 @@ function steeringFiles(worktree) {
21191
21525
  function readAutoMemory(project) {
21192
21526
  const rows = [];
21193
21527
  for (const segs of [...MEMORY_FILES, ...steeringFiles(project.worktree)]) {
21194
- const path8 = join9(project.worktree, ...segs);
21528
+ const path8 = join10(project.worktree, ...segs);
21195
21529
  if (!isInside(project.worktree, path8)) continue;
21196
21530
  try {
21197
- const st = statSync5(path8);
21531
+ const st = statSync6(path8);
21198
21532
  if (!st.isFile()) continue;
21199
21533
  rows.push({
21200
21534
  origin: "memory",
@@ -21203,7 +21537,7 @@ function readAutoMemory(project) {
21203
21537
  sourceId: null,
21204
21538
  path: path8,
21205
21539
  label: segs.join("/"),
21206
- text: readFileSync6(path8, "utf8")
21540
+ text: readFileSync7(path8, "utf8")
21207
21541
  });
21208
21542
  } catch {
21209
21543
  }
@@ -21267,10 +21601,11 @@ function sourceCount(db, scope, ctx, source) {
21267
21601
  function zeroHits(db, scope, ctx, source, mem, nm, queries, offset = 0) {
21268
21602
  const inScope = sourceCount(db, scope, ctx, source);
21269
21603
  const n = inScope + mem.rows.length;
21270
- if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
21271
21604
  const head2 = 'No hits in scope "' + scope + '" across ' + n + " source(s).";
21272
21605
  const pick2 = nm.pick;
21273
- if (pick2 === null || mem.named || inScope > 0) return reply(head2, false);
21606
+ if (pick2 === null || mem.named || inScope > 0) {
21607
+ return reply(offset > 0 ? "No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s)." : head2, false);
21608
+ }
21274
21609
  if (pick2.id !== null) {
21275
21610
  const wider = scope === "session" && sourceCount(db, "worktree", ctx, source) > 0 ? "worktree" : "project";
21276
21611
  return reply(head2 + "\nSource " + JSON.stringify(nm.arg) + ' is stored in scope "' + wider + '": ' + callText(queries, wider, nm.arg, "") + " searches it.", false);
@@ -21297,9 +21632,9 @@ function unknownSource(db, scope, ctx, given) {
21297
21632
  return line + "\nStored sources, newest first: " + names.join(", ") + more + ". " + callText([], scope, void 0, 'sort:"timeline"') + " lists them all.";
21298
21633
  }
21299
21634
  function named(given, pick2) {
21300
- if (given === void 0 || pick2 === null) return { arg: given, note: null, pick: null };
21635
+ if (given === void 0 || pick2 === null) return { arg: given, note: null, pick: null, lost: null };
21301
21636
  const arg = pick2.id !== null && isLongLabel(given) ? sourceHandle(pick2.id) : given;
21302
- return { arg, note: collisionLine(given, pick2), pick: pick2 };
21637
+ return { arg, note: collisionLine(given, pick2), pick: pick2, lost: null };
21303
21638
  }
21304
21639
  function sourceCard(db, id2, input, scope, arg) {
21305
21640
  const row5 = sourceCardRow(db, id2);
@@ -21323,7 +21658,7 @@ function decisionQueries(input) {
21323
21658
  function pageSize(input) {
21324
21659
  return input.source === DECISION_SOURCE ? SEARCH_PAGE_SIZE : SEARCH_REPLY_HITS;
21325
21660
  }
21326
- function page(db, q, input, scope, ctx, offset, extra = 0) {
21661
+ function page(db, q, input, scope, ctx, offset, extra = 0, h9 = { n: 0, list: true }) {
21327
21662
  const size = pageSize(input) + extra;
21328
21663
  if (input.source === DECISION_SOURCE && q.trim() === "") {
21329
21664
  return ftsListSource(db, DECISION_SOURCE, scope, ctx.project, ctx.sessionId, size, offset);
@@ -21332,6 +21667,8 @@ function page(db, q, input, scope, ctx, offset, extra = 0) {
21332
21667
  if (hits.length > 0 || input.source === void 0) return hits;
21333
21668
  const any2 = offset === 0 ? hits : ftsQuery(db, q, scope, ctx.project, ctx.sessionId, 1, 0, input.source);
21334
21669
  if (any2.length > 0) return hits;
21670
+ h9.n++;
21671
+ if (!h9.list) return [];
21335
21672
  return ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, size, offset);
21336
21673
  }
21337
21674
  var JSON_ROWS_PAGE = 5;
@@ -21420,15 +21757,27 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
21420
21757
  const size = pageSize(input);
21421
21758
  const mem = ms.named || offset === 0 ? memoryChunks(ms.rows) : [];
21422
21759
  const count2 = (hits, n) => ms.named ? Math.min(n, hits.length) : contentIn(hits, n);
21423
- const fetched = input.queries.map((q) => {
21760
+ const h9 = { n: 0, list: false };
21761
+ const listed = [];
21762
+ const fetched = input.queries.map((q, qi) => {
21424
21763
  if (ms.named) {
21425
21764
  const want = offset + size + 1;
21426
21765
  const content2 = indexed ? ftsQuery(db, q, scope, ctx.project, ctx.sessionId, want, 0, input.source) : [];
21427
21766
  return mergeMemory(content2, memoryHits(mem, q, want)).slice(offset, want);
21428
21767
  }
21429
- const content = page(db, q, input, scope, ctx, offset, 1);
21768
+ const before = h9.n;
21769
+ const content = page(db, q, input, scope, ctx, offset, 1, h9);
21770
+ if (h9.n > before) listed.push(qi);
21430
21771
  return mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, q, MEMORY_HITS));
21431
21772
  });
21773
+ if (listed.length > 0 && listed.length === input.queries.length) {
21774
+ const ordered = orderedRead(db, input, scope, ctx, nm);
21775
+ if (ordered !== null) return ordered;
21776
+ }
21777
+ for (const qi of listed) {
21778
+ const content = ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, size + 1, offset);
21779
+ fetched[qi] = mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, input.queries[qi], MEMORY_HITS));
21780
+ }
21432
21781
  const take = fetched.map((h) => replyHits(h, size));
21433
21782
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
21434
21783
  if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, nm, input.queries, offset);
@@ -21493,6 +21842,49 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
21493
21842
  for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, nm.arg, "offset:" + pos));
21494
21843
  return reply(lines.concat(moreLines).join("\n"), false);
21495
21844
  }
21845
+ var ORDERED_LINE_BACK = 512;
21846
+ var SOURCE_IN_SCOPE = `
21847
+ SELECT session_id FROM sources WHERE id = :id
21848
+ AND (:scope <> 'session' OR session_id = :session_id)
21849
+ AND (:scope <> 'worktree' OR worktree = :worktree)`;
21850
+ function sourceText(db, id2) {
21851
+ const rows = db.raw.prepare("SELECT body FROM chunks WHERE source_id = ? ORDER BY CAST(ord AS INTEGER)").all(id2);
21852
+ const parts = [];
21853
+ for (let i = 0; i < rows.length; i++) {
21854
+ const body = rows[i].body;
21855
+ parts.push(body);
21856
+ if (i + 1 < rows.length && !body.endsWith("\n") && bytes2(body) < MAX_CHUNK_BYTES - 3) parts.push("\n\n");
21857
+ }
21858
+ return parts.join("");
21859
+ }
21860
+ function orderedRead(db, input, scope, ctx, nm) {
21861
+ const pick2 = nm.pick;
21862
+ if (pick2 === null || pick2.id === null || input.source === void 0 || input.source === DECISION_SOURCE) return null;
21863
+ const where = { id: pick2.id, scope, session_id: ctx.sessionId, worktree: ctx.project.worktree };
21864
+ const row5 = db.raw.prepare(SOURCE_IN_SCOPE).get(where);
21865
+ if (row5 === void 0) return null;
21866
+ const buf = Buffer.from(sourceText(db, pick2.id), "utf8");
21867
+ const total = buf.length;
21868
+ if (total === 0) return null;
21869
+ const name = isLongLabel(pick2.label) ? shownLabel(pick2.label, pick2.id) : JSON.stringify(pick2.label);
21870
+ let start = Math.min(input.offset ?? 0, total);
21871
+ while (start < total && (buf[start] & 192) === 128) start++;
21872
+ if (start >= total) return reply("No more text past offset " + start + " in source " + name + " (" + total + " B).", false);
21873
+ const note = nm.note === null ? "" : " " + nm.note;
21874
+ const headOf2 = (end2) => "Source " + name + " in order, bytes " + start + "-" + end2 + " of " + total + ":" + note;
21875
+ const moreOf = (end2) => "More: " + callText([""], scope, nm.arg, "offset:" + end2);
21876
+ let end = total;
21877
+ if (bytes2(headOf2(total)) + 1 + (total - start) > OUTPUT_CAP) {
21878
+ end = start + OUTPUT_CAP - bytes2(headOf2(total)) - 1 - bytes2(moreOf(total)) - 1;
21879
+ while (end > start && (buf[end] & 192) === 128) end--;
21880
+ const nl = buf.lastIndexOf(10, end - 1);
21881
+ if (nl >= start && nl + 1 > end - ORDERED_LINE_BACK) end = nl + 1;
21882
+ }
21883
+ const text = buf.subarray(start, end).toString("utf8");
21884
+ const key = end * 2 >= total ? betKeyOfLabel(pick2.label) : null;
21885
+ if (key !== null && !isLostBet(db, row5.session_id, key)) nm.lost = { sessionId: row5.session_id, key, source: sourceHandle(pick2.id) };
21886
+ return reply(headOf2(end) + "\n" + text + (end < total ? "\n" + moreOf(end) : ""), false);
21887
+ }
21496
21888
  function timelineLine(r) {
21497
21889
  const nl = r.text.indexOf("\n");
21498
21890
  const first = nl < 0 ? r.text : r.text.slice(0, nl);
@@ -21553,9 +21945,11 @@ async function handler(input, ctx) {
21553
21945
  }
21554
21946
  const scope = input.scope ?? "worktree";
21555
21947
  const db = await openDb(ctx.project, { readOnly: true });
21948
+ let lost = null;
21556
21949
  try {
21557
21950
  const given = input.source;
21558
- const pick2 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given) : null;
21951
+ const within = { scope, sessionId: ctx.sessionId, worktree: ctx.project.worktree };
21952
+ const pick2 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given, true, within) : null;
21559
21953
  if (pick2 !== null) input = { ...input, source: pick2.label };
21560
21954
  const nm = named(given, pick2);
21561
21955
  const indexed = pick2 !== null && pick2.id !== null;
@@ -21567,11 +21961,24 @@ async function handler(input, ctx) {
21567
21961
  nm.note = nm.note === null ? both : nm.note + "\n" + both;
21568
21962
  }
21569
21963
  const out = answer(db, input, scope, ctx, nm, ms, indexed, sort, pick2);
21964
+ lost = nm.lost;
21570
21965
  if (file2 === null || scope !== "session") return out;
21571
21966
  const call = callText(input.queries, "worktree", nm.arg, sort === "timeline" ? 'sort:"timeline"' : "");
21572
21967
  return reply(out.text + "\nMemory file " + file2.label + ' is in scope "worktree": ' + call + " searches it.", out.isError);
21573
21968
  } finally {
21574
21969
  closeDb(db);
21970
+ if (lost !== null) await recordLostBet(ctx, lost);
21971
+ }
21972
+ }
21973
+ async function recordLostBet(ctx, lost) {
21974
+ try {
21975
+ const w = await openDb(ctx.project);
21976
+ try {
21977
+ markLostBet(w, lost.sessionId, lost.key, "ordered-read", lost.source);
21978
+ } finally {
21979
+ closeDb(w);
21980
+ }
21981
+ } catch {
21575
21982
  }
21576
21983
  }
21577
21984
  var ctxSearch = Object.freeze({
@@ -21804,19 +22211,19 @@ var ctxBatch = Object.freeze({
21804
22211
  });
21805
22212
 
21806
22213
  // src/core/tools/doctor.ts
21807
- import { readdirSync as readdirSync8, readFileSync as readFileSync17, existsSync as existsSync17 } from "node:fs";
21808
- import { basename as basename5, join as join20 } from "node:path";
22214
+ import { readdirSync as readdirSync9, readFileSync as readFileSync18, existsSync as existsSync17 } from "node:fs";
22215
+ import { basename as basename5, join as join21 } from "node:path";
21809
22216
 
21810
22217
  // src/core/ops/bundle-dir.ts
21811
22218
  import { existsSync as existsSync4 } from "node:fs";
21812
- import { dirname as dirname5, join as join10 } from "node:path";
22219
+ import { dirname as dirname5, join as join11 } from "node:path";
21813
22220
  import { fileURLToPath } from "node:url";
21814
22221
  function bundleDirOf(argv1, moduleFile) {
21815
22222
  const own2 = dirname5(argv1);
21816
- if (existsSync4(join10(own2, SERVER_ENTRY_FILE))) return own2;
22223
+ if (existsSync4(join11(own2, SERVER_ENTRY_FILE))) return own2;
21817
22224
  let dir = dirname5(moduleFile);
21818
22225
  for (; ; ) {
21819
- if (existsSync4(join10(dir, SERVER_ENTRY_FILE))) return dir;
22226
+ if (existsSync4(join11(dir, SERVER_ENTRY_FILE))) return dir;
21820
22227
  const up = dirname5(dir);
21821
22228
  if (up === dir) return own2;
21822
22229
  dir = up;
@@ -21830,17 +22237,17 @@ function ownBundleDir() {
21830
22237
  }
21831
22238
 
21832
22239
  // src/core/ops/doctor-config.ts
21833
- import { existsSync as existsSync11, readdirSync as readdirSync6, readFileSync as readFileSync13 } from "node:fs";
21834
- import { dirname as dirname8, isAbsolute as isAbsolute5, join as join16, resolve as resolve9 } from "node:path";
22240
+ import { existsSync as existsSync11, readdirSync as readdirSync7, readFileSync as readFileSync14 } from "node:fs";
22241
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join17, resolve as resolve9 } from "node:path";
21835
22242
 
21836
22243
  // src/core/ops/detect-v1.ts
21837
- import { existsSync as existsSync6, opendirSync, readdirSync as readdirSync4, readFileSync as readFileSync8 } from "node:fs";
22244
+ import { existsSync as existsSync6, opendirSync, readdirSync as readdirSync5, readFileSync as readFileSync9 } from "node:fs";
21838
22245
  import { tmpdir } from "node:os";
21839
- import { join as join12 } from "node:path";
22246
+ import { join as join13 } from "node:path";
21840
22247
 
21841
22248
  // src/core/ops/host-config.ts
21842
- import { existsSync as existsSync5, readFileSync as readFileSync7 } from "node:fs";
21843
- import { dirname as dirname6, join as join11 } from "node:path";
22249
+ import { existsSync as existsSync5, readFileSync as readFileSync8 } from "node:fs";
22250
+ import { dirname as dirname6, join as join12 } from "node:path";
21844
22251
 
21845
22252
  // node_modules/eslint-visitor-keys/lib/visitor-keys.js
21846
22253
  var KEYS2 = {
@@ -23886,7 +24293,7 @@ function parseTOML(code, options) {
23886
24293
  }
23887
24294
 
23888
24295
  // src/core/ops/atomic-file.ts
23889
- import { mkdirSync as mkdirSync3, renameSync as renameSync2, unlinkSync, writeFileSync } from "node:fs";
24296
+ import { mkdirSync as mkdirSync4, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
23890
24297
  import path3 from "node:path";
23891
24298
  function sleepSync(ms) {
23892
24299
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
@@ -23895,7 +24302,7 @@ function errCode2(e) {
23895
24302
  return e.code;
23896
24303
  }
23897
24304
  function renameWithRetry(from, to, opts = {}) {
23898
- const rename = opts.rename ?? renameSync2;
24305
+ const rename = opts.rename ?? renameSync3;
23899
24306
  const sleep = opts.sleep ?? sleepSync;
23900
24307
  const win = (opts.platform ?? process.platform) === "win32";
23901
24308
  for (let attempt = 0; ; attempt += 1) {
@@ -23910,7 +24317,7 @@ function renameWithRetry(from, to, opts = {}) {
23910
24317
  }
23911
24318
  }
23912
24319
  function unlinkWithRetry(file2, opts = {}) {
23913
- const unlink = opts.unlink ?? unlinkSync;
24320
+ const unlink = opts.unlink ?? unlinkSync2;
23914
24321
  const sleep = opts.sleep ?? sleepSync;
23915
24322
  const win = (opts.platform ?? process.platform) === "win32";
23916
24323
  for (let attempt = 0; ; attempt += 1) {
@@ -23937,10 +24344,10 @@ function removeTmpFile(tmp, opts = {}) {
23937
24344
  }
23938
24345
  }
23939
24346
  function atomicWriteFile(file2, text, opts = {}) {
23940
- mkdirSync3(path3.dirname(file2), { recursive: true });
24347
+ mkdirSync4(path3.dirname(file2), { recursive: true });
23941
24348
  const tmp = path3.join(path3.dirname(file2), `${ATOMIC_TMP_PREFIX}${path3.basename(file2)}${ATOMIC_TMP_MARK}${process.pid}`);
23942
24349
  try {
23943
- writeFileSync(tmp, text);
24350
+ writeFileSync2(tmp, text);
23944
24351
  renameWithRetry(tmp, file2, opts);
23945
24352
  } catch (e) {
23946
24353
  removeTmpFile(tmp, opts);
@@ -23957,10 +24364,10 @@ function formatOf(path8) {
23957
24364
  function readHostConfig(agent, path8) {
23958
24365
  let file2 = path8;
23959
24366
  if (agent === "opencode") {
23960
- const jsonc = join11(dirname6(path8), OPENCODE_CONFIG_FILES[0]);
24367
+ const jsonc = join12(dirname6(path8), OPENCODE_CONFIG_FILES[0]);
23961
24368
  if (existsSync5(jsonc)) file2 = jsonc;
23962
24369
  }
23963
- const raw = existsSync5(file2) ? readFileSync7(file2, "utf8") : "";
24370
+ const raw = existsSync5(file2) ? readFileSync8(file2, "utf8") : "";
23964
24371
  return { agent, text: hostText(raw), format: agent === "opencode" && !file2.endsWith(TOML_EXT) ? "jsonc" : formatOf(file2), path: file2, layout: hostLayout(raw) };
23965
24372
  }
23966
24373
  function stripJsonComments(text) {
@@ -24305,7 +24712,7 @@ function setText(agent, path8, text, format, key, value) {
24305
24712
  }
24306
24713
  }
24307
24714
  function serverScript() {
24308
- return join11(dirname6(process.argv[1] ?? ""), SERVER_ENTRY_FILE);
24715
+ return join12(dirname6(process.argv[1] ?? ""), SERVER_ENTRY_FILE);
24309
24716
  }
24310
24717
  function isNodeCommand(command) {
24311
24718
  if (typeof command !== "string") return false;
@@ -24432,14 +24839,14 @@ function stripJsonc(text) {
24432
24839
  }
24433
24840
  function readJson(file2) {
24434
24841
  try {
24435
- return JSON.parse(stripJsonc(hostText(readFileSync8(file2, "utf8"))));
24842
+ return JSON.parse(stripJsonc(hostText(readFileSync9(file2, "utf8"))));
24436
24843
  } catch {
24437
24844
  return void 0;
24438
24845
  }
24439
24846
  }
24440
24847
  function readText(file2) {
24441
24848
  try {
24442
- return hostText(readFileSync8(file2, "utf8"));
24849
+ return hostText(readFileSync9(file2, "utf8"));
24443
24850
  } catch {
24444
24851
  return "";
24445
24852
  }
@@ -24504,7 +24911,7 @@ function mcpEntry(file2, doc, out) {
24504
24911
  }
24505
24912
  }
24506
24913
  function claudeShapeSettings(agentHome, out) {
24507
- const file2 = join12(agentHome, SETTINGS_FILE);
24914
+ const file2 = join13(agentHome, SETTINGS_FILE);
24508
24915
  const doc = readJson(file2);
24509
24916
  for (const c of nestedCommands(doc)) {
24510
24917
  if (c.command.includes(V1_CACHE_HEAL_NAME)) out.push(finding(file2, c.path, V1_REASON.cacheHealHook));
@@ -24524,63 +24931,63 @@ function v1HookFile(file2, out) {
24524
24931
  function scanClaudeCode(home, agentHome, out) {
24525
24932
  claudeShapeSettings(agentHome, out);
24526
24933
  for (const ext of V1_CACHE_HEAL_EXTS) {
24527
- const file2 = join12(agentHome, V1_HOOKS_DIR_NAME, V1_CACHE_HEAL_NAME + ext);
24934
+ const file2 = join13(agentHome, V1_HOOKS_DIR_NAME, V1_CACHE_HEAL_NAME + ext);
24528
24935
  if (existsSync6(file2)) out.push(finding(file2, "", V1_REASON.cacheHealFile));
24529
24936
  }
24530
- const userFile = join12(home, CLAUDE_USER_CONFIG_FILE);
24937
+ const userFile = join13(home, CLAUDE_USER_CONFIG_FILE);
24531
24938
  mcpEntry(userFile, readJson(userFile), out);
24532
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24939
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24533
24940
  }
24534
24941
  function scanCodex(agentHome, out) {
24535
- const hooksFile = join12(agentHome, HOOKS_JSON_FILE);
24942
+ const hooksFile = join13(agentHome, HOOKS_JSON_FILE);
24536
24943
  for (const c of nestedCommands(readJson(hooksFile))) {
24537
24944
  if (c.command.includes(V1_CODEX_HOOK_COMMAND) || isCodexScript(c.command)) {
24538
24945
  out.push(finding(hooksFile, c.path, V1_REASON.codexHook));
24539
24946
  }
24540
24947
  }
24541
- const tomlFile = join12(agentHome, CONFIG_TOML_FILE);
24948
+ const tomlFile = join13(agentHome, CONFIG_TOML_FILE);
24542
24949
  const config2 = readTomlValue(tomlFile);
24543
24950
  for (const span2 of readTomlTables(tomlFile)) {
24544
24951
  if (span2.path[0] !== V1_TOML_SECTION_ROOT || span2.path[1] !== SERVER_KEY) continue;
24545
24952
  if (isV2McpTable(hostConfigValueAt(config2, span2.path.slice(0, 2)))) continue;
24546
24953
  out.push(finding(tomlFile, span2.header.trim(), V1_REASON.codexToml));
24547
24954
  }
24548
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24955
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24549
24956
  }
24550
24957
  function scanGemini(agentHome, out) {
24551
- const file2 = join12(agentHome, SETTINGS_FILE);
24958
+ const file2 = join13(agentHome, SETTINGS_FILE);
24552
24959
  for (const c of nestedCommands(readJson(file2))) {
24553
24960
  if (c.command.includes(SERVER_KEY)) out.push(finding(file2, c.path, V1_REASON.hook));
24554
24961
  }
24555
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDirShared, out);
24962
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDirShared, out);
24556
24963
  }
24557
24964
  function scanVscode(agentHome, project, out) {
24558
24965
  if (project !== void 0) {
24559
- v1HookFile(join12(project, GITHUB_DIR_NAME, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out);
24560
- const mcpFile2 = join12(project, VSCODE_DIR_NAME, VSCODE_MCP_FILE);
24966
+ v1HookFile(join13(project, GITHUB_DIR_NAME, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out);
24967
+ const mcpFile2 = join13(project, VSCODE_DIR_NAME, VSCODE_MCP_FILE);
24561
24968
  const doc = readJson(mcpFile2);
24562
24969
  const servers = isObj(doc) && isObj(doc[VSCODE_MCP_SERVERS_KEY]) ? doc[VSCODE_MCP_SERVERS_KEY] : {};
24563
24970
  const entry = Object.hasOwn(servers, SERVER_KEY) ? servers[SERVER_KEY] : void 0;
24564
24971
  if (isObj(entry) && (entry.command === V1_BIN_COMMAND || listOf(entry.args).some((a) => a === V1_BIN_COMMAND))) {
24565
24972
  out.push(finding(mcpFile2, keyPath(VSCODE_MCP_SERVERS_KEY, SERVER_KEY), V1_REASON.vscodeMcp));
24566
24973
  }
24567
- const sessions = join12(project, GITHUB_DIR_NAME, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME);
24974
+ const sessions = join13(project, GITHUB_DIR_NAME, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME);
24568
24975
  dataDir(sessions, reachedThroughLink(project, sessions) ? V1_REASON.projectLink : V1_REASON.dataDir, out);
24569
24976
  }
24570
- dataDir(join12(agentHome, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME), V1_REASON.dataDir, out);
24977
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME), V1_REASON.dataDir, out);
24571
24978
  }
24572
24979
  function jsonFiles(dir) {
24573
24980
  try {
24574
- return readdirSync4(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
24981
+ return readdirSync5(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
24575
24982
  } catch {
24576
24983
  return [];
24577
24984
  }
24578
24985
  }
24579
24986
  function scanKiro(agentHome, project, out) {
24580
- const agentsDir = join12(agentHome, KIRO_AGENTS_DIR);
24581
- const defaultFile = join12(agentHome, ...KIRO_AGENT_FILE);
24987
+ const agentsDir = join13(agentHome, KIRO_AGENTS_DIR);
24988
+ const defaultFile = join13(agentHome, ...KIRO_AGENT_FILE);
24582
24989
  for (const name of jsonFiles(agentsDir)) {
24583
- const file2 = join12(agentsDir, name);
24990
+ const file2 = join13(agentsDir, name);
24584
24991
  const doc = readJson(file2);
24585
24992
  if (isObj(doc) && doc[KIRO_AGENT_NAME_KEY] === SERVER_KEY) {
24586
24993
  out.push(finding(file2, "", V1_REASON.kiroAgentFile));
@@ -24591,31 +24998,31 @@ function scanKiro(agentHome, project, out) {
24591
24998
  if (isV1Hook(c.command)) out.push(finding(file2, c.path, V1_REASON.kiroHook));
24592
24999
  }
24593
25000
  }
24594
- const steeringDocs = [join12(agentHome, ...KIRO_STEERING_FILE)];
24595
- if (project !== void 0) steeringDocs.push(join12(project, ...AGENT_HOME_DIR.kiro, ...KIRO_STEERING_FILE));
25001
+ const steeringDocs = [join13(agentHome, ...KIRO_STEERING_FILE)];
25002
+ if (project !== void 0) steeringDocs.push(join13(project, ...AGENT_HOME_DIR.kiro, ...KIRO_STEERING_FILE));
24596
25003
  for (const file2 of steeringDocs) {
24597
25004
  if (existsSync6(file2)) out.push(finding(file2, "", V1_REASON.kiroSteering));
24598
25005
  }
24599
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
25006
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24600
25007
  }
24601
25008
  function piNpmIsCurrent(piAgentDir) {
24602
- const doc = readJson(join12(piAgentDir, PI_NPM_DIR, PI_NODE_MODULES_DIR, SERVER_KEY, PI_PACKAGE_JSON_FILE));
25009
+ const doc = readJson(join13(piAgentDir, PI_NPM_DIR, PI_NODE_MODULES_DIR, SERVER_KEY, PI_PACKAGE_JSON_FILE));
24603
25010
  const version2 = isObj(doc) && typeof doc.version === "string" ? doc.version : "";
24604
25011
  return Number.parseInt(version2, 10) >= PI_CURRENT_MAJOR;
24605
25012
  }
24606
25013
  function scanPi(piAgentDir, agentHome, out) {
24607
- const file2 = join12(piAgentDir, SETTINGS_FILE);
25014
+ const file2 = join13(piAgentDir, SETTINGS_FILE);
24608
25015
  const doc = readJson(file2);
24609
25016
  listOf(isObj(doc) ? doc[PI_PACKAGES_KEY] : void 0).forEach((pkg, i) => {
24610
25017
  const spec = isObj(pkg) ? pkg[PI_PACKAGE_SOURCE_KEY] : pkg;
24611
25018
  if (spec === V1_PI_PACKAGE && !piNpmIsCurrent(piAgentDir)) out.push(finding(file2, keyPath(PI_PACKAGES_KEY, i), V1_REASON.piNpm));
24612
25019
  if (spec === PI_GIT_PACKAGE) out.push(finding(file2, keyPath(PI_PACKAGES_KEY, i), V1_REASON.piGit));
24613
25020
  });
24614
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
25021
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24615
25022
  }
24616
25023
  function scanOpencode(agentHome, out) {
24617
25024
  for (const name of OPENCODE_CONFIG_FILES) {
24618
- const file2 = join12(agentHome, name);
25025
+ const file2 = join13(agentHome, name);
24619
25026
  const doc = readJson(file2);
24620
25027
  if (!isObj(doc) || !Array.isArray(doc[OPENCODE_PLUGIN_KEY])) continue;
24621
25028
  doc[OPENCODE_PLUGIN_KEY].forEach((spec, i) => {
@@ -24626,13 +25033,13 @@ function scanOpencode(agentHome, out) {
24626
25033
  }
24627
25034
  }
24628
25035
  function scanZcode(agentHome, out) {
24629
- const configFile = join12(agentHome, ZCODE_CLI_DIR, CONFIG_JSON_FILE);
25036
+ const configFile = join13(agentHome, ZCODE_CLI_DIR, CONFIG_JSON_FILE);
24630
25037
  const config2 = readJson(configFile);
24631
25038
  const events = isObj(config2) && isObj(config2[HOOKS_KEY]) ? config2[HOOKS_KEY][ZCODE_EVENTS_KEY] : void 0;
24632
25039
  for (const c of flatCommands(events, [HOOKS_KEY, ZCODE_EVENTS_KEY])) {
24633
25040
  if (c.command.includes(V1_HOOK_COMMAND)) out.push(finding(configFile, c.path, V1_REASON.zcodeHook));
24634
25041
  }
24635
- const hooksFile = join12(agentHome, ZCODE_CLI_DIR, HOOKS_JSON_FILE);
25042
+ const hooksFile = join13(agentHome, ZCODE_CLI_DIR, HOOKS_JSON_FILE);
24636
25043
  for (const c of nestedCommands(readJson(hooksFile))) {
24637
25044
  if (c.command.includes(V1_HOOK_COMMAND)) out.push(finding(hooksFile, c.path, V1_REASON.zcodeHook));
24638
25045
  }
@@ -24656,14 +25063,14 @@ function firstTmpMatch(dir) {
24656
25063
  }
24657
25064
  }
24658
25065
  function scanAll(home, tmp, out) {
24659
- const root = join12(home, DATA_ROOT.slice(1));
24660
- for (const name of V1_DATA_ROOT_ENTRIES) dataDir(join12(root, name), V1_REASON.dataRoot, out);
25066
+ const root = join13(home, DATA_ROOT.slice(1));
25067
+ for (const name of V1_DATA_ROOT_ENTRIES) dataDir(join13(root, name), V1_REASON.dataRoot, out);
24661
25068
  if (firstTmpMatch(tmp) !== null) out.push(finding(tmp, V1_TMP_PREFIX + "*", V1_REASON.tmpFile));
24662
25069
  }
24663
25070
  function detectV1(agent, home, scope = {}) {
24664
25071
  const out = [];
24665
25072
  const project = scope.project;
24666
- const agentHome = agent === "claude-code" && scope.claudeDir !== void 0 ? scope.claudeDir : agent === "codex" && scope.codexDir !== void 0 ? scope.codexDir : agent === "gemini" && scope.geminiDir !== void 0 ? scope.geminiDir : agent === "copilot-cli" && scope.copilotDir !== void 0 ? scope.copilotDir : agent === "kiro" && scope.kiroDir !== void 0 ? scope.kiroDir : agent === "opencode" && scope.opencodeDir !== void 0 ? scope.opencodeDir : join12(home, ...AGENT_HOME_DIR[agent]);
25073
+ const agentHome = agent === "claude-code" && scope.claudeDir !== void 0 ? scope.claudeDir : agent === "codex" && scope.codexDir !== void 0 ? scope.codexDir : agent === "gemini" && scope.geminiDir !== void 0 ? scope.geminiDir : agent === "copilot-cli" && scope.copilotDir !== void 0 ? scope.copilotDir : agent === "kiro" && scope.kiroDir !== void 0 ? scope.kiroDir : agent === "opencode" && scope.opencodeDir !== void 0 ? scope.opencodeDir : join13(home, ...AGENT_HOME_DIR[agent]);
24667
25074
  switch (agent) {
24668
25075
  case "claude-code":
24669
25076
  scanClaudeCode(home, agentHome, out);
@@ -24676,11 +25083,11 @@ function detectV1(agent, home, scope = {}) {
24676
25083
  break;
24677
25084
  case "qwen":
24678
25085
  claudeShapeSettings(agentHome, out);
24679
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
25086
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24680
25087
  break;
24681
25088
  case "copilot-cli":
24682
- v1HookFile(join12(agentHome, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out);
24683
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
25089
+ v1HookFile(join13(agentHome, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out);
25090
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24684
25091
  break;
24685
25092
  case "vscode":
24686
25093
  scanVscode(agentHome, project, out);
@@ -24689,7 +25096,7 @@ function detectV1(agent, home, scope = {}) {
24689
25096
  scanKiro(agentHome, project, out);
24690
25097
  break;
24691
25098
  case "pi":
24692
- scanPi(scope.piAgentDir !== void 0 && scope.piAgentDir !== "" ? scope.piAgentDir : join12(agentHome, PI_AGENT_DIR), agentHome, out);
25099
+ scanPi(scope.piAgentDir !== void 0 && scope.piAgentDir !== "" ? scope.piAgentDir : join13(agentHome, PI_AGENT_DIR), agentHome, out);
24693
25100
  break;
24694
25101
  // D-WIN-PIDIR-1: empty is unset
24695
25102
  case "opencode":
@@ -24704,8 +25111,8 @@ function detectV1(agent, home, scope = {}) {
24704
25111
  }
24705
25112
 
24706
25113
  // src/core/ops/plugin-root.ts
24707
- import { existsSync as existsSync7, readdirSync as readdirSync5, readFileSync as readFileSync9, realpathSync as realpathSync4 } from "node:fs";
24708
- import { dirname as dirname7, isAbsolute as isAbsolute3, join as join13, sep as sep4 } from "node:path";
25114
+ import { existsSync as existsSync7, readdirSync as readdirSync6, readFileSync as readFileSync10, realpathSync as realpathSync4 } from "node:fs";
25115
+ import { dirname as dirname7, isAbsolute as isAbsolute4, join as join14, sep as sep4 } from "node:path";
24709
25116
  import { fileURLToPath as fileURLToPath2 } from "node:url";
24710
25117
  function missing(agent, path8) {
24711
25118
  return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path8 });
@@ -24746,15 +25153,15 @@ var realOrNull = (path8) => {
24746
25153
  };
24747
25154
  var readOrNull = (file2) => {
24748
25155
  try {
24749
- return readFileSync9(file2, "utf8");
25156
+ return readFileSync10(file2, "utf8");
24750
25157
  } catch {
24751
25158
  return null;
24752
25159
  }
24753
25160
  };
24754
25161
  var samePath = (a, b) => a === b || (realOrNull(a) ?? a) === (realOrNull(b) ?? b);
24755
25162
  function enabledPlugins(claudeDir, project) {
24756
- const files = [join13(claudeDir, SETTINGS_FILE)];
24757
- if (project !== void 0) files.push(join13(project, HOST_CONFIG_DIR_NAME, SETTINGS_FILE), join13(project, HOST_CONFIG_DIR_NAME, SETTINGS_LOCAL_FILE));
25163
+ const files = [join14(claudeDir, SETTINGS_FILE)];
25164
+ if (project !== void 0) files.push(join14(project, HOST_CONFIG_DIR_NAME, SETTINGS_FILE), join14(project, HOST_CONFIG_DIR_NAME, SETTINGS_LOCAL_FILE));
24758
25165
  const out = {};
24759
25166
  for (const file2 of files) {
24760
25167
  const text = readOrNull(file2);
@@ -24770,7 +25177,7 @@ function marketplaceChoice(env, worktree) {
24770
25177
  const ownReal = script === void 0 || script === "" ? null : realOrNull(dirname7(script));
24771
25178
  const hostRoot = env[CLAUDE_PLUGIN_ROOT_ENV];
24772
25179
  if (ownReal !== null && hostRoot !== void 0 && hostRoot !== "" && realOrNull(hostRoot) === ownReal) return { root: ownReal };
24773
- const record4 = readOrNull(join13(claudeDir, HOST_PLUGINS_DIR_NAME, INSTALLED_PLUGINS_FILE));
25180
+ const record4 = readOrNull(join14(claudeDir, HOST_PLUGINS_DIR_NAME, INSTALLED_PLUGINS_FILE));
24774
25181
  const recorded = record4 === null ? [] : recordedInstalls(record4);
24775
25182
  if (recorded.length === 0) return { record: false };
24776
25183
  const live = recorded.filter((r) => existsSync7(r.installPath));
@@ -24793,18 +25200,18 @@ function marketplaceChoice(env, worktree) {
24793
25200
  }
24794
25201
  function marketplaceRoot(adapter, env, worktree) {
24795
25202
  const claudeDir = claudeDirOf(env, requireHomeDir(env));
24796
- const plugins = join13(claudeDir, HOST_PLUGINS_DIR_NAME);
24797
- const cache = join13(plugins, PLUGIN_CACHE_DIR_NAME);
25203
+ const plugins = join14(claudeDir, HOST_PLUGINS_DIR_NAME);
25204
+ const cache = join14(plugins, PLUGIN_CACHE_DIR_NAME);
24798
25205
  const script = process.argv[1];
24799
25206
  const ownReal = script === void 0 || script === "" ? null : realOrNull(dirname7(script));
24800
25207
  const choice = marketplaceChoice(env, worktree);
24801
25208
  if ("root" in choice) return choice.root;
24802
25209
  if ("installs" in choice) throw missing(adapter.id, choice.installs.map((r) => r.installPath).join(", "));
24803
25210
  const cacheReal = realOrNull(cache);
24804
- if (ownReal !== null && cacheReal !== null && ownReal.startsWith(cacheReal + sep4) && existsSync7(join13(ownReal, SERVER_ENTRY_FILE))) return ownReal;
24805
- const pattern = join13(cache, "*", PLUGIN_NAME);
25211
+ if (ownReal !== null && cacheReal !== null && ownReal.startsWith(cacheReal + sep4) && existsSync7(join14(ownReal, SERVER_ENTRY_FILE))) return ownReal;
25212
+ const pattern = join14(cache, "*", PLUGIN_NAME);
24806
25213
  if (!existsSync7(cache)) throw missing(adapter.id, pattern);
24807
- const found = readdirSync5(cache).sort().map((marketplace) => join13(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync7(dir));
25214
+ const found = readdirSync6(cache).sort().map((marketplace) => join14(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync7(dir));
24808
25215
  if (found.length !== 1) throw missing(adapter.id, found.length === 0 ? pattern : found.join(", "));
24809
25216
  return found[0];
24810
25217
  }
@@ -24817,12 +25224,12 @@ function configEntryRoot(adapter, env) {
24817
25224
  const value = parseHostConfig(adapter.id, file2, current.text, current.format);
24818
25225
  const args = hostConfigValueAt(value, [...spec.key, MCP_ARGS_FIELD]);
24819
25226
  const script = Array.isArray(args) ? args[0] : void 0;
24820
- if (typeof script !== "string" || !isAbsolute3(script)) throw missing(adapter.id, file2);
25227
+ if (typeof script !== "string" || !isAbsolute4(script)) throw missing(adapter.id, file2);
24821
25228
  return dirname7(script);
24822
25229
  }
24823
25230
  function packageDirOf(dir) {
24824
25231
  for (let cur = dir; ; ) {
24825
- if (existsSync7(join13(cur, D1_PACKAGE_FILE))) return cur;
25232
+ if (existsSync7(join14(cur, D1_PACKAGE_FILE))) return cur;
24826
25233
  const up = dirname7(cur);
24827
25234
  if (up === cur) return dir;
24828
25235
  cur = up;
@@ -24837,9 +25244,9 @@ function candidate(adapter, env, worktree) {
24837
25244
  case "hooks+mcp":
24838
25245
  return configEntryRoot(adapter, env);
24839
25246
  case "extension":
24840
- return join13(adapter.id === "gemini" ? geminiDirOf(env, requireHomeDir(env)) : join13(requireHomeDir(env), ...AGENT_HOME_DIR[adapter.id]), EXTENSIONS_DIR_NAME, PLUGIN_NAME);
25247
+ return join14(adapter.id === "gemini" ? geminiDirOf(env, requireHomeDir(env)) : join14(requireHomeDir(env), ...AGENT_HOME_DIR[adapter.id]), EXTENSIONS_DIR_NAME, PLUGIN_NAME);
24841
25248
  case "plugin":
24842
- return join13(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, adapter.id, PLUGIN_CURRENT_LINK);
25249
+ return join14(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, adapter.id, PLUGIN_CURRENT_LINK);
24843
25250
  case "in-process":
24844
25251
  return packageDirOf(dirname7(fileURLToPath2(import.meta.url)));
24845
25252
  }
@@ -24854,7 +25261,7 @@ function resolvePluginRoot(adapter, env, worktree) {
24854
25261
  }
24855
25262
 
24856
25263
  // src/setup/pi-gate.ts
24857
- import { existsSync as existsSync8, readFileSync as readFileSync10, realpathSync as realpathSync5 } from "node:fs";
25264
+ import { existsSync as existsSync8, readFileSync as readFileSync11, realpathSync as realpathSync5 } from "node:fs";
24858
25265
  import path4 from "node:path";
24859
25266
  var EXTENSIONS_KEY = "extensions";
24860
25267
  var PROJECT_DIR = ".pi";
@@ -24864,7 +25271,7 @@ var SOURCE_PREFIXES = ["npm:", "git:"];
24864
25271
  function load(file2) {
24865
25272
  if (!existsSync8(file2)) return void 0;
24866
25273
  try {
24867
- return { file: file2, doc: parseHostConfig("pi", file2, hostText(readFileSync10(file2, "utf8")), "json") };
25274
+ return { file: file2, doc: parseHostConfig("pi", file2, hostText(readFileSync11(file2, "utf8")), "json") };
24868
25275
  } catch {
24869
25276
  return void 0;
24870
25277
  }
@@ -24923,8 +25330,8 @@ function piInstalledIn(env, home, pkgDir, cwd) {
24923
25330
  }
24924
25331
 
24925
25332
  // src/core/ops/doctor-env.ts
24926
- import { existsSync as existsSync9, readFileSync as readFileSync11, realpathSync as realpathSync6 } from "node:fs";
24927
- import { isAbsolute as isAbsolute4, join as join14, relative as relative4 } from "node:path";
25333
+ import { existsSync as existsSync9, readFileSync as readFileSync12, realpathSync as realpathSync6 } from "node:fs";
25334
+ import { isAbsolute as isAbsolute5, join as join15, relative as relative4 } from "node:path";
24928
25335
  function pass(id2, detail = DOCTOR_PASS_DETAIL) {
24929
25336
  return { id: id2, label: DOCTOR_LABEL[id2], status: "PASS", detail };
24930
25337
  }
@@ -24939,7 +25346,7 @@ function warn(id2, detail, fixCommand) {
24939
25346
  }
24940
25347
  function bundleVersion(bundleDir2) {
24941
25348
  try {
24942
- const v = JSON.parse(readFileSync11(join14(bundleDir2, D1_PACKAGE_FILE), "utf8")).version;
25349
+ const v = JSON.parse(readFileSync12(join15(bundleDir2, D1_PACKAGE_FILE), "utf8")).version;
24943
25350
  return typeof v === "string" && v !== "" ? v : void 0;
24944
25351
  } catch {
24945
25352
  return void 0;
@@ -25093,7 +25500,7 @@ function checkMcp(ctx, adapter) {
25093
25500
  function piCwdInside(worktree, piCwd) {
25094
25501
  if (piCwd === void 0 || !existsSync9(piCwd)) return false;
25095
25502
  const rel = relative4(worktree, realpathSync6.native(piCwd));
25096
- return rel === "" || !rel.startsWith("..") && !isAbsolute4(rel);
25503
+ return rel === "" || !rel.startsWith("..") && !isAbsolute5(rel);
25097
25504
  }
25098
25505
  function checkProject(i) {
25099
25506
  const bad = fail2("D7", D7_DETAIL(i.project.source), D7_FIX);
@@ -25101,6 +25508,20 @@ function checkProject(i) {
25101
25508
  if (i.adapter.projectSource === "pi:ctx.cwd" && !piCwdInside(i.project.worktree, i.piCwd)) return bad;
25102
25509
  return pass("D7");
25103
25510
  }
25511
+ function projectOrMissing(ctx) {
25512
+ try {
25513
+ return { project: ctx.project };
25514
+ } catch (err) {
25515
+ if (err instanceof CtxError && err.code === "NO_PROJECT") return { missing: String(err.vars.kind) };
25516
+ throw err;
25517
+ }
25518
+ }
25519
+ function noProjectRow(kind) {
25520
+ return fail2("D7", D7_NO_PROJECT_DETAIL(kind), D7_FIX);
25521
+ }
25522
+ function needsProjectRow(id2) {
25523
+ return unknown2(id2, DOCTOR_NEEDS_PROJECT_DETAIL);
25524
+ }
25104
25525
  function checkMode(adapter, hostPermission) {
25105
25526
  if (hostPermission === "missing") return fail2("D10", D10_PERMISSION_MISSING_DETAIL, D10_PERMISSION_FIX);
25106
25527
  if (hostPermission === "wired") return pass("D10", D10_PERMISSION_DETAIL(adapter.denyChannel));
@@ -25123,8 +25544,8 @@ function checkRuntimes(env, shellRow) {
25123
25544
  }
25124
25545
 
25125
25546
  // src/core/ops/omp-import.ts
25126
- import { join as join15 } from "node:path";
25127
- var { existsSync: existsSync10, readFileSync: readFileSync12 } = process.getBuiltinModule("node:fs");
25547
+ import { join as join16 } from "node:path";
25548
+ var { existsSync: existsSync10, readFileSync: readFileSync13 } = process.getBuiltinModule("node:fs");
25128
25549
  var OMP_DISABLED_SERVERS_KEY = "disabledServers";
25129
25550
  var OMP_MCP_FILE = "mcp.json";
25130
25551
  var OMP_CONFIG_FILE = "config.yml";
@@ -25132,13 +25553,13 @@ var ENABLED_PROVIDERS = "enabledProviders";
25132
25553
  var DISABLED_PROVIDERS = "disabledProviders";
25133
25554
  var CLAUDE_PROVIDER = "claude";
25134
25555
  var ALL_PROVIDERS = ["*", "all"];
25135
- function ompImportFiles(home) {
25136
- const agentDir = join15(home, ...AGENT_HOME_DIR.omp, PI_AGENT_DIR);
25137
- return { config: join15(agentDir, OMP_CONFIG_FILE), mcp: join15(agentDir, OMP_MCP_FILE), claude: join15(home, CLAUDE_USER_CONFIG_FILE) };
25556
+ function ompImportFiles(env, home) {
25557
+ const agentDir = ompAgentDirOf(env, home);
25558
+ return { config: join16(agentDir, OMP_CONFIG_FILE), mcp: join16(agentDir, OMP_MCP_FILE), claude: join16(home, CLAUDE_USER_CONFIG_FILE) };
25138
25559
  }
25139
25560
  function readText2(file2) {
25140
25561
  try {
25141
- return existsSync10(file2) ? hostText(readFileSync12(file2, "utf8")) : void 0;
25562
+ return existsSync10(file2) ? hostText(readFileSync13(file2, "utf8")) : void 0;
25142
25563
  } catch {
25143
25564
  return void 0;
25144
25565
  }
@@ -25266,11 +25687,11 @@ function ownHooks(block, shape, timeoutKey, native, agent) {
25266
25687
  var validTimeout = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
25267
25688
  function mcpFile(row5, home, env) {
25268
25689
  const spec = OWN_MCP_ENTRY[row5.id];
25269
- if (row5.id === "codex") return join16(codexDirOf(env, home), CONFIG_TOML_FILE);
25690
+ if (row5.id === "codex") return join17(codexDirOf(env, home), CONFIG_TOML_FILE);
25270
25691
  if (spec !== void 0) return ownMcpFileOf(row5.id, spec.file, env, home);
25271
- if (row5.id === "opencode") return join16(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
25692
+ if (row5.id === "opencode") return join17(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
25272
25693
  if (row5.id === "pi") {
25273
- return join16(piAgentDirOf(env, home), SETTINGS_FILE);
25694
+ return join17(piAgentDirOf(env, home), SETTINGS_FILE);
25274
25695
  }
25275
25696
  return null;
25276
25697
  }
@@ -25283,27 +25704,27 @@ function codexNativeDir(env, home) {
25283
25704
  const codexDir = codexDirOf(env, home);
25284
25705
  let enabled;
25285
25706
  try {
25286
- enabled = hostConfigValueAt(readParsed("codex", join16(codexDir, CONFIG_TOML_FILE)).value, ["plugins", CODEX_PLUGIN_KEY, "enabled"]);
25707
+ enabled = hostConfigValueAt(readParsed("codex", join17(codexDir, CONFIG_TOML_FILE)).value, ["plugins", CODEX_PLUGIN_KEY, "enabled"]);
25287
25708
  } catch {
25288
25709
  return null;
25289
25710
  }
25290
25711
  if (enabled !== true) return null;
25291
- const cache = join16(codexDir, "plugins", PLUGIN_CACHE_DIR_NAME);
25712
+ const cache = join17(codexDir, "plugins", PLUGIN_CACHE_DIR_NAME);
25292
25713
  if (!existsSync11(cache)) return null;
25293
25714
  const found = [];
25294
- for (const market of readdirSync6(cache)) {
25295
- const plugin = join16(cache, market, SERVER_KEY);
25715
+ for (const market of readdirSync7(cache)) {
25716
+ const plugin = join17(cache, market, SERVER_KEY);
25296
25717
  if (!existsSync11(plugin)) continue;
25297
- for (const version2 of readdirSync6(plugin).sort()) {
25298
- const dir = join16(plugin, version2, CODEX_PLUGIN_SUBDIR);
25299
- if (existsSync11(join16(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
25718
+ for (const version2 of readdirSync7(plugin).sort()) {
25719
+ const dir = join17(plugin, version2, CODEX_PLUGIN_SUBDIR);
25720
+ if (existsSync11(join17(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
25300
25721
  }
25301
25722
  }
25302
25723
  return found.length === 0 ? null : found[found.length - 1];
25303
25724
  }
25304
25725
  function nativeMcpWrong(dir, row5) {
25305
25726
  try {
25306
- const entry = hostConfigValueAt(readParsed(row5.id, join16(dir, CODEX_PLUGIN_MCP_FILE)).value, [MCP_SERVERS_FIELD, SERVER_KEY]);
25727
+ const entry = hostConfigValueAt(readParsed(row5.id, join17(dir, CODEX_PLUGIN_MCP_FILE)).value, [MCP_SERVERS_FIELD, SERVER_KEY]);
25307
25728
  if (!isObject4(entry)) return true;
25308
25729
  const args = list2(entry[MCP_ARGS_FIELD]);
25309
25730
  const script = args[0];
@@ -25374,17 +25795,17 @@ function opencodePluginDirs(configDir, worktree) {
25374
25795
  return [configDir, opencodeProjectDir(worktree)];
25375
25796
  }
25376
25797
  function opencodeProjectDir(worktree) {
25377
- return join16(worktree, OPENCODE_PROJECT_DIR);
25798
+ return join17(worktree, OPENCODE_PROJECT_DIR);
25378
25799
  }
25379
25800
  function packageResolves(fromDir) {
25380
25801
  for (let d = fromDir; ; d = dirname8(d)) {
25381
- if (existsSync11(join16(d, NODE_MODULES_DIR, SERVER_KEY, PACKAGE_JSON_FILE))) return true;
25802
+ if (existsSync11(join17(d, NODE_MODULES_DIR, SERVER_KEY, PACKAGE_JSON_FILE))) return true;
25382
25803
  if (dirname8(d) === d) return false;
25383
25804
  }
25384
25805
  }
25385
25806
  function opencodeDirPlugins(dirs) {
25386
25807
  const bundle = opencodePluginFile();
25387
- const ownFile = join16(bundle, ...OPENCODE_PLUGIN_PATH).split("\\").join("/");
25808
+ const ownFile = join17(bundle, ...OPENCODE_PLUGIN_PATH).split("\\").join("/");
25388
25809
  const isModule = (p) => OWN_PLUGIN_MODULES.includes(p);
25389
25810
  const isPath = (p) => {
25390
25811
  if (p === ownFile || p === `${FILE_URL_PREFIX}${ownFile}`) return true;
@@ -25394,20 +25815,20 @@ function opencodeDirPlugins(dirs) {
25394
25815
  };
25395
25816
  const out = [];
25396
25817
  for (const dir of dirs) {
25397
- const pdir = join16(dir, OPENCODE_PLUGINS_DIR);
25818
+ const pdir = join17(dir, OPENCODE_PLUGINS_DIR);
25398
25819
  let names;
25399
25820
  try {
25400
- names = readdirSync6(pdir);
25821
+ names = readdirSync7(pdir);
25401
25822
  } catch {
25402
25823
  continue;
25403
25824
  }
25404
25825
  for (const name of names) {
25405
- const loose = OPENCODE_PLUGIN_EXTS.some((x) => name.endsWith(x)) ? [join16(pdir, name)] : [];
25406
- const files = [...loose, ...OPENCODE_PLUGIN_EXTS.map((x) => join16(pdir, name, `${OPENCODE_PLUGIN_INDEX}${x}`))];
25826
+ const loose = OPENCODE_PLUGIN_EXTS.some((x) => name.endsWith(x)) ? [join17(pdir, name)] : [];
25827
+ const files = [...loose, ...OPENCODE_PLUGIN_EXTS.map((x) => join17(pdir, name, `${OPENCODE_PLUGIN_INDEX}${x}`))];
25407
25828
  for (const f of files) {
25408
25829
  let text;
25409
25830
  try {
25410
- const b = readFileSync13(f);
25831
+ const b = readFileSync14(f);
25411
25832
  if (b.length > OPENCODE_DIR_FILE_MAX) continue;
25412
25833
  text = b.toString("utf8");
25413
25834
  } catch {
@@ -25418,7 +25839,7 @@ function opencodeDirPlugins(dirs) {
25418
25839
  const loads = lits.some((p) => {
25419
25840
  if (isModule(p)) return packageResolves(dirname8(f));
25420
25841
  const bare2 = p.startsWith(FILE_URL_PREFIX) ? p.slice(FILE_URL_PREFIX.length) : p;
25421
- return existsSync11(isAbsolute5(bare2) ? bare2 : resolve9(dirname8(f), bare2));
25842
+ return existsSync11(isAbsolute6(bare2) ? bare2 : resolve9(dirname8(f), bare2));
25422
25843
  });
25423
25844
  out.push({ file: f, loads });
25424
25845
  }
@@ -25437,18 +25858,18 @@ function opencodeMcpOwn(entry) {
25437
25858
  }
25438
25859
  function opencodeFileValue(file2) {
25439
25860
  if (!existsSync11(file2)) return {};
25440
- return parseHostConfig("opencode", file2, hostText(readFileSync13(file2, "utf8")), "jsonc");
25861
+ return parseHostConfig("opencode", file2, hostText(readFileSync14(file2, "utf8")), "jsonc");
25441
25862
  }
25442
25863
  function opencodeValueListed(value) {
25443
25864
  const bundle = opencodePluginFile();
25444
- const own2 = [bundle, join16(bundle, ...OPENCODE_PLUGIN_PATH)];
25865
+ const own2 = [bundle, join17(bundle, ...OPENCODE_PLUGIN_PATH)];
25445
25866
  if ([OPENCODE_PLUGIN_KEY, OPENCODE_PLUGINS_KEY].some((key) => list2(isObject4(value) ? value[key] : void 0).some((e) => isOwnOpencodeEntry(e, key, own2)))) return true;
25446
25867
  const mcp = isObject4(value) && isObject4(value.mcp) ? value.mcp : {};
25447
25868
  return opencodeMcpOwn(mcp[SERVER_KEY]) || isObject4(mcp.servers) && opencodeMcpOwn(mcp.servers[SERVER_KEY]);
25448
25869
  }
25449
25870
  function opencodeListed(file2, worktree) {
25450
25871
  const dirs = [dirname8(file2), worktree];
25451
- if (dirs.some((dir) => OPENCODE_CONFIG_FILES.some((name) => opencodeValueListed(opencodeFileValue(join16(dir, name)))))) return true;
25872
+ if (dirs.some((dir) => OPENCODE_CONFIG_FILES.some((name) => opencodeValueListed(opencodeFileValue(join17(dir, name)))))) return true;
25452
25873
  return opencodeDirPlugin(opencodePluginDirs(dirname8(file2), worktree)) !== void 0;
25453
25874
  }
25454
25875
  function mcpWrong(row5, home, env, worktree) {
@@ -25470,7 +25891,7 @@ function mcpWrong(row5, home, env, worktree) {
25470
25891
  function hookFile(row5, spec, home, env, worktree) {
25471
25892
  const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
25472
25893
  const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
25473
- const file2 = native !== null ? join16(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join16(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join16(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join16(kiroDirOf(env, home), ...spec.file.slice(1)) : join16(root, ...spec.file);
25894
+ const file2 = native !== null ? join17(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join17(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join17(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join17(kiroDirOf(env, home), ...spec.file.slice(1)) : join17(root, ...spec.file);
25474
25895
  return file2;
25475
25896
  }
25476
25897
  function hookParts(row5, home, env, worktree) {
@@ -25481,7 +25902,7 @@ function hookParts(row5, home, env, worktree) {
25481
25902
  const file2 = hookFile(row5, spec, home, env, worktree);
25482
25903
  block = hostConfigValueAt(readParsed(row5.id, file2).value, spec.key);
25483
25904
  if (row5.id === "codex") {
25484
- const config2 = readParsed(row5.id, join16(codexDirOf(env, home), CONFIG_TOML_FILE)).value;
25905
+ const config2 = readParsed(row5.id, join17(codexDirOf(env, home), CONFIG_TOML_FILE)).value;
25485
25906
  if (hostConfigValueAt(config2, CODEX_FEATURES_HOOKS_KEY) === false) return [PART_HOOKS];
25486
25907
  }
25487
25908
  } catch {
@@ -25516,7 +25937,7 @@ function checkHostConfig(row5, env, worktree) {
25516
25937
  if ("installs" in choice) return fail3("D3", D3_ROOT_DETAIL(choice.installs.map((r) => r.installPath)), D3_ROOT_FIX(choice.installs));
25517
25938
  }
25518
25939
  if (row5.id === "pi") return checkPiInstall(env, home, worktree);
25519
- if (row5.id === "omp") return checkOmpInstall(home);
25940
+ if (row5.id === "omp") return checkOmpInstall(env, home);
25520
25941
  const parts = [...mcpWrong(row5, home, env, worktree) ? [PART_MCP] : [], ...hookParts(row5, home, env, worktree)];
25521
25942
  if (parts.length === 0) return pass2("D3");
25522
25943
  const detail = D3_DETAIL(parts);
@@ -25526,13 +25947,12 @@ function checkHostConfig(row5, env, worktree) {
25526
25947
  function checkPiInstall(env, home, worktree) {
25527
25948
  const found = piInstalledIn(env, home, ownBundleDir(), worktree);
25528
25949
  if (found !== void 0) return { ...pass2("D3"), detail: found };
25529
- return fail3("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + join16(piAgentDirOf(env, home), SETTINGS_FILE), NATIVE_INSTALL.pi[0]);
25950
+ return fail3("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + join17(piAgentDirOf(env, home), SETTINGS_FILE), NATIVE_INSTALL.pi[0]);
25530
25951
  }
25531
- var OMP_PLUGINS_DIR = "plugins";
25532
25952
  var OMP_LOCK_FILE = "omp-plugins.lock.json";
25533
25953
  function readJson2(file2) {
25534
25954
  try {
25535
- const doc = JSON.parse(readFileSync13(file2, "utf8"));
25955
+ const doc = JSON.parse(readFileSync14(file2, "utf8"));
25536
25956
  return typeof doc === "object" && doc !== null ? doc : void 0;
25537
25957
  } catch {
25538
25958
  return void 0;
@@ -25542,10 +25962,10 @@ function ownEntry(doc, key) {
25542
25962
  const map2 = doc?.[key];
25543
25963
  return typeof map2 === "object" && map2 !== null ? map2[SERVER_KEY] : void 0;
25544
25964
  }
25545
- function checkOmpInstall(home) {
25546
- const dir = join16(home, ...AGENT_HOME_DIR.omp, OMP_PLUGINS_DIR);
25547
- const lock = join16(dir, OMP_LOCK_FILE);
25548
- const pkg = join16(dir, PI_PACKAGE_JSON_FILE);
25965
+ function checkOmpInstall(env, home) {
25966
+ const dir = ompPluginsDirOf(env, home);
25967
+ const lock = join17(dir, OMP_LOCK_FILE);
25968
+ const pkg = join17(dir, PI_PACKAGE_JSON_FILE);
25549
25969
  const entry = ownEntry(readJson2(lock), "plugins");
25550
25970
  const missing2 = (file2) => fail3("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + file2, NATIVE_INSTALL.omp[0]);
25551
25971
  if (typeof entry !== "object" || entry === null) return missing2(lock);
@@ -25559,12 +25979,26 @@ function ompInfoLines(env, version2) {
25559
25979
  out.push(OMP_CONTENT_INFO, OMP_PRINT_MODE_INFO, OMP_SCRIPTS_INFO);
25560
25980
  const home = homeDirOf(env);
25561
25981
  if (home === null) return out;
25562
- const files = ompImportFiles(home);
25982
+ const files = ompImportFiles(env, home);
25563
25983
  if (!ompImportsUs(files, env)) return out;
25564
25984
  const listed = readJson2(files.mcp)?.[OMP_DISABLED_SERVERS_KEY];
25565
25985
  if (!(Array.isArray(listed) && listed.includes(SERVER_KEY))) out.push(OMP_IMPORT_INFO(files.claude, files.mcp));
25566
25986
  return out;
25567
25987
  }
25988
+ function replaceTriggerInfoLines(agent, env, project) {
25989
+ const files = [];
25990
+ const home = homeDirOf(env);
25991
+ if (agent === "claude-code") {
25992
+ if (home !== null) files.push(join17(claudeDirOf(env, home), SETTINGS_FILE));
25993
+ if (project !== void 0 && project !== "") files.push(join17(project, HOST_CONFIG_DIR_NAME, SETTINGS_FILE));
25994
+ }
25995
+ const where = [...new Set(files)].filter((f) => {
25996
+ const block = readJson2(f)?.env;
25997
+ return typeof block === "object" && block !== null && REPLACE_TRIGGER_ENV in block;
25998
+ });
25999
+ if (where.length > 0) return [REPLACE_TRIGGER_RETIRED_INFO(where.join(" and "))];
26000
+ return env[REPLACE_TRIGGER_ENV] === void 0 ? [] : [REPLACE_TRIGGER_RETIRED_INFO("the process env")];
26001
+ }
25568
26002
  function checkV1Leftovers(agent, home, scope = {}) {
25569
26003
  const findings = detectV1(agent, home, scope);
25570
26004
  if (findings.length === 0) return pass2("D4");
@@ -25582,10 +26016,10 @@ function parsedOrNull(agent, file2, jsonc) {
25582
26016
  }
25583
26017
  function checkDoubleFire(agent, worktree) {
25584
26018
  if (agent !== "claude-code" && agent !== "vscode") return pass2("D5b");
25585
- const claude = parsedOrNull(agent, join16(worktree, HOST_CONFIG_DIR_NAME, SETTINGS_FILE), false);
26019
+ const claude = parsedOrNull(agent, join17(worktree, HOST_CONFIG_DIR_NAME, SETTINGS_FILE), false);
25586
26020
  const hooks = isObject4(claude) ? claude[HOOKS_KEY] : void 0;
25587
26021
  const hooksOn = isObject4(hooks) && Object.keys(hooks).length > 0;
25588
- const vscode = parsedOrNull(agent, join16(worktree, VSCODE_DIR_NAME, VSCODE_SETTINGS_FILE), true);
26022
+ const vscode = parsedOrNull(agent, join17(worktree, VSCODE_DIR_NAME, VSCODE_SETTINGS_FILE), true);
25589
26023
  const useClaudeHooks = isObject4(vscode) && vscode[VSCODE_CLAUDE_HOOKS_SETTING] === true;
25590
26024
  return hooksOn && useClaudeHooks ? fail3("D5b", D5B_DETAIL, D5B_FIX) : pass2("D5b");
25591
26025
  }
@@ -25596,7 +26030,7 @@ function configPaths(row5, env, worktree) {
25596
26030
  const mcp = mcpFile(row5, home, env);
25597
26031
  if (mcp !== null) out.push({ label: "MCP entry", path: mcp });
25598
26032
  const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
25599
- if (native !== null) out.push({ label: "Codex plugin MCP", path: join16(native, CODEX_PLUGIN_MCP_FILE) });
26033
+ if (native !== null) out.push({ label: "Codex plugin MCP", path: join17(native, CODEX_PLUGIN_MCP_FILE) });
25600
26034
  const spec = HOOK_HOST_FILE[row5.id];
25601
26035
  if (spec !== null) {
25602
26036
  try {
@@ -25616,7 +26050,7 @@ function configPaths(row5, env, worktree) {
25616
26050
  }
25617
26051
 
25618
26052
  // src/core/ops/doctor-db.ts
25619
- import { existsSync as existsSync12, statSync as statSync6 } from "node:fs";
26053
+ import { existsSync as existsSync12, statSync as statSync7 } from "node:fs";
25620
26054
  var unknown3 = (id2, detail) => ({ id: id2, label: DOCTOR_LABEL[id2], status: "UNKNOWN", detail });
25621
26055
  var pass3 = (id2, detail) => ({ id: id2, label: DOCTOR_LABEL[id2], status: "PASS", detail });
25622
26056
  var fail4 = (detail, fixCommand) => ({ id: "D8", label: DOCTOR_LABEL.D8, status: "FAIL", detail, fixCommand });
@@ -25627,7 +26061,7 @@ function isCorrupt2(err) {
25627
26061
  const primary = code & SQLITE_PRIMARY_CODE_MASK;
25628
26062
  return primary === SQLITE_CORRUPT_CODE || primary === SQLITE_NOTADB_CODE;
25629
26063
  }
25630
- var message2 = (err) => err instanceof Error ? err.message : String(err);
26064
+ var message3 = (err) => err instanceof Error ? err.message : String(err);
25631
26065
  async function loadSqlite2() {
25632
26066
  try {
25633
26067
  return await import(SQLITE_MODULE);
@@ -25658,7 +26092,7 @@ function orphanFiles(dbPath) {
25658
26092
  const files = [];
25659
26093
  for (const suffix of [DB_WAL_SUFFIX, DB_SHM_SUFFIX]) {
25660
26094
  const path8 = dbPath + suffix;
25661
- if (existsSync12(path8)) files.push({ path: path8, bytes: statSync6(path8).size });
26095
+ if (existsSync12(path8)) files.push({ path: path8, bytes: statSync7(path8).size });
25662
26096
  }
25663
26097
  return files.length > 0 && !existsSync12(dbPath) ? files : [];
25664
26098
  }
@@ -25686,7 +26120,7 @@ async function checkDb(project) {
25686
26120
  return { row: pass3("D8", DOCTOR_PASS_DETAIL), ...clean };
25687
26121
  } catch (err) {
25688
26122
  if (isCorrupt2(err)) return { row: fail4(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true, orphan: [] };
25689
- return { row: unknown3("D8", message2(err)), ...clean };
26123
+ return { row: unknown3("D8", message3(err)), ...clean };
25690
26124
  } finally {
25691
26125
  raw?.close();
25692
26126
  }
@@ -25702,14 +26136,14 @@ async function checkIndex(project) {
25702
26136
  const chunks = Number(cell(raw.prepare("SELECT count(*) FROM chunks").get()));
25703
26137
  return pass3("D9", D9_INDEX_DETAIL(sources, chunks));
25704
26138
  } catch (err) {
25705
- return unknown3("D9", message2(err));
26139
+ return unknown3("D9", message3(err));
25706
26140
  } finally {
25707
26141
  raw?.close();
25708
26142
  }
25709
26143
  }
25710
26144
 
25711
26145
  // src/core/ops/doctor-hook.ts
25712
- import { existsSync as existsSync14, mkdirSync as mkdirSync4, mkdtempSync, readFileSync as readFileSync14, realpathSync as realpathSync8, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
26146
+ import { existsSync as existsSync14, mkdirSync as mkdirSync5, mkdtempSync, readFileSync as readFileSync15, realpathSync as realpathSync8, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
25713
26147
  import { tmpdir as tmpdir2 } from "node:os";
25714
26148
  import path7 from "node:path";
25715
26149
 
@@ -27543,7 +27977,7 @@ import { spawn as spawn3, spawnSync as spawnSync2 } from "node:child_process";
27543
27977
 
27544
27978
  // src/setup/spawn-bin.ts
27545
27979
  import { spawnSync } from "node:child_process";
27546
- import { accessSync as accessSync2, constants as fsc, statSync as statSync7 } from "node:fs";
27980
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync8 } from "node:fs";
27547
27981
  import path5 from "node:path";
27548
27982
  var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
27549
27983
  var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
@@ -27561,7 +27995,7 @@ function whichBin(bin, env, platform = process.platform) {
27561
27995
  const f = path5.join(dir, n);
27562
27996
  try {
27563
27997
  accessSync2(f, fsc.X_OK);
27564
- if (statSync7(f).isFile()) return f;
27998
+ if (statSync8(f).isFile()) return f;
27565
27999
  } catch {
27566
28000
  }
27567
28001
  }
@@ -27763,7 +28197,7 @@ function loadFixture(bundleDir2, agent) {
27763
28197
  if (!existsSync14(file2)) return { cause: D5_FIXTURE_FILE_ABSENT(file2) };
27764
28198
  let all;
27765
28199
  try {
27766
- all = JSON.parse(hostText(readFileSync14(file2, "utf8")));
28200
+ all = JSON.parse(hostText(readFileSync15(file2, "utf8")));
27767
28201
  } catch (err) {
27768
28202
  return { cause: D5_FIXTURE_PARSE(file2, err instanceof Error ? err.message : String(err)) };
27769
28203
  }
@@ -27855,7 +28289,7 @@ async function mediaProbe(i, timeoutMs) {
27855
28289
  const home = mkdtempSync(path7.join(tmpdir2(), "cm-d5-media-"));
27856
28290
  try {
27857
28291
  const filePath = path7.join(home, "d5-media-probe.png");
27858
- writeFileSync2(filePath, Buffer.concat([PNG_SIGNATURE, Buffer.alloc(OUTPUT_CAP + 1)]));
28292
+ writeFileSync3(filePath, Buffer.concat([PNG_SIGNATURE, Buffer.alloc(OUTPUT_CAP + 1)]));
27859
28293
  const node = nodeLaunch({ ...i.env, HOME: home, USERPROFILE: home });
27860
28294
  const r = await runProcess([node.file, path7.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
27861
28295
  cwd: i.bundleDir,
@@ -27882,9 +28316,9 @@ async function ownProbe(i, timeoutMs) {
27882
28316
  try {
27883
28317
  const cfg = path7.join(home, ".claude");
27884
28318
  const refs = path7.join(cfg, "skills", "d5-probe", "references");
27885
- mkdirSync4(refs, { recursive: true });
28319
+ mkdirSync5(refs, { recursive: true });
27886
28320
  const filePath = path7.join(refs, "d5-own-probe.md");
27887
- writeFileSync2(filePath, "# d5 own probe\n".repeat(Math.ceil((OUTPUT_CAP + 1) / 15)));
28321
+ writeFileSync3(filePath, "# d5 own probe\n".repeat(Math.ceil((OUTPUT_CAP + 1) / 15)));
27888
28322
  const node = nodeLaunch({ ...i.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: cfg });
27889
28323
  const r = await runProcess([node.file, path7.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
27890
28324
  cwd: i.bundleDir,
@@ -28038,14 +28472,14 @@ async function checkHookRoundTrip(i) {
28038
28472
  }
28039
28473
 
28040
28474
  // src/core/ops/db-heal.ts
28041
- import { existsSync as existsSync15, mkdirSync as mkdirSync6, rmSync as rmSync4 } from "node:fs";
28042
- import { basename as basename4, dirname as dirname9, join as join18 } from "node:path";
28475
+ import { existsSync as existsSync15, mkdirSync as mkdirSync7, rmSync as rmSync4 } from "node:fs";
28476
+ import { basename as basename4, dirname as dirname9, join as join19 } from "node:path";
28043
28477
 
28044
28478
  // src/core/store/owners.ts
28045
- import { mkdirSync as mkdirSync5, readdirSync as readdirSync7, readFileSync as readFileSync15, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "node:fs";
28046
- import { basename as basename3, join as join17 } from "node:path";
28479
+ import { mkdirSync as mkdirSync6, readdirSync as readdirSync8, readFileSync as readFileSync16, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
28480
+ import { basename as basename3, join as join18 } from "node:path";
28047
28481
  function ownersDir(configDir, projectKey) {
28048
- return join17(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
28482
+ return join18(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
28049
28483
  }
28050
28484
  function errCode3(err) {
28051
28485
  return err.code;
@@ -28065,7 +28499,7 @@ function listLiveOwners(configDir, projectKey) {
28065
28499
  const dir = ownersDir(configDir, projectKey);
28066
28500
  let names;
28067
28501
  try {
28068
- names = readdirSync7(dir);
28502
+ names = readdirSync8(dir);
28069
28503
  } catch (err) {
28070
28504
  if (errCode3(err) === "ENOENT") return [];
28071
28505
  throw err;
@@ -28073,10 +28507,10 @@ function listLiveOwners(configDir, projectKey) {
28073
28507
  const live = [];
28074
28508
  for (const name of names) {
28075
28509
  if (!name.endsWith(OWNER_PID_EXT)) continue;
28076
- const file2 = join17(dir, name);
28510
+ const file2 = join18(dir, name);
28077
28511
  let text;
28078
28512
  try {
28079
- text = readFileSync15(file2, "utf8");
28513
+ text = readFileSync16(file2, "utf8");
28080
28514
  } catch (err) {
28081
28515
  if (errCode3(err) === "ENOENT") continue;
28082
28516
  throw err;
@@ -28145,11 +28579,11 @@ function utcStamp(now) {
28145
28579
  return now.toISOString().slice(0, 19).replaceAll("-", "").replaceAll(":", "") + "Z";
28146
28580
  }
28147
28581
  function makeOrphanDir(projectDir) {
28148
- const base = join18(projectDir, ORPHAN_DIR_PREFIX + utcStamp(/* @__PURE__ */ new Date()));
28582
+ const base = join19(projectDir, ORPHAN_DIR_PREFIX + utcStamp(/* @__PURE__ */ new Date()));
28149
28583
  for (let n = 1; ; n += 1) {
28150
28584
  const dir = n === 1 ? base : base + "-" + String(n);
28151
28585
  try {
28152
- mkdirSync6(dir);
28586
+ mkdirSync7(dir);
28153
28587
  return dir;
28154
28588
  } catch (err) {
28155
28589
  if (err.code !== "EEXIST") throw err;
@@ -28162,7 +28596,7 @@ async function healOrphan(project, files, row5) {
28162
28596
  try {
28163
28597
  dir = makeOrphanDir(dirname9(project.dbPath));
28164
28598
  for (const f of files) {
28165
- const to = join18(dir, basename4(f.path));
28599
+ const to = join19(dir, basename4(f.path));
28166
28600
  renameWithRetry(f.path, to);
28167
28601
  moved.push({ path: to, bytes: f.bytes });
28168
28602
  }
@@ -28260,8 +28694,8 @@ function unsupportedHostOf(sig) {
28260
28694
 
28261
28695
  // src/core/ops/doctor-issue.ts
28262
28696
  import { spawnSync as spawnSync3 } from "node:child_process";
28263
- import { closeSync as closeSync2, existsSync as existsSync16, fstatSync, mkdirSync as mkdirSync7, openSync as openSync2, readFileSync as readFileSync16, readSync as readSync2, realpathSync as realpathSync9, writeFileSync as writeFileSync4 } from "node:fs";
28264
- import { delimiter, dirname as dirname10, join as join19 } from "node:path";
28697
+ import { closeSync as closeSync2, existsSync as existsSync16, fstatSync, mkdirSync as mkdirSync8, openSync as openSync2, readFileSync as readFileSync17, readSync as readSync2, realpathSync as realpathSync9, writeFileSync as writeFileSync5 } from "node:fs";
28698
+ import { delimiter, dirname as dirname10, join as join20 } from "node:path";
28265
28699
  var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
28266
28700
  function tildeOf(env) {
28267
28701
  const home = homeDirOf(env);
@@ -28317,8 +28751,8 @@ function onPath(env, tool) {
28317
28751
  const out = [];
28318
28752
  for (const dir of (envValue(env, "PATH") ?? "").split(delimiter)) {
28319
28753
  if (dir === "") continue;
28320
- for (const n of names) if (existsSync16(join19(dir, n))) {
28321
- out.push(join19(dir, n));
28754
+ for (const n of names) if (existsSync16(join20(dir, n))) {
28755
+ out.push(join20(dir, n));
28322
28756
  break;
28323
28757
  }
28324
28758
  }
@@ -28346,9 +28780,11 @@ function hookLogTail(env) {
28346
28780
  }
28347
28781
  async function journalRows(ctx) {
28348
28782
  const head2 = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
28349
- if (!existsSync16(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
28783
+ const p = projectOrMissing(ctx);
28784
+ if ("missing" in p) return [`(no project: ${D7_NO_PROJECT_DETAIL(p.missing)})`];
28785
+ if (!existsSync16(p.project.dbPath)) return [`(context.db is absent at ${p.project.dbPath})`];
28350
28786
  try {
28351
- const db = await openDb(ctx.project, { readOnly: true });
28787
+ const db = await openDb(p.project, { readOnly: true });
28352
28788
  try {
28353
28789
  const rows = db.raw.prepare(`SELECT kind, tool, bytes, ok, exit_code, created_at FROM events ORDER BY seq DESC LIMIT ${DOCTOR_JOURNAL_ROWS}`).all();
28354
28790
  const cell5 = (v) => v === null || v === void 0 ? "" : String(v);
@@ -28364,8 +28800,8 @@ function agentConfig(adapter, env, worktree) {
28364
28800
  const home = homeDirOf(env);
28365
28801
  const files = configPaths(adapter, env, worktree);
28366
28802
  if (home !== null) {
28367
- if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join19(claudeDirOf(env, home), SETTINGS_FILE) });
28368
- if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join19(codexDirOf(env, home), CONFIG_TOML_FILE) });
28803
+ if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join20(claudeDirOf(env, home), SETTINGS_FILE) });
28804
+ if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join20(codexDirOf(env, home), CONFIG_TOML_FILE) });
28369
28805
  }
28370
28806
  const out = [];
28371
28807
  const seen = /* @__PURE__ */ new Set();
@@ -28378,7 +28814,7 @@ function agentConfig(adapter, env, worktree) {
28378
28814
  }
28379
28815
  let text = "";
28380
28816
  try {
28381
- text = readFileSync16(f.path, "utf8");
28817
+ text = readFileSync17(f.path, "utf8");
28382
28818
  } catch (err) {
28383
28819
  out.push(`${f.label}: ${f.path} (read: ${err instanceof Error ? err.message : String(err)})`);
28384
28820
  continue;
@@ -28407,6 +28843,7 @@ async function buildIssueBody(i) {
28407
28843
  const failRows = i.rows.filter((r) => r.status !== "PASS");
28408
28844
  const envNames = DOCTOR_ENV_NAMES.map((n) => i.env[n] === void 0 ? `${n} (unset)` : `${n}=${i.env[n]}`);
28409
28845
  const pathTools = DOCTOR_PATH_TOOLS.map((t) => `PATH holds ${t}: ${onPath(i.env, t).join(", ") || "(absent)"}`);
28846
+ const p = projectOrMissing(i.ctx);
28410
28847
  const sections = {
28411
28848
  "Summary": [summaryOf(agent, i.rows, i.unsupported)],
28412
28849
  "ctx-report": [i.table],
@@ -28417,7 +28854,7 @@ async function buildIssueBody(i) {
28417
28854
  ],
28418
28855
  "Hook errors": ["hook-errors.log, last " + DOCTOR_HOOK_LOG_LINES + " lines (UTC):", "```", ...hookLogTail(i.env), "```"],
28419
28856
  "Journal rows": ["events, newest first, last " + DOCTOR_JOURNAL_ROWS + " (bodies stay local):", ...await journalRows(i.ctx)],
28420
- "Agent config": agentConfig(i.adapter, i.env, i.ctx.project.worktree),
28857
+ "Agent config": agentConfig(i.adapter, i.env, "project" in p ? p.project.worktree : process.cwd()),
28421
28858
  "Expected": ["Expected: <the agent fills this in: what should happen, with the byte count>"],
28422
28859
  "Steps": [
28423
28860
  "Reproduced: <yes (2 of 2) or 1 of 2>",
@@ -28438,7 +28875,7 @@ async function buildIssueBody(i) {
28438
28875
  `git: ${gitVersion(i.env)}`,
28439
28876
  ...pathTools,
28440
28877
  ...envNames,
28441
- `Project: ${i.ctx.project.worktree} (key ${i.ctx.project.projectKey})`,
28878
+ "project" in p ? `Project: ${p.project.worktree} (key ${p.project.projectKey})` : `Project: ${D7_NO_PROJECT_DETAIL(p.missing)}`,
28442
28879
  "Filed by: <your agent name, version, model id>"
28443
28880
  ]
28444
28881
  };
@@ -28449,10 +28886,10 @@ async function buildIssueBody(i) {
28449
28886
  async function writeIssueReport(i) {
28450
28887
  const tilde = tildeOf(i.env);
28451
28888
  const body = await buildIssueBody(i);
28452
- const dir = join19(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
28453
- mkdirSync7(dir, { recursive: true });
28454
- const file2 = join19(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
28455
- writeFileSync4(file2, body);
28889
+ const dir = join20(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
28890
+ mkdirSync8(dir, { recursive: true });
28891
+ const file2 = join20(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
28892
+ writeFileSync5(file2, body);
28456
28893
  const shown2 = tilde(file2);
28457
28894
  const title = issueTitle(i.adapter.id, i.rows, i.unsupported);
28458
28895
  const gh = [`gh issue create --repo ${ISSUE_REPO_SLUG} --label bug \\`, `${DOCTOR_GH_NEXT}title ${JSON.stringify(title)} \\`, `${DOCTOR_GH_NEXT}body-file ${shown2}`];
@@ -28464,6 +28901,25 @@ function formUrl(title, summary) {
28464
28901
  return full.length < ISSUE_URL_MAX ? full : base;
28465
28902
  }
28466
28903
 
28904
+ // src/core/index/text.ts
28905
+ function storeText(db, project, sessionId, sourceKind, label2, text, kind, chunks = chunkText(text, kind)) {
28906
+ const sourceId = ftsInsert(db, {
28907
+ projectKey: project.projectKey,
28908
+ sessionId,
28909
+ worktree: project.worktree,
28910
+ agent: project.agent,
28911
+ kind: sourceKind,
28912
+ label: label2,
28913
+ bytes: Buffer.byteLength(text, "utf8"),
28914
+ chunkCount: chunks.length,
28915
+ createdAt: Date.now()
28916
+ }, chunks);
28917
+ return { sourceId, chunks: chunks.length };
28918
+ }
28919
+ function indexText(db, ctx, sessionId, source, text, kind, chunks) {
28920
+ return storeText(db, ctx, sessionId, "content", source, text, kind, chunks);
28921
+ }
28922
+
28467
28923
  // src/core/tools/doctor.ts
28468
28924
  var ctxDoctorSchema = external_exports.object({}).strict();
28469
28925
  function lineOf2(err) {
@@ -28477,10 +28933,10 @@ async function guard(id2, run) {
28477
28933
  return { id: id2, label: DOCTOR_LABEL[id2], status: "UNKNOWN", detail: lineOf2(err) };
28478
28934
  }
28479
28935
  }
28480
- async function codexDb(ctx, adapter) {
28481
- if (adapter.id !== "codex" || !existsSync17(ctx.project.dbPath)) return null;
28936
+ async function codexDb(project, adapter) {
28937
+ if (adapter.id !== "codex" || !existsSync17(project.dbPath)) return null;
28482
28938
  try {
28483
- return await openDb(ctx.project, { readOnly: true });
28939
+ return await openDb(project, { readOnly: true });
28484
28940
  } catch {
28485
28941
  return null;
28486
28942
  }
@@ -28491,12 +28947,12 @@ function d1UpdateCommand(agent, env, other) {
28491
28947
  function unsupportedRow(id2, h) {
28492
28948
  return { id: id2, label: DOCTOR_LABEL[id2], status: "WARN", detail: UNSUPPORTED_HOST_LINE(h.name) };
28493
28949
  }
28494
- async function hookRow(ctx, adapter, host) {
28495
- const db = await codexDb(ctx, adapter);
28950
+ async function hookRow(ctx, project, adapter, host) {
28951
+ const db = await codexDb(project, adapter);
28496
28952
  const runStart = Date.now();
28497
28953
  try {
28498
28954
  const row5 = await checkHookRoundTrip({
28499
- worktree: ctx.project.worktree,
28955
+ worktree: project.worktree,
28500
28956
  agent: adapter.id,
28501
28957
  bundleDir: host.bundleDir,
28502
28958
  env: buildChildEnv(host.env),
@@ -28514,18 +28970,20 @@ async function hookRow(ctx, adapter, host) {
28514
28970
  }
28515
28971
  }
28516
28972
  function ownServerId(configDir, projectKey) {
28517
- const dir = join20(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
28973
+ const dir = join21(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
28518
28974
  if (!existsSync17(dir)) return "";
28519
- for (const name of readdirSync8(dir)) {
28975
+ for (const name of readdirSync9(dir)) {
28520
28976
  if (!name.endsWith(OWNER_PID_EXT)) continue;
28521
- if (readFileSync17(join20(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
28977
+ if (readFileSync18(join21(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
28522
28978
  }
28523
28979
  return "";
28524
28980
  }
28525
28981
  async function runDoctorChecks(ctx, adapter, host0) {
28526
28982
  const host = adapter.id === "codex" ? { ...host0, env: { ...host0.env, CODEX_HOME: codexRunDirOf(host0.env, homeDirOf(host0.env) ?? "", host0.bundleDir) } } : host0;
28527
28983
  const env = host.env;
28528
- const project = ctx.project;
28984
+ const p = projectOrMissing(ctx);
28985
+ if ("missing" in p) return noProjectRows(ctx, adapter, host, p.missing);
28986
+ const project = p.project;
28529
28987
  const other = adapter.installMode === "in-process" ? void 0 : unsupportedHostOf({ clientName: ctx.clientInfo?.name, bundleDir: host.bundleDir, env });
28530
28988
  let integrityFailed = false;
28531
28989
  let orphan = [];
@@ -28535,7 +28993,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
28535
28993
  D3: () => other !== void 0 ? unsupportedRow("D3", other) : checkHostConfig(adapter, env, project.worktree),
28536
28994
  // D-UNSUPPORTED-HOSTS-1
28537
28995
  D4: () => checkV1Leftovers(adapter.id, requireHomeDir(env), { project: project.worktree, piAgentDir: piAgentDirOf(env, requireHomeDir(env)), claudeDir: claudeDirOf(env, requireHomeDir(env)), codexDir: codexDirOf(env, requireHomeDir(env)), geminiDir: geminiDirOf(env, requireHomeDir(env)), copilotDir: copilotDirOf(env, requireHomeDir(env)), kiroDir: kiroDirOf(env, requireHomeDir(env)), opencodeDir: opencodeDirOf(env, requireHomeDir(env)) }),
28538
- D5: () => other !== void 0 ? unsupportedRow("D5", other) : hookRow(ctx, adapter, host),
28996
+ D5: () => other !== void 0 ? unsupportedRow("D5", other) : hookRow(ctx, project, adapter, host),
28539
28997
  D5b: () => checkDoubleFire(adapter.id, project.worktree),
28540
28998
  D6: () => checkMcp(ctx, adapter),
28541
28999
  D7: () => checkProject({ project, adapter, piCwd: host.piCwd }),
@@ -28565,6 +29023,28 @@ async function runDoctorChecks(ctx, adapter, host0) {
28565
29023
  });
28566
29024
  return rows;
28567
29025
  }
29026
+ async function noProjectRows(ctx, adapter, host, missing2) {
29027
+ const env = host.env;
29028
+ const other = adapter.installMode === "in-process" ? void 0 : unsupportedHostOf({ clientName: ctx.clientInfo?.name, bundleDir: host.bundleDir, env });
29029
+ const wait = (id2) => () => needsProjectRow(id2);
29030
+ const checks = {
29031
+ D1: () => checkVersion({ bundleSha: BUNDLE_SHA, version: bundleVersion(host.bundleDir), registryUrl: D1_REGISTRY_URL, timeoutMs: DOCTOR_GIT_TIMEOUT_MS, env: buildChildEnv(env), cwd: process.cwd(), signal: ctx.signal, updateCommand: d1UpdateCommand(adapter.id, env, other) }),
29032
+ D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
29033
+ D3: other !== void 0 ? () => unsupportedRow("D3", other) : wait("D3"),
29034
+ D4: () => checkV1Leftovers(adapter.id, requireHomeDir(env), { piAgentDir: piAgentDirOf(env, requireHomeDir(env)), claudeDir: claudeDirOf(env, requireHomeDir(env)), codexDir: codexDirOf(env, requireHomeDir(env)), geminiDir: geminiDirOf(env, requireHomeDir(env)), copilotDir: copilotDirOf(env, requireHomeDir(env)), kiroDir: kiroDirOf(env, requireHomeDir(env)), opencodeDir: opencodeDirOf(env, requireHomeDir(env)) }),
29035
+ D5: other !== void 0 ? () => unsupportedRow("D5", other) : wait("D5"),
29036
+ D5b: wait("D5b"),
29037
+ D6: () => checkMcp(ctx, adapter),
29038
+ D7: () => noProjectRow(missing2),
29039
+ D8: wait("D8"),
29040
+ D9: wait("D9"),
29041
+ D10: () => checkMode(adapter, ctx.hostPermission),
29042
+ D11: () => checkRuntimes(env, checkShell(env))
29043
+ };
29044
+ const rows = [];
29045
+ for (const id2 of DOCTOR_CHECK_ORDER) rows.push(await guard(id2, checks[id2]));
29046
+ return rows;
29047
+ }
28568
29048
  function reportEnv(env) {
28569
29049
  const out = {};
28570
29050
  for (const key of Object.keys(REPORT_ENV_ENUMS)) {
@@ -28574,7 +29054,7 @@ function reportEnv(env) {
28574
29054
  return out;
28575
29055
  }
28576
29056
  async function doctorReply(ctx, host) {
28577
- const adapter = getAdapter(ctx.project.agent);
29057
+ const adapter = getAdapter(ctx.agent ?? ctx.project.agent);
28578
29058
  const runtime = runtimeInfo(host.env, ctx.signal);
28579
29059
  const rows = await runDoctorChecks(ctx, adapter, host);
28580
29060
  const failed = rows.some((r) => r.status === "FAIL");
@@ -28593,12 +29073,16 @@ async function doctorReply(ctx, host) {
28593
29073
  const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
28594
29074
  const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
28595
29075
  const info = adapter.id === "omp" ? ompInfoLines(host.env, ctx.clientInfo?.version) : [];
29076
+ const known = projectOrMissing(ctx);
29077
+ info.push(...replaceTriggerInfoLines(adapter.id, host.env, "missing" in known ? host.env.CLAUDE_PROJECT_DIR : known.project.worktree));
28596
29078
  const whole2 = [envLine2, table3, ...docs, ...info, ...notes].join("\n");
28597
29079
  const bytes5 = Buffer.byteLength(whole2, "utf8");
28598
29080
  if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
28599
- const db = await openDb(ctx.project);
29081
+ const p = known;
29082
+ if ("missing" in p) return { text: whole2, isError: false, sandboxBytes: bytes5 };
29083
+ const db = await openDb(p.project);
28600
29084
  try {
28601
- indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
29085
+ indexText(db, p.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
28602
29086
  } finally {
28603
29087
  closeDb(db);
28604
29088
  }
@@ -28623,9 +29107,9 @@ var ctxDoctor = Object.freeze({
28623
29107
  });
28624
29108
 
28625
29109
  // src/core/tools/execute.ts
28626
- import { existsSync as existsSync18, mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as writeFileSync5 } from "node:fs";
29110
+ import { existsSync as existsSync18, mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as writeFileSync6 } from "node:fs";
28627
29111
  import { tmpdir as tmpdir3 } from "node:os";
28628
- import { dirname as dirname12, join as join21, parse as parse3, resolve as resolve11 } from "node:path";
29112
+ import { dirname as dirname12, join as join22, parse as parse3, resolve as resolve11 } from "node:path";
28629
29113
 
28630
29114
  // src/core/sandbox/win-build.ts
28631
29115
  var SEPARATORS2 = ";&|(\n";
@@ -28706,11 +29190,11 @@ function schemaLine(issue2) {
28706
29190
  if (issue2.code === "unrecognized_keys") return new CtxError("UNKNOWN_FIELD", { f: issue2.keys[0] }).toLine();
28707
29191
  return issue2.message;
28708
29192
  }
28709
- function fileError(given, abs, root) {
29193
+ function fileError(given, abs, root, hostRoots) {
28710
29194
  let dir = abs;
28711
29195
  while (!existsSync18(dir) && dirname12(dir) !== dir) dir = dirname12(dir);
28712
- if (isInside(root, dir)) return null;
28713
- return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
29196
+ if (allowedRootOf(root, hostRoots, dir) !== void 0) return null;
29197
+ return { ...fail5(new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine()), outsideRoot: true };
28714
29198
  }
28715
29199
  function takesDashC(language, runtime) {
28716
29200
  if (language === "shell") return true;
@@ -28773,8 +29257,8 @@ async function handler3(raw, ctx) {
28773
29257
  const extra = { ...PLAIN_OUTPUT_ENV2 };
28774
29258
  if (input.file !== void 0) {
28775
29259
  const abs = resolve11(cwd, input.file);
28776
- const bad = fileError(input.file, abs, ctx.project.containmentRoot);
28777
- if (bad !== null) return fail5(bad);
29260
+ const bad = fileError(input.file, abs, ctx.project.containmentRoot, ctx.hostRoots);
29261
+ if (bad !== null) return bad;
28778
29262
  extra.CTX_FILE = abs;
28779
29263
  }
28780
29264
  let runtime;
@@ -28794,9 +29278,9 @@ async function handler3(raw, ctx) {
28794
29278
  if (takesDashC(input.language, runtime)) {
28795
29279
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
28796
29280
  } else {
28797
- tmpDir = mkdtempSync2(join21(tmpdir3(), TMP_PREFIX));
28798
- const file2 = join21(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
28799
- writeFileSync5(file2, scriptText(input.language, input.code), "utf8");
29281
+ tmpDir = mkdtempSync2(join22(tmpdir3(), TMP_PREFIX));
29282
+ const file2 = join22(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
29283
+ writeFileSync6(file2, scriptText(input.language, input.code), "utf8");
28800
29284
  argv = scriptArgv(input.language, runtime, file2);
28801
29285
  }
28802
29286
  if (input.background === true) {
@@ -28831,12 +29315,12 @@ var ctxExecute = {
28831
29315
  };
28832
29316
 
28833
29317
  // src/core/tools/index.ts
28834
- import { existsSync as existsSync19, readFileSync as readFileSync20, statSync as statSync9 } from "node:fs";
28835
- import { dirname as dirname13, extname as extname3, join as join24, relative as relative5, resolve as resolve12 } from "node:path";
29318
+ import { existsSync as existsSync19, readFileSync as readFileSync21, statSync as statSync10 } from "node:fs";
29319
+ import { dirname as dirname13, extname as extname3, join as join25, relative as relative5, resolve as resolve12 } from "node:path";
28836
29320
 
28837
29321
  // src/core/index/walk.ts
28838
- import { readdirSync as readdirSync9, readFileSync as readFileSync18, realpathSync as realpathSync10, statSync as statSync8 } from "node:fs";
28839
- import { join as join22 } from "node:path";
29322
+ import { readdirSync as readdirSync10, readFileSync as readFileSync19, realpathSync as realpathSync10, statSync as statSync9 } from "node:fs";
29323
+ import { join as join23 } from "node:path";
28840
29324
  var GITIGNORE = ".gitignore";
28841
29325
  var GIT_DIR = ".git";
28842
29326
  function walkDir(root, containmentRoot) {
@@ -28845,19 +29329,19 @@ function walkDir(root, containmentRoot) {
28845
29329
  const found = [];
28846
29330
  visit(real3, [], [], containmentRoot, /* @__PURE__ */ new Set([real3]), found);
28847
29331
  found.sort(compareFound);
28848
- return found.map((f) => ({ absPath: f.absPath, relPath: join22(...f.dir, f.name) }));
29332
+ return found.map((f) => ({ absPath: f.absPath, relPath: join23(...f.dir, f.name) }));
28849
29333
  }
28850
29334
  function visit(abs, rel, parent, contain, seen, found) {
28851
29335
  let entries;
28852
29336
  try {
28853
- entries = readdirSync9(abs, { withFileTypes: true });
29337
+ entries = readdirSync10(abs, { withFileTypes: true });
28854
29338
  } catch {
28855
29339
  return;
28856
29340
  }
28857
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join22(abs, GITIGNORE), rel)) : parent;
29341
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join23(abs, GITIGNORE), rel)) : parent;
28858
29342
  for (const e of entries) {
28859
29343
  if (e.name === GIT_DIR) continue;
28860
- const path8 = join22(abs, e.name);
29344
+ const path8 = join23(abs, e.name);
28861
29345
  let isDir = e.isDirectory();
28862
29346
  let isFile = e.isFile();
28863
29347
  let target = path8;
@@ -28869,7 +29353,7 @@ function visit(abs, rel, parent, contain, seen, found) {
28869
29353
  continue;
28870
29354
  }
28871
29355
  if (!isInside(contain, resolved)) continue;
28872
- const st = statSync8(resolved);
29356
+ const st = statSync9(resolved);
28873
29357
  isDir = st.isDirectory();
28874
29358
  isFile = st.isFile();
28875
29359
  target = resolved;
@@ -28897,7 +29381,7 @@ function compareFound(a, b) {
28897
29381
  function readRules(file2, base) {
28898
29382
  let body;
28899
29383
  try {
28900
- body = readFileSync18(file2, "utf8");
29384
+ body = readFileSync19(file2, "utf8");
28901
29385
  } catch {
28902
29386
  return [];
28903
29387
  }
@@ -28980,12 +29464,13 @@ function globSeg(pat, name) {
28980
29464
  }
28981
29465
 
28982
29466
  // src/core/sandbox/fetch.ts
28983
- import { readFileSync as readFileSync19 } from "node:fs";
29467
+ import { randomBytes } from "node:crypto";
29468
+ import { readFileSync as readFileSync20 } from "node:fs";
28984
29469
  import { lookup } from "node:dns/promises";
28985
29470
  import http from "node:http";
28986
29471
  import https from "node:https";
28987
29472
  import { BlockList, isIP } from "node:net";
28988
- import { join as join23 } from "node:path";
29473
+ import { join as join24 } from "node:path";
28989
29474
  import { connect as tlsConnect } from "node:tls";
28990
29475
  var PRIVATE_RANGES = [
28991
29476
  ["127.0.0.0", 8, "ipv4"],
@@ -29014,6 +29499,26 @@ var PRIVATE_RANGES = [
29014
29499
  ];
29015
29500
  var BLOCKED = new BlockList();
29016
29501
  for (const [net, prefix, type] of PRIVATE_RANGES) BLOCKED.addSubnet(net, prefix, type);
29502
+ var FAKE_IP_POOL = new BlockList();
29503
+ FAKE_IP_POOL.addSubnet("198.18.0.0", 15, "ipv4");
29504
+ var FAKE_IP_PROBE_TLD = ".invalid";
29505
+ var FAKE_IP_PROBE_BYTES = 8;
29506
+ var FAKE_IP_PROBE_MS = 1500;
29507
+ var fakeIpProbe;
29508
+ function inFakeIpPool(address) {
29509
+ return isIP(address) === 4 && FAKE_IP_POOL.check(address, "ipv4");
29510
+ }
29511
+ function fakeIpResolver() {
29512
+ fakeIpProbe ??= new Promise((resolve14) => {
29513
+ const timer = setTimeout(() => resolve14(false), FAKE_IP_PROBE_MS);
29514
+ timer.unref();
29515
+ lookup(randomBytes(FAKE_IP_PROBE_BYTES).toString("hex") + FAKE_IP_PROBE_TLD, { all: true }).then(
29516
+ (addrs) => resolve14(addrs.length > 0 && addrs.every((a) => inFakeIpPool(a.address))),
29517
+ () => resolve14(false)
29518
+ ).finally(() => clearTimeout(timer));
29519
+ });
29520
+ return fakeIpProbe;
29521
+ }
29017
29522
  var STATUS_OK_FIRST = 200;
29018
29523
  var STATUS_OK_END = 300;
29019
29524
  var STATUS_REDIRECT = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
@@ -29024,7 +29529,7 @@ function baseHeaders() {
29024
29529
  if (namedHeaders === void 0) {
29025
29530
  let version2 = UA_DEV_VERSION;
29026
29531
  try {
29027
- const v = JSON.parse(readFileSync19(join23(ownBundleDir(), D1_PACKAGE_FILE), "utf8")).version;
29532
+ const v = JSON.parse(readFileSync20(join24(ownBundleDir(), D1_PACKAGE_FILE), "utf8")).version;
29028
29533
  if (typeof v === "string" && v !== "") version2 = v;
29029
29534
  } catch {
29030
29535
  }
@@ -29116,8 +29621,15 @@ function checkAddress(hostname2, address) {
29116
29621
  throw new CtxError("SSRF", { host: hostname2 });
29117
29622
  }
29118
29623
  }
29119
- async function resolveTarget(u, signal) {
29120
- const host = bare(u.hostname);
29624
+ async function checkResolved(host, addrs, signal) {
29625
+ const pooled = isIP(host) === 0 ? addrs.filter((a) => inFakeIpPool(a.address)) : [];
29626
+ for (const a of addrs) if (!pooled.includes(a)) checkAddress(host, a.address);
29627
+ if (pooled.length === 0) return;
29628
+ const fakeIp = await fakeIpResolver();
29629
+ if (signal.aborted) throw fail6("ABORT_ERR");
29630
+ if (!fakeIp) checkAddress(host, pooled[0].address);
29631
+ }
29632
+ async function lookupAll(host, signal) {
29121
29633
  let addrs;
29122
29634
  try {
29123
29635
  addrs = await lookup(host, { all: true });
@@ -29126,9 +29638,26 @@ async function resolveTarget(u, signal) {
29126
29638
  }
29127
29639
  if (signal.aborted) throw fail6("ABORT_ERR");
29128
29640
  if (addrs.length === 0) throw fail6("ENOTFOUND");
29129
- for (const a of addrs) checkAddress(host, a.address);
29641
+ return addrs;
29642
+ }
29643
+ async function resolveTarget(u, signal, checked) {
29644
+ const host = bare(u.hostname);
29645
+ const addrs = await lookupAll(host, signal);
29646
+ if (checked) await checkResolved(host, addrs, signal);
29130
29647
  return { host, port: u.port === "" ? defaultPort(u.protocol) : Number(u.port), address: addrs[0].address };
29131
29648
  }
29649
+ async function checkProxiedTarget(u, signal) {
29650
+ const host = bare(u.hostname);
29651
+ if (isIP(host) !== 0) return checkAddress(host, host);
29652
+ let addrs;
29653
+ try {
29654
+ addrs = await lookupAll(host, signal);
29655
+ } catch (err) {
29656
+ if (signal.aborted) throw err;
29657
+ return;
29658
+ }
29659
+ await checkResolved(host, addrs, signal);
29660
+ }
29132
29661
  function tlsName(host) {
29133
29662
  return isIP(host) === 0 ? host : void 0;
29134
29663
  }
@@ -29186,9 +29715,8 @@ async function safeFetch(url2, signal) {
29186
29715
  for (let hop = 0; ; hop += 1) {
29187
29716
  if (signal.aborted) throw fail6("ABORT_ERR");
29188
29717
  const proxy = pickProxy(current);
29189
- const origin = bare(current.hostname);
29190
- if (proxy !== void 0 && isIP(origin) !== 0) checkAddress(origin, origin);
29191
- const conn = await resolveTarget(proxy === void 0 ? current : proxy.url, signal);
29718
+ if (proxy !== void 0) await checkProxiedTarget(current, signal);
29719
+ const conn = await resolveTarget(proxy === void 0 ? current : proxy.url, signal, proxy === void 0);
29192
29720
  const res = await request(current, conn, proxy, signal);
29193
29721
  const status = res.statusCode ?? 0;
29194
29722
  const location = res.headers.location;
@@ -29337,7 +29865,7 @@ function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCou
29337
29865
  readNgramReferences(ngramCount - dictSize + dict1AtomCount, dictSize + dict2AtomCount);
29338
29866
  readNgramReferences(dictSize - dict1AtomCount, dict1AtomCount);
29339
29867
  const pool = new Uint16Array(poolSize);
29340
- let write2 = 0;
29868
+ let write = 0;
29341
29869
  for (let index = 0; index < ngramIndex; index++) {
29342
29870
  for (let half = 0; half < 2; half++) {
29343
29871
  const source = references[index * 2 + half];
@@ -29346,9 +29874,9 @@ function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCou
29346
29874
  let read3 = start[source];
29347
29875
  const readEnd = read3 + length[source];
29348
29876
  while (read3 < readEnd)
29349
- pool[write2++] = pool[read3++];
29877
+ pool[write++] = pool[read3++];
29350
29878
  } else {
29351
- pool[write2++] = value;
29879
+ pool[write++] = value;
29352
29880
  }
29353
29881
  }
29354
29882
  }
@@ -33042,25 +33570,26 @@ function kindOfType(contentType) {
33042
33570
  }
33043
33571
  function readUtf8(absPath) {
33044
33572
  try {
33045
- return utf8.decode(readFileSync20(absPath));
33573
+ return utf8.decode(readFileSync21(absPath));
33046
33574
  } catch {
33047
33575
  return void 0;
33048
33576
  }
33049
33577
  }
33050
- function missingOrOutside(given, abs, root) {
33578
+ function missingOrOutside(given, abs, root, hostRoots) {
33051
33579
  let dir = abs;
33052
33580
  while (!existsSync19(dir) && dirname13(dir) !== dir) dir = dirname13(dir);
33053
- if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
33581
+ if (dir !== abs && allowedRootOf(root, hostRoots, dir) !== void 0) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
33054
33582
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
33055
33583
  }
33056
- function pathItems(input, project) {
33584
+ function pathItems(input, project, hostRoots) {
33057
33585
  const abs = resolve12(project.worktree, input.path);
33058
- if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
33586
+ const allowed = allowedRootOf(project.containmentRoot, hostRoots, abs);
33587
+ if (allowed === void 0) throw missingOrOutside(input.path, abs, project.containmentRoot, hostRoots);
33059
33588
  const base = relative5(project.worktree, abs);
33060
- if (statSync9(abs).isDirectory()) {
33061
- return walkDir(abs, project.containmentRoot).map((f) => ({
33589
+ if (statSync10(abs).isDirectory()) {
33590
+ return walkDir(abs, allowed).map((f) => ({
33062
33591
  sourceKind: "path",
33063
- label: pathLabel(join24(base, f.relPath)),
33592
+ label: pathLabel(join25(base, f.relPath)),
33064
33593
  kind: kindOfPath(f.relPath),
33065
33594
  read: () => readUtf8(f.absPath)
33066
33595
  }));
@@ -33075,7 +33604,7 @@ async function itemsOf(input, ctx) {
33075
33604
  return { items: [{ sourceKind: "content", label: label3, kind, read: () => text2 }], from: label3 };
33076
33605
  }
33077
33606
  if (input.path !== void 0) {
33078
- const items = pathItems({ ...input, path: input.path }, ctx.project);
33607
+ const items = pathItems({ ...input, path: input.path }, ctx.project, ctx.hostRoots);
33079
33608
  return { items, from: items.length === 1 ? items[0].label : pathLabel(input.path) };
33080
33609
  }
33081
33610
  const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
@@ -33142,7 +33671,7 @@ async function handler4(input, ctx) {
33142
33671
  journal: { kind: "index", key: from, path: from, exit_code: null }
33143
33672
  };
33144
33673
  } catch (err) {
33145
- if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0 };
33674
+ if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0, ...err.code === "OUTSIDE_ROOT" ? { outsideRoot: true } : {} };
33146
33675
  throw err;
33147
33676
  }
33148
33677
  }
@@ -33184,7 +33713,7 @@ function purgeScope(db, scope, input) {
33184
33713
  const chunks = deleteChunkRows(raw, "all");
33185
33714
  return changes(raw, "DELETE FROM events") + chunks + changes(raw, "DELETE FROM sources");
33186
33715
  }
33187
- function isBusy(err) {
33716
+ function isBusy2(err) {
33188
33717
  const code = err?.errcode;
33189
33718
  return typeof code === "number" && (code & SQLITE_PRIMARY_CODE_MASK) === SQLITE_BUSY_CODE;
33190
33719
  }
@@ -33202,7 +33731,7 @@ async function handler5(input, ctx) {
33202
33731
  closeDb(db);
33203
33732
  }
33204
33733
  } catch (err) {
33205
- if (isBusy(err)) return reply2(PURGE_BUSY_LINE, true);
33734
+ if (isBusy2(err)) return reply2(PURGE_BUSY_LINE, true);
33206
33735
  throw err;
33207
33736
  }
33208
33737
  }
@@ -33600,22 +34129,22 @@ var ctxStats = Object.freeze({
33600
34129
  });
33601
34130
 
33602
34131
  // src/core/ops/host-write.ts
33603
- import { copyFileSync, existsSync as existsSync20, mkdirSync as mkdirSync8, writeFileSync as writeFileSync6 } from "node:fs";
33604
- import { dirname as dirname14, join as join25 } from "node:path";
34132
+ import { copyFileSync, existsSync as existsSync20, mkdirSync as mkdirSync9, writeFileSync as writeFileSync7 } from "node:fs";
34133
+ import { dirname as dirname14, join as join26 } from "node:path";
33605
34134
  function defaultWrite(file2, text) {
33606
- writeFileSync6(file2, text, "utf8");
34135
+ writeFileSync7(file2, text, "utf8");
33607
34136
  }
33608
34137
  function hostConfigPath(agent, home, env) {
33609
34138
  const own2 = OWN_MCP_ENTRY[agent];
33610
34139
  if (own2 !== void 0) return ownMcpFileOf(agent, own2.file, env, home);
33611
34140
  switch (agent) {
33612
34141
  case "opencode":
33613
- return join25(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
34142
+ return join26(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
33614
34143
  // D-WIN-OPENCODE-DIR-1
33615
34144
  case "pi":
33616
- return join25(piAgentDirOf(env, home), SETTINGS_FILE);
34145
+ return join26(piAgentDirOf(env, home), SETTINGS_FILE);
33617
34146
  case "gemini":
33618
- return join25(geminiDirOf(env, home), SETTINGS_FILE);
34147
+ return join26(geminiDirOf(env, home), SETTINGS_FILE);
33619
34148
  // D-R38-GEMINI-HOME-1
33620
34149
  case "copilot-cli":
33621
34150
  return null;
@@ -33623,7 +34152,7 @@ function hostConfigPath(agent, home, env) {
33623
34152
  return null;
33624
34153
  // ADR-0026 decision 8 (D-OMP-UPGRADE-1): OMP loads the plugin from its own store; no MCP entry, nothing under ~/.pi
33625
34154
  default:
33626
- return join25(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
34155
+ return join26(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
33627
34156
  }
33628
34157
  }
33629
34158
  function cell3(value) {
@@ -33632,14 +34161,14 @@ function cell3(value) {
33632
34161
  function toRow(file2, edit) {
33633
34162
  return { area: file2 + UPGRADE_AREA_KEY_SEP + edit.path, before: cell3(edit.before), after: cell3(edit.after) };
33634
34163
  }
33635
- function writeWithRollback(file2, text, write2, atomic) {
34164
+ function writeWithRollback(file2, text, write, atomic) {
33636
34165
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
33637
34166
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
33638
34167
  const had = existsSync20(file2);
33639
- mkdirSync8(dirname14(file2), { recursive: true });
34168
+ mkdirSync9(dirname14(file2), { recursive: true });
33640
34169
  if (had) copyFileSync(file2, trash);
33641
34170
  try {
33642
- write2(tmp, text);
34171
+ write(tmp, text);
33643
34172
  renameWithRetry(tmp, file2, atomic);
33644
34173
  } catch (err) {
33645
34174
  removeTmpFile(tmp, atomic);
@@ -33673,15 +34202,15 @@ function regenerateHostConfig(row5, home, opts = {}) {
33673
34202
  }
33674
34203
 
33675
34204
  // src/core/ops/uninstall.ts
33676
- import { existsSync as existsSync21, readdirSync as readdirSync10, rmSync as rmSync6, writeFileSync as writeFileSync7 } from "node:fs";
33677
- import { join as join26 } from "node:path";
34205
+ import { existsSync as existsSync21, readdirSync as readdirSync11, rmSync as rmSync6, writeFileSync as writeFileSync8 } from "node:fs";
34206
+ import { join as join27 } from "node:path";
33678
34207
  function row2(area, before, after) {
33679
34208
  return { area, before, after };
33680
34209
  }
33681
34210
  function stopServers(configDir, projectKey) {
33682
34211
  const stopped = listLiveOwners(configDir, projectKey);
33683
- const dir = join26(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
33684
- for (const serverId of stopped) writeFileSync7(join26(dir, serverId + OWNER_STOP_EXT), "", "utf8");
34212
+ const dir = join27(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
34213
+ for (const serverId of stopped) writeFileSync8(join27(dir, serverId + OWNER_STOP_EXT), "", "utf8");
33685
34214
  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 };
33686
34215
  }
33687
34216
  function rootOrNull(adapter, env) {
@@ -33699,14 +34228,14 @@ function removeCache(adapter, env, configDir) {
33699
34228
  const root = rootOrNull(adapter, env);
33700
34229
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
33701
34230
  if (adapter.installMode === "marketplace") {
33702
- const cache = join26(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
34231
+ const cache = join27(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
33703
34232
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
33704
34233
  }
33705
34234
  rmSync6(root, { recursive: true, force: true });
33706
34235
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
33707
34236
  }
33708
34237
  case "plugin": {
33709
- const agentDir = join26(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
34238
+ const agentDir = join27(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
33710
34239
  if (!existsSync21(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
33711
34240
  rmSync6(agentDir, { recursive: true, force: true });
33712
34241
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
@@ -33752,7 +34281,7 @@ function ownEntries2(agent, env) {
33752
34281
  }
33753
34282
  if (agent === "opencode") {
33754
34283
  return [{
33755
- file: join26(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
34284
+ file: join27(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
33756
34285
  // D-WIN-OPENCODE-DIR-1
33757
34286
  key: OPENCODE_PLUGIN_KEY,
33758
34287
  shown: OPENCODE_PLUGIN_KEY,
@@ -33763,7 +34292,7 @@ function ownEntries2(agent, env) {
33763
34292
  if (agent === "pi") {
33764
34293
  const agentDir = piAgentDirOf(env, home);
33765
34294
  return [{
33766
- file: join26(agentDir, SETTINGS_FILE),
34295
+ file: join27(agentDir, SETTINGS_FILE),
33767
34296
  key: PI_PACKAGES_KEY,
33768
34297
  shown: PI_PACKAGES_KEY,
33769
34298
  has: (v) => Array.isArray(v) && v.some((x) => piSource2(x) === PI_GIT_PACKAGE),
@@ -33772,7 +34301,7 @@ function ownEntries2(agent, env) {
33772
34301
  }
33773
34302
  if (agent === "omp") {
33774
34303
  return [{
33775
- file: ompImportFiles(home).mcp,
34304
+ file: ompImportFiles(env, home).mcp,
33776
34305
  key: OMP_DISABLED_SERVERS_KEY,
33777
34306
  shown: OMP_DISABLED_SERVERS_KEY,
33778
34307
  has: (v) => Array.isArray(v) && v.includes(SERVER_KEY),
@@ -33794,12 +34323,12 @@ function removeOwnEntries(agent, env) {
33794
34323
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
33795
34324
  }
33796
34325
  function removeProjectData(configDir, projectKey) {
33797
- const projects = join26(configDir, PROJECTS_DIR_NAME);
33798
- const dir = join26(projects, projectKey);
34326
+ const projects = join27(configDir, PROJECTS_DIR_NAME);
34327
+ const dir = join27(projects, projectKey);
33799
34328
  if (!existsSync21(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
33800
34329
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
33801
- for (const name of readdirSync10(dir)) {
33802
- if (name !== OWNERS_DIR_NAME) rmSync6(join26(dir, name), { recursive: true, force: true });
34330
+ for (const name of readdirSync11(dir)) {
34331
+ if (name !== OWNERS_DIR_NAME) rmSync6(join27(dir, name), { recursive: true, force: true });
33803
34332
  }
33804
34333
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
33805
34334
  }
@@ -33807,12 +34336,12 @@ function runUninstall(input) {
33807
34336
  const configDir = resolveConfigDir(input.env);
33808
34337
  const stop = stopServers(configDir, input.project.projectKey);
33809
34338
  const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
33810
- rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join26(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
34339
+ rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join27(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
33811
34340
  return { rows, stopped: stop.stopped };
33812
34341
  }
33813
34342
 
33814
34343
  // src/core/ops/v1-remove.ts
33815
- import { copyFileSync as copyFileSync2, existsSync as existsSync22, readFileSync as readFileSync21, rmSync as rmSync7 } from "node:fs";
34344
+ import { copyFileSync as copyFileSync2, existsSync as existsSync22, readFileSync as readFileSync22, rmSync as rmSync7 } from "node:fs";
33816
34345
  var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
33817
34346
  var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
33818
34347
  var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
@@ -33863,8 +34392,8 @@ function locate(doc, path8) {
33863
34392
  return null;
33864
34393
  }
33865
34394
  function stripJsonEntries(agent, file2, findings, kept, undo) {
33866
- const layout = hostLayout(readFileSync21(file2, "utf8"));
33867
- const text = hostText(readFileSync21(file2, "utf8"));
34395
+ const layout = hostLayout(readFileSync22(file2, "utf8"));
34396
+ const text = hostText(readFileSync22(file2, "utf8"));
33868
34397
  const doc = parseHostConfig(agent, file2, text, "jsonc");
33869
34398
  const hit = /* @__PURE__ */ new Set();
33870
34399
  const byContainer = /* @__PURE__ */ new Map();
@@ -33914,7 +34443,7 @@ function removeV1(agent, findings, project) {
33914
34443
  continue;
33915
34444
  }
33916
34445
  if (file2.endsWith(TOML_EXT)) {
33917
- const rawToml = readFileSync21(file2, "utf8");
34446
+ const rawToml = readFileSync22(file2, "utf8");
33918
34447
  const tomlLayout = hostLayout(rawToml);
33919
34448
  let text = hostText(rawToml);
33920
34449
  for (const f of list4) {
@@ -34187,8 +34716,8 @@ async function setupLegacy(app) {
34187
34716
  "chat.message": async (input, output) => {
34188
34717
  const sessionId = input.sessionID ?? "";
34189
34718
  turns.set(sessionId, turnOf(sessionId) + 1);
34190
- const message3 = (output.parts ?? []).filter((p) => p.type === "text").map((p) => p.text ?? "").join("");
34191
- await call({ type: "prompt", sessionID: sessionId, message: message3, turn: turnOf(sessionId) });
34719
+ const message4 = (output.parts ?? []).filter((p) => p.type === "text").map((p) => p.text ?? "").join("");
34720
+ await call({ type: "prompt", sessionID: sessionId, message: message4, turn: turnOf(sessionId) });
34192
34721
  },
34193
34722
  // §4.4. Deny (exit 2) throws with the reason; the reason carries any rewritten command (Q3, D-M5-P2-3).
34194
34723
  "tool.execute.before": async (input, output) => {