@cortexkit/magic-context 0.41.0 → 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 +697 -141
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -14708,6 +14708,73 @@ function recordSwallowedWrite(error) {
14708
14708
  function ensureDir4(filePath) {
14709
14709
  fs.mkdirSync(path2.dirname(filePath), { recursive: true });
14710
14710
  }
14711
+ function isMissingFile(error) {
14712
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
14713
+ }
14714
+ function getCurrentLogSize(logFile) {
14715
+ if (activeLogFile === logFile && activeLogSize !== null && flushesSinceSizeCheck < SIZE_CHECK_INTERVAL_FLUSHES) {
14716
+ return activeLogSize;
14717
+ }
14718
+ try {
14719
+ const stat = fs.statSync(logFile);
14720
+ if (!stat.isFile()) {
14721
+ throw new Error(`Magic Context log path is not a regular file: ${logFile}`);
14722
+ }
14723
+ fs.chmodSync(logFile, 384);
14724
+ activeLogFile = logFile;
14725
+ activeLogSize = stat.size;
14726
+ flushesSinceSizeCheck = 0;
14727
+ return stat.size;
14728
+ } catch (error) {
14729
+ if (!isMissingFile(error))
14730
+ throw error;
14731
+ activeLogFile = logFile;
14732
+ activeLogSize = 0;
14733
+ flushesSinceSizeCheck = 0;
14734
+ return 0;
14735
+ }
14736
+ }
14737
+ function capLogData(data) {
14738
+ if (Buffer.byteLength(data) <= MAX_LOG_FILE_BYTES)
14739
+ return data;
14740
+ let bounded = Buffer.from(data).subarray(0, MAX_LOG_FILE_BYTES).toString("utf8");
14741
+ while (Buffer.byteLength(bounded) > MAX_LOG_FILE_BYTES) {
14742
+ bounded = bounded.slice(0, -1);
14743
+ }
14744
+ return bounded;
14745
+ }
14746
+ function writeBoundedPredecessor(logFile, predecessorPath, size) {
14747
+ const predecessorFd = fs.openSync(predecessorPath, "w", 384);
14748
+ try {
14749
+ fs.fchmodSync(predecessorFd, 384);
14750
+ const bytesToCopy = Math.min(size, MAX_LOG_FILE_BYTES);
14751
+ const sourceFd = fs.openSync(logFile, "r");
14752
+ try {
14753
+ const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, bytesToCopy));
14754
+ let remaining = bytesToCopy;
14755
+ let position = Math.max(0, size - bytesToCopy);
14756
+ while (remaining > 0) {
14757
+ const bytesRead = fs.readSync(sourceFd, chunk, 0, Math.min(chunk.length, remaining), position);
14758
+ if (bytesRead === 0)
14759
+ break;
14760
+ fs.writeSync(predecessorFd, chunk, 0, bytesRead);
14761
+ remaining -= bytesRead;
14762
+ position += bytesRead;
14763
+ }
14764
+ } finally {
14765
+ fs.closeSync(sourceFd);
14766
+ }
14767
+ } finally {
14768
+ fs.closeSync(predecessorFd);
14769
+ }
14770
+ }
14771
+ function rotateLogFile(logFile, size) {
14772
+ const predecessorPath = `${logFile}.1`;
14773
+ writeBoundedPredecessor(logFile, predecessorPath, size);
14774
+ fs.truncateSync(logFile, 0);
14775
+ activeLogSize = 0;
14776
+ flushesSinceSizeCheck = 0;
14777
+ }
14711
14778
  function flush() {
14712
14779
  if (flushTimer) {
14713
14780
  clearTimeout(flushTimer);
@@ -14715,13 +14782,26 @@ function flush() {
14715
14782
  }
14716
14783
  if (buffer.length === 0)
14717
14784
  return;
14718
- const data = buffer.join("");
14785
+ const bufferedData = buffer.join("");
14719
14786
  buffer = [];
14720
14787
  try {
14788
+ const data = capLogData(bufferedData);
14721
14789
  const logFile = getMagicContextLogPath();
14722
14790
  ensureDir4(logFile);
14723
- fs.appendFileSync(logFile, data);
14791
+ let currentSize = getCurrentLogSize(logFile);
14792
+ const dataSize = Buffer.byteLength(data);
14793
+ if (currentSize > 0 && currentSize + dataSize > MAX_LOG_FILE_BYTES) {
14794
+ rotateLogFile(logFile, currentSize);
14795
+ currentSize = 0;
14796
+ }
14797
+ fs.appendFileSync(logFile, data, { encoding: "utf8", mode: 384 });
14798
+ activeLogFile = logFile;
14799
+ activeLogSize = currentSize + dataSize;
14800
+ flushesSinceSizeCheck++;
14724
14801
  } catch (error) {
14802
+ activeLogFile = null;
14803
+ activeLogSize = null;
14804
+ flushesSinceSizeCheck = 0;
14725
14805
  recordSwallowedWrite(error);
14726
14806
  }
14727
14807
  }
@@ -14749,17 +14829,23 @@ ${data.stack}` : ""}`)}` : ` ${JSON.stringify(sanitizeConfigValue(data))}`;
14749
14829
  }
14750
14830
  } catch {}
14751
14831
  }
14752
- var isTestEnv = false, buffer, flushTimer = null, FLUSH_INTERVAL_MS = 500, BUFFER_SIZE_LIMIT = 50, swallowedWriteCount = 0, lastErrorMessage = null, lastErrorTime = null;
14832
+ var isTestEnv = false, buffer, flushTimer = null, FLUSH_INTERVAL_MS = 500, BUFFER_SIZE_LIMIT = 50, MAX_LOG_FILE_BYTES, SIZE_CHECK_INTERVAL_FLUSHES = 64, activeLogFile = null, activeLogSize = null, flushesSinceSizeCheck = 0, swallowedWriteCount = 0, lastErrorMessage = null, lastErrorTime = null;
14753
14833
  var init_logger = __esm(() => {
14754
14834
  init_data_path();
14755
14835
  init_redaction();
14756
14836
  buffer = [];
14837
+ MAX_LOG_FILE_BYTES = 32 * 1024 * 1024;
14757
14838
  if (!isTestEnv) {
14758
14839
  process.on("exit", flush);
14759
14840
  }
14760
14841
  });
14761
14842
  // ../plugin/src/shared/window-geometry.ts
14762
14843
  function setWindowOverlayPath(path3) {
14844
+ if (configuredOverlayPath === path3)
14845
+ return;
14846
+ reloadWindowOverlay(path3);
14847
+ }
14848
+ function reloadWindowOverlay(path3) {
14763
14849
  configuredOverlayPath = path3;
14764
14850
  loadedOverlayPath = undefined;
14765
14851
  loadedOverlay = undefined;
@@ -30132,6 +30218,7 @@ var init_magic_context = __esm(() => {
30132
30218
  query_input_type: exports_external.string().optional().describe("Optional input_type for query (search) embeddings on asymmetric models (e.g. NVIDIA NIM 'query'). When unset, query embeddings use embedding.input_type. Passage/stored content always uses embedding.input_type."),
30133
30219
  truncate: exports_external.string().optional().describe("Optional truncate mode sent in the embedding request body (e.g. NVIDIA NIM accepts 'NONE' | 'START' | 'END'). Omitted from the request when unset."),
30134
30220
  max_input_tokens: exports_external.number().int().positive().optional().describe("Optional maximum input tokens for chunk embeddings. Defaults conservatively to 512 when omitted."),
30221
+ local_runtime: exports_external.enum(["auto", "native", "wasm"]).default("auto").describe("Local provider only: ONNX runtime selection. 'auto' uses native under Node and uses WASM under Bun versions before 1.4.0, where Bun's NAPI teardown race can panic on quit; native is restored automatically on Bun 1.4.0+. Set 'native' only to prefer speed while accepting that pre-1.4.0 Bun crash risk, or 'wasm' to avoid loading the native addon."),
30135
30222
  local_dtype: exports_external.enum([
30136
30223
  "auto",
30137
30224
  "fp32",
@@ -30188,6 +30275,7 @@ var init_magic_context = __esm(() => {
30188
30275
  return {
30189
30276
  provider: "local",
30190
30277
  model: data.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL,
30278
+ local_runtime: data.local_runtime,
30191
30279
  ...data.max_input_tokens ? { max_input_tokens: data.max_input_tokens } : {},
30192
30280
  ...data.local_dtype ? { local_dtype: data.local_dtype } : {}
30193
30281
  };
@@ -30268,7 +30356,8 @@ var init_magic_context = __esm(() => {
30268
30356
  }).default({ enforce_private_permissions: true }).describe("Storage permission policy. The default keeps session content and memories owner-private. Disabling enforcement is for trusted shared-group storage managed externally; every group member able to read the storage can read all stored session content and memories."),
30269
30357
  embedding: EmbeddingConfigSchema.default({
30270
30358
  provider: "local",
30271
- model: DEFAULT_LOCAL_EMBEDDING_MODEL
30359
+ model: DEFAULT_LOCAL_EMBEDDING_MODEL,
30360
+ local_runtime: "auto"
30272
30361
  }).describe("Embedding provider configuration"),
30273
30362
  subc: exports_external.object({
30274
30363
  connection_file: exports_external.string().trim().min(1).transform(expandConfigPath).describe("Path to the owner-only subc connection file.")
@@ -31820,8 +31909,8 @@ function runOpenCode(args, binary, timeoutMs) {
31820
31909
  return null;
31821
31910
  }
31822
31911
  }
31823
- function getOpenCodeVersion(binary) {
31824
- 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);
31825
31914
  }
31826
31915
  function describeOpenCodeInstallations(installations, deps = {}) {
31827
31916
  const getVersion = deps.getVersion ?? getOpenCodeVersion;
@@ -32872,11 +32961,16 @@ function prepareMirrorPageStatements(db) {
32872
32961
  function mirrorIdentity(db, domain2, moduleProject, moduleRowId, statements) {
32873
32962
  return (statements?.identityByModule ?? db.prepare("SELECT context_row_id FROM mirror_identity WHERE domain = ? AND module_project = ? AND module_row_id = ?")).get(domain2, moduleProject, moduleRowId) ?? null;
32874
32963
  }
32875
- function rememberIdentity(db, domain2, moduleProject, moduleRowId, contextRowId, statements) {
32964
+ function rememberIdentity(db, domain2, moduleProject, moduleRowId, contextRowId, statements, replaceContextIdentity = domain2 === "notes") {
32876
32965
  const existing = mirrorIdentity(db, domain2, moduleProject, moduleRowId, statements);
32877
- if (existing)
32966
+ if (existing?.context_row_id === contextRowId)
32878
32967
  return;
32879
- if (domain2 === "notes") {
32968
+ if (existing) {
32969
+ if (!replaceContextIdentity)
32970
+ return;
32971
+ (statements?.deleteIdentity ?? db.prepare("DELETE FROM mirror_identity WHERE domain = ? AND module_project = ? AND module_row_id = ?")).run(domain2, moduleProject, moduleRowId);
32972
+ }
32973
+ if (replaceContextIdentity) {
32880
32974
  (statements?.deleteIdentityByContext ?? db.prepare("DELETE FROM mirror_identity WHERE domain = ? AND context_row_id = ?")).run(domain2, contextRowId);
32881
32975
  }
32882
32976
  (statements?.insertIdentity ?? db.prepare("INSERT OR IGNORE INTO mirror_identity(domain, module_project, module_row_id, context_row_id) VALUES (?, ?, ?, ?)")).run(domain2, moduleProject, moduleRowId, contextRowId);
@@ -32891,7 +32985,7 @@ function contextMemoryId(db, domain2, moduleProject, row, moduleRowId, statement
32891
32985
  if (sourceUuid && sourceUuid === localStoreUuid && sourceId >= 0) {
32892
32986
  const existing = (statements?.memoryIdByStoreId ?? db.prepare("SELECT id FROM memories WHERE id = ? AND project_path = ?")).get(sourceId, moduleProject);
32893
32987
  if (existing?.id !== undefined) {
32894
- rememberIdentity(db, domain2, moduleProject, moduleRowId, existing.id, statements);
32988
+ rememberIdentity(db, domain2, moduleProject, moduleRowId, existing.id, statements, true);
32895
32989
  return existing.id;
32896
32990
  }
32897
32991
  }
@@ -33120,6 +33214,24 @@ function applyMirrorPage(args) {
33120
33214
  if (page.domain === "memories" && resnapshotStatus !== "complete" && page.rows.some((feed) => feed.op === "tombstone")) {
33121
33215
  throw new Error("memory mirror resnapshot must complete before tombstones");
33122
33216
  }
33217
+ if (page.domain === "memories") {
33218
+ for (const feed of page.rows) {
33219
+ if (feed.domain !== "memories" || feed.op === "tombstone" || feed.feed_seq <= durableCursor) {
33220
+ continue;
33221
+ }
33222
+ const row = feed.full_row_snapshot;
33223
+ const moduleProject = rowString(row, "project_path");
33224
+ const sourceUuid = rowNullableString(row, "context_store_uuid");
33225
+ const sourceId = rowNumber(row, "context_row_id", -1);
33226
+ if (!moduleProject || !sourceUuid || sourceUuid !== statements.contextStoreUuid || sourceId < 0) {
33227
+ continue;
33228
+ }
33229
+ const existing = statements.memoryIdByStoreId.get(sourceId, moduleProject);
33230
+ if (existing?.id === undefined)
33231
+ continue;
33232
+ rememberIdentity(db, "memories", moduleProject, feed.module_row_id, existing.id, statements, true);
33233
+ }
33234
+ }
33123
33235
  const touchedProjects = new Set;
33124
33236
  for (const feed of page.rows) {
33125
33237
  if (feed.domain !== page.domain || feed.feed_seq <= nextCursor)
@@ -33314,7 +33426,7 @@ var init_context_authority = __esm(async () => {
33314
33426
  // ../plugin/src/features/magic-context/memory/project-identity.ts
33315
33427
  import { execFileSync as execFileSync3 } from "node:child_process";
33316
33428
  import { createHash as createHash2 } from "node:crypto";
33317
- import { existsSync as existsSync18, realpathSync as realpathSync2, statSync as statSync7 } from "node:fs";
33429
+ import { existsSync as existsSync18, realpathSync as realpathSync2, statSync as statSync8 } from "node:fs";
33318
33430
  import path3 from "node:path";
33319
33431
  function asError(error51) {
33320
33432
  return error51 instanceof Error ? error51 : undefined;
@@ -33359,7 +33471,7 @@ function directoryFallback(directory) {
33359
33471
  }
33360
33472
  function assertDirectoryUsable(canonicalDirectory, rawDirectory) {
33361
33473
  try {
33362
- const stat = statSync7(canonicalDirectory);
33474
+ const stat = statSync8(canonicalDirectory);
33363
33475
  if (!stat.isDirectory()) {
33364
33476
  throw new ProjectIdentityError("unknown", rawDirectory, `Project path is not a directory: ${canonicalDirectory}`);
33365
33477
  }
@@ -35613,7 +35725,7 @@ function readPsProcessStartTime(pid) {
35613
35725
  function readProcessStartTime(pid) {
35614
35726
  if (!Number.isInteger(pid) || pid <= 0)
35615
35727
  return null;
35616
- return rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(pid) : rpcIdentityPlatform === "win32" ? null : readPsProcessStartTime(pid);
35728
+ return rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(pid) : rpcIdentityPlatform === "win32" ? readWindowsProcessStartTime(pid) : readPsProcessStartTime(pid);
35617
35729
  }
35618
35730
  function readProcessProbeEvidence(pid) {
35619
35731
  return {
@@ -35621,6 +35733,9 @@ function readProcessProbeEvidence(pid) {
35621
35733
  commandLine: readProcessCommand(pid)
35622
35734
  };
35623
35735
  }
35736
+ function rememberWindowsProcessFacts(facts) {
35737
+ windowsProcessFactsCache = new Map(facts.map((fact) => [fact.pid, fact]));
35738
+ }
35624
35739
  function parseCsvLine(line) {
35625
35740
  const fields = [];
35626
35741
  let field = "";
@@ -35685,6 +35800,16 @@ function readWindowsProcess(pid) {
35685
35800
  return { state: "inconclusive" };
35686
35801
  }
35687
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
+ }
35688
35813
  function readLinuxProcessCommand(pid) {
35689
35814
  try {
35690
35815
  return String(rpcIdentityReadFileSync(`/proc/${pid}/cmdline`, "utf8"));
@@ -35707,7 +35832,15 @@ function readPsProcessCommand(pid) {
35707
35832
  function readProcessCommand(pid) {
35708
35833
  if (!Number.isInteger(pid) || pid <= 0)
35709
35834
  return null;
35710
- 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);
35711
35844
  }
35712
35845
  function executableName(token) {
35713
35846
  return (token ?? "").replace(/^['"]|['"]$/g, "").split("/").at(-1) ?? "";
@@ -35767,57 +35900,262 @@ function isPidIdentityPlausible(record2, evidence) {
35767
35900
  return "inconclusive";
35768
35901
  return commandLooksLikeOpenCode(command) ? "plausible" : "implausible";
35769
35902
  }
35770
- function commandLooksLikePi(command) {
35771
- const normalized = command.trim().toLowerCase().replaceAll("\\", "/");
35772
- const tokens = normalized.split(/\s+/).filter(Boolean);
35773
- const executableName2 = (token) => (token ?? "").split("/").at(-1) ?? "";
35774
- const first = executableName2(tokens[0]).replace(/\.exe$/, "");
35775
- 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)) {
35918
+ return true;
35919
+ }
35920
+ if (hasArc && PI_HARNESS_ARC_MARKERS.some((marker) => tokens[0].includes(marker))) {
35776
35921
  return true;
35922
+ }
35777
35923
  if (["node", "bun", "deno"].includes(first)) {
35778
- const script = executableName2(tokens[1]);
35779
- 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;
35780
35929
  }
35781
35930
  return false;
35782
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
+ }
35783
36142
  function inspectLivePiProcesses() {
35784
36143
  if (false) {}
35785
36144
  try {
35786
- const isWindows = rpcIdentityPlatform === "win32";
35787
- const output = String(rpcProcessListExecFileSync(isWindows ? "tasklist" : "ps", isWindows ? ["/FO", "CSV"] : ["-axo", "pid=,command="], {
35788
- encoding: "utf8",
35789
- timeout: PS_PROBE_TIMEOUT_MS,
35790
- stdio: ["ignore", "pipe", "pipe"]
35791
- }));
35792
- const pids = new Set;
35793
- if (isWindows) {
35794
- const entries = parseTasklistOutput(output);
35795
- if (entries === null) {
36145
+ if (rpcIdentityPlatform === "win32") {
36146
+ const cim = tryReadWindowsCimSnapshot(rpcProcessListExecFileSync);
36147
+ const snapshot = cim ?? tryReadWindowsTasklistSnapshot();
36148
+ if (!snapshot) {
35796
36149
  return {
35797
36150
  state: "unreadable",
35798
36151
  processIds: [],
35799
- error: "tasklist output unavailable"
36152
+ error: "process list unavailable"
35800
36153
  };
35801
36154
  }
35802
- for (const entry of entries) {
35803
- if (entry.pid === process.pid)
35804
- continue;
35805
- if (commandLooksLikePi(entry.command))
35806
- pids.add(entry.pid);
35807
- }
35808
- } else {
35809
- for (const line of output.split(/\r?\n/)) {
35810
- const match = /^\s*(\d+)\s+(.+)$/.exec(line);
35811
- if (!match)
35812
- continue;
35813
- const pid = Number(match[1]);
35814
- if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid)
35815
- continue;
35816
- if (commandLooksLikePi(match[2]))
35817
- pids.add(pid);
35818
- }
36155
+ rememberWindowsProcessFacts(snapshot.facts);
36156
+ return classifyLivePiSnapshot(snapshot);
35819
36157
  }
35820
- return { state: "known", processIds: [...pids].sort((left, right) => left - right) };
36158
+ return classifyLivePiSnapshot(readPosixProcessSnapshot());
35821
36159
  } catch (error51) {
35822
36160
  return {
35823
36161
  state: "unreadable",
@@ -35859,10 +36197,19 @@ function parseRpcPortFile(content, fallbackPid = 0) {
35859
36197
  function isValidPort(port) {
35860
36198
  return Number.isInteger(port) && port > 0 && port <= 65535;
35861
36199
  }
35862
- 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;
35863
36201
  var init_rpc_utils = __esm(() => {
36202
+ init_logger();
35864
36203
  OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
35865
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"]);
35866
36213
  rpcIdentityReadFileSync = readFileSync12;
35867
36214
  rpcIdentityExecFileSync = execFileSync4;
35868
36215
  rpcIdentityProcessKill = process.kill;
@@ -35982,8 +36329,8 @@ function formatFailClosedBlockingMessage(reason) {
35982
36329
  ].join(" ");
35983
36330
  }
35984
36331
  return [
35985
- `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.`,
35986
- "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.",
35987
36334
  `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
