@cortexkit/opencode-magic-context 0.49.64 → 0.49.66

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 (90) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{context-v1apxpct.js → context-1acz1d4x.js} +18 -15
  4. package/dist/features/magic-context/compartment-storage.d.ts +7 -0
  5. package/dist/features/magic-context/compartment-storage.d.ts.map +1 -1
  6. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  7. package/dist/features/magic-context/storage-meta-shared.d.ts +5 -1
  8. package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
  9. package/dist/features/magic-context/types.d.ts +2 -0
  10. package/dist/features/magic-context/types.d.ts.map +1 -1
  11. package/dist/hooks/magic-context/compartment-prompt.d.ts +8 -1
  12. package/dist/hooks/magic-context/compartment-prompt.d.ts.map +1 -1
  13. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  14. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  15. package/dist/hooks/magic-context/compartment-runner-types.d.ts +5 -0
  16. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  17. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/historian-prompt-fit.d.ts +10 -3
  19. package/dist/hooks/magic-context/historian-prompt-fit.d.ts.map +1 -1
  20. package/dist/hooks/magic-context/hook.d.ts +3 -0
  21. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/inject-compartments.d.ts +35 -1
  23. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/reference-retrieval.d.ts +3 -2
  25. package/dist/hooks/magic-context/reference-retrieval.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/transform.d.ts +3 -0
  28. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/unmanaged-over-window.d.ts +4 -0
  30. package/dist/hooks/magic-context/unmanaged-over-window.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/wrapup-orchestrator.d.ts +1 -0
  32. package/dist/hooks/magic-context/wrapup-orchestrator.d.ts.map +1 -1
  33. package/dist/{index-aq4yfcq6.js → index-2t9e10mt.js} +122 -43
  34. package/dist/{index-7dj3s7qq.js → index-2x46rnct.js} +1 -1
  35. package/dist/{index-71h616be.js → index-3v5mfapn.js} +1 -1
  36. package/dist/{index-m568xww6.js → index-8a1m48va.js} +3 -3
  37. package/dist/{index-gwb2wpz7.js → index-fybdhbd4.js} +2 -2
  38. package/dist/{index-qn27gh4e.js → index-g53qhdrb.js} +1 -1
  39. package/dist/{index-5fbeycst.js → index-gy33sq5h.js} +6 -6
  40. package/dist/{index-zdd01nhc.js → index-m47yte97.js} +124 -38
  41. package/dist/{index-c0k54yhd.js → index-m6cv2hv3.js} +3 -3
  42. package/dist/{index-g59gpt1j.js → index-nfvyraa3.js} +3 -3
  43. package/dist/{index-ezr8mr1c.js → index-ngrrs3yb.js} +13 -4
  44. package/dist/{index-6kgsfb81.js → index-q73yeb83.js} +1 -1
  45. package/dist/{index-kvfrse61.js → index-t20q6aj6.js} +12 -1
  46. package/dist/{index-0ab398z2.js → index-xmk2a6pq.js} +2 -2
  47. package/dist/{index-hs9xxmmy.js → index-z10dryn5.js} +6 -5
  48. package/dist/index.js +19 -18
  49. package/dist/{message-index-bounded-zs7ah2te.js → message-index-bounded-f27039js.js} +3 -3
  50. package/dist/migration-worker.js +1 -1
  51. package/dist/plugin/hooks/create-session-hooks.d.ts +6 -0
  52. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  53. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  54. package/dist/raw-ordinal-warmup-worker.js +4 -4
  55. package/dist/{read-session-chunk-jf2f8jz8.js → read-session-chunk-4ma2vsva.js} +2 -2
  56. package/dist/{recomp-orchestrator-6vxnrh2w.js → recomp-orchestrator-p9c4jg9m.js} +7 -7
  57. package/dist/{render-n46wpv2n.js → render-h16ea0th.js} +6 -6
  58. package/dist/{search-archive-9k6vsp44.js → search-archive-km2ahm3e.js} +4 -4
  59. package/dist/{search-s386bwwh.js → search-m9rpnh7m.js} +5 -5
  60. package/dist/{storage-tags-2r952wqy.js → storage-tags-ktp70q1e.js} +1 -1
  61. package/dist/{transform-postprocess-phase-jjc9jcer.js → transform-postprocess-phase-120s1ep8.js} +8 -8
  62. package/dist/v2/auto-search-worker.js +1 -1
  63. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  64. package/dist/v2/{context-nfkhb5sv.js → context-p0z7mrsf.js} +121 -40
  65. package/dist/v2/hooks/context.d.ts.map +1 -1
  66. package/dist/v2/{message-index-bounded-axbs1s97.js → message-index-bounded-td516y9c.js} +3 -3
  67. package/dist/v2/migration-worker.js +1 -1
  68. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  69. package/dist/v2/{read-session-chunk-41cm522x.js → read-session-chunk-6dz32wmh.js} +2 -2
  70. package/dist/v2/{recomp-orchestrator-krccyz0a.js → recomp-orchestrator-ayy7xzm3.js} +6 -6
  71. package/dist/v2/{render-7v7yx9xb.js → render-gqp4fwqn.js} +6 -6
  72. package/dist/v2/{search-archive-1yc8bh6y.js → search-archive-qn82j8k0.js} +4 -4
  73. package/dist/v2/{search-mabwkzw2.js → search-dhekqtfc.js} +4 -4
  74. package/dist/v2/{server-yxw43z2w.js → server-166m5nrw.js} +13 -4
  75. package/dist/v2/{server-bh9yzxpz.js → server-34vhmd1d.js} +2 -2
  76. package/dist/v2/{server-k97r77x3.js → server-77207nf4.js} +2 -2
  77. package/dist/v2/{server-hcgqsdrh.js → server-jew1m85s.js} +1 -1
  78. package/dist/v2/{server-xse5jngy.js → server-n6hdj0fn.js} +124 -38
  79. package/dist/v2/{server-8w9b5exq.js → server-q8ta10e5.js} +1 -1
  80. package/dist/v2/{server-cdddk5d1.js → server-s1a0bwpc.js} +1 -1
  81. package/dist/v2/{server-anh8gf0w.js → server-s66wvkpf.js} +2 -2
  82. package/dist/v2/{server-hb5zm7yh.js → server-verzg5w8.js} +12 -1
  83. package/dist/v2/{server-bnka2vf2.js → server-xwcg55a8.js} +3 -3
  84. package/dist/v2/server.js +2 -2
  85. package/dist/v2/{storage-tags-9zs0gc7w.js → storage-tags-qe8r1n9w.js} +1 -1
  86. package/dist/v2/{v2-archive-reader-pgk140pb.js → v2-archive-reader-tbjwxvc5.js} +1 -1
  87. package/dist/v2/{wrapup-orchestrator-v2rgtczc.js → wrapup-orchestrator-ksdzyfby.js} +7 -6
  88. package/dist/{v2-archive-reader-cv6veqnz.js → v2-archive-reader-j16k987e.js} +1 -1
  89. package/dist/{wrapup-orchestrator-qbtg1dhm.js → wrapup-orchestrator-w09bkgmk.js} +8 -8
  90. package/package.json +1 -1
