@cortexkit/magic-context 0.49.11 → 0.49.12

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 +689 -454
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1726,6 +1726,15 @@ var init_test_temp_dir = __esm(() => {
1726
1726
  });
1727
1727
 
1728
1728
  // ../plugin/src/shared/data-path.ts
1729
+ import {
1730
+ existsSync as existsSync2,
1731
+ lstatSync,
1732
+ mkdirSync,
1733
+ readFileSync as readFileSync2,
1734
+ readlinkSync,
1735
+ realpathSync,
1736
+ writeFileSync
1737
+ } from "node:fs";
1729
1738
  import * as os from "node:os";
1730
1739
  import * as path from "node:path";
1731
1740
  function getDataDir() {
@@ -1790,11 +1799,41 @@ function getMagicContextStorageResolution() {
1790
1799
  function getMagicContextStorageDir() {
1791
1800
  return getMagicContextStorageResolution().path;
1792
1801
  }
1802
+ function canonicalizeStoragePath(value, seen = new Set) {
1803
+ const absolute = path.resolve(value);
1804
+ if (seen.has(absolute))
1805
+ return absolute;
1806
+ seen.add(absolute);
1807
+ try {
1808
+ return realpathSync.native(absolute);
1809
+ } catch {
1810
+ try {
1811
+ if (lstatSync(absolute).isSymbolicLink()) {
1812
+ const target = readlinkSync(absolute);
1813
+ const resolvedTarget = path.isAbsolute(target) ? target : path.resolve(path.dirname(absolute), target);
1814
+ return canonicalizeStoragePath(resolvedTarget, seen);
1815
+ }
1816
+ } catch {}
1817
+ const parent = path.dirname(absolute);
1818
+ if (parent === absolute)
1819
+ return absolute;
1820
+ const resolvedParent = canonicalizeStoragePath(parent, seen);
1821
+ return path.resolve(resolvedParent, path.basename(absolute));
1822
+ }
1823
+ }
1824
+ function isMagicContextStorageOutsideEngram(storageDir = getMagicContextStorageDir(), backupDir = path.join(os.homedir(), ".local", "share", "cortexkit", "magic-context")) {
1825
+ const resolvedStorageDir = canonicalizeStoragePath(storageDir);
1826
+ const resolvedBackupDir = canonicalizeStoragePath(backupDir);
1827
+ const relative2 = path.relative(resolvedBackupDir, resolvedStorageDir);
1828
+ return path.isAbsolute(relative2) || relative2 === ".." || relative2.startsWith(`..${path.sep}`);
1829
+ }
1793
1830
  function getLegacyOpenCodeMagicContextStorageDir() {
1794
1831
  return path.join(getOpenCodeStorageDir(), "plugin", "magic-context");
1795
1832
  }
1833
+ var STORAGE_BACKUP_WARNING_CHECKED;
1796
1834
  var init_data_path = __esm(() => {
1797
1835
  init_test_temp_dir();
1836
+ STORAGE_BACKUP_WARNING_CHECKED = Symbol.for("magic-context.storage-backup-warning-checked");
1798
1837
  });
1799
1838
 
1800
1839
  // ../plugin/src/shared/redaction.ts
@@ -2332,19 +2371,19 @@ import {
2332
2371
  closeSync as closeSync2,
2333
2372
  createWriteStream,
2334
2373
  fsyncSync,
2335
- lstatSync,
2336
- mkdirSync as mkdirSync2,
2374
+ lstatSync as lstatSync2,
2375
+ mkdirSync as mkdirSync3,
2337
2376
  openSync as openSync2,
2338
2377
  readdirSync,
2339
- readlinkSync,
2378
+ readlinkSync as readlinkSync2,
2340
2379
  readSync as readSync2,
2341
2380
  renameSync,
2342
2381
  rmSync,
2343
2382
  symlinkSync,
2344
- writeFileSync,
2383
+ writeFileSync as writeFileSync2,
2345
2384
  writeSync as writeSync2
2346
2385
  } from "node:fs";
2347
- import { dirname as dirname2, join as join2 } from "node:path";
2386
+ import { dirname as dirname3, join as join2 } from "node:path";
2348
2387
  function setStoragePrivatePermissionEnforcement(enforce) {
2349
2388
  enforcePrivateStoragePermissions = enforce;
2350
2389
  }
@@ -2353,7 +2392,7 @@ function shouldEnforcePrivateStoragePermissions() {
2353
2392
  }
2354
2393
  function ensureStorageDirectorySync(directory, forcePrivate = false, recursive = true) {
2355
2394
  const privateMode = forcePrivate || shouldEnforcePrivateStoragePermissions();
2356
- mkdirSync2(directory, {
2395
+ mkdirSync3(directory, {
2357
2396
  recursive,
2358
2397
  ...privateMode ? { mode: 448 } : {}
2359
2398
  });
@@ -2361,13 +2400,13 @@ function ensureStorageDirectorySync(directory, forcePrivate = false, recursive =
2361
2400
  function writeStorageFileSync(filePath, content, options = {}) {
2362
2401
  const { forcePrivate = false, ...writeOptions } = options;
2363
2402
  const privateMode = forcePrivate || shouldEnforcePrivateStoragePermissions();
2364
- writeFileSync(filePath, content, {
2403
+ writeFileSync2(filePath, content, {
2365
2404
  ...writeOptions,
2366
2405
  ...privateMode ? { mode: 384 } : {}
2367
2406
  });
2368
2407
  }
2369
2408
  function writeStorageFileAtomicSync(filePath, content, forcePrivate = false) {
2370
- ensureStorageDirectorySync(dirname2(filePath), forcePrivate);
2409
+ ensureStorageDirectorySync(dirname3(filePath), forcePrivate);
2371
2410
  const tempPath = `${filePath}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
2372
2411
  try {
2373
2412
  writeStorageFileSync(tempPath, content, { flag: "wx", forcePrivate });
@@ -2378,7 +2417,7 @@ function writeStorageFileAtomicSync(filePath, content, forcePrivate = false) {
2378
2417
  }
2379
2418
  }
2380
2419
  function copyStorageFileSync(sourcePath, destinationPath, forcePrivate = false) {
2381
- ensureStorageDirectorySync(dirname2(destinationPath), forcePrivate);
2420
+ ensureStorageDirectorySync(dirname3(destinationPath), forcePrivate);
2382
2421
  const privateMode = forcePrivate || shouldEnforcePrivateStoragePermissions();
2383
2422
  const sourceFd = openSync2(sourcePath, "r");
2384
2423
  let destinationFd;
@@ -2405,10 +2444,10 @@ function copyStorageFileSync(sourcePath, destinationPath, forcePrivate = false)
2405
2444
  }
2406
2445
  }
2407
2446
  function copyStorageTreeSync(sourcePath, destinationPath, forcePrivate = false) {
2408
- const stat = lstatSync(sourcePath);
2447
+ const stat = lstatSync2(sourcePath);
2409
2448
  if (stat.isSymbolicLink()) {
2410
- ensureStorageDirectorySync(dirname2(destinationPath), forcePrivate);
2411
- symlinkSync(readlinkSync(sourcePath), destinationPath);
2449
+ ensureStorageDirectorySync(dirname3(destinationPath), forcePrivate);
2450
+ symlinkSync(readlinkSync2(sourcePath), destinationPath);
2412
2451
  return;
2413
2452
  }
2414
2453
  if (!stat.isDirectory()) {
@@ -2421,7 +2460,7 @@ function copyStorageTreeSync(sourcePath, destinationPath, forcePrivate = false)
2421
2460
  }
2422
2461
  }
2423
2462
  function openStorageFileSync(filePath, flags, forcePrivate = false) {
2424
- ensureStorageDirectorySync(dirname2(filePath), forcePrivate);
2463
+ ensureStorageDirectorySync(dirname3(filePath), forcePrivate);
2425
2464
  const privateMode = forcePrivate || shouldEnforcePrivateStoragePermissions();
2426
2465
  return openSync2(filePath, flags, privateMode ? 384 : 438);
2427
2466
  }
@@ -2434,7 +2473,7 @@ function tightenStorageTreeSync(root) {
2434
2473
  const visit = (entryPath) => {
2435
2474
  let stat;
2436
2475
  try {
2437
- stat = lstatSync(entryPath);
2476
+ stat = lstatSync2(entryPath);
2438
2477
  } catch {
2439
2478
  failures++;
2440
2479
  return;
@@ -2813,9 +2852,9 @@ var init_jsonc_edit = __esm(() => {
2813
2852
  });
2814
2853
 
2815
2854
  // ../plugin/src/config/migrate-config-location.ts
2816
- import { existsSync as existsSync2, readFileSync as readFileSync2, rmSync as rmSync2, statSync as statSync2, unlinkSync } from "node:fs";
2855
+ import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync as rmSync2, statSync as statSync2, unlinkSync } from "node:fs";
2817
2856
  import { homedir as homedir3 } from "node:os";
2818
- import { basename, dirname as dirname3, isAbsolute as isAbsolute2, join as join3 } from "node:path";
2857
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute2, join as join3 } from "node:path";
2819
2858
  function homeDir() {
2820
2859
  if (process.platform === "win32") {
2821
2860
  return process.env.USERPROFILE || process.env.HOME || homedir3();
@@ -3039,8 +3078,8 @@ function markLegacySourcesMovedAside(sources, targetPath, logger) {
3039
3078
  for (const source of sources) {
3040
3079
  const markerPath = `${source.path}${MOVED_MARKER_SUFFIX}`;
3041
3080
  try {
3042
- const original = readFileSync2(source.path, "utf-8");
3043
- atomicWriteConfigFile(markerPath, movedMarkerContent(targetPath, basename(source.path), original));
3081
+ const original = readFileSync3(source.path, "utf-8");
3082
+ atomicWriteConfigFile(markerPath, movedMarkerContent(targetPath, basename2(source.path), original));
3044
3083
  unlinkSync(source.path);
3045
3084
  info?.(`Moved legacy Magic Context config ${source.path} aside to ${markerPath}; now reading ${targetPath}`);
3046
3085
  } catch (err) {
@@ -3057,12 +3096,12 @@ function visibleConfigMigrationWarning(scope, targetPath, paths, reason) {
3057
3096
  }
3058
3097
  function migrateConfigFile(opts) {
3059
3098
  const warnings = [];
3060
- const existingSources = opts.legacySources.filter((source) => existsSync2(source.path));
3099
+ const existingSources = opts.legacySources.filter((source) => existsSync3(source.path));
3061
3100
  const info = opts.logger?.info ?? opts.logger?.log;
3062
3101
  if (existingSources.length === 0) {
3063
3102
  return { migrated: false, conflict: false, targetPath: opts.targetPath, warnings };
3064
3103
  }
3065
- ensureStorageDirectorySync(dirname3(opts.targetPath), true);
3104
+ ensureStorageDirectorySync(dirname4(opts.targetPath), true);
3066
3105
  const release = acquireConfigMigrationLock(`${opts.targetPath}.lock`);
3067
3106
  if (!release) {
3068
3107
  warnings.push(`Config migration for ${opts.scope} skipped this run (another instance is migrating); will retry on next start.`);
@@ -3071,10 +3110,10 @@ function migrateConfigFile(opts) {
3071
3110
  try {
3072
3111
  const sources = existingSources.map((source) => ({
3073
3112
  ...source,
3074
- content: readFileSync2(source.path, "utf-8")
3113
+ content: readFileSync3(source.path, "utf-8")
3075
3114
  }));
3076
- if (existsSync2(opts.targetPath)) {
3077
- const targetContent = readFileSync2(opts.targetPath, "utf-8");
3115
+ if (existsSync3(opts.targetPath)) {
3116
+ const targetContent = readFileSync3(opts.targetPath, "utf-8");
3078
3117
  const differing = sources.filter((source) => !fileSemanticsMatch(source.content, targetContent));
3079
3118
  if (differing.length > 0) {
3080
3119
  const message = visibleConfigMigrationWarning(opts.scope, opts.targetPath, differing.map((source) => source.path), "the CortexKit target already exists with different settings");
@@ -9158,7 +9197,7 @@ var init_magic_context = __esm(() => {
9158
9197
  max_tokens: 12000
9159
9198
  })),
9160
9199
  "evaluate-smart-notes": DreamTaskBaseConfigSchema.default(() => DreamTaskBaseConfigSchema.parse(defaultTaskConfig("evaluate-smart-notes"))),
9161
- "review-user-memories": ReviewUserMemoriesTaskConfigSchema.default(() => ReviewUserMemoriesTaskConfigSchema.parse(defaultTaskConfig("review-user-memories"))),
9200
+ "review-user-memories": ReviewUserMemoriesTaskConfigSchema.default(() => ReviewUserMemoriesTaskConfigSchema.parse(defaultTaskConfig("review-user-memories"))).describe("Promote recurring user observations into the <user-profile> block. A non-empty schedule also makes the historian collect user observations, but only while the dreamer is runnable (dreamer.disable not true); collection and review follow that one gate and do not depend on memory.enabled."),
9162
9201
  "promote-primers": PromotePrimersTaskConfigSchema.default(() => PromotePrimersTaskConfigSchema.parse(defaultTaskConfig("promote-primers"))),
9163
9202
  "refresh-primers": DreamTaskBaseConfigSchema.default(() => DreamTaskBaseConfigSchema.parse(defaultTaskConfig("refresh-primers")))
9164
9203
  }).describe("Harness-independent task metadata. schedule, promotion_threshold, and other task metadata remain here; execution settings live under dreamer.opencode.tasks, dreamer.pi.tasks, or dreamer.omp.tasks.");
@@ -9176,13 +9215,13 @@ var init_magic_context = __esm(() => {
9176
9215
  maxTokens: true
9177
9216
  });
9178
9217
  DreamerConfigSchema = AgentMetadataSchema.extend({
9179
- disable: boolean2().optional().describe("Disable this agent"),
9218
+ disable: boolean2().optional().describe("Disable the dreamer: no scheduled or manual dream task runs. Also turns off smart notes (ctx_note drops surface_condition even with smart_notes.enabled true) and the historian's collection of user observations for review-user-memories. dreamer.inject_docs still applies."),
9180
9219
  runner: _enum(["broca", "host"]).optional().describe(`Which side runs the dreamer completions the Rust module routes (classify-memories) in Rust transform mode: "host" runs them on this process's carrier, "broca" routes them to the Broca module. When unset, historian.runner applies, and when that is unset too the harness decides the same way it does for the historian. User-level config only.`),
9181
9220
  opencode: DreamerOpenCodeHarnessBlockSchema.optional(),
9182
9221
  pi: DreamerPiHarnessBlockSchema.optional(),
9183
9222
  omp: DreamerOmpHarnessBlockSchema.optional(),
9184
9223
  tasks: DreamTasksSchema.default(() => DreamTasksSchema.parse({})),
9185
- inject_docs: boolean2().default(true).describe("Inject ARCHITECTURE.md and STRUCTURE.md into the m[0] `<project-docs>` block (default true)")
9224
+ inject_docs: boolean2().default(true).describe("Inject ARCHITECTURE.md and STRUCTURE.md into the m[0] `<project-docs>` block (default true). Not a dreamer setting despite its place under dreamer: it applies on every host, also with dreamer.disable true.")
9186
9225
  });
9187
9226
  HistorianConfigSchema = AgentMetadataSchema.extend({
9188
9227
  expand_tools: record(string2(), union([
@@ -9313,9 +9352,9 @@ var init_magic_context = __esm(() => {
9313
9352
  profile: string2().trim().min(1).optional().describe("Select a named user-owned model profile. A valid project name overrides this user default; an empty string, null, or other non-string project value is ignored with a warning so the user selection still applies. Unknown names warn and use the base configuration."),
9314
9353
  profiles: ConfigProfilesSchema.optional().describe("User-level named model profiles. A profile may contain only historian/dreamer model, fallback_models, OpenCode variant, and Pi/OMP thinking_level fields; task execution policy (including timeout_minutes) is excluded. Project configs may select a name but cannot define profiles."),
9315
9354
  historian: HistorianConfigSchema.describe("Historian metadata plus independent strict OpenCode, Pi, and OMP execution blocks. Retained metadata stays at historian; model, fallback_models, variant, and thinking_level belong only in historian.opencode, historian.pi, or historian.omp."),
9316
- dreamer: DreamerConfigSchema.optional().describe("Dreamer metadata and scheduling plus independent strict OpenCode, Pi, and OMP execution blocks. schedule and promotion_threshold stay at dreamer.tasks; model, fallback_models, variant, thinking_level, and timeout_minutes belong only in the matching harness block."),
9355
+ dreamer: DreamerConfigSchema.optional().describe("Dreamer metadata and scheduling plus independent strict OpenCode, Pi, and OMP execution blocks. schedule and promotion_threshold stay at dreamer.tasks; model, fallback_models, variant, thinking_level, and timeout_minutes belong only in the matching harness block. Each task follows the setting it serves: memory tasks need memory.enabled, evaluate-smart-notes needs smart_notes.enabled, review-user-memories needs its schedule, maintain-docs only a runnable dreamer."),
9317
9356
  smart_notes: object({
9318
- enabled: boolean2().default(true).describe("Enable smart-note authoring and condition evaluation. User-level only: tool definitions are process-wide. Changes require a host restart and rebuild each session's cached prompt once. Pending notes remain stored and unchecked; already-ready notes still surface."),
9357
+ enabled: boolean2().default(true).describe("Enable smart-note authoring and condition evaluation. Needs a runnable dreamer, which evaluates the conditions: with dreamer.disable true (or no dreamer block) ctx_note offers no surface_condition whatever this says. User-level only: tool definitions are process-wide. Changes require a host restart and rebuild each session's cached prompt once. Pending notes remain stored and unchecked; already-ready notes still surface."),
9319
9358
  retina_handoff: boolean2().default(false).describe("When true, dreamer skips smart notes whose surface conditions compiled to retina provider configs at authoring time. Default false keeps both paths active until the retina consumer is deployed.")
9320
9359
  }).default({ enabled: true, retina_handoff: false }).describe("Smart-note ownership transition controls."),
9321
9360
  cache_ttl: union([string2(), object({ default: string2() }).catchall(string2())]).default("5m").describe(`How long Magic Context assumes the provider's cached prefix stays valid. This is MC's own deferral gate — it does not change the provider's actual cache lifetime. String (e.g. "5m", "1h", "30s") or per-model object ({ default: "5m", "provider/model": "1h", "provider/*": "never" }); keys resolve most-specific first (exact provider/model, bare model ID, shorter dash-prefixes, then the provider/* wildcard, then default). User and project settings, including an explicit "5m" or object default, apply on the next pass. Only built-in defaults are frozen per session, including across restarts: when unset, GPT-5.6 and later (including gpt-6*, through any provider prefix) use 30m, other models use 5m. /ctx-status shows the effective TTL and whether it comes from your config or a frozen built-in default. Editing the TTL does not itself rewrite prompt bytes; a lowered TTL rebuilds only after normal idle expiry. OpenAI documents at least 30 minutes since the latest write or reuse: https://developers.openai.com/api/docs/guides/prompt-caching (Cache lifetime and Summary of model differences). Set to "never" to mean MC never assumes expiry (for lanes kept warm externally by a cache-keep tool) — disables the idle-TTL heuristic so MC never initiates a rebuild based on elapsed time. Provider-side extended TTL is a separate request-level concern (cache_control: { ttl } in the request body).`),
@@ -9343,11 +9382,11 @@ var init_magic_context = __esm(() => {
9343
9382
  object({ default: number2().int().min(0).max(1e6).optional() }).catchall(number2().int().min(0).max(1e6))
9344
9383
  ]).optional().describe("Reasoning tokens to keep on rebuilding passes. Number or per-model object; exact, shorter model keys, provider/*, then default. Omitted: fixed 10,000. 0 removes all eligible historical reasoning; newest and exempt steps always stay."),
9345
9384
  history_budget_percentage: number2().min(0.05).max(0.5).default(DEFAULT_HISTORY_BUDGET_PERCENTAGE).describe("Fraction of usable context (context_limit × execute_threshold) reserved for the session history block (default: 0.15)"),
9346
- historian_timeout_ms: number2().min(60000).default(DEFAULT_HISTORIAN_TIMEOUT_MS).describe("Timeout for each historian prompt call in both TypeScript and Rust transform modes, in milliseconds (default: 600000)"),
9385
+ historian_timeout_ms: number2().min(60000).default(DEFAULT_HISTORIAN_TIMEOUT_MS).describe("Timeout for each historian prompt call in both TypeScript and Rust transform modes, in milliseconds (default: 600000). A historian setting kept at the top level for compatibility; no effect while historian.disable is true or compaction.enabled is false."),
9347
9386
  commit_cluster_trigger: object({
9348
9387
  enabled: boolean2().default(true).describe("Enable commit-cluster based historian triggering (default: true)"),
9349
9388
  min_clusters: number2().min(1).default(3).describe("Minimum commit clusters required to trigger historian (min: 1, default: 3)")
9350
- }).default({ enabled: true, min_clusters: 3 }).describe("Commit-cluster trigger: fire historian when enough commit clusters accumulate in the unsummarized tail"),
9389
+ }).default({ enabled: true, min_clusters: 3 }).describe("Commit-cluster trigger: fire historian when enough commit clusters accumulate in the unsummarized tail. A historian setting kept at the top level for compatibility; no effect while historian.disable is true or compaction.enabled is false."),
9351
9390
  system_prompt_injection: object({
9352
9391
  enabled: boolean2().default(true).describe("When false, NO injection happens for ANY agent — global escape hatch. (default: true)"),
9353
9392
  skip_signatures: array(string2()).default(["<!-- magic-context: skip -->"]).describe(`Substring opt-out list. If the agent's system prompt contains any of these strings, skip ALL Magic Context injection for that call. Default "<!-- magic-context: skip -->" is meant to be added inside a user's custom agent prompt to opt that agent out.`)
@@ -9392,20 +9431,20 @@ var init_magic_context = __esm(() => {
9392
9431
  min_chars: number2().min(100).max(1e4).default(500).describe("Text parts shorter than this (characters) stay untouched. Min 100, max 10000. Default: 500.")
9393
9432
  }).default({ enabled: false, min_chars: 500 }).describe("Age-tier caveman compression for long user/assistant text parts. Active for primary sessions when enabled; never for subagents. Oldest 20% of eligible tags (outside protected tail) go to ultra, next 20% to full, next 20% to lite, newest 40% untouched. Graduated from experimental.caveman_text_compression; opt-in, default off (lossy)."),
9394
9433
  memory: object({
9395
- enabled: boolean2().default(true).describe("Enable cross-session memory (default: true). Does not affect history embedding or semantic ctx_search over session history; set embedding.provider to 'off' to stop all embedding."),
9434
+ enabled: boolean2().default(true).describe("Enable cross-session project memory (default: true). Also gates the dreamer's project-memory tasks: while false, map-memories, verify, verify-broad, curate, compress-cues, classify-memories, retrospective, promote-primers and refresh-primers neither run on schedule nor through /ctx-dream; maintain-docs, evaluate-smart-notes and review-user-memories still run. memory.auto_search and memory.git_commit_indexing do not depend on it. Does not affect history embedding or semantic ctx_search over session history; set embedding.provider to 'off' to stop all embedding."),
9396
9435
  injection_budget_tokens: number2().min(500).max(20000).default(4000).describe("Token budget for memory injection on session start (min: 500, max: 20000, default: 4000)"),
9397
- auto_promote: boolean2().default(true).describe("Automatically promote eligible session facts into memory (default: true)"),
9398
- retrieval_count_promotion_threshold: number2().min(1).default(3).describe("retrieval_count threshold for promoting memory to permanent status (min: 1, default: 3)"),
9436
+ auto_promote: boolean2().default(true).describe("Automatically promote eligible session facts into memory (default: true). No effect while memory.enabled is false."),
9437
+ retrieval_count_promotion_threshold: number2().min(1).default(3).describe("Currently has no effect: no code reads this value, and memories are not promoted to permanent by retrieval count. Kept so existing configs stay valid (min: 1, default: 3)."),
9399
9438
  auto_search: object({
9400
- enabled: boolean2().default(true).describe("Automatically append a compact <ctx-search-hint> to eligible user messages when relevant memories, conversation, or commits are found. Graduated from experimental.auto_search; on by default (set false to opt out). Independent of memory.enabled."),
9439
+ enabled: boolean2().default(true).describe("Automatically append a compact <ctx-search-hint> to eligible user messages when relevant memories, conversation, or commits are found. Graduated from experimental.auto_search; on by default (set false to opt out). Independent of memory.enabled despite its place under memory: with memory off it still searches past conversation and commits, only the memory source is skipped."),
9401
9440
  score_threshold: number2().min(0.3).max(0.95).default(0.6).describe("Top hit score must exceed this threshold for the hint to fire (min: 0.3, max: 0.95, default: 0.60)"),
9402
9441
  min_prompt_chars: number2().min(5).max(500).default(20).describe("Skip hint when user message is shorter than this (min: 5, max: 500, default: 20)")
9403
- }).default({ enabled: true, score_threshold: 0.6, min_prompt_chars: 20 }).describe("Auto-search hint: transform-time ctx_search on each new user message; when the top hit clears the threshold, append a compact <ctx-search-hint> block of vague fragments to that user message. Does NOT inject full content. Graduated from experimental.auto_search; enabled by default (set enabled: false to opt out). Independent of memory.enabled."),
9442
+ }).default({ enabled: true, score_threshold: 0.6, min_prompt_chars: 20 }).describe("Auto-search hint: transform-time ctx_search on each new user message; when the top hit clears the threshold, append a compact <ctx-search-hint> block of vague fragments to that user message. Does NOT inject full content. Graduated from experimental.auto_search; enabled by default (set enabled: false to opt out). Independent of memory.enabled despite its place under memory: with memory off it still searches past conversation and commits."),
9404
9443
  git_commit_indexing: object({
9405
- enabled: boolean2().default(false).describe("Index HEAD git commits for ctx_search (git_commit source). Graduated from experimental.git_commit_indexing; opt-in, default off. Independent of memory.enabled."),
9444
+ enabled: boolean2().default(false).describe("Index HEAD git commits for ctx_search (git_commit source). Graduated from experimental.git_commit_indexing; opt-in, default off. Independent of memory.enabled despite its place under memory."),
9406
9445
  since_days: number2().min(7).max(3650).default(365).describe("Days of HEAD history to index (min: 7, max: 3650, default: 365)"),
9407
9446
  max_commits: number2().min(100).max(20000).default(2000).describe("Max commits kept per project; oldest evicted (min: 100, max: 20000, default: 2000)")
9408
- }).default({ enabled: false, since_days: 365, max_commits: 2000 }).describe("Index git commit messages from HEAD into ctx_search. Commits become a 4th searchable source alongside memories and session history. Graduated from experimental.git_commit_indexing; opt-in, default off (per-project embedding cost). Independent of memory.enabled.")
9447
+ }).default({ enabled: false, since_days: 365, max_commits: 2000 }).describe("Index git commit messages from HEAD into ctx_search. Commits become a 4th searchable source alongside memories and session history. Graduated from experimental.git_commit_indexing; opt-in, default off (per-project embedding cost). Independent of memory.enabled despite its place under memory.")
9409
9448
  }).default({
9410
9449
  enabled: true,
9411
9450
  injection_budget_tokens: 4000,
@@ -9413,7 +9452,7 @@ var init_magic_context = __esm(() => {
9413
9452
  retrieval_count_promotion_threshold: 3,
9414
9453
  auto_search: { enabled: true, score_threshold: 0.6, min_prompt_chars: 20 },
9415
9454
  git_commit_indexing: { enabled: false, since_days: 365, max_commits: 2000 }
9416
- }).describe("Cross-session memory configuration")
9455
+ }).describe("Cross-session memory configuration. auto_search and git_commit_indexing sit here for history but work with memory.enabled false.")
9417
9456
  }).transform((data) => {
9418
9457
  return {
9419
9458
  ...data,
@@ -10190,17 +10229,17 @@ function pruneNestedConfigLeaf(block, relativePath) {
10190
10229
  // ../plugin/src/config/raw-loader.ts
10191
10230
  import {
10192
10231
  closeSync as closeSync3,
10193
- existsSync as existsSync3,
10232
+ existsSync as existsSync4,
10194
10233
  linkSync,
10195
10234
  openSync as openSync3,
10196
- readFileSync as readFileSync3,
10197
- realpathSync,
10235
+ readFileSync as readFileSync4,
10236
+ realpathSync as realpathSync2,
10198
10237
  renameSync as renameSync2,
10199
10238
  statSync as statSync3,
10200
10239
  unlinkSync as unlinkSync2,
10201
- writeFileSync as writeFileSync2
10240
+ writeFileSync as writeFileSync3
10202
10241
  } from "node:fs";
10203
- import { basename as basename2, dirname as dirname4, join as join4 } from "node:path";
10242
+ import { basename as basename3, dirname as dirname5, join as join4 } from "node:path";
10204
10243
  function isRecord(value) {
10205
10244
  return typeof value === "object" && value !== null && !Array.isArray(value);
10206
10245
  }
@@ -10394,7 +10433,7 @@ function writeExclusiveBackup(backupPath, bytes, mode) {
10394
10433
  if (error.code !== "EEXIST")
10395
10434
  throw error;
10396
10435
  }
10397
- const existingBytes = readFileSync3(backupPath);
10436
+ const existingBytes = readFileSync4(backupPath);
10398
10437
  if (existingBytes.equals(bytes))
10399
10438
  return;
10400
10439
  if (bytes.subarray(0, existingBytes.length).equals(existingBytes)) {
@@ -10408,15 +10447,15 @@ function writeExclusiveBackup(backupPath, bytes, mode) {
10408
10447
  }
10409
10448
  }
10410
10449
  function writeTemporaryCandidate(configPath, bytes, mode) {
10411
- const directory = dirname4(configPath);
10412
- const stem = basename2(configPath);
10450
+ const directory = dirname5(configPath);
10451
+ const stem = basename3(configPath);
10413
10452
  for (let attempt = 0;attempt < 32; attempt++) {
10414
10453
  temporaryFileSequence += 1;
10415
10454
  const path = join4(directory, `.${stem}.per-harness-${process.pid}-${temporaryFileSequence}.tmp`);
10416
10455
  let descriptor;
10417
10456
  try {
10418
10457
  descriptor = openSync3(path, "wx", mode);
10419
- writeFileSync2(descriptor, bytes);
10458
+ writeFileSync3(descriptor, bytes);
10420
10459
  closeSync3(descriptor);
10421
10460
  return path;
10422
10461
  } catch (error) {
@@ -10438,11 +10477,11 @@ function migrationWarning(diagnostic) {
10438
10477
  return diagnostic.message;
10439
10478
  }
10440
10479
  function loadRawConfigFile(options) {
10441
- if (!existsSync3(options.configPath))
10480
+ if (!existsSync4(options.configPath))
10442
10481
  return null;
10443
10482
  let observedBytes;
10444
10483
  try {
10445
- observedBytes = readFileSync3(options.configPath);
10484
+ observedBytes = readFileSync4(options.configPath);
10446
10485
  } catch (error) {
10447
10486
  throw new Error(`failed to read config: ${error instanceof Error ? error.message : String(error)}`);
10448
10487
  }
@@ -10482,12 +10521,12 @@ function loadRawConfigFile(options) {
10482
10521
  }
10483
10522
  let temporaryPath;
10484
10523
  try {
10485
- const writePath = realpathSync(options.configPath);
10524
+ const writePath = realpathSync2(options.configPath);
10486
10525
  const mode = options.tier === "user" ? 384 : statSync3(writePath).mode & 511;
10487
10526
  writeExclusiveBackup(backupPath, observedBytes, mode);
10488
10527
  temporaryPath = writeTemporaryCandidate(writePath, migration.bytes, mode);
10489
10528
  options.afterTemporaryWrite?.();
10490
- const currentBytes = readFileSync3(options.configPath);
10529
+ const currentBytes = readFileSync4(options.configPath);
10491
10530
  if (!hasFlatKeys(currentBytes)) {
10492
10531
  unlinkSync2(temporaryPath);
10493
10532
  return {
@@ -10597,9 +10636,9 @@ function resolveTransformMode(args) {
10597
10636
  var RUST_COMPACTION_OFF_WARNING = "compaction-off mode does not support rust transform mode; using the TypeScript transform.", RUST_REQUIRES_USER_SUBC_WARNING = "rust mode requires user-level subc configuration; running ts.";
10598
10637
 
10599
10638
  // ../plugin/src/config/variable.ts
10600
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
10639
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
10601
10640
  import { homedir as homedir5 } from "node:os";
10602
- import { dirname as dirname5, isAbsolute as isAbsolute3, resolve as resolve2 } from "node:path";
10641
+ import { dirname as dirname6, isAbsolute as isAbsolute3, resolve as resolve2 } from "node:path";
10603
10642
  function sensitiveFilePathReason(resolvedPath) {
10604
10643
  const home = homedir5();
10605
10644
  const sensitiveDirs = [
@@ -10646,7 +10685,7 @@ function substituteConfigVariables(input) {
10646
10685
  if (fileMatches.length === 0) {
10647
10686
  return { text, warnings };
10648
10687
  }
10649
- const configDir = input.configPath ? dirname5(input.configPath) : process.cwd();
10688
+ const configDir = input.configPath ? dirname6(input.configPath) : process.cwd();
10650
10689
  let output = "";
10651
10690
  let cursor = 0;
10652
10691
  for (const match of fileMatches) {
@@ -10672,13 +10711,13 @@ function substituteConfigVariables(input) {
10672
10711
  if (sensitiveReason) {
10673
10712
  warnings.push(`${token} resolves to a sensitive path (${sensitiveReason}: ${filePath}); ` + "inlining its contents into config — make sure this is intentional.");
10674
10713
  }
10675
- if (!existsSync4(filePath)) {
10714
+ if (!existsSync5(filePath)) {
10676
10715
  warnings.push(`File not found for ${token} (resolved to ${filePath}); using empty string`);
10677
10716
  continue;
10678
10717
  }
10679
10718
  let contents;
10680
10719
  try {
10681
- contents = readFileSync4(filePath, "utf-8").trim();
10720
+ contents = readFileSync5(filePath, "utf-8").trim();
10682
10721
  } catch (error) {
10683
10722
  const message = error instanceof Error ? error.message : String(error);
10684
10723
  warnings.push(`Failed to read file for ${token} (${filePath}): ${message}; using empty string`);
@@ -10697,7 +10736,7 @@ var init_variable = __esm(() => {
10697
10736
  });
10698
10737
 
10699
10738
  // ../plugin/src/config/index.ts
10700
- import { existsSync as existsSync5 } from "node:fs";
10739
+ import { existsSync as existsSync6 } from "node:fs";
10701
10740
  function getUserConfigBasePath() {
10702
10741
  return cortexKitUserConfigBasePath();
10703
10742
  }
@@ -10705,10 +10744,10 @@ function getProjectConfigBasePath(directory) {
10705
10744
  return cortexKitProjectConfigBasePath(directory);
10706
10745
  }
10707
10746
  function resolveLegacyReadFallback(sources) {
10708
- return { source: sources.find((s) => existsSync5(s.path)) ?? null };
10747
+ return { source: sources.find((s) => existsSync6(s.path)) ?? null };
10709
10748
  }
10710
10749
  function loadConfigFileDetailed(configPath, source) {
10711
- if (!existsSync5(configPath)) {
10750
+ if (!existsSync6(configPath)) {
10712
10751
  return null;
10713
10752
  }
10714
10753
  let rawText;
@@ -11062,8 +11101,8 @@ function loadPluginConfigDetailed(directory, applyRuntimeGlobals = true) {
11062
11101
  const harnessLegacy = resolveLegacyConfigSourcesForHarness(directory, "opencode");
11063
11102
  const userLegacyFallback = userDetected.format === "none" ? resolveLegacyReadFallback(harnessLegacy.user) : { source: null };
11064
11103
  const projectLegacyFallback = projectDetected.format === "none" ? resolveLegacyReadFallback(harnessLegacy.project) : { source: null };
11065
- const legacyUserUnmigrated = userDetected.format === "none" && !userLegacyFallback.source && legacySources.user.some((source) => existsSync5(source.path));
11066
- const legacyProjectUnmigrated = projectDetected.format === "none" && !projectLegacyFallback.source && legacySources.project.some((source) => existsSync5(source.path));
11104
+ const legacyUserUnmigrated = userDetected.format === "none" && !userLegacyFallback.source && legacySources.user.some((source) => existsSync6(source.path));
11105
+ const legacyProjectUnmigrated = projectDetected.format === "none" && !projectLegacyFallback.source && legacySources.project.some((source) => existsSync6(source.path));
11067
11106
  const userLoaded = userDetected.format !== "none" ? loadConfigFileDetailed(userDetected.path, "user") : userLegacyFallback.source ? loadConfigFileDetailed(userLegacyFallback.source.path, "user") : null;
11068
11107
  const projectLoaded = projectDetected.format !== "none" ? loadConfigFileDetailed(projectDetected.path, "project") : projectLegacyFallback.source ? loadConfigFileDetailed(projectLegacyFallback.source.path, "project") : null;
11069
11108
  const allWarnings = [];
@@ -13724,17 +13763,17 @@ import {
13724
13763
  accessSync,
13725
13764
  chmodSync as chmodSync3,
13726
13765
  constants,
13727
- existsSync as existsSync6,
13728
- mkdirSync as mkdirSync3,
13766
+ existsSync as existsSync7,
13767
+ mkdirSync as mkdirSync4,
13729
13768
  mkdtempSync,
13730
- readFileSync as readFileSync5,
13769
+ readFileSync as readFileSync6,
13731
13770
  renameSync as renameSync3,
13732
13771
  rmSync as rmSync3,
13733
13772
  statSync as statSync5,
13734
- writeFileSync as writeFileSync3
13773
+ writeFileSync as writeFileSync4
13735
13774
  } from "node:fs";
13736
13775
  import { homedir as homedir6, tmpdir as tmpdir2 } from "node:os";
13737
- import { dirname as dirname6, join as join5 } from "node:path";
13776
+ import { dirname as dirname7, join as join5 } from "node:path";
13738
13777
  import { promisify } from "node:util";
13739
13778
  import { gunzipSync } from "node:zlib";
13740
13779
  function resolveDashboardChoice(argv, interactive) {
@@ -13883,7 +13922,7 @@ async function download(deps, asset) {
13883
13922
  }
13884
13923
  function readMacAppVersion(appPath) {
13885
13924
  try {
13886
- const plist = readFileSync5(join5(appPath, "Contents", "Info.plist"), "utf8");
13925
+ const plist = readFileSync6(join5(appPath, "Contents", "Info.plist"), "utf8");
13887
13926
  const match = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(plist);
13888
13927
  return match?.[1]?.trim() ?? null;
13889
13928
  } catch {
@@ -13904,16 +13943,16 @@ async function detectInstalledDashboard(target, deps) {
13904
13943
  case "macos":
13905
13944
  for (const dir of macApplicationDirs(deps)) {
13906
13945
  const location = join5(dir, DASHBOARD_MAC_APP_NAME);
13907
- if (existsSync6(location))
13946
+ if (existsSync7(location))
13908
13947
  return { location, version: readMacAppVersion(location) };
13909
13948
  }
13910
13949
  return null;
13911
13950
  case "linux": {
13912
13951
  const location = linuxAppImagePath(deps.homeDir);
13913
- if (existsSync6(location)) {
13952
+ if (existsSync7(location)) {
13914
13953
  let version = null;
13915
13954
  try {
13916
- const marker = JSON.parse(readFileSync5(linuxVersionMarkerPath(deps.homeDir), "utf8"));
13955
+ const marker = JSON.parse(readFileSync6(linuxVersionMarkerPath(deps.homeDir), "utf8"));
13917
13956
  if (typeof marker.version === "string")
13918
13957
  version = marker.version;
13919
13958
  } catch {
@@ -13921,7 +13960,7 @@ async function detectInstalledDashboard(target, deps) {
13921
13960
  }
13922
13961
  return { location, version };
13923
13962
  }
13924
- if (existsSync6(deps.linuxSystemBinaryPath)) {
13963
+ if (existsSync7(deps.linuxSystemBinaryPath)) {
13925
13964
  return { location: deps.linuxSystemBinaryPath, version: null };
13926
13965
  }
13927
13966
  return null;
@@ -14042,7 +14081,7 @@ function findUnsafeTarEntry(tar) {
14042
14081
  async function installMac(data, deps, installed) {
14043
14082
  let destinationDir;
14044
14083
  if (installed) {
14045
- destinationDir = dirname6(installed.location);
14084
+ destinationDir = dirname7(installed.location);
14046
14085
  } else if (isWritableDir(deps.macSystemApplicationsDir)) {
14047
14086
  destinationDir = deps.macSystemApplicationsDir;
14048
14087
  } else {
@@ -14052,21 +14091,21 @@ async function installMac(data, deps, installed) {
14052
14091
  const unsafe = findUnsafeTarEntry(gunzipSync(data));
14053
14092
  if (unsafe)
14054
14093
  throw new Error(`the app archive is unsafe to extract: ${unsafe}`);
14055
- mkdirSync3(destinationDir, { recursive: true });
14094
+ mkdirSync4(destinationDir, { recursive: true });
14056
14095
  const staging = mkdtempSync(join5(destinationDir, ".magic-context-dashboard-"));
14057
14096
  try {
14058
14097
  const archive = join5(staging, "dashboard.app.tar.gz");
14059
- writeFileSync3(archive, data);
14098
+ writeFileSync4(archive, data);
14060
14099
  const extractDir = join5(staging, "extracted");
14061
- mkdirSync3(extractDir);
14100
+ mkdirSync4(extractDir);
14062
14101
  await deps.extractTarGz(archive, extractDir);
14063
14102
  const extracted = join5(extractDir, DASHBOARD_MAC_APP_NAME);
14064
- if (!existsSync6(extracted)) {
14103
+ if (!existsSync7(extracted)) {
14065
14104
  throw new Error(`the archive did not contain ${DASHBOARD_MAC_APP_NAME}`);
14066
14105
  }
14067
14106
  const finalPath = join5(destinationDir, DASHBOARD_MAC_APP_NAME);
14068
14107
  const previous = join5(staging, "previous.app");
14069
- const hadPrevious = existsSync6(finalPath);
14108
+ const hadPrevious = existsSync7(finalPath);
14070
14109
  if (hadPrevious)
14071
14110
  renameSync3(finalPath, previous);
14072
14111
  try {
@@ -14083,18 +14122,18 @@ async function installMac(data, deps, installed) {
14083
14122
  }
14084
14123
  function installLinux(data, version, deps) {
14085
14124
  const finalPath = linuxAppImagePath(deps.homeDir);
14086
- mkdirSync3(dirname6(finalPath), { recursive: true });
14125
+ mkdirSync4(dirname7(finalPath), { recursive: true });
14087
14126
  const partial = `${finalPath}.partial-${process.pid}`;
14088
14127
  try {
14089
- writeFileSync3(partial, data, { mode: 493 });
14128
+ writeFileSync4(partial, data, { mode: 493 });
14090
14129
  chmodSync3(partial, 493);
14091
14130
  renameSync3(partial, finalPath);
14092
14131
  } finally {
14093
14132
  rmSync3(partial, { force: true });
14094
14133
  }
14095
14134
  const marker = linuxVersionMarkerPath(deps.homeDir);
14096
- mkdirSync3(dirname6(marker), { recursive: true });
14097
- writeFileSync3(marker, `${JSON.stringify({ version, path: finalPath }, null, 2)}
14135
+ mkdirSync4(dirname7(marker), { recursive: true });
14136
+ writeFileSync4(marker, `${JSON.stringify({ version, path: finalPath }, null, 2)}
14098
14137
  `);
14099
14138
  return finalPath;
14100
14139
  }
@@ -14102,7 +14141,7 @@ async function installWindows(data, asset, deps) {
14102
14141
  const dir = mkdtempSync(join5(deps.tempRoot, "magic-context-dashboard-"));
14103
14142
  try {
14104
14143
  const installer = join5(dir, asset.name);
14105
- writeFileSync3(installer, data);
14144
+ writeFileSync4(installer, data);
14106
14145
  deps.log.info("Running the dashboard installer (per-user install, no administrator rights).");
14107
14146
  await deps.runWindowsInstaller(installer);
14108
14147
  } finally {
@@ -14258,7 +14297,7 @@ var init_dashboard_install = __esm(() => {
14258
14297
  });
14259
14298
 
14260
14299
  // src/lib/docs-proposal-gitignore.ts
14261
- import { appendFileSync as appendFileSync2, existsSync as existsSync7, readFileSync as readFileSync6 } from "node:fs";
14300
+ import { appendFileSync as appendFileSync2, existsSync as existsSync8, readFileSync as readFileSync7 } from "node:fs";
14262
14301
  import { join as join6 } from "node:path";
14263
14302
  function coversProposalState(line) {
14264
14303
  const rule = line.trim();
@@ -14268,16 +14307,16 @@ function coversProposalState(line) {
14268
14307
  return COVERING_PATHS.has(normalized);
14269
14308
  }
14270
14309
  function ensureDocsProposalGitignore(projectDir) {
14271
- if (!existsSync7(join6(projectDir, ".git")))
14310
+ if (!existsSync8(join6(projectDir, ".git")))
14272
14311
  return { status: "not-a-repository" };
14273
14312
  const path = join6(projectDir, ".gitignore");
14274
14313
  try {
14275
- const text = existsSync7(path) ? readFileSync6(path, "utf8") : "";
14314
+ const text = existsSync8(path) ? readFileSync7(path, "utf8") : "";
14276
14315
  if (text.split(/\r?\n/).some(coversProposalState))
14277
14316
  return { status: "covered" };
14278
14317
  const nestedPath = join6(projectDir, ".cortexkit", ".gitignore");
14279
- if (existsSync7(nestedPath)) {
14280
- const nested = readFileSync6(nestedPath, "utf8").split(/\r?\n/);
14318
+ if (existsSync8(nestedPath)) {
14319
+ const nested = readFileSync7(nestedPath, "utf8").split(/\r?\n/);
14281
14320
  if (nested.some((line) => /^\/?magic-context(\/(\*\*?)?)?$/.test(line.trim()))) {
14282
14321
  return { status: "covered" };
14283
14322
  }
@@ -14301,7 +14340,7 @@ var init_docs_proposal_gitignore = __esm(() => {
14301
14340
  });
14302
14341
 
14303
14342
  // src/lib/find-on-path.ts
14304
- import { accessSync as accessSync2, constants as constants2, existsSync as existsSync8, statSync as statSync6 } from "node:fs";
14343
+ import { accessSync as accessSync2, constants as constants2, existsSync as existsSync9, statSync as statSync6 } from "node:fs";
14305
14344
  import { delimiter, join as join7 } from "node:path";
14306
14345
  function findOnPath(binary) {
14307
14346
  const PATH = process.env.PATH;
@@ -14323,7 +14362,7 @@ function findOnPath(binary) {
14323
14362
  }
14324
14363
  function isExecutableFile(path, isWindows = process.platform === "win32") {
14325
14364
  try {
14326
- if (!existsSync8(path))
14365
+ if (!existsSync9(path))
14327
14366
  return false;
14328
14367
  const st = statSync6(path);
14329
14368
  if (!st.isFile())
@@ -14340,9 +14379,9 @@ function isExecutableFile(path, isWindows = process.platform === "win32") {
14340
14379
  var init_find_on_path = () => {};
14341
14380
 
14342
14381
  // src/lib/paths.ts
14343
- import { existsSync as existsSync9, readdirSync as readdirSync2, statSync as statSync7 } from "node:fs";
14382
+ import { existsSync as existsSync10, readdirSync as readdirSync2, statSync as statSync7 } from "node:fs";
14344
14383
  import { homedir as homedir7 } from "node:os";
14345
- import { delimiter as delimiter2, dirname as dirname7, join as join8, resolve as resolve3 } from "node:path";
14384
+ import { delimiter as delimiter2, dirname as dirname8, join as join8, resolve as resolve3 } from "node:path";
14346
14385
  function getOpenCodeConfigDir() {
14347
14386
  const envDir = process.env.OPENCODE_CONFIG_DIR?.trim();
14348
14387
  if (envDir)
@@ -14361,7 +14400,7 @@ function findOmoConfig(configDir) {
14361
14400
  join8(configDir, "oh-my-opencode.json")
14362
14401
  ];
14363
14402
  for (const loc of locations) {
14364
- if (existsSync9(loc))
14403
+ if (existsSync10(loc))
14365
14404
  return loc;
14366
14405
  }
14367
14406
  return null;
@@ -14374,10 +14413,10 @@ function detectConfigPaths() {
14374
14413
  let tuiConfigFormat;
14375
14414
  const jsoncPath = join8(configDir, "opencode.jsonc");
14376
14415
  const jsonPath = join8(configDir, "opencode.json");
14377
- if (existsSync9(jsoncPath)) {
14416
+ if (existsSync10(jsoncPath)) {
14378
14417
  opencodeConfig = jsoncPath;
14379
14418
  opencodeConfigFormat = "jsonc";
14380
- } else if (existsSync9(jsonPath)) {
14419
+ } else if (existsSync10(jsonPath)) {
14381
14420
  opencodeConfig = jsonPath;
14382
14421
  opencodeConfigFormat = "json";
14383
14422
  } else {
@@ -14386,10 +14425,10 @@ function detectConfigPaths() {
14386
14425
  }
14387
14426
  const tuiJsoncPath = join8(configDir, "tui.jsonc");
14388
14427
  const tuiJsonPath = join8(configDir, "tui.json");
14389
- if (existsSync9(tuiJsoncPath)) {
14428
+ if (existsSync10(tuiJsoncPath)) {
14390
14429
  tuiConfig = tuiJsoncPath;
14391
14430
  tuiConfigFormat = "jsonc";
14392
- } else if (existsSync9(tuiJsonPath)) {
14431
+ } else if (existsSync10(tuiJsonPath)) {
14393
14432
  tuiConfig = tuiJsonPath;
14394
14433
  tuiConfigFormat = "json";
14395
14434
  } else {
@@ -14423,7 +14462,7 @@ function getPiSessionsRoot() {
14423
14462
  return join8(getPiAgentDir(), "sessions");
14424
14463
  }
14425
14464
  function getPiCacheRoot() {
14426
- return join8(dirname7(getPiAgentDir()), "cache");
14465
+ return join8(dirname8(getPiAgentDir()), "cache");
14427
14466
  }
14428
14467
  function getPiUserConfigPath() {
14429
14468
  return resolveCortexKitUserConfigPath();
@@ -14448,7 +14487,7 @@ function resolveOmpPaths() {
14448
14487
  if (xdgDataHome) {
14449
14488
  const appRoot = join8(xdgDataHome, "omp");
14450
14489
  const candidate = profile ? join8(appRoot, "profiles", profile) : appRoot;
14451
- if (existsSync9(candidate))
14490
+ if (existsSync10(candidate))
14452
14491
  dataRoot = candidate;
14453
14492
  }
14454
14493
  }
@@ -14485,7 +14524,7 @@ function getOmpPackageDir() {
14485
14524
  function getOmpNonGlobalConfigSources(cwd = process.cwd()) {
14486
14525
  const sources = getOmpConfigOverlayPaths(cwd);
14487
14526
  const projectConfig = resolve3(cwd, ".omp", "config.yml");
14488
- if (existsSync9(projectConfig))
14527
+ if (existsSync10(projectConfig))
14489
14528
  sources.push(projectConfig);
14490
14529
  return [...new Set(sources)];
14491
14530
  }
@@ -14663,7 +14702,7 @@ var init_pi_helpers = __esm(() => {
14663
14702
 
14664
14703
  // src/lib/omp-helpers.ts
14665
14704
  import { spawnSync as spawnSync2 } from "node:child_process";
14666
- import { existsSync as existsSync10, readFileSync as readFileSync7 } from "node:fs";
14705
+ import { existsSync as existsSync11, readFileSync as readFileSync8 } from "node:fs";
14667
14706
  import { homedir as homedir9 } from "node:os";
14668
14707
  import { extname as extname2, join as join10 } from "node:path";
14669
14708
  function detectOmpPackageCli() {
@@ -14673,11 +14712,11 @@ function detectOmpPackageCli() {
14673
14712
  if (!findOnPath("bun"))
14674
14713
  return null;
14675
14714
  try {
14676
- const manifest = JSON.parse(readFileSync7(join10(packageDir, "package.json"), "utf-8"));
14715
+ const manifest = JSON.parse(readFileSync8(join10(packageDir, "package.json"), "utf-8"));
14677
14716
  if (manifest.name !== "@oh-my-pi/pi-coding-agent")
14678
14717
  return null;
14679
14718
  const cli = join10(packageDir, "dist", "cli.js");
14680
- return existsSync10(cli) ? cli : null;
14719
+ return existsSync11(cli) ? cli : null;
14681
14720
  } catch {
14682
14721
  return null;
14683
14722
  }
@@ -14821,7 +14860,7 @@ var init_omp_helpers = __esm(() => {
14821
14860
  });
14822
14861
 
14823
14862
  // src/adapters/omp.ts
14824
- import { existsSync as existsSync11, readFileSync as readFileSync8 } from "node:fs";
14863
+ import { existsSync as existsSync12, readFileSync as readFileSync9 } from "node:fs";
14825
14864
  import { join as join11 } from "node:path";
14826
14865
 
14827
14866
  class OmpAdapter {
@@ -14923,7 +14962,7 @@ class OmpAdapter {
14923
14962
  }
14924
14963
  getPluginCacheInfo() {
14925
14964
  const path = join11(getOmpPluginsDir(), "cache");
14926
- return [{ path, exists: existsSync11(path), sizeBytes: dirSizeBytes(path) }];
14965
+ return [{ path, exists: existsSync12(path), sizeBytes: dirSizeBytes(path) }];
14927
14966
  }
14928
14967
  getLogPath() {
14929
14968
  return getMagicContextLogPath2("omp");
@@ -14936,7 +14975,7 @@ class OmpAdapter {
14936
14975
  }
14937
14976
  readRuntimeEnabled(configPath) {
14938
14977
  try {
14939
- const lock = JSON.parse(readFileSync8(configPath, "utf-8"));
14978
+ const lock = JSON.parse(readFileSync9(configPath, "utf-8"));
14940
14979
  const enabled = lock.plugins?.[OMP_PLUGIN_PACKAGE]?.enabled;
14941
14980
  return typeof enabled === "boolean" ? enabled : undefined;
14942
14981
  } catch {
@@ -14964,7 +15003,7 @@ var init_omp = __esm(() => {
14964
15003
  });
14965
15004
 
14966
15005
  // ../plugin/src/shared/opencode-db-path.ts
14967
- import { existsSync as existsSync12, readdirSync as readdirSync3, statSync as statSync8 } from "node:fs";
15006
+ import { existsSync as existsSync13, readdirSync as readdirSync3, statSync as statSync8 } from "node:fs";
14968
15007
  import { homedir as homedir10 } from "node:os";
14969
15008
  import { isAbsolute as isAbsolute4, join as join12, resolve as resolve4 } from "node:path";
14970
15009
  function openCodeHostGenerationFromVersion(version) {
@@ -15063,7 +15102,7 @@ function resolveOpenCodeDbPath(hostGeneration = "v1", options = {}) {
15063
15102
  const dataDir = openCodeDataDir(env, options.dataHome);
15064
15103
  const channel = options.channel ?? env.OPENCODE_CHANNEL;
15065
15104
  const key = environmentKey(dataDir, hostGeneration, channel, env);
15066
- if (cachedResolution?.key === key && (!cachedResolution.existed || existsSync12(cachedResolution.resolution.path))) {
15105
+ if (cachedResolution?.key === key && (!cachedResolution.existed || existsSync13(cachedResolution.resolution.path))) {
15067
15106
  if (cachedResolution.existed)
15068
15107
  return cachedResolution.resolution;
15069
15108
  }
@@ -15071,7 +15110,7 @@ function resolveOpenCodeDbPath(hostGeneration = "v1", options = {}) {
15071
15110
  cachedResolution = {
15072
15111
  key,
15073
15112
  resolution,
15074
- existed: resolution.path !== ":memory:" && existsSync12(resolution.path)
15113
+ existed: resolution.path !== ":memory:" && existsSync13(resolution.path)
15075
15114
  };
15076
15115
  return resolution;
15077
15116
  }
@@ -15111,7 +15150,7 @@ function assertOpenCodeStoreGeneration(db, expected, path, schema = "main") {
15111
15150
  throw new Error(`OpenCode store generation mismatch at ${path}: expected ${expected}, found ${actual}; refusing generation-specific database access`);
15112
15151
  }
15113
15152
  function openCodeDbPathExists(resolution = resolveOpenCodeDbPath()) {
15114
- return resolution.path !== ":memory:" && existsSync12(resolution.path);
15153
+ return resolution.path !== ":memory:" && existsSync13(resolution.path);
15115
15154
  }
15116
15155
  function getOpenCodeDbProbeDescriptions(resolution = resolveOpenCodeDbPath()) {
15117
15156
  if (resolution.source === "OPENCODE_DB")
@@ -23030,7 +23069,7 @@ var init_project_directory_key = () => {};
23030
23069
 
23031
23070
  // ../plugin/src/shared/rpc-utils.ts
23032
23071
  import { execFile as execFile2, execFileSync as execFileSync2 } from "node:child_process";
23033
- import { readFileSync as readFileSync9 } from "node:fs";
23072
+ import { readFileSync as readFileSync10 } from "node:fs";
23034
23073
  function isOwnRpcServerRecord(record) {
23035
23074
  return record.pid === process.pid && record.instance_id !== undefined && ownRpcServerInstanceIds.has(record.instance_id);
23036
23075
  }
@@ -23625,7 +23664,7 @@ var init_rpc_utils = __esm(() => {
23625
23664
  "cljs/dist",
23626
23665
  "dist/bundle/cli"
23627
23666
  ];
23628
- rpcIdentityReadFileSync = readFileSync9;
23667
+ rpcIdentityReadFileSync = readFileSync10;
23629
23668
  rpcIdentityExecFileSync = execFileSync2;
23630
23669
  rpcIdentityProcessKill = process.kill;
23631
23670
  rpcProcessListExecFileSync = execFileSync2;
@@ -23666,7 +23705,7 @@ var init_opencode_plugin_registration = __esm(() => {
23666
23705
  });
23667
23706
 
23668
23707
  // src/lib/opencode-plugin-cache.ts
23669
- import { readdirSync as readdirSync4, readFileSync as readFileSync10 } from "node:fs";
23708
+ import { readdirSync as readdirSync4, readFileSync as readFileSync11 } from "node:fs";
23670
23709
  import { join as join13 } from "node:path";
23671
23710
  function getOpenCodePluginCacheRoots() {
23672
23711
  const cacheDir = getOpenCodePluginCacheDir();
@@ -23769,7 +23808,7 @@ function readOpenCodeV2CachedPluginVersion(slot) {
23769
23808
  if (!generation)
23770
23809
  return;
23771
23810
  try {
23772
- const pkg = JSON.parse(readFileSync10(getOpenCodePluginPackageJsonPath(generation), "utf-8"));
23811
+ const pkg = JSON.parse(readFileSync11(getOpenCodePluginPackageJsonPath(generation), "utf-8"));
23773
23812
  return typeof pkg.version === "string" ? pkg.version : undefined;
23774
23813
  } catch {
23775
23814
  return;
@@ -23783,7 +23822,7 @@ var init_opencode_plugin_cache = __esm(() => {
23783
23822
  });
23784
23823
 
23785
23824
  // src/commands/doctor-windows-holders.ts
23786
- import { existsSync as existsSync13 } from "node:fs";
23825
+ import { existsSync as existsSync14 } from "node:fs";
23787
23826
  function assertWindowsStoresClosed(paths, processes) {
23788
23827
  if (processes.pi.state !== "known" || processes.pi.processIds.length > 0 || (processes.pi.inconclusivePids?.length ?? 0) > 0 || processes.processSnapshot?.source !== "cim") {
23789
23828
  throw new Error(`Windows process probe could not rule out OpenCode, Pi or ck-mc holders${processes.pi.processIds.length || processes.pi.inconclusivePids?.length ? ` (PID ${[...processes.pi.processIds, ...processes.pi.inconclusivePids ?? []].join(", ")})` : ""}`);
@@ -23799,7 +23838,7 @@ function assertWindowsStoresClosed(paths, processes) {
23799
23838
  if (blockers.length)
23800
23839
  throw new Error(`OpenCode, Pi or ck-mc process is running (${blockers.map(({ pid, imageName, commandLine }) => `${imageName ?? commandLine} PID ${pid}`).join(", ")})`);
23801
23840
  for (const path of [...new Set(paths)]) {
23802
- if (!existsSync13(path))
23841
+ if (!existsSync14(path))
23803
23842
  continue;
23804
23843
  let db;
23805
23844
  let locked = false;
@@ -23823,7 +23862,7 @@ var init_doctor_windows_holders = __esm(async () => {
23823
23862
 
23824
23863
  // src/commands/doctor-opencode2-cache.ts
23825
23864
  import { spawnSync as spawnSync3 } from "node:child_process";
23826
- import { existsSync as existsSync14, rmSync as rmSync4 } from "node:fs";
23865
+ import { existsSync as existsSync15, rmSync as rmSync4 } from "node:fs";
23827
23866
  function runLsof(args, spawn) {
23828
23867
  const result = spawn("lsof", args, { encoding: "utf-8", timeout: 15000, windowsHide: true });
23829
23868
  if (result.error)
@@ -23838,7 +23877,7 @@ function probeHostProcessesUsing(targets, spawn = spawnSync3) {
23838
23877
  if (process.platform === "win32") {
23839
23878
  try {
23840
23879
  assertWindowsStoresClosed(targets.files.filter((path) => !/-(?:wal|shm)$/.test(path)), inspectWindowsProcessesSync());
23841
- if (targets.directories.some(existsSync14))
23880
+ if (targets.directories.some(existsSync15))
23842
23881
  return {
23843
23882
  status: "unknown",
23844
23883
  reason: "Windows cannot rule out open files in plugin cache directories"
@@ -23851,8 +23890,8 @@ function probeHostProcessesUsing(targets, spawn = spawnSync3) {
23851
23890
  };
23852
23891
  }
23853
23892
  }
23854
- const files = targets.files.filter((file) => existsSync14(file));
23855
- const directories = targets.directories.filter((directory) => existsSync14(directory));
23893
+ const files = targets.files.filter((file) => existsSync15(file));
23894
+ const directories = targets.directories.filter((directory) => existsSync15(directory));
23856
23895
  const queries = [];
23857
23896
  if (files.length > 0)
23858
23897
  queries.push(["-w", "-t", "--", ...files]);
@@ -23947,9 +23986,9 @@ function checkOpenCodeV2PluginCache(options, deps = {}) {
23947
23986
  const slot = deps.slot ?? getOpenCodeV2PluginCacheSlot(undefined, distTag ?? "latest");
23948
23987
  const tagged = distTag ? { distTag } : {};
23949
23988
  if (options.referencedSpecs !== undefined && !options.referencedSpecs.has(distTag ?? "latest")) {
23950
- return existsSync14(slot) ? { action: "unused", slot, cached: readOpenCodeV2CachedPluginVersion(slot), ...tagged } : { action: "not_found", slot, unused: true, ...tagged };
23989
+ return existsSync15(slot) ? { action: "unused", slot, cached: readOpenCodeV2CachedPluginVersion(slot), ...tagged } : { action: "not_found", slot, unused: true, ...tagged };
23951
23990
  }
23952
- if (!existsSync14(slot))
23991
+ if (!existsSync15(slot))
23953
23992
  return { action: "not_found", slot, ...tagged };
23954
23993
  const cached = readOpenCodeV2CachedPluginVersion(slot);
23955
23994
  const latest = options.latestVersion ?? undefined;
@@ -24041,22 +24080,22 @@ var init_doctor_opencode2_cache = __esm(async () => {
24041
24080
  // src/lib/atomic-write.ts
24042
24081
  import { randomBytes as randomBytes2 } from "node:crypto";
24043
24082
  import {
24044
- lstatSync as lstatSync2,
24045
- mkdirSync as mkdirSync4,
24046
- readlinkSync as readlinkSync2,
24083
+ lstatSync as lstatSync3,
24084
+ mkdirSync as mkdirSync5,
24085
+ readlinkSync as readlinkSync3,
24047
24086
  renameSync as renameSync4,
24048
24087
  rmSync as rmSync5,
24049
24088
  statSync as statSync9,
24050
- writeFileSync as writeFileSync4
24089
+ writeFileSync as writeFileSync5
24051
24090
  } from "node:fs";
24052
- import { dirname as dirname8, resolve as resolve5 } from "node:path";
24091
+ import { dirname as dirname9, resolve as resolve5 } from "node:path";
24053
24092
  function resolveWriteTarget(targetPath) {
24054
24093
  let current = resolve5(targetPath);
24055
24094
  for (let hop = 0;hop < MAX_SYMLINK_HOPS; hop++) {
24056
- const stat = lstatSync2(current, { throwIfNoEntry: false });
24095
+ const stat = lstatSync3(current, { throwIfNoEntry: false });
24057
24096
  if (!stat?.isSymbolicLink())
24058
24097
  return current;
24059
- current = resolve5(dirname8(current), readlinkSync2(current));
24098
+ current = resolve5(dirname9(current), readlinkSync3(current));
24060
24099
  }
24061
24100
  throw new Error(`Too many levels of symbolic links resolving ${targetPath}`);
24062
24101
  }
@@ -24066,12 +24105,12 @@ function writeFileAtomic(targetPath, data, options = {}) {
24066
24105
  writeStorageFileAtomicSync(finalPath, data, true);
24067
24106
  return;
24068
24107
  }
24069
- mkdirSync4(dirname8(finalPath), { recursive: true });
24108
+ mkdirSync5(dirname9(finalPath), { recursive: true });
24070
24109
  const existing = statSync9(finalPath, { throwIfNoEntry: false });
24071
24110
  const mode = existing?.isFile() ? existing.mode & 511 : undefined;
24072
24111
  const tmpPath = `${finalPath}.${process.pid}.${randomBytes2(6).toString("hex")}.tmp`;
24073
24112
  try {
24074
- writeFileSync4(tmpPath, data, {
24113
+ writeFileSync5(tmpPath, data, {
24075
24114
  encoding: "utf-8",
24076
24115
  flag: "wx",
24077
24116
  ...mode !== undefined ? { mode } : {}
@@ -24088,7 +24127,7 @@ var init_atomic_write = __esm(() => {
24088
24127
  });
24089
24128
 
24090
24129
  // src/lib/jsonc-config.ts
24091
- import { existsSync as existsSync15, readFileSync as readFileSync11 } from "node:fs";
24130
+ import { existsSync as existsSync16, readFileSync as readFileSync12 } from "node:fs";
24092
24131
  function parseErrorLocation(content, error) {
24093
24132
  const lines = content.split(`
24094
24133
  `);
@@ -24104,9 +24143,9 @@ function parseErrorLocation(content, error) {
24104
24143
  return { line: messageLine ? Number.parseInt(messageLine, 10) : 1, column: 1 };
24105
24144
  }
24106
24145
  function readJsoncConfig(path) {
24107
- if (!existsSync15(path))
24146
+ if (!existsSync16(path))
24108
24147
  return { kind: "missing" };
24109
- const content = readFileSync11(path, "utf-8");
24148
+ const content = readFileSync12(path, "utf-8");
24110
24149
  try {
24111
24150
  const rejectedKeyPaths = [];
24112
24151
  const parsed = sanitizeParsedJson(import_comment_json.parse(content), {
@@ -24132,7 +24171,7 @@ function readJsoncConfigForUpdate(path) {
24132
24171
  return result.value;
24133
24172
  }
24134
24173
  function readJsoncTextForEdit(configPath) {
24135
- const raw = readFileSync11(configPath, "utf-8");
24174
+ const raw = readFileSync12(configPath, "utf-8");
24136
24175
  return raw.startsWith(BYTE_ORDER_MARK) ? { bom: BYTE_ORDER_MARK, text: raw.slice(BYTE_ORDER_MARK.length) } : { bom: "", text: raw };
24137
24176
  }
24138
24177
  function assertJsoncConfigsParseable(paths) {
@@ -24221,13 +24260,13 @@ var init_jsonc_config = __esm(() => {
24221
24260
  });
24222
24261
 
24223
24262
  // src/lib/opencode-detect.ts
24224
- import { existsSync as existsSync16, realpathSync as realpathSync2 } from "node:fs";
24263
+ import { existsSync as existsSync17, realpathSync as realpathSync3 } from "node:fs";
24225
24264
  import { homedir as homedir11 } from "node:os";
24226
24265
  import { join as join14 } from "node:path";
24227
24266
  function defaultDeps(overrides = {}) {
24228
24267
  const env = overrides.env ?? process.env;
24229
24268
  return {
24230
- exists: overrides.exists ?? existsSync16,
24269
+ exists: overrides.exists ?? existsSync17,
24231
24270
  isExecutable: overrides.isExecutable ?? isExecutableFile,
24232
24271
  home: overrides.home ?? (env.HOME?.trim() || homedir11()),
24233
24272
  platform: overrides.platform ?? process.platform,
@@ -24278,7 +24317,7 @@ function openChamberCliCandidates(d) {
24278
24317
  }
24279
24318
  function canonicalPath(d, path) {
24280
24319
  try {
24281
- return d.realpath ? d.realpath(path) : realpathSync2(path);
24320
+ return d.realpath ? d.realpath(path) : realpathSync3(path);
24282
24321
  } catch {
24283
24322
  return path;
24284
24323
  }
@@ -24441,8 +24480,8 @@ var OPENCODE_BINARY_ENV = "MAGIC_CONTEXT_OPENCODE_BINARY", OPENCODE_VERSION_PROB
24441
24480
  var init_opencode_helpers = () => {};
24442
24481
 
24443
24482
  // src/adapters/opencode.ts
24444
- import { existsSync as existsSync17, readFileSync as readFileSync12, statSync as statSync10 } from "node:fs";
24445
- import { dirname as dirname9, isAbsolute as isAbsolute5, parse as parsePath, resolve as resolve6 } from "node:path";
24483
+ import { existsSync as existsSync18, readFileSync as readFileSync13, statSync as statSync10 } from "node:fs";
24484
+ import { dirname as dirname10, isAbsolute as isAbsolute5, parse as parsePath, resolve as resolve6 } from "node:path";
24446
24485
  import { fileURLToPath as fileURLToPath2 } from "node:url";
24447
24486
 
24448
24487
  class OpenCodeAdapter {
@@ -24473,7 +24512,7 @@ class OpenCodeAdapter {
24473
24512
  if (paths.opencodeConfigFormat === "none")
24474
24513
  return false;
24475
24514
  try {
24476
- const raw = readFileSync12(paths.opencodeConfig, "utf-8");
24515
+ const raw = readFileSync13(paths.opencodeConfig, "utf-8");
24477
24516
  const cfg = import_comment_json2.parse(raw);
24478
24517
  return readPluginEntries(cfg).some(({ entry }) => matchesPluginEntry(entry, OPENCODE_PLUGIN_NAME));
24479
24518
  } catch {
@@ -24509,7 +24548,7 @@ class OpenCodeAdapter {
24509
24548
  configPath: target
24510
24549
  };
24511
24550
  }
24512
- const raw = readFileSync12(target, "utf-8");
24551
+ const raw = readFileSync13(target, "utf-8");
24513
24552
  const cfg = import_comment_json2.parse(raw);
24514
24553
  if (cfg === null || typeof cfg !== "object") {
24515
24554
  return {
@@ -24521,7 +24560,7 @@ class OpenCodeAdapter {
24521
24560
  }
24522
24561
  const entries = readPluginEntries(cfg);
24523
24562
  const existing = entries.find(({ entry }) => matchesPluginEntry(entry, OPENCODE_PLUGIN_NAME));
24524
- const existingDev = entries.find(({ entry }) => isDevPathPluginEntry(entry, dirname9(target)));
24563
+ const existingDev = entries.find(({ entry }) => isDevPathPluginEntry(entry, dirname10(target)));
24525
24564
  if (!existing && !existingDev) {
24526
24565
  const list = Array.isArray(cfg[this.writeKey]) ? cfg[this.writeKey] : [];
24527
24566
  list.push(OPENCODE_PLUGIN_ENTRY_WITH_VERSION);
@@ -24584,7 +24623,7 @@ class OpenCodeAdapter {
24584
24623
  };
24585
24624
  }
24586
24625
  try {
24587
- const raw = readFileSync12(target, "utf-8");
24626
+ const raw = readFileSync13(target, "utf-8");
24588
24627
  const cfg = import_comment_json2.parse(raw);
24589
24628
  if (cfg === null || typeof cfg !== "object") {
24590
24629
  return {
@@ -24635,9 +24674,9 @@ class OpenCodeAdapter {
24635
24674
  }
24636
24675
  getPluginCacheInfo() {
24637
24676
  const legacyPath = getOpenCodePluginCacheDir();
24638
- const legacyExists = existsSync17(legacyPath);
24677
+ const legacyExists = existsSync18(legacyPath);
24639
24678
  const slot = getOpenCodeV2PluginCacheSlot();
24640
- const slotExists = existsSync17(slot);
24679
+ const slotExists = existsSync18(slot);
24641
24680
  const caches = [];
24642
24681
  if (legacyExists || !slotExists) {
24643
24682
  caches.push({
@@ -24695,7 +24734,7 @@ class OpenCodeAdapter {
24695
24734
  if (paths.opencodeConfigFormat === "none")
24696
24735
  return "latest";
24697
24736
  try {
24698
- const cfg = import_comment_json2.parse(readFileSync12(paths.opencodeConfig, "utf-8"));
24737
+ const cfg = import_comment_json2.parse(readFileSync13(paths.opencodeConfig, "utf-8"));
24699
24738
  return readConfiguredOpenCodePluginSpec(cfg);
24700
24739
  } catch {
24701
24740
  return "latest";
@@ -24707,10 +24746,10 @@ class OpenCodeAdapter {
24707
24746
  return readOpenCodeV2CachedPluginVersion(slot) ?? null;
24708
24747
  }
24709
24748
  for (const candidate of getOpenCodePluginPackageJsonPaths()) {
24710
- if (!existsSync17(candidate))
24749
+ if (!existsSync18(candidate))
24711
24750
  continue;
24712
24751
  try {
24713
- const raw = readFileSync12(candidate, "utf-8");
24752
+ const raw = readFileSync13(candidate, "utf-8");
24714
24753
  const pkg = JSON.parse(raw);
24715
24754
  if (typeof pkg.version === "string")
24716
24755
  return pkg.version;
@@ -24749,15 +24788,15 @@ function isDevPathPluginEntry(entry, configDir) {
24749
24788
  localPath = resolve6(configDir, candidate);
24750
24789
  }
24751
24790
  if (statSync10(localPath).isFile())
24752
- localPath = dirname9(localPath);
24791
+ localPath = dirname10(localPath);
24753
24792
  const root = parsePath(localPath).root;
24754
24793
  while (localPath !== root) {
24755
24794
  const packagePath = resolve6(localPath, "package.json");
24756
- if (existsSync17(packagePath)) {
24757
- const pkg = JSON.parse(readFileSync12(packagePath, "utf8"));
24795
+ if (existsSync18(packagePath)) {
24796
+ const pkg = JSON.parse(readFileSync13(packagePath, "utf8"));
24758
24797
  return pkg.name === OPENCODE_PLUGIN_NAME;
24759
24798
  }
24760
- localPath = dirname9(localPath);
24799
+ localPath = dirname10(localPath);
24761
24800
  }
24762
24801
  } catch {}
24763
24802
  return false;
@@ -24773,8 +24812,8 @@ function matchesPluginEntry(entry, pkgName) {
24773
24812
  return head === pkgName;
24774
24813
  }
24775
24814
  function ensureDir2(filePath) {
24776
- const dir = dirname9(filePath);
24777
- if (!existsSync17(dir)) {
24815
+ const dir = dirname10(filePath);
24816
+ if (!existsSync18(dir)) {
24778
24817
  const { mkdirSync } = __require("node:fs");
24779
24818
  mkdirSync(dir, { recursive: true });
24780
24819
  }
@@ -24795,7 +24834,7 @@ var init_opencode = __esm(async () => {
24795
24834
  });
24796
24835
 
24797
24836
  // src/lib/pi-package-entry.ts
24798
- import { existsSync as existsSync18, readFileSync as readFileSync13 } from "node:fs";
24837
+ import { existsSync as existsSync19, readFileSync as readFileSync14 } from "node:fs";
24799
24838
  import { isAbsolute as isAbsolute6, join as join15 } from "node:path";
24800
24839
  function stripNpmPrefix(value) {
24801
24840
  return value.startsWith("npm:") ? value.slice("npm:".length) : value;
@@ -24852,10 +24891,10 @@ function hasPiMagicContextPackage(entries, agentDir = getPiAgentConfigDir()) {
24852
24891
  }
24853
24892
  function isPiMagicContextPackageDir(dir) {
24854
24893
  const packageJson = join15(dir, "package.json");
24855
- if (!existsSync18(packageJson))
24894
+ if (!existsSync19(packageJson))
24856
24895
  return false;
24857
24896
  try {
24858
- const pkg = JSON.parse(readFileSync13(packageJson, "utf-8"));
24897
+ const pkg = JSON.parse(readFileSync14(packageJson, "utf-8"));
24859
24898
  return typeof pkg.name === "string" && pkg.name === PI_MAGIC_CONTEXT_PACKAGE_NAME;
24860
24899
  } catch {
24861
24900
  return false;
@@ -24891,8 +24930,8 @@ var init_pi_package_entry = __esm(() => {
24891
24930
  });
24892
24931
 
24893
24932
  // src/adapters/pi.ts
24894
- import { existsSync as existsSync19 } from "node:fs";
24895
- import { dirname as dirname10 } from "node:path";
24933
+ import { existsSync as existsSync20 } from "node:fs";
24934
+ import { dirname as dirname11 } from "node:path";
24896
24935
 
24897
24936
  class PiAdapter {
24898
24937
  kind = "pi";
@@ -25029,8 +25068,8 @@ function writePiSettings(settings) {
25029
25068
  `);
25030
25069
  }
25031
25070
  function ensureDir3(filePath) {
25032
- const dir = dirname10(filePath);
25033
- if (!existsSync19(dir)) {
25071
+ const dir = dirname11(filePath);
25072
+ if (!existsSync20(dir)) {
25034
25073
  const { mkdirSync } = __require("node:fs");
25035
25074
  mkdirSync(dir, { recursive: true });
25036
25075
  }
@@ -26612,7 +26651,7 @@ function installCompartmentHistoryVersions(db) {
26612
26651
 
26613
26652
  // ../plugin/src/features/magic-context/memory/project-identity-cache.ts
26614
26653
  import { createHash as createHash4 } from "node:crypto";
26615
- import { readFileSync as readFileSync14 } from "node:fs";
26654
+ import { readFileSync as readFileSync15 } from "node:fs";
26616
26655
  import path4 from "node:path";
26617
26656
  function cachePath(directory, storageDir = getMagicContextStorageDir()) {
26618
26657
  const hash = createHash4("sha256").update(projectDirectoryKey(directory)).digest("hex");
@@ -26626,7 +26665,7 @@ function rememberGitIdentity(directory, identity) {
26626
26665
  }
26627
26666
  function readRememberedGitIdentity(directory, storageDir) {
26628
26667
  try {
26629
- const record = JSON.parse(readFileSync14(cachePath(directory, storageDir), "utf8"));
26668
+ const record = JSON.parse(readFileSync15(cachePath(directory, storageDir), "utf8"));
26630
26669
  if (record.directory === projectDirectoryKey(directory) && /^git:[0-9a-f]{7,64}$/.test(record.identity))
26631
26670
  return record.identity;
26632
26671
  } catch {}
@@ -26638,12 +26677,171 @@ var init_project_identity_cache = __esm(() => {
26638
26677
  init_storage_permissions();
26639
26678
  });
26640
26679
 
26680
+ // ../plugin/src/features/magic-context/memory/unborn-head.ts
26681
+ import { readFileSync as readFileSync16, realpathSync as realpathSync4, statSync as statSync11 } from "node:fs";
26682
+ import path5 from "node:path";
26683
+ function errorCode(error) {
26684
+ if (error === null || typeof error !== "object" || !("code" in error))
26685
+ return;
26686
+ const code = error.code;
26687
+ return typeof code === "string" ? code : undefined;
26688
+ }
26689
+ function readText(file) {
26690
+ try {
26691
+ return { ok: true, text: readFileSync16(file, "utf8") };
26692
+ } catch (error) {
26693
+ return { ok: false, missing: errorCode(error) === "ENOENT" };
26694
+ }
26695
+ }
26696
+ function entryKind(entry) {
26697
+ try {
26698
+ const stat = statSync11(entry);
26699
+ if (stat.isFile())
26700
+ return "file";
26701
+ if (stat.isDirectory())
26702
+ return "directory";
26703
+ return "other";
26704
+ } catch (error) {
26705
+ return errorCode(error) === "ENOENT" ? "missing" : "error";
26706
+ }
26707
+ }
26708
+ function stripLineEnding(text) {
26709
+ return text.replace(/\r?\n$/u, "");
26710
+ }
26711
+ function resolveMetadataPath(baseDirectory, value) {
26712
+ return path5.resolve(baseDirectory, value);
26713
+ }
26714
+ function isPlainBranchName(name) {
26715
+ if (name.length === 0 || name.endsWith("/") || name.endsWith("."))
26716
+ return false;
26717
+ if (name.includes("..") || name.includes("//") || name.includes("@{"))
26718
+ return false;
26719
+ for (const character of name) {
26720
+ const code = character.charCodeAt(0);
26721
+ if (code <= 32 || code === 127 || "~^:?*[\\".includes(character))
26722
+ return false;
26723
+ }
26724
+ return name.split("/").every((component) => !component.startsWith(".") && !component.endsWith(".lock"));
26725
+ }
26726
+ function findGitDirectory(start) {
26727
+ let current = start;
26728
+ while (true) {
26729
+ const dotGit = path5.join(current, ".git");
26730
+ const kind = entryKind(dotGit);
26731
+ if (kind === "directory")
26732
+ return dotGit;
26733
+ if (kind === "file") {
26734
+ const read = readText(dotGit);
26735
+ if (!read.ok)
26736
+ return;
26737
+ const match = /^gitdir: (.+)$/u.exec(stripLineEnding(read.text));
26738
+ if (!match?.[1] || match[1].includes(`
26739
+ `))
26740
+ return;
26741
+ return resolveMetadataPath(current, match[1]);
26742
+ }
26743
+ if (kind !== "missing")
26744
+ return;
26745
+ const parent = path5.dirname(current);
26746
+ if (parent === current)
26747
+ return;
26748
+ current = parent;
26749
+ }
26750
+ }
26751
+ function packedRefsList(text, ref) {
26752
+ for (const rawLine of text.split(`
26753
+ `)) {
26754
+ const line = rawLine.replace(/\r$/u, "");
26755
+ if (line === "" || line.startsWith("#") || line.startsWith("^"))
26756
+ continue;
26757
+ const match = /^[0-9a-f]{40,64} (\S+)$/u.exec(line);
26758
+ if (!match)
26759
+ return;
26760
+ if (match[1] === ref)
26761
+ return true;
26762
+ }
26763
+ return false;
26764
+ }
26765
+ function isUnbornHeadInLayout(directory) {
26766
+ const gitDirectory = findGitDirectory(directory);
26767
+ if (gitDirectory === undefined)
26768
+ return false;
26769
+ let commonDirectory = gitDirectory;
26770
+ const commondir = readText(path5.join(gitDirectory, "commondir"));
26771
+ if (commondir.ok) {
26772
+ const value = stripLineEnding(commondir.text);
26773
+ if (value === "" || value.includes(`
26774
+ `))
26775
+ return false;
26776
+ commonDirectory = resolveMetadataPath(gitDirectory, value);
26777
+ } else if (!commondir.missing) {
26778
+ return false;
26779
+ }
26780
+ if (entryKind(path5.join(gitDirectory, "HEAD")) !== "file")
26781
+ return false;
26782
+ if (entryKind(path5.join(commonDirectory, "objects")) !== "directory")
26783
+ return false;
26784
+ if (entryKind(path5.join(commonDirectory, "refs")) !== "directory")
26785
+ return false;
26786
+ if (entryKind(path5.join(commonDirectory, "reftable")) !== "missing")
26787
+ return false;
26788
+ const config = readText(path5.join(commonDirectory, "config"));
26789
+ if (config.ok) {
26790
+ if (/refstorage/iu.test(config.text))
26791
+ return false;
26792
+ } else if (!config.missing) {
26793
+ return false;
26794
+ }
26795
+ const head = readText(path5.join(gitDirectory, "HEAD"));
26796
+ if (!head.ok)
26797
+ return false;
26798
+ const headMatch = /^ref: (refs\/heads\/(.+))$/u.exec(head.text.replace(/\s+$/u, ""));
26799
+ const ref = headMatch?.[1];
26800
+ const branch = headMatch?.[2];
26801
+ if (!ref || branch === undefined || !isPlainBranchName(branch))
26802
+ return false;
26803
+ const refSegments = ref.split("/");
26804
+ for (const base of new Set([commonDirectory, gitDirectory])) {
26805
+ if (entryKind(path5.join(base, ...refSegments)) !== "missing")
26806
+ return false;
26807
+ }
26808
+ const packed = readText(path5.join(commonDirectory, "packed-refs"));
26809
+ if (packed.ok) {
26810
+ if (packedRefsList(packed.text, ref) !== false)
26811
+ return false;
26812
+ } else if (!packed.missing) {
26813
+ return false;
26814
+ }
26815
+ return true;
26816
+ }
26817
+ function isUnbornHeadOnDisk(directory, env = process.env) {
26818
+ if (GIT_LOCATION_ENV_VARS.some((name) => env[name] !== undefined && env[name] !== "")) {
26819
+ return false;
26820
+ }
26821
+ let realDirectory;
26822
+ try {
26823
+ realDirectory = realpathSync4.native(path5.resolve(directory));
26824
+ } catch {
26825
+ return false;
26826
+ }
26827
+ return isUnbornHeadInLayout(realDirectory);
26828
+ }
26829
+ var GIT_LOCATION_ENV_VARS;
26830
+ var init_unborn_head = __esm(() => {
26831
+ GIT_LOCATION_ENV_VARS = [
26832
+ "GIT_DIR",
26833
+ "GIT_COMMON_DIR",
26834
+ "GIT_WORK_TREE",
26835
+ "GIT_CEILING_DIRECTORIES"
26836
+ ];
26837
+ });
26838
+
26641
26839
  // ../plugin/src/features/magic-context/memory/project-identity.ts
26642
26840
  import { execFileSync as execFileSync4 } from "node:child_process";
26643
26841
  import { createHash as createHash5 } from "node:crypto";
26644
- import { existsSync as existsSync20, realpathSync as realpathSync3, statSync as statSync11 } from "node:fs";
26842
+ import { existsSync as existsSync21, realpathSync as realpathSync5, statSync as statSync12 } from "node:fs";
26645
26843
  import { homedir as homedir12 } from "node:os";
26646
- import path5 from "node:path";
26844
+ import path6 from "node:path";
26647
26845
  function asError(error) {
26648
26846
  return error instanceof Error ? error : undefined;
26649
26847
  }
@@ -26681,7 +26879,7 @@ function getErrorStderr(error) {
26681
26879
  return "";
26682
26880
  }
26683
26881
  function directoryFallback(directory) {
26684
- const canonical = path5.resolve(directory);
26882
+ const canonical = path6.resolve(directory);
26685
26883
  const hash = createHash5("md5").update(canonical, "utf8").digest("hex").slice(0, 12);
26686
26884
  return `dir:${hash}`;
26687
26885
  }
@@ -26690,7 +26888,7 @@ function rememberedIdentityOrDirectoryFallback(canonical) {
26690
26888
  }
26691
26889
  function assertDirectoryUsable(canonicalDirectory, rawDirectory) {
26692
26890
  try {
26693
- const stat = statSync11(canonicalDirectory);
26891
+ const stat = statSync12(canonicalDirectory);
26694
26892
  if (!stat.isDirectory()) {
26695
26893
  throw new ProjectIdentityError("unknown", rawDirectory, `Project path is not a directory: ${canonicalDirectory}`);
26696
26894
  }
@@ -26716,7 +26914,7 @@ function hasUnbornHead(directory) {
26716
26914
  encoding: "utf8",
26717
26915
  env: { ...process.env, LC_ALL: "C", LANG: "C" },
26718
26916
  stdio: ["ignore", "pipe", "pipe"],
26719
- timeout: GIT_TIMEOUT_MS,
26917
+ timeout: gitTimeoutMs,
26720
26918
  windowsHide: true
26721
26919
  };
26722
26920
  try {
@@ -26733,7 +26931,7 @@ function hasUnbornHead(directory) {
26733
26931
  }
26734
26932
  function classifyGitError(error, rawDirectory) {
26735
26933
  if (isGitTimeoutError(error)) {
26736
- return new ProjectIdentityError("git_timeout", rawDirectory, `git rev-list timed out after ${GIT_TIMEOUT_MS}ms`, asError(error));
26934
+ return new ProjectIdentityError("git_timeout", rawDirectory, `git rev-list timed out after ${gitTimeoutMs}ms`, asError(error));
26737
26935
  }
26738
26936
  const code = getErrorCode(error);
26739
26937
  if (code === "ENOENT") {
@@ -26753,7 +26951,7 @@ function classifyGitError(error, rawDirectory) {
26753
26951
  }
26754
26952
  function resolveProjectIdentityStrict(directory, allowHomeProject = homeProjectPermission, options = {}) {
26755
26953
  assertProjectAllowed(directory, allowHomeProject);
26756
- const canonical = path5.resolve(directory);
26954
+ const canonical = path6.resolve(directory);
26757
26955
  const cached = options.cache === false ? undefined : identityCache.get(canonical);
26758
26956
  if (cached !== undefined) {
26759
26957
  return cached;
@@ -26762,6 +26960,9 @@ function resolveProjectIdentityStrict(directory, allowHomeProject = homeProjectP
26762
26960
  if (!hasGitDir(canonical)) {
26763
26961
  throw new ProjectIdentityError("not_git_repo", directory, "Directory has no git metadata; caller may use directory fallback");
26764
26962
  }
26963
+ if (isUnbornHeadOnDisk(canonical)) {
26964
+ throw new ProjectIdentityError("no_commits", directory, "Git repository has no commits yet");
26965
+ }
26765
26966
  let output;
26766
26967
  try {
26767
26968
  output = execFileSyncForIdentity("git", ["rev-list", "--max-parents=0", "HEAD"], {
@@ -26769,7 +26970,7 @@ function resolveProjectIdentityStrict(directory, allowHomeProject = homeProjectP
26769
26970
  encoding: "utf8",
26770
26971
  env: { ...process.env, LC_ALL: "C", LANG: "C" },
26771
26972
  stdio: ["ignore", "pipe", "pipe"],
26772
- timeout: GIT_TIMEOUT_MS,
26973
+ timeout: gitTimeoutMs,
26773
26974
  windowsHide: true
26774
26975
  });
26775
26976
  } catch (error) {
@@ -26822,9 +27023,9 @@ function nearestLastKnownGitIdentity(canonical) {
26822
27023
  const cached = lastKnownGitIdentity(current);
26823
27024
  if (cached !== undefined)
26824
27025
  return { identity: cached, source: current };
26825
- if (existsSync20(path5.join(current, ".git")))
27026
+ if (existsSync21(path6.join(current, ".git")))
26826
27027
  break;
26827
- const parent = path5.dirname(current);
27028
+ const parent = path6.dirname(current);
26828
27029
  if (parent === current)
26829
27030
  break;
26830
27031
  current = parent;
@@ -26835,7 +27036,7 @@ function nearestLastKnownGitIdentity(canonical) {
26835
27036
  if (exactOrAncestor)
26836
27037
  return exactOrAncestor;
26837
27038
  try {
26838
- const realCanonical = realpathSync3.native(canonical);
27039
+ const realCanonical = realpathSync5.native(canonical);
26839
27040
  if (realCanonical !== canonical)
26840
27041
  return walk(realCanonical);
26841
27042
  } catch {}
@@ -26865,7 +27066,7 @@ function recordDubiousOwnershipFallback(canonical) {
26865
27066
  function canonicalUserHomeDirectory() {
26866
27067
  const homeDirectory = userHomeDirectoryForIdentity();
26867
27068
  try {
26868
- return realpathSync3.native(homeDirectory);
27069
+ return realpathSync5.native(homeDirectory);
26869
27070
  } catch {
26870
27071
  return homeDirectory;
26871
27072
  }
@@ -26874,20 +27075,20 @@ function isUserHomeDirectory(directory) {
26874
27075
  if (projectDirectoryKey(directory) === projectDirectoryKey(userHomeDirectoryForIdentity()))
26875
27076
  return true;
26876
27077
  try {
26877
- return projectDirectoryKey(realpathSync3.native(path5.resolve(directory))) === projectDirectoryKey(canonicalUserHomeDirectory());
27078
+ return projectDirectoryKey(realpathSync5.native(path6.resolve(directory))) === projectDirectoryKey(canonicalUserHomeDirectory());
26878
27079
  } catch {
26879
27080
  return false;
26880
27081
  }
26881
27082
  }
26882
27083
  function assertProjectAllowed(directory, allowHomeProject) {
26883
- const canonical = path5.resolve(directory);
27084
+ const canonical = path6.resolve(directory);
26884
27085
  if (!allowHomeProject && (isUserHomeDirectory(directory) || isUserHomeDirectory(gitRootDirectory(canonical) ?? canonical))) {
26885
27086
  throw new ProjectIdentityError("home_project_disabled", directory, "Home project memory is disabled; set allow_home_project to opt in");
26886
27087
  }
26887
27088
  }
26888
27089
  function resolveProjectIdentity(directory, allowHomeProject = homeProjectPermission) {
26889
27090
  assertProjectAllowed(directory, allowHomeProject);
26890
- const canonical = path5.resolve(directory);
27091
+ const canonical = path6.resolve(directory);
26891
27092
  const cachedFallback = directoryFallbackCache.get(canonical);
26892
27093
  if (cachedFallback !== undefined) {
26893
27094
  if (!hasGitDir(canonical)) {
@@ -26936,7 +27137,7 @@ function hasGitDir(canonical) {
26936
27137
  return true;
26937
27138
  }
26938
27139
  try {
26939
- const realCanonical = realpathSync3.native(canonical);
27140
+ const realCanonical = realpathSync5.native(canonical);
26940
27141
  return realCanonical !== canonical && hasGitDirInAncestorChain(realCanonical);
26941
27142
  } catch {
26942
27143
  return false;
@@ -26945,14 +27146,14 @@ function hasGitDir(canonical) {
26945
27146
  function gitRootInAncestorChain(startDirectory) {
26946
27147
  let current = startDirectory;
26947
27148
  while (true) {
26948
- if (existsSync20(path5.join(current, ".git"))) {
27149
+ if (existsSync21(path6.join(current, ".git"))) {
26949
27150
  try {
26950
- return realpathSync3.native(current);
27151
+ return realpathSync5.native(current);
26951
27152
  } catch {
26952
- return path5.resolve(current);
27153
+ return path6.resolve(current);
26953
27154
  }
26954
27155
  }
26955
- const parent = path5.dirname(current);
27156
+ const parent = path6.dirname(current);
26956
27157
  if (parent === current) {
26957
27158
  return null;
26958
27159
  }
@@ -26967,16 +27168,17 @@ function gitRootDirectory(canonical) {
26967
27168
  if (direct)
26968
27169
  return direct;
26969
27170
  try {
26970
- const realCanonical = realpathSync3.native(canonical);
27171
+ const realCanonical = realpathSync5.native(canonical);
26971
27172
  return realCanonical === canonical ? null : gitRootInAncestorChain(realCanonical);
26972
27173
  } catch {
26973
27174
  return null;
26974
27175
  }
26975
27176
  }
26976
- var GIT_TIMEOUT_MS = 5000, TRANSIENT_FAILURE_COOLDOWN_MS, identityCache, linkedGitWorktreeCache, lastKnownGitIdentityCache, directoryFallbackCache, transientFailureCooldown, dubiousOwnershipFallbackDirectories, dubiousOwnershipLoggedDirectories, dubiousOwnershipWarnedDirectories, transientGitIdentityReuseLoggedDirectories, sessionIdentityCache, homeProjectPermission = false, pausedIdentityReasons, pausedIdentityLogged, execFileSyncForIdentity, userHomeDirectoryForIdentity = () => homedir12(), nowMs = () => Date.now(), ProjectIdentityError;
27177
+ var GIT_TIMEOUT_MS = 5000, TRANSIENT_FAILURE_COOLDOWN_MS, identityCache, linkedGitWorktreeCache, lastKnownGitIdentityCache, directoryFallbackCache, transientFailureCooldown, dubiousOwnershipFallbackDirectories, dubiousOwnershipLoggedDirectories, dubiousOwnershipWarnedDirectories, transientGitIdentityReuseLoggedDirectories, sessionIdentityCache, homeProjectPermission = false, pausedIdentityReasons, pausedIdentityLogged, execFileSyncForIdentity, gitTimeoutMs, userHomeDirectoryForIdentity = () => homedir12(), nowMs = () => Date.now(), ProjectIdentityError;
26977
27178
  var init_project_identity = __esm(() => {
26978
27179
  init_logger();
26979
27180
  init_project_identity_cache();
27181
+ init_unborn_head();
26980
27182
  TRANSIENT_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
26981
27183
  identityCache = new Map;
26982
27184
  linkedGitWorktreeCache = new Map;
@@ -26991,6 +27193,7 @@ var init_project_identity = __esm(() => {
26991
27193
  pausedIdentityReasons = new Map;
26992
27194
  pausedIdentityLogged = new Set;
26993
27195
  execFileSyncForIdentity = execFileSync4;
27196
+ gitTimeoutMs = GIT_TIMEOUT_MS;
26994
27197
  ProjectIdentityError = class ProjectIdentityError extends Error {
26995
27198
  errorClass;
26996
27199
  rawDirectory;
@@ -30262,7 +30465,7 @@ var init_tool_definition_tokens = __esm(() => {
30262
30465
  });
30263
30466
 
30264
30467
  // ../plugin/src/features/magic-context/tool-owner-backfill.ts
30265
- import { existsSync as existsSync21 } from "node:fs";
30468
+ import { existsSync as existsSync22 } from "node:fs";
30266
30469
  function resolveOpencodeDbPath() {
30267
30470
  return resolveOpenCodeDbPath().path;
30268
30471
  }
@@ -30299,7 +30502,7 @@ function runToolOwnerBackfill(db) {
30299
30502
  return result;
30300
30503
  }
30301
30504
  const opencodeDbPath = resolveOpencodeDbPath();
30302
- if (!existsSync21(opencodeDbPath)) {
30505
+ if (!existsSync22(opencodeDbPath)) {
30303
30506
  log(`[backfill] OpenCode DB not found at ${opencodeDbPath} — marking all unbackfilled sessions as skipped. Lazy adoption (defense-in-depth) handles legacy rows at runtime.`);
30304
30507
  markAllUnbackfilledSessionsSkipped(db);
30305
30508
  result.sessionsSkippedNoOcDb = countSessionsByStatus(db, "skipped");
@@ -31159,7 +31362,7 @@ function pickNearestPriorOwner(candidates, currentMessageId, times) {
31159
31362
  }
31160
31363
  return best?.id ?? null;
31161
31364
  }
31162
- var insertTagStatements, updateTagStatusStatements, updateTagDropModeStatements, updateTagMessageIdStatements, getTagNumbersByMessageIdStatements, deleteTagsByMessageIdStatements, getMaxTagNumberBySessionStatements, getTagNumberByMessageIdStatements, getAssignableTagNumberByMessageIdStatements, hasPiFallbackMessageTagStatements, updateTagByteSizeStatements, updateTagInputByteSizeStatements, recentTagOwnerStatements, RECLAIM_HINT_EXCLUDED_TOOLS, getActiveToolTagsForAgeReclaimStatements, scopedActiveTokenTotalStatements, updateTagTokenCountStatements, updateTagInputTokenCountStatements, tagOwnerSummaries, TAG_OWNER_COLUMNS = "id, type, message_id, tool_owner_message_id, tag_number, reasoning_token_count", TAG_OWNER_APPENDED_WITH_SHAPE_SQL, inertWhitespaceStatements, inertWhitespaceByNumberStatements, foldStatements, getOwnerScopedToolTagNumbersStatements, getMinMessageTagNumberForRawIdStatements, getActiveTagsBySessionStatements, getNullOwnerToolTagsBySessionStatements, getDroppedTagsBySessionStatements, getMaxDroppedTagNumberStatements, newestToolTagNumberStatements, droppedNumberStatements, tagByIdStatements, getToolTagNumberByOwnerStatements, getNullOwnerToolTagStatements, adoptNullOwnerToolTagStatements, getToolOwnerByTagIdStatements, deleteToolTagsByOwnerStatements;
31365
+ var insertTagStatements, updateTagStatusStatements, updateTagDropModeStatements, updateTagMessageIdStatements, getTagNumbersByMessageIdStatements, deleteTagsByMessageIdStatements, getMaxTagNumberBySessionStatements, getTagNumberByMessageIdStatements, getAssignableTagNumberByMessageIdStatements, hasPiFallbackMessageTagStatements, updateTagByteSizeStatements, updateTagInputByteSizeStatements, recentTagOwnerStatements, RECLAIM_HINT_EXCLUDED_TOOLS, getActiveToolTagsForAgeReclaimStatements, scopedActiveTokenTotalStatements, updateTagTokenCountStatements, updateTagInputTokenCountStatements, tagOwnerSummaries, TAG_OWNER_COLUMNS = "id, type, message_id, tool_owner_message_id, tag_number, reasoning_token_count", TAG_OWNER_APPENDED_WITH_SHAPE_SQL, droppedTagStatements, inertWhitespaceStatements, inertWhitespaceByNumberStatements, foldStatements, getOwnerScopedToolTagNumbersStatements, getMinMessageTagNumberForRawIdStatements, getActiveTagsBySessionStatements, getNullOwnerToolTagsBySessionStatements, getDroppedTagsBySessionStatements, getMaxDroppedTagNumberStatements, newestToolTagNumberStatements, droppedNumberStatements, tagByIdStatements, getToolTagNumberByOwnerStatements, getNullOwnerToolTagStatements, adoptNullOwnerToolTagStatements, getToolOwnerByTagIdStatements, deleteToolTagsByOwnerStatements;
31163
31366
  var init_storage_tags = __esm(async () => {
31164
31367
  init_emergency_drop();
31165
31368
  init_tag_owner_id();
@@ -31200,6 +31403,7 @@ var init_storage_tags = __esm(async () => {
31200
31403
  UNION ALL
31201
31404
  SELECT NULL, NULL, NULL, NULL, NULL, NULL, 1, COUNT(*), MAX(id), (SELECT value FROM schema_migrations_meta WHERE key = ?)
31202
31405
  FROM tags WHERE session_id = ?`;
31406
+ droppedTagStatements = new WeakMap;
31203
31407
  inertWhitespaceStatements = new WeakMap;
31204
31408
  inertWhitespaceByNumberStatements = new WeakMap;
31205
31409
  foldStatements = new WeakMap;
@@ -31541,6 +31745,7 @@ function readRawSessionMessageIdOrdinalsForRangeFromDb(db, sessionId, fromOrdina
31541
31745
  const to = Math.floor(toOrdinal);
31542
31746
  if (to < from)
31543
31747
  return new Map;
31748
+ exactOrdinalScansOnThisThread += 1;
31544
31749
  const rows = db.prepare(`
31545
31750
  SELECT id, data FROM message WHERE session_id = ?
31546
31751
  AND CASE WHEN json_valid(data) THEN NOT (
@@ -32215,7 +32420,7 @@ function readRawSessionBoundaryEndpointsFromDb(db, sessionId, ids, blockIds = []
32215
32420
  return new Map(wanted.map((id) => [id, endpoints.get(id) ?? null]));
32216
32421
  }
32217
32422
  }
32218
- var RAW_MESSAGE_PARTS_BY_ID_SQL = "SELECT message_id, data, time_updated FROM part WHERE +session_id = ? AND likelihood(message_id = ?, 0.000001) ORDER BY time_created ASC, id ASC", RAW_METADATA_KEEP_CHARS = 16384, RAW_METADATA_KEPT_KEYS, RAW_PART_DATA_SQL, rawMessagePageRowsVisited = 0, RAW_SUMMARY_TEXT_MAX_CHARS = 8192, RAW_SUMMARY_ARG_MAX_CHARS = 512, RAW_SUMMARY_TOOL_INPUT_KEYS, RAW_SUMMARY_PART_DATA_SQL, ORDINAL_SUMMARY_FLAG_SQL = `(CASE WHEN json_valid(data) = 1
32423
+ var RAW_MESSAGE_PARTS_BY_ID_SQL = "SELECT message_id, data, time_updated FROM part WHERE +session_id = ? AND likelihood(message_id = ?, 0.000001) ORDER BY time_created ASC, id ASC", RAW_METADATA_KEEP_CHARS = 16384, RAW_METADATA_KEPT_KEYS, RAW_PART_DATA_SQL, rawMessagePageRowsVisited = 0, RAW_SUMMARY_TEXT_MAX_CHARS = 8192, RAW_SUMMARY_ARG_MAX_CHARS = 512, RAW_SUMMARY_TOOL_INPUT_KEYS, RAW_SUMMARY_PART_DATA_SQL, exactOrdinalScansOnThisThread = 0, ORDINAL_SUMMARY_FLAG_SQL = `(CASE WHEN json_valid(data) = 1
32219
32424
  THEN COALESCE(json_extract(data, '$.summary'), 0)
32220
32425
  ELSE 0 END = 1)`, ORDINAL_STOP_FLAG_SQL = `(CASE WHEN json_valid(data) = 1
32221
32426
  THEN COALESCE(json_extract(data, '$.finish'), '')
@@ -32407,6 +32612,8 @@ function runSessionWarmupWorker(input, options) {
32407
32612
  finish({ inserted: reply.inserted, measurements: reply.measurements });
32408
32613
  else if (reply.kind === "orphan-sweep")
32409
32614
  finish({ orphanSweep: reply.result });
32615
+ else if (reply.kind === "exact-ordinal-ids")
32616
+ finish({ exactOrdinalIds: reply.ids });
32410
32617
  else
32411
32618
  finish({ failure: "worker-error", detail: reply.error });
32412
32619
  });
@@ -34187,14 +34394,14 @@ var init_message_time_backfill = __esm(async () => {
34187
34394
 
34188
34395
  // ../plugin/src/features/magic-context/storage-db.ts
34189
34396
  import {
34190
- existsSync as existsSync22,
34397
+ existsSync as existsSync23,
34191
34398
  readdirSync as readdirSync5,
34192
- readFileSync as readFileSync15,
34399
+ readFileSync as readFileSync17,
34193
34400
  rmdirSync,
34194
- statSync as statSync12,
34401
+ statSync as statSync13,
34195
34402
  unlinkSync as unlinkSync3
34196
34403
  } from "node:fs";
34197
- import { basename as basename3, dirname as dirname11, join as join16, resolve as resolve7 } from "node:path";
34404
+ import { basename as basename4, dirname as dirname12, join as join16, resolve as resolve7 } from "node:path";
34198
34405
  function ensureSecureStorageDir(dir) {
34199
34406
  ensureStorageDirectorySync(dir);
34200
34407
  }
@@ -34215,17 +34422,17 @@ function installBootBusyTimeout(db, dbPath, timeoutMs, report = log) {
34215
34422
  }
34216
34423
  function resolveDatabasePath(dbPathOverride) {
34217
34424
  if (dbPathOverride) {
34218
- return { dbDir: dirname11(dbPathOverride), dbPath: dbPathOverride };
34425
+ return { dbDir: dirname12(dbPathOverride), dbPath: dbPathOverride };
34219
34426
  }
34220
34427
  const dbDir = getMagicContextStorageDir();
34221
34428
  return { dbDir, dbPath: join16(dbDir, "context.db") };
34222
34429
  }
34223
34430
  function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
34224
- if (existsSync22(targetDbPath))
34431
+ if (existsSync23(targetDbPath))
34225
34432
  return;
34226
34433
  const legacyDir = getLegacyOpenCodeMagicContextStorageDir();
34227
34434
  const legacyDbPath = join16(legacyDir, "context.db");
34228
- if (!existsSync22(legacyDbPath))
34435
+ if (!existsSync23(legacyDbPath))
34229
34436
  return;
34230
34437
  log(`[magic-context] migrating legacy plugin storage: ${legacyDir} -> ${targetDbDir} (legacy left in place as backup)`);
34231
34438
  ensureSecureStorageDir(targetDbDir);
@@ -34243,7 +34450,7 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
34243
34450
  for (const suffix of ["", "-wal", "-shm"]) {
34244
34451
  const src = `${legacyDbPath}${suffix}`;
34245
34452
  const dst = join16(targetDbDir, `context.db${suffix}`);
34246
- if (existsSync22(src)) {
34453
+ if (existsSync23(src)) {
34247
34454
  try {
34248
34455
  copyStorageFileSync(src, dst);
34249
34456
  } catch (error) {
@@ -34253,7 +34460,7 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
34253
34460
  }
34254
34461
  const legacyModelsDir = join16(legacyDir, "models");
34255
34462
  const targetModelsDir = join16(targetDbDir, "models");
34256
- if (existsSync22(legacyModelsDir) && !existsSync22(targetModelsDir)) {
34463
+ if (existsSync23(legacyModelsDir) && !existsSync23(targetModelsDir)) {
34257
34464
  try {
34258
34465
  copyStorageTreeSync(legacyModelsDir, targetModelsDir);
34259
34466
  } catch (error) {
@@ -34415,7 +34622,7 @@ function inspectRpcServerDiscovery(storageDir, processes, options) {
34415
34622
  continue;
34416
34623
  return unreadableDiscovery(portFile, "io");
34417
34624
  }
34418
- const filename = basename3(portFile);
34625
+ const filename = basename4(portFile);
34419
34626
  const pidFromName = /^port-(\d+)/.exec(filename)?.[1];
34420
34627
  const fallbackPid = pidFromName ? Number(pidFromName) : 0;
34421
34628
  const record = parseRpcPortFile(raw, fallbackPid);
@@ -34519,8 +34726,8 @@ function removeRpcDiscoveryRecords(storageDir, files) {
34519
34726
  const removed = [];
34520
34727
  const failed = [];
34521
34728
  for (const file of files) {
34522
- const projectDir = dirname11(resolve7(file));
34523
- if (dirname11(projectDir) !== rpcRoot || !basename3(file).startsWith("port")) {
34729
+ const projectDir = dirname12(resolve7(file));
34730
+ if (dirname12(projectDir) !== rpcRoot || !basename4(file).startsWith("port")) {
34524
34731
  failed.push({ file, error: "not an RPC discovery record" });
34525
34732
  continue;
34526
34733
  }
@@ -34677,7 +34884,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
34677
34884
  }
34678
34885
  setDatabase(db);
34679
34886
  loadToolDefinitionMeasurements(db);
34680
- tightenStorageTree(dirname11(dbPath));
34887
+ tightenStorageTree(dirname12(dbPath));
34681
34888
  databases.set(dbPath, db);
34682
34889
  pathByDatabase.set(db, dbPath);
34683
34890
  persistenceByDatabase.set(db, true);
@@ -35972,7 +36179,7 @@ function openDatabase(dbPathOrOptions) {
35972
36179
  }
35973
36180
  ensureSecureStorageDir(dbDir);
35974
36181
  tightenStorageTree(dbDir);
35975
- if (!existsSync22(dbPath) && shouldEnforcePrivateStoragePermissions()) {
36182
+ if (!existsSync23(dbPath) && shouldEnforcePrivateStoragePermissions()) {
35976
36183
  try {
35977
36184
  writeStorageFileSync(dbPath, new Uint8Array, { flag: "wx" });
35978
36185
  } catch (error) {
@@ -36059,8 +36266,8 @@ var init_storage_db = __esm(async () => {
36059
36266
  RPC_DISCOVERY_PARSE_GRACE_MS = 10 * 60 * 1000;
36060
36267
  defaultRpcDiscoveryFs = {
36061
36268
  readdirSync: (path, options) => options?.withFileTypes ? readdirSync5(path, { withFileTypes: true }) : readdirSync5(path),
36062
- readFileSync: (path, encoding) => String(readFileSync15(path, encoding)),
36063
- statSync: (path) => ({ mtimeMs: statSync12(path).mtimeMs }),
36269
+ readFileSync: (path, encoding) => String(readFileSync17(path, encoding)),
36270
+ statSync: (path) => ({ mtimeMs: statSync13(path).mtimeMs }),
36064
36271
  unlinkSync: (path) => unlinkSync3(path),
36065
36272
  rmdirSync: (path) => rmdirSync(path)
36066
36273
  };
@@ -36074,14 +36281,14 @@ var init_storage_db = __esm(async () => {
36074
36281
  });
36075
36282
 
36076
36283
  // src/lib/database-access.ts
36077
- import { existsSync as existsSync23, rmSync as rmSync6 } from "node:fs";
36078
- import { dirname as dirname12 } from "node:path";
36284
+ import { existsSync as existsSync24, rmSync as rmSync6 } from "node:fs";
36285
+ import { dirname as dirname13 } from "node:path";
36079
36286
  import { pathToFileURL } from "node:url";
36080
36287
  function getPersistedSchemaVersion2(db) {
36081
36288
  return getPersistedSchemaVersion(db);
36082
36289
  }
36083
36290
  function openExistingDatabase(path, options) {
36084
- if (!existsSync23(path))
36291
+ if (!existsSync24(path))
36085
36292
  return null;
36086
36293
  if (options.readonly) {
36087
36294
  const db = new Database(path, { readonly: true });
@@ -36130,7 +36337,7 @@ function openExistingContextDatabaseForMutation(path) {
36130
36337
  async function backupDatabaseSnapshot(db, sourcePath, destination) {
36131
36338
  const serializable = db;
36132
36339
  if (typeof serializable.serialize === "function") {
36133
- ensureStorageDirectorySync(dirname12(destination));
36340
+ ensureStorageDirectorySync(dirname13(destination));
36134
36341
  writeStorageFileSync(destination, serializable.serialize(), { flag: "wx" });
36135
36342
  return;
36136
36343
  }
@@ -36139,7 +36346,7 @@ async function backupDatabaseSnapshot(db, sourcePath, destination) {
36139
36346
  if (typeof sqlite.backup !== "function") {
36140
36347
  throw new Error("The active SQLite runtime does not provide a snapshot backup API");
36141
36348
  }
36142
- if (existsSync23(destination)) {
36349
+ if (existsSync24(destination)) {
36143
36350
  throw new Error(`Refusing to overwrite existing backup ${destination}`);
36144
36351
  }
36145
36352
  const reader = new Database(sourcePath, { readonly: true });
@@ -36249,7 +36456,7 @@ var init_config_location_migration = __esm(() => {
36249
36456
  function availableDreamTasks(smartNotesEnabled = true) {
36250
36457
  return CANONICAL_DREAM_TASKS.filter((task) => smartNotesEnabled || task !== "evaluate-smart-notes");
36251
36458
  }
36252
- var CANONICAL_DREAM_TASKS, DREAM_TOOL_LOOP_TOKEN_BUDGETS, MEMORY_DOMAIN_TASKS, MEMORY_DOMAIN_SET;
36459
+ var CANONICAL_DREAM_TASKS, DREAM_TOOL_LOOP_TOKEN_BUDGETS, MEMORY_DOMAIN_TASKS, MEMORY_DOMAIN_SET, PROJECT_MEMORY_DREAM_TASKS, PROJECT_MEMORY_DREAM_TASK_SET;
36253
36460
  var init_task_registry = __esm(() => {
36254
36461
  CANONICAL_DREAM_TASKS = [
36255
36462
  "map-memories",
@@ -36286,6 +36493,18 @@ var init_task_registry = __esm(() => {
36286
36493
  "refresh-primers"
36287
36494
  ];
36288
36495
  MEMORY_DOMAIN_SET = new Set(MEMORY_DOMAIN_TASKS);
36496
+ PROJECT_MEMORY_DREAM_TASKS = [
36497
+ "map-memories",
36498
+ "verify",
36499
+ "verify-broad",
36500
+ "curate",
36501
+ "compress-cues",
36502
+ "classify-memories",
36503
+ "retrospective",
36504
+ "promote-primers",
36505
+ "refresh-primers"
36506
+ ];
36507
+ PROJECT_MEMORY_DREAM_TASK_SET = new Set(PROJECT_MEMORY_DREAM_TASKS);
36289
36508
  });
36290
36509
 
36291
36510
  // src/lib/model-picker.ts
@@ -36425,11 +36644,11 @@ var init_dreamer_setup = __esm(() => {
36425
36644
  });
36426
36645
 
36427
36646
  // src/commands/setup-pi.ts
36428
- import { existsSync as existsSync24, mkdirSync as mkdirSync5 } from "node:fs";
36429
- import { dirname as dirname13 } from "node:path";
36647
+ import { existsSync as existsSync25, mkdirSync as mkdirSync6 } from "node:fs";
36648
+ import { dirname as dirname14 } from "node:path";
36430
36649
  function ensureDir4(path) {
36431
- if (!existsSync24(path))
36432
- mkdirSync5(path, { recursive: true });
36650
+ if (!existsSync25(path))
36651
+ mkdirSync6(path, { recursive: true });
36433
36652
  }
36434
36653
  async function getDefaultPrompts() {
36435
36654
  await Promise.resolve().then(() => init_prompts());
@@ -36461,7 +36680,7 @@ function comparePiVersion(a, b) {
36461
36680
  }
36462
36681
  function writePiSettingsPackage(settingsPath, packageSource = PI_PACKAGE_SOURCE) {
36463
36682
  const settings = readJsoncConfigForUpdate(settingsPath);
36464
- ensureDir4(dirname13(settingsPath));
36683
+ ensureDir4(dirname14(settingsPath));
36465
36684
  if (settings.packages !== undefined && !Array.isArray(settings.packages)) {
36466
36685
  throw new Error(`Refusing to rewrite ${settingsPath}: "packages" is ${typeof settings.packages}, expected an array. Fix it by hand, then rerun setup.`);
36467
36686
  }
@@ -36492,7 +36711,7 @@ function removePiSettingsPackage(settingsPath, packageSource = PI_PACKAGE_SOURCE
36492
36711
  }
36493
36712
  function writeMagicContextConfig(configPath, options) {
36494
36713
  const config = readMagicContextConfigForSetup(configPath);
36495
- ensureDir4(dirname13(configPath));
36714
+ ensureDir4(dirname14(configPath));
36496
36715
  if (!config.$schema) {
36497
36716
  config.$schema = "https://raw.githubusercontent.com/cortexkit/magic-context/master/assets/magic-context.schema.json";
36498
36717
  }
@@ -37185,7 +37404,7 @@ var init_conflict_detector = __esm(() => {
37185
37404
  });
37186
37405
 
37187
37406
  // ../plugin/src/shared/conflict-fixer.ts
37188
- import { existsSync as existsSync25, readFileSync as readFileSync16, writeFileSync as writeFileSync5 } from "node:fs";
37407
+ import { existsSync as existsSync26, readFileSync as readFileSync18, writeFileSync as writeFileSync6 } from "node:fs";
37189
37408
  import { homedir as homedir15 } from "node:os";
37190
37409
  import { join as join19 } from "node:path";
37191
37410
  function isRecord3(value) {
@@ -37195,11 +37414,11 @@ function asStringArray(value) {
37195
37414
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
37196
37415
  }
37197
37416
  function readConfig(filePath) {
37198
- if (!existsSync25(filePath)) {
37417
+ if (!existsSync26(filePath)) {
37199
37418
  return null;
37200
37419
  }
37201
37420
  try {
37202
- const text = readFileSync16(filePath, "utf-8");
37421
+ const text = readFileSync18(filePath, "utf-8");
37203
37422
  const parsed = import_comment_json5.parse(text);
37204
37423
  return isRecord3(parsed) ? { config: parsed, text } : null;
37205
37424
  } catch {
@@ -37207,18 +37426,18 @@ function readConfig(filePath) {
37207
37426
  }
37208
37427
  }
37209
37428
  function writeConfig(filePath, text) {
37210
- writeFileSync5(filePath, text);
37429
+ writeFileSync6(filePath, text);
37211
37430
  }
37212
37431
  function resolveUserOpenCodeConfigPath() {
37213
37432
  const paths = getOpenCodeConfigPaths({ binary: "opencode" });
37214
- if (existsSync25(paths.configJsonc))
37433
+ if (existsSync26(paths.configJsonc))
37215
37434
  return paths.configJsonc;
37216
37435
  return paths.configJson;
37217
37436
  }
37218
37437
  function collectOpenCodeConfigPaths(directory) {
37219
37438
  const paths = new Set;
37220
37439
  const userConfig = resolveUserOpenCodeConfigPath();
37221
- if (existsSync25(userConfig)) {
37440
+ if (existsSync26(userConfig)) {
37222
37441
  paths.add(userConfig);
37223
37442
  }
37224
37443
  for (const filePath of [
@@ -37227,7 +37446,7 @@ function collectOpenCodeConfigPaths(directory) {
37227
37446
  join19(directory, "opencode.jsonc"),
37228
37447
  join19(directory, "opencode.json")
37229
37448
  ]) {
37230
- if (existsSync25(filePath)) {
37449
+ if (existsSync26(filePath)) {
37231
37450
  paths.add(filePath);
37232
37451
  }
37233
37452
  }
@@ -37239,10 +37458,10 @@ function collectOmoConfigPaths(directory) {
37239
37458
  for (const fileName of OMO_CONFIG_NAMES) {
37240
37459
  const userPath = join19(configDir, fileName);
37241
37460
  const projectPath = join19(directory, fileName);
37242
- if (existsSync25(userPath)) {
37461
+ if (existsSync26(userPath)) {
37243
37462
  paths.add(userPath);
37244
37463
  }
37245
- if (existsSync25(projectPath)) {
37464
+ if (existsSync26(projectPath)) {
37246
37465
  paths.add(projectPath);
37247
37466
  }
37248
37467
  }
@@ -37250,13 +37469,13 @@ function collectOmoConfigPaths(directory) {
37250
37469
  const omoHomeDir = join19(homeDir, ".omo");
37251
37470
  for (const name of OMO_UNIFIED_NAMES) {
37252
37471
  const userPath = join19(omoHomeDir, name);
37253
- if (existsSync25(userPath)) {
37472
+ if (existsSync26(userPath)) {
37254
37473
  paths.add(userPath);
37255
37474
  }
37256
37475
  }
37257
37476
  for (const name of OMO_UNIFIED_NAMES) {
37258
37477
  const projectPath = join19(directory, ".omo", name);
37259
- if (existsSync25(projectPath)) {
37478
+ if (existsSync26(projectPath)) {
37260
37479
  paths.add(projectPath);
37261
37480
  }
37262
37481
  }
@@ -37384,8 +37603,8 @@ var init_conflict_fixer = __esm(() => {
37384
37603
  });
37385
37604
 
37386
37605
  // src/commands/setup-opencode.ts
37387
- import { existsSync as existsSync26 } from "node:fs";
37388
- import { basename as basename4, dirname as dirname14 } from "node:path";
37606
+ import { existsSync as existsSync27 } from "node:fs";
37607
+ import { basename as basename5, dirname as dirname15 } from "node:path";
37389
37608
  function resolveCompactionEnabledForWriter() {
37390
37609
  try {
37391
37610
  const config = loadPluginConfig(process.cwd());
@@ -37400,7 +37619,7 @@ function isPlainObject5(value) {
37400
37619
  }
37401
37620
  function planOpenCodeConfigUpdate(configPath, removeDcp = false, compactionEnabled = true, hostGeneration = "v1") {
37402
37621
  const registrationKey = pluginConfigKeyFor(hostGeneration);
37403
- const existsAtCommit = existsSync26(configPath);
37622
+ const existsAtCommit = existsSync27(configPath);
37404
37623
  const existing = existsAtCommit ? readJsoncConfigForUpdate(configPath) : {};
37405
37624
  if (!existsAtCommit) {
37406
37625
  const created = { [registrationKey]: [OPENCODE_PLUGIN_ENTRY_WITH_VERSION] };
@@ -37415,7 +37634,7 @@ function planOpenCodeConfigUpdate(configPath, removeDcp = false, compactionEnabl
37415
37634
  let changed = false;
37416
37635
  const rawPlugins = readPluginEntries(existing).map(({ entry }) => entry);
37417
37636
  const retainedPlugins = removeDcp ? rawPlugins.filter((plugin) => !matchesPluginEntry(plugin, DCP_PLUGIN_NAME)) : rawPlugins;
37418
- if (retainedPlugins.some((plugin) => isLocalPathPluginEntry(plugin) && String(plugin).includes("magic-context") && !isDevPathPluginEntry(plugin, dirname14(configPath)))) {
37637
+ if (retainedPlugins.some((plugin) => isLocalPathPluginEntry(plugin) && String(plugin).includes("magic-context") && !isDevPathPluginEntry(plugin, dirname15(configPath)))) {
37419
37638
  log3.warn("An unverifiable local OpenCode plugin path was ignored; its package name is not Magic Context.");
37420
37639
  }
37421
37640
  if (removeDcp) {
@@ -37430,7 +37649,7 @@ function planOpenCodeConfigUpdate(configPath, removeDcp = false, compactionEnabl
37430
37649
  }
37431
37650
  }
37432
37651
  const hasNpmEntry = retainedPlugins.some((plugin) => matchesPluginEntry(plugin, OPENCODE_PLUGIN_NAME));
37433
- const hasDevEntry = retainedPlugins.some((plugin) => isDevPathPluginEntry(plugin, dirname14(configPath)));
37652
+ const hasDevEntry = retainedPlugins.some((plugin) => isDevPathPluginEntry(plugin, dirname15(configPath)));
37434
37653
  if (!hasNpmEntry && !hasDevEntry) {
37435
37654
  text = Array.isArray(existing[registrationKey]) ? appendJsoncArrayValues(text, [registrationKey], [OPENCODE_PLUGIN_ENTRY_WITH_VERSION]) : setJsoncValue(text, [registrationKey], [OPENCODE_PLUGIN_ENTRY_WITH_VERSION]);
37436
37655
  changed = true;
@@ -37456,18 +37675,18 @@ function planOpenCodeConfigUpdate(configPath, removeDcp = false, compactionEnabl
37456
37675
  return changed ? document.bom + text : null;
37457
37676
  }
37458
37677
  function planTuiConfigUpdate(configPath) {
37459
- const existsAtCommit = existsSync26(configPath);
37678
+ const existsAtCommit = existsSync27(configPath);
37460
37679
  const existing = existsAtCommit ? readJsoncConfigForUpdate(configPath) : {};
37461
37680
  if (!existsAtCommit) {
37462
37681
  return `${import_comment_json6.stringify({ plugin: [OPENCODE_PLUGIN_ENTRY_WITH_VERSION] }, null, 2)}
37463
37682
  `;
37464
37683
  }
37465
37684
  const rawPlugins = Array.isArray(existing.plugin) ? existing.plugin : [];
37466
- if (rawPlugins.some((plugin) => isLocalPathPluginEntry(plugin) && String(plugin).includes("magic-context") && !isDevPathPluginEntry(plugin, dirname14(configPath)))) {
37685
+ if (rawPlugins.some((plugin) => isLocalPathPluginEntry(plugin) && String(plugin).includes("magic-context") && !isDevPathPluginEntry(plugin, dirname15(configPath)))) {
37467
37686
  log3.warn("An unverifiable local TUI plugin path was ignored; its package name is not Magic Context.");
37468
37687
  }
37469
37688
  const hasNpmEntry = rawPlugins.some((plugin) => matchesPluginEntry(plugin, OPENCODE_PLUGIN_NAME));
37470
- const hasDevEntry = rawPlugins.some((plugin) => isDevPathPluginEntry(plugin, dirname14(configPath)));
37689
+ const hasDevEntry = rawPlugins.some((plugin) => isDevPathPluginEntry(plugin, dirname15(configPath)));
37471
37690
  if (hasNpmEntry || hasDevEntry)
37472
37691
  return null;
37473
37692
  const document = readJsoncTextForEdit(configPath);
@@ -37583,7 +37802,7 @@ async function runSetup3(dryRun = false) {
37583
37802
  log3.warn("You can configure models manually in magic-context.jsonc later");
37584
37803
  }
37585
37804
  const paths = detectConfigPaths();
37586
- const hadExistingSetup = paths.opencodeConfigFormat !== "none" || existsSync26(paths.magicContextConfig) || paths.tuiConfigFormat !== "none";
37805
+ const hadExistingSetup = paths.opencodeConfigFormat !== "none" || existsSync27(paths.magicContextConfig) || paths.tuiConfigFormat !== "none";
37587
37806
  if (!dryRun) {
37588
37807
  try {
37589
37808
  assertJsoncConfigsParseable([
@@ -37695,7 +37914,7 @@ async function runSetup3(dryRun = false) {
37695
37914
  }
37696
37915
  log3.success(`Config written to ${paths.magicContextConfig}`);
37697
37916
  if (hostGeneration === "v1") {
37698
- log3.success(`TUI sidebar plugin added to ${basename4(paths.tuiConfig)}`);
37917
+ log3.success(`TUI sidebar plugin added to ${basename5(paths.tuiConfig)}`);
37699
37918
  } else {
37700
37919
  log3.info("TUI sidebar loads from the plugin entry on OpenCode 2 (tui.json not used)");
37701
37920
  }
@@ -37876,8 +38095,8 @@ var init_setup = __esm(async () => {
37876
38095
  });
37877
38096
 
37878
38097
  // src/lib/disk-space.ts
37879
- import { existsSync as existsSync27, statfsSync, statSync as statSync13 } from "node:fs";
37880
- import { dirname as dirname15, resolve as resolve9 } from "node:path";
38098
+ import { existsSync as existsSync28, statfsSync, statSync as statSync14 } from "node:fs";
38099
+ import { dirname as dirname16, resolve as resolve9 } from "node:path";
37881
38100
  function availableDiskBytes(path) {
37882
38101
  const filesystem = statfsSync(path);
37883
38102
  return filesystem.bavail * filesystem.bsize;
@@ -37894,9 +38113,9 @@ function checkDiskSpace(path, bytes, freeBytes) {
37894
38113
  function existingDirectoryAncestor(path) {
37895
38114
  let current = resolve9(path);
37896
38115
  for (;; ) {
37897
- if (existsSync27(current) && statSync13(current).isDirectory())
38116
+ if (existsSync28(current) && statSync14(current).isDirectory())
37898
38117
  return current;
37899
- const parent = dirname15(current);
38118
+ const parent = dirname16(current);
37900
38119
  if (parent === current)
37901
38120
  throw new Error(`No existing directory for ${path}`);
37902
38121
  current = parent;
@@ -37947,14 +38166,14 @@ var init_types = __esm(() => {
37947
38166
  // ../plugin/src/hooks/auto-update-checker/checker.ts
37948
38167
  import {
37949
38168
  accessSync as accessSync3,
37950
- existsSync as existsSync28,
38169
+ existsSync as existsSync29,
37951
38170
  constants as fsConstants,
37952
- readFileSync as readFileSync17,
38171
+ readFileSync as readFileSync19,
37953
38172
  renameSync as renameSync5,
37954
- statSync as statSync14,
37955
- writeFileSync as writeFileSync6
38173
+ statSync as statSync15,
38174
+ writeFileSync as writeFileSync7
37956
38175
  } from "node:fs";
37957
- import { dirname as dirname16, isAbsolute as isAbsolute7, join as join21, resolve as resolve10 } from "node:path";
38176
+ import { dirname as dirname17, isAbsolute as isAbsolute7, join as join21, resolve as resolve10 } from "node:path";
37958
38177
  function warn(message) {
37959
38178
  log(`WARN: ${message}`);
37960
38179
  }
@@ -37980,7 +38199,7 @@ function parseJsonConfig(content) {
37980
38199
  }
37981
38200
  function getSurfaceConfigPaths(directory, surface) {
37982
38201
  const name = surface === "server" ? "opencode" : "tui";
37983
- const globalDir = dirname16(USER_OPENCODE_CONFIG);
38202
+ const globalDir = dirname17(USER_OPENCODE_CONFIG);
37984
38203
  const dirs = [
37985
38204
  globalDir,
37986
38205
  directory,
@@ -38001,9 +38220,9 @@ function getWinningConfig(directory, surface) {
38001
38220
  let winner = null;
38002
38221
  for (const path of getSurfaceConfigPaths(directory, surface)) {
38003
38222
  try {
38004
- if (!existsSync28(path))
38223
+ if (!existsSync29(path))
38005
38224
  continue;
38006
- const parsed = parseJsonConfig(readFileSync17(path, "utf-8"));
38225
+ const parsed = parseJsonConfig(readFileSync19(path, "utf-8"));
38007
38226
  const entries = getPluginEntries(parsed);
38008
38227
  if (entries.some((entry) => entry === PACKAGE_NAME || entry.startsWith(`${PACKAGE_NAME}@`))) {
38009
38228
  if (winner) {
@@ -38040,14 +38259,14 @@ var init_checker = __esm(async () => {
38040
38259
  });
38041
38260
 
38042
38261
  // src/lib/opencode-plugin-schema-fence.ts
38043
- import { existsSync as existsSync29, readdirSync as readdirSync6, readFileSync as readFileSync18 } from "node:fs";
38262
+ import { existsSync as existsSync30, readdirSync as readdirSync6, readFileSync as readFileSync20 } from "node:fs";
38044
38263
  import { join as join22 } from "node:path";
38045
38264
  import { gunzipSync as gunzipSync2 } from "node:zlib";
38046
38265
  function readPackageVersion(packageJsonPath) {
38047
38266
  try {
38048
- if (!existsSync29(packageJsonPath))
38267
+ if (!existsSync30(packageJsonPath))
38049
38268
  return null;
38050
- const packageJson = JSON.parse(readFileSync18(packageJsonPath, "utf-8"));
38269
+ const packageJson = JSON.parse(readFileSync20(packageJsonPath, "utf-8"));
38051
38270
  if (packageJson.name !== OPENCODE_PLUGIN_NAME || typeof packageJson.version !== "string") {
38052
38271
  return null;
38053
38272
  }
@@ -38067,7 +38286,7 @@ function readFenceValue(text) {
38067
38286
  }
38068
38287
  function readFenceFromDist(packageDirectory) {
38069
38288
  const distDirectory = join22(packageDirectory, "dist");
38070
- if (!existsSync29(distDirectory))
38289
+ if (!existsSync30(distDirectory))
38071
38290
  return null;
38072
38291
  const pending = [distDirectory];
38073
38292
  const fenceValues = new Set;
@@ -38084,7 +38303,7 @@ function readFenceFromDist(packageDirectory) {
38084
38303
  }
38085
38304
  if (!entry.isFile() || !/\.(?:[cm]?js|ts)$/.test(entry.name))
38086
38305
  continue;
38087
- const fence = readFenceValue(readFileSync18(path, "utf-8"));
38306
+ const fence = readFenceValue(readFileSync20(path, "utf-8"));
38088
38307
  if (fence !== null)
38089
38308
  fenceValues.add(fence);
38090
38309
  }
@@ -38253,13 +38472,13 @@ var init_opencode_plugin_schema_fence = __esm(async () => {
38253
38472
  });
38254
38473
 
38255
38474
  // src/commands/doctor-opencode-cache.ts
38256
- import { existsSync as existsSync30, readFileSync as readFileSync19, rmSync as rmSync7 } from "node:fs";
38475
+ import { existsSync as existsSync31, readFileSync as readFileSync21, rmSync as rmSync7 } from "node:fs";
38257
38476
  function readCachedPluginVersion(pluginCacheDir) {
38258
38477
  try {
38259
38478
  const installedPkgPath = getOpenCodePluginPackageJsonPath(pluginCacheDir);
38260
- if (!existsSync30(installedPkgPath))
38479
+ if (!existsSync31(installedPkgPath))
38261
38480
  return;
38262
- const pkg = JSON.parse(readFileSync19(installedPkgPath, "utf-8"));
38481
+ const pkg = JSON.parse(readFileSync21(installedPkgPath, "utf-8"));
38263
38482
  return typeof pkg.version === "string" ? pkg.version : undefined;
38264
38483
  } catch {
38265
38484
  return;
@@ -38286,7 +38505,7 @@ function readOpenCodePluginConfigUse(config, configDir) {
38286
38505
  async function clearPluginCache(options = {}, deps = {}) {
38287
38506
  const remove = deps.remove ?? ((path) => rmSync7(path, { recursive: true, force: true }));
38288
38507
  const pluginCacheRoots = getOpenCodePluginCacheRoots();
38289
- const existingRoots = pluginCacheRoots.filter((root) => existsSync30(root));
38508
+ const existingRoots = pluginCacheRoots.filter((root) => existsSync31(root));
38290
38509
  if (existingRoots.length === 0) {
38291
38510
  return { action: "not_found", path: pluginCacheRoots[0] ?? "" };
38292
38511
  }
@@ -38383,8 +38602,8 @@ var init_doctor_opencode_cache = __esm(async () => {
38383
38602
  });
38384
38603
 
38385
38604
  // src/commands/doctor-cached-plugin-fence.ts
38386
- import { existsSync as existsSync31 } from "node:fs";
38387
- import { dirname as dirname17 } from "node:path";
38605
+ import { existsSync as existsSync32 } from "node:fs";
38606
+ import { dirname as dirname18 } from "node:path";
38388
38607
  function isReferenced(sources, host, spec) {
38389
38608
  const specs = sources.referencedSpecs?.[host];
38390
38609
  return specs === undefined || specs.has(spec);
@@ -38394,13 +38613,13 @@ function listCachedOpenCodePluginFences(sources = {}) {
38394
38613
  const v1Referenced = isReferenced(sources, "opencode1", "latest");
38395
38614
  for (const root of v1Referenced ? sources.openCodeV1Roots ?? getOpenCodePluginCacheRoots() : []) {
38396
38615
  const packageJson = getOpenCodePluginPackageJsonPath(root);
38397
- if (!existsSync31(packageJson))
38616
+ if (!existsSync32(packageJson))
38398
38617
  continue;
38399
38618
  fences.push({
38400
38619
  host: "opencode1",
38401
38620
  directory: root,
38402
38621
  version: readCachedPluginVersion(root),
38403
- supportedVersion: readFenceFromDist(dirname17(packageJson))
38622
+ supportedVersion: readFenceFromDist(dirname18(packageJson))
38404
38623
  });
38405
38624
  }
38406
38625
  for (const slot of listOpenCodeV2PluginCacheSlots(sources.openCodeV2NpmCacheDir)) {
@@ -38416,7 +38635,7 @@ function listCachedOpenCodePluginFences(sources = {}) {
38416
38635
  directory: slot.slot,
38417
38636
  spec: slot.spec,
38418
38637
  version: slot.version,
38419
- supportedVersion: readFenceFromDist(dirname17(getOpenCodePluginPackageJsonPath(generation)))
38638
+ supportedVersion: readFenceFromDist(dirname18(getOpenCodePluginPackageJsonPath(generation)))
38420
38639
  });
38421
38640
  }
38422
38641
  return fences;
@@ -38599,11 +38818,11 @@ var init_doctor_prune_discovery = __esm(async () => {
38599
38818
 
38600
38819
  // src/commands/doctor-storage-holders.ts
38601
38820
  import { execFileSync as execFileSync5 } from "node:child_process";
38602
- import { readFileSync as readFileSync20, realpathSync as realpathSync4 } from "node:fs";
38821
+ import { readFileSync as readFileSync22, realpathSync as realpathSync6 } from "node:fs";
38603
38822
  import { join as join23, resolve as resolve11 } from "node:path";
38604
38823
  function canonicalStoragePath(path) {
38605
38824
  try {
38606
- return realpathSync4(path);
38825
+ return realpathSync6(path);
38607
38826
  } catch {
38608
38827
  return resolve11(path);
38609
38828
  }
@@ -38627,7 +38846,7 @@ function processReferencesStorage(pid, storageDir) {
38627
38846
  if (process.platform === "linux") {
38628
38847
  for (const name of ["cmdline", "environ"]) {
38629
38848
  try {
38630
- texts.push(readFileSync20(`/proc/${pid}/${name}`, "utf8"));
38849
+ texts.push(readFileSync22(`/proc/${pid}/${name}`, "utf8"));
38631
38850
  } catch {}
38632
38851
  }
38633
38852
  } else {
@@ -38649,9 +38868,9 @@ var init_doctor_storage_holders = () => {};
38649
38868
 
38650
38869
  // src/commands/doctor-repair-db.ts
38651
38870
  import { spawnSync as spawnSync4 } from "node:child_process";
38652
- import { closeSync as closeSync4, existsSync as existsSync32, openSync as openSync4, renameSync as renameSync6, rmSync as rmSync8, statSync as statSync15 } from "node:fs";
38871
+ import { closeSync as closeSync4, existsSync as existsSync33, openSync as openSync4, renameSync as renameSync6, rmSync as rmSync8, statSync as statSync16 } from "node:fs";
38653
38872
  import { homedir as homedir17 } from "node:os";
38654
- import { dirname as dirname18, join as join24 } from "node:path";
38873
+ import { dirname as dirname19, join as join24 } from "node:path";
38655
38874
  function defaultInspectHolders(storageDir, overrides = {}) {
38656
38875
  const deps = {
38657
38876
  defaultStorageDir: join24(homedir17(), ".local", "share", "cortexkit", "magic-context"),
@@ -38717,11 +38936,11 @@ function timestamp(date) {
38717
38936
  return date.toISOString().replaceAll("-", "").replaceAll(":", "").replace(".", "");
38718
38937
  }
38719
38938
  function uniqueBase(preferred) {
38720
- if (!DATABASE_SUFFIXES.some((suffix) => existsSync32(`${preferred}${suffix}`)))
38939
+ if (!DATABASE_SUFFIXES.some((suffix) => existsSync33(`${preferred}${suffix}`)))
38721
38940
  return preferred;
38722
38941
  for (let attempt = 1;attempt < 1e4; attempt++) {
38723
38942
  const candidate = `${preferred}-${attempt}`;
38724
- if (!DATABASE_SUFFIXES.some((suffix) => existsSync32(`${candidate}${suffix}`)))
38943
+ if (!DATABASE_SUFFIXES.some((suffix) => existsSync33(`${candidate}${suffix}`)))
38725
38944
  return candidate;
38726
38945
  }
38727
38946
  throw new Error(`Could not allocate a unique recovery path beside ${preferred}`);
@@ -38735,8 +38954,8 @@ function databaseBundleSizeBytes(sourceBase) {
38735
38954
  let size = 0;
38736
38955
  for (const suffix of DATABASE_SUFFIXES) {
38737
38956
  const source = `${sourceBase}${suffix}`;
38738
- if (existsSync32(source))
38739
- size += statSync15(source).size;
38957
+ if (existsSync33(source))
38958
+ size += statSync16(source).size;
38740
38959
  }
38741
38960
  return size;
38742
38961
  }
@@ -38744,7 +38963,7 @@ function copyDatabaseBundle(sourceBase, destinationBase, forcePrivate = false) {
38744
38963
  const copiedPaths = [];
38745
38964
  for (const suffix of DATABASE_SUFFIXES) {
38746
38965
  const source = `${sourceBase}${suffix}`;
38747
- if (!existsSync32(source))
38966
+ if (!existsSync33(source))
38748
38967
  continue;
38749
38968
  const destination = `${destinationBase}${suffix}`;
38750
38969
  copyStorageFileSync(source, destination, forcePrivate);
@@ -38966,7 +39185,7 @@ function activateReplacement(dbPath, replacementPath, originalAsidePath) {
38966
39185
  try {
38967
39186
  for (const suffix of DATABASE_SUFFIXES) {
38968
39187
  const from = `${dbPath}${suffix}`;
38969
- if (!existsSync32(from))
39188
+ if (!existsSync33(from))
38970
39189
  continue;
38971
39190
  const to = `${originalAsidePath}${suffix}`;
38972
39191
  renameSync6(from, to);
@@ -38976,7 +39195,7 @@ function activateReplacement(dbPath, replacementPath, originalAsidePath) {
38976
39195
  return movedOriginals.map(({ to }) => to);
38977
39196
  } catch (error) {
38978
39197
  for (const moved of movedOriginals.reverse()) {
38979
- if (existsSync32(moved.to) && !existsSync32(moved.from))
39198
+ if (existsSync33(moved.to) && !existsSync33(moved.from))
38980
39199
  renameSync6(moved.to, moved.from);
38981
39200
  }
38982
39201
  throw error;
@@ -39007,12 +39226,12 @@ function printHelp() {
39007
39226
  async function runRepairDb(options = {}) {
39008
39227
  const prompts = options.prompts ?? promptIO;
39009
39228
  const deps = { ...DEFAULT_DEPS3, ...options.deps };
39010
- const storageDir = options.storageDir ?? dirname18(options.dbPath ?? join24(getMagicContextStorageDir(), "context.db"));
39229
+ const storageDir = options.storageDir ?? dirname19(options.dbPath ?? join24(getMagicContextStorageDir(), "context.db"));
39011
39230
  const dbPath = options.dbPath ?? join24(storageDir, "context.db");
39012
39231
  const stamp = timestamp(deps.now());
39013
39232
  prompts.intro("Magic Context — Repair shared database");
39014
39233
  prompts.log.info(`Database: ${dbPath}`);
39015
- if (!existsSync32(dbPath)) {
39234
+ if (!existsSync33(dbPath)) {
39016
39235
  prompts.log.error(`Database not found: ${dbPath}`);
39017
39236
  prompts.log.info("Backup: not created (database does not exist)");
39018
39237
  prompts.outro("Database repair failed");
@@ -39222,13 +39441,13 @@ var init_doctor_repair_db = __esm(async () => {
39222
39441
 
39223
39442
  // src/commands/doctor-single-store-repair.ts
39224
39443
  import { spawnSync as spawnSync5 } from "node:child_process";
39225
- import { existsSync as existsSync33, statfsSync as statfsSync2, statSync as statSync16 } from "node:fs";
39444
+ import { existsSync as existsSync34, statfsSync as statfsSync2, statSync as statSync17 } from "node:fs";
39226
39445
  import { homedir as homedir18 } from "node:os";
39227
- import { dirname as dirname19, join as join25, resolve as resolve12 } from "node:path";
39446
+ import { dirname as dirname20, join as join25, resolve as resolve12 } from "node:path";
39228
39447
  function existingAncestor(path) {
39229
39448
  let current = resolve12(path);
39230
- while (!existsSync33(current))
39231
- current = dirname19(current);
39449
+ while (!existsSync34(current))
39450
+ current = dirname20(current);
39232
39451
  return current;
39233
39452
  }
39234
39453
  function describe2(plan, print) {
@@ -39264,13 +39483,13 @@ function runDoctorSingleStoreRepair(options, overrides = {}) {
39264
39483
  try {
39265
39484
  const { dbPath: context, dbDir: data } = resolveDatabasePath();
39266
39485
  const store = join25(data, "store.db");
39267
- if (!existsSync33(context) || !existsSync33(store))
39486
+ if (!existsSync34(context) || !existsSync34(store))
39268
39487
  return refuse("repair_missing_database", `Both ${context} and ${store} must exist.`);
39269
39488
  if (!options.fromBackup)
39270
39489
  return refuse("repair_usage", "--from-backup <dir> is required");
39271
39490
  const fromBackup = resolve12(options.fromBackup);
39272
39491
  for (const name of ["context.db", "store.db"])
39273
- if (!existsSync33(join25(fromBackup, name)))
39492
+ if (!existsSync34(join25(fromBackup, name)))
39274
39493
  return refuse("repair_backup_missing", `${join25(fromBackup, name)} does not exist`);
39275
39494
  const sessions = options.sessions ?? [];
39276
39495
  if (options.live && sessions.length === 0)
@@ -39299,7 +39518,7 @@ function runDoctorSingleStoreRepair(options, overrides = {}) {
39299
39518
  deps.print(`Repairing while hosts hold the stores (--live): ${blockers.join("; ") || "holders unknown"}`);
39300
39519
  }
39301
39520
  const backupRoot = resolve12(options.backupRoot ?? join25(data, "backups"));
39302
- const need = Math.ceil((statSync16(context).size + statSync16(store).size) * 1.1);
39521
+ const need = Math.ceil((statSync17(context).size + statSync17(store).size) * 1.1);
39303
39522
  const volume = existingAncestor(backupRoot);
39304
39523
  const have = deps.freeBytes(volume);
39305
39524
  if (have < need)
@@ -39395,7 +39614,7 @@ var init_doctor_single_store_repair = __esm(async () => {
39395
39614
 
39396
39615
  // src/commands/doctor-single-store.ts
39397
39616
  import { spawnSync as spawnSync6 } from "node:child_process";
39398
- import { existsSync as existsSync34, realpathSync as realpathSync5, statSync as statSync17 } from "node:fs";
39617
+ import { existsSync as existsSync35, realpathSync as realpathSync7, statSync as statSync18 } from "node:fs";
39399
39618
  import { homedir as homedir19 } from "node:os";
39400
39619
  import { join as join26, resolve as resolve13 } from "node:path";
39401
39620
  function engineContextPath() {
@@ -39429,7 +39648,7 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
39429
39648
  try {
39430
39649
  const { dbPath: context, dbDir: data } = resolveDatabasePath();
39431
39650
  const store = join26(data, "store.db");
39432
- if (!existsSync34(context) || !existsSync34(store))
39651
+ if (!existsSync35(context) || !existsSync35(store))
39433
39652
  return refuse("single_store_missing_database", `Both ${context} and ${store} must exist.`);
39434
39653
  const probe = probeHostProcessesUsing({ files: [context, store].flatMap((p) => SUFFIXES2.map((s) => p + s)), directories: [] }, deps.lsofSpawn);
39435
39654
  const holders = deps.inspectHolders(data);
@@ -39444,7 +39663,7 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
39444
39663
  return refuse("single_store_files_in_use", [...lines, STOP].join(`
39445
39664
  `));
39446
39665
  }
39447
- if (!existsSync34(engineContextPath()) || realpathSync5(context) !== realpathSync5(engineContextPath()))
39666
+ if (!existsSync35(engineContextPath()) || realpathSync7(context) !== realpathSync7(engineContextPath()))
39448
39667
  return refuse("single_store_path_mismatch", `CLI ${context}; engine ${engineContextPath()}`);
39449
39668
  const backupRoot = resolve13(options.backupRoot ?? join26(data, "backups"));
39450
39669
  const contextDb = new Database(context, { readonly: true });
@@ -39473,10 +39692,10 @@ function runDoctorSingleStore(options = {}, overrides = {}) {
39473
39692
  }
39474
39693
  if (contextVersion > LATEST_SUPPORTED_VERSION || storeVersion !== 60)
39475
39694
  return refuse("single_store_version_mismatch", `context.db v${contextVersion}; store.db v${storeVersion}; need context.db v${LATEST_SUPPORTED_VERSION} and store.db v60 (apply current plugin migrations to context.db; upgrade store.db with ck-mc first)`);
39476
- const backupBytes = statSync17(context).size + statSync17(store).size;
39477
- const workingBytes = 2 * statSync17(store).size;
39695
+ const backupBytes = statSync18(context).size + statSync18(store).size;
39696
+ const workingBytes = 2 * statSync18(store).size;
39478
39697
  const backupVolume = existingDirectoryAncestor(backupRoot);
39479
- const sameVolume = statSync17(data).dev === statSync17(backupVolume).dev;
39698
+ const sameVolume = statSync18(data).dev === statSync18(backupVolume).dev;
39480
39699
  const dataSpace = checkDiskSpace(data, workingBytes + (sameVolume ? backupBytes : 0), deps.freeBytes);
39481
39700
  if (!dataSpace.sufficient)
39482
39701
  return refuse("single_store_disk_space", `need ${dataSpace.requiredBytes} bytes; have ${dataSpace.availableBytes} bytes on ${data}`);
@@ -39987,17 +40206,17 @@ var init_storage_identity_merge = __esm(() => {
39987
40206
  // src/commands/doctor-identity-splits.ts
39988
40207
  import { execFileSync as execFileSync6 } from "node:child_process";
39989
40208
  import { createHash as createHash6 } from "node:crypto";
39990
- import { existsSync as existsSync35, readdirSync as readdirSync7, realpathSync as realpathSync6, statSync as statSync18 } from "node:fs";
39991
- import { dirname as dirname20, join as join27, resolve as resolve14 } from "node:path";
40209
+ import { existsSync as existsSync36, readdirSync as readdirSync7, realpathSync as realpathSync8, statSync as statSync19 } from "node:fs";
40210
+ import { dirname as dirname21, join as join27, resolve as resolve14 } from "node:path";
39992
40211
  function tableExists5(db, table) {
39993
40212
  return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
39994
40213
  }
39995
40214
  function hasGitMetadataInAncestors(directory) {
39996
40215
  let current = resolve14(directory);
39997
40216
  while (true) {
39998
- if (existsSync35(join27(current, ".git")))
40217
+ if (existsSync36(join27(current, ".git")))
39999
40218
  return true;
40000
- const parent = dirname20(current);
40219
+ const parent = dirname21(current);
40001
40220
  if (parent === current)
40002
40221
  return false;
40003
40222
  current = parent;
@@ -40006,7 +40225,7 @@ function hasGitMetadataInAncestors(directory) {
40006
40225
  function orphanedPathReason(directory) {
40007
40226
  let entries;
40008
40227
  try {
40009
- if (!statSync18(directory).isDirectory())
40228
+ if (!statSync19(directory).isDirectory())
40010
40229
  return "path is no longer a directory";
40011
40230
  entries = readdirSync7(directory);
40012
40231
  } catch (error) {
@@ -40028,7 +40247,7 @@ function findIdentitySplits(db, host, includeSingles = false) {
40028
40247
  return cached;
40029
40248
  let canonical = directory;
40030
40249
  try {
40031
- canonical = realpathSync6.native(directory);
40250
+ canonical = realpathSync8.native(directory);
40032
40251
  } catch {}
40033
40252
  canonicalDirectories.set(directory, canonical);
40034
40253
  return canonical;
@@ -40176,8 +40395,8 @@ var init_doctor_identity_splits = __esm(async () => {
40176
40395
  // src/commands/doctor-merge-identity.ts
40177
40396
  import { execFileSync as execFileSync7 } from "node:child_process";
40178
40397
  import { createHash as createHash7 } from "node:crypto";
40179
- import { existsSync as existsSync36, mkdtempSync as mkdtempSync2, readdirSync as readdirSync8, readFileSync as readFileSync21, statSync as statSync19 } from "node:fs";
40180
- import { dirname as dirname21, join as join28, resolve as resolve15 } from "node:path";
40398
+ import { existsSync as existsSync37, mkdtempSync as mkdtempSync2, readdirSync as readdirSync8, readFileSync as readFileSync23, statSync as statSync20 } from "node:fs";
40399
+ import { dirname as dirname22, join as join28, resolve as resolve15 } from "node:path";
40181
40400
  function parseMergeIdentityArgs(args) {
40182
40401
  const values = {};
40183
40402
  const switches = new Set(["--apply", "--force", "--dry-run", "--yes", "--verbose"]);
@@ -40227,7 +40446,7 @@ function printReport(report) {
40227
40446
  console.log(" No writes. Review this preview, then repeat with --apply to confirm.");
40228
40447
  }
40229
40448
  function resolveReadOnly(directory) {
40230
- if (!existsSync36(directory))
40449
+ if (!existsSync37(directory))
40231
40450
  return;
40232
40451
  try {
40233
40452
  const roots = execFileSync7("git", ["rev-list", "--max-parents=0", "HEAD"], {
@@ -40261,7 +40480,7 @@ function canonicalIdentity(directory, storageDir) {
40261
40480
  }
40262
40481
  function directoryDoesNotExist(directory) {
40263
40482
  try {
40264
- statSync19(directory);
40483
+ statSync20(directory);
40265
40484
  } catch (error) {
40266
40485
  return error.code === "ENOENT";
40267
40486
  }
@@ -40384,12 +40603,12 @@ function observations(db, hostPath, storageDir) {
40384
40603
  row.identities.push({ identity, sessions: 0, memories: 0, notes: 0, dreamer: 0 });
40385
40604
  };
40386
40605
  const sidecars = join28(storageDir, "project-identities");
40387
- if (existsSync36(sidecars))
40606
+ if (existsSync37(sidecars))
40388
40607
  for (const file of readdirSync8(sidecars)) {
40389
40608
  if (!file.endsWith(".json"))
40390
40609
  continue;
40391
40610
  try {
40392
- const record = JSON.parse(readFileSync21(join28(sidecars, file), "utf8"));
40611
+ const record = JSON.parse(readFileSync23(join28(sidecars, file), "utf8"));
40393
40612
  if (typeof record.directory === "string" && typeof record.identity === "string")
40394
40613
  add(record.directory, record.identity);
40395
40614
  } catch {}
@@ -40401,7 +40620,7 @@ function observations(db, hostPath, storageDir) {
40401
40620
  function runMergeIdentityCli(args, deps = {}) {
40402
40621
  const options = parseMergeIdentityArgs(args);
40403
40622
  const dbPath = options.dbPath ?? join28(getMagicContextStorageDir(), "context.db");
40404
- const storageDir = dirname21(dbPath);
40623
+ const storageDir = dirname22(dbPath);
40405
40624
  const hostPath = options.hostPath ?? (options.dbPath ? join28(storageDir, "host.db") : resolveOpenCodeDbPath().path);
40406
40625
  let db = openExistingContextDatabase(dbPath, {
40407
40626
  readonly: true,
@@ -40456,8 +40675,8 @@ function runMergeIdentityCli(args, deps = {}) {
40456
40675
  const backupRoot = resolve15(options.backupRoot ?? storageDir);
40457
40676
  const backupVolume = existingDirectoryAncestor(backupRoot);
40458
40677
  const sidecarRoot = join28(storageDir, "project-identities");
40459
- const sidecarEntries = existsSync36(sidecarRoot) ? readdirSync8(sidecarRoot).filter((entry) => entry.endsWith(".json")) : [];
40460
- const sidecarBytes = sidecarEntries.reduce((size, entry) => size + statSync19(join28(sidecarRoot, entry)).size, 0);
40678
+ const sidecarEntries = existsSync37(sidecarRoot) ? readdirSync8(sidecarRoot).filter((entry) => entry.endsWith(".json")) : [];
40679
+ const sidecarBytes = sidecarEntries.reduce((size, entry) => size + statSync20(join28(sidecarRoot, entry)).size, 0);
40461
40680
  const diskSpace = checkDiskSpace(backupVolume, databaseBundleSizeBytes(dbPath) + sidecarBytes, deps.freeBytes ?? availableDiskBytes);
40462
40681
  if (!diskSpace.sufficient)
40463
40682
  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.`);
@@ -40470,13 +40689,13 @@ function runMergeIdentityCli(args, deps = {}) {
40470
40689
  ensureStorageDirectorySync(sidecarBackup, true);
40471
40690
  let backupBytes = 0;
40472
40691
  for (const entry of sidecarEntries) {
40473
- const content = readFileSync21(join28(sidecarRoot, entry));
40692
+ const content = readFileSync23(join28(sidecarRoot, entry));
40474
40693
  writeStorageFileAtomicSync(join28(sidecarBackup, entry), content, true);
40475
40694
  backupBytes += content.byteLength;
40476
40695
  }
40477
40696
  console.log(`Restore identity sidecars too: rm -rf ${quote(sidecarRoot)}; cp -R ${quote(sidecarBackup)} ${quote(sidecarRoot)}`);
40478
40697
  const copiedDatabaseFiles = copyDatabaseBundle(dbPath, join28(backup, "context.db"), true);
40479
- backupBytes += copiedDatabaseFiles.reduce((size, path) => size + statSync19(path).size, 0);
40698
+ backupBytes += copiedDatabaseFiles.reduce((size, path) => size + statSync20(path).size, 0);
40480
40699
  db = openExistingDatabase(dbPath, { readonly: false });
40481
40700
  if (!db)
40482
40701
  throw new Error(`Context database disappeared: ${dbPath}`);
@@ -40520,7 +40739,7 @@ var init_doctor_merge_identity = __esm(async () => {
40520
40739
  });
40521
40740
 
40522
40741
  // src/commands/doctor-git-fts-map.ts
40523
- import { existsSync as existsSync37, mkdtempSync as mkdtempSync3, statSync as statSync20 } from "node:fs";
40742
+ import { existsSync as existsSync38, mkdtempSync as mkdtempSync3, statSync as statSync21 } from "node:fs";
40524
40743
  import { join as join29, resolve as resolve16 } from "node:path";
40525
40744
  function inspectGitFtsMap(db) {
40526
40745
  const has = (name) => Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE name=? AND type='table'").get(name));
@@ -40597,9 +40816,9 @@ function runDoctorGitFtsMap(options = {}, overrides = {}) {
40597
40816
  deps.print(`Stop every host, then run \`${GIT_FTS_MAP_REPAIR_COMMAND}\`. The repair backs up context.db and store.db first.`);
40598
40817
  return damaged ? 1 : 0;
40599
40818
  }
40600
- if (!existsSync37(context) || !existsSync37(store))
40819
+ if (!existsSync38(context) || !existsSync38(store))
40601
40820
  throw new Error("Both context.db and store.db must exist before paired-backup repair; no replacement store will be created");
40602
- const cstat = statSync20(context), sstat = statSync20(store);
40821
+ const cstat = statSync21(context), sstat = statSync21(store);
40603
40822
  if (cstat.dev === sstat.dev && cstat.ino === sstat.ino)
40604
40823
  throw new Error("context.db and store.db must be distinct files");
40605
40824
  const holders = deps.inspectHolders(deps.storageDir);
@@ -40800,8 +41019,8 @@ var SINGLE_STORE_REQUIRED = "Magic Context's Rust mode needs a one-time migratio
40800
41019
 
40801
41020
  // src/commands/migrate.ts
40802
41021
  import { createHash as createHash8, randomBytes as randomBytes3 } from "node:crypto";
40803
- import { existsSync as existsSync38, mkdirSync as mkdirSync6, renameSync as renameSync7, unlinkSync as unlinkSync4 } from "node:fs";
40804
- import { dirname as dirname22, join as join30 } from "node:path";
41022
+ import { existsSync as existsSync39, mkdirSync as mkdirSync7, renameSync as renameSync7, unlinkSync as unlinkSync4 } from "node:fs";
41023
+ import { dirname as dirname23, join as join30 } from "node:path";
40805
41024
  function defaultOpenCodeDbPath() {
40806
41025
  return getOpenCodeDatabasePath();
40807
41026
  }
@@ -40812,7 +41031,7 @@ function defaultPiSessionsRoot() {
40812
41031
  return getPiSessionsRoot();
40813
41032
  }
40814
41033
  function defaultFs() {
40815
- return { writeFileAtomic, unlinkSync: unlinkSync4, existsSync: existsSync38, renameSync: renameSync7, mkdirSync: mkdirSync6 };
41034
+ return { writeFileAtomic, unlinkSync: unlinkSync4, existsSync: existsSync39, renameSync: renameSync7, mkdirSync: mkdirSync7 };
40816
41035
  }
40817
41036
  function stmt(db, sql) {
40818
41037
  return db.prepare(sql);
@@ -40866,7 +41085,7 @@ function sweepPendingMigrations(db, fs = defaultFs()) {
40866
41085
  }
40867
41086
  if (row.phase === "db_committed") {
40868
41087
  if (fs.existsSync(row.stage_path)) {
40869
- fs.mkdirSync(dirname22(row.final_path), { recursive: true });
41088
+ fs.mkdirSync(dirname23(row.final_path), { recursive: true });
40870
41089
  fs.renameSync(row.stage_path, row.final_path);
40871
41090
  stmt(db, "DELETE FROM migration_pending WHERE migration_key = ?").run(row.migration_key);
40872
41091
  report.rolledForward += 1;
@@ -41432,7 +41651,7 @@ function migrateOpenCodeSessionToPi(opts) {
41432
41651
  sourceSessionId: session.id,
41433
41652
  targetHarness,
41434
41653
  finalPathFor: (id) => join30(outputDir, `${formatPiFilenameTimestamp(now)}_${id}.jsonl`),
41435
- stageDir: join30(dirname22(piSessionsRoot), MIGRATION_STAGE_DIRNAME),
41654
+ stageDir: join30(dirname23(piSessionsRoot), MIGRATION_STAGE_DIRNAME),
41436
41655
  now: now.getTime()
41437
41656
  });
41438
41657
  piSessionId = claimed.row.pi_session_id;
@@ -41484,7 +41703,7 @@ function migrateOpenCodeSessionToPi(opts) {
41484
41703
  commitStagedChecksum(cortexkitDb, migrationKey, contentSha256);
41485
41704
  fs.writeFileAtomic(stagePath, jsonl);
41486
41705
  plan.commit(migrationKey);
41487
- fs.mkdirSync(dirname22(finalPath), { recursive: true });
41706
+ fs.mkdirSync(dirname23(finalPath), { recursive: true });
41488
41707
  fs.renameSync(stagePath, finalPath);
41489
41708
  stmt(cortexkitDb, "DELETE FROM migration_pending WHERE migration_key = ?").run(migrationKey);
41490
41709
  } else {
@@ -43159,15 +43378,15 @@ class SubcClient {
43159
43378
  }
43160
43379
  }
43161
43380
  notSentCallError(message, cause) {
43162
- return new SubcCallError("not_sent", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
43381
+ return new SubcCallError("not_sent", `${message}${causeMessage(cause)}`, errorCode2(cause), cause);
43163
43382
  }
43164
43383
  outcomeUnknownCallError(message, cause) {
43165
- return new SubcCallError("outcome_unknown", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
43384
+ return new SubcCallError("outcome_unknown", `${message}${causeMessage(cause)}`, errorCode2(cause), cause);
43166
43385
  }
43167
43386
  terminalCallError(message, cause) {
43168
43387
  if (cause instanceof SubcCallError)
43169
43388
  return cause;
43170
- return new SubcCallError("terminal", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
43389
+ return new SubcCallError("terminal", `${message}${causeMessage(cause)}`, errorCode2(cause), cause);
43171
43390
  }
43172
43391
  notSentRecoveryError(message, cause) {
43173
43392
  if (cause instanceof SubcCallError)
@@ -43236,7 +43455,7 @@ function isConsumerReconnectTransient(err) {
43236
43455
  return true;
43237
43456
  if (err instanceof SubcError || err instanceof ConnectionFileError)
43238
43457
  return false;
43239
- const code = errorCode(err);
43458
+ const code = errorCode2(err);
43240
43459
  return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EPIPE" || code === "ETIMEDOUT" || code === "ENOENT";
43241
43460
  }
43242
43461
  function isRouteOpenRefusal(err) {
@@ -43301,7 +43520,7 @@ function routeOpenConsumerIdentity(opts = {}) {
43301
43520
  return;
43302
43521
  return { module_id: moduleId, launch_nonce: launchNonce };
43303
43522
  }
43304
- function errorCode(err) {
43523
+ function errorCode2(err) {
43305
43524
  if (typeof err === "object" && err !== null && "code" in err) {
43306
43525
  const code = err.code;
43307
43526
  if (typeof code === "string")
@@ -43789,7 +44008,7 @@ var init_store_ahead_refusal = __esm(() => {
43789
44008
  });
43790
44009
 
43791
44010
  // ../plugin/src/hooks/magic-context/module-transport.ts
43792
- import { realpathSync as realpathSync7 } from "node:fs";
44011
+ import { realpathSync as realpathSync9 } from "node:fs";
43793
44012
  import { join as join31 } from "node:path";
43794
44013
  function monotonicNow() {
43795
44014
  return monotonicClockForTests?.() ?? performance.now();
@@ -44291,7 +44510,7 @@ class SubcModuleTransport {
44291
44510
  }
44292
44511
  let resolved = root;
44293
44512
  try {
44294
- resolved = realpathSync7.native(root);
44513
+ resolved = realpathSync9.native(root);
44295
44514
  } catch {}
44296
44515
  this.canonicalRootCache.set(root, resolved);
44297
44516
  while (this.canonicalRootCache.size > CANONICAL_ROOT_CACHE_MAX_ENTRIES) {
@@ -44404,9 +44623,9 @@ var init_module_transport = __esm(async () => {
44404
44623
  });
44405
44624
 
44406
44625
  // src/commands/migrate-session.ts
44407
- import { existsSync as existsSync39, realpathSync as realpathSync8 } from "node:fs";
44626
+ import { existsSync as existsSync40, realpathSync as realpathSync10 } from "node:fs";
44408
44627
  import { homedir as homedir20 } from "node:os";
44409
- import path6, { join as join32 } from "node:path";
44628
+ import path7, { join as join32 } from "node:path";
44410
44629
  function existingSessionColumns(db) {
44411
44630
  const rows = db.prepare("PRAGMA table_info(session)").all();
44412
44631
  return new Set(rows.map((r) => r.name).filter((n) => typeof n === "string"));
@@ -44461,7 +44680,7 @@ function planMigrateSession(sessionId, rawTargetDirectory, deps) {
44461
44680
  ocProjectId = "global";
44462
44681
  ocWorktree = globalRow.worktree || "/";
44463
44682
  }
44464
- const sessionPath = path6.relative(ocWorktree, targetDirectory);
44683
+ const sessionPath = path7.relative(ocWorktree, targetDirectory);
44465
44684
  const ownershipRow = deps.contextDb.prepare("SELECT project_path FROM session_projects WHERE session_id = ? AND harness = 'opencode'").get(sessionId);
44466
44685
  const fromMcIdentity = ownershipRow?.project_path ?? (sessionRow.directory ? deps.resolveIdentity(sessionRow.directory) : "");
44467
44686
  const toMcIdentity = deps.resolveIdentity(targetDirectory);
@@ -44594,8 +44813,8 @@ function realDeps(opencodeDb, contextDb) {
44594
44813
  opencodeDb,
44595
44814
  contextDb,
44596
44815
  resolveIdentity: resolveProjectIdentity,
44597
- hasGitDir: (dir) => existsSync39(join32(dir, ".git")),
44598
- realpath: (p) => realpathSync8(p)
44816
+ hasGitDir: (dir) => existsSync40(join32(dir, ".git")),
44817
+ realpath: (p) => realpathSync10(p)
44599
44818
  };
44600
44819
  }
44601
44820
  function valueAfter(args, flag) {
@@ -44673,7 +44892,7 @@ async function runMigrateSessionCli(args) {
44673
44892
  return 1;
44674
44893
  }
44675
44894
  const expandedTo = toDir.startsWith("~") ? join32(homedir20(), toDir.slice(1).replace(/^[/\\]/, "")) : toDir;
44676
- if (!existsSync39(expandedTo)) {
44895
+ if (!existsSync40(expandedTo)) {
44677
44896
  console.error(`Target directory does not exist: ${expandedTo}`);
44678
44897
  return 1;
44679
44898
  }
@@ -44827,8 +45046,8 @@ var init_migrate_session = __esm(async () => {
44827
45046
 
44828
45047
  // ../plugin/src/features/magic-context/v22-deferred-backfill.ts
44829
45048
  import { createHash as createHash10 } from "node:crypto";
44830
- import { realpathSync as realpathSync9 } from "node:fs";
44831
- import path7 from "node:path";
45049
+ import { realpathSync as realpathSync11 } from "node:fs";
45050
+ import path8 from "node:path";
44832
45051
  function readMeta(db, key) {
44833
45052
  const row = db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(key);
44834
45053
  return row?.value ?? null;
@@ -44871,9 +45090,9 @@ function resolveBackfillIdentity(rawProjectPath) {
44871
45090
  function computeLegacyRustDirIdentity(rawProjectPath) {
44872
45091
  let canonical;
44873
45092
  try {
44874
- canonical = realpathSync9(rawProjectPath);
45093
+ canonical = realpathSync11(rawProjectPath);
44875
45094
  } catch {
44876
- canonical = path7.isAbsolute(rawProjectPath) ? rawProjectPath : path7.join(process.cwd(), rawProjectPath);
45095
+ canonical = path8.isAbsolute(rawProjectPath) ? rawProjectPath : path8.join(process.cwd(), rawProjectPath);
44877
45096
  }
44878
45097
  return `dir:${createHash10("sha256").update(canonical, "utf8").digest("hex")}`;
44879
45098
  }
@@ -45096,7 +45315,7 @@ var init_tick_failure = __esm(() => {
45096
45315
  });
45097
45316
 
45098
45317
  // ../pi-plugin/src/config/index.ts
45099
- import { existsSync as existsSync40 } from "node:fs";
45318
+ import { existsSync as existsSync41 } from "node:fs";
45100
45319
  function getProjectConfigPaths(cwd) {
45101
45320
  const basePath = cortexKitProjectConfigBasePath(cwd);
45102
45321
  return [`${basePath}.jsonc`, `${basePath}.json`];
@@ -45106,10 +45325,10 @@ function getUserConfigPaths() {
45106
45325
  return [`${basePath}.jsonc`, `${basePath}.json`];
45107
45326
  }
45108
45327
  function resolveFirstExisting(paths) {
45109
- return paths.find((path) => existsSync40(path));
45328
+ return paths.find((path) => existsSync41(path));
45110
45329
  }
45111
45330
  function resolvePiLegacyFallback(sources) {
45112
- return sources.find((source) => existsSync40(source.path)) ?? null;
45331
+ return sources.find((source) => existsSync41(source.path)) ?? null;
45113
45332
  }
45114
45333
  function loadConfigFile(path, scope) {
45115
45334
  let raw;
@@ -45420,7 +45639,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
45420
45639
  if (loaded)
45421
45640
  loadedFiles.push(loaded);
45422
45641
  }
45423
- const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync40(source.path));
45642
+ const legacyProjectUnmigrated = !projectPath && !projectLegacyFallback && legacySources.project.some((source) => existsSync41(source.path));
45424
45643
  const userPath = resolveFirstExisting(getUserConfigPaths());
45425
45644
  const userLegacyFallback = userPath ? null : resolvePiLegacyFallback(harnessLegacy.user);
45426
45645
  const userReadPath = userPath ?? userLegacyFallback?.path;
@@ -45429,7 +45648,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
45429
45648
  if (loaded)
45430
45649
  loadedFiles.push(loaded);
45431
45650
  }
45432
- const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync40(source.path));
45651
+ const legacyUserUnmigrated = !userPath && !userLegacyFallback && legacySources.user.some((source) => existsSync41(source.path));
45433
45652
  if (userLegacyFallback) {
45434
45653
  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.`);
45435
45654
  } else if (legacyUserUnmigrated) {
@@ -45567,7 +45786,7 @@ var DATABASE_REPAIR_COMMAND = "bunx @cortexkit/magic-context@latest doctor repai
45567
45786
 
45568
45787
  // src/lib/github-issue.ts
45569
45788
  import { spawnSync as spawnSync7 } from "node:child_process";
45570
- import { readFileSync as readFileSync22 } from "node:fs";
45789
+ import { readFileSync as readFileSync24 } from "node:fs";
45571
45790
  function runGhCommand(args) {
45572
45791
  try {
45573
45792
  const result = spawnSync7("gh", args, {
@@ -45594,7 +45813,7 @@ function failed(result) {
45594
45813
  function submitGithubIssue(title, bodyPath, runner = runGhCommand) {
45595
45814
  let body;
45596
45815
  try {
45597
- body = readFileSync22(bodyPath, "utf-8");
45816
+ body = readFileSync24(bodyPath, "utf-8");
45598
45817
  } catch (error) {
45599
45818
  return {
45600
45819
  ok: false,
@@ -45652,7 +45871,7 @@ var MAX_GITHUB_ISSUE_BODY_CHARS = 65536;
45652
45871
  var init_github_issue = () => {};
45653
45872
 
45654
45873
  // src/lib/log-lines.ts
45655
- import { existsSync as existsSync41, readFileSync as readFileSync23, statSync as statSync21 } from "node:fs";
45874
+ import { existsSync as existsSync42, readFileSync as readFileSync25, statSync as statSync22 } from "node:fs";
45656
45875
  import { tmpdir as tmpdir3 } from "node:os";
45657
45876
  import { join as join33 } from "node:path";
45658
45877
  function tokenize(input, limit = Number.POSITIVE_INFINITY) {
@@ -45949,11 +46168,11 @@ function getMagicContextLogPaths(harness, options = {}) {
45949
46168
  ].filter((path, index, paths) => paths.indexOf(path) === index);
45950
46169
  }
45951
46170
  function inspectLogFile(path) {
45952
- if (!existsSync41(path)) {
46171
+ if (!existsSync42(path)) {
45953
46172
  return { path, exists: false, sizeKb: 0, lineCount: 0, grammar: "unknown" };
45954
46173
  }
45955
46174
  try {
45956
- const content = readFileSync23(path, "utf8");
46175
+ const content = readFileSync25(path, "utf8");
45957
46176
  const lines = content.split(/\r?\n/).filter((line) => line.length > 0);
45958
46177
  const grammars = new Set(lines.flatMap((line) => {
45959
46178
  const parsed = parseLogLine(line);
@@ -45963,7 +46182,7 @@ function inspectLogFile(path) {
45963
46182
  return {
45964
46183
  path,
45965
46184
  exists: true,
45966
- sizeKb: Math.round(statSync21(path).size / 1024),
46185
+ sizeKb: Math.round(statSync22(path).size / 1024),
45967
46186
  lineCount: lines.length,
45968
46187
  grammar
45969
46188
  };
@@ -45980,7 +46199,7 @@ function readLogLines(files) {
45980
46199
  return [];
45981
46200
  try {
45982
46201
  let precedingTimestamp = "";
45983
- return readFileSync23(file.path, "utf8").split(/\r?\n/).filter((line) => line.length > 0).map((line, lineIndex) => {
46202
+ return readFileSync25(file.path, "utf8").split(/\r?\n/).filter((line) => line.length > 0).map((line, lineIndex) => {
45984
46203
  precedingTimestamp = parseLogLine(line)?.ts ?? precedingTimestamp;
45985
46204
  return { line, timestamp: precedingTimestamp, fileIndex, lineIndex };
45986
46205
  });
@@ -46145,6 +46364,7 @@ class IssuePrivacy {
46145
46364
  "plugin",
46146
46365
  "manifest",
46147
46366
  "Shared storage",
46367
+ "Magic Context storage",
46148
46368
  "context DB",
46149
46369
  "SQLite integrity_check",
46150
46370
  "Background maintenance",
@@ -46487,7 +46707,7 @@ var init_issue_body = __esm(() => {
46487
46707
  });
46488
46708
 
46489
46709
  // src/lib/omp-hide-secrets.ts
46490
- import { existsSync as existsSync42, readdirSync as readdirSync9, readFileSync as readFileSync24, statSync as statSync22 } from "node:fs";
46710
+ import { existsSync as existsSync43, readdirSync as readdirSync9, readFileSync as readFileSync26, statSync as statSync23 } from "node:fs";
46491
46711
  import { join as join34, resolve as resolve17 } from "node:path";
46492
46712
  function stripYamlComment(line) {
46493
46713
  let quote = null;
@@ -46611,7 +46831,7 @@ function readHideSecretsFromJson(text) {
46611
46831
  function readSource(layer, path, format) {
46612
46832
  let text;
46613
46833
  try {
46614
- text = readFileSync24(path, "utf-8");
46834
+ text = readFileSync26(path, "utf-8");
46615
46835
  } catch (error) {
46616
46836
  const code = error.code;
46617
46837
  return {
@@ -46631,7 +46851,7 @@ function readSource(layer, path, format) {
46631
46851
  }
46632
46852
  function isNonEmptyDirectory(path) {
46633
46853
  try {
46634
- return statSync22(path).isDirectory() && readdirSync9(path).length > 0;
46854
+ return statSync23(path).isDirectory() && readdirSync9(path).length > 0;
46635
46855
  } catch {
46636
46856
  return false;
46637
46857
  }
@@ -46639,7 +46859,7 @@ function isNonEmptyDirectory(path) {
46639
46859
  function collectHideSecretsSources(cwd, home = envFirstHomeDir()) {
46640
46860
  const sources = [];
46641
46861
  const agentDir = getOmpAgentDir();
46642
- const mainConfig = ["config.yml", "config.yaml"].map((name) => join34(agentDir, name)).find((path) => existsSync42(path));
46862
+ const mainConfig = ["config.yml", "config.yaml"].map((name) => join34(agentDir, name)).find((path) => existsSync43(path));
46643
46863
  if (mainConfig)
46644
46864
  sources.push(readSource("user", mainConfig, "yaml"));
46645
46865
  const projectDir = join34(cwd, ".omp");
@@ -46649,12 +46869,12 @@ function collectHideSecretsSources(cwd, home = envFirstHomeDir()) {
46649
46869
  ["config.yml", "yaml"]
46650
46870
  ]) {
46651
46871
  const path = join34(projectDir, name);
46652
- if (existsSync42(path))
46872
+ if (existsSync43(path))
46653
46873
  sources.push(readSource("project", path, format));
46654
46874
  }
46655
46875
  }
46656
46876
  for (const path of getOmpConfigOverlayPaths(cwd)) {
46657
- if (existsSync42(path))
46877
+ if (existsSync43(path))
46658
46878
  sources.push(readSource("overlay", path, "yaml"));
46659
46879
  }
46660
46880
  return sources;
@@ -46712,7 +46932,7 @@ var init_omp_hide_secrets = __esm(() => {
46712
46932
 
46713
46933
  // src/commands/doctor-omp.ts
46714
46934
  import { execFileSync as execFileSync8, spawnSync as spawnSync8 } from "node:child_process";
46715
- import { existsSync as existsSync43, readFileSync as readFileSync25 } from "node:fs";
46935
+ import { existsSync as existsSync44, readFileSync as readFileSync27 } from "node:fs";
46716
46936
  import { createRequire as createRequire3 } from "node:module";
46717
46937
  import { isAbsolute as isAbsolute8, join as join35, resolve as resolve18 } from "node:path";
46718
46938
  function parseSemver(value) {
@@ -46756,10 +46976,10 @@ function selfVersion() {
46756
46976
  return "unknown";
46757
46977
  }
46758
46978
  function readConfig2(path) {
46759
- if (!existsSync43(path))
46979
+ if (!existsSync44(path))
46760
46980
  return {};
46761
46981
  try {
46762
- const parsed = import_comment_json8.parse(readFileSync25(path, "utf-8"));
46982
+ const parsed = import_comment_json8.parse(readFileSync27(path, "utf-8"));
46763
46983
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? {} : { error: "top level is not an object" };
46764
46984
  } catch (error) {
46765
46985
  return { error: error instanceof Error ? error.message : String(error) };
@@ -46769,7 +46989,7 @@ function pluginDeclaresOmp(path) {
46769
46989
  if (!path)
46770
46990
  return null;
46771
46991
  try {
46772
- const pkg = JSON.parse(readFileSync25(join35(path, "package.json"), "utf-8"));
46992
+ const pkg = JSON.parse(readFileSync27(join35(path, "package.json"), "utf-8"));
46773
46993
  return Array.isArray(pkg.omp?.extensions) || Array.isArray(pkg.pi?.extensions);
46774
46994
  } catch {
46775
46995
  return null;
@@ -46858,7 +47078,7 @@ async function runHealthChecks(options) {
46858
47078
  }
46859
47079
  }
46860
47080
  const userConfigPath = getOmpUserConfigPath();
46861
- if (!existsSync43(userConfigPath)) {
47081
+ if (!existsSync44(userConfigPath)) {
46862
47082
  add(results, "warn", `No Magic Context user config at ${userConfigPath}`);
46863
47083
  repairPlan.writeUserConfig = true;
46864
47084
  } else {
@@ -46876,8 +47096,11 @@ async function runHealthChecks(options) {
46876
47096
  add(results, "warn", warning);
46877
47097
  const storage = getMagicContextStorageResolution();
46878
47098
  const dbPath = join35(storage.path, "context.db");
47099
+ if (isMagicContextStorageOutsideEngram(storage.path)) {
47100
+ 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.`);
47101
+ }
46879
47102
  add(results, "info", `Shared storage: ${storage.path} (source: ${storage.source})`);
46880
- if (!existsSync43(dbPath))
47103
+ if (!existsSync44(dbPath))
46881
47104
  add(results, "info", `Shared context DB will be created at ${dbPath}`);
46882
47105
  else {
46883
47106
  let db = null;
@@ -46942,7 +47165,7 @@ function writeDefaultConfig(path) {
46942
47165
  }
46943
47166
  async function repair(plan, deps, prompts, cwd) {
46944
47167
  let fixed = 0;
46945
- if (plan.writeUserConfig && !existsSync43(getOmpUserConfigPath())) {
47168
+ if (plan.writeUserConfig && !existsSync44(getOmpUserConfigPath())) {
46946
47169
  writeDefaultConfig(getOmpUserConfigPath());
46947
47170
  prompts.log.success(`Wrote default Magic Context config to ${getOmpUserConfigPath()}`);
46948
47171
  fixed += 1;
@@ -48054,12 +48277,12 @@ function listShadowBackfillStalls(db, projectIdentity) {
48054
48277
  var SHADOW_BACKFILL_PROVENANCE_KEY = "_magicContextShadowBackfill";
48055
48278
 
48056
48279
  // ../plugin/src/shared/auto-update-provenance.ts
48057
- import { existsSync as existsSync44, readFileSync as readFileSync26 } from "node:fs";
48280
+ import { existsSync as existsSync45, readFileSync as readFileSync28 } from "node:fs";
48058
48281
  function readAutoUpdateCheckState(path) {
48059
- if (!existsSync44(path))
48282
+ if (!existsSync45(path))
48060
48283
  return null;
48061
48284
  try {
48062
- const value = JSON.parse(readFileSync26(path, "utf-8"));
48285
+ const value = JSON.parse(readFileSync28(path, "utf-8"));
48063
48286
  if (!value || typeof value !== "object" || Array.isArray(value))
48064
48287
  return null;
48065
48288
  const raw = value;
@@ -48087,14 +48310,14 @@ var init_auto_update_provenance = () => {};
48087
48310
  // ../plugin/src/shared/tui-config.ts
48088
48311
  import {
48089
48312
  chmodSync as chmodSync4,
48090
- existsSync as existsSync45,
48091
- mkdirSync as mkdirSync7,
48092
- readFileSync as readFileSync27,
48313
+ existsSync as existsSync46,
48314
+ mkdirSync as mkdirSync8,
48315
+ readFileSync as readFileSync29,
48093
48316
  renameSync as renameSync8,
48094
- statSync as statSync23,
48095
- writeFileSync as writeFileSync7
48317
+ statSync as statSync24,
48318
+ writeFileSync as writeFileSync8
48096
48319
  } from "node:fs";
48097
- import { dirname as dirname23, join as join36 } from "node:path";
48320
+ import { dirname as dirname24, join as join36 } from "node:path";
48098
48321
  function pluginEntryId(entry) {
48099
48322
  if (typeof entry === "string")
48100
48323
  return entry;
@@ -48125,10 +48348,10 @@ function writeTuiConfigAtomic(configPath, config) {
48125
48348
  const body = `${import_comment_json9.stringify(config, null, 2)}
48126
48349
  `;
48127
48350
  const tmpPath = `${configPath}.tmp`;
48128
- writeFileSync7(tmpPath, body);
48351
+ writeFileSync8(tmpPath, body);
48129
48352
  try {
48130
- if (statSync23(configPath, { throwIfNoEntry: false })?.isFile()) {
48131
- chmodSync4(tmpPath, statSync23(configPath).mode & 511);
48353
+ if (statSync24(configPath, { throwIfNoEntry: false })?.isFile()) {
48354
+ chmodSync4(tmpPath, statSync24(configPath).mode & 511);
48132
48355
  }
48133
48356
  } catch {}
48134
48357
  renameSync8(tmpPath, configPath);
@@ -48137,9 +48360,9 @@ function resolveTuiConfigPath(configDirOverride) {
48137
48360
  const configDir = configDirOverride ?? getOpenCodeConfigPaths({ binary: "opencode" }).configDir;
48138
48361
  const jsoncPath = join36(configDir, "tui.jsonc");
48139
48362
  const jsonPath = join36(configDir, "tui.json");
48140
- if (existsSync45(jsoncPath))
48363
+ if (existsSync46(jsoncPath))
48141
48364
  return jsoncPath;
48142
- if (existsSync45(jsonPath))
48365
+ if (existsSync46(jsonPath))
48143
48366
  return jsonPath;
48144
48367
  return jsoncPath;
48145
48368
  }
@@ -48147,8 +48370,8 @@ function ensureTuiPluginEntry(options = {}) {
48147
48370
  try {
48148
48371
  const configPath = resolveTuiConfigPath(options.configDir);
48149
48372
  let config = {};
48150
- if (existsSync45(configPath)) {
48151
- const raw = readFileSync27(configPath, "utf-8");
48373
+ if (existsSync46(configPath)) {
48374
+ const raw = readFileSync29(configPath, "utf-8");
48152
48375
  config = import_comment_json9.parse(raw) ?? {};
48153
48376
  }
48154
48377
  const plugins = Array.isArray(config.plugin) ? [...config.plugin] : [];
@@ -48182,7 +48405,7 @@ function ensureTuiPluginEntry(options = {}) {
48182
48405
  }
48183
48406
  }
48184
48407
  config.plugin = plugins;
48185
- mkdirSync7(dirname23(configPath), { recursive: true });
48408
+ mkdirSync8(dirname24(configPath), { recursive: true });
48186
48409
  writeTuiConfigAtomic(configPath, config);
48187
48410
  log(`[magic-context] updated TUI plugin entry in ${configPath}`);
48188
48411
  return true;
@@ -48200,7 +48423,7 @@ var init_tui_config = __esm(() => {
48200
48423
  });
48201
48424
 
48202
48425
  // src/lib/diagnostics-opencode.ts
48203
- import { existsSync as existsSync46, readdirSync as readdirSync10, readFileSync as readFileSync28, statSync as statSync24 } from "node:fs";
48426
+ import { existsSync as existsSync47, readdirSync as readdirSync10, readFileSync as readFileSync30, statSync as statSync25 } from "node:fs";
48204
48427
  import { createRequire as createRequire4 } from "node:module";
48205
48428
  import { join as join37 } from "node:path";
48206
48429
  function getSelfVersion() {
@@ -48217,7 +48440,7 @@ function getSelfVersion() {
48217
48440
  }
48218
48441
  function readLegacyCachedVersion(root) {
48219
48442
  try {
48220
- const pkg = JSON.parse(readFileSync28(getOpenCodePluginPackageJsonPath(root), "utf-8"));
48443
+ const pkg = JSON.parse(readFileSync30(getOpenCodePluginPackageJsonPath(root), "utf-8"));
48221
48444
  return typeof pkg.version === "string" ? pkg.version : undefined;
48222
48445
  } catch {
48223
48446
  return;
@@ -48226,7 +48449,7 @@ function readLegacyCachedVersion(root) {
48226
48449
  function collectOpenCodePluginCacheReport(hostGeneration, opencodeConfig) {
48227
48450
  const installs = [];
48228
48451
  for (const root of getOpenCodePluginCacheRoots()) {
48229
- if (!existsSync46(root))
48452
+ if (!existsSync47(root))
48230
48453
  continue;
48231
48454
  const spec = root.endsWith("@latest") ? "latest" : "(bare)";
48232
48455
  installs.push({
@@ -48260,7 +48483,7 @@ function getStorageResolution() {
48260
48483
  }
48261
48484
  function fileSize(path) {
48262
48485
  try {
48263
- return existsSync46(path) ? statSync24(path).size : 0;
48486
+ return existsSync47(path) ? statSync25(path).size : 0;
48264
48487
  } catch {
48265
48488
  return 0;
48266
48489
  }
@@ -48272,10 +48495,10 @@ function sanitizeValue(value) {
48272
48495
  return sanitizeConfigValue(value);
48273
48496
  }
48274
48497
  function readConfig3(path) {
48275
- if (!existsSync46(path))
48498
+ if (!existsSync47(path))
48276
48499
  return { value: null };
48277
48500
  try {
48278
- const raw = readFileSync28(path, "utf-8");
48501
+ const raw = readFileSync30(path, "utf-8");
48279
48502
  const value = import_comment_json10.parse(raw);
48280
48503
  return { value };
48281
48504
  } catch (error) {
@@ -48300,7 +48523,7 @@ function configHasPluginEntry(config) {
48300
48523
  }
48301
48524
  function parseHistorianDumpMeta(path) {
48302
48525
  try {
48303
- const xml = readFileSync28(path, "utf-8");
48526
+ const xml = readFileSync30(path, "utf-8");
48304
48527
  const parsed = parseCompartmentOutput(xml);
48305
48528
  const factCountByCategory = {};
48306
48529
  for (const fact of parsed.facts) {
@@ -48333,11 +48556,11 @@ function parseHistorianDumpMeta(path) {
48333
48556
  }
48334
48557
  }
48335
48558
  function listDumpsInDir(dir, limit) {
48336
- if (!existsSync46(dir))
48559
+ if (!existsSync47(dir))
48337
48560
  return { count: 0, recent: [] };
48338
48561
  try {
48339
48562
  const entries = readdirSync10(dir).filter((name) => name.endsWith(".xml")).map((name) => {
48340
- const stat = statSync24(join37(dir, name));
48563
+ const stat = statSync25(join37(dir, name));
48341
48564
  return {
48342
48565
  name,
48343
48566
  mtime: stat.mtimeMs,
@@ -48457,7 +48680,7 @@ function collectRecentSessionsFromDatabase(database) {
48457
48680
  });
48458
48681
  }
48459
48682
  async function collectDatabaseRows(path, read) {
48460
- if (!existsSync46(path))
48683
+ if (!existsSync47(path))
48461
48684
  return { available: false, reason: "path missing" };
48462
48685
  let backend;
48463
48686
  try {
@@ -48589,7 +48812,7 @@ async function collectDiagnostics() {
48589
48812
  opencodeConfigHasPlugin: configHasPluginEntry(opencodeConfig.value),
48590
48813
  tuiConfigHasPlugin: configHasPluginEntry(tuiConfig.value),
48591
48814
  magicContextConfig: {
48592
- exists: existsSync46(configPaths.magicContextConfig),
48815
+ exists: existsSync47(configPaths.magicContextConfig),
48593
48816
  ...magicContextConfig.error ? { parseError: magicContextConfig.error } : {},
48594
48817
  flags: sanitizeValue(magicContextConfig.value ?? {}) ?? {}
48595
48818
  },
@@ -48597,7 +48820,7 @@ async function collectDiagnostics() {
48597
48820
  storageDir: {
48598
48821
  path: storageDirPath,
48599
48822
  source: storageResolution.source,
48600
- exists: existsSync46(storageDirPath),
48823
+ exists: existsSync47(storageDirPath),
48601
48824
  contextDbSizeBytes: fileSize(contextDbPath)
48602
48825
  },
48603
48826
  openCodeDatabase: {
@@ -48657,6 +48880,7 @@ function renderDiagnosticsMarkdown(report) {
48657
48880
  exists: report.storageDir.exists,
48658
48881
  context_db_size: formatBytes(report.storageDir.contextDbSizeBytes)
48659
48882
  };
48883
+ const storageBackupWarning = isMagicContextStorageOutsideEngram(report.storageDir.path) ? `- Warning: Magic Context storage is at ${sanitizeString(report.storageDir.path)}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.` : null;
48660
48884
  const openCodeInstallations = report.opencodeInstallations ?? [];
48661
48885
  const openCodeInstallationTable = openCodeInstallations.length > 1 ? [
48662
48886
  "",
@@ -48719,6 +48943,7 @@ function renderDiagnosticsMarkdown(report) {
48719
48943
  "```",
48720
48944
  "",
48721
48945
  "### Storage",
48946
+ ...storageBackupWarning ? [storageBackupWarning] : [],
48722
48947
  "```json",
48723
48948
  JSON.stringify(storage, null, 2),
48724
48949
  "```",
@@ -48851,9 +49076,9 @@ var init_embedding_local = __esm(async () => {
48851
49076
 
48852
49077
  // src/lib/embedding-runtime.ts
48853
49078
  import { spawnSync as spawnSync9 } from "node:child_process";
48854
- import { existsSync as existsSync47, readFileSync as readFileSync29 } from "node:fs";
49079
+ import { existsSync as existsSync48, readFileSync as readFileSync31 } from "node:fs";
48855
49080
  import { createRequire as createRequire5 } from "node:module";
48856
- import { dirname as dirname24, join as join38, sep } from "node:path";
49081
+ import { dirname as dirname25, join as join38, sep as sep2 } from "node:path";
48857
49082
  function describeError(error) {
48858
49083
  const message = error instanceof Error ? error.message : String(error ?? "unknown error");
48859
49084
  const code = error?.code;
@@ -48999,7 +49224,7 @@ function expectedBinaryRelPath(platform, arch) {
48999
49224
  }
49000
49225
  function onnxRuntimeNodeVersion(packageDir) {
49001
49226
  try {
49002
- const parsed = JSON.parse(readFileSync29(join38(packageDir, "package.json"), "utf8"));
49227
+ const parsed = JSON.parse(readFileSync31(join38(packageDir, "package.json"), "utf8"));
49003
49228
  return typeof parsed.version === "string" ? parsed.version : undefined;
49004
49229
  } catch {
49005
49230
  return;
@@ -49048,7 +49273,7 @@ function formatLocalEmbeddingRuntimeWasmSelected(status) {
49048
49273
  function requireNodeWasmBundle(probe, candidates) {
49049
49274
  if (probe.state === "failed")
49050
49275
  return probe;
49051
- const bundlePath = candidates.find((candidate) => existsSync47(candidate));
49276
+ const bundlePath = candidates.find((candidate) => existsSync48(candidate));
49052
49277
  return bundlePath ? probe : {
49053
49278
  state: "failed",
49054
49279
  reason: `functional Node WASM Transformers bundle is missing (checked ${candidates.join(", ")})`
@@ -49073,7 +49298,7 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
49073
49298
  }
49074
49299
  const packageDir = join38(installRoot, "node_modules", "onnxruntime-node");
49075
49300
  let native;
49076
- if (!existsSync47(join38(packageDir, "package.json"))) {
49301
+ if (!existsSync48(join38(packageDir, "package.json"))) {
49077
49302
  native = { state: "package-missing", packageDir };
49078
49303
  } else {
49079
49304
  const rel = expectedBinaryRelPath(platform, arch);
@@ -49084,7 +49309,7 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
49084
49309
  };
49085
49310
  } else {
49086
49311
  const binaryPath = join38(packageDir, rel);
49087
- native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
49312
+ native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(packageDir) ?? { state: "ok", binaryPath } : {
49088
49313
  state: "binary-missing",
49089
49314
  packageDir,
49090
49315
  expectedBinary: binaryPath,
@@ -49095,7 +49320,7 @@ function checkLocalEmbeddingRuntimeAt(installRoot, platform = process.platform,
49095
49320
  return withWasmFallback(native, () => probeWasmRuntimeAt(installRoot));
49096
49321
  }
49097
49322
  function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
49098
- const existing = installRoots.filter((root) => existsSync47(root));
49323
+ const existing = installRoots.filter((root) => existsSync48(root));
49099
49324
  if (existing.length === 0) {
49100
49325
  return {
49101
49326
  state: "unknown",
@@ -49119,9 +49344,9 @@ function checkLocalEmbeddingRuntime(installRoots, platform = process.platform, a
49119
49344
  return firstFallback ?? firstFailure ?? { state: "unknown", reason: "no candidate roots" };
49120
49345
  }
49121
49346
  function packageDirFromResolved(resolvedPath, packageName) {
49122
- const marker = `node_modules${sep}${packageName.split("/").join(sep)}`;
49347
+ const marker = `node_modules${sep2}${packageName.split("/").join(sep2)}`;
49123
49348
  const idx = resolvedPath.indexOf(marker);
49124
- return idx >= 0 ? resolvedPath.slice(0, idx + marker.length) : dirname24(resolvedPath);
49349
+ return idx >= 0 ? resolvedPath.slice(0, idx + marker.length) : dirname25(resolvedPath);
49125
49350
  }
49126
49351
  function probeWasmRuntimeByResolution(pluginDir) {
49127
49352
  try {
@@ -49142,7 +49367,7 @@ function probeWasmRuntimeByResolution(pluginDir) {
49142
49367
  }
49143
49368
  }
49144
49369
  function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.platform, arch = process.arch, runtimePreference = "auto", host) {
49145
- if (!existsSync47(join38(pluginDir, "package.json"))) {
49370
+ if (!existsSync48(join38(pluginDir, "package.json"))) {
49146
49371
  return { state: "unknown", reason: "plugin package dir not found" };
49147
49372
  }
49148
49373
  const selectedRuntime = resolveLocalEmbeddingWorkerRuntime(runtimePreference, host);
@@ -49184,7 +49409,7 @@ function checkLocalEmbeddingRuntimeByResolution(pluginDir, platform = process.pl
49184
49409
  native = probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath: onnxDir };
49185
49410
  } else {
49186
49411
  const binaryPath = join38(onnxDir, rel);
49187
- native = existsSync47(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
49412
+ native = existsSync48(binaryPath) ? probeOnnxRuntimeNodeLoad(onnxDir) ?? { state: "ok", binaryPath } : {
49188
49413
  state: "binary-missing",
49189
49414
  packageDir: onnxDir,
49190
49415
  expectedBinary: binaryPath,
@@ -49219,8 +49444,8 @@ var init_embedding_runtime = __esm(async () => {
49219
49444
  });
49220
49445
 
49221
49446
  // src/lib/logs-opencode.ts
49222
- import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync8 } from "node:fs";
49223
- import { dirname as dirname25, join as join39 } from "node:path";
49447
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync9 } from "node:fs";
49448
+ import { dirname as dirname26, join as join39 } from "node:path";
49224
49449
  function formatTimestamp(date) {
49225
49450
  const pad = (value) => String(value).padStart(2, "0");
49226
49451
  return [
@@ -49310,12 +49535,12 @@ async function bundleIssueReport(report, description, title, sessionFilter = nul
49310
49535
  const truncated = bodyMarkdown !== rawBodyMarkdown;
49311
49536
  const timestamp = formatTimestamp(new Date);
49312
49537
  const path = options.outputPath ?? join39(process.cwd(), `magic-context-issue-${timestamp}.md`);
49313
- mkdirSync8(dirname25(path), { recursive: true });
49314
- writeFileSync8(path, `${bodyMarkdown}
49538
+ mkdirSync9(dirname26(path), { recursive: true });
49539
+ writeFileSync9(path, `${bodyMarkdown}
49315
49540
  `);
49316
49541
  const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join39(process.cwd(), `magic-context-issue-${timestamp}-full.md`) : undefined;
49317
49542
  if (fullPath)
49318
- writeFileSync8(fullPath, `${rawBodyMarkdown}
49543
+ writeFileSync9(fullPath, `${rawBodyMarkdown}
49319
49544
  `);
49320
49545
  return { path, bodyMarkdown, ...fullPath ? { fullPath } : {}, truncated };
49321
49546
  }
@@ -50126,10 +50351,10 @@ function removeDeprecatedReasoningAge(config) {
50126
50351
 
50127
50352
  // src/commands/doctor-opencode.ts
50128
50353
  import { spawnSync as spawnSync10 } from "node:child_process";
50129
- import { existsSync as existsSync48, mkdtempSync as mkdtempSync4, readFileSync as readFileSync30, rmSync as rmSync9 } from "node:fs";
50354
+ import { existsSync as existsSync49, mkdtempSync as mkdtempSync4, readFileSync as readFileSync32, rmSync as rmSync9 } from "node:fs";
50130
50355
  import { createRequire as createRequire6 } from "node:module";
50131
50356
  import { homedir as homedir21, tmpdir as tmpdir4 } from "node:os";
50132
- import { dirname as dirname26, join as join40, resolve as resolve19 } from "node:path";
50357
+ import { dirname as dirname27, join as join40, resolve as resolve19 } from "node:path";
50133
50358
  function formatSharedDbRowCounts(db) {
50134
50359
  return SHARED_DB_ROW_COUNT_TABLES.map((table) => {
50135
50360
  try {
@@ -50390,10 +50615,10 @@ function getUserNpmrcPath() {
50390
50615
  function collectNpmReleaseAgeWarnings() {
50391
50616
  const ageWarnings = [];
50392
50617
  const npmrcPath = getUserNpmrcPath();
50393
- if (!existsSync48(npmrcPath))
50618
+ if (!existsSync49(npmrcPath))
50394
50619
  return ageWarnings;
50395
50620
  try {
50396
- const npmrc = readFileSync30(npmrcPath, "utf-8");
50621
+ const npmrc = readFileSync32(npmrcPath, "utf-8");
50397
50622
  for (const line of npmrc.split(`
50398
50623
  `)) {
50399
50624
  const trimmed = line.trim();
@@ -50528,7 +50753,7 @@ function checkLocalEmbeddingRuntimeForDoctor(runtimePreference = "auto") {
50528
50753
  return { issues: 0 };
50529
50754
  }
50530
50755
  async function checkEmbeddingConfig(magicContextConfigPath) {
50531
- if (!existsSync48(magicContextConfigPath)) {
50756
+ if (!existsSync49(magicContextConfigPath)) {
50532
50757
  return checkLocalEmbeddingRuntimeForDoctor();
50533
50758
  }
50534
50759
  let rawText;
@@ -50735,6 +50960,10 @@ async function runDoctor2(options = {}) {
50735
50960
  failCount++;
50736
50961
  issues++;
50737
50962
  };
50963
+ const storageDir = getMagicContextStorageDir();
50964
+ if (isMagicContextStorageOutsideEngram(storageDir)) {
50965
+ 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.`);
50966
+ }
50738
50967
  const authorityDbPath = join40(getMagicContextStorageDir(), "context.db");
50739
50968
  let authorityDb = null;
50740
50969
  try {
@@ -50774,8 +51003,8 @@ async function runDoctor2(options = {}) {
50774
51003
  let magicContextStatusKnown = paths.opencodeConfigFormat === "none";
50775
51004
  if (!magicContextStatusKnown) {
50776
51005
  try {
50777
- const config = import_comment_json11.parse(readFileSync30(paths.opencodeConfig, "utf-8"));
50778
- magicContextInstalled = isOpenCodePluginRegistered(config, dirname26(paths.opencodeConfig));
51006
+ const config = import_comment_json11.parse(readFileSync32(paths.opencodeConfig, "utf-8"));
51007
+ magicContextInstalled = isOpenCodePluginRegistered(config, dirname27(paths.opencodeConfig));
50779
51008
  magicContextStatusKnown = true;
50780
51009
  } catch {}
50781
51010
  }
@@ -50910,7 +51139,7 @@ async function runDoctor2(options = {}) {
50910
51139
  pass(`OpenCode config: ${paths.opencodeConfig}`);
50911
51140
  }
50912
51141
  let autoUpdateEnabled = true;
50913
- if (existsSync48(paths.magicContextConfig)) {
51142
+ if (existsSync49(paths.magicContextConfig)) {
50914
51143
  pass(`Magic Context config: ${paths.magicContextConfig}`);
50915
51144
  try {
50916
51145
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
@@ -50946,7 +51175,7 @@ async function runDoctor2(options = {}) {
50946
51175
  warn(`No magic-context.jsonc found — using defaults`);
50947
51176
  log3.info(" Run 'setup' to create one with model recommendations");
50948
51177
  }
50949
- if (existsSync48(paths.magicContextConfig)) {
51178
+ if (existsSync49(paths.magicContextConfig)) {
50950
51179
  try {
50951
51180
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
50952
51181
  if (!raw)
@@ -51086,10 +51315,10 @@ async function runDoctor2(options = {}) {
51086
51315
  };
51087
51316
  if (paths.opencodeConfigFormat !== "none") {
51088
51317
  try {
51089
- const raw = readFileSync30(paths.opencodeConfig, "utf-8");
51318
+ const raw = readFileSync32(paths.opencodeConfig, "utf-8");
51090
51319
  const config = import_comment_json11.parse(raw);
51091
51320
  const configName = paths.opencodeConfigFormat === "jsonc" ? "opencode.jsonc" : "opencode.json";
51092
- const configDir = dirname26(paths.opencodeConfig);
51321
+ const configDir = dirname27(paths.opencodeConfig);
51093
51322
  magicContextInstalled = isOpenCodePluginRegistered(config, configDir);
51094
51323
  magicContextStatusKnown = true;
51095
51324
  if (magicContextInstalled) {
@@ -51179,11 +51408,11 @@ async function runDoctor2(options = {}) {
51179
51408
  pass("Added TUI sidebar plugin to tui.json");
51180
51409
  warn("Restart OpenCode to see the sidebar");
51181
51410
  fixed++;
51182
- } else if (existsSync48(paths.tuiConfig)) {
51411
+ } else if (existsSync49(paths.tuiConfig)) {
51183
51412
  try {
51184
- const tuiRaw = readFileSync30(paths.tuiConfig, "utf-8");
51413
+ const tuiRaw = readFileSync32(paths.tuiConfig, "utf-8");
51185
51414
  const tuiConfig = import_comment_json11.parse(tuiRaw);
51186
- const tuiConfigDir = dirname26(paths.tuiConfig);
51415
+ const tuiConfigDir = dirname27(paths.tuiConfig);
51187
51416
  const tuiRawPlugins = Array.isArray(tuiConfig?.plugin) ? tuiConfig.plugin : [];
51188
51417
  const tuiIdx = tuiRawPlugins.findIndex((entry) => matchesPluginEntry(entry, OPENCODE_PLUGIN_NAME) || isDevPathPluginEntry(entry, tuiConfigDir));
51189
51418
  if (tuiRawPlugins.some((entry) => isLocalPathPluginEntry(entry) && String(entry).includes("magic-context") && !isDevPathPluginEntry(entry, tuiConfigDir))) {
@@ -51220,7 +51449,7 @@ async function runDoctor2(options = {}) {
51220
51449
  fail("Could not create or verify the TUI sidebar config");
51221
51450
  }
51222
51451
  }
51223
- if (existsSync48(paths.magicContextConfig)) {
51452
+ if (existsSync49(paths.magicContextConfig)) {
51224
51453
  try {
51225
51454
  const raw = loadRawConfigFile({ configPath: paths.magicContextConfig, tier: "user" });
51226
51455
  if (!raw)
@@ -51244,7 +51473,7 @@ async function runDoctor2(options = {}) {
51244
51473
  const storage = getMagicContextStorageResolution();
51245
51474
  const dbPath = join40(storage.path, "context.db");
51246
51475
  log3.info(`Shared storage: ${storage.path} (source: ${storage.source})`);
51247
- if (!existsSync48(dbPath)) {
51476
+ if (!existsSync49(dbPath)) {
51248
51477
  log3.info(`Shared context DB not yet created at ${dbPath} (will be created on first run)`);
51249
51478
  } else {
51250
51479
  log3.info(`Shared context DB exists at ${dbPath}`);
@@ -51327,7 +51556,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
51327
51556
  let pluginConfigUse;
51328
51557
  if (paths.opencodeConfigFormat !== "none") {
51329
51558
  try {
51330
- pluginConfigUse = readOpenCodePluginConfigUse(import_comment_json11.parse(readFileSync30(paths.opencodeConfig, "utf-8")), dirname26(paths.opencodeConfig));
51559
+ pluginConfigUse = readOpenCodePluginConfigUse(import_comment_json11.parse(readFileSync32(paths.opencodeConfig, "utf-8")), dirname27(paths.opencodeConfig));
51331
51560
  } catch {}
51332
51561
  }
51333
51562
  const cacheResult = await clearPluginCache({
@@ -51379,7 +51608,7 @@ ${formatDatabaseRepairGuidance(dbPath)}`);
51379
51608
  let v2DistTag;
51380
51609
  if (paths.opencodeConfigFormat !== "none") {
51381
51610
  try {
51382
- v2DistTag = configuredOpenCodeV2DistTag(import_comment_json11.parse(readFileSync30(paths.opencodeConfig, "utf-8")));
51611
+ v2DistTag = configuredOpenCodeV2DistTag(import_comment_json11.parse(readFileSync32(paths.opencodeConfig, "utf-8")));
51383
51612
  } catch {}
51384
51613
  }
51385
51614
  const v2Cache = reportOpenCodeV2PluginCache(checkOpenCodeV2PluginCache({
@@ -51648,6 +51877,7 @@ function buildDreamTaskRuntimeConfigs(dreamer, harness, language, smartNotesEnab
51648
51877
  });
51649
51878
  }
51650
51879
  var init_task_config = __esm(() => {
51880
+ init_agent_disable();
51651
51881
  init_task_registry();
51652
51882
  });
51653
51883
 
@@ -51760,7 +51990,7 @@ var init_model_chain_health = __esm(() => {
51760
51990
  });
51761
51991
 
51762
51992
  // src/lib/diagnostics-pi.ts
51763
- import { existsSync as existsSync49, readdirSync as readdirSync11, readFileSync as readFileSync31, statSync as statSync25 } from "node:fs";
51993
+ import { existsSync as existsSync50, readdirSync as readdirSync11, readFileSync as readFileSync33, statSync as statSync26 } from "node:fs";
51764
51994
  import { createRequire as createRequire7 } from "node:module";
51765
51995
  import { join as join41 } from "node:path";
51766
51996
  function getSelfVersion3() {
@@ -51777,7 +52007,7 @@ function getSelfVersion3() {
51777
52007
  }
51778
52008
  function fileSize2(path) {
51779
52009
  try {
51780
- return existsSync49(path) ? statSync25(path).size : 0;
52010
+ return existsSync50(path) ? statSync26(path).size : 0;
51781
52011
  } catch {
51782
52012
  return 0;
51783
52013
  }
@@ -51789,11 +52019,11 @@ function sanitizeValue2(value) {
51789
52019
  return sanitizeConfigValue(value);
51790
52020
  }
51791
52021
  function readJsonc(path) {
51792
- if (!existsSync49(path))
52022
+ if (!existsSync50(path))
51793
52023
  return { value: {} };
51794
52024
  try {
51795
52025
  return {
51796
- value: import_comment_json12.parse(readFileSync31(path, "utf-8"))
52026
+ value: import_comment_json12.parse(readFileSync33(path, "utf-8"))
51797
52027
  };
51798
52028
  } catch (error) {
51799
52029
  return {
@@ -51809,7 +52039,7 @@ function readConfigDiagnostic(path) {
51809
52039
  const parsed = readJsonc(path);
51810
52040
  return {
51811
52041
  path,
51812
- exists: existsSync49(path),
52042
+ exists: existsSync50(path),
51813
52043
  ...parsed.parseError ? { parseError: parsed.parseError } : {},
51814
52044
  flags: sanitizeValue2(parsed.value)
51815
52045
  };
@@ -51827,7 +52057,7 @@ function reverseSlugToDirectory(slug) {
51827
52057
  }
51828
52058
  function collectPiRecentSessions() {
51829
52059
  const sessionsRoot = getPiSessionsRoot();
51830
- if (!existsSync49(sessionsRoot))
52060
+ if (!existsSync50(sessionsRoot))
51831
52061
  return [];
51832
52062
  try {
51833
52063
  const slugs = readdirSync11(sessionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
@@ -51845,7 +52075,7 @@ function collectPiRecentSessions() {
51845
52075
  }
51846
52076
  for (const file of files) {
51847
52077
  try {
51848
- const mtime = statSync25(join41(slugDir, file)).mtimeMs;
52078
+ const mtime = statSync26(join41(slugDir, file)).mtimeMs;
51849
52079
  const sessionId = file.replace(/\.jsonl$/, "");
51850
52080
  candidates.push({ sessionId, directory, mtime });
51851
52081
  } catch {}
@@ -51863,7 +52093,7 @@ function collectPiRecentSessions() {
51863
52093
  }
51864
52094
  function parseHistorianDumpMeta2(path) {
51865
52095
  try {
51866
- const xml = readFileSync31(path, "utf-8");
52096
+ const xml = readFileSync33(path, "utf-8");
51867
52097
  const parsed = parseCompartmentOutput(xml);
51868
52098
  const factCountByCategory = {};
51869
52099
  for (const fact of parsed.facts) {
@@ -51896,11 +52126,11 @@ function parseHistorianDumpMeta2(path) {
51896
52126
  }
51897
52127
  }
51898
52128
  function listDumpsInDir2(dir, limit) {
51899
- if (!existsSync49(dir))
52129
+ if (!existsSync50(dir))
51900
52130
  return { count: 0, recent: [] };
51901
52131
  try {
51902
52132
  const entries = readdirSync11(dir).filter((name) => name.endsWith(".xml")).map((name) => {
51903
- const stat = statSync25(join41(dir, name));
52133
+ const stat = statSync26(join41(dir, name));
51904
52134
  return {
51905
52135
  name,
51906
52136
  mtime: stat.mtimeMs,
@@ -51990,7 +52220,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
51990
52220
  piVersion: pi ? getPiVersion(pi.path) : null,
51991
52221
  settings: {
51992
52222
  path: settingsPath,
51993
- exists: existsSync49(settingsPath),
52223
+ exists: existsSync50(settingsPath),
51994
52224
  ...settingsParsed.parseError ? { parseError: settingsParsed.parseError } : {},
51995
52225
  hasMagicContextPackage: hasPiMagicContextPackage(packages),
51996
52226
  packages: sanitizeValue2(packages)
@@ -52007,7 +52237,7 @@ async function collectDiagnostics2(cwd = process.cwd()) {
52007
52237
  storageDir: {
52008
52238
  path: storageDirPath,
52009
52239
  source: storageResolution.source,
52010
- exists: existsSync49(storageDirPath),
52240
+ exists: existsSync50(storageDirPath),
52011
52241
  contextDbSizeBytes: fileSize2(dbPath)
52012
52242
  },
52013
52243
  conflicts: {
@@ -52042,6 +52272,7 @@ function renderDiagnosticsMarkdown2(report) {
52042
52272
  exists: report.storageDir.exists,
52043
52273
  context_db_size: formatBytes2(report.storageDir.contextDbSizeBytes)
52044
52274
  };
52275
+ const storageBackupWarning = isMagicContextStorageOutsideEngram(report.storageDir.path) ? `- Warning: Magic Context storage is at ${sanitizeString2(report.storageDir.path)}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.` : null;
52045
52276
  return [
52046
52277
  `- Timestamp: ${report.timestamp}`,
52047
52278
  `- Pi plugin: v${report.pluginVersion}`,
@@ -52082,6 +52313,7 @@ function renderDiagnosticsMarkdown2(report) {
52082
52313
  `),
52083
52314
  "",
52084
52315
  "### Shared storage",
52316
+ ...storageBackupWarning ? [storageBackupWarning] : [],
52085
52317
  "```json",
52086
52318
  JSON.stringify(storage, null, 2),
52087
52319
  "```",
@@ -52112,8 +52344,8 @@ var init_diagnostics_pi = __esm(() => {
52112
52344
  });
52113
52345
 
52114
52346
  // src/lib/logs-pi.ts
52115
- import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync9 } from "node:fs";
52116
- import { dirname as dirname27, join as join42 } from "node:path";
52347
+ import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync10 } from "node:fs";
52348
+ import { dirname as dirname28, join as join42 } from "node:path";
52117
52349
  function formatTimestamp2(date) {
52118
52350
  const pad = (value) => String(value).padStart(2, "0");
52119
52351
  return [
@@ -52168,12 +52400,12 @@ async function bundleIssueReport2(report, description, title, options = {}) {
52168
52400
  const cwd = options.cwd ?? process.cwd();
52169
52401
  const timestamp = formatTimestamp2(options.now ?? new Date);
52170
52402
  const path = options.outputPath ?? join42(cwd, `magic-context-pi-issue-${timestamp}.md`);
52171
- mkdirSync9(dirname27(path), { recursive: true });
52172
- writeFileSync9(path, `${bodyMarkdown}
52403
+ mkdirSync10(dirname28(path), { recursive: true });
52404
+ writeFileSync10(path, `${bodyMarkdown}
52173
52405
  `);
52174
52406
  const fullPath = truncated ? options.outputPath ? `${options.outputPath}.full.md` : join42(cwd, `magic-context-pi-issue-${timestamp}-full.md`) : undefined;
52175
52407
  if (fullPath)
52176
- writeFileSync9(fullPath, `${rawBodyMarkdown}
52408
+ writeFileSync10(fullPath, `${rawBodyMarkdown}
52177
52409
  `);
52178
52410
  return { path, bodyMarkdown, ...fullPath ? { fullPath } : {}, truncated };
52179
52411
  }
@@ -52185,7 +52417,7 @@ var init_logs_pi = __esm(() => {
52185
52417
 
52186
52418
  // src/commands/doctor-pi.ts
52187
52419
  import { execFileSync as execFileSync9, spawnSync as spawnSync11 } from "node:child_process";
52188
- import { existsSync as existsSync50, readdirSync as readdirSync12, readFileSync as readFileSync32, rmSync as rmSync10, statSync as statSync26 } from "node:fs";
52420
+ import { existsSync as existsSync51, readdirSync as readdirSync12, readFileSync as readFileSync34, rmSync as rmSync10, statSync as statSync27 } from "node:fs";
52189
52421
  import { createRequire as createRequire8 } from "node:module";
52190
52422
  import { homedir as homedir22 } from "node:os";
52191
52423
  import { isAbsolute as isAbsolute9, join as join43 } from "node:path";
@@ -52280,7 +52512,7 @@ function summarize(results) {
52280
52512
  function readJsonc2(path) {
52281
52513
  try {
52282
52514
  return {
52283
- value: import_comment_json13.parse(readFileSync32(path, "utf-8"))
52515
+ value: import_comment_json13.parse(readFileSync34(path, "utf-8"))
52284
52516
  };
52285
52517
  } catch (error) {
52286
52518
  return {
@@ -52332,13 +52564,13 @@ function piPluginDirCandidates(packages, cwd) {
52332
52564
  }
52333
52565
  dirs.push(join43(agentDir, "npm", "node_modules", PACKAGE_NAME2));
52334
52566
  dirs.push(join43(cwd, ".pi", "npm", "node_modules", PACKAGE_NAME2));
52335
- return dirs.filter((dir) => existsSync50(join43(dir, "package.json")));
52567
+ return dirs.filter((dir) => existsSync51(join43(dir, "package.json")));
52336
52568
  }
52337
52569
  function projectConfigPath(cwd) {
52338
52570
  return resolveCortexKitProjectConfigPath(cwd);
52339
52571
  }
52340
52572
  function readConfigForEmbedding(path, isProjectConfig) {
52341
- if (!existsSync50(path))
52573
+ if (!existsSync51(path))
52342
52574
  return null;
52343
52575
  try {
52344
52576
  const raw = loadRawConfigFile({
@@ -52439,20 +52671,20 @@ function cacheRoots(cwd) {
52439
52671
  function findPiMagicContextCacheDirs(cwd, expectedVersion, force = false) {
52440
52672
  const found = new Map;
52441
52673
  const visit = (path, depth) => {
52442
- if (depth < 0 || !existsSync50(path))
52674
+ if (depth < 0 || !existsSync51(path))
52443
52675
  return;
52444
52676
  let stat;
52445
52677
  try {
52446
- stat = statSync26(path);
52678
+ stat = statSync27(path);
52447
52679
  } catch {
52448
52680
  return;
52449
52681
  }
52450
52682
  if (!stat.isDirectory())
52451
52683
  return;
52452
52684
  const packageJson = join43(path, "package.json");
52453
- if (existsSync50(packageJson)) {
52685
+ if (existsSync51(packageJson)) {
52454
52686
  try {
52455
- const pkg = JSON.parse(readFileSync32(packageJson, "utf-8"));
52687
+ const pkg = JSON.parse(readFileSync34(packageJson, "utf-8"));
52456
52688
  const name = typeof pkg.name === "string" ? pkg.name : "";
52457
52689
  const version = typeof pkg.version === "string" ? pkg.version : undefined;
52458
52690
  if (name === PACKAGE_NAME2) {
@@ -52533,7 +52765,7 @@ async function runHealthChecks2(options) {
52533
52765
  const settingsPath = getPiUserExtensionsPath();
52534
52766
  let packages = [];
52535
52767
  let piPluginInstalled = false;
52536
- if (!existsSync50(settingsPath)) {
52768
+ if (!existsSync51(settingsPath)) {
52537
52769
  if (pi) {
52538
52770
  add2(results, "info", `${piVersion ? `Pi ${piVersion}` : "Pi"} found; Magic Context is not installed there (run setup to add it)`);
52539
52771
  }
@@ -52575,7 +52807,7 @@ async function runHealthChecks2(options) {
52575
52807
  ["user", userConfigPath, true],
52576
52808
  ["project", projectPath, false]
52577
52809
  ]) {
52578
- if (!existsSync50(path)) {
52810
+ if (!existsSync51(path)) {
52579
52811
  if (required) {
52580
52812
  add2(results, "warn", `No ${label} magic-context.jsonc found at ${path}`);
52581
52813
  if (userConfigMigrationRefused) {
@@ -52622,8 +52854,11 @@ async function runHealthChecks2(options) {
52622
52854
  const storage = getMagicContextStorageResolution();
52623
52855
  const storageDir = storage.path;
52624
52856
  const dbPath = join43(storageDir, "context.db");
52857
+ if (isMagicContextStorageOutsideEngram(storageDir)) {
52858
+ 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.`);
52859
+ }
52625
52860
  add2(results, "info", `Shared storage: ${storageDir} (source: ${storage.source})`);
52626
- const existedBeforeOpen = existsSync50(dbPath);
52861
+ const existedBeforeOpen = existsSync51(dbPath);
52627
52862
  if (existedBeforeOpen)
52628
52863
  add2(results, "pass", `Shared context DB exists at ${dbPath}`);
52629
52864
  else
@@ -52852,7 +53087,7 @@ function writeDefaultMagicContextConfig(path) {
52852
53087
  function repair2(plan, prompts) {
52853
53088
  let fixed = 0;
52854
53089
  for (const path of plan.reasoningAgeConfigPaths) {
52855
- const content = readFileSync32(path, "utf8");
53090
+ const content = readFileSync34(path, "utf8");
52856
53091
  const parsed = readJsonc2(path);
52857
53092
  if (parsed.error)
52858
53093
  continue;
@@ -52878,7 +53113,7 @@ function repair2(plan, prompts) {
52878
53113
  }
52879
53114
  if (plan.writeUserConfig) {
52880
53115
  const configPath = getPiUserConfigPath();
52881
- if (!existsSync50(configPath)) {
53116
+ if (!existsSync51(configPath)) {
52882
53117
  try {
52883
53118
  writeDefaultMagicContextConfig(configPath);
52884
53119
  prompts.log.success(`Wrote default Magic Context config to ${configPath}`);
@@ -53134,7 +53369,7 @@ var init_doctor_pi = __esm(async () => {
53134
53369
  });
53135
53370
 
53136
53371
  // src/commands/doctor.ts
53137
- import { existsSync as existsSync51, rmSync as rmSync11 } from "node:fs";
53372
+ import { existsSync as existsSync52, rmSync as rmSync11 } from "node:fs";
53138
53373
  import { join as join44 } from "node:path";
53139
53374
  async function runDoctor4(options) {
53140
53375
  if (options.clear)
@@ -53290,7 +53525,7 @@ async function runClear() {
53290
53525
  failed += 1;
53291
53526
  continue;
53292
53527
  }
53293
- } else if (existsSync51(item.path)) {
53528
+ } else if (existsSync52(item.path)) {
53294
53529
  rmSync11(item.path, { recursive: true, force: true });
53295
53530
  }
53296
53531
  s.stop(`Cleared ${item.path}`);