context-mode 2.0.0-next.8 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/search.mjs CHANGED
@@ -1,5 +1,7 @@
1
+ import{createRequire as __cmRequire}from"node:module";if(typeof process.getBuiltinModule!=="function")process.getBuiltinModule=(id)=>__cmRequire(import.meta.url)(id);
2
+
1
3
  // src/entries/run.ts
2
- import { basename as basename2 } from "node:path";
4
+ import { basename as basename3 } from "node:path";
3
5
 
4
6
  // src/core/contracts/constants.ts
5
7
  var SERVER_KEY = "context-mode";
@@ -11,7 +13,6 @@ function prefixToolNames(text, prefix) {
11
13
  return out;
12
14
  }
13
15
  var OUTPUT_CAP = 16384;
14
- var REPORT_CAP = 4096;
15
16
  var INDEX_WRITE_CHUNK = 1048576;
16
17
  var MAX_CHUNK_BYTES = 4096;
17
18
  var WEIGHT = Object.freeze({ toolerr: 900, decision: 700, prompt: 500, edit: 400, index: 200 });
@@ -157,7 +158,7 @@ var SQLITE_NOTADB_CODE = 26;
157
158
  var HOOK_TIMEOUT_MS = 5e3;
158
159
  var IN_PROCESS_TIMEOUT_MS = 0;
159
160
  var PROJECT_KEY_HEX_LEN = 16;
160
- var SCHEMA_VERSION = 5;
161
+ var SCHEMA_VERSION = 6;
161
162
  var PROJECTS_DIR_NAME = "projects";
162
163
  var DB_FILE_NAME = "context.db";
163
164
  var GIT_DIR_NAME = ".git";