@@ -32,6 +32,7 @@ import {
32
32
  providerVisibleMessage,
33
33
  MERGED_REASONING_PARTS_PREFIX,
34
34
  decodeMergedReasoningParts,
35
+ CACHED_TRIM_PARTIAL_SQL,
35
36
  SESSION_META_SELECT_COLUMNS,
36
37
  META_COLUMNS,
37
38
  BOOLEAN_META_KEYS,
@@ -57,7 +58,7 @@ import {
57
58
  getPendingPiCompactionMarkerState,
58
59
  logPiCompactionMarkerClear,
59
60
  isPrefixBoundThinkingModel
60
- } from "./server-hb5zm7yh.js";
61
+ } from "./server-verzg5w8.js";
61
62
  import {
62
63
  BoundedSessionMap,
63
64
  getMeasuredToolDefinitionTokens,
@@ -292,6 +293,10 @@ function getCompartments(db, sessionId) {
292
293
  FROM compartments WHERE session_id = ? ORDER BY sequence ASC`).all(sessionId).filter(isCompartmentRow);
293
294
  return rows.map(toCompartment);
294
295
  }
296
+ function getNewestCompartmentIds(db, sessionId, count) {
297
+ const rows = db.prepare("SELECT id FROM compartments WHERE session_id = ? ORDER BY sequence DESC LIMIT ?").all(sessionId, count);
298
+ return rows.reverse().map(({ id }) => id);
299
+ }
295
300
  function getLastCompartmentEndMessage(db, sessionId) {
296
301
  const row = db.prepare("SELECT MAX(end_message) as max_end FROM compartments WHERE session_id = ? AND rebase_status != 'unresolved'").get(sessionId);
297
302
  return row?.max_end ?? -1;
@@ -1354,6 +1359,7 @@ var SESSION_META_FALLBACK_SELECTS = {
1354
1359
  last_todo_state: "'' AS last_todo_state",
1355
1360
  tool_reclaim_watermark: "0 AS tool_reclaim_watermark",
1356
1361
  cached_m0_bytes: "NULL AS cached_m0_bytes",
1362
+ cached_m0_last_baseline_end_message_id: "NULL AS cached_m0_last_baseline_end_message_id",
1357
1363
  cached_m0_mural_data_url: "NULL AS cached_m0_mural_data_url",
1358
1364
  cached_m0_mural_hash: "NULL AS cached_m0_mural_hash",
1359
1365
  cached_m1_bytes: "NULL AS cached_m1_bytes",
@@ -1382,11 +1388,14 @@ function getSessionMetaSelectColumns(db) {
1382
1388
  if (cached !== undefined)
1383
1389
  return cached;
1384
1390
  const existingColumns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
1385
- const projection = SESSION_META_SELECT_COLUMNS.map((column) => {
1391
+ const columns = SESSION_META_SELECT_COLUMNS.map((column) => {
1386
1392
  if (existingColumns.has(column))
1387
1393
  return column;
1388
1394
  return SESSION_META_FALLBACK_SELECTS[column] ?? `0 AS ${column}`;
1389
- }).join(", ");
1395
+ });
1396
+ if (existingColumns.has("cached_m0_last_baseline_end_message_id") && getTableColumnNames(db, "compartments").has("end_block_index"))
1397
+ columns.push(`${CACHED_TRIM_PARTIAL_SQL} AS cached_trim_partial`);
1398
+ const projection = columns.join(", ");
1390
1399
  sessionMetaSelectColumnsCache.set(db, projection);
1391
1400
  return projection;
1392
1401
  }
@@ -5136,4 +5145,4 @@ var ERROR_CLASSES = new Set([
5136
5145
  "permission_denied",
5137
5146
  "unknown"
5138
5147
  ]);
5139
- export { COMPARTMENT_LEASE_RENEWAL_MS, getCompartmentLeaseBlocker, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, buildCompartmentBlock, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, readServerFallbackUsage, providerResponseFailed, isSuccessfulProviderCompletion, LkgRecoveryFenceError, lkgServedArrayDigest, hasCleanLkgRecoveryFence, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, advanceSessionActivity, backfillSessionActivity, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, clearPendingMaterializationOrigin, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, readPersistedLkgUntaggedInputIds, persistLkgUntaggedInputIds, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, beginServedRequest, noteServedPassPermission, noteServedModel, noteServedReplay, noteServedHostInput, noteServedRefusal, countServedRefusal, dropServedRecord, forgetServedRecord, commitServedRequest, lkgInputIdentity, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, externalHistorianFailureReason, getRecentFailedHistorianRunTimes, recordHistorianRun, summarizeImportance, tallyFactsByCategory, MEMORY_VISIBILITY_MUTATION_CATEGORY, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId };
5148
+ export { COMPARTMENT_LEASE_RENEWAL_MS, getCompartmentLeaseBlocker, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, queueM0Mutation, getMaxM0MutationId, getCompartments, getNewestCompartmentIds, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, buildCompartmentBlock, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, readServerFallbackUsage, providerResponseFailed, isSuccessfulProviderCompletion, LkgRecoveryFenceError, lkgServedArrayDigest, hasCleanLkgRecoveryFence, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, advanceSessionActivity, backfillSessionActivity, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, clearPendingMaterializationOrigin, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, readPersistedLkgUntaggedInputIds, persistLkgUntaggedInputIds, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, beginServedRequest, noteServedPassPermission, noteServedModel, noteServedReplay, noteServedHostInput, noteServedRefusal, countServedRefusal, dropServedRecord, forgetServedRecord, commitServedRequest, lkgInputIdentity, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, externalHistorianFailureReason, getRecentFailedHistorianRunTimes, recordHistorianRun, summarizeImportance, tallyFactsByCategory, MEMORY_VISIBILITY_MUTATION_CATEGORY, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId };
@@ -15,7 +15,7 @@ import {
15
15
  } from "./server-afsz3cmx.js";
16
16
  import {
17
17
  isRecord
18
- } from "./server-hb5zm7yh.js";
18
+ } from "./server-verzg5w8.js";
19
19
  import {
20
20
  cleanSearchText,
21
21
  hintKeywordRelevance,
@@ -25,7 +25,7 @@ import {
25
25
  isMessageIndexReconciledThrough,
26
26
  clearIndexedMessages,
27
27
  indexMessagesAfterOrdinal
28
- } from "./server-8w9b5exq.js";
28
+ } from "./server-q8ta10e5.js";
29
29
  import {
30
30
  Priority,
31
31
  AdmissionClass,
@@ -3,12 +3,12 @@ import {
3
3
  } from "./server-y8xjr8rx.js";
4
4
  import {
5
5
  getTagById2
6
- } from "./server-hb5zm7yh.js";
6
+ } from "./server-verzg5w8.js";
7
7
  import {
8
8
  expandToolPart,
9
9
  visitRawSessionMessages2,
10
10
  readRawSessionMessageById2
11
- } from "./server-cdddk5d1.js";
11
+ } from "./server-s1a0bwpc.js";
12
12
 
13
13
  // src/tools/ctx-expand/render.ts
14
14
  import { createHash } from "node:crypto";
@@ -1021,7 +1021,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1021
1021
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
1022
1022
  if (signal.aborted || !readsOpenCodeStore)
1023
1023
  return;
1024
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-41cm522x.js"));
1024
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-6dz32wmh.js"));
1025
1025
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-ynb3vg6r.js"));
1026
1026
  if (signal.aborted)
1027
1027
  return;
@@ -59,6 +59,7 @@ import {
59
59
  isRecord,
60
60
  escalationBands,
61
61
  sessionDecisionCalibration,
62
+ CACHED_TRIM_PARTIAL_SQL,
62
63
  ensureSessionMetaRow,
63
64
  persistCachedM0,
64
65
  clearCachedM0M1,
@@ -100,7 +101,7 @@ import {
100
101
  foldShrunkPartTags2,
101
102
  getTagNumberByMessageId2,
102
103
  getActiveTagsBySession2
103
- } from "./server-hb5zm7yh.js";
104
+ } from "./server-verzg5w8.js";
104
105
  import {
105
106
  hasMeaningfulUserText2,
106
107
  estimateTokens,
@@ -155,14 +156,14 @@ import {
155
156
  getRawSessionTagKeysThrough2,
156
157
  getLegacyProtectedTailStartOrdinal2,
157
158
  readSessionChunk2
158
- } from "./server-cdddk5d1.js";
159
+ } from "./server-s1a0bwpc.js";
159
160
  import {
160
161
  clearCompressionDepth,
161
162
  clearCompressionDepthRange,
162
163
  toMessageIndexSource,
163
164
  clearIndexedMessagesInTransaction,
164
165
  indexSourcesAfterOrdinal
165
- } from "./server-8w9b5exq.js";
166
+ } from "./server-q8ta10e5.js";
166
167
  import {
167
168
  COMPARTMENT_LEASE_RENEWAL_MS,
168
169
  getCompartmentLeaseBlocker,
@@ -175,6 +176,7 @@ import {
175
176
  queueM0Mutation,
176
177
  getMaxM0MutationId,
177
178
  getCompartments,
179
+ getNewestCompartmentIds,
178
180
  getLastCompartmentEndMessage,
179
181
  getLastCompartmentEndMessageId,
180
182
  getCompartmentsByEndMessageId,
@@ -207,7 +209,7 @@ import {
207
209
  getProjectState,
208
210
  recordSubagentInvocation,
209
211
  getLatestHistorianInvocationId
210
- } from "./server-yxw43z2w.js";
212
+ } from "./server-166m5nrw.js";
211
213
  import {
212
214
  invalidateAutoEmbedSession
213
215
  } from "./server-2amn2s73.js";
@@ -267,7 +269,7 @@ import {
267
269
  LATEST_SUPPORTED_VERSION,
268
270
  getPersistedSchemaVersion,
269
271
  openDatabase
270
- } from "./server-hcgqsdrh.js";
272
+ } from "./server-jew1m85s.js";
271
273
  import {
272
274
  parseCompartmentOutput,
273
275
  resolveWorkspaceShareCategories,
@@ -6016,11 +6018,11 @@ var USER_OBSERVATIONS_DISABLED_TOGGLE = `<user_observation_extraction>disabled</
6016
6018
  User-memory review is not running (the dreamer is disabled): do NOT emit a <user_observations> block.`;
6017
6019
  function buildCompartmentAgentPrompt(inputs) {
6018
6020
  const parts = [];
6021
+ parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
6019
6022
  if (inputs.seedExamples)
6020
6023
  parts.push(inputs.seedExamples);
6021
6024
  if (inputs.sessionReferences)
6022
6025
  parts.push(inputs.sessionReferences);
6023
- parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
6024
6026
  if (inputs.extractionFree) {
6025
6027
  parts.push(`<extraction>disabled</extraction>
6026
6028
  Structural recomp mode: emit compartments and <meta> only. Do NOT emit <facts>, <events>, <user_observations>, or <primer_candidates>.`);
@@ -6040,6 +6042,34 @@ Memory is disabled for this project: do NOT emit a <facts> block. Produce compar
6040
6042
 
6041
6043
  `);
6042
6044
  }
