@cortexkit/opencode-magic-context 0.44.2 → 0.44.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/{conflict-warning-hook-1msyvb51.js → conflict-warning-hook-hmpzxep6.js} +3 -3
  2. package/dist/{derive-budgets-gd2270s0.js → derive-budgets-vjmvh6pz.js} +3 -1
  3. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  4. package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts.map +1 -1
  5. package/dist/features/magic-context/dreamer/lease.d.ts +1 -1
  6. package/dist/features/magic-context/dreamer/lease.d.ts.map +1 -1
  7. package/dist/features/magic-context/memory/project-identity.d.ts +3 -0
  8. package/dist/features/magic-context/memory/project-identity.d.ts.map +1 -1
  9. package/dist/features/magic-context/message-index-async.d.ts +1 -1
  10. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  11. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  12. package/dist/features/magic-context/session-project-storage.d.ts +5 -5
  13. package/dist/features/magic-context/session-project-storage.d.ts.map +1 -1
  14. package/dist/features/magic-context/storage-embedding-measurements.d.ts.map +1 -1
  15. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +2 -1
  16. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  17. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/compartment-runner-types.d.ts +1 -0
  19. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  20. package/dist/hooks/magic-context/derive-budgets.d.ts +4 -0
  21. package/dist/hooks/magic-context/derive-budgets.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/lkg-persist.d.ts +1 -4
  24. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/producer-window-guard.d.ts +4 -1
  26. package/dist/hooks/magic-context/producer-window-guard.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/rust-mode-transform.d.ts +1 -0
  28. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/storage-busy-refusal.d.ts +6 -0
  30. package/dist/hooks/magic-context/storage-busy-refusal.d.ts.map +1 -1
  31. package/dist/{index-r9vkp4n9.js → index-33q7s9y2.js} +1 -1
  32. package/dist/{index-egkfvhms.js → index-4an2p8qa.js} +80 -14
  33. package/dist/{index-18tjha8g.js → index-638hf49n.js} +1 -1
  34. package/dist/{index-stb5fg12.js → index-9y5p0d50.js} +31 -1
  35. package/dist/{index-esxfcz5z.js → index-dgg5y7er.js} +1 -1
  36. package/dist/{index-3x9caerx.js → index-nf9sk8sh.js} +3 -3
  37. package/dist/{index-gtzcmv90.js → index-q5p1aqvv.js} +5 -5
  38. package/dist/{index-40s1xz22.js → index-rdsaxnf2.js} +1 -1
  39. package/dist/{index-ttdn47aq.js → index-yhm60r53.js} +134 -49
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +453 -226
  42. package/dist/plugin/dream-timer.d.ts.map +1 -1
  43. package/dist/plugin/embedding-bootstrap.d.ts.map +1 -1
  44. package/dist/plugin/messages-transform.d.ts.map +1 -1
  45. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  46. package/dist/{read-session-chunk-wmvgnd24.js → read-session-chunk-n072mcq4.js} +2 -2
  47. package/dist/{recomp-orchestrator-rk40ff15.js → recomp-orchestrator-19tr6zya.js} +6 -6
  48. package/dist/{send-session-notification-6xsrcxnp.js → send-session-notification-04hvd54c.js} +2 -2
  49. package/dist/shared/run-token-log.d.ts +13 -0
  50. package/dist/shared/run-token-log.d.ts.map +1 -0
  51. package/dist/shared/sqlite.d.ts +7 -0
  52. package/dist/shared/sqlite.d.ts.map +1 -1
  53. package/dist/{transform-postprocess-phase-t7xgdhdf.js → transform-postprocess-phase-z2mfc5w1.js} +6 -6
  54. package/dist/v2/hidden-completion.d.ts +7 -1
  55. package/dist/v2/hidden-completion.d.ts.map +1 -1
  56. package/dist/v2/hooks/context.d.ts.map +1 -1
  57. package/dist/v2/hooks/hidden-terminal-error.d.ts +8 -0
  58. package/dist/v2/hooks/hidden-terminal-error.d.ts.map +1 -0
  59. package/dist/v2/hooks/tools.d.ts +1 -1
  60. package/dist/v2/hooks/tools.d.ts.map +1 -1
  61. package/dist/v2/server.js +584 -153
  62. package/dist/{wrapup-orchestrator-h8tr10c6.js → wrapup-orchestrator-sy4m56a7.js} +7 -7
  63. package/package.json +1 -1
  64. package/src/config/latch-permanence-guard.test.ts +4 -0
  65. package/src/shared/data-path.test.ts +1 -1
  66. package/src/shared/models-dev-cache.test.ts +30 -1
  67. package/src/shared/run-token-log.test.ts +65 -0
  68. package/src/shared/run-token-log.ts +39 -0
  69. package/src/shared/sqlite-acquisition-routing.test.ts +19 -11
  70. package/src/shared/sqlite-pass-scope.test.ts +115 -144
  71. package/src/shared/sqlite.ts +123 -20
  72. package/src/shared/storage-busy.test.ts +34 -57
  73. package/src/shared/write-transaction-attribution.test.ts +13 -11
package/dist/v2/server.js CHANGED
@@ -2901,6 +2901,21 @@ function getSdkOutputLimit(providerID, modelID) {
2901
2901
  loadPersistedApiCacheOnce();
2902
2902
  return lookupMetadataWithTagFallback(apiCache, providerID, modelID)?.outputLimit;
2903
2903
  }
2904
+ function getSdkInputLimit(providerID, modelID) {
2905
+ loadPersistedApiCacheOnce();
2906
+ if (!apiCache)
2907
+ return;
2908
+ const direct = apiCache.get(`${providerID}/${modelID}`)?.inputLimit;
2909
+ if (isSaneLimit(direct))
2910
+ return direct;
2911
+ const colon = modelID.indexOf(":");
2912
+ if (colon > 0) {
2913
+ const tagless = apiCache.get(`${providerID}/${modelID.slice(0, colon)}`)?.inputLimit;
2914
+ if (isSaneLimit(tagless))
2915
+ return tagless;
2916
+ }
2917
+ return;
2918
+ }
2904
2919
  function lookupMetadataWithTagFallback(cache, providerID, modelID) {
2905
2920
  if (!cache)
2906
2921
  return;
@@ -11660,6 +11675,23 @@ import { createHash as createHash3 } from "node:crypto";
11660
11675
  import { existsSync as existsSync6, realpathSync, statSync as statSync4 } from "node:fs";
11661
11676
  import { homedir as homedir6 } from "node:os";
11662
11677
  import path4 from "node:path";
11678
+ function setHomeProjectPermission(allowed) {
11679
+ homeProjectPermission = allowed;
11680
+ }
11681
+ function shouldSkipHomeProjectMemory(directory) {
11682
+ try {
11683
+ assertProjectAllowed(directory, homeProjectPermission);
11684
+ return false;
11685
+ } catch (error) {
11686
+ if (!(error instanceof ProjectIdentityError) || error.errorClass !== "home_project_disabled")
11687
+ throw error;
11688
+ if (!homeProjectSkipLogged) {
11689
+ homeProjectSkipLogged = true;
11690
+ log("[magic-context] home project memory disabled; skipping memory features");
11691
+ }
11692
+ return true;
11693
+ }
11694
+ }
11663
11695
  function asError(error) {
11664
11696
  return error instanceof Error ? error : undefined;
11665
11697
  }
@@ -11743,7 +11775,7 @@ function classifyGitError(error, rawDirectory) {
11743
11775
  }
11744
11776
  return new ProjectIdentityError("unknown", rawDirectory, "git rev-list failed while resolving project identity", asError(error));
11745
11777
  }
11746
- function resolveProjectIdentityStrict(directory, allowHomeProject = false) {
11778
+ function resolveProjectIdentityStrict(directory, allowHomeProject = homeProjectPermission) {
11747
11779
  assertProjectAllowed(directory, allowHomeProject);
11748
11780
  const canonical = path4.resolve(directory);
11749
11781
  const cached = identityCache.get(canonical);
@@ -11880,7 +11912,7 @@ function assertProjectAllowed(directory, allowHomeProject) {
11880
11912
  throw new ProjectIdentityError("home_project_disabled", directory, "Home project memory is disabled; set allow_home_project to opt in");
11881
11913
  }
11882
11914
  }
11883
- function resolveProjectIdentity(directory, allowHomeProject = false) {
11915
+ function resolveProjectIdentity(directory, allowHomeProject = homeProjectPermission) {
11884
11916
  assertProjectAllowed(directory, allowHomeProject);
11885
11917
  const canonical = path4.resolve(directory);
11886
11918
  const cachedFallback = directoryFallbackCache.get(canonical);
@@ -11926,7 +11958,7 @@ function resolveProjectIdentity(directory, allowHomeProject = false) {
11926
11958
  throw error;
11927
11959
  }
11928
11960
  }
11929
- function resolveProjectIdentityOrFallback(directory, allowHomeProject = false) {
11961
+ function resolveProjectIdentityOrFallback(directory, allowHomeProject = homeProjectPermission) {
11930
11962
  try {
11931
11963
  return resolveProjectIdentity(directory, allowHomeProject);
11932
11964
  } catch (error) {
@@ -12004,7 +12036,7 @@ function describeUnresolvedProjectIdentity(directory) {
12004
12036
  function isUsableProjectIdentity(identity) {
12005
12037
  return typeof identity === "string" && identity.trim().length > 0;
12006
12038
  }
12007
- function resolveProjectIdentityForSession(directory, allowHomeProject = false) {
12039
+ function resolveProjectIdentityForSession(directory, allowHomeProject = homeProjectPermission) {
12008
12040
  const resolvedDirectory = path4.resolve(directory);
12009
12041
  const cacheKey = `${allowHomeProject ? "1" : "0"}\x00${resolvedDirectory}`;
12010
12042
  const cached = sessionIdentityCache.get(cacheKey);
@@ -12076,7 +12108,7 @@ function isLinkedGitWorktree(directory) {
12076
12108
  linkedGitWorktreeCache.set(resolvedDirectory, linked);
12077
12109
  return linked;
12078
12110
  }
12079
- var GIT_TIMEOUT_MS = 5000, TRANSIENT_FAILURE_COOLDOWN_MS, identityCache, linkedGitWorktreeCache, lastKnownGitIdentityCache, directoryFallbackCache, transientFailureCooldown, dubiousOwnershipFallbackDirectories, dubiousOwnershipLoggedDirectories, dubiousOwnershipWarnedDirectories, transientGitIdentityReuseLoggedDirectories, sessionIdentityCache, execFileSyncForIdentity, userHomeDirectoryForIdentity = () => homedir6(), nowMs = () => Date.now(), filesystemProbeObserverForTests, ProjectIdentityError;
12111
+ var GIT_TIMEOUT_MS = 5000, TRANSIENT_FAILURE_COOLDOWN_MS, identityCache, linkedGitWorktreeCache, lastKnownGitIdentityCache, directoryFallbackCache, transientFailureCooldown, dubiousOwnershipFallbackDirectories, dubiousOwnershipLoggedDirectories, dubiousOwnershipWarnedDirectories, transientGitIdentityReuseLoggedDirectories, sessionIdentityCache, homeProjectPermission = false, homeProjectSkipLogged = false, execFileSyncForIdentity, userHomeDirectoryForIdentity = () => homedir6(), nowMs = () => Date.now(), filesystemProbeObserverForTests, ProjectIdentityError;
12080
12112
  var init_project_identity = __esm(() => {
12081
12113
  init_logger();
12082
12114
  init_project_identity_cache();
@@ -17362,7 +17394,10 @@ function installTransactionRouting(db, readonly) {
17362
17394
  writable: true,
17363
17395
  value: (sql) => {
17364
17396
  if (/^\s*BEGIN\s+(?:IMMEDIATE|EXCLUSIVE)(?:\s+TRANSACTION)?\s*;?\s*$/i.test(sql)) {
17365
- retryAcquisition(() => nativeExec(sql), sql.trim());
17397
+ if (transformPassScope.getStore()?.active || backgroundWriterScope.getStore())
17398
+ acquireShort(db, () => nativeExec(sql), sql.trim());
17399
+ else
17400
+ nativeExec(sql);
17366
17401
  return db;
17367
17402
  }
17368
17403
  return nativeExec(sql);
@@ -17537,6 +17572,9 @@ function getSqliteMemoryStats() {
17537
17572
  connections
17538
17573
  };
17539
17574
  }
17575
+ function withSqliteBackgroundWriter(operation) {
17576
+ return backgroundWriterScope.run(true, operation);
17577
+ }
17540
17578
  function withSqliteTransformPass(operation) {
17541
17579
  const lease = { active: true };
17542
17580
  return transformPassScope.run(lease, () => {
@@ -17564,22 +17602,71 @@ function isTransientSqliteError(error) {
17564
17602
  const value = error;
17565
17603
  return typeof value.code === "string" && /^(SQLITE_BUSY|SQLITE_LOCKED)(_|$)/.test(value.code) || typeof value.errcode === "number" && [5, 6].includes(value.errcode & 255);
17566
17604
  }
17567
- function retryAcquisition(acquire, stage) {
17568
- if (!transformPassScope.getStore()?.active) {
17605
+ function acquireShort(db, acquire, site) {
17606
+ const started = performance.now();
17607
+ const previous = pragmaNumber(db, "busy_timeout");
17608
+ let acquired = false;
17609
+ try {
17610
+ const timeout = transformPassScope.getStore()?.active && !admissionScope.getStore() && !backgroundWriterScope.getStore() ? FOREGROUND_IN_PASS_BUSY_TIMEOUT_MS : SHORT_BUSY_TIMEOUT_MS;
17611
+ db.exec(`PRAGMA busy_timeout=${timeout}`);
17569
17612
  acquire();
17570
- return;
17613
+ acquired = true;
17614
+ } catch (error) {
17615
+ if (transformPassScope.getStore()?.active && isTransientSqliteError(error))
17616
+ throw new SqliteAcquisitionBusyError(error, site);
17617
+ throw error;
17618
+ } finally {
17619
+ if (previous !== null)
17620
+ db.exec(`PRAGMA busy_timeout=${previous}`);
17621
+ const elapsed = performance.now() - started;
17622
+ if (elapsed >= 250)
17623
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=${site} lane=${transformPassScope.getStore()?.active ? "foreground" : "background"} elapsed=${Math.round(elapsed)}ms attempts=1 outcome=${acquired ? "acquired" : "busy"}`);
17571
17624
  }
17572
- const delays = [500, 1000];
17573
- for (let attempt = 0;; attempt++) {
17625
+ }
17626
+ async function beginSqliteWriterAsync(db, site) {
17627
+ const started = performance.now();
17628
+ let attempts = 0;
17629
+ for (;; ) {
17630
+ attempts++;
17574
17631
  try {
17575
- acquire();
17632
+ withSqliteBackgroundWriter(() => db.exec("BEGIN IMMEDIATE"));
17633
+ const elapsed = performance.now() - started;
17634
+ if (elapsed >= 250)
17635
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=${site} lane=background elapsed=${Math.round(elapsed)}ms attempts=${attempts} outcome=acquired`);
17576
17636
  return;
17577
17637
  } catch (error) {
17578
- if (error instanceof SqliteAcquisitionBusyError || !isTransientSqliteError(error))
17638
+ if (!isTransientSqliteError(error))
17639
+ throw error;
17640
+ const elapsed = performance.now() - started;
17641
+ if (elapsed >= FOREGROUND_ACQUISITION_BUDGET_MS) {
17642
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=${site} lane=background elapsed=${Math.round(elapsed)}ms attempts=${attempts} outcome=busy`);
17643
+ throw error;
17644
+ }
17645
+ await new Promise((resolve) => setTimeout(resolve, Math.min(attempts === 1 ? 500 : 1000, FOREGROUND_ACQUISITION_BUDGET_MS - elapsed)));
17646
+ }
17647
+ }
17648
+ }
17649
+ async function withAsyncPrivilegedWriter(db, operation) {
17650
+ const started = performance.now();
17651
+ let attempts = 0;
17652
+ for (;; ) {
17653
+ attempts++;
17654
+ try {
17655
+ const result = admissionScope.run(true, () => withSqliteTransformPass(() => withPrivilegedWriter(db, operation)));
17656
+ const elapsed = performance.now() - started;
17657
+ if (elapsed >= 250)
17658
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=privileged_writer lane=foreground elapsed=${Math.round(elapsed)}ms attempts=${attempts} outcome=acquired`);
17659
+ return result;
17660
+ } catch (error) {
17661
+ if (!(error instanceof SqliteAcquisitionBusyError))
17579
17662
  throw error;
17580
- if (attempt === delays.length)
17581
- throw new SqliteAcquisitionBusyError(error, stage);
17582
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delays[attempt]);
17663
+ const elapsed = performance.now() - started;
17664
+ if (elapsed >= FOREGROUND_ACQUISITION_BUDGET_MS) {
17665
+ if (elapsed >= 250)
17666
+ console.warn(`[${new Date().toISOString()}] [magic-context] sqlite acquisition site=privileged_writer lane=foreground elapsed=${Math.round(elapsed)}ms attempts=${attempts} outcome=busy`);
17667
+ throw error instanceof SqliteAcquisitionBusyError ? error : new SqliteAcquisitionBusyError(error);
17668
+ }
17669
+ await new Promise((resolve) => setTimeout(resolve, Math.min(attempts === 1 ? 500 : 1000, FOREGROUND_ACQUISITION_BUDGET_MS - elapsed)));
17583
17670
  }
17584
17671
  }
17585
17672
  }
@@ -17595,7 +17682,13 @@ function withPrivilegedWriter(db, operation) {
17595
17682
  if (nested) {
17596
17683
  db.exec(`SAVEPOINT ${savepoint}`);
17597
17684
  } else {
17598
- retryAcquisition(() => db.exec("BEGIN IMMEDIATE"), "BEGIN IMMEDIATE");
17685
+ try {
17686
+ db.exec("BEGIN IMMEDIATE");
17687
+ } catch (error) {
17688
+ if (transformPassScope.getStore()?.active && isTransientSqliteError(error))
17689
+ throw new SqliteAcquisitionBusyError(error);
17690
+ throw error;
17691
+ }
17599
17692
  }
17600
17693
  privilegeDepth.set(db, previousDepth + 1);
17601
17694
  try {
@@ -17634,7 +17727,7 @@ function withPrivilegedWriter(db, operation) {
17634
17727
  throw error;
17635
17728
  }
17636
17729
  }
17637
- var reportSlowPrivilegedWrite, bunSpec, nodeSpec, SqliteRuntimeUnavailableError, detectedRuntime, isBun, sqliteModule, DatabaseImpl, trackedSqliteConnections, nextSqliteConnectionSequence = 1, TrackedDatabase, Database, privilegeDepth, transformPassScope, SqliteAcquisitionBusyError;
17730
+ var reportSlowPrivilegedWrite, bunSpec, nodeSpec, SqliteRuntimeUnavailableError, detectedRuntime, isBun, sqliteModule, DatabaseImpl, trackedSqliteConnections, nextSqliteConnectionSequence = 1, TrackedDatabase, Database, privilegeDepth, transformPassScope, admissionScope, backgroundWriterScope, SqliteAcquisitionBusyError, SHORT_BUSY_TIMEOUT_MS = 25, FOREGROUND_IN_PASS_BUSY_TIMEOUT_MS = 250, FOREGROUND_ACQUISITION_BUDGET_MS = 16500;
17638
17731
  var init_sqlite = __esm(async () => {
17639
17732
  bunSpec = "bun:" + "sqlite";
17640
17733
  nodeSpec = "node:" + "sqlite";
@@ -17663,11 +17756,13 @@ var init_sqlite = __esm(async () => {
17663
17756
  Database = TrackedDatabase;
17664
17757
  privilegeDepth = new WeakMap;
17665
17758
  transformPassScope = new AsyncLocalStorage;
17759
+ admissionScope = new AsyncLocalStorage;
17760
+ backgroundWriterScope = new AsyncLocalStorage;
17666
17761
  SqliteAcquisitionBusyError = class SqliteAcquisitionBusyError extends Error {
17667
17762
  code = "SQLITE_BUSY";
17668
17763
  stage;
17669
17764
  constructor(cause, stage = "BEGIN IMMEDIATE") {
17670
- super("SQLite writer acquisition remained busy after 3 attempts", { cause });
17765
+ super("SQLite writer acquisition remained busy", { cause });
17671
17766
  this.name = "SqliteAcquisitionBusyError";
17672
17767
  this.stage = stage;
17673
17768
  }
@@ -34390,7 +34485,12 @@ function pruneSynapseBatchLedgerForProject(db, projectIdentity, ttlMs = SYNAPSE_
34390
34485
  const ledgerTable = db.prepare("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'synapse_batch_ledger'").get();
34391
34486
  if (!ledgerTable)
34392
34487
  return 0;
34393
- return db.prepare("DELETE FROM synapse_batch_ledger WHERE session_id IN (?, ?) AND updated_at < ?").run(projectIdentity, `shadow:${projectIdentity}`, Date.now() - ttlMs).changes;
34488
+ const shadow = `shadow:${projectIdentity}`;
34489
+ const cutoff = Date.now() - ttlMs;
34490
+ const predicate = "session_id IN (?, ?) AND updated_at < ?";
34491
+ if (!db.prepare(`SELECT 1 FROM synapse_batch_ledger WHERE ${predicate} LIMIT 1`).get(projectIdentity, shadow, cutoff))
34492
+ return 0;
34493
+ return db.prepare(`DELETE FROM synapse_batch_ledger WHERE ${predicate}`).run(projectIdentity, shadow, cutoff).changes;
34394
34494
  }
34395
34495
  var MEASUREMENT_CORPUS_SESSION_ROW_CAP = 2000, SYNAPSE_BATCH_LEDGER_TTL_MS;
34396
34496
  var init_storage_embedding_measurements = __esm(() => {
@@ -36219,6 +36319,21 @@ function resolveKnownHistorianContextLimit(historianModelOverride) {
36219
36319
  const limit = getSdkContextLimit(providerID, modelID, undefined, { reservation: "none" });
36220
36320
  return typeof limit === "number" && limit > 0 ? limit : undefined;
36221
36321
  }
36322
+ function resolveHistorianProducerLimits(modelKey) {
36323
+ if (!modelKey?.includes("/"))
36324
+ return {};
36325
+ const [provider, ...parts] = modelKey.split("/");
36326
+ const model = parts.join("/");
36327
+ if (!provider || !model)
36328
+ return {};
36329
+ const input = getSdkInputLimit(provider, model);
36330
+ const window2 = getSdkWindowGeometry(provider, model)?.derivation.window;
36331
+ const context = window2 ?? (input === undefined ? resolveKnownHistorianContextLimit(modelKey) : undefined);
36332
+ return {
36333
+ ...context !== undefined ? { context } : {},
36334
+ ...input !== undefined ? { input } : {}
36335
+ };
36336
+ }
36222
36337
  function resolveHistorianContextLimit(historianModelOverride) {
36223
36338
  if (typeof historianModelOverride === "string" && historianModelOverride.includes("/")) {
36224
36339
  return resolveKnownHistorianContextLimit(historianModelOverride) ?? DEFAULT_HISTORIAN_CONTEXT_FALLBACK;
@@ -74831,6 +74946,14 @@ var init_embedding_cache = __esm(() => {
74831
74946
  });
74832
74947
 
74833
74948
  // src/features/magic-context/session-project-storage.ts
74949
+ function hasMisScopedCompartmentChunkEmbeddingsForProject(db, projectPath) {
74950
+ let stmt = misScopedProjectChunkStatements.get(db);
74951
+ if (!stmt) {
74952
+ stmt = db.prepare(`SELECT 1 FROM (${MIS_SCOPED_PROJECT_CHUNK_IDS_SQL}) LIMIT 1`);
74953
+ misScopedProjectChunkStatements.set(db, stmt);
74954
+ }
74955
+ return !!stmt.get(projectPath, projectPath);
74956
+ }
74834
74957
  function getUpsertSessionProjectStatement(db) {
74835
74958
  let stmt = upsertSessionProjectStatements.get(db);
74836
74959
  if (!stmt) {
@@ -74866,23 +74989,11 @@ function getRepairProjectChunkProjectStatement(db) {
74866
74989
  if (!stmt) {
74867
74990
  stmt = db.prepare(`UPDATE compartment_chunk_embeddings
74868
74991
  SET project_path = (
74869
- SELECT sp.project_path
74870
- FROM session_projects sp
74992
+ SELECT sp.project_path FROM session_projects sp
74871
74993
  WHERE sp.session_id = compartment_chunk_embeddings.session_id
74872
74994
  AND sp.harness = compartment_chunk_embeddings.harness
74873
- LIMIT 1
74874
74995
  )
74875
- WHERE EXISTS (
74876
- SELECT 1
74877
- FROM session_projects sp
74878
- WHERE sp.session_id = compartment_chunk_embeddings.session_id
74879
- AND sp.harness = compartment_chunk_embeddings.harness
74880
- AND sp.project_path <> compartment_chunk_embeddings.project_path
74881
- AND (
74882
- sp.project_path = ?
74883
- OR compartment_chunk_embeddings.project_path = ?
74884
- )
74885
- )`);
74996
+ WHERE id IN (${MIS_SCOPED_PROJECT_CHUNK_IDS_SQL})`);
74886
74997
  repairProjectChunkProjectStatements.set(db, stmt);
74887
74998
  }
74888
74999
  return stmt;
@@ -74902,14 +75013,24 @@ function recordSessionProjectIdentity(db, sessionId, projectPath) {
74902
75013
  function repairMisScopedCompartmentChunkEmbeddingsForProject(db, projectPath) {
74903
75014
  if (!projectPath)
74904
75015
  return 0;
75016
+ if (!hasMisScopedCompartmentChunkEmbeddingsForProject(db, projectPath))
75017
+ return 0;
74905
75018
  return getRepairProjectChunkProjectStatement(db).run(projectPath, projectPath).changes;
74906
75019
  }
74907
- var SESSION_CHUNK_REPAIR_BATCH_SIZE = 100, upsertSessionProjectStatements, repairSessionChunkProjectStatements, repairProjectChunkProjectStatements;
75020
+ var SESSION_CHUNK_REPAIR_BATCH_SIZE = 100, upsertSessionProjectStatements, repairSessionChunkProjectStatements, repairProjectChunkProjectStatements, misScopedProjectChunkStatements, MIS_SCOPED_PROJECT_CHUNK_IDS_SQL = `
75021
+ SELECT e.id FROM compartment_chunk_embeddings e
75022
+ JOIN session_projects sp ON sp.session_id = e.session_id AND sp.harness = e.harness
75023
+ WHERE e.project_path = ? AND sp.project_path <> e.project_path
75024
+ UNION ALL
75025
+ SELECT e.id FROM session_projects sp
75026
+ JOIN compartment_chunk_embeddings e ON e.session_id = sp.session_id
75027
+ WHERE sp.project_path = ? AND e.harness = sp.harness AND e.project_path <> sp.project_path`;
74908
75028
  var init_session_project_storage = __esm(() => {
74909
75029
  init_project_identity();
74910
75030
  upsertSessionProjectStatements = new WeakMap;
74911
75031
  repairSessionChunkProjectStatements = new WeakMap;
74912
75032
  repairProjectChunkProjectStatements = new WeakMap;
75033
+ misScopedProjectChunkStatements = new WeakMap;
74913
75034
  });
74914
75035
 
74915
75036
  // src/features/magic-context/shadow-backfill-state.ts
@@ -75338,6 +75459,14 @@ function recordActiveEmbeddingIdentity(db, projectIdentity, currentProviderIdent
75338
75459
  if (currentProviderIdentity === OFF_PROVIDER_IDENTITY) {
75339
75460
  return;
75340
75461
  }
75462
+ const scopes = [["chunk", currentChunkIdentity]];
75463
+ if (features.memoryEnabled)
75464
+ scopes.push(["memory", currentProviderIdentity]);
75465
+ if (features.gitCommitEnabled)
75466
+ scopes.push(["commit", currentProviderIdentity]);
75467
+ const active = db.prepare("SELECT 1 FROM embedding_identity_active WHERE project_path = ? AND scope = ? AND model_id = ?");
75468
+ if (scopes.every(([scope, model]) => active.get(projectIdentity, scope, model)) && !hasMisScopedCompartmentChunkEmbeddingsForProject(db, projectIdentity))
75469
+ return;
75341
75470
  const now = Date.now();
75342
75471
  const transactionStartedAt = performance.now();
75343
75472
  db.exec("BEGIN IMMEDIATE");
@@ -75385,7 +75514,9 @@ function registerProjectEmbedding(db, projectIdentity, config, features, sourceD
75385
75514
  observationMode: false
75386
75515
  };
75387
75516
  projectRegistrations.set(projectIdentity, registration);
75388
- persistPrimaryDescriptor(db, registration);
75517
+ if (generationChanged || !db.prepare("SELECT 1 FROM embedding_registrations WHERE project_path = ? AND provider_identity = ? AND chunk_model_id = ? AND generation = ?").get(projectIdentity, providerIdentity, registration.chunkModelId, generation)) {
75518
+ persistPrimaryDescriptor(db, registration);
75519
+ }
75389
75520
  if (!canReuseProvider) {
75390
75521
  disposeProvider(prior?.provider ?? null);
75391
75522
  }
@@ -81925,6 +82056,27 @@ async function teardownChildSession(args) {
81925
82056
  }
81926
82057
  var init_child_session_teardown = () => {};
81927
82058
 
82059
+ // src/shared/run-token-log.ts
82060
+ function count2(value) {
82061
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
82062
+ }
82063
+ function runTokenLog(tokens, maxTokens, finish) {
82064
+ const usage = tokens && typeof tokens === "object" ? tokens : {};
82065
+ const cache = usage.cache && typeof usage.cache === "object" ? usage.cache : {};
82066
+ return {
82067
+ input: count2(usage.input ?? usage.input_tokens),
82068
+ output: count2(usage.output ?? usage.output_tokens),
82069
+ reasoning: count2(usage.reasoning ?? usage.reasoning_tokens),
82070
+ cache_read: count2(usage.cacheRead ?? usage.cache_read ?? usage.cached_input_tokens ?? cache.read),
82071
+ cache_write: count2(usage.cacheWrite ?? usage.cache_write ?? usage.cache_write_tokens ?? cache.write),
82072
+ max_tokens: count2(maxTokens),
82073
+ finish_reason: typeof finish === "string" ? finish : null
82074
+ };
82075
+ }
82076
+ function formatRunTokenLog(tokens) {
82077
+ return `tokens=${JSON.stringify(tokens)}`;
82078
+ }
82079
+
81928
82080
  // src/features/magic-context/schema-fence-probe.ts
81929
82081
  function recordStaleFence(persistedVersion, supportedVersion, reason = "newer_schema") {
81930
82082
  state.consecutiveFailures += 1;
@@ -82314,11 +82466,14 @@ function clampProducerAtomChars(text, maxChars, marker) {
82314
82466
  const tailChars = Math.floor(keptChars / 2);
82315
82467
  return `${text.slice(0, headChars)}${marker}${text.slice(text.length - tailChars)}`;
82316
82468
  }
82317
- function producerInputTokenLimit(contextLimitTokens, maxOutputTokens) {
82318
- if (typeof contextLimitTokens !== "number" || !Number.isFinite(contextLimitTokens) || contextLimitTokens <= 0 || !Number.isFinite(maxOutputTokens) || maxOutputTokens < 0) {
82469
+ function producerInputTokenLimit(contextLimitTokens, maxOutputTokens, inputLimitTokens) {
82470
+ if (!Number.isFinite(maxOutputTokens) || maxOutputTokens < 0)
82319
82471
  return;
82320
- }
82321
- const usableInputTokens = Math.floor(contextLimitTokens - maxOutputTokens);
82472
+ const shared = typeof contextLimitTokens === "number" && Number.isFinite(contextLimitTokens) && contextLimitTokens > 0 ? contextLimitTokens - maxOutputTokens : undefined;
82473
+ const input = typeof inputLimitTokens === "number" && Number.isFinite(inputLimitTokens) && inputLimitTokens > 0 ? inputLimitTokens : undefined;
82474
+ if (shared === undefined && input === undefined)
82475
+ return;
82476
+ const usableInputTokens = Math.floor(Math.min(shared ?? Infinity, input ?? Infinity));
82322
82477
  if (usableInputTokens <= 0)
82323
82478
  return;
82324
82479
  const limit = Math.floor(usableInputTokens * (1 - PRODUCER_WINDOW_REFUSAL_MARGIN));
@@ -82330,15 +82485,15 @@ function historianProducerReserve(window2, configuredOutput, catalogOutput) {
82330
82485
  return window2 === undefined ? 0 : catalogOutputReserve(window2, catalogOutput);
82331
82486
  }
82332
82487
  function producerWindowFailureReason(input) {
82333
- const { producerSourceTokens, contextLimitTokens, maxOutputTokens } = input;
82334
- const producerInputLimitTokens = producerInputTokenLimit(contextLimitTokens, maxOutputTokens);
82335
- if (producerInputLimitTokens === undefined || typeof contextLimitTokens !== "number" || !Number.isFinite(producerSourceTokens) || producerSourceTokens <= 0) {
82488
+ const { producerSourceTokens, contextLimitTokens, inputLimitTokens, maxOutputTokens } = input;
82489
+ const producerInputLimitTokens = producerInputTokenLimit(contextLimitTokens, maxOutputTokens, inputLimitTokens);
82490
+ if (producerInputLimitTokens === undefined || !Number.isFinite(producerSourceTokens) || producerSourceTokens <= 0) {
82336
82491
  return null;
82337
82492
  }
82338
- const usableInputTokens = Math.max(0, Math.floor(contextLimitTokens - maxOutputTokens));
82493
+ const usableInputTokens = Math.floor(Math.min(contextLimitTokens === undefined ? Infinity : Math.max(0, contextLimitTokens - maxOutputTokens), inputLimitTokens ?? Infinity));
82339
82494
  if (producerSourceTokens <= producerInputLimitTokens)
82340
82495
  return null;
82341
- return `producer_source_exceeds_window producer_source_tokens=${Math.round(producerSourceTokens)} usable_input_tokens=${usableInputTokens} producer_input_limit_tokens=${producerInputLimitTokens} context_limit_tokens=${Math.round(contextLimitTokens)} max_output_tokens=${Math.round(maxOutputTokens)} estimator_margin=${PRODUCER_WINDOW_REFUSAL_MARGIN}`;
82496
+ return `producer_source_exceeds_window producer_source_tokens=${Math.round(producerSourceTokens)} usable_input_tokens=${usableInputTokens} producer_input_limit_tokens=${producerInputLimitTokens} context_limit_tokens=${contextLimitTokens === undefined ? "unknown" : Math.round(contextLimitTokens)} max_output_tokens=${Math.round(maxOutputTokens)} estimator_margin=${PRODUCER_WINDOW_REFUSAL_MARGIN}`;
82342
82497
  }
82343
82498
  function splitMarkerPair() {
82344
82499
  return `
@@ -82347,7 +82502,7 @@ ${HISTORIAN_TRUNCATION_MARKER}
82347
82502
  `;
82348
82503
  }
82349
82504
  function fitAtomicHistorianSourceToProducerWindow(args) {
82350
- const producerInputLimitTokens = producerInputTokenLimit(args.contextLimitTokens, args.maxOutputTokens);
82505
+ const producerInputLimitTokens = producerInputTokenLimit(args.contextLimitTokens, args.maxOutputTokens, args.inputLimitTokens);
82351
82506
  const originalTokens = estimateTokens(args.text);
82352
82507
  if (producerInputLimitTokens === undefined || originalTokens < producerInputLimitTokens || producerInputLimitTokens <= 0) {
82353
82508
  return { text: args.text, producerInputLimitTokens, removedTokens: 0 };
@@ -82381,7 +82536,7 @@ function fitAtomicHistorianSourceToProducerWindow(args) {
82381
82536
  };
82382
82537
  }
82383
82538
  function producerPromptFailureReason(input) {
82384
- const limit = producerInputTokenLimit(input.contextLimitTokens, input.maxOutputTokens);
82539
+ const limit = producerInputTokenLimit(input.contextLimitTokens, input.maxOutputTokens, input.inputLimitTokens);
82385
82540
  const tokens = providerMass({ prose: input.sourceLocal, system: input.systemLocal, tools: input.toolsLocal }, calibrationForModelKey(input.modelKey), true);
82386
82541
  if (limit === undefined)
82387
82542
  return null;
@@ -82497,12 +82652,15 @@ function createV1HiddenCompletionExecutor(client, db, directory) {
82497
82652
  throw new Error(`Historian host recorded an assistant error${finish}: ${describeAssistantFailure(assistantFailure.error)}`);
82498
82653
  }
82499
82654
  const text = extractLatestAssistantText(messages);
82655
+ const latest = Array.isArray(messages) ? messages.filter((message) => isRecord3(message) && isRecord3(message.info) && message.info.role === "assistant").sort((left, right) => historianMessageCreatedAt(right) - historianMessageCreatedAt(left))[0] : undefined;
82656
+ const info = latest && isRecord3(latest.info) ? latest.info : {};
82500
82657
  return {
82501
82658
  messages,
82502
82659
  text,
82503
82660
  reasoning: text ? null : extractLatestHistorianReasoning(messages),
82504
82661
  lengthCapped: hasLengthCappedOutput(messages),
82505
- usage: sumTokensFromChildMessages(messages)
82662
+ usage: sumTokensFromChildMessages(messages),
82663
+ tokenLog: runTokenLog(info.tokens, undefined, info.finish ?? info.finish_reason ?? info.finishReason)
82506
82664
  };
82507
82665
  },
82508
82666
  async close(handle, settlement) {
@@ -82521,8 +82679,8 @@ function createV1HiddenCompletionExecutor(client, db, directory) {
82521
82679
  }
82522
82680
  };
82523
82681
  }
82524
- function historianReasoningBudgetDiagnostic(outputTokens) {
82525
- return `historian ran out of output budget while reasoning (length-capped at ${outputTokens} tokens, no text) — set historian.maxTokens or route historian.model to a low-reasoning lane/variant`;
82682
+ function historianReasoningBudgetDiagnostic(outputTokens, tokens) {
82683
+ return `historian ran out of output budget while reasoning (length-capped at ${outputTokens} tokens, no text${tokens ? `; ${formatRunTokenLog(tokens)}` : ""}) — set historian.maxTokens or route historian.model to a low-reasoning lane/variant`;
82526
82684
  }
82527
82685
  async function runValidatedHistorianPass(args) {
82528
82686
  const firstRun = await runHistorianPrompt({
@@ -82711,8 +82869,10 @@ async function runHistorianPrompt(args) {
82711
82869
  const modelKey = selected ? `${selected.providerID}/${selected.modelID}` : undefined;
82712
82870
  const system = withContentLanguageDirective(agentId === HISTORIAN_EDITOR_AGENT ? HISTORIAN_EDITOR_SYSTEM_PROMPT : COMPARTMENT_AGENT_SYSTEM_PROMPT, args.language);
82713
82871
  const contextLimitTokens = selected ? getSdkContextLimit(selected.providerID, selected.modelID, undefined, { reservation: "none" }) : undefined;
82714
- const reserve = historianProducerReserve(contextLimitTokens, args.maxOutputTokens, selected ? getSdkOutputLimit(selected.providerID, selected.modelID) : undefined);
82715
- if (contextLimitTokens !== undefined && producerInputTokenLimit(contextLimitTokens, reserve) === undefined && modelKey && !unknownProducerWindows.has(modelKey)) {
82872
+ const producerLimits = selected ? resolveHistorianProducerLimits(modelKey) : {};
82873
+ const producerContext = producerLimits.context ?? (producerLimits.input === undefined ? contextLimitTokens : undefined);
82874
+ const reserve = historianProducerReserve(producerContext, args.maxOutputTokens, selected ? getSdkOutputLimit(selected.providerID, selected.modelID) : undefined);
82875
+ if (contextLimitTokens !== undefined && producerInputTokenLimit(producerContext, reserve, producerLimits.input) === undefined && modelKey && !unknownProducerWindows.has(modelKey)) {
82716
82876
  unknownProducerWindows.add(modelKey);
82717
82877
  sessionLog(parentSessionId, `producer window inconsistent for ${modelKey}: window=${contextLimitTokens} reserve=${reserve}; sending unguarded`);
82718
82878
  }
@@ -82721,7 +82881,8 @@ async function runHistorianPrompt(args) {
82721
82881
  systemLocal: estimateTokens(system),
82722
82882
  toolsLocal: 0,
82723
82883
  modelKey,
82724
- contextLimitTokens,
82884
+ contextLimitTokens: producerContext,
82885
+ inputLimitTokens: producerLimits.input,
82725
82886
  maxOutputTokens: reserve
82726
82887
  });
82727
82888
  if (failure)
@@ -82755,9 +82916,15 @@ async function runHistorianPrompt(args) {
82755
82916
  }
82756
82917
  completion = await executor.collect(handle, 50);
82757
82918
  const lengthCapped = completion.lengthCapped;
82919
+ const tokens = {
82920
+ ...runTokenLog(undefined, args.maxOutputTokens),
82921
+ ...completion.tokenLog,
82922
+ max_tokens: args.maxOutputTokens ?? null
82923
+ };
82924
+ sessionLog(parentSessionId, `historian response_chars=${(completion.text ?? completion.reasoning ?? "").length} ${formatRunTokenLog(tokens)}`);
82758
82925
  const textResult = completion.text;
82759
82926
  const reasoningResult = textResult ? null : completion.reasoning;
82760
- const emptyError = !textResult && reasoningResult && lengthCapped ? historianReasoningBudgetDiagnostic(completion.usage.output) : !textResult && !reasoningResult ? "Historian returned no assistant output." : !textResult ? "Historian returned reasoning but no assistant text." : lengthCapped ? "Historian returned length-capped output." : null;
82927
+ const emptyError = !textResult && reasoningResult && lengthCapped ? historianReasoningBudgetDiagnostic(completion.usage.output, tokens) : !textResult && !reasoningResult ? "Historian returned no assistant output." : !textResult ? "Historian returned reasoning but no assistant text." : lengthCapped ? `Historian returned length-capped output. ${formatRunTokenLog(tokens)}` : null;
82761
82928
  const invocationId = recordInvocation({
82762
82929
  status: emptyError ? "empty" : "completed",
82763
82930
  messages: completion.messages,
@@ -82943,6 +83110,7 @@ var init_compartment_runner_historian = __esm(async () => {
82943
83110
  init_compartment_prompt();
82944
83111
  init_compartment_runner_types();
82945
83112
  init_compartment_runner_validation();
83113
+ init_derive_budgets();
82946
83114
  init_producer_window_guard();
82947
83115
  init_read_session_formatting();
82948
83116
  await __promiseAll([
@@ -89179,6 +89347,8 @@ function findDanglingPublicationBoundary(sessionId, compartments, messageExists
89179
89347
  return null;
89180
89348
  }
89181
89349
  async function runCompartmentAgent(deps) {
89350
+ if (shouldSkipHomeProjectMemory(deps.directory ?? process.cwd()))
89351
+ return;
89182
89352
  const {
89183
89353
  client,
89184
89354
  db,
@@ -89409,11 +89579,14 @@ async function runCompartmentAgent(deps) {
89409
89579
  }
89410
89580
  const producerModel = toModelEntry(deps.model)?.model ?? deps.fallbackModelId;
89411
89581
  const modelParts = producerModel?.split("/");
89412
- const producerReserve = historianProducerReserve(deps.historianContextLimit, deps.historianMaxOutputTokens, modelParts && modelParts.length > 1 ? getSdkOutputLimit(modelParts[0], modelParts.slice(1).join("/")) : undefined);
89582
+ const producerLimits = resolveHistorianProducerLimits(producerModel);
89583
+ const producerContext = producerLimits.context ?? (producerLimits.input === undefined ? deps.historianContextLimit : undefined);
89584
+ const producerReserve = historianProducerReserve(producerContext, deps.historianMaxOutputTokens, modelParts && modelParts.length > 1 ? getSdkOutputLimit(modelParts[0], modelParts.slice(1).join("/")) : undefined);
89413
89585
  const fittedAtomicSource = chunk.oversizeAtomicUnit ? fitAtomicHistorianSourceToProducerWindow({
89414
89586
  text: chunk.text,
89415
89587
  resultBoundaries: chunk.toolResultBoundaries,
89416
- contextLimitTokens: deps.historianContextLimit,
89588
+ contextLimitTokens: producerContext,
89589
+ inputLimitTokens: producerLimits.input,
89417
89590
  maxOutputTokens: producerReserve
89418
89591
  }) : null;
89419
89592
  const chunkText = chunk.oversizeAtomicUnit ? fittedAtomicSource?.text ?? chunk.text : truncateHistorianInputIfNeeded(chunk.text, historianChunkTokens);
@@ -89426,10 +89599,11 @@ async function runCompartmentAgent(deps) {
89426
89599
  }
89427
89600
  const producerWindowFailure = producerWindowFailureReason({
89428
89601
  producerSourceTokens,
89429
- contextLimitTokens: deps.historianContextLimit,
89602
+ contextLimitTokens: producerContext,
89603
+ inputLimitTokens: producerLimits.input,
89430
89604
  maxOutputTokens: producerReserve
89431
89605
  });
89432
- if (deps.historianContextLimit !== undefined && producerInputTokenLimit(deps.historianContextLimit, producerReserve) === undefined) {
89606
+ if (deps.historianContextLimit !== undefined && producerInputTokenLimit(producerContext, producerReserve, producerLimits.input) === undefined) {
89433
89607
  logInconsistentProducerWindowOnce(sessionId, producerModel ?? "unknown", deps.historianContextLimit, producerReserve);
89434
89608
  }
89435
89609
  if (producerWindowFailure) {
@@ -89589,7 +89763,7 @@ ${chunkText}`,
89589
89763
  const compartmentTagKeys = await getRawSessionTagKeysThrough(sessionId, lastCompartmentEnd, { db, fromMessageIndex: offset });
89590
89764
  let published = false;
89591
89765
  const transactionStartedAt = startHistorianPublishStage(sessionId, "publish-txn");
89592
- db.exec("BEGIN IMMEDIATE");
89766
+ await beginSqliteWriterAsync(db, "historian-publish");
89593
89767
  try {
89594
89768
  if (!isCompartmentLeaseHeld(db, sessionId, holderId)) {
89595
89769
  db.exec("ROLLBACK");
@@ -89813,6 +89987,7 @@ var init_compartment_runner_incremental = __esm(async () => {
89813
89987
  init_reference_retrieval();
89814
89988
  await __promiseAll([
89815
89989
  init_store_generation_rebase(),
89990
+ init_sqlite(),
89816
89991
  init_memory(),
89817
89992
  init_storage_memory(),
89818
89993
  init_storage(),
@@ -107100,28 +107275,6 @@ class EmergencyFailClosedError extends Error {
107100
107275
  this.name = "EmergencyFailClosedError";
107101
107276
  }
107102
107277
  }
107103
- // src/hooks/magic-context/event-payloads.ts
107104
- function nonEmptyString(value) {
107105
- return typeof value === "string" && value.length > 0 ? value : undefined;
107106
- }
107107
- function getSessionErrorInfo(properties) {
107108
- if (!isRecord3(properties))
107109
- return null;
107110
- const sessionID = properties.sessionID;
107111
- if (typeof sessionID !== "string" || sessionID.length === 0)
107112
- return null;
107113
- const error = isRecord3(properties.error) ? properties.error : undefined;
107114
- const data = error && isRecord3(error.data) ? error.data : undefined;
107115
- const model = isRecord3(properties.model) ? properties.model : error && isRecord3(error.model) ? error.model : data && isRecord3(data.model) ? data.model : undefined;
107116
- const providerID = nonEmptyString(properties.providerID) ?? nonEmptyString(model?.providerID) ?? nonEmptyString(model?.provider) ?? nonEmptyString(error?.providerID) ?? nonEmptyString(data?.providerID);
107117
- const modelID = nonEmptyString(properties.modelID) ?? nonEmptyString(model?.modelID) ?? nonEmptyString(model?.id) ?? nonEmptyString(error?.modelID) ?? nonEmptyString(data?.modelID);
107118
- return {
107119
- sessionID,
107120
- error: properties.error,
107121
- ...providerID ? { providerID } : {},
107122
- ...modelID ? { modelID } : {}
107123
- };
107124
- }
107125
107278
 
107126
107279
  // src/features/magic-context/dreamer/verify-read-cap.ts
107127
107280
  var DREAMER_READ_MAX_CHARS = 8000;
@@ -107137,7 +107290,10 @@ function capDreamerReadOutput(input, output) {
107137
107290
 
107138
107291
  // src/features/magic-context/message-index-async.ts
107139
107292
  init_logger();
107140
- await init_message_index();
107293
+ await __promiseAll([
107294
+ init_sqlite(),
107295
+ init_message_index()
107296
+ ]);
107141
107297
  function isDatabaseLockedError(error) {
107142
107298
  if (!error || typeof error !== "object")
107143
107299
  return false;
@@ -107223,7 +107379,7 @@ async function reconcileSessionIndex(db, sessionId, readMessages) {
107223
107379
  const messages = readMessages.readPage ? readMessages.readPage(sessionId, cursor, RECONCILIATION_BATCH_SIZE, finalWatermark) : (fallbackSnapshot ?? []).filter((message) => message.ordinal > cursor && message.ordinal <= pageEnd);
107224
107380
  const retainedMessages = fallbackSnapshot ?? messages;
107225
107381
  heapHolder.activeReconcilerBuffers.set(sessionId, retainedMessages);
107226
- indexMessagesAfterOrdinal(db, sessionId, messages, cursor, pageEnd);
107382
+ withSqliteBackgroundWriter(() => indexMessagesAfterOrdinal(db, sessionId, messages, cursor, pageEnd));
107227
107383
  const nextCursor = getMessageIndexReconciliationStartOrdinal(db, sessionId);
107228
107384
  if (nextCursor <= cursor)
107229
107385
  break;
@@ -107249,6 +107405,8 @@ function scheduleReconciliation(db, sessionId, readMessages) {
107249
107405
  defer(() => {
107250
107406
  reconcileSessionIndex(db, sessionId, readMessages).catch((error) => {
107251
107407
  logIndexingError(sessionId, "reconciliation", error);
107408
+ if (isDatabaseLockedError(error))
107409
+ setTimeout(() => scheduleReconciliation(db, sessionId, readMessages), 1000).unref();
107252
107410
  }).finally(() => {
107253
107411
  heapHolder.reconciliationScheduledSessions.delete(sessionId);
107254
107412
  });
@@ -109675,6 +109833,28 @@ function annotateEmptyTaskOutput(tool, output) {
109675
109833
  ${EMPTY_TASK_OUTPUT_SENTINEL}
109676
109834
  The subagent completed without a final text response. Context-fill truncation may have omitted its final output, or its provider may have emitted reasoning only; inspect the child session and retry with a low-reasoning model or variant.`);
109677
109835
  }
109836
+ // src/hooks/magic-context/event-payloads.ts
109837
+ function nonEmptyString(value) {
109838
+ return typeof value === "string" && value.length > 0 ? value : undefined;
109839
+ }
109840
+ function getSessionErrorInfo(properties) {
109841
+ if (!isRecord3(properties))
109842
+ return null;
109843
+ const sessionID = properties.sessionID;
109844
+ if (typeof sessionID !== "string" || sessionID.length === 0)
109845
+ return null;
109846
+ const error = isRecord3(properties.error) ? properties.error : undefined;
109847
+ const data = error && isRecord3(error.data) ? error.data : undefined;
109848
+ const model = isRecord3(properties.model) ? properties.model : error && isRecord3(error.model) ? error.model : data && isRecord3(data.model) ? data.model : undefined;
109849
+ const providerID = nonEmptyString(properties.providerID) ?? nonEmptyString(model?.providerID) ?? nonEmptyString(model?.provider) ?? nonEmptyString(error?.providerID) ?? nonEmptyString(data?.providerID);
109850
+ const modelID = nonEmptyString(properties.modelID) ?? nonEmptyString(model?.modelID) ?? nonEmptyString(model?.id) ?? nonEmptyString(error?.modelID) ?? nonEmptyString(data?.modelID);
109851
+ return {
109852
+ sessionID,
109853
+ error: properties.error,
109854
+ ...providerID ? { providerID } : {},
109855
+ ...modelID ? { modelID } : {}
109856
+ };
109857
+ }
109678
109858
 
109679
109859
  // src/hooks/magic-context/hook-handlers.ts
109680
109860
  init_lkg_slot();
@@ -111976,10 +112156,12 @@ init_project_embedding_registry();
111976
112156
 
111977
112157
  // src/plugin/embedding-bootstrap.ts
111978
112158
  init_config();
112159
+ init_migrate_config_location();
111979
112160
  init_embedding();
111980
112161
  init_embedding_cache();
111981
112162
  init_project_identity();
111982
112163
  init_logger();
112164
+ import { readFileSync as readFileSync14, statSync as statSync13 } from "node:fs";
111983
112165
 
111984
112166
  // src/plugin/embedding-bootstrap-helpers.ts
111985
112167
  init_embedding();
@@ -112230,12 +112412,41 @@ async function resolveEmbeddingRouting(args) {
112230
112412
  }
112231
112413
 
112232
112414
  // src/plugin/embedding-bootstrap.ts
112233
- async function ensureProjectRegisteredFromOpenCodeDirectory(directory, db) {
112415
+ var configCache = new Map;
112416
+ function loadRegistrationConfig(directory) {
112417
+ const legacy = resolveLegacyConfigSources(directory);
112418
+ const paths = [cortexKitUserConfigBasePath(), cortexKitProjectConfigBasePath(directory)].flatMap((base) => [`${base}.jsonc`, `${base}.json`]).concat(legacy.user.map((source) => source.path), legacy.project.map((source) => source.path));
112419
+ const key = paths.map((path) => {
112420
+ const stat = statSync13(path, { throwIfNoEntry: false });
112421
+ return `${path}:${stat?.mtimeMs ?? "missing"}:${stat?.size ?? 0}`;
112422
+ }).join("|");
112423
+ const cached = configCache.get(directory);
112424
+ if (cached?.key === key)
112425
+ return cached.detailed;
112234
112426
  const detailed = loadPluginConfigDetailed(directory);
112427
+ const dynamic = paths.some((path) => {
112428
+ try {
112429
+ return /\{(?:env|file):/.test(readFileSync14(path, "utf8"));
112430
+ } catch {
112431
+ return false;
112432
+ }
112433
+ });
112434
+ if (!dynamic) {
112435
+ if (configCache.size >= 64) {
112436
+ const oldest = configCache.keys().next().value;
112437
+ if (oldest !== undefined)
112438
+ configCache.delete(oldest);
112439
+ }
112440
+ configCache.set(directory, { key, detailed });
112441
+ } else
112442
+ configCache.delete(directory);
112443
+ return detailed;
112444
+ }
112445
+ async function ensureProjectRegisteredFromOpenCodeDirectory(directory, db) {
112446
+ const detailed = loadRegistrationConfig(directory);
112235
112447
  const projectIdentity = resolveProjectIdentityForSession(directory, detailed.config.allow_home_project);
112236
112448
  if (!projectIdentity)
112237
112449
  return;
112238
- invalidateProject(projectIdentity);
112239
112450
  if (isConfigLoadUntrusted(detailed)) {
112240
112451
  handleUntrustedLoad(db, projectIdentity, directory, detailed);
112241
112452
  return;
@@ -112252,7 +112463,10 @@ async function ensureProjectRegisteredFromOpenCodeDirectory(directory, db) {
112252
112463
  memoryEnabled: detailed.config.memory.enabled,
112253
112464
  gitCommitEnabled: detailed.config.memory.git_commit_indexing.enabled
112254
112465
  };
112255
- registerProjectEmbedding(db, projectIdentity, routing.primary, features, directory);
112466
+ const before = getProjectEmbeddingSnapshot(projectIdentity);
112467
+ const registered = registerProjectEmbedding(db, projectIdentity, routing.primary, features, directory);
112468
+ if (!before || before.providerIdentity !== registered.providerIdentity || before.runtimeFingerprint !== registered.runtimeFingerprint)
112469
+ invalidateProject(projectIdentity);
112256
112470
  if (routing.shadow) {
112257
112471
  registerProjectShadowEmbedding(db, projectIdentity, routing.shadow, directory);
112258
112472
  } else {
@@ -116764,6 +116978,16 @@ function servedModuleM0Text(sessionId, readSlot = getSlot) {
116764
116978
  init_logger();
116765
116979
  await init_sqlite();
116766
116980
  var STORAGE_BUSY_MESSAGE = "Magic Context's database is busy (another process held it too long); send your message again.";
116981
+ function describeStorageBusyCause(cause) {
116982
+ let original = cause;
116983
+ for (let depth = 0;original instanceof SqliteAcquisitionBusyError && depth < 5; depth++) {
116984
+ original = original.cause;
116985
+ }
116986
+ if (!(original instanceof Error))
116987
+ return String(original);
116988
+ return original.stack ? `${original.message}
116989
+ ${original.stack}` : original.message;
116990
+ }
116767
116991
 
116768
116992
  class StorageBusyRefusalError extends Error {
116769
116993
  code = "STORAGE_BUSY_REFUSAL";
@@ -116771,8 +116995,7 @@ class StorageBusyRefusalError extends Error {
116771
116995
  constructor(cause, stage) {
116772
116996
  super(STORAGE_BUSY_MESSAGE, { cause });
116773
116997
  this.name = "StorageBusyRefusalError";
116774
- const original = cause instanceof SqliteAcquisitionBusyError ? cause.cause : cause;
116775
- const detail = original instanceof Error ? original.stack ?? original.message : String(original);
116998
+ const detail = describeStorageBusyCause(cause);
116776
116999
  log(`[magic-context] storage-busy refusal stage=${stage}${cause instanceof SqliteAcquisitionBusyError ? ` acquisition=${cause.stage}` : ""}: ${detail}`);
116777
117000
  }
116778
117001
  }
@@ -117219,7 +117442,24 @@ await init_inject_compartments();
117219
117442
 
117220
117443
  // src/hooks/magic-context/lkg-persist.ts
117221
117444
  init_logger();
117445
+ import { createHash as createHash25 } from "node:crypto";
117446
+ var persistedFingerprints = new WeakMap;
117222
117447
  function saveLkgSlotToDb(db, sessionId, slot) {
117448
+ const fingerprint = createHash25("sha256").update(JSON.stringify([
117449
+ slot.jsonPrefix,
117450
+ slot.inputIdSeq,
117451
+ slot.inputContentDigests,
117452
+ slot.inputContentSignatures,
117453
+ slot.piOutputEntryIds,
117454
+ slot.lastInputMessageId,
117455
+ slot.modelKey,
117456
+ slot.providerKey,
117457
+ slot.rowVersion,
117458
+ slot.captureSequence
117459
+ ])).digest("hex");
117460
+ let saved = persistedFingerprints.get(db);
117461
+ if (saved?.get(sessionId) === fingerprint)
117462
+ return true;
117223
117463
  try {
117224
117464
  db.prepare(`INSERT INTO lkg_slots (
117225
117465
  session_id, json_prefix, input_id_seq, input_content_digests,
@@ -117241,6 +117481,16 @@ function saveLkgSlotToDb(db, sessionId, slot) {
117241
117481
  inputIds: slot.inputIdSeq,
117242
117482
  piOutputEntryIds: slot.piOutputEntryIds
117243
117483
  } : slot.inputIdSeq), JSON.stringify(slot.inputContentDigests), slot.inputContentSignatures ? JSON.stringify(slot.inputContentSignatures) : null, slot.lastInputMessageId, slot.modelKey, slot.providerKey, slot.capturedAt, slot.rowVersion ?? null, slot.captureSequence ?? null);
117484
+ if (!saved) {
117485
+ saved = new Map;
117486
+ persistedFingerprints.set(db, saved);
117487
+ }
117488
+ if (saved.size >= 1000) {
117489
+ const oldest = saved.keys().next().value;
117490
+ if (oldest !== undefined)
117491
+ saved.delete(oldest);
117492
+ }
117493
+ saved.set(sessionId, fingerprint);
117244
117494
  return true;
117245
117495
  } catch (error) {
117246
117496
  sessionLog(sessionId, "LKG snapshot persistence failed (in-memory slot retained):", error);
@@ -117827,7 +118077,7 @@ await __promiseAll([
117827
118077
  // src/hooks/magic-context/rust-mode-transform.ts
117828
118078
  init_magic_context();
117829
118079
  await init_context_authority();
117830
- import { createHash as createHash26, randomUUID as randomUUID5 } from "node:crypto";
118080
+ import { createHash as createHash27, randomUUID as randomUUID5 } from "node:crypto";
117831
118081
  init_project_identity();
117832
118082
 
117833
118083
  // src/features/magic-context/memory/single-store-embedding-drain.ts
@@ -118300,13 +118550,16 @@ class HistorianHostRunner {
118300
118550
  this.log(`producer window unknown for ${key}: sending unguarded`);
118301
118551
  }
118302
118552
  const output = provider && parts.length ? getSdkOutputLimit(provider, parts.join("/")) : undefined;
118303
- const reserve = historianProducerReserve(window2, undefined, output);
118553
+ const producerLimits = resolveHistorianProducerLimits(key);
118554
+ const context = producerLimits.context ?? (producerLimits.input === undefined ? window2 : undefined);
118555
+ const reserve = historianProducerReserve(context, undefined, output);
118304
118556
  const failure = producerPromptFailureReason({
118305
118557
  sourceLocal: estimateTokens(claim.user),
118306
118558
  systemLocal: estimateTokens(claim.system),
118307
118559
  toolsLocal: 0,
118308
118560
  modelKey: key,
118309
- contextLimitTokens: window2,
118561
+ contextLimitTokens: context,
118562
+ inputLimitTokens: producerLimits.input,
118310
118563
  maxOutputTokens: reserve
118311
118564
  });
118312
118565
  if (failure)
@@ -120748,10 +121001,10 @@ function messageCacheSignature(message) {
120748
121001
  const parts = Array.isArray(message.parts) ? message.parts : [];
120749
121002
  const serializedParts = JSON.stringify(parts) ?? "null";
120750
121003
  const serializedMessage = JSON.stringify(message) ?? "null";
120751
- return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash26("sha256").update(serializedMessage).digest("hex")}`;
121004
+ return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash27("sha256").update(serializedMessage).digest("hex")}`;
120752
121005
  }
120753
121006
  function advanceWireFingerprint(previous, encoded) {
120754
- return createHash26("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
121007
+ return createHash27("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
120755
121008
  }
120756
121009
  function buildWireFingerprint(encoded) {
120757
121010
  let fingerprint = "rust-wire-v1";
@@ -121107,7 +121360,7 @@ function canonicalizeForChecksum(value) {
121107
121360
  return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalizeForChecksum(value[key])]));
121108
121361
  }
121109
121362
  function checksumSeedRows(rows) {
121110
- return createHash26("sha256").update(JSON.stringify(rows.map(canonicalizeForChecksum))).digest("hex");
121363
+ return createHash27("sha256").update(JSON.stringify(rows.map(canonicalizeForChecksum))).digest("hex");
121111
121364
  }
121112
121365
  function authoritySeedRows(db, projectPath, domain) {
121113
121366
  const snapshots = domain === "memories" ? db.prepare("SELECT * FROM memories WHERE project_path = ? ORDER BY id ASC").all(projectPath) : db.prepare(`SELECT n.*
@@ -121335,13 +121588,15 @@ function resolvedHistorianModelLimits(chain) {
121335
121588
  return Object.fromEntries(chain.map((key) => {
121336
121589
  const [provider, ...parts] = key.split("/");
121337
121590
  const output = provider && parts.length ? getSdkOutputLimit(provider, parts.join("/")) : undefined;
121338
- const known = resolveKnownHistorianContextLimit(key);
121591
+ const producerLimits = resolveHistorianProducerLimits(key);
121592
+ const known = producerLimits.input === undefined ? resolveKnownHistorianContextLimit(key) : undefined;
121339
121593
  const learned = provider && parts.length ? getSdkWindowGeometry(provider, parts.join("/"))?.derivation.window : undefined;
121340
- const context = known === undefined ? learned : learned === undefined ? known : Math.min(known, learned);
121594
+ const context = producerLimits.context ?? (known === undefined ? learned : learned === undefined ? known : Math.min(known, learned));
121341
121595
  return [
121342
121596
  key,
121343
121597
  {
121344
121598
  ...context !== undefined ? { context } : {},
121599
+ ...producerLimits.input !== undefined ? { input: producerLimits.input } : {},
121345
121600
  ...output !== undefined ? { output } : {}
121346
121601
  }
121347
121602
  ];
@@ -122744,6 +122999,16 @@ function createRustModeTransform(deps, options) {
122744
122999
  }
122745
123000
  pendingWireCache.nativeOutput = moduleMessages;
122746
123001
  if (!replayedFrozenRepresentation) {
123002
+ if (materializedBoundary && !deps.compactionOff) {
123003
+ try {
123004
+ await withAsyncPrivilegedWriter(deps.db, () => {
123005
+ return;
123006
+ });
123007
+ } catch (error) {
123008
+ if (!isTransientSqliteError(error))
123009
+ throw error;
123010
+ }
123011
+ }
122747
123012
  const postprocess = runRustModePostprocess({
122748
123013
  db: deps.db,
122749
123014
  sessionId,
@@ -122968,7 +123233,7 @@ function createRustModeTransform(deps, options) {
122968
123233
  if (mirrorDrain.rowsApplied > 0) {
122969
123234
  await reembedMirrorInvalidatedMemories(deps.db);
122970
123235
  }
122971
- await drainSingleStoreEmbeddingWatermarks(deps.db);
123236
+ await withSqliteBackgroundWriter(() => drainSingleStoreEmbeddingWatermarks(deps.db));
122972
123237
  if (mirrorDrain.complete) {
122973
123238
  state.memoryMirrorProjectionKey = projectionKey;
122974
123239
  } else if (mirrorDrain.budgetExhausted) {
@@ -124838,6 +125103,13 @@ function createMessagesTransformHandler(args) {
124838
125103
  }
124839
125104
  })() : null;
124840
125105
  try {
125106
+ if (!args.compactionOff && magicContext) {
125107
+ const admissionDb = openDatabase();
125108
+ if (admissionDb)
125109
+ await withAsyncPrivilegedWriter(admissionDb, () => {
125110
+ return;
125111
+ });
125112
+ }
124841
125113
  await magicContext?.["experimental.chat.messages.transform"]?.(input, output);
124842
125114
  return output.messages;
124843
125115
  } catch (error) {
@@ -126090,11 +126362,14 @@ function buildSidebarSnapshot(db, sessionId, directory, liveSessionState, inject
126090
126362
  };
126091
126363
  return applyStickySnapshotCache(sessionId, fresh);
126092
126364
  } catch (err) {
126093
- log("[rpc] sidebar-snapshot error:", err);
126365
+ if (!(err instanceof ProjectIdentityError && err.errorClass === "home_project_disabled"))
126366
+ log("[rpc] sidebar-snapshot error:", err);
126094
126367
  throw err;
126095
126368
  }
126096
126369
  }
126097
126370
  function buildSidebarSnapshotRpcResponse(db, sessionId, directory, liveSessionState, injectionBudgetTokens, config, moduleStatus, compactionEnabled = true) {
126371
+ if (shouldSkipHomeProjectMemory(directory))
126372
+ return { sessionId, disabled: true };
126098
126373
  try {
126099
126374
  return buildSidebarSnapshot(db, sessionId, directory, liveSessionState, injectionBudgetTokens, config, moduleStatus, compactionEnabled);
126100
126375
  } catch {
@@ -126111,7 +126386,7 @@ function safeTickFailure(db) {
126111
126386
  function buildStatusDetail(db, sessionId, directory, modelKey, config, liveSessionState, injectionBudgetTokens, moduleStatus, compactionEnabled = true) {
126112
126387
  const base = buildSidebarSnapshot(db, sessionId, directory, liveSessionState, injectionBudgetTokens, config, moduleStatus, compactionEnabled);
126113
126388
  const rustMode = config?.transform_mode === "rust";
126114
- const projectIdentity = rustMode ? resolveProjectIdentity(directory) : null;
126389
+ const projectIdentity = rustMode && !shouldSkipHomeProjectMemory(directory) ? resolveProjectIdentity(directory) : null;
126115
126390
  const moduleMemoryAuthority = moduleStatus?.authority?.memories;
126116
126391
  const moduleMemoryState = moduleMemoryAuthority?.state;
126117
126392
  const moduleFeedHead = moduleStatus?.memory_mirror?.feed_head;
@@ -126554,6 +126829,8 @@ function registerRpcHandlers(rpcServer, args) {
126554
126829
  rpcServer.handle("status-detail", async (params) => {
126555
126830
  const sessionId = String(params.sessionId ?? "");
126556
126831
  const dir = String(params.directory ?? directory);
126832
+ if (shouldSkipHomeProjectMemory(dir))
126833
+ return { sessionId, disabled: true };
126557
126834
  const modelKey = params.modelKey ? String(params.modelKey) : undefined;
126558
126835
  const db = readDatabase();
126559
126836
  if (!db || !sessionId)
@@ -126574,6 +126851,8 @@ function registerRpcHandlers(rpcServer, args) {
126574
126851
  rpcServer.handle("embed-detail", async (params) => {
126575
126852
  const sessionId = String(params.sessionId ?? "");
126576
126853
  const dir = String(params.directory ?? directory);
126854
+ if (shouldSkipHomeProjectMemory(dir))
126855
+ return { sessionId, disabled: true };
126577
126856
  const db = readDatabase();
126578
126857
  if (!db || !sessionId)
126579
126858
  return { error: "unavailable" };
@@ -127064,7 +127343,7 @@ import {
127064
127343
  chmodSync as chmodSync5,
127065
127344
  mkdirSync as mkdirSync11,
127066
127345
  readdirSync as readdirSync4,
127067
- readFileSync as readFileSync15,
127346
+ readFileSync as readFileSync16,
127068
127347
  renameSync as renameSync4,
127069
127348
  rmSync as rmSync2,
127070
127349
  unlinkSync as unlinkSync5,
@@ -127211,7 +127490,7 @@ class MagicContextRpcServer {
127211
127490
  for (const entry of readdirSync4(this.portDir)) {
127212
127491
  if (!entry.startsWith("port-") || !entry.endsWith(".json"))
127213
127492
  continue;
127214
- const record = parseRpcPortFile(readFileSync15(`${this.portDir}/${entry}`, "utf-8"));
127493
+ const record = parseRpcPortFile(readFileSync16(`${this.portDir}/${entry}`, "utf-8"));
127215
127494
  if (!record || record.pid === process.pid)
127216
127495
  continue;
127217
127496
  const processes = await inspectProcessesAsync();
@@ -127603,8 +127882,8 @@ function hostMediaAsset(data, mediaType) {
127603
127882
  }
127604
127883
 
127605
127884
  // src/v2/fold/owner.ts
127606
- import { createHash as createHash27 } from "node:crypto";
127607
- var foldDigest = (value) => createHash27("sha256").update(value).digest("hex");
127885
+ import { createHash as createHash28 } from "node:crypto";
127886
+ var foldDigest = (value) => createHash28("sha256").update(value).digest("hex");
127608
127887
 
127609
127888
  class FoldOwner {
127610
127889
  storage;
@@ -127907,6 +128186,64 @@ ${data.output?.output ?? ""}`
127907
128186
  return [...content.length ? [make("assistant", content)] : [], ...results];
127908
128187
  }
127909
128188
 
128189
+ // src/features/magic-context/dreamer/retrospective-orphan-sweep.ts
128190
+ init_logger();
128191
+ var HISTORIAN_CHILD_TITLE = "magic-context-compartment";
128192
+ var RETROSPECTIVE_CHILD_TITLE = "magic-context-dream-retrospective";
128193
+ var USER_MEMORIES_CHILD_TITLE = "magic-context-dream-user-memories";
128194
+ var CURATE_CHILD_TITLE = "magic-context-dream-curate";
128195
+ var MAINTAIN_DOCS_CHILD_TITLE = "magic-context-dream-maintain-docs";
128196
+ var REFRESH_PRIMERS_CHILD_TITLE = "magic-context-dream-refresh-primers";
128197
+ var MAP_MEMORIES_CHILD_TITLE = "magic-context-dream-map-memories";
128198
+ var VERIFY_CHILD_TITLE = "magic-context-dream-verify";
128199
+ var CLASSIFY_CHILD_TITLE = "magic-context-dream-classify";
128200
+ var COMPRESS_CUES_CHILD_TITLE = "magic-context-dream-compress-cues";
128201
+ var MEMORY_MIGRATION_CHILD_TITLE = "magic-context-memory-migration";
128202
+ var SMART_NOTE_COMPILE_CHILD_TITLE_PREFIX = "magic-context-smart-note-compile-";
128203
+ var SMART_NOTE_CONFIRM_CHILD_TITLE_PREFIX = "magic-context-smart-note-confirm-";
128204
+ var PRIVACY_SENSITIVE_CHILD_TITLE_MATCHES = {
128205
+ exact: [
128206
+ RETROSPECTIVE_CHILD_TITLE,
128207
+ USER_MEMORIES_CHILD_TITLE,
128208
+ CURATE_CHILD_TITLE,
128209
+ MAINTAIN_DOCS_CHILD_TITLE,
128210
+ REFRESH_PRIMERS_CHILD_TITLE,
128211
+ MAP_MEMORIES_CHILD_TITLE,
128212
+ VERIFY_CHILD_TITLE,
128213
+ CLASSIFY_CHILD_TITLE,
128214
+ COMPRESS_CUES_CHILD_TITLE
128215
+ ],
128216
+ prefixes: [SMART_NOTE_COMPILE_CHILD_TITLE_PREFIX, SMART_NOTE_CONFIRM_CHILD_TITLE_PREFIX]
128217
+ };
128218
+ var RETAINABLE_CHILD_TITLE_MATCHES = {
128219
+ exact: [HISTORIAN_CHILD_TITLE, MEMORY_MIGRATION_CHILD_TITLE],
128220
+ prefixes: []
128221
+ };
128222
+ var INTERNAL_CHILD_TITLE_MATCHES = {
128223
+ exact: [
128224
+ ...RETAINABLE_CHILD_TITLE_MATCHES.exact,
128225
+ ...PRIVACY_SENSITIVE_CHILD_TITLE_MATCHES.exact
128226
+ ],
128227
+ prefixes: PRIVACY_SENSITIVE_CHILD_TITLE_MATCHES.prefixes
128228
+ };
128229
+ var DREAMER_DETACHED_WRITER_GRACE_MS = 15 * 60000;
128230
+ function retrospectiveOrphanStaleMs(taskTimeoutMinutes) {
128231
+ const timeoutCandidates = Array.isArray(taskTimeoutMinutes) ? taskTimeoutMinutes : [taskTimeoutMinutes];
128232
+ const maxTimeoutMinutes = Math.max(...timeoutCandidates.map((minutes) => Math.max(1, minutes ?? 20)), 20);
128233
+ const timeoutMs = maxTimeoutMinutes * 60000;
128234
+ return Math.max(60 * 60000, timeoutMs * 3 + DREAMER_DETACHED_WRITER_GRACE_MS);
128235
+ }
128236
+ var HISTORIAN_OUTER_ATTEMPTS = 3;
128237
+ var HISTORIAN_MODEL_SUGGESTION_ATTEMPTS = 2;
128238
+ var HISTORIAN_MAX_RETRY_BACKOFF_MS = 11000;
128239
+ var HISTORIAN_DETACHED_WRITER_GRACE_MS = 15 * 60000;
128240
+ function historianOrphanStaleMs(timeoutMs, fallbackModelCount) {
128241
+ const timeout = Math.max(60000, timeoutMs);
128242
+ const fallbackCount = Math.max(0, Math.floor(fallbackModelCount));
128243
+ const fullAttemptBudget = timeout * HISTORIAN_OUTER_ATTEMPTS * HISTORIAN_MODEL_SUGGESTION_ATTEMPTS * (fallbackCount + 1);
128244
+ return Math.max(60 * 60000, fullAttemptBudget + HISTORIAN_MAX_RETRY_BACKOFF_MS + HISTORIAN_DETACHED_WRITER_GRACE_MS);
128245
+ }
128246
+
127910
128247
  // src/v2/hidden-completion.ts
127911
128248
  init_token_budget();
127912
128249
  init_compartment_runner_types();
@@ -127917,7 +128254,7 @@ init_hidden_child();
127917
128254
  // src/v2/host-service.ts
127918
128255
  init_data_path();
127919
128256
  await init_sqlite();
127920
- import { readdirSync as readdirSync5, readFileSync as readFileSync16 } from "node:fs";
128257
+ import { readdirSync as readdirSync5, readFileSync as readFileSync17 } from "node:fs";
127921
128258
  import { homedir as homedir11 } from "node:os";
127922
128259
  import { join as join17 } from "node:path";
127923
128260
 
@@ -128335,7 +128672,7 @@ class HostServiceUnavailable extends Error {
128335
128672
  function parseRegistration(path) {
128336
128673
  let text;
128337
128674
  try {
128338
- text = readFileSync16(path, "utf8");
128675
+ text = readFileSync17(path, "utf8");
128339
128676
  } catch {
128340
128677
  return;
128341
128678
  }
@@ -128449,8 +128786,8 @@ var POLL_INTERVAL_MS = 200;
128449
128786
  var REMOVAL_SPACING_MS = 250;
128450
128787
  var RETIRED_CHILDREN_LIMIT = 200;
128451
128788
  var LEGACY_CLEANUP_BOOT_LIMIT = 5;
128452
- function hiddenChildrenMetaKey(projectIdentity) {
128453
- return `${META_PREFIX}${projectIdentity}`;
128789
+ function hiddenChildrenMetaKey(projectIdentity, directory) {
128790
+ return directory === undefined ? `${META_PREFIX}${projectIdentity}` : `${META_PREFIX}${JSON.stringify([projectIdentity, directory])}`;
128454
128791
  }
128455
128792
  function emptyMeta() {
128456
128793
  return { version: 1, active: {}, retired_children: [] };
@@ -128512,9 +128849,49 @@ function parseMeta(value) {
128512
128849
  class HiddenChildStateStore {
128513
128850
  db;
128514
128851
  key;
128515
- constructor(db, projectIdentity) {
128852
+ constructor(db, projectIdentity, directory) {
128516
128853
  this.db = db;
128517
- this.key = hiddenChildrenMetaKey(projectIdentity);
128854
+ this.key = hiddenChildrenMetaKey(projectIdentity, directory);
128855
+ this.legacyKey = hiddenChildrenMetaKey(projectIdentity);
128856
+ }
128857
+ legacyKey;
128858
+ migrateStale(isStale) {
128859
+ this.db.transaction(() => {
128860
+ const legacyRow = this.db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(this.legacyKey);
128861
+ if (!legacyRow)
128862
+ return;
128863
+ const legacy = parseMeta(legacyRow.value);
128864
+ const scoped = this.read();
128865
+ for (const role of ["historian", "dreamer"]) {
128866
+ const child = legacy.active[role];
128867
+ if (!child || !isStale(child))
128868
+ continue;
128869
+ scoped.retired_children.push({
128870
+ ...child,
128871
+ retired_at: Date.now(),
128872
+ reason: "legacy-directory-scope"
128873
+ });
128874
+ delete legacy.active[role];
128875
+ }
128876
+ const remaining = [];
128877
+ for (const child of legacy.retired_children) {
128878
+ if (isStale(child))
128879
+ scoped.retired_children.push(child);
128880
+ else
128881
+ remaining.push(child);
128882
+ }
128883
+ legacy.retired_children = remaining;
128884
+ const excess = scoped.retired_children.length - RETIRED_CHILDREN_LIMIT;
128885
+ if (excess > 0)
128886
+ scoped.retired_children.splice(0, excess);
128887
+ this.db.prepare(`INSERT INTO schema_migrations_meta (key, value) VALUES (?, ?)
128888
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(this.key, JSON.stringify(scoped));
128889
+ if (Object.keys(legacy.active).length === 0 && legacy.retired_children.length === 0) {
128890
+ this.db.prepare("DELETE FROM schema_migrations_meta WHERE key = ?").run(this.legacyKey);
128891
+ } else {
128892
+ this.db.prepare("UPDATE schema_migrations_meta SET value = ? WHERE key = ?").run(JSON.stringify(legacy), this.legacyKey);
128893
+ }
128894
+ }).immediate();
128518
128895
  }
128519
128896
  read() {
128520
128897
  const row = this.db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(this.key);
@@ -128741,6 +129118,12 @@ async function sleepUntilPoll(signal, deadline) {
128741
129118
  }, delay);
128742
129119
  });
128743
129120
  }
129121
+ function isProviderFailure(error) {
129122
+ if (!error || typeof error !== "object")
129123
+ return false;
129124
+ const type = error.type;
129125
+ return typeof type === "string" && (type.startsWith("provider.") || type.toLowerCase().includes("provider"));
129126
+ }
128744
129127
  async function awaitAssistantRow(openReader, readSessionError, stepLimit, childID, afterSeq, deadline, signal) {
128745
129128
  for (;; ) {
128746
129129
  const { assistant, idle } = withReader(openReader, (reader) => ({
@@ -128761,7 +129144,7 @@ async function awaitAssistantRow(openReader, readSessionError, stepLimit, childI
128761
129144
  `terminal_row=${errorText(newIdle)}`,
128762
129145
  `session_error=${sessionError === undefined ? "unavailable" : errorText(sessionError)}`
128763
129146
  ];
128764
- throw sessionError === undefined ? new Error(`Hidden completion failed without a provider error: ${details.join("; ")}`) : new HiddenProviderError(details.join("; "));
129147
+ throw sessionError === undefined || !isProviderFailure(sessionError) ? new Error(`Hidden completion failed: ${details.join("; ")}`) : new HiddenProviderError(details.join("; "));
128765
129148
  }
128766
129149
  if (outcome === "succeeded" && newAssistant)
128767
129150
  return newAssistant;
@@ -128775,7 +129158,7 @@ async function awaitAssistantRow(openReader, readSessionError, stepLimit, childI
128775
129158
  `terminal_row=${errorText(newAssistant)}`,
128776
129159
  `session_error=${sessionError === undefined ? "unavailable" : errorText(sessionError)}`
128777
129160
  ];
128778
- throw sessionError === undefined ? new Error(`Hidden completion failed without a provider error: ${details.join("; ")}`) : new HiddenProviderError(details.join("; "));
129161
+ throw sessionError === undefined || !isProviderFailure(sessionError) ? new Error(`Hidden completion failed: ${details.join("; ")}`) : new HiddenProviderError(details.join("; "));
128779
129162
  }
128780
129163
  if (newAssistant.data.error !== undefined) {
128781
129164
  throw new HiddenProviderError(errorText(newAssistant.data.error), {
@@ -128815,9 +129198,35 @@ function createLateHiddenExecutor(current) {
128815
129198
  }
128816
129199
  async function createV2HiddenCompletionExecutor(host, options) {
128817
129200
  const runs = new WeakMap;
128818
- const store = new HiddenChildStateStore(options.db, options.projectIdentity);
129201
+ const store = new HiddenChildStateStore(options.db, options.projectIdentity, options.directory);
128819
129202
  const generation = options.generation ?? "opencode2";
128820
129203
  const roleTails = new Map;
129204
+ const legacy = options.db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(hiddenChildrenMetaKey(options.projectIdentity));
129205
+ if (legacy) {
129206
+ const children = parseMeta(legacy.value);
129207
+ const statuses = new Map;
129208
+ for (const child of [...Object.values(children.active), ...children.retired_children]) {
129209
+ if (!child || !host.status)
129210
+ continue;
129211
+ const directory = child.directory ?? options.directory;
129212
+ if (!statuses.has(directory)) {
129213
+ try {
129214
+ statuses.set(directory, await host.status({ directory }));
129215
+ } catch {
129216
+ statuses.set(directory, undefined);
129217
+ }
129218
+ }
129219
+ }
129220
+ store.migrateStale((child) => {
129221
+ const directory = child.directory ?? options.directory;
129222
+ const state = statuses.get(directory);
129223
+ if (host.status && (!state || state[child.id]?.type === "busy" || state[child.id]?.type === "retry"))
129224
+ return false;
129225
+ const last = Math.max(child.created_at, withReader(options.openReader, (reader) => Math.max(reader.latestAssistant(child.id)?.data.time?.created ?? 0, reader.latestIdle(child.id)?.data.time?.created ?? 0)));
129226
+ const staleMs = child.role === "historian" ? historianOrphanStaleMs(20 * 60000, 3) : retrospectiveOrphanStaleMs(undefined);
129227
+ return Date.now() - last > staleMs;
129228
+ });
129229
+ }
128821
129230
  const persisted = store.read();
128822
129231
  for (const child of [...Object.values(persisted.active), ...persisted.retired_children]) {
128823
129232
  if (child)
@@ -129187,6 +129596,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
129187
129596
  }
129188
129597
  run.completion = {
129189
129598
  text,
129599
+ tokenLog: runTokenLog(tokens, run.identity.maxOutputTokens, row.data.finish),
129190
129600
  ...hiddenToolLoop(run.identity) ? { messages: toolLoopMessages(attempt) } : {},
129191
129601
  reasoning: text ? null : assistantReasoning(row),
129192
129602
  usage: reportedInput !== undefined || reportedOutput !== undefined ? {
@@ -129479,8 +129889,8 @@ await __promiseAll([
129479
129889
  init_context_authority(),
129480
129890
  init_memory()
129481
129891
  ]);
129482
- import { createHash as createHash35 } from "node:crypto";
129483
- import { existsSync as existsSync19, readFileSync as readFileSync19 } from "node:fs";
129892
+ import { createHash as createHash36 } from "node:crypto";
129893
+ import { existsSync as existsSync19, readFileSync as readFileSync20 } from "node:fs";
129484
129894
 
129485
129895
  // src/features/magic-context/mural/compress-cues.ts
129486
129896
  init_dreamer();
@@ -129488,10 +129898,11 @@ init_compartment_runner_types();
129488
129898
  init_shared();
129489
129899
  init_logger();
129490
129900
  await init_compartment_runner_historian();
129491
- import { createHash as createHash29 } from "node:crypto";
129901
+ import { createHash as createHash30 } from "node:crypto";
129492
129902
 
129493
129903
  // src/features/magic-context/dreamer/lease.ts
129494
129904
  init_write_transaction_timing();
129905
+ await init_sqlite();
129495
129906
 
129496
129907
  // src/features/magic-context/dreamer/storage-dream-state.ts
129497
129908
  var getDreamStateStatements = new WeakMap;
@@ -129691,7 +130102,7 @@ function startLeaseHeartbeat(db, holderId, leaseKey, onLost, intervalOrAcquisiti
129691
130102
  }
129692
130103
  };
129693
130104
  beat();
129694
- const timer = lost ? undefined : setInterval(beat, intervalMs);
130105
+ const timer = lost ? undefined : setInterval(() => withSqliteBackgroundWriter(beat), intervalMs);
129695
130106
  return {
129696
130107
  stop: () => {
129697
130108
  if (timer)
@@ -129860,7 +130271,7 @@ function getModuleMemoryIdentities(db, projectIdentity, contextIds) {
129860
130271
  }
129861
130272
 
129862
130273
  // src/features/magic-context/dreamer/provider-output-failure.ts
129863
- import { createHash as createHash28 } from "node:crypto";
130274
+ import { createHash as createHash29 } from "node:crypto";
129864
130275
  var MAX_NEAR_ZERO_OUTPUT_TOKENS = 32;
129865
130276
 
129866
130277
  class DreamerProviderOutputFailureError extends Error {
@@ -129917,7 +130328,7 @@ function providerOutputFailureFromInvalidManifest(messages, responseText) {
129917
130328
  const normalized = responseText.trim().replace(/\s+/g, " ").toLowerCase();
129918
130329
  if (!normalized)
129919
130330
  return null;
129920
- const fingerprint = createHash28("sha256").update(normalized).digest("hex").slice(0, 16);
130331
+ const fingerprint = createHash29("sha256").update(normalized).digest("hex").slice(0, 16);
129921
130332
  return new DreamerProviderOutputFailureError(fingerprint, completion.outputTokens, completion.reasoningTokens, responseText);
129922
130333
  }
129923
130334
 
@@ -130329,7 +130740,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
130329
130740
  log(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
130330
130741
  }
130331
130742
  }
130332
- const commandId = `mural-cues:${route.moduleCommandId}:${createHash29("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
130743
+ const commandId = `mural-cues:${route.moduleCommandId}:${createHash30("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
130333
130744
  let response;
130334
130745
  try {
130335
130746
  response = await route.moduleClient.call({
@@ -130433,8 +130844,10 @@ async function runHiddenSingleShotPrompt(args) {
130433
130844
  callContext: args.callContext,
130434
130845
  fetchOutput: () => args.executor.collect(handle, 50),
130435
130846
  validateOutput: (completion) => {
130847
+ const tokens = completion.tokenLog ?? runTokenLog(undefined);
130848
+ sessionLog(args.parentSessionId ?? "dreamer", `${args.callContext} response_chars=${(completion.text ?? completion.reasoning ?? "").length} ${formatRunTokenLog(tokens)}`);
130436
130849
  if (completion.lengthCapped) {
130437
- throw new Error(completion.reasoning && !completion.text ? `${args.callContext} ran out of output budget while reasoning (length-capped at ${completion.usage.output} tokens, no text) — set dreamer.maxTokens or use a low-reasoning model` : `${args.callContext} returned length-capped output`);
130850
+ throw new Error(completion.reasoning && !completion.text ? `${args.callContext} ran out of output budget while reasoning (length-capped at ${completion.usage.output} tokens, no text; ${formatRunTokenLog(tokens)}) — set dreamer.maxTokens or use a low-reasoning model` : `${args.callContext} returned length-capped output; ${formatRunTokenLog(tokens)}`);
130438
130851
  }
130439
130852
  const text = completion.text;
130440
130853
  if (!text && !args.allowEmpty)
@@ -130913,7 +131326,7 @@ init_dreamer();
130913
131326
  init_language_directive();
130914
131327
  init_compartment_runner_types();
130915
131328
  await init_compartment_runner_historian();
130916
- import { createHash as createHash30 } from "node:crypto";
131329
+ import { createHash as createHash31 } from "node:crypto";
130917
131330
 
130918
131331
  // src/plugin/rust-tool-backends.ts
130919
131332
  function toolCallIdFromContext(context) {
@@ -131304,8 +131717,10 @@ async function classifyOneChunk(args, chunk, anchors, sliceMs, signal) {
131304
131717
  fetchOutput: () => executor.collect(opened, 50),
131305
131718
  validateOutput: (completion) => {
131306
131719
  const messages = completion.messages ?? [];
131720
+ const tokens = completion.tokenLog ?? runTokenLog(undefined);
131721
+ sessionLog(args.parentSessionId ?? "dreamer", `dreamer:classify response_chars=${(completion.text ?? completion.reasoning ?? "").length} ${formatRunTokenLog(tokens)}`);
131307
131722
  if (completion.lengthCapped) {
131308
- throw new Error(completion.reasoning && !completion.text ? `classify ran out of output budget while reasoning (length-capped at ${completion.usage.output} tokens, no text) — set dreamer.maxTokens or use a low-reasoning model` : "classify returned length-capped output");
131723
+ throw new Error(completion.reasoning && !completion.text ? `classify ran out of output budget while reasoning (length-capped at ${completion.usage.output} tokens, no text; ${formatRunTokenLog(tokens)}) — set dreamer.maxTokens or use a low-reasoning model` : `classify returned length-capped output; ${formatRunTokenLog(tokens)}`);
131309
131724
  }
131310
131725
  const text = completion.text;
131311
131726
  if (!text)
@@ -131382,7 +131797,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
131382
131797
  });
131383
131798
  const modelChain = [args.model, ...args.fallbackModels ?? []].map(toModelEntry).filter((entry) => entry !== undefined).map((entry) => entry.model);
131384
131799
  const resolvedModelChain = [...new Set(modelChain)];
131385
- const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash30("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
131800
+ const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash31("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
131386
131801
  const runTask = (hostCompletion) => args.moduleClient?.call({
131387
131802
  sessionId: args.moduleSessionId,
131388
131803
  projectRoot: args.moduleProjectRoot,
@@ -131664,13 +132079,13 @@ function takeCurateSafetyRefusalCount(sessionId) {
131664
132079
 
131665
132080
  // src/features/magic-context/dreamer/docs-proposals.ts
131666
132081
  import { execFileSync as execFileSync3 } from "node:child_process";
131667
- import { createHash as createHash31 } from "node:crypto";
132082
+ import { createHash as createHash32 } from "node:crypto";
131668
132083
  import {
131669
132084
  existsSync as existsSync16,
131670
132085
  mkdirSync as mkdirSync12,
131671
132086
  mkdtempSync,
131672
132087
  readdirSync as readdirSync6,
131673
- readFileSync as readFileSync17,
132088
+ readFileSync as readFileSync18,
131674
132089
  realpathSync as realpathSync5,
131675
132090
  renameSync as renameSync5,
131676
132091
  rmSync as rmSync3,
@@ -131679,12 +132094,12 @@ import {
131679
132094
  import { tmpdir as tmpdir2 } from "node:os";
131680
132095
  import { join as join18 } from "node:path";
131681
132096
  var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
131682
- var hash = (text) => createHash31("sha256").update(text).digest("hex");
132097
+ var hash = (text) => createHash32("sha256").update(text).digest("hex");
131683
132098
  var proposalDir = (projectDir) => join18(projectDir, ".cortexkit/magic-context/docs-update-proposals");
131684
132099
  function docsBaseHashes(projectDir) {
131685
132100
  return Object.fromEntries(FILES.map((name) => [
131686
132101
  name,
131687
- hash(existsSync16(join18(projectDir, name)) ? readFileSync17(join18(projectDir, name), "utf8") : "")
132102
+ hash(existsSync16(join18(projectDir, name)) ? readFileSync18(join18(projectDir, name), "utf8") : "")
131688
132103
  ]));
131689
132104
  }
131690
132105
  function listPendingDocsProposals(projectDir) {
@@ -131693,7 +132108,7 @@ function listPendingDocsProposals(projectDir) {
131693
132108
  }
131694
132109
  function hasCurrentDocsProposal(projectDir) {
131695
132110
  const hashes = docsBaseHashes(projectDir);
131696
- return listPendingDocsProposals(projectDir).some((path) => Object.entries(hashes).every(([name, value]) => readFileSync17(path, "utf8").includes(`Base SHA-256 ${name}: ${value}`)));
132111
+ return listPendingDocsProposals(projectDir).some((path) => Object.entries(hashes).every(([name, value]) => readFileSync18(path, "utf8").includes(`Base SHA-256 ${name}: ${value}`)));
131697
132112
  }
131698
132113
  function git(projectDir, args) {
131699
132114
  return execFileSync3("git", args, {
@@ -131732,7 +132147,7 @@ function docsChangeSet(projectDir, storedAnchor) {
131732
132147
  const files = [
131733
132148
  ...new Set(changed.flat().filter((file) => file !== "ARCHITECTURE.md" && file !== "STRUCTURE.md" && !/(?:^|[./-])(test|spec)(?:[./-]|$)/.test(file) && !file.endsWith(".lock")))
131734
132149
  ];
131735
- const docs = FILES.map((file) => existsSync16(join18(projectDir, file)) ? readFileSync17(join18(projectDir, file), "utf8") : "").join(`
132150
+ const docs = FILES.map((file) => existsSync16(join18(projectDir, file)) ? readFileSync18(join18(projectDir, file), "utf8") : "").join(`
131736
132151
  `);
131737
132152
  const relevant = files.some((file) => {
131738
132153
  const directory = file.split("/").slice(0, -1).join("/");
@@ -131877,7 +132292,7 @@ function validateDocsProposal(projectDir, output, budget, expected) {
131877
132292
  let tokens = 0;
131878
132293
  let diffs = "";
131879
132294
  for (const file of FILES) {
131880
- const before = existsSync16(join18(projectDir, file)) ? readFileSync17(join18(projectDir, file), "utf8") : "";
132295
+ const before = existsSync16(join18(projectDir, file)) ? readFileSync18(join18(projectDir, file), "utf8") : "";
131881
132296
  let after = before;
131882
132297
  const seen = new Set;
131883
132298
  for (const change of changes.filter((item) => item.file === file)) {
@@ -132471,7 +132886,7 @@ function throwIfAborted2(signal) {
132471
132886
  }
132472
132887
 
132473
132888
  // src/features/magic-context/smart-notes/compiler.ts
132474
- import { createHash as createHash32 } from "node:crypto";
132889
+ import { createHash as createHash33 } from "node:crypto";
132475
132890
  init_shared();
132476
132891
  init_assistant_message_extractor();
132477
132892
  init_child_session_teardown();
@@ -132785,7 +133200,7 @@ function manifestAdvisoryWarnings(code, manifest) {
132785
133200
  return warnings;
132786
133201
  }
132787
133202
  function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
132788
- return createHash32("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
133203
+ return createHash33("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
132789
133204
  }
132790
133205
  function extractJsonObject(output) {
132791
133206
  const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
@@ -133573,7 +133988,7 @@ async function archiveExpiredMemories(args) {
133573
133988
 
133574
133989
  // src/features/magic-context/dreamer/maintain-docs-protected-enforcement.ts
133575
133990
  init_logger();
133576
- import { existsSync as existsSync17, readFileSync as readFileSync18, writeFileSync as writeFileSync10 } from "node:fs";
133991
+ import { existsSync as existsSync17, readFileSync as readFileSync19, writeFileSync as writeFileSync10 } from "node:fs";
133577
133992
  import { join as join20 } from "node:path";
133578
133993
  var MAINTAIN_DOCS_SNAPSHOT_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
133579
133994
  function snapshotMaintainDocsFiles(docsDir) {
@@ -133582,7 +133997,7 @@ function snapshotMaintainDocsFiles(docsDir) {
133582
133997
  const path = join20(docsDir, name);
133583
133998
  try {
133584
133999
  if (existsSync17(path)) {
133585
- snapshot.set(name, readFileSync18(path, "utf8"));
134000
+ snapshot.set(name, readFileSync19(path, "utf8"));
133586
134001
  }
133587
134002
  } catch {}
133588
134003
  }
@@ -133600,10 +134015,10 @@ await __promiseAll([
133600
134015
  init_child_session_spawn(),
133601
134016
  init_memory()
133602
134017
  ]);
133603
- import { createHash as createHash33 } from "node:crypto";
134018
+ import { createHash as createHash34 } from "node:crypto";
133604
134019
 
133605
134020
  // src/features/magic-context/dreamer/map-memories-prompt.ts
133606
- import { existsSync as existsSync18, statSync as statSync13 } from "node:fs";
134021
+ import { existsSync as existsSync18, statSync as statSync14 } from "node:fs";
133607
134022
  import path11 from "node:path";
133608
134023
  var MAP_MEMORIES_SYSTEM_PROMPT = `You are a memory mapper for the magic-context system. You map project memories to the repository files that back them.
133609
134024
 
@@ -133641,7 +134056,7 @@ function extractMemoryCandidatePaths(content, repoDir) {
133641
134056
  if (!abs.startsWith(`${root}/`))
133642
134057
  continue;
133643
134058
  try {
133644
- if (existsSync18(abs) && statSync13(abs).isFile())
134059
+ if (existsSync18(abs) && statSync14(abs).isFile())
133645
134060
  found.add(rel);
133646
134061
  } catch {}
133647
134062
  if (found.size >= MAX_SEED_PATHS_PER_MEMORY)
@@ -134065,7 +134480,7 @@ async function applyParsedBatchMappings(args, batch, parsed) {
134065
134480
  memory_project: args.projectIdentity,
134066
134481
  context_store_uuid: args.moduleRoute.moduleContextStoreUuid,
134067
134482
  authority_generation: args.moduleRoute.moduleAuthorityGeneration,
134068
- command_id: `${args.moduleRoute.moduleCommandId}:${createHash33("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
134483
+ command_id: `${args.moduleRoute.moduleCommandId}:${createHash34("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
134069
134484
  rows
134070
134485
  }
134071
134486
  }
@@ -135047,7 +135462,7 @@ await __promiseAll([
135047
135462
  init_child_session_spawn(),
135048
135463
  init_memory()
135049
135464
  ]);
135050
- import { createHash as createHash34 } from "node:crypto";
135465
+ import { createHash as createHash35 } from "node:crypto";
135051
135466
  init_token_budget();
135052
135467
 
135053
135468
  // src/features/magic-context/dreamer/verify-diff.ts
@@ -135787,7 +136202,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt) {
135787
136202
  memory_project: args.projectIdentity,
135788
136203
  context_store_uuid: args.moduleRoute.moduleContextStoreUuid,
135789
136204
  authority_generation: args.moduleRoute.moduleAuthorityGeneration,
135790
- command_id: `${args.moduleRoute.moduleCommandId}:${createHash34("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
136205
+ command_id: `${args.moduleRoute.moduleCommandId}:${createHash35("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
135791
136206
  rows
135792
136207
  }
135793
136208
  }
@@ -136547,7 +136962,7 @@ function parseFrictionGateVerdict(verdict) {
136547
136962
  }
136548
136963
  function computeRetrospectiveWindowKey(flagged) {
136549
136964
  const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
136550
- return createHash35("sha256").update(anchors).digest("hex").slice(0, 32);
136965
+ return createHash36("sha256").update(anchors).digest("hex").slice(0, 32);
136551
136966
  }
136552
136967
  function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
136553
136968
  const flagged = new Set(flaggedOrdinals);
@@ -137013,8 +137428,8 @@ async function runAgenticTask(config, ctx, helpers) {
137013
137428
  existingDocs,
137014
137429
  docsChangeSet: changes?.text,
137015
137430
  docsContents: task === "maintain-docs" ? {
137016
- architecture: existingDocs?.architecture ? readFileSync19(`${docsDir}/ARCHITECTURE.md`, "utf8") : "(missing)",
137017
- structure: existingDocs?.structure ? readFileSync19(`${docsDir}/STRUCTURE.md`, "utf8") : "(missing)"
137431
+ architecture: existingDocs?.architecture ? readFileSync20(`${docsDir}/ARCHITECTURE.md`, "utf8") : "(missing)",
137432
+ structure: existingDocs?.structure ? readFileSync20(`${docsDir}/STRUCTURE.md`, "utf8") : "(missing)"
137018
137433
  } : undefined,
137019
137434
  docsBudget: config.docsMaxTokens ?? 12000,
137020
137435
  docsCurrentTokens: maintainDocsSnapshot ? Math.ceil([...maintainDocsSnapshot.values()].join("").length / 3.5) : 0,
@@ -137665,10 +138080,19 @@ function startDreamTrigger(context, args) {
137665
138080
  // src/v2/hooks/context.ts
137666
138081
  init_hidden_child();
137667
138082
 
138083
+ // src/v2/hooks/hidden-terminal-error.ts
138084
+ function hiddenTerminalError(event) {
138085
+ if (event.type === "session.execution.failed")
138086
+ return event.data?.error;
138087
+ if (event.type === "session.error")
138088
+ return getSessionErrorInfo(event.data)?.error;
138089
+ return;
138090
+ }
138091
+
137668
138092
  // src/v2/hooks/lkg-system.ts
137669
- import { createHash as createHash36 } from "node:crypto";
138093
+ import { createHash as createHash37 } from "node:crypto";
137670
138094
  function identity(slot) {
137671
- return createHash36("sha256").update(JSON.stringify({
138095
+ return createHash37("sha256").update(JSON.stringify({
137672
138096
  capturedAt: slot.capturedAt,
137673
138097
  captureSequence: slot.captureSequence,
137674
138098
  rowVersion: slot.rowVersion,
@@ -151434,6 +151858,7 @@ init_agent_disable();
151434
151858
  init_project_identity();
151435
151859
  init_protection_window();
151436
151860
  init_storage_meta_persisted();
151861
+ await init_sqlite();
151437
151862
 
151438
151863
  // src/tools/ctx-expand/tools.ts
151439
151864
  init_compartment_storage();
@@ -153470,7 +153895,7 @@ Keep: user messages (never stamp one for its directive), your own conversation t
153470
153895
 
153471
153896
  Look at each tag before stamping it; never blanket-stamp a range like "1-50". Many small targeted stamps beat one sweep. \`drop\` accepts "3-5", "1,2,9", "1-5,8,12-15".`;
153472
153897
  // src/tools/ctx-reduce/tools.ts
153473
- import { createHash as createHash37 } from "node:crypto";
153898
+ import { createHash as createHash38 } from "node:crypto";
153474
153899
  init_protection_window();
153475
153900
 
153476
153901
  // src/features/magic-context/range-parser.ts
@@ -153544,11 +153969,11 @@ function createCtxReduceTool(deps) {
153544
153969
  const stableId = `oc-${sessionId}-${callId}`;
153545
153970
  if (Buffer.byteLength(stableId) <= 128)
153546
153971
  return stableId;
153547
- return `oc-${createHash37("sha256").update(stableId).digest("hex")}`;
153972
+ return `oc-${createHash38("sha256").update(stableId).digest("hex")}`;
153548
153973
  }
153549
153974
  fallbackCommandSequence += 1;
153550
153975
  const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
153551
- return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash37("sha256").update(monotonicId).digest("hex")}`;
153976
+ return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash38("sha256").update(monotonicId).digest("hex")}`;
153552
153977
  };
153553
153978
  return tool({
153554
153979
  description: CTX_REDUCE_DESCRIPTION,
@@ -153909,6 +154334,10 @@ async function registerTools(context, db, config, rustToolBackends) {
153909
154334
  input: tool.schema.toJSONSchema(tool.schema.object(definition.args)),
153910
154335
  options: { codemode: false },
153911
154336
  async execute(input, call) {
154337
+ if (name === "ctx_memory" || name === "ctx_note" || name === "ctx_reduce")
154338
+ await withAsyncPrivilegedWriter(db, () => {
154339
+ return;
154340
+ });
153912
154341
  const result = await definition.execute(tool.schema.object(definition.args).parse(input), {
153913
154342
  sessionID: call.sessionID,
153914
154343
  messageID: call.messageID,
@@ -154145,6 +154574,7 @@ async function applyV2SystemPrompt(systemPrompt, draft) {
154145
154574
  async function registerContext(context) {
154146
154575
  const directory = context.location.directory;
154147
154576
  const config = loadPluginConfigDetailed(directory).config;
154577
+ setHomeProjectPermission(config.allow_home_project);
154148
154578
  if (!config.enabled)
154149
154579
  return;
154150
154580
  const liveConfigReader = pluginConfigReader(directory, config);
@@ -154253,6 +154683,7 @@ async function registerContext(context) {
154253
154683
  }, {
154254
154684
  db: database,
154255
154685
  projectIdentity: resolveProjectIdentityForSession(directory, config.allow_home_project) ?? "",
154686
+ directory,
154256
154687
  hook: hiddenChildHook,
154257
154688
  keepSubagents: config.keep_subagents === true,
154258
154689
  ensureAgent: () => hiddenAgentsReady ??= context.agent.reload(),
@@ -154455,8 +154886,8 @@ async function registerContext(context) {
154455
154886
  if (!event.data?.sessionID)
154456
154887
  continue;
154457
154888
  const sessionID = event.data.sessionID;
154458
- if (event.type === "session.error") {
154459
- const error = getSessionErrorInfo(event.data)?.error;
154889
+ if (event.type === "session.error" || event.type === "session.execution.failed") {
154890
+ const error = hiddenTerminalError(event);
154460
154891
  if (error !== undefined)
154461
154892
  hiddenSessionErrors.set(sessionID, error);
154462
154893
  continue;
@@ -154579,7 +155010,7 @@ async function registerContext(context) {
154579
155010
  try {
154580
155011
  const admissionDb = db ?? storage.current();
154581
155012
  if (!compactionOff && admissionDb)
154582
- withPrivilegedWriter(admissionDb, () => {
155013
+ await withAsyncPrivilegedWriter(admissionDb, () => {
154583
155014
  return;
154584
155015
  });
154585
155016
  recordV2ToolDefinitions(draft);
@@ -154965,7 +155396,7 @@ ${baseline}
154965
155396
  }
154966
155397
 
154967
155398
  // src/v2/hooks/update-check.ts
154968
- import { existsSync as existsSync22, readFileSync as readFileSync20 } from "node:fs";
155399
+ import { existsSync as existsSync22, readFileSync as readFileSync21 } from "node:fs";
154969
155400
  import { dirname as dirname11, join as join23 } from "node:path";
154970
155401
  import { fileURLToPath as fileURLToPath2 } from "node:url";
154971
155402
 
@@ -155046,7 +155477,7 @@ function packageInfo() {
155046
155477
  let directory = dirname11(fileURLToPath2(import.meta.url));
155047
155478
  for (;; ) {
155048
155479
  try {
155049
- const pkg = JSON.parse(readFileSync20(join23(directory, "package.json"), "utf8"));
155480
+ const pkg = JSON.parse(readFileSync21(join23(directory, "package.json"), "utf8"));
155050
155481
  if (pkg.name === "@cortexkit/opencode-magic-context" && typeof pkg.version === "string") {
155051
155482
  return {
155052
155483
  version: pkg.version,