@cortexkit/opencode-magic-context 0.49.15 → 0.49.17

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 +12 -10
  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 +343 -343
  6. package/dist/config/schema/magic-context.d.ts.map +1 -1
  7. package/dist/{conflict-warning-hook-mgq17yr3.js → conflict-warning-hook-4pmz879v.js} +6 -6
  8. package/dist/{context-0m46day0.js → context-yhetp0kn.js} +297 -141
  9. package/dist/embedding-backfill-fmz50tsy.js +24 -0
  10. package/dist/embedding-worker-process.js +1 -1
  11. package/dist/embedding-worker.js +5 -5
  12. package/dist/features/magic-context/compartment-chunk-embedding.d.ts +1 -1
  13. package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
  14. package/dist/features/magic-context/git-commits/indexer.d.ts.map +1 -1
  15. package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
  16. package/dist/features/magic-context/memory/project-identity-cache.d.ts +2 -0
  17. package/dist/features/magic-context/memory/project-identity-cache.d.ts.map +1 -1
  18. package/dist/features/magic-context/message-fts-rowid-map.d.ts +2 -2
  19. package/dist/features/magic-context/message-fts-rowid-map.d.ts.map +1 -1
  20. package/dist/features/magic-context/message-fts-session-filter.d.ts +2 -0
  21. package/dist/features/magic-context/message-fts-session-filter.d.ts.map +1 -1
  22. package/dist/features/magic-context/message-index-async.d.ts +1 -1
  23. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  24. package/dist/features/magic-context/message-index.d.ts +5 -0
  25. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  26. package/dist/features/magic-context/message-time-backfill.d.ts +2 -2
  27. package/dist/features/magic-context/message-time-backfill.d.ts.map +1 -1
  28. package/dist/features/magic-context/search.d.ts +6 -1
  29. package/dist/features/magic-context/search.d.ts.map +1 -1
  30. package/dist/features/magic-context/storage-db.d.ts +2 -1
  31. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  32. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  33. package/dist/features/magic-context/storage-meta-shared.d.ts +2 -2
  34. package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
  35. package/dist/features/magic-context/storage-session-tables.d.ts +9 -1
  36. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
  37. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/auto-search-deadline.d.ts +2 -1
  39. package/dist/hooks/magic-context/auto-search-deadline.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/auto-search-hint.d.ts +3 -0
  41. package/dist/hooks/magic-context/auto-search-hint.d.ts.map +1 -1
  42. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  43. package/dist/hooks/magic-context/auto-search-worker-client.d.ts +10 -2
  44. package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
  45. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +4 -2
  46. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  47. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  48. package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
  49. package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
  50. package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
  51. package/dist/hooks/magic-context/historian-prompt-fit.d.ts +2 -1
  52. package/dist/hooks/magic-context/historian-prompt-fit.d.ts.map +1 -1
  53. package/dist/hooks/magic-context/hook.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/raw-ordinal-warmup.d.ts +26 -0
  56. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts.map +1 -1
  57. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  58. package/dist/hooks/magic-context/recomp-orchestrator.d.ts +3 -3
  59. package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
  60. package/dist/hooks/magic-context/system-prompt-diagnostics.d.ts +8 -0
  61. package/dist/hooks/magic-context/system-prompt-diagnostics.d.ts.map +1 -0
  62. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  63. package/dist/hooks/magic-context/tag-messages.d.ts +6 -1
  64. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  65. package/dist/hooks/magic-context/todo-view.d.ts +2 -2
  66. package/dist/hooks/magic-context/tool-drop-target.d.ts +3 -2
  67. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  68. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  69. package/dist/hooks/magic-context/transform-stage-logger.d.ts +3 -0
  70. package/dist/hooks/magic-context/transform-stage-logger.d.ts.map +1 -1
  71. package/dist/hooks/magic-context/transform.d.ts +1 -0
  72. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  73. package/dist/{index-3kdm78zp.js → index-24fezq97.js} +4 -4
  74. package/dist/{index-a8bvhwqs.js → index-2vxtcb95.js} +32 -3
  75. package/dist/{index-f71thw8j.js → index-4s3t0nd0.js} +1 -1
  76. package/dist/{index-ts1hjk1h.js → index-4yt7dtf4.js} +453 -227
  77. package/dist/{index-mc1cqza6.js → index-5a1ex6x8.js} +5 -5
  78. package/dist/{index-fkx2qnvw.js → index-6x57ar45.js} +2 -2
  79. package/dist/{index-dyvbsvga.js → index-a6mc0v4d.js} +25 -11
  80. package/dist/{index-snp5wbge.js → index-a7c4r5re.js} +160 -749
  81. package/dist/{index-42vcjcwe.js → index-aabzay3h.js} +180 -103
  82. package/dist/{index-3kx0kg0f.js → index-b5vqckbw.js} +14 -8
  83. package/dist/{v2/server-wafzvyhg.js → index-beht37jy.js} +8 -0
  84. package/dist/{index-e20m7284.js → index-bjcnntmz.js} +3 -3
  85. package/dist/{index-hqkczed7.js → index-c5pytzne.js} +22 -2
  86. package/dist/{index-thvnpfsv.js → index-cwzfcbtq.js} +967 -88
  87. package/dist/{index-yxycg7fs.js → index-fb2qxs2y.js} +26 -18
  88. package/dist/{index-mht7bq0z.js → index-hqhm3wke.js} +32 -8
  89. package/dist/{index-e4dsjj1p.js → index-jn12fvvh.js} +1 -1
  90. package/dist/index-kaqs6h31.js +58 -0
  91. package/dist/{index-n6m03s3n.js → index-ke416mdc.js} +1 -1
  92. package/dist/index-kmdj7dsq.js +96 -0
  93. package/dist/{index-1d289pq2.js → index-kq82mtg0.js} +2 -2
  94. package/dist/{index-n78avt2p.js → index-n37sebck.js} +1 -1
  95. package/dist/{index-1vc7jrkg.js → index-nkpmm9q8.js} +3 -3
  96. package/dist/{index-944w16m0.js → index-p7m7j0cp.js} +25 -17
  97. package/dist/{index-wk0n1cgt.js → index-qn7xstt2.js} +2 -2
  98. package/dist/{index-saews2s3.js → index-rr2bb45z.js} +1 -1
  99. package/dist/{index-mmfa86mt.js → index-s734jcsr.js} +169 -149
  100. package/dist/{index-dgs16axy.js → index-s74zqahq.js} +1 -1
  101. package/dist/{index-bxdg2nbt.js → index-v8awdgvd.js} +4 -4
  102. package/dist/{index-xn6q9pg6.js → index-vrzjhftj.js} +36 -76
  103. package/dist/{index-1sarmj9z.js → index-wgypt3cs.js} +6 -6
  104. package/dist/{index-y1qysm3q.js → index-ze7mvk54.js} +11 -8
  105. package/dist/index.js +47 -45
  106. package/dist/message-fts-rowid-map-17s0dfn4.js +25 -0
  107. package/dist/{message-index-bounded-vtgpq6b4.js → message-index-bounded-1633vc7f.js} +17 -17
  108. package/dist/{message-index-a6gztaqx.js → message-index-dprebmtt.js} +15 -15
  109. package/dist/{message-time-backfill-qjge9044.js → message-time-backfill-73mmm76q.js} +5 -5
  110. package/dist/migration-worker.js +9 -7
  111. package/dist/plugin/dream-timer.d.ts +11 -0
  112. package/dist/plugin/dream-timer.d.ts.map +1 -1
  113. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  114. package/dist/{project-embedding-registry-x45bv3qr.js → project-embedding-registry-z74mhqkf.js} +12 -10
  115. package/dist/raw-ordinal-warmup-worker.js +40 -10
  116. package/dist/{read-session-chunk-3ae3nfdn.js → read-session-chunk-4zp09ejb.js} +9 -9
  117. package/dist/{read-session-raw-m56hc7v2.js → read-session-raw-rsc8c7qy.js} +2 -2
  118. package/dist/{recomp-orchestrator-nwzcfhx4.js → recomp-orchestrator-z3ecszx6.js} +26 -26
  119. package/dist/{search-deajrd90.js → search-6mee3vty.js} +23 -22
  120. package/dist/search-archive-znyy44ve.js +25 -0
  121. package/dist/{send-session-notification-24r4esbh.js → send-session-notification-6ve0e8p4.js} +5 -5
  122. package/dist/shared/historian-cache.d.ts +8 -0
  123. package/dist/shared/historian-cache.d.ts.map +1 -0
  124. package/dist/shared/model-suggestion-retry.d.ts +4 -0
  125. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  126. package/dist/shared/resolve-fallbacks.d.ts +3 -3
  127. package/dist/shared/rpc-discovery-cleanup.d.ts +3 -0
  128. package/dist/shared/rpc-discovery-cleanup.d.ts.map +1 -0
  129. package/dist/shared/rpc-server.d.ts +2 -0
  130. package/dist/shared/rpc-server.d.ts.map +1 -1
  131. package/dist/shared/search-text.d.ts +8 -0
  132. package/dist/shared/search-text.d.ts.map +1 -0
  133. package/dist/shared/sqlite.d.ts +4 -2
  134. package/dist/shared/sqlite.d.ts.map +1 -1
  135. package/dist/shared/storage-file-mutex.d.ts.map +1 -1
  136. package/dist/shared/subagent-runner.d.ts +2 -0
  137. package/dist/shared/subagent-runner.d.ts.map +1 -1
  138. package/dist/shared/system-directive.d.ts +2 -0
  139. package/dist/shared/system-directive.d.ts.map +1 -1
  140. package/dist/{sqlite-4pqyynrs.js → sqlite-zf72c52d.js} +1 -1
  141. package/dist/{storage-memory-j3v3hc83.js → storage-memory-y3qmy00r.js} +2 -2
  142. package/dist/{storage-tags-s5bg1ahx.js → storage-tags-8qns3012.js} +8 -4
  143. package/dist/tools/ctx-expand/search-archive.d.ts +5 -1
  144. package/dist/tools/ctx-expand/search-archive.d.ts.map +1 -1
  145. package/dist/{transform-postprocess-phase-ne3z1zmt.js → transform-postprocess-phase-3ydzxa62.js} +26 -26
  146. package/dist/v2/auto-search-worker.js +76 -63
  147. package/dist/v2/chunk-embedding-write-worker.js +12 -10
  148. package/dist/v2/{compaction-marker-candidates-1vqwr3s5.js → compaction-marker-candidates-ebx3388k.js} +2 -2
  149. package/dist/v2/compaction-marker-candidates-worker.js +2 -2
  150. package/dist/v2/{context-4qczzck7.js → context-jn3zpeqh.js} +909 -454
  151. package/dist/v2/embedding-backfill-7c7yr69y.js +23 -0
  152. package/dist/v2/embedding-worker-process.js +1 -1
  153. package/dist/v2/embedding-worker.js +5 -5
  154. package/dist/v2/fold/native-replay.d.ts +11 -2
  155. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  156. package/dist/v2/fold/policy.d.ts.map +1 -1
  157. package/dist/v2/fold/restore.d.ts.map +1 -1
  158. package/dist/v2/hooks/context.d.ts.map +1 -1
  159. package/dist/v2/hooks/hidden-child.d.ts +8 -0
  160. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  161. package/dist/v2/hooks/types.d.ts +17 -0
  162. package/dist/v2/hooks/types.d.ts.map +1 -1
  163. package/dist/v2/message-fts-rowid-map-wfx67gfd.js +24 -0
  164. package/dist/v2/{message-index-bounded-rxxznd34.js → message-index-bounded-hpejqyd8.js} +17 -17
  165. package/dist/v2/{message-index-f947qtbz.js → message-index-pxehjpzx.js} +15 -15
  166. package/dist/v2/{message-time-backfill-bsteyc4d.js → message-time-backfill-04t0km1z.js} +5 -5
  167. package/dist/v2/migration-worker.js +9 -7
  168. package/dist/v2/{project-embedding-registry-0msp56p8.js → project-embedding-registry-gnkj56xp.js} +12 -10
  169. package/dist/v2/raw-ordinal-warmup-worker.js +40 -10
  170. package/dist/v2/{read-session-chunk-rq9nx1nn.js → read-session-chunk-zdppn4bj.js} +9 -9
  171. package/dist/v2/{read-session-raw-b3tf6ra1.js → read-session-raw-yaegtjzh.js} +2 -2
  172. package/dist/v2/{recomp-orchestrator-5zhxtwha.js → recomp-orchestrator-cmqnfpp3.js} +26 -26
  173. package/dist/v2/{search-n8wqxb1j.js → search-66842dya.js} +23 -22
  174. package/dist/v2/search-archive-gfh11vs0.js +24 -0
  175. package/dist/v2/{send-session-notification-8ghn9tnv.js → send-session-notification-3pxn658x.js} +5 -5
  176. package/dist/v2/{server-yrvqaswb.js → server-1wy7b9de.js} +25 -11
  177. package/dist/v2/{server-th4y11y7.js → server-271qxsf5.js} +6 -6
  178. package/dist/v2/{server-e298hswg.js → server-3rhpvy84.js} +967 -88
  179. package/dist/v2/{server-qhfvvfxj.js → server-46neh5fa.js} +14 -8
  180. package/dist/v2/{server-rrqpvwqd.js → server-6tmj0s7j.js} +2 -2
  181. package/dist/v2/{server-hek6z3w6.js → server-8by8qfec.js} +11 -8
  182. package/dist/v2/{server-vbe4se57.js → server-a9xqj88f.js} +1 -1
  183. package/dist/{index-wafzvyhg.js → v2/server-beht37jy.js} +8 -0
  184. package/dist/v2/{server-05xjtq6c.js → server-d04vrx0j.js} +1 -1
  185. package/dist/v2/server-ec4ca92p.js +96 -0
  186. package/dist/v2/{server-dd0tz6cn.js → server-fw7wrk01.js} +160 -750
  187. package/dist/v2/{server-zs8d0s3b.js → server-g3qma5c0.js} +1 -1
  188. package/dist/v2/{server-k2bzedxk.js → server-gpvay0xz.js} +2 -2
  189. package/dist/v2/{server-kmbarfmn.js → server-gtfhttbr.js} +26 -18
  190. package/dist/v2/{server-g10mdym6.js → server-h1v0pyxb.js} +3 -3
  191. package/dist/v2/{server-4gn3z5an.js → server-hy3d3vsx.js} +1 -1
  192. package/dist/v2/server-kaqs6h31.js +58 -0
  193. package/dist/v2/{server-ehyava47.js → server-kh7dpa1a.js} +25 -17
  194. package/dist/v2/{server-6cdy4rc0.js → server-my7k4eds.js} +4 -4
  195. package/dist/v2/{server-d8tj10db.js → server-n1prf1g6.js} +1 -1
  196. package/dist/v2/{server-n78avt2p.js → server-n37sebck.js} +1 -1
  197. package/dist/v2/{server-zc3e54vy.js → server-nj659894.js} +6 -6
  198. package/dist/v2/{server-gvkm8xaj.js → server-rmygf5pn.js} +32 -3
  199. package/dist/v2/{server-0ppsweh6.js → server-tgnbmwah.js} +22 -2
  200. package/dist/v2/{server-cfbr1s2x.js → server-vsw8tmm6.js} +36 -76
  201. package/dist/v2/{server-prg55b7k.js → server-xj136kt8.js} +23 -3
  202. package/dist/v2/{server-atbc19ab.js → server-zyzawhdw.js} +32 -8
  203. package/dist/v2/{server-ef89gdsx.js → server-zzkj2fch.js} +4 -4
  204. package/dist/v2/server.js +5 -5
  205. package/dist/v2/{sqlite-4pqyynrs.js → sqlite-zf72c52d.js} +1 -1
  206. package/dist/v2/{storage-memory-j3v3hc83.js → storage-memory-y3qmy00r.js} +2 -2
  207. package/dist/v2/{storage-tags-hcc2adpf.js → storage-tags-1h8k6ra9.js} +8 -4
  208. package/dist/v2/store-reader.d.ts +2 -0
  209. package/dist/v2/store-reader.d.ts.map +1 -1
  210. package/dist/v2/{wrapup-orchestrator-65pwye0d.js → wrapup-orchestrator-xs8redz9.js} +26 -26
  211. package/dist/wrapup-orchestrator-j7d7ry5b.js +48 -0
  212. package/package.json +1 -1
  213. package/src/config/latch-permanence-guard.test.ts +4 -0
  214. package/src/config/schema/magic-context.ts +14 -6
  215. package/src/shared/historian-cache.test.ts +69 -0
  216. package/src/shared/historian-cache.ts +55 -0
  217. package/src/shared/model-resolution.test.ts +22 -0
  218. package/src/shared/model-suggestion-retry.ts +11 -3
  219. package/src/shared/resolve-fallbacks.test.ts +2 -3
  220. package/src/shared/resolve-fallbacks.ts +3 -3
  221. package/src/shared/rpc-discovery-cleanup.test.ts +57 -0
  222. package/src/shared/rpc-discovery-cleanup.ts +57 -0
  223. package/src/shared/rpc-server.ts +36 -13
  224. package/src/shared/search-text.test.ts +47 -0
  225. package/src/shared/search-text.ts +63 -0
  226. package/src/shared/sqlite.test.ts +56 -0
  227. package/src/shared/sqlite.ts +51 -2
  228. package/src/shared/storage-file-mutex-review.test.ts +22 -2
  229. package/src/shared/storage-file-mutex.ts +11 -1
  230. package/src/shared/subagent-runner.ts +2 -0
  231. package/src/shared/system-directive.ts +19 -1
  232. package/src/shared/tag-transcript.ts +12 -4
  233. package/dist/embedding-backfill-5e1t5wha.js +0 -22
  234. package/dist/v2/embedding-backfill-jmaf8zrr.js +0 -21
  235. package/dist/wrapup-orchestrator-28xzsj5q.js +0 -48
