@cortexkit/pi-magic-context 0.33.1 → 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.
@@ -7852,9 +7852,13 @@ var require_src2 = __commonJS((exports, module) => {
7852
7852
  });
7853
7853
 
7854
7854
  // ../plugin/src/config/agent-disable.ts
7855
+ var COMPACTION_ENABLED_PATH = `compaction${"."}enabled`;
7855
7856
  function isDreamerRunnable(config) {
7856
7857
  return !!config.dreamer && config.dreamer.disable !== true;
7857
7858
  }
7859
+ function isCompactionEnabled(config) {
7860
+ return config.compaction?.enabled !== false;
7861
+ }
7858
7862
  function clonePlainObject(value) {
7859
7863
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
7860
7864
  return;
@@ -8296,6 +8300,7 @@ var dubiousOwnershipLoggedDirectories = new Set;
8296
8300
  var dubiousOwnershipWarnedDirectories = new Set;
8297
8301
  var transientGitIdentityReuseLoggedDirectories = new Set;
8298
8302
  var execFileSyncForIdentity = execFileSync;
8303
+ var userHomeDirectoryForIdentity = () => homedir2();
8299
8304
  var nowMs = () => Date.now();
8300
8305
 
8301
8306
  class ProjectIdentityError extends Error {
@@ -8491,9 +8496,12 @@ function recordDubiousOwnershipFallback(canonical) {
8491
8496
  dubiousOwnershipLoggedDirectories.add(canonical);
8492
8497
  log(`[magic-context] ${formatDubiousOwnershipWarning(canonical)}`);
8493
8498
  }
8499
+ function canonicalUserHomeDirectory() {
8500
+ return realpathSync.native(userHomeDirectoryForIdentity());
8501
+ }
8494
8502
  function isUserHomeDirectory(directory) {
8495
8503
  try {
8496
- return realpathSync.native(path.resolve(directory)) === realpathSync.native(homedir2());
8504
+ return realpathSync.native(path.resolve(directory)) === canonicalUserHomeDirectory();
8497
8505
  } catch {
8498
8506
  return false;
8499
8507
  }
@@ -8562,22 +8570,52 @@ function hasGitDir(canonical) {
8562
8570
  return false;
8563
8571
  }
8564
8572
  }
8565
- function hasGitDirInAncestorChain(startDirectory) {
8573
+ function gitRootInAncestorChain(startDirectory) {
8566
8574
  let current = startDirectory;
8567
8575
  while (true) {
8568
8576
  if (existsSync2(path.join(current, ".git"))) {
8569
- return true;
8577
+ try {
8578
+ return realpathSync.native(current);
8579
+ } catch {
8580
+ return path.resolve(current);
8581
+ }
8570
8582
  }
8571
8583
  const parent = path.dirname(current);
8572
8584
  if (parent === current) {
8573
- return false;
8585
+ return null;
8574
8586
  }
8575
8587
  current = parent;
8576
8588
  }
8577
8589
  }
8578
- function resolveProjectIdentityForSession(directory) {
8579
- if (isUserHomeDirectory(directory))
8580
- return;
8590
+ function hasGitDirInAncestorChain(startDirectory) {
8591
+ return gitRootInAncestorChain(startDirectory) !== null;
8592
+ }
8593
+ function gitRootDirectory(canonical) {
8594
+ const direct = gitRootInAncestorChain(canonical);
8595
+ if (direct)
8596
+ return direct;
8597
+ try {
8598
+ const realCanonical = realpathSync.native(canonical);
8599
+ return realCanonical === canonical ? null : gitRootInAncestorChain(realCanonical);
8600
+ } catch {
8601
+ return null;
8602
+ }
8603
+ }
8604
+ function resolveProjectIdentityForSession(directory, allowHomeProject = false) {
8605
+ const canonicalHome = canonicalUserHomeDirectory();
8606
+ const canonicalDirectory = (() => {
8607
+ try {
8608
+ return realpathSync.native(path.resolve(directory));
8609
+ } catch {
8610
+ return path.resolve(directory);
8611
+ }
8612
+ })();
8613
+ const inheritsHomeRepository = gitRootDirectory(canonicalDirectory) === canonicalHome;
8614
+ if (canonicalDirectory === canonicalHome || inheritsHomeRepository) {
8615
+ if (!allowHomeProject)
8616
+ return;
8617
+ return directoryFallback(canonicalHome);
8618
+ }
8581
8619
  return resolveProjectIdentityOrFallback(directory);
8582
8620
  }
8583
8621
  function normalizeStoredProjectPath(rawOrStored) {
@@ -8610,9 +8648,28 @@ function scheduleAfterBootQuiet(task, additionalDelayMs = 0) {
8610
8648
  return timer;
8611
8649
  }
8612
8650
 
8651
+ // ../plugin/src/shared/storage-permissions.ts
8652
+ var enforcePrivateStoragePermissions = true;
8653
+ function setStoragePrivatePermissionEnforcement(enforce) {
8654
+ enforcePrivateStoragePermissions = enforce;
8655
+ }
8656
+ function shouldEnforcePrivateStoragePermissions() {
8657
+ return enforcePrivateStoragePermissions;
8658
+ }
8659
+
8613
8660
  // ../plugin/src/features/magic-context/storage-db.ts
8614
- import { chmodSync, copyFileSync, cpSync, existsSync as existsSync4, mkdirSync as mkdirSync2, mkdtempSync } from "node:fs";
8615
- import { dirname as dirname2, join as join3 } from "node:path";
8661
+ import {
8662
+ chmodSync,
8663
+ copyFileSync,
8664
+ cpSync,
8665
+ existsSync as existsSync4,
8666
+ mkdirSync as mkdirSync2,
8667
+ mkdtempSync,
8668
+ readdirSync,
8669
+ readFileSync as readFileSync3,
8670
+ unlinkSync as unlinkSync2
8671
+ } from "node:fs";
8672
+ import { basename as basename2, dirname as dirname2, join as join3 } from "node:path";
8616
8673
 
8617
8674
  // ../plugin/src/shared/error-message.ts
8618
8675
  function getErrorMessage(error) {
@@ -8690,6 +8747,129 @@ function safeString(value) {
8690
8747
  }
8691
8748
  }
8692
8749
 
8750
+ // ../plugin/src/shared/rpc-utils.ts
8751
+ import { execFileSync as execFileSync2 } from "node:child_process";
8752
+ import { readFileSync as readFileSync2 } from "node:fs";
8753
+ function isPidAlive(pid) {
8754
+ if (!Number.isInteger(pid) || pid <= 0)
8755
+ return false;
8756
+ try {
8757
+ process.kill(pid, 0);
8758
+ return true;
8759
+ } catch (err) {
8760
+ return err.code === "EPERM";
8761
+ }
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
+ }
8841
+ function parseRpcPortFile(content, fallbackPid = 0) {
8842
+ const trimmed = content.trim();
8843
+ if (!trimmed)
8844
+ return null;
8845
+ if (trimmed.startsWith("{")) {
8846
+ try {
8847
+ const parsed = JSON.parse(trimmed);
8848
+ const port2 = Number(parsed.port);
8849
+ const pid = Number(parsed.pid);
8850
+ const startedAt = Number(parsed.started_at);
8851
+ if (!isValidPort(port2) || !Number.isInteger(pid) || pid <= 0)
8852
+ return null;
8853
+ return {
8854
+ port: port2,
8855
+ pid,
8856
+ started_at: Number.isFinite(startedAt) ? startedAt : 0,
8857
+ token: typeof parsed.token === "string" ? parsed.token : undefined,
8858
+ instance_id: typeof parsed.instance_id === "string" ? parsed.instance_id : undefined
8859
+ };
8860
+ } catch {
8861
+ return null;
8862
+ }
8863
+ }
8864
+ const port = Number.parseInt(trimmed, 10);
8865
+ if (!isValidPort(port))
8866
+ return null;
8867
+ return { port, pid: fallbackPid, started_at: 0 };
8868
+ }
8869
+ function isValidPort(port) {
8870
+ return Number.isInteger(port) && port > 0 && port <= 65535;
8871
+ }
8872
+
8693
8873
  // ../plugin/src/shared/sqlite.ts
8694
8874
  var isBun = typeof process !== "undefined" && typeof process.versions?.bun === "string";
8695
8875
  var bunSpec = "bun:" + "sqlite";
@@ -9423,6 +9603,7 @@ function bumpEpochsForWorkspaceMemberSet(db, identities, now = Date.now()) {
9423
9603
  }
9424
9604
 
9425
9605
  // ../plugin/src/features/magic-context/migrations.ts
9606
+ var FORK_MIGRATION_VERSION_FLOOR = 1e4;
9426
9607
  var MIGRATION_LOCK_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000];
9427
9608
 
9428
9609
  class MigrationLockBusyError extends Error {
@@ -11433,6 +11614,33 @@ var MIGRATIONS = [
11433
11614
  up(db) {
11434
11615
  installLatestAuthorityTriggers(db);
11435
11616
  }
11617
+ },
11618
+ {
11619
+ version: 72,
11620
+ description: "add per-session compaction mode record column (issue #266)",
11621
+ up(db) {
11622
+ if (tableExists2(db, "session_meta")) {
11623
+ ensureColumn(db, "session_meta", "compaction_mode_record", "TEXT");
11624
+ }
11625
+ }
11626
+ },
11627
+ {
11628
+ version: 73,
11629
+ description: "persist the last successful todowrite permission verdict",
11630
+ up(db) {
11631
+ if (tableExists2(db, "session_meta")) {
11632
+ ensureColumn(db, "session_meta", "todo_permission_denied", "INTEGER NOT NULL DEFAULT 2");
11633
+ }
11634
+ }
11635
+ },
11636
+ {
11637
+ version: 74,
11638
+ description: "persist detected context-limit provenance",
11639
+ up(db) {
11640
+ if (tableExists2(db, "session_meta")) {
11641
+ ensureColumn(db, "session_meta", "detected_context_limit_provenance", "TEXT NOT NULL DEFAULT 'unknown'");
11642
+ }
11643
+ }
11436
11644
  }
11437
11645
  ];
11438
11646
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -11446,9 +11654,12 @@ function ensureMigrationsTable(db) {
11446
11654
  `);
11447
11655
  }
11448
11656
  function getCurrentVersion(db) {
11449
- 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);
11450
11658
  return row?.version ?? 0;
11451
11659
  }
11660
+ function isMigrationApplied(db, version) {
11661
+ return db.prepare("SELECT 1 FROM schema_migrations WHERE version = ?").get(version) != null;
11662
+ }
11452
11663
  function isSiblingMigrationConflict(db, error, version) {
11453
11664
  if (!(error instanceof Error))
11454
11665
  return false;
@@ -11477,12 +11688,12 @@ function runMigrations(db) {
11477
11688
  try {
11478
11689
  const applied = db.transaction(() => {
11479
11690
  currentVersion = getCurrentVersion(db);
11480
- migration = MIGRATIONS.find((candidate) => candidate.version > currentVersion);
11691
+ migration = MIGRATIONS.find((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version));
11481
11692
  if (!migration)
11482
11693
  return false;
11483
11694
  if (!loggedPlan) {
11484
- const pendingCount = MIGRATIONS.filter((candidate) => candidate.version > currentVersion).length;
11485
- 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)`);
11486
11697
  loggedPlan = true;
11487
11698
  }
11488
11699
  migration.up(db);
@@ -11519,7 +11730,7 @@ function runMigrations(db) {
11519
11730
  }
11520
11731
  }
11521
11732
  if (loggedPlan) {
11522
- log(`[migrations] schema version now: ${MIGRATIONS[MIGRATIONS.length - 1].version}`);
11733
+ log(`[migrations] upstream migration lane now: ${MIGRATIONS[MIGRATIONS.length - 1].version}`);
11523
11734
  }
11524
11735
  }
11525
11736
  async function runMigrationsWithRetry(db, options = {}) {
@@ -144458,30 +144669,40 @@ var persistenceByDatabase = new WeakMap;
144458
144669
  var persistenceErrorByDatabase = new WeakMap;
144459
144670
  var pathByDatabase = new WeakMap;
144460
144671
  var lastSchemaFenceRejection = null;
144672
+ var lastMigrationOnOpenRefusal = null;
144461
144673
  function getSchemaFenceRejection() {
144462
144674
  return lastSchemaFenceRejection;
144463
144675
  }
144464
- var LATEST_SUPPORTED_VERSION = 71;
144676
+ function getMigrationOnOpenRefusal() {
144677
+ return lastMigrationOnOpenRefusal;
144678
+ }
144679
+ var LATEST_SUPPORTED_VERSION = 74;
144465
144680
  var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
144681
+ var defaultStoragePermissionFs = { chmodSync, mkdirSync: mkdirSync2 };
144682
+ var storagePermissionFs = defaultStoragePermissionFs;
144466
144683
  function ensureSecureStorageDir(dir) {
144467
- mkdirSync2(dir, { recursive: true, mode: 448 });
144684
+ if (!shouldEnforcePrivateStoragePermissions()) {
144685
+ storagePermissionFs.mkdirSync(dir, { recursive: true });
144686
+ return;
144687
+ }
144688
+ storagePermissionFs.mkdirSync(dir, { recursive: true, mode: 448 });
144468
144689
  if (!PERMISSIONS_ENFORCEABLE)
144469
144690
  return;
144470
144691
  try {
144471
- chmodSync(dir, 448);
144692
+ storagePermissionFs.chmodSync(dir, 448);
144472
144693
  } catch (error) {
144473
144694
  log(`[magic-context] could not restrict storage dir permissions on ${dir}: ${getErrorMessage(error)}`);
144474
144695
  }
144475
144696
  }
144476
144697
  function restrictDatabaseFilePermissions(dbPath) {
144477
- if (!PERMISSIONS_ENFORCEABLE)
144698
+ if (!PERMISSIONS_ENFORCEABLE || !shouldEnforcePrivateStoragePermissions())
144478
144699
  return;
144479
144700
  for (const suffix of ["", "-wal", "-shm"]) {
144480
144701
  const file = `${dbPath}${suffix}`;
144481
144702
  if (!existsSync4(file))
144482
144703
  continue;
144483
144704
  try {
144484
- chmodSync(file, 384);
144705
+ storagePermissionFs.chmodSync(file, 384);
144485
144706
  } catch (error) {
144486
144707
  log(`[magic-context] could not restrict DB file permissions on ${file}: ${getErrorMessage(error)}`);
144487
144708
  }
@@ -144548,9 +144769,12 @@ function getPersistedSchemaVersion(db) {
144548
144769
  if (!hasMigrationsTable) {
144549
144770
  return 0;
144550
144771
  }
144551
- 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);
144552
144773
  return row?.version ?? 0;
144553
144774
  }
144775
+ function formatSchemaFenceBootLog(persistedVersion, supportedVersion) {
144776
+ return `[magic-context] upstream migration lane at boot: database=v${persistedVersion}, supported_fence=v${supportedVersion}`;
144777
+ }
144554
144778
  function getRuntimeLatestSupportedVersion(options) {
144555
144779
  if (options?.latestSupportedVersion !== undefined) {
144556
144780
  return options.latestSupportedVersion;
@@ -144567,10 +144791,107 @@ function getRuntimeLatestSupportedVersion(options) {
144567
144791
  function enforceSchemaFence(db, dbPath, latestSupportedVersion) {
144568
144792
  const persistedVersion = getPersistedSchemaVersion(db);
144569
144793
  if (persistedVersion <= latestSupportedVersion) {
144794
+ lastSchemaFenceRejection = null;
144570
144795
  return true;
144571
144796
  }
144572
144797
  lastSchemaFenceRejection = { persistedVersion, supportedVersion: latestSupportedVersion };
144573
- 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.`);
144799
+ return false;
144800
+ }
144801
+ function unreadableDiscovery(path2) {
144802
+ return {
144803
+ state: "unreadable",
144804
+ serverPids: [],
144805
+ staleFiles: [],
144806
+ unreadableFile: path2
144807
+ };
144808
+ }
144809
+ function inspectRpcServerDiscovery(storageDir) {
144810
+ const rpcRoot = join3(storageDir, "rpc");
144811
+ let projectEntries;
144812
+ try {
144813
+ projectEntries = readdirSync(rpcRoot, { withFileTypes: true });
144814
+ } catch (error) {
144815
+ if (error.code === "ENOENT") {
144816
+ return { state: "absent", serverPids: [], staleFiles: [] };
144817
+ }
144818
+ return unreadableDiscovery(rpcRoot);
144819
+ }
144820
+ const portFiles = [];
144821
+ for (const projectEntry of projectEntries) {
144822
+ if (!projectEntry.isDirectory())
144823
+ continue;
144824
+ const projectDir = join3(rpcRoot, projectEntry.name);
144825
+ let entries;
144826
+ try {
144827
+ entries = readdirSync(projectDir);
144828
+ } catch {
144829
+ return unreadableDiscovery(projectDir);
144830
+ }
144831
+ for (const entry of entries) {
144832
+ if (entry === "port" || entry.startsWith("port-") && entry.endsWith(".json")) {
144833
+ portFiles.push(join3(projectDir, entry));
144834
+ }
144835
+ }
144836
+ }
144837
+ if (portFiles.length === 0) {
144838
+ return { state: "absent", serverPids: [], staleFiles: [] };
144839
+ }
144840
+ const pids = new Set;
144841
+ const staleFiles = [];
144842
+ for (const portFile of portFiles) {
144843
+ let raw;
144844
+ try {
144845
+ raw = readFileSync3(portFile, "utf8");
144846
+ } catch {
144847
+ return unreadableDiscovery(portFile);
144848
+ }
144849
+ const filename = basename2(portFile);
144850
+ const pidFromName = /^port-(\d+)/.exec(filename)?.[1];
144851
+ const record = parseRpcPortFile(raw, pidFromName ? Number(pidFromName) : 0);
144852
+ if (!record || !Number.isInteger(record.pid) || record.pid <= 0) {
144853
+ return unreadableDiscovery(portFile);
144854
+ }
144855
+ if (isPidAlive(record.pid) && isPidIdentityPlausible(record))
144856
+ pids.add(record.pid);
144857
+ else
144858
+ staleFiles.push(portFile);
144859
+ }
144860
+ for (const staleFile of staleFiles) {
144861
+ try {
144862
+ unlinkSync2(staleFile);
144863
+ } catch {
144864
+ return unreadableDiscovery(staleFile);
144865
+ }
144866
+ }
144867
+ const serverPids = [...pids].sort((a, b) => a - b);
144868
+ if (serverPids.length > 0) {
144869
+ return { state: "live", serverPids, staleFiles };
144870
+ }
144871
+ return { state: "stale", serverPids: [], staleFiles };
144872
+ }
144873
+ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion) {
144874
+ const persistedVersion = getPersistedSchemaVersion(db);
144875
+ if (persistedVersion >= latestSupportedVersion) {
144876
+ lastMigrationOnOpenRefusal = null;
144877
+ return true;
144878
+ }
144879
+ const discovery = inspectRpcServerDiscovery(dbDir);
144880
+ if (discovery.state === "absent" || discovery.state === "stale") {
144881
+ lastMigrationOnOpenRefusal = null;
144882
+ return true;
144883
+ }
144884
+ lastMigrationOnOpenRefusal = {
144885
+ persistedVersion,
144886
+ supportedVersion: latestSupportedVersion,
144887
+ serverPids: discovery.serverPids,
144888
+ ...discovery.unreadableFile ? { unreadableFile: discovery.unreadableFile } : {}
144889
+ };
144890
+ if (discovery.state === "unreadable") {
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.`);
144892
+ } else {
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.`);
144894
+ }
144574
144895
  return false;
144575
144896
  }
144576
144897
  var sqlitePragmaConfig = {
@@ -144617,6 +144938,9 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
144617
144938
  pathByDatabase.set(db, dbPath);
144618
144939
  persistenceByDatabase.set(db, true);
144619
144940
  persistenceErrorByDatabase.delete(db);
144941
+ if (!explicitDbPath) {
144942
+ log(formatSchemaFenceBootLog(getPersistedSchemaVersion(db), latestSupportedVersion));
144943
+ }
144620
144944
  return db;
144621
144945
  }
144622
144946
  function initializeDatabase(db) {
@@ -145217,12 +145541,14 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
145217
145541
  note_nudge_anchors TEXT NOT NULL DEFAULT '[]',
145218
145542
  auto_search_hint_decisions TEXT NOT NULL DEFAULT '[]',
145219
145543
  last_todo_state TEXT DEFAULT '',
145544
+ todo_permission_denied INTEGER NOT NULL DEFAULT 2,
145220
145545
  todo_synthetic_call_id TEXT DEFAULT '',
145221
145546
  todo_synthetic_anchor_message_id TEXT DEFAULT '',
145222
145547
  todo_synthetic_state_json TEXT DEFAULT '',
145223
145548
  is_subagent INTEGER DEFAULT 0,
145224
145549
  last_context_percentage REAL DEFAULT 0,
145225
145550
  last_input_tokens INTEGER DEFAULT 0,
145551
+ detected_context_limit_provenance TEXT NOT NULL DEFAULT 'unknown',
145226
145552
  observed_safe_input_tokens INTEGER NOT NULL DEFAULT 0,
145227
145553
  cache_alert_sent INTEGER NOT NULL DEFAULT 0,
145228
145554
  times_execute_threshold_reached INTEGER DEFAULT 0,
@@ -145277,6 +145603,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
145277
145603
  emergency_drain_active INTEGER NOT NULL DEFAULT 0,
145278
145604
  historian_drain_failure_at INTEGER NOT NULL DEFAULT 0,
145279
145605
  wrapup_in_progress_state TEXT,
145606
+ compaction_mode_record TEXT,
145280
145607
  cached_m0_materialized_at INTEGER,
145281
145608
  cached_m0_session_facts_version INTEGER,
145282
145609
  cached_m0_upgrade_state TEXT,
@@ -145476,6 +145803,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
145476
145803
  ensureColumn(db, "session_meta", "note_nudge_anchors", "TEXT NOT NULL DEFAULT '[]'");
145477
145804
  ensureColumn(db, "session_meta", "auto_search_hint_decisions", "TEXT NOT NULL DEFAULT '[]'");
145478
145805
  ensureColumn(db, "session_meta", "last_todo_state", "TEXT DEFAULT ''");
145806
+ ensureColumn(db, "session_meta", "todo_permission_denied", "INTEGER NOT NULL DEFAULT 2");
145479
145807
  ensureColumn(db, "session_meta", "todo_synthetic_call_id", "TEXT DEFAULT ''");
145480
145808
  ensureColumn(db, "session_meta", "todo_synthetic_anchor_message_id", "TEXT DEFAULT ''");
145481
145809
  ensureColumn(db, "session_meta", "todo_synthetic_state_json", "TEXT DEFAULT ''");
@@ -145532,6 +145860,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
145532
145860
  ensureColumn(db, "session_meta", "recomp_partial_range_end", "INTEGER DEFAULT 0");
145533
145861
  ensureColumn(db, "session_meta", "detected_context_limit", "INTEGER DEFAULT 0");
145534
145862
  ensureColumn(db, "session_meta", "detected_context_limit_model_key", "TEXT");
145863
+ ensureColumn(db, "session_meta", "detected_context_limit_provenance", "TEXT NOT NULL DEFAULT 'unknown'");
145535
145864
  ensureColumn(db, "session_meta", "needs_emergency_recovery", "INTEGER DEFAULT 0");
145536
145865
  ensureColumn(db, "session_meta", "emergency_recovery_origin", "TEXT DEFAULT ''");
145537
145866
  ensureColumn(db, "session_meta", "pending_compaction_marker_state", "TEXT");
@@ -145582,6 +145911,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
145582
145911
  ensureColumn(db, "session_meta", "emergency_drain_active", "INTEGER NOT NULL DEFAULT 0");
145583
145912
  ensureColumn(db, "session_meta", "historian_drain_failure_at", "INTEGER NOT NULL DEFAULT 0");
145584
145913
  ensureColumn(db, "session_meta", "wrapup_in_progress_state", "TEXT");
145914
+ ensureColumn(db, "session_meta", "compaction_mode_record", "TEXT");
145585
145915
  ensureColumn(db, "session_meta", "cached_m0_materialized_at", "INTEGER");
145586
145916
  ensureColumn(db, "session_meta", "cached_m0_session_facts_version", "INTEGER");
145587
145917
  ensureColumn(db, "session_meta", "cached_m0_upgrade_state", "TEXT");
@@ -145721,6 +146051,8 @@ function openDatabase(dbPathOrOptions) {
145721
146051
  const explicitDbPath = options?.dbPath !== undefined;
145722
146052
  const { dbDir, dbPath } = resolveDatabasePath(options?.dbPath);
145723
146053
  const latestSupportedVersion = getRuntimeLatestSupportedVersion(options);
146054
+ lastSchemaFenceRejection = null;
146055
+ lastMigrationOnOpenRefusal = null;
145724
146056
  const existing = databases.get(dbPath);
145725
146057
  if (existing) {
145726
146058
  if (!enforceSchemaFence(existing, dbPath, latestSupportedVersion)) {
@@ -145742,6 +146074,10 @@ function openDatabase(dbPathOrOptions) {
145742
146074
  closeQuietly(db);
145743
146075
  return null;
145744
146076
  }
146077
+ if (!enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)) {
146078
+ closeQuietly(db);
146079
+ return null;
146080
+ }
145745
146081
  initializeDatabase(db);
145746
146082
  runMigrations(db);
145747
146083
  ensureContextStoreUuid(db);
@@ -145757,6 +146093,8 @@ async function openDatabaseAsync(dbPathOrOptions) {
145757
146093
  const explicitDbPath = options?.dbPath !== undefined;
145758
146094
  const { dbDir, dbPath } = resolveDatabasePath(options?.dbPath);
145759
146095
  const latestSupportedVersion = getRuntimeLatestSupportedVersion(options);
146096
+ lastSchemaFenceRejection = null;
146097
+ lastMigrationOnOpenRefusal = null;
145760
146098
  const existing = databases.get(dbPath);
145761
146099
  if (existing) {
145762
146100
  if (!enforceSchemaFence(existing, dbPath, latestSupportedVersion))
@@ -145780,6 +146118,10 @@ async function openDatabaseAsync(dbPathOrOptions) {
145780
146118
  closeQuietly(db);
145781
146119
  return null;
145782
146120
  }
146121
+ if (!enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)) {
146122
+ closeQuietly(db);
146123
+ return null;
146124
+ }
145783
146125
  initializeDatabase(db);
145784
146126
  await runMigrationsWithRetry(db);
145785
146127
  ensureContextStoreUuid(db);
@@ -145801,6 +146143,24 @@ async function openDatabaseAsync(dbPathOrOptions) {
145801
146143
  }
145802
146144
  }
145803
146145
 
146146
+ // ../plugin/src/shared/context-limit-provenance.ts
146147
+ function normalizeContextLimitProvenance(value) {
146148
+ if (value === "prompt_only" || value === "combined")
146149
+ return value;
146150
+ return "unknown";
146151
+ }
146152
+
146153
+ // ../plugin/src/shared/escalation-bands.ts
146154
+ var MAX_EXECUTE_THRESHOLD = 90;
146155
+ var ABSOLUTE_EMERGENCY_PERCENTAGE = 95;
146156
+ function escalationBands(effectiveThresholdPercentage) {
146157
+ const threshold = Number.isFinite(effectiveThresholdPercentage) ? Math.min(effectiveThresholdPercentage, MAX_EXECUTE_THRESHOLD) : 65;
146158
+ return {
146159
+ forceMaterializationPercentage: Math.max(85, threshold + 2),
146160
+ emergencyPercentage: ABSOLUTE_EMERGENCY_PERCENTAGE
146161
+ };
146162
+ }
146163
+
145804
146164
  // ../plugin/src/features/magic-context/storage-meta-shared.ts
145805
146165
  import { Buffer as Buffer2 } from "node:buffer";
145806
146166
  var SESSION_META_SELECT_COLUMNS = [
@@ -146440,6 +146800,45 @@ function releaseWrapupInProgress(db, sessionId, holderId) {
146440
146800
  }
146441
146801
  }
146442
146802
  }
146803
+ var COMPACTION_MODE_RECORD_VALUES = new Set([
146804
+ "on",
146805
+ "off",
146806
+ "on_notice_pending",
146807
+ "off_notice_pending",
146808
+ "off_cleanup_pending"
146809
+ ]);
146810
+ function normalizeCompactionModeRecord(value) {
146811
+ if (value === null || value === undefined)
146812
+ return null;
146813
+ if (typeof value === "string" && COMPACTION_MODE_RECORD_VALUES.has(value)) {
146814
+ return value;
146815
+ }
146816
+ return null;
146817
+ }
146818
+ function resolveCompactionModeRecord(record) {
146819
+ switch (record) {
146820
+ case "on":
146821
+ case "on_notice_pending":
146822
+ return "on";
146823
+ case "off":
146824
+ case "off_notice_pending":
146825
+ case "off_cleanup_pending":
146826
+ return "off";
146827
+ default:
146828
+ return null;
146829
+ }
146830
+ }
146831
+ function getCompactionModeRecord(db, sessionId) {
146832
+ const row = db.prepare("SELECT compaction_mode_record FROM session_meta WHERE session_id = ?").get(sessionId);
146833
+ return normalizeCompactionModeRecord(row?.compaction_mode_record);
146834
+ }
146835
+ function setCompactionModeRecord(db, sessionId, value) {
146836
+ if (value !== null && !COMPACTION_MODE_RECORD_VALUES.has(value)) {
146837
+ throw new Error(`Invalid compaction_mode_record value: ${String(value)} (expected a supported compaction mode record or null)`);
146838
+ }
146839
+ ensureSessionMetaRow(db, sessionId);
146840
+ db.prepare("UPDATE session_meta SET compaction_mode_record = ? WHERE session_id = ?").run(value, sessionId);
146841
+ }
146443
146842
  function protectedTailWindowBudget(usagePercentage, usable, perRunCap) {
146444
146843
  if (usagePercentage >= 95)
146445
146844
  return Math.min(1e6, Math.max(4 * perRunCap, Math.round(0.5 * usable)));
@@ -146447,7 +146846,6 @@ function protectedTailWindowBudget(usagePercentage, usable, perRunCap) {
146447
146846
  return Math.min(750000, Math.max(3 * perRunCap, Math.round(0.35 * usable)));
146448
146847
  return Math.min(500000, Math.max(perRunCap, Math.round(0.2 * usable)));
146449
146848
  }
146450
- var EMERGENCY_DRAIN_ENTER_PERCENTAGE = 95;
146451
146849
  var EMERGENCY_DRAIN_EXIT_MARGIN = 10;
146452
146850
  var EMERGENCY_DRAIN_FALLBACK_EXIT_PERCENTAGE = 55;
146453
146851
  var EMERGENCY_DRAIN_FAILURE_BACKOFF_MS = 60000;
@@ -146482,7 +146880,8 @@ function reserveProtectedTailDrainTokens(args) {
146482
146880
  }
146483
146881
  const exitThreshold = emergencyDrainExitThreshold(args.executeThresholdPercentage);
146484
146882
  let latchActiveSince = meta.emergencyDrainActive;
146485
- if (args.usagePercentage >= EMERGENCY_DRAIN_ENTER_PERCENTAGE) {
146883
+ const { forceMaterializationPercentage } = escalationBands(args.executeThresholdPercentage);
146884
+ if (args.usagePercentage >= forceMaterializationPercentage) {
146486
146885
  if (latchActiveSince <= 0)
146487
146886
  latchActiveSince = now;
146488
146887
  } else if (latchActiveSince > 0) {
@@ -146851,17 +147250,19 @@ function normalizeEmergencyRecoveryOrigin(value) {
146851
147250
  return value === "provider_overflow" || value === "proactive_model_shrink" ? value : null;
146852
147251
  }
146853
147252
  function getOverflowState(db, sessionId, modelKey) {
146854
- const result = db.prepare("SELECT detected_context_limit, detected_context_limit_model_key, needs_emergency_recovery, emergency_recovery_origin FROM session_meta WHERE session_id = ?").get(sessionId);
147253
+ const result = db.prepare("SELECT detected_context_limit, detected_context_limit_model_key, detected_context_limit_provenance, needs_emergency_recovery, emergency_recovery_origin FROM session_meta WHERE session_id = ?").get(sessionId);
146855
147254
  if (!result) {
146856
147255
  return {
146857
147256
  detectedContextLimit: 0,
146858
147257
  detectedContextLimitModelKey: null,
147258
+ detectedContextLimitProvenance: "unknown",
146859
147259
  needsEmergencyRecovery: false,
146860
147260
  emergencyRecoveryOrigin: null
146861
147261
  };
146862
147262
  }
146863
147263
  const storedModelKey = normalizeDetectedLimitModelKey(result.detected_context_limit_model_key);
146864
147264
  const requestedModelKey = normalizeDetectedLimitModelKey(modelKey);
147265
+ const provenance = normalizeContextLimitProvenance(result.detected_context_limit_provenance);
146865
147266
  const limit = typeof result.detected_context_limit === "number" && result.detected_context_limit > 0 ? result.detected_context_limit : 0;
146866
147267
  const modelMatches = limit > 0 && requestedModelKey && storedModelKey ? requestedModelKey === storedModelKey : true;
146867
147268
  const needs = typeof result.needs_emergency_recovery === "number" && result.needs_emergency_recovery > 0;
@@ -146870,11 +147271,12 @@ function getOverflowState(db, sessionId, modelKey) {
146870
147271
  return {
146871
147272
  detectedContextLimit: modelMatches ? limit : 0,
146872
147273
  detectedContextLimitModelKey: storedModelKey,
147274
+ detectedContextLimitProvenance: provenance,
146873
147275
  needsEmergencyRecovery: needs,
146874
147276
  emergencyRecoveryOrigin: recoveryOrigin
146875
147277
  };
146876
147278
  }
146877
- function recordOverflowDetected(db, sessionId, reportedLimit, modelKey, origin = "provider_overflow") {
147279
+ function recordOverflowDetected(db, sessionId, reportedLimit, modelKey, origin = "provider_overflow", provenance = "unknown") {
146878
147280
  emergencyRecoveryArmedSessions.add(sessionId);
146879
147281
  db.transaction(() => {
146880
147282
  ensureSessionMetaRow(db, sessionId);
@@ -146883,7 +147285,7 @@ function recordOverflowDetected(db, sessionId, reportedLimit, modelKey, origin =
146883
147285
  providerOverflowReconfirmedSessions.add(sessionId);
146884
147286
  }
146885
147287
  if (typeof reportedLimit === "number" && reportedLimit > 0) {
146886
- db.prepare("UPDATE session_meta SET detected_context_limit = ?, detected_context_limit_model_key = ?, needs_emergency_recovery = 1, emergency_recovery_origin = ?, observed_safe_input_tokens = 0, cache_alert_sent = 0 WHERE session_id = ?").run(reportedLimit, normalizeDetectedLimitModelKey(modelKey), origin, sessionId);
147288
+ db.prepare("UPDATE session_meta SET detected_context_limit = ?, detected_context_limit_model_key = ?, detected_context_limit_provenance = ?, needs_emergency_recovery = 1, emergency_recovery_origin = ?, observed_safe_input_tokens = 0, cache_alert_sent = 0 WHERE session_id = ?").run(reportedLimit, normalizeDetectedLimitModelKey(modelKey), normalizeContextLimitProvenance(provenance), origin, sessionId);
146887
147289
  } else {
146888
147290
  db.prepare("UPDATE session_meta SET needs_emergency_recovery = 1, emergency_recovery_origin = ?, observed_safe_input_tokens = 0, cache_alert_sent = 0 WHERE session_id = ?").run(origin, sessionId);
146889
147291
  }
@@ -146904,7 +147306,7 @@ function clearEmergencyRecovery(db, sessionId) {
146904
147306
  function clearDetectedContextLimit(db, sessionId) {
146905
147307
  db.transaction(() => {
146906
147308
  ensureSessionMetaRow(db, sessionId);
146907
- db.prepare("UPDATE session_meta SET detected_context_limit = 0, detected_context_limit_model_key = NULL WHERE session_id = ?").run(sessionId);
147309
+ db.prepare("UPDATE session_meta SET detected_context_limit = 0, detected_context_limit_model_key = NULL, detected_context_limit_provenance = 'unknown' WHERE session_id = ?").run(sessionId);
146908
147310
  })();
146909
147311
  }
146910
147312
  function getPersistedCompactionMarkerState(db, sessionId) {
@@ -147169,6 +147571,62 @@ function getRawSessionMessageCountFromDb(db, sessionId) {
147169
147571
  AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')`).get(sessionId);
147170
147572
  return typeof row?.count === "number" ? row.count : 0;
147171
147573
  }
147574
+ function isMidTurn(_deps, sessionId) {
147575
+ try {
147576
+ return withReadOnlySessionDb((db) => isMidTurnFromOpenCodeDb(db, sessionId));
147577
+ } catch (error) {
147578
+ log("[magic-context] failed to inspect OpenCode mid-turn state:", error);
147579
+ return false;
147580
+ }
147581
+ }
147582
+ function isMidTurnFromOpenCodeDb(db, sessionId) {
147583
+ const latestAssistant = db.prepare(`SELECT id,
147584
+ json_extract(data, '$.finish') as finish,
147585
+ time_created as timeCreated
147586
+ FROM message
147587
+ WHERE session_id = ?
147588
+ AND json_extract(data, '$.role') = 'assistant'
147589
+ ORDER BY time_created DESC
147590
+ LIMIT 1`).get(sessionId);
147591
+ if (typeof latestAssistant?.id !== "string")
147592
+ return false;
147593
+ if (hasNewerRealUserMessage(db, sessionId, latestAssistant.timeCreated))
147594
+ return false;
147595
+ if (latestAssistant.finish === "tool-calls")
147596
+ return true;
147597
+ const partRows = db.prepare("SELECT data FROM part WHERE session_id = ? AND message_id = ?").all(sessionId, latestAssistant.id);
147598
+ return partRows.some((row) => {
147599
+ if (typeof row.data !== "string" || row.data.length === 0)
147600
+ return false;
147601
+ try {
147602
+ const part = JSON.parse(row.data);
147603
+ return part.type === "tool" && part.providerExecuted !== true;
147604
+ } catch {
147605
+ return false;
147606
+ }
147607
+ });
147608
+ }
147609
+ function hasNewerRealUserMessage(db, sessionId, latestAssistantTimeCreated) {
147610
+ if (typeof latestAssistantTimeCreated !== "number")
147611
+ return false;
147612
+ const row = db.prepare(`SELECT 1 as one
147613
+ FROM message m
147614
+ WHERE m.session_id = ?
147615
+ AND m.time_created > ?
147616
+ AND json_extract(m.data, '$.role') = 'user'
147617
+ AND NOT (
147618
+ EXISTS (SELECT 1 FROM part p WHERE p.message_id = m.id)
147619
+ AND NOT EXISTS (
147620
+ SELECT 1 FROM part p
147621
+ WHERE p.message_id = m.id
147622
+ AND COALESCE(json_extract(p.data, '$.synthetic'), 0) NOT IN (1, 'true')
147623
+ AND json_extract(p.data, '$.metadata.marker.kind') IS NULL
147624
+ AND COALESCE(json_extract(p.data, '$.ignored'), 0) NOT IN (1, 'true')
147625
+ )
147626
+ )
147627
+ LIMIT 1`).get(sessionId, latestAssistantTimeCreated);
147628
+ return row?.one === 1;
147629
+ }
147172
147630
 
147173
147631
  // ../plugin/src/hooks/magic-context/read-session-raw.ts
147174
147632
  function isRawMessageRow(row) {
@@ -148647,7 +149105,7 @@ function escapeXmlContent(s) {
148647
149105
  }
148648
149106
  // ../plugin/src/features/magic-context/project-docs-hash.ts
148649
149107
  import { createHash as createHash5 } from "node:crypto";
148650
- import { lstatSync, readFileSync as readFileSync2, statSync as statSync3 } from "node:fs";
149108
+ import { lstatSync, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
148651
149109
  import path2 from "node:path";
148652
149110
  var PROJECT_DOC_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
148653
149111
  var PROJECT_DOCS_DELIMITER = `
@@ -148721,7 +149179,7 @@ function readCanonicalPieces(projectDirectory, files) {
148721
149179
  if (!safeToRead) {
148722
149180
  continue;
148723
149181
  }
148724
- const canonicalContent = canonicalizeDocContent(readFileSync2(filePath, "utf8"));
149182
+ const canonicalContent = canonicalizeDocContent(readFileSync4(filePath, "utf8"));
148725
149183
  hashPieces.push(`file:${filename}
148726
149184
  ${canonicalContent}`);
148727
149185
  renderedSections.push(`<file name="${escapeXmlAttr(filename)}">
@@ -149168,7 +149626,7 @@ function getMemoryMutationsForRenderByIdentitySet(db, projectPaths, afterId, ren
149168
149626
  }
149169
149627
  visited.add(terminal);
149170
149628
  const next = byTarget.get(terminal);
149171
- if (!next || next.mutationType !== "superseded")
149629
+ if (next?.mutationType !== "superseded")
149172
149630
  break;
149173
149631
  if (depth >= MAX_MEMORY_REPLACEMENT_DEPTH - 1) {
149174
149632
  terminal = null;
@@ -149428,6 +149886,14 @@ function getPendingOpsStatement(db) {
149428
149886
  }
149429
149887
  return stmt;
149430
149888
  }
149889
+ function getClearPendingOpsStatement(db) {
149890
+ let stmt = clearPendingOpsStatements.get(db);
149891
+ if (!stmt) {
149892
+ stmt = db.prepare("DELETE FROM pending_ops WHERE session_id = ?");
149893
+ clearPendingOpsStatements.set(db, stmt);
149894
+ }
149895
+ return stmt;
149896
+ }
149431
149897
  function getRemovePendingOpStatement(db) {
149432
149898
  let stmt = removePendingOpStatements.get(db);
149433
149899
  if (!stmt) {
@@ -149462,6 +149928,9 @@ function getPendingOps(db, sessionId) {
149462
149928
  const rows = getPendingOpsStatement(db).all(sessionId).filter(isPendingOpRow);
149463
149929
  return rows.map(toPendingOp).filter((op) => op !== null);
149464
149930
  }
149931
+ function clearPendingOps(db, sessionId) {
149932
+ getClearPendingOpsStatement(db).run(sessionId);
149933
+ }
149465
149934
  function removePendingOp(db, sessionId, tagId) {
149466
149935
  getRemovePendingOpStatement(db).run(sessionId, tagId);
149467
149936
  }
@@ -150421,76 +150890,6 @@ var ERROR_CLASSES = new Set([
150421
150890
  "permission_denied",
150422
150891
  "unknown"
150423
150892
  ]);
150424
- // ../plugin/src/shared/models-dev-cache.ts
150425
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
150426
- import { join as join5 } from "node:path";
150427
- var MIN_SANE_LIMIT = 20000;
150428
- var MAX_SANE_LIMIT = 3000000;
150429
- function isSaneLimit(limit) {
150430
- return typeof limit === "number" && limit >= MIN_SANE_LIMIT && limit <= MAX_SANE_LIMIT;
150431
- }
150432
- var apiCache = null;
150433
- var persistSeedLoaded = false;
150434
- function persistFilePath() {
150435
- return join5(getMagicContextStorageDir(), `model-context-limits-${getHarness()}.json`);
150436
- }
150437
- function loadPersistedApiCacheOnce() {
150438
- if (persistSeedLoaded || apiCache !== null)
150439
- return;
150440
- persistSeedLoaded = true;
150441
- try {
150442
- const raw = readFileSync3(persistFilePath(), "utf-8");
150443
- const obj = JSON.parse(raw);
150444
- const map = new Map;
150445
- for (const [key, persisted] of Object.entries(obj)) {
150446
- const limit = typeof persisted === "number" ? persisted : persisted.limit;
150447
- const inputLimit = typeof persisted === "number" ? undefined : persisted.inputLimit;
150448
- const vision = typeof persisted === "number" ? false : persisted.vision === true;
150449
- if (isSaneLimit(limit)) {
150450
- map.set(key, {
150451
- limit,
150452
- inputLimit: isSaneLimit(inputLimit) ? inputLimit : undefined,
150453
- vision
150454
- });
150455
- }
150456
- }
150457
- if (map.size > 0) {
150458
- apiCache = map;
150459
- sessionLog("global", `models-dev-cache: seeded ${map.size} entries from persisted cache (cold start)`);
150460
- }
150461
- } catch {}
150462
- }
150463
- function getSdkContextLimit(providerID, modelID) {
150464
- loadPersistedApiCacheOnce();
150465
- const fromApi = lookupLimitWithTagFallback(apiCache, providerID, modelID);
150466
- return isSaneLimit(fromApi) ? fromApi : undefined;
150467
- }
150468
- function modelSupportsVision(providerID, modelID) {
150469
- loadPersistedApiCacheOnce();
150470
- if (!apiCache)
150471
- return false;
150472
- const exact = apiCache.get(`${providerID}/${modelID}`);
150473
- if (exact?.vision === true)
150474
- return true;
150475
- const colon = modelID.lastIndexOf(":");
150476
- return colon > 0 ? apiCache.get(`${providerID}/${modelID.slice(0, colon)}`)?.vision === true : false;
150477
- }
150478
- function lookupLimitWithTagFallback(cache, providerID, modelID) {
150479
- if (!cache)
150480
- return;
150481
- const exact = cache.get(`${providerID}/${modelID}`)?.limit;
150482
- if (typeof exact === "number")
150483
- return exact;
150484
- const colonIdx = modelID.lastIndexOf(":");
150485
- if (colonIdx > 0) {
150486
- const baseModel = modelID.slice(0, colonIdx);
150487
- const fallback = cache.get(`${providerID}/${baseModel}`)?.limit;
150488
- if (typeof fallback === "number")
150489
- return fallback;
150490
- }
150491
- return;
150492
- }
150493
-
150494
150893
  // ../plugin/src/hooks/magic-context/todo-view.ts
150495
150894
  import { createHash as createHash7 } from "node:crypto";
150496
150895
  var TODO_STATUS_PENDING = "pending";
@@ -150948,7 +151347,7 @@ function pruneNestedConfigLeaf(block, relativePath) {
150948
151347
  }
150949
151348
 
150950
151349
  // src/config/index.ts
150951
- import { existsSync as existsSync7, readFileSync as readFileSync5 } from "node:fs";
151350
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
150952
151351
 
150953
151352
  // ../plugin/src/config/migrate-dreamer-v2.ts
150954
151353
  var OLD_VERIFY_TASK = "verify";
@@ -151164,9 +151563,10 @@ function migrateLegacyExperimental(rawConfig, warnings) {
151164
151563
  const exp = experimental;
151165
151564
  const hasUM = "user_memories" in exp;
151166
151565
  const hasPKF = "pin_key_files" in exp;
151566
+ const hasMural = "mural" in exp;
151167
151567
  const TOP_LEVEL_GRADUATED = ["temporal_awareness", "caveman_text_compression"];
151168
151568
  const MEMORY_GRADUATED = ["auto_search", "git_commit_indexing"];
151169
- 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;
151170
151570
  if (!hasUM && !hasPKF && !hasGraduated) {
151171
151571
  return rawConfig;
151172
151572
  }
@@ -151174,6 +151574,15 @@ function migrateLegacyExperimental(rawConfig, warnings) {
151174
151574
  const dreamer = typeof patched.dreamer === "object" && patched.dreamer !== null ? { ...patched.dreamer } : {};
151175
151575
  const memory = typeof patched.memory === "object" && patched.memory !== null ? { ...patched.memory } : {};
151176
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
+ };
151177
151586
  const relocate = (key, dest, destLabel) => {
151178
151587
  if (!(key in exp))
151179
151588
  return;
@@ -151194,15 +151603,20 @@ function migrateLegacyExperimental(rawConfig, warnings) {
151194
151603
  relocate(key, patched, "");
151195
151604
  for (const key of MEMORY_GRADUATED)
151196
151605
  relocate(key, memory, "memory.");
151197
- const coerceToObject = (value) => {
151198
- if (typeof value === "boolean") {
151199
- return { enabled: value };
151200
- }
151201
- if (typeof value === "object" && value !== null) {
151202
- 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
+ };
151203
151617
  }
151204
- return;
151205
- };
151618
+ delete newExperimental.mural;
151619
+ }
151206
151620
  if (hasUM) {
151207
151621
  const oldUM = coerceToObject(exp.user_memories);
151208
151622
  if (oldUM !== undefined) {
@@ -165782,7 +166196,7 @@ var AgentOverrideConfigSchema = exports_external.object({
165782
166196
 
165783
166197
  // ../plugin/src/config/schema/magic-context.ts
165784
166198
  var DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE = 65;
165785
- var EXECUTE_THRESHOLD_CAP_MESSAGE = "execute_threshold is capped at 80% for cache safety: a single large agent step can overflow the context window before Magic Context can compact between turns, forcing OpenCode's native compaction (hard to recover from). 80% also leaves headroom below the 85%/95% emergency bands. Use a value between 20 and 80.";
166199
+ var EXECUTE_THRESHOLD_CAP_MESSAGE = "execute_threshold is capped at 90% for cache safety: output capacity is reserved from the usable context window, and the remaining 10% absorbs mid-turn growth before the absolute 95% emergency wall. Use a value between 20 and 90.";
165786
166200
  var DEFAULT_HISTORIAN_TIMEOUT_MS = 300000;
165787
166201
  var DEFAULT_HISTORY_BUDGET_PERCENTAGE = 0.15;
165788
166202
  var DEFAULT_LOCAL_EMBEDDING_MODEL = "Xenova/all-MiniLM-L6-v2";
@@ -165880,7 +166294,22 @@ var BaseEmbeddingConfigSchema = exports_external.object({
165880
166294
  input_type: exports_external.string().optional().describe("Default input_type for stored/indexed (passage) embeddings in the request body. Required by some openai-compatible providers (e.g. NVIDIA NIM). Omitted from the request when unset."),
165881
166295
  query_input_type: exports_external.string().optional().describe("Optional input_type for query (search) embeddings on asymmetric models (e.g. NVIDIA NIM 'query'). When unset, query embeddings use embedding.input_type. Passage/stored content always uses embedding.input_type."),
165882
166296
  truncate: exports_external.string().optional().describe("Optional truncate mode sent in the embedding request body (e.g. NVIDIA NIM accepts 'NONE' | 'START' | 'END'). Omitted from the request when unset."),
165883
- max_input_tokens: exports_external.number().int().positive().optional().describe("Optional maximum input tokens for chunk embeddings. Defaults conservatively to 512 when omitted.")
166297
+ max_input_tokens: exports_external.number().int().positive().optional().describe("Optional maximum input tokens for chunk embeddings. Defaults conservatively to 512 when omitted."),
166298
+ local_dtype: exports_external.enum([
166299
+ "auto",
166300
+ "fp32",
166301
+ "fp16",
166302
+ "q8",
166303
+ "int8",
166304
+ "uint8",
166305
+ "q4",
166306
+ "bnb4",
166307
+ "q4f16",
166308
+ "q2",
166309
+ "q2f16",
166310
+ "q1",
166311
+ "q1f16"
166312
+ ]).optional().describe("Local provider only: ONNX model dtype passed to the transformers.js feature-extraction pipeline. Accepts the @huggingface/transformers DataType strings (auto, fp32, fp16, q8, int8, uint8, q4, bnb4, q4f16, q2, q2f16, q1, q1f16). Omitted keeps today's behavior (fp32). A non-default value changes the produced vectors and folds into the embedding model identity, so switching dtype re-embeds rather than mixing vector spaces. Useful for selecting a quantized variant (e.g. q8) of a larger multilingual model to cut memory and CPU cost; see issue #259.")
165884
166313
  }).superRefine((data, ctx) => {
165885
166314
  const validationProvider = data.provider === "synapse" ? data.fallback_provider : data.provider;
165886
166315
  if (validationProvider === "openai-compatible" && !data.endpoint?.trim()) {
@@ -165922,7 +166351,8 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
165922
166351
  return {
165923
166352
  provider: "local",
165924
166353
  model: data.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL,
165925
- ...data.max_input_tokens ? { max_input_tokens: data.max_input_tokens } : {}
166354
+ ...data.max_input_tokens ? { max_input_tokens: data.max_input_tokens } : {},
166355
+ ...data.local_dtype ? { local_dtype: data.local_dtype } : {}
165926
166356
  };
165927
166357
  }
165928
166358
  if (data.provider === "openai-compatible") {
@@ -165945,26 +166375,29 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
165945
166375
  });
165946
166376
  var MagicContextConfigSchema = exports_external.object({
165947
166377
  enabled: exports_external.boolean().default(true).describe("Enable magic context (default: true)"),
165948
- experimental: exports_external.object({
165949
- mural: exports_external.object({
165950
- enabled: exports_external.boolean().default(false),
165951
- 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).")
165952
- }).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.")
165953
- }).default({ mural: { enabled: false } }).describe("Experimental feature switches. User and project configuration are both accepted."),
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."),
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."),
165954
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.'),
165955
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."),
165956
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."),
165957
166386
  historian: HistorianConfigSchema.describe("Historian agent configuration (model, fallback_models, variant, temperature, maxTokens, permission, two_pass, etc.)"),
165958
166387
  dreamer: DreamerConfigSchema.optional().describe("Dreamer agent + scheduling configuration (model, fallback_models, disable, schedule, tasks, etc.)"),
165959
- cache_ttl: exports_external.union([exports_external.string(), exports_external.object({ default: exports_external.string() }).catchall(exports_external.string())]).default("5m").describe('Cache TTL: string (e.g. "5m") or per-model object ({ default: "5m", "model-id": "10m" })'),
166388
+ cache_ttl: exports_external.union([exports_external.string(), exports_external.object({ default: exports_external.string() }).catchall(exports_external.string())]).default("5m").describe('Cache TTL: string (e.g. "5m", "1h", "30s") or per-model object ({ default: "5m", "model-id": "10m" }). Set to "never" for lanes kept warm by an external keepwarm proxy — disables the idle-TTL heuristic so MC never initiates a rebuild based on elapsed time.'),
166389
+ output_reserve: exports_external.union([
166390
+ exports_external.number().min(0),
166391
+ exports_external.object({ default: exports_external.number().min(0) }).catchall(exports_external.number().min(0))
166392
+ ]).optional().describe('User-only output-token reservation override. Number or per-model object ({ default: 16384, "provider/model": 8192 }); 0 disables reservation. When unset, Magic Context reserves the catalog output limit (capped at 25% of context) for shared-window providers and keeps proven separate-quota Google/Gemini windows unchanged.'),
165960
166393
  toast_duration_ms: exports_external.number().min(0).max(60000).default(5000).describe("TUI toast lifetime in milliseconds for Magic Context notifications. Set to 0 to disable Magic Context toasts entirely (min: 0, max: 60000, default: 5000)"),
165961
166394
  execute_threshold_percentage: exports_external.union([
165962
- exports_external.number().min(20).max(80, EXECUTE_THRESHOLD_CAP_MESSAGE),
165963
- exports_external.object({ default: exports_external.number().min(20).max(80, EXECUTE_THRESHOLD_CAP_MESSAGE) }).catchall(exports_external.number().min(20).max(80, EXECUTE_THRESHOLD_CAP_MESSAGE))
165964
- ]).default(DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE).describe('Context percentage that forces queued operations to execute. Number or per-model object ({ default: 65, "provider/model": 45 }). Values above 80 are rejected because the runtime caps at 80% for cache safety (MAX_EXECUTE_THRESHOLD). Default: DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE'),
166395
+ exports_external.number().min(20).max(90, EXECUTE_THRESHOLD_CAP_MESSAGE),
166396
+ exports_external.object({ default: exports_external.number().min(20).max(90, EXECUTE_THRESHOLD_CAP_MESSAGE) }).catchall(exports_external.number().min(20).max(90, EXECUTE_THRESHOLD_CAP_MESSAGE))
166397
+ ]).default(DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE).describe('Context percentage that forces queued operations to execute. Number or per-model object ({ default: 65, "provider/model": 45 }). Values above 90 are rejected because the runtime caps at 90% of the output-reserved safe window (MAX_EXECUTE_THRESHOLD). Default: DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE'),
165965
166398
  execute_threshold_tokens: exports_external.object({
165966
166399
  default: exports_external.number().min(5000).max(2000000).optional()
165967
- }).catchall(exports_external.number().min(5000).max(2000000)).optional().describe("Absolute token thresholds per model. When matched, overrides execute_threshold_percentage for that model. Accepts `default` for all models or per-model keys. Values above 80% × context_limit are clamped with a warning log. Min 5_000, max 2_000_000."),
166400
+ }).catchall(exports_external.number().min(5000).max(2000000)).optional().describe("Absolute token thresholds per model. When matched, overrides execute_threshold_percentage for that model. Accepts `default` for all models or per-model keys. Values above 90% × context_limit are clamped with a warning log. Min 5_000, max 2_000_000."),
165968
166401
  protected_tags: exports_external.number().min(1).max(100).optional().describe("Number of recent tags to protect from dropping (min: 1, max: 100, default: 20)"),
165969
166402
  clear_reasoning_age: exports_external.number().min(10).default(50).describe("Clear reasoning/thinking blocks older than N tags (default: 50)"),
165970
166403
  history_budget_percentage: exports_external.number().min(0.05).max(0.5).default(DEFAULT_HISTORY_BUDGET_PERCENTAGE).describe("Fraction of usable context (context_limit × execute_threshold) reserved for the session history block (default: 0.15)"),
@@ -165984,6 +166417,9 @@ var MagicContextConfigSchema = exports_external.object({
165984
166417
  cache_size_mb: exports_external.number().min(2).max(2048).default(64).describe("Page-cache size in MiB per connection (PRAGMA cache_size). Larger keeps more hot pages resident, cutting re-reads on repeated full-table scans. (min 2, max 2048, default 64)"),
165985
166418
  mmap_size_mb: exports_external.number().min(0).max(8192).default(0).describe("Memory-mapped I/O size in MiB (PRAGMA mmap_size). 0 disables mmap (SQLite default). Raising it can cut read overhead on large DBs at the cost of address space. (min 0, max 8192, default 0)")
165986
166419
  }).default({ cache_size_mb: 64, mmap_size_mb: 0 }).describe("SQLite connection tuning for Magic Context's own context.db. These are per-connection PRAGMAs applied at open; they do not change the schema or what is stored."),
166420
+ storage: exports_external.object({
166421
+ enforce_private_permissions: exports_external.boolean().default(true).describe("When true (default), Magic Context creates and re-tightens its storage directories to owner-only 0700 and storage files to owner-only 0600. Set false only for a deliberate trusted-group deployment whose operator manages directory, database, WAL/SHM, cache, and RPC file permissions externally; Magic Context then never chmods or supplies restrictive creation modes. USER-LEVEL ONLY — ignored in project config for security. On Windows, POSIX chmod modes are already meaningless, so this setting is a no-op.")
166422
+ }).default({ enforce_private_permissions: true }).describe("Storage permission policy. The default keeps session content and memories owner-private. Disabling enforcement is for trusted shared-group storage managed externally; every group member able to read the storage can read all stored session content and memories."),
165987
166423
  embedding: EmbeddingConfigSchema.default({
165988
166424
  provider: "local",
165989
166425
  model: DEFAULT_LOCAL_EMBEDDING_MODEL
@@ -165997,6 +166433,9 @@ var MagicContextConfigSchema = exports_external.object({
165997
166433
  temporal_awareness: exports_external.boolean().default(true).describe('Inject wall-clock gap markers (<!-- +Xm -->) between user messages where > 5 min elapsed since the previous message, and add compact date ranges to compartment headings. Gives the agent a sense of session pacing and "how long ago" across multi-day sessions. Graduated from experimental.temporal_awareness; default: true (set false to opt out).'),
165998
166434
  keep_subagents: exports_external.boolean().default(false).describe("Debug: keep the child sessions Magic Context spawns for its own subagents (historian, dreamer, sidekick, memory-migration) instead of deleting them on success. Useful for short-term inspection/data collection — their full transcript (prompt, tool calls, token usage, output) stays in the host session store. Kept sessions accumulate until manually cleared; leave false for normal use. Requires a restart to take effect."),
165999
166435
  fail_closed_blocking: exports_external.boolean().default(true).describe("When Magic Context cannot operate (schema fence mismatch, storage open/migration failure), block the primary-session prompt with a loud recovery error instead of silently degrading to native compaction. Default true. Set false only to restore the old degrade-silently behavior (not recommended). USER-LEVEL ONLY — ignored in project config for security. Requires a restart."),
166436
+ compaction: exports_external.object({
166437
+ enabled: exports_external.boolean().default(true).describe("When false, Magic Context stops managing the context window and keeps its knowledge layer: memory and docs/user-profile/key-files injection through additive m[0]/m[1], raw-message FTS indexing, dreamer, notes, ctx_search, ctx_expand, ctx_memory, and /ctx-embed remain available. MC's historian/compartment preparation, tagging, markers, pruning, folding, drops, strips, splicing, synthetic context-management todos, temporal markers, nudges, and fail-closed blocking stop; ctx_expand remains a knowledge-surface tool. fail_closed_blocking is inert: a transform failure passes the input messages through without blocking or cancelling. This setting does not enable native compaction: OpenCode's compaction.auto / compaction.prune or Pi's equivalent owns the window, or nothing does. MC's compaction.enabled in magic-context.jsonc is distinct from OpenCode's compaction.auto / compaction.prune in opencode.jsonc; they are different files and different owners. On the first turn after disabling, a long session may trigger one native compaction cycle; MC removes only its own marker boundary, leaves native boundaries and stored compartments intact, and does no pre-trimming mitigation. Marker cleanup is lazy per session, so an unresumed session is cleaned when it is next resumed. If compaction is enabled again, run /ctx-wrapup when the historian is runnable to catch up. OpenCode peer verification against v1.18.4 confirms native compaction covers child sessions: subagents receive additive memory/docs injection and no MC reclaim in this mode, so keep subagent tasks small or leave compaction.enabled on for long subagent runs. If transform_mode is rust, compaction-off resolves to the TypeScript transform and emits one frozen boot warning because there is no Rust reduced-mode contract. This is boot-resolved and requires a process restart; project-tier compaction.enabled is stripped so a cloned repository cannot disable the user's setting. The sidebar reports raw usage as Context: <pct>% · native compaction or Context: <pct>% · no active compaction and does not show an MC execute-threshold fill. /ctx-wrapup, /ctx-recomp, /ctx-flush, and /ctx-session-upgrade refuse without context-management side effects; /ctx-embed remains functional. Raw content hidden by a native boundary before Magic Context's first pass is not retroactively indexed.")
166438
+ }).default({ enabled: true }).describe("Compaction-off mode gate. Default true (MC manages the context window as today). Set compaction.enabled=false to keep the knowledge layer while letting native compaction (or nothing) own the window. Boot-resolved; requires a restart to change."),
166000
166439
  todowrite: exports_external.object({
166001
166440
  enabled: exports_external.boolean().default(true).describe("Pi only: register Magic Context's todowrite task-list tool. Disable if you use your own todo extension. OpenCode ships its own built-in todowrite; this setting has no effect there."),
166002
166441
  overlay: exports_external.boolean().default(true).describe("Pi only: show the persistent todo overlay above the editor while tasks are active.")
@@ -166150,6 +166589,19 @@ function stripUnsafeProjectConfigFields(projectRaw) {
166150
166589
  delete projectRaw.fail_closed_blocking;
166151
166590
  warnings.push("Ignoring fail_closed_blocking from project config (security: only user-level config may disable or force the loud inoperability gate).");
166152
166591
  }
166592
+ if ("allow_home_project" in projectRaw) {
166593
+ delete projectRaw.allow_home_project;
166594
+ warnings.push("Ignoring allow_home_project from project config (security: only user-level config may opt the user's home directory into Magic Context).");
166595
+ }
166596
+ const compaction = projectRaw.compaction;
166597
+ if (isPlainObject3(compaction) && "enabled" in compaction) {
166598
+ delete compaction.enabled;
166599
+ warnings.push("Ignoring compaction.enabled from project config (security: only user-level config may disable Magic Context's context-window management; a cloned repo cannot change how the user's window is owned).");
166600
+ }
166601
+ if ("output_reserve" in projectRaw) {
166602
+ delete projectRaw.output_reserve;
166603
+ warnings.push("Ignoring output_reserve from project config (security: output-token reservation only honors user-level config).");
166604
+ }
166153
166605
  if ("language" in projectRaw) {
166154
166606
  delete projectRaw.language;
166155
166607
  warnings.push("Ignoring language from project config (security: output language is a user-level setting).");
@@ -166158,6 +166610,11 @@ function stripUnsafeProjectConfigFields(projectRaw) {
166158
166610
  delete projectRaw.sqlite;
166159
166611
  warnings.push("Ignoring sqlite.* from project config (security: SQLite cache/mmap PRAGMAs apply to the " + "process-global shared database handle; only user-level config may set them).");
166160
166612
  }
166613
+ const storage = projectRaw.storage;
166614
+ if (isPlainObject3(storage) && "enforce_private_permissions" in storage) {
166615
+ delete storage.enforce_private_permissions;
166616
+ warnings.push("Ignoring storage.enforce_private_permissions from project config (security: only user-level config may opt into externally managed shared storage permissions).");
166617
+ }
166161
166618
  const pi = projectRaw.pi;
166162
166619
  if (isPlainObject3(pi) && "subagent_extensions" in pi) {
166163
166620
  delete pi.subagent_extensions;
@@ -166195,6 +166652,17 @@ function stripUnsafeProjectConfigFields(projectRaw) {
166195
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).");
166196
166653
  }
166197
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
+ }
166198
166666
  for (const agentKey of HIDDEN_AGENT_KEYS) {
166199
166667
  const block = projectRaw[agentKey];
166200
166668
  if (!isPlainObject3(block))
@@ -166343,7 +166811,7 @@ function dropInheritedEmbeddingKeyOnRedirect(projectRaw, mergedRaw, userRaw) {
166343
166811
  }
166344
166812
 
166345
166813
  // ../plugin/src/config/variable.ts
166346
- import { existsSync as existsSync6, readFileSync as readFileSync4 } from "node:fs";
166814
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
166347
166815
  import { homedir as homedir4 } from "node:os";
166348
166816
  import { dirname as dirname3, isAbsolute as isAbsolute2, resolve } from "node:path";
166349
166817
 
@@ -166484,7 +166952,7 @@ function substituteConfigVariables(input) {
166484
166952
  }
166485
166953
  let contents;
166486
166954
  try {
166487
- contents = readFileSync4(filePath, "utf-8").trim();
166955
+ contents = readFileSync5(filePath, "utf-8").trim();
166488
166956
  } catch (error51) {
166489
166957
  const message = error51 instanceof Error ? error51.message : String(error51);
166490
166958
  warnings.push(`Failed to read file for ${token} (${filePath}): ${message}; using empty string`);
@@ -166496,6 +166964,188 @@ function substituteConfigVariables(input) {
166496
166964
  return { text: output, warnings };
166497
166965
  }
166498
166966
 
166967
+ // ../plugin/src/shared/models-dev-cache.ts
166968
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync6, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
166969
+ import { join as join5 } from "node:path";
166970
+
166971
+ // ../plugin/src/shared/harness-provider-map.ts
166972
+ var CANONICAL_TO_PI_PROVIDER = {
166973
+ openai: "openai-codex",
166974
+ google: "google-antigravity"
166975
+ };
166976
+ var PI_TO_CANONICAL_PROVIDER = {
166977
+ "openai-codex": "openai",
166978
+ "google-antigravity": "google"
166979
+ };
166980
+ function remapProviderPrefix(ref, map2) {
166981
+ if (typeof ref !== "string")
166982
+ return ref;
166983
+ const slash = ref.indexOf("/");
166984
+ if (slash <= 0)
166985
+ return ref;
166986
+ const provider = ref.slice(0, slash);
166987
+ const mapped = map2[provider];
166988
+ return mapped ? `${mapped}${ref.slice(slash)}` : ref;
166989
+ }
166990
+ function piModelRefToCanonical(ref) {
166991
+ return remapProviderPrefix(ref, PI_TO_CANONICAL_PROVIDER);
166992
+ }
166993
+ function resolveModelRefForPi(ref) {
166994
+ return remapProviderPrefix(piModelRefToCanonical(ref), CANONICAL_TO_PI_PROVIDER);
166995
+ }
166996
+
166997
+ // ../plugin/src/shared/models-dev-cache.ts
166998
+ var MIN_SANE_LIMIT = 20000;
166999
+ var MAX_SANE_LIMIT = 3000000;
167000
+ function isSaneLimit(limit) {
167001
+ return typeof limit === "number" && limit >= MIN_SANE_LIMIT && limit <= MAX_SANE_LIMIT;
167002
+ }
167003
+ var SEPARATE_OUTPUT_QUOTA_PROVIDERS = new Set(["google", "google-antigravity"]);
167004
+ var MIN_PLAUSIBLE_CONTEXT_LIMIT = 1024;
167005
+ var OUTPUT_RESERVE_CAP_RATIO = 0.25;
167006
+ var outputReserveConfig;
167007
+ var reserveClampLogSeen = new Set;
167008
+ var apiCache = null;
167009
+ var persistSeedLoaded = false;
167010
+ function persistFilePath() {
167011
+ return join5(getMagicContextStorageDir(), `model-context-limits-${getHarness()}.json`);
167012
+ }
167013
+ function loadPersistedApiCacheOnce() {
167014
+ if (persistSeedLoaded || apiCache !== null)
167015
+ return;
167016
+ persistSeedLoaded = true;
167017
+ try {
167018
+ const raw = readFileSync6(persistFilePath(), "utf-8");
167019
+ const obj = JSON.parse(raw);
167020
+ const map2 = new Map;
167021
+ for (const [key, persisted] of Object.entries(obj)) {
167022
+ const limit = typeof persisted === "number" ? persisted : persisted.limit;
167023
+ const contextLimit = typeof persisted === "number" ? undefined : persisted.contextLimit;
167024
+ const inputLimit = typeof persisted === "number" ? undefined : persisted.inputLimit;
167025
+ const outputLimit = typeof persisted === "number" ? undefined : persisted.outputLimit;
167026
+ const vision = typeof persisted === "number" ? false : persisted.vision === true;
167027
+ if (isSaneLimit(contextLimit) || isSaneLimit(limit)) {
167028
+ map2.set(key, {
167029
+ limit: isSaneLimit(limit) ? limit : undefined,
167030
+ contextLimit: isSaneLimit(contextLimit) ? contextLimit : undefined,
167031
+ inputLimit: isSaneLimit(inputLimit) ? inputLimit : undefined,
167032
+ outputLimit: isFinitePositive(outputLimit) ? outputLimit : undefined,
167033
+ vision
167034
+ });
167035
+ }
167036
+ }
167037
+ if (map2.size > 0) {
167038
+ apiCache = map2;
167039
+ sessionLog("global", `models-dev-cache: seeded ${map2.size} entries from persisted cache (cold start)`);
167040
+ }
167041
+ } catch {}
167042
+ }
167043
+ function isFinitePositive(value) {
167044
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
167045
+ }
167046
+ function modelKeyLookupOrder(providerID, modelID) {
167047
+ const full = `${providerID}/${modelID}`;
167048
+ const canonicalFull = piModelRefToCanonical(full);
167049
+ const candidates = [full, canonicalFull, modelID];
167050
+ const colon = modelID.lastIndexOf(":");
167051
+ if (colon > 0) {
167052
+ const bareModel = modelID.slice(0, colon);
167053
+ const providerBare = `${providerID}/${bareModel}`;
167054
+ candidates.push(providerBare, piModelRefToCanonical(providerBare), bareModel);
167055
+ }
167056
+ return [...new Set(candidates)];
167057
+ }
167058
+ function configuredOutputReserve(config2, providerID, modelID) {
167059
+ if (typeof config2 === "number")
167060
+ return Number.isFinite(config2) && config2 >= 0 ? config2 : undefined;
167061
+ if (!config2)
167062
+ return;
167063
+ for (const candidate of modelKeyLookupOrder(providerID, modelID)) {
167064
+ const value = config2[candidate];
167065
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0)
167066
+ return value;
167067
+ }
167068
+ return Number.isFinite(config2.default) && config2.default >= 0 ? config2.default : undefined;
167069
+ }
167070
+ function logReserveClampOnce(key, message) {
167071
+ if (reserveClampLogSeen.has(key))
167072
+ return;
167073
+ reserveClampLogSeen.add(key);
167074
+ sessionLog("global", `models-dev-cache: ${message}`);
167075
+ }
167076
+ function setOutputReserveConfig(config2) {
167077
+ outputReserveConfig = config2;
167078
+ }
167079
+ function resolveLimit(limit, providerID, modelID, reserveConfig = outputReserveConfig) {
167080
+ if (!limit)
167081
+ return;
167082
+ const context = isFinitePositive(limit.context) ? limit.context : undefined;
167083
+ const input = isFinitePositive(limit.input) ? limit.input : undefined;
167084
+ if (input !== undefined && (context === undefined || input < context))
167085
+ return input;
167086
+ if (context === undefined)
167087
+ return;
167088
+ const configuredReserve = configuredOutputReserve(reserveConfig, providerID, modelID);
167089
+ let reserve;
167090
+ if (configuredReserve !== undefined) {
167091
+ reserve = configuredReserve;
167092
+ } else if (SEPARATE_OUTPUT_QUOTA_PROVIDERS.has(providerID)) {
167093
+ reserve = 0;
167094
+ } else {
167095
+ const output = isFinitePositive(limit.output) ? limit.output : 0;
167096
+ const cap = context * OUTPUT_RESERVE_CAP_RATIO;
167097
+ reserve = Math.min(output, cap);
167098
+ if (output > cap) {
167099
+ logReserveClampOnce(`cap|${providerID}/${modelID}|${context}|${output}`, `output reserve capped at 25% for ${providerID}/${modelID}: ${output} → ${cap}`);
167100
+ }
167101
+ }
167102
+ const floor = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, context * 0.5);
167103
+ const maxReserve = Math.max(0, context - floor);
167104
+ if (reserve > maxReserve) {
167105
+ logReserveClampOnce(`floor|${providerID}/${modelID}|${context}|${reserve}`, `output reserve clamped for ${providerID}/${modelID}: ${reserve} → ${maxReserve} (usable floor ${floor})`);
167106
+ reserve = maxReserve;
167107
+ }
167108
+ return Math.floor(context - reserve);
167109
+ }
167110
+ function getSdkContextLimit(providerID, modelID, detectedContextLimit, options) {
167111
+ loadPersistedApiCacheOnce();
167112
+ const metadata = lookupMetadataWithTagFallback(apiCache, providerID, modelID);
167113
+ if (!metadata)
167114
+ return;
167115
+ const rawContext = metadata.contextLimit ?? metadata.limit;
167116
+ const promptOnlyDetected = options?.detectedLimitProvenance === "prompt_only" && isFinitePositive(detectedContextLimit) ? detectedContextLimit : undefined;
167117
+ const context = promptOnlyDetected === undefined && isFinitePositive(detectedContextLimit) && isFinitePositive(rawContext) ? Math.min(rawContext, detectedContextLimit) : promptOnlyDetected === undefined && isFinitePositive(detectedContextLimit) ? detectedContextLimit : rawContext;
167118
+ const inputCandidates = [metadata.inputLimit, promptOnlyDetected].filter(isFinitePositive);
167119
+ const input = inputCandidates.length > 0 ? Math.min(...inputCandidates) : undefined;
167120
+ return resolveLimit({
167121
+ context,
167122
+ input,
167123
+ output: metadata.outputLimit
167124
+ }, providerID, modelID, options?.reservation === "none" ? 0 : undefined);
167125
+ }
167126
+ function modelSupportsVision(providerID, modelID) {
167127
+ loadPersistedApiCacheOnce();
167128
+ if (!apiCache)
167129
+ return false;
167130
+ const exact = apiCache.get(`${providerID}/${modelID}`);
167131
+ if (exact?.vision === true)
167132
+ return true;
167133
+ const colon = modelID.lastIndexOf(":");
167134
+ return colon > 0 ? apiCache.get(`${providerID}/${modelID.slice(0, colon)}`)?.vision === true : false;
167135
+ }
167136
+ function lookupMetadataWithTagFallback(cache, providerID, modelID) {
167137
+ if (!cache)
167138
+ return;
167139
+ const exact = cache.get(`${providerID}/${modelID}`);
167140
+ if (exact)
167141
+ return exact;
167142
+ const colonIdx = modelID.lastIndexOf(":");
167143
+ if (colonIdx > 0) {
167144
+ return cache.get(`${providerID}/${modelID.slice(0, colonIdx)}`);
167145
+ }
167146
+ return;
167147
+ }
167148
+
166499
167149
  // src/config/index.ts
166500
167150
  var import_comment_json = __toESM(require_src2(), 1);
166501
167151
  function getProjectConfigPaths(cwd) {
@@ -166514,7 +167164,7 @@ function resolvePiLegacyFallback(sources) {
166514
167164
  }
166515
167165
  function loadConfigFile(path3, scope) {
166516
167166
  try {
166517
- const rawText = readFileSync5(path3, "utf-8");
167167
+ const rawText = readFileSync7(path3, "utf-8");
166518
167168
  const substituted = substituteConfigVariables({
166519
167169
  text: rawText,
166520
167170
  configPath: path3,
@@ -166699,6 +167349,7 @@ function loadPiConfig(opts = {}) {
166699
167349
  }
166700
167350
  }
166701
167351
  const parsed = parsePiConfig(rawConfig);
167352
+ setOutputReserveConfig(parsed.config.output_reserve);
166702
167353
  warnings.push(...parsed.warnings.map((warning) => `[merged config] ${warning}`));
166703
167354
  return {
166704
167355
  config: parsed.config,
@@ -166818,6 +167469,7 @@ function loadPiConfigDetailed(opts = {}) {
166818
167469
  }
166819
167470
  const recoveredTopLevelKeys = [];
166820
167471
  const parsed = parsePiConfig(rawConfig, recoveredTopLevelKeys);
167472
+ setOutputReserveConfig(parsed.config.output_reserve);
166821
167473
  warnings.push(...parsed.warnings.map((warning) => `[merged config] ${warning}`));
166822
167474
  const substitutionFailures = loadedFiles.flatMap(bindSubstitutionFailures);
166823
167475
  const userLoaded = loadedFiles.find((loaded) => loaded.scope === "user");
@@ -166940,9 +167592,6 @@ var existingHashStatements = new WeakMap;
166940
167592
  var existingHashByProjectStatements = new WeakMap;
166941
167593
  var deleteByCompartmentStatements = new WeakMap;
166942
167594
  var insertEmbeddingStatements = new WeakMap;
166943
- var distinctModelStatements = new WeakMap;
166944
- var clearProjectStatements = new WeakMap;
166945
- var clearProjectModelStatements = new WeakMap;
166946
167595
  var searchRowsStatements = new WeakMap;
166947
167596
  var searchRowsByModelStatements = new WeakMap;
166948
167597
  var searchPoolProbeStatements = new WeakMap;
@@ -170209,6 +170858,7 @@ function getEmbeddingProviderIdentity(config2) {
170209
170858
  throw new Error("Unknown embedding provider");
170210
170859
  }
170211
170860
  const truncate = config2.provider === "openai-compatible" ? config2.truncate?.trim() : undefined;
170861
+ const localDtype = config2.provider === "local" && config2.local_dtype && config2.local_dtype !== "fp32" ? config2.local_dtype : undefined;
170212
170862
  const identityInput = config2.provider === "openai-compatible" ? {
170213
170863
  provider: "openai-compatible",
170214
170864
  model: config2.model.trim(),
@@ -170220,7 +170870,8 @@ function getEmbeddingProviderIdentity(config2) {
170220
170870
  provider: "local",
170221
170871
  model: config2.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL,
170222
170872
  endpoint: "",
170223
- apiKeyPresent: false
170873
+ apiKeyPresent: false,
170874
+ ...localDtype ? { localDtype } : {}
170224
170875
  };
170225
170876
  return `embedding-provider:${computeNormalizedHash(JSON.stringify(identityInput))}`;
170226
170877
  }
@@ -170308,6 +170959,7 @@ async function injectWasmOrtForElectron() {
170308
170959
  return false;
170309
170960
  }
170310
170961
  }
170962
+ var DEFAULT_LOCAL_DTYPE = "fp32";
170311
170963
  async function withQuietConsole(fn) {
170312
170964
  const origWarn = console.warn;
170313
170965
  const origError = console.error;
@@ -170384,16 +171036,22 @@ class LocalEmbeddingProvider {
170384
171036
  modelId;
170385
171037
  maxInputTokens;
170386
171038
  model;
171039
+ dtype;
170387
171040
  pipeline = null;
170388
171041
  initPromise = null;
170389
171042
  inFlight = 0;
170390
171043
  disposing = false;
170391
171044
  disposePromise = null;
170392
171045
  inFlightWaiters = [];
170393
- constructor(model = DEFAULT_LOCAL_EMBEDDING_MODEL, maxInputTokens = 512) {
171046
+ constructor(model = DEFAULT_LOCAL_EMBEDDING_MODEL, maxInputTokens = 512, dtype = DEFAULT_LOCAL_DTYPE) {
170394
171047
  this.model = model;
170395
171048
  this.maxInputTokens = maxInputTokens;
170396
- this.modelId = getEmbeddingProviderIdentity({ provider: "local", model });
171049
+ this.dtype = dtype || DEFAULT_LOCAL_DTYPE;
171050
+ this.modelId = getEmbeddingProviderIdentity({
171051
+ provider: "local",
171052
+ model,
171053
+ ...dtype && dtype !== DEFAULT_LOCAL_DTYPE ? { local_dtype: dtype } : {}
171054
+ });
170397
171055
  }
170398
171056
  async initialize() {
170399
171057
  if (this.disposing) {
@@ -170424,11 +171082,15 @@ class LocalEmbeddingProvider {
170424
171082
  }
170425
171083
  const modelCacheDir = join6(getMagicContextStorageDir(), "models");
170426
171084
  try {
170427
- mkdirSync4(modelCacheDir, { recursive: true, mode: 448 });
170428
- if (process.platform !== "win32") {
170429
- try {
170430
- chmodSync2(modelCacheDir, 448);
170431
- } catch {}
171085
+ if (shouldEnforcePrivateStoragePermissions()) {
171086
+ mkdirSync4(modelCacheDir, { recursive: true, mode: 448 });
171087
+ if (process.platform !== "win32") {
171088
+ try {
171089
+ chmodSync2(modelCacheDir, 448);
171090
+ } catch {}
171091
+ }
171092
+ } else {
171093
+ mkdirSync4(modelCacheDir, { recursive: true });
170432
171094
  }
170433
171095
  env.cacheDir = modelCacheDir;
170434
171096
  } catch {
@@ -170444,7 +171106,7 @@ class LocalEmbeddingProvider {
170444
171106
  for (let attempt = 1;attempt <= MAX_ATTEMPTS; attempt++) {
170445
171107
  try {
170446
171108
  const pipeline = await withQuietConsole(() => createPipeline("feature-extraction", this.model, {
170447
- dtype: "fp32",
171109
+ dtype: this.dtype,
170448
171110
  ...injectedWasmOrt ? { device: "auto" } : {}
170449
171111
  }));
170450
171112
  if (this.disposing) {
@@ -170916,9 +171578,6 @@ var saveStatements = new WeakMap;
170916
171578
  var loadProjectStatements = new WeakMap;
170917
171579
  var loadUnembeddedStatements = new WeakMap;
170918
171580
  var countEmbeddedStatements = new WeakMap;
170919
- var clearProjectStatements2 = new WeakMap;
170920
- var clearProjectModelStatements2 = new WeakMap;
170921
- var distinctModelIdStatements = new WeakMap;
170922
171581
  function getSaveStatement(db) {
170923
171582
  let stmt = saveStatements.get(db);
170924
171583
  if (!stmt) {
@@ -170989,7 +171648,6 @@ function countEmbeddedCommits(db, projectPath, modelId) {
170989
171648
  var insertStatements = new WeakMap;
170990
171649
  var existingShasStatements = new WeakMap;
170991
171650
  var projectCountStatements = new WeakMap;
170992
- var evictStatements = new WeakMap;
170993
171651
  var evictOverflowStatements = new WeakMap;
170994
171652
  var latestCommitTimeStatements = new WeakMap;
170995
171653
  function getInsertStatement(db) {
@@ -171238,7 +171896,6 @@ var deleteEmbeddingStatements = new WeakMap;
171238
171896
  var getStoredModelIdStatements = new WeakMap;
171239
171897
  var clearAllEmbeddingsStatements = new WeakMap;
171240
171898
  var clearModelEmbeddingsStatements = new WeakMap;
171241
- var getDistinctStoredModelIdsStatements = new WeakMap;
171242
171899
  function isEmbeddingBlob(value) {
171243
171900
  return value instanceof Uint8Array || value instanceof ArrayBuffer;
171244
171901
  }
@@ -171516,7 +172173,8 @@ function resolveEmbeddingConfig(config2) {
171516
172173
  model: config2?.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL,
171517
172174
  ...config2?.max_input_tokens ? {
171518
172175
  max_input_tokens: normalizeCompartmentChunkMaxInputTokens(config2.max_input_tokens)
171519
- } : {}
172176
+ } : {},
172177
+ ...config2?.local_dtype ? { local_dtype: config2.local_dtype } : {}
171520
172178
  };
171521
172179
  }
171522
172180
  if (config2.provider === "openai-compatible") {
@@ -171575,7 +172233,7 @@ function createProvider(config2, context) {
171575
172233
  });
171576
172234
  }
171577
172235
  if (config2.provider === "local") {
171578
- return new LocalEmbeddingProvider(config2.model, config2.max_input_tokens);
172236
+ return new LocalEmbeddingProvider(config2.model, config2.max_input_tokens, config2.local_dtype);
171579
172237
  }
171580
172238
  if (config2.provider === "synapse") {
171581
172239
  const synapse = config2;
@@ -172718,7 +173376,7 @@ function createProvider2(config2) {
172718
173376
  });
172719
173377
  }
172720
173378
  if (config2.provider === "local") {
172721
- return new LocalEmbeddingProvider(config2.model, config2.max_input_tokens);
173379
+ return new LocalEmbeddingProvider(config2.model, config2.max_input_tokens, config2.local_dtype);
172722
173380
  }
172723
173381
  if (config2.provider === "synapse") {
172724
173382
  const synapse = config2;
@@ -172895,7 +173553,8 @@ function configFingerprint(paths) {
172895
173553
  }).join("|");
172896
173554
  }
172897
173555
  async function ensureProjectRegisteredFromPiDirectory(directory, db) {
172898
- const projectIdentity = resolveProjectIdentityForSession(directory);
173556
+ const detailed = loadPiConfigDetailed({ cwd: directory });
173557
+ const projectIdentity = resolveProjectIdentityForSession(directory, detailed.config.allow_home_project);
172899
173558
  if (!projectIdentity)
172900
173559
  return;
172901
173560
  let registrationFingerprints = registrationFingerprintsByDatabase.get(db);
@@ -172906,7 +173565,6 @@ async function ensureProjectRegisteredFromPiDirectory(directory, db) {
172906
173565
  const cached2 = registrationFingerprints.get(projectIdentity);
172907
173566
  if (cached2 && configFingerprint(cached2.paths) === cached2.fingerprint)
172908
173567
  return;
172909
- const detailed = loadPiConfigDetailed({ cwd: directory });
172910
173568
  if (isConfigLoadUntrusted(detailed)) {
172911
173569
  handleUntrustedLoad(db, projectIdentity, directory, detailed);
172912
173570
  return;
@@ -179338,6 +179996,7 @@ function queueEmbedding(args) {
179338
179996
  }
179339
179997
  function createCtxMemoryTool(deps) {
179340
179998
  const dreamerAllowed = deps.allowDreamerActions === true;
179999
+ const resolveProject = deps.resolveProjectIdentity ?? resolveProjectIdentityForSession;
179341
180000
  const description = dreamerAllowed ? `${CTX_MEMORY_DESCRIPTION}
179342
180001
  - list: enumerate stored memories (maintenance sessions).` : CTX_MEMORY_DESCRIPTION;
179343
180002
  return {
@@ -179360,7 +180019,7 @@ function createCtxMemoryTool(deps) {
179360
180019
  if (!dreamerAllowed && DREAMER_ONLY_ACTIONS.has(params.action)) {
179361
180020
  return err2(`Error: Action '${params.action}' is not allowed in this context.`);
179362
180021
  }
179363
- const projectIdentity = resolveProjectIdentityForSession(ctx.cwd);
180022
+ const projectIdentity = resolveProject(ctx.cwd);
179364
180023
  if (!projectIdentity) {
179365
180024
  return err2("Error: Could not resolve project identity for memory action.");
179366
180025
  }
@@ -179730,6 +180389,7 @@ function paginateNewestFirst(notes, limit, offset) {
179730
180389
  return { page, total, footer };
179731
180390
  }
179732
180391
  function createCtxNoteTool(deps) {
180392
+ const resolveProject = deps.resolveProjectIdentity ?? resolveProjectIdentityForSession;
179733
180393
  return {
179734
180394
  name: "ctx_note",
179735
180395
  label: "Magic Context: Notes",
@@ -179761,7 +180421,7 @@ function createCtxNoteTool(deps) {
179761
180421
  if (dreamerEnabled !== true) {
179762
180422
  return err3("Error: Smart notes require dreamer to be enabled. Enable dreamer in magic-context.jsonc to use surface_condition.");
179763
180423
  }
179764
- const projectIdentity = resolveProjectIdentityForSession(ctx.cwd);
180424
+ const projectIdentity = resolveProject(ctx.cwd);
179765
180425
  if (!projectIdentity) {
179766
180426
  return err3("Error: Could not resolve project identity for smart note.");
179767
180427
  }
@@ -179787,7 +180447,7 @@ function createCtxNoteTool(deps) {
179787
180447
  if (typeof params.note_id !== "number") {
179788
180448
  return err3("Error: 'note_id' is required when action is 'dismiss'.");
179789
180449
  }
179790
- const projectIdentity = resolveProjectIdentityForSession(ctx.cwd);
180450
+ const projectIdentity = resolveProject(ctx.cwd);
179791
180451
  if (!projectIdentity) {
179792
180452
  return err3("Error: Could not resolve project identity for note dismiss.");
179793
180453
  }
@@ -179809,7 +180469,7 @@ function createCtxNoteTool(deps) {
179809
180469
  if (!updates.content && !updates.surfaceCondition) {
179810
180470
  return err3("Error: Provide 'content' and/or 'surface_condition' to update.");
179811
180471
  }
179812
- const projectIdentity = resolveProjectIdentityForSession(ctx.cwd);
180472
+ const projectIdentity = resolveProject(ctx.cwd);
179813
180473
  if (!projectIdentity) {
179814
180474
  return err3("Error: Could not resolve project identity for note update.");
179815
180475
  }
@@ -179835,6 +180495,7 @@ function createCtxNoteTool(deps) {
179835
180495
  db: deps.db,
179836
180496
  sessionId,
179837
180497
  cwd: ctx.cwd,
180498
+ resolveProjectIdentity: resolveProject,
179838
180499
  filter: params.filter,
179839
180500
  limit,
179840
180501
  offset
@@ -179858,7 +180519,7 @@ No session notes or smart notes.`);
179858
180519
  };
179859
180520
  }
179860
180521
  function readNotes(args) {
179861
- const projectIdentity = resolveProjectIdentityForSession(args.cwd);
180522
+ const projectIdentity = args.resolveProjectIdentity(args.cwd);
179862
180523
  if (args.filter === undefined) {
179863
180524
  const sessionNotes2 = getNotes(args.db, {
179864
180525
  sessionId: args.sessionId,
@@ -181591,32 +182252,6 @@ async function unifiedSearch(db, sessionId, projectPath, query, options = {}) {
181591
182252
  // ../plugin/src/features/magic-context/mural/render-trigger.ts
181592
182253
  import { createHash as createHash15 } from "node:crypto";
181593
182254
 
181594
- // ../plugin/src/shared/harness-provider-map.ts
181595
- var CANONICAL_TO_PI_PROVIDER = {
181596
- openai: "openai-codex",
181597
- google: "google-antigravity"
181598
- };
181599
- var PI_TO_CANONICAL_PROVIDER = {
181600
- "openai-codex": "openai",
181601
- "google-antigravity": "google"
181602
- };
181603
- function remapProviderPrefix(ref3, map2) {
181604
- if (typeof ref3 !== "string")
181605
- return ref3;
181606
- const slash = ref3.indexOf("/");
181607
- if (slash <= 0)
181608
- return ref3;
181609
- const provider2 = ref3.slice(0, slash);
181610
- const mapped3 = map2[provider2];
181611
- return mapped3 ? `${mapped3}${ref3.slice(slash)}` : ref3;
181612
- }
181613
- function piModelRefToCanonical(ref3) {
181614
- return remapProviderPrefix(ref3, PI_TO_CANONICAL_PROVIDER);
181615
- }
181616
- function resolveModelRefForPi(ref3) {
181617
- return remapProviderPrefix(piModelRefToCanonical(ref3), CANONICAL_TO_PI_PROVIDER);
181618
- }
181619
-
181620
182255
  // ../plugin/src/features/magic-context/mural/mural-selection.ts
181621
182256
  var DEFAULT_MURAL_MEMORY_BUDGET = 8000;
181622
182257
  function muralOverflowMemories(memories, budgetTokens = DEFAULT_MURAL_MEMORY_BUDGET) {
@@ -181818,6 +182453,8 @@ function naturalLineLengths(entries, roomWidth) {
181818
182453
  let currentCategory = null;
181819
182454
  for (let index = 0;index < entries.length; index++) {
181820
182455
  const entry = entries[index];
182456
+ if (!entry)
182457
+ continue;
181821
182458
  if (entry.category !== currentCategory) {
181822
182459
  currentCategory = entry.category;
181823
182460
  lengths.push(codepoints(` <${entry.category}> `));
@@ -181850,6 +182487,8 @@ function planLines(entries, roomWidth) {
181850
182487
  let currentCategory = null;
181851
182488
  for (let index = 0;index < entries.length; index++) {
181852
182489
  const entry = entries[index];
182490
+ if (!entry)
182491
+ continue;
181853
182492
  if (entry.category !== currentCategory) {
181854
182493
  currentCategory = entry.category;
181855
182494
  lines.push({
@@ -181913,8 +182552,11 @@ function renderLayout(entries, plan, roomWidth, columnCount) {
181913
182552
  const usage = {};
181914
182553
  let filledLineCount = 0;
181915
182554
  for (const [column, columnPlan] of splitPlan(plan, columnCount).entries()) {
182555
+ const columnGrid = grid[column];
182556
+ if (!columnGrid)
182557
+ continue;
181916
182558
  for (const [row, line] of columnPlan.entries()) {
181917
- grid[column][row] = line.text;
182559
+ columnGrid[row] = line.text;
181918
182560
  filledLineCount += 1;
181919
182561
  usage[line.category] = (usage[line.category] ?? 0) + 1;
181920
182562
  const placementLine = row + 1;
@@ -182025,6 +182667,7 @@ function glyph(character) {
182025
182667
  }
182026
182668
  function drawGlyph(pixels, width, height, x, y, character, color) {
182027
182669
  const glyphData = glyph(character);
182670
+ const [red, green, blue] = color;
182028
182671
  for (let row = 0;row < MURAL_CELL_HEIGHT; row++) {
182029
182672
  const pattern2 = glyphData.rows[row] ?? 0;
182030
182673
  for (let column = 0;column < glyphData.width; column++) {
@@ -182035,9 +182678,9 @@ function drawGlyph(pixels, width, height, x, y, character, color) {
182035
182678
  if (px < 0 || py < 0 || px >= width || py >= height)
182036
182679
  continue;
182037
182680
  const offset = (py * width + px) * 3;
182038
- pixels[offset] = color[0];
182039
- pixels[offset + 1] = color[1];
182040
- pixels[offset + 2] = color[2];
182681
+ pixels[offset] = red;
182682
+ pixels[offset + 1] = green;
182683
+ pixels[offset + 2] = blue;
182041
182684
  }
182042
182685
  }
182043
182686
  }
@@ -182049,6 +182692,7 @@ function drawText(pixels, width, height, x, y, text, color) {
182049
182692
  }
182050
182693
  }
182051
182694
  function fillRect(pixels, canvasWidth, canvasHeight, x, y, width, height, color) {
182695
+ const [red, green, blue] = color;
182052
182696
  const left = Math.max(0, x);
182053
182697
  const top = Math.max(0, y);
182054
182698
  const right = Math.min(canvasWidth, x + width);
@@ -182056,9 +182700,9 @@ function fillRect(pixels, canvasWidth, canvasHeight, x, y, width, height, color)
182056
182700
  for (let py = top;py < bottom; py++) {
182057
182701
  for (let px = left;px < right; px++) {
182058
182702
  const offset = (py * canvasWidth + px) * 3;
182059
- pixels[offset] = color[0];
182060
- pixels[offset + 1] = color[1];
182061
- pixels[offset + 2] = color[2];
182703
+ pixels[offset] = red;
182704
+ pixels[offset + 1] = green;
182705
+ pixels[offset + 2] = blue;
182062
182706
  }
182063
182707
  }
182064
182708
  }
@@ -182085,6 +182729,9 @@ function renderMural(entries) {
182085
182729
  });
182086
182730
  const fittingCandidates = candidates2.filter((candidate) => candidate.layout.droppedIds.length === 0);
182087
182731
  const candidatesToCompare = fittingCandidates.length > 0 ? fittingCandidates : candidates2;
182732
+ const firstCandidate = candidatesToCompare[0];
182733
+ if (!firstCandidate)
182734
+ throw new Error("mural layout candidate list is empty");
182088
182735
  const selected = candidatesToCompare.reduce((best, candidate) => {
182089
182736
  if (!best)
182090
182737
  return candidate;
@@ -182095,7 +182742,7 @@ function renderMural(entries) {
182095
182742
  return candidate.tileArea < best.tileArea ? candidate : best;
182096
182743
  }
182097
182744
  return candidate.requestedColumnCount < best.requestedColumnCount ? candidate : best;
182098
- }, candidatesToCompare[0]);
182745
+ }, firstCandidate);
182099
182746
  const { layout, width, height } = selected;
182100
182747
  const pixels = new Uint8Array(width * height * 3).fill(255);
182101
182748
  const contentWidth = layout.columnCount === 0 ? 0 : layout.columnCount * roomWidth * MURAL_CELL_WIDTH + MURAL_COLUMN_GAP * (layout.columnCount - 1) * MURAL_CELL_WIDTH;
@@ -183379,6 +184026,7 @@ function formatSearchResults(query, results, currentSessionId) {
183379
184026
  ${body}`;
183380
184027
  }
183381
184028
  function createCtxSearchTool(deps) {
184029
+ const resolveProject = deps.resolveProjectIdentity ?? resolveProjectIdentityForSession;
183382
184030
  return {
183383
184031
  name: "ctx_search",
183384
184032
  label: "Magic Context: Search",
@@ -183404,7 +184052,7 @@ function createCtxSearchTool(deps) {
183404
184052
  };
183405
184053
  }
183406
184054
  const sessionId = ctx.sessionManager.getSessionId();
183407
- const projectIdentity = resolveProjectIdentityForSession(ctx.cwd);
184055
+ const projectIdentity = resolveProject(ctx.cwd);
183408
184056
  if (!projectIdentity) {
183409
184057
  return {
183410
184058
  content: [
@@ -183529,12 +184177,14 @@ function createTodowriteTool() {
183529
184177
 
183530
184178
  // src/tools/index.ts
183531
184179
  function registerMagicContextTools(pi, opts) {
184180
+ const resolveProjectIdentity2 = opts.resolveProjectIdentity ? (directory) => opts.resolveProjectIdentity?.({ cwd: directory }) : undefined;
183532
184181
  pi.registerTool(createCtxSearchTool({
183533
184182
  db: opts.db,
183534
184183
  ensureProjectRegistered: opts.ensureProjectRegistered,
183535
184184
  memoryEnabled: opts.memoryEnabled,
183536
184185
  embeddingEnabled: opts.embeddingEnabled,
183537
- gitCommitsEnabled: opts.gitCommitsEnabled
184186
+ gitCommitsEnabled: opts.gitCommitsEnabled,
184187
+ resolveProjectIdentity: resolveProjectIdentity2
183538
184188
  }));
183539
184189
  if (opts.memoryToolEnabled !== false) {
183540
184190
  pi.registerTool(createCtxMemoryTool({
@@ -183542,14 +184192,16 @@ function registerMagicContextTools(pi, opts) {
183542
184192
  ensureProjectRegistered: opts.ensureProjectRegistered,
183543
184193
  memoryEnabled: opts.memoryEnabled,
183544
184194
  embeddingEnabled: opts.embeddingEnabled,
183545
- allowDreamerActions: opts.allowDreamerActions ?? false
184195
+ allowDreamerActions: opts.allowDreamerActions ?? false,
184196
+ resolveProjectIdentity: resolveProjectIdentity2
183546
184197
  }));
183547
184198
  }
183548
184199
  if (!opts.sessionScopedToolsDisabled) {
183549
184200
  pi.registerTool(createCtxNoteTool({
183550
184201
  db: opts.db,
183551
184202
  dreamerEnabled: opts.dreamerEnabled ?? false,
183552
- resolveDreamerEnabled: opts.resolveDreamerEnabled
184203
+ resolveDreamerEnabled: opts.resolveDreamerEnabled,
184204
+ resolveProjectIdentity: resolveProjectIdentity2
183553
184205
  }));
183554
184206
  pi.registerTool(createCtxExpandTool({ db: opts.db }));
183555
184207
  }
@@ -183559,7 +184211,7 @@ function registerMagicContextTools(pi, opts) {
183559
184211
  registerTodosCommand(pi);
183560
184212
  }
183561
184213
  }
183562
- if (!opts.sessionScopedToolsDisabled) {
184214
+ if (!opts.sessionScopedToolsDisabled && !opts.compactionOff) {
183563
184215
  pi.registerTool(createCtxReduceTool({
183564
184216
  db: opts.db,
183565
184217
  protectedTags: opts.protectedTags ?? 20,
@@ -183568,4 +184220,4 @@ function registerMagicContextTools(pi, opts) {
183568
184220
  }
183569
184221
  }
183570
184222
 
183571
- export { isDreamerRunnable, migrateMagicContextConfigLocations, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, Database, closeQuietly, 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, stableStringify, getSchemaFenceRejection, getDatabasePath, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, 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, 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, isSaneLimit, getSdkContextLimit, normalizeTodoStateJson, buildSyntheticTodoPart, SYNTH_USER_ID_PREFIX, resolvePiStableId, isMidTurnPi, readPiSessionMessages, findLastModelKeyFromBranch, convertEntriesToRawMessages, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, piModelRefToCanonical, resolveModelRefForPi, 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 };