@cortexkit/magic-context 0.49.48 → 0.49.50

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 +570 -587
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1733,6 +1733,7 @@ import {
1733
1733
  readFileSync as readFileSync2,
1734
1734
  readlinkSync,
1735
1735
  realpathSync,
1736
+ unlinkSync,
1736
1737
  writeFileSync
1737
1738
  } from "node:fs";
1738
1739
  import * as os from "node:os";
@@ -1832,6 +1833,7 @@ function getLegacyOpenCodeMagicContextStorageDir() {
1832
1833
  }
1833
1834
  var STORAGE_BACKUP_WARNING_CHECKED;
1834
1835
  var init_data_path = __esm(() => {
1836
+ init_logger();
1835
1837
  init_test_temp_dir();
1836
1838
  STORAGE_BACKUP_WARNING_CHECKED = Symbol.for("magic-context.storage-backup-warning-checked");
1837
1839
  });
@@ -2872,7 +2874,7 @@ var init_jsonc_edit = __esm(() => {
2872
2874
  });
2873
2875
 
2874
2876
  // ../plugin/src/config/migrate-config-location.ts
2875
- import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync as rmSync2, statSync as statSync2, unlinkSync } from "node:fs";
2877
+ import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync as rmSync2, statSync as statSync2, unlinkSync as unlinkSync2 } from "node:fs";
2876
2878
  import { homedir as homedir3 } from "node:os";
2877
2879
  import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute2, join as join3 } from "node:path";
