@cortexkit/magic-context 0.41.1 → 0.41.2

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.
Files changed (2) hide show
  1. package/dist/index.js +453 -91
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -14841,6 +14841,11 @@ var init_logger = __esm(() => {
14841
14841
  });
14842
14842
  // ../plugin/src/shared/window-geometry.ts
14843
14843
  function setWindowOverlayPath(path3) {
14844
+ if (configuredOverlayPath === path3)
14845
+ return;
14846
+ reloadWindowOverlay(path3);
14847
+ }
14848
+ function reloadWindowOverlay(path3) {
14844
14849
  configuredOverlayPath = path3;
14845
14850
  loadedOverlayPath = undefined;
14846
14851
  loadedOverlay = undefined;
@@ -31904,8 +31909,8 @@ function runOpenCode(args, binary, timeoutMs) {
31904
31909
  return null;
31905
31910
  }
31906
31911
  }
31907
- function getOpenCodeVersion(binary) {
31908
- return runOpenCode(["--version"], binary, OPENCODE_VERSION_PROBE_TIMEOUT_MS);
31912
+ function getOpenCodeVersion(binary, timeoutMs = OPENCODE_VERSION_PROBE_TIMEOUT_MS) {
31913
+ return runOpenCode(["--version"], binary, timeoutMs);
31909
31914
  }
31910
31915
  function describeOpenCodeInstallations(installations, deps = {}) {
31911
31916
  const getVersion = deps.getVersion ?? getOpenCodeVersion;
@@ -35720,7 +35725,7 @@ function readPsProcessStartTime(pid) {
35720
35725
  function readProcessStartTime(pid) {
35721
35726
  if (!Number.isInteger(pid) || pid <= 0)
35722
35727
  return null;
35723
- return rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(pid) : rpcIdentityPlatform === "win32" ? null : readPsProcessStartTime(pid);
35728
+ return rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(pid) : rpcIdentityPlatform === "win32" ? readWindowsProcessStartTime(pid) : readPsProcessStartTime(pid);
35724
35729
  }
35725
35730
  function readProcessProbeEvidence(pid) {
35726
35731
  return {
@@ -35728,6 +35733,9 @@ function readProcessProbeEvidence(pid) {
35728
35733
  commandLine: readProcessCommand(pid)
35729
35734
  };
35730
35735
  }
35736
+ function rememberWindowsProcessFacts(facts) {
35737
+ windowsProcessFactsCache = new Map(facts.map((fact) => [fact.pid, fact]));
35738
+ }
35731
35739
  function parseCsvLine(line) {
35732
35740
  const fields = [];
35733
35741
  let field = "";
@@ -35792,6 +35800,16 @@ function readWindowsProcess(pid) {
35792
35800
  return { state: "inconclusive" };
35793
35801
  }
35794
35802
  }
35803
+ function readWindowsProcessStartTime(pid) {
35804
+ const cached2 = windowsProcessFactsCache?.get(pid);
35805
+ if (cached2)
35806
+ return cached2.startTime;
35807
+ const snapshot = tryReadWindowsCimSnapshot(rpcIdentityExecFileSync);
35808
+ if (!snapshot)
35809
+ return null;
35810
+ rememberWindowsProcessFacts(snapshot.facts);
35811
+ return windowsProcessFactsCache?.get(pid)?.startTime ?? null;
35812
+ }
35795
35813
  function readLinuxProcessCommand(pid) {
35796
35814
  try {
35797
35815
  return String(rpcIdentityReadFileSync(`/proc/${pid}/cmdline`, "utf8"));
@@ -35814,7 +35832,15 @@ function readPsProcessCommand(pid) {
35814
35832
  function readProcessCommand(pid) {
35815
35833
  if (!Number.isInteger(pid) || pid <= 0)
35816
35834
  return null;
35817
- return rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(pid) : rpcIdentityPlatform === "win32" ? readWindowsProcess(pid).command ?? null : readPsProcessCommand(pid);
35835
+ if (rpcIdentityPlatform === "linux")
35836
+ return readLinuxProcessCommand(pid);
35837
+ if (rpcIdentityPlatform === "win32") {
35838
+ const cached2 = windowsProcessFactsCache?.get(pid);
35839
+ if (cached2?.commandLine)
35840
+ return cached2.commandLine;
35841
+ return readWindowsProcess(pid).command ?? null;
35842
+ }
35843
+ return readPsProcessCommand(pid);
35818
35844
  }
35819
35845
  function executableName(token) {
35820
35846
  return (token ?? "").replace(/^['"]|['"]$/g, "").split("/").at(-1) ?? "";
@@ -35874,57 +35900,262 @@ function isPidIdentityPlausible(record2, evidence) {
35874
35900
  return "inconclusive";
35875
35901
  return commandLooksLikeOpenCode(command) ? "plausible" : "implausible";
35876
35902
  }
35877
- function commandLooksLikePi(command) {
35878
- const normalized = command.trim().toLowerCase().replaceAll("\\", "/");
35879
- const tokens = normalized.split(/\s+/).filter(Boolean);
35880
- const executableName2 = (token) => (token ?? "").split("/").at(-1) ?? "";
35881
- const first = executableName2(tokens[0]).replace(/\.exe$/, "");
35882
- if (["pi", "pi.cmd", "omp", "oh-my-pi"].includes(first))
35903
+ function commandLooksLikePiImage(command) {
35904
+ const tokens = commandTokens(command);
35905
+ const first = executableName(tokens[0]).replace(/\.(?:exe|cmd)$/, "");
35906
+ return PI_IMAGE_NAMES.has(first);
35907
+ }
35908
+ function commandHasPiHarnessArc(command) {
35909
+ const normalized = command.trim().toLowerCase().replaceAll("\\", "/").replaceAll("\x00", " ");
35910
+ if (!normalized)
35911
+ return false;
35912
+ const tokens = commandTokens(command);
35913
+ if (tokens.length === 0)
35914
+ return false;
35915
+ const hasArc = PI_HARNESS_ARC_MARKERS.some((marker) => normalized.includes(marker));
35916
+ const first = executableName(tokens[0]).replace(/\.(?:exe|cmd)$/, "");
35917
+ if (hasArc && ["pi", "omp", "oh-my-pi", "node", "bun", "deno", "cmd"].includes(first)) {
35883
35918
  return true;
35919
+ }
35920
+ if (hasArc && PI_HARNESS_ARC_MARKERS.some((marker) => tokens[0].includes(marker))) {
35921
+ return true;
35922
+ }
35884
35923
  if (["node", "bun", "deno"].includes(first)) {
35885
- const script = executableName2(tokens[1]);
35886
- return ["pi", "pi.js", "pi.mjs", "pi.cjs"].includes(script) || normalized.includes("pi-coding-agent");
35924
+ const script = executableName(tokens[1]).replace(/\.(?:exe|cmd)$/, "");
35925
+ if (["pi", "pi.js", "pi.mjs", "pi.cjs"].includes(script))
35926
+ return true;
35927
+ if (hasArc)
35928
+ return true;
35887
35929
  }
35888
35930
  return false;
35889
35931
  }
35932
+ function execProcessList(exec2, file2, args, timeout = PS_PROBE_TIMEOUT_MS) {
35933
+ return String(exec2(file2, [...args], {
35934
+ encoding: "utf8",
35935
+ timeout,
35936
+ stdio: ["ignore", "pipe", "pipe"]
35937
+ }));
35938
+ }
35939
+ function parseWindowsCreationDate(value) {
35940
+ if (typeof value === "number" && Number.isFinite(value)) {
35941
+ return value > 1000000000000 ? value : value * 1000;
35942
+ }
35943
+ if (typeof value !== "string")
35944
+ return null;
35945
+ const trimmed = value.trim();
35946
+ if (!trimmed)
35947
+ return null;
35948
+ const wmi = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/.exec(trimmed);
35949
+ if (wmi) {
35950
+ const utcMs = Date.UTC(Number(wmi[1]), Number(wmi[2]) - 1, Number(wmi[3]), Number(wmi[4]), Number(wmi[5]), Number(wmi[6]), Number(wmi[7]) / 1000);
35951
+ if (!Number.isFinite(utcMs))
35952
+ return null;
35953
+ const offsetMinutes = Number(wmi[9]);
35954
+ const sign = wmi[8] === "+" ? 1 : -1;
35955
+ return utcMs - sign * offsetMinutes * 60000;
35956
+ }
35957
+ const dotNet = /^\/Date\((-?\d+)\)\/$/.exec(trimmed);
35958
+ if (dotNet) {
35959
+ const milliseconds = Number(dotNet[1]);
35960
+ return Number.isFinite(milliseconds) ? milliseconds : null;
35961
+ }
35962
+ const parsed = Date.parse(trimmed);
35963
+ return Number.isFinite(parsed) ? parsed : null;
35964
+ }
35965
+ function parseWindowsCimOutput(output) {
35966
+ const trimmed = output.trim();
35967
+ if (!trimmed)
35968
+ return null;
35969
+ const bracket = trimmed.indexOf("[");
35970
+ const brace = trimmed.indexOf("{");
35971
+ const start = Math.min(bracket === -1 ? Number.POSITIVE_INFINITY : bracket, brace === -1 ? Number.POSITIVE_INFINITY : brace);
35972
+ if (!Number.isFinite(start))
35973
+ return null;
35974
+ let parsed;
35975
+ try {
35976
+ parsed = JSON.parse(trimmed.slice(start));
35977
+ } catch {
35978
+ return null;
35979
+ }
35980
+ if (parsed == null)
35981
+ return null;
35982
+ const rows = Array.isArray(parsed) ? parsed : [parsed];
35983
+ const facts = [];
35984
+ for (const row of rows) {
35985
+ if (!row || typeof row !== "object")
35986
+ continue;
35987
+ const record2 = row;
35988
+ const pid = Number(record2.ProcessId);
35989
+ if (!Number.isInteger(pid) || pid <= 0)
35990
+ continue;
35991
+ const parentRaw = record2.ParentProcessId;
35992
+ const parentPid = parentRaw == null || parentRaw === "" ? Number.NaN : Number(parentRaw);
35993
+ const commandLine = typeof record2.CommandLine === "string" ? record2.CommandLine : null;
35994
+ facts.push({
35995
+ pid,
35996
+ parentPid: Number.isInteger(parentPid) && parentPid > 0 ? parentPid : null,
35997
+ commandLine,
35998
+ imageName: commandLine ? executableName(commandTokens(commandLine)[0]) : null,
35999
+ startTime: parseWindowsCreationDate(record2.CreationDate)
36000
+ });
36001
+ }
36002
+ return facts.length > 0 ? facts : null;
36003
+ }
36004
+ function snapshotFromFacts(facts, source) {
36005
+ const parentByPid = new Map;
36006
+ for (const fact of facts) {
36007
+ if (fact.parentPid != null)
36008
+ parentByPid.set(fact.pid, fact.parentPid);
36009
+ }
36010
+ return { facts, parentByPid, source };
36011
+ }
36012
+ function tryReadWindowsCimSnapshot(exec2) {
36013
+ try {
36014
+ const output = execProcessList(exec2, "powershell", ["-NoProfile", "-Command", WINDOWS_CIM_COMMAND], WINDOWS_CIM_PROBE_TIMEOUT_MS);
36015
+ const facts = parseWindowsCimOutput(output);
36016
+ return facts ? snapshotFromFacts(facts, "cim") : null;
36017
+ } catch {
36018
+ return null;
36019
+ }
36020
+ }
36021
+ function tryReadWindowsTasklistSnapshot() {
36022
+ try {
36023
+ const output = execProcessList(rpcProcessListExecFileSync, "tasklist", ["/FO", "CSV"]);
36024
+ const entries = parseTasklistOutput(output);
36025
+ if (entries === null)
36026
+ return null;
36027
+ const facts = entries.map((entry) => ({
36028
+ pid: entry.pid,
36029
+ parentPid: null,
36030
+ commandLine: null,
36031
+ imageName: entry.command,
36032
+ startTime: null
36033
+ }));
36034
+ return snapshotFromFacts(facts, "tasklist");
36035
+ } catch {
36036
+ return null;
36037
+ }
36038
+ }
36039
+ function readPosixProcessSnapshot() {
36040
+ const output = execProcessList(rpcProcessListExecFileSync, "ps", ["-axo", "pid=,command="]);
36041
+ const facts = [];
36042
+ for (const line of output.split(/\r?\n/)) {
36043
+ const match = /^\s*(\d+)\s+(.+)$/.exec(line);
36044
+ if (!match)
36045
+ continue;
36046
+ const pid = Number(match[1]);
36047
+ if (!Number.isInteger(pid) || pid <= 0)
36048
+ continue;
36049
+ facts.push({
36050
+ pid,
36051
+ parentPid: null,
36052
+ commandLine: match[2],
36053
+ imageName: executableName(commandTokens(match[2])[0]),
36054
+ startTime: null
36055
+ });
36056
+ }
36057
+ return snapshotFromFacts(facts, "ps");
36058
+ }
36059
+ function readPosixParentPid(pid) {
36060
+ try {
36061
+ const output = execProcessList(rpcProcessListExecFileSync, "ps", [
36062
+ "-o",
36063
+ "ppid=",
36064
+ "-p",
36065
+ String(pid)
36066
+ ]);
36067
+ const match = /^\s*(\d+)\s*$/.exec(output);
36068
+ if (!match)
36069
+ return null;
36070
+ const ppid = Number(match[1]);
36071
+ return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
36072
+ } catch {
36073
+ return null;
36074
+ }
36075
+ }
36076
+ function collectAncestorPids(selfPid, parentByPid) {
36077
+ const ancestors = new Set;
36078
+ let current = selfPid;
36079
+ for (let depth = 0;depth < MAX_ANCESTOR_WALK_DEPTH; depth += 1) {
36080
+ let ppid = null;
36081
+ if (parentByPid.has(current)) {
36082
+ ppid = parentByPid.get(current) ?? null;
36083
+ } else if (rpcIdentityPlatform !== "win32") {
36084
+ ppid = readPosixParentPid(current);
36085
+ if (ppid == null && current === process.pid && process.ppid > 0) {
36086
+ ppid = process.ppid;
36087
+ }
36088
+ } else if (current === process.pid && process.ppid > 0) {
36089
+ ppid = process.ppid;
36090
+ } else {
36091
+ break;
36092
+ }
36093
+ if (ppid == null || ppid <= 0 || ppid === current || ancestors.has(ppid))
36094
+ break;
36095
+ ancestors.add(ppid);
36096
+ current = ppid;
36097
+ }
36098
+ return ancestors;
36099
+ }
36100
+ function classifyLivePiSnapshot(snapshot) {
36101
+ const ancestors = collectAncestorPids(process.pid, snapshot.parentByPid);
36102
+ const processIds = new Set;
36103
+ const inconclusivePids = new Set;
36104
+ const skippedAncestorPids = [];
36105
+ for (const fact of snapshot.facts) {
36106
+ if (fact.pid === process.pid)
36107
+ continue;
36108
+ const command = fact.commandLine ?? fact.imageName ?? "";
36109
+ const looksLikeHarness = commandHasPiHarnessArc(command) || commandLooksLikePiImage(command);
36110
+ if (!looksLikeHarness)
36111
+ continue;
36112
+ if (ancestors.has(fact.pid)) {
36113
+ skippedAncestorPids.push(fact.pid);
36114
+ log3(`[magic-context] Pi process scan: skipping ancestor PID ${fact.pid} (session launcher shim)`);
36115
+ continue;
36116
+ }
36117
+ if (commandHasPiHarnessArc(command)) {
36118
+ processIds.add(fact.pid);
36119
+ continue;
36120
+ }
36121
+ inconclusivePids.add(fact.pid);
36122
+ log3(`[magic-context] Pi process scan: PID ${fact.pid} command line is ambiguous (image-name or missing Pi/OMP arc); treating as inconclusive`);
36123
+ }
36124
+ skippedAncestorPids.sort((left, right) => left - right);
36125
+ const verified = [...processIds].sort((left, right) => left - right);
36126
+ const inconclusive = [...inconclusivePids].sort((left, right) => left - right);
36127
+ if (verified.length === 0 && inconclusive.length > 0) {
36128
+ return {
36129
+ state: "inconclusive",
36130
+ processIds: [],
36131
+ inconclusivePids: inconclusive,
36132
+ ...skippedAncestorPids.length > 0 ? { skippedAncestorPids } : {}
36133
+ };
36134
+ }
36135
+ return {
36136
+ state: "known",
36137
+ processIds: verified,
36138
+ ...inconclusive.length > 0 ? { inconclusivePids: inconclusive } : {},
36139
+ ...skippedAncestorPids.length > 0 ? { skippedAncestorPids } : {}
36140
+ };
36141
+ }
35890
36142
  function inspectLivePiProcesses() {
35891
36143
  if (false) {}
35892
36144
  try {
35893
- const isWindows = rpcIdentityPlatform === "win32";
35894
- const output = String(rpcProcessListExecFileSync(isWindows ? "tasklist" : "ps", isWindows ? ["/FO", "CSV"] : ["-axo", "pid=,command="], {
35895
- encoding: "utf8",
35896
- timeout: PS_PROBE_TIMEOUT_MS,
35897
- stdio: ["ignore", "pipe", "pipe"]
35898
- }));
35899
- const pids = new Set;
35900
- if (isWindows) {
35901
- const entries = parseTasklistOutput(output);
35902
- if (entries === null) {
36145
+ if (rpcIdentityPlatform === "win32") {
36146
+ const cim = tryReadWindowsCimSnapshot(rpcProcessListExecFileSync);
36147
+ const snapshot = cim ?? tryReadWindowsTasklistSnapshot();
36148
+ if (!snapshot) {
35903
36149
  return {
35904
36150
  state: "unreadable",
35905
36151
  processIds: [],
35906
- error: "tasklist output unavailable"
36152
+ error: "process list unavailable"
35907
36153
  };
35908
36154
  }
35909
- for (const entry of entries) {
35910
- if (entry.pid === process.pid)
35911
- continue;
35912
- if (commandLooksLikePi(entry.command))
35913
- pids.add(entry.pid);
35914
- }
35915
- } else {
35916
- for (const line of output.split(/\r?\n/)) {
35917
- const match = /^\s*(\d+)\s+(.+)$/.exec(line);
35918
- if (!match)
35919
- continue;
35920
- const pid = Number(match[1]);
35921
- if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid)
35922
- continue;
35923
- if (commandLooksLikePi(match[2]))
35924
- pids.add(pid);
35925
- }
36155
+ rememberWindowsProcessFacts(snapshot.facts);
36156
+ return classifyLivePiSnapshot(snapshot);
35926
36157
  }
35927
- return { state: "known", processIds: [...pids].sort((left, right) => left - right) };
36158
+ return classifyLivePiSnapshot(readPosixProcessSnapshot());
35928
36159
  } catch (error51) {
35929
36160
  return {
35930
36161
  state: "unreadable",
@@ -35966,10 +36197,19 @@ function parseRpcPortFile(content, fallbackPid = 0) {
35966
36197
  function isValidPort(port) {
35967
36198
  return Number.isInteger(port) && port > 0 && port <= 65535;
35968
36199
  }
35969
- var RPC_IDENTITY_SKEW_TOLERANCE_MS = 120000, LINUX_CLOCK_TICKS_PER_SECOND = 100, PS_PROBE_TIMEOUT_MS = 1000, OPEN_CODE_COMMAND_MARKERS, TASKLIST_NO_TASKS_PATTERN, rpcIdentityReadFileSync, rpcIdentityExecFileSync, rpcIdentityProcessKill, rpcProcessListExecFileSync, rpcIdentityPlatform, rpcIdentityNowMs = () => Date.now();
36200
+ var RPC_IDENTITY_SKEW_TOLERANCE_MS = 120000, LINUX_CLOCK_TICKS_PER_SECOND = 100, PS_PROBE_TIMEOUT_MS = 1000, WINDOWS_CIM_PROBE_TIMEOUT_MS = 5000, MAX_ANCESTOR_WALK_DEPTH = 16, OPEN_CODE_COMMAND_MARKERS, TASKLIST_NO_TASKS_PATTERN, WINDOWS_CIM_COMMAND = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine,CreationDate | ConvertTo-Json -Compress", PI_HARNESS_ARC_MARKERS, PI_IMAGE_NAMES, rpcIdentityReadFileSync, rpcIdentityExecFileSync, rpcIdentityProcessKill, rpcProcessListExecFileSync, rpcIdentityPlatform, rpcIdentityNowMs = () => Date.now(), windowsProcessFactsCache = null;
35970
36201
  var init_rpc_utils = __esm(() => {
36202
+ init_logger();
35971
36203
  OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
35972
36204
  TASKLIST_NO_TASKS_PATTERN = /^INFO:\s+No tasks are running which match the specified criteria\.?$/im;
36205
+ PI_HARNESS_ARC_MARKERS = [
36206
+ "pi-coding-agent",
36207
+ "oh-my-pi",
36208
+ "@oh-my-pi",
36209
+ "cljs/dist",
36210
+ "dist/bundle/cli"
36211
+ ];
36212
+ PI_IMAGE_NAMES = new Set(["pi", "pi.cmd", "omp", "oh-my-pi"]);
35973
36213
  rpcIdentityReadFileSync = readFileSync12;
35974
36214
  rpcIdentityExecFileSync = execFileSync4;
35975
36215
  rpcIdentityProcessKill = process.kill;
@@ -36089,8 +36329,8 @@ function formatFailClosedBlockingMessage(reason) {
36089
36329
  ].join(" ");
36090
36330
  }
36091
36331
  return [
36092
- `Magic Context cannot migrate the shared database because ${formatFailClosedBlockingProcesses(reason.blockingProcesses)} may be running an older Magic Context build that would fail against the migrated database.`,
36093
- "Restart the blocking process (it will pick up the new build and migrate on start), or shut it down and retry.",
36332
+ `Magic Context cannot migrate the shared database (one database serves every project on this machine) because ${formatFailClosedBlockingProcesses(reason.blockingProcesses)} may be running an older Magic Context build that would fail against the migrated database.`,
36333
+ "Restart the blocking process — even one from a different project — and it will pick up the new build and migrate on start; or shut it down and retry.",
36094
36334
  `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
36095
36335
  ].join(" ");
36096
36336
  }
@@ -36113,6 +36353,16 @@ var init_fail_closed_block = __esm(() => {
36113
36353
  OPENCODE_INTERNAL_AGENT_NAMES = new Set(["title", "summary", "compaction"]);
36114
36354
  });
36115
36355
 
36356
+ // ../plugin/src/features/magic-context/message-fts-rowid-map.ts
36357
+ import { createHash as createHash3 } from "node:crypto";
36358
+ var EMPTY_INDEX_CONTENT_HASH, upsertMapStatements, rangeReadyStatements, activeBackfills;
36359
+ var init_message_fts_rowid_map = __esm(() => {
36360
+ EMPTY_INDEX_CONTENT_HASH = createHash3("sha256").update("").digest("hex");
36361
+ upsertMapStatements = new WeakMap;
36362
+ rangeReadyStatements = new WeakMap;
36363
+ activeBackfills = new WeakMap;
36364
+ });
36365
+
36116
36366
  // ../plugin/src/hooks/magic-context/compartment-parser.ts
36117
36367
  function makeTierOpenRegex(n2) {
36118
36368
  return new RegExp(`<p${n2}\\s*(/?)>`);
@@ -36351,6 +36601,7 @@ function healAllNullColumns(db) {
36351
36601
  ["stale_reduce_stripped_ids", ""],
36352
36602
  ["processed_image_stripped_ids", ""],
36353
36603
  ["merged_reasoning_stripped_ids", ""],
36604
+ ["thinking_binding_recovery_target", ""],
36354
36605
  ["trailing_blank_decisions", ""],
36355
36606
  ["memory_block_cache", ""],
36356
36607
  ["memory_block_ids", ""],
@@ -38730,6 +38981,30 @@ var init_migrations = __esm(() => {
38730
38981
  return;
38731
38982
  ensureColumn(db, "memory_verifications", "mapping_origin", "TEXT NOT NULL DEFAULT 'mapper'");
38732
38983
  }
38984
+ },
38985
+ {
38986
+ version: 83,
38987
+ description: "add indexed rowid access for message FTS content",
38988
+ up(db) {
38989
+ db.exec(`
38990
+ CREATE TABLE IF NOT EXISTS message_fts_rowid_map (
38991
+ session_id TEXT NOT NULL,
38992
+ message_ordinal INTEGER NOT NULL,
38993
+ fts_rowid INTEGER NOT NULL,
38994
+ PRIMARY KEY(session_id, message_ordinal)
38995
+ );
38996
+
38997
+ CREATE TABLE IF NOT EXISTS message_fts_rowid_map_backfill_state (
38998
+ id INTEGER PRIMARY KEY CHECK(id = 1),
38999
+ watermark_rowid INTEGER NOT NULL DEFAULT 0,
39000
+ completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0, 1)),
39001
+ updated_at INTEGER NOT NULL DEFAULT 0
39002
+ );
39003
+ INSERT OR IGNORE INTO message_fts_rowid_map_backfill_state
39004
+ (id, watermark_rowid, completed, updated_at)
39005
+ VALUES (1, 0, 0, 0);
39006
+ `);
39007
+ }
38733
39008
  }
38734
39009
  ];
38735
39010
  LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m3) => Math.max(max, m3.version), 0);
@@ -39492,6 +39767,23 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
39492
39767
  tokenize='porter unicode61'
39493
39768
  );
39494
39769
 
39770
+ CREATE TABLE IF NOT EXISTS message_fts_rowid_map (
39771
+ session_id TEXT NOT NULL,
39772
+ message_ordinal INTEGER NOT NULL,
39773
+ fts_rowid INTEGER NOT NULL,
39774
+ PRIMARY KEY(session_id, message_ordinal)
39775
+ );
39776
+
39777
+ CREATE TABLE IF NOT EXISTS message_fts_rowid_map_backfill_state (
39778
+ id INTEGER PRIMARY KEY CHECK(id = 1),
39779
+ watermark_rowid INTEGER NOT NULL DEFAULT 0,
39780
+ completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0, 1)),
39781
+ updated_at INTEGER NOT NULL DEFAULT 0
39782
+ );
39783
+ INSERT OR IGNORE INTO message_fts_rowid_map_backfill_state
39784
+ (id, watermark_rowid, completed, updated_at)
39785
+ VALUES (1, 0, 0, 0);
39786
+
39495
39787
  CREATE TABLE IF NOT EXISTS message_history_index (
39496
39788
  session_id TEXT PRIMARY KEY,
39497
39789
  last_indexed_ordinal INTEGER NOT NULL DEFAULT 0,
@@ -39635,8 +39927,9 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
39635
39927
  cached_m0_system_hash TEXT,
39636
39928
  cached_m0_tool_set_hash TEXT,
39637
39929
  cached_m0_model_key TEXT,
39638
- cached_m0_project_identity TEXT,
39639
- cached_m0_last_baseline_end_message_id TEXT,
39930
+ cached_m0_project_identity TEXT,
39931
+ cached_m0_last_baseline_end_message_id TEXT,
39932
+ thinking_binding_recovery_target TEXT NOT NULL DEFAULT '',
39640
39933
  upgrade_reminded_at INTEGER,
39641
39934
  pi_stable_id_scheme INTEGER
39642
39935
  );
@@ -39858,6 +40151,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
39858
40151
  ensureColumn(db, "session_meta", "stale_reduce_stripped_ids", "TEXT DEFAULT ''");
39859
40152
  ensureColumn(db, "session_meta", "processed_image_stripped_ids", "TEXT DEFAULT ''");
39860
40153
  ensureColumn(db, "session_meta", "merged_reasoning_stripped_ids", "TEXT DEFAULT ''");
40154
+ ensureColumn(db, "session_meta", "thinking_binding_recovery_target", "TEXT DEFAULT ''");
39861
40155
  ensureColumn(db, "session_meta", "trailing_blank_decisions", "TEXT DEFAULT ''");
39862
40156
  ensureColumn(db, "compartments", "start_message_id", "TEXT DEFAULT ''");
39863
40157
  ensureColumn(db, "compartments", "end_message_id", "TEXT DEFAULT ''");
@@ -40091,12 +40385,13 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
40091
40385
  `);
40092
40386
  ensureColumn(db, "workspaces", "share_categories", `TEXT NOT NULL DEFAULT '["CONSTRAINTS"]'`);
40093
40387
  }
40094
- var databases, pendingAsyncOpens, persistenceByDatabase, persistenceErrorByDatabase, pathByDatabase, LATEST_SUPPORTED_VERSION = 82, PERMISSIONS_ENFORCEABLE, RPC_DISCOVERY_PARSE_GRACE_MS, defaultRpcDiscoveryFs, rpcDiscoveryFs, sqlitePragmaConfig, CHANNEL2_CLAIM_TTL_MS;
40388
+ var databases, pendingAsyncOpens, persistenceByDatabase, persistenceErrorByDatabase, pathByDatabase, LATEST_SUPPORTED_VERSION = 83, PERMISSIONS_ENFORCEABLE, RPC_DISCOVERY_PARSE_GRACE_MS, defaultRpcDiscoveryFs, rpcDiscoveryFs, sqlitePragmaConfig, CHANNEL2_CLAIM_TTL_MS;
40095
40389
  var init_storage_db = __esm(async () => {
40096
40390
  init_data_path();
40097
40391
  init_logger();
40098
40392
  init_rpc_utils();
40099
40393
  init_fail_closed_block();
40394
+ init_message_fts_rowid_map();
40100
40395
  init_migrations();
40101
40396
  init_tool_definition_tokens();
40102
40397
  init_tool_owner_backfill();
@@ -40777,11 +41072,11 @@ function defaultInspectHolders(storageDir) {
40777
41072
  }
40778
41073
  const blockers = rpc.state === "live" ? rpc.serverPids.map((pid) => `OpenCode server (PID ${pid})`) : [];
40779
41074
  const pi = inspectLivePiProcesses();
40780
- if (pi.state === "unreadable") {
41075
+ if (pi.state === "unreadable" || pi.state === "inconclusive") {
40781
41076
  return {
40782
41077
  safe: false,
40783
41078
  blockers,
40784
- uncertainty: `Pi/OMP process liveness could not be determined: ${pi.error ?? "process list unavailable"}`
41079
+ uncertainty: pi.state === "inconclusive" ? `Pi/OMP process image or command line was ambiguous (PID ${(pi.inconclusivePids ?? []).join(", ")})` : `Pi/OMP process liveness could not be determined: ${pi.error ?? "process list unavailable"}`
40785
41080
  };
40786
41081
  }
40787
41082
  blockers.push(...pi.processIds.map((pid) => `Pi/OMP harness (PID ${pid})`));
@@ -41283,7 +41578,7 @@ __export(exports_migrate, {
41283
41578
  runMigrateCli: () => runMigrateCli,
41284
41579
  sweepPendingMigrations: () => sweepPendingMigrations
41285
41580
  });
41286
- import { createHash as createHash3, randomBytes as randomBytes2 } from "node:crypto";
41581
+ import { createHash as createHash4, randomBytes as randomBytes2 } from "node:crypto";
41287
41582
  import { existsSync as existsSync22, mkdirSync as mkdirSync8, renameSync as renameSync5, unlinkSync as unlinkSync4 } from "node:fs";
41288
41583
  import { dirname as dirname13, join as join19 } from "node:path";
41289
41584
  function defaultOpenCodeDbPath() {
@@ -41323,7 +41618,7 @@ function shortId() {
41323
41618
  return randomBytes2(4).toString("hex");
41324
41619
  }
41325
41620
  function migrationKeyFor(sourceSessionId, targetHarness) {
41326
- return createHash3("sha256").update(`${sourceSessionId}
41621
+ return createHash4("sha256").update(`${sourceSessionId}
41327
41622
  ${targetHarness}`).digest("hex");
41328
41623
  }
41329
41624
  function moduleManagedProjectForSession(db, sessionId) {
@@ -41969,7 +42264,7 @@ function migrateOpenCodeSessionToPi(opts) {
41969
42264
  `;
41970
42265
  if (!opts.dryRun) {
41971
42266
  if (journalActive && cortexkitDb !== null && migrationKey !== undefined && plan) {
41972
- const contentSha256 = createHash3("sha256").update(jsonl, "utf8").digest("hex");
42267
+ const contentSha256 = createHash4("sha256").update(jsonl, "utf8").digest("hex");
41973
42268
  commitStagedChecksum(cortexkitDb, migrationKey, contentSha256);
41974
42269
  fs3.writeFileAtomic(stagePath, jsonl);
41975
42270
  plan.commit(migrationKey);
@@ -42695,7 +42990,7 @@ var init_migrate_session = __esm(async () => {
42695
42990
  });
42696
42991
 
42697
42992
  // ../plugin/src/features/magic-context/v22-deferred-backfill.ts
42698
- import { createHash as createHash4 } from "node:crypto";
42993
+ import { createHash as createHash5 } from "node:crypto";
42699
42994
  import { realpathSync as realpathSync5 } from "node:fs";
42700
42995
  import path5 from "node:path";
42701
42996
  function readMeta(db, key) {
@@ -42744,7 +43039,7 @@ function computeLegacyRustDirIdentity(rawProjectPath) {
42744
43039
  } catch {
42745
43040
  canonical = path5.isAbsolute(rawProjectPath) ? rawProjectPath : path5.join(process.cwd(), rawProjectPath);
42746
43041
  }
42747
- return `dir:${createHash4("sha256").update(canonical, "utf8").digest("hex")}`;
43042
+ return `dir:${createHash5("sha256").update(canonical, "utf8").digest("hex")}`;
42748
43043
  }
42749
43044
  function upsertRekeyMap(db, oldProjectPath, newProjectPath, rekeyedAt) {
42750
43045
  db.prepare(`INSERT INTO v22_identity_rekey_map (old_project_path, new_project_path, rekeyed_at)
@@ -44475,7 +44770,6 @@ var init_diagnostics_opencode = __esm(() => {
44475
44770
  init_redaction2();
44476
44771
  import_comment_json10 = __toESM(require_src3(), 1);
44477
44772
  });
44478
-
44479
44773
  // ../plugin/src/features/magic-context/memory/embedding-synapse.ts
44480
44774
  var SYNAPSE_CERTIFICATION_REFUSAL_REASONS, factoryClients;
44481
44775
  var init_embedding_synapse = __esm(() => {
@@ -44502,11 +44796,13 @@ var init_embedding_identity = __esm(() => {
44502
44796
  // ../plugin/src/features/magic-context/memory/embedding-local.ts
44503
44797
  function currentLocalEmbeddingHost() {
44504
44798
  const bun = globalThis.Bun;
44505
- const bunVersion = typeof process !== "undefined" && typeof process.versions?.bun === "string" ? process.versions.bun : undefined;
44799
+ const hasProcess = typeof process !== "undefined";
44800
+ const bunVersion = hasProcess && typeof process.versions?.bun === "string" ? process.versions.bun : undefined;
44506
44801
  return {
44507
- isElectron: typeof process !== "undefined" && Boolean(process.versions?.electron),
44802
+ isElectron: hasProcess && Boolean(process.versions?.electron),
44508
44803
  isBun: Boolean(bun) || Boolean(bunVersion),
44509
- bunVersion
44804
+ bunVersion,
44805
+ hasNodeFilesystem: hasProcess && (typeof process.versions?.node === "string" || typeof bunVersion === "string")
44510
44806
  };
44511
44807
  }
44512
44808
  function bunHasNapiTeardownFix(version2) {
@@ -44538,7 +44834,7 @@ var init_embedding_local = __esm(() => {
44538
44834
 
44539
44835
  // src/lib/embedding-runtime.ts
44540
44836
  import { spawnSync as spawnSync6 } from "node:child_process";
44541
- import { existsSync as existsSync28 } from "node:fs";
44837
+ import { existsSync as existsSync28, readFileSync as readFileSync18 } from "node:fs";
44542
44838
  import { createRequire as createRequire4 } from "node:module";
44543
44839
  import { dirname as dirname16, join as join24, sep } from "node:path";
44544
44840
  function describeError(error51) {
@@ -44641,7 +44937,13 @@ function isNativeLocalEmbeddingRuntimeFailure(status) {
44641
44937
  return status.state === "package-missing" || status.state === "binary-missing" || status.state === "load-failed";
44642
44938
  }
44643
44939
  function describeNativeFailure(status) {
44644
- return status.state === "package-missing" ? "package is not installed" : status.state === "binary-missing" ? "expected platform binding file is absent" : `binding failed to load: ${status.reason}`;
44940
+ return status.state === "package-missing" ? "package is not installed" : status.state === "binary-missing" ? status.knownUnavailable ? `onnxruntime-node ${status.knownUnavailable.packageVersion} does not ship a darwin/x64 native binding` : "expected platform binding file is absent" : `binding failed to load: ${status.reason}`;
44941
+ }
44942
+ function knownUnavailableNativeBinding(status) {
44943
+ return status.state === "binary-missing" ? status.knownUnavailable : undefined;
44944
+ }
44945
+ function intelMacNativeGuidance(version2) {
44946
+ return `onnxruntime-node ${version2} has no native binding for darwin/x64; reinstalling the same package ` + "(including doctor --force) cannot restore native inference. The supported fallback is WASM. " + "For optional native speed, manually pin onnxruntime-node@1.23.0.";
44645
44947
  }
44646
44948
  function isLocalEmbeddingRuntimeBroken(status) {
44647
44949
  return status.state === "both-broken" || status.state === "wasm-broken" || isNativeLocalEmbeddingRuntimeFailure(status);
@@ -44651,12 +44953,24 @@ function formatLocalEmbeddingRuntimeDoctorWarning(status) {
44651
44953
  return "Embedding provider: local — configured/selected onnxruntime-web (WASM) is unavailable — " + `${status.wasmReason}. Reinstall the plugin package or select embedding.local_runtime: native ` + "only on a host where its native runtime is safe.";
44652
44954
  }
44653
44955
  if (status.state !== "both-broken") {
44956
+ const knownUnavailable2 = knownUnavailableNativeBinding(status);
44957
+ if (knownUnavailable2) {
44958
+ return `Embedding provider: local — ${intelMacNativeGuidance(knownUnavailable2.packageVersion)} WASM fallback is unavailable, so embeddings will not work.`;
44959
+ }
44654
44960
  return "Embedding provider: local — onnxruntime-node native binding missing — " + `${describeNativeFailure(status)}; its postinstall likely failed. Embeddings will not work. ` + "Reinstall with network access to the npm registry and GitHub releases, " + "or switch `embedding.provider` to an HTTP endpoint (`openai-compatible`).";
44655
44961
  }
44962
+ const knownUnavailable = knownUnavailableNativeBinding(status.nativeFailure);
44963
+ if (knownUnavailable) {
44964
+ return `Embedding provider: local — ${intelMacNativeGuidance(knownUnavailable.packageVersion)} ` + `The WASM fallback is also unavailable: ${status.wasmReason}. Reinstall may repair the WASM package only; ` + "otherwise switch `embedding.provider` to an HTTP endpoint (`openai-compatible`).";
44965
+ }
44656
44966
  return "Embedding provider: local — native runtime and WASM fallback both unavailable — " + `native: ${describeNativeFailure(status.nativeFailure)}; WASM: ${status.wasmReason}; ` + "their install or postinstall likely failed. Reinstall with network access to the npm registry and GitHub releases, " + "or switch `embedding.provider` to an HTTP endpoint (`openai-compatible`).";
44657
44967
  }
44658
44968
  function formatLocalEmbeddingRuntimeWasmFallback(status) {
44659
- return "Embedding provider: local — onnxruntime-node native binding failed " + `(${describeNativeFailure(status.nativeFailure)}); using onnxruntime-web (WASM) at ${status.wasmPath}. ` + "WASM inference is slower than native; a remote `openai-compatible` provider may be faster.";
44969
+ const knownUnavailable = knownUnavailableNativeBinding(status.nativeFailure);
44970
+ if (knownUnavailable) {
44971
+ return "Embedding provider: local — " + `onnxruntime-node ${knownUnavailable.packageVersion} has no native binding for darwin/x64; ` + `WASM fallback active at ${status.wasmPath}. Reinstalling the same package (including doctor --force) ` + "cannot restore native inference. WASM is slower; for optional native speed, manually pin onnxruntime-node@1.23.0.";
44972
+ }
44973
+ return "Embedding provider: local — onnxruntime-node native binding failed " + `(${describeNativeFailure(status.nativeFailure)}); WASM fallback active at ${status.wasmPath}. ` + "WASM inference is slower than native; a remote `openai-compatible` provider may be faster.";
44660
44974
  }
44661
44975
  function expectedBinaryRelPath(platform, arch) {
44662
44976
  const supportedPlatform = platform === "linux" || platform === "darwin" || platform === "win32";
@@ -44665,6 +44979,27 @@ function expectedBinaryRelPath(platform, arch) {
44665
44979
  return null;
44666
44980
  return join24("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
44667
44981
  }
44982
+ function onnxRuntimeNodeVersion(packageDir) {
44983
+ try {
44984
+ const parsed = JSON.parse(readFileSync18(join24(packageDir, "package.json"), "utf8"));
44985
+ return typeof parsed.version === "string" ? parsed.version : undefined;
44986
+ } catch {
44987
+ return;
44988
+ }
44989
+ }
44990
+ function darwinX64BindingDropped(packageDir, platform, arch) {
44991
+ if (platform !== "darwin" || arch !== "x64")
44992
+ return;
44993
+ const packageVersion = onnxRuntimeNodeVersion(packageDir);
44994
+ const match = packageVersion?.match(/^(\d+)\.(\d+)(?:\.|$)/);
44995
+ if (!match)
44996
+ return;
44997
+ const major = Number(match[1]);
44998
+ const minor = Number(match[2]);
44999
+ if (major < 1 || major === 1 && minor < 24)
45000
+ return;
45001
+ return { kind: "darwin-x64-dropped", packageVersion };
45002
+ }
44668
45003
  function probeWasmRuntimeFromRequire(requireFn) {
44669
45004
  try {
44670
45005
  const resolved = requireFn.resolve("onnxruntime-web");
@@ -44692,9 +45027,25 @@ function withWasmFallback(native, probeWasm) {
44692
45027
  function formatLocalEmbeddingRuntimeWasmSelected(status) {
44693
45028
  return "Embedding provider: local — onnxruntime-web (WASM) selected by embedding.local_runtime/host at " + `${status.wasmPath}. The native addon was not probed or loaded. WASM inference is slower than native.`;
44694
45029
  }
45030
+ function requireNodeWasmBundle(probe, candidates) {
45031
+ if (probe.state === "failed")
45032
+ return probe;
45033
+ const bundlePath = candidates.find((candidate) => existsSync28(candidate));
45034
+ return bundlePath ? probe : {
45035
+ state: "failed",
45036
+ reason: `functional Node WASM Transformers bundle is missing (checked ${candidates.join(", ")})`
45037
+ };
45038
+ }
45039
+ function nodeWasmBundleCandidates(installRoot) {
45040
+ return [
45041
+ join24(installRoot, "dist", "transformers-node-wasm.js"),
45042
+ join24(installRoot, "node_modules", "@cortexkit", "opencode-magic-context", "dist", "transformers-node-wasm.js"),
45043
+ join24(installRoot, "node_modules", "@cortexkit", "pi-magic-context", "dist", "transformers-node-wasm.js")
45044
+ ];
45045
+ }
44695
45046
  function probeWasmRuntimeAt(installRoot) {
44696
45047
  const requireFn = createRequire4(join24(installRoot, "package.json"));
44697
- return probeWasmRuntimeFromRequire(requireFn);
45048
+ return requireNodeWasmBundle(probeWasmRuntimeFromRequire(requireFn), nodeWasmBundleCandidates(installRoot));
44698
45049
  }
44699
45050
  function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
44700
45051
  const selectedRuntime = resolveLocalEmbeddingRuntime(runtimePreference, host);
@@ -44715,7 +45066,12 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
44715
45066
  };
44716
45067
  } else {
44717
45068
  const binaryPath = join24(packageDir, rel);
44718
- native = existsSync28(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : { state: "binary-missing", packageDir, expectedBinary: binaryPath };
45069
+ native = existsSync28(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
45070
+ state: "binary-missing",
45071
+ packageDir,
45072
+ expectedBinary: binaryPath,
45073
+ knownUnavailable: darwinX64BindingDropped(packageDir, platform, arch)
45074
+ };
44719
45075
  }
44720
45076
  }
44721
45077
  return withWasmFallback(native, () => probeWasmRuntimeAt(installRoot));
@@ -44753,12 +45109,13 @@ function probeWasmRuntimeByResolution(pluginDir) {
44753
45109
  try {
44754
45110
  const reqPlugin = createRequire4(join24(pluginDir, "package.json"));
44755
45111
  const direct = probeWasmRuntimeFromRequire(reqPlugin);
44756
- if (direct.state === "ok" || !direct.reason.startsWith("onnxruntime-web is not resolvable")) {
44757
- return direct;
45112
+ let probe = direct;
45113
+ if (direct.state === "failed" && direct.reason.startsWith("onnxruntime-web is not resolvable")) {
45114
+ const tfResolved = reqPlugin.resolve("@huggingface/transformers");
45115
+ const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
45116
+ probe = probeWasmRuntimeFromRequire(createRequire4(join24(tfDir, "package.json")));
44758
45117
  }
44759
- const tfResolved = reqPlugin.resolve("@huggingface/transformers");
44760
- const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
44761
- return probeWasmRuntimeFromRequire(createRequire4(join24(tfDir, "package.json")));
45118
+ return requireNodeWasmBundle(probe, [join24(pluginDir, "dist", "transformers-node-wasm.js")]);
44762
45119
  } catch (error51) {
44763
45120
  return {
44764
45121
  state: "failed",
@@ -44809,7 +45166,12 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
44809
45166
  native = probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath: onnxDir };
44810
45167
  } else {
44811
45168
  const binaryPath = join24(onnxDir, rel);
44812
- native = existsSync28(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : { state: "binary-missing", packageDir: onnxDir, expectedBinary: binaryPath };
45169
+ native = existsSync28(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
45170
+ state: "binary-missing",
45171
+ packageDir: onnxDir,
45172
+ expectedBinary: binaryPath,
45173
+ knownUnavailable: darwinX64BindingDropped(onnxDir, platform, arch)
45174
+ };
44813
45175
  }
44814
45176
  return withWasmFallback(native, () => probeWasmRuntimeByResolution(pluginDir));
44815
45177
  }
@@ -44938,7 +45300,7 @@ var init_issue_body = __esm(() => {
44938
45300
  });
44939
45301
 
44940
45302
  // src/lib/logs-opencode.ts
44941
- import { readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "node:fs";
45303
+ import { readFileSync as readFileSync19, writeFileSync as writeFileSync8 } from "node:fs";
44942
45304
  import { join as join25 } from "node:path";
44943
45305
  function sanitizeLogContent(content) {
44944
45306
  return sanitizeDiagnosticText(content);
@@ -44981,7 +45343,7 @@ function filterLogLinesBySession(lines, sessionId) {
44981
45343
  }
44982
45344
  async function bundleIssueReport(report, description, title, sessionFilter = null) {
44983
45345
  const LOG_TAIL_LINES = 400;
44984
- const allLogLines = report.logFile.exists ? readFileSync18(report.logFile.path, "utf-8").split(/\r?\n/) : [];
45346
+ const allLogLines = report.logFile.exists ? readFileSync19(report.logFile.path, "utf-8").split(/\r?\n/) : [];
44985
45347
  const logLines = filterLogLinesBySession(allLogLines, sessionFilter);
44986
45348
  const recentLog = sanitizeLogContent(logLines.slice(-LOG_TAIL_LINES).join(`
44987
45349
  `)).trim();
@@ -45353,7 +45715,7 @@ import {
45353
45715
  accessSync as accessSync2,
45354
45716
  existsSync as existsSync29,
45355
45717
  constants as fsConstants,
45356
- readFileSync as readFileSync19,
45718
+ readFileSync as readFileSync20,
45357
45719
  renameSync as renameSync7,
45358
45720
  statSync as statSync13,
45359
45721
  writeFileSync as writeFileSync9
@@ -45407,7 +45769,7 @@ function getWinningConfig(directory, surface) {
45407
45769
  try {
45408
45770
  if (!existsSync29(path6))
45409
45771
  continue;
45410
- const parsed = parseJsonConfig(readFileSync19(path6, "utf-8"));
45772
+ const parsed = parseJsonConfig(readFileSync20(path6, "utf-8"));
45411
45773
  const entries = getPluginEntries(parsed);
45412
45774
  if (entries.some((entry) => entry === PACKAGE_NAME || entry.startsWith(`${PACKAGE_NAME}@`))) {
45413
45775
  if (winner) {
@@ -45443,14 +45805,14 @@ var init_checker = __esm(() => {
45443
45805
  });
45444
45806
 
45445
45807
  // src/lib/opencode-plugin-schema-fence.ts
45446
- import { existsSync as existsSync30, readdirSync as readdirSync4, readFileSync as readFileSync20 } from "node:fs";
45808
+ import { existsSync as existsSync30, readdirSync as readdirSync4, readFileSync as readFileSync21 } from "node:fs";
45447
45809
  import { join as join28 } from "node:path";
45448
45810
  import { gunzipSync } from "node:zlib";
45449
45811
  function readPackageVersion(packageJsonPath) {
45450
45812
  try {
45451
45813
  if (!existsSync30(packageJsonPath))
45452
45814
  return null;
45453
- const packageJson = JSON.parse(readFileSync20(packageJsonPath, "utf-8"));
45815
+ const packageJson = JSON.parse(readFileSync21(packageJsonPath, "utf-8"));
45454
45816
  if (packageJson.name !== OPENCODE_PLUGIN_NAME || typeof packageJson.version !== "string") {
45455
45817
  return null;
45456
45818
  }
@@ -45487,7 +45849,7 @@ function readFenceFromDist(packageDirectory) {
45487
45849
  }
45488
45850
  if (!entry.isFile() || !/\.(?:[cm]?js|ts)$/.test(entry.name))
45489
45851
  continue;
45490
- const fence = readFenceValue(readFileSync20(path6, "utf-8"));
45852
+ const fence = readFenceValue(readFileSync21(path6, "utf-8"));
45491
45853
  if (fence !== null)
45492
45854
  fenceValues.add(fence);
45493
45855
  }
@@ -45705,13 +46067,13 @@ var init_storage_versions = __esm(async () => {
45705
46067
  });
45706
46068
 
45707
46069
  // src/commands/doctor-opencode-cache.ts
45708
- import { existsSync as existsSync31, readFileSync as readFileSync21, rmSync as rmSync3 } from "node:fs";
46070
+ import { existsSync as existsSync31, readFileSync as readFileSync22, rmSync as rmSync3 } from "node:fs";
45709
46071
  function readCachedPluginVersion(pluginCacheDir) {
45710
46072
  try {
45711
46073
  const installedPkgPath = getOpenCodePluginPackageJsonPath(pluginCacheDir);
45712
46074
  if (!existsSync31(installedPkgPath))
45713
46075
  return;
45714
- const pkg = JSON.parse(readFileSync21(installedPkgPath, "utf-8"));
46076
+ const pkg = JSON.parse(readFileSync22(installedPkgPath, "utf-8"));
45715
46077
  return typeof pkg.version === "string" ? pkg.version : undefined;
45716
46078
  } catch {
45717
46079
  return;
@@ -45788,7 +46150,7 @@ var init_doctor_opencode_cache = __esm(() => {
45788
46150
 
45789
46151
  // src/commands/doctor-opencode.ts
45790
46152
  import { spawnSync as spawnSync7 } from "node:child_process";
45791
- import { existsSync as existsSync32, readFileSync as readFileSync22, statSync as statSync14 } from "node:fs";
46153
+ import { existsSync as existsSync32, readFileSync as readFileSync23, statSync as statSync14 } from "node:fs";
45792
46154
  import { createRequire as createRequire5 } from "node:module";
45793
46155
  import { homedir as homedir17 } from "node:os";
45794
46156
  import { join as join29 } from "node:path";
@@ -45898,7 +46260,7 @@ function collectNpmReleaseAgeWarnings() {
45898
46260
  if (!existsSync32(npmrcPath))
45899
46261
  return ageWarnings;
45900
46262
  try {
45901
- const npmrc = readFileSync22(npmrcPath, "utf-8");
46263
+ const npmrc = readFileSync23(npmrcPath, "utf-8");
45902
46264
  for (const line of npmrc.split(`
45903
46265
  `)) {
45904
46266
  const trimmed = line.trim();
@@ -46399,7 +46761,7 @@ async function runDoctor2(options = {}) {
46399
46761
  }
46400
46762
  if (paths.opencodeConfigFormat !== "none") {
46401
46763
  try {
46402
- const raw = readFileSync22(paths.opencodeConfig, "utf-8");
46764
+ const raw = readFileSync23(paths.opencodeConfig, "utf-8");
46403
46765
  const config2 = import_comment_json12.parse(raw);
46404
46766
  const rawPlugins = Array.isArray(config2?.plugin) ? config2.plugin : [];
46405
46767
  const existingIdx = rawPlugins.findIndex((entry) => matchesPluginEntry(entry, OPENCODE_PLUGIN_NAME) || isDevPathPluginEntry(entry));
@@ -46486,7 +46848,7 @@ async function runDoctor2(options = {}) {
46486
46848
  fixed++;
46487
46849
  } else if (existsSync32(paths.tuiConfig)) {
46488
46850
  try {
46489
- const tuiRaw = readFileSync22(paths.tuiConfig, "utf-8");
46851
+ const tuiRaw = readFileSync23(paths.tuiConfig, "utf-8");
46490
46852
  const tuiConfig = import_comment_json12.parse(tuiRaw);
46491
46853
  const tuiRawPlugins = Array.isArray(tuiConfig?.plugin) ? tuiConfig.plugin : [];
46492
46854
  const tuiIdx = tuiRawPlugins.findIndex((entry) => matchesPluginEntry(entry, OPENCODE_PLUGIN_NAME) || isDevPathPluginEntry(entry));
@@ -46764,7 +47126,7 @@ var init_doctor_opencode = __esm(async () => {
46764
47126
  });
46765
47127
 
46766
47128
  // src/lib/diagnostics-pi.ts
46767
- import { existsSync as existsSync33, readdirSync as readdirSync5, readFileSync as readFileSync23, statSync as statSync15 } from "node:fs";
47129
+ import { existsSync as existsSync33, readdirSync as readdirSync5, readFileSync as readFileSync24, statSync as statSync15 } from "node:fs";
46768
47130
  import { createRequire as createRequire6 } from "node:module";
46769
47131
  import { join as join30 } from "node:path";
46770
47132
  function getSelfVersion3() {
@@ -46797,7 +47159,7 @@ function readJsonc(path6) {
46797
47159
  return { value: {} };
46798
47160
  try {
46799
47161
  return {
46800
- value: import_comment_json13.parse(readFileSync23(path6, "utf-8"))
47162
+ value: import_comment_json13.parse(readFileSync24(path6, "utf-8"))
46801
47163
  };
46802
47164
  } catch (error51) {
46803
47165
  return {
@@ -46867,7 +47229,7 @@ function collectPiRecentSessions() {
46867
47229
  }
46868
47230
  function parseHistorianDumpMeta2(path6) {
46869
47231
  try {
46870
- const xml = readFileSync23(path6, "utf-8");
47232
+ const xml = readFileSync24(path6, "utf-8");
46871
47233
  const parsed = parseCompartmentOutput(xml);
46872
47234
  const factCountByCategory = {};
46873
47235
  for (const fact of parsed.facts) {
@@ -47115,7 +47477,7 @@ var init_diagnostics_pi = __esm(() => {
47115
47477
  });
47116
47478
 
47117
47479
  // src/lib/logs-pi.ts
47118
- import { readFileSync as readFileSync24, writeFileSync as writeFileSync10 } from "node:fs";
47480
+ import { readFileSync as readFileSync25, writeFileSync as writeFileSync10 } from "node:fs";
47119
47481
  import { join as join31 } from "node:path";
47120
47482
  function sanitizeLogContent2(content) {
47121
47483
  return sanitizeString2(content);
@@ -47145,7 +47507,7 @@ function filterLogLinesBySession2(lines, sessionId) {
47145
47507
  }
47146
47508
  async function bundleIssueReport2(report, description, title, options = {}) {
47147
47509
  const LOG_TAIL_LINES = 400;
47148
- const allLogLines = report.logFile.exists ? readFileSync24(report.logFile.path, "utf-8").split(/\r?\n/) : [];
47510
+ const allLogLines = report.logFile.exists ? readFileSync25(report.logFile.path, "utf-8").split(/\r?\n/) : [];
47149
47511
  const logLines = filterLogLinesBySession2(allLogLines, options.sessionFilter ?? null);
47150
47512
  const recentLog = sanitizeLogContent2(logLines.slice(-LOG_TAIL_LINES).join(`
47151
47513
  `)).trim();
@@ -47199,7 +47561,7 @@ var init_logs_pi = __esm(() => {
47199
47561
 
47200
47562
  // src/commands/doctor-pi.ts
47201
47563
  import { execFileSync as execFileSync6, spawnSync as spawnSync8 } from "node:child_process";
47202
- import { existsSync as existsSync34, mkdirSync as mkdirSync11, readdirSync as readdirSync6, readFileSync as readFileSync25, rmSync as rmSync4, statSync as statSync16 } from "node:fs";
47564
+ import { existsSync as existsSync34, mkdirSync as mkdirSync11, readdirSync as readdirSync6, readFileSync as readFileSync26, rmSync as rmSync4, statSync as statSync16 } from "node:fs";
47203
47565
  import { createRequire as createRequire7 } from "node:module";
47204
47566
  import { homedir as homedir18 } from "node:os";
47205
47567
  import { dirname as dirname18, isAbsolute as isAbsolute6, join as join32 } from "node:path";
@@ -47292,7 +47654,7 @@ function summarize(results) {
47292
47654
  function readJsonc2(path6) {
47293
47655
  try {
47294
47656
  return {
47295
- value: import_comment_json14.parse(readFileSync25(path6, "utf-8"))
47657
+ value: import_comment_json14.parse(readFileSync26(path6, "utf-8"))
47296
47658
  };
47297
47659
  } catch (error51) {
47298
47660
  return {
@@ -47449,7 +47811,7 @@ function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
47449
47811
  const packageJson = join32(path6, "package.json");
47450
47812
  if (existsSync34(packageJson)) {
47451
47813
  try {
47452
- const pkg = JSON.parse(readFileSync25(packageJson, "utf-8"));
47814
+ const pkg = JSON.parse(readFileSync26(packageJson, "utf-8"));
47453
47815
  const name = typeof pkg.name === "string" ? pkg.name : "";
47454
47816
  const version2 = typeof pkg.version === "string" ? pkg.version : undefined;
47455
47817
  if (name === PACKAGE_NAME2) {
@@ -47730,7 +48092,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
47730
48092
  if (existsSync34(logPath)) {
47731
48093
  const stat = statSync16(logPath);
47732
48094
  const sizeKb = (stat.size / 1024).toFixed(0);
47733
- const lines = readFileSync25(logPath, "utf-8").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
48095
+ const lines = readFileSync26(logPath, "utf-8").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
47734
48096
  add2(results, "info", `Log file: ${logPath} (${sizeKb} KB)`);
47735
48097
  const lastLine = lines.at(-1);
47736
48098
  add2(results, "info", `Last plugin log line: ${lastLine ? sanitizeDiagnosticText(lastLine) : "<empty log>"}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/magic-context",
3
- "version": "0.41.1",
3
+ "version": "0.41.2",
4
4
  "description": "Unified CLI for Magic Context — setup, doctor, and migration across OpenCode, Pi, and OMP",
5
5
  "keywords": [
6
6
  "opencode",