@@ -92,7 +92,7 @@ import {
92
92
  getRawSessionTagKeysThrough2,
93
93
  getLegacyProtectedTailStartOrdinal2,
94
94
  readSessionChunk2
95
- } from "./index-944w16m0.js";
95
+ } from "./index-p7m7j0cp.js";
96
96
  import {
97
97
  getHarness2,
98
98
  harnessOwnsOpenCodeStore2
@@ -142,7 +142,7 @@ import {
142
142
  ConfigProfilesSchema,
143
143
  MagicContextConfigSchema,
144
144
  LIVE_RELOAD_CONFIG_PATHS
145
- } from "./index-1sarmj9z.js";
145
+ } from "./index-wgypt3cs.js";
146
146
  import {
147
147
  providerMass,
148
148
  calibrationForModelKey,
@@ -152,14 +152,14 @@ import {
152
152
  hasMeaningfulUserText2,
153
153
  estimateTokens,
154
154
  estimateFixedPromptTokens
155
- } from "./index-hqkczed7.js";
155
+ } from "./index-c5pytzne.js";
156
156
  import {
157
157
  FAIL_CLOSED_DOCTOR_COMMAND,
158
158
  getSchemaFenceRejection,
159
159
  LATEST_SUPPORTED_VERSION,
160
160
  getPersistedSchemaVersion,
161
161
  openDatabase
162
- } from "./index-yxycg7fs.js";
162
+ } from "./index-fb2qxs2y.js";
163
163
  import {
164
164
  inRootAsyncContext2,
165
165
  Database2,
@@ -167,14 +167,20 @@ import {
167
167
  withSqliteBackgroundWriter2,
168
168
  withoutSqliteTransformPass2,
169
169
  beginSqliteWriterAsync2
170
- } from "./index-wafzvyhg.js";
170
+ } from "./index-beht37jy.js";
171
171
  import {
172
172
  shouldSkipHomeProjectMemory,
173
173
  resolveProjectIdentity
174
- } from "./index-a8bvhwqs.js";
174
+ } from "./index-2vxtcb95.js";
175
175
  import {
176
176
  isPidAlive
177
177
  } from "./index-nj7yykkx.js";
178
+ import {
179
+ isStrictGapHealingMessage2,
180
+ noteRawSessionSummaryRowWritten2,
181
+ RawOrdinalsNotReady2,
182
+ runSessionWarmupWorker
183
+ } from "./index-s734jcsr.js";
178
184
  import {
179
185
  layoutLkgPrefix,
180
186
  assembleLkgPrefix,
@@ -185,7 +191,7 @@ import {
185
191
  resolveStoredPathWorkspaceIdentity,
186
192
  sourceNameForMemory,
187
193
  computeWorkspaceEpochFingerprint
188
- } from "./index-wk0n1cgt.js";
194
+ } from "./index-qn7xstt2.js";
189
195
  import {
190
196
  getTableColumnNames
191
197
  } from "./index-bp5083x2.js";
@@ -202,7 +208,7 @@ import {
202
208
  } from "./index-58e3y90n.js";
