@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
@@ -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-jf2f8jz8.js"));
1024
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-4ma2vsva.js"));
1025
1025
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-pz5981mf.js"));
1026
1026
  if (signal.aborted)
1027
1027
  return;
@@ -171,7 +171,7 @@ import {
171
171
  adoptNullOwnerToolTag2,
172
172
  getCandidateToolOwners2,
173
173
  pickNearestPriorOwner2
174
- } from "./index-kvfrse61.js";
174
+ } from "./index-t20q6aj6.js";
175
175
  import {
176
176
  textMentionsRecentCommit,
177
177
  hasMeaningfulUserText2,
@@ -224,11 +224,11 @@ import {
224
224
  saveSourceContent,
225
225
  replaceSourceContent,
226
226
  getSourceContents
227
- } from "./index-ezr8mr1c.js";
227
+ } from "./index-ngrrs3yb.js";
228
228
  import {
229
229
  cleanSearchText,
230
230
  matchedSearchSnippet
231
- } from "./index-7dj3s7qq.js";
231
+ } from "./index-2x46rnct.js";
232
232
  import {
233
233
  getProjectEmbeddingSnapshot2,
234
234
  embedTextForProject2,
@@ -241,7 +241,7 @@ import {
241
241
  getMessageIndexEpoch,
242
242
  isMessageIndexSearchable,
243
243
  createAutoSearchDiagnostics
244
- } from "./index-71h616be.js";
244
+ } from "./index-3v5mfapn.js";
245
245
  import {
246
246
  openCodeDbExists,
247
247
  withReadOnlySessionDb,
@@ -259,7 +259,7 @@ import {
259
259
  extractToolCallObservation,
260
260
  ToolMutationBatch,
261
261
  createToolDropTarget
262
- } from "./index-6kgsfb81.js";
262
+ } from "./index-q73yeb83.js";
263
263
  import {
264
264
  compareOpenCodeMessagesByCanonicalOrder,
265
265
  startCompactionMarkerCandidatePreparation,
@@ -281,7 +281,7 @@ import {
281
281
  peekNoteNudgeText,
282
282
  markNoteNudgeDelivered,
283
283
  getActiveCompartmentRun
284
- } from "./index-zdd01nhc.js";
284
+ } from "./index-m47yte97.js";
285
285
  import {
286
286
  userFacingFailureCode
287
287
  } from "./index-n6aye6ny.js";
@@ -35,7 +35,7 @@ import {
35
35
  getRawSessionTagKeysThrough2,
36
36
  getLegacyProtectedTailStartOrdinal2,
37
37
  readSessionChunk2
38
- } from "./index-6kgsfb81.js";
38
+ } from "./index-q73yeb83.js";
39
39
  import {
40
40
  getHarness2,
41
41
  harnessOwnsOpenCodeStore2
@@ -113,7 +113,7 @@ import {
113
113
  LATEST_SUPPORTED_VERSION,
114
114
  getPersistedSchemaVersion,
115
115
  openDatabase
116
- } from "./index-qn27gh4e.js";
116
+ } from "./index-g53qhdrb.js";
117
117
  import {
118
118
  areRustHistorianSyntheticParts2,
119
119
  isStrictGapHealingMessage2,
@@ -170,6 +170,7 @@ import {
170
170
  queueM0Mutation,
171
171
  getMaxM0MutationId,
172
172
  getCompartments,
173
+ getNewestCompartmentIds,
173
174
  getLastCompartmentEndMessage,
174
175
  getLastCompartmentEndMessageId,
175
176
  getCompartmentsByEndMessageId,
@@ -200,20 +201,21 @@ import {
200
201
  getProjectState,
201
202
  recordSubagentInvocation,
202
203
  getLatestHistorianInvocationId
203
- } from "./index-ezr8mr1c.js";
204
+ } from "./index-ngrrs3yb.js";
204
205
  import {
205
206
  clearCompressionDepth,
206
207
  clearCompressionDepthRange,
207
208
  toMessageIndexSource,
208
209
  clearIndexedMessagesInTransaction,
209
210
  indexSourcesAfterOrdinal
210
- } from "./index-7dj3s7qq.js";
211
+ } from "./index-2x46rnct.js";
211
212
  import {
212
213
  stripWellFormedLeadingTagPrefix,
213
214
  peelLeadingMcTagNotation,
214
215
  isRecord,
215
216
  escalationBands,
216
217
  sessionDecisionCalibration,
218
+ CACHED_TRIM_PARTIAL_SQL,
217
219
  ensureSessionMetaRow,
218
220
  persistCachedM0,
219
221
  clearCachedM0M1,
@@ -256,7 +258,7 @@ import {
256
258
  foldShrunkPartTags2,
257
259
  getTagNumberByMessageId2,
258
260
  getActiveTagsBySession2
259
- } from "./index-kvfrse61.js";
261
+ } from "./index-t20q6aj6.js";
260
262
  import {
261
263
  openCodeDbExists,
262
264
  withReadOnlySessionDb,
@@ -4323,11 +4325,11 @@ var USER_OBSERVATIONS_DISABLED_TOGGLE = `<user_observation_extraction>disabled</
4323
4325
  User-memory review is not running (the dreamer is disabled): do NOT emit a <user_observations> block.`;
4324
4326
  function buildCompartmentAgentPrompt(inputs) {
4325
4327
  const parts = [];
4328
+ parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
4326
4329
  if (inputs.seedExamples)
4327
4330
  parts.push(inputs.seedExamples);
4328
4331
  if (inputs.sessionReferences)
4329
4332
  parts.push(inputs.sessionReferences);
4330
- parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
4331
4333
  if (inputs.extractionFree) {
4332
4334
  parts.push(`<extraction>disabled</extraction>
4333
4335
  Structural recomp mode: emit compartments and <meta> only. Do NOT emit <facts>, <events>, <user_observations>, or <primer_candidates>.`);
@@ -4347,6 +4349,34 @@ Memory is disabled for this project: do NOT emit a <facts> block. Produce compar
4347
4349
 
4348
4350
  `);
4349
4351
  }
4352
+ function logHistorianPromptSizes(sessionId, system, prompt) {
4353
+ const sourceStart = prompt.indexOf(`<new_messages>
4354
+
4355
+ `);
4356
+ const sourceEnd = prompt.lastIndexOf(`
4357
+
4358
+ </new_messages>
4359
+
4360
+ ${HISTORIAN_TRANSCRIPT_GUARD}`);
4361
+ const hasSource = sourceStart !== -1 && sourceEnd > sourceStart;
4362
+ const blockBytes = (tag) => {
4363
+ if (!hasSource)
4364
+ return 0;
4365
+ const start = prompt.indexOf(`<${tag}>`);
4366
+ const close = `</${tag}>`;
4367
+ const end = prompt.indexOf(close, start + 1);
4368
+ return start >= 0 && end > start && end < sourceStart ? Buffer.byteLength(prompt.slice(start, end + close.length)) : 0;
4369
+ };
4370
+ const memoryBytes = blockBytes("project-memory");
4371
+ const seedBytes = blockBytes("compartment_examples_from_other_projects");
4372
+ const referenceBytes = blockBytes("session_references");
4373
+ const newMessageBytes = hasSource ? Buffer.byteLength(prompt.slice(sourceStart, sourceEnd + `
4374
+
4375
+ </new_messages>`.length)) : 0;
4376
+ const systemBytes = Buffer.byteLength(system);
4377
+ const userBytes = Buffer.byteLength(prompt);
4378
+ sessionLog2(sessionId, `historian request sizes: systemBytes=${systemBytes} userBytes=${userBytes} memoryBytes=${memoryBytes} seedBytes=${seedBytes} referenceBytes=${referenceBytes} newMessageBytes=${newMessageBytes}`);
4379
+ }
4350
4380
 
4351
4381
  // src/hooks/magic-context/producer-window-guard.ts
4352
4382
  var PRODUCER_WINDOW_REFUSAL_MARGIN = 0.03;
@@ -10326,13 +10356,13 @@ function cutCoveredPrefix(messages, count, coveredInstructions) {
10326
10356
  coveredInstructions.push(message);
10327
10357
  }
10328
10358
  }
10329
- function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, coveredInstructions, projectPath, injectionBudgetTokens, temporalAwareness) {
10359
+ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, coveredInstructions, projectPath, injectionBudgetTokens, temporalAwareness, frozenBaseline) {
10330
10360
  const cached = injectionCache.get(sessionId);
10331
10361
  if (cached && cached.db !== db) {
10332
10362
  clearInjectionCache(sessionId);
10333
10363
  }
10334
10364
  const usableCached = cached?.db === db ? cached : undefined;
10335
- if (!isCacheBusting && usableCached) {
10365
+ if (!isCacheBusting && usableCached && (!frozenBaseline?.hasCachedM0 || (usableCached.kind === "empty" ? frozenBaseline.boundary === null : usableCached.injection.compartmentEndMessageId === (frozenBaseline.boundary ?? "")))) {
10336
10366
  if (usableCached.kind === "empty") {
10337
10367
  return null;
10338
10368
  }
@@ -10343,7 +10373,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
10343
10373
  if (prepared.compartmentEndMessageId.length > 0) {
10344
10374
  const cutoffIndex = findBoundaryIndex(sessionId, messages, prepared.compartmentEndMessageId);
10345
10375
  if (cutoffIndex >= 0) {
10346
- cutCoveredPrefix(messages, cutoffIndex + (isPartialCompartmentEnd(db, sessionId, prepared.compartmentEndMessageId) ? 0 : 1), coveredInstructions);
10376
+ cutCoveredPrefix(messages, cutoffIndex + ((frozenBaseline?.hasCachedM0 ? frozenBaseline.partial : prepared.compartmentEndMessagePartial) ? 0 : 1), coveredInstructions);
10347
10377
  } else {
10348
10378
  sessionLog2(sessionId, `compartment injection: cached boundary ${prepared.compartmentEndMessageId} not in messages (already trimmed), reusing cache`);
10349
10379
  }
@@ -10429,11 +10459,13 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
10429
10459
  const lastEnd = lastCompartment.endMessage;
10430
10460
  const lastEndMessageId = newestCompartmentEndId(compartments) ?? "";
10431
10461
  let trimEndMessageId = lastEndMessageId;
10432
- const baseline = readCachedBaselineState(db, sessionId);
10462
+ const baseline = frozenBaseline ?? readCachedBaselineState(db, sessionId);
10463
+ let trimEndMessagePartial = compartments.some((row) => row.endMessageId === lastEndMessageId && row.endBlockIndex != null);
10433
10464
  if (!isCacheBusting || baseline.hasCachedM0) {
10434
10465
  if (baseline.hasCachedM0) {
10435
10466
  if (baseline.boundary) {
10436
10467
  trimEndMessageId = baseline.boundary;
10468
+ trimEndMessagePartial = baseline.partial;
10437
10469
  } else {
10438
10470
  trimEndMessageId = "";
10439
10471
  }
@@ -10461,12 +10493,14 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
10461
10493
  let needsFreshMaterialization = false;
10462
10494
  let resultEndMessage = lastEnd;
10463
10495
  let resultEndMessageId = null;
10496
+ let resultEndMessagePartial = false;
10464
10497
  const cutoffIndex = findBoundaryIndex(sessionId, messages, trimEndMessageId);
10465
10498
  if (cutoffIndex >= 0) {
10466
10499
  clearDegradedRebuild(sessionId);
10467
- skippedVisibleMessages = cutoffIndex + (isPartialCompartmentEnd(db, sessionId, trimEndMessageId) ? 0 : 1);
10500
+ skippedVisibleMessages = cutoffIndex + (trimEndMessagePartial ? 0 : 1);
10468
10501
  cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
10469
10502
  resultEndMessageId = trimEndMessageId;
10503
+ resultEndMessagePartial = trimEndMessagePartial;
10470
10504
  } else {
10471
10505
  const degradedCount = noteDegradedRebuild(sessionId);
10472
10506
  if (isCacheBusting) {
@@ -10484,7 +10518,8 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
10484
10518
  const reAnchorCompartment = compartments[reAnchorIndex];
10485
10519
  const reAnchorCutoff = findBoundaryIndex(sessionId, messages, reAnchorCompartment.endMessageId);
10486
10520
  if (reAnchorCutoff >= 0) {
10487
- skippedVisibleMessages = reAnchorCutoff + (isPartialCompartmentEnd(db, sessionId, reAnchorCompartment.endMessageId) ? 0 : 1);
10521
+ resultEndMessagePartial = compartments.some((row) => row.endMessageId === reAnchorCompartment.endMessageId && row.endBlockIndex != null);
10522
+ skippedVisibleMessages = reAnchorCutoff + (resultEndMessagePartial ? 0 : 1);
10488
10523
  cutCoveredPrefix(messages, skippedVisibleMessages, coveredInstructions);
10489
10524
  resultEndMessage = reAnchorCompartment.endMessage;
10490
10525
  resultEndMessageId = reAnchorCompartment.endMessageId;
@@ -10504,6 +10539,7 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
10504
10539
  block,
10505
10540
  compartmentEndMessage: resultEndMessage,
10506
10541
  compartmentEndMessageId: resultEndMessageId,
10542
+ compartmentEndMessagePartial: resultEndMessagePartial,
10507
10543
  compartmentCount: compartments.length,
10508
10544
  skippedVisibleMessages,
10509
10545
  factCount: facts.length,
@@ -10517,11 +10553,13 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
10517
10553
  return result;
10518
10554
  }
10519
10555
  function readCachedBaselineState(db, sessionId) {
10520
- 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);
10556
+ const row = db.prepare(`SELECT cached_m0_bytes AS m0, cached_m0_last_baseline_end_message_id AS boundary,
10557
+ ${CACHED_TRIM_PARTIAL_SQL} AS partial FROM session_meta WHERE session_id = ?`).get(sessionId);
10521
10558
  const boundary = row?.boundary;
10522
10559
  return {
10523
10560
  hasCachedM0: row?.m0 != null,
10524
- boundary: boundary && boundary.length > 0 ? boundary : null
10561
+ boundary: boundary && boundary.length > 0 ? boundary : null,
10562
+ partial: row?.partial === 1
10525
10563
  };
10526
10564
  }
10527
10565
  function renderCompartmentInjection(sessionId, messages, prepared) {
@@ -10661,6 +10699,9 @@ function sourceNamesForMemories(args) {
10661
10699
  }
10662
10700
  return names.size > 0 ? names : undefined;
10663
10701
  }
10702
+ function readM0ProjectMemories(db, projectPath, workspace, at = Date.now()) {
10703
+ return workspace.isWorkspaced ? getMemoriesByProjects2(db, workspace.expandedIdentities, ["active", "permanent"], at, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject2(db, projectPath, ["active", "permanent"], at);
10704
+ }
10664
10705
  function memoryCanonicalIdentity(memory, workspace) {
10665
10706
  return resolveStoredPathWorkspaceIdentity(memory.projectPath, workspace.identities, workspace.canonicalIdentityByStoredPath);
10666
10707
  }
@@ -11437,7 +11478,7 @@ function materializeM0(options) {
11437
11478
  snapshotMarkers.projectDocsHash = docs.canonicalHash;
11438
11479
  compartments = options.compactionOff ? [] : readM0Compartments(options.db, options.sessionId);
11439
11480
  facts = [];
11440
- memories = projectPath ? workspace.isWorkspaced ? getMemoriesByProjects2(options.db, workspace.expandedIdentities, ["active", "permanent"], foldMaterializedAt, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject2(options.db, projectPath, ["active", "permanent"], foldMaterializedAt) : [];
11481
+ memories = projectPath ? readM0ProjectMemories(options.db, projectPath, workspace, foldMaterializedAt) : [];
11441
11482
  userMemories = options.memoryEnabled === false ? [] : safeGetActiveUserMemories(options.db);
11442
11483
  options.db.exec("COMMIT");
11443
11484
  } catch (error) {
@@ -11501,6 +11542,7 @@ function materializeM0(options) {
11501
11542
  const steps = new WriteTransactionSteps;
11502
11543
  const upgradeIdentity = withCachedM0ToolDefinitionsHash(withCachedM0MemoryIds(encodeCachedM0UpgradeIdentity(snapshotMarkers.upgradeState, snapshotMarkers.compartmentRenderEpoch, snapshotMarkers.muralEnabled, snapshotMarkers.renderBudgetIdentity, snapshotMarkers.memoryRenderEpoch, snapshotMarkers.renderedBudgets ?? null), renderedMemoryIds), snapshotMarkers.toolDefinitionsHash ?? null);
11503
11544
  const baselineEndMessageId = lastCompartmentBoundaryId(compartments);
11545
+ const baselineEndPartial = compartments.some((row) => row.endMessageId === baselineEndMessageId && row.endBlockIndex != null);
11504
11546
  steps.mark("pre_metadata");
11505
11547
  const commitFold = options.onFoldPrepare?.();
11506
11548
  steps.mark("pre_onFoldPrepare");
@@ -11591,6 +11633,8 @@ function materializeM0(options) {
11591
11633
  logSlowWriteTransaction("opencode_materialize_cache", transactionStartedAt, undefined, performance.now(), steps.durations);
11592
11634
  options.state.cachedM0MuralDataUrl = frozenMuralDataUrl;
11593
11635
  options.state.cachedM0MuralHash = frozenMuralHash;
11636
+ options.state.cachedM0TrimBoundaryId = baselineEndMessageId;
11637
+ options.state.cachedM0TrimBoundaryPartial = baselineEndPartial;
11594
11638
  } catch (error) {
11595
11639
  try {
11596
11640
  options.db.exec("ROLLBACK");
@@ -11775,7 +11819,7 @@ function hydrateCachedM0Mural(db, sessionId, state) {
11775
11819
  state.cachedM0MuralHash = row.cached_m0_mural_hash ?? null;
11776
11820
  }
11777
11821
  }
11778
- function readCachedM0M1Row(db, sessionId) {
11822
+ function readCachedM0M1Row(db, sessionId, includePartialBoundary = false) {
11779
11823
  return db.prepare(`SELECT cached_m0_bytes, cached_m0_mural_data_url,
11780
11824
  cached_m0_mural_hash, cached_m1_bytes,
11781
11825
  cached_m0_project_memory_epoch,
@@ -11794,7 +11838,7 @@ function readCachedM0M1Row(db, sessionId) {
11794
11838
  cached_m0_model_key,
11795
11839
  cached_m0_project_identity,
11796
11840
  cached_m0_last_baseline_end_message_id,
11797
- memory_block_ids
11841
+ memory_block_ids${includePartialBoundary ? `, ${CACHED_TRIM_PARTIAL_SQL} AS cached_trim_partial` : ""}
11798
11842
  FROM session_meta
11799
11843
  WHERE session_id = ?`).get(sessionId);
11800
11844
  }
@@ -11853,6 +11897,8 @@ function applyCachedRowToState(state, row) {
11853
11897
  state.cachedM0MuralDataUrl = row.cached_m0_mural_data_url ?? null;
11854
11898
  state.cachedM0MuralHash = row.cached_m0_mural_hash ?? null;
11855
11899
  state.cachedM1Bytes = toBuffer(row.cached_m1_bytes);
11900
+ state.cachedM0TrimBoundaryId = row.cached_m0_last_baseline_end_message_id || null;
11901
+ state.cachedM0TrimBoundaryPartial = row.cached_trim_partial === 1;
11856
11902
  state.cachedM0ProjectMemoryEpoch = markers.projectMemoryEpoch;
11857
11903
  state.cachedM0WorkspaceFingerprint = markers.workspaceFingerprint;
11858
11904
  state.cachedM0ProjectUserProfileVersion = markers.projectUserProfileVersion;
@@ -11886,7 +11932,7 @@ function softRefreshCachedM1(options) {
11886
11932
  const row = readCachedM0M1Row(options.db, options.sessionId);
11887
11933
  if (!row || !cachedRowMatchesState(row, options.state)) {
11888
11934
  options.db.exec("ROLLBACK");
11889
- const sibling = readCachedM0M1Row(options.db, options.sessionId);
11935
+ const sibling = readCachedM0M1Row(options.db, options.sessionId, true);
11890
11936
  if (!sibling)
11891
11937
  throw new RenderM1InvalidMarkersError(options.sessionId);
11892
11938
  applyCachedRowToState(options.state, sibling);
@@ -11906,6 +11952,7 @@ function softRefreshCachedM1(options) {
11906
11952
  const m1Bytes = Buffer2.from(rendered.text, "utf8");
11907
11953
  const visibleIdsJson = JSON.stringify(visibleMemoryIds);
11908
11954
  const baselineEndMessageId = getLastCompartmentEndMessageId(options.db, options.sessionId);
11955
+ const baselineEndPartial = baselineEndMessageId != null && isPartialCompartmentEnd(options.db, options.sessionId, baselineEndMessageId);
11909
11956
  steps.mark("m1Render");
11910
11957
  options.db.prepare(`UPDATE session_meta
11911
11958
  SET cached_m1_bytes = ?,
@@ -11919,6 +11966,8 @@ function softRefreshCachedM1(options) {
11919
11966
  steps.mark("commit");
11920
11967
  logSlowWriteTransaction("opencode_soft_refresh_cache", transactionStartedAt, undefined, performance.now(), steps.durations);
11921
11968
  options.state.cachedM1Bytes = m1Bytes;
11969
+ options.state.cachedM0TrimBoundaryId = baselineEndMessageId;
11970
+ options.state.cachedM0TrimBoundaryPartial = baselineEndPartial;
11922
11971
  options.state.cachedM0UpgradeState = withCachedM0MemoryIds(row.cached_m0_upgrade_state, renderedM0Ids);
11923
11972
  options.state.snapshotMarkers = markers;
11924
11973
  return rendered;
@@ -12228,13 +12277,14 @@ function trimToPreparedPrefix(options, prepared) {
12228
12277
  const boundary = prepared.preparedTrimBoundaryId;
12229
12278
  let outcome = { status: "not-required" };
12230
12279
  if (boundary) {
12280
+ const preserveBoundary = prepared.preparedTrimBoundaryPartial ?? isPartialCompartmentEnd(options.db, options.sessionId, boundary);
12231
12281
  const retireDecisions = (messageIds) => {
12232
12282
  queueAutoSearchHintDecisionRetirement(options.db, options.sessionId, new Set(messageIds));
12233
12283
  };
12234
12284
  const trimAtVisibleBoundary = (reanchor) => {
12235
12285
  const index = findBoundaryIndex(options.sessionId, messages, boundary);
12236
12286
  if (index >= 0) {
12237
- const cut = index + (isPartialCompartmentEnd(options.db, options.sessionId, boundary) ? 0 : 1);
12287
+ const cut = index + (preserveBoundary ? 0 : 1);
12238
12288
  const unplaced = messages.slice(0, cut).filter(isHostRenderedSystemMessage);
12239
12289
  const removed = messages.splice(0, cut, ...unplaced);
12240
12290
  retireDecisions(removed.map((message) => message.info.id).filter((id) => typeof id === "string"));
@@ -12322,7 +12372,7 @@ function trimToPreparedPrefix(options, prepared) {
12322
12372
  }
12323
12373
  lastSourcePosition = position;
12324
12374
  placeUnplaced(position <= boundaryPosition);
12325
- if (position > boundaryPosition || position === boundaryPosition && isPartialCompartmentEnd(options.db, options.sessionId, boundary))
12375
+ if (position > boundaryPosition || position === boundaryPosition && preserveBoundary)
12326
12376
  retained.push(message);
12327
12377
  }
12328
12378
  placeUnplaced(false);
@@ -12333,7 +12383,6 @@ function trimToPreparedPrefix(options, prepared) {
12333
12383
  logBoundaryPrecedesWindow(options, boundary, firstLiveId);
12334
12384
  }
12335
12385
  options.messages.splice(0, options.messages.length, ...retained);
12336
- const preserveBoundary = isPartialCompartmentEnd(options.db, options.sessionId, boundary);
12337
12386
  retireDecisions(sourceOrder.messageIds.slice(0, boundaryPosition + (preserveBoundary ? 0 : 1)));
12338
12387
  outcome = { status: "applied" };
12339
12388
  }
@@ -12348,7 +12397,7 @@ function trimToPreparedPrefix(options, prepared) {
12348
12397
  return outcome;
12349
12398
  }
12350
12399
  function prepareCachedM0M1Replay(db, sessionId) {
12351
- const row = readCachedM0M1Row(db, sessionId);
12400
+ const row = readCachedM0M1Row(db, sessionId, true);
12352
12401
  if (!row?.cached_m0_bytes || !row.cached_m1_bytes)
12353
12402
  return;
12354
12403
  const m0Bytes = toBuffer(row.cached_m0_bytes);
@@ -12366,7 +12415,8 @@ function prepareCachedM0M1Replay(db, sessionId) {
12366
12415
  m0Bytes,
12367
12416
  m1Text,
12368
12417
  preparedMessages,
12369
- preparedTrimBoundaryId: row.cached_m0_last_baseline_end_message_id
12418
+ preparedTrimBoundaryId: row.cached_m0_last_baseline_end_message_id,
12419
+ preparedTrimBoundaryPartial: row.cached_trim_partial === 1
12370
12420
  };
12371
12421
  }
12372
12422
  function headMessagesForSizing(options, folds = false) {
@@ -12429,7 +12479,6 @@ function injectM0M1(options) {
12429
12479
  if (options.state.isSubagent && !options.compactionOff)
12430
12480
  return skipped;
12431
12481
  const completePairAtEntry = options.state.cachedM0Bytes != null && options.state.cachedM1Bytes != null;
12432
- let contentionReplayBoundary = options.contentionFallbackPrefix?.preparedTrimBoundaryId ?? null;
12433
12482
  const decision = mustMaterialize({
12434
12483
  db: options.db,
12435
12484
  sessionId: options.sessionId,
@@ -12467,11 +12516,12 @@ function injectM0M1(options) {
12467
12516
  if (captured?.m0Bytes && captured.m1Text !== null) {
12468
12517
  options.state.cachedM0Bytes = Buffer2.from(captured.m0Bytes);
12469
12518
  options.state.cachedM1Bytes = Buffer2.from(captured.m1Text, "utf8");
12519
+ options.state.cachedM0TrimBoundaryId = captured.preparedTrimBoundaryId ?? null;
12520
+ options.state.cachedM0TrimBoundaryPartial = captured.preparedTrimBoundaryPartial;
12470
12521
  } else {
12471
- const persisted = readCachedM0M1Row(options.db, options.sessionId);
12522
+ const persisted = readCachedM0M1Row(options.db, options.sessionId, true);
12472
12523
  if (persisted?.cached_m0_bytes && persisted.cached_m1_bytes) {
12473
12524
  applyCachedRowToState(options.state, persisted);
12474
- contentionReplayBoundary = persisted.cached_m0_last_baseline_end_message_id;
12475
12525
  }
12476
12526
  }
12477
12527
  }
@@ -12536,11 +12586,19 @@ function injectM0M1(options) {
12536
12586
  const M1_DRIFT_RATIO = 0.15;
12537
12587
  const M1_ABSOLUTE_CAP_RATIO = 0.2;
12538
12588
  const m1AbsoluteBudget = (options.historyBudgetTokens ?? DEFAULT_HISTORY_BUDGET_TOKENS) * M1_ABSOLUTE_CAP_RATIO;
12539
- const m1HasContent = m1Text !== M1_EMPTY_PLACEHOLDER;
12540
- const m1Tokens = m1HasContent ? estimateTokens(m1Text) : 0;
12541
- const m0Tokens = estimateTokens(m0Text);
12542
- const m1OverAbsoluteCap = m1HasContent && m1Tokens > m1AbsoluteBudget;
12543
- if (!rematerialized && !contentionExhausted && m1Recomputed && options.isCacheBustingPass && (memoryUpdateCount > 40 || m1OverAbsoluteCap || m1HasContent && m0Tokens >= M0_DRIFT_RATIO_FLOOR_TOKENS && m1Tokens > m0Tokens * M1_DRIFT_RATIO)) {
12589
+ let driftNeedsRefold = false;
12590
+ if (!rematerialized && !contentionExhausted && m1Recomputed && options.isCacheBustingPass) {
12591
+ driftNeedsRefold = memoryUpdateCount > 40;
12592
+ if (!driftNeedsRefold && m1Text !== M1_EMPTY_PLACEHOLDER) {
12593
+ const m1Tokens = estimateTokens(m1Text);
12594
+ driftNeedsRefold = m1Tokens > m1AbsoluteBudget;
12595
+ if (!driftNeedsRefold) {
12596
+ const m0Tokens = estimateTokens(m0Text);
12597
+ driftNeedsRefold = m0Tokens >= M0_DRIFT_RATIO_FLOOR_TOKENS && m1Tokens > m0Tokens * M1_DRIFT_RATIO;
12598
+ }
12599
+ }
12600
+ }
12601
+ if (driftNeedsRefold) {
12544
12602
  try {
12545
12603
  const refolded = materializeWithRetry(options);
12546
12604
  applyMarkersToState(options.state, refolded.m0Bytes, refolded.snapshotMarkers, refolded.m1Bytes, refolded.renderedMemoryIds);
@@ -12555,7 +12613,10 @@ function injectM0M1(options) {
12555
12613
  if (!options.state.cachedM0MuralDataUrl) {
12556
12614
  m0Text = stripMemoryMuralBlock(m0Text);
12557
12615
  }
12558
- 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;
12616
+ const freshContentionFallback = contentionExhausted && freshFallbackRenderedMemoryIds !== null;
12617
+ const persistedBoundary = !options.compactionOff && !freshContentionFallback && !contentionExhausted && options.state.cachedM0TrimBoundaryId === undefined ? readCachedBaselineState(options.db, options.sessionId) : undefined;
12618
+ 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;
12619
+ const preparedTrimBoundaryPartial = preparedTrimBoundaryId ? freshContentionFallback ? isPartialCompartmentEnd(options.db, options.sessionId, preparedTrimBoundaryId) : options.state.cachedM0TrimBoundaryPartial ?? persistedBoundary?.partial ?? options.contentionFallbackPrefix?.preparedTrimBoundaryPartial ?? true : false;
12559
12620
  const preparedMessages = [];
12560
12621
  const muralForWire = options.state.cachedM0MuralDataUrl ? {
12561
12622
  enabled: true,
@@ -12569,7 +12630,8 @@ function injectM0M1(options) {
12569
12630
  prefixTrim = trimToPreparedPrefix(options, {
12570
12631
  m0RematerializedThisPass: rematerialized,
12571
12632
  materializationContentionRetryExhausted: contentionExhausted,
12572
- preparedTrimBoundaryId
12633
+ preparedTrimBoundaryId,
12634
+ preparedTrimBoundaryPartial
12573
12635
  });
12574
12636
  options.messages.unshift(...structuredClone(preparedMessages));
12575
12637
  } else
@@ -12584,6 +12646,7 @@ function injectM0M1(options) {
12584
12646
  m1Text,
12585
12647
  preparedMessages,
12586
12648
  preparedTrimBoundaryId,
12649
+ preparedTrimBoundaryPartial,
12587
12650
  prefixTrimStatus: prefixTrim.status,
12588
12651
  ...prefixTrim.refusal ? { prefixTrimRefusal: prefixTrim.refusal } : {}
12589
12652
  };
@@ -14299,9 +14362,9 @@ function fnv1a(input) {
14299
14362
  }
14300
14363
  return h >>> 0;
14301
14364
  }
14302
- function selectSeeds(sessionId, chunkStart, count = SEED_FLOOR) {
14365
+ function selectSeeds(sessionId, _chunkStart, count = SEED_FLOOR) {
14303
14366
  const bands = seedsByBand();
14304
- const seed = fnv1a(`${sessionId}:${chunkStart}`);
14367
+ const seed = fnv1a(sessionId);
14305
14368
  const picks = [];
14306
14369
  const bandOrder = [];
14307
14370
  for (let i = 0;i < SEED_BANDS.length; i++) {
@@ -14448,7 +14511,22 @@ function fitHistorianPrompt(args) {
14448
14511
  const requested = Math.max(0, Math.floor(args.requestedChunkTokens));
14449
14512
  const seeds = selectSeeds(args.sessionId, args.chunkStart);
14450
14513
  const references = selectSessionReferences(args.sessionCompartments, seeds, args.sessionId, args.chunkStart);
14451
- const memories = orderHistorianMemories(readEnabledProjectMemories(args.memoryEnabled, () => typeof args.memories === "function" ? args.memories() : args.memories));
14514
+ const memories = readEnabledProjectMemories(args.memoryEnabled, () => {
14515
+ const project = args.memoryProject;
14516
+ const projectPath = project?.projectPath;
14517
+ const workspace = project && resolveWorkspaceRenderContext(project);
14518
+ const rows = project ? projectPath && workspace ? readM0ProjectMemories(project.db, projectPath, workspace) : [] : (typeof args.memories === "function" ? args.memories() : args.memories) ?? [];
14519
+ const budget = args.memoryInjectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS;
14520
+ const { selected } = workspace?.isWorkspaced ? trimWorkspaceMemoriesToBudgetV2(args.sessionId, rows, budget, workspace, {
14521
+ sourceNameByMemoryId: sourceNamesForMemories({
14522
+ memories: rows,
14523
+ projectPath,
14524
+ workspace
14525
+ })
14526
+ }) : trimMemoriesToBudgetV2(args.sessionId, rows, budget);
14527
+ const selectedIds = new Set(selected.map((memory) => memory.id));
14528
+ return orderHistorianMemories(rows.filter((memory) => selectedIds.has(memory.id)));
14529
+ });
14452
14530
  const render = (refs, memoryCount, seedCount) => ({
14453
14531
  seedExamples: renderSeedExamplesBlock(seeds.slice(0, seedCount)),
14454
14532
  sessionReferences: renderSessionReferencesBlock(references, refs),
@@ -15010,6 +15088,7 @@ async function runHistorianPrompt(args) {
15010
15088
  });
15011
15089
  if (failure)
15012
15090
  throw new Error(failure);
15091
+ logHistorianPromptSizes(parentSessionId, system, prompt);
15013
15092
  return executor.attempt(opened, request);
15014
15093
  }, { childSessionId: opened.childSessionId }),
15015
15094
  timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
@@ -17866,7 +17945,11 @@ async function runCompartmentAgent(deps) {
17866
17945
  chunkStart: Math.max(1, offset),
17867
17946
  lastOrdinal: eligibleEndOrdinal - 1,
17868
17947
  sessionCompartments: priorCompartments,
17869
- memories: () => getMemoriesByProject2(db, projectPath, ["active", "permanent"]),
17948
+ memoryProject: {
17949
+ db,
17950
+ projectPath: deps.memoryProjectPath === undefined ? projectPath : deps.memoryProjectPath ?? undefined
17951
+ },
17952
+ memoryInjectionBudgetTokens: deps.memoryInjectionBudgetTokens,
17870
17953
  memoryEnabled: deps.memoryEnabled !== false,
17871
17954
  userObservationsRequested: deps.userObservationsRequested
17872
17955
  });
@@ -17987,6 +18070,9 @@ async function runCompartmentAgent(deps) {
17987
18070
  }
17988
18071
  historianRunStarted = true;
17989
18072
  deps.onHistorianRunStarted?.();
18073
+ if (deps.recoveryTriggerReason) {
18074
+ sessionLog2(sessionId, `historian recovery fire: admittedBy=${deps.recoveryTriggerReason} trueRawTokens=${boundarySnapshot.trueRawEligibleTokens} formattedChunkTokens=${chunk.tokenEstimate}`);
18075
+ }
17990
18076
  const prompt = buildCompartmentAgentPrompt({
17991
18077
  seedExamples: promptFit.seedExamples,
17992
18078
  sessionReferences: promptFit.sessionReferences,
@@ -18133,7 +18219,7 @@ ${chunkText}`,
18133
18219
  return;
18134
18220
  }
18135
18221
  appendCompartments(db, sessionId, persistedCompartments);
18136
- persistedIds = getCompartments(db, sessionId).slice(-persistedCompartments.length).map((c) => c.id);
18222
+ persistedIds = getNewestCompartmentIds(db, sessionId, persistedCompartments.length);
18137
18223
  if (promotionActive && !skipUnanchoredPromotion) {
18138
18224
  try {
18139
18225
  const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity, validatedPass.facts ?? []);
@@ -67,21 +67,21 @@ import {
67
67
  import {
68
68
  matchedSearchSnippet,
69
69
  getIndexedMessageCorpusSize
70
- } from "./index-7dj3s7qq.js";
70
+ } from "./index-2x46rnct.js";
71
71
  import {
72
72
  getMessageIndexEpoch,
73
73
  isMessageIndexSearchable,
74
74
  withMemoryHintContent,
75
75
  autoSearchRelevance,
76
76
  recordAutoSearchLane
77
- } from "./index-71h616be.js";
77
+ } from "./index-3v5mfapn.js";
78
78
  import {
79
79
  MESSAGE_FTS_SESSION_FILTER_SQL,
80
80
  withMessageFtsSessionFilter
81
81
  } from "./index-52x68mj4.js";
82
82
  import {
83
83
  isRecord
84
- } from "./index-kvfrse61.js";
84
+ } from "./index-t20q6aj6.js";
85
85
  import {
86
86
  resolveWorkspaceShareCategories,
87
87
  resolveWorkspaceIdentitySet,
@@ -139,9 +139,9 @@ async function serveV2ArchiveReads2(port, openConnections) {
139
139
  import("./sqlite-zdgm52sv.js"),
140
140
  import("./store-reader-3eh1s1m8.js"),
141
141
  import("./store-h20ny8b8.js"),
142
- import("./read-session-chunk-jf2f8jz8.js"),
143
- import("./render-n46wpv2n.js"),
144
- import("./search-archive-9k6vsp44.js"),
142
+ import("./read-session-chunk-4ma2vsva.js"),
143
+ import("./render-h16ea0th.js"),
144
+ import("./search-archive-km2ahm3e.js"),
145
145
  import("./expand-attachments-h33jbgyz.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -42,6 +42,7 @@ import {
42
42
  providerVisibleMessage,
43
43
  MERGED_REASONING_PARTS_PREFIX,
44
44
  decodeMergedReasoningParts,
45
+ CACHED_TRIM_PARTIAL_SQL,
45
46
  SESSION_META_SELECT_COLUMNS,
46
47
  META_COLUMNS,
47
48
  BOOLEAN_META_KEYS,
@@ -67,7 +68,7 @@ import {
67
68
  getPendingPiCompactionMarkerState,
68
69
  logPiCompactionMarkerClear,
69
70
  isPrefixBoundThinkingModel
70
- } from "./index-kvfrse61.js";
71
+ } from "./index-t20q6aj6.js";
71
72
  import {
72
73
  withReadOnlySessionDb
73
74
  } from "./index-x40zr813.js";
@@ -370,6 +371,10 @@ function getCompartments(db, sessionId) {
370
371
  FROM compartments WHERE session_id = ? ORDER BY sequence ASC`).all(sessionId).filter(isCompartmentRow);
371
372
  return rows.map(toCompartment);
372
373
  }
374
+ function getNewestCompartmentIds(db, sessionId, count) {
375
+ const rows = db.prepare("SELECT id FROM compartments WHERE session_id = ? ORDER BY sequence DESC LIMIT ?").all(sessionId, count);
376
+ return rows.reverse().map(({ id }) => id);
377
+ }
373
378
  function getLastCompartmentEndMessage(db, sessionId) {
374
379
  const row = db.prepare("SELECT MAX(end_message) as max_end FROM compartments WHERE session_id = ? AND rebase_status != 'unresolved'").get(sessionId);
375
380
  return row?.max_end ?? -1;
@@ -1385,6 +1390,7 @@ var SESSION_META_FALLBACK_SELECTS = {
1385
1390
  last_todo_state: "'' AS last_todo_state",
1386
1391
  tool_reclaim_watermark: "0 AS tool_reclaim_watermark",
1387
1392
  cached_m0_bytes: "NULL AS cached_m0_bytes",
1393
+ cached_m0_last_baseline_end_message_id: "NULL AS cached_m0_last_baseline_end_message_id",
1388
1394
  cached_m0_mural_data_url: "NULL AS cached_m0_mural_data_url",
1389
1395
  cached_m0_mural_hash: "NULL AS cached_m0_mural_hash",
1390
1396
  cached_m1_bytes: "NULL AS cached_m1_bytes",
@@ -1413,11 +1419,14 @@ function getSessionMetaSelectColumns(db) {
1413
1419
  if (cached !== undefined)
1414
1420
  return cached;
1415
1421
  const existingColumns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
1416
- const projection = SESSION_META_SELECT_COLUMNS.map((column) => {
1422
+ const columns = SESSION_META_SELECT_COLUMNS.map((column) => {
1417
1423
  if (existingColumns.has(column))
1418
1424
  return column;
1419
1425
  return SESSION_META_FALLBACK_SELECTS[column] ?? `0 AS ${column}`;
1420
- }).join(", ");
1426
+ });
1427
+ if (existingColumns.has("cached_m0_last_baseline_end_message_id") && getTableColumnNames(db, "compartments").has("end_block_index"))
1428
+ columns.push(`${CACHED_TRIM_PARTIAL_SQL} AS cached_trim_partial`);
1429
+ const projection = columns.join(", ");
1421
1430
  sessionMetaSelectColumnsCache.set(db, projection);
1422
1431
  return projection;
1423
1432
  }
@@ -5178,4 +5187,4 @@ var ERROR_CLASSES = new Set([
5178
5187
  "permission_denied",
5179
5188
  "unknown"
5180
5189
  ]);
5181
- export { advanceSessionActivity, observeSessionActivity, backfillSessionActivity, 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, cancelAutoSearchWork, 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, createDbLkgPersistence, 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, registerLkgPersistence, 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 };
5190
+ export { advanceSessionActivity, observeSessionActivity, backfillSessionActivity, 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, cancelAutoSearchWork, 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, createDbLkgPersistence, 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, registerLkgPersistence, 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 };