2878
2880
  function homeDir() {
@@ -3100,7 +3102,7 @@ function markLegacySourcesMovedAside(sources, targetPath, logger) {
3100
3102
  try {
3101
3103
  const original = readFileSync3(source.path, "utf-8");
3102
3104
  atomicWriteConfigFile(markerPath, movedMarkerContent(targetPath, basename2(source.path), original));
3103
- unlinkSync(source.path);
3105
+ unlinkSync2(source.path);
3104
3106
  info?.(`Moved legacy Magic Context config ${source.path} aside to ${markerPath}; now reading ${targetPath}`);
3105
3107
  } catch (err) {
3106
3108
  const msg = err instanceof Error ? err.message : String(err);
@@ -10455,6 +10457,7 @@ var init_magic_context = __esm(() => {
10455
10457
  query_instruction: union([string2(), literal(false)]).optional().describe("OpenAI-compatible query prefix override. A string is prepended verbatim to search queries; false disables the built-in model-family instruction. Qwen3-Embedding, gte-Qwen instruct, e5 instruct, and Nomic families have built-in recipes. Query-only changes do not re-embed stored content. User-level only; project values are ignored."),
10456
10458
  document_prefix: string2().optional().describe("OpenAI-compatible stored-document prefix override, prepended verbatim. Defaults to the model-family recipe (empty for Qwen3/gte/e5 instruct; 'search_document: ' for Nomic). Changing it changes stored vectors and triggers re-embedding. User-level only; project values are ignored."),
10457
10459
  truncate: string2().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."),
10460
+ dimensions: number2().int().min(1).max(8192).optional().describe("Optional output width for Matryoshka embedding models (e.g. Qwen3-Embedding-8B accepts 768 | 1024 | 2048 | 4096; OpenAI text-embedding-3-* accept smaller widths than native). Sent as the OpenAI-compatible `dimensions` request field. Omitted from the request when unset, so the endpoint default applies. Changing it changes the produced vectors and folds into the embedding model identity, so switching widths re-embeds rather than mixing vector spaces. Not supported for the local provider, and ignored from project config like the other embedding fields (a repository cannot choose how private text is embedded)."),
10458
10461
  max_input_tokens: number2().int().positive().optional().describe("Optional maximum input tokens for chunk embeddings. Defaults conservatively to 512 when omitted."),
10459
10462
  local_runtime: _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+. Inference runs in a dedicated worker after disabling POSIX telemetry in the native process environment. Compiled Bun hosts and hosts without a verified in-process opt-out use a subprocess instead. Windows native ONNX emits OS-controlled ETW diagnostics, not direct uploads. On Bun before 1.4.0, even explicit 'native' uses WASM because native worker teardown can crash the process. Set 'wasm' to avoid loading the native addon on newer hosts too."),
10460
10463
  local_dtype: _enum([
@@ -10503,6 +10506,7 @@ var init_magic_context = __esm(() => {
10503
10506
  ...model ? { model } : {},
10504
10507
  ...endpoint ? { endpoint } : {},
10505
10508
  ...apiKey ? { api_key: apiKey } : {},
10509
+ ...data.dimensions ? { dimensions: data.dimensions } : {},
10506
10510
  ...inputType ? { input_type: inputType } : {},
10507
10511
  ...queryInputType ? { query_input_type: queryInputType } : {},
10508
10512
  ...data.query_instruction !== undefined ? { query_instruction: data.query_instruction } : {},
@@ -10529,6 +10533,7 @@ var init_magic_context = __esm(() => {
10529
10533
  provider: "openai-compatible",
10530
10534
  model: data.model?.trim() ?? "",
10531
10535
  endpoint: data.endpoint?.trim() ?? "",
10536
+ ...data.dimensions ? { dimensions: data.dimensions } : {},
10532
10537
  ...apiKey ? { api_key: apiKey } : {},
10533
10538
  ...inputType ? { input_type: inputType } : {},
10534
10539
  ...queryInputType ? { query_input_type: queryInputType } : {},
@@ -11424,7 +11429,8 @@ var init_project_security = __esm(() => {
11424
11429
  "provider",
11425
11430
  "fallback_provider",
11426
11431
  "query_instruction",
11427
- "document_prefix"
11432
+ "document_prefix",
11433
+ "dimensions"
11428
11434
  ];
11429
11435
  PROTECTED_TOKENS_TIER_OVERRIDES = Symbol.for("@cortexkit/magic-context/protected-tokens-tier-overrides");
11430
11436
  PROJECT_COMMAND_STRING_FIELDS = ["description", "agent", "model"];
@@ -11472,7 +11478,7 @@ import {
11472
11478
  realpathSync as realpathSync2,
11473
11479
  renameSync as renameSync2,
11474
11480
  statSync as statSync3,
11475
- unlinkSync as unlinkSync2,
11481
+ unlinkSync as unlinkSync3,
11476
11482
  writeFileSync as writeFileSync3
11477
11483
  } from "node:fs";
11478
11484
  import { basename as basename3, dirname as dirname5, join as join4 } from "node:path";
@@ -11678,7 +11684,7 @@ function writeExclusiveBackup(backupPath, bytes, mode) {
11678
11684
  }
11679
11685
  } finally {
11680
11686
  try {
11681
- unlinkSync2(temporaryPath);
11687
+ unlinkSync3(temporaryPath);
11682
11688
  } catch {}
11683
11689
  }
11684
11690
  }
@@ -11701,7 +11707,7 @@ function writeTemporaryCandidate(configPath, bytes, mode) {
11701
11707
  } catch {}
11702
11708
  }
11703
11709
  try {
11704
- unlinkSync2(path);
11710
+ unlinkSync3(path);
11705
11711
  } catch {}
11706
11712
  if (error.code !== "EEXIST")
11707
11713
  throw error;
@@ -11764,7 +11770,7 @@ function loadRawConfigFile(options) {
11764
11770
  options.afterTemporaryWrite?.();
11765
11771
  const currentBytes = readFileSync4(options.configPath);
11766
11772
  if (!hasFlatKeys(currentBytes)) {
11767
- unlinkSync2(temporaryPath);
11773
+ unlinkSync3(temporaryPath);
11768
11774
  return {
11769
11775
  configPath: options.configPath,
11770
11776
  bytes: currentBytes,
@@ -11774,7 +11780,7 @@ function loadRawConfigFile(options) {
11774
11780
  };
11775
11781
  }
11776
11782
  if (!currentBytes.equals(observedBytes)) {
11777
- unlinkSync2(temporaryPath);
11783
+ unlinkSync3(temporaryPath);
11778
11784
  observedBytes = currentBytes;
11779
11785
  continue;
11780
11786
  }
@@ -11792,7 +11798,7 @@ function loadRawConfigFile(options) {
11792
11798
  } catch (error) {
11793
11799
  if (temporaryPath) {
11794
11800
  try {
11795
- unlinkSync2(temporaryPath);
11801
+ unlinkSync3(temporaryPath);
11796
11802
  } catch {}
11797
11803
  }
11798
11804
  return {
@@ -15787,52 +15793,9 @@ var init_dashboard_install = __esm(() => {
15787
15793
  WINDOWS_UNINSTALL_KEY = `Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${DASHBOARD_PRODUCT_NAME}`;
15788
15794
  });
15789
15795
 
15790
- // src/lib/docs-proposal-gitignore.ts
15791
- import { appendFileSync as appendFileSync2, existsSync as existsSync8, readFileSync as readFileSync7 } from "node:fs";
15792
- import { join as join6 } from "node:path";
15793
- function coversProposalState(line) {
15794
- const rule = line.trim();
15795
- if (rule === "" || rule.startsWith("#") || rule.startsWith("!"))
15796
- return false;
15797
- const normalized = rule.replace(/^\//, "").replace(/^\*\*\//, "").replace(/\/(\*\*?)?$/, "");
15798
- return COVERING_PATHS.has(normalized);
15799
- }
15800
- function ensureDocsProposalGitignore(projectDir) {
15801
- if (!existsSync8(join6(projectDir, ".git")))
15802
- return { status: "not-a-repository" };
15803
- const path = join6(projectDir, ".gitignore");
15804
- try {
15805
- const text = existsSync8(path) ? readFileSync7(path, "utf8") : "";
15806
- if (text.split(/\r?\n/).some(coversProposalState))
15807
- return { status: "covered" };
15808
- const nestedPath = join6(projectDir, ".cortexkit", ".gitignore");
15809
- if (existsSync8(nestedPath)) {
15810
- const nested = readFileSync7(nestedPath, "utf8").split(/\r?\n/);
15811
- if (nested.some((line) => /^\/?magic-context(\/(\*\*?)?)?$/.test(line.trim()))) {
15812
- return { status: "covered" };
15813
- }
15814
- }
15815
- appendFileSync2(path, `${text && !text.endsWith(`
15816
- `) ? `
15817
- ` : ""}.cortexkit/magic-context/
15818
- `);
15819
- return { status: "added", path };
15820
- } catch (error) {
15821
- return {
15822
- status: "failed",
15823
- path,
15824
- error: error instanceof Error ? error.message : String(error)
15825
- };
15826
- }
15827
- }
15828
- var COVERING_PATHS;
15829
- var init_docs_proposal_gitignore = __esm(() => {
15830
- COVERING_PATHS = new Set([".cortexkit", ".cortexkit/magic-context"]);
15831
- });
15832
-
15833
15796
  // src/lib/find-on-path.ts
15834
- import { accessSync as accessSync2, constants as constants2, existsSync as existsSync9, statSync as statSync6 } from "node:fs";
15835
- import { delimiter, join as join7 } from "node:path";
15797
+ import { accessSync as accessSync2, constants as constants2, existsSync as existsSync8, statSync as statSync6 } from "node:fs";
15798
+ import { delimiter, join as join6 } from "node:path";
15836
15799
  function findOnPath(binary) {
15837
15800
  const PATH = process.env.PATH;
15838
15801
  if (typeof PATH !== "string" || PATH.length === 0)
@@ -15844,7 +15807,7 @@ function findOnPath(binary) {
15844
15807
  if (!dir)
15845
15808
  continue;
15846
15809
  for (const candidate of candidates) {
15847
- const fullPath = join7(dir, candidate);
15810
+ const fullPath = join6(dir, candidate);
15848
15811
  if (isExecutableFile(fullPath, isWindows))
15849
15812
  return fullPath;
15850
15813
  }
@@ -15853,7 +15816,7 @@ function findOnPath(binary) {
15853
15816
  }
15854
15817
  function isExecutableFile(path, isWindows = process.platform === "win32") {
15855
15818
  try {
15856
- if (!existsSync9(path))
15819
+ if (!existsSync8(path))
15857
15820
  return false;
15858
15821
  const st = statSync6(path);
15859
15822
  if (!st.isFile())
@@ -15870,28 +15833,28 @@ function isExecutableFile(path, isWindows = process.platform === "win32") {
15870
15833
  var init_find_on_path = () => {};
15871
15834
 
15872
15835
  // src/lib/paths.ts
15873
- import { existsSync as existsSync10, readdirSync as readdirSync2, statSync as statSync7 } from "node:fs";
15836
+ import { existsSync as existsSync9, readdirSync as readdirSync2, statSync as statSync7 } from "node:fs";
15874
15837
  import { homedir as homedir7 } from "node:os";
15875
- import { delimiter as delimiter2, dirname as dirname8, join as join8, resolve as resolve3 } from "node:path";
15838
+ import { delimiter as delimiter2, dirname as dirname8, join as join7, resolve as resolve3 } from "node:path";
15876
15839
  function getOpenCodeConfigDir() {
15877
15840
  const envDir = process.env.OPENCODE_CONFIG_DIR?.trim();
15878
15841
  if (envDir)
15879
15842
  return envDir;
15880
15843
  if (process.platform === "win32") {
15881
- return join8(homedir7(), ".config", "opencode");
15844
+ return join7(homedir7(), ".config", "opencode");
15882
15845
  }
15883
- const xdgConfig = process.env.XDG_CONFIG_HOME || join8(homedir7(), ".config");
15884
- return join8(xdgConfig, "opencode");
15846
+ const xdgConfig = process.env.XDG_CONFIG_HOME || join7(homedir7(), ".config");
15847
+ return join7(xdgConfig, "opencode");
15885
15848
  }
15886
15849
  function findOmoConfig(configDir) {
15887
15850
  const locations = [
15888
- join8(configDir, "oh-my-openagent.jsonc"),
15889
- join8(configDir, "oh-my-openagent.json"),
15890
- join8(configDir, "oh-my-opencode.jsonc"),
15891
- join8(configDir, "oh-my-opencode.json")
15851
+ join7(configDir, "oh-my-openagent.jsonc"),
15852
+ join7(configDir, "oh-my-openagent.json"),
15853
+ join7(configDir, "oh-my-opencode.jsonc"),
15854
+ join7(configDir, "oh-my-opencode.json")
15892
15855
  ];
15893
15856
  for (const loc of locations) {
15894
- if (existsSync10(loc))
15857
+ if (existsSync9(loc))
15895
15858
  return loc;
15896
15859
  }
15897
15860
  return null;
@@ -15902,24 +15865,24 @@ function detectConfigPaths() {
15902
15865
  let opencodeConfigFormat;
15903
15866
  let tuiConfig;
15904
15867
  let tuiConfigFormat;
15905
- const jsoncPath = join8(configDir, "opencode.jsonc");
15906
- const jsonPath = join8(configDir, "opencode.json");
15907
- if (existsSync10(jsoncPath)) {
15868
+ const jsoncPath = join7(configDir, "opencode.jsonc");
15869
+ const jsonPath = join7(configDir, "opencode.json");
15870
+ if (existsSync9(jsoncPath)) {
15908
15871
  opencodeConfig = jsoncPath;
15909
15872
  opencodeConfigFormat = "jsonc";
15910
- } else if (existsSync10(jsonPath)) {
15873
+ } else if (existsSync9(jsonPath)) {
15911
15874
  opencodeConfig = jsonPath;
15912
15875
  opencodeConfigFormat = "json";
15913
15876
  } else {
15914
15877
  opencodeConfig = jsoncPath;
15915
15878
  opencodeConfigFormat = "none";
15916
15879
  }
15917
- const tuiJsoncPath = join8(configDir, "tui.jsonc");
15918
- const tuiJsonPath = join8(configDir, "tui.json");
15919
- if (existsSync10(tuiJsoncPath)) {
15880
+ const tuiJsoncPath = join7(configDir, "tui.jsonc");
15881
+ const tuiJsonPath = join7(configDir, "tui.json");
15882
+ if (existsSync9(tuiJsoncPath)) {
15920
15883
  tuiConfig = tuiJsoncPath;
15921
15884
  tuiConfigFormat = "jsonc";
15922
- } else if (existsSync10(tuiJsonPath)) {
15885
+ } else if (existsSync9(tuiJsonPath)) {
15923
15886
  tuiConfig = tuiJsonPath;
15924
15887
  tuiConfigFormat = "json";
15925
15888
  } else {
@@ -15944,31 +15907,31 @@ function getPiAgentDir() {
15944
15907
  const envDir = process.env.PI_CODING_AGENT_DIR?.trim();
15945
15908
  if (envDir)
15946
15909
  return envDir;
15947
- return join8(envFirstHomeDir(), ".pi", "agent");
15910
+ return join7(envFirstHomeDir(), ".pi", "agent");
15948
15911
  }
15949
15912
  function getPiAgentConfigDir() {
15950
15913
  return getPiAgentDir();
15951
15914
  }
15952
15915
  function getPiSessionsRoot() {
15953
- return join8(getPiAgentDir(), "sessions");
15916
+ return join7(getPiAgentDir(), "sessions");
15954
15917
  }
15955
15918
  function getPiCacheRoot() {
15956
- return join8(dirname8(getPiAgentDir()), "cache");
15919
+ return join7(dirname8(getPiAgentDir()), "cache");
15957
15920
  }
15958
15921
  function getPiUserConfigPath() {
15959
15922
  return resolveCortexKitUserConfigPath();
15960
15923
  }
15961
15924
  function getPiUserExtensionsPath() {
15962
- return join8(getPiAgentConfigDir(), "settings.json");
15925
+ return join7(getPiAgentConfigDir(), "settings.json");
15963
15926
  }
15964
15927
  function resolveOmpPaths() {
15965
15928
  const rawProfile = process.env.OMP_PROFILE ?? process.env.PI_PROFILE;
15966
15929
  const normalizedProfile = rawProfile?.trim();
15967
15930
  const profile = normalizedProfile && normalizedProfile !== "default" && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(normalizedProfile) ? normalizedProfile : undefined;
15968
15931
  const configDirName = process.env.PI_CONFIG_DIR?.trim() || ".omp";
15969
- const baseConfigRoot = join8(envFirstHomeDir(), configDirName);
15970
- const configRoot = profile ? join8(baseConfigRoot, "profiles", profile) : baseConfigRoot;
15971
- const defaultAgentDir = join8(configRoot, "agent");
15932
+ const baseConfigRoot = join7(envFirstHomeDir(), configDirName);
15933
+ const configRoot = profile ? join7(baseConfigRoot, "profiles", profile) : baseConfigRoot;
15934
+ const defaultAgentDir = join7(configRoot, "agent");
15972
15935
  const override = profile ? undefined : process.env.PI_CODING_AGENT_DIR?.trim();
15973
15936
  const agentDir = override ? resolve3(override) : defaultAgentDir;
15974
15937
  const canUseXdg = (process.platform === "linux" || process.platform === "darwin") && agentDir === defaultAgentDir;
@@ -15976,9 +15939,9 @@ function resolveOmpPaths() {
15976
15939
  if (canUseXdg) {
15977
15940
  const xdgDataHome = process.env.XDG_DATA_HOME?.trim();
15978
15941
  if (xdgDataHome) {
15979
- const appRoot = join8(xdgDataHome, "omp");
15980
- const candidate = profile ? join8(appRoot, "profiles", profile) : appRoot;
15981
- if (existsSync10(candidate))
15942
+ const appRoot = join7(xdgDataHome, "omp");
15943
+ const candidate = profile ? join7(appRoot, "profiles", profile) : appRoot;
15944
+ if (existsSync9(candidate))
15982
15945
  dataRoot = candidate;
15983
15946
  }
15984
15947
  }
@@ -15988,8 +15951,8 @@ function resolveOmpPaths() {
15988
15951
  agentDir,
15989
15952
  dataRoot,
15990
15953
  dataAgentRoot,
15991
- pluginsDir: join8(dataRoot, "plugins"),
15992
- sessionsRoot: join8(dataAgentRoot, "sessions")
15954
+ pluginsDir: join7(dataRoot, "plugins"),
15955
+ sessionsRoot: join7(dataAgentRoot, "sessions")
15993
15956
  };
15994
15957
  }
15995
15958
  function getOmpAgentDir() {
@@ -15999,7 +15962,7 @@ function getOmpSessionsRoot() {
15999
15962
  return resolveOmpPaths().sessionsRoot;
16000
15963
  }
16001
15964
  function getOmpConfigPath() {
16002
- return join8(resolveOmpPaths().agentDir, "config.yml");
15965
+ return join7(resolveOmpPaths().agentDir, "config.yml");
16003
15966
  }
16004
15967
  function getOmpPackageDir() {
16005
15968
  const value = process.env.PI_PACKAGE_DIR?.trim();
@@ -16015,7 +15978,7 @@ function getOmpPackageDir() {
16015
15978
  function getOmpNonGlobalConfigSources(cwd = process.cwd()) {
16016
15979
  const sources = getOmpConfigOverlayPaths(cwd);
16017
15980
  const projectConfig = resolve3(cwd, ".omp", "config.yml");
16018
- if (existsSync10(projectConfig))
15981
+ if (existsSync9(projectConfig))
16019
15982
  sources.push(projectConfig);
16020
15983
  return [...new Set(sources)];
16021
15984
  }
@@ -16023,7 +15986,7 @@ function getOmpConfigOverlayPaths(cwd = process.cwd()) {
16023
15986
  return process.env.PI_CONFIG_FILES?.split(delimiter2).map((entry) => entry.trim()).filter(Boolean).map((entry) => {
16024
15987
  if (entry === "~")
16025
15988
  return envFirstHomeDir();
16026
- const expanded = entry.startsWith("~/") || entry.startsWith("~\\") ? join8(envFirstHomeDir(), entry.slice(2)) : entry;
15989
+ const expanded = entry.startsWith("~/") || entry.startsWith("~\\") ? join7(envFirstHomeDir(), entry.slice(2)) : entry;
16027
15990
  return resolve3(cwd, expanded);
16028
15991
  }) ?? [];
16029
15992
  }
@@ -16031,7 +15994,7 @@ function getOmpPluginsDir() {
16031
15994
  return resolveOmpPaths().pluginsDir;
16032
15995
  }
16033
15996
  function getOmpPluginsLockPath() {
16034
- return join8(resolveOmpPaths().pluginsDir, "omp-plugins.lock.json");
15997
+ return join7(resolveOmpPaths().pluginsDir, "omp-plugins.lock.json");
16035
15998
  }
16036
15999
  function getOmpUserConfigPath() {
16037
16000
  return resolveCortexKitUserConfigPath();
@@ -16043,12 +16006,12 @@ function getMagicContextHistorianDir2(harness) {
16043
16006
  return getMagicContextHistorianDir(harness);
16044
16007
  }
16045
16008
  function getOpenCodePluginCacheDir() {
16046
- const xdg = process.env.XDG_CACHE_HOME || join8(homedir7(), ".cache");
16047
- return join8(xdg, "opencode", "packages");
16009
+ const xdg = process.env.XDG_CACHE_HOME || join7(homedir7(), ".cache");
16010
+ return join7(xdg, "opencode", "packages");
16048
16011
  }
16049
16012
  function getOpenCodeV2NpmCacheDir() {
16050
- const xdg = process.env.XDG_CACHE_HOME || join8(homedir7(), ".cache");
16051
- return join8(xdg, "opencode", "npm");
16013
+ const xdg = process.env.XDG_CACHE_HOME || join7(homedir7(), ".cache");
16014
+ return join7(xdg, "opencode", "npm");
16052
16015
  }
16053
16016
  function isDir(path) {
16054
16017
  try {
@@ -16069,7 +16032,7 @@ function dirSizeBytes(path) {
16069
16032
  try {
16070
16033
  const entries = readdirSync2(cur, { withFileTypes: true });
16071
16034
  for (const entry of entries) {
16072
- const child = join8(cur, entry.name);
16035
+ const child = join7(cur, entry.name);
16073
16036
  if (entry.isDirectory()) {
16074
16037
  stack.push(child);
16075
16038
  } else if (entry.isFile()) {
@@ -16090,7 +16053,7 @@ var init_paths = __esm(() => {
16090
16053
  // src/lib/pi-helpers.ts
16091
16054
  import { execFileSync, spawnSync } from "node:child_process";
16092
16055
  import { homedir as homedir8 } from "node:os";
16093
- import { extname, join as join9 } from "node:path";
16056
+ import { extname, join as join8 } from "node:path";
16094
16057
  function getPiCommandInvocation(piPath, args) {
16095
16058
  const extension = extname(piPath).toLowerCase();
16096
16059
  if (extension !== ".cmd" && extension !== ".bat") {
@@ -16104,7 +16067,7 @@ function detectPiBinary() {
16104
16067
  if (fromPath)
16105
16068
  return { path: fromPath, source: "path" };
16106
16069
  const home = process.env.HOME?.trim() || homedir8();
16107
- const homeCandidate = process.platform === "win32" ? join9(home, ".pi", "bin", "pi.cmd") : join9(home, ".pi", "bin", "pi");
16070
+ const homeCandidate = process.platform === "win32" ? join8(home, ".pi", "bin", "pi.cmd") : join8(home, ".pi", "bin", "pi");
16108
16071
  if (isExecutableFile(homeCandidate))
16109
16072
  return { path: homeCandidate, source: "home" };
16110
16073
  return null;
@@ -16193,9 +16156,9 @@ var init_pi_helpers = __esm(() => {
16193
16156
 
16194
16157
  // src/lib/omp-helpers.ts
16195
16158
  import { spawnSync as spawnSync2 } from "node:child_process";
16196
- import { existsSync as existsSync11, readFileSync as readFileSync8 } from "node:fs";
16159
+ import { existsSync as existsSync10, readFileSync as readFileSync7 } from "node:fs";
16197
16160
  import { homedir as homedir9 } from "node:os";
16198
- import { extname as extname2, join as join10 } from "node:path";
16161
+ import { extname as extname2, join as join9 } from "node:path";
16199
16162
  function detectOmpPackageCli() {
16200
16163
  const packageDir = getOmpPackageDir();
16201
16164
  if (!packageDir)
@@ -16203,11 +16166,11 @@ function detectOmpPackageCli() {
16203
16166
  if (!findOnPath("bun"))
16204
16167
  return null;
16205
16168
  try {
16206
- const manifest = JSON.parse(readFileSync8(join10(packageDir, "package.json"), "utf-8"));
16169
+ const manifest = JSON.parse(readFileSync7(join9(packageDir, "package.json"), "utf-8"));
16207
16170
  if (manifest.name !== "@oh-my-pi/pi-coding-agent")
16208
16171
  return null;
16209
- const cli = join10(packageDir, "dist", "cli.js");
16210
- return existsSync11(cli) ? cli : null;
16172
+ const cli = join9(packageDir, "dist", "cli.js");
16173
+ return existsSync10(cli) ? cli : null;
16211
16174
  } catch {
16212
16175
  return null;
16213
16176
  }
@@ -16222,13 +16185,13 @@ function getOmpCommandInvocation(ompPath, args) {
16222
16185
  }
16223
16186
  function getOmpFallbackCandidates(platform, home, appData) {
16224
16187
  if (platform !== "win32") {
16225
- return [join10(home, ".bun", "bin", "omp"), join10(home, ".local", "bin", "omp")];
16188
+ return [join9(home, ".bun", "bin", "omp"), join9(home, ".local", "bin", "omp")];
16226
16189
  }
16227
16190
  const npmRoot = appData?.trim();
16228
16191
  return [
16229
- ...npmRoot ? [join10(npmRoot, "npm", "omp.cmd"), join10(npmRoot, "npm", "omp.exe")] : [],
16230
- join10(home, ".bun", "bin", "omp.exe"),
16231
- join10(home, ".bun", "bin", "omp.cmd")
16192
+ ...npmRoot ? [join9(npmRoot, "npm", "omp.cmd"), join9(npmRoot, "npm", "omp.exe")] : [],
16193
+ join9(home, ".bun", "bin", "omp.exe"),
16194
+ join9(home, ".bun", "bin", "omp.cmd")
16232
16195
  ];
16233
16196
  }
16234
16197
  function detectOmpBinary() {
@@ -16351,8 +16314,8 @@ var init_omp_helpers = __esm(() => {
16351
16314
  });
16352
16315
 
16353
16316
  // src/adapters/omp.ts
16354
- import { existsSync as existsSync12, readFileSync as readFileSync9 } from "node:fs";
16355
- import { join as join11 } from "node:path";
16317
+ import { existsSync as existsSync11, readFileSync as readFileSync8 } from "node:fs";
16318
+ import { join as join10 } from "node:path";
16356
16319
 
16357
16320
  class OmpAdapter {
16358
16321
  kind = "omp";
@@ -16452,8 +16415,8 @@ class OmpAdapter {
16452
16415
  return "Install OMP: https://omp.sh (npm: @oh-my-pi/pi-coding-agent)";
16453
16416
  }
16454
16417
  getPluginCacheInfo() {
16455
- const path = join11(getOmpPluginsDir(), "cache");
16456
- return [{ path, exists: existsSync12(path), sizeBytes: dirSizeBytes(path) }];
16418
+ const path = join10(getOmpPluginsDir(), "cache");
16419
+ return [{ path, exists: existsSync11(path), sizeBytes: dirSizeBytes(path) }];
16457
16420
  }
16458
16421
  getLogPath() {
16459
16422
  return getMagicContextLogPath2("omp");
@@ -16466,7 +16429,7 @@ class OmpAdapter {
16466
16429
  }
16467
16430
  readRuntimeEnabled(configPath) {
16468
16431
  try {
16469
- const lock = JSON.parse(readFileSync9(configPath, "utf-8"));
16432
+ const lock = JSON.parse(readFileSync8(configPath, "utf-8"));
16470
16433
  const enabled = lock.plugins?.[OMP_PLUGIN_PACKAGE]?.enabled;
16471
16434
  return typeof enabled === "boolean" ? enabled : undefined;
16472
16435
  } catch {
@@ -16494,9 +16457,9 @@ var init_omp = __esm(() => {
16494
16457
  });
16495
16458
 
16496
16459
  // ../plugin/src/shared/opencode-db-path.ts
16497
- import { existsSync as existsSync13, readdirSync as readdirSync3, statSync as statSync8 } from "node:fs";
16460
+ import { existsSync as existsSync12, readdirSync as readdirSync3, statSync as statSync8 } from "node:fs";
16498
16461
  import { homedir as homedir10 } from "node:os";
16499
- import { isAbsolute as isAbsolute4, join as join12, resolve as resolve4 } from "node:path";
16462
+ import { isAbsolute as isAbsolute4, join as join11, resolve as resolve4 } from "node:path";
16500
16463
  function openCodeHostGenerationFromVersion(version) {
16501
16464
  const text = version ?? "";
16502
16465
  if (/(?:^|\s|v)0\.0\.0-(?:beta|dev)-/.test(text))
@@ -16505,7 +16468,7 @@ function openCodeHostGenerationFromVersion(version) {
16505
16468
  return Number.isFinite(major) && major >= 2 ? "v2" : "v1";
16506
16469
  }
16507
16470
  function openCodeDataDir(env = process.env, dataHome) {
16508
- return join12(dataHome ?? env.XDG_DATA_HOME ?? join12(homedir10(), ".local", "share"), "opencode");
16471
+ return join11(dataHome ?? env.XDG_DATA_HOME ?? join11(homedir10(), ".local", "share"), "opencode");
16509
16472
  }
16510
16473
  function environmentKey(dataDir, hostGeneration, channel, env) {
16511
16474
  return [
@@ -16517,7 +16480,7 @@ function environmentKey(dataDir, hostGeneration, channel, env) {
16517
16480
  ].join("\x00");
16518
16481
  }
16519
16482
  function channelPath(dataDir, channel) {
16520
- return ["latest", "beta", "prod"].includes(channel) ? join12(dataDir, "opencode.db") : join12(dataDir, `opencode-${channel}.db`);
16483
+ return ["latest", "beta", "prod"].includes(channel) ? join11(dataDir, "opencode.db") : join11(dataDir, `opencode-${channel}.db`);
16521
16484
  }
16522
16485
  function discoveredCandidateNames(dataDir) {
16523
16486
  const names = ["opencode.db", "opencode-local.db", "opencode-dev.db"];
@@ -16529,7 +16492,7 @@ function discoveredCandidateNames(dataDir) {
16529
16492
  }
16530
16493
  function discoverOpenCodeDb(dataDir) {
16531
16494
  const candidates = discoveredCandidateNames(dataDir).map((name, order) => {
16532
- const path = join12(dataDir, name);
16495
+ const path = join11(dataDir, name);
16533
16496
  try {
16534
16497
  const metadata = statSync8(path);
16535
16498
  return metadata.isFile() ? { path, order, mtimeMs: metadata.mtimeMs } : null;
@@ -16539,7 +16502,7 @@ function discoverOpenCodeDb(dataDir) {
16539
16502
  });
16540
16503
  const existing = candidates.filter((candidate) => candidate !== null).sort((left, right) => right.mtimeMs - left.mtimeMs || left.order - right.order)[0];
16541
16504
  if (!existing) {
16542
- return { path: join12(dataDir, "opencode.db"), source: "default", channel: null };
16505
+ return { path: join11(dataDir, "opencode.db"), source: "default", channel: null };
16543
16506
  }
16544
16507
  const name = existing.path.slice(dataDir.length + 1);
16545
16508
  const channel = name === "opencode.db" ? null : name.slice("opencode-".length, -".db".length) || null;
@@ -16552,14 +16515,14 @@ function resolveV1Fresh(dataDir, env = process.env) {
16552
16515
  return { path: explicit, source: "OPENCODE_DB", channel: null };
16553
16516
  }
16554
16517
  return {
16555
- path: isAbsolute4(explicit) ? explicit : join12(dataDir, explicit),
16518
+ path: isAbsolute4(explicit) ? explicit : join11(dataDir, explicit),
16556
16519
  source: "OPENCODE_DB",
16557
16520
  channel: null
16558
16521
  };
16559
16522
  }
16560
16523
  const disableChannelDb = env.OPENCODE_DISABLE_CHANNEL_DB;
16561
16524
  if (disableChannelDb === "1" || disableChannelDb === "true") {
16562
- return { path: join12(dataDir, "opencode.db"), source: "default", channel: null };
16525
+ return { path: join11(dataDir, "opencode.db"), source: "default", channel: null };
16563
16526
  }
16564
16527
  const channel = env.OPENCODE_CHANNEL;
16565
16528
  if (channel !== undefined && channel.length > 0) {
@@ -16593,7 +16556,7 @@ function resolveOpenCodeDbPath(hostGeneration = "v1", options = {}) {
16593
16556
  const dataDir = openCodeDataDir(env, options.dataHome);
16594
16557
  const channel = options.channel ?? env.OPENCODE_CHANNEL;
16595
16558
  const key = environmentKey(dataDir, hostGeneration, channel, env);
16596
- if (cachedResolution?.key === key && (!cachedResolution.existed || existsSync13(cachedResolution.resolution.path))) {
16559
+ if (cachedResolution?.key === key && (!cachedResolution.existed || existsSync12(cachedResolution.resolution.path))) {
16597
16560
  if (cachedResolution.existed)
16598
16561
  return cachedResolution.resolution;
16599
16562
  }
@@ -16601,7 +16564,7 @@ function resolveOpenCodeDbPath(hostGeneration = "v1", options = {}) {
16601
16564
  cachedResolution = {
16602
16565
  key,
16603
16566
  resolution,
16604
- existed: resolution.path !== ":memory:" && existsSync13(resolution.path)
16567
+ existed: resolution.path !== ":memory:" && existsSync12(resolution.path)
16605
16568
  };
16606
16569
  return resolution;
16607
16570
  }
@@ -16641,7 +16604,7 @@ function assertOpenCodeStoreGeneration(db, expected, path, schema = "main") {
16641
16604
  throw new Error(`OpenCode store generation mismatch at ${path}: expected ${expected}, found ${actual}; refusing generation-specific database access`);
16642
16605
  }
16643
16606
  function openCodeDbPathExists(resolution = resolveOpenCodeDbPath()) {
16644
- return resolution.path !== ":memory:" && existsSync13(resolution.path);
16607
+ return resolution.path !== ":memory:" && existsSync12(resolution.path);
16645
16608
  }
16646
16609
  function getOpenCodeDbProbeDescriptions(resolution = resolveOpenCodeDbPath()) {
16647
16610
  if (resolution.source === "OPENCODE_DB")
@@ -16651,10 +16614,10 @@ function getOpenCodeDbProbeDescriptions(resolution = resolveOpenCodeDbPath()) {
16651
16614
  }
16652
16615
  const dataDir = openCodeDataDir();
16653
16616
  return [
16654
- join12(dataDir, "opencode.db"),
16655
- join12(dataDir, "opencode-local.db"),
16656
- join12(dataDir, "opencode-dev.db"),
16657
- join12(dataDir, "opencode-<channel>.db")
16617
+ join11(dataDir, "opencode.db"),
16618
+ join11(dataDir, "opencode-local.db"),
16619
+ join11(dataDir, "opencode-dev.db"),
16620
+ join11(dataDir, "opencode-<channel>.db")
16658
16621
  ];
16659
16622
  }
16660
16623
  function lookedForText(resolution) {
@@ -24560,7 +24523,7 @@ var init_project_directory_key = () => {};
24560
24523
 
24561
24524
  // ../plugin/src/shared/rpc-utils.ts
24562
24525
  import { execFile as execFile2, execFileSync as execFileSync2 } from "node:child_process";
24563
- import { readFileSync as readFileSync10 } from "node:fs";
24526
+ import { readFileSync as readFileSync9 } from "node:fs";
24564
24527
  function isOwnRpcServerRecord(record) {
24565
24528
  return record.pid === process.pid && record.instance_id !== undefined && ownRpcServerInstanceIds.has(record.instance_id);
24566
24529
  }
@@ -25155,7 +25118,7 @@ var init_rpc_utils = __esm(() => {
25155
25118
  "cljs/dist",
25156
25119
  "dist/bundle/cli"
25157
25120
  ];
25158
- rpcIdentityReadFileSync = readFileSync10;
25121
+ rpcIdentityReadFileSync = readFileSync9;
25159
25122
  rpcIdentityExecFileSync = execFileSync2;
25160
25123
  rpcIdentityProcessKill = process.kill;
25161
25124
  rpcProcessListExecFileSync = execFileSync2;
@@ -25196,23 +25159,23 @@ var init_opencode_plugin_registration = __esm(() => {
25196
25159
  });
25197
25160
 
25198
25161
  // src/lib/opencode-plugin-cache.ts
25199
- import { readdirSync as readdirSync4, readFileSync as readFileSync11 } from "node:fs";
25200
- import { join as join13 } from "node:path";
25162
+ import { readdirSync as readdirSync4, readFileSync as readFileSync10 } from "node:fs";
25163
+ import { join as join12 } from "node:path";
25201
25164
  function getOpenCodePluginCacheRoots() {
25202
25165
  const cacheDir = getOpenCodePluginCacheDir();
25203
25166
  return [
25204
- join13(cacheDir, OPENCODE_PLUGIN_ENTRY_WITH_VERSION),
25205
- join13(cacheDir, OPENCODE_PLUGIN_NAME)
25167
+ join12(cacheDir, OPENCODE_PLUGIN_ENTRY_WITH_VERSION),
25168
+ join12(cacheDir, OPENCODE_PLUGIN_NAME)
25206
25169
  ];
25207
25170
  }
25208
25171
  function getOpenCodePluginPackageJsonPath(pluginCacheRoot) {
25209
- return join13(pluginCacheRoot, "node_modules", ...OPENCODE_PLUGIN_NAME.split("/"), "package.json");
25172
+ return join12(pluginCacheRoot, "node_modules", ...OPENCODE_PLUGIN_NAME.split("/"), "package.json");
25210
25173
  }
25211
25174
  function getOpenCodePluginPackageJsonPaths() {
25212
25175
  return getOpenCodePluginCacheRoots().map(getOpenCodePluginPackageJsonPath);
25213
25176
  }
25214
25177
  function getOpenCodeV2PluginCacheSlot(npmCacheDir = getOpenCodeV2NpmCacheDir(), spec = "latest") {
25215
- return join13(npmCacheDir, ...`${OPENCODE_PLUGIN_NAME}@${spec}`.split("/"));
25178
+ return join12(npmCacheDir, ...`${OPENCODE_PLUGIN_NAME}@${spec}`.split("/"));
25216
25179
  }
25217
25180
  function openCodeV2PluginSpecOf(specifier) {
25218
25181
  if (specifier === OPENCODE_PLUGIN_NAME)
@@ -25265,7 +25228,7 @@ function pluginEntrySpecifier(entry) {
25265
25228
  }
25266
25229
  function listOpenCodeV2PluginCacheSlots(npmCacheDir = getOpenCodeV2NpmCacheDir()) {
25267
25230
  const [scope = "", name = ""] = OPENCODE_PLUGIN_NAME.split("/");
25268
- const scopeDir = join13(npmCacheDir, scope);
25231
+ const scopeDir = join12(npmCacheDir, scope);
25269
25232
  let names;
25270
25233
  try {
25271
25234
  names = readdirSync4(scopeDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name.startsWith(`${name}@`)).map((entry) => entry.name);
@@ -25273,7 +25236,7 @@ function listOpenCodeV2PluginCacheSlots(npmCacheDir = getOpenCodeV2NpmCacheDir()
25273
25236
  return [];
25274
25237
  }
25275
25238
  return names.map((dirName) => {
25276
- const slot = join13(scopeDir, dirName);
25239
+ const slot = join12(scopeDir, dirName);
25277
25240
  return {
25278
25241
  spec: dirName.slice(name.length + 1),
25279
25242
  slot,
@@ -25289,7 +25252,7 @@ function getOpenCodeV2ActiveGeneration(slot) {
25289
25252
  try {
25290
25253
  const generations = readdirSync4(slot, { withFileTypes: true }).filter((entry) => entry.isDirectory() && /^\d+$/.test(entry.name)).map((entry) => entry.name).sort((a, b) => Number(a) - Number(b));
25291
25254
  const newest = generations.at(-1);
25292
- return newest === undefined ? undefined : join13(slot, newest);
25255
+ return newest === undefined ? undefined : join12(slot, newest);
25293
25256
  } catch {
25294
25257
  return;
25295
25258
  }
@@ -25322,7 +25285,7 @@ function readOpenCodeV2CachedPluginVersion(slot) {
25322
25285
  if (!generation)
25323
25286
  return;
25324
25287
  try {
25325
- const pkg = JSON.parse(readFileSync11(getOpenCodePluginPackageJsonPath(generation), "utf-8"));
25288
+ const pkg = JSON.parse(readFileSync10(getOpenCodePluginPackageJsonPath(generation), "utf-8"));
25326
25289
  return typeof pkg.version === "string" ? pkg.version : undefined;
25327
25290
  } catch {
25328
25291
  return;
@@ -25336,7 +25299,7 @@ var init_opencode_plugin_cache = __esm(() => {
25336
25299
  });
25337
25300
 
25338
25301
  // src/commands/doctor-windows-holders.ts
25339
- import { existsSync as existsSync14 } from "node:fs";
25302
+ import { existsSync as existsSync13 } from "node:fs";
25340
25303
  function fileName(path) {
25341
25304
  return path.toLowerCase().replaceAll("\\", "/").split("/").at(-1) ?? "";
25342
25305
  }
@@ -25429,7 +25392,7 @@ function assertWindowsStoresClosed(paths, processes) {
25429
25392
  if (blockers.length)
25430
25393
  throw new Error(`OpenCode, Pi or ck-mc process is running (${blockers.map(({ pid, imageName, commandLine }) => `${imageName ?? commandLine} PID ${pid}`).join(", ")})`);
25431
25394
  for (const path of [...new Set(paths)]) {
25432
- if (!existsSync14(path))
25395
+ if (!existsSync13(path))
25433
25396
  continue;
25434
25397
  let db;
25435
25398
  let locked = false;
@@ -25536,7 +25499,7 @@ var init_doctor_windows_holders = __esm(async () => {
25536
25499
 
25537
25500
  // src/commands/doctor-opencode2-cache.ts
25538
25501
  import { spawnSync as spawnSync3 } from "node:child_process";
25539
- import { existsSync as existsSync15, rmSync as rmSync4 } from "node:fs";
25502
+ import { existsSync as existsSync14, rmSync as rmSync4 } from "node:fs";
25540
25503
  function runLsof(args, spawn) {
25541
25504
  const result = spawn("lsof", args, { encoding: "utf-8", timeout: 15000, windowsHide: true });
25542
25505
  if (result.error)
@@ -25551,7 +25514,7 @@ function probeHostProcessesUsing(targets, spawn = spawnSync3) {
25551
25514
  if (process.platform === "win32") {
25552
25515
  try {
25553
25516
  assertWindowsStoresClosed(targets.files.filter((path) => !/-(?:wal|shm)$/.test(path)), inspectWindowsProcessesSync());
25554
- if (targets.directories.some(existsSync15))
25517
+ if (targets.directories.some(existsSync14))
25555
25518
  return {
25556
25519
  status: "unknown",
25557
25520
  reason: "Windows cannot rule out open files in plugin cache directories"
@@ -25564,8 +25527,8 @@ function probeHostProcessesUsing(targets, spawn = spawnSync3) {
25564
25527
  };
25565
25528
  }
25566
25529
  }
25567
- const files = targets.files.filter((file) => existsSync15(file));
25568
- const directories = targets.directories.filter((directory) => existsSync15(directory));
25530
+ const files = targets.files.filter((file) => existsSync14(file));
25531
+ const directories = targets.directories.filter((directory) => existsSync14(directory));
25569
25532
  const queries = [];
25570
25533
  if (files.length > 0)
25571
25534
  queries.push(["-w", "-t", "--", ...files]);
@@ -25660,9 +25623,9 @@ function checkOpenCodeV2PluginCache(options, deps = {}) {
25660
25623
  const slot = deps.slot ?? getOpenCodeV2PluginCacheSlot(undefined, distTag ?? "latest");
25661
25624
  const tagged = distTag ? { distTag } : {};
25662
25625
  if (options.referencedSpecs !== undefined && !options.referencedSpecs.has(distTag ?? "latest")) {
25663
- return existsSync15(slot) ? { action: "unused", slot, cached: readOpenCodeV2CachedPluginVersion(slot), ...tagged } : { action: "not_found", slot, unused: true, ...tagged };
25626
+ return existsSync14(slot) ? { action: "unused", slot, cached: readOpenCodeV2CachedPluginVersion(slot), ...tagged } : { action: "not_found", slot, unused: true, ...tagged };
25664
25627
  }
25665
- if (!existsSync15(slot))
25628
+ if (!existsSync14(slot))
25666
25629
  return { action: "not_found", slot, ...tagged };
25667
25630
  const cached = readOpenCodeV2CachedPluginVersion(slot);
25668
25631
  const latest = options.latestVersion ?? undefined;
@@ -25801,7 +25764,7 @@ var init_atomic_write = __esm(() => {
25801
25764
  });
25802
25765
 
25803
25766
  // src/lib/jsonc-config.ts
25804
- import { existsSync as existsSync16, readFileSync as readFileSync12 } from "node:fs";
25767
+ import { existsSync as existsSync15, readFileSync as readFileSync11 } from "node:fs";
25805
25768
  function parseErrorLocation(content, error) {
25806
25769
  const lines = content.split(`
25807
25770
  `);
@@ -25817,9 +25780,9 @@ function parseErrorLocation(content, error) {
25817
25780
  return { line: messageLine ? Number.parseInt(messageLine, 10) : 1, column: 1 };
25818
25781
  }
25819
25782
  function readJsoncConfig(path) {
25820
- if (!existsSync16(path))
25783
+ if (!existsSync15(path))
25821
25784
  return { kind: "missing" };
25822
- const content = readFileSync12(path, "utf-8");
25785
+ const content = readFileSync11(path, "utf-8");
25823
25786
  try {
25824
25787
  const rejectedKeyPaths = [];
25825
25788
  const parsed = sanitizeParsedJson(import_comment_json.parse(content), {
@@ -25845,7 +25808,7 @@ function readJsoncConfigForUpdate(path) {
25845
25808
  return result.value;
25846
25809
  }
25847
25810
  function readJsoncTextForEdit(configPath) {
25848
- const raw = readFileSync12(configPath, "utf-8");
25811
+ const raw = readFileSync11(configPath, "utf-8");
25849
25812
  return raw.startsWith(BYTE_ORDER_MARK) ? { bom: BYTE_ORDER_MARK, text: raw.slice(BYTE_ORDER_MARK.length) } : { bom: "", text: raw };
25850
25813
  }
25851
25814
  function assertJsoncConfigsParseable(paths) {
@@ -25934,13 +25897,13 @@ var init_jsonc_config = __esm(() => {
25934
25897
  });
25935
25898
 
25936
25899
  // src/lib/opencode-detect.ts
25937
- import { existsSync as existsSync17, realpathSync as realpathSync3 } from "node:fs";
25900
+ import { existsSync as existsSync16, realpathSync as realpathSync3 } from "node:fs";
25938
25901
  import { homedir as homedir11 } from "node:os";
25939
- import { join as join14 } from "node:path";
25902
+ import { join as join13 } from "node:path";
25940
25903
  function defaultDeps(overrides = {}) {
25941
25904
  const env = overrides.env ?? process.env;
25942
25905
  return {
25943
- exists: overrides.exists ?? existsSync17,
25906
+ exists: overrides.exists ?? existsSync16,
25944
25907
  isExecutable: overrides.isExecutable ?? isExecutableFile,
25945
25908
  home: overrides.home ?? (env.HOME?.trim() || homedir11()),
25946
25909
  platform: overrides.platform ?? process.platform,
@@ -25950,7 +25913,7 @@ function defaultDeps(overrides = {}) {
25950
25913
  };
25951
25914
  }
25952
25915
  function stockCliBinary(d) {
25953
- return d.platform === "win32" ? join14(d.home, ".opencode", "bin", "opencode.exe") : join14(d.home, ".opencode", "bin", "opencode");
25916
+ return d.platform === "win32" ? join13(d.home, ".opencode", "bin", "opencode.exe") : join13(d.home, ".opencode", "bin", "opencode");
25954
25917
  }
25955
25918
  function extraCliCandidates(d) {
25956
25919
  if (d.platform === "win32") {
@@ -25959,25 +25922,25 @@ function extraCliCandidates(d) {
25959
25922
  const userprofile = d.env.USERPROFILE ?? d.home;
25960
25923
  const out = [];
25961
25924
  if (appdata) {
25962
- out.push(join14(appdata, "npm", "opencode.cmd"));
25963
- out.push(join14(appdata, "npm", "opencode.exe"));
25925
+ out.push(join13(appdata, "npm", "opencode.cmd"));
25926
+ out.push(join13(appdata, "npm", "opencode.exe"));
25964
25927
  }
25965
25928
  if (localappdata) {
25966
- out.push(join14(localappdata, "Microsoft", "WinGet", "Links", "opencode.exe"));
25967
- out.push(join14(localappdata, "opencode", "bin", "opencode.exe"));
25929
+ out.push(join13(localappdata, "Microsoft", "WinGet", "Links", "opencode.exe"));
25930
+ out.push(join13(localappdata, "opencode", "bin", "opencode.exe"));
25968
25931
  }
25969
25932
  if (userprofile) {
25970
- out.push(join14(userprofile, "scoop", "shims", "opencode.exe"));
25933
+ out.push(join13(userprofile, "scoop", "shims", "opencode.exe"));
25971
25934
  }
25972
25935
  return out;
25973
25936
  }
25974
25937
  return [
25975
25938
  "/usr/local/bin/opencode",
25976
25939
  "/opt/homebrew/bin/opencode",
25977
- join14(d.home, ".local", "bin", "opencode"),
25978
- join14(d.home, ".local", "share", "mise", "shims", "opencode"),
25979
- join14(d.home, ".asdf", "shims", "opencode"),
25980
- join14(d.home, ".volta", "bin", "opencode")
25940
+ join13(d.home, ".local", "bin", "opencode"),
25941
+ join13(d.home, ".local", "share", "mise", "shims", "opencode"),
25942
+ join13(d.home, ".asdf", "shims", "opencode"),
25943
+ join13(d.home, ".volta", "bin", "opencode")
25981
25944
  ];
25982
25945
  }
25983
25946
  function openChamberCliCandidates(d) {
@@ -25985,8 +25948,8 @@ function openChamberCliCandidates(d) {
25985
25948
  return [];
25986
25949
  const bundled = ["Contents", "Resources", "opencode-cli", "opencode"];
25987
25950
  return [
25988
- join14("/Applications", "OpenChamber.app", ...bundled),
25989
- join14(d.home, "Applications", "OpenChamber.app", ...bundled)
25951
+ join13("/Applications", "OpenChamber.app", ...bundled),
25952
+ join13(d.home, "Applications", "OpenChamber.app", ...bundled)
25990
25953
  ];
25991
25954
  }
25992
25955
  function canonicalPath(d, path) {
@@ -26007,29 +25970,29 @@ function xdgConfigHome(d) {
26007
25970
  const xdg = d.env.XDG_CONFIG_HOME;
26008
25971
  if (xdg && xdg.length > 0)
26009
25972
  return xdg;
26010
- return join14(d.home, ".config");
25973
+ return join13(d.home, ".config");
26011
25974
  }
26012
25975
  function desktopUserDataDir(d, appId) {
26013
25976
  switch (d.platform) {
26014
25977
  case "darwin":
26015
- return join14(d.home, "Library", "Application Support", appId);
25978
+ return join13(d.home, "Library", "Application Support", appId);
26016
25979
  case "win32":
26017
- return join14(d.env.APPDATA ?? join14(d.home, "AppData", "Roaming"), appId);
25980
+ return join13(d.env.APPDATA ?? join13(d.home, "AppData", "Roaming"), appId);
26018
25981
  default:
26019
- return join14(xdgConfigHome(d), appId);
25982
+ return join13(xdgConfigHome(d), appId);
26020
25983
  }
26021
25984
  }
26022
25985
  function desktopAppPaths(d) {
26023
25986
  switch (d.platform) {
26024
25987
  case "darwin":
26025
- return ["/Applications/OpenCode.app", join14(d.home, "Applications", "OpenCode.app")];
25988
+ return ["/Applications/OpenCode.app", join13(d.home, "Applications", "OpenCode.app")];
26026
25989
  case "win32": {
26027
- const localappdata = d.env.LOCALAPPDATA ?? join14(d.home, "AppData", "Local");
26028
- return [join14(localappdata, "Programs", "OpenCode", "OpenCode.exe")];
25990
+ const localappdata = d.env.LOCALAPPDATA ?? join13(d.home, "AppData", "Local");
25991
+ return [join13(localappdata, "Programs", "OpenCode", "OpenCode.exe")];
26029
25992
  }
26030
25993
  default: {
26031
- const dataHome = d.env.XDG_DATA_HOME && d.env.XDG_DATA_HOME.length > 0 ? d.env.XDG_DATA_HOME : join14(d.home, ".local", "share");
26032
- return OPENCODE_DESKTOP_APP_IDS.map((appId) => join14(dataHome, "applications", `${appId}.desktop`));
25994
+ const dataHome = d.env.XDG_DATA_HOME && d.env.XDG_DATA_HOME.length > 0 ? d.env.XDG_DATA_HOME : join13(d.home, ".local", "share");
25995
+ return OPENCODE_DESKTOP_APP_IDS.map((appId) => join13(dataHome, "applications", `${appId}.desktop`));
26033
25996
  }
26034
25997
  }
26035
25998
  }
@@ -26056,7 +26019,7 @@ function detectOpenCodeInstallations(deps) {
26056
26019
  }
26057
26020
  }
26058
26021
  for (const appId of OPENCODE_DESKTOP_APP_IDS) {
26059
- const marker = join14(desktopUserDataDir(d, appId), OPENCODE_DESKTOP_SETTINGS_FILE);
26022
+ const marker = join13(desktopUserDataDir(d, appId), OPENCODE_DESKTOP_SETTINGS_FILE);
26060
26023
  if (d.exists(marker)) {
26061
26024
  addCandidate(installations, seenRealpaths, d, marker, "desktop", "desktop");
26062
26025
  }
@@ -26154,7 +26117,7 @@ var OPENCODE_BINARY_ENV = "MAGIC_CONTEXT_OPENCODE_BINARY", OPENCODE_VERSION_PROB
26154
26117
  var init_opencode_helpers = () => {};
26155
26118
 
26156
26119
  // src/adapters/opencode.ts
26157
- import { existsSync as existsSync18, readFileSync as readFileSync13, statSync as statSync10 } from "node:fs";
26120
+ import { existsSync as existsSync17, readFileSync as readFileSync12, statSync as statSync10 } from "node:fs";
26158
26121
  import { dirname as dirname10, isAbsolute as isAbsolute5, parse as parsePath, resolve as resolve6 } from "node:path";
26159
26122
  import { fileURLToPath as fileURLToPath2 } from "node:url";
26160
26123
 
@@ -26186,7 +26149,7 @@ class OpenCodeAdapter {
26186
26149
  if (paths.opencodeConfigFormat === "none")
26187
26150
  return false;
26188
26151
  try {
26189
- const raw = readFileSync13(paths.opencodeConfig, "utf-8");
26152
+ const raw = readFileSync12(paths.opencodeConfig, "utf-8");
26190
26153
  const cfg = import_comment_json2.parse(raw);
26191
26154
  return readPluginEntries(cfg).some(({ entry }) => matchesPluginEntry(entry, OPENCODE_PLUGIN_NAME));
26192
26155
  } catch {
@@ -26222,7 +26185,7 @@ class OpenCodeAdapter {
26222
26185
  configPath: target
26223
26186
  };
26224
26187
  }
26225
- const raw = readFileSync13(target, "utf-8");
26188
+ const raw = readFileSync12(target, "utf-8");
26226
26189
  const cfg = import_comment_json2.parse(raw);
26227
26190
  if (cfg === null || typeof cfg !== "object") {
26228
26191
  return {
@@ -26297,7 +26260,7 @@ class OpenCodeAdapter {
26297
26260
  };
26298
26261
  }
26299
26262
  try {
26300
- const raw = readFileSync13(target, "utf-8");
26263
+ const raw = readFileSync12(target, "utf-8");
26301
26264
  const cfg = import_comment_json2.parse(raw);
26302
26265
  if (cfg === null || typeof cfg !== "object") {
26303
26266
  return {
@@ -26348,9 +26311,9 @@ class OpenCodeAdapter {
26348
26311
  }
26349
26312
  getPluginCacheInfo() {
26350
26313
  const legacyPath = getOpenCodePluginCacheDir();
26351
- const legacyExists = existsSync18(legacyPath);
26314
+ const legacyExists = existsSync17(legacyPath);
26352
26315
  const slot = getOpenCodeV2PluginCacheSlot();
26353
- const slotExists = existsSync18(slot);
26316
+ const slotExists = existsSync17(slot);
26354
26317
  const caches = [];
26355
26318
  if (legacyExists || !slotExists) {
26356
26319
  caches.push({
@@ -26408,7 +26371,7 @@ class OpenCodeAdapter {
26408
26371
  if (paths.opencodeConfigFormat === "none")
26409
26372
  return "latest";
26410
26373
  try {
26411
- const cfg = import_comment_json2.parse(readFileSync13(paths.opencodeConfig, "utf-8"));
26374
+ const cfg = import_comment_json2.parse(readFileSync12(paths.opencodeConfig, "utf-8"));
26412
26375
  return readConfiguredOpenCodePluginSpec(cfg);
26413
26376
  } catch {
26414
26377
  return "latest";
@@ -26420,10 +26383,10 @@ class OpenCodeAdapter {
26420
26383
  return readOpenCodeV2CachedPluginVersion(slot) ?? null;
26421
26384
  }
26422
26385
  for (const candidate of getOpenCodePluginPackageJsonPaths()) {
26423
- if (!existsSync18(candidate))
26386
+ if (!existsSync17(candidate))
26424
26387
  continue;
26425
26388
  try {
26426
- const raw = readFileSync13(candidate, "utf-8");
26389
+ const raw = readFileSync12(candidate, "utf-8");
26427
26390
  const pkg = JSON.parse(raw);
26428
26391
  if (typeof pkg.version === "string")
26429
26392
  return pkg.version;
@@ -26466,8 +26429,8 @@ function isDevPathPluginEntry(entry, configDir) {
26466
26429
  const root = parsePath(localPath).root;
26467
26430
  while (localPath !== root) {
26468
26431
  const packagePath = resolve6(localPath, "package.json");
26469
- if (existsSync18(packagePath)) {
26470
- const pkg = JSON.parse(readFileSync13(packagePath, "utf8"));
26432
+ if (existsSync17(packagePath)) {
26433
+ const pkg = JSON.parse(readFileSync12(packagePath, "utf8"));
26471
26434
  return pkg.name === OPENCODE_PLUGIN_NAME;
26472
26435
  }
26473
26436
  localPath = dirname10(localPath);
@@ -26487,7 +26450,7 @@ function matchesPluginEntry(entry, pkgName) {
26487
26450
  }
26488
26451
  function ensureDir2(filePath) {
26489
26452
  const dir = dirname10(filePath);
26490
- if (!existsSync18(dir)) {
26453
+ if (!existsSync17(dir)) {
26491
26454
  const { mkdirSync } = __require("node:fs");
26492
26455
  mkdirSync(dir, { recursive: true });
26493
26456
  }
@@ -26508,8 +26471,8 @@ var init_opencode = __esm(async () => {
26508
26471
  });
26509
26472
 
26510
26473
  // src/lib/pi-package-entry.ts
26511
- import { existsSync as existsSync19, readFileSync as readFileSync14 } from "node:fs";
26512
- import { isAbsolute as isAbsolute6, join as join15 } from "node:path";
26474
+ import { existsSync as existsSync18, readFileSync as readFileSync13 } from "node:fs";
26475
+ import { isAbsolute as isAbsolute6, join as join14 } from "node:path";
26513
26476
  function stripNpmPrefix(value) {
26514
26477
  return value.startsWith("npm:") ? value.slice("npm:".length) : value;
26515
26478
  }
@@ -26564,11 +26527,11 @@ function hasPiMagicContextPackage(entries, agentDir = getPiAgentConfigDir()) {
26564
26527
  return entries.some((entry) => isConfiguredPiMagicContextEntry(entry, agentDir));
26565
26528
  }
26566
26529
  function isPiMagicContextPackageDir(dir) {
26567
- const packageJson = join15(dir, "package.json");
26568
- if (!existsSync19(packageJson))
26530
+ const packageJson = join14(dir, "package.json");
26531
+ if (!existsSync18(packageJson))
26569
26532
  return false;
26570
26533
  try {
26571
- const pkg = JSON.parse(readFileSync14(packageJson, "utf-8"));
26534
+ const pkg = JSON.parse(readFileSync13(packageJson, "utf-8"));
26572
26535
  return typeof pkg.name === "string" && pkg.name === PI_MAGIC_CONTEXT_PACKAGE_NAME;
26573
26536
  } catch {
26574
26537
  return false;
@@ -26580,7 +26543,7 @@ function localPiMagicContextPackageDir(entry, agentDir) {
26580
26543
  if (!spec || spec.startsWith("npm:"))
26581
26544
  return null;
26582
26545
  const path = spec.startsWith("file:") ? spec.slice("file:".length) : spec;
26583
- const dir = isAbsolute6(path) ? path : join15(agentDir, path);
26546
+ const dir = isAbsolute6(path) ? path : join14(agentDir, path);
26584
26547
  return isPiMagicContextPackageDir(dir) ? dir : null;
26585
26548
  }
26586
26549
  function isConfiguredPiMagicContextEntry(entry, agentDir) {
@@ -26604,7 +26567,7 @@ var init_pi_package_entry = __esm(() => {
26604
26567
  });
26605
26568
 
26606
26569
  // src/adapters/pi.ts
26607
- import { existsSync as existsSync20 } from "node:fs";
26570
+ import { existsSync as existsSync19 } from "node:fs";
26608
26571
  import { dirname as dirname11 } from "node:path";
26609
26572
 
26610
26573
  class PiAdapter {
@@ -26743,7 +26706,7 @@ function writePiSettings(settings) {
26743
26706
  }
26744
26707
  function ensureDir3(filePath) {
26745
26708
  const dir = dirname11(filePath);
26746
- if (!existsSync20(dir)) {
26709
+ if (!existsSync19(dir)) {
26747
26710
  const { mkdirSync } = __require("node:fs");
26748
26711
  mkdirSync(dir, { recursive: true });
26749
26712
  }
@@ -29851,7 +29814,7 @@ function installCompartmentHistoryVersions(db) {
29851
29814
 
29852
29815
  // ../plugin/src/features/magic-context/memory/project-identity-cache.ts
29853
29816
  import { createHash as createHash4 } from "node:crypto";
29854
- import { promises as fs2, readFileSync as readFileSync15 } from "node:fs";
29817
+ import { promises as fs2, readFileSync as readFileSync14 } from "node:fs";
29855
29818
  import path4 from "node:path";
29856
29819
  function cachePath(directory, storageDir = getMagicContextStorageDir()) {
29857
29820
  const hash = createHash4("sha256").update(projectDirectoryKey(directory)).digest("hex");
@@ -29865,7 +29828,7 @@ function rememberGitIdentity(directory, identity) {
29865
29828
  }
29866
29829
  function readRememberedGitIdentity(directory, storageDir) {
29867
29830
  try {
29868
- const record = JSON.parse(readFileSync15(cachePath(directory, storageDir), "utf8"));
29831
+ const record = JSON.parse(readFileSync14(cachePath(directory, storageDir), "utf8"));
29869
29832
  if (record.directory === projectDirectoryKey(directory) && /^git:[0-9a-f]{7,64}$/.test(record.identity))
29870
29833
  return record.identity;
29871
29834
  } catch {}
@@ -29878,7 +29841,7 @@ var init_project_identity_cache = __esm(() => {
29878
29841
  });
29879
29842
 
29880
29843
  // ../plugin/src/features/magic-context/memory/unborn-head.ts
29881
- import { readFileSync as readFileSync16, realpathSync as realpathSync4, statSync as statSync11 } from "node:fs";
29844
+ import { readFileSync as readFileSync15, realpathSync as realpathSync4, statSync as statSync11 } from "node:fs";
29882
29845
  import path5 from "node:path";
29883
29846
  function errorCode(error) {
29884
29847
  if (error === null || typeof error !== "object" || !("code" in error))
@@ -29888,7 +29851,7 @@ function errorCode(error) {
29888
29851
  }
29889
29852
  function readText(file) {
29890
29853
  try {
29891
- return { ok: true, text: readFileSync16(file, "utf8") };
29854
+ return { ok: true, text: readFileSync15(file, "utf8") };
29892
29855
  } catch (error) {
29893
29856
  return { ok: false, missing: errorCode(error) === "ENOENT" };
29894
29857
  }
@@ -30039,7 +30002,7 @@ var init_unborn_head = __esm(() => {
30039
30002
  // ../plugin/src/features/magic-context/memory/project-identity.ts
30040
30003
  import { execFileSync as execFileSync4 } from "node:child_process";
30041
30004
  import { createHash as createHash5 } from "node:crypto";
30042
- import { existsSync as existsSync21, realpathSync as realpathSync5, statSync as statSync12 } from "node:fs";
30005
+ import { existsSync as existsSync20, realpathSync as realpathSync5, statSync as statSync12 } from "node:fs";
30043
30006
  import { homedir as homedir12 } from "node:os";
30044
30007
  import path6 from "node:path";
30045
30008
  function asError(error) {
@@ -30223,7 +30186,7 @@ function nearestLastKnownGitIdentity(canonical) {
30223
30186
  const cached = lastKnownGitIdentity(current);
30224
30187
  if (cached !== undefined)
30225
30188
  return { identity: cached, source: current };
30226
- if (existsSync21(path6.join(current, ".git")))
30189
+ if (existsSync20(path6.join(current, ".git")))
30227
30190
  break;
30228
30191
  const parent = path6.dirname(current);
30229
30192
  if (parent === current)
@@ -30346,7 +30309,7 @@ function hasGitDir(canonical) {
30346
30309
  function gitRootInAncestorChain(startDirectory) {
30347
30310
  let current = startDirectory;
30348
30311
  while (true) {
30349
- if (existsSync21(path6.join(current, ".git"))) {
30312
+ if (existsSync20(path6.join(current, ".git"))) {
30350
30313
  try {
30351
30314
  return realpathSync5.native(current);
30352
30315
  } catch {
@@ -33818,7 +33781,7 @@ var init_tool_definition_tokens = __esm(() => {
33818
33781
  });
33819
33782
 
33820
33783
  // ../plugin/src/features/magic-context/tool-owner-backfill.ts
33821
- import { existsSync as existsSync22 } from "node:fs";
33784
+ import { existsSync as existsSync21 } from "node:fs";
33822
33785
  function resolveOpencodeDbPath() {
33823
33786
  return resolveOpenCodeDbPath().path;
33824
33787
  }
@@ -33855,7 +33818,7 @@ function runToolOwnerBackfill(db) {
33855
33818
  return result;
33856
33819
  }
33857
33820
  const opencodeDbPath = resolveOpencodeDbPath();
33858
- if (!existsSync22(opencodeDbPath)) {
33821
+ if (!existsSync21(opencodeDbPath)) {
33859
33822
  log(`[backfill] OpenCode DB not found at ${opencodeDbPath} — marking all unbackfilled sessions as skipped. Lazy adoption (defense-in-depth) handles legacy rows at runtime.`);
33860
33823
  markAllUnbackfilledSessionsSkipped(db);
33861
33824
  result.sessionsSkippedNoOcDb = countSessionsByStatus(db, "skipped");
@@ -36703,14 +36666,14 @@ var init_message_time_backfill = __esm(async () => {
36703
36666
 
36704
36667
  // ../plugin/src/features/magic-context/storage-db.ts
36705
36668
  import {
36706
- existsSync as existsSync23,
36669
+ existsSync as existsSync22,
36707
36670
  readdirSync as readdirSync5,
36708
- readFileSync as readFileSync17,
36671
+ readFileSync as readFileSync16,
36709
36672
  rmdirSync,
36710
36673
  statSync as statSync13,
36711
- unlinkSync as unlinkSync3
36674
+ unlinkSync as unlinkSync4
36712
36675
  } from "node:fs";
36713
- import { basename as basename4, dirname as dirname12, join as join16, resolve as resolve7 } from "node:path";
36676
+ import { basename as basename4, dirname as dirname12, join as join15, resolve as resolve7 } from "node:path";
36714
36677
  function ensureSecureStorageDir(dir) {
36715
36678
  ensureStorageDirectorySync(dir);
36716
36679
  }
@@ -36734,14 +36697,14 @@ function resolveDatabasePath(dbPathOverride) {
36734
36697
  return { dbDir: dirname12(dbPathOverride), dbPath: dbPathOverride };
36735
36698
  }
36736
36699
  const dbDir = getMagicContextStorageDir();
36737
- return { dbDir, dbPath: join16(dbDir, "context.db") };
36700
+ return { dbDir, dbPath: join15(dbDir, "context.db") };
36738
36701
  }
36739
36702
  function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
36740
- if (existsSync23(targetDbPath))
36703
+ if (existsSync22(targetDbPath))
36741
36704
  return;
36742
36705
  const legacyDir = getLegacyOpenCodeMagicContextStorageDir();
36743
- const legacyDbPath = join16(legacyDir, "context.db");
36744
- if (!existsSync23(legacyDbPath))
36706
+ const legacyDbPath = join15(legacyDir, "context.db");
36707
+ if (!existsSync22(legacyDbPath))
36745
36708
  return;
36746
36709
  log(`[magic-context] migrating legacy plugin storage: ${legacyDir} -> ${targetDbDir} (legacy left in place as backup)`);
36747
36710
  ensureSecureStorageDir(targetDbDir);
@@ -36758,8 +36721,8 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
36758
36721
  }
36759
36722
  for (const suffix of ["", "-wal", "-shm"]) {
36760
36723
  const src = `${legacyDbPath}${suffix}`;
36761
- const dst = join16(targetDbDir, `context.db${suffix}`);
36762
- if (existsSync23(src)) {
36724
+ const dst = join15(targetDbDir, `context.db${suffix}`);
36725
+ if (existsSync22(src)) {
36763
36726
  try {
36764
36727
  copyStorageFileSync(src, dst);
36765
36728
  } catch (error) {
@@ -36767,9 +36730,9 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
36767
36730
  }
36768
36731
  }
36769
36732
  }
36770
- const legacyModelsDir = join16(legacyDir, "models");
36771
- const targetModelsDir = join16(targetDbDir, "models");
36772
- if (existsSync23(legacyModelsDir) && !existsSync23(targetModelsDir)) {
36733
+ const legacyModelsDir = join15(legacyDir, "models");
36734
+ const targetModelsDir = join15(targetDbDir, "models");
36735
+ if (existsSync22(legacyModelsDir) && !existsSync22(targetModelsDir)) {
36773
36736
  try {
36774
36737
  copyStorageTreeSync(legacyModelsDir, targetModelsDir);
36775
36738
  } catch (error) {
@@ -36877,7 +36840,7 @@ function classifyJunkDiscovery(portFile, raw, staleFiles) {
36877
36840
  function inspectRpcServerDiscovery(storageDir, processes, options) {
36878
36841
  const deadline = options?.deadlineMs === undefined ? Number.POSITIVE_INFINITY : Date.now() + options.deadlineMs;
36879
36842
  let progressAt = Date.now() + 3000;
36880
- const rpcRoot = join16(storageDir, "rpc");
36843
+ const rpcRoot = join15(storageDir, "rpc");
36881
36844
  let projectEntries;
36882
36845
  try {
36883
36846
  projectEntries = rpcDiscoveryFs.readdirSync(rpcRoot, { withFileTypes: true });
@@ -36891,7 +36854,7 @@ function inspectRpcServerDiscovery(storageDir, processes, options) {
36891
36854
  for (const projectEntry of projectEntries) {
36892
36855
  if (!projectEntry.isDirectory())
36893
36856
  continue;
36894
- const projectDir = join16(rpcRoot, projectEntry.name);
36857
+ const projectDir = join15(rpcRoot, projectEntry.name);
36895
36858
  let entries;
36896
36859
  try {
36897
36860
  entries = rpcDiscoveryFs.readdirSync(projectDir);
@@ -36902,7 +36865,7 @@ function inspectRpcServerDiscovery(storageDir, processes, options) {
36902
36865
  }
36903
36866
  for (const entry of entries) {
36904
36867
  if (entry === "port" || entry.startsWith("port-") && entry.endsWith(".json")) {
36905
- portFiles.push(join16(projectDir, entry));
36868
+ portFiles.push(join15(projectDir, entry));
36906
36869
  }
36907
36870
  }
36908
36871
  }
@@ -37005,7 +36968,7 @@ function inspectRpcServerDiscovery(storageDir, processes, options) {
37005
36968
  return { state: "stale", serverPids: [], staleFiles };
37006
36969
  }
37007
36970
  function pruneEmptyRpcDiscoveryDirs(storageDir) {
37008
- const rpcRoot = join16(storageDir, "rpc");
36971
+ const rpcRoot = join15(storageDir, "rpc");
37009
36972
  let entries;
37010
36973
  try {
37011
36974
  entries = rpcDiscoveryFs.readdirSync(rpcRoot, { withFileTypes: true });
@@ -37017,7 +36980,7 @@ function pruneEmptyRpcDiscoveryDirs(storageDir) {
37017
36980
  for (const entry of entries) {
37018
36981
  if (!entry.isDirectory())
37019
36982
  continue;
37020
- const projectDir = join16(rpcRoot, entry.name);
36983
+ const projectDir = join15(rpcRoot, entry.name);
37021
36984
  try {
37022
36985
  if (rpcDiscoveryFs.readdirSync(projectDir).length > 0)
37023
36986
  continue;
@@ -37031,7 +36994,7 @@ function pruneEmptyRpcDiscoveryDirs(storageDir) {
37031
36994
  return removed;
37032
36995
  }
37033
36996
  function removeRpcDiscoveryRecords(storageDir, files) {
37034
- const rpcRoot = resolve7(join16(storageDir, "rpc"));
36997
+ const rpcRoot = resolve7(join15(storageDir, "rpc"));
37035
36998
  const removed = [];
37036
36999
  const failed = [];
37037
37000
  for (const file of files) {
@@ -37083,7 +37046,7 @@ function isDefaultSharedDatabasePath(dbPath) {
37083
37046
  if (!process.env.XDG_DATA_HOME && (process.env.MAGIC_CONTEXT_TEST_DATA_DIR || false)) {
37084
37047
  return false;
37085
37048
  }
37086
- return resolve7(dbPath) === resolve7(join16(getMagicContextStorageDir(), "context.db"));
37049
+ return resolve7(dbPath) === resolve7(join15(getMagicContextStorageDir(), "context.db"));
37087
37050
  }
37088
37051
  function migrationBlockingPiPids(dbPath, discovery, discoveredPiPids) {
37089
37052
  if (isDefaultSharedDatabasePath(dbPath))
@@ -37155,7 +37118,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
37155
37118
  return null;
37156
37119
  }
37157
37120
  healWedgedChannel2Claims(db);
37158
- if (!explicitDbPath) {
37121
+ if (!explicitDbPath && scheduleStartupMaintenanceOnOpen) {
37159
37122
  const readsOpenCodeStore = harnessOwnsOpenCodeStore();
37160
37123
  const state = { controller: new AbortController };
37161
37124
  startupBackfills.set(db, state);
@@ -37196,6 +37159,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
37196
37159
  log(`[magic-context] message-index backfill failed (will resume next startup): ${getErrorMessage(error)}`);
37197
37160
  });
37198
37161
  }));
37162
+ state.run = runBackfills;
37199
37163
  state.timer = scheduleAfterBootQuiet(runBackfills);
37200
37164
  }
37201
37165
  setDatabase(db);
@@ -38499,7 +38463,7 @@ function openDatabase(dbPathOrOptions) {
38499
38463
  }
38500
38464
  ensureSecureStorageDir(dbDir);
38501
38465
  tightenStorageTree(dbDir);
38502
- if (!existsSync23(dbPath) && shouldEnforcePrivateStoragePermissions()) {
38466
+ if (!existsSync22(dbPath) && shouldEnforcePrivateStoragePermissions()) {
38503
38467
  try {
38504
38468
  writeStorageFileSync(dbPath, new Uint8Array, { flag: "wx" });
38505
38469
  } catch (error) {
@@ -38566,7 +38530,7 @@ function closeDatabase() {
38566
38530
  }
38567
38531
  return Promise.all(pendingDatabaseCloses).then(() => {});
38568
38532
  }
38569
- var databases, pendingAsyncOpens, pendingDatabaseCloses, startupBackfills, persistenceByDatabase, persistenceErrorByDatabase, pathByDatabase, lastSchemaFenceRejection = null, lastMigrationOnOpenRefusal = null, lastUnconfirmedMigrationHolders = null, LATEST_SUPPORTED_VERSION = 95, BOOT_SQLITE_BUSY_TIMEOUT_MS = 5000, RPC_DISCOVERY_PARSE_GRACE_MS, defaultRpcDiscoveryFs, rpcDiscoveryFs, RPC_DISCOVERY_DIR_PRUNE_MIN_AGE_MS = 60000, sqlitePragmaConfig, CHANNEL2_CLAIM_TTL_MS, channel2HealStatements;
38533
+ var databases, pendingAsyncOpens, pendingDatabaseCloses, startupBackfills, scheduleStartupMaintenanceOnOpen = true, persistenceByDatabase, persistenceErrorByDatabase, pathByDatabase, lastSchemaFenceRejection = null, lastMigrationOnOpenRefusal = null, lastUnconfirmedMigrationHolders = null, LATEST_SUPPORTED_VERSION = 95, BOOT_SQLITE_BUSY_TIMEOUT_MS = 5000, RPC_DISCOVERY_PARSE_GRACE_MS, defaultRpcDiscoveryFs, rpcDiscoveryFs, RPC_DISCOVERY_DIR_PRUNE_MIN_AGE_MS = 60000, sqlitePragmaConfig, CHANNEL2_CLAIM_TTL_MS, channel2HealStatements;
38570
38534
  var init_storage_db = __esm(async () => {
38571
38535
  init_data_path();
38572
38536
  init_logger();
@@ -38601,9 +38565,9 @@ var init_storage_db = __esm(async () => {
38601
38565
  RPC_DISCOVERY_PARSE_GRACE_MS = 10 * 60 * 1000;
38602
38566
  defaultRpcDiscoveryFs = {
38603
38567
  readdirSync: (path, options) => options?.withFileTypes ? readdirSync5(path, { withFileTypes: true }) : readdirSync5(path),
38604
- readFileSync: (path, encoding) => String(readFileSync17(path, encoding)),
38568
+ readFileSync: (path, encoding) => String(readFileSync16(path, encoding)),
38605
38569
  statSync: (path) => ({ mtimeMs: statSync13(path).mtimeMs }),
38606
- unlinkSync: (path) => unlinkSync3(path),
38570
+ unlinkSync: (path) => unlinkSync4(path),
38607
38571
  rmdirSync: (path) => rmdirSync(path)
38608
38572
  };
38609
38573
  rpcDiscoveryFs = defaultRpcDiscoveryFs;
@@ -38616,18 +38580,18 @@ var init_storage_db = __esm(async () => {
38616
38580
  });
38617
38581
 
38618
38582
  // src/lib/database-access.ts
38619
- import { existsSync as existsSync24, rmSync as rmSync6 } from "node:fs";
38583
+ import { existsSync as existsSync23, rmSync as rmSync6 } from "node:fs";
38620
38584
  import { basename as basename5, dirname as dirname13 } from "node:path";
38621
38585
  import { pathToFileURL as pathToFileURL2 } from "node:url";
38622
38586
  function getPersistedSchemaVersion2(db) {
38623
38587
  return getPersistedSchemaVersion(db);
38624
38588
  }
38625
38589
  function openExistingDatabase(path, options) {
38626
- if (!existsSync24(path))
38590
+ if (!existsSync23(path))
38627
38591
  return null;
38628
38592
  if (options.readonly) {
38629
38593
  const name = basename5(path);
38630
- if ((name === "context.db" || name === "store.db") && !existsSync24(`${path}-wal`) && !existsSync24(`${path}-shm`)) {
38594
+ if ((name === "context.db" || name === "store.db") && !existsSync23(`${path}-wal`) && !existsSync23(`${path}-shm`)) {
38631
38595
  const probe = probeHostProcessesUsing({
38632
38596
  files: [path, `${path}-wal`, `${path}-shm`],
38633
38597
  directories: []
@@ -38693,7 +38657,7 @@ async function backupDatabaseSnapshot(db, sourcePath, destination) {
38693
38657
  if (typeof sqlite.backup !== "function") {
38694
38658
  throw new Error("The active SQLite runtime does not provide a snapshot backup API");
38695
38659
  }
38696
- if (existsSync24(destination)) {
38660
+ if (existsSync23(destination)) {
38697
38661
  throw new Error(`Refusing to overwrite existing backup ${destination}`);
38698
38662
  }
38699
38663
  const reader = openExistingDatabase(sourcePath, { readonly: true });
@@ -38994,10 +38958,10 @@ var init_dreamer_setup = __esm(() => {
38994
38958
  });
38995
38959
 
38996
38960
  // src/commands/setup-pi.ts
38997
- import { existsSync as existsSync25, mkdirSync as mkdirSync6 } from "node:fs";
38961
+ import { existsSync as existsSync24, mkdirSync as mkdirSync6 } from "node:fs";
38998
38962
  import { dirname as dirname14 } from "node:path";
38999
38963
  function ensureDir4(path) {
39000
- if (!existsSync25(path))
38964
+ if (!existsSync24(path))
39001
38965
  mkdirSync6(path, { recursive: true });
39002
38966
  }
39003
38967
  async function getDefaultPrompts() {
@@ -39453,15 +39417,15 @@ var init_setup_omp = __esm(() => {
39453
39417
 
39454
39418
  // ../plugin/src/shared/opencode-config-dir.ts
39455
39419
  import { homedir as homedir13 } from "node:os";
39456
- import { join as join17, resolve as resolve8 } from "node:path";
39420
+ import { join as join16, resolve as resolve8 } from "node:path";
39457
39421
  function resolveHomeDir() {
39458
39422
  return process.env.HOME?.trim() || homedir13();
39459
39423
  }
39460
39424
  function getOpenCodeGlobalConfigDir() {
39461
39425
  if (process.platform === "win32") {
39462
- return join17(resolveHomeDir(), ".config", "opencode");
39426
+ return join16(resolveHomeDir(), ".config", "opencode");
39463
39427
  }
39464
- return join17(process.env.XDG_CONFIG_HOME || join17(resolveHomeDir(), ".config"), "opencode");
39428
+ return join16(process.env.XDG_CONFIG_HOME || join16(resolveHomeDir(), ".config"), "opencode");
39465
39429
  }
39466
39430
  function getEnvConfigDir() {
39467
39431
  const envConfigDir = process.env.OPENCODE_CONFIG_DIR?.trim();
@@ -39477,14 +39441,14 @@ function getOpenCodeConfigPaths(options) {
39477
39441
  const configDir = getOpenCodeConfigDir2(options);
39478
39442
  return {
39479
39443
  configDir,
39480
- configJson: join17(configDir, "opencode.json"),
39481
- configJsonc: join17(configDir, "opencode.jsonc"),
39482
- packageJson: join17(configDir, "package.json"),
39483
- omoConfig: join17(configDir, "magic-context.jsonc")
39444
+ configJson: join16(configDir, "opencode.json"),
39445
+ configJsonc: join16(configDir, "opencode.jsonc"),
39446
+ packageJson: join16(configDir, "package.json"),
39447
+ omoConfig: join16(configDir, "magic-context.jsonc")
39484
39448
  };
39485
39449
  }
39486
39450
  function getOpenCodeConfigDirs() {
39487
- const dirs = [getOpenCodeGlobalConfigDir(), join17(resolveHomeDir(), ".opencode")];
39451
+ const dirs = [getOpenCodeGlobalConfigDir(), join16(resolveHomeDir(), ".opencode")];
39488
39452
  const envDir = getEnvConfigDir();
39489
39453
  if (envDir)
39490
39454
  dirs.push(envDir);
@@ -39494,7 +39458,7 @@ var init_opencode_config_dir = () => {};
39494
39458
 
39495
39459
  // ../plugin/src/shared/conflict-detector.ts
39496
39460
  import { homedir as homedir14 } from "node:os";
39497
- import { join as join18 } from "node:path";
39461
+ import { join as join17 } from "node:path";
39498
39462
  function detectConflicts(directory, options) {
39499
39463
  const compactionEnabled = options?.compactionEnabled ?? true;
39500
39464
  const hostGeneration = options?.hostGeneration ?? "v1";
@@ -39561,19 +39525,19 @@ function checkCompaction(directory, hostGeneration) {
39561
39525
  function openCodeConfigFileChain(directory, hostGeneration) {
39562
39526
  const globalDir = getOpenCodeGlobalConfigDir();
39563
39527
  const wellKnown = [
39564
- join18(globalDir, "config.json"),
39565
- join18(globalDir, "opencode.json"),
39566
- join18(globalDir, "opencode.jsonc")
39528
+ join17(globalDir, "config.json"),
39529
+ join17(globalDir, "opencode.json"),
39530
+ join17(globalDir, "opencode.jsonc")
39567
39531
  ];
39568
- const globalSupplementary = getOpenCodeConfigDirs().filter((dir) => dir !== globalDir).flatMap((dir) => [join18(dir, "opencode.json"), join18(dir, "opencode.jsonc")]);
39532
+ const globalSupplementary = getOpenCodeConfigDirs().filter((dir) => dir !== globalDir).flatMap((dir) => [join17(dir, "opencode.json"), join17(dir, "opencode.jsonc")]);
39569
39533
  const explicitConfig = process.env.OPENCODE_CONFIG?.trim();
39570
39534
  const explicit = explicitConfig ? [explicitConfig] : [];
39571
39535
  const disableProjectConfig = process.env.OPENCODE_DISABLE_PROJECT_CONFIG?.toLowerCase();
39572
39536
  const skipProject = hostGeneration === "v1" && (disableProjectConfig === "true" || disableProjectConfig === "1");
39573
- const direct = skipProject ? [] : [join18(directory, "opencode.json"), join18(directory, "opencode.jsonc")];
39537
+ const direct = skipProject ? [] : [join17(directory, "opencode.json"), join17(directory, "opencode.jsonc")];
39574
39538
  const projectSupplementary = skipProject ? [] : [
39575
- join18(directory, ".opencode", "opencode.json"),
39576
- join18(directory, ".opencode", "opencode.jsonc")
39539
+ join17(directory, ".opencode", "opencode.json"),
39540
+ join17(directory, ".opencode", "opencode.jsonc")
39577
39541
  ];
39578
39542
  const files = hostGeneration === "v2" ? [
39579
39543
  ...wellKnown,
@@ -39660,10 +39624,10 @@ function collectPluginEntries(directory) {
39660
39624
  }
39661
39625
  };
39662
39626
  for (const configPath of [
39663
- join18(directory, ".opencode", "opencode.jsonc"),
39664
- join18(directory, ".opencode", "opencode.json"),
39665
- join18(directory, "opencode.jsonc"),
39666
- join18(directory, "opencode.json")
39627
+ join17(directory, ".opencode", "opencode.jsonc"),
39628
+ join17(directory, ".opencode", "opencode.json"),
39629
+ join17(directory, "opencode.jsonc"),
39630
+ join17(directory, "opencode.json")
39667
39631
  ]) {
39668
39632
  const config = readJsoncFile(configPath);
39669
39633
  pushFrom(config?.plugin);
@@ -39673,7 +39637,7 @@ function collectPluginEntries(directory) {
39673
39637
  for (const dir of getOpenCodeConfigDirs()) {
39674
39638
  const names = dir === globalDir ? ["config.json", "opencode.json", "opencode.jsonc"] : ["opencode.json", "opencode.jsonc"];
39675
39639
  for (const name of names) {
39676
- const config = readJsoncFile(join18(dir, name));
39640
+ const config = readJsoncFile(join17(dir, name));
39677
39641
  pushFrom(config?.plugin);
39678
39642
  }
39679
39643
  }
@@ -39707,7 +39671,7 @@ function readOmoDisabledHooks(directory) {
39707
39671
  try {
39708
39672
  for (const dir of getOpenCodeConfigDirs()) {
39709
39673
  for (const name of configNames) {
39710
- const config = readJsoncFile(join18(dir, name));
39674
+ const config = readJsoncFile(join17(dir, name));
39711
39675
  if (config?.disabled_hooks) {
39712
39676
  for (const hook of config.disabled_hooks) {
39713
39677
  disabled.add(hook);
@@ -39717,7 +39681,7 @@ function readOmoDisabledHooks(directory) {
39717
39681
  }
39718
39682
  } catch {}
39719
39683
  for (const name of configNames) {
39720
- const config = readJsoncFile(join18(directory, name));
39684
+ const config = readJsoncFile(join17(directory, name));
39721
39685
  if (config?.disabled_hooks) {
39722
39686
  for (const hook of config.disabled_hooks) {
39723
39687
  disabled.add(hook);
@@ -39725,9 +39689,9 @@ function readOmoDisabledHooks(directory) {
39725
39689
  }
39726
39690
  }
39727
39691
  const homeDir = process.env.HOME || homedir14();
39728
- const omoHomeDir = join18(homeDir, ".omo");
39692
+ const omoHomeDir = join17(homeDir, ".omo");
39729
39693
  for (const name of ["omo.jsonc", "omo.json"]) {
39730
- const config = readJsoncFile(join18(omoHomeDir, name));
39694
+ const config = readJsoncFile(join17(omoHomeDir, name));
39731
39695
  if (config?.["[opencode]"]?.disabled_hooks) {
39732
39696
  for (const hook of config["[opencode]"].disabled_hooks) {
39733
39697
  disabled.add(hook);
@@ -39735,7 +39699,7 @@ function readOmoDisabledHooks(directory) {
39735
39699
  }
39736
39700
  }
39737
39701
  for (const name of ["omo.jsonc", "omo.json"]) {
39738
- const config = readJsoncFile(join18(directory, ".omo", name));
39702
+ const config = readJsoncFile(join17(directory, ".omo", name));
39739
39703
  if (config?.["[opencode]"]?.disabled_hooks) {
39740
39704
  for (const hook of config["[opencode]"].disabled_hooks) {
39741
39705
  disabled.add(hook);
@@ -39754,9 +39718,9 @@ var init_conflict_detector = __esm(() => {
39754
39718
  });
39755
39719
 
39756
39720
  // ../plugin/src/shared/conflict-fixer.ts
39757
- import { existsSync as existsSync26, readFileSync as readFileSync18, writeFileSync as writeFileSync6 } from "node:fs";
39721
+ import { existsSync as existsSync25, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "node:fs";
39758
39722
  import { homedir as homedir15 } from "node:os";
39759
- import { join as join19 } from "node:path";
39723
+ import { join as join18 } from "node:path";
39760
39724
  function isRecord3(value) {
39761
39725
  return typeof value === "object" && value !== null && !Array.isArray(value);
39762
39726
  }
@@ -39764,11 +39728,11 @@ function asStringArray(value) {
39764
39728
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
39765
39729
  }
39766
39730
  function readConfig(filePath) {
39767
- if (!existsSync26(filePath)) {
39731
+ if (!existsSync25(filePath)) {
39768
39732
  return null;
39769
39733
  }
39770
39734
  try {
39771
- const text = readFileSync18(filePath, "utf-8");
39735
+ const text = readFileSync17(filePath, "utf-8");
39772
39736
  const parsed = import_comment_json5.parse(text);
39773
39737
  return isRecord3(parsed) ? { config: parsed, text } : null;
39774
39738
  } catch {
@@ -39780,23 +39744,23 @@ function writeConfig(filePath, text) {
39780
39744
  }
39781
39745
  function resolveUserOpenCodeConfigPath() {
39782
39746
  const paths = getOpenCodeConfigPaths({ binary: "opencode" });
39783
- if (existsSync26(paths.configJsonc))
39747
+ if (existsSync25(paths.configJsonc))
39784
39748
  return paths.configJsonc;
39785
39749
  return paths.configJson;
39786
39750
  }
39787
39751
  function collectOpenCodeConfigPaths(directory) {
39788
39752
  const paths = new Set;
39789
39753
  const userConfig = resolveUserOpenCodeConfigPath();
39790
- if (existsSync26(userConfig)) {
39754
+ if (existsSync25(userConfig)) {
39791
39755
  paths.add(userConfig);
39792
39756
  }
39793
39757
  for (const filePath of [
39794
- join19(directory, ".opencode", "opencode.jsonc"),
39795
- join19(directory, ".opencode", "opencode.json"),
39796
- join19(directory, "opencode.jsonc"),
39797
- join19(directory, "opencode.json")
39758
+ join18(directory, ".opencode", "opencode.jsonc"),
39759
+ join18(directory, ".opencode", "opencode.json"),
39760
+ join18(directory, "opencode.jsonc"),
39761
+ join18(directory, "opencode.json")
39798
39762
  ]) {
39799
- if (existsSync26(filePath)) {
39763
+ if (existsSync25(filePath)) {
39800
39764
  paths.add(filePath);
39801
39765
  }
39802
39766
  }
@@ -39806,26 +39770,26 @@ function collectOmoConfigPaths(directory) {
39806
39770
  const paths = new Set;
39807
39771
  const configDir = getOpenCodeConfigPaths({ binary: "opencode" }).configDir;
39808
39772
  for (const fileName of OMO_CONFIG_NAMES) {
39809
- const userPath = join19(configDir, fileName);
39810
- const projectPath = join19(directory, fileName);
39811
- if (existsSync26(userPath)) {
39773
+ const userPath = join18(configDir, fileName);
39774
+ const projectPath = join18(directory, fileName);
39775
+ if (existsSync25(userPath)) {
39812
39776
  paths.add(userPath);
39813
39777
  }
39814
- if (existsSync26(projectPath)) {
39778
+ if (existsSync25(projectPath)) {
39815
39779
  paths.add(projectPath);
39816
39780
  }
39817
39781
  }
39818
39782
  const homeDir = process.env.HOME || homedir15();
39819
- const omoHomeDir = join19(homeDir, ".omo");
39783
+ const omoHomeDir = join18(homeDir, ".omo");
39820
39784
  for (const name of OMO_UNIFIED_NAMES) {
39821
- const userPath = join19(omoHomeDir, name);
39822
- if (existsSync26(userPath)) {
39785
+ const userPath = join18(omoHomeDir, name);
39786
+ if (existsSync25(userPath)) {
39823
39787
  paths.add(userPath);
39824
39788
  }
39825
39789
  }
39826
39790
  for (const name of OMO_UNIFIED_NAMES) {
39827
- const projectPath = join19(directory, ".omo", name);
39828
- if (existsSync26(projectPath)) {
39791
+ const projectPath = join18(directory, ".omo", name);
39792
+ if (existsSync25(projectPath)) {
39829
39793
  paths.add(projectPath);
39830
39794
  }
39831
39795
  }
@@ -39953,7 +39917,7 @@ var init_conflict_fixer = __esm(() => {
39953
39917
  });
39954
39918
 
39955
39919
  // src/commands/setup-opencode.ts
39956
- import { existsSync as existsSync27 } from "node:fs";
39920
+ import { existsSync as existsSync26 } from "node:fs";
39957
39921
  import { basename as basename6, dirname as dirname15 } from "node:path";
39958
39922
  function resolveCompactionEnabledForWriter() {
39959
39923
  try {
@@ -39969,7 +39933,7 @@ function isPlainObject5(value) {
39969
39933
  }
39970
39934
  function planOpenCodeConfigUpdate(configPath, removeDcp = false, compactionEnabled = true, hostGeneration = "v1") {
39971
39935
  const registrationKey = pluginConfigKeyFor(hostGeneration);
39972
- const existsAtCommit = existsSync27(configPath);
39936
+ const existsAtCommit = existsSync26(configPath);
39973
39937
  const existing = existsAtCommit ? readJsoncConfigForUpdate(configPath) : {};
39974
39938
  if (!existsAtCommit) {
39975
39939
  const created = { [registrationKey]: [OPENCODE_PLUGIN_ENTRY_WITH_VERSION] };
@@ -40025,7 +39989,7 @@ function planOpenCodeConfigUpdate(configPath, removeDcp = false, compactionEnabl
40025
39989
  return changed ? document.bom + text : null;
40026
39990
  }
40027
39991
  function planTuiConfigUpdate(configPath) {
40028
- const existsAtCommit = existsSync27(configPath);
39992
+ const existsAtCommit = existsSync26(configPath);
40029
39993
  const existing = existsAtCommit ? readJsoncConfigForUpdate(configPath) : {};
40030
39994
  if (!existsAtCommit) {
40031
39995
  return `${import_comment_json6.stringify({ plugin: [OPENCODE_PLUGIN_ENTRY_WITH_VERSION] }, null, 2)}
@@ -40152,7 +40116,7 @@ async function runSetup3(dryRun = false) {
40152
40116
  log3.warn("You can configure models manually in magic-context.jsonc later");
40153
40117
  }
40154
40118
  const paths = detectConfigPaths();
40155
- const hadExistingSetup = paths.opencodeConfigFormat !== "none" || existsSync27(paths.magicContextConfig) || paths.tuiConfigFormat !== "none";
40119
+ const hadExistingSetup = paths.opencodeConfigFormat !== "none" || existsSync26(paths.magicContextConfig) || paths.tuiConfigFormat !== "none";
40156
40120
  if (!dryRun) {
40157
40121
  try {
40158
40122
  assertJsoncConfigsParseable([
@@ -40379,12 +40343,6 @@ async function runSetup4(argv) {
40379
40343
  continue;
40380
40344
  }
40381
40345
  if (!dryRun) {
40382
- const ignore = ensureDocsProposalGitignore(process.cwd());
40383
- if (ignore.status === "added") {
40384
- log3.info(`Added .cortexkit/magic-context/ to ${ignore.path}`);
40385
- } else if (ignore.status === "failed") {
40386
- log3.warn(`Could not update ${ignore.path}: ${ignore.error}`);
40387
- }
40388
40346
  printNextSteps(adapter);
40389
40347
  }
40390
40348
  }
@@ -40433,7 +40391,6 @@ function printNextSteps(adapter) {
40433
40391
  }
40434
40392
  var init_setup = __esm(async () => {
40435
40393
  init_dashboard_install();
40436
- init_docs_proposal_gitignore();
40437
40394
  init_prompts();
40438
40395
  init_setup_omp();
40439
40396
  init_setup_pi();
@@ -40445,7 +40402,7 @@ var init_setup = __esm(async () => {
40445
40402
  });
40446
40403
 
40447
40404
  // src/lib/disk-space.ts
40448
- import { existsSync as existsSync28, statfsSync, statSync as statSync14 } from "node:fs";
40405
+ import { existsSync as existsSync27, statfsSync, statSync as statSync14 } from "node:fs";
40449
40406
  import { dirname as dirname16, resolve as resolve9 } from "node:path";
40450
40407
  function availableDiskBytes(path) {
40451
40408
  const filesystem = statfsSync(path);
@@ -40463,7 +40420,7 @@ function checkDiskSpace(path, bytes, freeBytes) {
40463
40420
  function existingDirectoryAncestor(path) {
40464
40421
  let current = resolve9(path);
40465
40422
  for (;; ) {
40466
- if (existsSync28(current) && statSync14(current).isDirectory())
40423
+ if (existsSync27(current) && statSync14(current).isDirectory())
40467
40424
  return current;
40468
40425
  const parent = dirname16(current);
40469
40426
  if (parent === current)
@@ -40475,24 +40432,24 @@ var init_disk_space = () => {};
40475
40432
 
40476
40433
  // ../plugin/src/hooks/auto-update-checker/constants.ts
40477
40434
  import { homedir as homedir16, platform } from "node:os";
40478
- import { join as join20 } from "node:path";
40435
+ import { join as join19 } from "node:path";
40479
40436
  function getOpenCodeCacheRoot() {
40480
40437
  if (platform() === "win32") {
40481
- return join20(process.env.LOCALAPPDATA ?? homedir16(), "opencode");
40438
+ return join19(process.env.LOCALAPPDATA ?? homedir16(), "opencode");
40482
40439
  }
40483
- return join20(homedir16(), ".cache", "opencode");
40440
+ return join19(homedir16(), ".cache", "opencode");
40484
40441
  }
40485
40442
  function getOpenCodeConfigRoot() {
40486
40443
  if (platform() === "win32") {
40487
- return join20(process.env.APPDATA ?? join20(homedir16(), "AppData", "Roaming"), "opencode");
40444
+ return join19(process.env.APPDATA ?? join19(homedir16(), "AppData", "Roaming"), "opencode");
40488
40445
  }
40489
- return join20(process.env.XDG_CONFIG_HOME ?? join20(homedir16(), ".config"), "opencode");
40446
+ return join19(process.env.XDG_CONFIG_HOME ?? join19(homedir16(), ".config"), "opencode");
40490
40447
  }
40491
40448
  var PACKAGE_NAME = "@cortexkit/opencode-magic-context", CACHE_DIR, USER_OPENCODE_CONFIG, USER_OPENCODE_CONFIG_JSONC;
40492
40449
  var init_constants2 = __esm(() => {
40493
- CACHE_DIR = join20(getOpenCodeCacheRoot(), "packages");
40494
- USER_OPENCODE_CONFIG = join20(getOpenCodeConfigRoot(), "opencode.json");
40495
- USER_OPENCODE_CONFIG_JSONC = join20(getOpenCodeConfigRoot(), "opencode.jsonc");
40450
+ CACHE_DIR = join19(getOpenCodeCacheRoot(), "packages");
40451
+ USER_OPENCODE_CONFIG = join19(getOpenCodeConfigRoot(), "opencode.json");
40452
+ USER_OPENCODE_CONFIG_JSONC = join19(getOpenCodeConfigRoot(), "opencode.jsonc");
40496
40453
  });
40497
40454
 
40498
40455
  // ../plugin/src/hooks/auto-update-checker/types.ts
@@ -40516,14 +40473,14 @@ var init_types = __esm(() => {
40516
40473
  // ../plugin/src/hooks/auto-update-checker/checker.ts
40517
40474
  import {
40518
40475
  accessSync as accessSync3,
40519
- existsSync as existsSync29,
40476
+ existsSync as existsSync28,
40520
40477
  constants as fsConstants,
40521
- readFileSync as readFileSync19,
40478
+ readFileSync as readFileSync18,
40522
40479
  renameSync as renameSync5,
40523
40480
  statSync as statSync15,
40524
40481
  writeFileSync as writeFileSync7
40525
40482
  } from "node:fs";
40526
- import { dirname as dirname17, isAbsolute as isAbsolute7, join as join21, resolve as resolve10 } from "node:path";
40483
+ import { dirname as dirname17, isAbsolute as isAbsolute7, join as join20, resolve as resolve10 } from "node:path";
40527
40484
  function warn(message) {
40528
40485
  log(`WARN: ${message}`);
40529
40486
  }
@@ -40553,13 +40510,13 @@ function getSurfaceConfigPaths(directory, surface) {
40553
40510
  const dirs = [
40554
40511
  globalDir,
40555
40512
  directory,
40556
- join21(directory, ".opencode"),
40513
+ join20(directory, ".opencode"),
40557
40514
  process.env.OPENCODE_CONFIG_DIR
40558
40515
  ].filter((value) => Boolean(value));
40559
40516
  const paths = [];
40560
40517
  for (const dir of dirs) {
40561
40518
  for (const extension of ["json", "jsonc"]) {
40562
- const path = join21(dir, `${name}.${extension}`);
40519
+ const path = join20(dir, `${name}.${extension}`);
40563
40520
  if (!paths.includes(path))
40564
40521
  paths.push(path);
40565
40522
  }
@@ -40570,9 +40527,9 @@ function getWinningConfig(directory, surface) {
40570
40527
  let winner = null;
40571
40528
  for (const path of getSurfaceConfigPaths(directory, surface)) {
40572
40529
  try {
40573
- if (!existsSync29(path))
40530
+ if (!existsSync28(path))
40574
40531
  continue;
40575
- const parsed = parseJsonConfig(readFileSync19(path, "utf-8"));
40532
+ const parsed = parseJsonConfig(readFileSync18(path, "utf-8"));
40576
40533
  const entries = getPluginEntries(parsed);
40577
40534
  if (entries.some((entry) => entry === PACKAGE_NAME || entry.startsWith(`${PACKAGE_NAME}@`))) {
40578
40535
  if (winner) {
@@ -40609,14 +40566,14 @@ var init_checker = __esm(async () => {
40609
40566
  });
40610
40567
 
40611
40568
  // src/lib/opencode-plugin-schema-fence.ts
40612
- import { existsSync as existsSync30, readdirSync as readdirSync6, readFileSync as readFileSync20 } from "node:fs";
40613
- import { join as join22 } from "node:path";
40569
+ import { existsSync as existsSync29, readdirSync as readdirSync6, readFileSync as readFileSync19 } from "node:fs";
40570
+ import { join as join21 } from "node:path";
40614
40571
  import { gunzipSync as gunzipSync2 } from "node:zlib";
40615
40572
  function readPackageVersion(packageJsonPath) {
40616
40573
  try {
40617
- if (!existsSync30(packageJsonPath))
40574
+ if (!existsSync29(packageJsonPath))
40618
40575
  return null;
40619
- const packageJson = JSON.parse(readFileSync20(packageJsonPath, "utf-8"));
40576
+ const packageJson = JSON.parse(readFileSync19(packageJsonPath, "utf-8"));
40620
40577
  if (packageJson.name !== OPENCODE_PLUGIN_NAME || typeof packageJson.version !== "string") {
40621
40578
  return null;
40622
40579
  }
@@ -40635,8 +40592,8 @@ function readFenceValue(text) {
40635
40592
  return values.size === 1 ? [...values][0] ?? null : null;
40636
40593
  }
40637
40594
  function readFenceFromDist(packageDirectory) {
40638
- const distDirectory = join22(packageDirectory, "dist");
40639
- if (!existsSync30(distDirectory))
40595
+ const distDirectory = join21(packageDirectory, "dist");
40596
+ if (!existsSync29(distDirectory))
40640
40597
  return null;
40641
40598
  const pending = [distDirectory];
40642
40599
  const fenceValues = new Set;
@@ -40646,14 +40603,14 @@ function readFenceFromDist(packageDirectory) {
40646
40603
  continue;
40647
40604
  try {
40648
40605
  for (const entry of readdirSync6(directory, { withFileTypes: true })) {
40649
- const path = join22(directory, entry.name);
40606
+ const path = join21(directory, entry.name);
40650
40607
  if (entry.isDirectory()) {
40651
40608
  pending.push(path);
40652
40609
  continue;
40653
40610
  }
40654
40611
  if (!entry.isFile() || !/\.(?:[cm]?js|ts)$/.test(entry.name))
40655
40612
  continue;
40656
- const fence = readFenceValue(readFileSync20(path, "utf-8"));
40613
+ const fence = readFenceValue(readFileSync19(path, "utf-8"));
40657
40614
  if (fence !== null)
40658
40615
  fenceValues.add(fence);
40659
40616
  }
@@ -40664,20 +40621,20 @@ function readFenceFromDist(packageDirectory) {
40664
40621
  return fenceValues.size === 1 ? [...fenceValues][0] ?? null : null;
40665
40622
  }
40666
40623
  function findInstalledPluginPackage(cacheDirectory, specifier, requestedVersion) {
40667
- const directCacheRoot = join22(cacheDirectory, specifier);
40624
+ const directCacheRoot = join21(cacheDirectory, specifier);
40668
40625
  const candidates = [directCacheRoot];
40669
40626
  try {
40670
40627
  for (const entry of readdirSync6(cacheDirectory, { withFileTypes: true })) {
40671
40628
  if (!entry.isDirectory())
40672
40629
  continue;
40673
- const candidate = join22(cacheDirectory, entry.name);
40630
+ const candidate = join21(cacheDirectory, entry.name);
40674
40631
  if (!candidates.includes(candidate))
40675
40632
  candidates.push(candidate);
40676
40633
  }
40677
40634
  } catch {}
40678
40635
  for (const cacheRoot of candidates) {
40679
- const directory = join22(cacheRoot, "node_modules", ...PACKAGE_PATH_SEGMENTS);
40680
- const version = readPackageVersion(join22(directory, "package.json"));
40636
+ const directory = join21(cacheRoot, "node_modules", ...PACKAGE_PATH_SEGMENTS);
40637
+ const version = readPackageVersion(join21(directory, "package.json"));
40681
40638
  if (!version)
40682
40639
  continue;
40683
40640
  if (cacheRoot === directCacheRoot || EXACT_VERSION_PATTERN.test(requestedVersion) && version === requestedVersion) {
@@ -40822,13 +40779,13 @@ var init_opencode_plugin_schema_fence = __esm(async () => {
40822
40779
  });
40823
40780
 
40824
40781
  // src/commands/doctor-opencode-cache.ts
40825
- import { existsSync as existsSync31, readFileSync as readFileSync21, rmSync as rmSync7 } from "node:fs";
40782
+ import { existsSync as existsSync30, readFileSync as readFileSync20, rmSync as rmSync7 } from "node:fs";
40826
40783
  function readCachedPluginVersion(pluginCacheDir) {
40827
40784
  try {
40828
40785
  const installedPkgPath = getOpenCodePluginPackageJsonPath(pluginCacheDir);
40829
- if (!existsSync31(installedPkgPath))
40786
+ if (!existsSync30(installedPkgPath))
40830
40787
  return;
40831
- const pkg = JSON.parse(readFileSync21(installedPkgPath, "utf-8"));
40788
+ const pkg = JSON.parse(readFileSync20(installedPkgPath, "utf-8"));
40832
40789
  return typeof pkg.version === "string" ? pkg.version : undefined;
40833
40790
  } catch {
40834
40791
  return;
@@ -40855,7 +40812,7 @@ function readOpenCodePluginConfigUse(config, configDir) {
40855
40812
  async function clearPluginCache(options = {}, deps = {}) {
40856
40813
  const remove = deps.remove ?? ((path) => rmSync7(path, { recursive: true, force: true }));
40857
40814
  const pluginCacheRoots = getOpenCodePluginCacheRoots();
40858
- const existingRoots = pluginCacheRoots.filter((root) => existsSync31(root));
40815
+ const existingRoots = pluginCacheRoots.filter((root) => existsSync30(root));
40859
40816
  if (existingRoots.length === 0) {
40860
40817
  return { action: "not_found", path: pluginCacheRoots[0] ?? "" };
40861
40818
  }
@@ -40952,7 +40909,7 @@ var init_doctor_opencode_cache = __esm(async () => {
40952
40909
  });
40953
40910
 
40954
40911
  // src/commands/doctor-cached-plugin-fence.ts
40955
- import { existsSync as existsSync32 } from "node:fs";
40912
+ import { existsSync as existsSync31 } from "node:fs";
40956
40913
  import { dirname as dirname18 } from "node:path";
40957
40914
  function isReferenced(sources, host, spec) {
40958
40915
  const specs = sources.referencedSpecs?.[host];
@@ -40963,7 +40920,7 @@ function listCachedOpenCodePluginFences(sources = {}) {
40963
40920
  const v1Referenced = isReferenced(sources, "opencode1", "latest");
40964
40921
  for (const root of v1Referenced ? sources.openCodeV1Roots ?? getOpenCodePluginCacheRoots() : []) {
40965
40922
  const packageJson = getOpenCodePluginPackageJsonPath(root);
40966
- if (!existsSync32(packageJson))
40923
+ if (!existsSync31(packageJson))
40967
40924
  continue;
40968
40925
  fences.push({
40969
40926
  host: "opencode1",
@@ -41168,8 +41125,8 @@ var init_doctor_prune_discovery = __esm(async () => {
41168
41125
 
41169
41126
  // src/commands/doctor-storage-holders.ts
41170
41127
  import { execFileSync as execFileSync5 } from "node:child_process";
41171
- import { readFileSync as readFileSync22, realpathSync as realpathSync6 } from "node:fs";
41172
- import { join as join23, resolve as resolve11 } from "node:path";
41128
+ import { readFileSync as readFileSync21, realpathSync as realpathSync6 } from "node:fs";
41129
+ import { join as join22, resolve as resolve11 } from "node:path";
41173
41130
  function canonicalStoragePath(path) {
41174
41131
  try {
41175
41132
  return realpathSync6(path);
@@ -41186,7 +41143,7 @@ function textReferencesStorage(text, storageDir) {
41186
41143
  continue;
41187
41144
  if (canonicalStoragePath(value) === target)
41188
41145
  return true;
41189
- if (token.startsWith("XDG_DATA_HOME=") && canonicalStoragePath(join23(value, "cortexkit", "magic-context")) === target)
41146
+ if (token.startsWith("XDG_DATA_HOME=") && canonicalStoragePath(join22(value, "cortexkit", "magic-context")) === target)
41190
41147
  return true;
41191
41148
  }
41192
41149
  return false;
@@ -41196,7 +41153,7 @@ function processReferencesStorage(pid, storageDir) {
41196
41153
  if (process.platform === "linux") {
41197
41154
  for (const name of ["cmdline", "environ"]) {
41198
41155
  try {
41199
- texts.push(readFileSync22(`/proc/${pid}/${name}`, "utf8"));
41156
+ texts.push(readFileSync21(`/proc/${pid}/${name}`, "utf8"));
41200
41157
  } catch {}
41201
41158
  }
41202
41159
  } else {
@@ -41218,12 +41175,12 @@ var init_doctor_storage_holders = () => {};
41218
41175
 
41219
41176
  // src/commands/doctor-repair-db.ts
41220
41177
  import { spawnSync as spawnSync4 } from "node:child_process";
41221
- import { closeSync as closeSync4, existsSync as existsSync33, openSync as openSync4, renameSync as renameSync6, rmSync as rmSync8, statSync as statSync16 } from "node:fs";
41178
+ import { closeSync as closeSync4, existsSync as existsSync32, openSync as openSync4, renameSync as renameSync6, rmSync as rmSync8, statSync as statSync16 } from "node:fs";
41222
41179
  import { homedir as homedir17 } from "node:os";
41223
- import { dirname as dirname19, join as join24 } from "node:path";
41180
+ import { dirname as dirname19, join as join23 } from "node:path";
41224
41181
  function defaultInspectHolders(storageDir, overrides = {}) {
41225
41182
  const deps = {
41226
- defaultStorageDir: join24(homedir17(), ".local", "share", "cortexkit", "magic-context"),
41183
+ defaultStorageDir: join23(homedir17(), ".local", "share", "cortexkit", "magic-context"),
41227
41184
  inspectRpc: inspectRpcServerDiscovery,
41228
41185
  inspectPi: inspectLivePiProcesses,
41229
41186
  probeFiles: probeHostProcessesUsing,
@@ -41240,7 +41197,7 @@ function defaultInspectHolders(storageDir, overrides = {}) {
41240
41197
  return {
41241
41198
  safe: false,
41242
41199
  blockers: [],
41243
- uncertainty: `RPC discovery ${rpc.unreadableFile ?? join24(storageDir, "rpc")} ${arm}`
41200
+ uncertainty: `RPC discovery ${rpc.unreadableFile ?? join23(storageDir, "rpc")} ${arm}`
41244
41201
  };
41245
41202
  }
41246
41203
  const blockers = rpc.state === "live" ? rpc.serverPids.map((pid) => `OpenCode server (PID ${pid})`) : [];
@@ -41253,7 +41210,7 @@ function defaultInspectHolders(storageDir, overrides = {}) {
41253
41210
  const pi = overrides.inspectPi ? deps.inspectPi() : processes?.pi ?? deps.inspectPi();
41254
41211
  if (canonicalStoragePath(storageDir) !== canonicalStoragePath(deps.defaultStorageDir)) {
41255
41212
  const holders = deps.probeFiles({
41256
- files: ["context.db", "store.db"].flatMap((name) => DATABASE_SUFFIXES.map((suffix) => join24(storageDir, `${name}${suffix}`))),
41213
+ files: ["context.db", "store.db"].flatMap((name) => DATABASE_SUFFIXES.map((suffix) => join23(storageDir, `${name}${suffix}`))),
41257
41214
  directories: []
41258
41215
  });
41259
41216
  if (holders.status === "unknown") {
@@ -41286,11 +41243,11 @@ function timestamp(date) {
41286
41243
  return date.toISOString().replaceAll("-", "").replaceAll(":", "").replace(".", "");
41287
41244
  }
41288
41245
  function uniqueBase(preferred) {
41289
- if (!DATABASE_SUFFIXES.some((suffix) => existsSync33(`${preferred}${suffix}`)))
41246
+ if (!DATABASE_SUFFIXES.some((suffix) => existsSync32(`${preferred}${suffix}`)))
41290
41247
  return preferred;
41291
41248
  for (let attempt = 1;attempt < 1e4; attempt++) {
41292
41249
  const candidate = `${preferred}-${attempt}`;
41293
- if (!DATABASE_SUFFIXES.some((suffix) => existsSync33(`${candidate}${suffix}`)))
41250
+ if (!DATABASE_SUFFIXES.some((suffix) => existsSync32(`${candidate}${suffix}`)))
41294
41251
  return candidate;
41295
41252
  }
41296
41253
  throw new Error(`Could not allocate a unique recovery path beside ${preferred}`);
@@ -41304,7 +41261,7 @@ function databaseBundleSizeBytes(sourceBase) {
41304
41261
  let size = 0;
41305
41262
  for (const suffix of DATABASE_SUFFIXES) {
41306
41263
  const source = `${sourceBase}${suffix}`;
41307
- if (existsSync33(source))
41264
+ if (existsSync32(source))
41308
41265
  size += statSync16(source).size;
41309
41266
  }
41310
41267
  return size;
@@ -41313,7 +41270,7 @@ function copyDatabaseBundle(sourceBase, destinationBase, forcePrivate = false) {
41313
41270
  const copiedPaths = [];
41314
41271
  for (const suffix of DATABASE_SUFFIXES) {
41315
41272
  const source = `${sourceBase}${suffix}`;
41316
- if (!existsSync33(source))
41273
+ if (!existsSync32(source))
41317
41274
  continue;
41318
41275
  const destination = `${destinationBase}${suffix}`;
41319
41276
  copyStorageFileSync(source, destination, forcePrivate);
@@ -41535,7 +41492,7 @@ function activateReplacement(dbPath, replacementPath, originalAsidePath) {
41535
41492
  try {
41536
41493
  for (const suffix of DATABASE_SUFFIXES) {
41537
41494
  const from = `${dbPath}${suffix}`;
41538
- if (!existsSync33(from))
41495
+ if (!existsSync32(from))
41539
41496
  continue;
41540
41497
  const to = `${originalAsidePath}${suffix}`;
41541
41498
  renameSync6(from, to);
@@ -41545,7 +41502,7 @@ function activateReplacement(dbPath, replacementPath, originalAsidePath) {
41545
41502
  return movedOriginals.map(({ to }) => to);
41546
41503
  } catch (error) {
41547
41504
  for (const moved of movedOriginals.reverse()) {
41548
- if (existsSync33(moved.to) && !existsSync33(moved.from))
41505
+ if (existsSync32(moved.to) && !existsSync32(moved.from))
41549
41506
  renameSync6(moved.to, moved.from);
41550
41507
  }
41551
41508
  throw error;
@@ -41576,12 +41533,12 @@ function printHelp() {
41576
41533
  async function runRepairDb(options = {}) {
41577
41534
  const prompts = options.prompts ?? promptIO;
41578
41535
  const deps = { ...DEFAULT_DEPS3, ...options.deps };
41579
- const storageDir = options.storageDir ?? dirname19(options.dbPath ?? join24(getMagicContextStorageDir(), "context.db"));
41580
- const dbPath = options.dbPath ?? join24(storageDir, "context.db");
41536
+ const storageDir = options.storageDir ?? dirname19(options.dbPath ?? join23(getMagicContextStorageDir(), "context.db"));
41537
+ const dbPath = options.dbPath ?? join23(storageDir, "context.db");
41581
41538
  const stamp = timestamp(deps.now());
41582
41539
  prompts.intro("Magic Context — Repair shared database");
41583
41540
  prompts.log.info(`Database: ${dbPath}`);
41584
- if (!existsSync33(dbPath)) {
41541
+ if (!existsSync32(dbPath)) {
41585
41542
  prompts.log.error(`Database not found: ${dbPath}`);
41586
41543
  prompts.log.info("Backup: not created (database does not exist)");
41587
41544
  prompts.outro("Database repair failed");
@@ -41791,12 +41748,12 @@ var init_doctor_repair_db = __esm(async () => {
41791
41748
 
41792
41749
  // src/commands/doctor-single-store-repair.ts
41793
41750
  import { spawnSync as spawnSync5 } from "node:child_process";
41794
- import { existsSync as existsSync34, statfsSync as statfsSync2, statSync as statSync17 } from "node:fs";
41751
+ import { existsSync as existsSync33, statfsSync as statfsSync2, statSync as statSync17 } from "node:fs";
41795
41752
  import { homedir as homedir18 } from "node:os";
41796
- import { dirname as dirname20, join as join25, resolve as resolve12 } from "node:path";
41753
+ import { dirname as dirname20, join as join24, resolve as resolve12 } from "node:path";
41797
41754
  function existingAncestor(path) {
41798
41755
  let current = resolve12(path);
41799
- while (!existsSync34(current))
41756
+ while (!existsSync33(current))
41800
41757
  current = dirname20(current);
41801
41758
  return current;
41802
41759
  }
@@ -41832,15 +41789,15 @@ function runDoctorSingleStoreRepair(options, overrides = {}) {
41832
41789
  };
41833
41790
  try {
41834
41791
  const { dbPath: context, dbDir: data } = resolveDatabasePath();
41835
- const store = join25(data, "store.db");
41836
- if (!existsSync34(context) || !existsSync34(store))
41792
+ const store = join24(data, "store.db");
41793
+ if (!existsSync33(context) || !existsSync33(store))
41837
41794
  return refuse("repair_missing_database", `Both ${context} and ${store} must exist.`);
41838
41795
  if (!options.fromBackup)
41839
41796
  return refuse("repair_usage", "--from-backup <dir> is required");
41840
41797
  const fromBackup = resolve12(options.fromBackup);
41841
41798
  for (const name of ["context.db", "store.db"])
41842
- if (!existsSync34(join25(fromBackup, name)))
41843
- return refuse("repair_backup_missing", `${join25(fromBackup, name)} does not exist`);
41799
+ if (!existsSync33(join24(fromBackup, name)))
41800
+ return refuse("repair_backup_missing", `${join24(fromBackup, name)} does not exist`);
41844
41801
  const sessions = options.sessions ?? [];
41845
41802
  if (options.live && sessions.length === 0)
41846
41803
  return refuse("repair_usage", "--live repairs named sessions only; pass --session <id>");
@@ -41867,16 +41824,16 @@ function runDoctorSingleStoreRepair(options, overrides = {}) {
41867
41824
  `));
41868
41825
  deps.print(`Repairing while hosts hold the stores (--live): ${blockers.join("; ") || "holders unknown"}`);
41869
41826
  }
41870
- const backupRoot = resolve12(options.backupRoot ?? join25(data, "backups"));
41827
+ const backupRoot = resolve12(options.backupRoot ?? join24(data, "backups"));
41871
41828
  const need = Math.ceil((statSync17(context).size + statSync17(store).size) * 1.1);
41872
41829
  const volume = existingAncestor(backupRoot);
41873
41830
  const have = deps.freeBytes(volume);
41874
41831
  if (have < need)
41875
41832
  return refuse("repair_disk_space", `the backup needs ${need} bytes; have ${have} bytes on ${volume}`);
41876
- backupDir = join25(backupRoot, `repair-history-${deps.now().toISOString().replaceAll(":", "-")}`);
41833
+ backupDir = join24(backupRoot, `repair-history-${deps.now().toISOString().replaceAll(":", "-")}`);
41877
41834
  deps.print(`Backing up the live stores to ${backupDir} before any write.`);
41878
41835
  }
41879
- const binary = options.ckMc ?? join25(homedir18(), ".local", "share", "cortexkit", "bin", "ck-mc");
41836
+ const binary = options.ckMc ?? join24(homedir18(), ".local", "share", "cortexkit", "bin", "ck-mc");
41880
41837
  const args = [
41881
41838
  "single-store-repair-history",
41882
41839
  "--context-db",
@@ -41964,22 +41921,22 @@ var init_doctor_single_store_repair = __esm(async () => {
41964
41921
 
41965
41922
  // src/commands/doctor-single-store.ts
41966
41923
  import { spawnSync as spawnSync6 } from "node:child_process";
41967
- import { existsSync as existsSync35, realpathSync as realpathSync7, statSync as statSync18 } from "node:fs";
41924
+ import { existsSync as existsSync34, realpathSync as realpathSync7, statSync as statSync18 } from "node:fs";
41968
41925
  import { homedir as homedir19 } from "node:os";
41969
- import { join as join26, resolve as resolve13 } from "node:path";
41926
+ import { join as join25, resolve as resolve13 } from "node:path";
41970
41927
  function engineContextPath() {
41971
41928
  const value = (key) => process.env[key]?.trim() || undefined;
41972
41929
  const test = value("MAGIC_CONTEXT_TEST_DATA_DIR");
41973
41930
  const xdg = value("XDG_DATA_HOME");
41974
- const dir = test ? join26(xdg && xdg !== test ? xdg : test, "cortexkit", "magic-context") : value("MAGIC_CONTEXT_STORAGE_DIR") ?? join26(xdg ?? join26(value("HOME") ?? ".", ".local", "share"), "cortexkit", "magic-context");
41975
- return join26(dir, "context.db");
41931
+ const dir = test ? join25(xdg && xdg !== test ? xdg : test, "cortexkit", "magic-context") : value("MAGIC_CONTEXT_STORAGE_DIR") ?? join25(xdg ?? join25(value("HOME") ?? ".", ".local", "share"), "cortexkit", "magic-context");
41932
+ return join25(dir, "context.db");
41976
41933
  }
41977
41934
  function undo(backup, data, print) {
41978
41935
  const quote = (s) => `'${s.replaceAll("'", "'\\''")}'`;
41979
41936
  print(`Backup: ${backup}`);
41980
41937
  print("To undo: quit every host, then");
41981
- print(` rm -f ${["context.db-wal", "context.db-shm", "store.db-wal", "store.db-shm"].map((name) => quote(join26(data, name))).join(" ")}`);
41982
- print(` cp ${quote(join26(backup, "context.db"))} ${quote(join26(backup, "store.db"))} ${quote(data + "/")}`);
41938
+ print(` rm -f ${["context.db-wal", "context.db-shm", "store.db-wal", "store.db-shm"].map((name) => quote(join25(data, name))).join(" ")}`);
41939
+ print(` cp ${quote(join25(backup, "context.db"))} ${quote(join25(backup, "store.db"))} ${quote(data + "/")}`);
41983
41940
  print("This restores the unmigrated stores. Keep the current plugin and ck-mc: TypeScript mode works as before, and Rust mode will refuse with MC-C14 until you run this command again.");
41984
41941
  }
41985
41942
  function runDoctorSingleStore(options = {}, overrides = {}) {
@@ -41997,8 +41954,8 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
41997
41954
  };
41998
41955
  try {
41999
41956
  const { dbPath: context, dbDir: data } = resolveDatabasePath();
42000
- const store = join26(data, "store.db");
42001
- if (!existsSync35(context) || !existsSync35(store))
41957
+ const store = join25(data, "store.db");
41958
+ if (!existsSync34(context) || !existsSync34(store))
42002
41959
  return refuse("single_store_missing_database", `Both ${context} and ${store} must exist.`);
42003
41960
  const probe = probeHostProcessesUsing({ files: [context, store].flatMap((p) => SUFFIXES2.map((s) => p + s)), directories: [] }, deps.lsofSpawn);
42004
41961
  const holders = deps.inspectHolders(data);
@@ -42013,9 +41970,9 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
42013
41970
  return refuse("single_store_files_in_use", [...lines, STOP].join(`
42014
41971
  `));
42015
41972
  }
42016
- if (!existsSync35(engineContextPath()) || realpathSync7(context) !== realpathSync7(engineContextPath()))
41973
+ if (!existsSync34(engineContextPath()) || realpathSync7(context) !== realpathSync7(engineContextPath()))
42017
41974
  return refuse("single_store_path_mismatch", `CLI ${context}; engine ${engineContextPath()}`);
42018
- const backupRoot = resolve13(options.backupRoot ?? join26(data, "backups"));
41975
+ const backupRoot = resolve13(options.backupRoot ?? join25(data, "backups"));
42019
41976
  const contextDb = openExistingDatabase(context, { readonly: true });
42020
41977
  if (!contextDb)
42021
41978
  return refuse("single_store_missing_database", `Database disappeared: ${context}`);
@@ -42057,7 +42014,7 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
42057
42014
  const backupSpace = sameVolume ? undefined : checkDiskSpace(backupVolume, backupBytes, deps.freeBytes);
42058
42015
  if (backupSpace && !backupSpace.sufficient)
42059
42016
  return refuse("single_store_disk_space", `backup needs ${backupSpace.requiredBytes} bytes; have ${backupSpace.availableBytes} bytes on ${backupVolume}`);
42060
- const backupDir = join26(backupRoot, `single-store-${deps.now().toISOString().replaceAll(":", "-")}`);
42017
+ const backupDir = join25(backupRoot, `single-store-${deps.now().toISOString().replaceAll(":", "-")}`);
42061
42018
  undo(backupDir, data, deps.print);
42062
42019
  const opened = openDatabase(context);
42063
42020
  if (!opened)
@@ -42069,7 +42026,7 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
42069
42026
  }
42070
42027
  if (contextVersion !== LATEST_SUPPORTED_VERSION)
42071
42028
  return refuse("single_store_version_mismatch", `context.db v${contextVersion}; store.db v${storeVersion}`);
42072
- const binary = options.ckMc ?? join26(homedir19(), ".local", "share", "cortexkit", "bin", "ck-mc");
42029
+ const binary = options.ckMc ?? join25(homedir19(), ".local", "share", "cortexkit", "bin", "ck-mc");
42073
42030
  const args = [
42074
42031
  "single-store-migrate",
42075
42032
  "--context-db",
@@ -42561,15 +42518,15 @@ var init_storage_identity_merge = __esm(() => {
42561
42518
  // src/commands/doctor-identity-splits.ts
42562
42519
  import { execFileSync as execFileSync6 } from "node:child_process";
42563
42520
  import { createHash as createHash6 } from "node:crypto";
42564
- import { existsSync as existsSync36, readdirSync as readdirSync7, realpathSync as realpathSync8, statSync as statSync19 } from "node:fs";
42565
- import { dirname as dirname21, join as join27, resolve as resolve14 } from "node:path";
42521
+ import { existsSync as existsSync35, readdirSync as readdirSync7, realpathSync as realpathSync8, statSync as statSync19 } from "node:fs";
42522
+ import { dirname as dirname21, join as join26, resolve as resolve14 } from "node:path";
42566
42523
  function tableExists5(db, table) {
42567
42524
  return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
42568
42525
  }
42569
42526
  function hasGitMetadataInAncestors(directory) {
42570
42527
  let current = resolve14(directory);
42571
42528
  while (true) {
42572
- if (existsSync36(join27(current, ".git")))
42529
+ if (existsSync35(join26(current, ".git")))
42573
42530
  return true;
42574
42531
  const parent = dirname21(current);
42575
42532
  if (parent === current)
@@ -42724,7 +42681,7 @@ function identityLines(split) {
42724
42681
  return split.identities.map((row) => ` ${row.identity}: ${row.sessions} sessions, ${row.memories} memories, ${row.notes} notes, ${row.dreamer} dreamer rows (identity-wide counts)`);
42725
42682
  }
42726
42683
  function diagnoseIdentitySplits() {
42727
- const db = openExistingContextDatabase(join27(getMagicContextStorageDir(), "context.db"), {
42684
+ const db = openExistingContextDatabase(join26(getMagicContextStorageDir(), "context.db"), {
42728
42685
  readonly: true
42729
42686
  });
42730
42687
  if (!db)
@@ -42750,8 +42707,8 @@ var init_doctor_identity_splits = __esm(async () => {
42750
42707
  // src/commands/doctor-merge-identity.ts
42751
42708
  import { execFileSync as execFileSync7 } from "node:child_process";
42752
42709
  import { createHash as createHash7 } from "node:crypto";
42753
- import { existsSync as existsSync37, mkdtempSync as mkdtempSync2, readdirSync as readdirSync8, readFileSync as readFileSync23, statSync as statSync20 } from "node:fs";
42754
- import { dirname as dirname22, join as join28, resolve as resolve15 } from "node:path";
42710
+ import { existsSync as existsSync36, mkdtempSync as mkdtempSync2, readdirSync as readdirSync8, readFileSync as readFileSync22, statSync as statSync20 } from "node:fs";
42711
+ import { dirname as dirname22, join as join27, resolve as resolve15 } from "node:path";
42755
42712
  function parseMergeIdentityArgs(args) {
42756
42713
  const values = {};
42757
42714
  const switches = new Set(["--apply", "--force", "--dry-run", "--yes", "--verbose"]);
@@ -42801,7 +42758,7 @@ function printReport(report) {
42801
42758
  console.log(" No writes. Review this preview, then repeat with --apply to confirm.");
42802
42759
  }
42803
42760
  function resolveReadOnly(directory) {
42804
- if (!existsSync37(directory))
42761
+ if (!existsSync36(directory))
42805
42762
  return;
42806
42763
  try {
42807
42764
  const roots = execFileSync7("git", ["rev-list", "--max-parents=0", "HEAD"], {
@@ -42957,13 +42914,13 @@ function observations(db, hostPath, storageDir) {
42957
42914
  if (!row.identities.some((item) => item.identity === identity))
42958
42915
  row.identities.push({ identity, sessions: 0, memories: 0, notes: 0, dreamer: 0 });
42959
42916
  };
42960
- const sidecars = join28(storageDir, "project-identities");
42961
- if (existsSync37(sidecars))
42917
+ const sidecars = join27(storageDir, "project-identities");
42918
+ if (existsSync36(sidecars))
42962
42919
  for (const file of readdirSync8(sidecars)) {
42963
42920
  if (!file.endsWith(".json"))
42964
42921
  continue;
42965
42922
  try {
42966
- const record = JSON.parse(readFileSync23(join28(sidecars, file), "utf8"));
42923
+ const record = JSON.parse(readFileSync22(join27(sidecars, file), "utf8"));
42967
42924
  if (typeof record.directory === "string" && typeof record.identity === "string")
42968
42925
  add(record.directory, record.identity);
42969
42926
  } catch {}
@@ -42974,9 +42931,9 @@ function observations(db, hostPath, storageDir) {
42974
42931
  }
42975
42932
  function runMergeIdentityCli(args, deps = {}) {
42976
42933
  const options = parseMergeIdentityArgs(args);
42977
- const dbPath = options.dbPath ?? join28(getMagicContextStorageDir(), "context.db");
42934
+ const dbPath = options.dbPath ?? join27(getMagicContextStorageDir(), "context.db");
42978
42935
  const storageDir = dirname22(dbPath);
42979
- const hostPath = options.hostPath ?? (options.dbPath ? join28(storageDir, "host.db") : resolveOpenCodeDbPath().path);
42936
+ const hostPath = options.hostPath ?? (options.dbPath ? join27(storageDir, "host.db") : resolveOpenCodeDbPath().path);
42980
42937
  let db = openExistingContextDatabase(dbPath, {
42981
42938
  readonly: true,
42982
42939
  minimumSupportedVersion: CLI_SCHEMA_FLOOR_VERSION
@@ -43029,27 +42986,27 @@ function runMergeIdentityCli(args, deps = {}) {
43029
42986
  throw new Error(`Refusing merge: close OpenCode, Pi, OpenCode 2 and ck-mc. ${holders.blockers.join(", ")} ${holders.uncertainty ?? ""} ${probe.status === "in_use" ? `context.db holders: ${probe.pids.join(", ")}` : probe.status === "unknown" ? probe.reason : ""}`);
43030
42987
  const backupRoot = resolve15(options.backupRoot ?? storageDir);
43031
42988
  const backupVolume = existingDirectoryAncestor(backupRoot);
43032
- const sidecarRoot = join28(storageDir, "project-identities");
43033
- const sidecarEntries = existsSync37(sidecarRoot) ? readdirSync8(sidecarRoot).filter((entry) => entry.endsWith(".json")) : [];
43034
- const sidecarBytes = sidecarEntries.reduce((size, entry) => size + statSync20(join28(sidecarRoot, entry)).size, 0);
42989
+ const sidecarRoot = join27(storageDir, "project-identities");
42990
+ const sidecarEntries = existsSync36(sidecarRoot) ? readdirSync8(sidecarRoot).filter((entry) => entry.endsWith(".json")) : [];
42991
+ const sidecarBytes = sidecarEntries.reduce((size, entry) => size + statSync20(join27(sidecarRoot, entry)).size, 0);
43035
42992
  const diskSpace = checkDiskSpace(backupVolume, databaseBundleSizeBytes(dbPath) + sidecarBytes, deps.freeBytes ?? availableDiskBytes);
43036
42993
  if (!diskSpace.sufficient)
43037
42994
  throw new Error(`merge_identity_disk_space: refusing identity merge: backup needs ${diskSpace.requiredBytes} bytes; have ${diskSpace.availableBytes} bytes on ${backupVolume}. Use --backup-root <dir> to choose a volume with enough free space.`);
43038
42995
  ensureStorageDirectorySync(backupRoot, true);
43039
- const backup = mkdtempSync2(join28(backupRoot, "identity-merge-backup-"));
42996
+ const backup = mkdtempSync2(join27(backupRoot, "identity-merge-backup-"));
43040
42997
  const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
43041
42998
  console.log(`Backup directory: ${backup}`);
43042
- console.log(`Restore with hosts closed: rm -f ${quote(`${dbPath}-wal`)} ${quote(`${dbPath}-shm`)}; cp ${quote(join28(backup, "context.db"))} ${quote(dbPath)}; if test -f ${quote(join28(backup, "context.db-wal"))}; then cp ${quote(join28(backup, "context.db-wal"))} ${quote(`${dbPath}-wal`)}; fi`);
43043
- const sidecarBackup = join28(backup, "project-identities");
42999
+ console.log(`Restore with hosts closed: rm -f ${quote(`${dbPath}-wal`)} ${quote(`${dbPath}-shm`)}; cp ${quote(join27(backup, "context.db"))} ${quote(dbPath)}; if test -f ${quote(join27(backup, "context.db-wal"))}; then cp ${quote(join27(backup, "context.db-wal"))} ${quote(`${dbPath}-wal`)}; fi`);
43000
+ const sidecarBackup = join27(backup, "project-identities");
43044
43001
  ensureStorageDirectorySync(sidecarBackup, true);
43045
43002
  let backupBytes = 0;
43046
43003
  for (const entry of sidecarEntries) {
43047
- const content = readFileSync23(join28(sidecarRoot, entry));
43048
- writeStorageFileAtomicSync(join28(sidecarBackup, entry), content, true);
43004
+ const content = readFileSync22(join27(sidecarRoot, entry));
43005
+ writeStorageFileAtomicSync(join27(sidecarBackup, entry), content, true);
43049
43006
  backupBytes += content.byteLength;
43050
43007
  }
43051
43008
  console.log(`Restore identity sidecars too: rm -rf ${quote(sidecarRoot)}; cp -R ${quote(sidecarBackup)} ${quote(sidecarRoot)}`);
43052
- const copiedDatabaseFiles = copyDatabaseBundle(dbPath, join28(backup, "context.db"), true);
43009
+ const copiedDatabaseFiles = copyDatabaseBundle(dbPath, join27(backup, "context.db"), true);
43053
43010
  backupBytes += copiedDatabaseFiles.reduce((size, path) => size + statSync20(path).size, 0);
43054
43011
  db = openExistingDatabase(dbPath, { readonly: false });
43055
43012
  if (!db)
@@ -43068,9 +43025,9 @@ function runMergeIdentityCli(args, deps = {}) {
43068
43025
  }
43069
43026
  if (to.startsWith("git:"))
43070
43027
  for (const directory of directories) {
43071
- const root = join28(storageDir, "project-identities");
43028
+ const root = join27(storageDir, "project-identities");
43072
43029
  ensureStorageDirectorySync(root);
43073
- const path = join28(root, `${createHash7("sha256").update(projectDirectoryKey(directory)).digest("hex")}.json`);
43030
+ const path = join27(root, `${createHash7("sha256").update(projectDirectoryKey(directory)).digest("hex")}.json`);
43074
43031
  writeStorageFileAtomicSync(path, JSON.stringify({ directory: projectDirectoryKey(directory), identity: options.to }));
43075
43032
  }
43076
43033
  console.log(`Backup: ${backup} (${backupBytes} bytes)`);
@@ -43094,8 +43051,8 @@ var init_doctor_merge_identity = __esm(async () => {
43094
43051
  });
43095
43052
 
43096
43053
  // src/commands/doctor-git-fts-map.ts
43097
- import { existsSync as existsSync38, mkdtempSync as mkdtempSync3, statSync as statSync21 } from "node:fs";
43098
- import { join as join29, resolve as resolve16 } from "node:path";
43054
+ import { existsSync as existsSync37, mkdtempSync as mkdtempSync3, statSync as statSync21 } from "node:fs";
43055
+ import { join as join28, resolve as resolve16 } from "node:path";
43099
43056
  function inspectGitFtsMap(db) {
43100
43057
  const has = (name) => Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE name=? AND type='table'").get(name));
43101
43058
  const indexed = has("git_commits_fts");
@@ -43148,8 +43105,8 @@ function runDoctorGitFtsMap(options = {}, overrides = {}) {
43148
43105
  verify: verifyInventory,
43149
43106
  ...overrides
43150
43107
  };
43151
- const context = join29(deps.storageDir, "context.db");
43152
- const store = join29(deps.storageDir, "store.db");
43108
+ const context = join28(deps.storageDir, "context.db");
43109
+ const store = join28(deps.storageDir, "store.db");
43153
43110
  let db = null, storeDb = null;
43154
43111
  let contextLocked = false, storeLocked = false;
43155
43112
  try {
@@ -43171,7 +43128,7 @@ function runDoctorGitFtsMap(options = {}, overrides = {}) {
43171
43128
  deps.print(`Stop every host, then run \`${GIT_FTS_MAP_REPAIR_COMMAND}\`. The repair backs up context.db and store.db first.`);
43172
43129
  return damaged ? 1 : 0;
43173
43130
  }
43174
- if (!existsSync38(context) || !existsSync38(store))
43131
+ if (!existsSync37(context) || !existsSync37(store))
43175
43132
  throw new Error("Both context.db and store.db must exist before paired-backup repair; no replacement store will be created");
43176
43133
  const cstat = statSync21(context), sstat = statSync21(store);
43177
43134
  if (cstat.dev === sstat.dev && cstat.ino === sstat.ino)
@@ -43201,12 +43158,12 @@ function runDoctorGitFtsMap(options = {}, overrides = {}) {
43201
43158
  const stillFree = deps.inspectHolders(deps.storageDir);
43202
43159
  if (!stillFree.safe)
43203
43160
  throw new Error(`A host appeared before backup: ${[...stillFree.blockers, stillFree.uncertainty].filter(Boolean).join("; ")}`);
43204
- const backupRoot = resolve16(options.backupRoot ?? join29(deps.storageDir, "backups"));
43161
+ const backupRoot = resolve16(options.backupRoot ?? join28(deps.storageDir, "backups"));
43205
43162
  ensureStorageDirectorySync(backupRoot, true);
43206
- const backup = mkdtempSync3(join29(backupRoot, "git-fts-map-"));
43207
- snapshot(context, join29(backup, "context.db"));
43208
- snapshot(store, join29(backup, "store.db"));
43209
- writeStorageFileSync(join29(backup, "manifest.json"), JSON.stringify({
43163
+ const backup = mkdtempSync3(join28(backupRoot, "git-fts-map-"));
43164
+ snapshot(context, join28(backup, "context.db"));
43165
+ snapshot(store, join28(backup, "store.db"));
43166
+ writeStorageFileSync(join28(backup, "manifest.json"), JSON.stringify({
43210
43167
  contextVersion: version,
43211
43168
  createdAt: new Date().toISOString(),
43212
43169
  repair: "git-fts-map",
@@ -43374,19 +43331,19 @@ var SINGLE_STORE_REQUIRED = "Magic Context's Rust mode needs a one-time migratio
43374
43331
 
43375
43332
  // src/commands/migrate.ts
43376
43333
  import { createHash as createHash8, randomBytes as randomBytes3 } from "node:crypto";
43377
- import { existsSync as existsSync39, mkdirSync as mkdirSync7, renameSync as renameSync7, unlinkSync as unlinkSync4 } from "node:fs";
43378
- import { dirname as dirname23, join as join30 } from "node:path";
43334
+ import { existsSync as existsSync38, mkdirSync as mkdirSync7, renameSync as renameSync7, unlinkSync as unlinkSync5 } from "node:fs";
43335
+ import { dirname as dirname23, join as join29 } from "node:path";
43379
43336
  function defaultOpenCodeDbPath() {
43380
43337
  return getOpenCodeDatabasePath();
43381
43338
  }
43382
43339
  function defaultCortexkitDbPath() {
43383
- return join30(getMagicContextStorageDir(), "context.db");
43340
+ return join29(getMagicContextStorageDir(), "context.db");
43384
43341
  }
43385
43342
  function defaultPiSessionsRoot() {
43386
43343
  return getPiSessionsRoot();
43387
43344
  }
43388
43345
  function defaultFs() {
43389
- return { writeFileAtomic, unlinkSync: unlinkSync4, existsSync: existsSync39, renameSync: renameSync7, mkdirSync: mkdirSync7 };
43346
+ return { writeFileAtomic, unlinkSync: unlinkSync5, existsSync: existsSync38, renameSync: renameSync7, mkdirSync: mkdirSync7 };
43390
43347
  }
43391
43348
  function stmt(db, sql) {
43392
43349
  return db.prepare(sql);
@@ -43470,7 +43427,7 @@ function claimJournalIdentity(args) {
43470
43427
  migration_key, source_session_id, target_harness, pi_session_id,
43471
43428
  final_path, stage_path, content_sha256, phase, created_at
43472
43429
  ) VALUES (?, ?, ?, ?, ?, ?, '', 'staged', ?)
43473
- ON CONFLICT(migration_key) DO NOTHING`).run(args.migrationKey, args.sourceSessionId, args.targetHarness, piSessionId, args.finalPathFor(piSessionId), join30(args.stageDir, `${args.migrationKey}.jsonl`), args.now);
43430
+ ON CONFLICT(migration_key) DO NOTHING`).run(args.migrationKey, args.sourceSessionId, args.targetHarness, piSessionId, args.finalPathFor(piSessionId), join29(args.stageDir, `${args.migrationKey}.jsonl`), args.now);
43474
43431
  const row = readPendingMigration(args.db, args.migrationKey);
43475
43432
  if (!row) {
43476
43433
  throw new Error("migration journal row disappeared during insert; aborting migration");
@@ -43978,7 +43935,7 @@ function migrateOpenCodeSessionToPi(opts) {
43978
43935
  const provider = opts.provider ?? model.provider;
43979
43936
  const modelId = opts.modelId ?? model.modelId;
43980
43937
  const cwd = session.directory ?? session.path ?? process.cwd();
43981
- const outputDir = join30(piSessionsRoot, projectPathToPiDirSlug(cwd));
43938
+ const outputDir = join29(piSessionsRoot, projectPathToPiDirSlug(cwd));
43982
43939
  const targetHarness = opts.targetHarness ?? "pi";
43983
43940
  if (cortexkitDb !== null) {
43984
43941
  assertNoUnmigratedAuthority(cortexkitDb);
@@ -44005,8 +43962,8 @@ function migrateOpenCodeSessionToPi(opts) {
44005
43962
  migrationKey,
44006
43963
  sourceSessionId: session.id,
44007
43964
  targetHarness,
44008
- finalPathFor: (id) => join30(outputDir, `${formatPiFilenameTimestamp(now)}_${id}.jsonl`),
44009
- stageDir: join30(dirname23(piSessionsRoot), MIGRATION_STAGE_DIRNAME),
43965
+ finalPathFor: (id) => join29(outputDir, `${formatPiFilenameTimestamp(now)}_${id}.jsonl`),
43966
+ stageDir: join29(dirname23(piSessionsRoot), MIGRATION_STAGE_DIRNAME),
44010
43967
  now: now.getTime()
44011
43968
  });
44012
43969
  piSessionId = claimed.row.pi_session_id;
@@ -44015,7 +43972,7 @@ function migrateOpenCodeSessionToPi(opts) {
44015
43972
  journalResumed = claimed.resumed;
44016
43973
  } else {
44017
43974
  piSessionId = generateUuidV7(now);
44018
- finalPath = join30(outputDir, `${formatPiFilenameTimestamp(now)}_${piSessionId}.jsonl`);
43975
+ finalPath = join29(outputDir, `${formatPiFilenameTimestamp(now)}_${piSessionId}.jsonl`);
44019
43976
  stagePath = "";
44020
43977
  }
44021
43978
  const buildResult = buildPiEntries({
@@ -46364,12 +46321,12 @@ var init_store_ahead_refusal = __esm(() => {
46364
46321
 
46365
46322
  // ../plugin/src/hooks/magic-context/module-transport.ts
46366
46323
  import { realpathSync as realpathSync9 } from "node:fs";
46367
- import { join as join31 } from "node:path";
46324
+ import { join as join30 } from "node:path";
46368
46325
  function monotonicNow() {
46369
46326
  return monotonicClockForTests?.() ?? performance.now();
46370
46327
  }
46371
46328
  function getDefaultSubcConnectionFile() {
46372
- return join31(getDataDir(), "cortexkit", "run", "subc-connection.json");
46329
+ return join30(getDataDir(), "cortexkit", "run", "subc-connection.json");
46373
46330
  }
46374
46331
  function errorChainSome(error, predicate) {
46375
46332
  let current = error;
@@ -46978,9 +46935,9 @@ var init_module_transport = __esm(async () => {
46978
46935
  });
46979
46936
 
46980
46937
  // src/commands/migrate-session.ts
46981
- import { existsSync as existsSync40, realpathSync as realpathSync10 } from "node:fs";
46938
+ import { existsSync as existsSync39, realpathSync as realpathSync10 } from "node:fs";
46982
46939
  import { homedir as homedir20 } from "node:os";
46983
- import path7, { join as join32 } from "node:path";
46940
+ import path7, { join as join31 } from "node:path";
46984
46941
  function existingSessionColumns(db) {
46985
46942
  const rows = db.prepare("PRAGMA table_info(session)").all();
46986
46943
  return new Set(rows.map((r) => r.name).filter((n) => typeof n === "string"));
@@ -47161,14 +47118,14 @@ function defaultOpenCodeDbPath2() {
47161
47118
  return getOpenCodeDatabasePath();
47162
47119
  }
47163
47120
  function defaultContextDbPath() {
47164
- return join32(getMagicContextStorageDir(), "context.db");
47121
+ return join31(getMagicContextStorageDir(), "context.db");
47165
47122
  }
47166
47123
  function realDeps(opencodeDb, contextDb) {
47167
47124
  return {
47168
47125
  opencodeDb,
47169
47126
  contextDb,
47170
47127
  resolveIdentity: resolveProjectIdentity,
47171
- hasGitDir: (dir) => existsSync40(join32(dir, ".git")),
47128
+ hasGitDir: (dir) => existsSync39(join31(dir, ".git")),
47172
47129
  realpath: (p) => realpathSync10(p)
47173
47130
  };
47174
47131
  }
@@ -47246,8 +47203,8 @@ async function runMigrateSessionCli(args) {
47246
47203
  printMigrateSessionHelp();
47247
47204
  return 1;
47248
47205
  }
47249
- const expandedTo = toDir.startsWith("~") ? join32(homedir20(), toDir.slice(1).replace(/^[/\\]/, "")) : toDir;
47250
- if (!existsSync40(expandedTo)) {
47206
+ const expandedTo = toDir.startsWith("~") ? join31(homedir20(), toDir.slice(1).replace(/^[/\\]/, "")) : toDir;
47207
+ if (!existsSync39(expandedTo)) {
47251
47208
  console.error(`Target directory does not exist: ${expandedTo}`);
47252
47209
  return 1;
47253
47210
  }
@@ -47670,7 +47627,7 @@ var init_tick_failure = __esm(() => {
47670
47627
  });
47671
47628
 
47672
47629
  // ../pi-plugin/src/config/index.ts
47673
- import { existsSync as existsSync41 } from "node:fs";
47630
+ import { existsSync as existsSync40 } from "node:fs";
47674
47631
  function getProjectConfigPaths(cwd) {
47675
47632
  const basePath = cortexKitProjectConfigBasePath(cwd);
47676
47633
  return [`${basePath}.jsonc`, `${basePath}.json`];
@@ -47680,10 +47637,10 @@ function getUserConfigPaths() {
47680
47637
  return [`${basePath}.jsonc`, `${basePath}.json`];
47681
47638
  }
47682
47639
  function resolveFirstExisting(paths) {
47683
- return paths.find((path) => existsSync41(path));
47640
+ return paths.find((path) => existsSync40(path));
47684
47641
  }
47685
47642
  function resolvePiLegacyFallback(sources) {
47686
- return sources.find((source) => existsSync41(source.path)) ?? null;
47643
+ return sources.find((source) => existsSync40(source.path)) ?? null;
47687
47644
  }
47688
47645
  function loadConfigFile(path, scope) {
47689
47646
  let raw;
@@ -47997,7 +47954,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
47997
47954
  if (loaded)
47998
47955
  loadedFiles.push(loaded);
47999
47956
  }
48000
- const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync41(source.path));
47957
+ const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync40(source.path));
48001
47958
  const userPath = resolveFirstExisting(getUserConfigPaths());
48002
47959
  const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
48003
47960
  const userReadPath = userPath ?? userLegacyFallback?.path;
@@ -48006,7 +47963,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
48006
47963
  if (loaded)
48007
47964
  loadedFiles.push(loaded);
48008
47965
  }
48009
- const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync41(source.path));
47966
+ const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync40(source.path));
48010
47967
  if (userLegacyFallback) {
48011
47968
  warnings.push(`[user config] reading legacy config from ${userLegacyFallback.path} until migration completes; run \`npx @cortexkit/magic-context doctor\` to consolidate into the shared CortexKit location.`);
48012
47969
  } else if (legacyUserUnmigrated) {
@@ -48151,7 +48108,7 @@ var DATABASE_REPAIR_COMMAND = "bunx @cortexkit/magic-context@latest doctor repai
48151
48108
 
48152
48109
  // src/lib/github-issue.ts
48153
48110
  import { spawnSync as spawnSync7 } from "node:child_process";
48154
- import { readFileSync as readFileSync24 } from "node:fs";
48111
+ import { readFileSync as readFileSync23 } from "node:fs";
48155
48112
  function runGhCommand(args) {
48156
48113
  try {
48157
48114
  const result = spawnSync7("gh", args, {
@@ -48178,7 +48135,7 @@ function failed(result) {
48178
48135
  function submitGithubIssue(title, bodyPath, runner = runGhCommand) {
48179
48136
  let body;
48180
48137
  try {
48181
- body = readFileSync24(bodyPath, "utf-8");
48138
+ body = readFileSync23(bodyPath, "utf-8");
48182
48139
  } catch (error) {
48183
48140
  return {
48184
48141
  ok: false,
@@ -48566,6 +48523,7 @@ var init_issue_log_templates_generated = __esm(() => {
48566
48523
  "injecting legacy compartments without visible-prefix trimming because latest stored compartment has no end_message_id",
48567
48524
  "prefix trim: boundary \x01; pass=priced; no in-pass trim applied (Hidden completion accepts text-only calibrated prompts)",
48568
48525
  'Pi subagent "\x01" is dropping unavailable built-in "\x01". This source-inspection task cannot read local files without read.',
48526
+ "v2 usage: ignored server-fallback reply inputTokens=\x01 (invalid server-fallback usage marker); keeping previous reading",
48569
48527
  "auto-search: decision outcome=error reason=\x01 lanes=\x01 nearMisses=\x01 threshold=\x01 pool=\x01 rows=\x01 workerStarted=\x01 peek=\x01 elapsedMs=\x01",
48570
48528
  "auto-search: decision outcome=no-candidates lanes=\x01 nearMisses=\x01 threshold=\x01 pool=\x01 rows=\x01 workerStarted=\x01 peek=\x01 elapsedMs=\x01",
48571
48529
  "compartment trigger: not firing at \x01% — no eligible head; offset=\x01 protectedStart=\x01 eligibleEnd=\x01 rawTokens=\x01 chunkTokens=\x01",
@@ -48591,7 +48549,6 @@ var init_issue_log_templates_generated = __esm(() => {
48591
48549
  "[magic-context] host stall profiler enabled: threshold \x01ms, sample interval \x01ms, backend v8, rotation \x01ms, reports in \x01",
48592
48550
  "rust transform deferred; the module is still applying an earlier transform of this session; attempting LKG replay: \x01",
48593
48551
  "[magic-context] WARN: workspace member has no workspace share_categories row; sharing no foreign memory categories",
48594
- "compartment trigger: force_band skipped — raw exists but protected head genuinely empty after emergency tail scale",
48595
48552
  "rust transform deferred; the module is still applying an earlier transform of this session; attempting LKG replay:",
48596
48553
  "prefix trim: boundary \x01; pass=defer; no in-pass trim applied (Hidden child first step requires a registered marker)",
48597
48554
  "[magic-context] [ERROR] compaction-marker: candidate worker unavailable \x01: \x01; marker unchanged, advancement deferred\x020p",
@@ -48632,6 +48589,7 @@ var init_issue_log_templates_generated = __esm(() => {
48632
48589
  "compartment injection entering degraded mode: boundary \x01 not in visible messages (consecutive degraded passes: \x01)\x021s",
48633
48590
  "auto-search: decision outcome=timeout lanes=\x01 nearMisses=\x01 threshold=\x01 pool=\x01 rows=\x01 workerStarted=\x01 peek=\x01 elapsedMs=\x01",
48634
48591
  "[auto-update-checker] Explicit @latest leaves the active package unpinned; OpenCode may delete it mid-session.",
48592
+ "compartment trigger: force_band skipped — no protected head meets summary admission after emergency tail scale",
48635
48593
  "historian: refusing to publish over a stale protected-tail snapshot (was: \x01); ending the run without publishing",
48636
48594
  "ERROR: compaction marker disabled: incompatible host binding harness=\x01 arity=\x01 getEntry=\x01; leaving marker pending",
48637
48595
  "heuristic cleanup: dropped \x01 tool tags, stale ctx_reduce=\x01, deduplicated \x01 tool calls, dropped \x01 system injections",
@@ -48690,6 +48648,7 @@ var init_issue_log_templates_generated = __esm(() => {
48690
48648
  "channel2 ceiling nudge delivery failed after its claim was no longer owned; lease state left unchanged:",
48691
48649
  "compaction-marker drain: CAS-clear failed but no pending blob remains; another drain already cleared it",
48692
48650
  "[\x01] primary (primary) failed validation/prompt: \x01: \x01; \x01 fallback(s) configured, subject to remaining budget",
48651
+ "v2 usage: ignored server-fallback reply inputTokens=\x01 (sum of two server runs); keeping previous reading",
48693
48652
  "caveman cleanup: switched to current rules (language-neutral word rules), rewrote \x01 compressed text tags",
48694
48653
  "[magic-context] sqlite writer site=\x01 db=opencode acquire_ms=\x01 hold_ms=\x01 work_ms=\x01 end_ms=\x01 outcome=committed",
48695
48654
  '[magic-context] partial recomp failed session=\x01 code=\x01 reason="chunk coverage ends at \x01 but chunk end is \x01"\x020s',
@@ -50305,9 +50264,9 @@ var init_issue_log_templates_generated = __esm(() => {
50305
50264
  "single-store embedding drain failed (ignored):",
50306
50265
  "system prompt meta persist failed (fail-open):",
50307
50266
  "system prompt sticky date record write failed:",
50308
- "[\x01] \x01; skipping primary for this run until reset",
50309
50267
  "[\x01] \x01: model not found, retrying with suggestion",
50310
50268
  "run \x01 left for the lease: this host is stopping",
50269
+ "skipping \x01 until \x01: provider said to retry later\x020m",
50311
50270
  "[dreamer] classify: stage=\x01 nothing to classify",
50312
50271
  "[\x01] primary (\x01/\x01) failed: \x01: \x01; trying \x01 fallback(s)\x021m,2m",
50313
50272
  "[historian] Dropped <facts> category \x01 (\x01 facts)",
@@ -50409,6 +50368,7 @@ var init_issue_log_templates_generated = __esm(() => {
50409
50368
  "channel2 delivery wrapper failed (ignored): \x01",
50410
50369
  "channel2 fold-cycle reset failed (ignored): \x01",
50411
50370
  "channel2 U-collapse reset failed (ignored): \x01",
50371
+ "Failed to ensure project artifact gitignore \x01",
50412
50372
  "lkg_fit_basis=provider_input measured_input=\x01",
50413
50373
  "mc-module: aborting historian trigger for \x01: \x01",
50414
50374
  "Pi note-nudge delivery skipped wire append: \x01",
@@ -50424,6 +50384,7 @@ var init_issue_log_templates_generated = __esm(() => {
50424
50384
  "channel2 delivery wrapper failed (ignored):",
50425
50385
  "channel2 fold-cycle reset failed (ignored):",
50426
50386
  "channel2 U-collapse reset failed (ignored):",
50387
+ "Failed to ensure project artifact gitignore",
50427
50388
  "historian skip: internal drain budget spent",
50428
50389
  "historian trigger eval: in-flight, skipping",
50429
50390
  "historian two-pass: running editor on draft",
@@ -50548,7 +50509,6 @@ var init_issue_log_templates_generated = __esm(() => {
50548
50509
  "promoted fact embedding dispatch failed:",
50549
50510
  "wrapup: compartment lease renewal failed",
50550
50511
  "report for \x01 accepted (publish=immediate)",
50551
- "[\x01] \x01; skipping \x01/\x01 for this run until reset\x022m,3m",
50552
50512
  "[mural] skipped for \x01: no active memories",
50553
50513
  "variant changed (\x01 -> \x01), triggering flush\x020s",
50554
50514
  "variant changed (\x01 -> \x01), triggering flush",
@@ -51217,13 +51177,13 @@ var init_issue_log_templates_generated = __esm(() => {
51217
51177
  }
51218
51178
  return { parts, slots };
51219
51179
  });
51220
- ISSUE_LOG_IDENTIFIERS = "abort,aborted,above_cap,accepted,acquire,adopted,agent,agent-drops-applied,aligned,already-current,already-present,already_ran_this_turn,ambiguous,anchor-missing,anchors-disagree,appended,applied,archive,assistant,attachment,attempt_mismatch,audio,auth_failed,auto_search_hint,backoff,band-crossing,band-deescalation,baseline-reset,baseline-unavailable,baseline-unevaluable,batch,batch-timeout,behind,below-emergency-band,below-threshold,boot_recovery,boundary_repair,busy,bytes,cache_hit,cache_invalid,cached_m1_missing,cadence-growth,cadence-refire,candidate-preparation,candidate_conflict,candidate_loss,candidate_rows_changed,candidates,capture_failed,cas-exhausted,cas-exhaustion,catalog,category,ceiling-threshold-met,changes-request,channel-2-ceiling-nudge,checkpoint,chunk_empty_canonical_text,chunk_fts_mapping_incomplete,chunk_partial_vector_set,chunk_window_contract_mismatch,cleared_reasoning_through_tag,close,closed-book,commit_clusters,committed,compaction,compartment-removed,compartment_render_epoch,compiled-check,compressed,compressor,config-re-read,conflict,content,content-loss,context_boundary,cooldown_active,count,coverage_fold,ctx_search_hint,custom_tool_call,darwin,data,deadline,defer,deferred,deferred_materialization,deferred_publication,definitely-no-cut,degraded,destination-not-empty,diagnostics,directive-shaped-project-rule,directory,disabled,discarded_last,divergent,document,done,drained,dreamer,dreamer-task,drift,drop_seed,duplicate_submission_budget,embed,embedded,empty,empty-session,empty_output,end_block_index,endpoint_unsupported,entry,entry-removed,envelope_unreadable,epoch_change,error,error_content,error_text,evaluate-smart-notes,exact-ordinal-ids,exception,excluded,execute,exited,expired,explicit_flush,failed,fatal,fenced_path,file,file_contains,first_render,fit_retry,flush,fold,force,force_band,force_materialization,found,frozen_slot,fts-rowid-backfill,full,function_call,generation-invalidated,git_commit_after,git_identity_unavailable,git_tag_matching,has-state,heavy_reasoning,historian,historian-editor,historian_editor,hold,home_directory,host,host-checkpoint,host_compaction,host_cut_before_watermark,host_history_change,host_rerender,http_error,identity_paused,image,images,incremental,indexed,intact,invalid-pid,invalid_prompt,invalid_scheme,invocation,io,leaked-id,lease_active,legacy,length,live-geometry,lkg_anthropic_reasoning_run_invalid,lkg_content_mismatch,lkg_invalidated_reshape,lkg_miss,lkg_model_mismatch,lkg_output_mapping_unavailable,lkg_recovery_input_rebuild,lkg_recovery_unproven,lkg_restart_rebuild,lkg_seam_invalid,lkg_system_state_mismatch,lkg_unsafe_seam,m1_delta,magic-context-host-stall,maintain-docs,malformed,management_surface,manual-full-recomp,manual-wrapup-empty,max_mutation_id,memory,memory_hash_guard_rejected,merged-reasoning-strip-exception,merged-reasoning-strip-persistence-failure,message,messages,migrated,migration_guard,migration_required,mismatch,missing,missing-active-same-category-successor,missing_tool_messages,model_change,model_failed,model_or_limit_changed,mtime_after,mutation_drift,native,network_error,newer_schema,no-anchor,no-file,no-output,no-result,no_assistant,no_head,no_originating_cache_bust,no_recent_heavy_reasoning,non-finite-input,non_zero_exit,none,not-a-fork,not-accepted,not-ready,not_a_repo,not_certified,not_found,not_owned,not_tracked,note,note_nudge_anchor,object,ok,omp,opaque,open-tool-arc,openai-codex-responses,openai-responses,opencode,opencode2,orphan_tool_message,other,overflow,oversized,ownership_lost,pair_commit_failed,parent-missing,parse,parse-invalid,parse_failed,partial,partial-message-boundary,partial-recomp,parts,pass,pass-cap,patch,path_exists,pending_agent_drop,pending_materialization,pi,placeholder,polarity-missing-mechanism,populated,post-reduce-band-escalation,post-reduce-baseline-pending,post-reduce-compliance-grace,post-reduce-regrowth-reached,pressure_refold,prewarm,primary,probe_required,proceed,process,processed_image,profile_transition,prohibition-missing-marker,project,project_change,project_memory_epoch,projected_headroom,provider-overflow-abort,provider_error,provider_returned_no_vectors,publication-failed,query,range,ratio-below-ceiling,ratio-below-gentle,raw,read-outstanding,read_error,ready,reason,reasoning,reasoning-removal-persistence-failure,reasoning-removal-read-failure,recent-reduce-refresh,reclaimable-below-floor,recomp,reconnect,recovery-request-over-limit,recovery_prefix_released,recovery_tail_normalized,redacted_reasoning,redacted_thinking,refresh,refusal-grade-final-wire-over-limit,registration_retired_during_embed,release,reminder-strip,renew,repaired,replace,resolved,response,restore,result,retry,retryable-failure,rpc_error,run,scan,scheduler_defer,schema_fence,seam-temporal-strip,search-archive,search-failure,seeded,shifted,size-walk,skip,skipped,snapshot,source,source-revision,source_changed,source_removed,spawn-failed,spawn_failed,stacked,stale,stale-skip,stale_reduce,stale_snapshot,stalled,stalled_no_progress,start,start-failed,start_block_index,steer,step-finish,step-start,step_limit,sticky-turn-floor,stop,stopped,storage,storage-busy,storage_failure,store_not_found,store_schema_unknown,store_unreadable,string,strip,strip_seed,structural,subtask,summary,summary_message,superseded,synthetic-boundary-merged,synthetic-kept-entry,system_hash,system_injected,tag,tag-delta,tag-identity-rebuild-failed,tag-identity-recurring,tag-identity-repair-once,tag-identity-repair-pending,tag-summary,tag_identity_repair,tag_prefix,tail-below-minimum,tail_size,target-superseded,test-legacy,text,thinking,thinking_binding,thinking_hold,timeout,timeout-circuit-breaker,token-budget,token_budget,too-short,tool,tool_call,tool_definitions,tool_provider,tool_result,tool_use,transform,transient,truncated,trusted-final-wire-disarm,ttl_expiry,ttl_idle,turn,type,unanchored,unavailable,unbalanced-parens,uncaptured_replay,uncertain,unknown,unknown_write_rejection,unmatched_tool_call_id,unplaceable,unregistered,unresolved,update,upgrade,upgrade_state,url,user-memories,user-profile-is-not-project-memory,user_flush,user_memory_review,v1,v2,v2-archive-read,v2-archive-ready,v2-archive-result,validated,validation-failed,variant_change,verbose,verified,verify,video,view_error,waiting,waiting-for-entry,weak_lookahead_final_compartment,whole-session-smaller-than-tail,worker-busy,worker-error,worker-failed,wrapup,x64".split(",");
51180
+ ISSUE_LOG_IDENTIFIERS = "abort,aborted,above_cap,accepted,acquire,adopted,agent,agent-drops-applied,aligned,already-current,already-present,already_ran_this_turn,ambiguous,anchor-missing,anchors-disagree,appended,applied,archive,assistant,attachment,attempt_mismatch,audio,auth_failed,auto_search_hint,backoff,band-crossing,band-deescalation,baseline-reset,baseline-unavailable,baseline-unevaluable,batch,batch-timeout,behind,below-emergency-band,below-threshold,boot_recovery,boundary,boundary_repair,busy,bytes,cache_hit,cache_invalid,cached_m1_missing,cadence-growth,cadence-refire,candidate-preparation,candidate_conflict,candidate_loss,candidate_rows_changed,candidates,capture_failed,cas-exhausted,cas-exhaustion,catalog,category,ceiling-threshold-met,changes-request,channel-2-ceiling-nudge,checkpoint,chunk_empty_canonical_text,chunk_fts_mapping_incomplete,chunk_partial_vector_set,chunk_window_contract_mismatch,cleared_reasoning_through_tag,close,closed-book,commit_clusters,committed,compaction,compartment-removed,compartment_render_epoch,compiled-check,compressed,compressor,config-re-read,conflict,content,content-loss,context_boundary,cooldown_active,count,coverage_fold,ctx_search_hint,custom_tool_call,darwin,data,deadline,defer,deferred,deferred_materialization,deferred_publication,definitely-no-cut,degraded,destination-not-empty,diagnostics,dimensions_mismatch,directive-shaped-project-rule,directory,disabled,discarded_last,divergent,document,done,drained,dreamer,dreamer-task,drift,drop_seed,duplicate_submission_budget,embed,embedded,empty,empty-session,empty_output,end_block_index,endpoint_unsupported,entry,entry-removed,envelope_unreadable,epoch_change,error,error_content,error_text,evaluate-smart-notes,exact-ordinal-ids,exception,excluded,execute,exited,expired,explicit_flush,failed,fatal,fenced_path,file,file_contains,first_render,fit_retry,flush,fold,force,force_band,force_materialization,found,frozen_slot,fts-rowid-backfill,full,function_call,generation-invalidated,git_commit_after,git_identity_unavailable,git_tag_matching,has-state,heavy_reasoning,historian,historian-editor,historian_editor,hold,home_directory,host,host-checkpoint,host_compaction,host_cut_before_watermark,host_history_change,host_rerender,http_error,identity_paused,image,images,incremental,indexed,intact,invalid-pid,invalid_prompt,invalid_scheme,invocation,io,leaked-id,lease_active,legacy,length,live-geometry,lkg_anthropic_reasoning_run_invalid,lkg_content_mismatch,lkg_invalidated_reshape,lkg_miss,lkg_model_mismatch,lkg_output_mapping_unavailable,lkg_recovery_input_rebuild,lkg_recovery_unproven,lkg_restart_rebuild,lkg_seam_invalid,lkg_system_state_mismatch,lkg_unsafe_seam,m1_delta,magic-context-host-stall,maintain-docs,malformed,management_surface,manual-full-recomp,manual-wrapup-empty,max_mutation_id,memory,memory_hash_guard_rejected,merged-reasoning-strip-exception,merged-reasoning-strip-persistence-failure,message,messages,migrated,migration_guard,migration_required,mismatch,missing,missing-active-same-category-successor,missing_tool_messages,model_change,model_failed,model_or_limit_changed,mtime_after,mutation_drift,native,network_error,newer_schema,no-anchor,no-file,no-output,no-result,no_assistant,no_head,no_originating_cache_bust,no_recent_heavy_reasoning,non-finite-input,non_zero_exit,none,not-a-fork,not-accepted,not-ready,not_a_repo,not_certified,not_found,not_owned,not_tracked,note,note_nudge_anchor,object,ok,omp,opaque,open-tool-arc,openai-codex-responses,openai-responses,opencode,opencode2,orphan_tool_message,other,overflow,oversized,ownership_lost,pair_commit_failed,parent-missing,parse,parse-invalid,parse_failed,partial,partial-message-boundary,partial-recomp,parts,pass,pass-cap,patch,path_exists,pending_agent_drop,pending_materialization,pi,placeholder,polarity-missing-mechanism,populated,post-reduce-band-escalation,post-reduce-baseline-pending,post-reduce-compliance-grace,post-reduce-regrowth-reached,pressure_refold,prewarm,primary,probe_required,proceed,process,processed_image,profile_transition,prohibition-missing-marker,project,project_change,project_memory_epoch,projected_headroom,provider-overflow-abort,provider_error,provider_returned_no_vectors,publication-failed,query,range,ratio-below-ceiling,ratio-below-gentle,raw,read-outstanding,read_error,ready,reason,reasoning,reasoning-removal-persistence-failure,reasoning-removal-read-failure,recent-reduce-refresh,reclaimable-below-floor,recomp,reconnect,recovery-request-over-limit,recovery_prefix_released,recovery_tail_normalized,redacted_reasoning,redacted_thinking,refresh,refusal-grade-final-wire-over-limit,registration_retired_during_embed,release,reminder-strip,renew,repaired,replace,resolved,response,restore,result,retry,retryable-failure,rpc_error,run,scan,scheduler_defer,schema_fence,seam-temporal-strip,search-archive,search-failure,seeded,shifted,size-walk,skip,skipped,snapshot,source,source-revision,source_changed,source_removed,spawn-failed,spawn_failed,stacked,stale,stale-skip,stale_reduce,stale_snapshot,stalled,stalled_no_progress,start,start-failed,start_block_index,steer,step-finish,step-start,step_limit,sticky-turn-floor,stop,stopped,storage,storage-busy,storage_failure,store_not_found,store_schema_unknown,store_unreadable,string,strip,strip_seed,structural,subtask,summary,summary_message,superseded,synthetic-boundary-merged,synthetic-kept-entry,system_hash,system_injected,tag,tag-delta,tag-identity-rebuild-failed,tag-identity-recurring,tag-identity-repair-once,tag-identity-repair-pending,tag-summary,tag_identity_repair,tag_prefix,tail-below-minimum,tail_size,target-superseded,test-legacy,text,thinking,thinking_binding,thinking_hold,timeout,timeout-circuit-breaker,token-budget,token_budget,too-short,tool,tool_call,tool_definitions,tool_provider,tool_result,tool_use,transform,transient,truncated,trusted-final-wire-disarm,ttl_expiry,ttl_idle,turn,type,unanchored,unavailable,unbalanced-parens,uncaptured_replay,uncertain,unknown,unknown_write_rejection,unmatched_tool_call_id,unplaceable,unregistered,unresolved,update,upgrade,upgrade_state,url,usage,user-memories,user-profile-is-not-project-memory,user_flush,user_memory_review,v1,v2,v2-archive-read,v2-archive-ready,v2-archive-result,validated,validation-failed,variant_change,verbose,verified,verify,video,view_error,waiting,waiting-for-entry,weak_lookahead_final_compartment,whole-session-smaller-than-tail,worker-busy,worker-error,worker-failed,wrapup,x64".split(",");
51221
51181
  });
51222
51182
 
51223
51183
  // src/lib/log-lines.ts
51224
- import { existsSync as existsSync42, readFileSync as readFileSync25, statSync as statSync22 } from "node:fs";
51184
+ import { existsSync as existsSync41, readFileSync as readFileSync24, statSync as statSync22 } from "node:fs";
51225
51185
  import { tmpdir as tmpdir3 } from "node:os";
51226
- import { join as join33 } from "node:path";
51186
+ import { join as join32 } from "node:path";
51227
51187
  function tokenize(input, limit = Number.POSITIVE_INFINITY) {
51228
51188
  const tokens = [];
51229
51189
  let index = 0;
@@ -51509,20 +51469,20 @@ function parseLogLine(line) {
51509
51469
  }
51510
51470
  function getMagicContextLogPaths(harness, options = {}) {
51511
51471
  const override = options.override === undefined ? process.env.MAGIC_CONTEXT_LOG_PATH?.trim() : options.override?.trim();
51512
- const storageLogs = join33(options.storageDir ?? getMagicContextStorageDir(), "logs");
51472
+ const storageLogs = join32(options.storageDir ?? getMagicContextStorageDir(), "logs");
51513
51473
  return [
51514
51474
  ...override ? [override] : [],
51515
- join33(options.tempDir ?? tmpdir3(), harness, "magic-context", "magic-context.log"),
51516
- join33(storageLogs, `magic-context.${harness}.log`),
51517
- join33(storageLogs, "magic-context.log")
51475
+ join32(options.tempDir ?? tmpdir3(), harness, "magic-context", "magic-context.log"),
51476
+ join32(storageLogs, `magic-context.${harness}.log`),
51477
+ join32(storageLogs, "magic-context.log")
51518
51478
  ].filter((path, index, paths) => paths.indexOf(path) === index);
51519
51479
  }
51520
51480
  function inspectLogFile(path) {
51521
- if (!existsSync42(path)) {
51481
+ if (!existsSync41(path)) {
51522
51482
  return { path, exists: false, sizeKb: 0, lineCount: 0, grammar: "unknown" };
51523
51483
  }
51524
51484
  try {
51525
- const content = readFileSync25(path, "utf8");
51485
+ const content = readFileSync24(path, "utf8");
51526
51486
  const lines = content.split(/\r?\n/).filter((line) => line.length > 0);
51527
51487
  const grammars = new Set(lines.flatMap((line) => {
51528
51488
  const parsed = parseLogLine(line);
@@ -51549,7 +51509,7 @@ function readLogLines(files) {
51549
51509
  return [];
51550
51510
  try {
51551
51511
  let precedingTimestamp = "";
51552
- return readFileSync25(file.path, "utf8").split(/\r?\n/).filter((line) => line.length > 0).map((line, lineIndex) => {
51512
+ return readFileSync24(file.path, "utf8").split(/\r?\n/).filter((line) => line.length > 0).map((line, lineIndex) => {
51553
51513
  precedingTimestamp = parseLogLine(line)?.ts ?? precedingTimestamp;
51554
51514
  return { line, timestamp: precedingTimestamp, fileIndex, lineIndex };
51555
51515
  });
@@ -52157,8 +52117,8 @@ var init_issue_body = __esm(() => {
52157
52117
  });
52158
52118
 
52159
52119
  // src/lib/omp-hide-secrets.ts
52160
- import { existsSync as existsSync43, readdirSync as readdirSync9, readFileSync as readFileSync26, statSync as statSync23 } from "node:fs";
52161
- import { join as join34, resolve as resolve17 } from "node:path";
52120
+ import { existsSync as existsSync42, readdirSync as readdirSync9, readFileSync as readFileSync25, statSync as statSync23 } from "node:fs";
52121
+ import { join as join33, resolve as resolve17 } from "node:path";
52162
52122
  function stripYamlComment(line) {
52163
52123
  let quote = null;
52164
52124
  for (let index = 0;index < line.length; index += 1) {
@@ -52281,7 +52241,7 @@ function readHideSecretsFromJson(text) {
52281
52241
  function readSource(layer, path, format) {
52282
52242
  let text;
52283
52243
  try {
52284
- text = readFileSync26(path, "utf-8");
52244
+ text = readFileSync25(path, "utf-8");
52285
52245
  } catch (error) {
52286
52246
  const code = error.code;
52287
52247
  return {
@@ -52309,22 +52269,22 @@ function isNonEmptyDirectory(path) {
52309
52269
  function collectHideSecretsSources(cwd, home = envFirstHomeDir()) {
52310
52270
  const sources = [];
52311
52271
  const agentDir = getOmpAgentDir();
52312
- const mainConfig = ["config.yml", "config.yaml"].map((name) => join34(agentDir, name)).find((path) => existsSync43(path));
52272
+ const mainConfig = ["config.yml", "config.yaml"].map((name) => join33(agentDir, name)).find((path) => existsSync42(path));
52313
52273
  if (mainConfig)
52314
52274
  sources.push(readSource("user", mainConfig, "yaml"));
52315
- const projectDir = join34(cwd, ".omp");
52275
+ const projectDir = join33(cwd, ".omp");
52316
52276
  if (resolve17(cwd) !== resolve17(home) && isNonEmptyDirectory(projectDir)) {
52317
52277
  for (const [name, format] of [
52318
52278
  ["settings.json", "json"],
52319
52279
  ["config.yml", "yaml"]
52320
52280
  ]) {
52321
- const path = join34(projectDir, name);
52322
- if (existsSync43(path))
52281
+ const path = join33(projectDir, name);
52282
+ if (existsSync42(path))
52323
52283
  sources.push(readSource("project", path, format));
52324
52284
  }
52325
52285
  }
52326
52286
  for (const path of getOmpConfigOverlayPaths(cwd)) {
52327
- if (existsSync43(path))
52287
+ if (existsSync42(path))
52328
52288
  sources.push(readSource("overlay", path, "yaml"));
52329
52289
  }
52330
52290
  return sources;
@@ -52382,9 +52342,9 @@ var init_omp_hide_secrets = __esm(() => {
52382
52342
 
52383
52343
  // src/commands/doctor-omp.ts
52384
52344
  import { execFileSync as execFileSync8, spawnSync as spawnSync8 } from "node:child_process";
52385
- import { existsSync as existsSync44, readFileSync as readFileSync27 } from "node:fs";
52345
+ import { existsSync as existsSync43, readFileSync as readFileSync26 } from "node:fs";
52386
52346
  import { createRequire as createRequire3 } from "node:module";
52387
- import { isAbsolute as isAbsolute8, join as join35, resolve as resolve18 } from "node:path";
52347
+ import { isAbsolute as isAbsolute8, join as join34, resolve as resolve18 } from "node:path";
52388
52348
  function parseSemver(value) {
52389
52349
  const match = value?.match(/(\d+)\.(\d+)\.(\d+)/);
52390
52350
  return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
@@ -52426,10 +52386,10 @@ function selfVersion() {
52426
52386
  return "unknown";
52427
52387
  }
52428
52388
  function readConfig2(path) {
52429
- if (!existsSync44(path))
52389
+ if (!existsSync43(path))
52430
52390
  return {};
52431
52391
  try {
52432
- const parsed = import_comment_json8.parse(readFileSync27(path, "utf-8"));
52392
+ const parsed = import_comment_json8.parse(readFileSync26(path, "utf-8"));
52433
52393
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? {} : { error: "top level is not an object" };
52434
52394
  } catch (error) {
52435
52395
  return { error: error instanceof Error ? error.message : String(error) };
@@ -52439,7 +52399,7 @@ function pluginDeclaresOmp(path) {
52439
52399
  if (!path)
52440
52400
  return null;
52441
52401
  try {
52442
- const pkg = JSON.parse(readFileSync27(join35(path, "package.json"), "utf-8"));
52402
+ const pkg = JSON.parse(readFileSync26(join34(path, "package.json"), "utf-8"));
52443
52403
  return Array.isArray(pkg.omp?.extensions) || Array.isArray(pkg.pi?.extensions);
52444
52404
  } catch {
52445
52405
  return null;
@@ -52528,7 +52488,7 @@ async function runHealthChecks(options) {
52528
52488
  }
52529
52489
  }
52530
52490
  const userConfigPath = getOmpUserConfigPath();
52531
- if (!existsSync44(userConfigPath)) {
52491
+ if (!existsSync43(userConfigPath)) {
52532
52492
  add(results, "warn", `No Magic Context user config at ${userConfigPath}`);
52533
52493
  repairPlan.writeUserConfig = true;
52534
52494
  } else {
@@ -52545,12 +52505,12 @@ async function runHealthChecks(options) {
52545
52505
  for (const warning of loaded.warnings.slice(0, 5))
52546
52506
  add(results, "warn", warning);
52547
52507
  const storage = getMagicContextStorageResolution();
52548
- const dbPath = join35(storage.path, "context.db");
52508
+ const dbPath = join34(storage.path, "context.db");
52549
52509
  if (isMagicContextStorageOutsideEngram(storage.path)) {
52550
52510
  add(results, "warn", `Magic Context storage is at ${storage.path}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
52551
52511
  }
52552
52512
  add(results, "info", `Shared storage: ${storage.path} (source: ${storage.source})`);
52553
- if (!existsSync44(dbPath))
52513
+ if (!existsSync43(dbPath))
52554
52514
  add(results, "info", `Shared context DB will be created at ${dbPath}`);
52555
52515
  else {
52556
52516
  let db = null;
@@ -52615,7 +52575,7 @@ function writeDefaultConfig(path) {
52615
52575
  }
52616
52576
  async function repair(plan, deps, prompts, cwd) {
52617
52577
  let fixed = 0;
52618
- if (plan.writeUserConfig && !existsSync44(getOmpUserConfigPath())) {
52578
+ if (plan.writeUserConfig && !existsSync43(getOmpUserConfigPath())) {
52619
52579
  writeDefaultConfig(getOmpUserConfigPath());
52620
52580
  prompts.log.success(`Wrote default Magic Context config to ${getOmpUserConfigPath()}`);
52621
52581
  fixed += 1;
@@ -52728,7 +52688,7 @@ function runGhCommandWithDeps(deps, args) {
52728
52688
  async function runIssueFlow(options) {
52729
52689
  if (options.reportPath) {
52730
52690
  const report = await runHealthChecks({ ...options, quiet: true });
52731
- const path = isAbsolute8(options.reportPath) ? options.reportPath : join35(options.cwd, options.reportPath);
52691
+ const path = isAbsolute8(options.reportPath) ? options.reportPath : join34(options.cwd, options.reportPath);
52732
52692
  const bundle = writeOmpIssueReport(path, ompIssueBody("Generated non-interactively by `doctor --issue --report`.", report, readLogLines(report.logFiles), null, options.cwd));
52733
52693
  options.prompts.log.success(bundle.fullPath ? `Sanitized report written to ${bundle.path}; full report at ${bundle.fullPath}` : `Sanitized report written to ${bundle.path}`);
52734
52694
  return 0;
@@ -52755,7 +52715,7 @@ async function runIssueFlow(options) {
52755
52715
  ]);
52756
52716
  sessionFilter = choice === "__all__" ? null : choice;
52757
52717
  }
52758
- const path = join35(options.cwd, `magic-context-omp-issue-${timestamp2(options.deps.now())}.md`);
52718
+ const path = join34(options.cwd, `magic-context-omp-issue-${timestamp2(options.deps.now())}.md`);
52759
52719
  const bundle = writeOmpIssueReport(path, ompIssueBody(description, report, logLines, sessionFilter, options.cwd));
52760
52720
  options.prompts.log.success(bundle.fullPath ? `Sanitized report written to ${bundle.path}; full report at ${bundle.fullPath}` : `Sanitized report written to ${bundle.path}`);
52761
52721
  if (await options.prompts.confirm("Submit this issue on GitHub now?", false)) {
@@ -52849,11 +52809,13 @@ async function probeEmbeddingEndpoint(options) {
52849
52809
  }
52850
52810
  const inputType = options.inputType?.trim();
52851
52811
  const truncateMode = options.truncate?.trim();
52812
+ const requestedDimensions = typeof options.dimensions === "number" && Number.isInteger(options.dimensions) && options.dimensions > 0 ? options.dimensions : undefined;
52852
52813
  const body = JSON.stringify({
52853
52814
  model: options.model,
52854
52815
  input: "magic-context probe",
52855
52816
  ...inputType ? { input_type: inputType } : {},
52856
- ...truncateMode ? { truncate: truncateMode } : {}
52817
+ ...truncateMode ? { truncate: truncateMode } : {},
52818
+ ...requestedDimensions ? { dimensions: requestedDimensions } : {}
52857
52819
  });
52858
52820
  let response;
52859
52821
  try {
@@ -52891,6 +52853,14 @@ async function probeEmbeddingEndpoint(options) {
52891
52853
  preview: await readPreview(parsed)
52892
52854
  };
52893
52855
  }
52856
+ if (requestedDimensions !== undefined && dimensions !== requestedDimensions) {
52857
+ return {
52858
+ kind: "dimensions_mismatch",
52859
+ status,
52860
+ requested: requestedDimensions,
52861
+ returned: dimensions
52862
+ };
52863
+ }
52894
52864
  return { kind: "ok", status, dimensions };
52895
52865
  }
52896
52866
  const preview = await previewErrorBody(response);
@@ -53725,12 +53695,12 @@ function listShadowBackfillStalls(db, projectIdentity) {
53725
53695
  var SHADOW_BACKFILL_PROVENANCE_KEY = "_magicContextShadowBackfill";
53726
53696
 
53727
53697
  // ../plugin/src/shared/auto-update-provenance.ts
53728
- import { existsSync as existsSync45, readFileSync as readFileSync28 } from "node:fs";
53698
+ import { existsSync as existsSync44, readFileSync as readFileSync27 } from "node:fs";
53729
53699
  function readAutoUpdateCheckState(path) {
53730
- if (!existsSync45(path))
53700
+ if (!existsSync44(path))
53731
53701
  return null;
53732
53702
  try {
53733
- const value = JSON.parse(readFileSync28(path, "utf-8"));
53703
+ const value = JSON.parse(readFileSync27(path, "utf-8"));
53734
53704
  if (!value || typeof value !== "object" || Array.isArray(value))
53735
53705
  return null;
53736
53706
  const raw = value;
@@ -53758,14 +53728,14 @@ var init_auto_update_provenance = () => {};
53758
53728
  // ../plugin/src/shared/tui-config.ts
53759
53729
  import {
53760
53730
  chmodSync as chmodSync4,
53761
- existsSync as existsSync46,
53731
+ existsSync as existsSync45,
53762
53732
  mkdirSync as mkdirSync8,
53763
- readFileSync as readFileSync29,
53733
+ readFileSync as readFileSync28,
53764
53734
  renameSync as renameSync8,
53765
53735
  statSync as statSync24,
53766
53736
  writeFileSync as writeFileSync8
53767
53737
  } from "node:fs";
53768
- import { dirname as dirname24, join as join36 } from "node:path";
53738
+ import { dirname as dirname24, join as join35 } from "node:path";
53769
53739
  function pluginEntryId(entry) {
53770
53740
  if (typeof entry === "string")
53771
53741
  return entry;
@@ -53806,11 +53776,11 @@ function writeTuiConfigAtomic(configPath, config) {
53806
53776
  }
53807
53777
  function resolveTuiConfigPath(configDirOverride) {
53808
53778
  const configDir = configDirOverride ?? getOpenCodeConfigPaths({ binary: "opencode" }).configDir;
53809
- const jsoncPath = join36(configDir, "tui.jsonc");
53810
- const jsonPath = join36(configDir, "tui.json");
53811
- if (existsSync46(jsoncPath))
53779
+ const jsoncPath = join35(configDir, "tui.jsonc");
53780
+ const jsonPath = join35(configDir, "tui.json");
53781
+ if (existsSync45(jsoncPath))
53812
53782
  return jsoncPath;
53813
- if (existsSync46(jsonPath))
53783
+ if (existsSync45(jsonPath))
53814
53784
  return jsonPath;
53815
53785
  return jsoncPath;
53816
53786
  }
@@ -53818,8 +53788,8 @@ function ensureTuiPluginEntry(options = {}) {
53818
53788
  try {
53819
53789
  const configPath = resolveTuiConfigPath(options.configDir);
53820
53790
  let config = {};
53821
- if (existsSync46(configPath)) {
53822
- const raw = readFileSync29(configPath, "utf-8");
53791
+ if (existsSync45(configPath)) {
53792
+ const raw = readFileSync28(configPath, "utf-8");
53823
53793
  config = import_comment_json9.parse(raw) ?? {};
53824
53794
  }
53825
53795
  const plugins = Array.isArray(config.plugin) ? [...config.plugin] : [];
@@ -53871,9 +53841,9 @@ var init_tui_config = __esm(() => {
53871
53841
  });
53872
53842
 
53873
53843
  // src/lib/diagnostics-opencode.ts
53874
- import { existsSync as existsSync47, readdirSync as readdirSync10, readFileSync as readFileSync30, statSync as statSync25 } from "node:fs";
53844
+ import { existsSync as existsSync46, readdirSync as readdirSync10, readFileSync as readFileSync29, statSync as statSync25 } from "node:fs";
53875
53845
  import { createRequire as createRequire4 } from "node:module";
53876
- import { join as join37 } from "node:path";
53846
+ import { join as join36 } from "node:path";
53877
53847
  function getSelfVersion() {
53878
53848
  const require2 = createRequire4(import.meta.url);
53879
53849
  for (const relPath of ["../../package.json", "../package.json"]) {
@@ -53888,7 +53858,7 @@ function getSelfVersion() {
53888
53858
  }
53889
53859
  function readLegacyCachedVersion(root) {
53890
53860
  try {
53891
- const pkg = JSON.parse(readFileSync30(getOpenCodePluginPackageJsonPath(root), "utf-8"));
53861
+ const pkg = JSON.parse(readFileSync29(getOpenCodePluginPackageJsonPath(root), "utf-8"));
53892
53862
  return typeof pkg.version === "string" ? pkg.version : undefined;
53893
53863
  } catch {
53894
53864
  return;
@@ -53897,7 +53867,7 @@ function readLegacyCachedVersion(root) {
53897
53867
  function collectOpenCodePluginCacheReport(hostGeneration, opencodeConfig) {
53898
53868
  const installs = [];
53899
53869
  for (const root of getOpenCodePluginCacheRoots()) {
53900
- if (!existsSync47(root))
53870
+ if (!existsSync46(root))
53901
53871
  continue;
53902
53872
  const spec = root.endsWith("@latest") ? "latest" : "(bare)";
53903
53873
  installs.push({
@@ -53931,7 +53901,7 @@ function getStorageResolution() {
53931
53901
  }
53932
53902
  function fileSize(path) {
53933
53903
  try {
53934
- return existsSync47(path) ? statSync25(path).size : 0;
53904
+ return existsSync46(path) ? statSync25(path).size : 0;
53935
53905
  } catch {
53936
53906
  return 0;
53937
53907
  }
@@ -53943,10 +53913,10 @@ function sanitizeValue(value) {
53943
53913
  return sanitizeConfigValue(value);
53944
53914
  }
53945
53915
  function readConfig3(path) {
53946
- if (!existsSync47(path))
53916
+ if (!existsSync46(path))
53947
53917
  return { value: null };
53948
53918
  try {
53949
- const raw = readFileSync30(path, "utf-8");
53919
+ const raw = readFileSync29(path, "utf-8");
53950
53920
  const value = import_comment_json10.parse(raw);
53951
53921
  return { value };
53952
53922
  } catch (error) {
@@ -53971,7 +53941,7 @@ function configHasPluginEntry(config) {
53971
53941
  }
53972
53942
  function parseHistorianDumpMeta(path) {
53973
53943
  try {
53974
- const xml = readFileSync30(path, "utf-8");
53944
+ const xml = readFileSync29(path, "utf-8");
53975
53945
  const parsed = parseCompartmentOutput(xml);
53976
53946
  const factCountByCategory = {};
53977
53947
  for (const fact of parsed.facts) {
@@ -54004,11 +53974,11 @@ function parseHistorianDumpMeta(path) {
54004
53974
  }
54005
53975
  }
54006
53976
  function listDumpsInDir(dir, limit) {
54007
- if (!existsSync47(dir))
53977
+ if (!existsSync46(dir))
54008
53978
  return { count: 0, recent: [] };
54009
53979
  try {
54010
53980
  const entries = readdirSync10(dir).filter((name) => name.endsWith(".xml")).map((name) => {
54011
- const stat = statSync25(join37(dir, name));
53981
+ const stat = statSync25(join36(dir, name));
54012
53982
  return {
54013
53983
  name,
54014
53984
  mtime: stat.mtimeMs,
@@ -54017,7 +53987,7 @@ function listDumpsInDir(dir, limit) {
54017
53987
  }).sort((a, b) => b.mtime - a.mtime);
54018
53988
  const now = Date.now();
54019
53989
  const recent = entries.slice(0, limit).map((entry) => {
54020
- const meta = parseHistorianDumpMeta(join37(dir, entry.name));
53990
+ const meta = parseHistorianDumpMeta(join36(dir, entry.name));
54021
53991
  const summary = {
54022
53992
  name: entry.name,
54023
53993
  ageMinutes: Math.round((now - entry.mtime) / 60000),
@@ -54128,7 +54098,7 @@ function collectRecentSessionsFromDatabase(database) {
54128
54098
  });
54129
54099
  }
54130
54100
  async function collectDatabaseRows(path, read) {
54131
- if (!existsSync47(path))
54101
+ if (!existsSync46(path))
54132
54102
  return { available: false, reason: "path missing" };
54133
54103
  let backend;
54134
54104
  try {
@@ -54160,7 +54130,7 @@ async function collectRecentSessions(resolution, hostGeneration) {
54160
54130
  });
54161
54131
  }
54162
54132
  async function collectHistorianFailures(storageDirPath) {
54163
- return collectDatabaseRows(join37(storageDirPath, "context.db"), (db) => {
54133
+ return collectDatabaseRows(join36(storageDirPath, "context.db"), (db) => {
54164
54134
  const rows = db.prepare("SELECT session_id, historian_failure_count, historian_last_error, historian_last_failure_at FROM session_meta WHERE historian_failure_count > 0 ORDER BY historian_last_failure_at DESC LIMIT 10").all();
54165
54135
  return rows.map((row) => {
54166
54136
  const sessionId = typeof row.session_id === "string" ? row.session_id : "<unknown>";
@@ -54173,7 +54143,7 @@ async function collectHistorianFailures(storageDirPath) {
54173
54143
  });
54174
54144
  }
54175
54145
  async function collectHistorianRuns(storageDirPath) {
54176
- return collectDatabaseRows(join37(storageDirPath, "context.db"), (db) => {
54146
+ return collectDatabaseRows(join36(storageDirPath, "context.db"), (db) => {
54177
54147
  const aggRows = db.prepare(`SELECT session_id,
54178
54148
  COUNT(*) AS total,
54179
54149
  SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) AS success,
@@ -54228,7 +54198,7 @@ async function collectDiagnostics() {
54228
54198
  const magicContextConfig = readConfig3(configPaths.magicContextConfig);
54229
54199
  const storageResolution = getStorageResolution();
54230
54200
  const storageDirPath = storageResolution.path;
54231
- const contextDbPath = join37(storageDirPath, "context.db");
54201
+ const contextDbPath = join36(storageDirPath, "context.db");
54232
54202
  let compactionEnabled = false;
54233
54203
  try {
54234
54204
  compactionEnabled = isCompactionEnabled(loadPluginConfig(process.cwd()));
@@ -54260,7 +54230,7 @@ async function collectDiagnostics() {
54260
54230
  opencodeConfigHasPlugin: configHasPluginEntry(opencodeConfig.value),
54261
54231
  tuiConfigHasPlugin: configHasPluginEntry(tuiConfig.value),
54262
54232
  magicContextConfig: {
54263
- exists: existsSync47(configPaths.magicContextConfig),
54233
+ exists: existsSync46(configPaths.magicContextConfig),
54264
54234
  ...magicContextConfig.error ? { parseError: magicContextConfig.error } : {},
54265
54235
  flags: sanitizeValue(magicContextConfig.value ?? {}) ?? {}
54266
54236
  },
@@ -54268,7 +54238,7 @@ async function collectDiagnostics() {
54268
54238
  storageDir: {
54269
54239
  path: storageDirPath,
54270
54240
  source: storageResolution.source,
54271
- exists: existsSync47(storageDirPath),
54241
+ exists: existsSync46(storageDirPath),
54272
54242
  contextDbSizeBytes: fileSize(contextDbPath)
54273
54243
  },
54274
54244
  openCodeDatabase: {
@@ -54538,9 +54508,9 @@ var init_embedding_local = __esm(async () => {
54538
54508
 
54539
54509
  // src/lib/embedding-runtime.ts
54540
54510
  import { spawnSync as spawnSync9 } from "node:child_process";
54541
- import { existsSync as existsSync48, readFileSync as readFileSync31 } from "node:fs";
54511
+ import { existsSync as existsSync47, readFileSync as readFileSync30 } from "node:fs";
54542
54512
  import { createRequire as createRequire5 } from "node:module";
54543
- import { dirname as dirname25, join as join38, sep as sep2 } from "node:path";
54513
+ import { dirname as dirname25, join as join37, sep as sep2 } from "node:path";
54544
54514
  function describeError(error) {
54545
54515
  const message = error instanceof Error ? error.message : String(error ?? "unknown error");
54546
54516
  const code = error?.code;
@@ -54682,11 +54652,11 @@ function expectedBinaryRelPath(platform, arch) {
54682
54652
  const supportedArch = arch === "x64" || arch === "arm64";
54683
54653
  if (!supportedPlatform || !supportedArch)
54684
54654
  return null;
54685
- return join38("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
54655
+ return join37("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
54686
54656
  }
54687
54657
  function onnxRuntimeNodeVersion(packageDir) {
54688
54658
  try {
54689
- const parsed = JSON.parse(readFileSync31(join38(packageDir, "package.json"), "utf8"));
54659
+ const parsed = JSON.parse(readFileSync30(join37(packageDir, "package.json"), "utf8"));
54690
54660
  return typeof parsed.version === "string" ? parsed.version : undefined;
54691
54661
  } catch {
54692
54662
  return;
@@ -54735,7 +54705,7 @@ function formatLocalEmbeddingRuntimeWasmSelected(status) {
54735
54705
  function requireNodeWasmBundle(probe, candidates) {
54736
54706
  if (probe.state === "failed")
54737
54707
  return probe;
54738
- const bundlePath = candidates.find((candidate) => existsSync48(candidate));
54708
+ const bundlePath = candidates.find((candidate) => existsSync47(candidate));
54739
54709
  return bundlePath ? probe : {
54740
54710
  state: "failed",
54741
54711
  reason: `functional Node WASM Transformers bundle is missing (checked ${candidates.join(", ")})`
@@ -54743,13 +54713,13 @@ function requireNodeWasmBundle(probe, candidates) {
54743
54713
  }
54744
54714
  function nodeWasmBundleCandidates(installRoot) {
54745
54715
  return [
54746
- join38(installRoot, "dist", "transformers-node-wasm.js"),
54747
- join38(installRoot, "node_modules", "@cortexkit", "opencode-magic-context", "dist", "transformers-node-wasm.js"),
54748
- join38(installRoot, "node_modules", "@cortexkit", "pi-magic-context", "dist", "transformers-node-wasm.js")
54716
+ join37(installRoot, "dist", "transformers-node-wasm.js"),
54717
+ join37(installRoot, "node_modules", "@cortexkit", "opencode-magic-context", "dist", "transformers-node-wasm.js"),
54718
+ join37(installRoot, "node_modules", "@cortexkit", "pi-magic-context", "dist", "transformers-node-wasm.js")
54749
54719
  ];
54750
54720
  }
54751
54721
  function probeWasmRuntimeAt(installRoot) {
54752
- const requireFn = createRequire5(join38(installRoot, "package.json"));
54722
+ const requireFn = createRequire5(join37(installRoot, "package.json"));
54753
54723
  return requireNodeWasmBundle(probeWasmRuntimeFromRequire(requireFn), nodeWasmBundleCandidates(installRoot));
54754
54724
  }
54755
54725
  function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
@@ -54758,9 +54728,9 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
54758
54728
  const wasm = probeWasmRuntimeAt(installRoot);
54759
54729
  return wasm.state === "ok" ? { state: "wasm-selected", wasmPath: wasm.wasmPath } : { state: "wasm-broken", wasmReason: wasm.reason };
54760
54730
  }
54761
- const packageDir = join38(installRoot, "node_modules", "onnxruntime-node");
54731
+ const packageDir = join37(installRoot, "node_modules", "onnxruntime-node");
54762
54732
  let native;
54763
- if (!existsSync48(join38(packageDir, "package.json"))) {
54733
+ if (!existsSync47(join37(packageDir, "package.json"))) {
54764
54734
  native = { state: "package-missing", packageDir };
54765
54735
  } else {
54766
54736
  const rel = expectedBinaryRelPath(platform, arch);
@@ -54770,8 +54740,8 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
54770
54740
  binaryPath: packageDir
54771
54741
  };
54772
54742
  } else {
54773
- const binaryPath = join38(packageDir, rel);
54774
- native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
54743
+ const binaryPath = join37(packageDir, rel);
54744
+ native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
54775
54745
  state: "binary-missing",
54776
54746
  packageDir,
54777
54747
  expectedBinary: binaryPath,
@@ -54782,7 +54752,7 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
54782
54752
  return withWasmFallback(native, () => probeWasmRuntimeAt(installRoot));
54783
54753
  }
54784
54754
  function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
54785
- const existing = installRoots.filter((root) => existsSync48(root));
54755
+ const existing = installRoots.filter((root) => existsSync47(root));
54786
54756
  if (existing.length === 0) {
54787
54757
  return {
54788
54758
  state: "unknown",
@@ -54812,15 +54782,15 @@ function packageDirFromResolved(resolvedPath, packageName) {
54812
54782
  }
54813
54783
  function probeWasmRuntimeByResolution(pluginDir) {
54814
54784
  try {
54815
- const reqPlugin = createRequire5(join38(pluginDir, "package.json"));
54785
+ const reqPlugin = createRequire5(join37(pluginDir, "package.json"));
54816
54786
  const direct = probeWasmRuntimeFromRequire(reqPlugin);
54817
54787
  let probe = direct;
54818
54788
  if (direct.state === "failed" && direct.reason.startsWith("onnxruntime-web is not resolvable")) {
54819
54789
  const tfResolved = reqPlugin.resolve("@huggingface/transformers");
54820
54790
  const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
54821
- probe = probeWasmRuntimeFromRequire(createRequire5(join38(tfDir, "package.json")));
54791
+ probe = probeWasmRuntimeFromRequire(createRequire5(join37(tfDir, "package.json")));
54822
54792
  }
54823
- return requireNodeWasmBundle(probe, [join38(pluginDir, "dist", "transformers-node-wasm.js")]);
54793
+ return requireNodeWasmBundle(probe, [join37(pluginDir, "dist", "transformers-node-wasm.js")]);
54824
54794
  } catch (error) {
54825
54795
  return {
54826
54796
  state: "failed",
@@ -54829,7 +54799,7 @@ function probeWasmRuntimeByResolution(pluginDir) {
54829
54799
  }
54830
54800
  }
54831
54801
  function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
54832
- if (!existsSync48(join38(pluginDir, "package.json"))) {
54802
+ if (!existsSync47(join37(pluginDir, "package.json"))) {
54833
54803
  return { state: "unknown", reason: "plugin package dir not found" };
54834
54804
  }
54835
54805
  const selectedRuntime = resolveLocalEmbeddingWorkerRuntime(runtimePreference, host);
@@ -54840,13 +54810,13 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
54840
54810
  let onnxDir = null;
54841
54811
  let resolveError;
54842
54812
  try {
54843
- const reqPlugin = createRequire5(join38(pluginDir, "package.json"));
54813
+ const reqPlugin = createRequire5(join37(pluginDir, "package.json"));
54844
54814
  try {
54845
54815
  onnxDir = packageDirFromResolved(reqPlugin.resolve("onnxruntime-node"), "onnxruntime-node");
54846
54816
  } catch {
54847
54817
  const tfResolved = reqPlugin.resolve("@huggingface/transformers");
54848
54818
  const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
54849
- const reqTf = createRequire5(join38(tfDir, "package.json"));
54819
+ const reqTf = createRequire5(join37(tfDir, "package.json"));
54850
54820
  onnxDir = packageDirFromResolved(reqTf.resolve("onnxruntime-node"), "onnxruntime-node");
54851
54821
  }
54852
54822
  } catch (error) {
@@ -54854,7 +54824,7 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
54854
54824
  if (resolveError === "ERR_MODULE_NOT_FOUND" || resolveError === "MODULE_NOT_FOUND") {
54855
54825
  return withWasmFallback({
54856
54826
  state: "package-missing",
54857
- packageDir: join38(pluginDir, "node_modules", "onnxruntime-node")
54827
+ packageDir: join37(pluginDir, "node_modules", "onnxruntime-node")
54858
54828
  }, () => probeWasmRuntimeByResolution(pluginDir));
54859
54829
  }
54860
54830
  return {
@@ -54870,8 +54840,8 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
54870
54840
  if (rel === null) {
54871
54841
  native = probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath: onnxDir };
54872
54842
  } else {
54873
- const binaryPath = join38(onnxDir, rel);
54874
- native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
54843
+ const binaryPath = join37(onnxDir, rel);
54844
+ native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
54875
54845
  state: "binary-missing",
54876
54846
  packageDir: onnxDir,
54877
54847
  expectedBinary: binaryPath,
@@ -54907,7 +54877,7 @@ var init_embedding_runtime = __esm(async () => {
54907
54877
 
54908
54878
  // src/lib/logs-opencode.ts
54909
54879
  import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync9 } from "node:fs";
54910
- import { dirname as dirname26, join as join39 } from "node:path";
54880
+ import { dirname as dirname26, join as join38 } from "node:path";
54911
54881
  function formatTimestamp(date) {
54912
54882
  const pad = (value) => String(value).padStart(2, "0");
54913
54883
  return [
@@ -54996,11 +54966,11 @@ async function bundleIssueReport(report, description, title, sessionFilter = nul
54996
54966
  const bodyMarkdown = capBodyToGithubLimit(rawBodyMarkdown);
54997
54967
  const truncated = bodyMarkdown !== rawBodyMarkdown;
54998
54968
  const timestamp = formatTimestamp(new Date);
54999
- const path = options.outputPath ?? join39(process.cwd(), `magic-context-issue-${timestamp}.md`);
54969
+ const path = options.outputPath ?? join38(process.cwd(), `magic-context-issue-${timestamp}.md`);
55000
54970
  mkdirSync9(dirname26(path), { recursive: true });
55001
54971
  writeFileSync9(path, `${bodyMarkdown}
55002
54972
  `);
55003
- const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join39(process.cwd(), `magic-context-issue-${timestamp}-full.md`) : undefined;
54973
+ const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join38(process.cwd(), `magic-context-issue-${timestamp}-full.md`) : undefined;
55004
54974
  if (fullPath)
55005
54975
  writeFileSync9(fullPath, `${rawBodyMarkdown}
55006
54976
  `);
@@ -55821,10 +55791,10 @@ function removeDeprecatedReasoningAge(config) {
55821
55791
 
55822
55792
  // src/commands/doctor-opencode.ts
55823
55793
  import { spawnSync as spawnSync10 } from "node:child_process";
55824
- import { existsSync as existsSync49, mkdtempSync as mkdtempSync4, readFileSync as readFileSync32, rmSync as rmSync9 } from "node:fs";
55794
+ import { existsSync as existsSync48, mkdtempSync as mkdtempSync4, readFileSync as readFileSync31, rmSync as rmSync9 } from "node:fs";
55825
55795
  import { createRequire as createRequire6 } from "node:module";
55826
55796
  import { homedir as homedir21, tmpdir as tmpdir4 } from "node:os";
55827
- import { dirname as dirname27, join as join40, resolve as resolve19 } from "node:path";
55797
+ import { dirname as dirname27, join as join39, resolve as resolve19 } from "node:path";
55828
55798
  function formatSharedDbRowCounts(db) {
55829
55799
  return SHARED_DB_ROW_COUNT_TABLES.map((table) => {
55830
55800
  try {
@@ -55895,7 +55865,7 @@ function checkConfiguredVariantCatalog(config, hostGeneration, warn, run = (args
55895
55865
  }
55896
55866
  if (models.length === 0)
55897
55867
  return;
55898
- const tempRoot = mkdtempSync4(join40(tmpdir4(), "magic-context-opencode-catalog-"));
55868
+ const tempRoot = mkdtempSync4(join39(tmpdir4(), "magic-context-opencode-catalog-"));
55899
55869
  try {
55900
55870
  const command = hostGeneration === "v2" ? ["api", "model.list", "--param", `directory=${projectDir}`] : ["models", "--verbose"];
55901
55871
  const guidance = `opencode ${command.join(" ")}`;
@@ -56071,7 +56041,7 @@ function getSelfVersion2() {
56071
56041
  function describeAutoUpdateStall(specifier, autoUpdateEnabled, storageDir = getMagicContextStorageDir()) {
56072
56042
  if (!autoUpdateEnabled || !isPinnedOpenCodePluginSpecifier(specifier))
56073
56043
  return null;
56074
- const state = readAutoUpdateCheckState(join40(storageDir, AUTO_UPDATE_CHECK_STATE_FILENAME));
56044
+ const state = readAutoUpdateCheckState(join39(storageDir, AUTO_UPDATE_CHECK_STATE_FILENAME));
56075
56045
  const owner = isUpdaterPinnedSpec(state, specifier) ? "updater" : "you";
56076
56046
  return `auto-update: stalled — config pinned to ${specifier} (by ${owner})`;
56077
56047
  }
@@ -56080,15 +56050,15 @@ function getUserNpmrcPath() {
56080
56050
  if (custom)
56081
56051
  return custom;
56082
56052
  const home = process.env.HOME?.trim();
56083
- return join40(home || homedir21(), ".npmrc");
56053
+ return join39(home || homedir21(), ".npmrc");
56084
56054
  }
56085
56055
  function collectNpmReleaseAgeWarnings() {
56086
56056
  const ageWarnings = [];
56087
56057
  const npmrcPath = getUserNpmrcPath();
56088
- if (!existsSync49(npmrcPath))
56058
+ if (!existsSync48(npmrcPath))
56089
56059
  return ageWarnings;
56090
56060
  try {
56091
- const npmrc = readFileSync32(npmrcPath, "utf-8");
56061
+ const npmrc = readFileSync31(npmrcPath, "utf-8");
56092
56062
  for (const line of npmrc.split(`
56093
56063
  `)) {
56094
56064
  const trimmed = line.trim();
@@ -56223,7 +56193,7 @@ function checkLocalEmbeddingRuntimeForDoctor(installRoots, runtimePreference = "
56223
56193
  return { issues: 0 };
56224
56194
  }
56225
56195
  async function checkEmbeddingConfig(magicContextConfigPath, installRoots) {
56226
- if (!existsSync49(magicContextConfigPath)) {
56196
+ if (!existsSync48(magicContextConfigPath)) {
56227
56197
  return checkLocalEmbeddingRuntimeForDoctor(installRoots);
56228
56198
  }
56229
56199
  let rawText;
@@ -56291,6 +56261,7 @@ async function checkEmbeddingConfig(magicContextConfigPath, installRoots) {
56291
56261
  const apiKey = typeof embedding?.api_key === "string" ? embedding.api_key : undefined;
56292
56262
  const inputType = typeof embedding?.input_type === "string" ? embedding.input_type.trim() : undefined;
56293
56263
  const truncateMode = typeof embedding?.truncate === "string" ? embedding.truncate.trim() : undefined;
56264
+ const dimensions = typeof embedding?.dimensions === "number" ? embedding.dimensions : undefined;
56294
56265
  let localIssues = 0;
56295
56266
  if (!endpoint) {
56296
56267
  log3.error("Embedding provider is openai-compatible but 'endpoint' is missing");
@@ -56324,6 +56295,7 @@ async function checkEmbeddingConfig(magicContextConfigPath, installRoots) {
56324
56295
  apiKey,
56325
56296
  ...inputType ? { inputType } : {},
56326
56297
  ...truncateMode ? { truncate: truncateMode } : {},
56298
+ ...dimensions !== undefined ? { dimensions } : {},
56327
56299
  timeoutMs: 1e4
56328
56300
  });
56329
56301
  } catch (error) {
@@ -56336,6 +56308,10 @@ async function checkEmbeddingConfig(magicContextConfigPath, installRoots) {
56336
56308
  case "ok":
56337
56309
  log3.success(`Embedding endpoint OK (${outcome.status}, ${outcome.dimensions ?? "?"}-dim vectors)`);
56338
56310
  return { issues: localIssues };
56311
+ case "dimensions_mismatch":
56312
+ log3.error(`Embedding endpoint ignored dimensions=${outcome.requested} and returned ${outcome.returned}-dim vectors (${outcome.status})`);
56313
+ log3.info(" The endpoint or model does not support the dimensions parameter. Remove embedding.dimensions, or use a Matryoshka-capable model/endpoint. Mismatched vectors are rejected at runtime.");
56314
+ return { issues: localIssues + 1 };
56339
56315
  case "auth_failed":
56340
56316
  log3.error(`Embedding endpoint rejected credentials (${outcome.status}) — check api_key / env var`);
56341
56317
  if (outcome.preview)
@@ -56398,7 +56374,7 @@ async function runDoctor2(options = {}) {
56398
56374
  const v22Result = await runV22BackfillCommands({
56399
56375
  name: "OpenCode",
56400
56376
  openDatabase: (readonly = true) => {
56401
- const dbPath = join40(getMagicContextStorageDir(), "context.db");
56377
+ const dbPath = join39(getMagicContextStorageDir(), "context.db");
56402
56378
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
56403
56379
  return v22Db;
56404
56380
  },
@@ -56434,7 +56410,7 @@ async function runDoctor2(options = {}) {
56434
56410
  if (isMagicContextStorageOutsideEngram(storageDir)) {
56435
56411
  warn(`Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
56436
56412
  }
56437
- const authorityDbPath = join40(getMagicContextStorageDir(), "context.db");
56413
+ const authorityDbPath = join39(getMagicContextStorageDir(), "context.db");
56438
56414
  let authorityDb = null;
56439
56415
  try {
56440
56416
  authorityDb = openExistingContextDatabase(authorityDbPath, { readonly: true });
@@ -56473,7 +56449,7 @@ async function runDoctor2(options = {}) {
56473
56449
  let magicContextStatusKnown = paths.opencodeConfigFormat === "none";
56474
56450
  if (!magicContextStatusKnown) {
56475
56451
  try {
56476
- const config = import_comment_json11.parse(readFileSync32(paths.opencodeConfig, "utf-8"));
56452
+ const config = import_comment_json11.parse(readFileSync31(paths.opencodeConfig, "utf-8"));
56477
56453
  magicContextInstalled = isOpenCodePluginRegistered(config, dirname27(paths.opencodeConfig));
56478
56454
  magicContextStatusKnown = true;
56479
56455
  } catch {}
@@ -56609,7 +56585,7 @@ async function runDoctor2(options = {}) {
56609
56585
  pass(`OpenCode config: ${paths.opencodeConfig}`);
56610
56586
  }
56611
56587
  let autoUpdateEnabled = true;
56612
- if (existsSync49(paths.magicContextConfig)) {
56588
+ if (existsSync48(paths.magicContextConfig)) {
56613
56589
  pass(`Magic Context config: ${paths.magicContextConfig}`);
56614
56590
  try {
56615
56591
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
@@ -56647,7 +56623,7 @@ async function runDoctor2(options = {}) {
56647
56623
  log3.info(rerankConfigSummary());
56648
56624
  log3.info(" Run 'setup' to create one with model recommendations");
56649
56625
  }
56650
- if (existsSync49(paths.magicContextConfig)) {
56626
+ if (existsSync48(paths.magicContextConfig)) {
56651
56627
  try {
56652
56628
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
56653
56629
  if (!raw)
@@ -56787,7 +56763,7 @@ async function runDoctor2(options = {}) {
56787
56763
  };
56788
56764
  if (paths.opencodeConfigFormat !== "none") {
56789
56765
  try {
56790
- const raw = readFileSync32(paths.opencodeConfig, "utf-8");
56766
+ const raw = readFileSync31(paths.opencodeConfig, "utf-8");
56791
56767
  const config = import_comment_json11.parse(raw);
56792
56768
  const configName = paths.opencodeConfigFormat === "jsonc" ? "opencode.jsonc" : "opencode.json";
56793
56769
  const configDir = dirname27(paths.opencodeConfig);
@@ -56880,9 +56856,9 @@ async function runDoctor2(options = {}) {
56880
56856
  pass("Added TUI sidebar plugin to tui.json");
56881
56857
  warn("Restart OpenCode to see the sidebar");
56882
56858
  fixed++;
56883
- } else if (existsSync49(paths.tuiConfig)) {
56859
+ } else if (existsSync48(paths.tuiConfig)) {
56884
56860
  try {
56885
- const tuiRaw = readFileSync32(paths.tuiConfig, "utf-8");
56861
+ const tuiRaw = readFileSync31(paths.tuiConfig, "utf-8");
56886
56862
  const tuiConfig = import_comment_json11.parse(tuiRaw);
56887
56863
  const tuiConfigDir = dirname27(paths.tuiConfig);
56888
56864
  const tuiRawPlugins = Array.isArray(tuiConfig?.plugin) ? tuiConfig.plugin : [];
@@ -56921,7 +56897,7 @@ async function runDoctor2(options = {}) {
56921
56897
  fail("Could not create or verify the TUI sidebar config");
56922
56898
  }
56923
56899
  }
56924
- if (existsSync49(paths.magicContextConfig)) {
56900
+ if (existsSync48(paths.magicContextConfig)) {
56925
56901
  try {
56926
56902
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
56927
56903
  if (!raw)
@@ -56937,10 +56913,10 @@ async function runDoctor2(options = {}) {
56937
56913
  let embeddingHostConfig = null;
56938
56914
  try {
56939
56915
  if (paths.opencodeConfigFormat !== "none")
56940
- embeddingHostConfig = import_comment_json11.parse(readFileSync32(paths.opencodeConfig, "utf-8"));
56916
+ embeddingHostConfig = import_comment_json11.parse(readFileSync31(paths.opencodeConfig, "utf-8"));
56941
56917
  } catch {}
56942
56918
  const embeddingInstalls = getOpenCodeLoadedPluginInstallRoots(hostGeneration, embeddingHostConfig);
56943
- const unusedInstalls = embeddingInstalls.others.filter((root) => existsSync49(root));
56919
+ const unusedInstalls = embeddingInstalls.others.filter((root) => existsSync48(root));
56944
56920
  if (unusedInstalls.length > 0)
56945
56921
  log3.info(`Local embedding runtime: checked only the copy ${hostGeneration === "v2" ? "OpenCode 2" : "OpenCode 1"} loads; other installed copies (not loaded, not checked): ${unusedInstalls.join(", ")}`);
56946
56922
  const embeddingCheck = await checkEmbeddingConfig(paths.magicContextConfig, embeddingInstalls.loaded);
@@ -56952,9 +56928,9 @@ async function runDoctor2(options = {}) {
56952
56928
  else
56953
56929
  passCount++;
56954
56930
  const storage = getMagicContextStorageResolution();
56955
- const dbPath = join40(storage.path, "context.db");
56931
+ const dbPath = join39(storage.path, "context.db");
56956
56932
  log3.info(`Shared storage: ${storage.path} (source: ${storage.source})`);
56957
- if (!existsSync49(dbPath)) {
56933
+ if (!existsSync48(dbPath)) {
56958
56934
  log3.info(`Shared context DB not yet created at ${dbPath} (will be created on first run)`);
56959
56935
  } else {
56960
56936
  log3.info(`Shared context DB exists at ${dbPath}`);
@@ -57037,7 +57013,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
57037
57013
  let pluginConfigUse;
57038
57014
  if (paths.opencodeConfigFormat !== "none") {
57039
57015
  try {
57040
- pluginConfigUse = readOpenCodePluginConfigUse(import_comment_json11.parse(readFileSync32(paths.opencodeConfig, "utf-8")), dirname27(paths.opencodeConfig));
57016
+ pluginConfigUse = readOpenCodePluginConfigUse(import_comment_json11.parse(readFileSync31(paths.opencodeConfig, "utf-8")), dirname27(paths.opencodeConfig));
57041
57017
  } catch {}
57042
57018
  }
57043
57019
  const cacheResult = await clearPluginCache({
@@ -57089,7 +57065,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
57089
57065
  let v2DistTag;
57090
57066
  if (paths.opencodeConfigFormat !== "none") {
57091
57067
  try {
57092
- v2DistTag = configuredOpenCodeV2DistTag(import_comment_json11.parse(readFileSync32(paths.opencodeConfig, "utf-8")));
57068
+ v2DistTag = configuredOpenCodeV2DistTag(import_comment_json11.parse(readFileSync31(paths.opencodeConfig, "utf-8")));
57093
57069
  } catch {}
57094
57070
  }
57095
57071
  const v2Cache = reportOpenCodeV2PluginCache(checkOpenCodeV2PluginCache({
@@ -57491,9 +57467,9 @@ var init_model_chain_health = __esm(() => {
57491
57467
  });
57492
57468
 
57493
57469
  // src/lib/diagnostics-pi.ts
57494
- import { existsSync as existsSync50, readdirSync as readdirSync11, readFileSync as readFileSync33, statSync as statSync26 } from "node:fs";
57470
+ import { existsSync as existsSync49, readdirSync as readdirSync11, readFileSync as readFileSync32, statSync as statSync26 } from "node:fs";
57495
57471
  import { createRequire as createRequire7 } from "node:module";
57496
- import { join as join41 } from "node:path";
57472
+ import { join as join40 } from "node:path";
57497
57473
  function getSelfVersion3() {
57498
57474
  const req = createRequire7(import.meta.url);
57499
57475
  for (const relPath of ["../../package.json", "../package.json"]) {
@@ -57508,7 +57484,7 @@ function getSelfVersion3() {
57508
57484
  }
57509
57485
  function fileSize2(path) {
57510
57486
  try {
57511
- return existsSync50(path) ? statSync26(path).size : 0;
57487
+ return existsSync49(path) ? statSync26(path).size : 0;
57512
57488
  } catch {
57513
57489
  return 0;
57514
57490
  }
@@ -57520,11 +57496,11 @@ function sanitizeValue2(value) {
57520
57496
  return sanitizeConfigValue(value);
57521
57497
  }
57522
57498
  function readJsonc(path) {
57523
- if (!existsSync50(path))
57499
+ if (!existsSync49(path))
57524
57500
  return { value: {} };
57525
57501
  try {
57526
57502
  return {
57527
- value: import_comment_json12.parse(readFileSync33(path, "utf-8"))
57503
+ value: import_comment_json12.parse(readFileSync32(path, "utf-8"))
57528
57504
  };
57529
57505
  } catch (error) {
57530
57506
  return {
@@ -57540,7 +57516,7 @@ function readConfigDiagnostic(path) {
57540
57516
  const parsed = readJsonc(path);
57541
57517
  return {
57542
57518
  path,
57543
- exists: existsSync50(path),
57519
+ exists: existsSync49(path),
57544
57520
  ...parsed.parseError ? { parseError: parsed.parseError } : {},
57545
57521
  flags: sanitizeValue2(parsed.value)
57546
57522
  };
@@ -57558,7 +57534,7 @@ function reverseSlugToDirectory(slug) {
57558
57534
  }
57559
57535
  function collectPiRecentSessions() {
57560
57536
  const sessionsRoot = getPiSessionsRoot();
57561
- if (!existsSync50(sessionsRoot))
57537
+ if (!existsSync49(sessionsRoot))
57562
57538
  return [];
57563
57539
  try {
57564
57540
  const slugs = readdirSync11(sessionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
@@ -57567,7 +57543,7 @@ function collectPiRecentSessions() {
57567
57543
  const directory = reverseSlugToDirectory(slug);
57568
57544
  if (!directory)
57569
57545
  continue;
57570
- const slugDir = join41(sessionsRoot, slug);
57546
+ const slugDir = join40(sessionsRoot, slug);
57571
57547
  let files;
57572
57548
  try {
57573
57549
  files = readdirSync11(slugDir).filter((name) => name.endsWith(".jsonl"));
@@ -57576,7 +57552,7 @@ function collectPiRecentSessions() {
57576
57552
  }
57577
57553
  for (const file of files) {
57578
57554
  try {
57579
- const mtime = statSync26(join41(slugDir, file)).mtimeMs;
57555
+ const mtime = statSync26(join40(slugDir, file)).mtimeMs;
57580
57556
  const sessionId = file.replace(/\.jsonl$/, "");
57581
57557
  candidates.push({ sessionId, directory, mtime });
57582
57558
  } catch {}
@@ -57594,7 +57570,7 @@ function collectPiRecentSessions() {
57594
57570
  }
57595
57571
  function parseHistorianDumpMeta2(path) {
57596
57572
  try {
57597
- const xml = readFileSync33(path, "utf-8");
57573
+ const xml = readFileSync32(path, "utf-8");
57598
57574
  const parsed = parseCompartmentOutput(xml);
57599
57575
  const factCountByCategory = {};
57600
57576
  for (const fact of parsed.facts) {
@@ -57627,11 +57603,11 @@ function parseHistorianDumpMeta2(path) {
57627
57603
  }
57628
57604
  }
57629
57605
  function listDumpsInDir2(dir, limit) {
57630
- if (!existsSync50(dir))
57606
+ if (!existsSync49(dir))
57631
57607
  return { count: 0, recent: [] };
57632
57608
  try {
57633
57609
  const entries = readdirSync11(dir).filter((name) => name.endsWith(".xml")).map((name) => {
57634
- const stat = statSync26(join41(dir, name));
57610
+ const stat = statSync26(join40(dir, name));
57635
57611
  return {
57636
57612
  name,
57637
57613
  mtime: stat.mtimeMs,
@@ -57640,7 +57616,7 @@ function listDumpsInDir2(dir, limit) {
57640
57616
  }).sort((a, b) => b.mtime - a.mtime);
57641
57617
  const now = Date.now();
57642
57618
  const recent = entries.slice(0, limit).map((entry) => {
57643
- const meta = parseHistorianDumpMeta2(join41(dir, entry.name));
57619
+ const meta = parseHistorianDumpMeta2(join40(dir, entry.name));
57644
57620
  const summary = {
57645
57621
  name: entry.name,
57646
57622
  ageMinutes: Math.round((now - entry.mtime) / 60000),
@@ -57704,7 +57680,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
57704
57680
  const loaded = loadPiConfig({ cwd });
57705
57681
  const storageResolution = getMagicContextStorageResolution();
57706
57682
  const storageDirPath = storageResolution.path;
57707
- const dbPath = join41(storageDirPath, "context.db");
57683
+ const dbPath = join40(storageDirPath, "context.db");
57708
57684
  const logFiles = inspectMagicContextLogs("pi");
57709
57685
  const primaryLog = logFiles.find((file) => file.exists) ?? logFiles[0];
57710
57686
  const otherPiExtensions = packages.filter((entry) => !isPiMagicContextPackageEntry(entry)).map(describePiPackageEntry);
@@ -57721,7 +57697,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
57721
57697
  piVersion: pi ? getPiVersion(pi.path) : null,
57722
57698
  settings: {
57723
57699
  path: settingsPath,
57724
- exists: existsSync50(settingsPath),
57700
+ exists: existsSync49(settingsPath),
57725
57701
  ...settingsParsed.parseError ? { parseError: settingsParsed.parseError } : {},
57726
57702
  hasMagicContextPackage: hasPiMagicContextPackage(packages),
57727
57703
  packages: sanitizeValue2(packages)
@@ -57738,7 +57714,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
57738
57714
  storageDir: {
57739
57715
  path: storageDirPath,
57740
57716
  source: storageResolution.source,
57741
- exists: existsSync50(storageDirPath),
57717
+ exists: existsSync49(storageDirPath),
57742
57718
  contextDbSizeBytes: fileSize2(dbPath)
57743
57719
  },
57744
57720
  conflicts: {
@@ -57846,7 +57822,7 @@ var init_diagnostics_pi = __esm(() => {
57846
57822
 
57847
57823
  // src/lib/logs-pi.ts
57848
57824
  import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync10 } from "node:fs";
57849
- import { dirname as dirname28, join as join42 } from "node:path";
57825
+ import { dirname as dirname28, join as join41 } from "node:path";
57850
57826
  function formatTimestamp2(date) {
57851
57827
  const pad = (value) => String(value).padStart(2, "0");
57852
57828
  return [
@@ -57900,11 +57876,11 @@ async function bundleIssueReport2(report, description, title, options = {}) {
57900
57876
  const truncated = bodyMarkdown !== rawBodyMarkdown;
57901
57877
  const cwd = options.cwd ?? process.cwd();
57902
57878
  const timestamp = formatTimestamp2(options.now ?? new Date);
57903
- const path = options.outputPath ?? join42(cwd, `magic-context-pi-issue-${timestamp}.md`);
57879
+ const path = options.outputPath ?? join41(cwd, `magic-context-pi-issue-${timestamp}.md`);
57904
57880
  mkdirSync10(dirname28(path), { recursive: true });
57905
57881
  writeFileSync10(path, `${bodyMarkdown}
57906
57882
  `);
57907
- const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join42(cwd, `magic-context-pi-issue-${timestamp}-full.md`) : undefined;
57883
+ const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join41(cwd, `magic-context-pi-issue-${timestamp}-full.md`) : undefined;
57908
57884
  if (fullPath)
57909
57885
  writeFileSync10(fullPath, `${rawBodyMarkdown}
57910
57886
  `);
@@ -57918,10 +57894,10 @@ var init_logs_pi = __esm(() => {
57918
57894
 
57919
57895
  // src/commands/doctor-pi.ts
57920
57896
  import { execFileSync as execFileSync9, spawnSync as spawnSync11 } from "node:child_process";
57921
- import { existsSync as existsSync51, readdirSync as readdirSync12, readFileSync as readFileSync34, rmSync as rmSync10, statSync as statSync27 } from "node:fs";
57897
+ import { existsSync as existsSync50, readdirSync as readdirSync12, readFileSync as readFileSync33, rmSync as rmSync10, statSync as statSync27 } from "node:fs";
57922
57898
  import { createRequire as createRequire8 } from "node:module";
57923
57899
  import { homedir as homedir22 } from "node:os";
57924
- import { isAbsolute as isAbsolute9, join as join43 } from "node:path";
57900
+ import { isAbsolute as isAbsolute9, join as join42 } from "node:path";
57925
57901
  function depsFrom(options) {
57926
57902
  return {
57927
57903
  ...DEFAULT_DEPS5,
@@ -58013,7 +57989,7 @@ function summarize(results) {
58013
57989
  function readJsonc2(path) {
58014
57990
  try {
58015
57991
  return {
58016
- value: import_comment_json13.parse(readFileSync34(path, "utf-8"))
57992
+ value: import_comment_json13.parse(readFileSync33(path, "utf-8"))
58017
57993
  };
58018
57994
  } catch (error) {
58019
57995
  return {
@@ -58063,15 +58039,15 @@ function piPluginDirCandidates(packages, cwd) {
58063
58039
  if (resolved)
58064
58040
  dirs.push(resolved);
58065
58041
  }
58066
- dirs.push(join43(agentDir, "npm", "node_modules", PACKAGE_NAME2));
58067
- dirs.push(join43(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2));
58068
- return dirs.filter((dir) => existsSync51(join43(dir, "package.json")));
58042
+ dirs.push(join42(agentDir, "npm", "node_modules", PACKAGE_NAME2));
58043
+ dirs.push(join42(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2));
58044
+ return dirs.filter((dir) => existsSync50(join42(dir, "package.json")));
58069
58045
  }
58070
58046
  function projectConfigPath(cwd) {
58071
58047
  return resolveCortexKitProjectConfigPath(cwd);
58072
58048
  }
58073
58049
  function readConfigForEmbedding(path, isProjectConfig) {
58074
- if (!existsSync51(path))
58050
+ if (!existsSync50(path))
58075
58051
  return null;
58076
58052
  try {
58077
58053
  const raw = loadRawConfigFile({
@@ -58104,6 +58080,11 @@ function classifyEmbeddingOutcome(outcome) {
58104
58080
  status: "pass",
58105
58081
  message: `Embedding endpoint OK (${outcome.status}, ${outcome.dimensions ?? "?"}-dim vectors)`
58106
58082
  };
58083
+ case "dimensions_mismatch":
58084
+ return {
58085
+ status: "fail",
58086
+ message: `Embedding endpoint ignored dimensions=${outcome.requested} and returned ${outcome.returned}-dim vectors (${outcome.status}); remove embedding.dimensions or use a Matryoshka-capable model`
58087
+ };
58107
58088
  case "auth_failed":
58108
58089
  return {
58109
58090
  status: "fail",
@@ -58157,22 +58138,22 @@ function pinnedVersionFromPackageSpecifier(specifier) {
58157
58138
  }
58158
58139
  function cacheRoots(cwd) {
58159
58140
  const home = process.env.HOME?.trim();
58160
- const cacheHome = process.env.XDG_CACHE_HOME || join43(home || homedir22(), ".cache");
58141
+ const cacheHome = process.env.XDG_CACHE_HOME || join42(home || homedir22(), ".cache");
58161
58142
  const piCacheRoot = getPiCacheRoot();
58162
58143
  return [
58163
- join43(piCacheRoot, "extensions"),
58164
- join43(piCacheRoot, "packages"),
58165
- join43(cacheHome, "pi", "extensions"),
58166
- join43(cacheHome, "pi", "packages"),
58167
- join43(getPiAgentConfigDir(), "cache", "extensions"),
58168
- join43(getPiAgentConfigDir(), "npm", "node_modules", PACKAGE_NAME2),
58169
- join43(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2)
58144
+ join42(piCacheRoot, "extensions"),
58145
+ join42(piCacheRoot, "packages"),
58146
+ join42(cacheHome, "pi", "extensions"),
58147
+ join42(cacheHome, "pi", "packages"),
58148
+ join42(getPiAgentConfigDir(), "cache", "extensions"),
58149
+ join42(getPiAgentConfigDir(), "npm", "node_modules", PACKAGE_NAME2),
58150
+ join42(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2)
58170
58151
  ];
58171
58152
  }
58172
58153
  function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
58173
58154
  const found = new Map;
58174
58155
  const visit = (path, depth) => {
58175
- if (depth < 0 || !existsSync51(path))
58156
+ if (depth < 0 || !existsSync50(path))
58176
58157
  return;
58177
58158
  let stat;
58178
58159
  try {
@@ -58182,10 +58163,10 @@ function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
58182
58163
  }
58183
58164
  if (!stat.isDirectory())
58184
58165
  return;
58185
- const packageJson = join43(path, "package.json");
58186
- if (existsSync51(packageJson)) {
58166
+ const packageJson = join42(path, "package.json");
58167
+ if (existsSync50(packageJson)) {
58187
58168
  try {
58188
- const pkg = JSON.parse(readFileSync34(packageJson, "utf-8"));
58169
+ const pkg = JSON.parse(readFileSync33(packageJson, "utf-8"));
58189
58170
  const name = typeof pkg.name === "string" ? pkg.name : "";
58190
58171
  const version = typeof pkg.version === "string" ? pkg.version : undefined;
58191
58172
  if (name === PACKAGE_NAME2) {
@@ -58205,7 +58186,7 @@ function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
58205
58186
  return;
58206
58187
  }
58207
58188
  for (const entry of entries)
58208
- visit(join43(path, entry), depth - 1);
58189
+ visit(join42(path, entry), depth - 1);
58209
58190
  };
58210
58191
  for (const root of cacheRoots(cwd))
58211
58192
  visit(root, 5);
@@ -58266,7 +58247,7 @@ async function runHealthChecks2(options) {
58266
58247
  const settingsPath = getPiUserExtensionsPath();
58267
58248
  let packages = [];
58268
58249
  let piPluginInstalled = false;
58269
- if (!existsSync51(settingsPath)) {
58250
+ if (!existsSync50(settingsPath)) {
58270
58251
  if (pi) {
58271
58252
  add2(results, "info", `${piVersion ? `Pi ${piVersion}` : "Pi"} found; Magic Context is not installed there (run setup to add it)`);
58272
58253
  }
@@ -58308,7 +58289,7 @@ async function runHealthChecks2(options) {
58308
58289
  ["user", userConfigPath, true],
58309
58290
  ["project", projectPath, false]
58310
58291
  ]) {
58311
- if (!existsSync51(path)) {
58292
+ if (!existsSync50(path)) {
58312
58293
  if (required) {
58313
58294
  add2(results, "warn", `No ${label} magic-context.jsonc found at ${path}`);
58314
58295
  if (userConfigMigrationRefused) {
@@ -58355,12 +58336,12 @@ async function runHealthChecks2(options) {
58355
58336
  checkPiModelChains(results, pi, loadedConfig.config, options.deps);
58356
58337
  const storage = getMagicContextStorageResolution();
58357
58338
  const storageDir = storage.path;
58358
- const dbPath = join43(storageDir, "context.db");
58339
+ const dbPath = join42(storageDir, "context.db");
58359
58340
  if (isMagicContextStorageOutsideEngram(storageDir)) {
58360
58341
  add2(results, "warn", `Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
58361
58342
  }
58362
58343
  add2(results, "info", `Shared storage: ${storageDir} (source: ${storage.source})`);
58363
- const existedBeforeOpen = existsSync51(dbPath);
58344
+ const existedBeforeOpen = existsSync50(dbPath);
58364
58345
  if (existedBeforeOpen)
58365
58346
  add2(results, "pass", `Shared context DB exists at ${dbPath}`);
58366
58347
  else
@@ -58458,6 +58439,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
58458
58439
  const apiKey = typeof mergedEmbedding.api_key === "string" ? mergedEmbedding.api_key : undefined;
58459
58440
  const inputType = typeof mergedEmbedding.input_type === "string" ? mergedEmbedding.input_type.trim() : undefined;
58460
58441
  const truncateMode = typeof mergedEmbedding.truncate === "string" ? mergedEmbedding.truncate.trim() : undefined;
58442
+ const dimensions = typeof mergedEmbedding.dimensions === "number" ? mergedEmbedding.dimensions : undefined;
58461
58443
  if (!endpoint || !model) {
58462
58444
  add2(results, "fail", "Embedding provider is openai-compatible but endpoint/model is missing");
58463
58445
  } else {
@@ -58468,6 +58450,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
58468
58450
  apiKey,
58469
58451
  ...inputType ? { inputType } : {},
58470
58452
  ...truncateMode ? { truncate: truncateMode } : {},
58453
+ ...dimensions !== undefined ? { dimensions } : {},
58471
58454
  timeoutMs: 1e4
58472
58455
  });
58473
58456
  const classified = classifyEmbeddingOutcome(outcome);
@@ -58589,7 +58572,7 @@ function writeDefaultMagicContextConfig(path) {
58589
58572
  function repair2(plan, prompts) {
58590
58573
  let fixed = 0;
58591
58574
  for (const path of plan.reasoningAgeConfigPaths) {
58592
- const content = readFileSync34(path, "utf8");
58575
+ const content = readFileSync33(path, "utf8");
58593
58576
  const parsed = readJsonc2(path);
58594
58577
  if (parsed.error)
58595
58578
  continue;
@@ -58615,7 +58598,7 @@ function repair2(plan, prompts) {
58615
58598
  }
58616
58599
  if (plan.writeUserConfig) {
58617
58600
  const configPath = getPiUserConfigPath();
58618
- if (!existsSync51(configPath)) {
58601
+ if (!existsSync50(configPath)) {
58619
58602
  try {
58620
58603
  writeDefaultMagicContextConfig(configPath);
58621
58604
  prompts.log.success(`Wrote default Magic Context config to ${configPath}`);
@@ -58669,7 +58652,7 @@ async function runIssueFlow3(options) {
58669
58652
  if (options.reportPath) {
58670
58653
  try {
58671
58654
  const report = await options.deps.collectDiagnostics(options.cwd);
58672
- const outputPath = isAbsolute9(options.reportPath) ? options.reportPath : join43(options.cwd, options.reportPath);
58655
+ const outputPath = isAbsolute9(options.reportPath) ? options.reportPath : join42(options.cwd, options.reportPath);
58673
58656
  const bundled = await bundleIssueReport2(report, "Generated non-interactively by `doctor --issue --report`.", "Magic Context diagnostic report", { cwd: options.cwd, now: options.deps.now(), outputPath });
58674
58657
  options.prompts.log.info(`Report written to ${bundled.path}`);
58675
58658
  return 0;
@@ -58753,7 +58736,7 @@ async function runDoctor3(options = {}) {
58753
58736
  const v22Result = await runV22BackfillCommands({
58754
58737
  name: "Pi",
58755
58738
  openDatabase: (readonly = true) => {
58756
- const dbPath = join43(getMagicContextStorageDir(), "context.db");
58739
+ const dbPath = join42(getMagicContextStorageDir(), "context.db");
58757
58740
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
58758
58741
  return v22Db;
58759
58742
  },
@@ -58871,8 +58854,8 @@ var init_doctor_pi = __esm(async () => {
58871
58854
  });
58872
58855
 
58873
58856
  // src/commands/doctor.ts
58874
- import { existsSync as existsSync52, rmSync as rmSync11 } from "node:fs";
58875
- import { join as join44 } from "node:path";
58857
+ import { existsSync as existsSync51, rmSync as rmSync11 } from "node:fs";
58858
+ import { join as join43 } from "node:path";
58876
58859
  async function runDoctor4(options) {
58877
58860
  if (options.clear)
58878
58861
  return runClear();
@@ -58890,7 +58873,7 @@ async function runDoctor4(options) {
58890
58873
  const result = await runV22BackfillCommands({
58891
58874
  name: "Magic Context",
58892
58875
  openDatabase: (readonly = true) => {
58893
- const dbPath = join44(getMagicContextStorageDir(), "context.db");
58876
+ const dbPath = join43(getMagicContextStorageDir(), "context.db");
58894
58877
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
58895
58878
  return v22Db;
58896
58879
  },
@@ -58910,7 +58893,7 @@ async function runDoctor4(options) {
58910
58893
  log3.warn(`Identity split check unavailable: ${error instanceof Error ? error.message : String(error)}`);
58911
58894
  }
58912
58895
  await init_migrate();
58913
- const sweepDbPath = join44(getMagicContextStorageDir(), "context.db");
58896
+ const sweepDbPath = join43(getMagicContextStorageDir(), "context.db");
58914
58897
  let sweepDb = null;
58915
58898
  try {
58916
58899
  sweepDb = openExistingContextDatabaseForMutation(sweepDbPath);
@@ -59027,7 +59010,7 @@ async function runClear() {
59027
59010
  failed += 1;
59028
59011
  continue;
59029
59012
  }
59030
- } else if (existsSync52(item.path)) {
59013
+ } else if (existsSync51(item.path)) {
59031
59014
  rmSync11(item.path, { recursive: true, force: true });
59032
59015
  }
59033
59016
  s.stop(`Cleared ${item.path}`);