203
209
  import {
204
210
  getMeasuredToolDefinitionTokens
205
- } from "./index-n6m03s3n.js";
211
+ } from "./index-ke416mdc.js";
206
212
  import {
207
213
  invalidateAutoEmbedSession,
208
214
  drainBackgroundBatches,
@@ -211,7 +217,7 @@ import {
211
217
  getProjectChunkEmbeddingModelId2,
212
218
  getProjectEmbeddingMaxInputTokens2,
213
219
  embedItemsForProject2
214
- } from "./index-y1qysm3q.js";
220
+ } from "./index-ze7mvk54.js";
215
221
  import {
216
222
  buildCanonicalChunkTextFromFts,
217
223
  buildCompartmentSummaryFallbackText,
@@ -221,7 +227,7 @@ import {
221
227
  replaceCompartmentChunkEmbeddings,
222
228
  deleteChunkEmbedBackoffForSession,
223
229
  chunkWindowSourceKey
224
- } from "./index-3kx0kg0f.js";
230
+ } from "./index-b5vqckbw.js";
225
231
  import {
226
232
  BoundedSessionMap,
227
233
  clearCompressionDepth,
@@ -232,11 +238,13 @@ import {
232
238
  ownsLkgDirtyFence,
233
239
  commitLkgWithRecoveryFence,
234
240
  clearLkgRecoveryFence,
241
+ gaDatabasePath,
242
+ V2StoreReader,
235
243
  deleteSessionScopedRows,
236
244
  toMessageIndexSource2,
237
245
  clearIndexedMessagesInTransaction2,
238
246
  indexSourcesAfterOrdinal2
239
- } from "./index-thvnpfsv.js";
247
+ } from "./index-cwzfcbtq.js";
240
248
  import {
241
249
  stripWellFormedLeadingTagPrefix,
242
250
  stripTagPrefix,
@@ -249,18 +257,12 @@ import {
249
257
  foldShrunkPartTags2,
250
258
  getTagNumberByMessageId2,
251
259
  getActiveTagsBySession2
252
- } from "./index-mht7bq0z.js";
253
- import {
254
- isStrictGapHealingMessage2,
255
- noteRawSessionSummaryRowWritten2,
256
- RawOrdinalsNotReady2,
257
- runSessionWarmupWorker
258
- } from "./index-mmfa86mt.js";
260
+ } from "./index-hqhm3wke.js";
259
261
  import {
260
262
  openCodeDbExists,
261
263
  withReadOnlySessionDb,
262
264
  getMessageTimesFromOpenCodeDb
263
- } from "./index-1d289pq2.js";
265
+ } from "./index-kq82mtg0.js";
264
266
  import {
265
267
  renderUserFacingFailure,
266
268
  userFacingFailureCode,
@@ -269,7 +271,7 @@ import {
269
271
  insertPrimerCandidates,
270
272
  promoteSessionFactsDurable,
271
273
  embedPromotedFacts
272
- } from "./index-bxdg2nbt.js";
274
+ } from "./index-v8awdgvd.js";
273
275
  import {
274
276
  pushNotification2
275
277
  } from "./index-x8a7jmkh.js";
