@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
@@ -152,7 +152,7 @@ import {
152
152
  getRawSessionTagKeysThrough2,
153
153
  getLegacyProtectedTailStartOrdinal2,
154
154
  readSessionChunk2
155
- } from "./server-3bfc26r7.js";
155
+ } from "./server-77rvx3wn.js";
156
156
  import {
157
157
  BoundedSessionMap
158
158
  } from "./server-kgq2e2hh.js";
@@ -162,7 +162,7 @@ import {
162
162
  toMessageIndexSource,
163
163
  clearIndexedMessagesInTransaction,
164
164
  indexSourcesAfterOrdinal
165
- } from "./server-16kfxcxj.js";
165
+ } from "./server-bzh1fkvd.js";
166
166
  import {
167
167
  COMPARTMENT_LEASE_RENEWAL_MS,
168
168
  getCompartmentLeaseBlocker,
@@ -206,7 +206,7 @@ import {
206
206
  getProjectState,
207
207
  recordSubagentInvocation,
208
208
  getLatestHistorianInvocationId
209
- } from "./server-88yvx6r9.js";
209
+ } from "./server-zq704789.js";
210
210
  import {
211
211
  invalidateAutoEmbedSession
212
212
  } from "./server-2amn2s73.js";
@@ -240,8 +240,8 @@ import {
240
240
  enqueueShadowEmbeddingItems2,
241
241
  getProjectChunkEmbeddingModelId2,
242
242
  getProjectEmbeddingMaxInputTokens2,
243
- embedItemsForProject2
244
- } from "./server-4h4acntc.js";
243
+ embedItemsWindowBounded2
244
+ } from "./server-k3vtc89v.js";
245
245
  import {
246
246
  V2_MEMORY_CATEGORIES,
247
247
  CATEGORY_PRIORITY,
@@ -260,13 +260,13 @@ import {
260
260
  userFacingFailureCode,
261
261
  promoteSessionFactsDurable,
262
262
  embedPromotedFacts
263
- } from "./server-sgn61hht.js";
263
+ } from "./server-bjsmb6zs.js";
264
264
  import {
265
265
  getSchemaFenceRejection,
266
266
  LATEST_SUPPORTED_VERSION,
267
267
  getPersistedSchemaVersion,
268
268
  openDatabase
269
- } from "./server-scp3y4dh.js";
269
+ } from "./server-28g1b00j.js";
270
270
  import {
271
271
  parseCompartmentOutput,
272
272
  resolveWorkspaceShareCategories,
@@ -2390,11 +2390,11 @@ async function embedAndStoreCompartmentChunks(db, sessionId, projectPath, compar
2390
2390
  if (currentModelId !== "off" && chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
2391
2391
  continue;
2392
2392
  }
2393
- const result = await embedItemsForProject2(projectPath, windows.map((window) => ({
2393
+ const result = await embedItemsWindowBounded2(projectPath, windows.map((window) => ({
2394
2394
  id: `chunk:${compartment.id}:${window.windowIndex}`,
2395
2395
  text: window.text,
2396
2396
  contentSha256: contentSha2562(window.text)
2397
- })), undefined, db, sessionId);
2397
+ })), undefined, db, sessionId, { stopOnIncompleteSlice: true });
2398
2398
  if (!result)
2399
2399
  continue;
2400
2400
  if (chunkEmbeddingWindowsAreCurrent2(db, compartment.id, currentModelId, windows, projectPath)) {
@@ -2548,7 +2548,7 @@ function updateUserMemoryContent(db, id, content) {
2548
2548
  db.prepare("UPDATE user_memories SET content = ?, updated_at = ? WHERE id = ?").run(content, Date.now(), id);
2549
2549
  }
2550
2550
  function dismissUserMemory(db, id) {
2551
- db.prepare("UPDATE user_memories SET status = 'dismissed', updated_at = ? WHERE id = ?").run(Date.now(), id);
2551
+ db.prepare("UPDATE user_memories SET status = 'dismissed', updated_at = ? WHERE id = ? AND status = 'active'").run(Date.now(), id);
2552
2552
  }
2553
2553
  function parseCandidateIds(raw) {
2554
2554
  try {
@@ -9067,6 +9067,13 @@ function stripMemoryMuralBlock(m0Text) {
9067
9067
 
9068
9068
  `).trim();
9069
9069
  }
9070
+ function servedHeadTexts(state) {
9071
+ const m0Text = decodeM0Bytes(state.cachedM0Bytes);
9072
+ return {
9073
+ m0Text: m0Text !== null && !state.cachedM0MuralDataUrl ? stripMemoryMuralBlock(m0Text) : m0Text,
9074
+ m1Text: decodeM0Bytes(state.cachedM1Bytes)
9075
+ };
9076
+ }
9070
9077
  function renderM0(args) {
9071
9078
  const sections = [];
9072
9079
  if (args.projectDocs.length > 0)
@@ -9838,10 +9845,10 @@ function findHostCompactionWindow(messages, readMagicContextSummaryMessageId) {
9838
9845
  completedAt
9839
9846
  };
9840
9847
  }
9841
- function boundaryPrecedesWindow(sessionId, boundary, firstLiveId) {
9848
+ function boundaryOrderAgainstWindow(sessionId, boundary, firstLiveId) {
9842
9849
  const cached = precedesVerdictBySession.get(sessionId);
9843
9850
  if (cached && cached.boundary === boundary && cached.firstLiveId === firstLiveId) {
9844
- return cached.precedes;
9851
+ return cached.verdict;
9845
9852
  }
9846
9853
  let order = null;
9847
9854
  try {
@@ -9854,9 +9861,9 @@ function boundaryPrecedesWindow(sessionId, boundary, firstLiveId) {
9854
9861
  sessionLog2(sessionId, `prefix trim: placing boundary ${boundary} failed:`, error);
9855
9862
  order = null;
9856
9863
  }
9857
- const precedes = order !== null && order < 0;
9858
- precedesVerdictBySession.set(sessionId, { boundary, firstLiveId, precedes });
9859
- return precedes;
9864
+ const verdict = order === null || !Number.isFinite(order) ? "unknown" : order < 0 ? "precedes" : "not-before";
9865
+ precedesVerdictBySession.set(sessionId, { boundary, firstLiveId, verdict });
9866
+ return verdict;
9860
9867
  }
9861
9868
  function logBoundaryPrecedesWindow(options, boundary, firstLiveId) {
9862
9869
  const { sessionId } = options;
@@ -9870,9 +9877,10 @@ function classifyAbsentBoundary(options, messages, boundary) {
9870
9877
  const { sessionId } = options;
9871
9878
  const pass = options.isCacheBustingPass ? "priced" : "defer";
9872
9879
  const firstLiveId = firstPersistedLiveId(messages);
9873
- if (firstLiveId !== null && boundaryPrecedesWindow(sessionId, boundary, firstLiveId)) {
9880
+ const order = firstLiveId === null ? "unknown" : boundaryOrderAgainstWindow(sessionId, boundary, firstLiveId);
9881
+ if (firstLiveId !== null && order === "precedes") {
9874
9882
  logBoundaryPrecedesWindow(options, boundary, firstLiveId);
9875
- return "boundary-precedes-window";
9883
+ return { status: "boundary-precedes-window" };
9876
9884
  }
9877
9885
  precedesWindowLoggedBySession.delete(sessionId);
9878
9886
  const current = absentBoundaryEpisodeBySession.get(sessionId);
@@ -9882,7 +9890,10 @@ function classifyAbsentBoundary(options, messages, boundary) {
9882
9890
  if (episode.passes === 1 || options.isCacheBustingPass) {
9883
9891
  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)`);
9884
9892
  }
9885
- return "refused";
9893
+ return {
9894
+ status: "refused",
9895
+ refusal: order === "not-before" ? "boundary-not-in-request" : "boundary-unordered"
9896
+ };
9886
9897
  }
9887
9898
  function isSyntheticPrefixHead(message) {
9888
9899
  if (message.info.id !== undefined || message.info.role !== "user" || message.parts.length === 0) {
@@ -9896,17 +9907,14 @@ function capturePrefixTrimSourceOrder(messages) {
9896
9907
  let syntheticHeadCount = 0;
9897
9908
  let sawPersistedRow = false;
9898
9909
  let invalidReason = null;
9899
- for (const [index, message] of messages.entries()) {
9910
+ for (const message of messages) {
9900
9911
  const id = message.info.id;
9901
9912
  if (isHostRenderedSystemMessage(message))
9902
9913
  continue;
9903
9914
  if (typeof id !== "string" || id.length === 0) {
9904
- if (!sawPersistedRow && isSyntheticPrefixHead(message)) {
9915
+ if (!sawPersistedRow && isSyntheticPrefixHead(message))
9905
9916
  syntheticHeadCount += 1;
9906
- continue;
9907
- }
9908
- invalidReason = `source message at index ${index} has no stable id outside the synthetic head`;
9909
- break;
9917
+ continue;
9910
9918
  }
9911
9919
  sawPersistedRow = true;
9912
9920
  if (seen.has(id)) {
@@ -9955,21 +9963,49 @@ function reanchorStoredBoundary(options, boundary) {
9955
9963
  }
9956
9964
  function trimToPreparedPrefix(options, prepared) {
9957
9965
  if (options.compactionOff || !options.messages)
9958
- return "not-attempted";
9966
+ return { status: "not-attempted" };
9967
+ const messages = options.messages;
9959
9968
  const boundary = prepared.preparedTrimBoundaryId;
9960
- let status = "not-required";
9969
+ let outcome = { status: "not-required" };
9961
9970
  if (boundary) {
9962
9971
  const retireDecisions = (messageIds) => {
9963
9972
  queueAutoSearchHintDecisionRetirement(options.db, options.sessionId, new Set(messageIds));
9964
9973
  };
9974
+ const trimAtVisibleBoundary = (reanchor) => {
9975
+ const index = findBoundaryIndex(options.sessionId, messages, boundary);
9976
+ if (index >= 0) {
9977
+ const cut = index + (isPartialCompartmentEnd(options.db, options.sessionId, boundary) ? 0 : 1);
9978
+ const unplaced = messages.slice(0, cut).filter(isHostRenderedSystemMessage);
9979
+ const removed = messages.splice(0, cut, ...unplaced);
9980
+ retireDecisions(removed.map((message) => message.info.id).filter((id) => typeof id === "string"));
9981
+ resetPrefixTrimFallbackState(options.sessionId);
9982
+ return { status: "applied" };
9983
+ }
9984
+ if (reanchor) {
9985
+ const reanchored = reanchorStoredBoundary(options, boundary);
9986
+ if (reanchored && reanchored.messageIds[0] !== boundary) {
9987
+ return trimToPreparedPrefix({ ...options, prefixTrimSourceOrder: reanchored }, prepared);
9988
+ }
9989
+ }
9990
+ return classifyAbsentBoundary(options, messages, boundary);
9991
+ };
9965
9992
  const sourceOrder = options.prefixTrimSourceOrder;
9966
9993
  if (sourceOrder) {
9967
- const refuse = (reason) => {
9968
- sessionLog2(options.sessionId, `prefix trim: boundary ${boundary}; pass=${options.isCacheBustingPass ? "priced" : "defer"}; no in-pass trim applied (${reason})`);
9969
- return "refused";
9994
+ const pass = options.isCacheBustingPass ? "priced" : "defer";
9995
+ const refuse = (reason, refusal) => {
9996
+ sessionLog2(options.sessionId, `prefix trim: boundary ${boundary}; pass=${pass}; no in-pass trim applied (${reason})`);
9997
+ return { status: "refused", refusal };
9998
+ };
9999
+ const placeWithoutSourceOrder = (reason) => {
10000
+ sessionLog2(options.sessionId, `prefix trim: boundary ${boundary}; pass=${pass}; source order not usable (${reason}); placing the boundary by the live messages`);
10001
+ const served = resolveHostServedBoundaryId2(options.sessionId, boundary);
10002
+ const copies = messages.filter((message) => message.info.id === boundary || message.info.id === served).length;
10003
+ if (copies > 1)
10004
+ return refuse(`boundary ${boundary} appears ${copies} times in the live messages`, "boundary-unordered");
10005
+ return trimAtVisibleBoundary(false);
9970
10006
  };
9971
10007
  if (sourceOrder.invalidReason) {
9972
- status = refuse(sourceOrder.invalidReason);
10008
+ outcome = placeWithoutSourceOrder(sourceOrder.invalidReason);
9973
10009
  } else {
9974
10010
  const sourcePosition = new Map;
9975
10011
  sourceOrder.messageIds.forEach((id, index) => {
@@ -9978,7 +10014,7 @@ function trimToPreparedPrefix(options, prepared) {
9978
10014
  const boundaryPosition = sourcePosition.get(boundary) ?? sourcePosition.get(resolveHostServedBoundaryId2(options.sessionId, boundary));
9979
10015
  if (boundaryPosition === undefined) {
9980
10016
  const reanchored = reanchorStoredBoundary(options, boundary);
9981
- status = reanchored ? trimToPreparedPrefix({ ...options, prefixTrimSourceOrder: reanchored }, prepared) : refuse("boundary absent from immutable source order");
10017
+ outcome = reanchored ? trimToPreparedPrefix({ ...options, prefixTrimSourceOrder: reanchored }, prepared) : refuse("boundary absent from immutable source order", "boundary-unordered");
9982
10018
  } else {
9983
10019
  let lastSourcePosition = -1;
9984
10020
  let sawPersistedRow = false;
@@ -9986,17 +10022,29 @@ function trimToPreparedPrefix(options, prepared) {
9986
10022
  let firstLiveId;
9987
10023
  let liveOrderError = null;
9988
10024
  const retained = [];
9989
- for (const [index, message] of options.messages.entries()) {
10025
+ let unplaced = [];
10026
+ const placeUnplaced = (cut) => {
10027
+ for (const message of unplaced) {
10028
+ if (!cut || isHostRenderedSystemMessage(message))
10029
+ retained.push(message);
10030
+ }
10031
+ unplaced = [];
10032
+ };
10033
+ for (const message of options.messages) {
9990
10034
  const id = message.info.id;
9991
10035
  if (isHostRenderedSystemMessage(message)) {
10036
+ if (unplaced.length > 0) {
10037
+ unplaced.push(message);
10038
+ continue;
10039
+ }
9992
10040
  retained.push(message);
9993
10041
  continue;
9994
10042
  }
9995
10043
  if (typeof id !== "string" || id.length === 0) {
9996
10044
  if (!sawPersistedRow && isSyntheticPrefixHead(message))
9997
10045
  continue;
9998
- liveOrderError = `live message at index ${index} has no stable id outside the synthetic head`;
9999
- break;
10046
+ unplaced.push(message);
10047
+ continue;
10000
10048
  }
10001
10049
  sawPersistedRow = true;
10002
10050
  const position = sourcePosition.get(id);
@@ -10013,44 +10061,31 @@ function trimToPreparedPrefix(options, prepared) {
10013
10061
  firstLiveId = id;
10014
10062
  }
10015
10063
  lastSourcePosition = position;
10064
+ placeUnplaced(position <= boundaryPosition);
10016
10065
  if (position > boundaryPosition || position === boundaryPosition && isPartialCompartmentEnd(options.db, options.sessionId, boundary))
10017
10066
  retained.push(message);
10018
10067
  }
10019
- if (liveOrderError)
10020
- status = refuse(liveOrderError);
10021
- else {
10068
+ placeUnplaced(false);
10069
+ if (liveOrderError) {
10070
+ outcome = placeWithoutSourceOrder(liveOrderError);
10071
+ } else {
10022
10072
  if (firstLiveId && firstLivePosition !== undefined && firstLivePosition > boundaryPosition) {
10023
10073
  logBoundaryPrecedesWindow(options, boundary, firstLiveId);
10024
10074
  }
10025
10075
  options.messages.splice(0, options.messages.length, ...retained);
10026
10076
  const preserveBoundary = isPartialCompartmentEnd(options.db, options.sessionId, boundary);
10027
10077
  retireDecisions(sourceOrder.messageIds.slice(0, boundaryPosition + (preserveBoundary ? 0 : 1)));
10028
- status = "applied";
10078
+ outcome = { status: "applied" };
10029
10079
  }
10030
10080
  }
10031
10081
  }
10032
10082
  } else {
10033
- const index = findBoundaryIndex(options.sessionId, options.messages, boundary);
10034
- if (index >= 0) {
10035
- const cut = index + (isPartialCompartmentEnd(options.db, options.sessionId, boundary) ? 0 : 1);
10036
- const unplaced = options.messages.slice(0, cut).filter(isHostRenderedSystemMessage);
10037
- const removed = options.messages.splice(0, cut, ...unplaced);
10038
- retireDecisions(removed.map((message) => message.info.id).filter((id) => typeof id === "string"));
10039
- resetPrefixTrimFallbackState(options.sessionId);
10040
- status = "applied";
10041
- } else {
10042
- const reanchored = reanchorStoredBoundary(options, boundary);
10043
- if (reanchored && reanchored.messageIds[0] !== boundary) {
10044
- status = trimToPreparedPrefix({ ...options, prefixTrimSourceOrder: reanchored }, prepared);
10045
- } else {
10046
- status = classifyAbsentBoundary(options, options.messages, boundary);
10047
- }
10048
- }
10083
+ outcome = trimAtVisibleBoundary(true);
10049
10084
  }
10050
10085
  }
10051
10086
  if (prepared.m0RematerializedThisPass || options.isCacheBustingPass && !prepared.materializationContentionRetryExhausted)
10052
10087
  clearInjectionCache(options.sessionId);
10053
- return status;
10088
+ return outcome;
10054
10089
  }
10055
10090
  function prepareCachedM0M1Replay(db, sessionId) {
10056
10091
  const row = readCachedM0M1Row(db, sessionId);
@@ -10103,15 +10138,16 @@ function injectM0M1(options) {
10103
10138
  const prepared = options.preparedPrefix;
10104
10139
  if (prepared?.preparedMessages) {
10105
10140
  const head = prepared.preparedMessages;
10106
- let prefixTrimStatus = "not-attempted";
10141
+ let prefixTrim = { status: "not-attempted" };
10107
10142
  if (options.messages) {
10108
- prefixTrimStatus = trimToPreparedPrefix(options, prepared);
10143
+ prefixTrim = trimToPreparedPrefix(options, prepared);
10109
10144
  options.messages.unshift(...structuredClone(head));
10110
10145
  }
10111
10146
  return {
10112
10147
  ...prepared,
10113
10148
  prependedMessageCount: options.messages ? head.length : 0,
10114
- prefixTrimStatus
10149
+ prefixTrimStatus: prefixTrim.status,
10150
+ prefixTrimRefusal: prefixTrim.refusal
10115
10151
  };
10116
10152
  }
10117
10153
  hydrateCachedM0Mural(options.db, options.sessionId, options.state);
@@ -10268,9 +10304,9 @@ function injectM0M1(options) {
10268
10304
  contentHash: options.state.cachedM0MuralHash ?? undefined
10269
10305
  } : undefined;
10270
10306
  let prependedMessageCount = prependM0M1Messages(options.sessionId, preparedMessages, m0Text, m1Text, muralForWire);
10271
- let prefixTrimStatus = "not-attempted";
10307
+ let prefixTrim = { status: "not-attempted" };
10272
10308
  if (options.messages) {
10273
- prefixTrimStatus = trimToPreparedPrefix(options, {
10309
+ prefixTrim = trimToPreparedPrefix(options, {
10274
10310
  m0RematerializedThisPass: rematerialized,
10275
10311
  materializationContentionRetryExhausted: contentionExhausted,
10276
10312
  preparedTrimBoundaryId
@@ -10288,7 +10324,8 @@ function injectM0M1(options) {
10288
10324
  m1Text,
10289
10325
  preparedMessages,
10290
10326
  preparedTrimBoundaryId,
10291
- prefixTrimStatus
10327
+ prefixTrimStatus: prefixTrim.status,
10328
+ ...prefixTrim.refusal ? { prefixTrimRefusal: prefixTrim.refusal } : {}
10292
10329
  };
10293
10330
  }
10294
10331
 
@@ -13393,6 +13430,11 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
13393
13430
  const start = chunk.startIndex;
13394
13431
  if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
13395
13432
  return false;
13433
+ const endId = rows[rows.length - 1].messageId;
13434
+ if (!hasRawSessionMessageById2(sessionId, endId)) {
13435
+ sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
13436
+ return false;
13437
+ }
13396
13438
  const saved = db.transaction(() => {
13397
13439
  const prior = getCompartments(db, sessionId);
13398
13440
  const last = prior.at(-1);
@@ -16237,4 +16279,4 @@ ${failure}`;
16237
16279
  }
16238
16280
  }
16239
16281
 
16240
- export { historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, readCoordinateGeneration, rebaseSessionCoordinatesAsync, HiddenCompletionRefusal, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, getCompartmentEvents, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, 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, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, teardownChildSession, runTokenLog, formatRunTokenLog, createChildSessionWithFence, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, 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, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure2, isRecompSkip2, extractRecompReason2, setRecompStarting2, setRecompNote2, setRecompTerminal2, buildRecompDeps2, runManagedRecomp2 };
16282
+ export { historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, readCoordinateGeneration, rebaseSessionCoordinatesAsync, HiddenCompletionRefusal, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, getCompartmentEvents, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, 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, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, teardownChildSession, runTokenLog, formatRunTokenLog, createChildSessionWithFence, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, 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, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure2, isRecompSkip2, extractRecompReason2, setRecompStarting2, setRecompNote2, setRecompTerminal2, buildRecompDeps2, runManagedRecomp2 };
@@ -25,7 +25,7 @@ import {
25
25
  isMessageIndexReconciledThrough,
26
26
  clearIndexedMessages,
27
27
  indexMessagesAfterOrdinal
28
- } from "./server-16kfxcxj.js";
28
+ } from "./server-bzh1fkvd.js";
29
29
  import {
30
30
  Priority,
31
31
  AdmissionClass,
@@ -56,7 +56,7 @@ import {
56
56
  enqueueShadowEmbeddingItems2,
57
57
  getProjectEmbeddingSnapshot2,
58
58
  embedItemsForProject2
59
- } from "./server-4h4acntc.js";
59
+ } from "./server-k3vtc89v.js";
60
60
  import {
61
61
  recordEmbeddingMeasurement
62
62
  } from "./server-2amn2s73.js";
@@ -68,7 +68,7 @@ import {
68
68
  isEmbeddingEnabled,
69
69
  embedText,
70
70
  ensureMemoryEmbeddings2
71
- } from "./server-vjadwb3j.js";
71
+ } from "./server-d5zgah57.js";
72
72
  import {
73
73
  ModuleMemoryAuthorityError2,
74
74
  getMemoriesByProject2,
@@ -81,11 +81,11 @@ import {
81
81
  sanitizeFtsQuery,
82
82
  searchMemoriesFTS,
83
83
  searchMemoriesFTSUnion
84
- } from "./server-sgn61hht.js";
84
+ } from "./server-bjsmb6zs.js";
85
85
  import {
86
86
  MESSAGE_FTS_SESSION_FILTER_SQL,
87
87
  withMessageFtsSessionFilter
88
- } from "./server-kaqs6h31.js";
88
+ } from "./server-52x68mj4.js";
89
89
  import {
90
90
  resolveWorkspaceShareCategories,
91
91
  resolveWorkspaceIdentitySet,
@@ -2265,7 +2265,7 @@ function getMessageSearchStatement(db, sessionFirst) {
2265
2265
  const statements = sessionFirst ? sessionFirstMessageSearchStatements : messageSearchStatements;
2266
2266
  let stmt = statements.get(db);
2267
2267
  if (!stmt) {
2268
- stmt = db.prepare(`SELECT message_ordinal AS messageOrdinal, message_id AS messageId, role, content FROM message_history_fts WHERE ${sessionFirst ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}session_id = ?1 AND message_history_fts MATCH ? ORDER BY bm25(message_history_fts), CAST(message_ordinal AS INTEGER) ASC LIMIT ?`);
2268
+ stmt = db.prepare(`SELECT message_ordinal AS messageOrdinal, message_id AS messageId, role, content FROM message_history_fts WHERE ${sessionFirst ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}session_id = ? AND message_history_fts MATCH ? ORDER BY bm25(message_history_fts), CAST(message_ordinal AS INTEGER) ASC LIMIT ?`);
2269
2269
  statements.set(db, stmt);
2270
2270
  }
2271
2271
  return stmt;
@@ -2274,7 +2274,7 @@ function getMessageSearchStatementWithCutoff(db, sessionFirst) {
2274
2274
  const statements = sessionFirst ? sessionFirstMessageSearchStatementsWithCutoff : messageSearchStatementsWithCutoff;
2275
2275
  let stmt = statements.get(db);
2276
2276
  if (!stmt) {
2277
- stmt = db.prepare(`SELECT message_ordinal AS messageOrdinal, message_id AS messageId, role, content FROM message_history_fts WHERE ${sessionFirst ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}session_id = ?1 AND message_history_fts MATCH ? AND CAST(message_ordinal AS INTEGER) <= ? ORDER BY bm25(message_history_fts), CAST(message_ordinal AS INTEGER) ASC LIMIT ?`);
2277
+ stmt = db.prepare(`SELECT message_ordinal AS messageOrdinal, message_id AS messageId, role, content FROM message_history_fts WHERE ${sessionFirst ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}session_id = ? AND message_history_fts MATCH ? AND CAST(message_ordinal AS INTEGER) <= ? ORDER BY bm25(message_history_fts), CAST(message_ordinal AS INTEGER) ASC LIMIT ?`);
2278
2278
  statements.set(db, stmt);
2279
2279
  }
2280
2280
  return stmt;
@@ -2296,7 +2296,7 @@ function getMessageSearchStatementWithDateRange(db, withCutoff) {
2296
2296
  JOIN message_fts_rowid_map AS map
2297
2297
  ON map.session_id = message_history_fts.session_id
2298
2298
  AND map.fts_rowid = message_history_fts.rowid
2299
- WHERE ${MESSAGE_FTS_SESSION_FILTER_SQL}message_history_fts.session_id = ?1
2299
+ WHERE ${MESSAGE_FTS_SESSION_FILTER_SQL}message_history_fts.session_id = ?
2300
2300
  AND message_history_fts MATCH ?
2301
2301
  AND map.message_time_ms BETWEEN ? AND ?
2302
2302
  ${withCutoff ? "AND CAST(message_history_fts.message_ordinal AS INTEGER) <= ?" : ""}
@@ -2321,7 +2321,7 @@ function getMessageSearchDiagnosticStatement(db, sessionFirst) {
2321
2321
  CAST(message_ordinal AS INTEGER) AS ordinalValue,
2322
2322
  bm25(message_history_fts) AS ftsRank
2323
2323
  FROM message_history_fts
2324
- WHERE ${sessionFirst ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}session_id = ?1 AND message_history_fts MATCH ?
2324
+ WHERE ${sessionFirst ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}session_id = ? AND message_history_fts MATCH ?
2325
2325
  ),
2326
2326
  eligible AS (
2327
2327
  SELECT * FROM matches
@@ -2369,7 +2369,7 @@ function getMessageSearchDiagnosticStatementWithDateRange(db) {
2369
2369
  JOIN message_fts_rowid_map AS map
2370
2370
  ON map.session_id = message_history_fts.session_id
2371
2371
  AND map.fts_rowid = message_history_fts.rowid
2372
- WHERE ${MESSAGE_FTS_SESSION_FILTER_SQL}message_history_fts.session_id = ?1
2372
+ WHERE ${MESSAGE_FTS_SESSION_FILTER_SQL}message_history_fts.session_id = ?
2373
2373
  AND message_history_fts MATCH ?
2374
2374
  AND map.message_time_ms BETWEEN ? AND ?
2375
2375
  ),
@@ -2419,7 +2419,7 @@ function getBatchedFtsCountStatement(db, queryCount, cutoff, dateRange, sessionF
2419
2419
  const dateSql = dateRange === null ? "" : " AND map.message_time_ms BETWEEN ? AND ?";
2420
2420
  statement = db.prepare(Array.from({ length: queryCount }, (_, index) => `SELECT ${index} AS queryIndex, COUNT(*) AS count
2421
2421
  FROM message_history_fts${joinSql}
2422
- WHERE ${sessionFirst || dateRange !== null ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}message_history_fts.session_id = ${index === 0 ? "?1" : "?"}
2422
+ WHERE ${sessionFirst || dateRange !== null ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}message_history_fts.session_id = ?
2423
2423
  AND message_history_fts MATCH ?${dateSql}${cutoffSql}`).join(`
2424
2424
  UNION ALL
2425
2425
  `));
@@ -2435,6 +2435,8 @@ function countSessionFtsMatchesBatch(db, sessionId, ftsQueries, cutoff, dateRang
2435
2435
  return [];
2436
2436
  const bindings = [];
2437
2437
  for (const query of ftsQueries) {
2438
+ if (sessionFirst || dateRange !== null)
2439
+ bindings.push(sessionId);
2438
2440
  bindings.push(sessionId, contentOnlyMessageQuery(query));
2439
2441
  if (dateRange !== null)
2440
2442
  bindings.push(dateRange.from, dateRange.to);
@@ -2699,13 +2701,20 @@ function runMessageFtsQuery(db, sessionId, ftsQuery, fetchLimit, cutoff, dateRan
2699
2701
  let rawRows;
2700
2702
  const matchQuery = contentOnlyMessageQuery(ftsQuery);
2701
2703
  if (dateRange !== null) {
2702
- const bindings = [sessionId, matchQuery, dateRange.from, dateRange.to];
2704
+ const bindings = [
2705
+ sessionId,
2706
+ sessionId,
2707
+ matchQuery,
2708
+ dateRange.from,
2709
+ dateRange.to
2710
+ ];
2703
2711
  if (cutoff !== null)
2704
2712
  bindings.push(cutoff);
2705
2713
  bindings.push(fetchLimit);
2706
2714
  rawRows = getMessageSearchStatementWithDateRange(db, cutoff !== null).all(...bindings);
2707
2715
  } else {
2708
- rawRows = cutoff !== null ? getMessageSearchStatementWithCutoff(db, sessionFirst).all(sessionId, matchQuery, cutoff, fetchLimit) : getMessageSearchStatement(db, sessionFirst).all(sessionId, matchQuery, fetchLimit);
2716
+ const sessionBindings = sessionFirst ? [sessionId, sessionId] : [sessionId];
2717
+ rawRows = cutoff !== null ? getMessageSearchStatementWithCutoff(db, sessionFirst).all(...sessionBindings, matchQuery, cutoff, fetchLimit) : getMessageSearchStatement(db, sessionFirst).all(...sessionBindings, matchQuery, fetchLimit);
2709
2718
  }
2710
2719
  const rows = rawRows.map((row) => row);
2711
2720
  const result = [];
@@ -2720,7 +2729,7 @@ function runMessageFtsQueryWithDiagnostics(args) {
2720
2729
  if (args.ftsQuery.length === 0)
2721
2730
  return { rows: [], suppressedCount: 0 };
2722
2731
  const matchQuery = contentOnlyMessageQuery(args.ftsQuery);
2723
- const rawRows = (args.dateRange === null ? getMessageSearchDiagnosticStatement(args.db, args.sessionFirst).all(args.sessionId, matchQuery, args.cutoff, args.fetchLimit, args.cutoff) : getMessageSearchDiagnosticStatementWithDateRange(args.db).all(args.sessionId, matchQuery, args.dateRange.from, args.dateRange.to, args.cutoff, args.fetchLimit, args.cutoff)).map((row) => row);
2732
+ const rawRows = (args.dateRange === null ? getMessageSearchDiagnosticStatement(args.db, args.sessionFirst).all(...args.sessionFirst ? [args.sessionId, args.sessionId] : [args.sessionId], matchQuery, args.cutoff, args.fetchLimit, args.cutoff) : getMessageSearchDiagnosticStatementWithDateRange(args.db).all(args.sessionId, args.sessionId, matchQuery, args.dateRange.from, args.dateRange.to, args.cutoff, args.fetchLimit, args.cutoff)).map((row) => row);
2724
2733
  const suppressedCount = rawRows[0]?.suppressedCount ?? 0;
2725
2734
  const rows = [];
2726
2735
  for (const row of rawRows) {
@@ -2754,7 +2763,7 @@ function getBatchedMessageSearchStatement(db, queryCount, cutoff, dateRange, ses
2754
2763
  message_history_fts.content AS content,
2755
2764
  bm25(message_history_fts) AS ftsRank
2756
2765
  FROM message_history_fts${joinSql}
2757
- WHERE ${sessionFirst || dateRange !== null ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}message_history_fts.session_id = ${index === 0 ? "?1" : "?"}
2766
+ WHERE ${sessionFirst || dateRange !== null ? MESSAGE_FTS_SESSION_FILTER_SQL : ""}message_history_fts.session_id = ?
2758
2767
  AND message_history_fts MATCH ?${dateSql}${cutoffSql}
2759
2768
  ORDER BY ftsRank
2760
2769
  LIMIT ?
@@ -2772,6 +2781,8 @@ function runMessageFtsQueriesBatch(db, sessionId, ftsQueries, fetchLimit, cutoff
2772
2781
  return [];
2773
2782
  const bindings = [];
2774
2783
  for (const query of ftsQueries) {
2784
+ if (sessionFirst || dateRange !== null)
2785
+ bindings.push(sessionId);
2775
2786
  bindings.push(sessionId, contentOnlyMessageQuery(query));
2776
2787
  if (dateRange !== null)
2777
2788
  bindings.push(dateRange.from, dateRange.to);
@@ -2573,17 +2573,21 @@ async function embedItemsForProject2(projectIdentity, items, signal, db, session
2573
2573
  }
2574
2574
  return { vectors, modelId, generation };
2575
2575
  }
2576
- async function embedItemsWindowBounded(projectIdentity, items, signal, db) {
2576
+ async function embedItemsWindowBounded2(projectIdentity, items, signal, db, sessionId = projectIdentity, options = {}) {
2577
2577
  if (items.length <= MAX_WINDOWS_PER_EMBED_CALL) {
2578
- return embedItemsForProject2(projectIdentity, items, signal, db, projectIdentity);
2578
+ return embedItemsForProject2(projectIdentity, items, signal, db, sessionId);
2579
2579
  }
2580
2580
  const vectors = new Map;
2581
2581
  let modelId = null;
2582
2582
  let generation = null;
2583
2583
  for (let start = 0;start < items.length; start += MAX_WINDOWS_PER_EMBED_CALL) {
2584
- const result = await embedItemsForProject2(projectIdentity, items.slice(start, start + MAX_WINDOWS_PER_EMBED_CALL), signal, db, projectIdentity);
2584
+ const slice = items.slice(start, start + MAX_WINDOWS_PER_EMBED_CALL);
2585
+ const result = await embedItemsForProject2(projectIdentity, slice, signal, db, sessionId);
2585
2586
  if (!result)
2586
2587
  return null;
2588
+ if (options.stopOnIncompleteSlice && slice.some((item) => !result.vectors.has(item.id))) {
2589
+ return null;
2590
+ }
2587
2591
  if (modelId === null) {
2588
2592
  modelId = result.modelId;
2589
2593
  generation = result.generation;
@@ -2796,7 +2800,7 @@ async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates
2796
2800
  let result = null;
2797
2801
  const attemptStart = Date.now();
2798
2802
  try {
2799
- result = await embedItemsWindowBounded(projectIdentity, items, signal, db);
2803
+ result = await embedItemsWindowBounded2(projectIdentity, items, signal, db);
2800
2804
  } catch (error) {
2801
2805
  log2("[magic-context] failed to proactively embed compartment chunks:", error);
2802
2806
  }
@@ -3160,4 +3164,4 @@ function _resetProjectEmbeddingRegistryForTests2() {
3160
3164
  setBootQuietPeriodForTests(null);
3161
3165
  }
3162
3166
 
3163
- export { saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitSha, enforceProjectCap, withQueryEmbeddingDeadline, OpenAICompatibleEmbeddingProvider, describeShadowBackfillWriteRefusal2, listShadowBackfillStalls2, retainProjectEmbedding2, getShadowBackfillStopReason2, markProjectLoadUntrusted2, contentSha2562, drainProjectEmbeddingIdentityMaintenance2, drainStaleEmbeddingIdentitiesForProject2, registerProjectEmbedding2, registerProjectShadowEmbedding2, getShadowEmbeddingMeasurementCohort2, getPrimaryEmbeddingMeasurementCohort2, embedShadowTextForProject2, enqueueShadowEmbeddingItems2, getShadowBackfillRemaining2, flushShadowEmbeddingBacklog2, registerProjectInObservationMode2, unregisterProjectShadowEmbedding2, unregisterProjectEmbedding2, getProjectEmbeddingSnapshot2, installProjectEmbeddingSearchBridge2, getProjectChunkEmbeddingModelId2, getProjectEmbeddingMaxInputTokens2, embedTextForProject2, embedBatchForProject2, embedItemsForProject2, embedUnembeddedMemoriesForProject2, embedUnembeddedMemoriesForProjectOutcome2, drainCommitBacklogForProject2, embedUnembeddedCompartmentChunksForProject2, embedSessionCompartmentChunks2, getEmbeddingCoverageStatus2, getAutoEmbeddingSessionCoverage2, sweepAllRegisteredProjects2, _setTestProviderFactoryForProject2, _resetProjectEmbeddingRegistryForTests2 };
3167
+ export { saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitSha, enforceProjectCap, withQueryEmbeddingDeadline, OpenAICompatibleEmbeddingProvider, describeShadowBackfillWriteRefusal2, listShadowBackfillStalls2, retainProjectEmbedding2, getShadowBackfillStopReason2, markProjectLoadUntrusted2, contentSha2562, drainProjectEmbeddingIdentityMaintenance2, drainStaleEmbeddingIdentitiesForProject2, registerProjectEmbedding2, registerProjectShadowEmbedding2, getShadowEmbeddingMeasurementCohort2, getPrimaryEmbeddingMeasurementCohort2, embedShadowTextForProject2, enqueueShadowEmbeddingItems2, getShadowBackfillRemaining2, flushShadowEmbeddingBacklog2, registerProjectInObservationMode2, unregisterProjectShadowEmbedding2, unregisterProjectEmbedding2, getProjectEmbeddingSnapshot2, installProjectEmbeddingSearchBridge2, getProjectChunkEmbeddingModelId2, getProjectEmbeddingMaxInputTokens2, embedTextForProject2, embedBatchForProject2, embedItemsForProject2, embedItemsWindowBounded2, embedUnembeddedMemoriesForProject2, embedUnembeddedMemoriesForProjectOutcome2, drainCommitBacklogForProject2, embedUnembeddedCompartmentChunksForProject2, embedSessionCompartmentChunks2, getEmbeddingCoverageStatus2, getAutoEmbeddingSessionCoverage2, sweepAllRegisteredProjects2, _setTestProviderFactoryForProject2, _resetProjectEmbeddingRegistryForTests2 };