@cortexkit/pi-magic-context 0.34.0 → 0.34.1

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.
@@ -8666,7 +8666,7 @@ import {
8666
8666
  mkdirSync as mkdirSync2,
8667
8667
  mkdtempSync,
8668
8668
  readdirSync,
8669
- readFileSync as readFileSync2,
8669
+ readFileSync as readFileSync3,
8670
8670
  unlinkSync as unlinkSync2
8671
8671
  } from "node:fs";
8672
8672
  import { basename as basename2, dirname as dirname2, join as join3 } from "node:path";
@@ -8748,6 +8748,8 @@ function safeString(value) {
8748
8748
  }
8749
8749
 
8750
8750
  // ../plugin/src/shared/rpc-utils.ts
8751
+ import { execFileSync as execFileSync2 } from "node:child_process";
8752
+ import { readFileSync as readFileSync2 } from "node:fs";
8751
8753
  function isPidAlive(pid) {
8752
8754
  if (!Number.isInteger(pid) || pid <= 0)
8753
8755
  return false;
@@ -8758,6 +8760,84 @@ function isPidAlive(pid) {
8758
8760
  return err.code === "EPERM";
8759
8761
  }
8760
8762
  }
8763
+ var RPC_IDENTITY_SKEW_TOLERANCE_MS = 120000;
8764
+ var LINUX_CLOCK_TICKS_PER_SECOND = 100;
8765
+ var PS_PROBE_TIMEOUT_MS = 1000;
8766
+ var OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
8767
+ var rpcIdentityReadFileSync = readFileSync2;
8768
+ var rpcIdentityExecFileSync = execFileSync2;
8769
+ var rpcIdentityPlatform = process.platform;
8770
+ var rpcIdentityNowMs = () => Date.now();
8771
+ function parseLinuxProcessStartTime(statContent, uptimeContent) {
8772
+ const closingCommandName = statContent.lastIndexOf(")");
8773
+ if (closingCommandName < 0)
8774
+ return null;
8775
+ const statFields = statContent.slice(closingCommandName + 1).trim().split(/\s+/);
8776
+ const startTimeTicks = Number(statFields[19]);
8777
+ const uptimeSeconds = Number(uptimeContent.trim().split(/\s+/)[0]);
8778
+ if (!Number.isFinite(startTimeTicks) || startTimeTicks < 0 || !Number.isFinite(uptimeSeconds) || uptimeSeconds < 0) {
8779
+ return null;
8780
+ }
8781
+ const processStartTime = rpcIdentityNowMs() - uptimeSeconds * 1000 + startTimeTicks / LINUX_CLOCK_TICKS_PER_SECOND * 1000;
8782
+ return Number.isFinite(processStartTime) ? processStartTime : null;
8783
+ }
8784
+ function readLinuxProcessStartTime(pid) {
8785
+ try {
8786
+ const statContent = String(rpcIdentityReadFileSync(`/proc/${pid}/stat`, "utf8"));
8787
+ const uptimeContent = String(rpcIdentityReadFileSync("/proc/uptime", "utf8"));
8788
+ return parseLinuxProcessStartTime(statContent, uptimeContent);
8789
+ } catch {
8790
+ return null;
8791
+ }
8792
+ }
8793
+ function readPsProcessStartTime(pid) {
8794
+ try {
8795
+ const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "lstart="], {
8796
+ encoding: "utf8",
8797
+ timeout: PS_PROBE_TIMEOUT_MS
8798
+ });
8799
+ const processStartTime = Date.parse(String(output).trim());
8800
+ return Number.isFinite(processStartTime) ? processStartTime : null;
8801
+ } catch {
8802
+ return null;
8803
+ }
8804
+ }
8805
+ function readLinuxProcessCommand(pid) {
8806
+ try {
8807
+ return String(rpcIdentityReadFileSync(`/proc/${pid}/cmdline`, "utf8"));
8808
+ } catch {
8809
+ return null;
8810
+ }
8811
+ }
8812
+ function readPsProcessCommand(pid) {
8813
+ try {
8814
+ const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "command="], {
8815
+ encoding: "utf8",
8816
+ timeout: PS_PROBE_TIMEOUT_MS
8817
+ });
8818
+ return String(output);
8819
+ } catch {
8820
+ return null;
8821
+ }
8822
+ }
8823
+ function commandLooksLikeOpenCode(command) {
8824
+ const normalized = command.toLowerCase();
8825
+ return OPEN_CODE_COMMAND_MARKERS.some((marker) => normalized.includes(marker));
8826
+ }
8827
+ function isPidIdentityPlausible(record) {
8828
+ if (!Number.isInteger(record.pid) || record.pid <= 0)
8829
+ return false;
8830
+ if (Number.isFinite(record.started_at) && record.started_at > 0) {
8831
+ const processStartTime = rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(record.pid) : readPsProcessStartTime(record.pid);
8832
+ if (processStartTime === null)
8833
+ return true;
8834
+ return processStartTime <= record.started_at + RPC_IDENTITY_SKEW_TOLERANCE_MS;
8835
+ }
8836
+ const command = rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(record.pid) : readPsProcessCommand(record.pid);
8837
+ if (command === null)
8838
+ return true;
8839
+ return commandLooksLikeOpenCode(command);
8840
+ }
8761
8841
  function parseRpcPortFile(content, fallbackPid = 0) {
8762
8842
  const trimmed = content.trim();
8763
8843
  if (!trimmed)
@@ -9523,6 +9603,7 @@ function bumpEpochsForWorkspaceMemberSet(db, identities, now = Date.now()) {
9523
9603
  }
9524
9604
 
9525
9605
  // ../plugin/src/features/magic-context/migrations.ts
9606
+ var FORK_MIGRATION_VERSION_FLOOR = 1e4;
9526
9607
  var MIGRATION_LOCK_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000];
9527
9608
 
9528
9609
  class MigrationLockBusyError extends Error {
@@ -11573,9 +11654,12 @@ function ensureMigrationsTable(db) {
11573
11654
  `);
11574
11655
  }
11575
11656
  function getCurrentVersion(db) {
11576
- const row = db.prepare("SELECT MAX(version) as version FROM schema_migrations").get();
11657
+ const row = db.prepare("SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations WHERE version < ?").get(FORK_MIGRATION_VERSION_FLOOR);
11577
11658
  return row?.version ?? 0;
11578
11659
  }
11660
+ function isMigrationApplied(db, version) {
11661
+ return db.prepare("SELECT 1 FROM schema_migrations WHERE version = ?").get(version) != null;
11662
+ }
11579
11663
  function isSiblingMigrationConflict(db, error, version) {
11580
11664
  if (!(error instanceof Error))
11581
11665
  return false;
@@ -11604,12 +11688,12 @@ function runMigrations(db) {
11604
11688
  try {
11605
11689
  const applied = db.transaction(() => {
11606
11690
  currentVersion = getCurrentVersion(db);
11607
- migration = MIGRATIONS.find((candidate) => candidate.version > currentVersion);
11691
+ migration = MIGRATIONS.find((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version));
11608
11692
  if (!migration)
11609
11693
  return false;
11610
11694
  if (!loggedPlan) {
11611
- const pendingCount = MIGRATIONS.filter((candidate) => candidate.version > currentVersion).length;
11612
- log(`[migrations] current schema version: ${currentVersion}, applying ${pendingCount} migration(s)`);
11695
+ const pendingCount = MIGRATIONS.filter((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version)).length;
11696
+ log(`[migrations] current upstream migration lane: ${currentVersion}, applying ${pendingCount} migration(s)`);
11613
11697
  loggedPlan = true;
11614
11698
  }
11615
11699
  migration.up(db);
@@ -11646,7 +11730,7 @@ function runMigrations(db) {
11646
11730
  }
11647
11731
  }
11648
11732
  if (loggedPlan) {
11649
- log(`[migrations] schema version now: ${MIGRATIONS[MIGRATIONS.length - 1].version}`);
11733
+ log(`[migrations] upstream migration lane now: ${MIGRATIONS[MIGRATIONS.length - 1].version}`);
11650
11734
  }
11651
11735
  }
11652
11736
  async function runMigrationsWithRetry(db, options = {}) {
@@ -144685,11 +144769,11 @@ function getPersistedSchemaVersion(db) {
144685
144769
  if (!hasMigrationsTable) {
144686
144770
  return 0;
144687
144771
  }
144688
- const row = db.prepare("SELECT MAX(version) AS version FROM schema_migrations").get();
144772
+ const row = db.prepare("SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations WHERE version < ?").get(FORK_MIGRATION_VERSION_FLOOR);
144689
144773
  return row?.version ?? 0;
144690
144774
  }
144691
144775
  function formatSchemaFenceBootLog(persistedVersion, supportedVersion) {
144692
- return `[magic-context] storage schema at boot: database=v${persistedVersion}, supported_fence=v${supportedVersion}`;
144776
+ return `[magic-context] upstream migration lane at boot: database=v${persistedVersion}, supported_fence=v${supportedVersion}`;
144693
144777
  }
144694
144778
  function getRuntimeLatestSupportedVersion(options) {
144695
144779
  if (options?.latestSupportedVersion !== undefined) {
@@ -144711,7 +144795,7 @@ function enforceSchemaFence(db, dbPath, latestSupportedVersion) {
144711
144795
  return true;
144712
144796
  }
144713
144797
  lastSchemaFenceRejection = { persistedVersion, supportedVersion: latestSupportedVersion };
144714
- log(`[magic-context] storage fatal: refusing to open ${dbPath}; database schema v${persistedVersion} is newer than this binary supports (max v${latestSupportedVersion}). A pinned or stale plugin is likely sharing this database with a newer instance; update or unpin Magic Context with 'npx @cortexkit/magic-context@latest doctor --force', then restart.`);
144798
+ log(`[magic-context] storage fatal: refusing to open ${dbPath}; upstream migration lane v${persistedVersion} is newer than this binary supports (max v${latestSupportedVersion}). A pinned or stale plugin is likely sharing this database with a newer instance; update or unpin Magic Context with 'npx @cortexkit/magic-context@latest doctor --force', then restart.`);
144715
144799
  return false;
144716
144800
  }
144717
144801
  function unreadableDiscovery(path2) {
@@ -144758,7 +144842,7 @@ function inspectRpcServerDiscovery(storageDir) {
144758
144842
  for (const portFile of portFiles) {
144759
144843
  let raw;
144760
144844
  try {
144761
- raw = readFileSync2(portFile, "utf8");
144845
+ raw = readFileSync3(portFile, "utf8");
144762
144846
  } catch {
144763
144847
  return unreadableDiscovery(portFile);
144764
144848
  }
@@ -144768,15 +144852,11 @@ function inspectRpcServerDiscovery(storageDir) {
144768
144852
  if (!record || !Number.isInteger(record.pid) || record.pid <= 0) {
144769
144853
  return unreadableDiscovery(portFile);
144770
144854
  }
144771
- if (isPidAlive(record.pid))
144855
+ if (isPidAlive(record.pid) && isPidIdentityPlausible(record))
144772
144856
  pids.add(record.pid);
144773
144857
  else
144774
144858
  staleFiles.push(portFile);
144775
144859
  }
144776
- const serverPids = [...pids].sort((a, b) => a - b);
144777
- if (serverPids.length > 0) {
144778
- return { state: "live", serverPids, staleFiles };
144779
- }
144780
144860
  for (const staleFile of staleFiles) {
144781
144861
  try {
144782
144862
  unlinkSync2(staleFile);
@@ -144784,6 +144864,10 @@ function inspectRpcServerDiscovery(storageDir) {
144784
144864
  return unreadableDiscovery(staleFile);
144785
144865
  }
144786
144866
  }
144867
+ const serverPids = [...pids].sort((a, b) => a - b);
144868
+ if (serverPids.length > 0) {
144869
+ return { state: "live", serverPids, staleFiles };
144870
+ }
144787
144871
  return { state: "stale", serverPids: [], staleFiles };
144788
144872
  }
144789
144873
  function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion) {
@@ -144804,9 +144888,9 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
144804
144888
  ...discovery.unreadableFile ? { unreadableFile: discovery.unreadableFile } : {}
144805
144889
  };
144806
144890
  if (discovery.state === "unreadable") {
144807
- log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from schema v${persistedVersion} to v${latestSupportedVersion} because RPC discovery file ${discovery.unreadableFile ?? "<unknown>"} is unreadable or invalid, so the absence of a live OpenCode server cannot be proven. Restart OpenCode, remove or repair the named discovery file, then retry this process.`);
144891
+ log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} because RPC discovery file ${discovery.unreadableFile ?? "<unknown>"} is unreadable or invalid, so the absence of a live OpenCode server cannot be proven. Restart OpenCode, remove or repair the named discovery file, then retry this process.`);
144808
144892
  } else {
144809
- log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from schema v${persistedVersion} to v${latestSupportedVersion} while live OpenCode server PID(s) ${discovery.serverPids.join(", ")} may still use the old plugin build. Restart OpenCode, then retry this process.`);
144893
+ log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} while live OpenCode server PID(s) ${discovery.serverPids.join(", ")} may still use the old plugin build. Restart OpenCode, then retry this process.`);
144810
144894
  }
144811
144895
  return false;
144812
144896
  }
@@ -149021,7 +149105,7 @@ function escapeXmlContent(s) {
149021
149105
  }
149022
149106
  // ../plugin/src/features/magic-context/project-docs-hash.ts
149023
149107
  import { createHash as createHash5 } from "node:crypto";
149024
- import { lstatSync, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
149108
+ import { lstatSync, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
149025
149109
  import path2 from "node:path";
149026
149110
  var PROJECT_DOC_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
149027
149111
  var PROJECT_DOCS_DELIMITER = `
@@ -149095,7 +149179,7 @@ function readCanonicalPieces(projectDirectory, files) {
149095
149179
  if (!safeToRead) {
149096
149180
  continue;
149097
149181
  }
149098
- const canonicalContent = canonicalizeDocContent(readFileSync3(filePath, "utf8"));
149182
+ const canonicalContent = canonicalizeDocContent(readFileSync4(filePath, "utf8"));
149099
149183
  hashPieces.push(`file:${filename}
149100
149184
  ${canonicalContent}`);
149101
149185
  renderedSections.push(`<file name="${escapeXmlAttr(filename)}">
@@ -151263,7 +151347,7 @@ function pruneNestedConfigLeaf(block, relativePath) {
151263
151347
  }
151264
151348
 
151265
151349
  // src/config/index.ts
151266
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "node:fs";
151350
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
151267
151351
 
151268
151352
  // ../plugin/src/config/migrate-dreamer-v2.ts
151269
151353
  var OLD_VERIFY_TASK = "verify";
@@ -151479,9 +151563,10 @@ function migrateLegacyExperimental(rawConfig, warnings) {
151479
151563
  const exp = experimental;
151480
151564
  const hasUM = "user_memories" in exp;
151481
151565
  const hasPKF = "pin_key_files" in exp;
151566
+ const hasMural = "mural" in exp;
151482
151567
  const TOP_LEVEL_GRADUATED = ["temporal_awareness", "caveman_text_compression"];
151483
151568
  const MEMORY_GRADUATED = ["auto_search", "git_commit_indexing"];
151484
- const hasGraduated = TOP_LEVEL_GRADUATED.some((k) => (k in exp)) || MEMORY_GRADUATED.some((k) => (k in exp));
151569
+ const hasGraduated = TOP_LEVEL_GRADUATED.some((k) => (k in exp)) || MEMORY_GRADUATED.some((k) => (k in exp)) || hasMural;
151485
151570
  if (!hasUM && !hasPKF && !hasGraduated) {
151486
151571
  return rawConfig;
151487
151572
  }
@@ -151489,6 +151574,15 @@ function migrateLegacyExperimental(rawConfig, warnings) {
151489
151574
  const dreamer = typeof patched.dreamer === "object" && patched.dreamer !== null ? { ...patched.dreamer } : {};
151490
151575
  const memory = typeof patched.memory === "object" && patched.memory !== null ? { ...patched.memory } : {};
151491
151576
  const newExperimental = { ...exp };
151577
+ const coerceToObject = (value) => {
151578
+ if (typeof value === "boolean") {
151579
+ return { enabled: value };
151580
+ }
151581
+ if (typeof value === "object" && value !== null) {
151582
+ return { ...value };
151583
+ }
151584
+ return;
151585
+ };
151492
151586
  const relocate = (key, dest, destLabel) => {
151493
151587
  if (!(key in exp))
151494
151588
  return;
@@ -151509,15 +151603,20 @@ function migrateLegacyExperimental(rawConfig, warnings) {
151509
151603
  relocate(key, patched, "");
151510
151604
  for (const key of MEMORY_GRADUATED)
151511
151605
  relocate(key, memory, "memory.");
151512
- const coerceToObject = (value) => {
151513
- if (typeof value === "boolean") {
151514
- return { enabled: value };
151515
- }
151516
- if (typeof value === "object" && value !== null) {
151517
- return { ...value };
151606
+ if (hasMural) {
151607
+ const oldMural = coerceToObject(exp.mural);
151608
+ const existingMural = patched.mural;
151609
+ if (existingMural === undefined) {
151610
+ patched.mural = oldMural ?? exp.mural;
151611
+ warnings.push('Deprecated "experimental.mural"; use top-level "mural" instead (migrated in memory; run `doctor` to persist).');
151612
+ } else if (oldMural !== undefined && typeof existingMural === "object" && existingMural !== null && !Array.isArray(existingMural)) {
151613
+ patched.mural = {
151614
+ ...oldMural,
151615
+ ...existingMural
151616
+ };
151518
151617
  }
151519
- return;
151520
- };
151618
+ delete newExperimental.mural;
151619
+ }
151521
151620
  if (hasUM) {
151522
151621
  const oldUM = coerceToObject(exp.user_memories);
151523
151622
  if (oldUM !== undefined) {
@@ -166277,12 +166376,10 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
166277
166376
  var MagicContextConfigSchema = exports_external.object({
166278
166377
  enabled: exports_external.boolean().default(true).describe("Enable magic context (default: true)"),
166279
166378
  allow_home_project: exports_external.boolean().default(false).describe("Allow Magic Context sessions launched from the exact canonical home directory. The home session uses its deterministic dir: identity so pre-gate memories reconnect. USER-LEVEL ONLY: project config is ignored. The home identity is excluded from registry seed exports, never resolves descendants by containment, and cannot join a workspace."),
166280
- experimental: exports_external.object({
166281
- mural: exports_external.object({
166282
- enabled: exports_external.boolean().default(false),
166283
- model: exports_external.string().trim().min(1).optional().describe("Model for the compress-cues task that compresses each memory into a mural cue. The mural image itself is rendered deterministically (no author model).")
166284
- }).default({ enabled: false }).describe("Experimental mural: a single deterministically-rendered image of project memories that did not fit the context budget. Cues are compressed per-memory by the compress-cues dreamer task.")
166285
- }).default({ mural: { enabled: false } }).describe("Experimental feature switches. User and project configuration are both accepted."),
166379
+ mural: exports_external.object({
166380
+ enabled: exports_external.boolean().default(false),
166381
+ model: exports_external.string().trim().min(1).optional().describe("Model for the compress-cues task that compresses each memory into a mural cue. The mural image itself is rendered deterministically (no author model).")
166382
+ }).default({ enabled: false }).describe("Experimental mural: a single deterministically-rendered image of project memories that did not fit the context budget. Cues are compressed per-memory by the compress-cues dreamer task."),
166286
166383
  transform_mode: exports_external.enum(["ts", "rust"]).default("ts").describe('Experimental: routes the entire Magic Context runtime for the project through the ck-mc Rust module over subc (requires user-level `subc` config); "ts" is the current TypeScript pipeline.'),
166287
166384
  auto_update: exports_external.boolean().optional().describe("Enable automatic npm self-update checks for the OpenCode plugin. Security: USER-only in config loader, so hostile project configs cannot suppress updates."),
166288
166385
  language: exports_external.string().trim().toLowerCase().refine((s) => isValidLanguageCode(s), 'language must be a 2-letter ISO 639-1 code (e.g. "tr", "es", "de")').optional().describe("Output language for Magic Context's generated content and guidance, as a " + '2-letter ISO 639-1 code (e.g. "tr", "es", "de", "ja", "pt"). When set, the ' + "historian, dreamer, sidekick, and the agent-guidance block instruct the model to " + "write its PROSE in this language while keeping all structural tokens (XML tags, " + "the five memory category names, code identifiers, file paths) in English. " + "USER-LEVEL ONLY (ignored in project config for security). Unset = today's " + "behavior (model mirrors the conversation; English scaffolding). Changing it " + "triggers one cache re-materialization; existing compartments/memories keep their " + "original language until naturally rewritten."),
@@ -166555,6 +166652,17 @@ function stripUnsafeProjectConfigFields(projectRaw) {
166555
166652
  warnings.push(`Ignoring historian.${removed.join("/")} from project config ` + "(security: historian model selection is user-level only; a repository cannot force extra compaction cost).");
166556
166653
  }
166557
166654
  }
166655
+ const mural = projectRaw.mural;
166656
+ if (isPlainObject3(mural) && "model" in mural) {
166657
+ delete mural.model;
166658
+ warnings.push("Ignoring mural.model from project config (security: the mural cue-compressor model is a user-level setting; a repository cannot choose where project memory is sent).");
166659
+ }
166660
+ const experimental = projectRaw.experimental;
166661
+ const legacyMural = isPlainObject3(experimental) ? experimental.mural : undefined;
166662
+ if (isPlainObject3(legacyMural) && "model" in legacyMural) {
166663
+ delete legacyMural.model;
166664
+ warnings.push("Ignoring experimental.mural.model from project config (security: the mural cue-compressor model is a user-level setting; use user-level mural.model).");
166665
+ }
166558
166666
  for (const agentKey of HIDDEN_AGENT_KEYS) {
166559
166667
  const block = projectRaw[agentKey];
166560
166668
  if (!isPlainObject3(block))
@@ -166703,7 +166811,7 @@ function dropInheritedEmbeddingKeyOnRedirect(projectRaw, mergedRaw, userRaw) {
166703
166811
  }
166704
166812
 
166705
166813
  // ../plugin/src/config/variable.ts
166706
- import { existsSync as existsSync6, readFileSync as readFileSync4 } from "node:fs";
166814
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
166707
166815
  import { homedir as homedir4 } from "node:os";
166708
166816
  import { dirname as dirname3, isAbsolute as isAbsolute2, resolve } from "node:path";
166709
166817
 
@@ -166844,7 +166952,7 @@ function substituteConfigVariables(input) {
166844
166952
  }
166845
166953
  let contents;
166846
166954
  try {
166847
- contents = readFileSync4(filePath, "utf-8").trim();
166955
+ contents = readFileSync5(filePath, "utf-8").trim();
166848
166956
  } catch (error51) {
166849
166957
  const message = error51 instanceof Error ? error51.message : String(error51);
166850
166958
  warnings.push(`Failed to read file for ${token} (${filePath}): ${message}; using empty string`);
@@ -166857,7 +166965,7 @@ function substituteConfigVariables(input) {
166857
166965
  }
166858
166966
 
166859
166967
  // ../plugin/src/shared/models-dev-cache.ts
166860
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
166968
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync6, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
166861
166969
  import { join as join5 } from "node:path";
166862
166970
 
166863
166971
  // ../plugin/src/shared/harness-provider-map.ts
@@ -166907,7 +167015,7 @@ function loadPersistedApiCacheOnce() {
166907
167015
  return;
166908
167016
  persistSeedLoaded = true;
166909
167017
  try {
166910
- const raw = readFileSync5(persistFilePath(), "utf-8");
167018
+ const raw = readFileSync6(persistFilePath(), "utf-8");
166911
167019
  const obj = JSON.parse(raw);
166912
167020
  const map2 = new Map;
166913
167021
  for (const [key, persisted] of Object.entries(obj)) {
@@ -167056,7 +167164,7 @@ function resolvePiLegacyFallback(sources) {
167056
167164
  }
167057
167165
  function loadConfigFile(path3, scope) {
167058
167166
  try {
167059
- const rawText = readFileSync6(path3, "utf-8");
167167
+ const rawText = readFileSync7(path3, "utf-8");
167060
167168
  const substituted = substituteConfigVariables({
167061
167169
  text: rawText,
167062
167170
  configPath: path3,
@@ -184112,4 +184220,4 @@ function registerMagicContextTools(pi, opts) {
184112
184220
  }
184113
184221
  }
184114
184222
 
184115
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, estimateTokens, normalizeText, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, stableStringify, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, updateTagByteSize, getActiveTagTokenAggregate, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, piModelRefToCanonical, resolveModelRefForPi, isSaneLimit, resolveLimit, getSdkContextLimit, normalizeTodoStateJson, buildSyntheticTodoPart, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, computeNormalizedHash, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, invalidateMemory, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, computeCueContentHash, getMuralCueState, memoryNeedsCue, setMuralCue, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, registerMagicContextTools };
184223
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, isMidTurn, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, estimateTokens, normalizeText, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, isCompartmentLeaseHeld, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, copySessionStateForClone, getErrorMessage, describeError, setStoragePrivatePermissionEnforcement, stableStringify, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getLastNudgeLevel, setLastNudgeLevel, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, setSessionWorkMetrics, getSessionWorkMetrics, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, updateTagByteSize, getActiveTagTokenAggregate, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, BoundedSessionMap, piModelRefToCanonical, resolveModelRefForPi, isSaneLimit, resolveLimit, getSdkContextLimit, normalizeTodoStateJson, buildSyntheticTodoPart, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath2 as getOpenCodeDbPath, parseCron, nextOccurrence, nextDueAtMs, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, registerMagicContextTools };