@cortexkit/pi-magic-context 0.34.0 → 0.34.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8666,7 +8666,8 @@ import {
8666
8666
  mkdirSync as mkdirSync2,
8667
8667
  mkdtempSync,
8668
8668
  readdirSync,
8669
- readFileSync as readFileSync2,
8669
+ readFileSync as readFileSync3,
8670
+ statSync as statSync3,
8670
8671
  unlinkSync as unlinkSync2
8671
8672
  } from "node:fs";
8672
8673
  import { basename as basename2, dirname as dirname2, join as join3 } from "node:path";
@@ -8748,6 +8749,8 @@ function safeString(value) {
8748
8749
  }
8749
8750
 
8750
8751
  // ../plugin/src/shared/rpc-utils.ts
8752
+ import { execFileSync as execFileSync2 } from "node:child_process";
8753
+ import { readFileSync as readFileSync2 } from "node:fs";
8751
8754
  function isPidAlive(pid) {
8752
8755
  if (!Number.isInteger(pid) || pid <= 0)
8753
8756
  return false;
@@ -8758,6 +8761,84 @@ function isPidAlive(pid) {
8758
8761
  return err.code === "EPERM";
8759
8762
  }
8760
8763
  }
8764
+ var RPC_IDENTITY_SKEW_TOLERANCE_MS = 120000;
8765
+ var LINUX_CLOCK_TICKS_PER_SECOND = 100;
8766
+ var PS_PROBE_TIMEOUT_MS = 1000;
8767
+ var OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
8768
+ var rpcIdentityReadFileSync = readFileSync2;
8769
+ var rpcIdentityExecFileSync = execFileSync2;
8770
+ var rpcIdentityPlatform = process.platform;
8771
+ var rpcIdentityNowMs = () => Date.now();
8772
+ function parseLinuxProcessStartTime(statContent, uptimeContent) {
8773
+ const closingCommandName = statContent.lastIndexOf(")");
8774
+ if (closingCommandName < 0)
8775
+ return null;
8776
+ const statFields = statContent.slice(closingCommandName + 1).trim().split(/\s+/);
8777
+ const startTimeTicks = Number(statFields[19]);
8778
+ const uptimeSeconds = Number(uptimeContent.trim().split(/\s+/)[0]);
8779
+ if (!Number.isFinite(startTimeTicks) || startTimeTicks < 0 || !Number.isFinite(uptimeSeconds) || uptimeSeconds < 0) {
8780
+ return null;
8781
+ }
8782
+ const processStartTime = rpcIdentityNowMs() - uptimeSeconds * 1000 + startTimeTicks / LINUX_CLOCK_TICKS_PER_SECOND * 1000;
8783
+ return Number.isFinite(processStartTime) ? processStartTime : null;
8784
+ }
8785
+ function readLinuxProcessStartTime(pid) {
8786
+ try {
8787
+ const statContent = String(rpcIdentityReadFileSync(`/proc/${pid}/stat`, "utf8"));
8788
+ const uptimeContent = String(rpcIdentityReadFileSync("/proc/uptime", "utf8"));
8789
+ return parseLinuxProcessStartTime(statContent, uptimeContent);
8790
+ } catch {
8791
+ return null;
8792
+ }
8793
+ }
8794
+ function readPsProcessStartTime(pid) {
8795
+ try {
8796
+ const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "lstart="], {
8797
+ encoding: "utf8",
8798
+ timeout: PS_PROBE_TIMEOUT_MS
8799
+ });
8800
+ const processStartTime = Date.parse(String(output).trim());
8801
+ return Number.isFinite(processStartTime) ? processStartTime : null;
8802
+ } catch {
8803
+ return null;
8804
+ }
8805
+ }
8806
+ function readLinuxProcessCommand(pid) {
8807
+ try {
8808
+ return String(rpcIdentityReadFileSync(`/proc/${pid}/cmdline`, "utf8"));
8809
+ } catch {
8810
+ return null;
8811
+ }
8812
+ }
8813
+ function readPsProcessCommand(pid) {
8814
+ try {
8815
+ const output = rpcIdentityExecFileSync("ps", ["-p", String(pid), "-o", "command="], {
8816
+ encoding: "utf8",
8817
+ timeout: PS_PROBE_TIMEOUT_MS
8818
+ });
8819
+ return String(output);
8820
+ } catch {
8821
+ return null;
8822
+ }
8823
+ }
8824
+ function commandLooksLikeOpenCode(command) {
8825
+ const normalized = command.toLowerCase();
8826
+ return OPEN_CODE_COMMAND_MARKERS.some((marker) => normalized.includes(marker));
8827
+ }
8828
+ function isPidIdentityPlausible(record) {
8829
+ if (!Number.isInteger(record.pid) || record.pid <= 0)
8830
+ return false;
8831
+ if (Number.isFinite(record.started_at) && record.started_at > 0) {
8832
+ const processStartTime = rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(record.pid) : readPsProcessStartTime(record.pid);
8833
+ if (processStartTime === null)
8834
+ return true;
8835
+ return processStartTime <= record.started_at + RPC_IDENTITY_SKEW_TOLERANCE_MS;
8836
+ }
8837
+ const command = rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(record.pid) : readPsProcessCommand(record.pid);
8838
+ if (command === null)
8839
+ return true;
8840
+ return commandLooksLikeOpenCode(command);
8841
+ }
8761
8842
  function parseRpcPortFile(content, fallbackPid = 0) {
8762
8843
  const trimmed = content.trim();
8763
8844
  if (!trimmed)
@@ -9523,6 +9604,7 @@ function bumpEpochsForWorkspaceMemberSet(db, identities, now = Date.now()) {
9523
9604
  }
9524
9605
 
9525
9606
  // ../plugin/src/features/magic-context/migrations.ts
9607
+ var FORK_MIGRATION_VERSION_FLOOR = 1e4;
9526
9608
  var MIGRATION_LOCK_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000];
