@cortexkit/magic-context 0.49.74 → 0.49.76

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 +715 -574
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -15794,9 +15794,54 @@ var init_dashboard_install = __esm(() => {
15794
15794
  WINDOWS_UNINSTALL_KEY = `Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${DASHBOARD_PRODUCT_NAME}`;
15795
15795
  });
15796
15796
 
15797
+ // src/lib/cache-clear-path.ts
15798
+ import { lstatSync as lstatSync3, realpathSync as realpathSync3 } from "node:fs";
15799
+ import { isAbsolute as isAbsolute4, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
15800
+ function descendantPath(root, path) {
15801
+ const child = relative2(root, path);
15802
+ if (!child || child === ".." || child.startsWith(`..${sep2}`) || isAbsolute4(child)) {
15803
+ return;
15804
+ }
15805
+ return child;
15806
+ }
15807
+ function checkCacheClearPath(cacheRoot, candidate) {
15808
+ const root = resolve3(cacheRoot);
15809
+ const path = resolve3(candidate);
15810
+ const child = descendantPath(root, path);
15811
+ if (child === undefined)
15812
+ return { allowed: false, reason: "outside", path };
15813
+ let current = root;
15814
+ try {
15815
+ for (const part of ["", ...child.split(sep2)]) {
15816
+ current = join6(current, part);
15817
+ const entry = lstatSync3(current);
15818
+ if (entry.isSymbolicLink())
15819
+ return { allowed: false, reason: "linked", path: current };
15820
+ if (!entry.isDirectory())
15821
+ return { allowed: false, reason: "unavailable", path: current };
15822
+ }
15823
+ if (descendantPath(realpathSync3(root), realpathSync3(path)) === undefined) {
15824
+ return { allowed: false, reason: "outside", path };
15825
+ }
15826
+ } catch (error) {
15827
+ const reason = error.code === "ENOENT" ? "missing" : "unavailable";
15828
+ return { allowed: false, reason, path: current };
15829
+ }
15830
+ return { allowed: true, path };
15831
+ }
15832
+ function describeCacheClearRefusal(path, reason) {
15833
+ if (reason === "linked") {
15834
+ return `Left ${path} alone: it is reached through a linked folder, so it isn't a cache Magic Context can clear.`;
15835
+ }
15836
+ if (reason === "outside")
15837
+ return `Left ${path} alone: it is outside the cache folder.`;
15838
+ return `Left ${path} alone: could not verify it is a directory inside the cache folder.`;
15839
+ }
15840
+ var init_cache_clear_path = () => {};
15841
+
15797
15842
  // src/lib/find-on-path.ts
15798
15843
  import { accessSync as accessSync2, constants as constants2, existsSync as existsSync8, statSync as statSync6 } from "node:fs";
15799
- import { delimiter, join as join6 } from "node:path";
15844
+ import { delimiter, join as join7 } from "node:path";
15800
15845
  function findOnPath(binary) {
15801
15846
  const PATH = process.env.PATH;
15802
15847
  if (typeof PATH !== "string" || PATH.length === 0)
@@ -15808,7 +15853,7 @@ function findOnPath(binary) {
15808
15853
  if (!dir)
15809
15854
  continue;
15810
15855
  for (const candidate of candidates) {
15811
- const fullPath = join6(dir, candidate);
15856
+ const fullPath = join7(dir, candidate);
15812
15857
  if (isExecutableFile(fullPath, isWindows))
15813
15858
  return fullPath;
15814
15859
  }
@@ -15834,25 +15879,25 @@ function isExecutableFile(path, isWindows = process.platform === "win32") {
15834
15879
  var init_find_on_path = () => {};
15835
15880
 
15836
15881
  // src/lib/paths.ts
15837
- import { existsSync as existsSync9, readdirSync as readdirSync2, statSync as statSync7 } from "node:fs";
15882
+ import { existsSync as existsSync9, lstatSync as lstatSync4, readdirSync as readdirSync2, statSync as statSync7 } from "node:fs";
15838
15883
  import { homedir as homedir7 } from "node:os";
15839
- import { delimiter as delimiter2, dirname as dirname8, join as join7, resolve as resolve3 } from "node:path";
15884
+ import { delimiter as delimiter2, dirname as dirname8, join as join8, resolve as resolve4 } from "node:path";
15840
15885
  function getOpenCodeConfigDir() {
15841
15886
  const envDir = process.env.OPENCODE_CONFIG_DIR?.trim();
15842
15887
  if (envDir)
15843
15888
  return envDir;
15844
15889
  if (process.platform === "win32") {
15845
- return join7(homedir7(), ".config", "opencode");
15890
+ return join8(homedir7(), ".config", "opencode");
15846
15891
  }
15847
- const xdgConfig = process.env.XDG_CONFIG_HOME || join7(homedir7(), ".config");
15848
- return join7(xdgConfig, "opencode");
15892
+ const xdgConfig = process.env.XDG_CONFIG_HOME || join8(homedir7(), ".config");
15893
+ return join8(xdgConfig, "opencode");
15849
15894
  }
15850
15895
  function findOmoConfig(configDir) {
15851
15896
  const locations = [
15852
- join7(configDir, "oh-my-openagent.jsonc"),
15853
- join7(configDir, "oh-my-openagent.json"),
15854
- join7(configDir, "oh-my-opencode.jsonc"),
15855
- join7(configDir, "oh-my-opencode.json")
15897
+ join8(configDir, "oh-my-openagent.jsonc"),
15898
+ join8(configDir, "oh-my-openagent.json"),
15899
+ join8(configDir, "oh-my-opencode.jsonc"),
15900
+ join8(configDir, "oh-my-opencode.json")
15856
15901
  ];
15857
15902
  for (const loc of locations) {
15858
15903
  if (existsSync9(loc))
@@ -15866,8 +15911,8 @@ function detectConfigPaths() {
15866
15911
  let opencodeConfigFormat;
15867
15912
  let tuiConfig;
15868
15913
  let tuiConfigFormat;
15869
- const jsoncPath = join7(configDir, "opencode.jsonc");
15870
- const jsonPath = join7(configDir, "opencode.json");
15914
+ const jsoncPath = join8(configDir, "opencode.jsonc");
15915
+ const jsonPath = join8(configDir, "opencode.json");
15871
15916
  if (existsSync9(jsoncPath)) {
15872
15917
  opencodeConfig = jsoncPath;
15873
15918
  opencodeConfigFormat = "jsonc";
@@ -15878,8 +15923,8 @@ function detectConfigPaths() {
15878
15923
  opencodeConfig = jsoncPath;
15879
15924
  opencodeConfigFormat = "none";
15880
15925
  }
15881
- const tuiJsoncPath = join7(configDir, "tui.jsonc");
15882
- const tuiJsonPath = join7(configDir, "tui.json");
15926
+ const tuiJsoncPath = join8(configDir, "tui.jsonc");
15927
+ const tuiJsonPath = join8(configDir, "tui.json");
15883
15928
  if (existsSync9(tuiJsoncPath)) {
15884
15929
  tuiConfig = tuiJsoncPath;
15885
15930
  tuiConfigFormat = "jsonc";
@@ -15908,40 +15953,40 @@ function getPiAgentDir() {
15908
15953
  const envDir = process.env.PI_CODING_AGENT_DIR?.trim();
15909
15954
  if (envDir)
15910
15955
  return envDir;
15911
- return join7(envFirstHomeDir(), ".pi", "agent");
15956
+ return join8(envFirstHomeDir(), ".pi", "agent");
15912
15957
  }
15913
15958
  function getPiAgentConfigDir() {
15914
15959
  return getPiAgentDir();
15915
15960
  }
15916
15961
  function getPiSessionsRoot() {
15917
- return join7(getPiAgentDir(), "sessions");
15962
+ return join8(getPiAgentDir(), "sessions");
15918
15963
  }
15919
15964
  function getPiCacheRoot() {
15920
- return join7(dirname8(getPiAgentDir()), "cache");
15965
+ return join8(dirname8(getPiAgentDir()), "cache");
15921
15966
  }
15922
15967
  function getPiUserConfigPath() {
15923
15968
  return resolveCortexKitUserConfigPath();
15924
15969
  }
15925
15970
  function getPiUserExtensionsPath() {
15926
- return join7(getPiAgentConfigDir(), "settings.json");
15971
+ return join8(getPiAgentConfigDir(), "settings.json");
15927
15972
  }
15928
15973
  function resolveOmpPaths() {
15929
15974
  const rawProfile = process.env.OMP_PROFILE ?? process.env.PI_PROFILE;
15930
15975
  const normalizedProfile = rawProfile?.trim();
15931
15976
  const profile = normalizedProfile && normalizedProfile !== "default" && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(normalizedProfile) ? normalizedProfile : undefined;
15932
15977
  const configDirName = process.env.PI_CONFIG_DIR?.trim() || ".omp";
15933
- const baseConfigRoot = join7(envFirstHomeDir(), configDirName);
15934
- const configRoot = profile ? join7(baseConfigRoot, "profiles", profile) : baseConfigRoot;
15935
- const defaultAgentDir = join7(configRoot, "agent");
15978
+ const baseConfigRoot = join8(envFirstHomeDir(), configDirName);
15979
+ const configRoot = profile ? join8(baseConfigRoot, "profiles", profile) : baseConfigRoot;
15980
+ const defaultAgentDir = join8(configRoot, "agent");
15936
15981
  const override = profile ? undefined : process.env.PI_CODING_AGENT_DIR?.trim();
15937
- const agentDir = override ? resolve3(override) : defaultAgentDir;
15982
+ const agentDir = override ? resolve4(override) : defaultAgentDir;
15938
15983
  const canUseXdg = (process.platform === "linux" || process.platform === "darwin") && agentDir === defaultAgentDir;
15939
15984
  let dataRoot = configRoot;
15940
15985
  if (canUseXdg) {
15941
15986
  const xdgDataHome = process.env.XDG_DATA_HOME?.trim();
15942
15987
  if (xdgDataHome) {
15943
- const appRoot = join7(xdgDataHome, "omp");
15944
- const candidate = profile ? join7(appRoot, "profiles", profile) : appRoot;
15988
+ const appRoot = join8(xdgDataHome, "omp");
15989
+ const candidate = profile ? join8(appRoot, "profiles", profile) : appRoot;
15945
15990
  if (existsSync9(candidate))
15946
15991
  dataRoot = candidate;
15947
15992
  }
@@ -15952,8 +15997,8 @@ function resolveOmpPaths() {
15952
15997
  agentDir,
15953
15998
  dataRoot,
15954
15999
  dataAgentRoot,
15955
- pluginsDir: join7(dataRoot, "plugins"),
15956
- sessionsRoot: join7(dataAgentRoot, "sessions")
16000
+ pluginsDir: join8(dataRoot, "plugins"),
16001
+ sessionsRoot: join8(dataAgentRoot, "sessions")
15957
16002
  };
15958
16003
  }
15959
16004
  function getOmpAgentDir() {
@@ -15963,7 +16008,7 @@ function getOmpSessionsRoot() {
15963
16008
  return resolveOmpPaths().sessionsRoot;
15964
16009
  }
15965
16010
  function getOmpConfigPath() {
15966
- return join7(resolveOmpPaths().agentDir, "config.yml");
16011
+ return join8(resolveOmpPaths().agentDir, "config.yml");
15967
16012
  }
15968
16013
  function getOmpPackageDir() {
15969
16014
  const value = process.env.PI_PACKAGE_DIR?.trim();
@@ -15972,13 +16017,13 @@ function getOmpPackageDir() {
15972
16017
  if (value === "~")
15973
16018
  return envFirstHomeDir();
15974
16019
  if (value.startsWith("~/") || value.startsWith("~\\")) {
15975
- return resolve3(envFirstHomeDir(), value.slice(2));
16020
+ return resolve4(envFirstHomeDir(), value.slice(2));
15976
16021
  }
15977
- return resolve3(value);
16022
+ return resolve4(value);
15978
16023
  }
15979
16024
  function getOmpNonGlobalConfigSources(cwd = process.cwd()) {
15980
16025
  const sources = getOmpConfigOverlayPaths(cwd);
15981
- const projectConfig = resolve3(cwd, ".omp", "config.yml");
16026
+ const projectConfig = resolve4(cwd, ".omp", "config.yml");
15982
16027
  if (existsSync9(projectConfig))
15983
16028
  sources.push(projectConfig);
15984
16029
  return [...new Set(sources)];
@@ -15987,15 +16032,12 @@ function getOmpConfigOverlayPaths(cwd = process.cwd()) {
15987
16032
  return process.env.PI_CONFIG_FILES?.split(delimiter2).map((entry) => entry.trim()).filter(Boolean).map((entry) => {
15988
16033
  if (entry === "~")
15989
16034
  return envFirstHomeDir();
15990
- const expanded = entry.startsWith("~/") || entry.startsWith("~\\") ? join7(envFirstHomeDir(), entry.slice(2)) : entry;
15991
- return resolve3(cwd, expanded);
16035
+ const expanded = entry.startsWith("~/") || entry.startsWith("~\\") ? join8(envFirstHomeDir(), entry.slice(2)) : entry;
16036
+ return resolve4(cwd, expanded);
15992
16037
  }) ?? [];
15993
16038
  }
15994
- function getOmpPluginsDir() {
15995
- return resolveOmpPaths().pluginsDir;
15996
- }
15997
16039
  function getOmpPluginsLockPath() {
15998
- return join7(resolveOmpPaths().pluginsDir, "omp-plugins.lock.json");
16040
+ return join8(resolveOmpPaths().pluginsDir, "omp-plugins.lock.json");
15999
16041
  }
16000
16042
  function getOmpUserConfigPath() {
16001
16043
  return resolveCortexKitUserConfigPath();
@@ -16007,26 +16049,18 @@ function getMagicContextHistorianDir2(harness) {
16007
16049
  return getMagicContextHistorianDir(harness);
16008
16050
  }
16009
16051
  function getProjectHistorianDumpDir(directory) {
16010
- return join7(getProjectMagicContextDir(directory), "historian");
16052
+ return join8(getProjectMagicContextDir(directory), "historian");
16053
+ }
16054
+ function getOpenCodeCacheHome() {
16055
+ return process.env.XDG_CACHE_HOME || join8(homedir7(), ".cache");
16011
16056
  }
16012
16057
  function getOpenCodePluginCacheDir() {
16013
- const xdg = process.env.XDG_CACHE_HOME || join7(homedir7(), ".cache");
16014
- return join7(xdg, "opencode", "packages");
16058
+ return join8(getOpenCodeCacheHome(), "opencode", "packages");
16015
16059
  }
16016
16060
  function getOpenCodeV2NpmCacheDir() {
16017
- const xdg = process.env.XDG_CACHE_HOME || join7(homedir7(), ".cache");
16018
- return join7(xdg, "opencode", "npm");
16019
- }
16020
- function isDir(path) {
16021
- try {
16022
- return statSync7(path).isDirectory();
16023
- } catch {
16024
- return false;
16025
- }
16061
+ return join8(getOpenCodeCacheHome(), "opencode", "npm");
16026
16062
  }
16027
16063
  function dirSizeBytes(path) {
16028
- if (!isDir(path))
16029
- return 0;
16030
16064
  let total = 0;
16031
16065
  const stack = [path];
16032
16066
  while (stack.length > 0) {
@@ -16034,14 +16068,18 @@ function dirSizeBytes(path) {
16034
16068
  if (cur === undefined)
16035
16069
  break;
16036
16070
  try {
16071
+ if (!lstatSync4(cur).isDirectory())
16072
+ continue;
16037
16073
  const entries = readdirSync2(cur, { withFileTypes: true });
16038
16074
  for (const entry of entries) {
16039
- const child = join7(cur, entry.name);
16075
+ const child = join8(cur, entry.name);
16040
16076
  if (entry.isDirectory()) {
16041
16077
  stack.push(child);
16042
16078
  } else if (entry.isFile()) {
16043
16079
  try {
16044
- total += statSync7(child).size;
16080
+ const file = lstatSync4(child);
16081
+ if (file.isFile())
16082
+ total += file.size;
16045
16083
  } catch {}
16046
16084
  }
16047
16085
  }
@@ -16057,7 +16095,7 @@ var init_paths = __esm(() => {
16057
16095
  // src/lib/pi-helpers.ts
16058
16096
  import { execFileSync, spawnSync } from "node:child_process";
16059
16097
  import { homedir as homedir8 } from "node:os";
16060
- import { extname, join as join8 } from "node:path";
16098
+ import { extname, join as join9 } from "node:path";
16061
16099
  function getPiCommandInvocation(piPath, args) {
16062
16100
  const extension = extname(piPath).toLowerCase();
16063
16101
  if (extension !== ".cmd" && extension !== ".bat") {
@@ -16071,7 +16109,7 @@ function detectPiBinary() {
16071
16109
  if (fromPath)
16072
16110
  return { path: fromPath, source: "path" };
16073
16111
  const home = process.env.HOME?.trim() || homedir8();
16074
- const homeCandidate = process.platform === "win32" ? join8(home, ".pi", "bin", "pi.cmd") : join8(home, ".pi", "bin", "pi");
16112
+ const homeCandidate = process.platform === "win32" ? join9(home, ".pi", "bin", "pi.cmd") : join9(home, ".pi", "bin", "pi");
16075
16113
  if (isExecutableFile(homeCandidate))
16076
16114
  return { path: homeCandidate, source: "home" };
16077
16115
  return null;
@@ -16152,7 +16190,7 @@ var init_pi_helpers = __esm(() => {
16152
16190
  import { spawnSync as spawnSync2 } from "node:child_process";
16153
16191
  import { existsSync as existsSync10, readFileSync as readFileSync7 } from "node:fs";
16154
16192
  import { homedir as homedir9 } from "node:os";
16155
- import { extname as extname2, join as join9 } from "node:path";
16193
+ import { extname as extname2, join as join10 } from "node:path";
16156
16194
  function detectOmpPackageCli() {
16157
16195
  const packageDir = getOmpPackageDir();
16158
16196
  if (!packageDir)
@@ -16160,10 +16198,10 @@ function detectOmpPackageCli() {
16160
16198
  if (!findOnPath("bun"))
16161
16199
  return null;
16162
16200
  try {
16163
- const manifest = JSON.parse(readFileSync7(join9(packageDir, "package.json"), "utf-8"));
16201
+ const manifest = JSON.parse(readFileSync7(join10(packageDir, "package.json"), "utf-8"));
16164
16202
  if (manifest.name !== "@oh-my-pi/pi-coding-agent")
16165
16203
  return null;
16166
- const cli = join9(packageDir, "dist", "cli.js");
16204
+ const cli = join10(packageDir, "dist", "cli.js");
16167
16205
  return existsSync10(cli) ? cli : null;
16168
16206
  } catch {
16169
16207
  return null;
@@ -16179,13 +16217,13 @@ function getOmpCommandInvocation(ompPath, args) {
16179
16217
  }
16180
16218
  function getOmpFallbackCandidates(platform, home, appData) {
16181
16219
  if (platform !== "win32") {
16182
- return [join9(home, ".bun", "bin", "omp"), join9(home, ".local", "bin", "omp")];
16220
+ return [join10(home, ".bun", "bin", "omp"), join10(home, ".local", "bin", "omp")];
16183
16221
  }
16184
16222
  const npmRoot = appData?.trim();
16185
16223
  return [
16186
- ...npmRoot ? [join9(npmRoot, "npm", "omp.cmd"), join9(npmRoot, "npm", "omp.exe")] : [],
16187
- join9(home, ".bun", "bin", "omp.exe"),
16188
- join9(home, ".bun", "bin", "omp.cmd")
16224
+ ...npmRoot ? [join10(npmRoot, "npm", "omp.cmd"), join10(npmRoot, "npm", "omp.exe")] : [],
16225
+ join10(home, ".bun", "bin", "omp.exe"),
16226
+ join10(home, ".bun", "bin", "omp.cmd")
16189
16227
  ];
16190
16228
  }
16191
16229
  function detectOmpBinary() {
@@ -16308,8 +16346,8 @@ var init_omp_helpers = __esm(() => {
16308
16346
  });
16309
16347
 
16310
16348
  // src/adapters/omp.ts
16311
- import { existsSync as existsSync11, readFileSync as readFileSync8 } from "node:fs";
16312
- import { join as join10 } from "node:path";
16349
+ import { readFileSync as readFileSync8 } from "node:fs";
16350
+ import { join as join11 } from "node:path";
16313
16351
 
16314
16352
  class OmpAdapter {
16315
16353
  kind = "omp";
@@ -16409,8 +16447,17 @@ class OmpAdapter {
16409
16447
  return "Install OMP: https://omp.sh (npm: @oh-my-pi/pi-coding-agent)";
16410
16448
  }
16411
16449
  getPluginCacheInfo() {
16412
- const path = join10(getOmpPluginsDir(), "cache");
16413
- return [{ path, exists: existsSync11(path), sizeBytes: dirSizeBytes(path) }];
16450
+ const { dataRoot, pluginsDir } = resolveOmpPaths();
16451
+ const path = join11(pluginsDir, "cache");
16452
+ const check = checkCacheClearPath(dataRoot, path);
16453
+ return [
16454
+ {
16455
+ path,
16456
+ cacheRoot: dataRoot,
16457
+ exists: check.allowed || check.reason !== "missing",
16458
+ sizeBytes: check.allowed ? dirSizeBytes(check.path) : 0
16459
+ }
16460
+ ];
16414
16461
  }
16415
16462
  getLogPath() {
16416
16463
  return getMagicContextLogPath2("omp");
@@ -16441,6 +16488,7 @@ class OmpAdapter {
16441
16488
  }
16442
16489
  var DEFAULT_DEPS;
16443
16490
  var init_omp = __esm(() => {
16491
+ init_cache_clear_path();
16444
16492
  init_omp_helpers();
16445
16493
  init_paths();
16446
16494
  DEFAULT_DEPS = {
@@ -16451,9 +16499,9 @@ var init_omp = __esm(() => {
16451
16499
  });
16452
16500
 
16453
16501
  // ../plugin/src/shared/opencode-db-path.ts
16454
- import { existsSync as existsSync12, readdirSync as readdirSync3, statSync as statSync8 } from "node:fs";
16502
+ import { existsSync as existsSync11, readdirSync as readdirSync3, statSync as statSync8 } from "node:fs";
16455
16503
  import { homedir as homedir10 } from "node:os";
16456
- import { isAbsolute as isAbsolute4, join as join11, resolve as resolve4 } from "node:path";
16504
+ import { isAbsolute as isAbsolute5, join as join12, resolve as resolve5 } from "node:path";
16457
16505
  function openCodeHostGenerationFromVersion(version) {
16458
16506
  const text = version ?? "";
16459
16507
  if (/(?:^|\s|v)0\.0\.0-(?:beta|dev)-/.test(text))
@@ -16462,7 +16510,7 @@ function openCodeHostGenerationFromVersion(version) {
16462
16510
  return Number.isFinite(major) && major >= 2 ? "v2" : "v1";
16463
16511
  }
16464
16512
  function openCodeDataDir(env = process.env, dataHome) {
16465
- return join11(dataHome ?? env.XDG_DATA_HOME ?? join11(homedir10(), ".local", "share"), "opencode");
16513
+ return join12(dataHome ?? env.XDG_DATA_HOME ?? join12(homedir10(), ".local", "share"), "opencode");
16466
16514
  }
16467
16515
  function environmentKey(dataDir, hostGeneration, channel, env) {
16468
16516
  return [
@@ -16474,7 +16522,7 @@ function environmentKey(dataDir, hostGeneration, channel, env) {
16474
16522
  ].join("\x00");
16475
16523
  }
16476
16524
  function channelPath(dataDir, channel) {
16477
- return ["latest", "beta", "prod"].includes(channel) ? join11(dataDir, "opencode.db") : join11(dataDir, `opencode-${channel}.db`);
16525
+ return ["latest", "beta", "prod"].includes(channel) ? join12(dataDir, "opencode.db") : join12(dataDir, `opencode-${channel}.db`);
16478
16526
  }
16479
16527
  function discoveredCandidateNames(dataDir) {
16480
16528
  const names = ["opencode.db", "opencode-local.db", "opencode-dev.db"];
@@ -16486,7 +16534,7 @@ function discoveredCandidateNames(dataDir) {
16486
16534
  }
16487
16535
  function discoverOpenCodeDb(dataDir) {
16488
16536
  const candidates = discoveredCandidateNames(dataDir).map((name, order) => {
16489
- const path = join11(dataDir, name);
16537
+ const path = join12(dataDir, name);
16490
16538
  try {
16491
16539
  const metadata = statSync8(path);
16492
16540
  return metadata.isFile() ? { path, order, mtimeMs: metadata.mtimeMs } : null;
@@ -16496,7 +16544,7 @@ function discoverOpenCodeDb(dataDir) {
16496
16544
  });
16497
16545
  const existing = candidates.filter((candidate) => candidate !== null).sort((left, right) => right.mtimeMs - left.mtimeMs || left.order - right.order)[0];
16498
16546
  if (!existing) {
16499
- return { path: join11(dataDir, "opencode.db"), source: "default", channel: null };
16547
+ return { path: join12(dataDir, "opencode.db"), source: "default", channel: null };
16500
16548
  }
16501
16549
  const name = existing.path.slice(dataDir.length + 1);
16502
16550
  const channel = name === "opencode.db" ? null : name.slice("opencode-".length, -".db".length) || null;
@@ -16509,14 +16557,14 @@ function resolveV1Fresh(dataDir, env = process.env) {
16509
16557
  return { path: explicit, source: "OPENCODE_DB", channel: null };
16510
16558
  }
16511
16559
  return {
16512
- path: isAbsolute4(explicit) ? explicit : join11(dataDir, explicit),
16560
+ path: isAbsolute5(explicit) ? explicit : join12(dataDir, explicit),
16513
16561
  source: "OPENCODE_DB",
16514
16562
  channel: null
16515
16563
  };
16516
16564
  }
16517
16565
  const disableChannelDb = env.OPENCODE_DISABLE_CHANNEL_DB;
16518
16566
  if (disableChannelDb === "1" || disableChannelDb === "true") {
16519
- return { path: join11(dataDir, "opencode.db"), source: "default", channel: null };
16567
+ return { path: join12(dataDir, "opencode.db"), source: "default", channel: null };
16520
16568
  }
16521
16569
  const channel = env.OPENCODE_CHANNEL;
16522
16570
  if (channel !== undefined && channel.length > 0) {
@@ -16540,7 +16588,7 @@ function resolveV2Fresh(dataDir, channel, env) {
16540
16588
  const filename = sourceOpenCodeDatabaseFilename("v2", channel, env);
16541
16589
  const explicit = env.OPENCODE_DB !== undefined;
16542
16590
  return {
16543
- path: filename === ":memory:" ? filename : resolve4(dataDir, filename),
16591
+ path: filename === ":memory:" ? filename : resolve5(dataDir, filename),
16544
16592
  source: explicit ? "OPENCODE_DB" : env.OPENCODE_CHANNEL ? "channel" : "default",
16545
16593
  channel: explicit ? null : channel
16546
16594
  };
@@ -16550,7 +16598,7 @@ function resolveOpenCodeDbPath(hostGeneration = "v1", options = {}) {
16550
16598
  const dataDir = openCodeDataDir(env, options.dataHome);
16551
16599
  const channel = options.channel ?? env.OPENCODE_CHANNEL;
16552
16600
  const key = environmentKey(dataDir, hostGeneration, channel, env);
16553
- if (cachedResolution?.key === key && (!cachedResolution.existed || existsSync12(cachedResolution.resolution.path))) {
16601
+ if (cachedResolution?.key === key && (!cachedResolution.existed || existsSync11(cachedResolution.resolution.path))) {
16554
16602
  if (cachedResolution.existed)
16555
16603
  return cachedResolution.resolution;
16556
16604
  }
@@ -16558,7 +16606,7 @@ function resolveOpenCodeDbPath(hostGeneration = "v1", options = {}) {
16558
16606
  cachedResolution = {
16559
16607
  key,
16560
16608
  resolution,
16561
- existed: resolution.path !== ":memory:" && existsSync12(resolution.path)
16609
+ existed: resolution.path !== ":memory:" && existsSync11(resolution.path)
16562
16610
  };
16563
16611
  return resolution;
16564
16612
  }
@@ -16598,7 +16646,7 @@ function assertOpenCodeStoreGeneration(db, expected, path, schema = "main") {
16598
16646
  throw new Error(`OpenCode store generation mismatch at ${path}: expected ${expected}, found ${actual}; refusing generation-specific database access`);
16599
16647
  }
16600
16648
  function openCodeDbPathExists(resolution = resolveOpenCodeDbPath()) {
16601
- return resolution.path !== ":memory:" && existsSync12(resolution.path);
16649
+ return resolution.path !== ":memory:" && existsSync11(resolution.path);
16602
16650
  }
16603
16651
  function getOpenCodeDbProbeDescriptions(resolution = resolveOpenCodeDbPath()) {
16604
16652
  if (resolution.source === "OPENCODE_DB")
@@ -16608,10 +16656,10 @@ function getOpenCodeDbProbeDescriptions(resolution = resolveOpenCodeDbPath()) {
16608
16656
  }
16609
16657
  const dataDir = openCodeDataDir();
16610
16658
  return [
16611
- join11(dataDir, "opencode.db"),
16612
- join11(dataDir, "opencode-local.db"),
16613
- join11(dataDir, "opencode-dev.db"),
16614
- join11(dataDir, "opencode-<channel>.db")
16659
+ join12(dataDir, "opencode.db"),
16660
+ join12(dataDir, "opencode-local.db"),
16661
+ join12(dataDir, "opencode-dev.db"),
16662
+ join12(dataDir, "opencode-<channel>.db")
16615
16663
  ];
16616
16664
  }
16617
16665
  function lookedForText(resolution) {
@@ -25154,22 +25202,22 @@ var init_opencode_plugin_registration = __esm(() => {
25154
25202
 
25155
25203
  // src/lib/opencode-plugin-cache.ts
25156
25204
  import { readdirSync as readdirSync4, readFileSync as readFileSync10 } from "node:fs";
25157
- import { join as join12 } from "node:path";
25205
+ import { join as join13 } from "node:path";
25158
25206
  function getOpenCodePluginCacheRoots() {
25159
25207
  const cacheDir = getOpenCodePluginCacheDir();
25160
25208
  return [
25161
- join12(cacheDir, OPENCODE_PLUGIN_ENTRY_WITH_VERSION),
25162
- join12(cacheDir, OPENCODE_PLUGIN_NAME)
25209
+ join13(cacheDir, OPENCODE_PLUGIN_ENTRY_WITH_VERSION),
25210
+ join13(cacheDir, OPENCODE_PLUGIN_NAME)
25163
25211
  ];
25164
25212
  }
25165
25213
  function getOpenCodePluginPackageJsonPath(pluginCacheRoot) {
25166
- return join12(pluginCacheRoot, "node_modules", ...OPENCODE_PLUGIN_NAME.split("/"), "package.json");
25214
+ return join13(pluginCacheRoot, "node_modules", ...OPENCODE_PLUGIN_NAME.split("/"), "package.json");
25167
25215
  }
25168
25216
  function getOpenCodePluginPackageJsonPaths() {
25169
25217
  return getOpenCodePluginCacheRoots().map(getOpenCodePluginPackageJsonPath);
25170
25218
  }
25171
25219
  function getOpenCodeV2PluginCacheSlot(npmCacheDir = getOpenCodeV2NpmCacheDir(), spec = "latest") {
25172
- return join12(npmCacheDir, ...`${OPENCODE_PLUGIN_NAME}@${spec}`.split("/"));
25220
+ return join13(npmCacheDir, ...`${OPENCODE_PLUGIN_NAME}@${spec}`.split("/"));
25173
25221
  }
25174
25222
  function openCodeV2PluginSpecOf(specifier) {
25175
25223
  if (specifier === OPENCODE_PLUGIN_NAME)
@@ -25222,7 +25270,7 @@ function pluginEntrySpecifier(entry) {
25222
25270
  }
25223
25271
  function listOpenCodeV2PluginCacheSlots(npmCacheDir = getOpenCodeV2NpmCacheDir()) {
25224
25272
  const [scope = "", name = ""] = OPENCODE_PLUGIN_NAME.split("/");
25225
- const scopeDir = join12(npmCacheDir, scope);
25273
+ const scopeDir = join13(npmCacheDir, scope);
25226
25274
  let names;
25227
25275
  try {
25228
25276
  names = readdirSync4(scopeDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name.startsWith(`${name}@`)).map((entry) => entry.name);
@@ -25230,7 +25278,7 @@ function listOpenCodeV2PluginCacheSlots(npmCacheDir = getOpenCodeV2NpmCacheDir()
25230
25278
  return [];
25231
25279
  }
25232
25280
  return names.map((dirName) => {
25233
- const slot = join12(scopeDir, dirName);
25281
+ const slot = join13(scopeDir, dirName);
25234
25282
  return {
25235
25283
  spec: dirName.slice(name.length + 1),
25236
25284
  slot,
@@ -25246,7 +25294,7 @@ function getOpenCodeV2ActiveGeneration(slot) {
25246
25294
  try {
25247
25295
  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));
25248
25296
  const newest = generations.at(-1);
25249
- return newest === undefined ? undefined : join12(slot, newest);
25297
+ return newest === undefined ? undefined : join13(slot, newest);
25250
25298
  } catch {
25251
25299
  return;
25252
25300
  }
@@ -25293,7 +25341,7 @@ var init_opencode_plugin_cache = __esm(() => {
25293
25341
  });
25294
25342
 
25295
25343
  // src/commands/doctor-windows-holders.ts
25296
- import { existsSync as existsSync13 } from "node:fs";
25344
+ import { existsSync as existsSync12 } from "node:fs";
25297
25345
  function fileName(path) {
25298
25346
  return path.toLowerCase().replaceAll("\\", "/").split("/").at(-1) ?? "";
25299
25347
  }
@@ -25386,7 +25434,7 @@ function assertWindowsStoresClosed(paths, processes) {
25386
25434
  if (blockers.length)
25387
25435
  throw new Error(`OpenCode, Pi or ck-mc process is running (${blockers.map(({ pid, imageName, commandLine }) => `${imageName ?? commandLine} PID ${pid}`).join(", ")})`);
25388
25436
  for (const path of [...new Set(paths)]) {
25389
- if (!existsSync13(path))
25437
+ if (!existsSync12(path))
25390
25438
  continue;
25391
25439
  let db;
25392
25440
  let locked = false;
@@ -25493,7 +25541,7 @@ var init_doctor_windows_holders = __esm(async () => {
25493
25541
 
25494
25542
  // src/commands/doctor-opencode2-cache.ts
25495
25543
  import { spawnSync as spawnSync3 } from "node:child_process";
25496
- import { existsSync as existsSync14, rmSync as rmSync4 } from "node:fs";
25544
+ import { existsSync as existsSync13, rmSync as rmSync4 } from "node:fs";
25497
25545
  function runLsof(args, spawn) {
25498
25546
  const result = spawn("lsof", args, { encoding: "utf-8", timeout: 15000, windowsHide: true });
25499
25547
  if (result.error)
@@ -25508,7 +25556,7 @@ function probeHostProcessesUsing(targets, spawn = spawnSync3) {
25508
25556
  if (process.platform === "win32") {
25509
25557
  try {
25510
25558
  assertWindowsStoresClosed(targets.files.filter((path) => !/-(?:wal|shm)$/.test(path)), inspectWindowsProcessesSync());
25511
- if (targets.directories.some(existsSync14))
25559
+ if (targets.directories.some(existsSync13))
25512
25560
  return {
25513
25561
  status: "unknown",
25514
25562
  reason: "Windows cannot rule out open files in plugin cache directories"
@@ -25521,8 +25569,8 @@ function probeHostProcessesUsing(targets, spawn = spawnSync3) {
25521
25569
  };
25522
25570
  }
25523
25571
  }
25524
- const files = targets.files.filter((file) => existsSync14(file));
25525
- const directories = targets.directories.filter((directory) => existsSync14(directory));
25572
+ const files = targets.files.filter((file) => existsSync13(file));
25573
+ const directories = targets.directories.filter((directory) => existsSync13(directory));
25526
25574
  const queries = [];
25527
25575
  if (files.length > 0)
25528
25576
  queries.push(["-w", "-t", "--", ...files]);
@@ -25590,7 +25638,11 @@ function isStale(cached, latest) {
25590
25638
  return true;
25591
25639
  return comparison < 0;
25592
25640
  }
25593
- function removeOpenCodeV2PluginCacheSlot(slot, hostFiles, deps = {}) {
25641
+ function removeOpenCodeV2PluginCacheSlot(cacheRoot, slot, hostFiles, deps = {}) {
25642
+ const beforeProbe = checkCacheClearPath(cacheRoot, slot);
25643
+ if (!beforeProbe.allowed) {
25644
+ return { action: "skipped", reason: describeCacheClearRefusal(slot, beforeProbe.reason) };
25645
+ }
25594
25646
  const probe = deps.probe ?? probeHostProcessesUsing;
25595
25647
  const use = probe({ files: hostFiles, directories: [slot] });
25596
25648
  if (use.status === "in_use")
@@ -25598,8 +25650,12 @@ function removeOpenCodeV2PluginCacheSlot(slot, hostFiles, deps = {}) {
25598
25650
  if (use.status === "unknown")
25599
25651
  return { action: "in_use_unknown", reason: use.reason };
25600
25652
  const remove = deps.remove ?? ((path) => rmSync4(path, { recursive: true, force: true }));
25653
+ const check = checkCacheClearPath(cacheRoot, slot);
25654
+ if (!check.allowed) {
25655
+ return { action: "skipped", reason: describeCacheClearRefusal(slot, check.reason) };
25656
+ }
25601
25657
  try {
25602
- remove(slot);
25658
+ remove(check.path);
25603
25659
  } catch (err) {
25604
25660
  return { action: "error", error: err instanceof Error ? err.message : String(err) };
25605
25661
  }
@@ -25614,14 +25670,25 @@ function configuredOpenCodeV2DistTag(config) {
25614
25670
  }
25615
25671
  function checkOpenCodeV2PluginCache(options, deps = {}) {
25616
25672
  const distTag = options.distTag && options.distTag !== "latest" ? options.distTag : undefined;
25617
- const slot = deps.slot ?? getOpenCodeV2PluginCacheSlot(undefined, distTag ?? "latest");
25673
+ const cacheRoot = deps.npmCacheDir ?? getOpenCodeCacheHome();
25674
+ const slot = getOpenCodeV2PluginCacheSlot(deps.npmCacheDir, distTag ?? "latest");
25618
25675
  const tagged = distTag ? { distTag } : {};
25619
- if (options.referencedSpecs !== undefined && !options.referencedSpecs.has(distTag ?? "latest")) {
25620
- return existsSync14(slot) ? { action: "unused", slot, cached: readOpenCodeV2CachedPluginVersion(slot), ...tagged } : { action: "not_found", slot, unused: true, ...tagged };
25676
+ const unused = options.referencedSpecs !== undefined && !options.referencedSpecs.has(distTag ?? "latest");
25677
+ const check = checkCacheClearPath(cacheRoot, slot);
25678
+ if (!check.allowed) {
25679
+ if (check.reason === "missing") {
25680
+ return { action: "not_found", slot, ...unused ? { unused: true } : {}, ...tagged };
25681
+ }
25682
+ return {
25683
+ action: "skipped",
25684
+ slot,
25685
+ reason: describeCacheClearRefusal(slot, check.reason),
25686
+ ...tagged
25687
+ };
25621
25688
  }
25622
- if (!existsSync14(slot))
25623
- return { action: "not_found", slot, ...tagged };
25624
- const cached = readOpenCodeV2CachedPluginVersion(slot);
25689
+ const cached = readOpenCodeV2CachedPluginVersion(check.path);
25690
+ if (unused)
25691
+ return { action: "unused", slot, cached, ...tagged };
25625
25692
  const latest = options.latestVersion ?? undefined;
25626
25693
  const force = options.force === true;
25627
25694
  if (latest === undefined && !force) {
@@ -25633,7 +25700,7 @@ function checkOpenCodeV2PluginCache(options, deps = {}) {
25633
25700
  if (!force && options.fix !== true) {
25634
25701
  return { action: "stale", slot, cached, latest, ...tagged };
25635
25702
  }
25636
- const removal = removeOpenCodeV2PluginCacheSlot(slot, options.hostFiles, deps);
25703
+ const removal = removeOpenCodeV2PluginCacheSlot(cacheRoot, slot, options.hostFiles, deps);
25637
25704
  switch (removal.action) {
25638
25705
  case "in_use":
25639
25706
  return { action: "in_use", slot, cached, latest, pids: removal.pids, ...tagged };
@@ -25646,6 +25713,8 @@ function checkOpenCodeV2PluginCache(options, deps = {}) {
25646
25713
  reason: removal.reason,
25647
25714
  ...tagged
25648
25715
  };
25716
+ case "skipped":
25717
+ return { action: "skipped", slot, cached, latest, reason: removal.reason, ...tagged };
25649
25718
  case "error":
25650
25719
  return { action: "error", slot, cached, latest, error: removal.error, ...tagged };
25651
25720
  case "cleared":
@@ -25686,6 +25755,9 @@ function reportOpenCodeV2PluginCache(result, report, options) {
25686
25755
  report.pass(`Cleared ${result.forced ? "" : "outdated "}Magic Context${slotName} from the OpenCode 2 plugin cache (${versions}${result.forced ? ", --force" : ""}) — OpenCode installs the ${result.distTag ? `current ${tag} release` : "latest"} on next start`);
25687
25756
  report.info(` ${result.slot}`);
25688
25757
  return { fixed: true, issue: false };
25758
+ case "skipped":
25759
+ report.warn(result.reason ?? `Left ${result.slot} alone`);
25760
+ return { fixed: false, issue: false };
25689
25761
  case "unused":
25690
25762
  report.info(describeUnusedOpenCodePluginCache({
25691
25763
  host: "OpenCode 2",
@@ -25704,14 +25776,16 @@ function reportOpenCodeV2PluginCache(result, report, options) {
25704
25776
  var OPENCODE_V2_PLUGIN_UPDATE_HINT = "update it from OpenCode: open /plugins, select Magic Context and press ctrl+u (ctrl+r only re-checks), or run `opencode plugin update`";
25705
25777
  var init_doctor_opencode2_cache = __esm(async () => {
25706
25778
  init_rpc_utils();
25779
+ init_cache_clear_path();
25707
25780
  init_opencode_plugin_cache();
25781
+ init_paths();
25708
25782
  await init_doctor_windows_holders();
25709
25783
  });
25710
25784
 
25711
25785
  // src/lib/atomic-write.ts
25712
25786
  import { randomBytes as randomBytes2 } from "node:crypto";
25713
25787
  import {
25714
- lstatSync as lstatSync3,
25788
+ lstatSync as lstatSync5,
25715
25789
  mkdirSync as mkdirSync5,
25716
25790
  readlinkSync as readlinkSync3,
25717
25791
  renameSync as renameSync4,
@@ -25719,14 +25793,14 @@ import {
25719
25793
  statSync as statSync9,
25720
25794
  writeFileSync as writeFileSync5
25721
25795
  } from "node:fs";
25722
- import { dirname as dirname9, resolve as resolve5 } from "node:path";
25796
+ import { dirname as dirname9, resolve as resolve6 } from "node:path";
25723
25797
  function resolveWriteTarget(targetPath) {
25724
- let current = resolve5(targetPath);
25798
+ let current = resolve6(targetPath);
25725
25799
  for (let hop = 0;hop < MAX_SYMLINK_HOPS; hop++) {
25726
- const stat = lstatSync3(current, { throwIfNoEntry: false });
25800
+ const stat = lstatSync5(current, { throwIfNoEntry: false });
25727
25801
  if (!stat?.isSymbolicLink())
25728
25802
  return current;
25729
- current = resolve5(dirname9(current), readlinkSync3(current));
25803
+ current = resolve6(dirname9(current), readlinkSync3(current));
25730
25804
  }
25731
25805
  throw new Error(`Too many levels of symbolic links resolving ${targetPath}`);
25732
25806
  }
@@ -25758,7 +25832,7 @@ var init_atomic_write = __esm(() => {
25758
25832
  });
25759
25833
 
25760
25834
  // src/lib/jsonc-config.ts
25761
- import { existsSync as existsSync15, readFileSync as readFileSync11 } from "node:fs";
25835
+ import { existsSync as existsSync14, readFileSync as readFileSync11 } from "node:fs";
25762
25836
  function parseErrorLocation(content, error) {
25763
25837
  const lines = content.split(`
25764
25838
  `);
@@ -25774,7 +25848,7 @@ function parseErrorLocation(content, error) {
25774
25848
  return { line: messageLine ? Number.parseInt(messageLine, 10) : 1, column: 1 };
25775
25849
  }
25776
25850
  function readJsoncConfig(path) {
25777
- if (!existsSync15(path))
25851
+ if (!existsSync14(path))
25778
25852
  return { kind: "missing" };
25779
25853
  const content = readFileSync11(path, "utf-8");
25780
25854
  try {
@@ -25891,13 +25965,13 @@ var init_jsonc_config = __esm(() => {
25891
25965
  });
25892
25966
 
25893
25967
  // src/lib/opencode-detect.ts
25894
- import { existsSync as existsSync16, realpathSync as realpathSync3 } from "node:fs";
25968
+ import { existsSync as existsSync15, realpathSync as realpathSync4 } from "node:fs";
25895
25969
  import { homedir as homedir11 } from "node:os";
25896
- import { join as join13 } from "node:path";
25970
+ import { join as join14 } from "node:path";
25897
25971
  function defaultDeps(overrides = {}) {
25898
25972
  const env = overrides.env ?? process.env;
25899
25973
  return {
25900
- exists: overrides.exists ?? existsSync16,
25974
+ exists: overrides.exists ?? existsSync15,
25901
25975
  isExecutable: overrides.isExecutable ?? isExecutableFile,
25902
25976
  home: overrides.home ?? (env.HOME?.trim() || homedir11()),
25903
25977
  platform: overrides.platform ?? process.platform,
@@ -25907,7 +25981,7 @@ function defaultDeps(overrides = {}) {
25907
25981
  };
25908
25982
  }
25909
25983
  function stockCliBinary(d) {
25910
- return d.platform === "win32" ? join13(d.home, ".opencode", "bin", "opencode.exe") : join13(d.home, ".opencode", "bin", "opencode");
25984
+ return d.platform === "win32" ? join14(d.home, ".opencode", "bin", "opencode.exe") : join14(d.home, ".opencode", "bin", "opencode");
25911
25985
  }
25912
25986
  function extraCliCandidates(d) {
25913
25987
  if (d.platform === "win32") {
@@ -25916,25 +25990,25 @@ function extraCliCandidates(d) {
25916
25990
  const userprofile = d.env.USERPROFILE ?? d.home;
25917
25991
  const out = [];
25918
25992
  if (appdata) {
25919
- out.push(join13(appdata, "npm", "opencode.cmd"));
25920
- out.push(join13(appdata, "npm", "opencode.exe"));
25993
+ out.push(join14(appdata, "npm", "opencode.cmd"));
25994
+ out.push(join14(appdata, "npm", "opencode.exe"));
25921
25995
  }
25922
25996
  if (localappdata) {
25923
- out.push(join13(localappdata, "Microsoft", "WinGet", "Links", "opencode.exe"));
25924
- out.push(join13(localappdata, "opencode", "bin", "opencode.exe"));
25997
+ out.push(join14(localappdata, "Microsoft", "WinGet", "Links", "opencode.exe"));
25998
+ out.push(join14(localappdata, "opencode", "bin", "opencode.exe"));
25925
25999
  }
25926
26000
  if (userprofile) {
25927
- out.push(join13(userprofile, "scoop", "shims", "opencode.exe"));
26001
+ out.push(join14(userprofile, "scoop", "shims", "opencode.exe"));
25928
26002
  }
25929
26003
  return out;
25930
26004
  }
25931
26005
  return [
25932
26006
  "/usr/local/bin/opencode",
25933
26007
  "/opt/homebrew/bin/opencode",
25934
- join13(d.home, ".local", "bin", "opencode"),
25935
- join13(d.home, ".local", "share", "mise", "shims", "opencode"),
25936
- join13(d.home, ".asdf", "shims", "opencode"),
25937
- join13(d.home, ".volta", "bin", "opencode")
26008
+ join14(d.home, ".local", "bin", "opencode"),
26009
+ join14(d.home, ".local", "share", "mise", "shims", "opencode"),
26010
+ join14(d.home, ".asdf", "shims", "opencode"),
26011
+ join14(d.home, ".volta", "bin", "opencode")
25938
26012
  ];
25939
26013
  }
25940
26014
  function openChamberCliCandidates(d) {
@@ -25942,13 +26016,13 @@ function openChamberCliCandidates(d) {
25942
26016
  return [];
25943
26017
  const bundled = ["Contents", "Resources", "opencode-cli", "opencode"];
25944
26018
  return [
25945
- join13("/Applications", "OpenChamber.app", ...bundled),
25946
- join13(d.home, "Applications", "OpenChamber.app", ...bundled)
26019
+ join14("/Applications", "OpenChamber.app", ...bundled),
26020
+ join14(d.home, "Applications", "OpenChamber.app", ...bundled)
25947
26021
  ];
25948
26022
  }
25949
26023
  function canonicalPath(d, path) {
25950
26024
  try {
25951
- return d.realpath ? d.realpath(path) : realpathSync3(path);
26025
+ return d.realpath ? d.realpath(path) : realpathSync4(path);
25952
26026
  } catch {
25953
26027
  return path;
25954
26028
  }
@@ -25964,29 +26038,29 @@ function xdgConfigHome(d) {
25964
26038
  const xdg = d.env.XDG_CONFIG_HOME;
25965
26039
  if (xdg && xdg.length > 0)
25966
26040
  return xdg;
25967
- return join13(d.home, ".config");
26041
+ return join14(d.home, ".config");
25968
26042
  }
25969
26043
  function desktopUserDataDir(d, appId) {
25970
26044
  switch (d.platform) {
25971
26045
  case "darwin":
25972
- return join13(d.home, "Library", "Application Support", appId);
26046
+ return join14(d.home, "Library", "Application Support", appId);
25973
26047
  case "win32":
25974
- return join13(d.env.APPDATA ?? join13(d.home, "AppData", "Roaming"), appId);
26048
+ return join14(d.env.APPDATA ?? join14(d.home, "AppData", "Roaming"), appId);
25975
26049
  default:
25976
- return join13(xdgConfigHome(d), appId);
26050
+ return join14(xdgConfigHome(d), appId);
25977
26051
  }
25978
26052
  }
25979
26053
  function desktopAppPaths(d) {
25980
26054
  switch (d.platform) {
25981
26055
  case "darwin":
25982
- return ["/Applications/OpenCode.app", join13(d.home, "Applications", "OpenCode.app")];
26056
+ return ["/Applications/OpenCode.app", join14(d.home, "Applications", "OpenCode.app")];
25983
26057
  case "win32": {
25984
- const localappdata = d.env.LOCALAPPDATA ?? join13(d.home, "AppData", "Local");
25985
- return [join13(localappdata, "Programs", "OpenCode", "OpenCode.exe")];
26058
+ const localappdata = d.env.LOCALAPPDATA ?? join14(d.home, "AppData", "Local");
26059
+ return [join14(localappdata, "Programs", "OpenCode", "OpenCode.exe")];
25986
26060
  }
25987
26061
  default: {
25988
- const dataHome = d.env.XDG_DATA_HOME && d.env.XDG_DATA_HOME.length > 0 ? d.env.XDG_DATA_HOME : join13(d.home, ".local", "share");
25989
- return OPENCODE_DESKTOP_APP_IDS.map((appId) => join13(dataHome, "applications", `${appId}.desktop`));
26062
+ const dataHome = d.env.XDG_DATA_HOME && d.env.XDG_DATA_HOME.length > 0 ? d.env.XDG_DATA_HOME : join14(d.home, ".local", "share");
26063
+ return OPENCODE_DESKTOP_APP_IDS.map((appId) => join14(dataHome, "applications", `${appId}.desktop`));
25990
26064
  }
25991
26065
  }
25992
26066
  }
@@ -26013,7 +26087,7 @@ function detectOpenCodeInstallations(deps) {
26013
26087
  }
26014
26088
  }
26015
26089
  for (const appId of OPENCODE_DESKTOP_APP_IDS) {
26016
- const marker = join13(desktopUserDataDir(d, appId), OPENCODE_DESKTOP_SETTINGS_FILE);
26090
+ const marker = join14(desktopUserDataDir(d, appId), OPENCODE_DESKTOP_SETTINGS_FILE);
26017
26091
  if (d.exists(marker)) {
26018
26092
  addCandidate(installations, seenRealpaths, d, marker, "desktop", "desktop");
26019
26093
  }
@@ -26111,8 +26185,8 @@ var OPENCODE_BINARY_ENV = "MAGIC_CONTEXT_OPENCODE_BINARY", OPENCODE_VERSION_PROB
26111
26185
  var init_opencode_helpers = () => {};
26112
26186
 
26113
26187
  // src/adapters/opencode.ts
26114
- import { existsSync as existsSync17, readFileSync as readFileSync12, statSync as statSync10 } from "node:fs";
26115
- import { dirname as dirname10, isAbsolute as isAbsolute5, parse as parsePath, resolve as resolve6 } from "node:path";
26188
+ import { existsSync as existsSync16, readFileSync as readFileSync12, statSync as statSync10 } from "node:fs";
26189
+ import { dirname as dirname10, isAbsolute as isAbsolute6, parse as parsePath, resolve as resolve7 } from "node:path";
26116
26190
  import { fileURLToPath as fileURLToPath2 } from "node:url";
26117
26191
 
26118
26192
  class OpenCodeAdapter {
@@ -26304,31 +26378,36 @@ class OpenCodeAdapter {
26304
26378
  return "Install OpenCode: curl -fsSL https://opencode.ai/install | bash";
26305
26379
  }
26306
26380
  getPluginCacheInfo() {
26381
+ const cacheRoot = getOpenCodeCacheHome();
26307
26382
  const legacyPath = getOpenCodePluginCacheDir();
26308
- const legacyExists = existsSync17(legacyPath);
26383
+ const legacyCheck = checkCacheClearPath(cacheRoot, legacyPath);
26384
+ const legacyExists = legacyCheck.allowed || legacyCheck.reason !== "missing";
26309
26385
  const slot = getOpenCodeV2PluginCacheSlot();
26310
- const slotExists = existsSync17(slot);
26386
+ const slotCheck = checkCacheClearPath(cacheRoot, slot);
26387
+ const slotExists = slotCheck.allowed || slotCheck.reason !== "missing";
26311
26388
  const caches = [];
26312
26389
  if (legacyExists || !slotExists) {
26313
26390
  caches.push({
26314
26391
  path: legacyPath,
26392
+ cacheRoot,
26315
26393
  exists: legacyExists,
26316
- sizeBytes: dirSizeBytes(legacyPath),
26394
+ sizeBytes: legacyCheck.allowed ? dirSizeBytes(legacyCheck.path) : 0,
26317
26395
  label: "OpenCode 1 plugin packages"
26318
26396
  });
26319
26397
  }
26320
26398
  if (slotExists) {
26321
26399
  caches.push({
26322
26400
  path: slot,
26401
+ cacheRoot,
26323
26402
  exists: true,
26324
- sizeBytes: dirSizeBytes(slot),
26403
+ sizeBytes: slotCheck.allowed ? dirSizeBytes(slotCheck.path) : 0,
26325
26404
  label: "OpenCode 2 Magic Context @latest install",
26326
- clear: () => this.clearOpenCodeV2Slot(slot)
26405
+ clear: () => this.clearOpenCodeV2Slot(cacheRoot, slot)
26327
26406
  });
26328
26407
  }
26329
26408
  return caches;
26330
26409
  }
26331
- clearOpenCodeV2Slot(slot) {
26410
+ clearOpenCodeV2Slot(cacheRoot, slot) {
26332
26411
  let databases;
26333
26412
  try {
26334
26413
  databases = [
@@ -26340,7 +26419,7 @@ class OpenCodeAdapter {
26340
26419
  reason: `could not locate the OpenCode database to check whether OpenCode is running (${err instanceof Error ? err.message : String(err)})`
26341
26420
  };
26342
26421
  }
26343
- const removal = removeOpenCodeV2PluginCacheSlot(slot, openCodeHostDatabaseFiles(databases), {
26422
+ const removal = removeOpenCodeV2PluginCacheSlot(cacheRoot, slot, openCodeHostDatabaseFiles(databases), {
26344
26423
  probe: this.probeHostUse
26345
26424
  });
26346
26425
  switch (removal.action) {
@@ -26352,6 +26431,7 @@ class OpenCodeAdapter {
26352
26431
  reason: `OpenCode is running (pid ${removal.pids.join(", ")}); quit it (and \`opencode service stop\`) first`
26353
26432
  };
26354
26433
  case "in_use_unknown":
26434
+ case "skipped":
26355
26435
  return { cleared: false, reason: removal.reason };
26356
26436
  case "error":
26357
26437
  return { cleared: false, reason: removal.error };
@@ -26377,7 +26457,7 @@ class OpenCodeAdapter {
26377
26457
  return readOpenCodeV2CachedPluginVersion(slot) ?? null;
26378
26458
  }
26379
26459
  for (const candidate of getOpenCodePluginPackageJsonPaths()) {
26380
- if (!existsSync17(candidate))
26460
+ if (!existsSync16(candidate))
26381
26461
  continue;
26382
26462
  try {
26383
26463
  const raw = readFileSync12(candidate, "utf-8");
@@ -26405,7 +26485,7 @@ function isLocalPathPluginEntry(entry) {
26405
26485
  const candidate = pluginEntryPackage(entry);
26406
26486
  if (!candidate)
26407
26487
  return false;
26408
- return candidate.startsWith("file://") || isAbsolute5(candidate) || candidate.startsWith("./") || candidate.startsWith("../");
26488
+ return candidate.startsWith("file://") || isAbsolute6(candidate) || candidate.startsWith("./") || candidate.startsWith("../");
26409
26489
  }
26410
26490
  function isDevPathPluginEntry(entry, configDir) {
26411
26491
  const candidate = pluginEntryPackage(entry);
@@ -26416,14 +26496,14 @@ function isDevPathPluginEntry(entry, configDir) {
26416
26496
  if (candidate.startsWith("file://")) {
26417
26497
  localPath = fileURLToPath2(candidate);
26418
26498
  } else {
26419
- localPath = resolve6(configDir, candidate);
26499
+ localPath = resolve7(configDir, candidate);
26420
26500
  }
26421
26501
  if (statSync10(localPath).isFile())
26422
26502
  localPath = dirname10(localPath);
26423
26503
  const root = parsePath(localPath).root;
26424
26504
  while (localPath !== root) {
26425
- const packagePath = resolve6(localPath, "package.json");
26426
- if (existsSync17(packagePath)) {
26505
+ const packagePath = resolve7(localPath, "package.json");
26506
+ if (existsSync16(packagePath)) {
26427
26507
  const pkg = JSON.parse(readFileSync12(packagePath, "utf8"));
26428
26508
  return pkg.name === OPENCODE_PLUGIN_NAME;
26429
26509
  }
@@ -26444,7 +26524,7 @@ function matchesPluginEntry(entry, pkgName) {
26444
26524
  }
26445
26525
  function ensureDir2(filePath) {
26446
26526
  const dir = dirname10(filePath);
26447
- if (!existsSync17(dir)) {
26527
+ if (!existsSync16(dir)) {
26448
26528
  const { mkdirSync } = __require("node:fs");
26449
26529
  mkdirSync(dir, { recursive: true });
26450
26530
  }
@@ -26454,6 +26534,7 @@ var init_opencode = __esm(async () => {
26454
26534
  init_jsonc_edit();
26455
26535
  init_opencode_db_path();
26456
26536
  init_atomic_write();
26537
+ init_cache_clear_path();
26457
26538
  init_jsonc_config();
26458
26539
  init_opencode_detect();
26459
26540
  init_opencode_helpers();
@@ -26465,8 +26546,8 @@ var init_opencode = __esm(async () => {
26465
26546
  });
26466
26547
 
26467
26548
  // src/lib/pi-package-entry.ts
26468
- import { existsSync as existsSync18, readFileSync as readFileSync13 } from "node:fs";
26469
- import { isAbsolute as isAbsolute6, join as join14 } from "node:path";
26549
+ import { existsSync as existsSync17, readFileSync as readFileSync13 } from "node:fs";
26550
+ import { isAbsolute as isAbsolute7, join as join15 } from "node:path";
26470
26551
  function stripNpmPrefix(value) {
26471
26552
  return value.startsWith("npm:") ? value.slice("npm:".length) : value;
26472
26553
  }
@@ -26521,8 +26602,8 @@ function hasPiMagicContextPackage(entries, agentDir = getPiAgentConfigDir()) {
26521
26602
  return entries.some((entry) => isConfiguredPiMagicContextEntry(entry, agentDir));
26522
26603
  }
26523
26604
  function isPiMagicContextPackageDir(dir) {
26524
- const packageJson = join14(dir, "package.json");
26525
- if (!existsSync18(packageJson))
26605
+ const packageJson = join15(dir, "package.json");
26606
+ if (!existsSync17(packageJson))
26526
26607
  return false;
26527
26608
  try {
26528
26609
  const pkg = JSON.parse(readFileSync13(packageJson, "utf-8"));
@@ -26537,7 +26618,7 @@ function localPiMagicContextPackageDir(entry, agentDir) {
26537
26618
  if (!spec || spec.startsWith("npm:"))
26538
26619
  return null;
26539
26620
  const path = spec.startsWith("file:") ? spec.slice("file:".length) : spec;
26540
- const dir = isAbsolute6(path) ? path : join14(agentDir, path);
26621
+ const dir = isAbsolute7(path) ? path : join15(agentDir, path);
26541
26622
  return isPiMagicContextPackageDir(dir) ? dir : null;
26542
26623
  }
26543
26624
  function isConfiguredPiMagicContextEntry(entry, agentDir) {
@@ -26561,7 +26642,7 @@ var init_pi_package_entry = __esm(() => {
26561
26642
  });
26562
26643
 
26563
26644
  // src/adapters/pi.ts
26564
- import { existsSync as existsSync19 } from "node:fs";
26645
+ import { existsSync as existsSync18 } from "node:fs";
26565
26646
  import { dirname as dirname11 } from "node:path";
26566
26647
 
26567
26648
  class PiAdapter {
@@ -26700,7 +26781,7 @@ function writePiSettings(settings) {
26700
26781
  }
26701
26782
  function ensureDir3(filePath) {
26702
26783
  const dir = dirname11(filePath);
26703
- if (!existsSync19(dir)) {
26784
+ if (!existsSync18(dir)) {
26704
26785
  const { mkdirSync } = __require("node:fs");
26705
26786
  mkdirSync(dir, { recursive: true });
26706
26787
  }
@@ -29835,7 +29916,7 @@ var init_project_identity_cache = __esm(() => {
29835
29916
  });
29836
29917
 
29837
29918
  // ../plugin/src/features/magic-context/memory/unborn-head.ts
29838
- import { readFileSync as readFileSync15, realpathSync as realpathSync4, statSync as statSync11 } from "node:fs";
29919
+ import { readFileSync as readFileSync15, realpathSync as realpathSync5, statSync as statSync11 } from "node:fs";
29839
29920
  import path5 from "node:path";
29840
29921
  function errorCode(error) {
29841
29922
  if (error === null || typeof error !== "object" || !("code" in error))
@@ -29977,7 +30058,7 @@ function isUnbornHeadOnDisk(directory, env = process.env) {
29977
30058
  }
29978
30059
  let realDirectory;
29979
30060
  try {
29980
- realDirectory = realpathSync4.native(path5.resolve(directory));
30061
+ realDirectory = realpathSync5.native(path5.resolve(directory));
29981
30062
  } catch {
29982
30063
  return false;
29983
30064
  }
@@ -29996,7 +30077,7 @@ var init_unborn_head = __esm(() => {
29996
30077
  // ../plugin/src/features/magic-context/memory/project-identity.ts
29997
30078
  import { execFileSync as execFileSync4 } from "node:child_process";
29998
30079
  import { createHash as createHash5 } from "node:crypto";
29999
- import { existsSync as existsSync20, realpathSync as realpathSync5, statSync as statSync12 } from "node:fs";
30080
+ import { existsSync as existsSync19, realpathSync as realpathSync6, statSync as statSync12 } from "node:fs";
30000
30081
  import { homedir as homedir12 } from "node:os";
30001
30082
  import path6 from "node:path";
30002
30083
  function asError(error) {
@@ -30180,7 +30261,7 @@ function nearestLastKnownGitIdentity(canonical) {
30180
30261
  const cached = lastKnownGitIdentity(current);
30181
30262
  if (cached !== undefined)
30182
30263
  return { identity: cached, source: current };
30183
- if (existsSync20(path6.join(current, ".git")))
30264
+ if (existsSync19(path6.join(current, ".git")))
30184
30265
  break;
30185
30266
  const parent = path6.dirname(current);
30186
30267
  if (parent === current)
@@ -30193,7 +30274,7 @@ function nearestLastKnownGitIdentity(canonical) {
30193
30274
  if (exactOrAncestor)
30194
30275
  return exactOrAncestor;
30195
30276
  try {
30196
- const realCanonical = realpathSync5.native(canonical);
30277
+ const realCanonical = realpathSync6.native(canonical);
30197
30278
  if (realCanonical !== canonical)
30198
30279
  return walk(realCanonical);
30199
30280
  } catch {}
@@ -30223,7 +30304,7 @@ function recordDubiousOwnershipFallback(canonical) {
30223
30304
  function canonicalUserHomeDirectory() {
30224
30305
  const homeDirectory = userHomeDirectoryForIdentity();
30225
30306
  try {
30226
- return realpathSync5.native(homeDirectory);
30307
+ return realpathSync6.native(homeDirectory);
30227
30308
  } catch {
30228
30309
  return homeDirectory;
30229
30310
  }
@@ -30232,7 +30313,7 @@ function isUserHomeDirectory(directory) {
30232
30313
  if (projectDirectoryKey(directory) === projectDirectoryKey(userHomeDirectoryForIdentity()))
30233
30314
  return true;
30234
30315
  try {
30235
- return projectDirectoryKey(realpathSync5.native(path6.resolve(directory))) === projectDirectoryKey(canonicalUserHomeDirectory());
30316
+ return projectDirectoryKey(realpathSync6.native(path6.resolve(directory))) === projectDirectoryKey(canonicalUserHomeDirectory());
30236
30317
  } catch {
30237
30318
  return false;
30238
30319
  }
@@ -30294,7 +30375,7 @@ function hasGitDir(canonical) {
30294
30375
  return true;
30295
30376
  }
30296
30377
  try {
30297
- const realCanonical = realpathSync5.native(canonical);
30378
+ const realCanonical = realpathSync6.native(canonical);
30298
30379
  return realCanonical !== canonical && hasGitDirInAncestorChain(realCanonical);
30299
30380
  } catch {
30300
30381
  return false;
@@ -30303,9 +30384,9 @@ function hasGitDir(canonical) {
30303
30384
  function gitRootInAncestorChain(startDirectory) {
30304
30385
  let current = startDirectory;
30305
30386
  while (true) {
30306
- if (existsSync20(path6.join(current, ".git"))) {
30387
+ if (existsSync19(path6.join(current, ".git"))) {
30307
30388
  try {
30308
- return realpathSync5.native(current);
30389
+ return realpathSync6.native(current);
30309
30390
  } catch {
30310
30391
  return path6.resolve(current);
30311
30392
  }
@@ -30325,7 +30406,7 @@ function gitRootDirectory(canonical) {
30325
30406
  if (direct)
30326
30407
  return direct;
30327
30408
  try {
30328
- const realCanonical = realpathSync5.native(canonical);
30409
+ const realCanonical = realpathSync6.native(canonical);
30329
30410
  return realCanonical === canonical ? null : gitRootInAncestorChain(realCanonical);
30330
30411
  } catch {
30331
30412
  return null;
@@ -33775,7 +33856,7 @@ var init_tool_definition_tokens = __esm(() => {
33775
33856
  });
33776
33857
 
33777
33858
  // ../plugin/src/features/magic-context/tool-owner-backfill.ts
33778
- import { existsSync as existsSync21 } from "node:fs";
33859
+ import { existsSync as existsSync20 } from "node:fs";
33779
33860
  function resolveOpencodeDbPath() {
33780
33861
  return resolveOpenCodeDbPath().path;
33781
33862
  }
@@ -33812,7 +33893,7 @@ function runToolOwnerBackfill(db) {
33812
33893
  return result;
33813
33894
  }
33814
33895
  const opencodeDbPath = resolveOpencodeDbPath();
33815
- if (!existsSync21(opencodeDbPath)) {
33896
+ if (!existsSync20(opencodeDbPath)) {
33816
33897
  log(`[backfill] OpenCode DB not found at ${opencodeDbPath} — marking all unbackfilled sessions as skipped. Lazy adoption (defense-in-depth) handles legacy rows at runtime.`);
33817
33898
  markAllUnbackfilledSessionsSkipped(db);
33818
33899
  result.sessionsSkippedNoOcDb = countSessionsByStatus(db, "skipped");
@@ -36768,14 +36849,14 @@ var init_message_time_backfill = __esm(async () => {
36768
36849
 
36769
36850
  // ../plugin/src/features/magic-context/storage-db.ts
36770
36851
  import {
36771
- existsSync as existsSync22,
36852
+ existsSync as existsSync21,
36772
36853
  readdirSync as readdirSync5,
36773
36854
  readFileSync as readFileSync16,
36774
36855
  rmdirSync,
36775
36856
  statSync as statSync13,
36776
36857
  unlinkSync as unlinkSync4
36777
36858
  } from "node:fs";
36778
- import { basename as basename4, dirname as dirname12, join as join15, resolve as resolve7 } from "node:path";
36859
+ import { basename as basename4, dirname as dirname12, join as join16, resolve as resolve8 } from "node:path";
36779
36860
  function ensureSecureStorageDir(dir) {
36780
36861
  ensureStorageDirectorySync(dir);
36781
36862
  }
@@ -36799,14 +36880,14 @@ function resolveDatabasePath(dbPathOverride) {
36799
36880
  return { dbDir: dirname12(dbPathOverride), dbPath: dbPathOverride };
36800
36881
  }
36801
36882
  const dbDir = getMagicContextStorageDir();
36802
- return { dbDir, dbPath: join15(dbDir, "context.db") };
36883
+ return { dbDir, dbPath: join16(dbDir, "context.db") };
36803
36884
  }
36804
36885
  function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
36805
- if (existsSync22(targetDbPath))
36886
+ if (existsSync21(targetDbPath))
36806
36887
  return;
36807
36888
  const legacyDir = getLegacyOpenCodeMagicContextStorageDir();
36808
- const legacyDbPath = join15(legacyDir, "context.db");
36809
- if (!existsSync22(legacyDbPath))
36889
+ const legacyDbPath = join16(legacyDir, "context.db");
36890
+ if (!existsSync21(legacyDbPath))
36810
36891
  return;
36811
36892
  log(`[magic-context] migrating legacy plugin storage: ${legacyDir} -> ${targetDbDir} (legacy left in place as backup)`);
36812
36893
  ensureSecureStorageDir(targetDbDir);
@@ -36823,8 +36904,8 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
36823
36904
  }
36824
36905
  for (const suffix of ["", "-wal", "-shm"]) {
36825
36906
  const src = `${legacyDbPath}${suffix}`;
36826
- const dst = join15(targetDbDir, `context.db${suffix}`);
36827
- if (existsSync22(src)) {
36907
+ const dst = join16(targetDbDir, `context.db${suffix}`);
36908
+ if (existsSync21(src)) {
36828
36909
  try {
36829
36910
  copyStorageFileSync(src, dst);
36830
36911
  } catch (error) {
@@ -36832,9 +36913,9 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
36832
36913
  }
36833
36914
  }
36834
36915
  }
36835
- const legacyModelsDir = join15(legacyDir, "models");
36836
- const targetModelsDir = join15(targetDbDir, "models");
36837
- if (existsSync22(legacyModelsDir) && !existsSync22(targetModelsDir)) {
36916
+ const legacyModelsDir = join16(legacyDir, "models");
36917
+ const targetModelsDir = join16(targetDbDir, "models");
36918
+ if (existsSync21(legacyModelsDir) && !existsSync21(targetModelsDir)) {
36838
36919
  try {
36839
36920
  copyStorageTreeSync(legacyModelsDir, targetModelsDir);
36840
36921
  } catch (error) {
@@ -36942,7 +37023,7 @@ function classifyJunkDiscovery(portFile, raw, staleFiles) {
36942
37023
  function inspectRpcServerDiscovery(storageDir, processes, options) {
36943
37024
  const deadline = options?.deadlineMs === undefined ? Number.POSITIVE_INFINITY : Date.now() + options.deadlineMs;
36944
37025
  let progressAt = Date.now() + 3000;
36945
- const rpcRoot = join15(storageDir, "rpc");
37026
+ const rpcRoot = join16(storageDir, "rpc");
36946
37027
  let projectEntries;
36947
37028
  try {
36948
37029
  projectEntries = rpcDiscoveryFs.readdirSync(rpcRoot, { withFileTypes: true });
@@ -36956,7 +37037,7 @@ function inspectRpcServerDiscovery(storageDir, processes, options) {
36956
37037
  for (const projectEntry of projectEntries) {
36957
37038
  if (!projectEntry.isDirectory())
36958
37039
  continue;
36959
- const projectDir = join15(rpcRoot, projectEntry.name);
37040
+ const projectDir = join16(rpcRoot, projectEntry.name);
36960
37041
  let entries;
36961
37042
  try {
36962
37043
  entries = rpcDiscoveryFs.readdirSync(projectDir);
@@ -36967,7 +37048,7 @@ function inspectRpcServerDiscovery(storageDir, processes, options) {
36967
37048
  }
36968
37049
  for (const entry of entries) {
36969
37050
  if (entry === "port" || entry.startsWith("port-") && entry.endsWith(".json")) {
36970
- portFiles.push(join15(projectDir, entry));
37051
+ portFiles.push(join16(projectDir, entry));
36971
37052
  }
36972
37053
  }
36973
37054
  }
@@ -37070,7 +37151,7 @@ function inspectRpcServerDiscovery(storageDir, processes, options) {
37070
37151
  return { state: "stale", serverPids: [], staleFiles };
37071
37152
  }
37072
37153
  function pruneEmptyRpcDiscoveryDirs(storageDir) {
37073
- const rpcRoot = join15(storageDir, "rpc");
37154
+ const rpcRoot = join16(storageDir, "rpc");
37074
37155
  let entries;
37075
37156
  try {
37076
37157
  entries = rpcDiscoveryFs.readdirSync(rpcRoot, { withFileTypes: true });
@@ -37082,7 +37163,7 @@ function pruneEmptyRpcDiscoveryDirs(storageDir) {
37082
37163
  for (const entry of entries) {
37083
37164
  if (!entry.isDirectory())
37084
37165
  continue;
37085
- const projectDir = join15(rpcRoot, entry.name);
37166
+ const projectDir = join16(rpcRoot, entry.name);
37086
37167
  try {
37087
37168
  if (rpcDiscoveryFs.readdirSync(projectDir).length > 0)
37088
37169
  continue;
@@ -37096,11 +37177,11 @@ function pruneEmptyRpcDiscoveryDirs(storageDir) {
37096
37177
  return removed;
37097
37178
  }
37098
37179
  function removeRpcDiscoveryRecords(storageDir, files) {
37099
- const rpcRoot = resolve7(join15(storageDir, "rpc"));
37180
+ const rpcRoot = resolve8(join16(storageDir, "rpc"));
37100
37181
  const removed = [];
37101
37182
  const failed = [];
37102
37183
  for (const file of files) {
37103
- const projectDir = dirname12(resolve7(file));
37184
+ const projectDir = dirname12(resolve8(file));
37104
37185
  if (dirname12(projectDir) !== rpcRoot || !basename4(file).startsWith("port")) {
37105
37186
  failed.push({ file, error: "not an RPC discovery record" });
37106
37187
  continue;
@@ -37148,7 +37229,7 @@ function isDefaultSharedDatabasePath(dbPath) {
37148
37229
  if (!process.env.XDG_DATA_HOME && (process.env.MAGIC_CONTEXT_TEST_DATA_DIR || false)) {
37149
37230
  return false;
37150
37231
  }
37151
- return resolve7(dbPath) === resolve7(join15(getMagicContextStorageDir(), "context.db"));
37232
+ return resolve8(dbPath) === resolve8(join16(getMagicContextStorageDir(), "context.db"));
37152
37233
  }
37153
37234
  function migrationBlockingPiPids(dbPath, discovery, discoveredPiPids) {
37154
37235
  if (isDefaultSharedDatabasePath(dbPath))
@@ -38565,7 +38646,7 @@ function openDatabase(dbPathOrOptions) {
38565
38646
  }
38566
38647
  ensureSecureStorageDir(dbDir);
38567
38648
  tightenStorageTree(dbDir);
38568
- if (!existsSync22(dbPath) && shouldEnforcePrivateStoragePermissions()) {
38649
+ if (!existsSync21(dbPath) && shouldEnforcePrivateStoragePermissions()) {
38569
38650
  try {
38570
38651
  writeStorageFileSync(dbPath, new Uint8Array, { flag: "wx" });
38571
38652
  } catch (error) {
@@ -38682,18 +38763,18 @@ var init_storage_db = __esm(async () => {
38682
38763
  });
38683
38764
 
38684
38765
  // src/lib/database-access.ts
38685
- import { existsSync as existsSync23, rmSync as rmSync6 } from "node:fs";
38766
+ import { existsSync as existsSync22, rmSync as rmSync6 } from "node:fs";
38686
38767
  import { basename as basename5, dirname as dirname13 } from "node:path";
38687
38768
  import { pathToFileURL as pathToFileURL2 } from "node:url";
38688
38769
  function getPersistedSchemaVersion2(db) {
38689
38770
  return getPersistedSchemaVersion(db);
38690
38771
  }
38691
38772
  function openExistingDatabase(path, options) {
38692
- if (!existsSync23(path))
38773
+ if (!existsSync22(path))
38693
38774
  return null;
38694
38775
  if (options.readonly) {
38695
38776
  const name = basename5(path);
38696
- if ((name === "context.db" || name === "store.db") && !existsSync23(`${path}-wal`) && !existsSync23(`${path}-shm`)) {
38777
+ if ((name === "context.db" || name === "store.db") && !existsSync22(`${path}-wal`) && !existsSync22(`${path}-shm`)) {
38697
38778
  const probe = probeHostProcessesUsing({
38698
38779
  files: [path, `${path}-wal`, `${path}-shm`],
38699
38780
  directories: []
@@ -38759,7 +38840,7 @@ async function backupDatabaseSnapshot(db, sourcePath, destination) {
38759
38840
  if (typeof sqlite.backup !== "function") {
38760
38841
  throw new Error("The active SQLite runtime does not provide a snapshot backup API");
38761
38842
  }
38762
- if (existsSync23(destination)) {
38843
+ if (existsSync22(destination)) {
38763
38844
  throw new Error(`Refusing to overwrite existing backup ${destination}`);
38764
38845
  }
38765
38846
  const reader = openExistingDatabase(sourcePath, { readonly: true });
@@ -39060,10 +39141,10 @@ var init_dreamer_setup = __esm(() => {
39060
39141
  });
39061
39142
 
39062
39143
  // src/commands/setup-pi.ts
39063
- import { existsSync as existsSync24, mkdirSync as mkdirSync6 } from "node:fs";
39144
+ import { existsSync as existsSync23, mkdirSync as mkdirSync6 } from "node:fs";
39064
39145
  import { dirname as dirname14 } from "node:path";
39065
39146
  function ensureDir4(path) {
39066
- if (!existsSync24(path))
39147
+ if (!existsSync23(path))
39067
39148
  mkdirSync6(path, { recursive: true });
39068
39149
  }
39069
39150
  async function getDefaultPrompts() {
@@ -39519,19 +39600,19 @@ var init_setup_omp = __esm(() => {
39519
39600
 
39520
39601
  // ../plugin/src/shared/opencode-config-dir.ts
39521
39602
  import { homedir as homedir13 } from "node:os";
39522
- import { join as join16, resolve as resolve8 } from "node:path";
39603
+ import { join as join17, resolve as resolve9 } from "node:path";
39523
39604
  function resolveHomeDir() {
39524
39605
  return process.env.HOME?.trim() || homedir13();
39525
39606
  }
39526
39607
  function getOpenCodeGlobalConfigDir() {
39527
39608
  if (process.platform === "win32") {
39528
- return join16(resolveHomeDir(), ".config", "opencode");
39609
+ return join17(resolveHomeDir(), ".config", "opencode");
39529
39610
  }
39530
- return join16(process.env.XDG_CONFIG_HOME || join16(resolveHomeDir(), ".config"), "opencode");
39611
+ return join17(process.env.XDG_CONFIG_HOME || join17(resolveHomeDir(), ".config"), "opencode");
39531
39612
  }
39532
39613
  function getEnvConfigDir() {
39533
39614
  const envConfigDir = process.env.OPENCODE_CONFIG_DIR?.trim();
39534
- return envConfigDir ? resolve8(envConfigDir) : undefined;
39615
+ return envConfigDir ? resolve9(envConfigDir) : undefined;
39535
39616
  }
39536
39617
  function getCliConfigDir() {
39537
39618
  return getEnvConfigDir() ?? getOpenCodeGlobalConfigDir();
@@ -39543,14 +39624,14 @@ function getOpenCodeConfigPaths(options) {
39543
39624
  const configDir = getOpenCodeConfigDir2(options);
39544
39625
  return {
39545
39626
  configDir,
39546
- configJson: join16(configDir, "opencode.json"),
39547
- configJsonc: join16(configDir, "opencode.jsonc"),
39548
- packageJson: join16(configDir, "package.json"),
39549
- omoConfig: join16(configDir, "magic-context.jsonc")
39627
+ configJson: join17(configDir, "opencode.json"),
39628
+ configJsonc: join17(configDir, "opencode.jsonc"),
39629
+ packageJson: join17(configDir, "package.json"),
39630
+ omoConfig: join17(configDir, "magic-context.jsonc")
39550
39631
  };
39551
39632
  }
39552
39633
  function getOpenCodeConfigDirs() {
39553
- const dirs = [getOpenCodeGlobalConfigDir(), join16(resolveHomeDir(), ".opencode")];
39634
+ const dirs = [getOpenCodeGlobalConfigDir(), join17(resolveHomeDir(), ".opencode")];
39554
39635
  const envDir = getEnvConfigDir();
39555
39636
  if (envDir)
39556
39637
  dirs.push(envDir);
@@ -39560,7 +39641,7 @@ var init_opencode_config_dir = () => {};
39560
39641
 
39561
39642
  // ../plugin/src/shared/conflict-detector.ts
39562
39643
  import { homedir as homedir14 } from "node:os";
39563
- import { join as join17 } from "node:path";
39644
+ import { join as join18 } from "node:path";
39564
39645
  function detectConflicts(directory, options) {
39565
39646
  const compactionEnabled = options?.compactionEnabled ?? true;
39566
39647
  const hostGeneration = options?.hostGeneration ?? "v1";
@@ -39627,19 +39708,19 @@ function checkCompaction(directory, hostGeneration) {
39627
39708
  function openCodeConfigFileChain(directory, hostGeneration) {
39628
39709
  const globalDir = getOpenCodeGlobalConfigDir();
39629
39710
  const wellKnown = [
39630
- join17(globalDir, "config.json"),
39631
- join17(globalDir, "opencode.json"),
39632
- join17(globalDir, "opencode.jsonc")
39711
+ join18(globalDir, "config.json"),
39712
+ join18(globalDir, "opencode.json"),
39713
+ join18(globalDir, "opencode.jsonc")
39633
39714
  ];
39634
- const globalSupplementary = getOpenCodeConfigDirs().filter((dir) => dir !== globalDir).flatMap((dir) => [join17(dir, "opencode.json"), join17(dir, "opencode.jsonc")]);
39715
+ const globalSupplementary = getOpenCodeConfigDirs().filter((dir) => dir !== globalDir).flatMap((dir) => [join18(dir, "opencode.json"), join18(dir, "opencode.jsonc")]);
39635
39716
  const explicitConfig = process.env.OPENCODE_CONFIG?.trim();
39636
39717
  const explicit = explicitConfig ? [explicitConfig] : [];
39637
39718
  const disableProjectConfig = process.env.OPENCODE_DISABLE_PROJECT_CONFIG?.toLowerCase();
39638
39719
  const skipProject = hostGeneration === "v1" && (disableProjectConfig === "true" || disableProjectConfig === "1");
39639
- const direct = skipProject ? [] : [join17(directory, "opencode.json"), join17(directory, "opencode.jsonc")];
39720
+ const direct = skipProject ? [] : [join18(directory, "opencode.json"), join18(directory, "opencode.jsonc")];
39640
39721
  const projectSupplementary = skipProject ? [] : [
39641
- join17(directory, ".opencode", "opencode.json"),
39642
- join17(directory, ".opencode", "opencode.jsonc")
39722
+ join18(directory, ".opencode", "opencode.json"),
39723
+ join18(directory, ".opencode", "opencode.jsonc")
39643
39724
  ];
39644
39725
  const files = hostGeneration === "v2" ? [
39645
39726
  ...wellKnown,
@@ -39726,10 +39807,10 @@ function collectPluginEntries(directory) {
39726
39807
  }
39727
39808
  };
39728
39809
  for (const configPath of [
39729
- join17(directory, ".opencode", "opencode.jsonc"),
39730
- join17(directory, ".opencode", "opencode.json"),
39731
- join17(directory, "opencode.jsonc"),
39732
- join17(directory, "opencode.json")
39810
+ join18(directory, ".opencode", "opencode.jsonc"),
39811
+ join18(directory, ".opencode", "opencode.json"),
39812
+ join18(directory, "opencode.jsonc"),
39813
+ join18(directory, "opencode.json")
39733
39814
  ]) {
39734
39815
  const config = readJsoncFile(configPath);
39735
39816
  pushFrom(config?.plugin);
@@ -39739,7 +39820,7 @@ function collectPluginEntries(directory) {
39739
39820
  for (const dir of getOpenCodeConfigDirs()) {
39740
39821
  const names = dir === globalDir ? ["config.json", "opencode.json", "opencode.jsonc"] : ["opencode.json", "opencode.jsonc"];
39741
39822
  for (const name of names) {
39742
- const config = readJsoncFile(join17(dir, name));
39823
+ const config = readJsoncFile(join18(dir, name));
39743
39824
  pushFrom(config?.plugin);
39744
39825
  }
39745
39826
  }
@@ -39773,7 +39854,7 @@ function readOmoDisabledHooks(directory) {
39773
39854
  try {
39774
39855
  for (const dir of getOpenCodeConfigDirs()) {
39775
39856
  for (const name of configNames) {
39776
- const config = readJsoncFile(join17(dir, name));
39857
+ const config = readJsoncFile(join18(dir, name));
39777
39858
  if (config?.disabled_hooks) {
39778
39859
  for (const hook of config.disabled_hooks) {
39779
39860
  disabled.add(hook);
@@ -39783,7 +39864,7 @@ function readOmoDisabledHooks(directory) {
39783
39864
  }
39784
39865
  } catch {}
39785
39866
  for (const name of configNames) {
39786
- const config = readJsoncFile(join17(directory, name));
39867
+ const config = readJsoncFile(join18(directory, name));
39787
39868
  if (config?.disabled_hooks) {
39788
39869
  for (const hook of config.disabled_hooks) {
39789
39870
  disabled.add(hook);
@@ -39791,9 +39872,9 @@ function readOmoDisabledHooks(directory) {
39791
39872
  }
39792
39873
  }
39793
39874
  const homeDir = process.env.HOME || homedir14();
39794
- const omoHomeDir = join17(homeDir, ".omo");
39875
+ const omoHomeDir = join18(homeDir, ".omo");
39795
39876
  for (const name of ["omo.jsonc", "omo.json"]) {
39796
- const config = readJsoncFile(join17(omoHomeDir, name));
39877
+ const config = readJsoncFile(join18(omoHomeDir, name));
39797
39878
  if (config?.["[opencode]"]?.disabled_hooks) {
39798
39879
  for (const hook of config["[opencode]"].disabled_hooks) {
39799
39880
  disabled.add(hook);
@@ -39801,7 +39882,7 @@ function readOmoDisabledHooks(directory) {
39801
39882
  }
39802
39883
  }
39803
39884
  for (const name of ["omo.jsonc", "omo.json"]) {
39804
- const config = readJsoncFile(join17(directory, ".omo", name));
39885
+ const config = readJsoncFile(join18(directory, ".omo", name));
39805
39886
  if (config?.["[opencode]"]?.disabled_hooks) {
39806
39887
  for (const hook of config["[opencode]"].disabled_hooks) {
39807
39888
  disabled.add(hook);
@@ -39820,9 +39901,9 @@ var init_conflict_detector = __esm(() => {
39820
39901
  });
39821
39902
 
39822
39903
  // ../plugin/src/shared/conflict-fixer.ts
39823
- import { existsSync as existsSync25, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "node:fs";
39904
+ import { existsSync as existsSync24, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "node:fs";
39824
39905
  import { homedir as homedir15 } from "node:os";
39825
- import { join as join18 } from "node:path";
39906
+ import { join as join19 } from "node:path";
39826
39907
  function isRecord3(value) {
39827
39908
  return typeof value === "object" && value !== null && !Array.isArray(value);
39828
39909
  }
@@ -39830,7 +39911,7 @@ function asStringArray(value) {
39830
39911
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
39831
39912
  }
39832
39913
  function readConfig(filePath) {
39833
- if (!existsSync25(filePath)) {
39914
+ if (!existsSync24(filePath)) {
39834
39915
  return null;
39835
39916
  }
39836
39917
  try {
@@ -39846,23 +39927,23 @@ function writeConfig(filePath, text) {
39846
39927
  }
39847
39928
  function resolveUserOpenCodeConfigPath() {
39848
39929
  const paths = getOpenCodeConfigPaths({ binary: "opencode" });
39849
- if (existsSync25(paths.configJsonc))
39930
+ if (existsSync24(paths.configJsonc))
39850
39931
  return paths.configJsonc;
39851
39932
  return paths.configJson;
39852
39933
  }
39853
39934
  function collectOpenCodeConfigPaths(directory) {
39854
39935
  const paths = new Set;
39855
39936
  const userConfig = resolveUserOpenCodeConfigPath();
39856
- if (existsSync25(userConfig)) {
39937
+ if (existsSync24(userConfig)) {
39857
39938
  paths.add(userConfig);
39858
39939
  }
39859
39940
  for (const filePath of [
39860
- join18(directory, ".opencode", "opencode.jsonc"),
39861
- join18(directory, ".opencode", "opencode.json"),
39862
- join18(directory, "opencode.jsonc"),
39863
- join18(directory, "opencode.json")
39941
+ join19(directory, ".opencode", "opencode.jsonc"),
39942
+ join19(directory, ".opencode", "opencode.json"),
39943
+ join19(directory, "opencode.jsonc"),
39944
+ join19(directory, "opencode.json")
39864
39945
  ]) {
39865
- if (existsSync25(filePath)) {
39946
+ if (existsSync24(filePath)) {
39866
39947
  paths.add(filePath);
39867
39948
  }
39868
39949
  }
@@ -39872,26 +39953,26 @@ function collectOmoConfigPaths(directory) {
39872
39953
  const paths = new Set;
39873
39954
  const configDir = getOpenCodeConfigPaths({ binary: "opencode" }).configDir;
39874
39955
  for (const fileName of OMO_CONFIG_NAMES) {
39875
- const userPath = join18(configDir, fileName);
39876
- const projectPath = join18(directory, fileName);
39877
- if (existsSync25(userPath)) {
39956
+ const userPath = join19(configDir, fileName);
39957
+ const projectPath = join19(directory, fileName);
39958
+ if (existsSync24(userPath)) {
39878
39959
  paths.add(userPath);
39879
39960
  }
39880
- if (existsSync25(projectPath)) {
39961
+ if (existsSync24(projectPath)) {
39881
39962
  paths.add(projectPath);
39882
39963
  }
39883
39964
  }
39884
39965
  const homeDir = process.env.HOME || homedir15();
39885
- const omoHomeDir = join18(homeDir, ".omo");
39966
+ const omoHomeDir = join19(homeDir, ".omo");
39886
39967
  for (const name of OMO_UNIFIED_NAMES) {
39887
- const userPath = join18(omoHomeDir, name);
39888
- if (existsSync25(userPath)) {
39968
+ const userPath = join19(omoHomeDir, name);
39969
+ if (existsSync24(userPath)) {
39889
39970
  paths.add(userPath);
39890
39971
  }
39891
39972
  }
39892
39973
  for (const name of OMO_UNIFIED_NAMES) {
39893
- const projectPath = join18(directory, ".omo", name);
39894
- if (existsSync25(projectPath)) {
39974
+ const projectPath = join19(directory, ".omo", name);
39975
+ if (existsSync24(projectPath)) {
39895
39976
  paths.add(projectPath);
39896
39977
  }
39897
39978
  }
@@ -40019,7 +40100,7 @@ var init_conflict_fixer = __esm(() => {
40019
40100
  });
40020
40101
 
40021
40102
  // src/commands/setup-opencode.ts
40022
- import { existsSync as existsSync26 } from "node:fs";
40103
+ import { existsSync as existsSync25 } from "node:fs";
40023
40104
  import { basename as basename6, dirname as dirname15 } from "node:path";
40024
40105
  function resolveCompactionEnabledForWriter() {
40025
40106
  try {
@@ -40035,7 +40116,7 @@ function isPlainObject5(value) {
40035
40116
  }
40036
40117
  function planOpenCodeConfigUpdate(configPath, removeDcp = false, compactionEnabled = true, hostGeneration = "v1") {
40037
40118
  const registrationKey = pluginConfigKeyFor(hostGeneration);
40038
- const existsAtCommit = existsSync26(configPath);
40119
+ const existsAtCommit = existsSync25(configPath);
40039
40120
  const existing = existsAtCommit ? readJsoncConfigForUpdate(configPath) : {};
40040
40121
  if (!existsAtCommit) {
40041
40122
  const created = { [registrationKey]: [OPENCODE_PLUGIN_ENTRY_WITH_VERSION] };
@@ -40091,7 +40172,7 @@ function planOpenCodeConfigUpdate(configPath, removeDcp = false, compactionEnabl
40091
40172
  return changed ? document.bom + text : null;
40092
40173
  }
40093
40174
  function planTuiConfigUpdate(configPath) {
40094
- const existsAtCommit = existsSync26(configPath);
40175
+ const existsAtCommit = existsSync25(configPath);
40095
40176
  const existing = existsAtCommit ? readJsoncConfigForUpdate(configPath) : {};
40096
40177
  if (!existsAtCommit) {
40097
40178
  return `${import_comment_json6.stringify({ plugin: [OPENCODE_PLUGIN_ENTRY_WITH_VERSION] }, null, 2)}
@@ -40218,7 +40299,7 @@ async function runSetup3(dryRun = false) {
40218
40299
  log3.warn("You can configure models manually in magic-context.jsonc later");
40219
40300
  }
40220
40301
  const paths = detectConfigPaths();
40221
- const hadExistingSetup = paths.opencodeConfigFormat !== "none" || existsSync26(paths.magicContextConfig) || paths.tuiConfigFormat !== "none";
40302
+ const hadExistingSetup = paths.opencodeConfigFormat !== "none" || existsSync25(paths.magicContextConfig) || paths.tuiConfigFormat !== "none";
40222
40303
  if (!dryRun) {
40223
40304
  try {
40224
40305
  assertJsoncConfigsParseable([
@@ -40504,8 +40585,8 @@ var init_setup = __esm(async () => {
40504
40585
  });
40505
40586
 
40506
40587
  // src/lib/disk-space.ts
40507
- import { existsSync as existsSync27, statfsSync, statSync as statSync14 } from "node:fs";
40508
- import { dirname as dirname16, resolve as resolve9 } from "node:path";
40588
+ import { existsSync as existsSync26, statfsSync, statSync as statSync14 } from "node:fs";
40589
+ import { dirname as dirname16, resolve as resolve10 } from "node:path";
40509
40590
  function availableDiskBytes(path) {
40510
40591
  const filesystem = statfsSync(path);
40511
40592
  return filesystem.bavail * filesystem.bsize;
@@ -40520,9 +40601,9 @@ function checkDiskSpace(path, bytes, freeBytes) {
40520
40601
  };
40521
40602
  }
40522
40603
  function existingDirectoryAncestor(path) {
40523
- let current = resolve9(path);
40604
+ let current = resolve10(path);
40524
40605
  for (;; ) {
40525
- if (existsSync27(current) && statSync14(current).isDirectory())
40606
+ if (existsSync26(current) && statSync14(current).isDirectory())
40526
40607
  return current;
40527
40608
  const parent = dirname16(current);
40528
40609
  if (parent === current)
@@ -40534,24 +40615,24 @@ var init_disk_space = () => {};
40534
40615
 
40535
40616
  // ../plugin/src/hooks/auto-update-checker/constants.ts
40536
40617
  import { homedir as homedir16, platform } from "node:os";
40537
- import { join as join19 } from "node:path";
40618
+ import { join as join20 } from "node:path";
40538
40619
  function getOpenCodeCacheRoot() {
40539
40620
  if (platform() === "win32") {
40540
- return join19(process.env.LOCALAPPDATA ?? homedir16(), "opencode");
40621
+ return join20(process.env.LOCALAPPDATA ?? homedir16(), "opencode");
40541
40622
  }
40542
- return join19(homedir16(), ".cache", "opencode");
40623
+ return join20(homedir16(), ".cache", "opencode");
40543
40624
  }
40544
40625
  function getOpenCodeConfigRoot() {
40545
40626
  if (platform() === "win32") {
40546
- return join19(process.env.APPDATA ?? join19(homedir16(), "AppData", "Roaming"), "opencode");
40627
+ return join20(process.env.APPDATA ?? join20(homedir16(), "AppData", "Roaming"), "opencode");
40547
40628
  }
40548
- return join19(process.env.XDG_CONFIG_HOME ?? join19(homedir16(), ".config"), "opencode");
40629
+ return join20(process.env.XDG_CONFIG_HOME ?? join20(homedir16(), ".config"), "opencode");
40549
40630
  }
40550
40631
  var PACKAGE_NAME = "@cortexkit/opencode-magic-context", CACHE_DIR, USER_OPENCODE_CONFIG, USER_OPENCODE_CONFIG_JSONC;
40551
40632
  var init_constants2 = __esm(() => {
40552
- CACHE_DIR = join19(getOpenCodeCacheRoot(), "packages");
40553
- USER_OPENCODE_CONFIG = join19(getOpenCodeConfigRoot(), "opencode.json");
40554
- USER_OPENCODE_CONFIG_JSONC = join19(getOpenCodeConfigRoot(), "opencode.jsonc");
40633
+ CACHE_DIR = join20(getOpenCodeCacheRoot(), "packages");
40634
+ USER_OPENCODE_CONFIG = join20(getOpenCodeConfigRoot(), "opencode.json");
40635
+ USER_OPENCODE_CONFIG_JSONC = join20(getOpenCodeConfigRoot(), "opencode.jsonc");
40555
40636
  });
40556
40637
 
40557
40638
  // ../plugin/src/hooks/auto-update-checker/types.ts
@@ -40575,14 +40656,14 @@ var init_types = __esm(() => {
40575
40656
  // ../plugin/src/hooks/auto-update-checker/checker.ts
40576
40657
  import {
40577
40658
  accessSync as accessSync3,
40578
- existsSync as existsSync28,
40659
+ existsSync as existsSync27,
40579
40660
  constants as fsConstants,
40580
40661
  readFileSync as readFileSync18,
40581
40662
  renameSync as renameSync5,
40582
40663
  statSync as statSync15,
40583
40664
  writeFileSync as writeFileSync7
40584
40665
  } from "node:fs";
40585
- import { dirname as dirname17, isAbsolute as isAbsolute7, join as join20, resolve as resolve10 } from "node:path";
40666
+ import { dirname as dirname17, isAbsolute as isAbsolute8, join as join21, resolve as resolve11 } from "node:path";
40586
40667
  function warn(message) {
40587
40668
  log(`WARN: ${message}`);
40588
40669
  }
@@ -40612,13 +40693,13 @@ function getSurfaceConfigPaths(directory, surface) {
40612
40693
  const dirs = [
40613
40694
  globalDir,
40614
40695
  directory,
40615
- join20(directory, ".opencode"),
40696
+ join21(directory, ".opencode"),
40616
40697
  process.env.OPENCODE_CONFIG_DIR
40617
40698
  ].filter((value) => Boolean(value));
40618
40699
  const paths = [];
40619
40700
  for (const dir of dirs) {
40620
40701
  for (const extension of ["json", "jsonc"]) {
40621
- const path = join20(dir, `${name}.${extension}`);
40702
+ const path = join21(dir, `${name}.${extension}`);
40622
40703
  if (!paths.includes(path))
40623
40704
  paths.push(path);
40624
40705
  }
@@ -40629,7 +40710,7 @@ function getWinningConfig(directory, surface) {
40629
40710
  let winner = null;
40630
40711
  for (const path of getSurfaceConfigPaths(directory, surface)) {
40631
40712
  try {
40632
- if (!existsSync28(path))
40713
+ if (!existsSync27(path))
40633
40714
  continue;
40634
40715
  const parsed = parseJsonConfig(readFileSync18(path, "utf-8"));
40635
40716
  const entries = getPluginEntries(parsed);
@@ -40668,12 +40749,12 @@ var init_checker = __esm(async () => {
40668
40749
  });
40669
40750
 
40670
40751
  // src/lib/opencode-plugin-schema-fence.ts
40671
- import { existsSync as existsSync29, readdirSync as readdirSync6, readFileSync as readFileSync19 } from "node:fs";
40672
- import { join as join21 } from "node:path";
40752
+ import { existsSync as existsSync28, readdirSync as readdirSync6, readFileSync as readFileSync19 } from "node:fs";
40753
+ import { join as join22 } from "node:path";
40673
40754
  import { gunzipSync as gunzipSync2 } from "node:zlib";
40674
40755
  function readPackageVersion(packageJsonPath) {
40675
40756
  try {
40676
- if (!existsSync29(packageJsonPath))
40757
+ if (!existsSync28(packageJsonPath))
40677
40758
  return null;
40678
40759
  const packageJson = JSON.parse(readFileSync19(packageJsonPath, "utf-8"));
40679
40760
  if (packageJson.name !== OPENCODE_PLUGIN_NAME || typeof packageJson.version !== "string") {
@@ -40694,8 +40775,8 @@ function readFenceValue(text) {
40694
40775
  return values.size === 1 ? [...values][0] ?? null : null;
40695
40776
  }
40696
40777
  function readFenceFromDist(packageDirectory) {
40697
- const distDirectory = join21(packageDirectory, "dist");
40698
- if (!existsSync29(distDirectory))
40778
+ const distDirectory = join22(packageDirectory, "dist");
40779
+ if (!existsSync28(distDirectory))
40699
40780
  return null;
40700
40781
  const pending = [distDirectory];
40701
40782
  const fenceValues = new Set;
@@ -40705,7 +40786,7 @@ function readFenceFromDist(packageDirectory) {
40705
40786
  continue;
40706
40787
  try {
40707
40788
  for (const entry of readdirSync6(directory, { withFileTypes: true })) {
40708
- const path = join21(directory, entry.name);
40789
+ const path = join22(directory, entry.name);
40709
40790
  if (entry.isDirectory()) {
40710
40791
  pending.push(path);
40711
40792
  continue;
@@ -40723,20 +40804,20 @@ function readFenceFromDist(packageDirectory) {
40723
40804
  return fenceValues.size === 1 ? [...fenceValues][0] ?? null : null;
40724
40805
  }
40725
40806
  function findInstalledPluginPackage(cacheDirectory, specifier, requestedVersion) {
40726
- const directCacheRoot = join21(cacheDirectory, specifier);
40807
+ const directCacheRoot = join22(cacheDirectory, specifier);
40727
40808
  const candidates = [directCacheRoot];
40728
40809
  try {
40729
40810
  for (const entry of readdirSync6(cacheDirectory, { withFileTypes: true })) {
40730
40811
  if (!entry.isDirectory())
40731
40812
  continue;
40732
- const candidate = join21(cacheDirectory, entry.name);
40813
+ const candidate = join22(cacheDirectory, entry.name);
40733
40814
  if (!candidates.includes(candidate))
40734
40815
  candidates.push(candidate);
40735
40816
  }
40736
40817
  } catch {}
40737
40818
  for (const cacheRoot of candidates) {
40738
- const directory = join21(cacheRoot, "node_modules", ...PACKAGE_PATH_SEGMENTS);
40739
- const version = readPackageVersion(join21(directory, "package.json"));
40819
+ const directory = join22(cacheRoot, "node_modules", ...PACKAGE_PATH_SEGMENTS);
40820
+ const version = readPackageVersion(join22(directory, "package.json"));
40740
40821
  if (!version)
40741
40822
  continue;
40742
40823
  if (cacheRoot === directCacheRoot || EXACT_VERSION_PATTERN.test(requestedVersion) && version === requestedVersion) {
@@ -40881,11 +40962,11 @@ var init_opencode_plugin_schema_fence = __esm(async () => {
40881
40962
  });
40882
40963
 
40883
40964
  // src/commands/doctor-opencode-cache.ts
40884
- import { existsSync as existsSync30, readFileSync as readFileSync20, rmSync as rmSync7 } from "node:fs";
40965
+ import { existsSync as existsSync29, readFileSync as readFileSync20, rmSync as rmSync7 } from "node:fs";
40885
40966
  function readCachedPluginVersion(pluginCacheDir) {
40886
40967
  try {
40887
40968
  const installedPkgPath = getOpenCodePluginPackageJsonPath(pluginCacheDir);
40888
- if (!existsSync30(installedPkgPath))
40969
+ if (!existsSync29(installedPkgPath))
40889
40970
  return;
40890
40971
  const pkg = JSON.parse(readFileSync20(installedPkgPath, "utf-8"));
40891
40972
  return typeof pkg.version === "string" ? pkg.version : undefined;
@@ -40913,23 +40994,35 @@ function readOpenCodePluginConfigUse(config, configDir) {
40913
40994
  }
40914
40995
  async function clearPluginCache(options = {}, deps = {}) {
40915
40996
  const remove = deps.remove ?? ((path) => rmSync7(path, { recursive: true, force: true }));
40997
+ const cacheRoot = getOpenCodeCacheHome();
40916
40998
  const pluginCacheRoots = getOpenCodePluginCacheRoots();
40917
- const existingRoots = pluginCacheRoots.filter((root) => existsSync30(root));
40918
- if (existingRoots.length === 0) {
40919
- return { action: "not_found", path: pluginCacheRoots[0] ?? "" };
40999
+ const skippedWarnings = [];
41000
+ const reportSkipped = () => skippedWarnings.length > 0 ? { skippedWarnings } : {};
41001
+ const cacheEntries = pluginCacheRoots.flatMap((path) => {
41002
+ const check = checkCacheClearPath(cacheRoot, path);
41003
+ if (check.allowed)
41004
+ return [{ path, cached: readCachedPluginVersion(check.path) }];
41005
+ if (check.reason !== "missing") {
41006
+ skippedWarnings.push(describeCacheClearRefusal(path, check.reason));
41007
+ }
41008
+ return [];
41009
+ });
41010
+ if (cacheEntries.length === 0) {
41011
+ return {
41012
+ action: skippedWarnings.length > 0 ? "skipped" : "not_found",
41013
+ path: pluginCacheRoots[0] ?? "",
41014
+ ...reportSkipped()
41015
+ };
40920
41016
  }
40921
41017
  const latestVersion = options.latestVersion ?? undefined;
40922
- const cacheEntries = existingRoots.map((path) => ({
40923
- path,
40924
- cached: readCachedPluginVersion(path)
40925
- }));
40926
41018
  if (options.referencedSpecs !== undefined && !options.referencedSpecs.has("latest")) {
40927
41019
  const firstEntry = cacheEntries[0];
40928
41020
  return {
40929
41021
  action: "unused",
40930
41022
  path: firstEntry?.path ?? pluginCacheRoots[0] ?? "",
40931
41023
  paths: cacheEntries.map((entry) => entry.path),
40932
- cached: firstEntry?.cached
41024
+ cached: firstEntry?.cached,
41025
+ ...reportSkipped()
40933
41026
  };
40934
41027
  }
40935
41028
  if (options.force !== true && latestVersion === undefined) {
@@ -40938,7 +41031,8 @@ async function clearPluginCache(options = {}, deps = {}) {
40938
41031
  action: "check_unavailable",
40939
41032
  path: firstEntry?.path ?? pluginCacheRoots[0] ?? "",
40940
41033
  paths: cacheEntries.map((entry) => entry.path),
40941
- cached: firstEntry?.cached
41034
+ cached: firstEntry?.cached,
41035
+ ...reportSkipped()
40942
41036
  };
40943
41037
  }
40944
41038
  const clearTargets = cacheEntries.filter((entry) => options.force === true || entry.cached === undefined || entry.cached !== latestVersion);
@@ -40949,7 +41043,8 @@ async function clearPluginCache(options = {}, deps = {}) {
40949
41043
  path: firstEntry?.path ?? pluginCacheRoots[0] ?? "",
40950
41044
  paths: cacheEntries.map((entry) => entry.path),
40951
41045
  cached: firstEntry?.cached,
40952
- latest: latestVersion
41046
+ latest: latestVersion,
41047
+ ...reportSkipped()
40953
41048
  };
40954
41049
  }
40955
41050
  const probe = deps.probe ?? probeHostProcessesUsing;
@@ -40965,14 +41060,20 @@ async function clearPluginCache(options = {}, deps = {}) {
40965
41060
  paths: clearTargets.map((entry) => entry.path),
40966
41061
  cached: firstTarget?.cached,
40967
41062
  latest: latestVersion,
41063
+ ...reportSkipped(),
40968
41064
  ...use.status === "in_use" ? { pids: use.pids } : { reason: use.reason }
40969
41065
  };
40970
41066
  }
40971
41067
  const cleared = [];
40972
41068
  const failed = [];
40973
41069
  for (const entry of clearTargets) {
41070
+ const check = checkCacheClearPath(cacheRoot, entry.path);
41071
+ if (!check.allowed) {
41072
+ skippedWarnings.push(describeCacheClearRefusal(entry.path, check.reason));
41073
+ continue;
41074
+ }
40974
41075
  try {
40975
- remove(entry.path);
41076
+ remove(check.path);
40976
41077
  cleared.push(entry);
40977
41078
  } catch (err) {
40978
41079
  failed.push({
@@ -40985,25 +41086,29 @@ async function clearPluginCache(options = {}, deps = {}) {
40985
41086
  const firstFailure = failed[0];
40986
41087
  return {
40987
41088
  action: "error",
40988
- path: firstFailure?.path ?? clearTargets[0]?.path ?? existingRoots[0] ?? "",
41089
+ path: firstFailure?.path ?? clearTargets[0]?.path ?? cacheEntries[0]?.path ?? "",
40989
41090
  paths: failed.map((entry) => entry.path),
40990
41091
  clearedPaths: cleared.map((entry) => entry.path),
40991
41092
  failedPaths: failed.map((entry) => entry.path),
40992
- error: firstFailure?.error
41093
+ error: firstFailure?.error,
41094
+ ...reportSkipped()
40993
41095
  };
40994
41096
  }
40995
41097
  const firstTarget = cleared[0];
40996
41098
  return {
40997
- action: "cleared",
41099
+ action: firstTarget === undefined ? "skipped" : "cleared",
40998
41100
  path: firstTarget?.path ?? pluginCacheRoots[0] ?? "",
40999
41101
  paths: cleared.map((entry) => entry.path),
41000
41102
  cached: firstTarget?.cached,
41001
- latest: latestVersion
41103
+ latest: latestVersion,
41104
+ ...reportSkipped()
41002
41105
  };
41003
41106
  }
41004
41107
  var init_doctor_opencode_cache = __esm(async () => {
41108
+ init_cache_clear_path();
41005
41109
  init_opencode_plugin_cache();
41006
41110
  init_opencode_plugin_registration();
41111
+ init_paths();
41007
41112
  await __promiseAll([
41008
41113
  init_opencode(),
41009
41114
  init_doctor_opencode2_cache()
@@ -41011,7 +41116,7 @@ var init_doctor_opencode_cache = __esm(async () => {
41011
41116
  });
41012
41117
 
41013
41118
  // src/commands/doctor-cached-plugin-fence.ts
41014
- import { existsSync as existsSync31 } from "node:fs";
41119
+ import { existsSync as existsSync30 } from "node:fs";
41015
41120
  import { dirname as dirname18 } from "node:path";
41016
41121
  function isReferenced(sources, host, spec) {
41017
41122
  const specs = sources.referencedSpecs?.[host];
@@ -41022,7 +41127,7 @@ function listCachedOpenCodePluginFences(sources = {}) {
41022
41127
  const v1Referenced = isReferenced(sources, "opencode1", "latest");
41023
41128
  for (const root of v1Referenced ? sources.openCodeV1Roots ?? getOpenCodePluginCacheRoots() : []) {
41024
41129
  const packageJson = getOpenCodePluginPackageJsonPath(root);
41025
- if (!existsSync31(packageJson))
41130
+ if (!existsSync30(packageJson))
41026
41131
  continue;
41027
41132
  fences.push({
41028
41133
  host: "opencode1",
@@ -41227,13 +41332,13 @@ var init_doctor_prune_discovery = __esm(async () => {
41227
41332
 
41228
41333
  // src/commands/doctor-storage-holders.ts
41229
41334
  import { execFileSync as execFileSync5 } from "node:child_process";
41230
- import { readFileSync as readFileSync21, realpathSync as realpathSync6 } from "node:fs";
41231
- import { join as join22, resolve as resolve11 } from "node:path";
41335
+ import { readFileSync as readFileSync21, realpathSync as realpathSync7 } from "node:fs";
41336
+ import { join as join23, resolve as resolve12 } from "node:path";
41232
41337
  function canonicalStoragePath(path) {
41233
41338
  try {
41234
- return realpathSync6(path);
41339
+ return realpathSync7(path);
41235
41340
  } catch {
41236
- return resolve11(path);
41341
+ return resolve12(path);
41237
41342
  }
41238
41343
  }
41239
41344
  function textReferencesStorage(text, storageDir) {
@@ -41245,7 +41350,7 @@ function textReferencesStorage(text, storageDir) {
41245
41350
  continue;
41246
41351
  if (canonicalStoragePath(value) === target)
41247
41352
  return true;
41248
- if (token.startsWith("XDG_DATA_HOME=") && canonicalStoragePath(join22(value, "cortexkit", "magic-context")) === target)
41353
+ if (token.startsWith("XDG_DATA_HOME=") && canonicalStoragePath(join23(value, "cortexkit", "magic-context")) === target)
41249
41354
  return true;
41250
41355
  }
41251
41356
  return false;
@@ -41277,12 +41382,12 @@ var init_doctor_storage_holders = () => {};
41277
41382
 
41278
41383
  // src/commands/doctor-repair-db.ts
41279
41384
  import { spawnSync as spawnSync4 } from "node:child_process";
41280
- import { closeSync as closeSync4, existsSync as existsSync32, openSync as openSync4, renameSync as renameSync6, rmSync as rmSync8, statSync as statSync16 } from "node:fs";
41385
+ import { closeSync as closeSync4, existsSync as existsSync31, openSync as openSync4, renameSync as renameSync6, rmSync as rmSync8, statSync as statSync16 } from "node:fs";
41281
41386
  import { homedir as homedir17 } from "node:os";
41282
- import { dirname as dirname19, join as join23 } from "node:path";
41387
+ import { dirname as dirname19, join as join24 } from "node:path";
41283
41388
  function defaultInspectHolders(storageDir, overrides = {}) {
41284
41389
  const deps = {
41285
- defaultStorageDir: join23(homedir17(), ".local", "share", "cortexkit", "magic-context"),
41390
+ defaultStorageDir: join24(homedir17(), ".local", "share", "cortexkit", "magic-context"),
41286
41391
  inspectRpc: inspectRpcServerDiscovery,
41287
41392
  inspectPi: inspectLivePiProcesses,
41288
41393
  probeFiles: probeHostProcessesUsing,
@@ -41299,7 +41404,7 @@ function defaultInspectHolders(storageDir, overrides = {}) {
41299
41404
  return {
41300
41405
  safe: false,
41301
41406
  blockers: [],
41302
- uncertainty: `RPC discovery ${rpc.unreadableFile ?? join23(storageDir, "rpc")} ${arm}`
41407
+ uncertainty: `RPC discovery ${rpc.unreadableFile ?? join24(storageDir, "rpc")} ${arm}`
41303
41408
  };
41304
41409
  }
41305
41410
  const blockers = rpc.state === "live" ? rpc.serverPids.map((pid) => `OpenCode server (PID ${pid})`) : [];
@@ -41312,7 +41417,7 @@ function defaultInspectHolders(storageDir, overrides = {}) {
41312
41417
  const pi = overrides.inspectPi ? deps.inspectPi() : processes?.pi ?? deps.inspectPi();
41313
41418
  if (canonicalStoragePath(storageDir) !== canonicalStoragePath(deps.defaultStorageDir)) {
41314
41419
  const holders = deps.probeFiles({
41315
- files: ["context.db", "store.db"].flatMap((name) => DATABASE_SUFFIXES.map((suffix) => join23(storageDir, `${name}${suffix}`))),
41420
+ files: ["context.db", "store.db"].flatMap((name) => DATABASE_SUFFIXES.map((suffix) => join24(storageDir, `${name}${suffix}`))),
41316
41421
  directories: []
41317
41422
  });
41318
41423
  if (holders.status === "unknown") {
@@ -41345,11 +41450,11 @@ function timestamp(date) {
41345
41450
  return date.toISOString().replaceAll("-", "").replaceAll(":", "").replace(".", "");
41346
41451
  }
41347
41452
  function uniqueBase(preferred) {
41348
- if (!DATABASE_SUFFIXES.some((suffix) => existsSync32(`${preferred}${suffix}`)))
41453
+ if (!DATABASE_SUFFIXES.some((suffix) => existsSync31(`${preferred}${suffix}`)))
41349
41454
  return preferred;
41350
41455
  for (let attempt = 1;attempt < 1e4; attempt++) {
41351
41456
  const candidate = `${preferred}-${attempt}`;
41352
- if (!DATABASE_SUFFIXES.some((suffix) => existsSync32(`${candidate}${suffix}`)))
41457
+ if (!DATABASE_SUFFIXES.some((suffix) => existsSync31(`${candidate}${suffix}`)))
41353
41458
  return candidate;
41354
41459
  }
41355
41460
  throw new Error(`Could not allocate a unique recovery path beside ${preferred}`);
@@ -41363,7 +41468,7 @@ function databaseBundleSizeBytes(sourceBase) {
41363
41468
  let size = 0;
41364
41469
  for (const suffix of DATABASE_SUFFIXES) {
41365
41470
  const source = `${sourceBase}${suffix}`;
41366
- if (existsSync32(source))
41471
+ if (existsSync31(source))
41367
41472
  size += statSync16(source).size;
41368
41473
  }
41369
41474
  return size;
@@ -41372,7 +41477,7 @@ function copyDatabaseBundle(sourceBase, destinationBase, forcePrivate = false) {
41372
41477
  const copiedPaths = [];
41373
41478
  for (const suffix of DATABASE_SUFFIXES) {
41374
41479
  const source = `${sourceBase}${suffix}`;
41375
- if (!existsSync32(source))
41480
+ if (!existsSync31(source))
41376
41481
  continue;
41377
41482
  const destination = `${destinationBase}${suffix}`;
41378
41483
  copyStorageFileSync(source, destination, forcePrivate);
@@ -41594,7 +41699,7 @@ function activateReplacement(dbPath, replacementPath, originalAsidePath) {
41594
41699
  try {
41595
41700
  for (const suffix of DATABASE_SUFFIXES) {
41596
41701
  const from = `${dbPath}${suffix}`;
41597
- if (!existsSync32(from))
41702
+ if (!existsSync31(from))
41598
41703
  continue;
41599
41704
  const to = `${originalAsidePath}${suffix}`;
41600
41705
  renameSync6(from, to);
@@ -41604,7 +41709,7 @@ function activateReplacement(dbPath, replacementPath, originalAsidePath) {
41604
41709
  return movedOriginals.map(({ to }) => to);
41605
41710
  } catch (error) {
41606
41711
  for (const moved of movedOriginals.reverse()) {
41607
- if (existsSync32(moved.to) && !existsSync32(moved.from))
41712
+ if (existsSync31(moved.to) && !existsSync31(moved.from))
41608
41713
  renameSync6(moved.to, moved.from);
41609
41714
  }
41610
41715
  throw error;
@@ -41635,12 +41740,12 @@ function printHelp() {
41635
41740
  async function runRepairDb(options = {}) {
41636
41741
  const prompts = options.prompts ?? promptIO;
41637
41742
  const deps = { ...DEFAULT_DEPS3, ...options.deps };
41638
- const storageDir = options.storageDir ?? dirname19(options.dbPath ?? join23(getMagicContextStorageDir(), "context.db"));
41639
- const dbPath = options.dbPath ?? join23(storageDir, "context.db");
41743
+ const storageDir = options.storageDir ?? dirname19(options.dbPath ?? join24(getMagicContextStorageDir(), "context.db"));
41744
+ const dbPath = options.dbPath ?? join24(storageDir, "context.db");
41640
41745
  const stamp = timestamp(deps.now());
41641
41746
  prompts.intro("Magic Context — Repair shared database");
41642
41747
  prompts.log.info(`Database: ${dbPath}`);
41643
- if (!existsSync32(dbPath)) {
41748
+ if (!existsSync31(dbPath)) {
41644
41749
  prompts.log.error(`Database not found: ${dbPath}`);
41645
41750
  prompts.log.info("Backup: not created (database does not exist)");
41646
41751
  prompts.outro("Database repair failed");
@@ -41850,12 +41955,12 @@ var init_doctor_repair_db = __esm(async () => {
41850
41955
 
41851
41956
  // src/commands/doctor-single-store-repair.ts
41852
41957
  import { spawnSync as spawnSync5 } from "node:child_process";
41853
- import { existsSync as existsSync33, statfsSync as statfsSync2, statSync as statSync17 } from "node:fs";
41958
+ import { existsSync as existsSync32, statfsSync as statfsSync2, statSync as statSync17 } from "node:fs";
41854
41959
  import { homedir as homedir18 } from "node:os";
41855
- import { dirname as dirname20, join as join24, resolve as resolve12 } from "node:path";
41960
+ import { dirname as dirname20, join as join25, resolve as resolve13 } from "node:path";
41856
41961
  function existingAncestor(path) {
41857
- let current = resolve12(path);
41858
- while (!existsSync33(current))
41962
+ let current = resolve13(path);
41963
+ while (!existsSync32(current))
41859
41964
  current = dirname20(current);
41860
41965
  return current;
41861
41966
  }
@@ -41891,15 +41996,15 @@ function runDoctorSingleStoreRepair(options, overrides = {}) {
41891
41996
  };
41892
41997
  try {
41893
41998
  const { dbPath: context, dbDir: data } = resolveDatabasePath();
41894
- const store = join24(data, "store.db");
41895
- if (!existsSync33(context) || !existsSync33(store))
41999
+ const store = join25(data, "store.db");
42000
+ if (!existsSync32(context) || !existsSync32(store))
41896
42001
  return refuse("repair_missing_database", `Both ${context} and ${store} must exist.`);
41897
42002
  if (!options.fromBackup)
41898
42003
  return refuse("repair_usage", "--from-backup <dir> is required");
41899
- const fromBackup = resolve12(options.fromBackup);
42004
+ const fromBackup = resolve13(options.fromBackup);
41900
42005
  for (const name of ["context.db", "store.db"])
41901
- if (!existsSync33(join24(fromBackup, name)))
41902
- return refuse("repair_backup_missing", `${join24(fromBackup, name)} does not exist`);
42006
+ if (!existsSync32(join25(fromBackup, name)))
42007
+ return refuse("repair_backup_missing", `${join25(fromBackup, name)} does not exist`);
41903
42008
  const sessions = options.sessions ?? [];
41904
42009
  if (options.live && sessions.length === 0)
41905
42010
  return refuse("repair_usage", "--live repairs named sessions only; pass --session <id>");
@@ -41926,16 +42031,16 @@ function runDoctorSingleStoreRepair(options, overrides = {}) {
41926
42031
  `));
41927
42032
  deps.print(`Repairing while hosts hold the stores (--live): ${blockers.join("; ") || "holders unknown"}`);
41928
42033
  }
41929
- const backupRoot = resolve12(options.backupRoot ?? join24(data, "backups"));
42034
+ const backupRoot = resolve13(options.backupRoot ?? join25(data, "backups"));
41930
42035
  const need = Math.ceil((statSync17(context).size + statSync17(store).size) * 1.1);
41931
42036
  const volume = existingAncestor(backupRoot);
41932
42037
  const have = deps.freeBytes(volume);
41933
42038
  if (have < need)
41934
42039
  return refuse("repair_disk_space", `the backup needs ${need} bytes; have ${have} bytes on ${volume}`);
41935
- backupDir = join24(backupRoot, `repair-history-${deps.now().toISOString().replaceAll(":", "-")}`);
42040
+ backupDir = join25(backupRoot, `repair-history-${deps.now().toISOString().replaceAll(":", "-")}`);
41936
42041
  deps.print(`Backing up the live stores to ${backupDir} before any write.`);
41937
42042
  }
41938
- const binary = options.ckMc ?? join24(homedir18(), ".local", "share", "cortexkit", "bin", "ck-mc");
42043
+ const binary = options.ckMc ?? join25(homedir18(), ".local", "share", "cortexkit", "bin", "ck-mc");
41939
42044
  const args = [
41940
42045
  "single-store-repair-history",
41941
42046
  "--context-db",
@@ -42023,22 +42128,22 @@ var init_doctor_single_store_repair = __esm(async () => {
42023
42128
 
42024
42129
  // src/commands/doctor-single-store.ts
42025
42130
  import { spawnSync as spawnSync6 } from "node:child_process";
42026
- import { existsSync as existsSync34, realpathSync as realpathSync7, statSync as statSync18 } from "node:fs";
42131
+ import { existsSync as existsSync33, realpathSync as realpathSync8, statSync as statSync18 } from "node:fs";
42027
42132
  import { homedir as homedir19 } from "node:os";
42028
- import { join as join25, resolve as resolve13 } from "node:path";
42133
+ import { join as join26, resolve as resolve14 } from "node:path";
42029
42134
  function engineContextPath() {
42030
42135
  const value = (key) => process.env[key]?.trim() || undefined;
42031
42136
  const test = value("MAGIC_CONTEXT_TEST_DATA_DIR");
42032
42137
  const xdg = value("XDG_DATA_HOME");
42033
- 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");
42034
- return join25(dir, "context.db");
42138
+ 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");
42139
+ return join26(dir, "context.db");
42035
42140
  }
42036
42141
  function undo(backup, data, print) {
42037
42142
  const quote = (s) => `'${s.replaceAll("'", "'\\''")}'`;
42038
42143
  print(`Backup: ${backup}`);
42039
42144
  print("To undo: quit every host, then");
42040
- print(` rm -f ${["context.db-wal", "context.db-shm", "store.db-wal", "store.db-shm"].map((name) => quote(join25(data, name))).join(" ")}`);
42041
- print(` cp ${quote(join25(backup, "context.db"))} ${quote(join25(backup, "store.db"))} ${quote(data + "/")}`);
42145
+ print(` rm -f ${["context.db-wal", "context.db-shm", "store.db-wal", "store.db-shm"].map((name) => quote(join26(data, name))).join(" ")}`);
42146
+ print(` cp ${quote(join26(backup, "context.db"))} ${quote(join26(backup, "store.db"))} ${quote(data + "/")}`);
42042
42147
  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.");
42043
42148
  }
42044
42149
  function runDoctorSingleStore(options = {}, overrides = {}) {
@@ -42056,8 +42161,8 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
42056
42161
  };
42057
42162
  try {
42058
42163
  const { dbPath: context, dbDir: data } = resolveDatabasePath();
42059
- const store = join25(data, "store.db");
42060
- if (!existsSync34(context) || !existsSync34(store))
42164
+ const store = join26(data, "store.db");
42165
+ if (!existsSync33(context) || !existsSync33(store))
42061
42166
  return refuse("single_store_missing_database", `Both ${context} and ${store} must exist.`);
42062
42167
  const probe = probeHostProcessesUsing({ files: [context, store].flatMap((p) => SUFFIXES2.map((s) => p + s)), directories: [] }, deps.lsofSpawn);
42063
42168
  const holders = deps.inspectHolders(data);
@@ -42072,9 +42177,9 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
42072
42177
  return refuse("single_store_files_in_use", [...lines, STOP].join(`
42073
42178
  `));
42074
42179
  }
42075
- if (!existsSync34(engineContextPath()) || realpathSync7(context) !== realpathSync7(engineContextPath()))
42180
+ if (!existsSync33(engineContextPath()) || realpathSync8(context) !== realpathSync8(engineContextPath()))
42076
42181
  return refuse("single_store_path_mismatch", `CLI ${context}; engine ${engineContextPath()}`);
42077
- const backupRoot = resolve13(options.backupRoot ?? join25(data, "backups"));
42182
+ const backupRoot = resolve14(options.backupRoot ?? join26(data, "backups"));
42078
42183
  const contextDb = openExistingDatabase(context, { readonly: true });
42079
42184
  if (!contextDb)
42080
42185
  return refuse("single_store_missing_database", `Database disappeared: ${context}`);
@@ -42116,7 +42221,7 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
42116
42221
  const backupSpace = sameVolume ? undefined : checkDiskSpace(backupVolume, backupBytes, deps.freeBytes);
42117
42222
  if (backupSpace && !backupSpace.sufficient)
42118
42223
  return refuse("single_store_disk_space", `backup needs ${backupSpace.requiredBytes} bytes; have ${backupSpace.availableBytes} bytes on ${backupVolume}`);
42119
- const backupDir = join25(backupRoot, `single-store-${deps.now().toISOString().replaceAll(":", "-")}`);
42224
+ const backupDir = join26(backupRoot, `single-store-${deps.now().toISOString().replaceAll(":", "-")}`);
42120
42225
  undo(backupDir, data, deps.print);
42121
42226
  const opened = openDatabase(context);
42122
42227
  if (!opened)
@@ -42128,7 +42233,7 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
42128
42233
  }
42129
42234
  if (contextVersion !== LATEST_SUPPORTED_VERSION)
42130
42235
  return refuse("single_store_version_mismatch", `context.db v${contextVersion}; store.db v${storeVersion}`);
42131
- const binary = options.ckMc ?? join25(homedir19(), ".local", "share", "cortexkit", "bin", "ck-mc");
42236
+ const binary = options.ckMc ?? join26(homedir19(), ".local", "share", "cortexkit", "bin", "ck-mc");
42132
42237
  const args = [
42133
42238
  "single-store-migrate",
42134
42239
  "--context-db",
@@ -42620,15 +42725,15 @@ var init_storage_identity_merge = __esm(() => {
42620
42725
  // src/commands/doctor-identity-splits.ts
42621
42726
  import { execFileSync as execFileSync6 } from "node:child_process";
42622
42727
  import { createHash as createHash6 } from "node:crypto";
42623
- import { existsSync as existsSync35, readdirSync as readdirSync7, realpathSync as realpathSync8, statSync as statSync19 } from "node:fs";
42624
- import { dirname as dirname21, join as join26, resolve as resolve14 } from "node:path";
42728
+ import { existsSync as existsSync34, readdirSync as readdirSync7, realpathSync as realpathSync9, statSync as statSync19 } from "node:fs";
42729
+ import { dirname as dirname21, join as join27, resolve as resolve15 } from "node:path";
42625
42730
  function tableExists5(db, table) {
42626
42731
  return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
42627
42732
  }
42628
42733
  function hasGitMetadataInAncestors(directory) {
42629
- let current = resolve14(directory);
42734
+ let current = resolve15(directory);
42630
42735
  while (true) {
42631
- if (existsSync35(join26(current, ".git")))
42736
+ if (existsSync34(join27(current, ".git")))
42632
42737
  return true;
42633
42738
  const parent = dirname21(current);
42634
42739
  if (parent === current)
@@ -42661,7 +42766,7 @@ function findIdentitySplits(db, host, includeSingles = false) {
42661
42766
  return cached;
42662
42767
  let canonical = directory;
42663
42768
  try {
42664
- canonical = realpathSync8.native(directory);
42769
+ canonical = realpathSync9.native(directory);
42665
42770
  } catch {}
42666
42771
  canonicalDirectories.set(directory, canonical);
42667
42772
  return canonical;
@@ -42714,7 +42819,7 @@ function findIdentitySplits(db, host, includeSingles = false) {
42714
42819
  const gitIdentities = new Map;
42715
42820
  for (const [directoryKey, spellings] of directorySpellings) {
42716
42821
  for (const directory of spellings) {
42717
- const dirIdentity = `dir:${createHash6("md5").update(resolve14(directory), "utf8").digest("hex").slice(0, 12)}`;
42822
+ const dirIdentity = `dir:${createHash6("md5").update(resolve15(directory), "utf8").digest("hex").slice(0, 12)}`;
42718
42823
  const hasData = [
42719
42824
  "memories",
42720
42825
  "notes",
@@ -42783,7 +42888,7 @@ function identityLines(split) {
42783
42888
  return split.identities.map((row) => ` ${row.identity}: ${row.sessions} sessions, ${row.memories} memories, ${row.notes} notes, ${row.dreamer} dreamer rows (identity-wide counts)`);
42784
42889
  }
42785
42890
  function diagnoseIdentitySplits() {
42786
- const db = openExistingContextDatabase(join26(getMagicContextStorageDir(), "context.db"), {
42891
+ const db = openExistingContextDatabase(join27(getMagicContextStorageDir(), "context.db"), {
42787
42892
  readonly: true
42788
42893
  });
42789
42894
  if (!db)
@@ -42809,8 +42914,8 @@ var init_doctor_identity_splits = __esm(async () => {
42809
42914
  // src/commands/doctor-merge-identity.ts
42810
42915
  import { execFileSync as execFileSync7 } from "node:child_process";
42811
42916
  import { createHash as createHash7 } from "node:crypto";
42812
- import { existsSync as existsSync36, mkdtempSync as mkdtempSync2, readdirSync as readdirSync8, readFileSync as readFileSync22, statSync as statSync20 } from "node:fs";
42813
- import { dirname as dirname22, join as join27, resolve as resolve15 } from "node:path";
42917
+ import { existsSync as existsSync35, mkdtempSync as mkdtempSync2, readdirSync as readdirSync8, readFileSync as readFileSync22, statSync as statSync20 } from "node:fs";
42918
+ import { dirname as dirname22, join as join28, resolve as resolve16 } from "node:path";
42814
42919
  function parseMergeIdentityArgs(args) {
42815
42920
  const values = {};
42816
42921
  const switches = new Set(["--apply", "--force", "--dry-run", "--yes", "--verbose"]);
@@ -42860,7 +42965,7 @@ function printReport(report) {
42860
42965
  console.log(" No writes. Review this preview, then repeat with --apply to confirm.");
42861
42966
  }
42862
42967
  function resolveReadOnly(directory) {
42863
- if (!existsSync36(directory))
42968
+ if (!existsSync35(directory))
42864
42969
  return;
42865
42970
  try {
42866
42971
  const roots = execFileSync7("git", ["rev-list", "--max-parents=0", "HEAD"], {
@@ -43016,13 +43121,13 @@ function observations(db, hostPath, storageDir) {
43016
43121
  if (!row.identities.some((item) => item.identity === identity))
43017
43122
  row.identities.push({ identity, sessions: 0, memories: 0, notes: 0, dreamer: 0 });
43018
43123
  };
43019
- const sidecars = join27(storageDir, "project-identities");
43020
- if (existsSync36(sidecars))
43124
+ const sidecars = join28(storageDir, "project-identities");
43125
+ if (existsSync35(sidecars))
43021
43126
  for (const file of readdirSync8(sidecars)) {
43022
43127
  if (!file.endsWith(".json"))
43023
43128
  continue;
43024
43129
  try {
43025
- const record = JSON.parse(readFileSync22(join27(sidecars, file), "utf8"));
43130
+ const record = JSON.parse(readFileSync22(join28(sidecars, file), "utf8"));
43026
43131
  if (typeof record.directory === "string" && typeof record.identity === "string")
43027
43132
  add(record.directory, record.identity);
43028
43133
  } catch {}
@@ -43033,9 +43138,9 @@ function observations(db, hostPath, storageDir) {
43033
43138
  }
43034
43139
  function runMergeIdentityCli(args, deps = {}) {
43035
43140
  const options = parseMergeIdentityArgs(args);
43036
- const dbPath = options.dbPath ?? join27(getMagicContextStorageDir(), "context.db");
43141
+ const dbPath = options.dbPath ?? join28(getMagicContextStorageDir(), "context.db");
43037
43142
  const storageDir = dirname22(dbPath);
43038
- const hostPath = options.hostPath ?? (options.dbPath ? join27(storageDir, "host.db") : resolveOpenCodeDbPath().path);
43143
+ const hostPath = options.hostPath ?? (options.dbPath ? join28(storageDir, "host.db") : resolveOpenCodeDbPath().path);
43039
43144
  let db = openExistingContextDatabase(dbPath, {
43040
43145
  readonly: true,
43041
43146
  minimumSupportedVersion: CLI_SCHEMA_FLOOR_VERSION
@@ -43086,29 +43191,29 @@ function runMergeIdentityCli(args, deps = {}) {
43086
43191
  });
43087
43192
  if (!holders.safe || probe.status !== "free")
43088
43193
  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 : ""}`);
43089
- const backupRoot = resolve15(options.backupRoot ?? storageDir);
43194
+ const backupRoot = resolve16(options.backupRoot ?? storageDir);
43090
43195
  const backupVolume = existingDirectoryAncestor(backupRoot);
43091
- const sidecarRoot = join27(storageDir, "project-identities");
43092
- const sidecarEntries = existsSync36(sidecarRoot) ? readdirSync8(sidecarRoot).filter((entry) => entry.endsWith(".json")) : [];
43093
- const sidecarBytes = sidecarEntries.reduce((size, entry) => size + statSync20(join27(sidecarRoot, entry)).size, 0);
43196
+ const sidecarRoot = join28(storageDir, "project-identities");
43197
+ const sidecarEntries = existsSync35(sidecarRoot) ? readdirSync8(sidecarRoot).filter((entry) => entry.endsWith(".json")) : [];
43198
+ const sidecarBytes = sidecarEntries.reduce((size, entry) => size + statSync20(join28(sidecarRoot, entry)).size, 0);
43094
43199
  const diskSpace = checkDiskSpace(backupVolume, databaseBundleSizeBytes(dbPath) + sidecarBytes, deps.freeBytes ?? availableDiskBytes);
43095
43200
  if (!diskSpace.sufficient)
43096
43201
  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.`);
43097
43202
  ensureStorageDirectorySync(backupRoot, true);
43098
- const backup = mkdtempSync2(join27(backupRoot, "identity-merge-backup-"));
43203
+ const backup = mkdtempSync2(join28(backupRoot, "identity-merge-backup-"));
43099
43204
  const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
43100
43205
  console.log(`Backup directory: ${backup}`);
43101
- 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`);
43102
- const sidecarBackup = join27(backup, "project-identities");
43206
+ 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`);
43207
+ const sidecarBackup = join28(backup, "project-identities");
43103
43208
  ensureStorageDirectorySync(sidecarBackup, true);
43104
43209
  let backupBytes = 0;
43105
43210
  for (const entry of sidecarEntries) {
43106
- const content = readFileSync22(join27(sidecarRoot, entry));
43107
- writeStorageFileAtomicSync(join27(sidecarBackup, entry), content, true);
43211
+ const content = readFileSync22(join28(sidecarRoot, entry));
43212
+ writeStorageFileAtomicSync(join28(sidecarBackup, entry), content, true);
43108
43213
  backupBytes += content.byteLength;
43109
43214
  }
43110
43215
  console.log(`Restore identity sidecars too: rm -rf ${quote(sidecarRoot)}; cp -R ${quote(sidecarBackup)} ${quote(sidecarRoot)}`);
43111
- const copiedDatabaseFiles = copyDatabaseBundle(dbPath, join27(backup, "context.db"), true);
43216
+ const copiedDatabaseFiles = copyDatabaseBundle(dbPath, join28(backup, "context.db"), true);
43112
43217
  backupBytes += copiedDatabaseFiles.reduce((size, path) => size + statSync20(path).size, 0);
43113
43218
  db = openExistingDatabase(dbPath, { readonly: false });
43114
43219
  if (!db)
@@ -43127,9 +43232,9 @@ function runMergeIdentityCli(args, deps = {}) {
43127
43232
  }
43128
43233
  if (to.startsWith("git:"))
43129
43234
  for (const directory of directories) {
43130
- const root = join27(storageDir, "project-identities");
43235
+ const root = join28(storageDir, "project-identities");
43131
43236
  ensureStorageDirectorySync(root);
43132
- const path = join27(root, `${createHash7("sha256").update(projectDirectoryKey(directory)).digest("hex")}.json`);
43237
+ const path = join28(root, `${createHash7("sha256").update(projectDirectoryKey(directory)).digest("hex")}.json`);
43133
43238
  writeStorageFileAtomicSync(path, JSON.stringify({ directory: projectDirectoryKey(directory), identity: options.to }));
43134
43239
  }
43135
43240
  console.log(`Backup: ${backup} (${backupBytes} bytes)`);
@@ -43153,8 +43258,8 @@ var init_doctor_merge_identity = __esm(async () => {
43153
43258
  });
43154
43259
 
43155
43260
  // src/commands/doctor-git-fts-map.ts
43156
- import { existsSync as existsSync37, mkdtempSync as mkdtempSync3, statSync as statSync21 } from "node:fs";
43157
- import { join as join28, resolve as resolve16 } from "node:path";
43261
+ import { existsSync as existsSync36, mkdtempSync as mkdtempSync3, statSync as statSync21 } from "node:fs";
43262
+ import { join as join29, resolve as resolve17 } from "node:path";
43158
43263
  function inspectGitFtsMap(db) {
43159
43264
  const has = (name) => Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE name=? AND type='table'").get(name));
43160
43265
  const indexed = has("git_commits_fts");
@@ -43207,8 +43312,8 @@ function runDoctorGitFtsMap(options = {}, overrides = {}) {
43207
43312
  verify: verifyInventory,
43208
43313
  ...overrides
43209
43314
  };
43210
- const context = join28(deps.storageDir, "context.db");
43211
- const store = join28(deps.storageDir, "store.db");
43315
+ const context = join29(deps.storageDir, "context.db");
43316
+ const store = join29(deps.storageDir, "store.db");
43212
43317
  let db = null, storeDb = null;
43213
43318
  let contextLocked = false, storeLocked = false;
43214
43319
  try {
@@ -43230,7 +43335,7 @@ function runDoctorGitFtsMap(options = {}, overrides = {}) {
43230
43335
  deps.print(`Stop every host, then run \`${GIT_FTS_MAP_REPAIR_COMMAND}\`. The repair backs up context.db and store.db first.`);
43231
43336
  return damaged ? 1 : 0;
43232
43337
  }
43233
- if (!existsSync37(context) || !existsSync37(store))
43338
+ if (!existsSync36(context) || !existsSync36(store))
43234
43339
  throw new Error("Both context.db and store.db must exist before paired-backup repair; no replacement store will be created");
43235
43340
  const cstat = statSync21(context), sstat = statSync21(store);
43236
43341
  if (cstat.dev === sstat.dev && cstat.ino === sstat.ino)
@@ -43260,12 +43365,12 @@ function runDoctorGitFtsMap(options = {}, overrides = {}) {
43260
43365
  const stillFree = deps.inspectHolders(deps.storageDir);
43261
43366
  if (!stillFree.safe)
43262
43367
  throw new Error(`A host appeared before backup: ${[...stillFree.blockers, stillFree.uncertainty].filter(Boolean).join("; ")}`);
43263
- const backupRoot = resolve16(options.backupRoot ?? join28(deps.storageDir, "backups"));
43368
+ const backupRoot = resolve17(options.backupRoot ?? join29(deps.storageDir, "backups"));
43264
43369
  ensureStorageDirectorySync(backupRoot, true);
43265
- const backup = mkdtempSync3(join28(backupRoot, "git-fts-map-"));
43266
- snapshot(context, join28(backup, "context.db"));
43267
- snapshot(store, join28(backup, "store.db"));
43268
- writeStorageFileSync(join28(backup, "manifest.json"), JSON.stringify({
43370
+ const backup = mkdtempSync3(join29(backupRoot, "git-fts-map-"));
43371
+ snapshot(context, join29(backup, "context.db"));
43372
+ snapshot(store, join29(backup, "store.db"));
43373
+ writeStorageFileSync(join29(backup, "manifest.json"), JSON.stringify({
43269
43374
  contextVersion: version,
43270
43375
  createdAt: new Date().toISOString(),
43271
43376
  repair: "git-fts-map",
@@ -43433,19 +43538,19 @@ var SINGLE_STORE_REQUIRED = "Magic Context's Rust mode needs a one-time migratio
43433
43538
 
43434
43539
  // src/commands/migrate.ts
43435
43540
  import { createHash as createHash8, randomBytes as randomBytes3 } from "node:crypto";
43436
- import { existsSync as existsSync38, mkdirSync as mkdirSync7, renameSync as renameSync7, unlinkSync as unlinkSync5 } from "node:fs";
43437
- import { dirname as dirname23, join as join29 } from "node:path";
43541
+ import { existsSync as existsSync37, mkdirSync as mkdirSync7, renameSync as renameSync7, unlinkSync as unlinkSync5 } from "node:fs";
43542
+ import { dirname as dirname23, join as join30 } from "node:path";
43438
43543
  function defaultOpenCodeDbPath() {
43439
43544
  return getOpenCodeDatabasePath();
43440
43545
  }
43441
43546
  function defaultCortexkitDbPath() {
43442
- return join29(getMagicContextStorageDir(), "context.db");
43547
+ return join30(getMagicContextStorageDir(), "context.db");
43443
43548
  }
43444
43549
  function defaultPiSessionsRoot() {
43445
43550
  return getPiSessionsRoot();
43446
43551
  }
43447
43552
  function defaultFs() {
43448
- return { writeFileAtomic, unlinkSync: unlinkSync5, existsSync: existsSync38, renameSync: renameSync7, mkdirSync: mkdirSync7 };
43553
+ return { writeFileAtomic, unlinkSync: unlinkSync5, existsSync: existsSync37, renameSync: renameSync7, mkdirSync: mkdirSync7 };
43449
43554
  }
43450
43555
  function stmt(db, sql) {
43451
43556
  return db.prepare(sql);
@@ -43529,7 +43634,7 @@ function claimJournalIdentity(args) {
43529
43634
  migration_key, source_session_id, target_harness, pi_session_id,
43530
43635
  final_path, stage_path, content_sha256, phase, created_at
43531
43636
  ) VALUES (?, ?, ?, ?, ?, ?, '', 'staged', ?)
43532
- 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);
43637
+ 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);
43533
43638
  const row = readPendingMigration(args.db, args.migrationKey);
43534
43639
  if (!row) {
43535
43640
  throw new Error("migration journal row disappeared during insert; aborting migration");
@@ -44037,7 +44142,7 @@ function migrateOpenCodeSessionToPi(opts) {
44037
44142
  const provider = opts.provider ?? model.provider;
44038
44143
  const modelId = opts.modelId ?? model.modelId;
44039
44144
  const cwd = session.directory ?? session.path ?? process.cwd();
44040
- const outputDir = join29(piSessionsRoot, projectPathToPiDirSlug(cwd));
44145
+ const outputDir = join30(piSessionsRoot, projectPathToPiDirSlug(cwd));
44041
44146
  const targetHarness = opts.targetHarness ?? "pi";
44042
44147
  if (cortexkitDb !== null) {
44043
44148
  assertNoUnmigratedAuthority(cortexkitDb);
@@ -44064,8 +44169,8 @@ function migrateOpenCodeSessionToPi(opts) {
44064
44169
  migrationKey,
44065
44170
  sourceSessionId: session.id,
44066
44171
  targetHarness,
44067
- finalPathFor: (id) => join29(outputDir, `${formatPiFilenameTimestamp(now)}_${id}.jsonl`),
44068
- stageDir: join29(dirname23(piSessionsRoot), MIGRATION_STAGE_DIRNAME),
44172
+ finalPathFor: (id) => join30(outputDir, `${formatPiFilenameTimestamp(now)}_${id}.jsonl`),
44173
+ stageDir: join30(dirname23(piSessionsRoot), MIGRATION_STAGE_DIRNAME),
44069
44174
  now: now.getTime()
44070
44175
  });
44071
44176
  piSessionId = claimed.row.pi_session_id;
@@ -44074,7 +44179,7 @@ function migrateOpenCodeSessionToPi(opts) {
44074
44179
  journalResumed = claimed.resumed;
44075
44180
  } else {
44076
44181
  piSessionId = generateUuidV7(now);
44077
- finalPath = join29(outputDir, `${formatPiFilenameTimestamp(now)}_${piSessionId}.jsonl`);
44182
+ finalPath = join30(outputDir, `${formatPiFilenameTimestamp(now)}_${piSessionId}.jsonl`);
44078
44183
  stagePath = "";
44079
44184
  }
44080
44185
  const buildResult = buildPiEntries({
@@ -46427,13 +46532,13 @@ var init_store_ahead_refusal = __esm(() => {
46427
46532
  });
46428
46533
 
46429
46534
  // ../plugin/src/hooks/magic-context/module-transport.ts
46430
- import { realpathSync as realpathSync9 } from "node:fs";
46431
- import { join as join30 } from "node:path";
46535
+ import { realpathSync as realpathSync10 } from "node:fs";
46536
+ import { join as join31 } from "node:path";
46432
46537
  function monotonicNow() {
46433
46538
  return monotonicClockForTests?.() ?? performance.now();
46434
46539
  }
46435
46540
  function getDefaultSubcConnectionFile() {
46436
- return join30(getDataDir(), "cortexkit", "run", "subc-connection.json");
46541
+ return join31(getDataDir(), "cortexkit", "run", "subc-connection.json");
46437
46542
  }
46438
46543
  function errorChainSome(error, predicate) {
46439
46544
  let current = error;
@@ -46929,7 +47034,7 @@ class SubcModuleTransport {
46929
47034
  }
46930
47035
  let resolved = root;
46931
47036
  try {
46932
- resolved = realpathSync9.native(root);
47037
+ resolved = realpathSync10.native(root);
46933
47038
  } catch {}
46934
47039
  this.canonicalRootCache.set(root, resolved);
46935
47040
  while (this.canonicalRootCache.size > CANONICAL_ROOT_CACHE_MAX_ENTRIES) {
@@ -47042,9 +47147,9 @@ var init_module_transport = __esm(async () => {
47042
47147
  });
47043
47148
 
47044
47149
  // src/commands/migrate-session.ts
47045
- import { existsSync as existsSync39, realpathSync as realpathSync10 } from "node:fs";
47150
+ import { existsSync as existsSync38, realpathSync as realpathSync11 } from "node:fs";
47046
47151
  import { homedir as homedir20 } from "node:os";
47047
- import path7, { join as join31 } from "node:path";
47152
+ import path7, { join as join32 } from "node:path";
47048
47153
  function existingSessionColumns(db) {
47049
47154
  const rows = db.prepare("PRAGMA table_info(session)").all();
47050
47155
  return new Set(rows.map((r) => r.name).filter((n) => typeof n === "string"));
@@ -47225,15 +47330,15 @@ function defaultOpenCodeDbPath2() {
47225
47330
  return getOpenCodeDatabasePath();
47226
47331
  }
47227
47332
  function defaultContextDbPath() {
47228
- return join31(getMagicContextStorageDir(), "context.db");
47333
+ return join32(getMagicContextStorageDir(), "context.db");
47229
47334
  }
47230
47335
  function realDeps(opencodeDb, contextDb) {
47231
47336
  return {
47232
47337
  opencodeDb,
47233
47338
  contextDb,
47234
47339
  resolveIdentity: resolveProjectIdentity,
47235
- hasGitDir: (dir) => existsSync39(join31(dir, ".git")),
47236
- realpath: (p) => realpathSync10(p)
47340
+ hasGitDir: (dir) => existsSync38(join32(dir, ".git")),
47341
+ realpath: (p) => realpathSync11(p)
47237
47342
  };
47238
47343
  }
47239
47344
  function valueAfter(args, flag) {
@@ -47310,8 +47415,8 @@ async function runMigrateSessionCli(args) {
47310
47415
  printMigrateSessionHelp();
47311
47416
  return 1;
47312
47417
  }
47313
- const expandedTo = toDir.startsWith("~") ? join31(homedir20(), toDir.slice(1).replace(/^[/\\]/, "")) : toDir;
47314
- if (!existsSync39(expandedTo)) {
47418
+ const expandedTo = toDir.startsWith("~") ? join32(homedir20(), toDir.slice(1).replace(/^[/\\]/, "")) : toDir;
47419
+ if (!existsSync38(expandedTo)) {
47315
47420
  console.error(`Target directory does not exist: ${expandedTo}`);
47316
47421
  return 1;
47317
47422
  }
@@ -47465,7 +47570,7 @@ var init_migrate_session = __esm(async () => {
47465
47570
 
47466
47571
  // ../plugin/src/features/magic-context/v22-deferred-backfill.ts
47467
47572
  import { createHash as createHash10 } from "node:crypto";
47468
- import { realpathSync as realpathSync11 } from "node:fs";
47573
+ import { realpathSync as realpathSync12 } from "node:fs";
47469
47574
  import path8 from "node:path";
47470
47575
  function readMeta(db, key) {
47471
47576
  const row = db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(key);
@@ -47509,7 +47614,7 @@ function resolveBackfillIdentity(rawProjectPath) {
47509
47614
  function computeLegacyRustDirIdentity(rawProjectPath) {
47510
47615
  let canonical;
47511
47616
  try {
47512
- canonical = realpathSync11(rawProjectPath);
47617
+ canonical = realpathSync12(rawProjectPath);
47513
47618
  } catch {
47514
47619
  canonical = path8.isAbsolute(rawProjectPath) ? rawProjectPath : path8.join(process.cwd(), rawProjectPath);
47515
47620
  }
@@ -47734,7 +47839,7 @@ var init_tick_failure = __esm(() => {
47734
47839
  });
47735
47840
 
47736
47841
  // ../pi-plugin/src/config/index.ts
47737
- import { existsSync as existsSync40 } from "node:fs";
47842
+ import { existsSync as existsSync39 } from "node:fs";
47738
47843
  function getProjectConfigPaths(cwd) {
47739
47844
  const basePath = cortexKitProjectConfigBasePath(cwd);
47740
47845
  return [`${basePath}.jsonc`, `${basePath}.json`];
@@ -47744,10 +47849,10 @@ function getUserConfigPaths() {
47744
47849
  return [`${basePath}.jsonc`, `${basePath}.json`];
47745
47850
  }
47746
47851
  function resolveFirstExisting(paths) {
47747
- return paths.find((path) => existsSync40(path));
47852
+ return paths.find((path) => existsSync39(path));
47748
47853
  }
47749
47854
  function resolvePiLegacyFallback(sources) {
47750
- return sources.find((source) => existsSync40(source.path)) ?? null;
47855
+ return sources.find((source) => existsSync39(source.path)) ?? null;
47751
47856
  }
47752
47857
  function loadConfigFile(path, scope) {
47753
47858
  let raw;
@@ -48061,7 +48166,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
48061
48166
  if (loaded)
48062
48167
  loadedFiles.push(loaded);
48063
48168
  }
48064
- const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync40(source.path));
48169
+ const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync39(source.path));
48065
48170
  const userPath = resolveFirstExisting(getUserConfigPaths());
48066
48171
  const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
48067
48172
  const userReadPath = userPath ?? userLegacyFallback?.path;
@@ -48070,7 +48175,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
48070
48175
  if (loaded)
48071
48176
  loadedFiles.push(loaded);
48072
48177
  }
48073
- const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync40(source.path));
48178
+ const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync39(source.path));
48074
48179
  if (userLegacyFallback) {
48075
48180
  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.`);
48076
48181
  } else if (legacyUserUnmigrated) {
@@ -50485,6 +50590,7 @@ var init_issue_log_templates_generated = __esm(() => {
50485
50590
  "producer window unknown for \x01: sending unguarded\x020m",
50486
50591
  "producer window unknown for \x01: sending unguarded",
50487
50592
  "[dreamer] user-memories: consumed \x01 candidate(s)",
50593
+ "[image omitted: model does not support vision]\x01:",
50488
50594
  "note-nudge: marked delivered, sticky anchor=\x01 (\x01)\x020i",
50489
50595
  "note-nudge: marked delivered, sticky anchor=\x01 (\x01)",
50490
50596
  "[\x01] \x01: model not found, retrying with suggestion \x01",
@@ -51354,6 +51460,7 @@ var init_issue_log_templates_generated = __esm(() => {
51354
51460
  "retrospective",
51355
51461
  "tag.assignTag",
51356
51462
  "thinking_hold",
51463
+ "conversation\x01:",
51357
51464
  "hidden_child:\x01",
51358
51465
  "poll failed: \x01",
51359
51466
  "tag_revision:\x01\x020s",
@@ -51391,6 +51498,7 @@ var init_issue_log_templates_generated = __esm(() => {
51391
51498
  "excluded\x00",
51392
51499
  "fit_retry",
51393
51500
  "undefined",
51501
+ "toolCall\x01:",
51394
51502
  "[config] \x01",
51395
51503
  "archived",
51396
51504
  "attached",
@@ -51452,9 +51560,9 @@ var init_issue_log_templates_generated = __esm(() => {
51452
51560
  });
51453
51561
 
51454
51562
  // src/lib/log-lines.ts
51455
- import { existsSync as existsSync41, readFileSync as readFileSync24, statSync as statSync22 } from "node:fs";
51563
+ import { existsSync as existsSync40, readFileSync as readFileSync24, statSync as statSync22 } from "node:fs";
51456
51564
  import { tmpdir as tmpdir3 } from "node:os";
51457
- import { join as join32 } from "node:path";
51565
+ import { join as join33 } from "node:path";
51458
51566
  function tokenize(input, limit = Number.POSITIVE_INFINITY) {
51459
51567
  const tokens = [];
51460
51568
  let index = 0;
@@ -51740,16 +51848,16 @@ function parseLogLine(line) {
51740
51848
  }
51741
51849
  function getMagicContextLogPaths(harness, options = {}) {
51742
51850
  const override = options.override === undefined ? process.env.MAGIC_CONTEXT_LOG_PATH?.trim() : options.override?.trim();
51743
- const storageLogs = join32(options.storageDir ?? getMagicContextStorageDir(), "logs");
51851
+ const storageLogs = join33(options.storageDir ?? getMagicContextStorageDir(), "logs");
51744
51852
  return [
51745
51853
  ...override ? [override] : [],
51746
- join32(options.tempDir ?? tmpdir3(), harness, "magic-context", "magic-context.log"),
51747
- join32(storageLogs, `magic-context.${harness}.log`),
51748
- join32(storageLogs, "magic-context.log")
51854
+ join33(options.tempDir ?? tmpdir3(), harness, "magic-context", "magic-context.log"),
51855
+ join33(storageLogs, `magic-context.${harness}.log`),
51856
+ join33(storageLogs, "magic-context.log")
51749
51857
  ].filter((path, index, paths) => paths.indexOf(path) === index);
51750
51858
  }
51751
51859
  function inspectLogFile(path) {
51752
- if (!existsSync41(path)) {
51860
+ if (!existsSync40(path)) {
51753
51861
  return { path, exists: false, sizeKb: 0, lineCount: 0, grammar: "unknown" };
51754
51862
  }
51755
51863
  try {
@@ -52389,8 +52497,8 @@ var init_issue_body = __esm(() => {
52389
52497
  });
52390
52498
 
52391
52499
  // src/lib/omp-hide-secrets.ts
52392
- import { existsSync as existsSync42, readdirSync as readdirSync9, readFileSync as readFileSync25, statSync as statSync23 } from "node:fs";
52393
- import { join as join33, resolve as resolve17 } from "node:path";
52500
+ import { existsSync as existsSync41, readdirSync as readdirSync9, readFileSync as readFileSync25, statSync as statSync23 } from "node:fs";
52501
+ import { join as join34, resolve as resolve18 } from "node:path";
52394
52502
  function stripYamlComment(line) {
52395
52503
  let quote = null;
52396
52504
  for (let index = 0;index < line.length; index += 1) {
@@ -52541,22 +52649,22 @@ function isNonEmptyDirectory(path) {
52541
52649
  function collectHideSecretsSources(cwd, home = envFirstHomeDir()) {
52542
52650
  const sources = [];
52543
52651
  const agentDir = getOmpAgentDir();
52544
- const mainConfig = ["config.yml", "config.yaml"].map((name) => join33(agentDir, name)).find((path) => existsSync42(path));
52652
+ const mainConfig = ["config.yml", "config.yaml"].map((name) => join34(agentDir, name)).find((path) => existsSync41(path));
52545
52653
  if (mainConfig)
52546
52654
  sources.push(readSource("user", mainConfig, "yaml"));
52547
- const projectDir = join33(cwd, ".omp");
52548
- if (resolve17(cwd) !== resolve17(home) && isNonEmptyDirectory(projectDir)) {
52655
+ const projectDir = join34(cwd, ".omp");
52656
+ if (resolve18(cwd) !== resolve18(home) && isNonEmptyDirectory(projectDir)) {
52549
52657
  for (const [name, format] of [
52550
52658
  ["settings.json", "json"],
52551
52659
  ["config.yml", "yaml"]
52552
52660
  ]) {
52553
- const path = join33(projectDir, name);
52554
- if (existsSync42(path))
52661
+ const path = join34(projectDir, name);
52662
+ if (existsSync41(path))
52555
52663
  sources.push(readSource("project", path, format));
52556
52664
  }
52557
52665
  }
52558
52666
  for (const path of getOmpConfigOverlayPaths(cwd)) {
52559
- if (existsSync42(path))
52667
+ if (existsSync41(path))
52560
52668
  sources.push(readSource("overlay", path, "yaml"));
52561
52669
  }
52562
52670
  return sources;
@@ -52614,9 +52722,9 @@ var init_omp_hide_secrets = __esm(() => {
52614
52722
 
52615
52723
  // src/commands/doctor-omp.ts
52616
52724
  import { execFileSync as execFileSync8, spawnSync as spawnSync8 } from "node:child_process";
52617
- import { existsSync as existsSync43, readFileSync as readFileSync26 } from "node:fs";
52725
+ import { existsSync as existsSync42, readFileSync as readFileSync26 } from "node:fs";
52618
52726
  import { createRequire as createRequire3 } from "node:module";
52619
- import { isAbsolute as isAbsolute8, join as join34, resolve as resolve18 } from "node:path";
52727
+ import { isAbsolute as isAbsolute9, join as join35, resolve as resolve19 } from "node:path";
52620
52728
  function parseSemver(value) {
52621
52729
  const match = value?.match(/(\d+)\.(\d+)\.(\d+)/);
52622
52730
  return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
@@ -52658,7 +52766,7 @@ function selfVersion() {
52658
52766
  return "unknown";
52659
52767
  }
52660
52768
  function readConfig2(path) {
52661
- if (!existsSync43(path))
52769
+ if (!existsSync42(path))
52662
52770
  return {};
52663
52771
  try {
52664
52772
  const parsed = import_comment_json8.parse(readFileSync26(path, "utf-8"));
@@ -52671,7 +52779,7 @@ function pluginDeclaresOmp(path) {
52671
52779
  if (!path)
52672
52780
  return null;
52673
52781
  try {
52674
- const pkg = JSON.parse(readFileSync26(join34(path, "package.json"), "utf-8"));
52782
+ const pkg = JSON.parse(readFileSync26(join35(path, "package.json"), "utf-8"));
52675
52783
  return Array.isArray(pkg.omp?.extensions) || Array.isArray(pkg.pi?.extensions);
52676
52784
  } catch {
52677
52785
  return null;
@@ -52748,8 +52856,8 @@ async function runHealthChecks(options) {
52748
52856
  if (!reportedAgentDir.ok) {
52749
52857
  add(results, "warn", "Could not verify OMP active agent directory");
52750
52858
  } else {
52751
- const reportedPath = resolve18(reportedAgentDir.stdout);
52752
- const expectedPath = resolve18(getOmpAgentDir());
52859
+ const reportedPath = resolve19(reportedAgentDir.stdout);
52860
+ const expectedPath = resolve19(getOmpAgentDir());
52753
52861
  if (reportedPath === expectedPath) {
52754
52862
  add(results, "pass", `OMP agent directory resolved to ${getOmpAgentDir()}`);
52755
52863
  } else {
@@ -52760,7 +52868,7 @@ async function runHealthChecks(options) {
52760
52868
  }
52761
52869
  }
52762
52870
  const userConfigPath = getOmpUserConfigPath();
52763
- if (!existsSync43(userConfigPath)) {
52871
+ if (!existsSync42(userConfigPath)) {
52764
52872
  add(results, "warn", `No Magic Context user config at ${userConfigPath}`);
52765
52873
  repairPlan.writeUserConfig = true;
52766
52874
  } else {
@@ -52777,12 +52885,12 @@ async function runHealthChecks(options) {
52777
52885
  for (const warning of loaded.warnings.slice(0, 5))
52778
52886
  add(results, "warn", warning);
52779
52887
  const storage = getMagicContextStorageResolution();
52780
- const dbPath = join34(storage.path, "context.db");
52888
+ const dbPath = join35(storage.path, "context.db");
52781
52889
  if (isMagicContextStorageOutsideEngram(storage.path)) {
52782
52890
  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.`);
52783
52891
  }
52784
52892
  add(results, "info", `Shared storage: ${storage.path} (source: ${storage.source})`);
52785
- if (!existsSync43(dbPath))
52893
+ if (!existsSync42(dbPath))
52786
52894
  add(results, "info", `Shared context DB will be created at ${dbPath}`);
52787
52895
  else {
52788
52896
  let db = null;
@@ -52847,7 +52955,7 @@ function writeDefaultConfig(path) {
52847
52955
  }
52848
52956
  async function repair(plan, deps, prompts, cwd) {
52849
52957
  let fixed = 0;
52850
- if (plan.writeUserConfig && !existsSync43(getOmpUserConfigPath())) {
52958
+ if (plan.writeUserConfig && !existsSync42(getOmpUserConfigPath())) {
52851
52959
  writeDefaultConfig(getOmpUserConfigPath());
52852
52960
  prompts.log.success(`Wrote default Magic Context config to ${getOmpUserConfigPath()}`);
52853
52961
  fixed += 1;
@@ -52960,7 +53068,7 @@ function runGhCommandWithDeps(deps, args) {
52960
53068
  async function runIssueFlow(options) {
52961
53069
  if (options.reportPath) {
52962
53070
  const report = await runHealthChecks({ ...options, quiet: true });
52963
- const path = isAbsolute8(options.reportPath) ? options.reportPath : join34(options.cwd, options.reportPath);
53071
+ const path = isAbsolute9(options.reportPath) ? options.reportPath : join35(options.cwd, options.reportPath);
52964
53072
  const bundle = writeOmpIssueReport(path, ompIssueBody("Generated non-interactively by `doctor --issue --report`.", report, readLogLines(report.logFiles), null, options.cwd));
52965
53073
  options.prompts.log.success(bundle.fullPath ? `Sanitized report written to ${bundle.path}; full report at ${bundle.fullPath}` : `Sanitized report written to ${bundle.path}`);
52966
53074
  return 0;
@@ -52987,7 +53095,7 @@ async function runIssueFlow(options) {
52987
53095
  ]);
52988
53096
  sessionFilter = choice === "__all__" ? null : choice;
52989
53097
  }
52990
- const path = join34(options.cwd, `magic-context-omp-issue-${timestamp2(options.deps.now())}.md`);
53098
+ const path = join35(options.cwd, `magic-context-omp-issue-${timestamp2(options.deps.now())}.md`);
52991
53099
  const bundle = writeOmpIssueReport(path, ompIssueBody(description, report, logLines, sessionFilter, options.cwd));
52992
53100
  options.prompts.log.success(bundle.fullPath ? `Sanitized report written to ${bundle.path}; full report at ${bundle.fullPath}` : `Sanitized report written to ${bundle.path}`);
52993
53101
  if (await options.prompts.confirm("Submit this issue on GitHub now?", false)) {
@@ -53973,9 +54081,9 @@ function listShadowBackfillStalls(db, projectIdentity) {
53973
54081
  var SHADOW_BACKFILL_PROVENANCE_KEY = "_magicContextShadowBackfill";
53974
54082
 
53975
54083
  // ../plugin/src/shared/auto-update-provenance.ts
53976
- import { existsSync as existsSync44, readFileSync as readFileSync27 } from "node:fs";
54084
+ import { existsSync as existsSync43, readFileSync as readFileSync27 } from "node:fs";
53977
54085
  function readAutoUpdateCheckState(path) {
53978
- if (!existsSync44(path))
54086
+ if (!existsSync43(path))
53979
54087
  return null;
53980
54088
  try {
53981
54089
  const value = JSON.parse(readFileSync27(path, "utf-8"));
@@ -54006,14 +54114,14 @@ var init_auto_update_provenance = () => {};
54006
54114
  // ../plugin/src/shared/tui-config.ts
54007
54115
  import {
54008
54116
  chmodSync as chmodSync4,
54009
- existsSync as existsSync45,
54117
+ existsSync as existsSync44,
54010
54118
  mkdirSync as mkdirSync8,
54011
54119
  readFileSync as readFileSync28,
54012
54120
  renameSync as renameSync8,
54013
54121
  statSync as statSync24,
54014
54122
  writeFileSync as writeFileSync8
54015
54123
  } from "node:fs";
54016
- import { dirname as dirname24, join as join35 } from "node:path";
54124
+ import { dirname as dirname24, join as join36 } from "node:path";
54017
54125
  function pluginEntryId(entry) {
54018
54126
  if (typeof entry === "string")
54019
54127
  return entry;
@@ -54054,11 +54162,11 @@ function writeTuiConfigAtomic(configPath, config) {
54054
54162
  }
54055
54163
  function resolveTuiConfigPath(configDirOverride) {
54056
54164
  const configDir = configDirOverride ?? getOpenCodeConfigPaths({ binary: "opencode" }).configDir;
54057
- const jsoncPath = join35(configDir, "tui.jsonc");
54058
- const jsonPath = join35(configDir, "tui.json");
54059
- if (existsSync45(jsoncPath))
54165
+ const jsoncPath = join36(configDir, "tui.jsonc");
54166
+ const jsonPath = join36(configDir, "tui.json");
54167
+ if (existsSync44(jsoncPath))
54060
54168
  return jsoncPath;
54061
- if (existsSync45(jsonPath))
54169
+ if (existsSync44(jsonPath))
54062
54170
  return jsonPath;
54063
54171
  return jsoncPath;
54064
54172
  }
@@ -54066,7 +54174,7 @@ function ensureTuiPluginEntry(options = {}) {
54066
54174
  try {
54067
54175
  const configPath = resolveTuiConfigPath(options.configDir);
54068
54176
  let config = {};
54069
- if (existsSync45(configPath)) {
54177
+ if (existsSync44(configPath)) {
54070
54178
  const raw = readFileSync28(configPath, "utf-8");
54071
54179
  config = import_comment_json9.parse(raw) ?? {};
54072
54180
  }
@@ -54119,14 +54227,14 @@ var init_tui_config = __esm(() => {
54119
54227
  });
54120
54228
 
54121
54229
  // src/lib/historian-dump-dirs.ts
54122
- import { existsSync as existsSync46, readdirSync as readdirSync10, statSync as statSync25 } from "node:fs";
54123
- import { join as join36 } from "node:path";
54230
+ import { existsSync as existsSync45, readdirSync as readdirSync10, statSync as statSync25 } from "node:fs";
54231
+ import { join as join37 } from "node:path";
54124
54232
  function scanHistorianDumpFiles(dir) {
54125
- if (!existsSync46(dir))
54233
+ if (!existsSync45(dir))
54126
54234
  return [];
54127
54235
  try {
54128
54236
  return readdirSync10(dir).filter((name) => name.endsWith(".xml")).map((name) => {
54129
- const stat = statSync25(join36(dir, name));
54237
+ const stat = statSync25(join37(dir, name));
54130
54238
  return { name, mtime: stat.mtimeMs, sizeKb: Math.round(stat.size / 1024) };
54131
54239
  }).sort((a, b) => b.mtime - a.mtime);
54132
54240
  } catch {
@@ -54134,14 +54242,14 @@ function scanHistorianDumpFiles(dir) {
54134
54242
  }
54135
54243
  }
54136
54244
  function scanHistorianSessionDumpDirs(root) {
54137
- if (!existsSync46(root))
54245
+ if (!existsSync45(root))
54138
54246
  return [];
54139
54247
  const sessions = [];
54140
54248
  try {
54141
54249
  for (const entry of readdirSync10(root, { withFileTypes: true })) {
54142
54250
  if (!entry.isDirectory())
54143
54251
  continue;
54144
- const dir = join36(root, entry.name);
54252
+ const dir = join37(root, entry.name);
54145
54253
  const files = scanHistorianDumpFiles(dir);
54146
54254
  if (files.length > 0)
54147
54255
  sessions.push({ sessionId: entry.name, dir, files });
@@ -54154,9 +54262,9 @@ function scanHistorianSessionDumpDirs(root) {
54154
54262
  var init_historian_dump_dirs = () => {};
54155
54263
 
54156
54264
  // src/lib/diagnostics-opencode.ts
54157
- import { existsSync as existsSync47, readFileSync as readFileSync29, statSync as statSync26 } from "node:fs";
54265
+ import { existsSync as existsSync46, readFileSync as readFileSync29, statSync as statSync26 } from "node:fs";
54158
54266
  import { createRequire as createRequire4 } from "node:module";
54159
- import { join as join37 } from "node:path";
54267
+ import { join as join38 } from "node:path";
54160
54268
  function getSelfVersion() {
54161
54269
  const require2 = createRequire4(import.meta.url);
54162
54270
  for (const relPath of ["../../package.json", "../package.json"]) {
@@ -54180,7 +54288,7 @@ function readLegacyCachedVersion(root) {
54180
54288
  function collectOpenCodePluginCacheReport(hostGeneration, opencodeConfig, npmVersions = {}) {
54181
54289
  const installs = [];
54182
54290
  for (const root of getOpenCodePluginCacheRoots()) {
54183
- if (!existsSync47(root))
54291
+ if (!existsSync46(root))
54184
54292
  continue;
54185
54293
  const spec = root.endsWith("@latest") ? "latest" : "(bare)";
54186
54294
  installs.push({
@@ -54228,7 +54336,7 @@ function getStorageResolution() {
54228
54336
  }
54229
54337
  function fileSize(path) {
54230
54338
  try {
54231
- return existsSync47(path) ? statSync26(path).size : 0;
54339
+ return existsSync46(path) ? statSync26(path).size : 0;
54232
54340
  } catch {
54233
54341
  return 0;
54234
54342
  }
@@ -54240,7 +54348,7 @@ function sanitizeValue(value) {
54240
54348
  return sanitizeConfigValue(value);
54241
54349
  }
54242
54350
  function readConfig3(path) {
54243
- if (!existsSync47(path))
54351
+ if (!existsSync46(path))
54244
54352
  return { value: null };
54245
54353
  try {
54246
54354
  const raw = readFileSync29(path, "utf-8");
@@ -54303,7 +54411,7 @@ function parseHistorianDumpMeta(path) {
54303
54411
  function summarizeDumps(dir, files, limit) {
54304
54412
  const now = Date.now();
54305
54413
  return files.slice(0, limit).map((entry) => {
54306
- const meta = parseHistorianDumpMeta(join37(dir, entry.name));
54414
+ const meta = parseHistorianDumpMeta(join38(dir, entry.name));
54307
54415
  const summary = {
54308
54416
  name: entry.name,
54309
54417
  ageMinutes: Math.round((now - entry.mtime) / 60000),
@@ -54424,7 +54532,7 @@ function collectRecentSessionsFromDatabase(database) {
54424
54532
  });
54425
54533
  }
54426
54534
  async function collectDatabaseRows(path, read) {
54427
- if (!existsSync47(path))
54535
+ if (!existsSync46(path))
54428
54536
  return { available: false, reason: "path missing" };
54429
54537
  let backend;
54430
54538
  try {
@@ -54456,7 +54564,7 @@ async function collectRecentSessions(resolution, hostGeneration) {
54456
54564
  });
54457
54565
  }
54458
54566
  async function collectHistorianFailures(storageDirPath) {
54459
- return collectDatabaseRows(join37(storageDirPath, "context.db"), (db) => {
54567
+ return collectDatabaseRows(join38(storageDirPath, "context.db"), (db) => {
54460
54568
  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();
54461
54569
  return rows.map((row) => {
54462
54570
  const sessionId = typeof row.session_id === "string" ? row.session_id : "<unknown>";
@@ -54469,7 +54577,7 @@ async function collectHistorianFailures(storageDirPath) {
54469
54577
  });
54470
54578
  }
54471
54579
  async function collectHistorianRuns(storageDirPath) {
54472
- return collectDatabaseRows(join37(storageDirPath, "context.db"), (db) => {
54580
+ return collectDatabaseRows(join38(storageDirPath, "context.db"), (db) => {
54473
54581
  const aggRows = db.prepare(`SELECT session_id,
54474
54582
  COUNT(*) AS total,
54475
54583
  SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) AS success,
@@ -54524,7 +54632,7 @@ async function collectDiagnostics(options = {}) {
54524
54632
  const magicContextConfig = readConfig3(configPaths.magicContextConfig);
54525
54633
  const storageResolution = getStorageResolution();
54526
54634
  const storageDirPath = storageResolution.path;
54527
- const contextDbPath = join37(storageDirPath, "context.db");
54635
+ const contextDbPath = join38(storageDirPath, "context.db");
54528
54636
  let compactionEnabled = false;
54529
54637
  try {
54530
54638
  compactionEnabled = isCompactionEnabled(loadPluginConfig(process.cwd()));
@@ -54556,7 +54664,7 @@ async function collectDiagnostics(options = {}) {
54556
54664
  opencodeConfigHasPlugin: configHasPluginEntry(opencodeConfig.value),
54557
54665
  tuiConfigHasPlugin: configHasPluginEntry(tuiConfig.value),
54558
54666
  magicContextConfig: {
54559
- exists: existsSync47(configPaths.magicContextConfig),
54667
+ exists: existsSync46(configPaths.magicContextConfig),
54560
54668
  ...magicContextConfig.error ? { parseError: magicContextConfig.error } : {},
54561
54669
  flags: sanitizeValue(magicContextConfig.value ?? {}) ?? {}
54562
54670
  },
@@ -54564,7 +54672,7 @@ async function collectDiagnostics(options = {}) {
54564
54672
  storageDir: {
54565
54673
  path: storageDirPath,
54566
54674
  source: storageResolution.source,
54567
- exists: existsSync47(storageDirPath),
54675
+ exists: existsSync46(storageDirPath),
54568
54676
  contextDbSizeBytes: fileSize(contextDbPath)
54569
54677
  },
54570
54678
  openCodeDatabase: {
@@ -54845,9 +54953,9 @@ var init_embedding_local = __esm(async () => {
54845
54953
 
54846
54954
  // src/lib/embedding-runtime.ts
54847
54955
  import { spawnSync as spawnSync9 } from "node:child_process";
54848
- import { existsSync as existsSync48, readFileSync as readFileSync30 } from "node:fs";
54956
+ import { existsSync as existsSync47, readFileSync as readFileSync30 } from "node:fs";
54849
54957
  import { createRequire as createRequire5 } from "node:module";
54850
- import { dirname as dirname25, join as join38, sep as sep2 } from "node:path";
54958
+ import { dirname as dirname25, join as join39, sep as sep3 } from "node:path";
54851
54959
  function describeError(error) {
54852
54960
  const message = error instanceof Error ? error.message : String(error ?? "unknown error");
54853
54961
  const code = error?.code;
@@ -54989,11 +55097,11 @@ function expectedBinaryRelPath(platform, arch) {
54989
55097
  const supportedArch = arch === "x64" || arch === "arm64";
54990
55098
  if (!supportedPlatform || !supportedArch)
54991
55099
  return null;
54992
- return join38("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
55100
+ return join39("bin", "napi-v6", platform, arch, "onnxruntime_binding.node");
54993
55101
  }
54994
55102
  function onnxRuntimeNodeVersion(packageDir) {
54995
55103
  try {
54996
- const parsed = JSON.parse(readFileSync30(join38(packageDir, "package.json"), "utf8"));
55104
+ const parsed = JSON.parse(readFileSync30(join39(packageDir, "package.json"), "utf8"));
54997
55105
  return typeof parsed.version === "string" ? parsed.version : undefined;
54998
55106
  } catch {
54999
55107
  return;
@@ -55042,7 +55150,7 @@ function formatLocalEmbeddingRuntimeWasmSelected(status) {
55042
55150
  function requireNodeWasmBundle(probe, candidates) {
55043
55151
  if (probe.state === "failed")
55044
55152
  return probe;
55045
- const bundlePath = candidates.find((candidate) => existsSync48(candidate));
55153
+ const bundlePath = candidates.find((candidate) => existsSync47(candidate));
55046
55154
  return bundlePath ? probe : {
55047
55155
  state: "failed",
55048
55156
  reason: `functional Node WASM Transformers bundle is missing (checked ${candidates.join(", ")})`
@@ -55050,13 +55158,13 @@ function requireNodeWasmBundle(probe, candidates) {
55050
55158
  }
55051
55159
  function nodeWasmBundleCandidates(installRoot) {
55052
55160
  return [
55053
- join38(installRoot, "dist", "transformers-node-wasm.js"),
55054
- join38(installRoot, "node_modules", "@cortexkit", "opencode-magic-context", "dist", "transformers-node-wasm.js"),
55055
- join38(installRoot, "node_modules", "@cortexkit", "pi-magic-context", "dist", "transformers-node-wasm.js")
55161
+ join39(installRoot, "dist", "transformers-node-wasm.js"),
55162
+ join39(installRoot, "node_modules", "@cortexkit", "opencode-magic-context", "dist", "transformers-node-wasm.js"),
55163
+ join39(installRoot, "node_modules", "@cortexkit", "pi-magic-context", "dist", "transformers-node-wasm.js")
55056
55164
  ];
55057
55165
  }
55058
55166
  function probeWasmRuntimeAt(installRoot) {
55059
- const requireFn = createRequire5(join38(installRoot, "package.json"));
55167
+ const requireFn = createRequire5(join39(installRoot, "package.json"));
55060
55168
  return requireNodeWasmBundle(probeWasmRuntimeFromRequire(requireFn), nodeWasmBundleCandidates(installRoot));
55061
55169
  }
55062
55170
  function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
@@ -55065,9 +55173,9 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
55065
55173
  const wasm = probeWasmRuntimeAt(installRoot);
55066
55174
  return wasm.state === "ok" ? { state: "wasm-selected", wasmPath: wasm.wasmPath } : { state: "wasm-broken", wasmReason: wasm.reason };
55067
55175
  }
55068
- const packageDir = join38(installRoot, "node_modules", "onnxruntime-node");
55176
+ const packageDir = join39(installRoot, "node_modules", "onnxruntime-node");
55069
55177
  let native;
55070
- if (!existsSync48(join38(packageDir, "package.json"))) {
55178
+ if (!existsSync47(join39(packageDir, "package.json"))) {
55071
55179
  native = { state: "package-missing", packageDir };
55072
55180
  } else {
55073
55181
  const rel = expectedBinaryRelPath(platform, arch);
@@ -55077,8 +55185,8 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
55077
55185
  binaryPath: packageDir
55078
55186
  };
55079
55187
  } else {
55080
- const binaryPath = join38(packageDir, rel);
55081
- native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
55188
+ const binaryPath = join39(packageDir, rel);
55189
+ native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
55082
55190
  state: "binary-missing",
55083
55191
  packageDir,
55084
55192
  expectedBinary: binaryPath,
@@ -55089,7 +55197,7 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
55089
55197
  return withWasmFallback(native, () => probeWasmRuntimeAt(installRoot));
55090
55198
  }
55091
55199
  function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
55092
- const existing = installRoots.filter((root) => existsSync48(root));
55200
+ const existing = installRoots.filter((root) => existsSync47(root));
55093
55201
  if (existing.length === 0) {
55094
55202
  return {
55095
55203
  state: "unknown",
@@ -55113,21 +55221,21 @@ function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, a
55113
55221
  return firstFallback ?? firstFailure ?? { state: "unknown", reason: "no candidate roots" };
55114
55222
  }
55115
55223
  function packageDirFromResolved(resolvedPath, packageName) {
55116
- const marker = `node_modules${sep2}${packageName.split("/").join(sep2)}`;
55224
+ const marker = `node_modules${sep3}${packageName.split("/").join(sep3)}`;
55117
55225
  const idx = resolvedPath.indexOf(marker);
55118
55226
  return idx >= 0 ? resolvedPath.slice(0, idx + marker.length) : dirname25(resolvedPath);
55119
55227
  }
55120
55228
  function probeWasmRuntimeByResolution(pluginDir) {
55121
55229
  try {
55122
- const reqPlugin = createRequire5(join38(pluginDir, "package.json"));
55230
+ const reqPlugin = createRequire5(join39(pluginDir, "package.json"));
55123
55231
  const direct = probeWasmRuntimeFromRequire(reqPlugin);
55124
55232
  let probe = direct;
55125
55233
  if (direct.state === "failed" && direct.reason.startsWith("onnxruntime-web is not resolvable")) {
55126
55234
  const tfResolved = reqPlugin.resolve("@huggingface/transformers");
55127
55235
  const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
55128
- probe = probeWasmRuntimeFromRequire(createRequire5(join38(tfDir, "package.json")));
55236
+ probe = probeWasmRuntimeFromRequire(createRequire5(join39(tfDir, "package.json")));
55129
55237
  }
55130
- return requireNodeWasmBundle(probe, [join38(pluginDir, "dist", "transformers-node-wasm.js")]);
55238
+ return requireNodeWasmBundle(probe, [join39(pluginDir, "dist", "transformers-node-wasm.js")]);
55131
55239
  } catch (error) {
55132
55240
  return {
55133
55241
  state: "failed",
@@ -55136,7 +55244,7 @@ function probeWasmRuntimeByResolution(pluginDir) {
55136
55244
  }
55137
55245
  }
55138
55246
  function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
55139
- if (!existsSync48(join38(pluginDir, "package.json"))) {
55247
+ if (!existsSync47(join39(pluginDir, "package.json"))) {
55140
55248
  return { state: "unknown", reason: "plugin package dir not found" };
55141
55249
  }
55142
55250
  const selectedRuntime = resolveLocalEmbeddingWorkerRuntime(runtimePreference, host);
@@ -55147,13 +55255,13 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
55147
55255
  let onnxDir = null;
55148
55256
  let resolveError;
55149
55257
  try {
55150
- const reqPlugin = createRequire5(join38(pluginDir, "package.json"));
55258
+ const reqPlugin = createRequire5(join39(pluginDir, "package.json"));
55151
55259
  try {
55152
55260
  onnxDir = packageDirFromResolved(reqPlugin.resolve("onnxruntime-node"), "onnxruntime-node");
55153
55261
  } catch {
55154
55262
  const tfResolved = reqPlugin.resolve("@huggingface/transformers");
55155
55263
  const tfDir = packageDirFromResolved(tfResolved, "@huggingface/transformers");
55156
- const reqTf = createRequire5(join38(tfDir, "package.json"));
55264
+ const reqTf = createRequire5(join39(tfDir, "package.json"));
55157
55265
  onnxDir = packageDirFromResolved(reqTf.resolve("onnxruntime-node"), "onnxruntime-node");
55158
55266
  }
55159
55267
  } catch (error) {
@@ -55161,7 +55269,7 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
55161
55269
  if (resolveError === "ERR_MODULE_NOT_FOUND" || resolveError === "MODULE_NOT_FOUND") {
55162
55270
  return withWasmFallback({
55163
55271
  state: "package-missing",
55164
- packageDir: join38(pluginDir, "node_modules", "onnxruntime-node")
55272
+ packageDir: join39(pluginDir, "node_modules", "onnxruntime-node")
55165
55273
  }, () => probeWasmRuntimeByResolution(pluginDir));
55166
55274
  }
55167
55275
  return {
@@ -55177,8 +55285,8 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
55177
55285
  if (rel === null) {
55178
55286
  native = probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath: onnxDir };
55179
55287
  } else {
55180
- const binaryPath = join38(onnxDir, rel);
55181
- native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
55288
+ const binaryPath = join39(onnxDir, rel);
55289
+ native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
55182
55290
  state: "binary-missing",
55183
55291
  packageDir: onnxDir,
55184
55292
  expectedBinary: binaryPath,
@@ -55214,7 +55322,7 @@ var init_embedding_runtime = __esm(async () => {
55214
55322
 
55215
55323
  // src/lib/logs-opencode.ts
55216
55324
  import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync9 } from "node:fs";
55217
- import { dirname as dirname26, join as join39 } from "node:path";
55325
+ import { dirname as dirname26, join as join40 } from "node:path";
55218
55326
  function formatTimestamp(date) {
55219
55327
  const pad = (value) => String(value).padStart(2, "0");
55220
55328
  return [
@@ -55305,11 +55413,11 @@ async function bundleIssueReport(report, description, title, sessionFilter = nul
55305
55413
  const bodyMarkdown = capBodyToGithubLimit(rawBodyMarkdown);
55306
55414
  const truncated = bodyMarkdown !== rawBodyMarkdown;
55307
55415
  const timestamp = formatTimestamp(new Date);
55308
- const path = options.outputPath ?? join39(process.cwd(), `magic-context-issue-${timestamp}.md`);
55416
+ const path = options.outputPath ?? join40(process.cwd(), `magic-context-issue-${timestamp}.md`);
55309
55417
  mkdirSync9(dirname26(path), { recursive: true });
55310
55418
  writeFileSync9(path, `${bodyMarkdown}
55311
55419
  `);
55312
- const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join39(process.cwd(), `magic-context-issue-${timestamp}-full.md`) : undefined;
55420
+ const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join40(process.cwd(), `magic-context-issue-${timestamp}-full.md`) : undefined;
55313
55421
  if (fullPath)
55314
55422
  writeFileSync9(fullPath, `${rawBodyMarkdown}
55315
55423
  `);
@@ -56130,10 +56238,10 @@ function removeDeprecatedReasoningAge(config) {
56130
56238
 
56131
56239
  // src/commands/doctor-opencode.ts
56132
56240
  import { spawnSync as spawnSync10 } from "node:child_process";
56133
- import { existsSync as existsSync49, mkdtempSync as mkdtempSync4, readFileSync as readFileSync31, rmSync as rmSync9 } from "node:fs";
56241
+ import { existsSync as existsSync48, mkdtempSync as mkdtempSync4, readFileSync as readFileSync31, rmSync as rmSync9 } from "node:fs";
56134
56242
  import { createRequire as createRequire6 } from "node:module";
56135
56243
  import { homedir as homedir21, tmpdir as tmpdir4 } from "node:os";
56136
- import { dirname as dirname27, join as join40, resolve as resolve19 } from "node:path";
56244
+ import { dirname as dirname27, join as join41, resolve as resolve20 } from "node:path";
56137
56245
  function formatSharedDbRowCounts(db) {
56138
56246
  return SHARED_DB_ROW_COUNT_TABLES.map((table) => {
56139
56247
  try {
@@ -56204,7 +56312,7 @@ function checkConfiguredVariantCatalog(config, hostGeneration, warn, run = (args
56204
56312
  }
56205
56313
  if (models.length === 0)
56206
56314
  return;
56207
- const tempRoot = mkdtempSync4(join40(tmpdir4(), "magic-context-opencode-catalog-"));
56315
+ const tempRoot = mkdtempSync4(join41(tmpdir4(), "magic-context-opencode-catalog-"));
56208
56316
  try {
56209
56317
  const command = hostGeneration === "v2" ? ["api", "model.list", "--param", `directory=${projectDir}`] : ["models", "--verbose"];
56210
56318
  const guidance = `opencode ${command.join(" ")}`;
@@ -56380,7 +56488,7 @@ function getSelfVersion2() {
56380
56488
  function describeAutoUpdateStall(specifier, autoUpdateEnabled, storageDir = getMagicContextStorageDir()) {
56381
56489
  if (!autoUpdateEnabled || !isPinnedOpenCodePluginSpecifier(specifier))
56382
56490
  return null;
56383
- const state = readAutoUpdateCheckState(join40(storageDir, AUTO_UPDATE_CHECK_STATE_FILENAME));
56491
+ const state = readAutoUpdateCheckState(join41(storageDir, AUTO_UPDATE_CHECK_STATE_FILENAME));
56384
56492
  const owner = isUpdaterPinnedSpec(state, specifier) ? "updater" : "you";
56385
56493
  return `auto-update: stalled — config pinned to ${specifier} (by ${owner})`;
56386
56494
  }
@@ -56389,12 +56497,12 @@ function getUserNpmrcPath() {
56389
56497
  if (custom)
56390
56498
  return custom;
56391
56499
  const home = process.env.HOME?.trim();
56392
- return join40(home || homedir21(), ".npmrc");
56500
+ return join41(home || homedir21(), ".npmrc");
56393
56501
  }
56394
56502
  function collectNpmReleaseAgeWarnings() {
56395
56503
  const ageWarnings = [];
56396
56504
  const npmrcPath = getUserNpmrcPath();
56397
- if (!existsSync49(npmrcPath))
56505
+ if (!existsSync48(npmrcPath))
56398
56506
  return ageWarnings;
56399
56507
  try {
56400
56508
  const npmrc = readFileSync31(npmrcPath, "utf-8");
@@ -56488,7 +56596,7 @@ async function runIssueFlow2(options = {}, deps = { collectDiagnostics }) {
56488
56596
  await warnOutdatedBeforeIssue(freshness, { platform, interactive: false });
56489
56597
  try {
56490
56598
  const report = await deps.collectDiagnostics({ npmVersions: freshness.npmVersions });
56491
- const bundled = await bundleIssueReport(report, "Generated non-interactively by `doctor --issue --report`.", "Magic Context diagnostic report", null, { outputPath: resolve19(process.cwd(), options.reportPath) });
56599
+ const bundled = await bundleIssueReport(report, "Generated non-interactively by `doctor --issue --report`.", "Magic Context diagnostic report", null, { outputPath: resolve20(process.cwd(), options.reportPath) });
56492
56600
  log3.info(bundled.fullPath ? `Report written to ${bundled.path}; full bundle at ${bundled.fullPath}` : `Report written to ${bundled.path}`);
56493
56601
  return 0;
56494
56602
  } catch (error) {
@@ -56586,7 +56694,7 @@ function checkLocalEmbeddingRuntimeForDoctor(installRoots, runtimePreference = "
56586
56694
  return { issues: 0 };
56587
56695
  }
56588
56696
  async function checkEmbeddingConfig(magicContextConfigPath, installRoots) {
56589
- if (!existsSync49(magicContextConfigPath)) {
56697
+ if (!existsSync48(magicContextConfigPath)) {
56590
56698
  return checkLocalEmbeddingRuntimeForDoctor(installRoots);
56591
56699
  }
56592
56700
  let rawText;
@@ -56767,7 +56875,7 @@ async function runDoctor2(options = {}) {
56767
56875
  const v22Result = await runV22BackfillCommands({
56768
56876
  name: "OpenCode",
56769
56877
  openDatabase: (readonly = true) => {
56770
- const dbPath = join40(getMagicContextStorageDir(), "context.db");
56878
+ const dbPath = join41(getMagicContextStorageDir(), "context.db");
56771
56879
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
56772
56880
  return v22Db;
56773
56881
  },
@@ -56803,7 +56911,7 @@ async function runDoctor2(options = {}) {
56803
56911
  if (isMagicContextStorageOutsideEngram(storageDir)) {
56804
56912
  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.`);
56805
56913
  }
56806
- const authorityDbPath = join40(getMagicContextStorageDir(), "context.db");
56914
+ const authorityDbPath = join41(getMagicContextStorageDir(), "context.db");
56807
56915
  let authorityDb = null;
56808
56916
  try {
56809
56917
  authorityDb = openExistingContextDatabase(authorityDbPath, { readonly: true });
@@ -56978,7 +57086,7 @@ async function runDoctor2(options = {}) {
56978
57086
  pass(`OpenCode config: ${paths.opencodeConfig}`);
56979
57087
  }
56980
57088
  let autoUpdateEnabled = true;
56981
- if (existsSync49(paths.magicContextConfig)) {
57089
+ if (existsSync48(paths.magicContextConfig)) {
56982
57090
  pass(`Magic Context config: ${paths.magicContextConfig}`);
56983
57091
  try {
56984
57092
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
@@ -57016,7 +57124,7 @@ async function runDoctor2(options = {}) {
57016
57124
  log3.info(rerankConfigSummary());
57017
57125
  log3.info(" Run 'setup' to create one with model recommendations");
57018
57126
  }
57019
- if (existsSync49(paths.magicContextConfig)) {
57127
+ if (existsSync48(paths.magicContextConfig)) {
57020
57128
  try {
57021
57129
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
57022
57130
  if (!raw)
@@ -57249,7 +57357,7 @@ async function runDoctor2(options = {}) {
57249
57357
  pass("Added TUI sidebar plugin to tui.json");
57250
57358
  warn("Restart OpenCode to see the sidebar");
57251
57359
  fixed++;
57252
- } else if (existsSync49(paths.tuiConfig)) {
57360
+ } else if (existsSync48(paths.tuiConfig)) {
57253
57361
  try {
57254
57362
  const tuiRaw = readFileSync31(paths.tuiConfig, "utf-8");
57255
57363
  const tuiConfig = import_comment_json11.parse(tuiRaw);
@@ -57290,7 +57398,7 @@ async function runDoctor2(options = {}) {
57290
57398
  fail("Could not create or verify the TUI sidebar config");
57291
57399
  }
57292
57400
  }
57293
- if (existsSync49(paths.magicContextConfig)) {
57401
+ if (existsSync48(paths.magicContextConfig)) {
57294
57402
  try {
57295
57403
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
57296
57404
  if (!raw)
@@ -57309,7 +57417,7 @@ async function runDoctor2(options = {}) {
57309
57417
  embeddingHostConfig = import_comment_json11.parse(readFileSync31(paths.opencodeConfig, "utf-8"));
57310
57418
  } catch {}
57311
57419
  const embeddingInstalls = getOpenCodeLoadedPluginInstallRoots(hostGeneration, embeddingHostConfig);
57312
- const unusedInstalls = embeddingInstalls.others.filter((root) => existsSync49(root));
57420
+ const unusedInstalls = embeddingInstalls.others.filter((root) => existsSync48(root));
57313
57421
  if (unusedInstalls.length > 0)
57314
57422
  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(", ")}`);
57315
57423
  const embeddingCheck = await checkEmbeddingConfig(paths.magicContextConfig, embeddingInstalls.loaded);
@@ -57321,9 +57429,9 @@ async function runDoctor2(options = {}) {
57321
57429
  else
57322
57430
  passCount++;
57323
57431
  const storage = getMagicContextStorageResolution();
57324
- const dbPath = join40(storage.path, "context.db");
57432
+ const dbPath = join41(storage.path, "context.db");
57325
57433
  log3.info(`Shared storage: ${storage.path} (source: ${storage.source})`);
57326
- if (!existsSync49(dbPath)) {
57434
+ if (!existsSync48(dbPath)) {
57327
57435
  log3.info(`Shared context DB not yet created at ${dbPath} (will be created on first run)`);
57328
57436
  } else {
57329
57437
  log3.info(`Shared context DB exists at ${dbPath}`);
@@ -57415,6 +57523,8 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
57415
57523
  hostFiles: openCodeHostDatabaseFiles([openCodeDbResolution.path]),
57416
57524
  referencedSpecs: pluginConfigUse?.referencedSpecs.opencode1
57417
57525
  });
57526
+ for (const warning of cacheResult.skippedWarnings ?? [])
57527
+ warn(warning);
57418
57528
  if (cacheResult.action === "unused") {
57419
57529
  log3.info(describeUnusedOpenCodePluginCache({
57420
57530
  host: "OpenCode 1",
@@ -57452,7 +57562,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
57452
57562
  log3.info(` Manually delete: ${cacheResult.path}`);
57453
57563
  }
57454
57564
  issues++;
57455
- } else if (hostGeneration !== "v2") {
57565
+ } else if (cacheResult.action === "not_found" && hostGeneration !== "v2") {
57456
57566
  pass("Plugin cache clean (no cached version found)");
57457
57567
  }
57458
57568
  let v2DistTag;
@@ -57878,9 +57988,9 @@ var init_model_chain_health = __esm(() => {
57878
57988
  });
57879
57989
 
57880
57990
  // src/lib/diagnostics-pi.ts
57881
- import { existsSync as existsSync50, readdirSync as readdirSync11, readFileSync as readFileSync32, statSync as statSync27 } from "node:fs";
57991
+ import { existsSync as existsSync49, readdirSync as readdirSync11, readFileSync as readFileSync32, statSync as statSync27 } from "node:fs";
57882
57992
  import { createRequire as createRequire7 } from "node:module";
57883
- import { join as join41 } from "node:path";
57993
+ import { join as join42 } from "node:path";
57884
57994
  function getSelfVersion3() {
57885
57995
  const req = createRequire7(import.meta.url);
57886
57996
  for (const relPath of ["../../package.json", "../package.json"]) {
@@ -57895,7 +58005,7 @@ function getSelfVersion3() {
57895
58005
  }
57896
58006
  function fileSize2(path) {
57897
58007
  try {
57898
- return existsSync50(path) ? statSync27(path).size : 0;
58008
+ return existsSync49(path) ? statSync27(path).size : 0;
57899
58009
  } catch {
57900
58010
  return 0;
57901
58011
  }
@@ -57907,7 +58017,7 @@ function sanitizeValue2(value) {
57907
58017
  return sanitizeConfigValue(value);
57908
58018
  }
57909
58019
  function readJsonc(path) {
57910
- if (!existsSync50(path))
58020
+ if (!existsSync49(path))
57911
58021
  return { value: {} };
57912
58022
  try {
57913
58023
  return {
@@ -57927,7 +58037,7 @@ function readConfigDiagnostic(path) {
57927
58037
  const parsed = readJsonc(path);
57928
58038
  return {
57929
58039
  path,
57930
- exists: existsSync50(path),
58040
+ exists: existsSync49(path),
57931
58041
  ...parsed.parseError ? { parseError: parsed.parseError } : {},
57932
58042
  flags: sanitizeValue2(parsed.value)
57933
58043
  };
@@ -57945,7 +58055,7 @@ function reverseSlugToDirectory(slug) {
57945
58055
  }
57946
58056
  function collectPiRecentSessions() {
57947
58057
  const sessionsRoot = getPiSessionsRoot();
57948
- if (!existsSync50(sessionsRoot))
58058
+ if (!existsSync49(sessionsRoot))
57949
58059
  return [];
57950
58060
  try {
57951
58061
  const slugs = readdirSync11(sessionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
@@ -57954,7 +58064,7 @@ function collectPiRecentSessions() {
57954
58064
  const directory = reverseSlugToDirectory(slug);
57955
58065
  if (!directory)
57956
58066
  continue;
57957
- const slugDir = join41(sessionsRoot, slug);
58067
+ const slugDir = join42(sessionsRoot, slug);
57958
58068
  let files;
57959
58069
  try {
57960
58070
  files = readdirSync11(slugDir).filter((name) => name.endsWith(".jsonl"));
@@ -57963,7 +58073,7 @@ function collectPiRecentSessions() {
57963
58073
  }
57964
58074
  for (const file of files) {
57965
58075
  try {
57966
- const mtime = statSync27(join41(slugDir, file)).mtimeMs;
58076
+ const mtime = statSync27(join42(slugDir, file)).mtimeMs;
57967
58077
  const sessionId = file.replace(/\.jsonl$/, "");
57968
58078
  candidates.push({ sessionId, directory, mtime });
57969
58079
  } catch {}
@@ -58016,7 +58126,7 @@ function parseHistorianDumpMeta2(path) {
58016
58126
  function summarizeDumps2(dir, files, limit) {
58017
58127
  const now = Date.now();
58018
58128
  return files.slice(0, limit).map((entry) => {
58019
- const meta = parseHistorianDumpMeta2(join41(dir, entry.name));
58129
+ const meta = parseHistorianDumpMeta2(join42(dir, entry.name));
58020
58130
  const summary = {
58021
58131
  name: entry.name,
58022
58132
  ageMinutes: Math.round((now - entry.mtime) / 60000),
@@ -58090,7 +58200,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
58090
58200
  const loaded = loadPiConfig({ cwd });
58091
58201
  const storageResolution = getMagicContextStorageResolution();
58092
58202
  const storageDirPath = storageResolution.path;
58093
- const dbPath = join41(storageDirPath, "context.db");
58203
+ const dbPath = join42(storageDirPath, "context.db");
58094
58204
  const logFiles = inspectMagicContextLogs("pi");
58095
58205
  const primaryLog = logFiles.find((file) => file.exists) ?? logFiles[0];
58096
58206
  const otherPiExtensions = packages.filter((entry) => !isPiMagicContextPackageEntry(entry)).map(describePiPackageEntry);
@@ -58107,7 +58217,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
58107
58217
  piVersion: pi ? getPiVersion(pi.path) : null,
58108
58218
  settings: {
58109
58219
  path: settingsPath,
58110
- exists: existsSync50(settingsPath),
58220
+ exists: existsSync49(settingsPath),
58111
58221
  ...settingsParsed.parseError ? { parseError: settingsParsed.parseError } : {},
58112
58222
  hasMagicContextPackage: hasPiMagicContextPackage(packages),
58113
58223
  packages: sanitizeValue2(packages)
@@ -58124,7 +58234,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
58124
58234
  storageDir: {
58125
58235
  path: storageDirPath,
58126
58236
  source: storageResolution.source,
58127
- exists: existsSync50(storageDirPath),
58237
+ exists: existsSync49(storageDirPath),
58128
58238
  contextDbSizeBytes: fileSize2(dbPath)
58129
58239
  },
58130
58240
  conflicts: {
@@ -58233,7 +58343,7 @@ var init_diagnostics_pi = __esm(() => {
58233
58343
 
58234
58344
  // src/lib/logs-pi.ts
58235
58345
  import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync10 } from "node:fs";
58236
- import { dirname as dirname28, join as join42 } from "node:path";
58346
+ import { dirname as dirname28, join as join43 } from "node:path";
58237
58347
  function formatTimestamp2(date) {
58238
58348
  const pad = (value) => String(value).padStart(2, "0");
58239
58349
  return [
@@ -58287,11 +58397,11 @@ async function bundleIssueReport2(report, description, title, options = {}) {
58287
58397
  const truncated = bodyMarkdown !== rawBodyMarkdown;
58288
58398
  const cwd = options.cwd ?? process.cwd();
58289
58399
  const timestamp = formatTimestamp2(options.now ?? new Date);
58290
- const path = options.outputPath ?? join42(cwd, `magic-context-pi-issue-${timestamp}.md`);
58400
+ const path = options.outputPath ?? join43(cwd, `magic-context-pi-issue-${timestamp}.md`);
58291
58401
  mkdirSync10(dirname28(path), { recursive: true });
58292
58402
  writeFileSync10(path, `${bodyMarkdown}
58293
58403
  `);
58294
- const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join42(cwd, `magic-context-pi-issue-${timestamp}-full.md`) : undefined;
58404
+ const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join43(cwd, `magic-context-pi-issue-${timestamp}-full.md`) : undefined;
58295
58405
  if (fullPath)
58296
58406
  writeFileSync10(fullPath, `${rawBodyMarkdown}
58297
58407
  `);
@@ -58305,10 +58415,10 @@ var init_logs_pi = __esm(() => {
58305
58415
 
58306
58416
  // src/commands/doctor-pi.ts
58307
58417
  import { execFileSync as execFileSync9, spawnSync as spawnSync11 } from "node:child_process";
58308
- import { existsSync as existsSync51, readdirSync as readdirSync12, readFileSync as readFileSync33, rmSync as rmSync10, statSync as statSync28 } from "node:fs";
58418
+ import { existsSync as existsSync50, lstatSync as lstatSync6, readdirSync as readdirSync12, readFileSync as readFileSync33, rmSync as rmSync10 } from "node:fs";
58309
58419
  import { createRequire as createRequire8 } from "node:module";
58310
58420
  import { homedir as homedir22 } from "node:os";
58311
- import { basename as basename7, isAbsolute as isAbsolute9, join as join43 } from "node:path";
58421
+ import { basename as basename7, isAbsolute as isAbsolute10, join as join44 } from "node:path";
58312
58422
  function depsFrom(options) {
58313
58423
  return {
58314
58424
  ...DEFAULT_DEPS5,
@@ -58451,15 +58561,15 @@ function piPluginDirCandidates(packages, cwd) {
58451
58561
  if (resolved)
58452
58562
  dirs.push(resolved);
58453
58563
  }
58454
- dirs.push(join43(agentDir, "npm", "node_modules", PACKAGE_NAME2));
58455
- dirs.push(join43(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2));
58456
- return dirs.filter((dir) => existsSync51(join43(dir, "package.json")));
58564
+ dirs.push(join44(agentDir, "npm", "node_modules", PACKAGE_NAME2));
58565
+ dirs.push(join44(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2));
58566
+ return dirs.filter((dir) => existsSync50(join44(dir, "package.json")));
58457
58567
  }
58458
58568
  function projectConfigPath(cwd) {
58459
58569
  return resolveCortexKitProjectConfigPath(cwd);
58460
58570
  }
58461
58571
  function readConfigForEmbedding(path, isProjectConfig) {
58462
- if (!existsSync51(path))
58572
+ if (!existsSync50(path))
58463
58573
  return null;
58464
58574
  try {
58465
58575
  const raw = loadRawConfigFile({
@@ -58537,58 +58647,65 @@ function countTable(db, table) {
58537
58647
  return null;
58538
58648
  }
58539
58649
  }
58540
- function pinnedVersionFromPackageSpecifier(specifier) {
58650
+ function expectedPiCacheVersion(specifier, latest, lookupTag) {
58541
58651
  if (!specifier)
58542
58652
  return null;
58543
- const normalized = specifier.replace(/^npm:/, "");
58544
- const slash = normalized.indexOf("/");
58545
- const versionAt = normalized.indexOf("@", slash + 1);
58546
- if (versionAt < 0)
58547
- return null;
58548
- const version = normalized.slice(versionAt + 1);
58549
- return /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version) ? version : null;
58653
+ const spec = specifier.replace(/^npm:/, "").slice(PACKAGE_NAME2.length + 1);
58654
+ if (isValidSemver(spec))
58655
+ return spec;
58656
+ const version = !spec || spec === "latest" ? latest : isOpenCodePluginDistTag(spec) ? lookupTag(spec) : null;
58657
+ return version && isValidSemver(version) ? version : null;
58550
58658
  }
58551
- function cacheRoots(cwd) {
58659
+ function cacheSearchPaths(cwd) {
58552
58660
  const home = process.env.HOME?.trim();
58553
- const cacheHome = process.env.XDG_CACHE_HOME || join43(home || homedir22(), ".cache");
58661
+ const cacheHome = process.env.XDG_CACHE_HOME || join44(home || homedir22(), ".cache");
58554
58662
  const piCacheRoot = getPiCacheRoot();
58663
+ const xdgPi = join44(cacheHome, "pi");
58664
+ const agent = getPiAgentConfigDir();
58665
+ const projectPi = join44(cwd, ".pi");
58555
58666
  return [
58556
- join43(piCacheRoot, "extensions"),
58557
- join43(piCacheRoot, "packages"),
58558
- join43(cacheHome, "pi", "extensions"),
58559
- join43(cacheHome, "pi", "packages"),
58560
- join43(getPiAgentConfigDir(), "cache", "extensions"),
58561
- join43(getPiAgentConfigDir(), "npm", "node_modules", PACKAGE_NAME2),
58562
- join43(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2)
58667
+ { root: piCacheRoot, path: join44(piCacheRoot, "extensions") },
58668
+ { root: piCacheRoot, path: join44(piCacheRoot, "packages") },
58669
+ { root: xdgPi, path: join44(xdgPi, "extensions") },
58670
+ { root: xdgPi, path: join44(xdgPi, "packages") },
58671
+ { root: agent, path: join44(agent, "cache", "extensions") },
58672
+ { root: agent, path: join44(agent, "npm", "node_modules", PACKAGE_NAME2) },
58673
+ { root: projectPi, path: join44(projectPi, "npm", "node_modules", PACKAGE_NAME2) }
58563
58674
  ];
58564
58675
  }
58565
58676
  function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
58566
58677
  const found = new Map;
58567
- const visit = (path, depth) => {
58568
- if (depth < 0 || !existsSync51(path))
58678
+ const warnings = new Set;
58679
+ const visit = (root, path, depth) => {
58680
+ if (depth < 0)
58569
58681
  return;
58570
58682
  let stat;
58571
58683
  try {
58572
- stat = statSync28(path);
58684
+ stat = lstatSync6(path);
58573
58685
  } catch {
58574
58686
  return;
58575
58687
  }
58688
+ if (stat.isSymbolicLink()) {
58689
+ warnings.add(describeCacheClearRefusal(path, "linked"));
58690
+ return;
58691
+ }
58576
58692
  if (!stat.isDirectory())
58577
58693
  return;
58578
- const packageJson = join43(path, "package.json");
58579
- if (existsSync51(packageJson)) {
58694
+ const packageJson = join44(path, "package.json");
58695
+ if (existsSync50(packageJson)) {
58580
58696
  try {
58581
58697
  const pkg = JSON.parse(readFileSync33(packageJson, "utf-8"));
58582
58698
  const name = typeof pkg.name === "string" ? pkg.name : "";
58583
58699
  const version = typeof pkg.version === "string" ? pkg.version : undefined;
58584
58700
  if (name === PACKAGE_NAME2) {
58585
- if (force || !version || expectedVersion && version !== expectedVersion) {
58586
- found.set(path, { path, version });
58701
+ const order = version && expectedVersion ? compareSemverPrecedence(version, expectedVersion) : null;
58702
+ if (force || order !== null && order < 0) {
58703
+ found.set(path, { root, path, version });
58587
58704
  }
58588
58705
  }
58589
58706
  } catch {
58590
- if (path.includes("pi-magic-context"))
58591
- found.set(path, { path });
58707
+ if (force && path.includes("pi-magic-context"))
58708
+ found.set(path, { root, path });
58592
58709
  }
58593
58710
  }
58594
58711
  let entries = [];
@@ -58598,11 +58715,17 @@ function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
58598
58715
  return;
58599
58716
  }
58600
58717
  for (const entry of entries)
58601
- visit(join43(path, entry), depth - 1);
58718
+ visit(root, join44(path, entry), depth - 1);
58602
58719
  };
58603
- for (const root of cacheRoots(cwd))
58604
- visit(root, 5);
58605
- return [...found.values()];
58720
+ for (const { root, path } of cacheSearchPaths(cwd)) {
58721
+ const check = checkCacheClearPath(root, path);
58722
+ if (check.allowed)
58723
+ visit(root, path, 5);
58724
+ else if (check.reason !== "missing") {
58725
+ warnings.add(describeCacheClearRefusal(check.path, check.reason));
58726
+ }
58727
+ }
58728
+ return { staleCaches: [...found.values()], warnings: [...warnings] };
58606
58729
  }
58607
58730
  function checkPiModelChains(results, pi, config, deps) {
58608
58731
  const chains = runnablePiModelChains(config, "pi");
@@ -58659,7 +58782,7 @@ async function runHealthChecks2(options) {
58659
58782
  const settingsPath = getPiUserExtensionsPath();
58660
58783
  let packages = [];
58661
58784
  let piPluginInstalled = false;
58662
- if (!existsSync51(settingsPath)) {
58785
+ if (!existsSync50(settingsPath)) {
58663
58786
  if (pi) {
58664
58787
  add2(results, "info", `${piVersion ? `Pi ${piVersion}` : "Pi"} found; Magic Context is not installed there (run setup to add it)`);
58665
58788
  }
@@ -58701,7 +58824,7 @@ async function runHealthChecks2(options) {
58701
58824
  ["user", userConfigPath, true],
58702
58825
  ["project", projectPath, false]
58703
58826
  ]) {
58704
- if (!existsSync51(path)) {
58827
+ if (!existsSync50(path)) {
58705
58828
  if (required) {
58706
58829
  add2(results, "warn", `No ${label} magic-context.jsonc found at ${path}`);
58707
58830
  if (userConfigMigrationRefused) {
@@ -58748,12 +58871,12 @@ async function runHealthChecks2(options) {
58748
58871
  checkPiModelChains(results, pi, loadedConfig.config, options.deps);
58749
58872
  const storage = getMagicContextStorageResolution();
58750
58873
  const storageDir = storage.path;
58751
- const dbPath = join43(storageDir, "context.db");
58874
+ const dbPath = join44(storageDir, "context.db");
58752
58875
  if (isMagicContextStorageOutsideEngram(storageDir)) {
58753
58876
  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.`);
58754
58877
  }
58755
58878
  add2(results, "info", `Shared storage: ${storageDir} (source: ${storage.source})`);
58756
- const existedBeforeOpen = existsSync51(dbPath);
58879
+ const existedBeforeOpen = existsSync50(dbPath);
58757
58880
  if (existedBeforeOpen)
58758
58881
  add2(results, "pass", `Shared context DB exists at ${dbPath}`);
58759
58882
  else
@@ -58927,14 +59050,16 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
58927
59050
  }
58928
59051
  const configuredEntry = packages.find(isPiMagicContextPackageEntry);
58929
59052
  const configuredSpecifier = getPiMagicContextPackageSpecifier(configuredEntry);
58930
- const expectedPluginVersion = pinnedVersionFromPackageSpecifier(configuredSpecifier) ?? latest ?? null;
58931
- const staleCaches = findPiMagicContextCacheDirs(options.cwd, expectedPluginVersion, options.force === true);
59053
+ const expectedPluginVersion = expectedPiCacheVersion(configuredSpecifier, latest, options.deps.getLatestNpmVersion);
59054
+ const { staleCaches, warnings } = findPiMagicContextCacheDirs(options.cwd, expectedPluginVersion, options.force === true);
59055
+ for (const warning of warnings)
59056
+ add2(results, "warn", warning);
58932
59057
  if (!expectedPluginVersion && !options.force) {
58933
59058
  add2(results, "warn", "Pi extension cache version check unavailable; preserving cached packages. Use doctor --force to clear them.");
58934
59059
  } else if (staleCaches.length > 0) {
58935
- repairPlan.clearCachePaths = staleCaches.map((entry) => entry.path);
59060
+ repairPlan.clearCachePaths = staleCaches;
58936
59061
  add2(results, "warn", `${options.force ? "Pi extension cache selected for clearing" : "Stale Pi extension cache found"}: ${staleCaches.map((entry) => `${entry.path}${entry.version ? ` (v${entry.version})` : ""}`).join(", ")}`);
58937
- } else {
59062
+ } else if (warnings.length === 0) {
58938
59063
  add2(results, "pass", "Pi extension cache clean (no stale cached package found)");
58939
59064
  }
58940
59065
  const logFiles = inspectMagicContextLogs("pi");
@@ -59017,7 +59142,7 @@ function piCacheClearBlocker(paths, deps) {
59017
59142
  const holders = cache.pids.map((pid) => `${cacheHolderName(deps.readProcessCommand(pid))} (PID ${pid})`);
59018
59143
  return `cache files are in use by ${holders.join(", ")}`;
59019
59144
  }
59020
- const db = join43(getMagicContextStorageDir(), "context.db");
59145
+ const db = join44(getMagicContextStorageDir(), "context.db");
59021
59146
  const use = deps.probeCacheUse({ files: [db, `${db}-wal`, `${db}-shm`], directories: [] });
59022
59147
  if (use.status === "unknown")
59023
59148
  return use.reason;
@@ -59064,7 +59189,7 @@ function repair2(plan, prompts, deps) {
59064
59189
  }
59065
59190
  if (plan.writeUserConfig) {
59066
59191
  const configPath = getPiUserConfigPath();
59067
- if (!existsSync51(configPath)) {
59192
+ if (!existsSync50(configPath)) {
59068
59193
  try {
59069
59194
  writeDefaultMagicContextConfig(configPath);
59070
59195
  prompts.log.success(`Wrote default Magic Context config to ${configPath}`);
@@ -59076,14 +59201,19 @@ function repair2(plan, prompts, deps) {
59076
59201
  }
59077
59202
  if (plan.clearCachePaths.length === 0)
59078
59203
  return { fixed, cacheBlocked: false };
59079
- const blocker = piCacheClearBlocker(plan.clearCachePaths, deps);
59204
+ const blocker = piCacheClearBlocker(plan.clearCachePaths.map(({ path }) => path), deps);
59080
59205
  if (blocker !== undefined) {
59081
59206
  prompts.log.warn(`Pi extension cache was not cleared: ${blocker}. Quit Pi or Oh My Pi and rerun doctor.`);
59082
59207
  return { fixed, cacheBlocked: true };
59083
59208
  }
59084
- for (const path of plan.clearCachePaths) {
59209
+ for (const { root, path } of plan.clearCachePaths) {
59210
+ const check = checkCacheClearPath(root, path);
59211
+ if (!check.allowed) {
59212
+ prompts.log.warn(describeCacheClearRefusal(path, check.reason));
59213
+ continue;
59214
+ }
59085
59215
  try {
59086
- rmSync10(path, { recursive: true, force: true });
59216
+ rmSync10(check.path, { recursive: true, force: true });
59087
59217
  prompts.log.success(`Cleared Pi extension cache: ${path}`);
59088
59218
  fixed += 1;
59089
59219
  } catch (error) {
@@ -59125,7 +59255,7 @@ async function runIssueFlow3(options) {
59125
59255
  if (options.reportPath) {
59126
59256
  try {
59127
59257
  const report = await options.deps.collectDiagnostics(options.cwd);
59128
- const outputPath = isAbsolute9(options.reportPath) ? options.reportPath : join43(options.cwd, options.reportPath);
59258
+ const outputPath = isAbsolute10(options.reportPath) ? options.reportPath : join44(options.cwd, options.reportPath);
59129
59259
  const bundled = await bundleIssueReport2(report, "Generated non-interactively by `doctor --issue --report`.", "Magic Context diagnostic report", { cwd: options.cwd, now: options.deps.now(), outputPath });
59130
59260
  options.prompts.log.info(`Report written to ${bundled.path}`);
59131
59261
  return 0;
@@ -59209,7 +59339,7 @@ async function runDoctor3(options = {}) {
59209
59339
  const v22Result = await runV22BackfillCommands({
59210
59340
  name: "Pi",
59211
59341
  openDatabase: (readonly = true) => {
59212
- const dbPath = join43(getMagicContextStorageDir(), "context.db");
59342
+ const dbPath = join44(getMagicContextStorageDir(), "context.db");
59213
59343
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
59214
59344
  return v22Db;
59215
59345
  },
@@ -59293,11 +59423,13 @@ var init_doctor_pi = __esm(async () => {
59293
59423
  init_config2();
59294
59424
  init_model_chain_health();
59295
59425
  init_atomic_write();
59426
+ init_cache_clear_path();
59296
59427
  init_config_location_migration();
59297
59428
  init_diagnostics_pi();
59298
59429
  init_github_issue();
59299
59430
  init_log_lines();
59300
59431
  init_logs_pi();
59432
+ init_opencode_plugin_cache();
59301
59433
  init_paths();
59302
59434
  init_pi_helpers();
59303
59435
  init_pi_package_entry();
@@ -59321,7 +59453,7 @@ var init_doctor_pi = __esm(async () => {
59321
59453
  detectPiBinary,
59322
59454
  getPiVersion,
59323
59455
  listPiModels: getAvailableModels,
59324
- getLatestNpmVersion: () => getLatestNpmVersion(PACKAGE_NAME2),
59456
+ getLatestNpmVersion: (tag) => getLatestNpmVersion(tag ? `${PACKAGE_NAME2}@${tag}` : PACKAGE_NAME2),
59325
59457
  selfVersion: selfVersion2,
59326
59458
  probeEmbeddingEndpoint,
59327
59459
  openExistingContextDatabase,
@@ -59334,8 +59466,8 @@ var init_doctor_pi = __esm(async () => {
59334
59466
  });
59335
59467
 
59336
59468
  // src/commands/doctor.ts
59337
- import { existsSync as existsSync52, rmSync as rmSync11 } from "node:fs";
59338
- import { join as join44 } from "node:path";
59469
+ import { rmSync as rmSync11 } from "node:fs";
59470
+ import { join as join45 } from "node:path";
59339
59471
  async function runDoctor4(options) {
59340
59472
  if (options.clear)
59341
59473
  return runClear();
@@ -59353,7 +59485,7 @@ async function runDoctor4(options) {
59353
59485
  const result = await runV22BackfillCommands({
59354
59486
  name: "Magic Context",
59355
59487
  openDatabase: (readonly = true) => {
59356
- const dbPath = join44(getMagicContextStorageDir(), "context.db");
59488
+ const dbPath = join45(getMagicContextStorageDir(), "context.db");
59357
59489
  v22Db = readonly ? openExistingContextDatabase(dbPath, { readonly: true }) : openExistingContextDatabaseForMutation(dbPath);
59358
59490
  return v22Db;
59359
59491
  },
@@ -59373,7 +59505,7 @@ async function runDoctor4(options) {
59373
59505
  log3.warn(`Identity split check unavailable: ${error instanceof Error ? error.message : String(error)}`);
59374
59506
  }
59375
59507
  await init_migrate();
59376
- const sweepDbPath = join44(getMagicContextStorageDir(), "context.db");
59508
+ const sweepDbPath = join45(getMagicContextStorageDir(), "context.db");
59377
59509
  let sweepDb = null;
59378
59510
  try {
59379
59511
  sweepDb = openExistingContextDatabaseForMutation(sweepDbPath);
@@ -59449,6 +59581,7 @@ async function runClear() {
59449
59581
  items.push({
59450
59582
  adapter,
59451
59583
  path: cache.path,
59584
+ cacheRoot: cache.cacheRoot,
59452
59585
  sizeBytes: cache.sizeBytes,
59453
59586
  label: cache.label,
59454
59587
  clear: cache.clear
@@ -59485,6 +59618,13 @@ async function runClear() {
59485
59618
  const s = spinner2();
59486
59619
  s.start(`Clearing ${item.path}`);
59487
59620
  try {
59621
+ const check = checkCacheClearPath(item.cacheRoot, item.path);
59622
+ if (!check.allowed) {
59623
+ s.stop(`Left in place: ${item.path}`);
59624
+ log3.warn(describeCacheClearRefusal(item.path, check.reason));
59625
+ failed += 1;
59626
+ continue;
59627
+ }
59488
59628
  if (item.clear) {
59489
59629
  const result = item.clear();
59490
59630
  if (!result.cleared) {
@@ -59493,8 +59633,8 @@ async function runClear() {
59493
59633
  failed += 1;
59494
59634
  continue;
59495
59635
  }
59496
- } else if (existsSync52(item.path)) {
59497
- rmSync11(item.path, { recursive: true, force: true });
59636
+ } else {
59637
+ rmSync11(check.path, { recursive: true, force: true });
59498
59638
  }
59499
59639
  s.stop(`Cleared ${item.path}`);
59500
59640
  } catch (err) {
@@ -59517,6 +59657,7 @@ function formatSize2(bytes) {
59517
59657
  }
59518
59658
  var init_doctor = __esm(async () => {
59519
59659
  init_data_path();
59660
+ init_cache_clear_path();
59520
59661
  init_prompts();
59521
59662
  await __promiseAll([
59522
59663
  init_adapters(),