35988
36335
  ].join(" ");
35989
36336
  }
@@ -36006,6 +36353,16 @@ var init_fail_closed_block = __esm(() => {
36006
36353
  OPENCODE_INTERNAL_AGENT_NAMES = new Set(["title", "summary", "compaction"]);
36007
36354
  });
36008
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
+
36009
36366
  // ../plugin/src/hooks/magic-context/compartment-parser.ts
36010
36367
  function makeTierOpenRegex(n2) {
36011
36368
  return new RegExp(`<p${n2}\\s*(/?)>`);
@@ -36244,6 +36601,7 @@ function healAllNullColumns(db) {
36244
36601
  ["stale_reduce_stripped_ids", ""],
36245
36602
  ["processed_image_stripped_ids", ""],
36246
36603
  ["merged_reasoning_stripped_ids", ""],
36604
+ ["thinking_binding_recovery_target", ""],
36247
36605
  ["trailing_blank_decisions", ""],
36248
36606
  ["memory_block_cache", ""],
36249
36607
  ["memory_block_ids", ""],
@@ -38623,6 +38981,30 @@ var init_migrations = __esm(() => {
38623
38981
  return;
38624
38982
  ensureColumn(db, "memory_verifications", "mapping_origin", "TEXT NOT NULL DEFAULT 'mapper'");
38625
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
+ }
38626
39008
  }
38627
39009
  ];
38628
39010
  LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m3) => Math.max(max, m3.version), 0);