6045
+ function logHistorianPromptSizes(sessionId, system, prompt) {
6046
+ const sourceStart = prompt.indexOf(`<new_messages>
6047
+
6048
+ `);
6049
+ const sourceEnd = prompt.lastIndexOf(`
6050
+
6051
+ </new_messages>
6052
+
6053
+ ${HISTORIAN_TRANSCRIPT_GUARD}`);
6054
+ const hasSource = sourceStart !== -1 && sourceEnd > sourceStart;
6055
+ const blockBytes = (tag) => {
6056
+ if (!hasSource)
6057
+ return 0;
6058
+ const start = prompt.indexOf(`<${tag}>`);
6059
+ const close = `</${tag}>`;
6060
+ const end = prompt.indexOf(close, start + 1);
6061
+ return start >= 0 && end > start && end < sourceStart ? Buffer.byteLength(prompt.slice(start, end + close.length)) : 0;
6062
+ };
6063
+ const memoryBytes = blockBytes("project-memory");
6064
+ const seedBytes = blockBytes("compartment_examples_from_other_projects");
6065
+ const referenceBytes = blockBytes("session_references");
6066
+ const newMessageBytes = hasSource ? Buffer.byteLength(prompt.slice(sourceStart, sourceEnd + `
6067
+
6068
+ </new_messages>`.length)) : 0;
6069
+ const systemBytes = Buffer.byteLength(system);
6070
+ const userBytes = Buffer.byteLength(prompt);
6071
+ sessionLog2(sessionId, `historian request sizes: systemBytes=${systemBytes} userBytes=${userBytes} memoryBytes=${memoryBytes} seedBytes=${seedBytes} referenceBytes=${referenceBytes} newMessageBytes=${newMessageBytes}`);
6072
+ }
6043
6073
 
6044
6074
  // src/hooks/magic-context/compartment-runner-drop-queue.ts
6045
6075
  function prepareCompartmentDrops(db, sessionId, upToMessageIndex, observedKeys, fromMessageIndex = 1) {
@@ -8187,13 +8217,13 @@ function cutCoveredPrefix(messages, count, coveredInstructions) {
8187
8217
  coveredInstructions.push(message);
8188
8218
  }
8189
8219
  }
8190
- function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, coveredInstructions, projectPath, injectionBudgetTokens, temporalAwareness) {
8220
+ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, coveredInstructions, projectPath, injectionBudgetTokens, temporalAwareness, frozenBaseline) {
8191
8221
  const cached = injectionCache.get(sessionId);
8192
8222
  if (cached && cached.db !== db) {
8193
8223
  clearInjectionCache(sessionId);
8194
8224
  }
8195
8225
  const usableCached = cached?.db === db ? cached : undefined;
8196
- if (!isCacheBusting && usableCached) {
8226
+ if (!isCacheBusting && usableCached && (!frozenBaseline?.hasCachedM0 || (usableCached.kind === "empty" ? frozenBaseline.boundary === null : usableCached.injection.compartmentEndMessageId === (frozenBaseline.boundary ?? "")))) {
8197
8227
  if (usableCached.kind === "empty") {
8198
8228
  return null;
8199
8229
  }
@@ -8204,7 +8234,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
8204
8234
  if (prepared.compartmentEndMessageId.length > 0) {
8205
8235
  const cutoffIndex = findBoundaryIndex(sessionId, messages, prepared.compartmentEndMessageId);
8206
8236
  if (cutoffIndex >= 0) {
8207
- cutCoveredPrefix(messages, cutoffIndex + (isPartialCompartmentEnd(db, sessionId, prepared.compartmentEndMessageId) ? 0 : 1), coveredInstructions);
8237
+ cutCoveredPrefix(messages, cutoffIndex + ((frozenBaseline?.hasCachedM0 ? frozenBaseline.partial : prepared.compartmentEndMessagePartial) ? 0 : 1), coveredInstructions);
8208
8238
  } else {
8209
8239
  sessionLog2(sessionId, `compartment injection: cached boundary ${prepared.compartmentEndMessageId} not in messages (already trimmed), reusing cache`);
8210
8240
  }
@@ -8290,11 +8320,13 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
8290
8320
  const lastEnd = lastCompartment.endMessage;
8291
8321
  const lastEndMessageId = newestCompartmentEndId(compartments) ?? "";
8292
8322
  let trimEndMessageId = lastEndMessageId;
8293
- const baseline = readCachedBaselineState(db, sessionId);
8323
+ const baseline = frozenBaseline ?? readCachedBaselineState(db, sessionId);
8324
+ let trimEndMessagePartial = compartments.some((row) => row.endMessageId === lastEndMessageId && row.endBlockIndex != null);
8294
8325
  if (!isCacheBusting || baseline.hasCachedM0) {
8295
8326
  if (baseline.hasCachedM0) {
8296
8327
  if (baseline.boundary) {
8297
8328
  trimEndMessageId = baseline.boundary;
8329
+ trimEndMessagePartial = baseline.partial;
8298
8330
  } else {
8299
8331
  trimEndMessageId = "";
8300
8332
  }
@@ -8322,12 +8354,14 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
8322
8354
  let needsFreshMaterialization = false;
8323
8355
  let resultEndMessage = lastEnd;
8324
8356
  let resultEndMessageId = null;
8357
+ let resultEndMessagePartial = false;
8325
8358
  const cutoffIndex = findBoundaryIndex(sessionId, messages, trimEndMessageId);
8326
8359
  if (cutoffIndex >= 0) {
8327
8360
  clearDegradedRebuild(sessionId);
8328
- skippedVisibleMessages = cutoffIndex + (isPartialCompartmentEnd(db, sessionId, trimEndMessageId) ? 0 : 1);
8361
+ skippedVisibleMessages = cutoffIndex + (trimEndMessagePartial ? 0 : 1);
8329
8362
  cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
8330
8363
  resultEndMessageId = trimEndMessageId;
8364
+ resultEndMessagePartial = trimEndMessagePartial;
8331
8365
  } else {
8332
8366
  const degradedCount = noteDegradedRebuild(sessionId);
8333
8367
  if (isCacheBusting) {
@@ -8345,7 +8379,8 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
8345
8379
  const reAnchorCompartment = compartments[reAnchorIndex];
8346
8380
  const reAnchorCutoff = findBoundaryIndex(sessionId, messages, reAnchorCompartment.endMessageId);
8347
8381
  if (reAnchorCutoff >= 0) {
8348
- skippedVisibleMessages = reAnchorCutoff + (isPartialCompartmentEnd(db, sessionId, reAnchorCompartment.endMessageId) ? 0 : 1);
8382
+ resultEndMessagePartial = compartments.some((row) => row.endMessageId === reAnchorCompartment.endMessageId && row.endBlockIndex != null);
8383
+ skippedVisibleMessages = reAnchorCutoff + (resultEndMessagePartial ? 0 : 1);
8349
8384
  cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
8350
8385
  resultEndMessage = reAnchorCompartment.endMessage;
8351
8386
  resultEndMessageId = reAnchorCompartment.endMessageId;
@@ -8365,6 +8400,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
8365
8400
  block,
8366
8401
  compartmentEndMessage: resultEndMessage,
8367
8402
  compartmentEndMessageId: resultEndMessageId,
8403
+ compartmentEndMessagePartial: resultEndMessagePartial,
8368
8404
  compartmentCount: compartments.length,
8369
8405
  skippedVisibleMessages,
8370
8406
  factCount: facts.length,
@@ -8378,11 +8414,13 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
8378
8414
  return result;
8379
8415
  }
8380
8416
  function readCachedBaselineState(db, sessionId) {
8381
- const row = db.prepare("SELECT cached_m0_bytes AS m0, cached_m0_last_baseline_end_message_id AS boundary FROM session_meta WHERE session_id = ?").get(sessionId);
8417
+ const row = db.prepare(`SELECT cached_m0_bytes AS m0, cached_m0_last_baseline_end_message_id AS boundary,
8418
+ ${CACHED_TRIM_PARTIAL_SQL} AS partial FROM session_meta WHERE session_id = ?`).get(sessionId);
8382
8419
  const boundary = row?.boundary;
8383
8420
  return {
8384
8421
  hasCachedM0: row?.m0 != null,
8385
- boundary: boundary && boundary.length > 0 ? boundary : null
8422
+ boundary: boundary && boundary.length > 0 ? boundary : null,
8423
+ partial: row?.partial === 1
8386
8424
  };
8387
8425
  }
8388
8426
  function renderCompartmentInjection(sessionId, messages, prepared) {
@@ -8522,6 +8560,9 @@ function sourceNamesForMemories(args) {
8522
8560
  }
8523
8561
  return names.size > 0 ? names : undefined;
8524
8562
  }
8563
+ function readM0ProjectMemories(db, projectPath, workspace, at = Date.now()) {
8564
+ return workspace.isWorkspaced ? getMemoriesByProjects2(db, workspace.expandedIdentities, ["active", "permanent"], at, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject2(db, projectPath, ["active", "permanent"], at);
8565
+ }
8525
8566
  function memoryCanonicalIdentity(memory, workspace) {
8526
8567
  return resolveStoredPathWorkspaceIdentity(memory.projectPath, workspace.identities, workspace.canonicalIdentityByStoredPath);
8527
8568
  }
@@ -9298,7 +9339,7 @@ function materializeM0(options) {
9298
9339
  snapshotMarkers.projectDocsHash = docs.canonicalHash;
9299
9340
  compartments = options.compactionOff ? [] : readM0Compartments(options.db, options.sessionId);
9300
9341
  facts = [];
9301
- memories = projectPath ? workspace.isWorkspaced ? getMemoriesByProjects2(options.db, workspace.expandedIdentities, ["active", "permanent"], foldMaterializedAt, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject2(options.db, projectPath, ["active", "permanent"], foldMaterializedAt) : [];
9342
+ memories = projectPath ? readM0ProjectMemories(options.db, projectPath, workspace, foldMaterializedAt) : [];
9302
9343
  userMemories = options.memoryEnabled === false ? [] : safeGetActiveUserMemories(options.db);
9303
9344
  options.db.exec("COMMIT");
9304
9345
  } catch (error) {
@@ -9362,6 +9403,7 @@ function materializeM0(options) {
9362
9403
  const steps = new WriteTransactionSteps;
9363
9404
  const upgradeIdentity = withCachedM0ToolDefinitionsHash(withCachedM0MemoryIds(encodeCachedM0UpgradeIdentity(snapshotMarkers.upgradeState, snapshotMarkers.compartmentRenderEpoch, snapshotMarkers.muralEnabled, snapshotMarkers.renderBudgetIdentity, snapshotMarkers.memoryRenderEpoch, snapshotMarkers.renderedBudgets ?? null), renderedMemoryIds), snapshotMarkers.toolDefinitionsHash ?? null);
9364
9405
  const baselineEndMessageId = lastCompartmentBoundaryId(compartments);
9406
+ const baselineEndPartial = compartments.some((row) => row.endMessageId === baselineEndMessageId && row.endBlockIndex != null);
9365
9407
  steps.mark("pre_metadata");
9366
9408
  const commitFold = options.onFoldPrepare?.();
9367
9409
  steps.mark("pre_onFoldPrepare");
@@ -9452,6 +9494,8 @@ function materializeM0(options) {
9452
9494
  logSlowWriteTransaction("opencode_materialize_cache", transactionStartedAt, undefined, performance.now(), steps.durations);
9453
9495
  options.state.cachedM0MuralDataUrl = frozenMuralDataUrl;
9454
9496
  options.state.cachedM0MuralHash = frozenMuralHash;
9497
+ options.state.cachedM0TrimBoundaryId = baselineEndMessageId;
9498
+ options.state.cachedM0TrimBoundaryPartial = baselineEndPartial;
9455
9499
  } catch (error) {
9456
9500
  try {
9457
9501
  options.db.exec("ROLLBACK");
@@ -9636,7 +9680,7 @@ function hydrateCachedM0Mural(db, sessionId, state) {
9636
9680
  state.cachedM0MuralHash = row.cached_m0_mural_hash ?? null;
9637
9681
  }
9638
9682
  }
9639
- function readCachedM0M1Row(db, sessionId) {
9683
+ function readCachedM0M1Row(db, sessionId, includePartialBoundary = false) {
9640
9684
  return db.prepare(`SELECT cached_m0_bytes, cached_m0_mural_data_url,
9641
9685
  cached_m0_mural_hash, cached_m1_bytes,
9642
9686
  cached_m0_project_memory_epoch,
@@ -9655,7 +9699,7 @@ function readCachedM0M1Row(db, sessionId) {
9655
9699
  cached_m0_model_key,
9656
9700
  cached_m0_project_identity,
9657
9701
  cached_m0_last_baseline_end_message_id,
9658
- memory_block_ids
9702
+ memory_block_ids${includePartialBoundary ? `, ${CACHED_TRIM_PARTIAL_SQL} AS cached_trim_partial` : ""}
9659
9703
  FROM session_meta
9660
9704
  WHERE session_id = ?`).get(sessionId);
9661
9705
  }
@@ -9714,6 +9758,8 @@ function applyCachedRowToState(state, row) {
9714
9758
  state.cachedM0MuralDataUrl = row.cached_m0_mural_data_url ?? null;
9715
9759
  state.cachedM0MuralHash = row.cached_m0_mural_hash ?? null;
9716
9760
  state.cachedM1Bytes = toBuffer(row.cached_m1_bytes);
9761
+ state.cachedM0TrimBoundaryId = row.cached_m0_last_baseline_end_message_id || null;
9762
+ state.cachedM0TrimBoundaryPartial = row.cached_trim_partial === 1;
9717
9763
  state.cachedM0ProjectMemoryEpoch = markers.projectMemoryEpoch;
9718
9764
  state.cachedM0WorkspaceFingerprint = markers.workspaceFingerprint;
9719
9765
  state.cachedM0ProjectUserProfileVersion = markers.projectUserProfileVersion;
@@ -9747,7 +9793,7 @@ function softRefreshCachedM1(options) {
9747
9793
  const row = readCachedM0M1Row(options.db, options.sessionId);
9748
9794
  if (!row || !cachedRowMatchesState(row, options.state)) {
9749
9795
  options.db.exec("ROLLBACK");
9750
- const sibling = readCachedM0M1Row(options.db, options.sessionId);
9796
+ const sibling = readCachedM0M1Row(options.db, options.sessionId, true);
9751
9797
  if (!sibling)
9752
9798
  throw new RenderM1InvalidMarkersError(options.sessionId);
9753
9799
  applyCachedRowToState(options.state, sibling);
@@ -9767,6 +9813,7 @@ function softRefreshCachedM1(options) {
9767
9813
  const m1Bytes = Buffer2.from(rendered.text, "utf8");
9768
9814
  const visibleIdsJson = JSON.stringify(visibleMemoryIds);
9769
9815
  const baselineEndMessageId = getLastCompartmentEndMessageId(options.db, options.sessionId);
9816
+ const baselineEndPartial = baselineEndMessageId != null && isPartialCompartmentEnd(options.db, options.sessionId, baselineEndMessageId);
9770
9817
  steps.mark("m1Render");
9771
9818
  options.db.prepare(`UPDATE session_meta
9772
9819
  SET cached_m1_bytes = ?,
@@ -9780,6 +9827,8 @@ function softRefreshCachedM1(options) {
9780
9827
  steps.mark("commit");
9781
9828
  logSlowWriteTransaction("opencode_soft_refresh_cache", transactionStartedAt, undefined, performance.now(), steps.durations);
9782
9829
  options.state.cachedM1Bytes = m1Bytes;
9830
+ options.state.cachedM0TrimBoundaryId = baselineEndMessageId;
9831
+ options.state.cachedM0TrimBoundaryPartial = baselineEndPartial;
9783
9832
  options.state.cachedM0UpgradeState = withCachedM0MemoryIds(row.cached_m0_upgrade_state, renderedM0Ids);
9784
9833
  options.state.snapshotMarkers = markers;
9785
9834
  return rendered;
@@ -10089,13 +10138,14 @@ function trimToPreparedPrefix(options, prepared) {
10089
10138
  const boundary = prepared.preparedTrimBoundaryId;
10090
10139
  let outcome = { status: "not-required" };
10091
10140
  if (boundary) {
10141
+ const preserveBoundary = prepared.preparedTrimBoundaryPartial ?? isPartialCompartmentEnd(options.db, options.sessionId, boundary);
10092
10142
  const retireDecisions = (messageIds) => {
10093
10143
  queueAutoSearchHintDecisionRetirement(options.db, options.sessionId, new Set(messageIds));
10094
10144
  };
10095
10145
  const trimAtVisibleBoundary = (reanchor) => {
10096
10146
  const index = findBoundaryIndex(options.sessionId, messages, boundary);
10097
10147
  if (index >= 0) {
10098
- const cut = index + (isPartialCompartmentEnd(options.db, options.sessionId, boundary) ? 0 : 1);
10148
+ const cut = index + (preserveBoundary ? 0 : 1);
10099
10149
  const unplaced = messages.slice(0, cut).filter(isHostRenderedSystemMessage);
10100
10150
  const removed = messages.splice(0, cut, ...unplaced);
10101
10151
  retireDecisions(removed.map((message) => message.info.id).filter((id) => typeof id === "string"));
@@ -10183,7 +10233,7 @@ function trimToPreparedPrefix(options, prepared) {
10183
10233
  }
10184
10234
  lastSourcePosition = position;
10185
10235
  placeUnplaced(position <= boundaryPosition);
10186
- if (position > boundaryPosition || position === boundaryPosition && isPartialCompartmentEnd(options.db, options.sessionId, boundary))
10236
+ if (position > boundaryPosition || position === boundaryPosition && preserveBoundary)
10187
10237
  retained.push(message);
10188
10238
  }
10189
10239
  placeUnplaced(false);
@@ -10194,7 +10244,6 @@ function trimToPreparedPrefix(options, prepared) {
10194
10244
  logBoundaryPrecedesWindow(options, boundary, firstLiveId);
10195
10245
  }
10196
10246
  options.messages.splice(0, options.messages.length, ...retained);
10197
- const preserveBoundary = isPartialCompartmentEnd(options.db, options.sessionId, boundary);
10198
10247
  retireDecisions(sourceOrder.messageIds.slice(0, boundaryPosition + (preserveBoundary ? 0 : 1)));
10199
10248
  outcome = { status: "applied" };
10200
10249
  }
@@ -10209,7 +10258,7 @@ function trimToPreparedPrefix(options, prepared) {
10209
10258
  return outcome;
10210
10259
  }
10211
10260
  function prepareCachedM0M1Replay(db, sessionId) {
10212
- const row = readCachedM0M1Row(db, sessionId);
10261
+ const row = readCachedM0M1Row(db, sessionId, true);
10213
10262
  if (!row?.cached_m0_bytes || !row.cached_m1_bytes)
10214
10263
  return;
10215
10264
  const m0Bytes = toBuffer(row.cached_m0_bytes);
@@ -10227,7 +10276,8 @@ function prepareCachedM0M1Replay(db, sessionId) {
10227
10276
  m0Bytes,
10228
10277
  m1Text,
10229
10278
  preparedMessages,
10230
- preparedTrimBoundaryId: row.cached_m0_last_baseline_end_message_id
10279
+ preparedTrimBoundaryId: row.cached_m0_last_baseline_end_message_id,
10280
+ preparedTrimBoundaryPartial: row.cached_trim_partial === 1
10231
10281
  };
10232
10282
  }
10233
10283
  function headMessagesForSizing(options, folds = false) {
@@ -10290,7 +10340,6 @@ function injectM0M1(options) {
10290
10340
  if (options.state.isSubagent && !options.compactionOff)
10291
10341
  return skipped;
10292
10342
  const completePairAtEntry = options.state.cachedM0Bytes != null && options.state.cachedM1Bytes != null;
10293
- let contentionReplayBoundary = options.contentionFallbackPrefix?.preparedTrimBoundaryId ?? null;
10294
10343
  const decision = mustMaterialize({
10295
10344
  db: options.db,
10296
10345
  sessionId: options.sessionId,
@@ -10328,11 +10377,12 @@ function injectM0M1(options) {
10328
10377
  if (captured?.m0Bytes && captured.m1Text !== null) {
10329
10378
  options.state.cachedM0Bytes = Buffer2.from(captured.m0Bytes);
10330
10379
  options.state.cachedM1Bytes = Buffer2.from(captured.m1Text, "utf8");
10380
+ options.state.cachedM0TrimBoundaryId = captured.preparedTrimBoundaryId ?? null;
10381
+ options.state.cachedM0TrimBoundaryPartial = captured.preparedTrimBoundaryPartial;
10331
10382
  } else {
10332
- const persisted = readCachedM0M1Row(options.db, options.sessionId);
10383
+ const persisted = readCachedM0M1Row(options.db, options.sessionId, true);
10333
10384
  if (persisted?.cached_m0_bytes && persisted.cached_m1_bytes) {
10334
10385
  applyCachedRowToState(options.state, persisted);
10335
- contentionReplayBoundary = persisted.cached_m0_last_baseline_end_message_id;
10336
10386
  }
10337
10387
  }
10338
10388
  }
@@ -10397,11 +10447,19 @@ function injectM0M1(options) {
10397
10447
  const M1_DRIFT_RATIO = 0.15;
10398
10448
  const M1_ABSOLUTE_CAP_RATIO = 0.2;
10399
10449
  const m1AbsoluteBudget = (options.historyBudgetTokens ?? DEFAULT_HISTORY_BUDGET_TOKENS) * M1_ABSOLUTE_CAP_RATIO;
10400
- const m1HasContent = m1Text !== M1_EMPTY_PLACEHOLDER;
10401
- const m1Tokens = m1HasContent ? estimateTokens(m1Text) : 0;
10402
- const m0Tokens = estimateTokens(m0Text);
10403
- const m1OverAbsoluteCap = m1HasContent && m1Tokens > m1AbsoluteBudget;
10404
- if (!rematerialized && !contentionExhausted && m1Recomputed && options.isCacheBustingPass && (memoryUpdateCount > 40 || m1OverAbsoluteCap || m1HasContent && m0Tokens >= M0_DRIFT_RATIO_FLOOR_TOKENS && m1Tokens > m0Tokens * M1_DRIFT_RATIO)) {
10450
+ let driftNeedsRefold = false;
10451
+ if (!rematerialized && !contentionExhausted && m1Recomputed && options.isCacheBustingPass) {
10452
+ driftNeedsRefold = memoryUpdateCount > 40;
10453
+ if (!driftNeedsRefold && m1Text !== M1_EMPTY_PLACEHOLDER) {
10454
+ const m1Tokens = estimateTokens(m1Text);
10455
+ driftNeedsRefold = m1Tokens > m1AbsoluteBudget;
10456
+ if (!driftNeedsRefold) {
10457
+ const m0Tokens = estimateTokens(m0Text);
10458
+ driftNeedsRefold = m0Tokens >= M0_DRIFT_RATIO_FLOOR_TOKENS && m1Tokens > m0Tokens * M1_DRIFT_RATIO;
10459
+ }
10460
+ }
10461
+ }
10462
+ if (driftNeedsRefold) {
10405
10463
  try {
10406
10464
  const refolded = materializeWithRetry(options);
10407
10465
  applyMarkersToState(options.state, refolded.m0Bytes, refolded.snapshotMarkers, refolded.m1Bytes, refolded.renderedMemoryIds);
@@ -10416,7 +10474,10 @@ function injectM0M1(options) {
10416
10474
  if (!options.state.cachedM0MuralDataUrl) {
10417
10475
  m0Text = stripMemoryMuralBlock(m0Text);
10418
10476
  }
10419
- const preparedTrimBoundaryId = options.compactionOff ? null : contentionExhausted && freshFallbackRenderedMemoryIds !== null ? options.db.prepare("SELECT end_message_id FROM compartments WHERE session_id = ? AND sequence <= ? ORDER BY sequence DESC LIMIT 1").get(options.sessionId, options.state.snapshotMarkers.maxCompartmentSeq)?.end_message_id ?? null : contentionExhausted ? contentionReplayBoundary : readCachedBaselineState(options.db, options.sessionId).boundary;
10477
+ const freshContentionFallback = contentionExhausted && freshFallbackRenderedMemoryIds !== null;
10478
+ const persistedBoundary = !options.compactionOff && !freshContentionFallback && !contentionExhausted && options.state.cachedM0TrimBoundaryId === undefined ? readCachedBaselineState(options.db, options.sessionId) : undefined;
10479
+ const preparedTrimBoundaryId = options.compactionOff ? null : freshContentionFallback ? options.db.prepare("SELECT end_message_id FROM compartments WHERE session_id = ? AND sequence <= ? ORDER BY sequence DESC LIMIT 1").get(options.sessionId, options.state.snapshotMarkers.maxCompartmentSeq)?.end_message_id ?? null : options.state.cachedM0TrimBoundaryId !== undefined ? options.state.cachedM0TrimBoundaryId : contentionExhausted ? options.contentionFallbackPrefix?.preparedTrimBoundaryId ?? null : persistedBoundary?.boundary ?? null;
10480
+ const preparedTrimBoundaryPartial = preparedTrimBoundaryId ? freshContentionFallback ? isPartialCompartmentEnd(options.db, options.sessionId, preparedTrimBoundaryId) : options.state.cachedM0TrimBoundaryPartial ?? persistedBoundary?.partial ?? options.contentionFallbackPrefix?.preparedTrimBoundaryPartial ?? true : false;
10420
10481
  const preparedMessages = [];
10421
10482
  const muralForWire = options.state.cachedM0MuralDataUrl ? {
10422
10483
  enabled: true,
@@ -10430,7 +10491,8 @@ function injectM0M1(options) {
10430
10491
  prefixTrim = trimToPreparedPrefix(options, {
10431
10492
  m0RematerializedThisPass: rematerialized,
10432
10493
  materializationContentionRetryExhausted: contentionExhausted,
10433
- preparedTrimBoundaryId
10494
+ preparedTrimBoundaryId,
10495
+ preparedTrimBoundaryPartial
10434
10496
  });
10435
10497
  options.messages.unshift(...structuredClone(preparedMessages));
10436
10498
  } else
@@ -10445,6 +10507,7 @@ function injectM0M1(options) {
10445
10507
  m1Text,
10446
10508
  preparedMessages,
10447
10509
  preparedTrimBoundaryId,
10510
+ preparedTrimBoundaryPartial,
10448
10511
  prefixTrimStatus: prefixTrim.status,
10449
10512
  ...prefixTrim.refusal ? { prefixTrimRefusal: prefixTrim.refusal } : {}
10450
10513
  };
@@ -12253,9 +12316,9 @@ function fnv1a(input) {
12253
12316
  }
12254
12317
  return h >>> 0;
12255
12318
  }
12256
- function selectSeeds(sessionId, chunkStart, count = SEED_FLOOR) {
12319
+ function selectSeeds(sessionId, _chunkStart, count = SEED_FLOOR) {
12257
12320
  const bands = seedsByBand();
12258
- const seed = fnv1a(`${sessionId}:${chunkStart}`);
12321
+ const seed = fnv1a(sessionId);
12259
12322
  const picks = [];
12260
12323
  const bandOrder = [];
12261
12324
  for (let i = 0;i < SEED_BANDS.length; i++) {
@@ -12402,7 +12465,22 @@ function fitHistorianPrompt(args) {
12402
12465
  const requested = Math.max(0, Math.floor(args.requestedChunkTokens));
12403
12466
  const seeds = selectSeeds(args.sessionId, args.chunkStart);
12404
12467
  const references = selectSessionReferences(args.sessionCompartments, seeds, args.sessionId, args.chunkStart);
12405
- const memories = orderHistorianMemories(readEnabledProjectMemories(args.memoryEnabled, () => typeof args.memories === "function" ? args.memories() : args.memories));
12468
+ const memories = readEnabledProjectMemories(args.memoryEnabled, () => {
12469
+ const project = args.memoryProject;
12470
+ const projectPath = project?.projectPath;
12471
+ const workspace = project && resolveWorkspaceRenderContext(project);
12472
+ const rows = project ? projectPath && workspace ? readM0ProjectMemories(project.db, projectPath, workspace) : [] : (typeof args.memories === "function" ? args.memories() : args.memories) ?? [];
12473
+ const budget = args.memoryInjectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS;
12474
+ const { selected } = workspace?.isWorkspaced ? trimWorkspaceMemoriesToBudgetV2(args.sessionId, rows, budget, workspace, {
12475
+ sourceNameByMemoryId: sourceNamesForMemories({
12476
+ memories: rows,
12477
+ projectPath,
12478
+ workspace
12479
+ })
12480
+ }) : trimMemoriesToBudgetV2(args.sessionId, rows, budget);
12481
+ const selectedIds = new Set(selected.map((memory) => memory.id));
12482
+ return orderHistorianMemories(rows.filter((memory) => selectedIds.has(memory.id)));
12483
+ });
12406
12484
  const render = (refs, memoryCount, seedCount) => ({
12407
12485
  seedExamples: renderSeedExamplesBlock(seeds.slice(0, seedCount)),
12408
12486
  sessionReferences: renderSessionReferencesBlock(references, refs),
@@ -12964,6 +13042,7 @@ async function runHistorianPrompt(args) {
12964
13042
  });
12965
13043
  if (failure)
12966
13044
  throw new Error(failure);
13045
+ logHistorianPromptSizes(parentSessionId, system, prompt);
12967
13046
  return executor.attempt(opened, request);
12968
13047
  }, { childSessionId: opened.childSessionId }),
12969
13048
  timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
@@ -14983,7 +15062,11 @@ async function runCompartmentAgent(deps) {
14983
15062
  chunkStart: Math.max(1, offset),
14984
15063
  lastOrdinal: eligibleEndOrdinal - 1,
14985
15064
  sessionCompartments: priorCompartments,
14986
- memories: () => getMemoriesByProject2(db, projectPath, ["active", "permanent"]),
15065
+ memoryProject: {
15066
+ db,
15067
+ projectPath: deps.memoryProjectPath === undefined ? projectPath : deps.memoryProjectPath ?? undefined
15068
+ },
15069
+ memoryInjectionBudgetTokens: deps.memoryInjectionBudgetTokens,
14987
15070
  memoryEnabled: deps.memoryEnabled !== false,
14988
15071
  userObservationsRequested: deps.userObservationsRequested
14989
15072
  });
@@ -15104,6 +15187,9 @@ async function runCompartmentAgent(deps) {
15104
15187
  }
15105
15188
  historianRunStarted = true;
15106
15189
  deps.onHistorianRunStarted?.();
15190
+ if (deps.recoveryTriggerReason) {
15191
+ sessionLog2(sessionId, `historian recovery fire: admittedBy=${deps.recoveryTriggerReason} trueRawTokens=${boundarySnapshot.trueRawEligibleTokens} formattedChunkTokens=${chunk.tokenEstimate}`);
15192
+ }
15107
15193
  const prompt = buildCompartmentAgentPrompt({
15108
15194
  seedExamples: promptFit.seedExamples,
15109
15195
  sessionReferences: promptFit.sessionReferences,
@@ -15250,7 +15336,7 @@ ${chunkText}`,
15250
15336
  return;
15251
15337
  }
15252
15338
  appendCompartments(db, sessionId, persistedCompartments);
15253
- persistedIds = getCompartments(db, sessionId).slice(-persistedCompartments.length).map((c) => c.id);
15339
+ persistedIds = getNewestCompartmentIds(db, sessionId, persistedCompartments.length);
15254
15340
  if (promotionActive && !skipUnanchoredPromotion) {
15255
15341
  try {
15256
15342
  const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity, validatedPass.facts ?? []);
@@ -9,7 +9,7 @@ import {
9
9
  } from "./server-pavzsdc6.js";
10
10
  import {
11
11
  cleanUserText2
12
- } from "./server-cdddk5d1.js";
12
+ } from "./server-s1a0bwpc.js";
13
13
  import {
14
14
  recordMessageFtsRowid2,
15
15
  recordIndexedMessageTime2,
@@ -6,7 +6,7 @@ import {
6
6
  estimateMessageTokens,
7
7
  getCandidateToolOwners2,
8
8
  pickNearestPriorOwner2
9
- } from "./server-hb5zm7yh.js";
9
+ } from "./server-verzg5w8.js";
10
10
  import {
11
11
  OMO_INTERNAL_INITIATOR_MARKER,
12
12
  isSystemDirective,
@@ -19,10 +19,10 @@ import {
19
19
  rawMessageWorkerSource2,
20
20
  rawMessageOffThreadRangeReader2,
21
21
  readRawSessionMessageIdOrdinalsForRange2
22
- } from "./server-cdddk5d1.js";
22
+ } from "./server-s1a0bwpc.js";
23
23
  import {
24
24
  readV2ArchiveOffThread2
25
- } from "./server-bnka2vf2.js";
25
+ } from "./server-xwcg55a8.js";
26
26
 
27
27
  // src/tools/ctx-expand/search-archive.ts
28
28
  var archiveReadsOnThisThread = 0;