@@ -280,16 +282,16 @@ import {
280
282
  getMemoriesByProject2,
281
283
  getMemoriesByProjects2,
282
284
  getMaxMemoryIdForProjects2
283
- } from "./index-n78avt2p.js";
285
+ } from "./index-n37sebck.js";
284
286
  import {
285
287
  isMarkerCandidateBasisCurrent2,
286
288
  invalidateMarkerCandidateBasis2,
287
289
  readMarkerCandidateBasis2,
288
290
  prepareMarkerCandidateBasis2
289
- } from "./index-f71thw8j.js";
291
+ } from "./index-4s3t0nd0.js";
290
292
  import {
291
293
  sendStatusNotification2
292
- } from "./index-dgs16axy.js";
294
+ } from "./index-s74zqahq.js";
293
295
  import {
294
296
  isCompactionEnabled,
295
297
  migrateLegacyAgentEnabledInMemory
@@ -297,9 +299,6 @@ import {
297
299
  import {
298
300
  piModelRefToCanonical
299
301
  } from "./index-avwt563y.js";
300
- import {
301
- sameProjectDirectory
302
- } from "./index-knvkbfvh.js";
303
302
  import {
304
303
  getErrorMessage,
305
304
  describeError
@@ -4912,10 +4911,10 @@ function readProjectDocsCanonical(projectDirectory) {
4912
4911
  return { renderedBlock, canonicalHash };
4913
4912
  }
4914
4913
  // src/hooks/magic-context/lkg-slot.ts
4915
- import { createHash as createHash6 } from "node:crypto";
4914
+ import { createHash as createHash5 } from "node:crypto";
4916
4915
 
4917
4916
  // src/hooks/magic-context/lkg-measured-request.ts
4918
- import { createHash as createHash4 } from "node:crypto";
4917
+ import { createHash as createHash3 } from "node:crypto";
4919
4918
 
4920
4919
  // src/shared/provider-response-completion.ts
4921
4920
  function providerResponseFailed(input) {
@@ -4983,691 +4982,6 @@ function cancelAutoSearchWork(sessionId) {
4983
4982
  }
4984
4983
  }
4985
4984
 
4986
- // src/v2/store-reader.ts
4987
- import { createHash as createHash3 } from "node:crypto";
4988
- import { statSync as statSync5 } from "node:fs";
4989
- import { hostname } from "node:os";
4990
- import { resolve as resolve2 } from "node:path";
4991
- function gaDatabasePath(dataHome, channel = "latest", env = process.env) {
4992
- return resolveOpenCodeDbPath("v2", { dataHome, channel, env }).path;
4993
- }
4994
- var RAW_MESSAGE_TYPES = [
4995
- "user",
4996
- "synthetic",
4997
- "assistant",
4998
- "skill",
4999
- "shell",
5000
- "system"
5001
- ];
5002
- var RAW_MESSAGE_TYPE_PARAMETERS = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
5003
- var V2_MESSAGE_PAGE_SQL = `WITH bounds AS (
5004
- SELECT
5005
- CASE WHEN ? = 0 THEN -1 ELSE COALESCE((
5006
- SELECT seq FROM session_message
5007
- WHERE session_id = ? AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
5008
- ORDER BY seq ASC LIMIT 1 OFFSET ?
5009
- ), (SELECT MAX(seq) FROM session_message WHERE session_id = ?), -1) END AS after_seq,
5010
- COALESCE((
5011
- SELECT seq FROM session_message
5012
- WHERE session_id = ? AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
5013
- ORDER BY seq ASC LIMIT 1 OFFSET ?
5014
- ), ?) AS watermark_seq
5015
- )
5016
- SELECT id, session_id, type, seq, time_created, data FROM session_message, bounds
5017
- WHERE session_id = ?
5018
- AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS})
5019
- AND seq > bounds.after_seq
5020
- AND seq <= bounds.watermark_seq
5021
- ORDER BY seq ASC LIMIT ?`;
5022
- var V2_STORE_READER_DEBUG_COUNTER_KEY = "magic-context.v2.store-reader-debug";
5023
- var debugSymbol = Symbol.for(V2_STORE_READER_DEBUG_COUNTER_KEY);
5024
- var debugGlobal = globalThis;
5025
- var QUERY_STATEMENTS = {
5026
- messagePage: V2_MESSAGE_PAGE_SQL,
5027
- messageCount: "SELECT COUNT(*) AS count FROM session_message WHERE session_id = ? AND type IN (?)",
5028
- storedMessageCount: "SELECT COUNT(*) AS count FROM session_message WHERE session_id = ?",
5029
- messageById: "SELECT id, session_id, type, seq, time_created, data FROM session_message WHERE session_id = ? AND id = ? AND type IN (?) LIMIT 1",
5030
- messageExistsById: "SELECT 1 FROM session_message WHERE id = ? AND session_id = ? AND type IN (?) LIMIT 1",
5031
- messageOrdinalById: `WITH target AS (
5032
- SELECT seq FROM session_message WHERE session_id = ? AND id = ? AND type IN (?) LIMIT 1
5033
- )
5034
- SELECT (SELECT COUNT(*) FROM session_message WHERE session_id = ? AND type IN (?) AND seq <= target.seq) AS ordinal FROM target`,
5035
- messageIdOrdinals: "SELECT id FROM session_message WHERE session_id = ? AND type IN (?) ORDER BY seq ASC LIMIT ? OFFSET ?",
5036
- 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 ?",
5037
- 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 ?"
5038
- };
5039
- function debugCounters() {
5040
- const counters = debugGlobal[debugSymbol] ??= {
5041
- decodedRows: 0,
5042
- operations: {},
5043
- openReaders: 0,
5044
- maxOpenReaders: 0,
5045
- readersOpened: 0,
5046
- readersClosed: 0
5047
- };
5048
- counters.openReaders ??= 0;
5049
- counters.maxOpenReaders ??= 0;
5050
- counters.readersOpened ??= 0;
5051
- counters.readersClosed ??= 0;
5052
- return counters;
5053
- }
5054
- function returnedRowCount(value) {
5055
- if (Array.isArray(value))
5056
- return value.length;
5057
- if (value === null || value === undefined || value === false)
5058
- return 0;
5059
- return 1;
5060
- }
5061
- function trackDecodeOperation(name, operation) {
5062
- const counters = debugCounters();
5063
- const before = counters.decodedRows;
5064
- const started = performance.now();
5065
- let value;
5066
- try {
5067
- value = operation();
5068
- return value;
5069
- } finally {
5070
- const decodedRows = counters.decodedRows - before;
5071
- const current = counters.operations[name] ?? {
5072
- calls: 0,
5073
- decodedRows: 0,
5074
- maxDecodedRows: 0
5075
- };
5076
- current.calls += 1;
5077
- current.decodedRows += decodedRows;
5078
- current.maxDecodedRows = Math.max(current.maxDecodedRows, decodedRows);
5079
- counters.operations[name] = current;
5080
- const statement = QUERY_STATEMENTS[name];
5081
- if (counters.captureQueries && statement) {
5082
- (counters.queries ??= []).push({
5083
- operation: name,
5084
- statement,
5085
- rows: returnedRowCount(value),
5086
- elapsedMs: performance.now() - started
5087
- });
5088
- }
5089
- }
5090
- }
5091
- function decode(row) {
5092
- debugCounters().decodedRows += 1;
5093
- const data = JSON.parse(row.data);
5094
- if (!data || typeof data !== "object" || Array.isArray(data)) {
5095
- throw new Error(`Invalid session_message data at seq ${row.seq}`);
5096
- }
5097
- if (row.type === "idle" && !["succeeded", "failed", "interrupted"].includes(String(data.outcome))) {
5098
- throw new Error(`Invalid idle outcome at seq ${row.seq}`);
5099
- }
5100
- return { ...row, data };
5101
- }
5102
- function connect(path, identity = "") {
5103
- const stat = statSync5(path);
5104
- const acquiredIdentity = identity || `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
5105
- const db = new Database2(path, { readonly: true, fileMustExist: true });
5106
- try {
5107
- assertOpenCodeStoreGeneration(db, "v2", path);
5108
- } catch (error) {
5109
- db.close();
5110
- throw error;
5111
- }
5112
- const counters = debugCounters();
5113
- counters.openReaders += 1;
5114
- counters.readersOpened += 1;
5115
- counters.maxOpenReaders = Math.max(counters.maxOpenReaders, counters.openReaders);
5116
- return { db, statements: new Map, identity: acquiredIdentity, leases: 0, retired: false };
5117
- }
5118
- function closeConnection(connection) {
5119
- connection.statements.clear();
5120
- try {
5121
- connection.db.close();
5122
- } finally {
5123
- const counters = debugCounters();
5124
- counters.openReaders = Math.max(0, counters.openReaders - 1);
5125
- counters.readersClosed += 1;
5126
- }
5127
- }
5128
-
5129
- class V2StoreReaderPool {
5130
- capacity;
5131
- connections = new Map;
5132
- closed = false;
5133
- closing = false;
5134
- holds = 0;
5135
- idleWaiters = new Set;
5136
- constructor(capacity = 4) {
5137
- this.capacity = capacity;
5138
- if (!Number.isSafeInteger(capacity) || capacity < 1)
5139
- throw new Error("Invalid reader capacity");
5140
- }
5141
- open(path) {
5142
- return new V2StoreReader(path, this);
5143
- }
5144
- acquire(path) {
5145
- if (this.closed)
5146
- throw new Error("Store reader pool is closed");
5147
- const key = resolve2(path);
5148
- const stat = statSync5(key);
5149
- const identity = `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
5150
- let connection = this.connections.get(key);
5151
- if (connection && connection.identity !== identity) {
5152
- this.connections.delete(key);
5153
- this.retire(connection);
5154
- connection = undefined;
5155
- }
5156
- if (!connection)
5157
- connection = connect(key, identity);
5158
- connection.leases++;
5159
- this.connections.delete(key);
5160
- this.connections.set(key, connection);
5161
- while (this.connections.size > this.capacity) {
5162
- const oldest = this.connections.entries().next().value;
5163
- if (!oldest)
5164
- break;
5165
- this.connections.delete(oldest[0]);
5166
- this.retire(oldest[1]);
5167
- }
5168
- return connection;
5169
- }
5170
- release(connection) {
5171
- connection.leases--;
5172
- if (connection.retired && connection.leases === 0)
5173
- closeConnection(connection);
5174
- }
5175
- retire(connection) {
5176
- connection.retired = true;
5177
- if (connection.leases === 0)
5178
- closeConnection(connection);
5179
- }
5180
- hold() {
5181
- if (this.closed || this.closing)
5182
- throw new Error("Store reader pool is closed");
5183
- this.holds++;
5184
- let released = false;
5185
- return () => {
5186
- if (released)
5187
- return;
5188
- released = true;
5189
- this.holds--;
5190
- if (this.holds === 0 && this.closing)
5191
- this.finishClose();
5192
- };
5193
- }
5194
- isClosed() {
5195
- return this.closed;
5196
- }
5197
- holdCount() {
5198
- return this.holds;
5199
- }
5200
- close() {
5201
- if (this.closed || this.closing)
5202
- return;
5203
- this.closing = true;
5204
- if (this.holds === 0)
5205
- this.finishClose();
5206
- }
5207
- async closeWhenIdle(timeoutMs) {
5208
- this.close();
5209
- if (this.closed)
5210
- return true;
5211
- let timer;
5212
- let waiter;
5213
- try {
5214
- await new Promise((resolve) => {
5215
- waiter = resolve;
5216
- this.idleWaiters.add(resolve);
5217
- timer = setTimeout(resolve, Math.max(0, timeoutMs));
5218
- });
5219
- } finally {
5220
- if (timer)
5221
- clearTimeout(timer);
5222
- if (waiter)
5223
- this.idleWaiters.delete(waiter);
5224
- }
5225
- return this.closed;
5226
- }
5227
- finishClose() {
5228
- if (this.closed)
5229
- return;
5230
- this.closed = true;
5231
- for (const connection of this.connections.values())
5232
- this.retire(connection);
5233
- this.connections.clear();
5234
- for (const resolve of this.idleWaiters)
5235
- resolve();
5236
- this.idleWaiters.clear();
5237
- }
5238
- }
5239
-
5240
- class V2StoreReader {
5241
- path;
5242
- pool;
5243
- db;
5244
- connection;
5245
- closed = false;
5246
- constructor(path, pool) {
5247
- this.path = path;
5248
- this.pool = pool;
5249
- this.connection = pool ? pool.acquire(path) : connect(path);
5250
- this.db = this.connection.db;
5251
- }
5252
- hostIdentity() {
5253
- return createHash3("sha256").update(JSON.stringify([hostname(), resolve2(this.path), this.connection.identity])).digest("hex");
5254
- }
5255
- prepare(sql) {
5256
- if (this.closed)
5257
- throw new Error("Store reader is closed");
5258
- const statements = this.connection.statements;
5259
- let statement = statements.get(sql);
5260
- if (!statement) {
5261
- statement = this.db.prepare(sql);
5262
- if (statements.size >= 128)
5263
- statements.clear();
5264
- statements.set(sql, statement);
5265
- }
5266
- return statement;
5267
- }
5268
- close() {
5269
- if (this.closed)
5270
- return;
5271
- this.closed = true;
5272
- if (this.pool)
5273
- this.pool.release(this.connection);
5274
- else
5275
- closeConnection(this.connection);
5276
- }
5277
- page(sessionID, options = {}) {
5278
- return trackDecodeOperation("page", () => {
5279
- const limit = options.limit ?? 100;
5280
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
5281
- throw new Error("Invalid page limit");
5282
- const after = options.after ?? -1;
5283
- if (!Number.isSafeInteger(after))
5284
- throw new Error("Invalid seq cursor");
5285
- if (options.through !== undefined && !Number.isSafeInteger(options.through))
5286
- throw new Error("Invalid seq upper bound");
5287
- const predicates = ["session_id = ?", "seq > ?"];
5288
- const parameters = [sessionID, after];
5289
- if (options.through !== undefined) {
5290
- predicates.push("seq <= ?");
5291
- parameters.push(options.through);
5292
- }
5293
- if (options.type) {
5294
- predicates.push("type = ?");
5295
- parameters.push(options.type);
5296
- }
5297
- const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
5298
- WHERE ${predicates.join(" AND ")}
5299
- ORDER BY seq ASC LIMIT ?`).all(...parameters, limit).map(decode);
5300
- return { rows, cursor: rows.at(-1)?.seq };
5301
- });
5302
- }
5303
- messagePage(sessionID, afterOrdinal, limit, finalWatermark, after) {
5304
- return trackDecodeOperation("messagePage", () => {
5305
- if (!Number.isSafeInteger(afterOrdinal) || afterOrdinal < 0)
5306
- throw new Error("Invalid raw-message ordinal cursor");
5307
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
5308
- throw new Error("Invalid page limit");
5309
- if (!Number.isSafeInteger(finalWatermark) || finalWatermark < 0)
5310
- throw new Error("Invalid raw-message watermark");
5311
- const pageSize = Math.min(limit, finalWatermark - afterOrdinal);
5312
- if (pageSize <= 0)
5313
- return [];
5314
- if (after) {
5315
- const anchor = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ?").get(sessionID, after.id);
5316
- if (anchor) {
5317
- return this.prepare(`SELECT id, session_id, type, seq, time_created, data
5318
- FROM session_message WHERE session_id = ? AND seq > ?
5319
- AND type IN (${RAW_MESSAGE_TYPE_PARAMETERS}) ORDER BY seq ASC LIMIT ?`).all(sessionID, anchor.seq, ...RAW_MESSAGE_TYPES, pageSize).map(decode);
5320
- }
5321
- }
5322
- const maximumSeq = Number.MAX_SAFE_INTEGER;
5323
- 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);
5324
- return rows.map(decode);
5325
- });
5326
- }
5327
- messageCount(sessionID) {
5328
- return trackDecodeOperation("messageCount", () => {
5329
- const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
5330
- const row = this.prepare(`SELECT COUNT(*) AS count FROM session_message
5331
- WHERE session_id = ? AND type IN (${rawTypes})`).get(sessionID, ...RAW_MESSAGE_TYPES);
5332
- return typeof row?.count === "number" ? row.count : 0;
5333
- });
5334
- }
5335
- sessionDirectoryPage(afterSessionID, limit) {
5336
- const rows = this.prepare(`SELECT id, COALESCE(directory, '') AS directory FROM session_v2
5337
- WHERE id > ? ORDER BY id ASC LIMIT ?`).all(afterSessionID ?? "", limit);
5338
- return rows.map((row) => ({ sessionId: row.id, directory: row.directory }));
5339
- }
5340
- latestMessageTime(sessionID) {
5341
- const row = this.prepare("SELECT MAX(time_created) AS time FROM session_message WHERE session_id = ?").get(sessionID);
5342
- return row?.time ?? undefined;
5343
- }
5344
- isSubagent(sessionID) {
5345
- const row = this.prepare("SELECT parent_id FROM session_v2 WHERE id = ?").get(sessionID);
5346
- if (!row)
5347
- return null;
5348
- return typeof row.parent_id === "string" && row.parent_id.length > 0;
5349
- }
5350
- latestRootSessionInDirectory(directory) {
5351
- const columns = new Set(this.prepare("PRAGMA table_info(session_v2)").all().map((column) => column.name));
5352
- const archived = columns.has("time_archived") ? " AND time_archived IS NULL" : "";
5353
- const order = columns.has("time_updated") ? "time_updated DESC, id DESC" : "id DESC";
5354
- const page = this.prepare(`SELECT id, COALESCE(directory, '') AS directory FROM session_v2
5355
- WHERE parent_id IS NULL${archived}
5356
- AND COALESCE(json_extract(metadata, '$.magic_context'), '') <> 'hidden-run'
5357
- ORDER BY ${order} LIMIT ? OFFSET ?`);
5358
- const pageSize = 500;
5359
- for (let offset = 0;; offset += pageSize) {
5360
- const rows = page.all(pageSize, offset);
5361
- const match = rows.find((row) => sameProjectDirectory(row.directory, directory));
5362
- if (match)
5363
- return match.id;
5364
- if (rows.length < pageSize)
5365
- return;
5366
- }
5367
- }
5368
- rootSessionActivity(sessionIDs) {
5369
- const roots = new Map;
5370
- for (let offset = 0;offset < sessionIDs.length; offset += 500) {
5371
- const chunk = sessionIDs.slice(offset, offset + 500);
5372
- const rows = this.prepare(`SELECT id, (
5373
- SELECT MAX(time_created) FROM session_message
5374
- WHERE session_id = session_v2.id AND type = 'user'
5375
- ) AS time FROM session_v2
5376
- WHERE parent_id IS NULL
5377
- AND COALESCE(json_extract(metadata, '$.magic_context'), '') <> 'hidden-run'
5378
- AND id IN (${chunk.map(() => "?").join(",")})`).all(...chunk);
5379
- for (const row of rows)
5380
- if (row.time !== null)
5381
- roots.set(row.id, row.time);
5382
- }
5383
- return roots;
5384
- }
5385
- oldestUserMessageTimesSince(sessionIDs, sinceMs) {
5386
- const result = new Map;
5387
- for (let offset = 0;offset < sessionIDs.length; offset += 500) {
5388
- const chunk = sessionIDs.slice(offset, offset + 500);
5389
- const rows = this.prepare(`SELECT session_id, MIN(time_created) AS time FROM session_message
5390
- WHERE type = 'user' AND time_created > ? AND session_id IN (${chunk.map(() => "?").join(",")})
5391
- GROUP BY session_id`).all(sinceMs, ...chunk);
5392
- for (const row of rows)
5393
- result.set(row.session_id, row.time);
5394
- }
5395
- return result;
5396
- }
5397
- retrospectiveUserPage(sessionID, options) {
5398
- const { boundaryMs, before, limit, maxChars, truncationMarker } = options;
5399
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
5400
- throw new Error("Invalid page limit");
5401
- if (!Number.isSafeInteger(maxChars) || maxChars <= truncationMarker.length)
5402
- throw new Error("Invalid text limit");
5403
- const direction = before ? "DESC" : "ASC";
5404
- const head = Math.floor((maxChars - truncationMarker.length) / 2);
5405
- const tail = maxChars - truncationMarker.length - head;
5406
- return this.prepare(`WITH users AS (
5407
- SELECT session_id, seq, time_created, data FROM session_message
5408
- WHERE session_id = ? AND type = 'user' AND time_created ${before ? "<=" : ">"}
5409
- ?
5410
- ORDER BY time_created ${direction}, seq ${direction} LIMIT ?
5411
- ), texts AS (
5412
- SELECT session_id, seq, time_created, CASE
5413
- WHEN json_extract(data, '$.synthetic') = 1 OR json_extract(data, '$.ignored') = 1 THEN ''
5414
- WHEN json_type(data, '$.text') = 'text' THEN json_extract(data, '$.text')
5415
- ELSE COALESCE((SELECT group_concat(json_extract(value, '$.text'), char(10))
5416
- FROM json_each(users.data, '$.content')
5417
- WHERE json_extract(value, '$.type') IN ('text', 'input_text')
5418
- AND COALESCE(json_extract(value, '$.synthetic'), 0) <> 1
5419
- AND COALESCE(json_extract(value, '$.ignored'), 0) <> 1), '') END AS text
5420
- FROM users WHERE json_valid(data)
5421
- ) SELECT seq, time_created, CASE WHEN length(text) > ?
5422
- THEN substr(text, 1, ?) || ? || substr(text, -?) ELSE text END AS text,
5423
- EXISTS (
5424
- SELECT 1 FROM session_message assistant_reply
5425
- WHERE assistant_reply.session_id = texts.session_id
5426
- AND assistant_reply.type = 'assistant'
5427
- AND assistant_reply.seq < texts.seq
5428
- AND EXISTS (
5429
- SELECT 1 FROM session_message prior_user
5430
- WHERE prior_user.session_id = texts.session_id
5431
- AND prior_user.type = 'user'
5432
- AND prior_user.seq < assistant_reply.seq
5433
- )
5434
- ) AS follows_assistant_reply
5435
- FROM texts ORDER BY time_created ${direction}, seq ${direction}`).all(sessionID, boundaryMs, limit, maxChars, head, truncationMarker, tail);
5436
- }
5437
- storedRowsAfter(sessionID, after) {
5438
- const row = this.prepare("SELECT COUNT(*) AS count FROM session_message WHERE session_id = ? AND seq > ?").get(sessionID, after);
5439
- return row.count;
5440
- }
5441
- storedMessageCount(sessionID) {
5442
- return trackDecodeOperation("storedMessageCount", () => {
5443
- const row = this.prepare("SELECT COUNT(*) AS count FROM session_message WHERE session_id = ?").get(sessionID);
5444
- return typeof row?.count === "number" ? row.count : 0;
5445
- });
5446
- }
5447
- messageById(sessionID, id) {
5448
- return trackDecodeOperation("messageById", () => {
5449
- const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
5450
- const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
5451
- WHERE session_id = ? AND id = ? AND type IN (${rawTypes}) LIMIT 1`).get(sessionID, id, ...RAW_MESSAGE_TYPES);
5452
- return row ? decode(row) : null;
5453
- });
5454
- }
5455
- messageTimes(sessionID, ids) {
5456
- const times = new Map;
5457
- for (let offset = 0;offset < ids.length; offset += 500) {
5458
- const batch = ids.slice(offset, offset + 500);
5459
- const rows = this.prepare(`SELECT id, COALESCE(time_created, json_extract(data, '$.time.created')) AS created,
5460
- json_extract(data, '$.time.completed') AS completed
5461
- FROM session_message WHERE session_id = ? AND id IN (${batch.map(() => "?").join(",")})`).all(sessionID, ...batch);
5462
- for (const row of rows)
5463
- times.set(row.id, {
5464
- created: typeof row.created === "number" ? row.created : undefined,
5465
- completed: typeof row.completed === "number" ? row.completed : undefined
5466
- });
5467
- }
5468
- return times;
5469
- }
5470
- messageExistsById(sessionID, id) {
5471
- return trackDecodeOperation("messageExistsById", () => {
5472
- const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
5473
- const row = this.prepare(`SELECT 1 FROM session_message
5474
- WHERE id = ? AND session_id = ? AND type IN (${rawTypes}) LIMIT 1`).get(id, sessionID, ...RAW_MESSAGE_TYPES);
5475
- return row != null;
5476
- });
5477
- }
5478
- messageOrdinalById(sessionID, id) {
5479
- return trackDecodeOperation("messageOrdinalById", () => {
5480
- const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
5481
- const row = this.prepare(`WITH target AS (
5482
- SELECT seq FROM session_message
5483
- WHERE session_id = ? AND id = ? AND type IN (${rawTypes})
5484
- LIMIT 1
5485
- )
5486
- SELECT (
5487
- SELECT COUNT(*) FROM session_message
5488
- WHERE session_id = ?
5489
- AND type IN (${rawTypes})
5490
- AND seq <= target.seq
5491
- ) AS ordinal
5492
- FROM target`).get(sessionID, id, ...RAW_MESSAGE_TYPES, sessionID, ...RAW_MESSAGE_TYPES);
5493
- return typeof row?.ordinal === "number" ? row.ordinal : null;
5494
- });
5495
- }
5496
- messageIdOrdinals(sessionID, fromOrdinal, toOrdinal) {
5497
- return trackDecodeOperation("messageIdOrdinals", () => {
5498
- if (!Number.isSafeInteger(fromOrdinal) || fromOrdinal < 1)
5499
- throw new Error("Invalid raw-message range start");
5500
- if (!Number.isSafeInteger(toOrdinal) || toOrdinal < fromOrdinal)
5501
- throw new Error("Invalid raw-message range end");
5502
- const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
5503
- const rows = this.prepare(`SELECT id FROM session_message
5504
- WHERE session_id = ? AND type IN (${rawTypes})
5505
- ORDER BY seq ASC LIMIT ? OFFSET ?`).all(sessionID, ...RAW_MESSAGE_TYPES, toOrdinal - fromOrdinal + 1, fromOrdinal - 1);
5506
- return new Map(rows.map((row, index) => [row.id, fromOrdinal + index]));
5507
- });
5508
- }
5509
- messageOrdinalPage(sessionID, after, limit) {
5510
- return trackDecodeOperation("messageOrdinalPage", () => {
5511
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
5512
- throw new Error("Invalid page limit");
5513
- const rows = after ? this.prepare(`SELECT id, type, seq, json_valid(data) AS valid
5514
- FROM session_message
5515
- WHERE session_id = ? AND (seq > ? OR (seq = ? AND id > ?))
5516
- 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
5517
- FROM session_message
5518
- WHERE session_id = ?
5519
- ORDER BY seq ASC, id ASC LIMIT ?`).all(sessionID, limit);
5520
- const rawTypes = new Set(RAW_MESSAGE_TYPES);
5521
- return rows.map((row) => ({
5522
- id: row.id,
5523
- timeCreated: row.seq,
5524
- contributesOrdinal: rawTypes.has(row.type),
5525
- hasValidInfo: row.valid === 1
5526
- }));
5527
- });
5528
- }
5529
- range(sessionID, after, through) {
5530
- return trackDecodeOperation("range", () => through <= after ? [] : this.all(sessionID, after, undefined, through));
5531
- }
5532
- spanRowStamps(sessionID, after, through) {
5533
- if (!Number.isSafeInteger(after) || !Number.isSafeInteger(through))
5534
- throw new Error("Invalid seq span");
5535
- const rows = this.prepare(`SELECT seq, id, time_updated AS updated, length(CAST(data AS BLOB)) AS bytes
5536
- FROM session_message WHERE session_id = ? AND seq > ? AND seq <= ?
5537
- ORDER BY seq ASC`).all(sessionID, after, through);
5538
- const stamps = new Map;
5539
- for (const row of rows)
5540
- stamps.set(row.seq, `${row.id}\x00${row.updated ?? ""}\x00${row.bytes ?? ""}`);
5541
- return stamps;
5542
- }
5543
- rawRowsThrough(sessionID, throughSeq, limit) {
5544
- return trackDecodeOperation("rawRowsThrough", () => {
5545
- if (!Number.isSafeInteger(throughSeq))
5546
- throw new Error("Invalid seq upper bound");
5547
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e4)
5548
- throw new Error("Invalid page limit");
5549
- const rawTypes = RAW_MESSAGE_TYPES.map(() => "?").join(", ");
5550
- return this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
5551
- WHERE session_id = ? AND type IN (${rawTypes}) AND seq <= ?
5552
- ORDER BY seq DESC LIMIT ?`).all(sessionID, ...RAW_MESSAGE_TYPES, throughSeq, limit).map(decode);
5553
- });
5554
- }
5555
- sequenceForId(sessionID, id) {
5556
- if (!id)
5557
- return;
5558
- const row = this.prepare("SELECT seq FROM session_message WHERE session_id = ? AND id = ? LIMIT 1").get(sessionID, id);
5559
- return typeof row?.seq === "number" ? row.seq : undefined;
5560
- }
5561
- syntheticMessageIDs(sessionID) {
5562
- const rows = this.prepare("SELECT id FROM session_message WHERE session_id = ? AND type = 'synthetic'").all(sessionID);
5563
- return new Set(rows.map((row) => row.id));
5564
- }
5565
- forkOrigin(sessionID) {
5566
- const columns = new Set(this.prepare("PRAGMA table_info(session_v2)").all().map((column) => column.name));
5567
- if (!columns.has("fork_session_id") || !columns.has("fork_boundary"))
5568
- return null;
5569
- const row = this.prepare("SELECT fork_session_id, fork_boundary FROM session_v2 WHERE id = ?").get(sessionID);
5570
- if (!row?.fork_session_id || !row.fork_boundary)
5571
- return null;
5572
- try {
5573
- const boundary = JSON.parse(row.fork_boundary);
5574
- if (boundary.type !== "before" && boundary.type !== "through" || typeof boundary.messageID !== "string" || boundary.messageID.length === 0)
5575
- return null;
5576
- return {
5577
- parentSessionID: row.fork_session_id,
5578
- boundary: { type: boundary.type, messageID: boundary.messageID }
5579
- };
5580
- } catch {
5581
- return null;
5582
- }
5583
- }
5584
- sessionExists(sessionID) {
5585
- return this.prepare("SELECT 1 FROM session_v2 WHERE id = ?").get(sessionID) != null;
5586
- }
5587
- rowStampsThrough(sessionID, throughSeq) {
5588
- return this.prepare(`SELECT id, type, seq, time_created FROM session_message
5589
- WHERE session_id = ? AND seq <= ? ORDER BY seq ASC`).all(sessionID, throughSeq);
5590
- }
5591
- latestSequenceForIds(sessionID, ids) {
5592
- let latest = -1;
5593
- for (let offset = 0;offset < ids.length; offset += 500) {
5594
- const chunk = ids.slice(offset, offset + 500);
5595
- const row = this.prepare(`SELECT MAX(seq) AS seq FROM session_message
5596
- WHERE session_id = ? AND id IN (${chunk.map(() => "?").join(", ")})`).get(sessionID, ...chunk);
5597
- if (typeof row?.seq === "number")
5598
- latest = Math.max(latest, row.seq);
5599
- }
5600
- return latest;
5601
- }
5602
- compactionByStatus(sessionID, status) {
5603
- const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
5604
- WHERE session_id = ? AND type = 'compaction'
5605
- AND json_extract(data, '$.status') = ?
5606
- ORDER BY seq DESC LIMIT 1`).get(sessionID, status);
5607
- return row ? decode(row) : undefined;
5608
- }
5609
- latestCompaction(sessionID) {
5610
- return trackDecodeOperation("latestCompaction", () => this.compactionByStatus(sessionID, "completed"));
5611
- }
5612
- latestRunningCompaction(sessionID) {
5613
- return trackDecodeOperation("latestRunningCompaction", () => this.compactionByStatus(sessionID, "running"));
5614
- }
5615
- idleRows(sessionID, after = -1) {
5616
- return trackDecodeOperation("idleRows", () => this.all(sessionID, after, "idle"));
5617
- }
5618
- earliestSequence(sessionID) {
5619
- const row = this.prepare("SELECT MIN(seq) AS seq FROM session_message WHERE session_id = ?").get(sessionID);
5620
- return typeof row?.seq === "number" ? row.seq : undefined;
5621
- }
5622
- latestSequence(sessionID) {
5623
- const row = this.prepare("SELECT MAX(seq) AS seq FROM session_message WHERE session_id = ?").get(sessionID);
5624
- return typeof row?.seq === "number" ? row.seq : -1;
5625
- }
5626
- assistantSince(sessionID, afterSeq) {
5627
- return trackDecodeOperation("assistantSince", () => {
5628
- const rows = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
5629
- WHERE session_id = ? AND type = 'assistant' AND seq > ?
5630
- ORDER BY seq ASC`).all(sessionID, afterSeq);
5631
- return rows.map((row) => decode(row));
5632
- });
5633
- }
5634
- latestAssistant(sessionID) {
5635
- return trackDecodeOperation("latestAssistant", () => {
5636
- const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
5637
- WHERE session_id = ? AND type = 'assistant'
5638
- ORDER BY seq DESC LIMIT 1`).get(sessionID);
5639
- return row ? decode(row) : undefined;
5640
- });
5641
- }
5642
- latestIdle(sessionID) {
5643
- return trackDecodeOperation("latestIdle", () => {
5644
- const row = this.prepare(`SELECT id, session_id, type, seq, time_created, data FROM session_message
5645
- WHERE session_id = ? AND type = 'idle'
5646
- ORDER BY seq DESC LIMIT 1`).get(sessionID);
5647
- return row ? decode(row) : undefined;
5648
- });
5649
- }
5650
- window(sessionID) {
5651
- return trackDecodeOperation("window", () => this.db.transaction(() => {
5652
- const cut = this.latestCompaction(sessionID);
5653
- return this.all(sessionID, cut ? cut.seq - 1 : -1);
5654
- }).deferred());
5655
- }
5656
- history(sessionID) {
5657
- return trackDecodeOperation("history", () => this.all(sessionID, -1));
5658
- }
5659
- all(sessionID, after, type, through) {
5660
- const rows = [];
5661
- for (;; ) {
5662
- const page = this.page(sessionID, { after, through, type });
5663
- rows.push(...page.rows);
5664
- if (page.rows.length < 100 || page.cursor === undefined)
5665
- return rows;
5666
- after = page.cursor;
5667
- }
5668
- }
5669
- }
5670
-
5671
4985
  // src/features/magic-context/resolve-subagent-fallback.ts