9527
9609
 
9528
9610
  class MigrationLockBusyError extends Error {
@@ -11560,6 +11642,15 @@ var MIGRATIONS = [
11560
11642
  ensureColumn(db, "session_meta", "detected_context_limit_provenance", "TEXT NOT NULL DEFAULT 'unknown'");
11561
11643
  }
11562
11644
  }
11645
+ },
11646
+ {
11647
+ version: 75,
11648
+ description: "persist mural cue validation rejection latches",
11649
+ up(db) {
11650
+ if (!tableExists2(db, "memories"))
11651
+ return;
11652
+ ensureColumn(db, "memories", "mural_cue_rejection_count", "INTEGER NOT NULL DEFAULT 0");
11653
+ }
11563
11654
  }
11564
11655
  ];
11565
11656
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -11573,9 +11664,12 @@ function ensureMigrationsTable(db) {
11573
11664
  `);
11574
11665
  }
11575
11666
  function getCurrentVersion(db) {
11576
- const row = db.prepare("SELECT MAX(version) as version FROM schema_migrations").get();
11667
+ const row = db.prepare("SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations WHERE version < ?").get(FORK_MIGRATION_VERSION_FLOOR);
11577
11668
  return row?.version ?? 0;
11578
11669
  }
11670
+ function isMigrationApplied(db, version) {
11671
+ return db.prepare("SELECT 1 FROM schema_migrations WHERE version = ?").get(version) != null;
11672
+ }
11579
11673
  function isSiblingMigrationConflict(db, error, version) {
11580
11674
  if (!(error instanceof Error))
11581
11675
  return false;
@@ -11604,12 +11698,12 @@ function runMigrations(db) {
11604
11698
  try {
11605
11699
  const applied = db.transaction(() => {
11606
11700
  currentVersion = getCurrentVersion(db);
11607
- migration = MIGRATIONS.find((candidate) => candidate.version > currentVersion);
11701
+ migration = MIGRATIONS.find((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version));
11608
11702
  if (!migration)
11609
11703
  return false;
11610
11704
  if (!loggedPlan) {
11611
- const pendingCount = MIGRATIONS.filter((candidate) => candidate.version > currentVersion).length;
11612
- log(`[migrations] current schema version: ${currentVersion}, applying ${pendingCount} migration(s)`);
11705
+ const pendingCount = MIGRATIONS.filter((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version)).length;
11706
+ log(`[migrations] current upstream migration lane: ${currentVersion}, applying ${pendingCount} migration(s)`);
11613
11707
  loggedPlan = true;
11614
11708
  }
11615
11709
  migration.up(db);
@@ -11646,7 +11740,7 @@ function runMigrations(db) {
11646
11740
  }
11647
11741
  }
11648
11742
  if (loggedPlan) {
11649
- log(`[migrations] schema version now: ${MIGRATIONS[MIGRATIONS.length - 1].version}`);
11743
+ log(`[migrations] upstream migration lane now: ${MIGRATIONS[MIGRATIONS.length - 1].version}`);
11650
11744
  }
11651
11745
  }
11652
11746
  async function runMigrationsWithRetry(db, options = {}) {
@@ -144592,7 +144686,7 @@ function getSchemaFenceRejection() {
144592
144686
  function getMigrationOnOpenRefusal() {
144593
144687
  return lastMigrationOnOpenRefusal;
144594
144688
  }
144595
- var LATEST_SUPPORTED_VERSION = 74;
144689
+ var LATEST_SUPPORTED_VERSION = 75;
144596
144690
  var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
144597
144691
  var defaultStoragePermissionFs = { chmodSync, mkdirSync: mkdirSync2 };
144598
144692
  var storagePermissionFs = defaultStoragePermissionFs;
@@ -144685,11 +144779,11 @@ function getPersistedSchemaVersion(db) {
144685
144779
  if (!hasMigrationsTable) {
144686
144780
  return 0;
144687
144781
  }
144688
- const row = db.prepare("SELECT MAX(version) AS version FROM schema_migrations").get();
144782
+ const row = db.prepare("SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations WHERE version < ?").get(FORK_MIGRATION_VERSION_FLOOR);
144689
144783
  return row?.version ?? 0;
144690
144784
  }
144691
144785
  function formatSchemaFenceBootLog(persistedVersion, supportedVersion) {
144692
- return `[magic-context] storage schema at boot: database=v${persistedVersion}, supported_fence=v${supportedVersion}`;
144786
+ return `[magic-context] upstream migration lane at boot: database=v${persistedVersion}, supported_fence=v${supportedVersion}`;
144693
144787
  }
144694
144788
  function getRuntimeLatestSupportedVersion(options) {
144695
144789
  if (options?.latestSupportedVersion !== undefined) {
@@ -144711,27 +144805,68 @@ function enforceSchemaFence(db, dbPath, latestSupportedVersion) {
144711
144805
  return true;
144712
144806
  }
144713
144807
  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.`);
144808
+ 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
144809
  return false;
144716
144810
  }
144717
- function unreadableDiscovery(path2) {
144811
+ function unreadableDiscovery(path2, arm) {
144718
144812
  return {
144719
144813
  state: "unreadable",
144720
144814
  serverPids: [],
144721
144815
  staleFiles: [],
144722
- unreadableFile: path2
144816
+ unreadableFile: path2,
144817
+ unreadableArm: arm
144723
144818
  };
144724
144819
  }
144820
+ var RPC_DISCOVERY_PARSE_GRACE_MS = 10 * 60 * 1000;
144821
+ var defaultRpcDiscoveryFs = {
144822
+ readdirSync: (path2, options) => options?.withFileTypes ? readdirSync(path2, { withFileTypes: true }) : readdirSync(path2),
144823
+ readFileSync: (path2, encoding) => String(readFileSync3(path2, encoding)),
144824
+ statSync: (path2) => ({ mtimeMs: statSync3(path2).mtimeMs }),
144825
+ unlinkSync: (path2) => unlinkSync2(path2)
144826
+ };
144827
+ var rpcDiscoveryFs = defaultRpcDiscoveryFs;
144828
+ function invalidDiscoveryReason(raw) {
144829
+ const trimmed = raw.trim();
144830
+ if (trimmed.startsWith("{")) {
144831
+ try {
144832
+ const parsed = JSON.parse(trimmed);
144833
+ if ("pid" in parsed) {
144834
+ const pid = Number(parsed.pid);
144835
+ if (!Number.isInteger(pid) || pid <= 0)
144836
+ return "invalid-pid";
144837
+ }
144838
+ } catch {}
144839
+ }
144840
+ return "parse-invalid";
144841
+ }
144842
+ function classifyJunkDiscovery(portFile, raw, staleFiles) {
144843
+ let mtimeMs;
144844
+ try {
144845
+ mtimeMs = rpcDiscoveryFs.statSync(portFile).mtimeMs;
144846
+ } catch (error) {
144847
+ if (error.code === "ENOENT")
144848
+ return null;
144849
+ return unreadableDiscovery(portFile, "io");
144850
+ }
144851
+ const ageMs = Date.now() - mtimeMs;
144852
+ if (!Number.isFinite(ageMs) || ageMs < RPC_DISCOVERY_PARSE_GRACE_MS) {
144853
+ return unreadableDiscovery(portFile, "parse");
144854
+ }
144855
+ staleFiles.push(portFile);
144856
+ const reason = invalidDiscoveryReason(raw);
144857
+ log(`[magic-context] removing stale RPC discovery file ${portFile}: ${reason} record older than 10 minutes`);
144858
+ return null;
144859
+ }
144725
144860
  function inspectRpcServerDiscovery(storageDir) {
144726
144861
  const rpcRoot = join3(storageDir, "rpc");
144727
144862
  let projectEntries;
144728
144863
  try {
144729
- projectEntries = readdirSync(rpcRoot, { withFileTypes: true });
144864
+ projectEntries = rpcDiscoveryFs.readdirSync(rpcRoot, { withFileTypes: true });
144730
144865
  } catch (error) {
144731
144866
  if (error.code === "ENOENT") {
144732
144867
  return { state: "absent", serverPids: [], staleFiles: [] };
144733
144868
  }
144734
- return unreadableDiscovery(rpcRoot);
144869
+ return unreadableDiscovery(rpcRoot, "io");
144735
144870
  }
144736
144871
  const portFiles = [];
144737
144872
  for (const projectEntry of projectEntries) {
@@ -144740,9 +144875,11 @@ function inspectRpcServerDiscovery(storageDir) {
144740
144875
  const projectDir = join3(rpcRoot, projectEntry.name);
144741
144876
  let entries;
144742
144877
  try {
144743
- entries = readdirSync(projectDir);
144744
- } catch {
144745
- return unreadableDiscovery(projectDir);
144878
+ entries = rpcDiscoveryFs.readdirSync(projectDir);
144879
+ } catch (error) {
144880
+ if (error.code === "ENOENT")
144881
+ continue;
144882
+ return unreadableDiscovery(projectDir, "io");
144746
144883
  }
144747
144884
  for (const entry of entries) {
144748
144885
  if (entry === "port" || entry.startsWith("port-") && entry.endsWith(".json")) {
@@ -144758,32 +144895,38 @@ function inspectRpcServerDiscovery(storageDir) {
144758
144895
  for (const portFile of portFiles) {
144759
144896
  let raw;
144760
144897
  try {
144761
- raw = readFileSync2(portFile, "utf8");
144762
- } catch {
144763
- return unreadableDiscovery(portFile);
144898
+ raw = rpcDiscoveryFs.readFileSync(portFile, "utf8");
144899
+ } catch (error) {
144900
+ if (error.code === "ENOENT")
144901
+ continue;
144902
+ return unreadableDiscovery(portFile, "io");
144764
144903
  }
144765
144904
  const filename = basename2(portFile);
144766
144905
  const pidFromName = /^port-(\d+)/.exec(filename)?.[1];
144767
- const record = parseRpcPortFile(raw, pidFromName ? Number(pidFromName) : 0);
144906
+ const fallbackPid = pidFromName ? Number(pidFromName) : 0;
144907
+ const record = parseRpcPortFile(raw, fallbackPid);
144768
144908
  if (!record || !Number.isInteger(record.pid) || record.pid <= 0) {
144769
- return unreadableDiscovery(portFile);
144909
+ const junk = classifyJunkDiscovery(portFile, raw, staleFiles);
144910
+ if (junk)
144911
+ return junk;
144912
+ continue;
144770
144913
  }
144771
- if (isPidAlive(record.pid))
144914
+ if (isPidAlive(record.pid) && isPidIdentityPlausible(record))
144772
144915
  pids.add(record.pid);
144773
144916
  else
144774
144917
  staleFiles.push(portFile);
144775
144918
  }
144776
- const serverPids = [...pids].sort((a, b) => a - b);
144777
- if (serverPids.length > 0) {
144778
- return { state: "live", serverPids, staleFiles };
144779
- }
144780
144919
  for (const staleFile of staleFiles) {
144781
144920
  try {
144782
- unlinkSync2(staleFile);
144921
+ rpcDiscoveryFs.unlinkSync(staleFile);
144783
144922
  } catch {
144784
- return unreadableDiscovery(staleFile);
144923
+ return unreadableDiscovery(staleFile, "io");
144785
144924
  }
144786
144925
  }
144926
+ const serverPids = [...pids].sort((a, b) => a - b);
144927
+ if (serverPids.length > 0) {
144928
+ return { state: "live", serverPids, staleFiles };
144929
+ }
144787
144930
  return { state: "stale", serverPids: [], staleFiles };
144788
144931
  }
144789
144932
  function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion) {
@@ -144801,12 +144944,16 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
144801
144944
  persistedVersion,
144802
144945
  supportedVersion: latestSupportedVersion,
144803
144946
  serverPids: discovery.serverPids,
144804
- ...discovery.unreadableFile ? { unreadableFile: discovery.unreadableFile } : {}
144947
+ ...discovery.unreadableFile ? { unreadableFile: discovery.unreadableFile } : {},
144948
+ ...discovery.unreadableArm ? { unreadableArm: discovery.unreadableArm } : {}
144805
144949
  };
144806
144950
  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.`);
144951
+ const unreadableFile = discovery.unreadableFile ?? "<unknown>";
144952
+ const arm = discovery.unreadableArm ?? "io";
144953
+ const recovery = arm === "io" ? `If no OpenCode server is running, it is safe to delete ${unreadableFile} and retry.` : `Retry after the file is older than the ten-minute grace window, or stop OpenCode before deleting it.`;
144954
+ log(`[magic-context] storage fatal: refusing to migrate ${dbPath} from upstream migration v${persistedVersion} to v${latestSupportedVersion} because RPC discovery file ${unreadableFile} is uncertain (${arm} arm), so the absence of a live OpenCode server cannot be proven. ${recovery}`);
144808
144955
  } 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.`);
144956
+ 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
144957
  }
144811
144958
  return false;
144812
144959
  }
@@ -145098,6 +145245,7 @@ function initializeDatabase(db) {
145098
145245
  mural_cue TEXT,
145099
145246
  mural_cue_hash TEXT,
145100
145247
  mural_cue_at INTEGER,
145248
+ mural_cue_rejection_count INTEGER NOT NULL DEFAULT 0,
145101
145249
  UNIQUE(project_path, category, normalized_hash)
145102
145250
  );
145103
145251
 
@@ -146429,6 +146577,7 @@ function clearCachedM0M1(db, sessionId) {
146429
146577
 
146430
146578
  // ../plugin/src/features/magic-context/storage-meta-persisted.ts
146431
146579
  var emergencyRecoveryArmedSessions = new Set;
146580
+ var emergencyRecoveryArmedAtBySession = new Map;
146432
146581
  var providerOverflowReconfirmedSessions = new Set;
146433
146582
  var CAS_RETRY_LIMIT = 5;
146434
146583
  var AUTO_SEARCH_NO_HINT_REASONS = new Set([
@@ -147194,6 +147343,7 @@ function getOverflowState(db, sessionId, modelKey) {
147194
147343
  }
147195
147344
  function recordOverflowDetected(db, sessionId, reportedLimit, modelKey, origin = "provider_overflow", provenance = "unknown") {
147196
147345
  emergencyRecoveryArmedSessions.add(sessionId);
147346
+ emergencyRecoveryArmedAtBySession.set(sessionId, Date.now());
147197
147347
  db.transaction(() => {
147198
147348
  ensureSessionMetaRow(db, sessionId);
147199
147349
  const prior = db.prepare("SELECT needs_emergency_recovery FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -147217,6 +147367,7 @@ function clearEmergencyRecovery(db, sessionId) {
147217
147367
  }
147218
147368
  })();
147219
147369
  emergencyRecoveryArmedSessions.delete(sessionId);
147370
+ emergencyRecoveryArmedAtBySession.delete(sessionId);
147220
147371
  providerOverflowReconfirmedSessions.delete(sessionId);
147221
147372
  }
147222
147373
  function clearDetectedContextLimit(db, sessionId) {
@@ -149021,7 +149172,7 @@ function escapeXmlContent(s) {
149021
149172
  }
149022
149173
  // ../plugin/src/features/magic-context/project-docs-hash.ts
149023
149174
  import { createHash as createHash5 } from "node:crypto";
149024
- import { lstatSync, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
149175
+ import { lstatSync, readFileSync as readFileSync4, statSync as statSync4 } from "node:fs";
149025
149176
  import path2 from "node:path";
149026
149177
  var PROJECT_DOC_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
149027
149178
  var PROJECT_DOCS_DELIMITER = `
@@ -149052,7 +149203,7 @@ function fingerprintFile(filePath) {
149052
149203
  }
149053
149204
  function readDirectoryMtimeMs(projectDirectory) {
149054
149205
  try {
149055
- return statSync3(projectDirectory).mtimeMs;
149206
+ return statSync4(projectDirectory).mtimeMs;
149056
149207
  } catch {
149057
149208
  return 0;
149058
149209
  }
@@ -149095,7 +149246,7 @@ function readCanonicalPieces(projectDirectory, files) {
149095
149246
  if (!safeToRead) {
149096
149247
  continue;
149097
149248
  }
149098
- const canonicalContent = canonicalizeDocContent(readFileSync3(filePath, "utf8"));
149249
+ const canonicalContent = canonicalizeDocContent(readFileSync4(filePath, "utf8"));
149099
149250
  hashPieces.push(`file:${filename}
149100
149251
  ${canonicalContent}`);
149101
149252
  renderedSections.push(`<file name="${escapeXmlAttr(filename)}">
@@ -151263,7 +151414,7 @@ function pruneNestedConfigLeaf(block, relativePath) {
151263
151414
  }
151264
151415
 
151265
151416
  // src/config/index.ts
151266
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "node:fs";
151417
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
151267
151418
 
151268
151419
  // ../plugin/src/config/migrate-dreamer-v2.ts
151269
151420
  var OLD_VERIFY_TASK = "verify";
@@ -151479,9 +151630,10 @@ function migrateLegacyExperimental(rawConfig, warnings) {
151479
151630
  const exp = experimental;
151480
151631
  const hasUM = "user_memories" in exp;
151481
151632
  const hasPKF = "pin_key_files" in exp;
151633
+ const hasMural = "mural" in exp;
151482
151634
  const TOP_LEVEL_GRADUATED = ["temporal_awareness", "caveman_text_compression"];
151483
151635
  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));
151636
+ const hasGraduated = TOP_LEVEL_GRADUATED.some((k) => (k in exp)) || MEMORY_GRADUATED.some((k) => (k in exp)) || hasMural;
151485
151637
  if (!hasUM && !hasPKF && !hasGraduated) {
151486
151638
  return rawConfig;
151487
151639
  }
@@ -151489,6 +151641,15 @@ function migrateLegacyExperimental(rawConfig, warnings) {
151489
151641
  const dreamer = typeof patched.dreamer === "object" && patched.dreamer !== null ? { ...patched.dreamer } : {};
151490
151642
  const memory = typeof patched.memory === "object" && patched.memory !== null ? { ...patched.memory } : {};
151491
151643
  const newExperimental = { ...exp };
151644
+ const coerceToObject = (value) => {
151645
+ if (typeof value === "boolean") {
151646
+ return { enabled: value };
151647
+ }
151648
+ if (typeof value === "object" && value !== null) {
151649
+ return { ...value };
151650
+ }
151651
+ return;
151652
+ };
151492
151653
  const relocate = (key, dest, destLabel) => {
151493
151654
  if (!(key in exp))
151494
151655
  return;
@@ -151509,15 +151670,20 @@ function migrateLegacyExperimental(rawConfig, warnings) {
151509
151670
  relocate(key, patched, "");
151510
151671
  for (const key of MEMORY_GRADUATED)
151511
151672
  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 };
151673
+ if (hasMural) {
151674
+ const oldMural = coerceToObject(exp.mural);
151675
+ const existingMural = patched.mural;
151676
+ if (existingMural === undefined) {
151677
+ patched.mural = oldMural ?? exp.mural;
151678
+ warnings.push('Deprecated "experimental.mural"; use top-level "mural" instead (migrated in memory; run `doctor` to persist).');
151679
+ } else if (oldMural !== undefined && typeof existingMural === "object" && existingMural !== null && !Array.isArray(existingMural)) {
151680
+ patched.mural = {
151681
+ ...oldMural,
151682
+ ...existingMural
151683
+ };
151518
151684
  }
151519
- return;
151520
- };
151685
+ delete newExperimental.mural;
151686
+ }
151521
151687
  if (hasUM) {
151522
151688
  const oldUM = coerceToObject(exp.user_memories);
151523
151689
  if (oldUM !== undefined) {
@@ -166277,12 +166443,10 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
166277
166443
  var MagicContextConfigSchema = exports_external.object({
166278
166444
  enabled: exports_external.boolean().default(true).describe("Enable magic context (default: true)"),
166279
166445
  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."),
166446
+ mural: exports_external.object({
166447
+ enabled: exports_external.boolean().default(false),
166448
+ 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).")
166449
+ }).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
166450
  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
166451
  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
166452
  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 +166719,17 @@ function stripUnsafeProjectConfigFields(projectRaw) {
166555
166719
  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
166720
  }
166557
166721
  }
166722
+ const mural = projectRaw.mural;
166723
+ if (isPlainObject3(mural) && "model" in mural) {
166724
+ delete mural.model;
166725
+ 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).");
166726
+ }
166727
+ const experimental = projectRaw.experimental;
166728
+ const legacyMural = isPlainObject3(experimental) ? experimental.mural : undefined;
166729
+ if (isPlainObject3(legacyMural) && "model" in legacyMural) {
166730
+ delete legacyMural.model;
166731
+ 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).");
166732
+ }
166558
166733
  for (const agentKey of HIDDEN_AGENT_KEYS) {
166559
166734
  const block = projectRaw[agentKey];
166560
166735
  if (!isPlainObject3(block))
@@ -166703,7 +166878,7 @@ function dropInheritedEmbeddingKeyOnRedirect(projectRaw, mergedRaw, userRaw) {
166703
166878
  }
166704
166879
 
166705
166880
  // ../plugin/src/config/variable.ts
166706
- import { existsSync as existsSync6, readFileSync as readFileSync4 } from "node:fs";
166881
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
166707
166882
  import { homedir as homedir4 } from "node:os";
166708
166883
  import { dirname as dirname3, isAbsolute as isAbsolute2, resolve } from "node:path";
166709
166884
 
@@ -166844,7 +167019,7 @@ function substituteConfigVariables(input) {
166844
167019
  }
166845
167020
  let contents;
166846
167021
  try {
166847
- contents = readFileSync4(filePath, "utf-8").trim();
167022
+ contents = readFileSync5(filePath, "utf-8").trim();
166848
167023
  } catch (error51) {
166849
167024
  const message = error51 instanceof Error ? error51.message : String(error51);
166850
167025
  warnings.push(`Failed to read file for ${token} (${filePath}): ${message}; using empty string`);
@@ -166857,7 +167032,7 @@ function substituteConfigVariables(input) {
166857
167032
  }
166858
167033
 
166859
167034
  // ../plugin/src/shared/models-dev-cache.ts
166860
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
167035
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync6, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
166861
167036
  import { join as join5 } from "node:path";
166862
167037
 
166863
167038
  // ../plugin/src/shared/harness-provider-map.ts
@@ -166907,7 +167082,7 @@ function loadPersistedApiCacheOnce() {
166907
167082
  return;
166908
167083
  persistSeedLoaded = true;
166909
167084
  try {
166910
- const raw = readFileSync5(persistFilePath(), "utf-8");
167085
+ const raw = readFileSync6(persistFilePath(), "utf-8");
166911
167086
  const obj = JSON.parse(raw);
166912
167087
  const map2 = new Map;
166913
167088
  for (const [key, persisted] of Object.entries(obj)) {
@@ -167056,7 +167231,7 @@ function resolvePiLegacyFallback(sources) {
167056
167231
  }
167057
167232
  function loadConfigFile(path3, scope) {
167058
167233
  try {
167059
- const rawText = readFileSync6(path3, "utf-8");
167234
+ const rawText = readFileSync7(path3, "utf-8");
167060
167235
  const substituted = substituteConfigVariables({
167061
167236
  text: rawText,
167062
167237
  configPath: path3,
@@ -167386,7 +167561,7 @@ function loadPiConfigDetailed(opts = {}) {
167386
167561
  }
167387
167562
 
167388
167563
  // src/embedding-bootstrap.ts
167389
- import { statSync as statSync4 } from "node:fs";
167564
+ import { statSync as statSync5 } from "node:fs";
167390
167565
 
167391
167566
  // ../plugin/src/features/magic-context/compartment-chunk-embedding.ts
167392
167567
  import { createHash as createHash8 } from "node:crypto";
@@ -173437,7 +173612,7 @@ function configCandidatePaths(directory, loadedPaths) {
173437
173612
  function configFingerprint(paths) {
173438
173613
  return paths.map((path3) => {
173439
173614
  try {
173440
- const stat2 = statSync4(path3);
173615
+ const stat2 = statSync5(path3);
173441
173616
  return `${path3}:${stat2.size}:${stat2.mtimeMs}`;
173442
173617
  } catch {
173443
173618
  return `${path3}:missing`;
@@ -178517,6 +178692,7 @@ function computeCueContentHash(content) {
178517
178692
  return createHash13("sha256").update(content).digest("hex");
178518
178693
  }
178519
178694
  var muralCueColumnCache = new WeakMap;
178695
+ var muralCueRejectionColumnCache = new WeakMap;
178520
178696
  function hasMuralCueColumns(db) {
178521
178697
  const cached2 = muralCueColumnCache.get(db);
178522
178698
  if (cached2 !== undefined)
@@ -178526,6 +178702,15 @@ function hasMuralCueColumns(db) {
178526
178702
  muralCueColumnCache.set(db, present);
178527
178703
  return present;
178528
178704
  }
178705
+ function hasMuralCueRejectionCountColumn(db) {
178706
+ const cached2 = muralCueRejectionColumnCache.get(db);
178707
+ if (cached2 !== undefined)
178708
+ return cached2;
178709
+ const columns = db.prepare("PRAGMA table_info(memories)").all();
178710
+ const present = columns.some((column) => column.name === "mural_cue_rejection_count");
178711
+ muralCueRejectionColumnCache.set(db, present);
178712
+ return present;
178713
+ }
178529
178714
  function getMuralCueState(db, memoryIds) {
178530
178715
  const out = new Map;
178531
178716
  if (!hasMuralCueColumns(db))
@@ -178534,9 +178719,14 @@ function getMuralCueState(db, memoryIds) {
178534
178719
  if (ids.length === 0)
178535
178720
  return out;
178536
178721
  const placeholders3 = ids.map(() => "?").join(", ");
178537
- const rows = db.prepare(`SELECT id, mural_cue, mural_cue_hash FROM memories WHERE id IN (${placeholders3})`).all(...ids);
178722
+ const rejectionCountColumn = hasMuralCueRejectionCountColumn(db) ? "COALESCE(mural_cue_rejection_count, 0) AS mural_cue_rejection_count" : "0 AS mural_cue_rejection_count";
178723
+ const rows = db.prepare(`SELECT id, mural_cue, mural_cue_hash, ${rejectionCountColumn} FROM memories WHERE id IN (${placeholders3})`).all(...ids);
178538
178724
  for (const row of rows) {
178539
- out.set(row.id, { cue: row.mural_cue ?? null, hash: row.mural_cue_hash ?? null });
178725
+ out.set(row.id, {
178726
+ cue: row.mural_cue ?? null,
178727
+ hash: row.mural_cue_hash ?? null,
178728
+ ...row.mural_cue_rejection_count > 0 ? { rejectionCount: row.mural_cue_rejection_count } : {}
178729
+ });
178540
178730
  }
178541
178731
  return out;
178542
178732
  }
@@ -178553,9 +178743,25 @@ function setMuralCue(db, projectPath, id, cue, contentHash) {
178553
178743
  if (!owned) {
178554
178744
  throw new Error(`Memory ${id} does not belong to project ${projectPath}`);
178555
178745
  }
178556
- db.prepare("UPDATE memories SET mural_cue = ?, mural_cue_hash = ?, mural_cue_at = ? WHERE id = ? AND project_path = ?").run(cue, contentHash, Date.now(), id, projectPath);
178746
+ const rejectionReset = hasMuralCueRejectionCountColumn(db) ? ", mural_cue_rejection_count = 0" : "";
178747
+ db.prepare(`UPDATE memories SET mural_cue = ?, mural_cue_hash = ?, mural_cue_at = ?${rejectionReset} WHERE id = ? AND project_path = ?`).run(cue, contentHash, Date.now(), id, projectPath);
178557
178748
  });
178558
178749
  }
178750
+ function recordMuralCueRejection(db, projectPath, id, contentHash) {
178751
+ if (!hasMuralCueColumns(db) || !hasMuralCueRejectionCountColumn(db))
178752
+ return 0;
178753
+ let count = 0;
178754
+ withPrivilegedWriter(db, () => {
178755
+ const owned = db.prepare("SELECT 1 FROM memories WHERE id = ? AND project_path = ?").get(id, projectPath);
178756
+ if (!owned) {
178757
+ throw new Error(`Memory ${id} does not belong to project ${projectPath}`);
178758
+ }
178759
+ const row = db.prepare("SELECT mural_cue_hash, mural_cue_rejection_count FROM memories WHERE id = ?").get(id);
178760
+ count = row?.mural_cue_hash === contentHash ? (row.mural_cue_rejection_count ?? 0) + 1 : 1;
178761
+ db.prepare("UPDATE memories SET mural_cue = NULL, mural_cue_hash = ?, mural_cue_at = ?, mural_cue_rejection_count = ? WHERE id = ? AND project_path = ?").run(contentHash, Date.now(), count, id, projectPath);
178762
+ });
178763
+ return count;
178764
+ }
178559
178765
 
178560
178766
  // ../plugin/src/features/magic-context/memory/visibility.ts
178561
178767
  var FOREIGN_VISIBLE_SQL = "status IN ('active','permanent') AND (expires_at IS NULL OR expires_at > :now_ms) AND shareable = 1 AND scope IN ('project','ecosystem','universe') AND category IN (SELECT value FROM json_each(:share_categories)) AND project_path IN (SELECT project_path FROM mc_workspace_members WHERE workspace_id = :workspace_id) AND project_path <> :reader_project";
@@ -179188,7 +179394,8 @@ function updateMemoryContent(db, id, content, normalizedHash) {
179188
179394
  db.prepare("UPDATE memories SET classified_at = NULL WHERE id = ?").run(id);
179189
179395
  }
179190
179396
  if (hasMuralCueColumns(db)) {
179191
- db.prepare("UPDATE memories SET mural_cue = NULL, mural_cue_hash = NULL, mural_cue_at = NULL WHERE id = ?").run(id);
179397
+ const rejectionReset = hasMuralCueRejectionCountColumn(db) ? ", mural_cue_rejection_count = 0" : "";
179398
+ db.prepare(`UPDATE memories SET mural_cue = NULL, mural_cue_hash = NULL, mural_cue_at = NULL${rejectionReset} WHERE id = ?`).run(id);
179192
179399
  }
179193
179400
  let stmt = deleteEmbeddingOnContentUpdateStatements.get(db);
179194
179401
  if (!stmt) {
@@ -179523,7 +179730,7 @@ function getMemoryVerifications(db, memoryIds) {
179523
179730
  }
179524
179731
  // ../plugin/src/features/magic-context/memory/verification-paths.ts
179525
179732
  import { execFile } from "node:child_process";
179526
- import { existsSync as existsSync8, realpathSync as realpathSync2, statSync as statSync5 } from "node:fs";
179733
+ import { existsSync as existsSync8, realpathSync as realpathSync2, statSync as statSync6 } from "node:fs";
179527
179734
  import path3 from "node:path";
179528
179735
  import { promisify } from "node:util";
179529
179736
  var execFileAsync = promisify(execFile);
@@ -179665,7 +179872,7 @@ async function normalizeVerificationFiles(args) {
179665
179872
  }
179666
179873
  if (existsSync8(candidate)) {
179667
179874
  try {
179668
- if (statSync5(candidate).isDirectory()) {
179875
+ if (statSync6(candidate).isDirectory()) {
179669
179876
  warnings.push(`Skipped verification path "${value}" because it is a directory.`);
179670
179877
  continue;
179671
179878
  }
@@ -184112,4 +184319,4 @@ function registerMagicContextTools(pi, opts) {
184112
184319
  }
184113
184320
  }
184114
184321
 
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 };
184322
+ 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, recordMuralCueRejection, 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 };