@@ -38656,14 +39038,14 @@ var init_tool_owner_backfill = __esm(() => {
38656
39038
 
38657
39039
  // ../plugin/src/features/magic-context/storage-db.ts
38658
39040
  import {
38659
- chmodSync as chmodSync2,
39041
+ chmodSync as chmodSync3,
38660
39042
  copyFileSync,
38661
39043
  cpSync,
38662
39044
  existsSync as existsSync19,
38663
39045
  mkdirSync as mkdirSync7,
38664
39046
  readdirSync as readdirSync2,
38665
39047
  readFileSync as readFileSync13,
38666
- statSync as statSync8,
39048
+ statSync as statSync9,
38667
39049
  unlinkSync as unlinkSync3
38668
39050
  } from "node:fs";
38669
39051
  import { basename as basename4, dirname as dirname11, join as join15, resolve as resolve6 } from "node:path";
@@ -39385,6 +39767,23 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
39385
39767
  tokenize='porter unicode61'
39386
39768
  );
39387
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
+
39388
39787
  CREATE TABLE IF NOT EXISTS message_history_index (
39389
39788
  session_id TEXT PRIMARY KEY,
39390
39789
  last_indexed_ordinal INTEGER NOT NULL DEFAULT 0,
@@ -39528,8 +39927,9 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
39528
39927
  cached_m0_system_hash TEXT,
39529
39928
  cached_m0_tool_set_hash TEXT,
39530
39929
  cached_m0_model_key TEXT,
39531
- cached_m0_project_identity TEXT,
39532
- 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 '',
39533
39933
  upgrade_reminded_at INTEGER,
39534
39934
  pi_stable_id_scheme INTEGER
39535
39935
  );
@@ -39751,6 +40151,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
39751
40151
  ensureColumn(db, "session_meta", "stale_reduce_stripped_ids", "TEXT DEFAULT ''");
39752
40152
  ensureColumn(db, "session_meta", "processed_image_stripped_ids", "TEXT DEFAULT ''");
39753
40153
  ensureColumn(db, "session_meta", "merged_reasoning_stripped_ids", "TEXT DEFAULT ''");
40154
+ ensureColumn(db, "session_meta", "thinking_binding_recovery_target", "TEXT DEFAULT ''");
39754
40155
  ensureColumn(db, "session_meta", "trailing_blank_decisions", "TEXT DEFAULT ''");
39755
40156
  ensureColumn(db, "compartments", "start_message_id", "TEXT DEFAULT ''");
39756
40157
  ensureColumn(db, "compartments", "end_message_id", "TEXT DEFAULT ''");
@@ -39984,12 +40385,13 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
39984
40385
  `);
39985
40386
  ensureColumn(db, "workspaces", "share_categories", `TEXT NOT NULL DEFAULT '["CONSTRAINTS"]'`);
39986
40387
  }
39987
- 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;
39988
40389
  var init_storage_db = __esm(async () => {
39989
40390
  init_data_path();
39990
40391
  init_logger();
39991
40392
  init_rpc_utils();
39992
40393
  init_fail_closed_block();
40394
+ init_message_fts_rowid_map();
39993
40395
  init_migrations();
39994
40396
  init_tool_definition_tokens();
39995
40397
  init_tool_owner_backfill();
@@ -40007,7 +40409,7 @@ var init_storage_db = __esm(async () => {
40007
40409
  defaultRpcDiscoveryFs = {
40008
40410
  readdirSync: (path4, options) => options?.withFileTypes ? readdirSync2(path4, { withFileTypes: true }) : readdirSync2(path4),
40009
40411
  readFileSync: (path4, encoding) => String(readFileSync13(path4, encoding)),
40010
- statSync: (path4) => ({ mtimeMs: statSync8(path4).mtimeMs }),
40412
+ statSync: (path4) => ({ mtimeMs: statSync9(path4).mtimeMs }),
40011
40413
  unlinkSync: (path4) => unlinkSync3(path4)
40012
40414
  };
40013
40415
  rpcDiscoveryFs = defaultRpcDiscoveryFs;
@@ -40647,15 +41049,15 @@ __export(exports_doctor_repair_db, {
40647
41049
  });
40648
41050
  import { spawnSync as spawnSync3 } from "node:child_process";
40649
41051
  import {
40650
- chmodSync as chmodSync3,
40651
- closeSync as closeSync3,
41052
+ chmodSync as chmodSync4,
41053
+ closeSync as closeSync4,
40652
41054
  constants as constants2,
40653
41055
  copyFileSync as copyFileSync2,
40654
41056
  existsSync as existsSync21,
40655
- openSync as openSync3,
41057
+ openSync as openSync4,
40656
41058
  renameSync as renameSync4,
40657
41059
  rmSync as rmSync2,
40658
- statSync as statSync9
41060
+ statSync as statSync10
40659
41061
  } from "node:fs";
40660
41062
  import { dirname as dirname12, join as join17 } from "node:path";
40661
41063
  function defaultInspectHolders(storageDir) {
@@ -40670,11 +41072,11 @@ function defaultInspectHolders(storageDir) {
40670
41072
  }
40671
41073
  const blockers = rpc.state === "live" ? rpc.serverPids.map((pid) => `OpenCode server (PID ${pid})`) : [];
40672
41074
  const pi = inspectLivePiProcesses();
40673
- if (pi.state === "unreadable") {
41075
+ if (pi.state === "unreadable" || pi.state === "inconclusive") {
40674
41076
  return {
40675
41077
  safe: false,
40676
41078
  blockers,
40677
- 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"}`
40678
41080
  };