5672
4986
  function resolveIsSubagentFromOpenCodeDb(sessionId) {
5673
4987
  try {
@@ -5744,17 +5058,48 @@ function findSessionMeta(db, sessionId) {
5744
5058
  const result = db.prepare(`SELECT ${getSessionMetaSelectColumns(db)} FROM session_meta WHERE session_id = ?`).get(sessionId);
5745
5059
  return isSessionMetaRow(result) ? toSessionMeta(result) : undefined;
5746
5060
  }
5061
+ var parentReadRetries = new WeakMap;
5062
+ var PARENT_READ_ATTEMPTS = 5;
5063
+ var PARENT_READ_COOLDOWN_MS = 30000;
5747
5064
  function getOrCreateSessionMeta(db, sessionId) {
5748
5065
  const existing = findSessionMeta(db, sessionId);
5749
- if (existing)
5750
- return existing;
5751
- const defaults = getDefaultSessionMeta(sessionId);
5752
5066
  const harness = getHarness2();
5067
+ if (existing) {
5068
+ if (harness !== "opencode2")
5069
+ return existing;
5070
+ const row = db.prepare("SELECT is_subagent FROM session_meta WHERE session_id = ?").get(sessionId);
5071
+ if (row.is_subagent !== null)
5072
+ return existing;
5073
+ }
5074
+ const defaults = existing ?? getDefaultSessionMeta(sessionId);
5075
+ let retries = parentReadRetries.get(db);
5076
+ if (harness === "opencode2") {
5077
+ if (!retries) {
5078
+ retries = new BoundedSessionMap(1000);
5079
+ parentReadRetries.set(db, retries);
5080
+ }
5081
+ const retry = retries.get(sessionId);
5082
+ if (retry && retry.attempts >= PARENT_READ_ATTEMPTS && Date.now() - retry.at < PARENT_READ_COOLDOWN_MS)
5083
+ return defaults;
5084
+ }
5753
5085
  const fallbackSubagent = harness === "opencode" ? resolveIsSubagentFromOpenCodeDb(sessionId) : harness === "opencode2" ? resolveIsSubagentFromOpenCode2Db(sessionId) : null;
5754
5086
  if (fallbackSubagent === true) {
5755
5087
  defaults.isSubagent = true;
5756
5088
  }
5757
- ensureSessionMetaRow(db, sessionId, harness === "opencode2" && fallbackSubagent === true);
5089
+ if (harness === "opencode2") {
5090
+ if (fallbackSubagent === null) {
5091
+ const previous = retries?.get(sessionId);
5092
+ const attempts = previous && Date.now() - previous.at < PARENT_READ_COOLDOWN_MS ? previous.attempts + 1 : 1;
5093
+ retries?.set(sessionId, { attempts, at: Date.now() });
5094
+ ensureSessionMetaRow(db, sessionId, null);
5095
+ return defaults;
5096
+ }
5097
+ retries?.delete(sessionId);
5098
+ ensureSessionMetaRow(db, sessionId, fallbackSubagent);
5099
+ db.prepare("UPDATE session_meta SET is_subagent = ? WHERE session_id = ? AND is_subagent IS NULL").run(fallbackSubagent ? 1 : 0, sessionId);
5100
+ return defaults;
5101
+ }
5102
+ ensureSessionMetaRow(db, sessionId);
5758
5103
  if (harness === "opencode" && fallbackSubagent === true) {
5759
5104
  db.prepare("UPDATE session_meta SET is_subagent = 1 WHERE session_id = ?").run(sessionId);
5760
5105
  }
@@ -5863,14 +5208,18 @@ function clearSession(db, sessionId, rustModuleCleanupAcknowledged = false, perm
5863
5208
  cancelAutoSearchWork(sessionId);
5864
5209
  let transactionStartedAt = 0;
5865
5210
  let clearedMarker = null;
5211
+ let eligibleSessions = 0;
5866
5212
  withoutSqliteTransformPass2(() => withSqliteBackgroundWriter2(() => db.transaction(() => {
5867
5213
  transactionStartedAt = performance.now();
5868
5214
  clearedMarker = getPendingPiCompactionMarkerState(db, sessionId);
5869
- deleteSessionScopedRows(db, [sessionId], undefined, {
5215
+ eligibleSessions = deleteSessionScopedRows(db, [sessionId], undefined, {
5870
5216
  rustModuleCleanupAcknowledged,
5871
- preserveTagRevisionTombstones: !permanentlyDeleted
5217
+ preserveTagRevisionTombstones: !permanentlyDeleted,
5218
+ deferRecoveryFenceCleanup: true
5872
5219
  });
5873
5220
  }).immediate()));
5221
+ if (eligibleSessions > 0)
5222
+ clearLkgRecoveryFence(sessionId);
5874
5223
  if (clearedMarker)
5875
5224
  logPiCompactionMarkerClear(sessionId, clearedMarker, "session-reset");
5876
5225
  clearUnpublishedAutoSearchNoHints(sessionId);
@@ -6033,7 +5382,7 @@ function lkgProviderInputTotal(tokens) {
6033
5382
  return counts.every((count) => Number.isSafeInteger(count) && count >= 0) ? counts.reduce((sum, count) => sum + count, 0) : Number.NaN;
6034
5383
  }
6035
5384
  function identity(slot) {
6036
- return createHash4("sha256").update(JSON.stringify([
5385
+ return createHash3("sha256").update(JSON.stringify([
6037
5386
  slot.capturedAt,
6038
5387
  slot.captureSequence,
6039
5388
  slot.rowVersion,
@@ -6129,7 +5478,7 @@ function clearCapturedLkgMeasurement(sessionId) {
6129
5478
  }
6130
5479
 
6131
5480
  // src/hooks/magic-context/lkg-persist.ts
6132
- import { createHash as createHash5 } from "node:crypto";
5481
+ import { createHash as createHash4 } from "node:crypto";
6133
5482
  function parseStringArray(value) {
6134
5483
  if (typeof value !== "string")
6135
5484
  return null;
@@ -6243,7 +5592,7 @@ function rememberFingerprint(db, sessionId, fingerprint) {
6243
5592
  saved.set(sessionId, fingerprint);
6244
5593
  }
6245
5594
  function slotFingerprint(slot) {
6246
- return createHash5("sha256").update(JSON.stringify([
5595
+ return createHash4("sha256").update(JSON.stringify([
6247
5596
  slot.jsonPrefix,
6248
5597
  slot.inputIdSeq,
6249
5598
  slot.inputContentDigests,
@@ -7357,7 +6706,7 @@ var DIGEST_CHUNK_BYTES = 64 * 1024;
7357
6706
  var digestChunk;
7358
6707
  function lkgContentDigestFromFields(fields) {
7359
6708
  lkgDigestsComputed += 1;
7360
- const hash = createHash6("sha256");
6709
+ const hash = createHash5("sha256");
7361
6710
  digestChunk ??= Buffer.allocUnsafe(DIGEST_CHUNK_BYTES);
7362
6711
  const chunk = digestChunk;
7363
6712
  let offset = 0;
@@ -7420,7 +6769,7 @@ function legacyLkgDigestFromFields(fields) {
7420
6769
  const value = typeof field === "symbol" ? field.description ?? "" : String(field);
7421
6770
  key += `${typeof field}:${value.length}:${value}\x00`;
7422
6771
  }
7423
- return createHash6("sha256").update(key).digest("base64url");
6772
+ return createHash5("sha256").update(key).digest("base64url");
7424
6773
  }
7425
6774
  function legacyLkgContentDigest(message) {
7426
6775
  const fields = flattenContentFields(withoutEmptyUserDiffSummary(message));
@@ -8888,7 +8237,7 @@ class HiddenCompletionRefusal extends Error {
8888
8237
  }
8889
8238
  // src/features/magic-context/dreamer/provider-output-failure.ts
8890
8239
  import { AsyncLocalStorage } from "node:async_hooks";
8891
- import { createHash as createHash7 } from "node:crypto";
8240
+ import { createHash as createHash6 } from "node:crypto";
8892
8241
  var MAX_NEAR_ZERO_OUTPUT_TOKENS = 32;
8893
8242
 
8894
8243
  class DreamerProviderOutputFailureError extends Error {
@@ -8985,12 +8334,45 @@ function providerOutputFailureFromInvalidManifest(messages, responseText, now =
8985
8334
  const resetAt = quotaResetAt(responseText, now);
8986
8335
  if (resetAt === undefined && completion.outputTokens > MAX_NEAR_ZERO_OUTPUT_TOKENS)
8987
8336
  return null;
8988
- const fingerprint = createHash7("sha256").update(normalized).digest("hex").slice(0, 16);
8337
+ const fingerprint = createHash6("sha256").update(normalized).digest("hex").slice(0, 16);
8989
8338
  return new DreamerProviderOutputFailureError(fingerprint, completion.outputTokens, completion.reasoningTokens, responseText, resetAt);
8990
8339
  }
8991
8340
 
8992
8341
  // src/v2/hooks/hidden-child.ts
8993
- import { createHash as createHash8 } from "node:crypto";
8342
+ import { createHash as createHash7 } from "node:crypto";
8343
+
8344
+ // src/shared/historian-cache.ts
8345
+ function withoutHistorianTailCache(body) {
8346
+ const value = JSON.parse(body);
8347
+ if (!value || typeof value.model !== "string" || typeof value.max_tokens !== "number" || !Array.isArray(value.system) || value.system.length === 0 || !value.system.every((part) => part?.type === "text" && typeof part.text === "string") || !value.system.some((part) => part.cache_control) || !Array.isArray(value.messages) || value.cache_control !== undefined)
8348
+ return body;
8349
+ const root = parseTree(body);
8350
+ const property = (node, key) => node?.children?.find((child) => child.children?.[0]?.value === key)?.children?.[1];
8351
+ const removals = [];
8352
+ for (const message of property(root, "messages")?.children ?? []) {
8353
+ for (const block of property(message, "content")?.children ?? []) {
8354
+ if (block.type !== "object")
8355
+ continue;
8356
+ const fields = block.children ?? [];
8357
+ fields.forEach((field, index) => {
8358
+ if (field.children?.[0]?.value !== "cache_control")
8359
+ return;
8360
+ const next = fields[index + 1];
8361
+ const previous = fields[index - 1];
8362
+ removals.push(next ? [field.offset, next.offset] : [
8363
+ previous ? previous.offset + previous.length : field.offset,
8364
+ field.offset + field.length
8365
+ ]);
8366
+ });
8367
+ }
8368
+ }
8369
+ for (const [start, end] of removals.sort((a, b) => b[0] - a[0])) {
8370
+ body = body.slice(0, start) + body.slice(end);
8371
+ }
8372
+ return body;
8373
+ }
8374
+
8375
+ // src/v2/hooks/hidden-child.ts
8994
8376
  var HIDDEN_HISTORIAN_AGENT = "historian";
8995
8377
  var HIDDEN_DREAMER_AGENT = "dreamer-classifier";
8996
8378
  var HIDDEN_CURATE_AGENT = DREAMER_AGENT;
@@ -9154,7 +8536,7 @@ function markerCandidates(text) {
9154
8536
  function textDigest(text) {
9155
8537
  return {
9156
8538
  length: text.length,
9157
- sha256: createHash8("sha256").update(text).digest("hex").slice(0, 16)
8539
+ sha256: createHash7("sha256").update(text).digest("hex").slice(0, 16)
9158
8540
  };
9159
8541
  }
9160
8542
  function firstDifference(a, b) {
@@ -9177,6 +8559,7 @@ class HiddenChildHook {
9177
8559
  childIDs = new Map;
9178
8560
  attempts = new Map;
9179
8561
  active = new Map;
8562
+ cacheWarnings = new Set;
9180
8563
  constructor(note = log2) {
9181
8564
  this.note = note;
9182
8565
  }
@@ -9202,6 +8585,30 @@ class HiddenChildHook {
9202
8585
  owns(sessionID) {
9203
8586
  return this.childIDs.has(sessionID);
9204
8587
  }
8588
+ async cacheRequest(draft) {
8589
+ const attempt = this.active.get(draft.sessionID);
8590
+ if (!this.owns(draft.sessionID) || !attempt || attempt.identity.kind !== "historian" || draft.kind !== "primary" || attempt.request.cacheTail !== "skip")
8591
+ return;
8592
+ if ((attempt.wireRequests ?? 0) > 0)
8593
+ return;
8594
+ attempt.wireRequests = 1;
8595
+ try {
8596
+ const original = await draft.request.clone().text();
8597
+ const body = withoutHistorianTailCache(original);
8598
+ if (body === original)
8599
+ return;
8600
+ const headers = new Headers(draft.request.headers);
8601
+ headers.delete("content-length");
8602
+ draft.request = new Request(draft.request, { body, headers });
8603
+ } catch (error) {
8604
+ if (!this.cacheWarnings.has(draft.sessionID)) {
8605
+ this.cacheWarnings.add(draft.sessionID);
8606
+ try {
8607
+ this.note(`Historian cache optimization skipped for ${draft.sessionID}: ${String(error)}`);
8608
+ } catch {}
8609
+ }
8610
+ }
8611
+ }
9205
8612
  compactionSummary(sessionID, agent) {
9206
8613
  if (!this.owns(sessionID)) {
9207
8614
  if (isChildOfDisposedInstance(sessionID)) {
@@ -9672,14 +9079,14 @@ function throwWithPromptFailure(legacyError, failedAttempts, args, timeoutMs, tr
9672
9079
  });
9673
9080
  throw error;
9674
9081
  }
9675
- async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport) {
9082
+ async function attemptOnce(client, args, timeoutMs, signal, callContext, label, transport, allowModelSuggestions = true) {
9676
9083
  const originalBody = { ...args.body };
9677
9084
  const attemptArgs = copyPromptArgs(args, originalBody);
9678
9085
  try {
9679
9086
  await promptWithTimeout(client, attemptArgs, timeoutMs, signal, transport);
9680
9087
  return;
9681
9088
  } catch (error) {
9682
- if (isNonRetryable(error, signal))
9089
+ if (isNonRetryable(error, signal) || !allowModelSuggestions)
9683
9090
  throw error;
9684
9091
  const suggestion = parseModelSuggestion(error);
9685
9092
  if (!suggestion || !originalBody.model) {
@@ -9707,7 +9114,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
9707
9114
  const explicitPrimaryLabel = baseBody.model?.providerID && baseBody.model.modelID ? `${baseBody.model.providerID}/${baseBody.model.modelID}` : "primary";
9708
9115
  let lastError = null;
9709
9116
  try {
9710
- await attemptOnce(client, baseArgs, timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport);
9117
+ await attemptOnce(client, baseArgs, timeoutMs, options.signal, callContext, explicitPrimaryLabel, options.transport, options.allowModelSuggestions);
9711
9118
  return;
9712
9119
  } catch (error) {
9713
9120
  lastError = error;
@@ -9733,7 +9140,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
9733
9140
  ...fallback?.qualifier ? { variant: fallback.qualifier } : {}
9734
9141
  });
9735
9142
  try {
9736
- await attemptOnce(client, attemptArgs, timeoutMs, options.signal, callContext, label, options.transport);
9143
+ await attemptOnce(client, attemptArgs, timeoutMs, options.signal, callContext, label, options.transport, options.allowModelSuggestions);
9737
9144
  log2(`[${callContext}] fallback succeeded with ${label} (attempt ${i + 2}/${fallbacks.length + 1})`);
9738
9145
  return;
9739
9146
  } catch (error) {
@@ -9751,7 +9158,7 @@ async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
9751
9158
  }
9752
9159
  async function attemptAndValidate(client, args, timeoutMs, signal, callContext, attempt, options) {
9753
9160
  try {
9754
- await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport);
9161
+ await attemptOnce(client, args, timeoutMs, signal, callContext, attempt.label, options.transport, options.allowModelSuggestions);
9755
9162
  } catch (error) {
9756
9163
  throw {
9757
9164
  error,
@@ -10300,9 +9707,9 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
10300
9707
  }
10301
9708
  }
10302
9709
  // src/shared/prompt-surface-runtime.ts
10303
- import { createHash as createHash9 } from "node:crypto";
10304
- import { existsSync as existsSync5, readFileSync as readFileSync6, statSync as statSync6 } from "node:fs";
10305
- import { dirname as dirname4, isAbsolute as isAbsolute3, resolve as resolve3 } from "node:path";
9710
+ import { createHash as createHash8 } from "node:crypto";
9711
+ import { existsSync as existsSync5, readFileSync as readFileSync6, statSync as statSync5 } from "node:fs";
9712
+ import { dirname as dirname4, isAbsolute as isAbsolute3, resolve as resolve2 } from "node:path";
10306
9713
 
10307
9714
  // src/tools/light-descriptions.ts
10308
9715
  var CTX_REDUCE_LIGHT_DESCRIPTION = `Stamp an item as no longer needed for the work ahead. Not a delete: stamping QUEUES it, the item stays readable until Magic Context clears stamped items in one sweep, newest tags are protected, and a cleared item goes to the archive (recent: a [dropped §N§] placeholder; older: removed) recoverable via ctx_expand(tag=N). The question is "does this need to stay on my desk for what comes next?" — a file you keep editing stays, the grep that found it goes. Stamp used reads/searches/outputs, acted-on build/test output, redundant dumps, extracted pasted payloads; keep user messages, your own text, unresolved errors, raw evidence, exact wording that may matter. Look at each tag; never blanket-stamp "1-50". Grammar: "3-5", "1,2,9", "1-5,8,12-15".`;
@@ -10333,12 +9740,12 @@ function promptSurfaceHashMaterial(systemContent, preset = "full") {
10333
9740
  \x00magic-context-prompt-surface:${preset}`;
10334
9741
  }
10335
9742
  function systemPromptFingerprint(systemContent, preset = "full") {
10336
- return createHash9("md5").update(promptSurfaceHashMaterial(systemContent, preset)).digest("hex");
9743
+ return createHash8("md5").update(promptSurfaceHashMaterial(systemContent, preset)).digest("hex");
10337
9744
  }
10338
9745
  var PROMPT_SURFACE_TOOL_ID_SET = new Set(ACTIVE_TOOL_IDS);
10339
9746
  function resolveUserConfigDirectory(options) {
10340
9747
  if (options.userConfigDirectory)
10341
- return resolve3(options.userConfigDirectory);
9748
+ return resolve2(options.userConfigDirectory);
10342
9749
  const sharedBase = cortexKitUserConfigBasePath();
10343
9750
  const shared = detectConfigFile(sharedBase);
10344
9751
  if (shared.format !== "none")
@@ -10365,10 +9772,10 @@ function createPromptSurfaceRuntime(options) {
10365
9772
  const readGuidanceOverride = (configuredPath) => {
10366
9773
  if (!configuredPath)
10367
9774
  return;
10368
- const path = isAbsolute3(configuredPath) ? configuredPath : resolve3(userConfigDirectory, configuredPath);
9775
+ const path = isAbsolute3(configuredPath) ? configuredPath : resolve2(userConfigDirectory, configuredPath);
10369
9776
  let content;
10370
9777
  try {
10371
- if (!statSync6(path).isFile()) {
9778
+ if (!statSync5(path).isFile()) {
10372
9779
  warnOnce(`guidance-not-file:${path}`, `prompt_surface.guidance_override_path (${path}) is not a file; using built-in guidance.`);
10373
9780
  return;
10374
9781
  }
@@ -10734,6 +10141,7 @@ function buildHistorianRepairPrompt(originalPrompt, previousOutput, validationEr
10734
10141
  "Return a corrected full XML response for the same existing state and new messages.",
10735
10142
  "Do not skip any displayed raw ordinal or displayed raw range, even if the message looks trivial.",
10736
10143
  "Every displayed message range must belong to exactly one compartment unless it is intentionally left in one trailing suffix marked by <unprocessed_from>.",
10144
+ "If every message in the chunk is covered by a compartment, nothing is unprocessed: set `<unprocessed_from>` to the chunk's last message index + 1.",
10737
10145
  "",
10738
10146
  "Previous invalid XML:",
10739
10147
  previousOutput
@@ -11018,7 +10426,7 @@ function compareMemorySelectionPriority(left, right) {
11018
10426
  }
11019
10427
 
11020
10428
  // src/features/magic-context/mural/render-trigger.ts
11021
- import { createHash as createHash10 } from "node:crypto";
10429
+ import { createHash as createHash9 } from "node:crypto";
11022
10430
 
11023
10431
  // src/features/magic-context/mural/mural-selection.ts
11024
10432
  var DEFAULT_MURAL_MEMORY_BUDGET = 8000;
@@ -11722,7 +11130,7 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
11722
11130
  return { ...cached.result };
11723
11131
  }
11724
11132
  const plan = planMuralRender(entries);
11725
- const textHash = createHash10("sha256").update(plan.layout.text).digest("hex");
11133
+ const textHash = createHash9("sha256").update(plan.layout.text).digest("hex");
11726
11134
  if (existing && existing.contentHash === textHash && existing.width === plan.width && existing.height === plan.height) {
11727
11135
  return rememberRender(db, projectIdentity, key, existing.image, {
11728
11136
  hasMural: true,
@@ -11911,14 +11319,14 @@ function parseUserMemoryRow(row) {
11911
11319
  }
11912
11320
 
11913
11321
  // src/features/magic-context/compaction-marker.ts
11914
- import { createHash as createHash11 } from "node:crypto";
11915
- import { existsSync as existsSync6, statSync as statSync7 } from "node:fs";
11322
+ import { createHash as createHash10 } from "node:crypto";
11323
+ import { existsSync as existsSync6, statSync as statSync6 } from "node:fs";
11916
11324
  var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
11917
11325
  var ID_PREFIX_HEX_LENGTH = 12;
11918
11326
  var ID_SUFFIX_LENGTH = 14;
11919
11327
  var ID_PREFIX_MASK = (1n << BigInt(ID_PREFIX_HEX_LENGTH * 4)) - 1n;
11920
11328
  function deterministicBase62(seed, length) {
11921
- let value = BigInt(`0x${createHash11("sha256").update(seed).digest("hex")}`);
11329
+ let value = BigInt(`0x${createHash10("sha256").update(seed).digest("hex")}`);
11922
11330
  const chars = Array(length);
11923
11331
  for (let index = length - 1;index >= 0; index -= 1) {
11924
11332
  chars[index] = BASE62_CHARS[Number(value % 62n)];
@@ -11984,7 +11392,7 @@ function runMarkerWriteTransaction(db, site, operation) {
11984
11392
  function markerWalPages(db) {
11985
11393
  try {
11986
11394
  const row = db.prepare("PRAGMA page_size").get();
11987
- const bytes = statSync7(`${getOpenCodeDbPath()}-wal`).size;
11395
+ const bytes = statSync6(`${getOpenCodeDbPath()}-wal`).size;
11988
11396
  return Math.max(0, Math.floor((bytes - 32) / (row.page_size + 24)));
11989
11397
  } catch {
11990
11398
  return null;
@@ -17931,6 +17339,7 @@ async function runHistorianPrompt(args) {
17931
17339
  let handle = null;
17932
17340
  let completion;
17933
17341
  const executor = resolveHiddenCompletionExecutor(args.hiddenCompletionExecutor, client, db, sessionDirectory, "historian");
17342
+ const cacheTail = args.cacheTail ?? (executor.capabilities.harness === "opencode2" ? "skip" : undefined);
17934
17343
  let promptSettled = false;
17935
17344
  let hadUnsettledPrompt = false;
17936
17345
  const startedAt = Date.now();
@@ -18012,6 +17421,7 @@ async function runHistorianPrompt(args) {
18012
17421
  try {
18013
17422
  await promptSyncWithModelSuggestionRetry(client, {
18014
17423
  path: { id: agentSessionId },
17424
+ ...cacheTail !== undefined ? { cacheTail: retryIndex > 0 ? "write" : cacheTail } : {},
18015
17425
  query: { directory: sessionDirectory },
18016
17426
  body: {
18017
17427
  agent: agentId,
@@ -18032,6 +17442,7 @@ async function runHistorianPrompt(args) {
18032
17442
  return executor.attempt(opened, request);
18033
17443
  }, { childSessionId: opened.childSessionId }),
18034
17444
  timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
17445
+ allowModelSuggestions: false,
18035
17446
  fallbackModels: modelOverride ? undefined : fallbackModels,
18036
17447
  callContext: agentId === HISTORIAN_EDITOR_AGENT ? "historian:editor" : "historian"
18037
17448
  });
@@ -18116,7 +17527,7 @@ async function runFallbackHistorianPass(args) {
18116
17527
  const primary = toModelEntry(args.model);
18117
17528
  for (const candidateInput of [
18118
17529
  ...args.fallbackModels ?? [],
18119
- ...args.fallbackModelId ? [{ model: args.fallbackModelId }] : []
17530
+ ...!primary && args.fallbackModelId ? [{ model: args.fallbackModelId }] : []
18120
17531
  ]) {
18121
17532
  const candidate = toModelEntry(candidateInput);
18122
17533
  if (!candidate)
@@ -20492,7 +19903,7 @@ async function runCompartmentAgent(deps) {
20492
19903
  const projectPath = resolveProjectIdentity(directory ?? process.cwd());
20493
19904
  const fallbackWindows = [
20494
19905
  ...(deps.fallbackModels ?? []).map((entry) => toModelEntry(entry)?.model),
20495
- deps.fallbackModelId
19906
+ ...toModelEntry(deps.model) ? [] : [deps.fallbackModelId]
20496
19907
  ].filter((key) => typeof key === "string" && key !== producerModel).map((key) => resolveHistorianProducerWindow(key, deps.historianMaxOutputTokens));
20497
19908
  const promptFit = fitHistorianPrompt({
20498
19909
  window: producerWindow,
@@ -21929,4 +21340,4 @@ async function executeContextRecomp(deps, options = {}) {
21929
21340
  return (await executeContextRecompWithResult(deps, options)).message;
21930
21341
  }
21931
21342
 
21932
- export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getUncoveredCompartmentEndsThrough, providerResponseFailed, isSuccessfulProviderCompletion, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, gaDatabasePath, RAW_MESSAGE_TYPES, V2StoreReaderPool, V2StoreReader, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, queueMemoryMutation, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, withDreamerModelCooldown, providerOutputFailureFromInvalidManifest, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, failedInvocationStatus, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, prepareCompactionMarkerCandidates, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
21343
+ export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getUncoveredCompartmentEndsThrough, providerResponseFailed, isSuccessfulProviderCompletion, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, queueMemoryMutation, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, withDreamerModelCooldown, providerOutputFailureFromInvalidManifest, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, failedInvocationStatus, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, prepareCompactionMarkerCandidates, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };