@cortexkit/opencode-magic-context 0.49.16 → 0.49.18

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 (235) hide show
  1. package/dist/auto-search-worker.js +76 -63
  2. package/dist/chunk-embedding-write-worker.js +11 -11
  3. package/dist/{compaction-marker-candidates-v5c6997n.js → compaction-marker-candidates-n4krhat4.js} +2 -2
  4. package/dist/compaction-marker-candidates-worker.js +2 -2
  5. package/dist/config/schema/magic-context.d.ts +394 -394
  6. package/dist/{conflict-warning-hook-znry4j76.js → conflict-warning-hook-4pmz879v.js} +5 -5
  7. package/dist/{context-3znk23va.js → context-m897gfp9.js} +304 -145
  8. package/dist/{embedding-backfill-q4n8dend.js → embedding-backfill-fmz50tsy.js} +11 -11
  9. package/dist/embedding-worker-process.js +1 -1
  10. package/dist/embedding-worker.js +4 -4
  11. package/dist/features/magic-context/compartment-chunk-embedding.d.ts +1 -1
  12. package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
  13. package/dist/features/magic-context/git-commits/indexer.d.ts.map +1 -1
  14. package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
  15. package/dist/features/magic-context/memory/project-identity-cache.d.ts +2 -0
  16. package/dist/features/magic-context/memory/project-identity-cache.d.ts.map +1 -1
  17. package/dist/features/magic-context/message-index-async.d.ts +1 -1
  18. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  19. package/dist/features/magic-context/message-index.d.ts +5 -0
  20. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  21. package/dist/features/magic-context/search.d.ts +6 -1
  22. package/dist/features/magic-context/search.d.ts.map +1 -1
  23. package/dist/features/magic-context/storage-host-instruction-retention.d.ts +11 -0
  24. package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -0
  25. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  26. package/dist/features/magic-context/storage-meta-shared.d.ts +2 -2
  27. package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
  28. package/dist/features/magic-context/storage-session-tables.d.ts +9 -1
  29. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
  30. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/auto-search-deadline.d.ts +2 -1
  32. package/dist/hooks/magic-context/auto-search-deadline.d.ts.map +1 -1
  33. package/dist/hooks/magic-context/auto-search-hint.d.ts +3 -0
  34. package/dist/hooks/magic-context/auto-search-hint.d.ts.map +1 -1
  35. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/auto-search-worker-client.d.ts +10 -2
  37. package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/cache-busting-signals.d.ts +22 -1
  39. package/dist/hooks/magic-context/cache-busting-signals.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +2 -0
  41. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  42. package/dist/hooks/magic-context/compartment-trigger.d.ts +4 -2
  43. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  44. package/dist/hooks/magic-context/file-token-coverage.d.ts +11 -0
  45. package/dist/hooks/magic-context/file-token-coverage.d.ts.map +1 -0
  46. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +9 -0
  47. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  48. package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
  49. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  50. package/dist/hooks/magic-context/host-served-rows.d.ts +25 -0
  51. package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
  52. package/dist/hooks/magic-context/inject-compartments.d.ts +7 -1
  53. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  54. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
  55. package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
  56. package/dist/hooks/magic-context/lkg-slot.d.ts +1 -1
  57. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  58. package/dist/hooks/magic-context/pass-outcome.d.ts +2 -0
  59. package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
  60. package/dist/hooks/magic-context/protected-tail-boundary.d.ts +2 -1
  61. package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
  62. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  63. package/dist/hooks/magic-context/signed-thinking-hold.d.ts +59 -0
  64. package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -0
  65. package/dist/hooks/magic-context/system-prompt-diagnostics.d.ts +8 -0
  66. package/dist/hooks/magic-context/system-prompt-diagnostics.d.ts.map +1 -0
  67. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  68. package/dist/hooks/magic-context/tag-content-primitives.d.ts.map +1 -1
  69. package/dist/hooks/magic-context/tag-messages.d.ts +6 -1
  70. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  71. package/dist/hooks/magic-context/todo-view.d.ts +2 -2
  72. package/dist/hooks/magic-context/tool-drop-target.d.ts +3 -2
  73. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  74. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +6 -0
  75. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  76. package/dist/hooks/magic-context/transform-context-state.d.ts +19 -0
  77. package/dist/hooks/magic-context/transform-context-state.d.ts.map +1 -1
  78. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +19 -0
  79. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  80. package/dist/hooks/magic-context/transform-stage-logger.d.ts +3 -0
  81. package/dist/hooks/magic-context/transform-stage-logger.d.ts.map +1 -1
  82. package/dist/hooks/magic-context/transform.d.ts +1 -0
  83. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  84. package/dist/{index-9nkg2dzk.js → index-24fezq97.js} +3 -3
  85. package/dist/{index-v9asb16b.js → index-24jbw52d.js} +5 -5
  86. package/dist/{index-a8bvhwqs.js → index-2vxtcb95.js} +32 -3
  87. package/dist/{index-f71thw8j.js → index-4s3t0nd0.js} +1 -1
  88. package/dist/{index-6a6dq53h.js → index-6s5941tm.js} +5 -5
  89. package/dist/{index-fkx2qnvw.js → index-6x57ar45.js} +2 -2
  90. package/dist/{index-ek1yxvvz.js → index-936py2wm.js} +361 -70
  91. package/dist/{index-dqe8pq4x.js → index-a6mc0v4d.js} +6 -3
  92. package/dist/{index-hehkf6zm.js → index-b5vqckbw.js} +12 -6
  93. package/dist/{v2/server-wafzvyhg.js → index-beht37jy.js} +8 -0
  94. package/dist/{index-7b2cfmaz.js → index-bjcnntmz.js} +2 -2
  95. package/dist/{index-hqkczed7.js → index-c5pytzne.js} +22 -2
  96. package/dist/{index-nd7m2a5a.js → index-cf74k5ak.js} +27 -5
  97. package/dist/{index-kn4t1haw.js → index-e4xv8890.js} +531 -253
  98. package/dist/{index-cj9g0j7a.js → index-fgncb0ng.js} +7 -7
  99. package/dist/{index-5mwk1nek.js → index-jn12fvvh.js} +1 -1
  100. package/dist/{index-n6m03s3n.js → index-ke416mdc.js} +1 -1
  101. package/dist/{index-mtw9e71a.js → index-kq82mtg0.js} +2 -2
  102. package/dist/{index-n78avt2p.js → index-n37sebck.js} +1 -1
  103. package/dist/{index-wk0n1cgt.js → index-qn7xstt2.js} +2 -2
  104. package/dist/{index-v63beg1z.js → index-r4nkrs05.js} +3 -3
  105. package/dist/{index-j6zw70pf.js → index-rmwykbbb.js} +60 -21
  106. package/dist/{index-saews2s3.js → index-rr2bb45z.js} +1 -1
  107. package/dist/{index-ayym1x7f.js → index-s1ex9y6p.js} +195 -748
  108. package/dist/{index-7pa32z07.js → index-s734jcsr.js} +1 -1
  109. package/dist/{index-b17m64g9.js → index-s74zqahq.js} +1 -1
  110. package/dist/{index-4qfy7v57.js → index-s7j8tvhv.js} +31 -20
  111. package/dist/{index-wv9n2zcq.js → index-v8awdgvd.js} +4 -4
  112. package/dist/{index-p4vde22c.js → index-x4njr8df.js} +965 -77
  113. package/dist/{index-qrahzcqv.js → index-ze7mvk54.js} +10 -7
  114. package/dist/index.js +39 -39
  115. package/dist/{message-fts-rowid-map-yvx5a9jw.js → message-fts-rowid-map-17s0dfn4.js} +5 -3
  116. package/dist/{message-index-t4pz7akd.js → message-index-66jv6fh4.js} +13 -13
  117. package/dist/{message-index-bounded-6th8djy9.js → message-index-bounded-n1frdn85.js} +17 -17
  118. package/dist/{message-time-backfill-8egzkd3z.js → message-time-backfill-73mmm76q.js} +1 -1
  119. package/dist/migration-worker.js +8 -8
  120. package/dist/plugin/dream-timer.d.ts +11 -0
  121. package/dist/plugin/dream-timer.d.ts.map +1 -1
  122. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  123. package/dist/{project-embedding-registry-2dea0a77.js → project-embedding-registry-z74mhqkf.js} +10 -10
  124. package/dist/raw-ordinal-warmup-worker.js +10 -10
  125. package/dist/{read-session-chunk-4pwqxm5a.js → read-session-chunk-v06g3vka.js} +7 -7
  126. package/dist/{read-session-raw-5ar8se5v.js → read-session-raw-rsc8c7qy.js} +2 -2
  127. package/dist/{recomp-orchestrator-tjcaj5x7.js → recomp-orchestrator-ghpk2dtq.js} +24 -24
  128. package/dist/{search-archive-02jws7hw.js → search-archive-4d53y23e.js} +8 -8
  129. package/dist/{search-rb01n29x.js → search-nkf271d4.js} +20 -20
  130. package/dist/{send-session-notification-2x9edkrp.js → send-session-notification-6ve0e8p4.js} +4 -4
  131. package/dist/shared/historian-cache.d.ts +8 -0
  132. package/dist/shared/historian-cache.d.ts.map +1 -0
  133. package/dist/shared/model-suggestion-retry.d.ts +2 -0
  134. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  135. package/dist/shared/rpc-discovery-cleanup.d.ts +3 -0
  136. package/dist/shared/rpc-discovery-cleanup.d.ts.map +1 -0
  137. package/dist/shared/rpc-server.d.ts +2 -0
  138. package/dist/shared/rpc-server.d.ts.map +1 -1
  139. package/dist/shared/search-text.d.ts +8 -0
  140. package/dist/shared/search-text.d.ts.map +1 -0
  141. package/dist/shared/sqlite.d.ts +4 -2
  142. package/dist/shared/sqlite.d.ts.map +1 -1
  143. package/dist/shared/storage-file-mutex.d.ts.map +1 -1
  144. package/dist/shared/subagent-runner.d.ts +2 -0
  145. package/dist/shared/subagent-runner.d.ts.map +1 -1
  146. package/dist/shared/system-directive.d.ts +2 -0
  147. package/dist/shared/system-directive.d.ts.map +1 -1
  148. package/dist/{sqlite-4pqyynrs.js → sqlite-zf72c52d.js} +1 -1
  149. package/dist/{storage-memory-j3v3hc83.js → storage-memory-y3qmy00r.js} +2 -2
  150. package/dist/{storage-tags-4z1w27xa.js → storage-tags-r7k9tjcv.js} +8 -4
  151. package/dist/{transform-postprocess-phase-xaw5c3xp.js → transform-postprocess-phase-zpgav0h7.js} +24 -24
  152. package/dist/v2/auto-search-worker.js +76 -63
  153. package/dist/v2/chunk-embedding-write-worker.js +11 -11
  154. package/dist/v2/{compaction-marker-candidates-1vqwr3s5.js → compaction-marker-candidates-ebx3388k.js} +2 -2
  155. package/dist/v2/compaction-marker-candidates-worker.js +2 -2
  156. package/dist/v2/{context-acw1nhv8.js → context-f2xh7ba4.js} +1171 -448
  157. package/dist/v2/embedding-backfill-7c7yr69y.js +23 -0
  158. package/dist/v2/embedding-worker-process.js +1 -1
  159. package/dist/v2/embedding-worker.js +4 -4
  160. package/dist/v2/fold/native-replay.d.ts +11 -2
  161. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  162. package/dist/v2/fold/policy.d.ts.map +1 -1
  163. package/dist/v2/fold/restore.d.ts.map +1 -1
  164. package/dist/v2/hooks/context.d.ts.map +1 -1
  165. package/dist/v2/hooks/hidden-child.d.ts +8 -0
  166. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  167. package/dist/v2/hooks/payload.d.ts.map +1 -1
  168. package/dist/v2/hooks/types.d.ts +17 -0
  169. package/dist/v2/hooks/types.d.ts.map +1 -1
  170. package/dist/v2/{message-fts-rowid-map-8vf0v7cr.js → message-fts-rowid-map-wfx67gfd.js} +5 -3
  171. package/dist/v2/{message-index-e6qzw477.js → message-index-48f7hw7a.js} +13 -13
  172. package/dist/v2/{message-index-bounded-dsrf49y7.js → message-index-bounded-w3hfm29z.js} +17 -17
  173. package/dist/v2/{message-time-backfill-q5pgxf0d.js → message-time-backfill-04t0km1z.js} +1 -1
  174. package/dist/v2/migration-worker.js +8 -8
  175. package/dist/v2/{project-embedding-registry-rek75aqw.js → project-embedding-registry-gnkj56xp.js} +10 -10
  176. package/dist/v2/raw-ordinal-warmup-worker.js +10 -10
  177. package/dist/v2/{read-session-chunk-7bpygfv2.js → read-session-chunk-zpgmxwte.js} +7 -7
  178. package/dist/v2/{read-session-raw-pw2n1qgc.js → read-session-raw-yaegtjzh.js} +2 -2
  179. package/dist/v2/{recomp-orchestrator-hzpgg06e.js → recomp-orchestrator-4vfxej9t.js} +24 -24
  180. package/dist/v2/{search-archive-fn4wy8sx.js → search-archive-vv48s2aa.js} +8 -8
  181. package/dist/v2/{search-sf2vg5pk.js → search-kza414f0.js} +20 -20
  182. package/dist/v2/{send-session-notification-hmr7q0nt.js → send-session-notification-3pxn658x.js} +4 -4
  183. package/dist/v2/{server-n5q841qn.js → server-1nyybqan.js} +31 -20
  184. package/dist/v2/{server-785mb90s.js → server-1wy7b9de.js} +6 -3
  185. package/dist/v2/{server-0mzjjw3s.js → server-27gq4mfz.js} +27 -5
  186. package/dist/v2/{server-g59aatsz.js → server-2ehj0bw7.js} +965 -77
  187. package/dist/v2/{server-kqpawe1a.js → server-46neh5fa.js} +12 -6
  188. package/dist/v2/{server-rrqpvwqd.js → server-6tmj0s7j.js} +2 -2
  189. package/dist/v2/{server-kr2kc9dz.js → server-8by8qfec.js} +10 -7
  190. package/dist/v2/{server-r9gjxcte.js → server-a2eqhkxr.js} +7 -7
  191. package/dist/v2/{server-vbe4se57.js → server-a9xqj88f.js} +1 -1
  192. package/dist/{index-wafzvyhg.js → v2/server-beht37jy.js} +8 -0
  193. package/dist/v2/{server-6fyp0v67.js → server-bfpda1tb.js} +195 -749
  194. package/dist/v2/{server-05xjtq6c.js → server-d04vrx0j.js} +1 -1
  195. package/dist/v2/{server-zs8d0s3b.js → server-g3qma5c0.js} +1 -1
  196. package/dist/v2/{server-00hx04yn.js → server-gpvay0xz.js} +2 -2
  197. package/dist/v2/{server-gha9x4qq.js → server-h1v0pyxb.js} +2 -2
  198. package/dist/v2/{server-hgg55hde.js → server-hy3d3vsx.js} +1 -1
  199. package/dist/v2/{server-vgpab6rd.js → server-my7k4eds.js} +4 -4
  200. package/dist/v2/{server-d8tj10db.js → server-n1prf1g6.js} +1 -1
  201. package/dist/v2/{server-n78avt2p.js → server-n37sebck.js} +1 -1
  202. package/dist/v2/{server-y5pznjt9.js → server-nj659894.js} +5 -5
  203. package/dist/v2/{server-zyw55ygv.js → server-qv7f0hhe.js} +5 -5
  204. package/dist/v2/{server-e3ftpk7v.js → server-rmygf5pn.js} +32 -3
  205. package/dist/v2/{server-0ppsweh6.js → server-tgnbmwah.js} +22 -2
  206. package/dist/v2/{server-1hcbw661.js → server-xhab8jx8.js} +60 -21
  207. package/dist/v2/{server-6714jebr.js → server-xj136kt8.js} +1 -1
  208. package/dist/v2/{server-aavz8pm6.js → server-zzkj2fch.js} +3 -3
  209. package/dist/v2/server.js +4 -4
  210. package/dist/v2/{sqlite-4pqyynrs.js → sqlite-zf72c52d.js} +1 -1
  211. package/dist/v2/{storage-memory-j3v3hc83.js → storage-memory-y3qmy00r.js} +2 -2
  212. package/dist/v2/{storage-tags-hkwtbp3g.js → storage-tags-3wdb8zph.js} +8 -4
  213. package/dist/v2/store-reader.d.ts +8 -0
  214. package/dist/v2/store-reader.d.ts.map +1 -1
  215. package/dist/v2/{wrapup-orchestrator-x4xj1782.js → wrapup-orchestrator-psqz7yh0.js} +24 -24
  216. package/dist/wrapup-orchestrator-s9zc5b00.js +48 -0
  217. package/package.json +1 -1
  218. package/src/config/latch-permanence-guard.test.ts +4 -0
  219. package/src/shared/historian-cache.test.ts +69 -0
  220. package/src/shared/historian-cache.ts +55 -0
  221. package/src/shared/model-suggestion-retry.ts +2 -0
  222. package/src/shared/rpc-discovery-cleanup.test.ts +57 -0
  223. package/src/shared/rpc-discovery-cleanup.ts +57 -0
  224. package/src/shared/rpc-server.ts +36 -13
  225. package/src/shared/search-text.test.ts +47 -0
  226. package/src/shared/search-text.ts +63 -0
  227. package/src/shared/sqlite.test.ts +56 -0
  228. package/src/shared/sqlite.ts +51 -2
  229. package/src/shared/storage-file-mutex-review.test.ts +22 -2
  230. package/src/shared/storage-file-mutex.ts +11 -1
  231. package/src/shared/subagent-runner.ts +2 -0
  232. package/src/shared/system-directive.ts +19 -1
  233. package/src/shared/tag-transcript.ts +12 -4
  234. package/dist/v2/embedding-backfill-jyd6492b.js +0 -23
  235. package/dist/wrapup-orchestrator-vj2tbp22.js +0 -48
@@ -1,18 +1,26 @@
1
1
  import {
2
2
  getHarness2
3
3
  } from "./server-pavzsdc6.js";
4
+ import {
5
+ getMagicContextStorageDir
6
+ } from "./server-f2xf5gcb.js";
7
+ import {
8
+ isPidAlive,
9
+ readProcessStartTime
10
+ } from "./server-da07v4xp.js";
4
11
  import {
5
12
  removeSystemReminders,
13
+ removeNestedBlocks,
6
14
  hasMeaningfulUserText2,
7
15
  extractTexts2
8
- } from "./server-0ppsweh6.js";
9
- import {
10
- getMagicContextStorageDir
11
- } from "./server-f2xf5gcb.js";
16
+ } from "./server-tgnbmwah.js";
12
17
  import {
18
+ Database2,
19
+ getSqliteDatabasePath2,
20
+ prepareCachedStatement2,
13
21
  withSqliteBackgroundWriter2,
14
22
  withoutSqliteTransformPass2
15
- } from "./server-wafzvyhg.js";
23
+ } from "./server-beht37jy.js";
16
24
  import {
17
25
  TAG_TOMBSTONE_OWNER_PREFIX,
18
26
  tagTombstoneOwnerRange,
@@ -21,22 +29,26 @@ import {
21
29
  tagIdentityRevisionKey,
22
30
  deleteTagIdentityRevisions
23
31
  } from "./server-pwv4ezb0.js";
32
+ import {
33
+ resolveOpenCodeDbPath,
34
+ assertOpenCodeStoreGeneration
35
+ } from "./server-2ra6pwf3.js";
24
36
  import {
25
37
  cleanUserText2
26
- } from "./server-1hcbw661.js";
38
+ } from "./server-xhab8jx8.js";
27
39
  import {
28
40
  recordMessageFtsRowid2,
29
41
  recordIndexedMessageTime2,
30
42
  messageFtsOrdinalRangeIsMapped2,
43
+ getMessageFtsRowidMapBackfillProgress2,
31
44
  deleteUnmappedMessageFtsRows2
32
- } from "./server-785mb90s.js";
33
- import {
34
- isPidAlive,
35
- readProcessStartTime
36
- } from "./server-da07v4xp.js";
45
+ } from "./server-1wy7b9de.js";
37
46
  import {
38
47
  deleteChunkEmbedBackoffForSession
39
- } from "./server-kqpawe1a.js";
48
+ } from "./server-46neh5fa.js";
49
+ import {
50
+ sameProjectDirectory
51
+ } from "./server-knvkbfvh.js";
40
52
  import {
41
53
  closeQuietly
42
54
  } from "./server-8ajstryz.js";
@@ -120,11 +132,11 @@ function clearCompressionDepthRange(db, sessionId, startOrdinal, endOrdinal) {
120
132
  }
121
133
 
122
134
  // src/features/magic-context/message-index.ts
123
- import { createHash as createHash3 } from "node:crypto";
135
+ import { createHash as createHash4 } from "node:crypto";
124
136
 
125
137
  // src/hooks/magic-context/lkg-recovery-fence.ts