40679
41081
  }
40680
41082
  blockers.push(...pi.processIds.map((pid) => `Pi/OMP harness (PID ${pid})`));
@@ -40772,13 +41174,13 @@ function isRecoverCapabilityMissing(errorDetail) {
40772
41174
  function runRecoverShell(sqliteExecutable, sourcePath, recoveredPath, dumpPath) {
40773
41175
  let dumpWriteFd = null;
40774
41176
  try {
40775
- dumpWriteFd = openSync3(dumpPath, "wx", 384);
41177
+ dumpWriteFd = openSync4(dumpPath, "wx", 384);
40776
41178
  const recovered = spawnSync3(sqliteExecutable, [sourcePath, ".recover"], {
40777
41179
  stdio: ["ignore", dumpWriteFd, "pipe"],
40778
41180
  encoding: "utf8",
40779
41181
  windowsHide: true
40780
41182
  });
40781
- closeSync3(dumpWriteFd);
41183
+ closeSync4(dumpWriteFd);
40782
41184
  dumpWriteFd = null;
40783
41185
  if (recovered.error || recovered.status !== 0) {
40784
41186
  const errorDetail = sqliteError(recovered);
@@ -40790,7 +41192,7 @@ function runRecoverShell(sqliteExecutable, sourcePath, recoveredPath, dumpPath)
40790
41192
  unavailable: attempted && isRecoverCapabilityMissing(errorDetail)
40791
41193
  };
40792
41194
  }
40793
- const dumpReadFd = openSync3(dumpPath, "r");
41195
+ const dumpReadFd = openSync4(dumpPath, "r");
40794
41196
  try {
40795
41197
  const replayed = spawnSync3(sqliteExecutable, [recoveredPath], {
40796
41198
  stdio: [dumpReadFd, "ignore", "pipe"],
@@ -40806,7 +41208,7 @@ function runRecoverShell(sqliteExecutable, sourcePath, recoveredPath, dumpPath)
40806
41208
  };
40807
41209
  }
40808
41210
  } finally {
40809
- closeSync3(dumpReadFd);
41211
+ closeSync4(dumpReadFd);
40810
41212
  }
40811
41213
  return { ok: true };
40812
41214
  } catch (error51) {
@@ -40818,7 +41220,7 @@ function runRecoverShell(sqliteExecutable, sourcePath, recoveredPath, dumpPath)
40818
41220
  };
40819
41221
  } finally {
40820
41222
  if (dumpWriteFd !== null)
40821
- closeSync3(dumpWriteFd);
41223
+ closeSync4(dumpWriteFd);
40822
41224
  rmSync2(dumpPath, { force: true });
40823
41225
  }
40824
41226
  }
@@ -41039,8 +41441,8 @@ async function runRepairDb(options = {}) {
41039
41441
  return reportSafetyRefusal(prompts, dbPath, finalInspection, backup.basePath);
41040
41442
  }
41041
41443
  try {
41042
- const originalMode = statSync9(dbPath).mode & 511;
41043
- chmodSync3(recoveredPath, originalMode);
41444
+ const originalMode = statSync10(dbPath).mode & 511;
41445
+ chmodSync4(recoveredPath, originalMode);
41044
41446
  const originalAsidePath = uniqueBase(`${dbPath}.corrupt-original-${stamp}`);
41045
41447
  const moved = activateReplacement(dbPath, recoveredPath, originalAsidePath);
41046
41448
  reportSchemaTransition(prompts, salvageResult);
@@ -41087,8 +41489,8 @@ async function runRepairDb(options = {}) {
41087
41489
  return REPAIR_DB_EXIT.failed;
41088
41490
  }
41089
41491
  try {
41090
- const originalMode = statSync9(dbPath).mode & 511;
41091
- chmodSync3(freshPath, originalMode);
41492
+ const originalMode = statSync10(dbPath).mode & 511;
41493
+ chmodSync4(freshPath, originalMode);
41092
41494
  const originalAsidePath = uniqueBase(`${dbPath}.corrupt-original-${stamp}`);
41093
41495
  const moved = activateReplacement(dbPath, freshPath, originalAsidePath);
41094
41496
  reportSchemaTransition(prompts, fresh);
@@ -41176,7 +41578,7 @@ __export(exports_migrate, {
41176
41578
  runMigrateCli: () => runMigrateCli,
41177
41579
  sweepPendingMigrations: () => sweepPendingMigrations
41178
41580
  });
41179
- import { createHash as createHash3, randomBytes as randomBytes2 } from "node:crypto";
41581
+ import { createHash as createHash4, randomBytes as randomBytes2 } from "node:crypto";
41180
41582
  import { existsSync as existsSync22, mkdirSync as mkdirSync8, renameSync as renameSync5, unlinkSync as unlinkSync4 } from "node:fs";
41181
41583
  import { dirname as dirname13, join as join19 } from "node:path";
41182
41584
  function defaultOpenCodeDbPath() {
@@ -41216,7 +41618,7 @@ function shortId() {
41216
41618
  return randomBytes2(4).toString("hex");
41217
41619
  }
41218
41620
  function migrationKeyFor(sourceSessionId, targetHarness) {
41219
- return createHash3("sha256").update(`${sourceSessionId}
41621
+ return createHash4("sha256").update(`${sourceSessionId}
41220
41622
  ${targetHarness}`).digest("hex");
41221
41623
  }
41222
41624
  function moduleManagedProjectForSession(db, sessionId) {
@@ -41862,7 +42264,7 @@ function migrateOpenCodeSessionToPi(opts) {
41862
42264
  `;
41863
42265
  if (!opts.dryRun) {
41864
42266
  if (journalActive && cortexkitDb !== null && migrationKey !== undefined && plan) {
41865
- const contentSha256 = createHash3("sha256").update(jsonl, "utf8").digest("hex");
42267
+ const contentSha256 = createHash4("sha256").update(jsonl, "utf8").digest("hex");
41866
42268
  commitStagedChecksum(cortexkitDb, migrationKey, contentSha256);
41867
42269
  fs3.writeFileAtomic(stagePath, jsonl);
41868
42270
  plan.commit(migrationKey);
@@ -42588,7 +42990,7 @@ var init_migrate_session = __esm(async () => {
42588
42990
  });
42589
42991
 
42590
42992
  // ../plugin/src/features/magic-context/v22-deferred-backfill.ts
42591
- import { createHash as createHash4 } from "node:crypto";
42993
+ import { createHash as createHash5 } from "node:crypto";
42592
42994
  import { realpathSync as realpathSync5 } from "node:fs";
42593
42995
  import path5 from "node:path";
42594
42996
  function readMeta(db, key) {
@@ -42637,7 +43039,7 @@ function computeLegacyRustDirIdentity(rawProjectPath) {
42637
43039
  } catch {
42638
43040
  canonical = path5.isAbsolute(rawProjectPath) ? rawProjectPath : path5.join(process.cwd(), rawProjectPath);
42639
43041
  }
42640
- return `dir:${createHash4("sha256").update(canonical, "utf8").digest("hex")}`;
43042
+ return `dir:${createHash5("sha256").update(canonical, "utf8").digest("hex")}`;
42641
43043
  }
42642
43044
  function upsertRekeyMap(db, oldProjectPath, newProjectPath, rekeyedAt) {
42643
43045
  db.prepare(`INSERT INTO v22_identity_rekey_map (old_project_path, new_project_path, rekeyed_at)
@@ -43686,12 +44088,12 @@ var DEFAULT_TIMEOUT_MS = 1e4, MAX_PREVIEW_CHARS = 240;
43686
44088
 
43687
44089
  // ../plugin/src/shared/tui-config.ts
43688
44090
  import {
43689
- chmodSync as chmodSync4,
44091
+ chmodSync as chmodSync5,
43690
44092
  existsSync as existsSync26,
43691
44093
  mkdirSync as mkdirSync10,
43692
44094
  readFileSync as readFileSync16,
43693
44095
  renameSync as renameSync6,
43694
- statSync as statSync10,
44096
+ statSync as statSync11,
43695
44097
  writeFileSync as writeFileSync7
43696
44098
  } from "node:fs";
43697
44099
  import { dirname as dirname15, join as join22 } from "node:path";
@@ -43727,8 +44129,8 @@ function writeTuiConfigAtomic(configPath, config2) {
43727
44129
  const tmpPath = `${configPath}.tmp`;
43728
44130
  writeFileSync7(tmpPath, body);
43729
44131
  try {
43730
- if (statSync10(configPath, { throwIfNoEntry: false })?.isFile()) {
43731
- chmodSync4(tmpPath, statSync10(configPath).mode & 511);
44132
+ if (statSync11(configPath, { throwIfNoEntry: false })?.isFile()) {
44133
+ chmodSync5(tmpPath, statSync11(configPath).mode & 511);
43732
44134
  }
43733
44135
  } catch {}
43734
44136
  renameSync6(tmpPath, configPath);
@@ -43800,7 +44202,7 @@ var init_tui_config = __esm(() => {
43800
44202
  });
43801
44203
 
43802
44204
  // src/lib/diagnostics-opencode.ts
43803
- import { existsSync as existsSync27, readdirSync as readdirSync3, readFileSync as readFileSync17, statSync as statSync11 } from "node:fs";
44205
+ import { existsSync as existsSync27, readdirSync as readdirSync3, readFileSync as readFileSync17, statSync as statSync12 } from "node:fs";
43804
44206
  import { createRequire as createRequire3 } from "node:module";
43805
44207
  import { homedir as homedir15 } from "node:os";
43806
44208
  import { join as join23 } from "node:path";
@@ -43838,7 +44240,7 @@ function getStorageResolution() {
43838
44240
  }
43839
44241
  function fileSize(path6) {
43840
44242
  try {
43841
- return existsSync27(path6) ? statSync11(path6).size : 0;
44243
+ return existsSync27(path6) ? statSync12(path6).size : 0;
43842
44244
  } catch {
43843
44245
  return 0;
43844
44246
  }
@@ -43915,7 +44317,7 @@ function listDumpsInDir(dir, limit) {
43915
44317
  return { count: 0, recent: [] };
43916
44318
  try {
43917
44319
  const entries = readdirSync3(dir).filter((name) => name.endsWith(".xml")).map((name) => {
43918
- const stat = statSync11(join23(dir, name));
44320
+ const stat = statSync12(join23(dir, name));
43919
44321
  return {
43920
44322
  name,
43921
44323
  mtime: stat.mtimeMs,
@@ -44169,7 +44571,7 @@ async function collectDiagnostics() {
44169
44571
  const storageDirPath = storageResolution.path;
44170
44572
  const contextDbPath = join23(storageDirPath, "context.db");
44171
44573
  const logPath = getMagicContextLogPath2("opencode");
44172
- const logFileSize = existsSync27(logPath) ? statSync11(logPath).size : 0;
44574
+ const logFileSize = existsSync27(logPath) ? statSync12(logPath).size : 0;
44173
44575
  let compactionEnabled = false;
44174
44576
  try {
44175
44577
  compactionEnabled = isCompactionEnabled(loadPluginConfig(process.cwd()));
@@ -44368,10 +44770,71 @@ var init_diagnostics_opencode = __esm(() => {
44368
44770
  init_redaction2();
44369
44771
  import_comment_json10 = __toESM(require_src3(), 1);
44370
44772
  });
44773
+ // ../plugin/src/features/magic-context/memory/embedding-synapse.ts
44774
+ var SYNAPSE_CERTIFICATION_REFUSAL_REASONS, factoryClients;
44775
+ var init_embedding_synapse = __esm(() => {
44776
+ init_dist5();
44777
+ init_logger();
44778
+ SYNAPSE_CERTIFICATION_REFUSAL_REASONS = new Set([
44779
+ "not_certified",
44780
+ "probe_required",
44781
+ "migration_required"
44782
+ ]);
44783
+ factoryClients = new WeakMap;
44784
+ });
44785
+
44786
+ // ../plugin/src/features/magic-context/memory/normalize-hash.ts
44787
+ var init_normalize_hash = () => {};
44788
+
44789
+ // ../plugin/src/features/magic-context/memory/embedding-identity.ts
44790
+ var init_embedding_identity = __esm(() => {
44791
+ init_magic_context();
44792
+ init_embedding_synapse();
44793
+ init_normalize_hash();
44794
+ });
44795
+
44796
+ // ../plugin/src/features/magic-context/memory/embedding-local.ts
44797
+ function currentLocalEmbeddingHost() {
44798
+ const bun = globalThis.Bun;
44799
+ const hasProcess = typeof process !== "undefined";
44800
+ const bunVersion = hasProcess && typeof process.versions?.bun === "string" ? process.versions.bun : undefined;
44801
+ return {
44802
+ isElectron: hasProcess && Boolean(process.versions?.electron),
44803
+ isBun: Boolean(bun) || Boolean(bunVersion),
44804
+ bunVersion,
44805
+ hasNodeFilesystem: hasProcess && (typeof process.versions?.node === "string" || typeof bunVersion === "string")
44806
+ };
44807
+ }
44808
+ function bunHasNapiTeardownFix(version2) {
44809
+ const match = version2?.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);
44810
+ if (!match || match[4])
44811
+ return false;
44812
+ const parsed = [Number(match[1]), Number(match[2]), Number(match[3])];
44813
+ return parsed.some((part) => !Number.isSafeInteger(part)) ? false : parsed[0] > BUN_NAPI_TEARDOWN_FIX_VERSION[0] || parsed[0] === BUN_NAPI_TEARDOWN_FIX_VERSION[0] && (parsed[1] > BUN_NAPI_TEARDOWN_FIX_VERSION[1] || parsed[1] === BUN_NAPI_TEARDOWN_FIX_VERSION[1] && parsed[2] >= BUN_NAPI_TEARDOWN_FIX_VERSION[2]);
44814
+ }
44815
+ function resolveLocalEmbeddingRuntime(preference = "auto", host = currentLocalEmbeddingHost()) {
44816
+ if (preference === "native" || preference === "wasm")
44817
+ return preference;
44818
+ if (host.isElectron)
44819
+ return "electron";
44820
+ if (host.isBun && !bunHasNapiTeardownFix(host.bunVersion))
44821
+ return "wasm";
44822
+ return "native";
44823
+ }
44824
+ var BUN_NAPI_TEARDOWN_FIX_VERSION, STALE_LOCK_MS, MAX_LOCK_WAIT_MS;
44825
+ var init_embedding_local = __esm(() => {
44826
+ init_magic_context();
44827
+ init_data_path();
44828
+ init_logger();
44829
+ init_embedding_identity();
44830
+ BUN_NAPI_TEARDOWN_FIX_VERSION = [1, 4, 0];
44831
+ STALE_LOCK_MS = 3 * 60000;
44832
+ MAX_LOCK_WAIT_MS = 5 * 60000;
44833
+ });
44371
44834
 
44372
44835
  // src/lib/embedding-runtime.ts
44373
44836
  import { spawnSync as spawnSync6 } from "node:child_process";
44374
- import { existsSync as existsSync28 } from "node:fs";
44837
+ import { existsSync as existsSync28, readFileSync as readFileSync18 } from "node:fs";
44375
44838
  import { createRequire as createRequire4 } from "node:module";
44376
44839
  import { dirname as dirname16, join as join24, sep } from "node:path";
44377
44840
  function describeError(error51) {
@@ -44474,19 +44937,40 @@ function isNativeLocalEmbeddingRuntimeFailure(status) {
44474
44937
  return status.state === "package-missing" || status.state === "binary-missing" || status.state === "load-failed";
44475
44938
  }
44476
44939
  function describeNativeFailure(status) {
44477
- 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.";
44478
44947
  }
44479
44948
  function isLocalEmbeddingRuntimeBroken(status) {
44480
- return status.state === "both-broken" || isNativeLocalEmbeddingRuntimeFailure(status);
44949
+ return status.state === "both-broken" || status.state === "wasm-broken" || isNativeLocalEmbeddingRuntimeFailure(status);
44481
44950
  }
44482
44951
  function formatLocalEmbeddingRuntimeDoctorWarning(status) {
44952
+ if (status.state === "wasm-broken") {
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.";
44954
+ }
44483
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
+ }
44484
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`).";
44485
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
+ }
44486
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`).";
44487
44967
  }
44488
44968
  function formatLocalEmbeddingRuntimeWasmFallback(status) {
44489
- 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.";
44490
44974
  }
44491
44975
  function expectedBinaryRelPath(platform, arch) {
44492
44976
  const supportedPlatform = platform === "linux" || platform === "darwin" || platform === "win32";
@@ -44495,6 +44979,27 @@ function expectedBinaryRelPath(platform, arch) {
44495
44979
  return null;
44496
44980
  return join24("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
44497
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
+ }
44498
45003
  function probeWasmRuntimeFromRequire(requireFn) {
44499
45004
  try {
44500
45005
  const resolved = requireFn.resolve("onnxruntime-web");
@@ -44519,11 +45024,35 @@ function withWasmFallback(native, probeWasm) {
44519
45024
  }
44520
45025
  return { state: "both-broken", nativeFailure: native, wasmReason: wasm.reason };
44521
45026
  }
45027
+ function formatLocalEmbeddingRuntimeWasmSelected(status) {
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.`;
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
+ }
44522
45046
  function probeWasmRuntimeAt(installRoot) {
44523
45047
  const requireFn = createRequire4(join24(installRoot, "package.json"));
44524
- return probeWasmRuntimeFromRequire(requireFn);
45048
+ return requireNodeWasmBundle(probeWasmRuntimeFromRequire(requireFn), nodeWasmBundleCandidates(installRoot));
44525
45049
  }
44526
- function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch) {
45050
+ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
45051
+ const selectedRuntime = resolveLocalEmbeddingRuntime(runtimePreference, host);
45052
+ if (selectedRuntime !== "native") {
45053
+ const wasm = probeWasmRuntimeAt(installRoot);
45054
+ return wasm.state === "ok" ? { state: "wasm-selected", wasmPath: wasm.wasmPath } : { state: "wasm-broken", wasmReason: wasm.reason };
45055
+ }
44527
45056
  const packageDir = join24(installRoot, "node_modules", "onnxruntime-node");
44528
45057
  let native;
44529
45058
  if (!existsSync28(join24(packageDir, "package.json"))) {
@@ -44537,12 +45066,17 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
44537
45066
  };
44538
45067
  } else {
44539
45068
  const binaryPath = join24(packageDir, rel);
44540
- 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
+ };
44541
45075
  }
44542
45076
  }
44543
45077
  return withWasmFallback(native, () => probeWasmRuntimeAt(installRoot));
44544
45078
  }
44545
- function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch) {
45079
+ function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
44546
45080
  const existing = installRoots.filter((root) => existsSync28(root));
44547
45081
  if (existing.length === 0) {
44548
45082
  return {
@@ -44553,7 +45087,7 @@ function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, a
44553
45087
  let firstFallback = null;
44554
45088
  let firstFailure = null;
44555
45089
  for (const root of existing) {
44556
- const status = checkLocalEmbeddingRuntimeAt(root, platform, arch);
45090
+ const status = checkLocalEmbeddingRuntimeAt(root, platform, arch, runtimePreference, host);
44557
45091
  if (status.state === "ok")
44558
45092
  return status;
44559
45093
  if (status.state === "wasm-fallback") {
@@ -44575,12 +45109,13 @@ function probeWasmRuntimeByResolution(pluginDir) {
44575
45109
  try {
44576
45110
  const reqPlugin = createRequire4(join24(pluginDir, "package.json"));
44577
45111
  const direct = probeWasmRuntimeFromRequire(reqPlugin);
44578
- if (direct.state === "ok" || !direct.reason.startsWith("onnxruntime-web is not resolvable")) {
44579
- 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")));
44580
45117
  }
44581
- const tfResolved = reqPlugin.resolve("@huggingface/transformers");
44582
- const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
44583
- return probeWasmRuntimeFromRequire(createRequire4(join24(tfDir, "package.json")));
45118
+ return requireNodeWasmBundle(probe, [join24(pluginDir, "dist", "transformers-node-wasm.js")]);
44584
45119
  } catch (error51) {
44585
45120
  return {
44586
45121
  state: "failed",
@@ -44588,10 +45123,15 @@ function probeWasmRuntimeByResolution(pluginDir) {
44588
45123
  };
44589
45124
  }
44590
45125
  }
44591
- function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch) {
45126
+ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
44592
45127
  if (!existsSync28(join24(pluginDir, "package.json"))) {
44593
45128
  return { state: "unknown", reason: "plugin package dir not found" };
44594
45129
  }
45130
+ const selectedRuntime = resolveLocalEmbeddingRuntime(runtimePreference, host);
45131
+ if (selectedRuntime !== "native") {
45132
+ const wasm = probeWasmRuntimeByResolution(pluginDir);
45133
+ return wasm.state === "ok" ? { state: "wasm-selected", wasmPath: wasm.wasmPath } : { state: "wasm-broken", wasmReason: wasm.reason };
45134
+ }
44595
45135
  let onnxDir = null;
44596
45136
  let resolveError;
44597
45137
  try {
@@ -44626,12 +45166,18 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
44626
45166
  native = probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath: onnxDir };
44627
45167
  } else {
44628
45168
  const binaryPath = join24(onnxDir, rel);
44629
- 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
+ };
44630
45175
  }
44631
45176
  return withWasmFallback(native, () => probeWasmRuntimeByResolution(pluginDir));
44632
45177
  }
44633
45178
  var ONNX_LOAD_PROBE_TIMEOUT_MS = 1e4, ONNX_LOAD_PROBE_OUTPUT_LIMIT = 800, ONNX_LOAD_PROBE_PACKAGE_DIR_ENV = "MAGIC_CONTEXT_ONNX_RUNTIME_NODE_PACKAGE_DIR", ONNX_RUNTIME_NODE_LOAD_PROBE_SCRIPT, runOnnxRuntimeNodeLoadProbeChildForRuntime;
44634
45179
  var init_embedding_runtime = __esm(() => {
45180
+ init_embedding_local();
44635
45181
  ONNX_RUNTIME_NODE_LOAD_PROBE_SCRIPT = [
44636
45182
  'const { createRequire } = require("node:module");',
44637
45183
  'const { join } = require("node:path");',
@@ -44754,7 +45300,7 @@ var init_issue_body = __esm(() => {
44754
45300
  });
44755
45301
 
44756
45302
  // src/lib/logs-opencode.ts
44757
- import { readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "node:fs";
45303
+ import { readFileSync as readFileSync19, writeFileSync as writeFileSync8 } from "node:fs";
44758
45304
  import { join as join25 } from "node:path";
44759
45305
  function sanitizeLogContent(content) {
44760
45306
  return sanitizeDiagnosticText(content);
@@ -44797,7 +45343,7 @@ function filterLogLinesBySession(lines, sessionId) {
44797
45343
  }
44798
45344
  async function bundleIssueReport(report, description, title, sessionFilter = null) {
44799
45345
  const LOG_TAIL_LINES = 400;
44800
- 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/) : [];
44801
45347
  const logLines = filterLogLinesBySession(allLogLines, sessionFilter);
44802
45348
  const recentLog = sanitizeLogContent(logLines.slice(-LOG_TAIL_LINES).join(`
44803
45349
  `)).trim();
@@ -45169,9 +45715,9 @@ import {
45169
45715
  accessSync as accessSync2,
45170
45716
  existsSync as existsSync29,
45171
45717
  constants as fsConstants,
45172
- readFileSync as readFileSync19,
45718
+ readFileSync as readFileSync20,
45173
45719
  renameSync as renameSync7,
45174
- statSync as statSync12,
45720
+ statSync as statSync13,
45175
45721
  writeFileSync as writeFileSync9
45176
45722
  } from "node:fs";
45177
45723
  import { dirname as dirname17, isAbsolute as isAbsolute5, join as join27, resolve as resolve8 } from "node:path";
@@ -45223,7 +45769,7 @@ function getWinningConfig(directory, surface) {
45223
45769
  try {
45224
45770
  if (!existsSync29(path6))
45225
45771
  continue;
45226
- const parsed = parseJsonConfig(readFileSync19(path6, "utf-8"));
45772
+ const parsed = parseJsonConfig(readFileSync20(path6, "utf-8"));
45227
45773
  const entries = getPluginEntries(parsed);
45228
45774
  if (entries.some((entry) => entry === PACKAGE_NAME || entry.startsWith(`${PACKAGE_NAME}@`))) {
45229
45775
  if (winner) {
@@ -45259,14 +45805,14 @@ var init_checker = __esm(() => {
45259
45805
  });
45260
45806
 
45261
45807
  // src/lib/opencode-plugin-schema-fence.ts
45262
- 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";
45263
45809
  import { join as join28 } from "node:path";
45264
45810
  import { gunzipSync } from "node:zlib";
45265
45811
  function readPackageVersion(packageJsonPath) {
45266
45812
  try {
45267
45813
  if (!existsSync30(packageJsonPath))
45268
45814
  return null;
45269
- const packageJson = JSON.parse(readFileSync20(packageJsonPath, "utf-8"));
45815
+ const packageJson = JSON.parse(readFileSync21(packageJsonPath, "utf-8"));
45270
45816
  if (packageJson.name !== OPENCODE_PLUGIN_NAME || typeof packageJson.version !== "string") {
45271
45817
  return null;
45272
45818
  }
@@ -45303,7 +45849,7 @@ function readFenceFromDist(packageDirectory) {
45303
45849
  }
45304
45850
  if (!entry.isFile() || !/\.(?:[cm]?js|ts)$/.test(entry.name))
45305
45851
  continue;
45306
- const fence = readFenceValue(readFileSync20(path6, "utf-8"));
45852
+ const fence = readFenceValue(readFileSync21(path6, "utf-8"));
45307
45853
  if (fence !== null)
45308
45854
  fenceValues.add(fence);
45309
45855
  }
@@ -45521,13 +46067,13 @@ var init_storage_versions = __esm(async () => {
45521
46067
  });
45522
46068
 
45523
46069
  // src/commands/doctor-opencode-cache.ts
45524
- 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";
45525
46071
  function readCachedPluginVersion(pluginCacheDir) {
45526
46072
  try {
45527
46073
  const installedPkgPath = getOpenCodePluginPackageJsonPath(pluginCacheDir);
45528
46074
  if (!existsSync31(installedPkgPath))
45529
46075
  return;
45530
- const pkg = JSON.parse(readFileSync21(installedPkgPath, "utf-8"));
46076
+ const pkg = JSON.parse(readFileSync22(installedPkgPath, "utf-8"));
45531
46077
  return typeof pkg.version === "string" ? pkg.version : undefined;
45532
46078
  } catch {
45533
46079
  return;
@@ -45604,7 +46150,7 @@ var init_doctor_opencode_cache = __esm(() => {
45604
46150
 
45605
46151
  // src/commands/doctor-opencode.ts
45606
46152
  import { spawnSync as spawnSync7 } from "node:child_process";
45607
- import { existsSync as existsSync32, readFileSync as readFileSync22, statSync as statSync13 } from "node:fs";
46153
+ import { existsSync as existsSync32, readFileSync as readFileSync23, statSync as statSync14 } from "node:fs";
45608
46154
  import { createRequire as createRequire5 } from "node:module";
45609
46155
  import { homedir as homedir17 } from "node:os";
45610
46156
  import { join as join29 } from "node:path";
@@ -45714,7 +46260,7 @@ function collectNpmReleaseAgeWarnings() {
45714
46260
  if (!existsSync32(npmrcPath))
45715
46261
  return ageWarnings;
45716
46262
  try {
45717
- const npmrc = readFileSync22(npmrcPath, "utf-8");
46263
+ const npmrc = readFileSync23(npmrcPath, "utf-8");
45718
46264
  for (const line of npmrc.split(`
45719
46265
  `)) {
45720
46266
  const trimmed = line.trim();
@@ -45826,8 +46372,12 @@ async function runIssueFlow2() {
45826
46372
  return 1;
45827
46373
  }
45828
46374
  }
45829
- function checkLocalEmbeddingRuntimeForDoctor() {
45830
- const runtime = checkLocalEmbeddingRuntime(getOpenCodePluginCacheRoots());
46375
+ function checkLocalEmbeddingRuntimeForDoctor(runtimePreference = "auto") {
46376
+ const runtime = checkLocalEmbeddingRuntime(getOpenCodePluginCacheRoots(), process.platform, process.arch, runtimePreference);
46377
+ if (runtime.state === "wasm-selected") {
46378
+ log2.info(formatLocalEmbeddingRuntimeWasmSelected(runtime));
46379
+ return { issues: 0 };
46380
+ }
45831
46381
  if (runtime.state === "wasm-fallback") {
45832
46382
  log2.warn(formatLocalEmbeddingRuntimeWasmFallback(runtime));
45833
46383
  return { issues: 0 };
@@ -45840,7 +46390,7 @@ function checkLocalEmbeddingRuntimeForDoctor() {
45840
46390
  log2.warn(`Local embedding runtime unverified: ${runtime.reason}`);
45841
46391
  return { issues: 0, unverified: true };
45842
46392
  }
45843
- log2.success("Embedding provider: local (native runtime OK; Xenova/all-MiniLM-L6-v2 bundled)");
46393
+ log2.success("Embedding provider: local (native runtime selected and OK; Xenova/all-MiniLM-L6-v2 bundled)");
45844
46394
  return { issues: 0 };
45845
46395
  }
45846
46396
  async function checkEmbeddingConfig(magicContextConfigPath) {
@@ -45875,7 +46425,8 @@ async function checkEmbeddingConfig(magicContextConfigPath) {
45875
46425
  return { issues: 0 };
45876
46426
  }
45877
46427
  if (provider === undefined || provider === "local") {
45878
- return checkLocalEmbeddingRuntimeForDoctor();
46428
+ const runtimePreference = embedding?.local_runtime === "native" || embedding?.local_runtime === "wasm" ? embedding.local_runtime : "auto";
46429
+ return checkLocalEmbeddingRuntimeForDoctor(runtimePreference);
45879
46430
  }
45880
46431
  if (provider !== "openai-compatible") {
45881
46432
  log2.warn(`Unknown embedding provider: ${String(provider)} (expected local | openai-compatible | off)`);
@@ -46210,7 +46761,7 @@ async function runDoctor2(options = {}) {
46210
46761
  }
46211
46762
  if (paths.opencodeConfigFormat !== "none") {
46212
46763
  try {
46213
- const raw = readFileSync22(paths.opencodeConfig, "utf-8");
46764
+ const raw = readFileSync23(paths.opencodeConfig, "utf-8");
46214
46765
  const config2 = import_comment_json12.parse(raw);
46215
46766
  const rawPlugins = Array.isArray(config2?.plugin) ? config2.plugin : [];
46216
46767
  const existingIdx = rawPlugins.findIndex((entry) => matchesPluginEntry(entry, OPENCODE_PLUGIN_NAME) || isDevPathPluginEntry(entry));
@@ -46297,7 +46848,7 @@ async function runDoctor2(options = {}) {
46297
46848
  fixed++;
46298
46849
  } else if (existsSync32(paths.tuiConfig)) {
46299
46850
  try {
46300
- const tuiRaw = readFileSync22(paths.tuiConfig, "utf-8");
46851
+ const tuiRaw = readFileSync23(paths.tuiConfig, "utf-8");
46301
46852
  const tuiConfig = import_comment_json12.parse(tuiRaw);
46302
46853
  const tuiRawPlugins = Array.isArray(tuiConfig?.plugin) ? tuiConfig.plugin : [];
46303
46854
  const tuiIdx = tuiRawPlugins.findIndex((entry) => matchesPluginEntry(entry, OPENCODE_PLUGIN_NAME) || isDevPathPluginEntry(entry));
@@ -46493,7 +47044,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
46493
47044
  }
46494
47045
  const logPath = getMagicContextLogPath2("opencode");
46495
47046
  if (existsSync32(logPath)) {
46496
- const logStat = statSync13(logPath);
47047
+ const logStat = statSync14(logPath);
46497
47048
  const sizeKb = (logStat.size / 1024).toFixed(0);
46498
47049
  log2.info(`Log file: ${logPath} (${sizeKb} KB)`);
46499
47050
  } else {
@@ -46575,7 +47126,7 @@ var init_doctor_opencode = __esm(async () => {
46575
47126
  });
46576
47127
 
46577
47128
  // src/lib/diagnostics-pi.ts
46578
- import { existsSync as existsSync33, readdirSync as readdirSync5, readFileSync as readFileSync23, statSync as statSync14 } from "node:fs";
47129
+ import { existsSync as existsSync33, readdirSync as readdirSync5, readFileSync as readFileSync24, statSync as statSync15 } from "node:fs";
46579
47130
  import { createRequire as createRequire6 } from "node:module";
46580
47131
  import { join as join30 } from "node:path";
46581
47132
  function getSelfVersion3() {
@@ -46592,7 +47143,7 @@ function getSelfVersion3() {
46592
47143
  }
46593
47144
  function fileSize2(path6) {
46594
47145
  try {
46595
- return existsSync33(path6) ? statSync14(path6).size : 0;
47146
+ return existsSync33(path6) ? statSync15(path6).size : 0;
46596
47147
  } catch {
46597
47148
  return 0;
46598
47149
  }
@@ -46608,7 +47159,7 @@ function readJsonc(path6) {
46608
47159
  return { value: {} };
46609
47160
  try {
46610
47161
  return {
46611
- value: import_comment_json13.parse(readFileSync23(path6, "utf-8"))
47162
+ value: import_comment_json13.parse(readFileSync24(path6, "utf-8"))
46612
47163
  };
46613
47164
  } catch (error51) {
46614
47165
  return {
@@ -46660,7 +47211,7 @@ function collectPiRecentSessions() {
46660
47211
  }
46661
47212
  for (const file2 of files) {
46662
47213
  try {
46663
- const mtime = statSync14(join30(slugDir, file2)).mtimeMs;
47214
+ const mtime = statSync15(join30(slugDir, file2)).mtimeMs;
46664
47215
  const sessionId = file2.replace(/\.jsonl$/, "");
46665
47216
  candidates.push({ sessionId, directory, mtime });
46666
47217
  } catch {}
@@ -46678,7 +47229,7 @@ function collectPiRecentSessions() {
46678
47229
  }
46679
47230
  function parseHistorianDumpMeta2(path6) {
46680
47231
  try {
46681
- const xml = readFileSync23(path6, "utf-8");
47232
+ const xml = readFileSync24(path6, "utf-8");
46682
47233
  const parsed = parseCompartmentOutput(xml);
46683
47234
  const factCountByCategory = {};
46684
47235
  for (const fact of parsed.facts) {
@@ -46715,7 +47266,7 @@ function listDumpsInDir2(dir, limit) {
46715
47266
  return { count: 0, recent: [] };
46716
47267
  try {
46717
47268
  const entries = readdirSync5(dir).filter((name) => name.endsWith(".xml")).map((name) => {
46718
- const stat = statSync14(join30(dir, name));
47269
+ const stat = statSync15(join30(dir, name));
46719
47270
  return {
46720
47271
  name,
46721
47272
  mtime: stat.mtimeMs,
@@ -46790,7 +47341,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
46790
47341
  const storageDirPath = storageResolution.path;
46791
47342
  const dbPath = join30(storageDirPath, "context.db");
46792
47343
  const logPath = getMagicContextLogPath2("pi");
46793
- const logFileSize = existsSync33(logPath) ? statSync14(logPath).size : 0;
47344
+ const logFileSize = existsSync33(logPath) ? statSync15(logPath).size : 0;
46794
47345
  const otherPiExtensions = packages.filter((entry) => !isPiMagicContextPackageEntry(entry)).map(describePiPackageEntry);
46795
47346
  const recentSessions = collectPiRecentSessions();
46796
47347
  const historianDumps = collectPiHistorianDumps(recentSessions);
@@ -46926,7 +47477,7 @@ var init_diagnostics_pi = __esm(() => {
46926
47477
  });
46927
47478
 
46928
47479
  // src/lib/logs-pi.ts
46929
- import { readFileSync as readFileSync24, writeFileSync as writeFileSync10 } from "node:fs";
47480
+ import { readFileSync as readFileSync25, writeFileSync as writeFileSync10 } from "node:fs";
46930
47481
  import { join as join31 } from "node:path";
46931
47482
  function sanitizeLogContent2(content) {
46932
47483
  return sanitizeString2(content);
@@ -46956,7 +47507,7 @@ function filterLogLinesBySession2(lines, sessionId) {
46956
47507
  }
46957
47508
  async function bundleIssueReport2(report, description, title, options = {}) {
46958
47509
  const LOG_TAIL_LINES = 400;
46959
- 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/) : [];
46960
47511
  const logLines = filterLogLinesBySession2(allLogLines, options.sessionFilter ?? null);
46961
47512
  const recentLog = sanitizeLogContent2(logLines.slice(-LOG_TAIL_LINES).join(`
46962
47513
  `)).trim();
@@ -47010,7 +47561,7 @@ var init_logs_pi = __esm(() => {
47010
47561
 
47011
47562
  // src/commands/doctor-pi.ts
47012
47563
  import { execFileSync as execFileSync6, spawnSync as spawnSync8 } from "node:child_process";
47013
- import { existsSync as existsSync34, mkdirSync as mkdirSync11, readdirSync as readdirSync6, readFileSync as readFileSync25, rmSync as rmSync4, statSync as statSync15 } 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";
47014
47565
  import { createRequire as createRequire7 } from "node:module";
47015
47566
  import { homedir as homedir18 } from "node:os";
47016
47567
  import { dirname as dirname18, isAbsolute as isAbsolute6, join as join32 } from "node:path";
@@ -47103,7 +47654,7 @@ function summarize(results) {
47103
47654
  function readJsonc2(path6) {
47104
47655
  try {
47105
47656
  return {
47106
- value: import_comment_json14.parse(readFileSync25(path6, "utf-8"))
47657
+ value: import_comment_json14.parse(readFileSync26(path6, "utf-8"))
47107
47658
  };
47108
47659
  } catch (error51) {
47109
47660
  return {
@@ -47251,7 +47802,7 @@ function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
47251
47802
  return;
47252
47803
  let stat;
47253
47804
  try {
47254
- stat = statSync15(path6);
47805
+ stat = statSync16(path6);
47255
47806
  } catch {
47256
47807
  return;
47257
47808
  }
@@ -47260,7 +47811,7 @@ function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
47260
47811
  const packageJson = join32(path6, "package.json");
47261
47812
  if (existsSync34(packageJson)) {
47262
47813
  try {
47263
- const pkg = JSON.parse(readFileSync25(packageJson, "utf-8"));
47814
+ const pkg = JSON.parse(readFileSync26(packageJson, "utf-8"));
47264
47815
  const name = typeof pkg.name === "string" ? pkg.name : "";
47265
47816
  const version2 = typeof pkg.version === "string" ? pkg.version : undefined;
47266
47817
  if (name === PACKAGE_NAME2) {
@@ -47487,9 +48038,14 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
47487
48038
  let runtimeReported = false;
47488
48039
  let runtimeUnverifiedReason = "no installed plugin tree found to inspect";
47489
48040
  for (const pluginDir of piPluginDirCandidates(packages, options.cwd)) {
47490
- const runtime = checkLocalEmbeddingRuntimeByResolution(pluginDir);
48041
+ const runtime = checkLocalEmbeddingRuntimeByResolution(pluginDir, process.platform, process.arch, loadedConfig.config.embedding.provider === "local" ? loadedConfig.config.embedding.local_runtime : "auto", { isBun: false, isElectron: false });
48042
+ if (runtime.state === "wasm-selected") {
48043
+ add2(results, "info", formatLocalEmbeddingRuntimeWasmSelected(runtime));
48044
+ runtimeReported = true;
48045
+ break;
48046
+ }
47491
48047
  if (runtime.state === "ok") {
47492
- add2(results, "pass", `Embedding provider: ${loadedConfig.config.embedding.provider} (native runtime OK)`);
48048
+ add2(results, "pass", `Embedding provider: ${loadedConfig.config.embedding.provider} (native runtime selected and OK)`);
47493
48049
  runtimeReported = true;
47494
48050
  break;
47495
48051
  }
@@ -47507,7 +48063,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
47507
48063
  runtimeUnverifiedReason = runtime.reason;
47508
48064
  }
47509
48065
  if (!runtimeReported) {
47510
- add2(results, "warn", `Embedding provider ${loadedConfig.config.embedding.provider}: native runtime unverified (${runtimeUnverifiedReason})`);
48066
+ add2(results, "warn", `Embedding provider ${loadedConfig.config.embedding.provider}: selected runtime unverified (${runtimeUnverifiedReason})`);
47511
48067
  }
47512
48068
  }
47513
48069
  const piEntries = packages.filter(isPiMagicContextPackageEntry).map(describePiPackageEntry);
@@ -47534,9 +48090,9 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
47534
48090
  }
47535
48091
  const logPath = getMagicContextLogPath2("pi");
47536
48092
  if (existsSync34(logPath)) {
47537
- const stat = statSync15(logPath);
48093
+ const stat = statSync16(logPath);
47538
48094
  const sizeKb = (stat.size / 1024).toFixed(0);
47539
- 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);
47540
48096
  add2(results, "info", `Log file: ${logPath} (${sizeKb} KB)`);
47541
48097
  const lastLine = lines.at(-1);
47542
48098
  add2(results, "info", `Last plugin log line: ${lastLine ? sanitizeDiagnosticText(lastLine) : "<empty log>"}`);