@@ -183,6 +184,8 @@ var HOST_SESSION_ENV = Object.freeze({ "claude-code": "CLAUDE_CODE_SESSION_ID" }
183
184
  var NODE_MIN = "24.15.0";
184
185
  var DATA_ROOT = "~/.context-mode";
185
186
  var REQUIRE_SECURITY_ENV = "CONTEXT_MODE_REQUIRE_SECURITY";
187
+ var PROJECT_PLUGIN_SCOPES = Object.freeze(["local", "project"]);
188
+ var PLUGIN_SCOPE_RANK = Object.freeze({ local: 0, project: 1, user: 2, managed: 2 });
186
189
  var MCP_HINT_EVERY_DEFAULT = 10;
187
190
  function readHintEvery(raw) {
188
191
  if (raw === void 0 || raw.trim() === "") return MCP_HINT_EVERY_DEFAULT;
@@ -207,6 +210,24 @@ var DENY_WEBFETCH_TOOLS = Object.freeze(["ctx_index", "ctx_search"]);
207
210
  var USER_DENY_REASON_PREFIX = "Blocked by security policy: matches deny pattern ";
208
211
  var POLICY_UNREADABLE_LINE = "context-mode: your deny rules could not be read. Fix: run ctx_doctor.";
209
212
  var PARSE_ERROR_DENY_LINE = "context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.";
213
+ var HOOK_FAIL_TOOL_KEYS = Object.freeze(["tool_name", "toolName", "tool"]);
214
+ var HOOK_FAIL_EVENT_KEYS = Object.freeze(["hook_event_name", "hookEventName", "type"]);
215
+ var HOOK_FAIL_INPUT_KEYS = Object.freeze(["tool_input", "toolArgs", "input", "args"]);
216
+ var HOOK_FAIL_CWD_KEYS = Object.freeze(["cwd", "directory"]);
217
+ var HOOK_FAIL_PRE_EVENTS = Object.freeze(["pretooluse", "beforetool", "tool_call", "execute.before", "tool.execute.before"]);
218
+ var HOOK_FAULT_STAGES = Object.freeze(["decode", "project", "policy", "store", "encode"]);
219
+ var HOOK_FAIL_TOOLS = Object.freeze({
220
+ shell: Object.freeze(["Bash", "bash", "shell"]),
221
+ read: Object.freeze(["Read", "read_file"]),
222
+ grep: Object.freeze(["Grep", "grep_search"]),
223
+ fetch: Object.freeze(["WebFetch", "web_fetch", "fetch"])
224
+ });
225
+ var HOOK_FAIL_REDIRECT = Object.freeze({
226
+ read: "Read the file in parts with offset and limit, or process it with ctx_execute(language, code); only what you print comes back.",
227
+ shell: "Run the command with ctx_execute(language, code) or ctx_batch instead; only the part that matches your intent comes back.",
228
+ grep: "Search with ctx_execute(language, code), or index the files with ctx_index and query them with ctx_search.",
229
+ fetch: "Index the URL with ctx_index and query it with ctx_search."
230
+ });
210
231
  var BOUNDED_COMMANDS = Object.freeze(["pwd", "whoami", "uname", "id", "realpath", "ln"]);
211
232
  var BOUNDED_GIT_SUBCOMMANDS = Object.freeze(["status"]);
212
233
  var VERSION_PROBE_FLAGS = Object.freeze(["--version", "-v"]);
@@ -235,7 +256,33 @@ var READ_PATH_KEYS = Object.freeze(["file_path", "absolute_path", "path"]);
235
256
  var EDIT_TOOLS = Object.freeze(["Write", "Edit"]);
236
257
  var EDIT_PATH_KEYS = Object.freeze(["file_path", "path"]);
237
258
  var STATS_COLUMNS = Object.freeze(["Scope", "Produced", "Returned", "Saved", "Reduction %"]);
259
+ var STATS_EMPTY_LINES = Object.freeze([
260
+ "Ready. Your savings show up here after the first tool call.",
261
+ "Large outputs from ctx_execute, ctx_batch and ctx_index stay in the",
262
+ "sandbox, and only the short answer goes to the chat."
263
+ ]);
264
+ var STATS_KIND_LABELS = Object.freeze([
265
+ // D-STATS-FIX-1 (8): the first five rows are call kinds, so they add up to the calls of the scope line.
266
+ ["index", "Content indexed"],
267
+ ["edit", "File edits"],
268
+ ["toolerr", "Issues kept"],
269
+ ["decision", "Your decisions"],
270
+ ["cmd", "Other tool calls"],
271
+ ["prompt", "Your prompts"]
272
+ ]);
273
+ var STATS_JOURNAL_HINTS = Object.freeze([
274
+ "ctx_resume brings back your last task, files changed and open issues",
275
+ "after a compact or a restart; ctx_search finds indexed content by words."
276
+ ]);
277
+ var STATS_WAYS = Object.freeze([
278
+ ["sandbox", "\u2588", "sandbox run"],
279
+ ["index", "\u2593", "index + search"],
280
+ ["redirect", "\u2592", "hook sent to sandbox"],
281
+ ["replace", "\u2591", "hook cut down"]
282
+ ]);
283
+ var STATS_INDEX_TOOLS = Object.freeze(["ctx_index", "ctx_search"]);
238
284
  var PURGE_SCOPES = Object.freeze(["session", "source", "project"]);
285
+ var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
239
286
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
240
287
  var DOCTOR_LABEL = Object.freeze({
241
288
  D1: "version",
@@ -251,7 +298,12 @@ var DOCTOR_LABEL = Object.freeze({
251
298
  D10: "enforcement mode",
252
299
  D11: "shell"
253
300
  });
254
- var REPORT_TRUNCATED_LINE = `(report truncated at ${REPORT_CAP} B; run ctx_doctor again after the first fix)`;
301
+ var ECHO_MAX_BYTES = 256;
302
+ var REPORT_SOURCE_LABEL = "ctx_doctor:report";
303
+ var REPORT_POINTER = `ctx_search({queries:["FAIL","PASS","UNKNOWN"], source:${JSON.stringify(REPORT_SOURCE_LABEL)}})`;
304
+ var GIT_LS_REMOTE_TAG_ARGS = Object.freeze(["--tags", "--refs"]);
305
+ var RELEASE_TAG_PATTERN = "v*";
306
+ var D1_GIT_CHECK_FIX = `git ls-remote --tags --refs ${RELEASE_REPO_URL} "${RELEASE_TAG_PATTERN}"`;
255
307
  var D2_NODE_FIX = `install Node ${NODE_MIN} or later`;
256
308
  var D3_PARTS = Object.freeze(["MCP entry", "hook entries", "hook timeout"]);
257
309
  var AGENT_HOME_DIR = Object.freeze({
@@ -357,10 +409,11 @@ var V1_REASON = Object.freeze({
357
409
  dataDir: "old context-mode data dir <agent home>/context-mode/",
358
410
  dataDirShared: "old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",
359
411
  dataRoot: "old context-mode content under ~/.context-mode/",
360
- tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, no action needed"
412
+ tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep"
361
413
  });
362
414
  var UPGRADE_REPORT_ONLY_REASONS = Object.freeze([V1_REASON.statusLine, V1_REASON.vscodeMcp, V1_REASON.dataDirShared, V1_REASON.tmpFile, V1_REASON.kiroSteering]);
363
415
  var OPENCODE_TOOL_PREFIX = SERVER_KEY + "_";
416
+ var OPENCODE_PLUGIN_PATH = Object.freeze(["opencode", "plugin.js"]);
364
417
  var ZCODE_MCP_FEATURE_KEY = Object.freeze(["features", "mcp"]);
365
418
  var CODEX_OMIT_TOOLS_FROM_FIELD = "omit_tools_from";
366
419
  var CODEX_OMIT_DEFERRED = Object.freeze(["deferred"]);
@@ -380,13 +433,69 @@ var OWN_MCP_ENTRY = Object.freeze({
380
433
  var REPORT_ENV_ENUMS = Object.freeze({
381
434
  NODE_ENV: Object.freeze(["development", "production", "test"])
382
435
  });
436
+ var DOCTOR_ENV_PREFIX = "Environment: ";
437
+ var DOCTOR_DOCS_LABEL = "Docs: ";
438
+ var DOCTOR_REPORT_LINE = "Report file: ";
439
+ var DOCTOR_GH_LINE = "File it: ";
440
+ var DOCTOR_URL_LINE = "Or open: ";
441
+ var DOCTOR_GH_NEXT = " --";
442
+ var DOCTOR_NOTE_PREFIXES = Object.freeze([
443
+ DOCTOR_ENV_PREFIX,
444
+ DOCTOR_DOCS_LABEL,
445
+ DOCTOR_REPORT_LINE,
446
+ DOCTOR_GH_LINE,
447
+ DOCTOR_GH_NEXT.trim(),
448
+ DOCTOR_URL_LINE
449
+ ]);
450
+ var ISSUE_REPO_SLUG = "mksglu/context-mode";
451
+ var ISSUE_FORM_FILE = "agent-report.yml";
452
+ var ISSUE_FORM_HEADINGS = Object.freeze([
453
+ "Summary",
454
+ "ctx-report",
455
+ "What happened",
456
+ "Hook errors",
457
+ "Journal rows",
458
+ "Agent config",
459
+ "Expected",
460
+ "Steps",
461
+ "Environment"
462
+ ]);
463
+ var DOCTOR_ENV_NAMES = Object.freeze([
464
+ "CODEX_HOME",
465
+ "CLAUDE_CONFIG_DIR",
466
+ "CLAUDE_PLUGIN_ROOT",
467
+ "COPILOT_HOME",
468
+ "KIRO_HOME",
469
+ "OPENCODE_CONFIG_DIR",
470
+ "PI_CODING_AGENT_DIR",
471
+ "XDG_CONFIG_HOME",
472
+ "SHELL"
473
+ ]);
474
+ var DOCTOR_PATH_TOOLS = Object.freeze(["node", "git", "sh"]);
475
+ var DOCTOR_SECRET_WORDS = Object.freeze(["token", "secret", "password", "apikey", "api_key", "authorization", "bearer"]);
476
+ var NATIVE_INSTALL = Object.freeze({
477
+ "claude-code": ["claude plugin marketplace add mksglu/context-mode#release", "claude plugin install context-mode@context-mode"],
478
+ codex: ["codex plugin marketplace add mksglu/context-mode@release", "codex plugin add context-mode@context-mode"],
479
+ gemini: ["gemini extensions install https://github.com/mksglu/context-mode --ref release"],
480
+ qwen: ["qwen extensions install https://github.com/mksglu/context-mode:context-mode --ref release"],
481
+ opencode: ["opencode plugin add context-mode@next"],
482
+ pi: ["pi install npm:context-mode@next"],
483
+ "copilot-cli": ["npm i -g context-mode@next", "context-mode setup --agents copilot-cli"],
484
+ vscode: ["npm i -g context-mode@next", "context-mode setup --agents vscode"],
485
+ kiro: ["npm i -g context-mode@next", "context-mode setup --agents kiro"],
486
+ zcode: ["npm i -g context-mode@next", "context-mode setup --agents zcode"]
487
+ });
488
+ var ISSUE_FORM_URL = `https://github.com/${ISSUE_REPO_SLUG}/issues/new?template=${ISSUE_FORM_FILE}`;
383
489
 
384
490
  // src/core/tools/run-wrapper.ts
385
491
  import { randomUUID } from "node:crypto";
386
- import { dirname as dirname3, join as join5 } from "node:path";
492
+ import { dirname as dirname4, join as join5 } from "node:path";
387
493
 
388
494
  // src/adapters/claude-code.ts
389
495
  var TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__";
496
+ var SHELL_TOOL_NAMES = Object.freeze(["Bash", "PowerShell"]);
497
+ var POWERSHELL_TOOL = "PowerShell";
498
+ var SHELL_CANONICAL = "Bash";
390
499
  var CLAUDE_SHAPE_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse"];
391
500
  var MCP_PREFIX = "mcp__";
392
501
  var MCP_SEP = "__";
@@ -512,6 +621,7 @@ function requireFields(raw) {
512
621
  function decode(raw) {
513
622
  requireFields(raw);
514
623
  const ev = decodeClaudeShape(raw, "claude-code", TOOL_NAME_PREFIX, CLAUDE_SOURCES);
624
+ if (ev.tool !== void 0 && ev.tool.name === POWERSHELL_TOOL) ev.tool.canonicalName = SHELL_CANONICAL;
515
625
  if (ev.cwd === "") ev.cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd();
516
626
  if (ev.event === "PostToolUse" && ev.tool !== void 0 && ev.tool.callId === void 0) {
517
627
  const cmd = typeof ev.tool.input.command === "string" ? ev.tool.input.command : JSON.stringify(ev.tool.input);
@@ -661,7 +771,8 @@ var RESULT_SUCCESS = "success";
661
771
  function isRecord(v) {
662
772
  return typeof v === "object" && v !== null && !Array.isArray(v);
663
773
  }
664
- var NATIVE_TO_CANONICAL3 = { bash: "Bash" };
774
+ var SHELL_TOOL_NAMES2 = Object.freeze(["bash", "powershell"]);
775
+ var NATIVE_TO_CANONICAL3 = Object.fromEntries(SHELL_TOOL_NAMES2.map((n) => [n, "Bash"]));
665
776
  function canonicalName3(name) {
666
777
  if (name.startsWith(TOOL_NAME_PREFIX5)) return name.slice(TOOL_NAME_PREFIX5.length);
667
778
  if (Object.hasOwn(NATIVE_TO_CANONICAL3, name)) return NATIVE_TO_CANONICAL3[name];
@@ -742,11 +853,11 @@ var VSCODE_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostTool
742
853
  var MCP_PREFIX2 = "mcp_";
743
854
  var MCP_SEP2 = "_";
744
855
  var SESSION_START_NEW = "new";
745
- var SHELL_TOOL_NAMES = Object.freeze(["run_in_terminal", "runTerminalCommand", "bash", "powershell"]);
856
+ var SHELL_TOOL_NAMES3 = Object.freeze(["run_in_terminal", "runTerminalCommand", "bash", "powershell"]);
746
857
  var READ_TOOL_NAMES = Object.freeze(["read_file", "view"]);
747
858
  var WEBFETCH_TOOL_NAMES = Object.freeze(["fetch_webpage", "web_fetch"]);
748
859
  var NATIVE_TO_CANONICAL4 = Object.fromEntries([
749
- ...SHELL_TOOL_NAMES.map((n) => [n, "Bash"]),
860
+ ...SHELL_TOOL_NAMES3.map((n) => [n, "Bash"]),
750
861
  ...READ_TOOL_NAMES.map((n) => [n, "Read"]),
751
862
  ...WEBFETCH_TOOL_NAMES.map((n) => [n, "WebFetch"])
752
863
  ]);
@@ -874,8 +985,8 @@ var KIRO_EVENTS = {
874
985
  };
875
986
  var PROMPT_ENV = "USER_PROMPT";
876
987
  var MCP_PREFIX3 = "mcp_";
877
- var SHELL_TOOL_NAMES2 = Object.freeze(["execute_bash", "execute_pwsh", "shell"]);
878
- var NATIVE_TO_CANONICAL5 = Object.fromEntries(SHELL_TOOL_NAMES2.map((n) => [n, "Bash"]));
988
+ var SHELL_TOOL_NAMES4 = Object.freeze(["execute_bash", "execute_pwsh", "shell"]);
989
+ var NATIVE_TO_CANONICAL5 = Object.fromEntries(SHELL_TOOL_NAMES4.map((n) => [n, "Bash"]));
879
990
  var MCP_SEP3 = "_";
880
991
  var KIRO_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
881
992
  function canonicalName5(name) {
@@ -1017,7 +1128,8 @@ var OPENCODE_EVENTS = {
1017
1128
  "step-finish": "Usage"
1018
1129
  };
1019
1130
  var SHELL_TOOL_NAME = "bash";
1020
- var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", [SHELL_TOOL_NAME]: "Bash" };
1131
+ var SHELL_TOOL_NAMES5 = Object.freeze([SHELL_TOOL_NAME, "shell"]);
1132
+ var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", ...Object.fromEntries(SHELL_TOOL_NAMES5.map((n) => [n, "Bash"])) };
1021
1133
  function toCanonicalTool(name) {
1022
1134
  if (name.startsWith(OWN_WIRE_PREFIX)) return name.slice(OWN_WIRE_PREFIX.length);
1023
1135
  return Object.prototype.hasOwnProperty.call(NATIVE_TO_CANONICAL7, name) ? NATIVE_TO_CANONICAL7[name] : name;
@@ -1065,13 +1177,14 @@ function encode10(ev, d, _extra) {
1065
1177
  // src/adapters/table.ts
1066
1178
  var CLAUDE_EVENTS = { SessionStart: "SessionStart", UserPromptSubmit: "UserPromptSubmit", PreToolUse: "PreToolUse", PostToolUse: "PostToolUse" };
1067
1179
  var CLAUDE_TOOLS = { shell: ["Bash"], read: ["Read"], grep: ["Grep"], webfetch: ["WebFetch"], edit: ["Write", "Edit", "NotebookEdit"] };
1180
+ var CLAUDE_CODE_TOOLS = { ...CLAUDE_TOOLS, shell: [...SHELL_TOOL_NAMES] };
1068
1181
  var ADAPTERS = Object.freeze([
1069
1182
  {
1070
1183
  id: "claude-code",
1071
1184
  installMode: "marketplace",
1072
1185
  projectSource: "env:CLAUDE_PROJECT_DIR",
1073
1186
  toolNamePrefix: TOOL_NAME_PREFIX,
1074
- nativeTools: CLAUDE_TOOLS,
1187
+ nativeTools: CLAUDE_CODE_TOOLS,
1075
1188
  execReadOnlyHint: false,
1076
1189
  eventMap: CLAUDE_EVENTS,
1077
1190
  compactDelivery: "sessionstart",
@@ -1147,8 +1260,9 @@ var ADAPTERS = Object.freeze([
1147
1260
  installMode: "plugin",
1148
1261
  projectSource: "arg:--agent+cwd",
1149
1262
  toolNamePrefix: TOOL_NAME_PREFIX5,
1150
- nativeTools: { shell: ["bash"] },
1263
+ nativeTools: { shell: [...SHELL_TOOL_NAMES2] },
1151
1264
  execReadOnlyHint: false,
1265
+ // D-PWSH-DUMP-1
1152
1266
  eventMap: { SessionStart: "sessionStart", UserPromptSubmit: "userPromptSubmitted", PreToolUse: "preToolUse", PostToolUse: "postToolUse" },
1153
1267
  compactDelivery: "pending-flag",
1154
1268
  compactSummary: "none",
@@ -1166,7 +1280,7 @@ var ADAPTERS = Object.freeze([
1166
1280
  projectSource: "arg:workspaceFolder",
1167
1281
  toolNamePrefix: TOOL_NAME_PREFIX6,
1168
1282
  // PreCompact sets the pending flag (ADR-0009 §6, DEVIATIONS D-M3-A4-1).
1169
- nativeTools: { shell: [...SHELL_TOOL_NAMES], read: [...READ_TOOL_NAMES], webfetch: [...WEBFETCH_TOOL_NAMES] },
1283
+ nativeTools: { shell: [...SHELL_TOOL_NAMES3], read: [...READ_TOOL_NAMES], webfetch: [...WEBFETCH_TOOL_NAMES] },
1170
1284
  // D-HF-VSCODE-PROJECT-1, D-N7-VSCODE-TOOLS-1
1171
1285
  execReadOnlyHint: false,
1172
1286
  eventMap: { ...CLAUDE_EVENTS, PreCompact: "PreCompact" },
@@ -1185,7 +1299,7 @@ var ADAPTERS = Object.freeze([
1185
1299
  installMode: "mcp-entry",
1186
1300
  projectSource: "arg:--agent+cwd",
1187
1301
  toolNamePrefix: TOOL_NAME_PREFIX7,
1188
- nativeTools: { shell: [...SHELL_TOOL_NAMES2] },
1302
+ nativeTools: { shell: [...SHELL_TOOL_NAMES4] },
1189
1303
  execReadOnlyHint: false,
1190
1304
  // D-HF-KIRO-SHELL-1, D-N7-KIRO-1
1191
1305
  eventMap: { SessionStart: "SessionStart", UserPromptSubmit: "UserPromptSubmit", PreToolUse: "PreToolUse", PostToolUse: "PostToolUse" },
@@ -1276,7 +1390,8 @@ function getAdapter(id) {
1276
1390
  var ERROR_TEXT = Object.freeze({
1277
1391
  NODE_TOO_OLD: "Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",
1278
1392
  NO_SQLITE: "node:sqlite failed to load. Fix: run ctx_doctor.",
1279
- DB_GONE: "context.db path vanished. Fix: run ctx_doctor.",
1393
+ DB_GONE: "context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",
1394
+ // D-ORPHAN-WAL-1
1280
1395
  NO_PROJECT: "Project source <kind> is missing. Fix: run ctx_doctor.",
1281
1396
  UNKNOWN_FIELD: 'Unknown field "<f>". Fix: use "queries".',
1282
1397
  TIMEOUT: "Timed out after <ms> ms. Fix: pass background: true.",
@@ -1441,12 +1556,16 @@ CREATE VIRTUAL TABLE line_units USING fts5(
1441
1556
  ${FTS_TOKENIZE}
1442
1557
  );
1443
1558
  `;
1559
+ var DDL_V6 = `
1560
+ UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
1561
+ `;
1444
1562
  var MIGRATIONS = [
1445
1563
  { version: 1, sql: DDL },
1446
1564
  { version: 2, sql: DDL_V2 },
1447
1565
  { version: 3, sql: DDL_V3 },
1448
1566
  { version: 4, sql: DDL_V4 },
1449
- { version: 5, sql: DDL_V5 }
1567
+ { version: 5, sql: DDL_V5 },
1568
+ { version: 6, sql: DDL_V6 }
1450
1569
  ];
1451
1570
  function applyMigrations(db, fromVersion) {
1452
1571
  if (fromVersion === SCHEMA_VERSION2) return;
@@ -1559,7 +1678,7 @@ async function openDb(project, opts) {
1559
1678
  } else {
1560
1679
  raw = openWritable(sqlite, path3);
1561
1680
  }
1562
- return { raw, projectKey: project.projectKey, path: path3 };
1681
+ return { raw, projectKey: project.projectKey, path: path3, ...opts?.readOnly === true ? { readOnly: true } : {} };
1563
1682
  } catch (err) {
1564
1683
  if (isCorrupt(err)) throw new CtxError("DB_CORRUPT");
1565
1684
  throw err;
@@ -1577,9 +1696,11 @@ function withWrite(db, fn) {
1577
1696
  }
1578
1697
  }
1579
1698
  function closeDb(db) {
1580
- try {
1581
- db.raw.exec("PRAGMA wal_checkpoint(TRUNCATE)");
1582
- } catch {
1699
+ if (db.readOnly !== true) {
1700
+ try {
1701
+ db.raw.exec("PRAGMA wal_checkpoint(PASSIVE)");
1702
+ } catch {
1703
+ }
1583
1704
  }
1584
1705
  try {
1585
1706
  db.raw.close();
@@ -3149,6 +3270,8 @@ RETURNING id`;
3149
3270
  var INSERT_CHUNK = `
3150
3271
  INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`;
3151
3272
  var TITLE_WEIGHT = 1;
3273
+ var RAW_LABEL_SUFFIX = " (raw)";
3274
+ var NOT_RAW = `AND (:source IS NOT NULL OR substr(s.label, -${RAW_LABEL_SUFFIX.length}) <> '${RAW_LABEL_SUFFIX}')`;
3152
3275
  var PORTER_MATCH = `
3153
3276
  SELECT chunks.rowid AS rid, chunks.source_id AS source_id, chunks.session_id AS session_id,
3154
3277
  chunks.worktree AS worktree, chunks.ord AS ord, s.created_ts AS created_ts,
@@ -3158,7 +3281,9 @@ var PORTER_MATCH = `
3158
3281
  WHERE chunks MATCH :match
3159
3282
  AND (:scope <> 'session' OR chunks.session_id = :session_id)
3160
3283
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
3161
- AND (:source IS NULL OR s.label = :source)`;
3284
+ AND (:source IS NULL OR s.label = :source)
3285
+ AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
3286
+ ${NOT_RAW}`;
3162
3287
  var PORTER_ORDER = `
3163
3288
  ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`;
3164
3289
  var PORTER_RANK_PROJECT = `
@@ -3183,6 +3308,8 @@ WHERE chunks_tri MATCH :match
3183
3308
  AND (:scope <> 'session' OR c.session_id = :session_id)
3184
3309
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
3185
3310
  AND (:source IS NULL OR s.label = :source)
3311
+ AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
3312
+ ${NOT_RAW}
3186
3313
  ORDER BY bm25(chunks_tri, 1.0, ${TITLE_WEIGHT}) ASC, c.source_id DESC, c.ord ASC`;
3187
3314
  var INSERT_TRI = "INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)";
3188
3315
  function ftsInsert(db, src, chunks) {
@@ -3338,11 +3465,12 @@ function select(chunks, intent, budget, label, rankQuery) {
3338
3465
  }
3339
3466
  function moreLine(intent, label) {
3340
3467
  const source = label === void 0 ? "" : ", source:" + JSON.stringify(label);
3341
- return "ctx_search({queries:[" + JSON.stringify(intent) + "]" + source + "})";
3468
+ const query = Buffer.byteLength(intent, "utf8") > ECHO_MAX_BYTES ? "..." : JSON.stringify(intent);
3469
+ return "ctx_search({queries:[" + query + "]" + source + "})";
3342
3470
  }
3343
3471
 
3344
3472
  // src/core/policy/decide.ts
3345
- import { resolve } from "node:path";
3473
+ import { resolve as resolve3 } from "node:path";
3346
3474
 
3347
3475
  // src/core/policy/lexer.ts
3348
3476
  var OPS = ["&&", "||", ";;", "|&", ";", "|", "&", "(", ")"];
@@ -4237,6 +4365,7 @@ function pipeline(p) {
4237
4365
  all.push(...last.cmds);
4238
4366
  const t = at(p);
4239
4367
  if (t !== void 0 && t.kind === "op" && PIPES.includes(t.text)) {
4368
+ for (const c of last.cmds) c.pipesOut = true;
4240
4369
  p.i++;
4241
4370
  continue;
4242
4371
  }
@@ -4282,11 +4411,348 @@ function parseShell(cmd) {
4282
4411
  return { ok: true, commands };
4283
4412
  }
4284
4413
 
4414
+ // src/core/policy/powershell.ts
4415
+ import { resolve } from "node:path";
4416
+ var SQ = "'";
4417
+ var DQ = '"';
4418
+ var TICK = "`";
4419
+ var SPACES = " \r";
4420
+ var OPENERS = "([{";
4421
+ var CLOSERS = ")]}";
4422
+ var GLUE_END = " \r\n|;>";
4423
+ var FD_STAR = "*";
4424
+ var STDOUT_FD = "1";
4425
+ var METHOD_MARK = "::";
4426
+ var PAIR = METHOD_MARK.length;
4427
+ var MIN_STATIC_CALL = PAIR;
4428
+ function quoteEnd(text, at2) {
4429
+ const q = text.charAt(at2);
4430
+ for (let j = at2 + 1; j < text.length; j++) {
4431
+ const c = text.charAt(j);
4432
+ if (q === DQ && c === TICK) {
4433
+ j++;
4434
+ continue;
4435
+ }
4436
+ if (c !== q) continue;
4437
+ if (text.charAt(j + 1) === q) {
4438
+ j++;
4439
+ continue;
4440
+ }
4441
+ return j;
4442
+ }
4443
+ return -1;
4444
+ }
4445
+ function unquote(body, q) {
4446
+ let out = "";
4447
+ for (let j = 0; j < body.length; j++) {
4448
+ const c = body.charAt(j);
4449
+ if (q === DQ && c === TICK && j + 1 < body.length) {
4450
+ out += body.charAt(++j);
4451
+ continue;
4452
+ }
4453
+ if (c === q && body.charAt(j + 1) === q) j++;
4454
+ out += c;
4455
+ }
4456
+ return out;
4457
+ }
4458
+ function closeOf(text, at2) {
4459
+ let depth = 0;
4460
+ for (let j = at2; j < text.length; j++) {
4461
+ const c = text.charAt(j);
4462
+ if (c === SQ || c === DQ) {
4463
+ const e = quoteEnd(text, j);
4464
+ if (e < 0) return -1;
4465
+ j = e;
4466
+ continue;
4467
+ }
4468
+ if (c === TICK) {
4469
+ j++;
4470
+ continue;
4471
+ }
4472
+ if (OPENERS.includes(c)) depth++;
4473
+ else if (CLOSERS.includes(c) && --depth === 0) return j;
4474
+ }
4475
+ return -1;
4476
+ }
4477
+ function glueEnd(text, from) {
4478
+ let depth = 0;
4479
+ for (let j = from; j < text.length; j++) {
4480
+ const c = text.charAt(j);
4481
+ if (c === SQ || c === DQ) {
4482
+ const e = quoteEnd(text, j);
4483
+ if (e < 0) return text.length;
4484
+ j = e;
4485
+ continue;
4486
+ }
4487
+ if (OPENERS.includes(c)) depth++;
4488
+ else if (CLOSERS.includes(c)) depth--;
4489
+ else if (depth <= 0 && GLUE_END.includes(c)) return j;
4490
+ }
4491
+ return text.length;
4492
+ }
4493
+ function splitArgs(inner) {
4494
+ const parts = [];
4495
+ let depth = 0;
4496
+ let from = 0;
4497
+ for (let j = 0; j < inner.length; j++) {
4498
+ const c = inner.charAt(j);
4499
+ if (c === SQ || c === DQ) {
4500
+ const e = quoteEnd(inner, j);
4501
+ if (e < 0) break;
4502
+ j = e;
4503
+ continue;
4504
+ }
4505
+ if (OPENERS.includes(c)) depth++;
4506
+ else if (CLOSERS.includes(c)) depth--;
4507
+ else if (c === "," && depth === 0) {
4508
+ parts.push(inner.slice(from, j));
4509
+ from = j + 1;
4510
+ }
4511
+ }
4512
+ parts.push(inner.slice(from));
4513
+ return parts;
4514
+ }
4515
+ var isFd = (w) => w !== "" && (w === FD_STAR || [...w].every((ch) => ch >= "0" && ch <= "9"));
4516
+ var fresh = () => ({ words: [], toFile: false, chained: false });
4517
+ function psParse(text) {
4518
+ const statements = [];
4519
+ let stages = [];
4520
+ let stage = fresh();
4521
+ let word = "";
4522
+ let has2 = false;
4523
+ let bare = true;
4524
+ let target = null;
4525
+ const n = text.length;
4526
+ const endWord = () => {
4527
+ if (!has2) return;
4528
+ if (target !== null) {
4529
+ if (target === "file") stage.toFile = true;
4530
+ target = null;
4531
+ } else stage.words.push(word);
4532
+ word = "";
4533
+ has2 = false;
4534
+ bare = true;
4535
+ };
4536
+ const endStage = () => {
4537
+ endWord();
4538
+ if (stage.words.length > 0 || stage.toFile) stages.push(stage);
4539
+ stage = fresh();
4540
+ };
4541
+ const endStatement = () => {
4542
+ endStage();
4543
+ if (stages.length > 0) statements.push(stages);
4544
+ stages = [];
4545
+ };
4546
+ const grow = (s, quoted) => {
4547
+ word += s;
4548
+ has2 = true;
4549
+ if (quoted) bare = false;
4550
+ };
4551
+ let i = 0;
4552
+ while (i < n) {
4553
+ const c = text.charAt(i);
4554
+ const next = text.charAt(i + 1);
4555
+ if (c === SQ || c === DQ) {
4556
+ const e = quoteEnd(text, i);
4557
+ grow(unquote(text.slice(i + 1, e < 0 ? n : e), c), true);
4558
+ i = e < 0 ? n : e + 1;
4559
+ } else if (c === TICK) {
4560
+ if (next !== "\n" && next !== "") grow(next, false);
4561
+ i += PAIR;
4562
+ } else if (c === "\n") {
4563
+ endStatement();
4564
+ i++;
4565
+ } else if (SPACES.includes(c)) {
4566
+ endWord();
4567
+ i++;
4568
+ } else if (c === ";") {
4569
+ endStatement();
4570
+ i++;
4571
+ } else if (c === "|") {
4572
+ if (next === "|") {
4573
+ endStatement();
4574
+ i += PAIR;
4575
+ } else {
4576
+ endStage();
4577
+ i++;
4578
+ }
4579
+ } else if (c === "&") {
4580
+ if (next === "&") {
4581
+ endStatement();
4582
+ i += PAIR;
4583
+ } else {
4584
+ if (has2 || stage.words.length > 0) grow(c, false);
4585
+ i++;
4586
+ }
4587
+ } else if (c === "#" && !has2) {
4588
+ while (i < n && text.charAt(i) !== "\n") i++;
4589
+ } else if (c === ">") {
4590
+ let fd = STDOUT_FD;
4591
+ if (has2 && bare && isFd(word)) {
4592
+ fd = word;
4593
+ word = "";
4594
+ has2 = false;
4595
+ } else if (has2) endWord();
4596
+ let j = i + 1;
4597
+ if (text.charAt(j) === ">") j++;
4598
+ if (text.charAt(j) === "&") {
4599
+ j++;
4600
+ while (j < n && !GLUE_END.includes(text.charAt(j))) j++;
4601
+ } else target = fd === STDOUT_FD || fd === FD_STAR ? "file" : "skip";
4602
+ i = j;
4603
+ } else if (c === "(" && has2 && bare && word.includes(METHOD_MARK)) {
4604
+ const e = closeOf(text, i);
4605
+ const inner = text.slice(i + 1, e < 0 ? n : e);
4606
+ endWord();
4607
+ for (const a of inner.trim() === "" ? [] : splitArgs(inner)) {
4608
+ const first = psParse(a)[0]?.[0]?.words[0];
4609
+ stage.words.push(first ?? a.trim());
4610
+ }
4611
+ i = e < 0 ? n : e + 1;
4612
+ if (i < n && !GLUE_END.includes(text.charAt(i))) {
4613
+ stage.chained = true;
4614
+ i = glueEnd(text, i);
4615
+ }
4616
+ } else if (c === "[" && !has2 && text.startsWith(METHOD_MARK, closeOf(text, i) + 1) && closeOf(text, i) >= 0) {
4617
+ const e = closeOf(text, i);
4618
+ grow(text.slice(i, e + 1), false);
4619
+ i = e + 1;
4620
+ } else if (OPENERS.includes(c) && (c !== "[" || !has2) || (c === "$" || c === "@") && OPENERS.includes(next) && next !== "[") {
4621
+ const open = c === "$" || c === "@" ? i + 1 : i;
4622
+ const e = closeOf(text, open);
4623
+ grow(text.slice(i, e < 0 ? n : e + 1), true);
4624
+ i = e < 0 ? n : e + 1;
4625
+ } else {
4626
+ grow(c, false);
4627
+ i++;
4628
+ }
4629
+ }
4630
+ endStatement();
4631
+ return statements;
4632
+ }
4633
+ var READ_COMMANDS = ["get-content", "gc", "cat", "type"];
4634
+ var FILE_CLASSES = ["[io.file]::", "[system.io.file]::"];
4635
+ var FILE_READS = ["readalltext", "readalllines", "readallbytes", "readlines"];
4636
+ var PATH_PARAMS = ["path", "literalpath"];
4637
+ var BOUND_PARAMS = ["totalcount", "head", "first", "tail", "last"];
4638
+ var VALUE_PARAMS = [...PATH_PARAMS, ...BOUND_PARAMS, "encoding", "readcount", "delimiter", "filter", "include", "exclude", "stream", "credential"];
4639
+ var SWITCH_PARAMS = ["raw", "wait", "force", "asbytestream"];
4640
+ var ALL_PARAMS = [...VALUE_PARAMS, ...SWITCH_PARAMS];
4641
+ var PASS_THROUGH = ["out-string", "write-output", "echo", "write", "out-host", "write-host", "out-default", "tee-object"];
4642
+ var CD_COMMANDS = ["cd", "chdir", "sl", "set-location", "pushd", "push-location"];
4643
+ var POWERSHELLS = ["powershell", "powershell.exe", "pwsh", "pwsh.exe"];
4644
+ var CMDS = ["cmd", "cmd.exe"];
4645
+ var CMD_RUN_FLAGS = ["/c", "/k", "/r"];
4646
+ var COMMAND_PARAM = "command";
4647
+ var DASH = "-";
4648
+ function cmdName(word) {
4649
+ const k = Math.max(word.lastIndexOf("\\"), word.lastIndexOf("/"));
4650
+ return (k >= 0 && k < word.length - 1 ? word.slice(k + 1) : word).toLowerCase();
4651
+ }
4652
+ function param(word, names) {
4653
+ const body = word.slice(DASH.length);
4654
+ const colon = body.indexOf(":");
4655
+ const name = (colon < 0 ? body : body.slice(0, colon)).toLowerCase();
4656
+ const inline = colon < 0 ? void 0 : body.slice(colon + 1);
4657
+ if (name === "") return { full: void 0, inline };
4658
+ if (names.includes(name)) return { full: name, inline };
4659
+ const hits = names.filter((p) => p.startsWith(name));
4660
+ return { full: hits.length === 1 ? hits[0] : void 0, inline };
4661
+ }
4662
+ function psDump(words) {
4663
+ if (words.length === 0) return null;
4664
+ const name = cmdName(words[0]);
4665
+ if (!READ_COMMANDS.includes(name)) {
4666
+ const lower = words[0].toLowerCase();
4667
+ const cls = FILE_CLASSES.find((c) => lower.startsWith(c));
4668
+ if (cls === void 0 || !FILE_READS.includes(lower.slice(cls.length)) || words.length < MIN_STATIC_CALL) return null;
4669
+ return { file: words[1], bounded: false };
4670
+ }
4671
+ const files = [];
4672
+ let bounded = false;
4673
+ for (let k = 1; k < words.length; k++) {
4674
+ const a = words[k];
4675
+ if (!a.startsWith(DASH) || a.length === DASH.length) {
4676
+ files.push(a);
4677
+ continue;
4678
+ }
4679
+ const p = param(a, ALL_PARAMS);
4680
+ if (p.full === void 0 || !VALUE_PARAMS.includes(p.full)) continue;
4681
+ const value = p.inline ?? words[++k];
4682
+ if (value === void 0) return null;
4683
+ if (PATH_PARAMS.includes(p.full)) files.push(value);
4684
+ if (BOUND_PARAMS.includes(p.full)) bounded = true;
4685
+ }
4686
+ return files.length === 1 ? { file: files[0], bounded } : null;
4687
+ }
4688
+ function nestedScript(name, words) {
4689
+ if (POWERSHELLS.includes(name)) {
4690
+ for (let k = 1; k < words.length; k++) {
4691
+ const w = words[k];
4692
+ if (!w.startsWith(DASH) || w.length === DASH.length) continue;
4693
+ const p = param(w, [COMMAND_PARAM]);
4694
+ if (p.full === void 0) continue;
4695
+ return [...p.inline === void 0 ? [] : [p.inline], ...words.slice(k + 1)].join(" ");
4696
+ }
4697
+ return null;
4698
+ }
4699
+ if (CMDS.includes(name)) {
4700
+ for (let k = 1; k < words.length; k++) {
4701
+ if (CMD_RUN_FLAGS.includes(words[k].toLowerCase())) return words.slice(k + 1).join(" ");
4702
+ }
4703
+ }
4704
+ return null;
4705
+ }
4706
+ function cdTarget(words) {
4707
+ for (let k = 1; k < words.length; k++) {
4708
+ const w = words[k];
4709
+ if (w.toLowerCase() === "/d") continue;
4710
+ if (!w.startsWith(DASH) || w.length === DASH.length) return w;
4711
+ const p = param(w, PATH_PARAMS);
4712
+ if (p.full !== void 0) return p.inline ?? words[k + 1] ?? null;
4713
+ }
4714
+ return null;
4715
+ }
4716
+ function walk(script, cwd, depth, found) {
4717
+ let dir = cwd;
4718
+ for (const stages of psParse(script)) {
4719
+ const head = stages[0];
4720
+ if (head.words.length === 0) continue;
4721
+ const name = cmdName(head.words[0]);
4722
+ if (stages.length === 1 && CD_COMMANDS.includes(name)) {
4723
+ const t = cdTarget(head.words);
4724
+ if (t !== null) dir = resolve(dir, t);
4725
+ continue;
4726
+ }
4727
+ const inner = depth < MAX_NEST_DEPTH ? nestedScript(name, head.words) : null;
4728
+ if (inner !== null) {
4729
+ walk(inner, dir, depth + 1, found);
4730
+ continue;
4731
+ }
4732
+ if (head.toFile || head.chained) continue;
4733
+ const d = psDump(head.words);
4734
+ if (d === null || d.bounded) continue;
4735
+ let shown = true;
4736
+ for (let k = 1; k < stages.length; k++) {
4737
+ if (stages[k].toFile || !PASS_THROUGH.includes(cmdName(stages[k].words[0] ?? ""))) {
4738
+ shown = false;
4739
+ break;
4740
+ }
4741
+ }
4742
+ if (shown) found.push(resolve(dir, d.file));
4743
+ }
4744
+ }
4745
+ function psDumpFiles(script, cwd) {
4746
+ const found = [];
4747
+ walk(script, cwd, 0, found);
4748
+ return found;
4749
+ }
4750
+
4285
4751
  // src/core/policy/subagent.ts
4286
4752
  import { join as join2 } from "node:path";
4287
4753
 
4288
4754
  // src/core/project/config-dir.ts
4289
- import { join, posix, win32 } from "node:path";
4755
+ import { basename, dirname, join, posix, resolve as resolve2, win32 } from "node:path";
4290
4756
  var { mkdirSync: mkdirSync2, realpathSync } = process.getBuiltinModule("node:fs");
4291
4757
  function homeDirOf(env, platform = process.platform) {
4292
4758
  const set = (v) => v !== void 0 && v !== "";
@@ -4326,7 +4792,7 @@ var WRAPPERS = Object.freeze({
4326
4792
  command: { valueShorts: NONE, valueLongs: [], assignments: false, duration: false, refuseShorts: "vV" },
4327
4793
  xargs: { valueShorts: "aEdILnPs", valueLongs: ["--arg-file", "--delimiter", "--max-args", "--max-procs", "--max-chars"], assignments: false, duration: false, refuseShorts: NONE }
4328
4794
  });
4329
- var SHELLS = ["bash", "sh"];
4795
+ var SHELLS = ["bash", "sh", "zsh"];
4330
4796
  var SCRIPT_FLAG = "c";
4331
4797
  var SHELL_LABEL_SUFFIX = " -c";
4332
4798
  var SHELL_VALUE_OPTS = ["-o", "+o", "-O", "+O"];
@@ -4555,15 +5021,15 @@ function matchesAnyDenyPattern(text, patterns, subject = BASH_SUBJECT) {
4555
5021
 
4556
5022
  // src/prompt/_generated.ts
4557
5023
  var TOOL_DESCRIPTIONS = Object.freeze({
4558
- ctx_execute: "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.\n",
4559
- ctx_batch: "Runs 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.",
4560
- ctx_index: "Stores 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.",
4561
- ctx_search: "Searches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.",
4562
- ctx_resume: "Returns 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.",
4563
- ctx_stats: "Reports how many bytes context-mode kept out of the conversation in this session and in this project, per agent, as a Markdown table. Show the table to the user as it is. Use it when the user asks what context-mode saved.",
4564
- ctx_doctor: "Checks 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 and the fix in one line. It changes nothing. Use it when the user asks whether context-mode works, or after a context-mode error.",
4565
- ctx_upgrade: "Updates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",
4566
- ctx_purge: "Deletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data."
5024
+ 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.',
5025
+ 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.',
5026
+ 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.',
5027
+ 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.',
5028
+ 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.",
5029
+ 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.",
5030
+ 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",
5031
+ ctx_upgrade: "Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",
5032
+ ctx_purge: 'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'
4567
5033
  });
4568
5034
  var READ_DENY_TEMPLATE = 'context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';
4569
5035
 
@@ -4629,7 +5095,7 @@ function readPath(input) {
4629
5095
  }
4630
5096
  function userDenyHit(canonical, input, cwd, rules) {
4631
5097
  if (rules.length === 0) return null;
4632
- const readRule = (p) => matchesAnyDenyPattern(resolve(cwd, p), rules, { tool: READ, projectDir: cwd });
5098
+ const readRule = (p) => matchesAnyDenyPattern(resolve3(cwd, p), rules, { tool: READ, projectDir: cwd });
4633
5099
  if (canonical === BASH) {
4634
5100
  const cmd = str(input.command);
4635
5101
  return cmd === void 0 ? null : matchesAnyDenyPattern(cmd, rules);
@@ -4681,7 +5147,7 @@ function webFetch(input, row) {
4681
5147
  function bash(ev, row, input, rules) {
4682
5148
  const cmd = str(input.command) ?? "";
4683
5149
  const parsed = parseShell(cmd);
4684
- if (!parsed.ok) return couldMatch(cmd, rules) ? deny(prefixToolNames(PARSE_ERROR_DENY_LINE, row.toolNamePrefix)) : ALLOW;
5150
+ if (!parsed.ok) return couldMatch(cmd, rules) ? deny(prefixToolNames(PARSE_ERROR_DENY_LINE, row.toolNamePrefix)) : psShellDump(cmd, ev.cwd, row) ?? ALLOW;
4685
5151
  const cmds = unwrap(parsed.commands);
4686
5152
  for (const c of cmds) {
4687
5153
  const h = segmentHit(c, rules);
@@ -4693,7 +5159,7 @@ function bash(ev, row, input, rules) {
4693
5159
  if (kind !== null) return deny(denyMessage(kind, cmd, row, str(input.description)));
4694
5160
  }
4695
5161
  }
4696
- return shellDump(cmds, ev.cwd, row) ?? ALLOW;
5162
+ return shellDump(cmds, ev.cwd, row) ?? psShellDump(cmd, ev.cwd, row) ?? ALLOW;
4697
5163
  }
4698
5164
  function denyKind(c) {
4699
5165
  const name = c.argv0.toLowerCase();
@@ -4727,6 +5193,7 @@ function inlineHttp(raw) {
4727
5193
  }
4728
5194
  return false;
4729
5195
  }
5196
+ var CD_COMMAND = "cd";
4730
5197
  function fileSize(abs) {
4731
5198
  try {
4732
5199
  const st = statSync(abs);
@@ -4739,7 +5206,7 @@ function read(ev, row, input) {
4739
5206
  if (!present(input.offset) && !present(input.limit)) {
4740
5207
  const p = readPath(input);
4741
5208
  if (p !== void 0) {
4742
- const abs = resolve(ev.cwd, p);
5209
+ const abs = resolve3(ev.cwd, p);
4743
5210
  const size = fileSize(abs);
4744
5211
  if (size > OUTPUT_CAP) return deny(READ_DENY_MESSAGE(abs, size, row.toolNamePrefix));
4745
5212
  }
@@ -4748,17 +5215,32 @@ function read(ev, row, input) {
4748
5215
  }
4749
5216
  function shellDump(cmds, cwd, row) {
4750
5217
  if (row.nativeTools.read !== void 0 && row.nativeTools.read.length > 0 && dumpRunsThenReplaces(row)) return null;
4751
- if (cmds.length !== 1) return null;
4752
- const c = cmds[0];
4753
- if (c.redirectsToFile || c.endsInBoundedSink) return null;
4754
- const name = c.argv0.toLowerCase();
4755
- if (!has(SHELL_DUMP_COMMANDS, name)) return null;
4756
- const d = dumpTarget(name, c.args);
4757
- if (d === null) return null;
4758
- if (d.bounded) return ALLOW;
4759
- const abs = resolve(cwd, d.file);
4760
- const size = fileSize(abs);
4761
- return size > OUTPUT_CAP ? deny(READ_DENY_MESSAGE(abs, size, row.toolNamePrefix)) : null;
5218
+ let dir = cwd;
5219
+ let verdict = null;
5220
+ for (const c of cmds) {
5221
+ const name = c.argv0.toLowerCase();
5222
+ if (name === CD_COMMAND && c.args.length === 1 && c.insideConstruct === void 0) dir = resolve3(dir, c.args[0]);
5223
+ if (c.redirectsToFile || c.endsInBoundedSink || c.pipesOut === true || c.insideConstruct !== void 0) continue;
5224
+ if (!has(SHELL_DUMP_COMMANDS, name)) continue;
5225
+ const d = dumpTarget(name, c.args);
5226
+ if (d === null) continue;
5227
+ if (d.bounded) {
5228
+ verdict = ALLOW;
5229
+ continue;
5230
+ }
5231
+ const abs = resolve3(dir, d.file);
5232
+ const size = fileSize(abs);
5233
+ if (size > OUTPUT_CAP) return deny(READ_DENY_MESSAGE(abs, size, row.toolNamePrefix));
5234
+ }
5235
+ return verdict;
5236
+ }
5237
+ function psShellDump(cmd, cwd, row) {
5238
+ if (row.nativeTools.read !== void 0 && row.nativeTools.read.length > 0 && dumpRunsThenReplaces(row)) return null;
5239
+ for (const abs of psDumpFiles(cmd, cwd)) {
5240
+ const size = fileSize(abs);
5241
+ if (size > OUTPUT_CAP) return deny(READ_DENY_MESSAGE(abs, size, row.toolNamePrefix));
5242
+ }
5243
+ return null;
4762
5244
  }
4763
5245
  var allDigits2 = (s) => s !== "" && [...s].every((ch) => ch >= "0" && ch <= "9");
4764
5246
  function countFlag(a) {
@@ -4817,10 +5299,10 @@ function dumpTarget(name, args) {
4817
5299
  }
4818
5300
 
4819
5301
  // src/core/project/resolve.ts
4820
- import { basename, dirname as dirname2, join as join4, resolve as resolve2 } from "node:path";
5302
+ import { basename as basename2, dirname as dirname3, join as join4, resolve as resolve4 } from "node:path";
4821
5303
 
4822
5304
  // src/core/project/contain.ts
4823
- import { dirname, sep as sep2 } from "node:path";
5305
+ import { dirname as dirname2, sep as sep2 } from "node:path";
4824
5306
  var { realpathSync: realpathSync2 } = process.getBuiltinModule("node:fs");
4825
5307
  function real(p) {
4826
5308
  try {
@@ -4845,7 +5327,7 @@ function commonRoot(paths) {
4845
5327
  n = i;
4846
5328
  }
4847
5329
  let q = first;
4848
- while (components(q).length > n && dirname(q) !== q) q = dirname(q);
5330
+ while (components(q).length > n && dirname2(q) !== q) q = dirname2(q);
4849
5331
  return q;
4850
5332
  }
4851
5333
 
@@ -5007,14 +5489,15 @@ function gitDirs(dir) {
5007
5489
  } catch {
5008
5490
  throw new CtxError("NO_GIT_DIR", { path: dir });
5009
5491
  }
5492
+ const start = cur;
5010
5493
  for (; ; ) {
5011
5494
  const gitDir = gitDirAt(join4(cur, GIT_DIR_NAME));
5012
5495
  if (gitDir !== null) {
5013
5496
  const common = firstLine(join4(gitDir, GIT_COMMONDIR_FILE));
5014
- return { commonDir: realpathSync3.native(common === null ? gitDir : resolve2(gitDir, common)), worktree: cur };
5497
+ return { commonDir: realpathSync3.native(common === null ? gitDir : resolve4(gitDir, common)), worktree: cur, start };
5015
5498
  }
5016
- const up = dirname2(cur);
5017
- if (up === cur) return null;
5499
+ const up = dirname3(cur);
5500
+ if (up === cur) return { commonDir: null, start };
5018
5501
  cur = up;
5019
5502
  }
5020
5503
  }
@@ -5026,7 +5509,7 @@ function gitDirAt(dotGit) {
5026
5509
  } else {
5027
5510
  const line = firstLine(dotGit);
5028
5511
  if (line === null || !line.startsWith(GITDIR_FILE_PREFIX)) return null;
5029
- gitDir = resolve2(dirname2(dotGit), line.slice(GITDIR_FILE_PREFIX.length));
5512
+ gitDir = resolve4(dirname3(dotGit), line.slice(GITDIR_FILE_PREFIX.length));
5030
5513
  }
5031
5514
  } catch {
5032
5515
  return null;
@@ -5051,25 +5534,33 @@ function git(dir, args) {
5051
5534
  return r.stdout.split("\n").filter((l) => l !== "");
5052
5535
  }
5053
5536
  function containmentRootOf(dir, commonDir) {
5054
- const repoDir = basename(commonDir) === GIT_DIR_NAME ? dirname2(commonDir) : commonDir;
5537
+ const repoDir = basename2(commonDir) === GIT_DIR_NAME ? dirname3(commonDir) : commonDir;
5055
5538
  const worktrees = git(dir, ["worktree", "list", "--porcelain"]).filter((l) => l.startsWith(GIT_WORKTREE_LINE_PREFIX)).map((l) => l.slice(GIT_WORKTREE_LINE_PREFIX.length));
5056
- return commonRoot([dirname2(repoDir), ...worktrees]);
5539
+ return commonRoot([dirname3(repoDir), ...worktrees]);
5057
5540
  }
5058
5541
  function resolveProject(agent, src) {
5059
5542
  const source = sourceOf(agent);
5060
5543
  const dir = dirOf(source, src);
5061
5544
  if (dir === void 0) throw new CtxError("NO_PROJECT", { kind: source });
5062
5545
  const repo = gitDirs(dir);
5063
- const plain = repo === null ? realpathSync3.native(dir) : void 0;
5064
- const commonDir = repo?.commonDir ?? plain;
5065
- const worktree = repo?.worktree ?? plain;
5066
- const projectKey = sha256Hex(commonDir).slice(0, PROJECT_KEY_HEX_LEN);
5067
- const projectDir = join4(resolveConfigDir(process.env), PROJECTS_DIR_NAME, projectKey);
5546
+ const plain = repo.commonDir === null ? repo.start : void 0;
5547
+ const commonDir = repo.commonDir ?? repo.start;
5548
+ const worktree = repo.commonDir === null ? repo.start : repo.worktree;
5549
+ let key;
5550
+ let pdir;
5068
5551
  let root;
5069
5552
  return {
5070
- projectKey,
5071
- projectDir,
5072
- dbPath: join4(projectDir, DB_FILE_NAME),
5553
+ get projectKey() {
5554
+ key ??= sha256Hex(commonDir).slice(0, PROJECT_KEY_HEX_LEN);
5555
+ return key;
5556
+ },
5557
+ get projectDir() {
5558
+ pdir ??= join4(resolveConfigDir(process.env), PROJECTS_DIR_NAME, this.projectKey);
5559
+ return pdir;
5560
+ },
5561
+ get dbPath() {
5562
+ return join4(this.projectDir, DB_FILE_NAME);
5563
+ },
5073
5564
  worktree,
5074
5565
  get containmentRoot() {
5075
5566
  root ??= plain ?? containmentRootOf(dir, commonDir);
@@ -5231,10 +5722,10 @@ function startArgv(argv) {
5231
5722
  return sh === null ? null : [sh, ...argv];
5232
5723
  }
5233
5724
  function runProcess(argv, o) {
5234
- return new Promise((resolve3) => {
5725
+ return new Promise((resolve5) => {
5235
5726
  const isWin2 = process.platform === "win32";
5236
5727
  const start = startArgv(argv);
5237
- if (start === null) return resolve3(NOT_STARTED);
5728
+ if (start === null) return resolve5(NOT_STARTED);
5238
5729
  let child;
5239
5730
  try {
5240
5731
  child = spawn(start[0], start.slice(1), {
@@ -5248,7 +5739,7 @@ function runProcess(argv, o) {
5248
5739
  windowsHide: true
5249
5740
  });
5250
5741
  } catch {
5251
- return resolve3(NOT_STARTED);
5742
+ return resolve5(NOT_STARTED);
5252
5743
  }
5253
5744
  const stdoutChunks = [];
5254
5745
  const stderrChunks = [];
@@ -5273,7 +5764,7 @@ function runProcess(argv, o) {
5273
5764
  settled = true;
5274
5765
  clearTimeout(timer);
5275
5766
  o.signal.removeEventListener("abort", onAbort);
5276
- resolve3({
5767
+ resolve5({
5277
5768
  stdout: Buffer.concat(stdoutChunks),
5278
5769
  stderr: Buffer.concat(stderrChunks),
5279
5770
  exitCode,
@@ -5721,7 +6212,7 @@ async function runWrapperMain(argv, env) {
5721
6212
  let text;
5722
6213
  try {
5723
6214
  const { sourceId } = indexText(db, project, sessionId, sourceLabel(command), combined, "text");
5724
- const more = moreLine2(dirname3(argv[1] ?? ""), sourceId, description);
6215
+ const more = moreLine2(dirname4(argv[1] ?? ""), sourceId, description);
5725
6216
  const picked = selectChunks(db, sourceId, description, OUTPUT_CAP - bytes(head) - bytes(more) - 2);
5726
6217
  text = head + "\n" + picked.text + (picked.more === null ? "" : "\n" + more);
5727
6218
  } finally {
@@ -5755,5 +6246,5 @@ async function searchWrapperMain(argv, _env) {
5755
6246
  }
5756
6247
 
5757
6248
  // src/entries/run.ts
5758
- var main = basename2(process.argv[1] ?? "") === SEARCH_WRAPPER_FILE ? searchWrapperMain : runWrapperMain;
6249
+ var main = basename3(process.argv[1] ?? "") === SEARCH_WRAPPER_FILE ? searchWrapperMain : runWrapperMain;
5759
6250
  void main(process.argv, process.env);