126
138
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
127
- import { lstatSync, readdirSync as readdirSync2, readFileSync as readFileSync2, rmSync as rmSync2 } from "node:fs";
139
+ import { lstatSync, readdirSync as readdirSync2, readFileSync as readFileSync2, rmdirSync, rmSync as rmSync2 } from "node:fs";
128
140
  import { basename, dirname, join as join2 } from "node:path";
129
141
 
130
142
  // src/shared/storage-file-mutex.ts
@@ -169,7 +181,16 @@ function withStorageFileMutex(directory, work, timeoutMs = 1000) {
169
181
  const birth = processBirth(process.pid);
170
182
  const ticket = { choosing: true, number: 0, birth, checksum: "" };
171
183
  const encodedTicket = () => JSON.stringify({ ...ticket, checksum: ticketChecksum(name, ticket) });
172
- writeStorageFileSync(ownPath, encodedTicket(), { flag: "wx", forcePrivate: true });
184
+ for (let attempt = 0;; attempt++) {
185
+ try {
186
+ writeStorageFileSync(ownPath, encodedTicket(), { flag: "wx", forcePrivate: true });
187
+ break;
188
+ } catch (error) {
189
+ if (error.code !== "ENOENT" || attempt >= 2)
190
+ throw error;
191
+ ensurePrivateStorageDirectorySync(directory);
192
+ }
193
+ }
173
194
  const deadline = performance.now() + timeoutMs;
174
195
  const peers = () => {
175
196
  const found = [];
@@ -507,15 +528,776 @@ function commitLkgWithRecoveryFence(args) {
507
528
  function clearLkgRecoveryFence(sessionId, remove, shouldClear) {
508
529
  if (!durableFencesSupported())
509
530
  return remove?.();
510
- return locked(sessionId, () => {
511
- const result = remove?.();
512
- if (shouldClear && !shouldClear(result))
513
- return result;
514
- rmSync2(lkgRecoveryFencePath(sessionId), { force: true });
515
- syncStorageDirectorySync(dirname(lkgRecoveryFencePath(sessionId)));
531
+ const path = lkgRecoveryFencePath(sessionId);
532
+ const missing = (file) => {
533
+ try {
534
+ lstatSync(file);
535
+ return false;
536
+ } catch (error) {
537
+ return error.code === "ENOENT";
538
+ }
539
+ };
540
+ if (!remove && !shouldClear && missing(path) && missing(`${path}.locks`)) {
516
541
  clearLkgFenceProcessState(sessionId);
542
+ return;
543
+ }
544
+ try {
545
+ return locked(sessionId, () => {
546
+ const result = remove?.();
547
+ if (shouldClear && !shouldClear(result))
548
+ return result;
549
+ rmSync2(lkgRecoveryFencePath(sessionId), { force: true });
550
+ syncStorageDirectorySync(dirname(lkgRecoveryFencePath(sessionId)));
551
+ clearLkgFenceProcessState(sessionId);
552
+ return result;
553
+ });
554
+ } finally {
555
+ try {
556
+ rmdirSync(`${path}.locks`);
557
+ } catch {}
558
+ }
559
+ }
560
+
561
+ // src/shared/search-text.ts
562
+ function removeTaskNotifications(text) {
563
+ return removeNestedBlocks(text, ["task", "task_cohort"]);
564
+ }
565
+ function cleanSearchText(text) {
566
+ return removeNestedBlocks(text, ["system-reminder", "task", "task_cohort"]).replace(/\s+/g, " ").trim();
567
+ }
568
+ var QUERY_STOP_WORDS = new Set("a an and are as at be been by can could did do does for from how i in is it me my of on or our please should that the their them there these they this to us was we were what when where which who why will with would you your".split(" "));
569
+ function terms(text) {
570
+ return [
571
+ ...new Set((text.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []).filter((term) => !QUERY_STOP_WORDS.has(term)))
572
+ ];
573
+ }
574
+ function keywordRelevance(query, content) {
575
+ const needles = terms(query);
576
+ if (needles.length === 0)
577
+ return 0;
578
+ const words = new Set(terms(cleanSearchText(content)));
579
+ return 0.8 * needles.filter((term) => words.has(term)).length / needles.length;
580
+ }
581
+ function matchedSearchSnippet(content, query, cap = 220) {
582
+ const text = cleanSearchText(content);
583
+ const needles = new Set(terms(query));
584
+ const matches = [...text.matchAll(/[\p{L}\p{N}_]+/gu)].filter((match) => needles.has(match[0].toLowerCase()));
585
+ if (matches.length === 0)
586
+ return "";
587
+ let bestStart = matches[0].index;
588
+ let bestCoverage = -1;
589
+ for (const match of matches) {
590
+ const start = Math.max(0, match.index - Math.floor(cap / 5));
591
+ const coverage = keywordRelevance(query, text.slice(start, start + cap));
592
+ if (coverage > bestCoverage) {
593
+ bestStart = start;
594
+ bestCoverage = coverage;
595
+ }
596
+ }
597
+ if (bestStart > 0) {
598
+ const boundary = text.indexOf(" ", bestStart);
599
+ if (boundary >= 0 && boundary < matches[matches.length - 1].index)
600
+ bestStart = boundary + 1;
601
+ }
602
+ const passage = text.slice(bestStart, bestStart + cap).trim();
603
+ return `${bestStart > 0 ? "…" : ""}${passage}${bestStart + cap < text.length ? "…" : ""}`;
604
+ }
605
+
606
+ // src/v2/store-reader.ts
607
+ import { createHash as createHash3 } from "node:crypto";
608
+ import { statSync } from "node:fs";
609
+ import { hostname } from "node:os";
610
+ import { resolve } from "node:path";
611
+ function gaDatabasePath(dataHome, channel = "latest", env = process.env) {
612
+ return resolveOpenCodeDbPath("v2", { dataHome, channel, env }).path;
613
+ }
614
+ var RAW_MESSAGE_TYPES = [
615
+ "user",
616
+ "synthetic",
617
+ "assistant",
618
+ "skill",
619
+ "shell",
620
+ "system"
621
+ ];
622
+ var RAW_MESSAGE_TYPE_PARAMETERS = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
623
+ var V2_MESSAGE_PAGE_SQL = `WITH bounds AS (
624
+ SELECT
625
+ CASE WHEN ? = 0 THEN -1 ELSE COALESCE((
626
+ SELECT seq FROM session_message
627
+ WHERE session_id = ? AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
628
+ ORDER BY seq ASC LIMIT 1 OFFSET ?
629
+ ), (SELECT MAX(seq) FROM session_message WHERE session_id = ?), -1) END AS after_seq,
630
+ COALESCE((
631
+ SELECT seq FROM session_message
632
+ WHERE session_id = ? AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
633
+ ORDER BY seq ASC LIMIT 1 OFFSET ?
634
+ ), ?) AS watermark_seq
635
+ )
636
+ SELECT id, session_id, type, seq, time_created, data FROM session_message, bounds
637
+ WHERE session_id = ?
638
+ AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
639
+ AND seq > bounds.after_seq
640
+ AND seq <= bounds.watermark_seq
641
+ ORDER BY seq ASC LIMIT ?`;
642
+ var V2_STORE_READER_DEBUG_COUNTER_KEY = "magic-context.v2.store-reader-debug";
643
+ var debugSymbol = Symbol.for(V2_STORE_READER_DEBUG_COUNTER_KEY);
644
+ var debugGlobal = globalThis;
645
+ var QUERY_STATEMENTS = {
646
+ messagePage: V2_MESSAGE_PAGE_SQL,
647
+ messageCount: "SELECT COUNT(*) AS count FROM session_message WHERE session_id = ? AND type IN (?)",
648
+ storedMessageCount: "SELECT COUNT(*) AS count FROM session_message WHERE session_id = ?",
649
+ messageById: "SELECT id, session_id, type, seq, time_created, data FROM session_message WHERE session_id = ? AND id = ? AND type IN (?) LIMIT 1",
650
+ messageExistsById: "SELECT 1 FROM session_message WHERE id = ? AND session_id = ? AND type IN (?) LIMIT 1",
651
+ messageOrdinalById: `WITH target AS (
652
+ SELECT seq FROM session_message WHERE session_id = ? AND id = ? AND type IN (?) LIMIT 1
653
+ )
654
+ SELECT (SELECT COUNT(*) FROM session_message WHERE session_id = ? AND type IN (?) AND seq <= target.seq) AS ordinal FROM target`,
655
+ messageIdOrdinals: "SELECT id FROM session_message WHERE session_id = ? AND type IN (?) ORDER BY seq ASC LIMIT ? OFFSET ?",
656
+ messageOrdinalPage: "SELECT id, type, seq, json_valid(data) AS valid FROM session_message WHERE session_id = ? AND seq > ? ORDER BY seq ASC, id ASC LIMIT ?",
657
+ rawRowsThrough: "SELECT id, session_id, type, seq, time_created, data FROM session_message WHERE session_id = ? AND type IN (?) AND seq <= ? ORDER BY seq DESC LIMIT ?"
658
+ };
659
+ function debugCounters() {
660
+ const counters = debugGlobal[debugSymbol] ??= {
661
+ decodedRows: 0,
662
+ operations: {},
663
+ openReaders: 0,
664
+ maxOpenReaders: 0,
665
+ readersOpened: 0,
666
+ readersClosed: 0
667
+ };
668
+ counters.openReaders ??= 0;
669
+ counters.maxOpenReaders ??= 0;
670
+ counters.readersOpened ??= 0;
671
+ counters.readersClosed ??= 0;
672
+ return counters;
673
+ }
674
+ function returnedRowCount(value) {
675
+ if (Array.isArray(value))
676
+ return value.length;
677
+ if (value === null || value === undefined || value === false)
678
+ return 0;
679
+ return 1;
680
+ }
681
+ function trackDecodeOperation(name, operation) {
682
+ const counters = debugCounters();
683
+ const before = counters.decodedRows;
684
+ const started = performance.now();
685
+ let value;
686
+ try {
687
+ value = operation();
688
+ return value;
689
+ } finally {
690
+ const decodedRows = counters.decodedRows - before;
691
+ const current = counters.operations[name] ?? {
692
+ calls: 0,
693
+ decodedRows: 0,
694
+ maxDecodedRows: 0
695
+ };
696
+ current.calls += 1;
697
+ current.decodedRows += decodedRows;
698
+ current.maxDecodedRows = Math.max(current.maxDecodedRows, decodedRows);
699
+ counters.operations[name] = current;
700
+ const statement = QUERY_STATEMENTS[name];
701
+ if (counters.captureQueries && statement) {
702
+ (counters.queries ??= []).push({
703
+ operation: name,
704
+ statement,
705
+ rows: returnedRowCount(value),
706
+ elapsedMs: performance.now() - started
707
+ });
708
+ }
709
+ }
710
+ }
711
+ function decode(row) {
712
+ debugCounters().decodedRows += 1;
713
+ const data = JSON.parse(row.data);
714
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
715
+ throw new Error(`Invalid session_message data at seq ${row.seq}`);
716
+ }
717
+ if (row.type === "idle" && !["succeeded", "failed", "interrupted"].includes(String(data.outcome))) {
718
+ throw new Error(`Invalid idle outcome at seq ${row.seq}`);
719
+ }
720
+ return { ...row, data };
721
+ }
722
+ function connect(path, identity = "") {
723
+ const stat = statSync(path);
724
+ const acquiredIdentity = identity || `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
725
+ const db = new Database2(path, { readonly: true, fileMustExist: true });
726
+ try {
727
+ assertOpenCodeStoreGeneration(db, "v2", path);
728
+ } catch (error) {
729
+ db.close();
730
+ throw error;
731
+ }
732
+ const counters = debugCounters();
733
+ counters.openReaders += 1;
734
+ counters.readersOpened += 1;
735
+ counters.maxOpenReaders = Math.max(counters.maxOpenReaders, counters.openReaders);
736
+ return { db, statements: new Map, identity: acquiredIdentity, leases: 0, retired: false };
737
+ }
738
+ function closeConnection(connection) {
739
+ connection.statements.clear();
740
+ try {
741
+ connection.db.close();
742
+ } finally {
743
+ const counters = debugCounters();
744
+ counters.openReaders = Math.max(0, counters.openReaders - 1);
745
+ counters.readersClosed += 1;
746
+ }
747
+ }
748
+
749
+ class V2StoreReaderPool {
750
+ capacity;
751
+ connections = new Map;
752
+ closed = false;
753
+ closing = false;
754
+ holds = 0;
755
+ idleWaiters = new Set;
756
+ constructor(capacity = 4) {
757
+ this.capacity = capacity;
758
+ if (!Number.isSafeInteger(capacity) || capacity < 1)
759
+ throw new Error("Invalid reader capacity");
760
+ }
761
+ open(path) {
762
+ return new V2StoreReader(path, this);
763
+ }
764
+ acquire(path) {
765
+ if (this.closed)
766
+ throw new Error("Store reader pool is closed");
767
+ const key = resolve(path);
768
+ const stat = statSync(key);
769
+ const identity = `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
770
+ let connection = this.connections.get(key);
771
+ if (connection && connection.identity !== identity) {
772
+ this.connections.delete(key);
773
+ this.retire(connection);
774
+ connection = undefined;
775
+ }
776
+ if (!connection)
777
+ connection = connect(key, identity);
778
+ connection.leases++;
779
+ this.connections.delete(key);
780
+ this.connections.set(key, connection);
781
+ while (this.connections.size > this.capacity) {
782
+ const oldest = this.connections.entries().next().value;
783
+ if (!oldest)
784
+ break;
785
+ this.connections.delete(oldest[0]);
786
+ this.retire(oldest[1]);
787
+ }
788
+ return connection;
789
+ }
790
+ release(connection) {
791
+ connection.leases--;
792
+ if (connection.retired && connection.leases === 0)
793
+ closeConnection(connection);
794
+ }
795
+ retire(connection) {
796
+ connection.retired = true;
797
+ if (connection.leases === 0)
798
+ closeConnection(connection);
799
+ }
800
+ hold() {
801
+ if (this.closed || this.closing)
802
+ throw new Error("Store reader pool is closed");
803
+ this.holds++;
804
+ let released = false;
805
+ return () => {
806
+ if (released)
807
+ return;
808
+ released = true;
809
+ this.holds--;
810
+ if (this.holds === 0 && this.closing)
811
+ this.finishClose();
812
+ };
813
+ }
814
+ isClosed() {
815
+ return this.closed;
816
+ }
817
+ holdCount() {
818
+ return this.holds;
819
+ }
820
+ close() {
821
+ if (this.closed || this.closing)
822
+ return;
823
+ this.closing = true;
824
+ if (this.holds === 0)
825
+ this.finishClose();
826
+ }
827
+ async closeWhenIdle(timeoutMs) {
828
+ this.close();
829
+ if (this.closed)
830
+ return true;
831
+ let timer;
832
+ let waiter;
833
+ try {
834
+ await new Promise((resolve) => {
835
+ waiter = resolve;
836
+ this.idleWaiters.add(resolve);
837
+ timer = setTimeout(resolve, Math.max(0, timeoutMs));
838
+ });
839
+ } finally {
840
+ if (timer)
841
+ clearTimeout(timer);
842
+ if (waiter)
843
+ this.idleWaiters.delete(waiter);
844
+ }
845
+ return this.closed;
846
+ }
847
+ finishClose() {
848
+ if (this.closed)
849
+ return;
850
+ this.closed = true;
851
+ for (const connection of this.connections.values())
852
+ this.retire(connection);
853
+ this.connections.clear();
854
+ for (const resolve of this.idleWaiters)
855
+ resolve();
856
+ this.idleWaiters.clear();
857
+ }
858
+ }
859
+
860
+ class V2StoreReader {
861
+ path;
862
+ pool;
863
+ db;
864
+ connection;
865
+ closed = false;
866
+ constructor(path, pool) {
867
+ this.path = path;
868
+ this.pool = pool;
869
+ this.connection = pool ? pool.acquire(path) : connect(path);
870
+ this.db = this.connection.db;
871
+ }
872
+ hostIdentity() {
873
+ return createHash3("sha256").update(JSON.stringify([hostname(), resolve(this.path), this.connection.identity])).digest("hex");
874
+ }
875
+ prepare(sql) {
876
+ if (this.closed)
877
+ throw new Error("Store reader is closed");
878
+ const statements = this.connection.statements;
879
+ let statement = statements.get(sql);
880
+ if (!statement) {
881
+ statement = this.db.prepare(sql);
882
+ if (statements.size >= 128)
883
+ statements.clear();
884
+ statements.set(sql, statement);
885
+ }
886
+ return statement;
887
+ }
888
+ close() {
889
+ if (this.closed)
890
+ return;
891
+ this.closed = true;
892
+ if (this.pool)
893
+ this.pool.release(this.connection);
894
+ else
895
+ closeConnection(this.connection);
896
+ }
897
+ page(sessionID, options = {}) {
898
+ return trackDecodeOperation("page", () => {
899
+ const limit = options.limit ?? 100;
900
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
901
+ throw new Error("Invalid page limit");
902
+ const after = options.after ?? -1;
903
+ if (!Number.isSafeInteger(after))
904
+ throw new Error("Invalid seq cursor");
905
+ if (options.through !== undefined && !Number.isSafeInteger(options.through))
906
+ throw new Error("Invalid seq upper bound");
907
+ const predicates = ["session_id = ?", "seq > ?"];
908
+ const parameters = [sessionID, after];
909
+ if (options.through !== undefined) {
910
+ predicates.push("seq <= ?");
911
+ parameters.push(options.through);
912
+ }
913
+ if (options.type) {
914
+ predicates.push("type = ?");
915
+ parameters.push(options.type);
916
+ }
917
+ const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
918
+ WHERE ${predicates.join(" AND ")}
919
+ ORDER BY seq ASC LIMIT ?`).all(...parameters, limit).map(decode);
920
+ return { rows, cursor: rows.at(-1)?.seq };
921
+ });
922
+ }
923
+ messagePage(sessionID, afterOrdinal, limit, finalWatermark, after) {
924
+ return trackDecodeOperation("messagePage", () => {
925
+ if (!Number.isSafeInteger(afterOrdinal) || afterOrdinal < 0)
926
+ throw new Error("Invalid raw-message ordinal cursor");
927
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
928
+ throw new Error("Invalid page limit");
929
+ if (!Number.isSafeInteger(finalWatermark) || finalWatermark < 0)
930
+ throw new Error("Invalid raw-message watermark");
931
+ const pageSize = Math.min(limit, finalWatermark - afterOrdinal);
932
+ if (pageSize <= 0)
933
+ return [];
934
+ if (after) {
935
+ const anchor = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ?").get(sessionID, after.id);
936
+ if (anchor) {
937
+ return this.prepare(`SELECT id, session_id, type, seq, time_created, data
938
+ FROM session_message WHERE session_id = ? AND seq > ?
939
+ AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS}) ORDER BY seq ASC LIMIT ?`).all(sessionID, anchor.seq, ...RAW_MESSAGE_TYPES, pageSize).map(decode);
940
+ }
941
+ }
942
+ const maximumSeq = Number.MAX_SAFE_INTEGER;
943
+ const rows = this.prepare(V2_MESSAGE_PAGE_SQL).all(afterOrdinal, sessionID, ...RAW_MESSAGE_TYPES, Math.max(0, afterOrdinal - 1), sessionID, sessionID, ...RAW_MESSAGE_TYPES, finalWatermark - 1, maximumSeq, sessionID, ...RAW_MESSAGE_TYPES, pageSize);
944
+ return rows.map(decode);
945
+ });
946
+ }
947
+ messageCount(sessionID) {
948
+ return trackDecodeOperation("messageCount", () => {
949
+ const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
950
+ const row = this.prepare(`SELECT COUNT(*) AS count FROM session_message
951
+ WHERE session_id = ? AND type IN (${rawTypes})`).get(sessionID, ...RAW_MESSAGE_TYPES);
952
+ return typeof row?.count === "number" ? row.count : 0;
953
+ });
954
+ }
955
+ sessionDirectoryPage(afterSessionID, limit) {
956
+ const rows = this.prepare(`SELECT id, COALESCE(directory, '') AS directory FROM session_v2
957
+ WHERE id > ? ORDER BY id ASC LIMIT ?`).all(afterSessionID ?? "", limit);
958
+ return rows.map((row) => ({ sessionId: row.id, directory: row.directory }));
959
+ }
960
+ latestMessageTime(sessionID) {
961
+ const row = this.prepare("SELECT MAX(time_created) AS time FROM session_message WHERE session_id = ?").get(sessionID);
962
+ return row?.time ?? undefined;
963
+ }
964
+ isSubagent(sessionID) {
965
+ const row = this.prepare("SELECT parent_id FROM session_v2 WHERE id = ?").get(sessionID);
966
+ if (!row)
967
+ return null;
968
+ return typeof row.parent_id === "string" && row.parent_id.length > 0;
969
+ }
970
+ sessionIds() {
971
+ return this.prepare("SELECT id FROM session_v2").all().map((row) => row.id);
972
+ }
973
+ latestRootSessionInDirectory(directory) {
974
+ const columns = new Set(this.prepare("PRAGMA table_info(session_v2)").all().map((column) => column.name));
975
+ const archived = columns.has("time_archived") ? " AND time_archived IS NULL" : "";
976
+ const order = columns.has("time_updated") ? "time_updated DESC, id DESC" : "id DESC";
977
+ const page = this.prepare(`SELECT id, COALESCE(directory, '') AS directory FROM session_v2
978
+ WHERE parent_id IS NULL${archived}
979
+ AND COALESCE(json_extract(metadata, '$.magic_context'), '') <> 'hidden-run'
980
+ ORDER BY ${order} LIMIT ? OFFSET ?`);
981
+ const pageSize = 500;
982
+ for (let offset = 0;; offset += pageSize) {
983
+ const rows = page.all(pageSize, offset);
984
+ const match = rows.find((row) => sameProjectDirectory(row.directory, directory));
985
+ if (match)
986
+ return match.id;
987
+ if (rows.length < pageSize)
988
+ return;
989
+ }
990
+ }
991
+ rootSessionActivity(sessionIDs) {
992
+ const roots = new Map;
993
+ for (let offset = 0;offset < sessionIDs.length; offset += 500) {
994
+ const chunk = sessionIDs.slice(offset, offset + 500);
995
+ const rows = this.prepare(`SELECT id, (
996
+ SELECT MAX(time_created) FROM session_message
997
+ WHERE session_id = session_v2.id AND type = 'user'
998
+ ) AS time FROM session_v2
999
+ WHERE parent_id IS NULL
1000
+ AND COALESCE(json_extract(metadata, '$.magic_context'), '') <> 'hidden-run'
1001
+ AND id IN (${chunk.map(() => "?").join(",")})`).all(...chunk);
1002
+ for (const row of rows)
1003
+ if (row.time !== null)
1004
+ roots.set(row.id, row.time);
1005
+ }
1006
+ return roots;
1007
+ }
1008
+ oldestUserMessageTimesSince(sessionIDs, sinceMs) {
1009
+ const result = new Map;
1010
+ for (let offset = 0;offset < sessionIDs.length; offset += 500) {
1011
+ const chunk = sessionIDs.slice(offset, offset + 500);
1012
+ const rows = this.prepare(`SELECT session_id, MIN(time_created) AS time FROM session_message
1013
+ WHERE type = 'user' AND time_created > ? AND session_id IN (${chunk.map(() => "?").join(",")})
1014
+ GROUP BY session_id`).all(sinceMs, ...chunk);
1015
+ for (const row of rows)
1016
+ result.set(row.session_id, row.time);
1017
+ }
517
1018
  return result;
518
- });
1019
+ }
1020
+ retrospectiveUserPage(sessionID, options) {
1021
+ const { boundaryMs, before, limit, maxChars, truncationMarker } = options;
1022
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
1023
+ throw new Error("Invalid page limit");
1024
+ if (!Number.isSafeInteger(maxChars) || maxChars <= truncationMarker.length)
1025
+ throw new Error("Invalid text limit");
1026
+ const direction = before ? "DESC" : "ASC";
1027
+ const head = Math.floor((maxChars - truncationMarker.length) / 2);
1028
+ const tail = maxChars - truncationMarker.length - head;
1029
+ return this.prepare(`WITH users AS (
1030
+ SELECT session_id, seq, time_created, data FROM session_message
1031
+ WHERE session_id = ? AND type = 'user' AND time_created ${before ? "<=" : ">"}
1032
+ ?
1033
+ ORDER BY time_created ${direction}, seq ${direction} LIMIT ?
1034
+ ), texts AS (
1035
+ SELECT session_id, seq, time_created, CASE
1036
+ WHEN json_extract(data, '$.synthetic') = 1 OR json_extract(data, '$.ignored') = 1 THEN ''
1037
+ WHEN json_type(data, '$.text') = 'text' THEN json_extract(data, '$.text')
1038
+ ELSE COALESCE((SELECT group_concat(json_extract(value, '$.text'), char(10))
1039
+ FROM json_each(users.data, '$.content')
1040
+ WHERE json_extract(value, '$.type') IN ('text', 'input_text')
1041
+ AND COALESCE(json_extract(value, '$.synthetic'), 0) <> 1
1042
+ AND COALESCE(json_extract(value, '$.ignored'), 0) <> 1), '') END AS text
1043
+ FROM users WHERE json_valid(data)
1044
+ ) SELECT seq, time_created, CASE WHEN length(text) > ?
1045
+ THEN substr(text, 1, ?) || ? || substr(text, -?) ELSE text END AS text,
1046
+ EXISTS (
1047
+ SELECT 1 FROM session_message assistant_reply
1048
+ WHERE assistant_reply.session_id = texts.session_id
1049
+ AND assistant_reply.type = 'assistant'
1050
+ AND assistant_reply.seq < texts.seq
1051
+ AND EXISTS (
1052
+ SELECT 1 FROM session_message prior_user
1053
+ WHERE prior_user.session_id = texts.session_id
1054
+ AND prior_user.type = 'user'
1055
+ AND prior_user.seq < assistant_reply.seq
1056
+ )
1057
+ ) AS follows_assistant_reply
1058
+ FROM texts ORDER BY time_created ${direction}, seq ${direction}`).all(sessionID, boundaryMs, limit, maxChars, head, truncationMarker, tail);
1059
+ }
1060
+ storedRowsAfter(sessionID, after) {
1061
+ const row = this.prepare("SELECT COUNT(*) AS count FROM session_message WHERE session_id = ? AND seq > ?").get(sessionID, after);
1062
+ return row.count;
1063
+ }
1064
+ storedMessageCount(sessionID) {
1065
+ return trackDecodeOperation("storedMessageCount", () => {
1066
+ const row = this.prepare("SELECT COUNT(*) AS count FROM session_message WHERE session_id = ?").get(sessionID);
1067
+ return typeof row?.count === "number" ? row.count : 0;
1068
+ });
1069
+ }
1070
+ messageById(sessionID, id) {
1071
+ return trackDecodeOperation("messageById", () => {
1072
+ const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
1073
+ const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
1074
+ WHERE session_id = ? AND id = ? AND type IN (${rawTypes}) LIMIT 1`).get(sessionID, id, ...RAW_MESSAGE_TYPES);
1075
+ return row ? decode(row) : null;
1076
+ });
1077
+ }
1078
+ messageTimes(sessionID, ids) {
1079
+ const times = new Map;
1080
+ for (let offset = 0;offset < ids.length; offset += 500) {
1081
+ const batch = ids.slice(offset, offset + 500);
1082
+ const rows = this.prepare(`SELECT id, COALESCE(time_created, json_extract(data, '$.time.created')) AS created,
1083
+ json_extract(data, '$.time.completed') AS completed
1084
+ FROM session_message WHERE session_id = ? AND id IN (${batch.map(() => "?").join(",")})`).all(sessionID, ...batch);
1085
+ for (const row of rows)
1086
+ times.set(row.id, {
1087
+ created: typeof row.created === "number" ? row.created : undefined,
1088
+ completed: typeof row.completed === "number" ? row.completed : undefined
1089
+ });
1090
+ }
1091
+ return times;
1092
+ }
1093
+ messageExistsById(sessionID, id) {
1094
+ return trackDecodeOperation("messageExistsById", () => {
1095
+ const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
1096
+ const row = this.prepare(`SELECT 1 FROM session_message
1097
+ WHERE id = ? AND session_id = ? AND type IN (${rawTypes}) LIMIT 1`).get(id, sessionID, ...RAW_MESSAGE_TYPES);
1098
+ return row != null;
1099
+ });
1100
+ }
1101
+ messageOrdinalById(sessionID, id) {
1102
+ return trackDecodeOperation("messageOrdinalById", () => {
1103
+ const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
1104
+ const row = this.prepare(`WITH target AS (
1105
+ SELECT seq FROM session_message
1106
+ WHERE session_id = ? AND id = ? AND type IN (${rawTypes})
1107
+ LIMIT 1
1108
+ )
1109
+ SELECT (
1110
+ SELECT COUNT(*) FROM session_message
1111
+ WHERE session_id = ?
1112
+ AND type IN (${rawTypes})
1113
+ AND seq <= target.seq
1114
+ ) AS ordinal
1115
+ FROM target`).get(sessionID, id, ...RAW_MESSAGE_TYPES, sessionID, ...RAW_MESSAGE_TYPES);
1116
+ return typeof row?.ordinal === "number" ? row.ordinal : null;
1117
+ });
1118
+ }
1119
+ messageIdOrdinals(sessionID, fromOrdinal, toOrdinal) {
1120
+ return trackDecodeOperation("messageIdOrdinals", () => {
1121
+ if (!Number.isSafeInteger(fromOrdinal) || fromOrdinal < 1)
1122
+ throw new Error("Invalid raw-message range start");
1123
+ if (!Number.isSafeInteger(toOrdinal) || toOrdinal < fromOrdinal)
1124
+ throw new Error("Invalid raw-message range end");
1125
+ const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
1126
+ const rows = this.prepare(`SELECT id FROM session_message
1127
+ WHERE session_id = ? AND type IN (${rawTypes})
1128
+ ORDER BY seq ASC LIMIT ? OFFSET ?`).all(sessionID, ...RAW_MESSAGE_TYPES, toOrdinal - fromOrdinal + 1, fromOrdinal - 1);
1129
+ return new Map(rows.map((row, index) => [row.id, fromOrdinal + index]));
1130
+ });
1131
+ }
1132
+ messageOrdinalPage(sessionID, after, limit) {
1133
+ return trackDecodeOperation("messageOrdinalPage", () => {
1134
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
1135
+ throw new Error("Invalid page limit");
1136
+ const rows = after ? this.prepare(`SELECT id, type, seq, json_valid(data) AS valid
1137
+ FROM session_message
1138
+ WHERE session_id = ? AND (seq > ? OR (seq = ? AND id > ?))
1139
+ ORDER BY seq ASC, id ASC LIMIT ?`).all(sessionID, after.timeCreated, after.timeCreated, after.id, limit) : this.prepare(`SELECT id, type, seq, json_valid(data) AS valid
1140
+ FROM session_message
1141
+ WHERE session_id = ?
1142
+ ORDER BY seq ASC, id ASC LIMIT ?`).all(sessionID, limit);
1143
+ const rawTypes = new Set(RAW_MESSAGE_TYPES);
1144
+ return rows.map((row) => ({
1145
+ id: row.id,
1146
+ timeCreated: row.seq,
1147
+ contributesOrdinal: rawTypes.has(row.type),
1148
+ hasValidInfo: row.valid === 1
1149
+ }));
1150
+ });
1151
+ }
1152
+ range(sessionID, after, through) {
1153
+ return trackDecodeOperation("range", () => through <= after ? [] : this.all(sessionID, after, undefined, through));
1154
+ }
1155
+ spanRowStamps(sessionID, after, through) {
1156
+ if (!Number.isSafeInteger(after) || !Number.isSafeInteger(through))
1157
+ throw new Error("Invalid seq span");
1158
+ const rows = this.prepare(`SELECT seq, id, time_updated AS updated, length(CAST(data AS BLOB)) AS bytes
1159
+ FROM session_message WHERE session_id = ? AND seq > ? AND seq <= ?
1160
+ ORDER BY seq ASC`).all(sessionID, after, through);
1161
+ const stamps = new Map;
1162
+ for (const row of rows)
1163
+ stamps.set(row.seq, `${row.id}\x00${row.updated ?? ""}\x00${row.bytes ?? ""}`);
1164
+ return stamps;
1165
+ }
1166
+ rawRowsThrough(sessionID, throughSeq, limit) {
1167
+ return trackDecodeOperation("rawRowsThrough", () => {
1168
+ if (!Number.isSafeInteger(throughSeq))
1169
+ throw new Error("Invalid seq upper bound");
1170
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
1171
+ throw new Error("Invalid page limit");
1172
+ const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
1173
+ return this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
1174
+ WHERE session_id = ? AND type IN (${rawTypes}) AND seq <= ?
1175
+ ORDER BY seq DESC LIMIT ?`).all(sessionID, ...RAW_MESSAGE_TYPES, throughSeq, limit).map(decode);
1176
+ });
1177
+ }
1178
+ instructionRowsThrough(sessionID, throughSeq) {
1179
+ return trackDecodeOperation("instructionRowsThrough", () => {
1180
+ if (!Number.isSafeInteger(throughSeq))
1181
+ throw new Error("Invalid seq upper bound");
1182
+ return this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
1183
+ WHERE session_id = ? AND type = 'system' AND seq <= ?
1184
+ ORDER BY seq ASC`).all(sessionID, throughSeq).map(decode);
1185
+ });
1186
+ }
1187
+ sequenceForId(sessionID, id) {
1188
+ if (!id)
1189
+ return;
1190
+ const row = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ? LIMIT 1").get(sessionID, id);
1191
+ return typeof row?.seq === "number" ? row.seq : undefined;
1192
+ }
1193
+ syntheticMessageIDs(sessionID) {
1194
+ const rows = this.prepare("SELECT id FROM session_message WHERE session_id = ? AND type = 'synthetic'").all(sessionID);
1195
+ return new Set(rows.map((row) => row.id));
1196
+ }
1197
+ forkOrigin(sessionID) {
1198
+ const columns = new Set(this.prepare("PRAGMA table_info(session_v2)").all().map((column) => column.name));
1199
+ if (!columns.has("fork_session_id") || !columns.has("fork_boundary"))
1200
+ return null;
1201
+ const row = this.prepare("SELECT fork_session_id, fork_boundary FROM session_v2 WHERE id = ?").get(sessionID);
1202
+ if (!row?.fork_session_id || !row.fork_boundary)
1203
+ return null;
1204
+ try {
1205
+ const boundary = JSON.parse(row.fork_boundary);
1206
+ if (boundary.type !== "before" && boundary.type !== "through" || typeof boundary.messageID !== "string" || boundary.messageID.length === 0)
1207
+ return null;
1208
+ return {
1209
+ parentSessionID: row.fork_session_id,
1210
+ boundary: { type: boundary.type, messageID: boundary.messageID }
1211
+ };
1212
+ } catch {
1213
+ return null;
1214
+ }
1215
+ }
1216
+ sessionExists(sessionID) {
1217
+ return this.prepare("SELECT 1 FROM session_v2 WHERE id = ?").get(sessionID) != null;
1218
+ }
1219
+ rowStampsThrough(sessionID, throughSeq) {
1220
+ return this.prepare(`SELECT id, type, seq, time_created FROM session_message
1221
+ WHERE session_id = ? AND seq <= ? ORDER BY seq ASC`).all(sessionID, throughSeq);
1222
+ }
1223
+ latestSequenceForIds(sessionID, ids) {
1224
+ let latest = -1;
1225
+ for (let offset = 0;offset < ids.length; offset += 500) {
1226
+ const chunk = ids.slice(offset, offset + 500);
1227
+ const row = this.prepare(`SELECT MAX(seq) AS seq FROM session_message
1228
+ WHERE session_id = ? AND id IN (${chunk.map(() => "?").join(", ")})`).get(sessionID, ...chunk);
1229
+ if (typeof row?.seq === "number")
1230
+ latest = Math.max(latest, row.seq);
1231
+ }
1232
+ return latest;
1233
+ }
1234
+ compactionByStatus(sessionID, status) {
1235
+ const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
1236
+ WHERE session_id = ? AND type = 'compaction'
1237
+ AND json_extract(data, '$.status') = ?
1238
+ ORDER BY seq DESC LIMIT 1`).get(sessionID, status);
1239
+ return row ? decode(row) : undefined;
1240
+ }
1241
+ latestCompaction(sessionID) {
1242
+ return trackDecodeOperation("latestCompaction", () => this.compactionByStatus(sessionID, "completed"));
1243
+ }
1244
+ latestRunningCompaction(sessionID) {
1245
+ return trackDecodeOperation("latestRunningCompaction", () => this.compactionByStatus(sessionID, "running"));
1246
+ }
1247
+ idleRows(sessionID, after = -1) {
1248
+ return trackDecodeOperation("idleRows", () => this.all(sessionID, after, "idle"));
1249
+ }
1250
+ earliestSequence(sessionID) {
1251
+ const row = this.prepare("SELECT MIN(seq) AS seq FROM session_message WHERE session_id = ?").get(sessionID);
1252
+ return typeof row?.seq === "number" ? row.seq : undefined;
1253
+ }
1254
+ latestSequence(sessionID) {
1255
+ const row = this.prepare("SELECT MAX(seq) AS seq FROM session_message WHERE session_id = ?").get(sessionID);
1256
+ return typeof row?.seq === "number" ? row.seq : -1;
1257
+ }
1258
+ assistantSince(sessionID, afterSeq) {
1259
+ return trackDecodeOperation("assistantSince", () => {
1260
+ const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
1261
+ WHERE session_id = ? AND type = 'assistant' AND seq > ?
1262
+ ORDER BY seq ASC`).all(sessionID, afterSeq);
1263
+ return rows.map((row) => decode(row));
1264
+ });
1265
+ }
1266
+ latestAssistant(sessionID) {
1267
+ return trackDecodeOperation("latestAssistant", () => {
1268
+ const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
1269
+ WHERE session_id = ? AND type = 'assistant'
1270
+ ORDER BY seq DESC LIMIT 1`).get(sessionID);
1271
+ return row ? decode(row) : undefined;
1272
+ });
1273
+ }
1274
+ latestIdle(sessionID) {
1275
+ return trackDecodeOperation("latestIdle", () => {
1276
+ const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
1277
+ WHERE session_id = ? AND type = 'idle'
1278
+ ORDER BY seq DESC LIMIT 1`).get(sessionID);
1279
+ return row ? decode(row) : undefined;
1280
+ });
1281
+ }
1282
+ window(sessionID) {
1283
+ return trackDecodeOperation("window", () => this.db.transaction(() => {
1284
+ const cut = this.latestCompaction(sessionID);
1285
+ return this.all(sessionID, cut ? cut.seq - 1 : -1);
1286
+ }).deferred());
1287
+ }
1288
+ history(sessionID) {
1289
+ return trackDecodeOperation("history", () => this.all(sessionID, -1));
1290
+ }
1291
+ all(sessionID, after, type, through) {
1292
+ const rows = [];
1293
+ for (;; ) {
1294
+ const page = this.page(sessionID, { after, through, type });
1295
+ rows.push(...page.rows);
1296
+ if (page.rows.length < 100 || page.cursor === undefined)
1297
+ return rows;
1298
+ after = page.cursor;
1299
+ }
1300
+ }
519
1301
  }
520
1302
 
521
1303
  // src/features/magic-context/session-activity.ts
@@ -611,6 +1393,22 @@ var SESSION_SCOPED_TABLES = [
611
1393
  { table: "lkg_slots" },
612
1394
  { table: "lkg_slot_chunks" }
613
1395
  ];
1396
+ var cleanupStatements = new WeakMap;
1397
+ function cleanupStatement(db, sql) {
1398
+ let cache = cleanupStatements.get(db);
1399
+ if (!cache) {
1400
+ cache = new Map;
1401
+ cleanupStatements.set(db, cache);
1402
+ }
1403
+ let statement = cache.get(sql);
1404
+ if (!statement) {
1405
+ if (cache.size >= 256)
1406
+ cache.clear();
1407
+ statement = prepareCachedStatement2(db, sql);
1408
+ cache.set(sql, statement);
1409
+ }
1410
+ return statement;
1411
+ }
614
1412
  function deleteSessionScopedRows(db, sessionIds, harness, options = {}) {
615
1413
  if (sessionIds.length === 0)
616
1414
  return 0;
@@ -618,7 +1416,7 @@ function deleteSessionScopedRows(db, sessionIds, harness, options = {}) {
618
1416
  if (options.rustModuleCleanupAcknowledged !== true) {
619
1417
  const placeholders = sessionIds.map(() => "?").join(", ");
620
1418
  const harnessPredicate = harness === undefined ? "" : " AND harness = ?";
621
- const protectedRows = db.prepare(`SELECT session_id
1419
+ const protectedRows = cleanupStatement(db, `SELECT session_id
622
1420
  FROM pending_session_cleanup
623
1421
  WHERE session_id IN (${placeholders})
624
1422
  AND harness LIKE '%:rust'${harnessPredicate}`).all(...sessionIds, ...harness === undefined ? [] : [`${harness}:rust`]);
@@ -630,11 +1428,11 @@ function deleteSessionScopedRows(db, sessionIds, harness, options = {}) {
630
1428
  const placeholders = deletableSessionIds.map(() => "?").join(", ");
631
1429
  const harnessTables = SESSION_SCOPED_TABLES.filter((definition) => definition.harnessScoped);
632
1430
  if (options.preserveTagRevisionTombstones) {
633
- const owners = db.prepare(harnessTables.map((definition) => `SELECT session_id, harness FROM ${definition.table} WHERE session_id IN (${placeholders})${definition.extraPredicate ? ` AND ${definition.extraPredicate}` : ""}`).join(" UNION ")).all(...harnessTables.flatMap(() => deletableSessionIds));
634
- const record = db.prepare("INSERT OR IGNORE INTO schema_migrations_meta (key, value) VALUES (?, ?)");
1431
+ const owners = cleanupStatement(db, harnessTables.map((definition) => `SELECT session_id, harness FROM ${definition.table} WHERE session_id IN (${placeholders})${definition.extraPredicate ? ` AND ${definition.extraPredicate}` : ""}`).join(" UNION ")).all(...harnessTables.flatMap(() => deletableSessionIds));
1432
+ const record = cleanupStatement(db, "INSERT OR IGNORE INTO schema_migrations_meta (key, value) VALUES (?, ?)");
635
1433
  for (const owner of owners)
636
1434
  record.run(tagTombstoneOwnerKey(owner.session_id, owner.harness), owner.harness);
637
- const fallback = db.prepare(`INSERT INTO schema_migrations_meta (key, value)
1435
+ const fallback = cleanupStatement(db, `INSERT INTO schema_migrations_meta (key, value)
638
1436
  SELECT ?, ? WHERE NOT EXISTS (SELECT 1 FROM schema_migrations_meta WHERE key >= ? AND key < ?)`);
639
1437
  for (const id of deletableSessionIds)
640
1438
  fallback.run(tagTombstoneOwnerKey(id, getHarness2()), getHarness2(), ...tagTombstoneOwnerRange(id));
@@ -643,7 +1441,7 @@ function deleteSessionScopedRows(db, sessionIds, harness, options = {}) {
643
1441
  deleteChunkEmbedBackoffForSession(db, sessionId);
644
1442
  for (const definition of SESSION_SCOPED_TABLES) {
645
1443
  if (definition.table === "message_history_fts") {
646
- db.prepare(`DELETE FROM message_history_fts
1444
+ cleanupStatement(db, `DELETE FROM message_history_fts
647
1445
  WHERE rowid IN (
648
1446
  SELECT fts_rowid
649
1447
  FROM message_fts_rowid_map
@@ -658,7 +1456,7 @@ function deleteSessionScopedRows(db, sessionIds, harness, options = {}) {
658
1456
  const bindHarness = harness !== undefined && definition.harnessScoped === true;
659
1457
  if (bindHarness)
660
1458
  predicates.push("harness = ?");
661
- const statement = db.prepare(`DELETE FROM ${definition.table} WHERE ${predicates.join(" AND ")}`);
1459
+ const statement = cleanupStatement(db, `DELETE FROM ${definition.table} WHERE ${predicates.join(" AND ")}`);
662
1460
  if (bindHarness)
663
1461
  statement.run(...deletableSessionIds, harness);
664
1462
  else
@@ -666,9 +1464,9 @@ function deleteSessionScopedRows(db, sessionIds, harness, options = {}) {
666
1464
  }
667
1465
  deleteSessionActivity(db, deletableSessionIds);
668
1466
  if (!options.preserveTagRevisionTombstones) {
669
- const retireOwner = db.prepare(harness === undefined ? "DELETE FROM schema_migrations_meta WHERE key >= ? AND key < ?" : "DELETE FROM schema_migrations_meta WHERE key = ?");
1467
+ const retireOwner = cleanupStatement(db, harness === undefined ? "DELETE FROM schema_migrations_meta WHERE key >= ? AND key < ?" : "DELETE FROM schema_migrations_meta WHERE key = ?");
670
1468
  const survivingRows = harnessTables.map((definition) => `EXISTS (SELECT 1 FROM ${definition.table} WHERE session_id = ?${definition.extraPredicate ? ` AND ${definition.extraPredicate}` : ""})`).join(" OR ");
671
- const retire = db.prepare(`DELETE FROM schema_migrations_meta WHERE key IN (?, ?)
1469
+ const retire = cleanupStatement(db, `DELETE FROM schema_migrations_meta WHERE key IN (?, ?)
672
1470
  AND NOT (${survivingRows})
673
1471
  AND NOT EXISTS (SELECT 1 FROM schema_migrations_meta AS owners WHERE owners.key >= ? AND owners.key < ?)`);
674
1472
  for (const id of deletableSessionIds) {
@@ -679,10 +1477,59 @@ function deleteSessionScopedRows(db, sessionIds, harness, options = {}) {
679
1477
  retire.run(tagIdentityRevisionKey(id), tagRevisionKey(id), ...harnessTables.map(() => id), ...tagTombstoneOwnerRange(id));
680
1478
  }
681
1479
  }
682
- for (const sessionId of deletableSessionIds)
683
- clearLkgRecoveryFence(sessionId);
1480
+ if (!options.deferRecoveryFenceCleanup)
1481
+ for (const sessionId of deletableSessionIds)
1482
+ clearLkgRecoveryFence(sessionId);
684
1483
  return deletableSessionIds.length;
685
1484
  }
1485
+ var SESSION_CLEANUP_SLICE_ROWS = 64;
1486
+ function deleteSessionScopedRowsSlice(db, sessionId, harness) {
1487
+ if (cleanupStatement(db, "SELECT 1 FROM pending_session_cleanup WHERE session_id = ? AND harness = ?").get(sessionId, `${harness}:rust`))
1488
+ return { complete: true, deleted: 0 };
1489
+ cleanupStatement(db, "INSERT OR IGNORE INTO schema_migrations_meta(key,value) VALUES (?,?)").run(tagTombstoneOwnerKey(sessionId, harness), harness);
1490
+ let remaining = SESSION_CLEANUP_SLICE_ROWS;
1491
+ const started = performance.now();
1492
+ remaining -= deleteChunkEmbedBackoffForSession(db, sessionId, remaining);
1493
+ if (remaining <= 0)
1494
+ return { complete: false, deleted: 0 };
1495
+ for (const definition of SESSION_SCOPED_TABLES) {
1496
+ if (definition.table === "message_history_fts") {
1497
+ const rows = cleanupStatement(db, "SELECT fts_rowid AS id FROM message_fts_rowid_map WHERE session_id = ? LIMIT ?").all(sessionId, remaining);
1498
+ const removeFts = cleanupStatement(db, "DELETE FROM message_history_fts WHERE rowid = ?");
1499
+ const removeMap = cleanupStatement(db, "DELETE FROM message_fts_rowid_map WHERE session_id = ? AND fts_rowid = ?");
1500
+ for (const row of rows) {
1501
+ removeFts.run(row.id);
1502
+ removeMap.run(sessionId, row.id);
1503
+ }
1504
+ remaining -= rows.length;
1505
+ if (remaining > 0 && !getMessageFtsRowidMapBackfillProgress2(db).completed)
1506
+ remaining -= cleanupStatement(db, `DELETE FROM message_history_fts WHERE rowid IN (
1507
+ SELECT rowid FROM message_history_fts WHERE session_id = ? LIMIT ?
1508
+ )`).run(sessionId, remaining).changes;
1509
+ } else {
1510
+ const predicates = ["session_id = ?"];
1511
+ if (definition.extraPredicate)
1512
+ predicates.push(definition.extraPredicate);
1513
+ if (definition.harnessScoped)
1514
+ predicates.push("harness = ?");
1515
+ const args = [sessionId, ...definition.harnessScoped ? [harness] : [], remaining];
1516
+ const withoutRowid = definition.table === "temporal_decisions" || definition.table === "session_replay_decisions";
1517
+ const key = withoutRowid ? "message_id" : "rowid";
1518
+ remaining -= cleanupStatement(db, `DELETE FROM ${definition.table}
1519
+ WHERE ${withoutRowid ? "session_id = ? AND " : ""}${key} IN (
1520
+ SELECT ${key} FROM ${definition.table} WHERE ${predicates.join(" AND ")} LIMIT ?
1521
+ )`).run(...withoutRowid ? [sessionId] : [], ...args).changes;
1522
+ }
1523
+ if (remaining <= 0 || performance.now() - started >= 10)
1524
+ return { complete: false, deleted: 0 };
1525
+ }
1526
+ return {
1527
+ complete: true,
1528
+ deleted: deleteSessionScopedRows(db, [sessionId], harness, {
1529
+ deferRecoveryFenceCleanup: true
1530
+ })
1531
+ };
1532
+ }
686
1533
 
687
1534
  // src/features/magic-context/message-index.ts
688
1535
  var MESSAGE_HISTORY_ORPHAN_SWEEP_BATCH_SIZE = 200;
@@ -913,7 +1760,7 @@ function toMessageIndexSource2(message) {
913
1760
  role: message.role,
914
1761
  createdAt: message.createdAt,
915
1762
  sourceVersion: normalizeSourceVersion(message.version),
916
- contentHash: createHash3("sha256").update(content).digest("hex"),
1763
+ contentHash: createHash4("sha256").update(content).digest("hex"),
917
1764
  content
918
1765
  };
919
1766
  }
@@ -1015,10 +1862,10 @@ function getIndexableContent2(role, parts) {
1015
1862
  if (!hasMeaningfulUserText2(parts)) {
1016
1863
  return "";
1017
1864
  }
1018
- return extractTexts2(parts).map(cleanUserText2).map(normalizeIndexText).filter((text) => text.length > 0).join(" / ");
1865
+ return extractTexts2(parts).map(removeTaskNotifications).map(cleanUserText2).map(normalizeIndexText).filter((text) => text.length > 0).join(" / ");
1019
1866
  }
1020
1867
  if (role === "assistant") {
1021
- return extractTexts2(parts).map(removeSystemReminders).map(normalizeIndexText).filter((text) => text.length > 0).join(" / ");
1868
+ return extractTexts2(parts).map(removeTaskNotifications).map(removeSystemReminders).map(normalizeIndexText).filter((text) => text.length > 0).join(" / ");
1022
1869
  }
1023
1870
  return "";
1024
1871
  }
@@ -1153,7 +2000,7 @@ function indexItemsAfterOrdinal(db, sessionId, items, finalWatermark, toSource)
1153
2000
  return inserted;
1154
2001
  }
1155
2002
  function harnessSupportsOpenCodeOrphanSweep(harness) {
1156
- return harness === "opencode";
2003
+ return harness === "opencode" || harness === "opencode2";
1157
2004
  }
1158
2005
  function getMessageHistoryOrphanSweepState(db, harness) {
1159
2006
  return db.prepare("SELECT cursor_session_id, last_swept_at FROM message_history_orphan_sweep WHERE harness = ?").get(harness) ?? {};
@@ -1182,7 +2029,7 @@ function getOpenCodeSessionScopedCandidateSourceSql(harness) {
1182
2029
  UNION
1183
2030
  `);
1184
2031
  }
1185
- function sweepOrphanedOpenCodeMessageIndexesInBackground(db, openReadableOpenCodeDb, options = {}) {
2032
+ function* sweepOrphanedOpenCodeMessageIndexesInBackground(db, openReadableOpenCodeDb, options = {}) {
1186
2033
  const now = options.now ?? Date.now();
1187
2034
  const batchSize = Math.max(1, Math.floor(options.batchSize ?? MESSAGE_HISTORY_ORPHAN_SWEEP_BATCH_SIZE));
1188
2035
  const safetyAgeMs = Math.max(0, options.safetyAgeMs ?? MESSAGE_HISTORY_ORPHAN_SAFETY_AGE_MS);
@@ -1196,15 +2043,6 @@ function sweepOrphanedOpenCodeMessageIndexesInBackground(db, openReadableOpenCod
1196
2043
  }
1197
2044
  if (!harnessSupportsOpenCodeOrphanSweep(harness)) {
1198
2045
  persistMessageHistoryOrphanSweepState(db, cursor, now + unavailableReprobeMs - cooldownMs, harness);
1199
- if (harness === "opencode2") {
1200
- return {
1201
- status: "unavailable",
1202
- scanned: 0,
1203
- deleted: 0,
1204
- cursor,
1205
- reason: "OpenCode 2 keeps its sessions in session_v2, which this sweep does not read"
1206
- };
1207
- }
1208
2046
  return { status: "unavailable", scanned: 0, deleted: 0, cursor };
1209
2047
  }
1210
2048
  let openCodeDb = null;
@@ -1217,7 +2055,27 @@ function sweepOrphanedOpenCodeMessageIndexesInBackground(db, openReadableOpenCod
1217
2055
  persistMessageHistoryOrphanSweepState(db, cursor, now + unavailableReprobeMs - cooldownMs, harness);
1218
2056
  return { status: "source_unavailable", scanned: 0, deleted: 0, cursor };
1219
2057
  }
2058
+ let v2Reader;
1220
2059
  try {
2060
+ let sessionExists;
2061
+ if (harness === "opencode2") {
2062
+ try {
2063
+ const path = getSqliteDatabasePath2(openCodeDb);
2064
+ if (!path)
2065
+ throw new Error("OpenCode 2 source has no durable path");
2066
+ v2Reader = new V2StoreReader(path);
2067
+ const liveIds = new Set(v2Reader.sessionIds());
2068
+ if (liveIds.size === 0)
2069
+ throw new Error("OpenCode 2 source has no sessions");
2070
+ sessionExists = (id) => liveIds.has(id);
2071
+ } catch {
2072
+ persistMessageHistoryOrphanSweepState(db, cursor, now + unavailableReprobeMs - cooldownMs, harness);
2073
+ return { status: "source_unavailable", scanned: 0, deleted: 0, cursor };
2074
+ }
2075
+ } else {
2076
+ const query = openCodeDb.prepare("SELECT 1 FROM session WHERE id = ? LIMIT 1");
2077
+ sessionExists = (id) => !!query.get(id);
2078
+ }
1221
2079
  const cutoff = now - safetyAgeMs;
1222
2080
  const candidateSourceSql = getOpenCodeSessionScopedCandidateSourceSql(harness);
1223
2081
  const candidates = db.prepare(`SELECT session_id
@@ -1232,39 +2090,56 @@ function sweepOrphanedOpenCodeMessageIndexesInBackground(db, openReadableOpenCod
1232
2090
  )
1233
2091
  ORDER BY session_id ASC
1234
2092
  LIMIT ?`).all(cursor, cutoff, batchSize);
1235
- const sessionExists = openCodeDb.prepare("SELECT 1 FROM session WHERE id = ? LIMIT 1");
1236
- const missingSessionIds = candidates.filter((candidate) => !sessionExists.get(candidate.session_id)).map((candidate) => candidate.session_id);
2093
+ const missingSessionIds = candidates.filter((candidate) => !sessionExists(candidate.session_id)).map((candidate) => candidate.session_id);
1237
2094
  const nextCursor = candidates.length < batchSize ? "" : candidates[candidates.length - 1]?.session_id ?? cursor;
1238
2095
  const completedAt = candidates.length < batchSize ? now : null;
1239
- db.exec("BEGIN IMMEDIATE");
1240
- const transactionStartedAt = performance.now();
1241
- let committed = false;
1242
2096
  let deleted = 0;
1243
- try {
1244
- const stillEligible = db.prepare(`SELECT 1
1245
- FROM (${candidateSourceSql}) AS session_candidates
1246
- WHERE session_id = ?
1247
- AND NOT EXISTS (
1248
- SELECT 1
1249
- FROM message_history_index
1250
- WHERE message_history_index.session_id = session_candidates.session_id
1251
- AND message_history_index.harness = '${harness}'
1252
- AND message_history_index.updated_at > ?
1253
- )
1254
- LIMIT 1`);
1255
- const eligibleSessionIds = missingSessionIds.filter((sessionId) => !sessionExists.get(sessionId) && stillEligible.get(sessionId, cutoff));
1256
- deleted = deleteSessionScopedRows(db, eligibleSessionIds, harness);
1257
- persistMessageHistoryOrphanSweepState(db, nextCursor, completedAt, harness);
1258
- db.exec("COMMIT");
1259
- committed = true;
1260
- logSlowWriteTransaction("message_index_orphan_sweep", transactionStartedAt);
1261
- } finally {
1262
- if (!committed) {
2097
+ let slices = 0;
2098
+ const stillEligible = db.prepare(`SELECT 1 WHERE NOT EXISTS (
2099
+ SELECT 1 FROM message_history_index
2100
+ WHERE session_id = ? AND harness = '${harness}' AND updated_at > ?
2101
+ )`);
2102
+ for (const sessionId of missingSessionIds) {
2103
+ let complete = false;
2104
+ do {
2105
+ let removed = 0;
2106
+ db.exec("BEGIN IMMEDIATE");
2107
+ const transactionStartedAt = performance.now();
2108
+ let committed = false;
1263
2109
  try {
1264
- db.exec("ROLLBACK");
1265
- } catch {}
1266
- }
2110
+ const hostStillMissing = v2Reader ? !v2Reader.sessionExists(sessionId) : !sessionExists(sessionId);
2111
+ if (hostStillMissing && stillEligible.get(sessionId, cutoff)) {
2112
+ const slice = deleteSessionScopedRowsSlice(db, sessionId, harness);
2113
+ removed = slice.deleted;
2114
+ complete = slice.complete;
2115
+ } else
2116
+ complete = true;
2117
+ db.exec("COMMIT");
2118
+ committed = true;
2119
+ logSlowWriteTransaction("message_index_orphan_sweep", transactionStartedAt);
2120
+ } finally {
2121
+ if (!committed) {
2122
+ try {
2123
+ db.exec("ROLLBACK");
2124
+ } catch {}
2125
+ }
2126
+ }
2127
+ deleted += removed;
2128
+ if (removed)
2129
+ clearLkgRecoveryFence(sessionId);
2130
+ yield;
2131
+ if (++slices >= Math.max(1, options.maxSlices ?? 512)) {
2132
+ return {
2133
+ status: "swept",
2134
+ scanned: candidates.length,
2135
+ deleted,
2136
+ cursor,
2137
+ partial: true
2138
+ };
2139
+ }
2140
+ } while (!complete);
1267
2141
  }
2142
+ persistMessageHistoryOrphanSweepState(db, nextCursor, completedAt, harness);
1268
2143
  return {
1269
2144
  status: "swept",
1270
2145
  scanned: candidates.length,
@@ -1272,11 +2147,24 @@ function sweepOrphanedOpenCodeMessageIndexesInBackground(db, openReadableOpenCod
1272
2147
  cursor: nextCursor
1273
2148
  };
1274
2149
  } finally {
2150
+ v2Reader?.close();
1275
2151
  closeQuietly(openCodeDb);
1276
2152
  }
1277
2153
  }
1278
- function sweepOrphanedOpenCodeMessageIndexes2(db, openReadableOpenCodeDb, options = {}) {
1279
- return withoutSqliteTransformPass2(() => withSqliteBackgroundWriter2(() => sweepOrphanedOpenCodeMessageIndexesInBackground(db, openReadableOpenCodeDb, options)));
2154
+ async function sweepOrphanedOpenCodeMessageIndexesCooperatively2(db, openSource, options = {}) {
2155
+ return withoutSqliteTransformPass2(() => withSqliteBackgroundWriter2(async () => {
2156
+ const sweep = sweepOrphanedOpenCodeMessageIndexesInBackground(db, openSource, options);
2157
+ try {
2158
+ for (;; ) {
2159
+ const step = sweep.next();
2160
+ if (step.done)
2161
+ return step.value;
2162
+ await new Promise((resolve) => setTimeout(resolve, 0));
2163
+ }
2164
+ } finally {
2165
+ sweep.return({ status: "source_unavailable", scanned: 0, deleted: 0, cursor: "" });
2166
+ }
2167
+ }));
1280
2168
  }
1281
2169
 
1282
- export { BoundedSessionMap, clearCompressionDepth, clearCompressionDepthRange, LkgRecoveryFenceError, clearLkgFenceProcessState, lkgServedArrayDigest, hasCleanLkgRecoveryFence, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, commitLkgWithRecoveryFence, clearLkgRecoveryFence, advanceSessionActivity, backfillSessionActivity, deleteSessionScopedRows, MESSAGE_INDEX_MAX_FTS_BYTES2, messageIndexSkipKey2, toMessageIndexSource2, getMessageIndexSourceIdentity2, isMessageIndexSourceCurrent2, getLastIndexedOrdinal2, getIndexedMessageCorpusSize2, markMessageIndexDirty2, getMessageIndexReconciliationStartOrdinal2, isMessageIndexReconciledThrough2, deleteIndexedMessage2, clearIndexedMessagesInTransaction2, clearIndexedMessages2, getIndexableContent2, indexSingleMessage2, indexMessagesAfterOrdinal2, indexSourcesAfterOrdinal2, sweepOrphanedOpenCodeMessageIndexes2 };
2170
+ export { BoundedSessionMap, clearCompressionDepth, clearCompressionDepthRange, LkgRecoveryFenceError, clearLkgFenceProcessState, lkgServedArrayDigest, hasCleanLkgRecoveryFence, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, commitLkgWithRecoveryFence, clearLkgRecoveryFence, cleanSearchText, keywordRelevance, matchedSearchSnippet, gaDatabasePath, RAW_MESSAGE_TYPES, V2StoreReaderPool, V2StoreReader, advanceSessionActivity, backfillSessionActivity, deleteSessionScopedRows, MESSAGE_INDEX_MAX_FTS_BYTES2, messageIndexSkipKey2, toMessageIndexSource2, getMessageIndexSourceIdentity2, isMessageIndexSourceCurrent2, getLastIndexedOrdinal2, getIndexedMessageCorpusSize2, markMessageIndexDirty2, getMessageIndexReconciliationStartOrdinal2, isMessageIndexReconciledThrough2, deleteIndexedMessage2, clearIndexedMessagesInTransaction2, clearIndexedMessages2, getIndexableContent2, indexSingleMessage2, indexMessagesAfterOrdinal2, indexSourcesAfterOrdinal2, sweepOrphanedOpenCodeMessageIndexesCooperatively2 };