@cortexkit/opencode-magic-context 0.49.51 → 0.49.53

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 (136) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{context-r77d4fdy.js → context-p6r0bk7a.js} +90 -51
  4. package/dist/{embedding-backfill-3wdjzrvs.js → embedding-backfill-qes2kf1c.js} +2 -2
  5. package/dist/features/magic-context/compartment-embedding.d.ts.map +1 -1
  6. package/dist/features/magic-context/message-fts-session-filter.d.ts +1 -1
  7. package/dist/features/magic-context/message-fts-session-filter.d.ts.map +1 -1
  8. package/dist/features/magic-context/project-embedding-registry.d.ts +8 -0
  9. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  10. package/dist/features/magic-context/search.d.ts.map +1 -1
  11. package/dist/features/magic-context/storage-host-instruction-retention.d.ts +10 -3
  12. package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -1
  13. package/dist/features/magic-context/storage-meta-persisted.d.ts +20 -1
  14. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  15. package/dist/features/magic-context/storage-meta.d.ts +1 -1
  16. package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
  17. package/dist/features/magic-context/storage.d.ts +1 -1
  18. package/dist/features/magic-context/storage.d.ts.map +1 -1
  19. package/dist/features/magic-context/transform-decision-log.d.ts +1 -1
  20. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/active-anthropic-turn.d.ts +6 -0
  22. package/dist/hooks/magic-context/active-anthropic-turn.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/compaction-marker-manager.d.ts +2 -1
  24. package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/history-boundary-recovery.d.ts +15 -0
  27. package/dist/hooks/magic-context/history-boundary-recovery.d.ts.map +1 -0
  28. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/host-served-rows.d.ts +12 -2
  30. package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/inject-compartments.d.ts +21 -0
  32. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  33. package/dist/hooks/magic-context/latest-assistant-turn.d.ts +43 -0
  34. package/dist/hooks/magic-context/latest-assistant-turn.d.ts.map +1 -1
  35. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts +102 -26
  36. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts.map +1 -1
  37. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts +18 -2
  38. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts.map +1 -1
  39. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
  41. package/dist/hooks/magic-context/pending-marker-rearm.d.ts +20 -0
  42. package/dist/hooks/magic-context/pending-marker-rearm.d.ts.map +1 -0
  43. package/dist/hooks/magic-context/persist-filtered-noise.d.ts +1 -1
  44. package/dist/hooks/magic-context/persist-filtered-noise.d.ts.map +1 -1
  45. package/dist/hooks/magic-context/priced-pass-sizing.d.ts +7 -0
  46. package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -1
  47. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +11 -1
  48. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -1
  49. package/dist/hooks/magic-context/rust-mode-transform.d.ts +1 -1
  50. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  51. package/dist/hooks/magic-context/served-check.d.ts +127 -0
  52. package/dist/hooks/magic-context/served-check.d.ts.map +1 -0
  53. package/dist/hooks/magic-context/signed-thinking-hold.d.ts +32 -4
  54. package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -1
  55. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +37 -2
  56. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  57. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  58. package/dist/hooks/magic-context/unresolved-history-boundary.d.ts +21 -2
  59. package/dist/hooks/magic-context/unresolved-history-boundary.d.ts.map +1 -1
  60. package/dist/{index-n0twfvah.js → index-2ctn7q09.js} +531 -17
  61. package/dist/{index-bamnjp2t.js → index-2m54t4g1.js} +9 -5
  62. package/dist/{index-30sf7e5k.js → index-3b5k5vma.js} +27 -16
  63. package/dist/{index-ct3ettqt.js → index-3h0wyv22.js} +3 -3
  64. package/dist/{index-hkveze74.js → index-3hhq18q0.js} +1 -1
  65. package/dist/{index-kaqs6h31.js → index-52x68mj4.js} +1 -1
  66. package/dist/{index-wr2t8zb0.js → index-5684dzbv.js} +648 -69
  67. package/dist/{index-s131svmx.js → index-7wasafnb.js} +1 -1
  68. package/dist/{index-8d7gkgjs.js → index-85chg6fw.js} +1 -1
  69. package/dist/{index-z4832qfe.js → index-a6bxwv4a.js} +1 -1
  70. package/dist/{index-h8g08nxs.js → index-chjsdqg6.js} +104 -62
  71. package/dist/{index-5dptmnvd.js → index-esm4farg.js} +8 -7
  72. package/dist/{index-97bjd14c.js → index-fbs0f5ch.js} +4 -4
  73. package/dist/{index-cwj6qhmf.js → index-kwpweqzs.js} +8 -3
  74. package/dist/{index-07rp6xcn.js → index-n3rxwtwt.js} +48 -15
  75. package/dist/{index-gv7dwx5b.js → index-p7ssfv6p.js} +503 -395
  76. package/dist/{index-v4a1pnny.js → index-pgbmbtdq.js} +4 -4
  77. package/dist/{index-mjh63zvw.js → index-wpab17w4.js} +1 -1
  78. package/dist/index.js +53 -32
  79. package/dist/{message-index-bounded-k0ebpy3y.js → message-index-bounded-7p3064st.js} +2 -2
  80. package/dist/migration-worker.js +1 -1
  81. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  82. package/dist/plugin/messages-transform.d.ts +6 -0
  83. package/dist/plugin/messages-transform.d.ts.map +1 -1
  84. package/dist/{project-embedding-registry-5dwh5zfn.js → project-embedding-registry-m8t547fb.js} +3 -1
  85. package/dist/raw-ordinal-warmup-worker.js +3 -3
  86. package/dist/{read-session-chunk-6712p893.js → read-session-chunk-cyks9yx4.js} +1 -1
  87. package/dist/{recomp-orchestrator-8ebydg5j.js → recomp-orchestrator-d4nks9da.js} +9 -9
  88. package/dist/{render-dtc4qkq4.js → render-gc1fn4nz.js} +5 -5
  89. package/dist/{search-75bj2430.js → search-1bjy7yhc.js} +8 -8
  90. package/dist/{search-archive-f6hjbnsa.js → search-archive-hdrfjgv8.js} +4 -4
  91. package/dist/shared/test-open-files.d.ts +17 -0
  92. package/dist/shared/test-open-files.d.ts.map +1 -0
  93. package/dist/shared/user-facing-codes.d.ts +7 -2
  94. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  95. package/dist/tools/ctx-expand/search-archive.d.ts.map +1 -1
  96. package/dist/{transform-postprocess-phase-1bg25094.js → transform-postprocess-phase-9e53b1dr.js} +10 -10
  97. package/dist/v2/auto-search-worker.js +3 -3
  98. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  99. package/dist/v2/{context-cpbhpxks.js → context-1p22880w.js} +1084 -370
  100. package/dist/v2/{embedding-backfill-x1zpc04f.js → embedding-backfill-bwcmw1te.js} +2 -2
  101. package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
  102. package/dist/v2/hooks/context.d.ts.map +1 -1
  103. package/dist/v2/{message-index-bounded-a36rw93p.js → message-index-bounded-mjpxz7wp.js} +2 -2
  104. package/dist/v2/migration-worker.js +1 -1
  105. package/dist/v2/{project-embedding-registry-v2fxrs8b.js → project-embedding-registry-7qcs8c61.js} +3 -1
  106. package/dist/v2/raw-ordinal-warmup-worker.js +3 -3
  107. package/dist/v2/{read-session-chunk-hzhxvhyv.js → read-session-chunk-cxk2kssy.js} +1 -1
  108. package/dist/v2/{recomp-orchestrator-yzr49pd0.js → recomp-orchestrator-e560ryjm.js} +8 -8
  109. package/dist/v2/{render-rhaevxv1.js → render-rk17pvy0.js} +5 -5
  110. package/dist/v2/{search-archive-9924fyk8.js → search-archive-a51g9sp7.js} +4 -4
  111. package/dist/v2/{search-3yrdpr38.js → search-kvzyj2mf.js} +7 -7
  112. package/dist/v2/{server-scp3y4dh.js → server-28g1b00j.js} +1 -1
  113. package/dist/v2/{server-kaqs6h31.js → server-52x68mj4.js} +1 -1
  114. package/dist/v2/{server-0k586y7d.js → server-71bg2psk.js} +3 -3
  115. package/dist/v2/{server-3bfc26r7.js → server-77rvx3wn.js} +34 -15
  116. package/dist/v2/{server-jxrqsn84.js → server-ah1j996f.js} +1 -1
  117. package/dist/v2/{server-sgn61hht.js → server-bjsmb6zs.js} +8 -3
  118. package/dist/v2/{server-16kfxcxj.js → server-bzh1fkvd.js} +1 -1
  119. package/dist/v2/{server-vjadwb3j.js → server-d5zgah57.js} +1 -1
  120. package/dist/v2/{server-q93jdtz8.js → server-e37d2zt4.js} +8 -7
  121. package/dist/v2/{server-016a1whm.js → server-fh6dhx8c.js} +104 -62
  122. package/dist/v2/{server-eznem83k.js → server-jmrd7vwc.js} +26 -15
  123. package/dist/v2/{server-4h4acntc.js → server-k3vtc89v.js} +9 -5
  124. package/dist/v2/{server-88yvx6r9.js → server-zq704789.js} +531 -17
  125. package/dist/v2/server.js +2 -2
  126. package/dist/v2/{v2-archive-reader-5ggewg8q.js → v2-archive-reader-hsvddme0.js} +1 -1
  127. package/dist/v2/{wrapup-orchestrator-36c5wyvq.js → wrapup-orchestrator-ckpj1yvj.js} +8 -8
  128. package/dist/{v2-archive-reader-gx5ke1d7.js → v2-archive-reader-qgqrxgrq.js} +1 -1
  129. package/dist/{wrapup-orchestrator-ya31knav.js → wrapup-orchestrator-6189f37j.js} +10 -10
  130. package/package.json +1 -1
  131. package/src/shared/escalation-bands.test.ts +16 -1
  132. package/src/shared/sqlite-placeholders.test.ts +103 -0
  133. package/src/shared/storage-file-mutex-review.test.ts +5 -7
  134. package/src/shared/test-open-files.test.ts +194 -0
  135. package/src/shared/test-open-files.ts +71 -0
  136. package/src/shared/user-facing-codes.ts +8 -2
@@ -28,7 +28,7 @@ import {
28
28
  clearIndexedMessages,
29
29
  indexSingleMessage,
30
30
  indexMessagesAfterOrdinal
31
- } from "./index-hkveze74.js";
31
+ } from "./index-3hhq18q0.js";
32
32
 
33
33
  // src/features/magic-context/message-index-async.ts
34
34
  var indexCancellations = new Map;
@@ -15,7 +15,7 @@ import {
15
15
  OpenAICompatibleEmbeddingProvider,
16
16
  getProjectEmbeddingSnapshot2,
17
17
  embedBatchForProject2
18
- } from "./index-bamnjp2t.js";
18
+ } from "./index-2m54t4g1.js";
19
19
  import {
20
20
  isEmbeddingHostBusy2
21
21
  } from "./index-qt1qqasc.js";
@@ -1023,7 +1023,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1023
1023
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
1024
1024
  if (signal.aborted || !readsOpenCodeStore)
1025
1025
  return;
1026
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-6712p893.js"));
1026
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-cyks9yx4.js"));
1027
1027
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-hp2jgn49.js"));
1028
1028
  if (signal.aborted)
1029
1029
  return;
@@ -72,7 +72,7 @@ import {
72
72
  getRawSessionTagKeysThrough2,
73
73
  getLegacyProtectedTailStartOrdinal2,
74
74
  readSessionChunk2
75
- } from "./index-07rp6xcn.js";
75
+ } from "./index-n3rxwtwt.js";
76
76
  import {
77
77
  getHarness2,
78
78
  harnessOwnsOpenCodeStore2
@@ -151,7 +151,7 @@ import {
151
151
  LATEST_SUPPORTED_VERSION,
152
152
  getPersistedSchemaVersion,
153
153
  openDatabase
154
- } from "./index-z4832qfe.js";
154
+ } from "./index-a6bxwv4a.js";
155
155
  import {
156
156
  areRustHistorianSyntheticParts2,
157
157
  isStrictGapHealingMessage2,
@@ -237,14 +237,14 @@ import {
237
237
  getProjectState,
238
238
  recordSubagentInvocation,
239
239
  getLatestHistorianInvocationId
240
- } from "./index-n0twfvah.js";
240
+ } from "./index-2ctn7q09.js";
241
241
  import {
242
242
  clearCompressionDepth,
243
243
  clearCompressionDepthRange,
244
244
  toMessageIndexSource,
245
245
  clearIndexedMessagesInTransaction,
246
246
  indexSourcesAfterOrdinal
247
- } from "./index-hkveze74.js";
247
+ } from "./index-3hhq18q0.js";
248
248
  import {
249
249
  stripWellFormedLeadingTagPrefix,
250
250
  peelLeadingMcTagNotation,
@@ -282,14 +282,14 @@ import {
282
282
  enqueueShadowEmbeddingItems2,
283
283
  getProjectChunkEmbeddingModelId2,
284
284
  getProjectEmbeddingMaxInputTokens2,
285
- embedItemsForProject2
286
- } from "./index-bamnjp2t.js";
285
+ embedItemsWindowBounded2
286
+ } from "./index-2m54t4g1.js";
287
287
  import {
288
288
  renderUserFacingFailure,
289
289
  userFacingFailureCode,
290
290
  promoteSessionFactsDurable,
291
291
  embedPromotedFacts
292
- } from "./index-cwj6qhmf.js";
292
+ } from "./index-kwpweqzs.js";
293
293
  import {
294
294
  isMarkerCandidateBasisCurrent2,
295
295
  invalidateMarkerCandidateBasis2,
@@ -8171,7 +8171,7 @@ function updateUserMemoryContent(db, id, content) {
8171
8171
  db.prepare("UPDATE user_memories SET content = ?, updated_at = ? WHERE id = ?").run(content, Date.now(), id);
8172
8172
  }
8173
8173
  function dismissUserMemory(db, id) {
8174
- db.prepare("UPDATE user_memories SET status = 'dismissed', updated_at = ? WHERE id = ?").run(Date.now(), id);
8174
+ db.prepare("UPDATE user_memories SET status = 'dismissed', updated_at = ? WHERE id = ? AND status = 'active'").run(Date.now(), id);
8175
8175
  }
8176
8176
  function parseCandidateIds(raw) {
8177
8177
  try {
@@ -11206,6 +11206,13 @@ function stripMemoryMuralBlock(m0Text) {
11206
11206
 
11207
11207
  `).trim();
11208
11208
  }
11209
+ function servedHeadTexts(state) {
11210
+ const m0Text = decodeM0Bytes(state.cachedM0Bytes);
11211
+ return {
11212
+ m0Text: m0Text !== null && !state.cachedM0MuralDataUrl ? stripMemoryMuralBlock(m0Text) : m0Text,
11213
+ m1Text: decodeM0Bytes(state.cachedM1Bytes)
11214
+ };
11215
+ }
11209
11216
  function renderM0(args) {
11210
11217
  const sections = [];
11211
11218
  if (args.projectDocs.length > 0)
@@ -11977,10 +11984,10 @@ function findHostCompactionWindow(messages, readMagicContextSummaryMessageId) {
11977
11984
  completedAt
11978
11985
  };
11979
11986
  }
11980
- function boundaryPrecedesWindow(sessionId, boundary, firstLiveId) {
11987
+ function boundaryOrderAgainstWindow(sessionId, boundary, firstLiveId) {
11981
11988
  const cached = precedesVerdictBySession.get(sessionId);
11982
11989
  if (cached && cached.boundary === boundary && cached.firstLiveId === firstLiveId) {
11983
- return cached.precedes;
11990
+ return cached.verdict;
11984
11991
  }
11985
11992
  let order = null;
11986
11993
  try {
@@ -11993,9 +12000,9 @@ function boundaryPrecedesWindow(sessionId, boundary, firstLiveId) {
11993
12000
  sessionLog2(sessionId, `prefix trim: placing boundary ${boundary} failed:`, error);
11994
12001
  order = null;
11995
12002
  }
11996
- const precedes = order !== null && order < 0;
11997
- precedesVerdictBySession.set(sessionId, { boundary, firstLiveId, precedes });
11998
- return precedes;
12003
+ const verdict = order === null || !Number.isFinite(order) ? "unknown" : order < 0 ? "precedes" : "not-before";
12004
+ precedesVerdictBySession.set(sessionId, { boundary, firstLiveId, verdict });
12005
+ return verdict;
11999
12006
  }
12000
12007
  function logBoundaryPrecedesWindow(options, boundary, firstLiveId) {
12001
12008
  const { sessionId } = options;
@@ -12009,9 +12016,10 @@ function classifyAbsentBoundary(options, messages, boundary) {
12009
12016
  const { sessionId } = options;
12010
12017
  const pass = options.isCacheBustingPass ? "priced" : "defer";
12011
12018
  const firstLiveId = firstPersistedLiveId(messages);
12012
- if (firstLiveId !== null && boundaryPrecedesWindow(sessionId, boundary, firstLiveId)) {
12019
+ const order = firstLiveId === null ? "unknown" : boundaryOrderAgainstWindow(sessionId, boundary, firstLiveId);
12020
+ if (firstLiveId !== null && order === "precedes") {
12013
12021
  logBoundaryPrecedesWindow(options, boundary, firstLiveId);
12014
- return "boundary-precedes-window";
12022
+ return { status: "boundary-precedes-window" };
12015
12023
  }
12016
12024
  precedesWindowLoggedBySession.delete(sessionId);
12017
12025
  const current = absentBoundaryEpisodeBySession.get(sessionId);
@@ -12021,7 +12029,10 @@ function classifyAbsentBoundary(options, messages, boundary) {
12021
12029
  if (episode.passes === 1 || options.isCacheBustingPass) {
12022
12030
  sessionLog2(sessionId, `prefix trim: boundary ${boundary} absent from current messages; pass=${pass}; no in-pass trim applied (degraded pass ${episode.passes}; ${firstLiveId === null ? "no persisted live message to compare with" : `boundary does not sort before the first live message ${firstLiveId}`}; whole window served until a cache-busting pass moves the boundary into the window)`);
12023
12031
  }
12024
- return "refused";
12032
+ return {
12033
+ status: "refused",
12034
+ refusal: order === "not-before" ? "boundary-not-in-request" : "boundary-unordered"
12035
+ };
12025
12036
  }
12026
12037
  function isSyntheticPrefixHead(message) {
12027
12038
  if (message.info.id !== undefined || message.info.role !== "user" || message.parts.length === 0) {
@@ -12035,17 +12046,14 @@ function capturePrefixTrimSourceOrder(messages) {
12035
12046
  let syntheticHeadCount = 0;
12036
12047
  let sawPersistedRow = false;
12037
12048
  let invalidReason = null;
12038
- for (const [index, message] of messages.entries()) {
12049
+ for (const message of messages) {
12039
12050
  const id = message.info.id;
12040
12051
  if (isHostRenderedSystemMessage(message))
12041
12052
  continue;
12042
12053
  if (typeof id !== "string" || id.length === 0) {
12043
- if (!sawPersistedRow && isSyntheticPrefixHead(message)) {
12054
+ if (!sawPersistedRow && isSyntheticPrefixHead(message))
12044
12055
  syntheticHeadCount += 1;
12045
- continue;
12046
- }
12047
- invalidReason = `source message at index ${index} has no stable id outside the synthetic head`;
12048
- break;
12056
+ continue;
12049
12057
  }
12050
12058
  sawPersistedRow = true;
12051
12059
  if (seen.has(id)) {
@@ -12094,21 +12102,49 @@ function reanchorStoredBoundary(options, boundary) {
12094
12102
  }
12095
12103
  function trimToPreparedPrefix(options, prepared) {
12096
12104
  if (options.compactionOff || !options.messages)
12097
- return "not-attempted";
12105
+ return { status: "not-attempted" };
12106
+ const messages = options.messages;
12098
12107
  const boundary = prepared.preparedTrimBoundaryId;
12099
- let status = "not-required";
12108
+ let outcome = { status: "not-required" };
12100
12109
  if (boundary) {
12101
12110
  const retireDecisions = (messageIds) => {
12102
12111
  queueAutoSearchHintDecisionRetirement(options.db, options.sessionId, new Set(messageIds));
12103
12112
  };
12113
+ const trimAtVisibleBoundary = (reanchor) => {
12114
+ const index = findBoundaryIndex(options.sessionId, messages, boundary);
12115
+ if (index >= 0) {
12116
+ const cut = index + (isPartialCompartmentEnd(options.db, options.sessionId, boundary) ? 0 : 1);
12117
+ const unplaced = messages.slice(0, cut).filter(isHostRenderedSystemMessage);
12118
+ const removed = messages.splice(0, cut, ...unplaced);
12119
+ retireDecisions(removed.map((message) => message.info.id).filter((id) => typeof id === "string"));
12120
+ resetPrefixTrimFallbackState(options.sessionId);
12121
+ return { status: "applied" };
12122
+ }
12123
+ if (reanchor) {
12124
+ const reanchored = reanchorStoredBoundary(options, boundary);
12125
+ if (reanchored && reanchored.messageIds[0] !== boundary) {
12126
+ return trimToPreparedPrefix({ ...options, prefixTrimSourceOrder: reanchored }, prepared);
12127
+ }
12128
+ }
12129
+ return classifyAbsentBoundary(options, messages, boundary);
12130
+ };
12104
12131
  const sourceOrder = options.prefixTrimSourceOrder;
12105
12132
  if (sourceOrder) {
12106
- const refuse = (reason) => {
12107
- sessionLog2(options.sessionId, `prefix trim: boundary ${boundary}; pass=${options.isCacheBustingPass ? "priced" : "defer"}; no in-pass trim applied (${reason})`);
12108
- return "refused";
12133
+ const pass = options.isCacheBustingPass ? "priced" : "defer";
12134
+ const refuse = (reason, refusal) => {
12135
+ sessionLog2(options.sessionId, `prefix trim: boundary ${boundary}; pass=${pass}; no in-pass trim applied (${reason})`);
12136
+ return { status: "refused", refusal };
12137
+ };
12138
+ const placeWithoutSourceOrder = (reason) => {
12139
+ sessionLog2(options.sessionId, `prefix trim: boundary ${boundary}; pass=${pass}; source order not usable (${reason}); placing the boundary by the live messages`);
12140
+ const served = resolveHostServedBoundaryId2(options.sessionId, boundary);
12141
+ const copies = messages.filter((message) => message.info.id === boundary || message.info.id === served).length;
12142
+ if (copies > 1)
12143
+ return refuse(`boundary ${boundary} appears ${copies} times in the live messages`, "boundary-unordered");
12144
+ return trimAtVisibleBoundary(false);
12109
12145
  };
12110
12146
  if (sourceOrder.invalidReason) {
12111
- status = refuse(sourceOrder.invalidReason);
12147
+ outcome = placeWithoutSourceOrder(sourceOrder.invalidReason);
12112
12148
  } else {
12113
12149
  const sourcePosition = new Map;
12114
12150
  sourceOrder.messageIds.forEach((id, index) => {
@@ -12117,7 +12153,7 @@ function trimToPreparedPrefix(options, prepared) {
12117
12153
  const boundaryPosition = sourcePosition.get(boundary) ?? sourcePosition.get(resolveHostServedBoundaryId2(options.sessionId, boundary));
12118
12154
  if (boundaryPosition === undefined) {
12119
12155
  const reanchored = reanchorStoredBoundary(options, boundary);
12120
- status = reanchored ? trimToPreparedPrefix({ ...options, prefixTrimSourceOrder: reanchored }, prepared) : refuse("boundary absent from immutable source order");
12156
+ outcome = reanchored ? trimToPreparedPrefix({ ...options, prefixTrimSourceOrder: reanchored }, prepared) : refuse("boundary absent from immutable source order", "boundary-unordered");
12121
12157
  } else {
12122
12158
  let lastSourcePosition = -1;
12123
12159
  let sawPersistedRow = false;
@@ -12125,17 +12161,29 @@ function trimToPreparedPrefix(options, prepared) {
12125
12161
  let firstLiveId;
12126
12162
  let liveOrderError = null;
12127
12163
  const retained = [];
12128
- for (const [index, message] of options.messages.entries()) {
12164
+ let unplaced = [];
12165
+ const placeUnplaced = (cut) => {
12166
+ for (const message of unplaced) {
12167
+ if (!cut || isHostRenderedSystemMessage(message))
12168
+ retained.push(message);
12169
+ }
12170
+ unplaced = [];
12171
+ };
12172
+ for (const message of options.messages) {
12129
12173
  const id = message.info.id;
12130
12174
  if (isHostRenderedSystemMessage(message)) {
12175
+ if (unplaced.length > 0) {
12176
+ unplaced.push(message);
12177
+ continue;
12178
+ }
12131
12179
  retained.push(message);
12132
12180
  continue;
12133
12181
  }
12134
12182
  if (typeof id !== "string" || id.length === 0) {
12135
12183
  if (!sawPersistedRow && isSyntheticPrefixHead(message))
12136
12184
  continue;
12137
- liveOrderError = `live message at index ${index} has no stable id outside the synthetic head`;
12138
- break;
12185
+ unplaced.push(message);
12186
+ continue;
12139
12187
  }
12140
12188
  sawPersistedRow = true;
12141
12189
  const position = sourcePosition.get(id);
@@ -12152,44 +12200,31 @@ function trimToPreparedPrefix(options, prepared) {
12152
12200
  firstLiveId = id;
12153
12201
  }
12154
12202
  lastSourcePosition = position;
12203
+ placeUnplaced(position <= boundaryPosition);
12155
12204
  if (position > boundaryPosition || position === boundaryPosition && isPartialCompartmentEnd(options.db, options.sessionId, boundary))
12156
12205
  retained.push(message);
12157
12206
  }
12158
- if (liveOrderError)
12159
- status = refuse(liveOrderError);
12160
- else {
12207
+ placeUnplaced(false);
12208
+ if (liveOrderError) {
12209
+ outcome = placeWithoutSourceOrder(liveOrderError);
12210
+ } else {
12161
12211
  if (firstLiveId && firstLivePosition !== undefined && firstLivePosition > boundaryPosition) {
12162
12212
  logBoundaryPrecedesWindow(options, boundary, firstLiveId);
12163
12213
  }
12164
12214
  options.messages.splice(0, options.messages.length, ...retained);
12165
12215
  const preserveBoundary = isPartialCompartmentEnd(options.db, options.sessionId, boundary);
12166
12216
  retireDecisions(sourceOrder.messageIds.slice(0, boundaryPosition + (preserveBoundary ? 0 : 1)));
12167
- status = "applied";
12217
+ outcome = { status: "applied" };
12168
12218
  }
12169
12219
  }
12170
12220
  }
12171
12221
  } else {
12172
- const index = findBoundaryIndex(options.sessionId, options.messages, boundary);
12173
- if (index >= 0) {
12174
- const cut = index + (isPartialCompartmentEnd(options.db, options.sessionId, boundary) ? 0 : 1);
12175
- const unplaced = options.messages.slice(0, cut).filter(isHostRenderedSystemMessage);
12176
- const removed = options.messages.splice(0, cut, ...unplaced);
12177
- retireDecisions(removed.map((message) => message.info.id).filter((id) => typeof id === "string"));
12178
- resetPrefixTrimFallbackState(options.sessionId);
12179
- status = "applied";
12180
- } else {
12181
- const reanchored = reanchorStoredBoundary(options, boundary);
12182
- if (reanchored && reanchored.messageIds[0] !== boundary) {
12183
- status = trimToPreparedPrefix({ ...options, prefixTrimSourceOrder: reanchored }, prepared);
12184
- } else {
12185
- status = classifyAbsentBoundary(options, options.messages, boundary);
12186
- }
12187
- }
12222
+ outcome = trimAtVisibleBoundary(true);
12188
12223
  }
12189
12224
  }
12190
12225
  if (prepared.m0RematerializedThisPass || options.isCacheBustingPass && !prepared.materializationContentionRetryExhausted)
12191
12226
  clearInjectionCache(options.sessionId);
12192
- return status;
12227
+ return outcome;
12193
12228
  }
12194
12229
  function prepareCachedM0M1Replay(db, sessionId) {
12195
12230
  const row = readCachedM0M1Row(db, sessionId);
@@ -12242,15 +12277,16 @@ function injectM0M1(options) {
12242
12277
  const prepared = options.preparedPrefix;
12243
12278
  if (prepared?.preparedMessages) {
12244
12279
  const head = prepared.preparedMessages;
12245
- let prefixTrimStatus = "not-attempted";
12280
+ let prefixTrim = { status: "not-attempted" };
12246
12281
  if (options.messages) {
12247
- prefixTrimStatus = trimToPreparedPrefix(options, prepared);
12282
+ prefixTrim = trimToPreparedPrefix(options, prepared);
12248
12283
  options.messages.unshift(...structuredClone(head));
12249
12284
  }
12250
12285
  return {
12251
12286
  ...prepared,
12252
12287
  prependedMessageCount: options.messages ? head.length : 0,
12253
- prefixTrimStatus
12288
+ prefixTrimStatus: prefixTrim.status,
12289
+ prefixTrimRefusal: prefixTrim.refusal
12254
12290
  };
12255
12291
  }
12256
12292
  hydrateCachedM0Mural(options.db, options.sessionId, options.state);
@@ -12407,9 +12443,9 @@ function injectM0M1(options) {
12407
12443
  contentHash: options.state.cachedM0MuralHash ?? undefined
12408
12444
  } : undefined;
12409
12445
  let prependedMessageCount = prependM0M1Messages(options.sessionId, preparedMessages, m0Text, m1Text, muralForWire);
12410
- let prefixTrimStatus = "not-attempted";
12446
+ let prefixTrim = { status: "not-attempted" };
12411
12447
  if (options.messages) {
12412
- prefixTrimStatus = trimToPreparedPrefix(options, {
12448
+ prefixTrim = trimToPreparedPrefix(options, {
12413
12449
  m0RematerializedThisPass: rematerialized,
12414
12450
  materializationContentionRetryExhausted: contentionExhausted,
12415
12451
  preparedTrimBoundaryId
@@ -12427,7 +12463,8 @@ function injectM0M1(options) {
12427
12463
  m1Text,
12428
12464
  preparedMessages,
12429
12465
  preparedTrimBoundaryId,
12430
- prefixTrimStatus
12466
+ prefixTrimStatus: prefixTrim.status,
12467
+ ...prefixTrim.refusal ? { prefixTrimRefusal: prefixTrim.refusal } : {}
12431
12468
  };
12432
12469
  }
12433
12470
 
@@ -15118,11 +15155,11 @@ async function embedAndStoreCompartmentChunks(db, sessionId, projectPath, compar
15118
15155
  if (currentModelId !== "off" && chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
15119
15156
  continue;
15120
15157
  }
15121
- const result = await embedItemsForProject2(projectPath, windows.map((window) => ({
15158
+ const result = await embedItemsWindowBounded2(projectPath, windows.map((window) => ({
15122
15159
  id: `chunk:${compartment.id}:${window.windowIndex}`,
15123
15160
  text: window.text,
15124
15161
  contentSha256: contentSha2562(window.text)
15125
- })), undefined, db, sessionId);
15162
+ })), undefined, db, sessionId, { stopOnIncompleteSlice: true });
15126
15163
  if (!result)
15127
15164
  continue;
15128
15165
  if (chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
@@ -16276,6 +16313,11 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
16276
16313
  const start = chunk.startIndex;
16277
16314
  if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
16278
16315
  return false;
16316
+ const endId = rows[rows.length - 1].messageId;
16317
+ if (!hasRawSessionMessageById2(sessionId, endId)) {
16318
+ sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
16319
+ return false;
16320
+ }
16279
16321
  const saved = db.transaction(() => {
16280
16322
  const prior = getCompartments(db, sessionId);
16281
16323
  const last = prior.at(-1);
@@ -18995,4 +19037,4 @@ async function executeContextRecomp(deps, options = {}) {
18995
19037
  return (await executeContextRecompWithResult(deps, options)).message;
18996
19038
  }
18997
19039
 
18998
- export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
19040
+ export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, servedHeadTexts, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  withMessageFtsSessionFilter
3
- } from "./index-kaqs6h31.js";
3
+ } from "./index-52x68mj4.js";
4
4
  import {
5
5
  getSqliteDatabasePath2
6
6
  } from "./index-gzy5w8ya.js";
@@ -19,10 +19,10 @@ import {
19
19
  rawMessageWorkerSource2,
20
20
  rawMessageOffThreadRangeReader2,
21
21
  readRawSessionMessageIdOrdinalsForRange2
22
- } from "./index-07rp6xcn.js";
22
+ } from "./index-n3rxwtwt.js";
23
23
  import {
24
24
  readV2ArchiveOffThread2
25
- } from "./index-ct3ettqt.js";
25
+ } from "./index-3h0wyv22.js";
26
26
 
27
27
  // src/tools/ctx-expand/search-archive.ts
28
28
  var archiveReadsOnThisThread = 0;
@@ -33,17 +33,18 @@ function renderSearchArchive2(db, sessionId, start, end, tokenBudget, archiveOnl
33
33
  const rows = db.prepare(sessionFirst ? `SELECT f.message_ordinal AS ordinal, f.message_id AS id, f.role, f.content
34
34
  FROM message_fts_rowid_map AS m
35
35
  JOIN message_history_fts AS f ON f.rowid = m.fts_rowid
36
- WHERE m.session_id = ?1 AND m.message_ordinal BETWEEN ?2 AND ?3
37
- AND f.session_id = ?1 AND f.message_ordinal BETWEEN ?2 AND ?3
36
+ WHERE m.session_id = ? AND m.message_ordinal BETWEEN ? AND ?
37
+ AND f.session_id = ? AND f.message_ordinal BETWEEN ? AND ?
38
38
  ORDER BY m.message_ordinal` : `SELECT message_ordinal AS ordinal, message_id AS id, role, content
39
39
  FROM message_history_fts
40
- WHERE session_id = ?1 AND message_ordinal BETWEEN ?2 AND ?3
40
+ WHERE session_id = ? AND message_ordinal BETWEEN ? AND ?
41
41
  ORDER BY CAST(message_ordinal AS INTEGER)`);
42
42
  const blocks = [];
43
43
  let tokens = 0;
44
44
  let lastOrdinal = start - 1;
45
45
  let truncated = false;
46
- for (const row of rows.iterate(sessionId, start, end)) {
46
+ const bindings = sessionFirst ? [sessionId, start, end, sessionId, start, end] : [sessionId, start, end];
47
+ for (const row of rows.iterate(...bindings)) {
47
48
  if (!row.content)
48
49
  continue;
49
50
  if (!archiveOnly) {
@@ -3,18 +3,18 @@ import {
3
3
  } from "./index-82dfe8en.js";
4
4
  import {
5
5
  clearEmergencyRecovery
6
- } from "./index-07rp6xcn.js";
6
+ } from "./index-n3rxwtwt.js";
7
7
  import {
8
8
  requestPendingMaterialization,
9
9
  dropSlot
10
- } from "./index-n0twfvah.js";
10
+ } from "./index-2ctn7q09.js";
11
11
  import {
12
12
  executeContextRecomp
13
- } from "./index-h8g08nxs.js";
13
+ } from "./index-chjsdqg6.js";
14
14
  import {
15
15
  renderUserFacingFailure,
16
16
  userFacingFailureCode
17
- } from "./index-cwj6qhmf.js";
17
+ } from "./index-kwpweqzs.js";
18
18
 
19
19
  // src/hooks/magic-context/recomp-orchestrator.ts
20
20
  function resolveLiveModelKey(liveSessionState, sessionId) {
@@ -10,7 +10,7 @@ import {
10
10
  } from "./index-82dfe8en.js";
11
11
  import {
12
12
  embedTextForProject2
13
- } from "./index-bamnjp2t.js";
13
+ } from "./index-2m54t4g1.js";
14
14
  import {
15
15
  saveEmbeddingIfHashMatches
16
16
  } from "./index-4dhv7mqz.js";
@@ -42,8 +42,13 @@ var USER_FACING_FAILURES = {
42
42
  },
43
43
  history_boundary_unresolved: {
44
44
  code: "MC-H04",
45
- sentence: "This request was not sent: Magic Context could not safely place the history summary boundary in the loaded conversation, and the untrimmed request is larger than the model's context window.",
46
- action: "Reopen this session in its current project directory, then run /ctx-recomp to rebuild the history summary. A model with a larger context window can also help."
45
+ sentence: "This request was not sent: it is larger than the model's context window, and Magic Context could not cut the already-summarized history out of it.",
46
+ action: "Run /ctx-flush to compress the history now, then send your message again."
47
+ },
48
+ history_boundary_recovering: {
49
+ code: "MC-H08",
50
+ sentence: "This request was not sent: it is larger than the model's context window, and Magic Context could not cut the already-summarized history out of it.",
51
+ action: "Send your message again: Magic Context will first summarize more of the history and drop old tool output to make it fit."
47
52
  },
48
53
  history_over_window_unmanaged: {
49
54
  code: "MC-H06",
@@ -3545,7 +3545,7 @@ function normalizeDetectedLimitModelKey(modelKey) {
3545
3545
  return typeof modelKey === "string" && modelKey.length > 0 ? piModelRefToCanonical(modelKey) : null;
3546
3546
  }
3547
3547
  function normalizeEmergencyRecoveryOrigin(value) {
3548
- return value === "provider_overflow" || value === "proactive_model_shrink" ? value : null;
3548
+ return value === "provider_overflow" || value === "proactive_model_shrink" || value === "history_boundary_over_window" ? value : null;
3549
3549
  }
3550
3550
  function parseOverflowState(result, modelKey) {
3551
3551
  if (!result) {
@@ -3838,6 +3838,24 @@ function getThinkingBindingRecoveryTarget(db, sessionId) {
3838
3838
  function armThinkingBindingRecovery(db, sessionId) {
3839
3839
  ensureSessionMetaRow(db, sessionId);
3840
3840
  db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(THINKING_BINDING_RECOVERY_ALL_ASSISTANTS, sessionId);
3841
+ bindingRecoveriesAwaitingClear.delete(sessionId);
3842
+ }
3843
+ var bindingRecoveriesAwaitingClear = new Map;
3844
+ function noteBindingRecoveryAwaitingClear(sessionId, target) {
3845
+ bindingRecoveriesAwaitingClear.set(sessionId, target);
3846
+ }
3847
+ function bindingRecoveryAwaitingClear(sessionId) {
3848
+ return bindingRecoveriesAwaitingClear.get(sessionId);
3849
+ }
3850
+ function retryBindingRecoveryClear(db, sessionId) {
3851
+ const target = bindingRecoveriesAwaitingClear.get(sessionId);
3852
+ if (target === undefined)
3853
+ return true;
3854
+ if (clearThinkingBindingRecoveryIf(db, sessionId, target) || getThinkingBindingRecoveryTarget(db, sessionId) !== target) {
3855
+ bindingRecoveriesAwaitingClear.delete(sessionId);
3856
+ return true;
3857
+ }
3858
+ return false;
3841
3859
  }
3842
3860
  function clearThinkingBindingRecoveryIf(db, sessionId, expectedTarget) {
3843
3861
  const result = db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, expectedTarget);
@@ -4144,6 +4162,20 @@ function getSessionsWithPendingMarker(db) {
4144
4162
  AND pending_compaction_marker_state != ''`).all();
4145
4163
  return rows.map((r) => r.session_id);
4146
4164
  }
4165
+ function cachedHeadCoversPendingCompactionMarker(db, sessionId) {
4166
+ const pending = getPendingCompactionMarkerState(db, sessionId);
4167
+ if (!pending)
4168
+ return false;
4169
+ const head = db.prepare(`SELECT length(cached_m0_bytes) > 0 AND length(cached_m1_bytes) > 0 AS complete,
4170
+ cached_m0_last_baseline_end_message_id AS baseline
4171
+ FROM session_meta WHERE session_id = ?`).get(sessionId);
4172
+ if (head?.complete !== 1 || !head.baseline)
4173
+ return false;
4174
+ if (head.baseline === pending.endMessageId)
4175
+ return true;
4176
+ const rendered = db.prepare("SELECT MAX(end_message) AS endMessage FROM compartments WHERE session_id = ? AND end_message_id = ?").get(sessionId, head.baseline);
4177
+ return typeof rendered?.endMessage === "number" && rendered.endMessage >= pending.ordinal;
4178
+ }
4147
4179
  var preSnapshotSessions = new Map;
4148
4180
  var warnedProtectedTokenTierOverrides = new WeakSet;
4149
4181
  function isPreSnapshotMemo(value) {
@@ -4719,22 +4751,23 @@ function activeAnthropicTurnStart(messages, anthropic) {
4719
4751
  if (!anthropic)
4720
4752
  return;
4721
4753
  for (let user = messages.length - 1;user >= 0; user--) {
4722
- const message = messages[user];
4723
- if (!isRecord(message))
4724
- continue;
4725
- const info = isRecord(message.info) ? message.info : message;
4726
- if (info.role !== "user" || info.synthetic === true || message.synthetic === true)
4727
- continue;
4728
- const id = typeof info.id === "string" ? info.id : "";
4729
- if (id.startsWith("synth-user-"))
4730
- continue;
4731
- const parts = Array.isArray(message.parts) ? message.parts : Array.isArray(message.content) ? message.content : [];
4732
- if (parts.length > 0 && parts.every((part) => isRecord(part) && (part.synthetic === true || part.ignored === true || ["tool_result", "toolResult", "tool-result"].includes(String(part.type)))))
4733
- continue;
4734
- return user + 1;
4754
+ if (isRealUserRequest(messages[user]))
4755
+ return user + 1;
4735
4756
  }
4736
4757
  return;
4737
4758
  }
4759
+ function isRealUserRequest(message) {
4760
+ if (!isRecord(message))
4761
+ return false;
4762
+ const info = isRecord(message.info) ? message.info : message;
4763
+ if (info.role !== "user" || info.synthetic === true || message.synthetic === true)
4764
+ return false;
4765
+ const id = typeof info.id === "string" ? info.id : "";
4766
+ if (id.startsWith("synth-user-"))
4767
+ return false;
4768
+ const parts = Array.isArray(message.parts) ? message.parts : Array.isArray(message.content) ? message.content : [];
4769
+ return !(parts.length > 0 && parts.every((part) => isRecord(part) && (part.synthetic === true || part.ignored === true || ["tool_result", "toolResult", "tool-result"].includes(String(part.type)))));
4770
+ }
4738
4771
  function hasAnthropicReasoning(messages) {
4739
4772
  return messages.some((message) => {
4740
4773
  if (!isRecord(message))
@@ -7606,4 +7639,4 @@ function readRawSessionSeedTail2(sessionId, boundaryId, onQuery) {
7606
7639
  });
7607
7640
  }
7608
7641
 
7609
- export { isToolFreeHiddenAgent, TOOL_USE_DISABLED, ZEN_READ_AGENT_SUFFIX, needsBlockedRead, withBlockedReadInstruction, rememberV1HiddenRun, shapeV1HiddenMessage, expandToolPart, askAnswerLines, removeUnsupportedCommitHashes, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, isTextPart, isToolPartWithOutput, isFilePart, toolPartHasUserAnswer, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, recordToolParameters, createDroppedInputGuard, assertExecutableToolInput, createDroppedInputToolExecuteBeforeHook, isEditTool, createFinalWireIncompleteLogger, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, readEpochFloorSnapshot, getProtectionWindowForSession, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, clearCachedM0, withReplayEnvelopeSnapshot, invalidateReplayEnvelopeSnapshot, isRustMarkerAdmissionFenced, setRustMarkerAdmissionFence, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadPersistedUsage, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, resetProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, removeNoteNudgeAnchorByMessageId, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, getCompactionMarkerPublicationState, compareAndSetCompactionMarkerPublicationState, setPersistedCompactionMarkerState, getDeferredClearedCompactionMarkerState, retireDeferredClearedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, compactionOffThinkingFrozenId, compactionOffFrozenThinkingIds, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, getProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, replacePendingCompactionMarkerStateIf, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingMarker, getObservedEpochFloor, resolveEpochFloorForPass, getReasoningRemovalState, addRemovedReasoningIds, markDropLeavesReasoning, detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, modelAcceptsEmptyContent, isAnthropicFamilyRoute, neutralizeDroppedReasoningPart, restoreNeutralizedReasoningPart, isNeutralizedReasoningPart, variantChangeBustsProviderCache, makeSentinel, makeWholeMessageSentinel, isSentinel, replaySentinelByMessageIds, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, markServedShapeRepair, prepareServedShapeRepair, stripSystemInjectedMessages, stripDroppedPlaceholderMessages, replayClearedReasoning, replayStrippedInlineThinking, clearOldReasoning, stripClearedReasoning, captureInlineThinkingRepairs, stripInlineThinking, findReasoningBearingAssistantIds, findLatestAssistantReasoningMutationExemptMessage, snapshotTrailingBlankSourceDecisions, findTrailingBlankDecisionCandidates, applyFrozenTrailingBlankDecisions, stripReasoningFromAssistantIds, findMergedReasoningStripDecisions, stripReasoningFromMergedAssistants, getEmptyImageParts, stripProcessedImages, projectOpencodeReasoningBudgetCutoff, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opencodeReasoningBudgetCutoff, describeFinalWireTail, estimatePartImageTokens, estimateMessageTokens, wireContentBytes, createFinalWireUsageTracker, estimateFinalWireInputTokens, estimateAppendedWireTokens, SKELETON_REAL_INPUT_MAX_BYTES, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, resolveHostServedBoundaryId2, hasRawMessageProvider2, rawMessageWorkerSource2, rawMessageOffThreadRangeReader2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, visitRawSessionMessagesAsync2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, readRawSessionBoundaryEndpoints2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, resolveHistorianChunkStart2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };
7642
+ export { isToolFreeHiddenAgent, TOOL_USE_DISABLED, ZEN_READ_AGENT_SUFFIX, needsBlockedRead, withBlockedReadInstruction, rememberV1HiddenRun, shapeV1HiddenMessage, expandToolPart, askAnswerLines, removeUnsupportedCommitHashes, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, isTextPart, isToolPartWithOutput, isFilePart, toolPartHasUserAnswer, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, recordToolParameters, createDroppedInputGuard, assertExecutableToolInput, createDroppedInputToolExecuteBeforeHook, isEditTool, createFinalWireIncompleteLogger, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, readEpochFloorSnapshot, getProtectionWindowForSession, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, clearCachedM0, withReplayEnvelopeSnapshot, invalidateReplayEnvelopeSnapshot, isRustMarkerAdmissionFenced, setRustMarkerAdmissionFence, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadPersistedUsage, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, resetProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, removeNoteNudgeAnchorByMessageId, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, getCompactionMarkerPublicationState, compareAndSetCompactionMarkerPublicationState, setPersistedCompactionMarkerState, getDeferredClearedCompactionMarkerState, retireDeferredClearedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, compactionOffThinkingFrozenId, compactionOffFrozenThinkingIds, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, noteBindingRecoveryAwaitingClear, bindingRecoveryAwaitingClear, retryBindingRecoveryClear, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, getProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, replacePendingCompactionMarkerStateIf, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingMarker, cachedHeadCoversPendingCompactionMarker, getObservedEpochFloor, resolveEpochFloorForPass, getReasoningRemovalState, addRemovedReasoningIds, markDropLeavesReasoning, detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, modelAcceptsEmptyContent, isAnthropicFamilyRoute, neutralizeDroppedReasoningPart, restoreNeutralizedReasoningPart, isNeutralizedReasoningPart, variantChangeBustsProviderCache, makeSentinel, makeWholeMessageSentinel, isSentinel, replaySentinelByMessageIds, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, markServedShapeRepair, prepareServedShapeRepair, stripSystemInjectedMessages, stripDroppedPlaceholderMessages, replayClearedReasoning, replayStrippedInlineThinking, clearOldReasoning, stripClearedReasoning, captureInlineThinkingRepairs, stripInlineThinking, findReasoningBearingAssistantIds, findLatestAssistantReasoningMutationExemptMessage, snapshotTrailingBlankSourceDecisions, findTrailingBlankDecisionCandidates, applyFrozenTrailingBlankDecisions, stripReasoningFromAssistantIds, findMergedReasoningStripDecisions, stripReasoningFromMergedAssistants, getEmptyImageParts, stripProcessedImages, projectOpencodeReasoningBudgetCutoff, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opencodeReasoningBudgetCutoff, describeFinalWireTail, estimatePartImageTokens, estimateMessageTokens, wireContentBytes, createFinalWireUsageTracker, estimateFinalWireInputTokens, estimateAppendedWireTokens, SKELETON_REAL_INPUT_MAX_BYTES, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, resolveHostServedBoundaryId2, hasRawMessageProvider2, rawMessageWorkerSource2, rawMessageOffThreadRangeReader2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, visitRawSessionMessagesAsync2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, readRawSessionBoundaryEndpoints2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, resolveHistorianChunkStart2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };