@cortexkit/opencode-magic-context 0.49.18 → 0.49.20

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 (296) hide show
  1. package/dist/auto-search-worker.js +53 -10
  2. package/dist/chunk-embedding-write-worker.js +30 -23
  3. package/dist/{compaction-marker-candidates-n4krhat4.js → compaction-marker-candidates-b2q30cft.js} +3 -3
  4. package/dist/compaction-marker-candidates-worker.js +2 -2
  5. package/dist/compartment-chunk-embedding-va090as0.js +65 -0
  6. package/dist/config/schema/magic-context.d.ts +6 -6
  7. package/dist/{conflict-warning-hook-4pmz879v.js → conflict-warning-hook-frp3z2wk.js} +9 -8
  8. package/dist/{context-m897gfp9.js → context-mkece1db.js} +460 -135
  9. package/dist/{derive-budgets-zn7yzd2d.js → derive-budgets-pqybnx09.js} +2 -2
  10. package/dist/embedding-backfill-gy3p78py.js +25 -0
  11. package/dist/embedding-worker-process.js +2 -2
  12. package/dist/embedding-worker.js +5 -5
  13. package/dist/features/magic-context/chunk-embedding-writer.d.ts.map +1 -1
  14. package/dist/features/magic-context/compartment-chunk-embedding.d.ts +44 -1
  15. package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
  16. package/dist/features/magic-context/dreamer/classify.d.ts +3 -0
  17. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  18. package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts +11 -0
  19. package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts.map +1 -1
  20. package/dist/features/magic-context/dreamer/map-memories.d.ts +3 -0
  21. package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
  22. package/dist/features/magic-context/dreamer/task-config.d.ts.map +1 -1
  23. package/dist/features/magic-context/dreamer/task-scheduler.d.ts +2 -0
  24. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  25. package/dist/features/magic-context/dreamer/verify.d.ts +3 -0
  26. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  27. package/dist/features/magic-context/memory/embedding-identity.d.ts.map +1 -1
  28. package/dist/features/magic-context/memory/embedding-local.d.ts +1 -0
  29. package/dist/features/magic-context/memory/embedding-local.d.ts.map +1 -1
  30. package/dist/features/magic-context/memory/local-embedding-pooling.d.ts +22 -0
  31. package/dist/features/magic-context/memory/local-embedding-pooling.d.ts.map +1 -0
  32. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  33. package/dist/features/magic-context/message-index.d.ts +2 -0
  34. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  35. package/dist/features/magic-context/migrations.d.ts.map +1 -1
  36. package/dist/features/magic-context/mural/compress-cues.d.ts.map +1 -1
  37. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  38. package/dist/features/magic-context/search.d.ts +27 -0
  39. package/dist/features/magic-context/search.d.ts.map +1 -1
  40. package/dist/features/magic-context/smart-notes/compiler.d.ts.map +1 -1
  41. package/dist/features/magic-context/storage-clone.d.ts.map +1 -1
  42. package/dist/features/magic-context/storage-meta-persisted.d.ts +14 -0
  43. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  44. package/dist/features/magic-context/subagent-token-capture.d.ts +20 -0
  45. package/dist/features/magic-context/subagent-token-capture.d.ts.map +1 -1
  46. package/dist/features/magic-context/user-memory/review-user-memories.d.ts.map +1 -1
  47. package/dist/{history-owner-xp3pngv7.js → history-owner-36wp3mkb.js} +2 -2
  48. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  49. package/dist/hooks/magic-context/auto-embed-session.d.ts.map +1 -1
  50. package/dist/hooks/magic-context/auto-search-hint.d.ts +7 -1
  51. package/dist/hooks/magic-context/auto-search-hint.d.ts.map +1 -1
  52. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  53. package/dist/hooks/magic-context/auto-search-worker-client.d.ts +33 -6
  54. package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
  55. package/dist/hooks/magic-context/auto-search-worker-evaluation.fixture.d.ts +2 -0
  56. package/dist/hooks/magic-context/auto-search-worker-evaluation.fixture.d.ts.map +1 -0
  57. package/dist/hooks/magic-context/cache-busting-signals.d.ts +5 -2
  58. package/dist/hooks/magic-context/cache-busting-signals.d.ts.map +1 -1
  59. package/dist/hooks/magic-context/channel2-delivery.d.ts.map +1 -1
  60. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  61. package/dist/hooks/magic-context/compartment-runner-types.d.ts +5 -0
  62. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  63. package/dist/hooks/magic-context/compartment-trigger.d.ts +1 -1
  64. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  65. package/dist/hooks/magic-context/diagnostic-log-state.d.ts +4 -0
  66. package/dist/hooks/magic-context/diagnostic-log-state.d.ts.map +1 -0
  67. package/dist/hooks/magic-context/execute-reclaim.d.ts +35 -0
  68. package/dist/hooks/magic-context/execute-reclaim.d.ts.map +1 -0
  69. package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
  70. package/dist/hooks/magic-context/hook.d.ts +1 -3
  71. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  72. package/dist/hooks/magic-context/latest-assistant-turn.d.ts +8 -0
  73. package/dist/hooks/magic-context/latest-assistant-turn.d.ts.map +1 -1
  74. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts +5 -0
  75. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
  76. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts +13 -0
  77. package/dist/hooks/magic-context/lkg-recovery-prefix.d.ts.map +1 -1
  78. package/dist/hooks/magic-context/nudge-evaluation-log.d.ts +3 -0
  79. package/dist/hooks/magic-context/nudge-evaluation-log.d.ts.map +1 -0
  80. package/dist/hooks/magic-context/pending-drop-eligibility.d.ts.map +1 -1
  81. package/dist/hooks/magic-context/protected-tail-boundary.d.ts +4 -0
  82. package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
  83. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts.map +1 -1
  84. package/dist/hooks/magic-context/system-date-refresh.d.ts +15 -2
  85. package/dist/hooks/magic-context/system-date-refresh.d.ts.map +1 -1
  86. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  87. package/dist/hooks/magic-context/system-prompt-sticky-date.d.ts +10 -0
  88. package/dist/hooks/magic-context/system-prompt-sticky-date.d.ts.map +1 -0
  89. package/dist/hooks/magic-context/tag-messages.d.ts +2 -0
  90. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  91. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  92. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +23 -6
  93. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  94. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  95. package/dist/{index-bjcnntmz.js → index-0wthn7fp.js} +468 -18
  96. package/dist/{index-kq82mtg0.js → index-11zf2wwc.js} +3 -3
  97. package/dist/{index-b5vqckbw.js → index-153r2q6z.js} +314 -127
  98. package/dist/{index-v8awdgvd.js → index-1pefp8ar.js} +5 -5
  99. package/dist/{v2/server-beht37jy.js → index-1zx2pa5d.js} +1 -1
  100. package/dist/{index-ze7mvk54.js → index-2yhtnfcf.js} +75 -57
  101. package/dist/{index-cf74k5ak.js → index-305y133n.js} +4 -4
  102. package/dist/{index-s734jcsr.js → index-35qc6606.js} +9 -3
  103. package/dist/{index-x4njr8df.js → index-48stjd56.js} +105 -19
  104. package/dist/{index-24jbw52d.js → index-4n7w9rad.js} +6 -6
  105. package/dist/{index-kee4kn5j.js → index-4pnsgvfk.js} +1 -1
  106. package/dist/{v2/server-8cd2j99z.js → index-5kym00ag.js} +32 -13
  107. package/dist/{index-4s3t0nd0.js → index-616rsjrv.js} +2 -2
  108. package/dist/{index-e4xv8890.js → index-67nyj0gy.js} +507 -210
  109. package/dist/{index-6x57ar45.js → index-adk2z5d8.js} +3 -3
  110. package/dist/{index-c5pytzne.js → index-b88dwwrh.js} +1 -1
  111. package/dist/{index-rr2bb45z.js → index-c4b76d4t.js} +2 -2
  112. package/dist/{index-nj7yykkx.js → index-c7phnbvk.js} +1 -1
  113. package/dist/index-cpjk5jd2.js +82 -0
  114. package/dist/{index-6s5941tm.js → index-d6rp4dxh.js} +5 -5
  115. package/dist/{index-s7j8tvhv.js → index-dc8hy95c.js} +69 -17
  116. package/dist/{index-j75v2476.js → index-h7tgn49j.js} +12 -15
  117. package/dist/{index-ke416mdc.js → index-j76ah6d7.js} +2 -2
  118. package/dist/{index-r4nkrs05.js → index-jfh3cktr.js} +4 -4
  119. package/dist/{index-a6mc0v4d.js → index-jmycsey7.js} +3 -3
  120. package/dist/{index-24fezq97.js → index-jr5na10t.js} +4 -4
  121. package/dist/{index-s74zqahq.js → index-kc9pn495.js} +4 -4
  122. package/dist/{index-p5y3k4g7.js → index-nda0zgna.js} +2 -1
  123. package/dist/{index-jn12fvvh.js → index-neb2jaed.js} +3 -3
  124. package/dist/{index-qn7xstt2.js → index-pnjwa6qa.js} +6 -7
  125. package/dist/{index-fgncb0ng.js → index-rmd0069m.js} +11 -11
  126. package/dist/{index-y9f76s3f.js → index-rrv26qjz.js} +1 -1
  127. package/dist/{index-v10f1rjv.js → index-spwjbkc7.js} +1 -1
  128. package/dist/{index-k29z4aqh.js → index-t5pck3ss.js} +1 -1
  129. package/dist/{index-936py2wm.js → index-t7hx3qcb.js} +361 -113
  130. package/dist/{index-s1ex9y6p.js → index-v7r4td4c.js} +464 -79
  131. package/dist/{index-2vxtcb95.js → index-vkc1ca9p.js} +2 -2
  132. package/dist/{index-rmwykbbb.js → index-x4k3f4mf.js} +33 -10
  133. package/dist/{index-bp5083x2.js → index-x9k3mqrf.js} +1 -1
  134. package/dist/{index-n37sebck.js → index-y4a3nhtk.js} +1 -1
  135. package/dist/index.js +57 -50
  136. package/dist/{logger-jm3sqqzr.js → logger-94kew5wm.js} +1 -1
  137. package/dist/{message-fts-rowid-map-17s0dfn4.js → message-fts-rowid-map-22tevnnj.js} +6 -5
  138. package/dist/{message-index-66jv6fh4.js → message-index-5qxcz6h7.js} +16 -15
  139. package/dist/{message-index-bounded-n1frdn85.js → message-index-bounded-n0m0t7tv.js} +16 -15
  140. package/dist/{message-time-backfill-73mmm76q.js → message-time-backfill-0myx7fz3.js} +3 -3
  141. package/dist/migration-worker.js +13 -12
  142. package/dist/{model-resolution-nx97z3x7.js → model-resolution-280gmqvd.js} +1 -1
  143. package/dist/plugin/embedding-bootstrap.d.ts +3 -1
  144. package/dist/plugin/embedding-bootstrap.d.ts.map +1 -1
  145. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  146. package/dist/plugin/messages-transform.d.ts.map +1 -1
  147. package/dist/plugin/rpc-handlers.d.ts +8 -0
  148. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  149. package/dist/plugin/subagent-tool-policy.d.ts +9 -0
  150. package/dist/plugin/subagent-tool-policy.d.ts.map +1 -1
  151. package/dist/plugin/tool-registry.d.ts.map +1 -1
  152. package/dist/{project-embedding-registry-z74mhqkf.js → project-embedding-registry-s2pqgec9.js} +13 -12
  153. package/dist/raw-ordinal-warmup-worker.js +136 -101
  154. package/dist/{read-session-chunk-v06g3vka.js → read-session-chunk-0a8vdyqp.js} +11 -10
  155. package/dist/{read-session-raw-rsc8c7qy.js → read-session-raw-y5cszf0b.js} +4 -3
  156. package/dist/recomp-orchestrator-61vyha9j.js +62 -0
  157. package/dist/{safe-notification-target-1szv1k5k.js → safe-notification-target-mkr9yzvr.js} +2 -2
  158. package/dist/{search-archive-4d53y23e.js → search-archive-8q9s49p5.js} +12 -11
  159. package/dist/{search-nkf271d4.js → search-v1y9ejws.js} +25 -24
  160. package/dist/{send-session-notification-6ve0e8p4.js → send-session-notification-0k6qzydk.js} +7 -6
  161. package/dist/shared/logger.d.ts.map +1 -1
  162. package/dist/shared/model-resolution.d.ts +2 -0
  163. package/dist/shared/model-resolution.d.ts.map +1 -1
  164. package/dist/shared/model-suggestion-retry.d.ts +30 -1
  165. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  166. package/dist/shared/prompt-async-transport.d.ts +3 -0
  167. package/dist/shared/prompt-async-transport.d.ts.map +1 -1
  168. package/dist/shared/rpc-types.d.ts +7 -0
  169. package/dist/shared/rpc-types.d.ts.map +1 -1
  170. package/dist/shared/sqlite.d.ts +1 -1
  171. package/dist/shared/sqlite.d.ts.map +1 -1
  172. package/dist/shared/subagent-runner.d.ts +2 -0
  173. package/dist/shared/subagent-runner.d.ts.map +1 -1
  174. package/dist/shared/worker-shutdown.d.ts +68 -0
  175. package/dist/shared/worker-shutdown.d.ts.map +1 -0
  176. package/dist/shared/worker-shutdown.fixture.d.ts +2 -0
  177. package/dist/shared/worker-shutdown.fixture.d.ts.map +1 -0
  178. package/dist/{sqlite-zf72c52d.js → sqlite-1rpvw2rj.js} +1 -1
  179. package/dist/{storage-memory-y3qmy00r.js → storage-memory-nm7v82mj.js} +2 -2
  180. package/dist/{storage-tags-r7k9tjcv.js → storage-tags-r6nk29n4.js} +5 -5
  181. package/dist/{task-config-x3qmayd2.js → task-config-t6bpyka7.js} +2 -2
  182. package/dist/tools/ctx-expand/rust-mode-tag.test-support.d.ts +15 -0
  183. package/dist/tools/ctx-expand/rust-mode-tag.test-support.d.ts.map +1 -0
  184. package/dist/tools/ctx-expand/tools.d.ts +11 -0
  185. package/dist/tools/ctx-expand/tools.d.ts.map +1 -1
  186. package/dist/tools/ctx-search/tools.d.ts.map +1 -1
  187. package/dist/{transform-postprocess-phase-zpgav0h7.js → transform-postprocess-phase-vtrgb7m6.js} +34 -31
  188. package/dist/v2/auto-search-worker.js +53 -10
  189. package/dist/v2/chunk-embedding-write-worker.js +30 -23
  190. package/dist/v2/{compaction-marker-candidates-ebx3388k.js → compaction-marker-candidates-cfab70cs.js} +3 -3
  191. package/dist/v2/compaction-marker-candidates-worker.js +2 -2
  192. package/dist/v2/compartment-chunk-embedding-nbdqx1td.js +64 -0
  193. package/dist/v2/{context-f2xh7ba4.js → context-cc33tv2z.js} +1259 -404
  194. package/dist/v2/{derive-budgets-2zh4gm2c.js → derive-budgets-knf763tt.js} +3 -3
  195. package/dist/v2/embedding-backfill-yxv2h5mc.js +24 -0
  196. package/dist/v2/embedding-worker-process.js +2 -2
  197. package/dist/v2/embedding-worker.js +5 -5
  198. package/dist/v2/hidden-child-record.d.ts +2 -0
  199. package/dist/v2/hidden-child-record.d.ts.map +1 -1
  200. package/dist/v2/hidden-completion.d.ts +2 -0
  201. package/dist/v2/hidden-completion.d.ts.map +1 -1
  202. package/dist/v2/hidden-model-activity.d.ts +7 -0
  203. package/dist/v2/hidden-model-activity.d.ts.map +1 -0
  204. package/dist/v2/{history-owner-42e16w0n.js → history-owner-ad0crnrn.js} +2 -2
  205. package/dist/v2/hooks/context.d.ts.map +1 -1
  206. package/dist/v2/hooks/generate.d.ts +36 -1
  207. package/dist/v2/hooks/generate.d.ts.map +1 -1
  208. package/dist/v2/hooks/lkg-system.d.ts +35 -4
  209. package/dist/v2/hooks/lkg-system.d.ts.map +1 -1
  210. package/dist/v2/hooks/payload.d.ts +16 -1
  211. package/dist/v2/hooks/payload.d.ts.map +1 -1
  212. package/dist/v2/hooks/tools.d.ts.map +1 -1
  213. package/dist/v2/{logger-7qt02bnb.js → logger-p34mjtja.js} +1 -1
  214. package/dist/v2/{message-fts-rowid-map-wfx67gfd.js → message-fts-rowid-map-dg12wymk.js} +6 -5
  215. package/dist/v2/{message-index-bounded-w3hfm29z.js → message-index-bounded-f4e01xk0.js} +16 -15
  216. package/dist/v2/{message-index-48f7hw7a.js → message-index-ydzrp6y6.js} +16 -15
  217. package/dist/v2/{message-time-backfill-04t0km1z.js → message-time-backfill-ddh8n9gy.js} +3 -3
  218. package/dist/v2/migration-worker.js +13 -12
  219. package/dist/v2/{model-resolution-nx97z3x7.js → model-resolution-280gmqvd.js} +1 -1
  220. package/dist/v2/{project-embedding-registry-gnkj56xp.js → project-embedding-registry-deza9ksw.js} +13 -12
  221. package/dist/v2/raw-ordinal-warmup-worker.js +136 -101
  222. package/dist/v2/{read-session-chunk-zpgmxwte.js → read-session-chunk-8cxfagky.js} +11 -10
  223. package/dist/v2/{read-session-raw-yaegtjzh.js → read-session-raw-1nrrecvx.js} +4 -3
  224. package/dist/v2/recomp-orchestrator-47m4hv5g.js +61 -0
  225. package/dist/v2/{safe-notification-target-qg7n2s77.js → safe-notification-target-khnzg57c.js} +2 -2
  226. package/dist/v2/{search-archive-vv48s2aa.js → search-archive-e80cvc09.js} +12 -11
  227. package/dist/v2/{search-kza414f0.js → search-fjz746zr.js} +25 -24
  228. package/dist/v2/{send-session-notification-3pxn658x.js → send-session-notification-nwvrv34d.js} +7 -6
  229. package/dist/v2/{server-8by8qfec.js → server-0epqaxhd.js} +75 -57
  230. package/dist/v2/{server-pwv4ezb0.js → server-168pb207.js} +1 -1
  231. package/dist/v2/{server-h0410h0v.js → server-1bw1wcbp.js} +1 -1
  232. package/dist/{index-beht37jy.js → v2/server-1zx2pa5d.js} +1 -1
  233. package/dist/v2/{server-a9xqj88f.js → server-230fnbws.js} +4 -4
  234. package/dist/v2/{server-tbe1femw.js → server-29qp8nz4.js} +1 -1
  235. package/dist/v2/{server-tgnbmwah.js → server-3mz2qh5a.js} +1 -1
  236. package/dist/v2/{server-hy3d3vsx.js → server-4nw4fqhr.js} +2 -2
  237. package/dist/v2/{server-qv7f0hhe.js → server-4sxjs6hn.js} +5 -5
  238. package/dist/v2/{server-34kwfsr4.js → server-53eh1r8r.js} +2 -2
  239. package/dist/v2/{server-xj136kt8.js → server-55rgxfrw.js} +9 -3
  240. package/dist/v2/{server-nj659894.js → server-5arr9ecn.js} +2 -2
  241. package/dist/{index-8cd2j99z.js → v2/server-5kym00ag.js} +32 -13
  242. package/dist/v2/{server-2ehj0bw7.js → server-63fqdghs.js} +106 -20
  243. package/dist/v2/{server-f2xf5gcb.js → server-6495nmn9.js} +12 -15
  244. package/dist/v2/{server-qd11g795.js → server-92g7d776.js} +2 -1
  245. package/dist/v2/{server-gpvay0xz.js → server-9x0kmta4.js} +6 -7
  246. package/dist/v2/{server-27gq4mfz.js → server-a3dwxfgd.js} +4 -4
  247. package/dist/v2/{server-6tmj0s7j.js → server-af2pght7.js} +3 -3
  248. package/dist/v2/{server-1wy7b9de.js → server-br1x0tev.js} +3 -3
  249. package/dist/v2/{server-n1prf1g6.js → server-brj8j2gk.js} +2 -2
  250. package/dist/v2/{server-bfpda1tb.js → server-c7dxxsj7.js} +466 -81
  251. package/dist/v2/server-cpjk5jd2.js +82 -0
  252. package/dist/v2/{server-g3qma5c0.js → server-dj7tz4ph.js} +2 -2
  253. package/dist/v2/{server-xhab8jx8.js → server-ej96a39v.js} +33 -10
  254. package/dist/v2/{server-6pmqg9m4.js → server-gyy4k6mf.js} +1 -1
  255. package/dist/v2/{server-a2eqhkxr.js → server-hqzyq8n4.js} +11 -11
  256. package/dist/v2/{server-h1v0pyxb.js → server-j4jnp9b5.js} +468 -18
  257. package/dist/v2/{server-da07v4xp.js → server-k3t06fxr.js} +1 -1
  258. package/dist/v2/{server-1nyybqan.js → server-m91f9m5s.js} +69 -17
  259. package/dist/v2/{server-rmygf5pn.js → server-ne8arh8t.js} +2 -2
  260. package/dist/v2/{server-my7k4eds.js → server-vn2nwcv6.js} +5 -5
  261. package/dist/v2/{server-46neh5fa.js → server-wyawsa88.js} +314 -127
  262. package/dist/v2/{server-zzkj2fch.js → server-xsryvyf6.js} +4 -4
  263. package/dist/v2/{server-n37sebck.js → server-y4a3nhtk.js} +1 -1
  264. package/dist/v2/{server-d04vrx0j.js → server-ygtykank.js} +2 -2
  265. package/dist/v2/server.js +6 -6
  266. package/dist/v2/{sqlite-zf72c52d.js → sqlite-1rpvw2rj.js} +1 -1
  267. package/dist/v2/{storage-memory-y3qmy00r.js → storage-memory-nm7v82mj.js} +2 -2
  268. package/dist/v2/{storage-tags-3wdb8zph.js → storage-tags-ss08kj5r.js} +5 -5
  269. package/dist/v2/store-reader.d.ts +8 -0
  270. package/dist/v2/store-reader.d.ts.map +1 -1
  271. package/dist/v2/{task-config-nvz8mapa.js → task-config-7md27rx8.js} +2 -2
  272. package/dist/v2/{wrapup-orchestrator-psqz7yh0.js → wrapup-orchestrator-639whfhq.js} +32 -31
  273. package/dist/wrapup-orchestrator-mnvt2g8m.js +49 -0
  274. package/package.json +1 -1
  275. package/src/config/index.test.ts +28 -6
  276. package/src/shared/logger.test.ts +42 -1
  277. package/src/shared/logger.ts +11 -13
  278. package/src/shared/model-resolution.test.ts +67 -12
  279. package/src/shared/model-resolution.ts +43 -16
  280. package/src/shared/model-suggestion-retry.test.ts +166 -0
  281. package/src/shared/model-suggestion-retry.ts +165 -14
  282. package/src/shared/prompt-async-transport.test.ts +107 -0
  283. package/src/shared/prompt-async-transport.ts +86 -3
  284. package/src/shared/rpc-types.ts +7 -0
  285. package/src/shared/sqlite-busy-budget-review.test.ts +6 -1
  286. package/src/shared/sqlite.ts +4 -2
  287. package/src/shared/subagent-runner.ts +2 -0
  288. package/src/shared/worker-shutdown-fence.test.ts +87 -0
  289. package/src/shared/worker-shutdown.fixture.ts +25 -0
  290. package/src/shared/worker-shutdown.test.ts +127 -0
  291. package/src/shared/worker-shutdown.ts +160 -0
  292. package/dist/embedding-backfill-fmz50tsy.js +0 -24
  293. package/dist/recomp-orchestrator-ghpk2dtq.js +0 -61
  294. package/dist/v2/embedding-backfill-7c7yr69y.js +0 -23
  295. package/dist/v2/recomp-orchestrator-4vfxej9t.js +0 -60
  296. package/dist/wrapup-orchestrator-s9zc5b00.js +0 -48
@@ -13,7 +13,7 @@ import {
13
13
  compareTaskOrder,
14
14
  buildDreamTaskRuntimeConfigs2,
15
15
  userMemoryCollectionEnabled2
16
- } from "./index-p5y3k4g7.js";
16
+ } from "./index-nda0zgna.js";
17
17
  import {
18
18
  getHarness2,
19
19
  harnessOwnsOpenCodeStore2
@@ -31,7 +31,7 @@ import {
31
31
  log2,
32
32
  sessionLog2,
33
33
  getLoggerDiagnostics2
34
- } from "./index-j75v2476.js";
34
+ } from "./index-h7tgn49j.js";
35
35
  import {
36
36
  resolveOpenCodeDbPath,
37
37
  assertOpenCodeStoreGeneration,
@@ -55,7 +55,7 @@ import {
55
55
  SqliteAcquisitionBusyError2,
56
56
  withAsyncPrivilegedWriter2,
57
57
  indexCoordinationInput2
58
- } from "./index-beht37jy.js";
58
+ } from "./index-1zx2pa5d.js";
59
59
  import {
60
60
  pruneMissingProjectIdentities,
61
61
  shouldSkipHomeProjectMemory,
@@ -71,7 +71,7 @@ import {
71
71
  storedPathBelongsToIdentity,
72
72
  beginBootQuietPeriod,
73
73
  scheduleAfterBootQuiet
74
- } from "./index-2vxtcb95.js";
74
+ } from "./index-vkc1ca9p.js";
75
75
  import {
76
76
  recordSessionProjectIdentity,
77
77
  hasRecordedSessionProjectIdentity,
@@ -81,7 +81,7 @@ import {
81
81
  markGitSweepSuccessAndRelease,
82
82
  parkGitSweepNonIndexable,
83
83
  releaseGitSweepLease
84
- } from "./index-rr2bb45z.js";
84
+ } from "./index-c4b76d4t.js";
85
85
  import {
86
86
  hasTrustedAbsoluteWall,
87
87
  applyProvenInputFloor,
@@ -93,7 +93,7 @@ import {
93
93
  deriveTriggerBudget2,
94
94
  resolveKnownHistorianContextLimit2,
95
95
  resolveHistorianProducerLimits2
96
- } from "./index-v10f1rjv.js";
96
+ } from "./index-spwjbkc7.js";
97
97
  import {
98
98
  resolveModelCalibration,
99
99
  calibrateBuckets,
@@ -107,7 +107,7 @@ import {
107
107
  estimateTokens,
108
108
  estimateFixedPromptTokens,
109
109
  normalizeText
110
- } from "./index-c5pytzne.js";
110
+ } from "./index-b88dwwrh.js";
111
111
  import {
112
112
  protectedToolTokenCount,
113
113
  peelLeadingMcTagNotation,
@@ -144,11 +144,11 @@ import {
144
144
  getDroppedTagsByNumbers2,
145
145
  getMaxDroppedTagNumber2,
146
146
  getTagById2
147
- } from "./index-cf74k5ak.js";
147
+ } from "./index-305y133n.js";
148
148
  import {
149
149
  observeTemporalDecisions,
150
150
  stableStringify
151
- } from "./index-bp5083x2.js";
151
+ } from "./index-x9k3mqrf.js";
152
152
  import {
153
153
  withContentLanguageDirective,
154
154
  parseCron,
@@ -168,7 +168,7 @@ import {
168
168
  buildInMemoryTailRawMessages2,
169
169
  RawOrdinalsNotReady2,
170
170
  runSessionWarmupWorker
171
- } from "./index-s734jcsr.js";
171
+ } from "./index-35qc6606.js";
172
172
  import {
173
173
  openCodeDbExists,
174
174
  withReadOnlySessionDb,
@@ -176,7 +176,7 @@ import {
176
176
  latestPersistedMessageForRecovery,
177
177
  latestRealUserTurnIdFromOpenCodeDb,
178
178
  findLastAssistantModelFromOpenCodeDb
179
- } from "./index-kq82mtg0.js";
179
+ } from "./index-11zf2wwc.js";
180
180
  import {
181
181
  expandToolPart,
182
182
  takeCoveredInstructionRows,
@@ -300,10 +300,10 @@ import {
300
300
  readRawSessionMessageById2,
301
301
  readSessionChunk2,
302
302
  readRawSessionSeedTail2
303
- } from "./index-rmwykbbb.js";
303
+ } from "./index-x4k3f4mf.js";
304
304
  import {
305
305
  getMeasuredToolDefinitionTokens
306
- } from "./index-ke416mdc.js";
306
+ } from "./index-j76ah6d7.js";
307
307
  import {
308
308
  isFailClosedBlockingError,
309
309
  shouldBypassFailClosedBlock,
@@ -317,14 +317,14 @@ import {
317
317
  runSqliteOptimize,
318
318
  openDatabase,
319
319
  openCurrentDatabase
320
- } from "./index-fgncb0ng.js";
320
+ } from "./index-rmd0069m.js";
321
321
  import {
322
322
  registerOwnRpcServerInstance,
323
323
  rpcPortDir,
324
324
  rpcPortFilePath,
325
325
  parseRpcPortFile,
326
326
  inspectProcessesAsync
327
- } from "./index-nj7yykkx.js";
327
+ } from "./index-c7phnbvk.js";
328
328
  import {
329
329
  configureContextDatabasePragmas2
330
330
  } from "./index-fb3zxn06.js";
@@ -336,7 +336,7 @@ import {
336
336
  resolveStoredPathWorkspaceIdentity,
337
337
  storedPathBelongsToWorkspace,
338
338
  computeWorkspaceEpochFingerprint
339
- } from "./index-qn7xstt2.js";
339
+ } from "./index-pnjwa6qa.js";
340
340
  import {
341
341
  V2_MEMORY_CATEGORIES,
342
342
  CATEGORY_PRIORITY
@@ -397,6 +397,8 @@ import {
397
397
  hasProcessLocalLkgProof,
398
398
  lkgDirtyRevision,
399
399
  rememberLkgDirtyRevision,
400
+ readPersistedLkgUntaggedInputIds,
401
+ persistLkgUntaggedInputIds,
400
402
  noteLkgRecoveryPrefix,
401
403
  readLkgRecoveryPrefix,
402
404
  noteLkgHealthyPrefix,
@@ -440,6 +442,7 @@ import {
440
442
  raceWithSignal,
441
443
  promptSyncWithValidatedOutputRetry,
442
444
  normalizeSDKResponse,
445
+ annotateSubagentInvocationError,
443
446
  failedInvocationStatus,
444
447
  sumTokensFromChildMessages,
445
448
  recordChildInvocation,
@@ -509,7 +512,7 @@ import {
509
512
  snapRangeToCompartments,
510
513
  getActiveCompartmentRun,
511
514
  startCompartmentAgent
512
- } from "./index-s1ex9y6p.js";
515
+ } from "./index-v7r4td4c.js";
513
516
  import {
514
517
  embedPauseBySession,
515
518
  embedRunStateBySession,
@@ -537,7 +540,7 @@ import {
537
540
  embedSessionCompartmentChunks2,
538
541
  getEmbeddingCoverageStatus2,
539
542
  getAutoEmbeddingSessionCoverage2
540
- } from "./index-ze7mvk54.js";
543
+ } from "./index-2yhtnfcf.js";
541
544
  import {
542
545
  SubcClient,
543
546
  connectionFileExists,
@@ -545,11 +548,12 @@ import {
545
548
  toSynapseLaneDescriptor,
546
549
  formatSynapseLaneDescriptor,
547
550
  SynapseEmbeddingProvider
548
- } from "./index-6x57ar45.js";
551
+ } from "./index-adk2z5d8.js";
549
552
  import {
550
553
  BoundedSessionMap,
551
554
  LkgRecoveryFenceError,
552
555
  lkgServedArrayDigest,
556
+ takeLkgRecoveryLockSweepPage,
553
557
  hasCleanLkgRecoveryFence,
554
558
  dirtyLkgRecoveryRevision,
555
559
  ownsLkgDirtyFence,
@@ -567,7 +571,7 @@ import {
567
571
  indexSingleMessage2,
568
572
  indexMessagesAfterOrdinal2,
569
573
  sweepOrphanedOpenCodeMessageIndexesCooperatively2
570
- } from "./index-x4njr8df.js";
574
+ } from "./index-48stjd56.js";
571
575
  import {
572
576
  renderUserFacingFailure,
573
577
  userFacingFailureCode,
@@ -611,7 +615,7 @@ import {
611
615
  readGitFileChangeTimesSince,
612
616
  verificationFileExists,
613
617
  normalizeVerificationFiles
614
- } from "./index-v8awdgvd.js";
618
+ } from "./index-1pefp8ar.js";
615
619
  import {
616
620
  registerNotificationSink2,
617
621
  pushNotification2,
@@ -620,8 +624,10 @@ import {
620
624
  isTuiConnected2
621
625
  } from "./index-x8a7jmkh.js";
622
626
  import {
627
+ getCachedLocalEmbeddingPooling,
628
+ preflightLocalEmbeddingPooling,
623
629
  getLocalEmbeddingNativeMemoryStats
624
- } from "./index-bjcnntmz.js";
630
+ } from "./index-0wthn7fp.js";
625
631
  import {
626
632
  saveEmbeddingIfHashMatches,
627
633
  invalidateProject2,
@@ -629,7 +635,7 @@ import {
629
635
  } from "./index-4dhv7mqz.js";
630
636
  import {
631
637
  cosineSimilarity
632
- } from "./index-24fezq97.js";
638
+ } from "./index-jr5na10t.js";
633
639
  import {
634
640
  computeCueContentHash,
635
641
  hasMuralCueColumns,
@@ -654,7 +660,7 @@ import {
654
660
  mergeMemoryStats2,
655
661
  archiveMemory2,
656
662
  getMemoryCountsByStatus2
657
- } from "./index-n37sebck.js";
663
+ } from "./index-y4a3nhtk.js";
658
664
  import {
659
665
  renderSingleStoreMigrationRequiredRefusal,
660
666
  SingleStoreMigrationRequiredError,
@@ -675,17 +681,17 @@ import {
675
681
  resolveMemoriesByIdsForSearch2,
676
682
  unifiedSearch2,
677
683
  formatSearchResults2
678
- } from "./index-s7j8tvhv.js";
684
+ } from "./index-dc8hy95c.js";
679
685
  import {
680
686
  flushIgnoredMessages2,
681
687
  clearIgnoredMessages2,
682
688
  observeIgnoredNotificationEvent2,
683
689
  sendStatusNotification2
684
- } from "./index-s74zqahq.js";
690
+ } from "./index-kc9pn495.js";
685
691
  import {
686
692
  setRecompStarting2,
687
693
  setRecompTerminal2
688
- } from "./index-r4nkrs05.js";
694
+ } from "./index-jfh3cktr.js";
689
695
  import {
690
696
  makeToolCompositeKey,
691
697
  searchMessageHistoryOffThread,
@@ -702,10 +708,17 @@ import {
702
708
  cachedToolPermissionDenied,
703
709
  resolveTodowriteAvailabilityFromMessages,
704
710
  resolveTodowriteAvailability,
711
+ diagnosticStateChanged,
712
+ clearDiagnosticLogState,
705
713
  canConsumeDeferredOnThisPass,
706
714
  hasReclaimRide,
707
715
  reclaimRidePermitted,
708
716
  reclaimRideLabel,
717
+ pendingDropEligibilityKey,
718
+ createPendingDropEligibilityCache,
719
+ readExecuteReclaimState,
720
+ writeExecuteReclaimState,
721
+ maintainExecuteFloorMark,
709
722
  captureOpencodeReasoningBudgetStatus,
710
723
  reasoningBudgetStatusLine,
711
724
  ENGINE_RECONNECTING_USER_MESSAGE,
@@ -722,8 +735,6 @@ import {
722
735
  replayCavemanCompression,
723
736
  DegradedPassRefusalError,
724
737
  degradedPassError,
725
- pendingDropEligibilityKey,
726
- createPendingDropEligibilityCache,
727
738
  applyFlushedStatuses,
728
739
  prewarmTagOwners,
729
740
  waitForTagOwners,
@@ -732,6 +743,7 @@ import {
732
743
  logTransformTiming,
733
744
  hasRecentAssistantCommit,
734
745
  tagMessages,
746
+ servesThinkingBlock2,
735
747
  rustModeServedKeyAfterPersistedStrips2,
736
748
  replayRustModeBindingMismatchStrips2,
737
749
  clearRustModeBoundaryRecord2,
@@ -740,7 +752,7 @@ import {
740
752
  abortSessionFailClosed2,
741
753
  evaluateEmergencyFailClosed2,
742
754
  runPostTransformPhase2
743
- } from "./index-e4xv8890.js";
755
+ } from "./index-67nyj0gy.js";
744
756
  import {
745
757
  ANNOUNCEMENT_VERSION2,
746
758
  ANNOUNCEMENT_FEATURES2,
@@ -753,7 +765,7 @@ import {
753
765
  } from "./index-fmsr7v69.js";
754
766
  import {
755
767
  renderSearchArchiveOffThread2
756
- } from "./index-6s5941tm.js";
768
+ } from "./index-d6rp4dxh.js";
757
769
  import {
758
770
  COMPACTION_ENABLED_PATH,
759
771
  isDreamerRunnable,
@@ -783,7 +795,7 @@ import {
783
795
  } from "./index-8ajstryz.js";
784
796
  import {
785
797
  logSlowWriteTransaction
786
- } from "./index-k29z4aqh.js";
798
+ } from "./index-t5pck3ss.js";
787
799
  import {
788
800
  shouldEnforcePrivateStoragePermissions,
789
801
  ensureStorageDirectorySync,
@@ -2694,7 +2706,9 @@ async function compressOneChunk(args, chunk, sliceMs, signal) {
2694
2706
  status: "completed",
2695
2707
  tokens: run.output.usage,
2696
2708
  providerId: run.output.providerId,
2697
- modelId: run.output.modelId
2709
+ modelId: run.output.modelId,
2710
+ attemptedModel: args.model,
2711
+ configuredModels: args.fallbackModels
2698
2712
  });
2699
2713
  }
2700
2714
  stage = "apply";
@@ -2861,6 +2875,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
2861
2875
  }
2862
2876
 
2863
2877
  // src/features/magic-context/dreamer/hidden-single-shot.ts
2878
+ var DREAMER_FIRST_OUTPUT_TIMEOUT_MS = 90000;
2864
2879
  async function runHiddenSingleShotPrompt(args) {
2865
2880
  const system = withContentLanguageDirective(args.system, args.language);
2866
2881
  const opening = args.executor.open({
@@ -2885,6 +2900,7 @@ async function runHiddenSingleShotPrompt(args) {
2885
2900
  });
2886
2901
  }).catch(() => {});
2887
2902
  const handle = await raceWithSignal(opening, args.signal);
2903
+ let completion;
2888
2904
  args.onOpened?.(handle.id);
2889
2905
  let promptSettled = false;
2890
2906
  try {
@@ -2902,10 +2918,14 @@ async function runHiddenSingleShotPrompt(args) {
2902
2918
  }, {
2903
2919
  transport: Object.assign((request) => args.executor.attempt(handle, request), { childSessionId: handle.childSessionId }),
2904
2920
  timeoutMs: args.timeoutMs,
2921
+ ...args.firstOutputTimeoutMs !== undefined ? { firstOutputTimeoutMs: args.firstOutputTimeoutMs } : {},
2905
2922
  ...args.signal ? { signal: args.signal } : {},
2906
2923
  fallbackModels: args.fallbackModels,
2907
2924
  callContext: args.callContext,
2908
- fetchOutput: () => args.executor.collect(handle, 50),
2925
+ fetchOutput: async () => {
2926
+ completion = await args.executor.collect(handle, 50);
2927
+ return completion;
2928
+ },
2909
2929
  validateOutput: (completion) => {
2910
2930
  const tokens = completion.tokenLog ?? runTokenLog(undefined);
2911
2931
  sessionLog2(args.parentSessionId ?? "dreamer", `${args.callContext} response_chars=${(completion.text ?? completion.reasoning ?? "").length} ${formatRunTokenLog(tokens)}`);
@@ -2921,6 +2941,12 @@ async function runHiddenSingleShotPrompt(args) {
2921
2941
  promptSettled = true;
2922
2942
  return { validated: run.validated, completion: run.output, childSessionId: handle.id };
2923
2943
  } catch (error) {
2944
+ const configuredModel = toModelEntry(args.model);
2945
+ annotateSubagentInvocationError(error, {
2946
+ attemptedModel: completion?.attemptedModel ?? handle.attemptedModel ?? configuredModel?.model,
2947
+ modelConfigKey: completion?.modelConfigKey ?? handle.modelConfigKey ?? configuredModel?.sourceConfigKey,
2948
+ ...completion?.hostError === undefined ? {} : { hostError: completion.hostError }
2949
+ });
2924
2950
  if (args.onFailureOutput) {
2925
2951
  let timer;
2926
2952
  try {
@@ -3049,6 +3075,8 @@ If no promotions are warranted, return empty arrays. Always consume reviewed can
3049
3075
  startedAt,
3050
3076
  status: params.status,
3051
3077
  messages: params.messages,
3078
+ attemptedModel: args.model,
3079
+ configuredModels: args.fallbackModels,
3052
3080
  error: params.error
3053
3081
  });
3054
3082
  };
@@ -3556,6 +3584,7 @@ async function classifyOneChunk(args, chunk, anchors, sliceMs, signal) {
3556
3584
  }, {
3557
3585
  transport: Object.assign((request) => executor.attempt(opened, request), { childSessionId: opened.childSessionId }),
3558
3586
  timeoutMs: sliceMs,
3587
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
3559
3588
  signal,
3560
3589
  fallbackModels: args.fallbackModels,
3561
3590
  callContext: "dreamer:classify-memories",
@@ -3835,6 +3864,8 @@ function recordInvocation(args, startedAt, params) {
3835
3864
  startedAt,
3836
3865
  status: params.status,
3837
3866
  messages: params.messages,
3867
+ attemptedModel: args.model,
3868
+ configuredModels: args.fallbackModels,
3838
3869
  ...params.completion && !params.completion.messages ? {
3839
3870
  tokens: params.completion.usage,
3840
3871
  providerId: params.completion.providerId,
@@ -5572,6 +5603,8 @@ Remember: output only the JSON object described by the system prompt.`;
5572
5603
  startedAt,
5573
5604
  status: params.status,
5574
5605
  messages: params.messages,
5606
+ attemptedModel: args.model,
5607
+ configuredModels: args.fallbackModels,
5575
5608
  error: params.error
5576
5609
  });
5577
5610
  };
@@ -6558,6 +6591,8 @@ async function confirmReadOnly(args, noteId, content, surfaceCondition, leaseSig
6558
6591
  startedAt,
6559
6592
  status: params.status,
6560
6593
  messages: params.messages,
6594
+ attemptedModel: args.model,
6595
+ configuredModels: args.fallbackModels,
6561
6596
  error: params.error
6562
6597
  });
6563
6598
  };
@@ -7224,6 +7259,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
7224
7259
  model: args.model,
7225
7260
  fallbackModels: args.fallbackModels,
7226
7261
  timeoutMs: sliceMs,
7262
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
7227
7263
  signal,
7228
7264
  onOpened: () => {
7229
7265
  stage = "prompt";
@@ -7278,6 +7314,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
7278
7314
  onBudgetUpdate
7279
7315
  }),
7280
7316
  timeoutMs: sliceMs,
7317
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
7281
7318
  signal,
7282
7319
  fallbackModels: args.fallbackModels,
7283
7320
  callContext: "dreamer:map-memories",
@@ -7470,12 +7507,14 @@ function recordInvocation2(args, startedAt, params) {
7470
7507
  recordChildInvocation({
7471
7508
  db: args.db,
7472
7509
  parentSessionId: args.parentSessionId,
7473
- harness: "opencode",
7510
+ harness: args.hiddenCompletionExecutor?.capabilities.harness ?? "opencode",
7474
7511
  subagent: "dreamer",
7475
7512
  task: "map-memories",
7476
7513
  startedAt,
7477
7514
  status: params.status,
7478
7515
  messages: params.messages,
7516
+ attemptedModel: args.model,
7517
+ configuredModels: args.fallbackModels,
7479
7518
  error: params.error
7480
7519
  });
7481
7520
  }
@@ -8100,12 +8139,14 @@ function recordInvocation3(args, startedAt, params) {
8100
8139
  recordChildInvocation({
8101
8140
  db: args.db,
8102
8141
  parentSessionId: args.parentSessionId,
8103
- harness: "opencode",
8142
+ harness: args.hiddenCompletionExecutor?.capabilities.harness ?? "opencode",
8104
8143
  subagent: "dreamer",
8105
8144
  task: "refresh-primers",
8106
8145
  startedAt,
8107
8146
  status: params.status,
8108
8147
  messages: params.messages,
8148
+ attemptedModel: args.model,
8149
+ configuredModels: args.fallbackModels,
8109
8150
  error: params.error
8110
8151
  });
8111
8152
  }
@@ -9211,6 +9252,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
9211
9252
  fallbackModels: args.fallbackModels,
9212
9253
  language: args.language,
9213
9254
  timeoutMs: sliceMs,
9255
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
9214
9256
  signal: batchSignal,
9215
9257
  onFailureOutput: (completion) => {
9216
9258
  failedCompletion = completion;
@@ -9268,6 +9310,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
9268
9310
  onBudgetUpdate
9269
9311
  }),
9270
9312
  timeoutMs: sliceMs,
9313
+ firstOutputTimeoutMs: args.firstOutputTimeoutMs ?? DREAMER_FIRST_OUTPUT_TIMEOUT_MS,
9271
9314
  signal: batchSignal,
9272
9315
  fallbackModels: args.fallbackModels,
9273
9316
  callContext: "dreamer:verify",
@@ -9560,12 +9603,14 @@ function recordInvocation4(args, startedAt, params) {
9560
9603
  recordChildInvocation({
9561
9604
  db: args.db,
9562
9605
  parentSessionId: args.parentSessionId,
9563
- harness: "opencode",
9606
+ harness: args.hiddenCompletionExecutor?.capabilities.harness ?? "opencode",
9564
9607
  subagent: "dreamer",
9565
9608
  task: args.forceBroad ? "verify-broad" : "verify",
9566
9609
  startedAt,
9567
9610
  status: params.status,
9568
9611
  messages: params.messages,
9612
+ attemptedModel: args.model,
9613
+ configuredModels: args.fallbackModels,
9569
9614
  error: params.error
9570
9615
  });
9571
9616
  }
@@ -10441,6 +10486,25 @@ async function runRetrospectiveTask(config, ctx, helpers) {
10441
10486
  let childSessionId = null;
10442
10487
  let hiddenHandle = null;
10443
10488
  let promptSettled = false;
10489
+ let invocationRecorded = false;
10490
+ const recordInvocation = (status, messages, error) => {
10491
+ if (!parent || !childSessionId || invocationRecorded)
10492
+ return;
10493
+ invocationRecorded = true;
10494
+ recordChildInvocation({
10495
+ db,
10496
+ parentSessionId: parent,
10497
+ harness: deps.hiddenCompletionExecutor?.capabilities.harness ?? "opencode",
10498
+ subagent: "dreamer",
10499
+ task: config.task,
10500
+ startedAt: helpers.invocationStartedAt,
10501
+ status,
10502
+ messages,
10503
+ attemptedModel: config.model,
10504
+ configuredModels: config.fallbackModels,
10505
+ error
10506
+ });
10507
+ };
10444
10508
  try {
10445
10509
  if (deps.hiddenCompletionExecutor) {
10446
10510
  hiddenHandle = await deps.hiddenCompletionExecutor.open({
@@ -10525,18 +10589,8 @@ async function runRetrospectiveTask(config, ctx, helpers) {
10525
10589
  return { ...run, output };
10526
10590
  };
10527
10591
  const finish = (run, watermark) => {
10528
- if (parent && run) {
10529
- recordChildInvocation({
10530
- db,
10531
- parentSessionId: parent,
10532
- harness: "opencode",
10533
- subagent: "dreamer",
10534
- task: config.task,
10535
- startedAt: helpers.invocationStartedAt,
10536
- status: "completed",
10537
- messages: run.output
10538
- });
10539
- }
10592
+ if (run)
10593
+ recordInvocation("completed", run.output);
10540
10594
  return completedWindow(watermark);
10541
10595
  };
10542
10596
  const userLines = renderGateUserLines(messages);
@@ -10629,6 +10683,7 @@ async function runRetrospectiveTask(config, ctx, helpers) {
10629
10683
  log2(`[dreamer] retrospective: flagged=${flagged.length} learnings=${learnings.length} memory=${applied.memoryWritten} observations=${applied.observationsInserted} dropped=${applied.observationsDropped} rejected=${applied.rejected.length}`);
10630
10684
  return finish(deepenRun, scan.maxScannedTs);
10631
10685
  } catch (error) {
10686
+ recordInvocation(abortController.signal.aborted ? "aborted" : failedInvocationStatus(error), undefined, error);
10632
10687
  if (!detectOverflow(error).isOverflow)
10633
10688
  throw error;
10634
10689
  const failures = (activeOverflow?.failures ?? 0) + 1;
@@ -10700,6 +10755,25 @@ async function runAgenticTask(config, ctx, helpers) {
10700
10755
  let childSessionId = null;
10701
10756
  let promptSettled = false;
10702
10757
  let expiredArchived = 0;
10758
+ let invocationRecorded = false;
10759
+ const recordInvocation = (status, messages, error) => {
10760
+ if (!parent || !childSessionId || invocationRecorded)
10761
+ return;
10762
+ invocationRecorded = true;
10763
+ recordChildInvocation({
10764
+ db,
10765
+ parentSessionId: parent,
10766
+ harness: deps.hiddenCompletionExecutor?.capabilities.harness ?? "opencode",
10767
+ subagent: "dreamer",
10768
+ task,
10769
+ startedAt: invocationStartedAt,
10770
+ status,
10771
+ messages,
10772
+ attemptedModel: config.model,
10773
+ configuredModels: config.fallbackModels,
10774
+ error
10775
+ });
10776
+ };
10703
10777
  try {
10704
10778
  let curateMemories;
10705
10779
  let curateCategory;
@@ -10788,6 +10862,9 @@ async function runAgenticTask(config, ctx, helpers) {
10788
10862
  callContext: `dreamer:${task}`,
10789
10863
  metadata: { tokenBudget: config.tokenBudget, onBudgetUpdate },
10790
10864
  allowEmpty: task === "curate",
10865
+ onOpened: (sessionId) => {
10866
+ childSessionId = sessionId;
10867
+ },
10791
10868
  model: config.model,
10792
10869
  fallbackModels: config.fallbackModels,
10793
10870
  language: task === "curate" ? config.language ?? deps.language : undefined,
@@ -10903,18 +10980,7 @@ async function runAgenticTask(config, ctx, helpers) {
10903
10980
  helpers.reportProgress(curateRefused, curateRefused);
10904
10981
  log2(`[dreamer] curate safety summary: refused=${curateRefused}`);
10905
10982
  }
10906
- if (parent) {
10907
- recordChildInvocation({
10908
- db,
10909
- parentSessionId: parent,
10910
- harness: "opencode",
10911
- subagent: "dreamer",
10912
- task,
10913
- startedAt: invocationStartedAt,
10914
- status: "completed",
10915
- messages: run.output
10916
- });
10917
- }
10983
+ recordInvocation("completed", run.output);
10918
10984
  if (task === "maintain-docs" && docsHashes && changes) {
10919
10985
  try {
10920
10986
  if (run.validated === "[]") {
@@ -10968,6 +11034,9 @@ async function runAgenticTask(config, ctx, helpers) {
10968
11034
  }
10969
11035
  } : {}
10970
11036
  };
11037
+ } catch (error) {
11038
+ recordInvocation(abortController.signal.aborted ? "aborted" : failedInvocationStatus(error), undefined, error);
11039
+ throw error;
10971
11040
  } finally {
10972
11041
  heartbeat.stop();
10973
11042
  if (childSessionId)
@@ -11620,6 +11689,11 @@ async function indexSingleMessageOffThread(db, sessionId, message) {
11620
11689
  return result.inserted;
11621
11690
  }
11622
11691
  async function sweepOrphanedOpenCodeMessageIndexesOffThread(db, openSource, options = {}) {
11692
+ if (getHarness2() === "opencode" || getHarness2() === "opencode2")
11693
+ options = {
11694
+ ...options,
11695
+ fenceLockNames: options.fenceLockNames ?? takeLkgRecoveryLockSweepPage()
11696
+ };
11623
11697
  if (getHarness2() === "opencode2")
11624
11698
  openSource = () => new Database2(gaDatabasePath(getDataDir(), process.env.OPENCODE_CHANNEL ?? "latest"), {
11625
11699
  readonly: true,
@@ -12467,7 +12541,7 @@ function loadRegistrationConfig(directory) {
12467
12541
  configCache.delete(directory);
12468
12542
  return detailed;
12469
12543
  }
12470
- async function ensureProjectRegisteredFromOpenCodeDirectory(directory, db) {
12544
+ async function ensureProjectRegisteredFromOpenCodeDirectory(directory, db, options = {}) {
12471
12545
  const detailed = loadRegistrationConfig(directory);
12472
12546
  const projectIdentity = resolveProjectIdentityForSession(directory, detailed.config.allow_home_project);
12473
12547
  if (!projectIdentity)
@@ -12488,6 +12562,9 @@ async function ensureProjectRegisteredFromOpenCodeDirectory(directory, db) {
12488
12562
  memoryEnabled: detailed.config.memory.enabled,
12489
12563
  gitCommitEnabled: detailed.config.memory.git_commit_indexing.enabled
12490
12564
  };
12565
+ if (options.preflightLocalPooling && routing.primary.provider === "local") {
12566
+ await preflightLocalEmbeddingPooling(routing.primary.model ?? "Xenova/all-MiniLM-L6-v2");
12567
+ }
12491
12568
  const before = getProjectEmbeddingSnapshot2(projectIdentity);
12492
12569
  const registered = registerProjectEmbedding2(db, projectIdentity, routing.primary, features, directory);
12493
12570
  if (!before || before.providerIdentity !== registered.providerIdentity || before.runtimeFingerprint !== registered.runtimeFingerprint)
@@ -13511,6 +13588,14 @@ function getMessageRemovedInfo(properties) {
13511
13588
  };
13512
13589
  }
13513
13590
 
13591
+ // src/hooks/magic-context/nudge-evaluation-log.ts
13592
+ function logNudgeEvaluation(sessionId, phase, line) {
13593
+ const category = `${phase}:${line.split(":", 1)[0]}`;
13594
+ const state = line.split(" ").filter((field) => /^(ctx_reduce|band|dampening|verdict|reason|lease)=/.test(field)).join(" ");
13595
+ if (diagnosticStateChanged(sessionId, category, state))
13596
+ sessionLog2(sessionId, line);
13597
+ }
13598
+
13514
13599
  // src/hooks/magic-context/command-handler.ts
13515
13600
  import { randomUUID as randomUUID2 } from "node:crypto";
13516
13601
 
@@ -13950,7 +14035,7 @@ function resolveBoundaryContextLimit(usage, fallbackContextLimit) {
13950
14035
  }
13951
14036
  return 128000;
13952
14037
  }
13953
- function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, inMemoryTail, taggerFloor = 0) {
14038
+ function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, inMemoryTail, taggerFloor = 0, liftLivePromptFloor = false) {
13954
14039
  return withRawSessionMessageCache2(() => {
13955
14040
  try {
13956
14041
  const memoryPrimed = inMemoryTail ? primeInMemoryTailRawMessageCache2({
@@ -13980,7 +14065,8 @@ function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThr
13980
14065
  executeThresholdPercentage,
13981
14066
  usage,
13982
14067
  usageSource: "live",
13983
- taggerFloor
14068
+ taggerFloor,
14069
+ liftLivePromptFloor
13984
14070
  });
13985
14071
  const hasProtectedEligibleHead = boundary.offset < Math.min(boundary.protectedTailStart, boundary.eligibleEndOrdinal);
13986
14072
  if (!hasProtectedEligibleHead) {
@@ -14016,7 +14102,10 @@ function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThr
14016
14102
  function formatProjectedPostDropPercentage(value) {
14017
14103
  return value === null ? "none" : `${value.toFixed(1)}%`;
14018
14104
  }
14019
- function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPercentage, executeThresholdPercentage, triggerBudget, keepReasoningTokens, commitClusterTrigger, preloadedActiveTags, contextLimit, inMemoryTail, taggerFloorOverride, reasoningProjection, reclaimRide, eligiblePendingDropTagIds) {
14105
+ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPercentage, executeThresholdPercentage, triggerBudget, keepReasoningTokens, commitClusterTrigger, preloadedActiveTags, contextLimit, inMemoryTail, taggerFloorOverride, reasoningProjection, reclaimRide, eligiblePendingDropTagIds, primaryExecute = false) {
14106
+ if (usage.percentage < executeThresholdPercentage) {
14107
+ writeExecuteReclaimState(db, sessionId, { floorOrdinal: null, floorPromptId: null });
14108
+ }
14020
14109
  if (sessionMeta.compartmentInProgress) {
14021
14110
  sessionLog2(sessionId, `compartment trigger: skipped — historian already in progress (usage=${usage.percentage.toFixed(1)}%)`);
14022
14111
  return { shouldFire: false };
@@ -14069,7 +14158,22 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
14069
14158
  resolvedInMemoryTail = undefined;
14070
14159
  }
14071
14160
  }
14072
- const tailInfo = getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, resolvedInMemoryTail, taggerFloor);
14161
+ let tailInfo = getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, resolvedInMemoryTail, taggerFloor);
14162
+ const markState = readExecuteReclaimState(db, sessionId);
14163
+ const mark = markState.floorOrdinal;
14164
+ const livePromptOrdinal = tailInfo.boundarySnapshot?.diagnostics?.livePromptFloor.ordinal;
14165
+ let consumedFloorMark = false;
14166
+ if (mark !== null) {
14167
+ const consumed = writeExecuteReclaimState(db, sessionId, {
14168
+ floorOrdinal: null,
14169
+ floorPromptId: null
14170
+ });
14171
+ if (consumed && mark === livePromptOrdinal && markState.floorPromptId === tailInfo.boundarySnapshot?.diagnostics?.livePromptFloor.messageId && usage.percentage >= executeThresholdPercentage) {
14172
+ consumedFloorMark = true;
14173
+ sessionLog2(sessionId, `compartment trigger: live-prompt floor mark consumed at ${mark}`);
14174
+ tailInfo = getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, resolvedInMemoryTail, taggerFloor, true);
14175
+ }
14176
+ }
14073
14177
  if (!tailInfo.hasNewRawHistory) {
14074
14178
  try {
14075
14179
  const lastCompartmentEnd = getLastCompartmentEndMessage(db, sessionId);
@@ -14153,7 +14257,21 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
14153
14257
  return { shouldFire: false };
14154
14258
  }
14155
14259
  if (!tailInfo.hasProtectedEligibleHead || !tailInfo.isMeaningful) {
14156
- sessionLog2(sessionId, `compartment trigger: not firing at ${usage.percentage.toFixed(1)}% because unsummarized tail from ${tailInfo.nextStartOrdinal} is too small`);
14260
+ let floorOnly = false;
14261
+ const boundary = tailInfo.boundarySnapshot;
14262
+ const floor = boundary?.diagnostics?.livePromptFloor;
14263
+ if (!consumedFloorMark && floor?.ordinal && floor.from > floor.to) {
14264
+ const withoutFloor = getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, resolvedInMemoryTail, taggerFloor, true);
14265
+ floorOnly = withoutFloor.hasProtectedEligibleHead && withoutFloor.isMeaningful;
14266
+ if (floorOnly && primaryExecute && usage.percentage >= executeThresholdPercentage && writeExecuteReclaimState(db, sessionId, {
14267
+ floorOrdinal: floor.ordinal,
14268
+ floorPromptId: floor.messageId ?? null
14269
+ })) {
14270
+ sessionLog2(sessionId, `compartment trigger: live-prompt floor mark set at ${floor.ordinal}`);
14271
+ }
14272
+ }
14273
+ const refusal = floorOnly ? `no eligible head (live-prompt floor at ${floor?.ordinal})` : tailInfo.hasProtectedEligibleHead ? "below meaningfulness" : "no eligible head";
14274
+ sessionLog2(sessionId, `compartment trigger: not firing at ${usage.percentage.toFixed(1)}% — ${refusal}; offset=${tailInfo.nextStartOrdinal} protectedStart=${boundary?.protectedTailStart ?? "none"} eligibleEnd=${boundary?.eligibleEndOrdinal ?? "none"} rawTokens=${tailInfo.trueRawEligibleTokens} chunkTokens=${tailInfo.tokenEstimate}`);
14157
14275
  return { shouldFire: false };
14158
14276
  }
14159
14277
  sessionLog2(sessionId, `compartment trigger: proactive fire at ${usage.percentage.toFixed(1)}% (floor=${proactiveTriggerPercentage}% projected post-drop=${formatProjectedPostDropPercentage(projectedPostDropPercentage)} target=${relativePostDropTarget.toFixed(1)}%)`);
@@ -15147,7 +15265,7 @@ function maybeInjectChannel1Nudge(args, sessionId, tool, output) {
15147
15265
  evaluable: state.evaluable,
15148
15266
  generationInvalidated: state.generationInvalidated
15149
15267
  });
15150
- sessionLog2(sessionId, formatChannel1Evaluation(decision));
15268
+ logNudgeEvaluation(sessionId, "tool-completion", formatChannel1Evaluation(decision));
15151
15269
  setLastNudgeUndropped(args.db, sessionId, decision.nextLastNudge);
15152
15270
  const nextNudgeState = {
15153
15271
  ...nudgeState,
@@ -15969,6 +16087,7 @@ function buildDebugMemoryUsage(runtimeHolders = {}) {
15969
16087
  const lkg = getLkgSlotHeapStats();
15970
16088
  const tagger = runtimeHolders.taggerCache ?? EMPTY_TAGGER_HEAP_STATS;
15971
16089
  const wire = runtimeHolders.wireCache ?? EMPTY_WIRE_HEAP_STATS;
16090
+ const replay = runtimeHolders.generateReplay ?? { totalBytes: 0, sessions: [] };
15972
16091
  const messageIndexQueue = getMessageIndexQueueHeapStats();
15973
16092
  const sessions = new Map;
15974
16093
  const session = (sessionId) => {
@@ -15982,7 +16101,8 @@ function buildDebugMemoryUsage(runtimeHolders = {}) {
15982
16101
  wireRawMessages: 0,
15983
16102
  wireMessages: 0,
15984
16103
  wireContentSnapshots: 0,
15985
- wireEstimatedBytes: 0
16104
+ wireEstimatedBytes: 0,
16105
+ generateReplayBytes: 0
15986
16106
  };
15987
16107
  sessions.set(sessionId, current);
15988
16108
  }
@@ -16002,6 +16122,8 @@ function buildDebugMemoryUsage(runtimeHolders = {}) {
16002
16122
  target.wireContentSnapshots += entry.rawContentSnapshots;
16003
16123
  target.wireEstimatedBytes += entry.estimatedBytes;
16004
16124
  }
16125
+ for (const entry of replay.sessions)
16126
+ session(entry.sessionId).generateReplayBytes += entry.bytes;
16005
16127
  return {
16006
16128
  pid: process.pid,
16007
16129
  bunVersion: typeof Bun !== "undefined" && typeof Bun.version === "string" ? Bun.version : "unavailable",
@@ -16032,6 +16154,10 @@ function buildDebugMemoryUsage(runtimeHolders = {}) {
16032
16154
  estimatedBytes: wire.estimatedBytes
16033
16155
  },
16034
16156
  compartmentMirrors: { entries: 0 },
16157
+ generateReplay: {
16158
+ sessionCount: replay.sessions.length,
16159
+ estimatedBytes: replay.totalBytes
16160
+ },
16035
16161
  messageIndexQueue,
16036
16162
  sessions: [...sessions.values()].sort((a, b) => a.sessionId.localeCompare(b.sessionId))
16037
16163
  }
@@ -16248,9 +16374,9 @@ function registerRpcHandlers(rpcServer, args) {
16248
16374
  return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
16249
16375
  });
16250
16376
  const buildManagedCtx = async (db) => {
16251
- const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-zn7yzd2d.js"));
16252
- const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-nx97z3x7.js"));
16253
- const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-x3qmayd2.js"));
16377
+ const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-pqybnx09.js"));
16378
+ const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-280gmqvd.js"));
16379
+ const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-t6bpyka7.js"));
16254
16380
  const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
16255
16381
  const runConfig = historianRunConfig(config, currentPluginConfigReader(directory)?.poll().effective ?? config);
16256
16382
  const historianModel = resolveHistorianModel(runConfig, "opencode");
@@ -16281,7 +16407,7 @@ function registerRpcHandlers(rpcServer, args) {
16281
16407
  return { ok: false, error: "no session" };
16282
16408
  const readDirectory = args.readSessionDirectory;
16283
16409
  if (readDirectory) {
16284
- const { handoffHistoryWork } = await import("./history-owner-xp3pngv7.js");
16410
+ const { handoffHistoryWork } = await import("./history-owner-36wp3mkb.js");
16285
16411
  const handed = await handoffHistoryWork({
16286
16412
  storageDir: args.storageDir ?? getMagicContextStorageDir(),
16287
16413
  directory,
@@ -16300,8 +16426,8 @@ function registerRpcHandlers(rpcServer, args) {
16300
16426
  const db = readDatabase();
16301
16427
  if (!db)
16302
16428
  return { ok: false, error: "db unavailable" };
16303
- const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-ghpk2dtq.js"));
16304
- const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-6ve0e8p4.js"));
16429
+ const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-61vyha9j.js"));
16430
+ const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-0k6qzydk.js"));
16305
16431
  log2(`[rpc] recomp requested for session ${sessionId}`);
16306
16432
  if (!args.client && !args.hiddenCompletionExecutor) {
16307
16433
  return {
@@ -16359,7 +16485,7 @@ function registerRpcHandlers(rpcServer, args) {
16359
16485
  rpcServer.handle("wrapup", async (params) => {
16360
16486
  const readDirectory = args.readSessionDirectory;
16361
16487
  if (readDirectory && params.sessionId) {
16362
- const { handoffHistoryWork } = await import("./history-owner-xp3pngv7.js");
16488
+ const { handoffHistoryWork } = await import("./history-owner-36wp3mkb.js");
16363
16489
  const sessionId = String(params.sessionId);
16364
16490
  const handed = await handoffHistoryWork({
16365
16491
  storageDir: args.storageDir ?? getMagicContextStorageDir(),
@@ -16385,7 +16511,7 @@ function registerRpcHandlers(rpcServer, args) {
16385
16511
  const db = readDatabase();
16386
16512
  if (!db)
16387
16513
  return { ok: false, error: "db unavailable" };
16388
- const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-s9zc5b00.js"));
16514
+ const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-mnvt2g8m.js"));
16389
16515
  const model = liveSessionState.liveModelBySession.get(sessionId);
16390
16516
  const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
16391
16517
  const ctx = {
@@ -16460,6 +16586,13 @@ function registerRpcHandlers(rpcServer, args) {
16460
16586
  }
16461
16587
 
16462
16588
  // src/hooks/magic-context/auto-embed-session.ts
16589
+ function localPoolingPreflightPending(projectIdentity) {
16590
+ const snapshot = getProjectEmbeddingSnapshot2(projectIdentity);
16591
+ if (snapshot?.provider !== "local")
16592
+ return false;
16593
+ const metadata = getCachedLocalEmbeddingPooling(snapshot.model);
16594
+ return !metadata || metadata.status === "unresolved";
16595
+ }
16463
16596
  function embeddingIdentity(projectIdentity) {
16464
16597
  const snapshot = getProjectEmbeddingSnapshot2(projectIdentity);
16465
16598
  return JSON.stringify([
@@ -16480,7 +16613,8 @@ function maybeAutoEmbedSessionBackfill(deps, sessionId) {
16480
16613
  invalidateAutoEmbedSession(sessionId);
16481
16614
  autoEmbedIdentityBySession.set(sessionId, identity);
16482
16615
  }
16483
- if (autoEmbedAttemptedBySession.has(sessionId) || embedPauseBySession.has(sessionId) || embedRunStateBySession.has(sessionId) || Date.now() < (autoEmbedRetryAfterBySession.get(sessionId) ?? 0))
16616
+ const poolingPreflightPending = localPoolingPreflightPending(deps.projectIdentity);
16617
+ if (embedPauseBySession.has(sessionId) || embedRunStateBySession.has(sessionId) || Date.now() < (autoEmbedRetryAfterBySession.get(sessionId) ?? 0) || autoEmbedAttemptedBySession.has(sessionId) && !poolingPreflightPending)
16484
16618
  return;
16485
16619
  const controller = new AbortController;
16486
16620
  embedRunStateBySession.set(sessionId, controller);
@@ -16490,6 +16624,7 @@ function maybeAutoEmbedSessionBackfill(deps, sessionId) {
16490
16624
  let started = false;
16491
16625
  let reason = "error";
16492
16626
  let registeredIdentity = identity;
16627
+ let poolingPendingAfterRegistration = poolingPreflightPending;
16493
16628
  try {
16494
16629
  await new Promise((resolve) => setTimeout(resolve, 0));
16495
16630
  if (controller.signal.aborted)
@@ -16497,6 +16632,7 @@ function maybeAutoEmbedSessionBackfill(deps, sessionId) {
16497
16632
  await deps.ensureRegistered();
16498
16633
  if (controller.signal.aborted)
16499
16634
  return;
16635
+ poolingPendingAfterRegistration = localPoolingPreflightPending(deps.projectIdentity);
16500
16636
  markActive();
16501
16637
  registeredIdentity = embeddingIdentity(deps.projectIdentity);
16502
16638
  autoEmbedIdentityBySession.set(sessionId, registeredIdentity);
@@ -16504,7 +16640,9 @@ function maybeAutoEmbedSessionBackfill(deps, sessionId) {
16504
16640
  if (controller.signal.aborted || !coverage.enabled)
16505
16641
  return;
16506
16642
  if (coverage.embedded === coverage.total) {
16507
- complete = true;
16643
+ complete = !poolingPendingAfterRegistration;
16644
+ if (!complete)
16645
+ retryDelay = 60000;
16508
16646
  return;
16509
16647
  }
16510
16648
  const model = getProjectEmbeddingSnapshot2(deps.projectIdentity)?.model;
@@ -16513,8 +16651,11 @@ function maybeAutoEmbedSessionBackfill(deps, sessionId) {
16513
16651
  const outcome = await embedSessionCompartmentChunks2(deps.db, deps.projectIdentity, sessionId, { signal: controller.signal, automatic: true });
16514
16652
  reason = outcome.status;
16515
16653
  const after = await getAutoEmbeddingSessionCoverage2(deps.db, deps.projectIdentity, sessionId);
16516
- complete = after.enabled && after.embedded === after.total;
16517
- if (!complete && outcome.status !== "busy" && outcome.status !== "aborted") {
16654
+ complete = after.enabled && after.embedded === after.total && !poolingPendingAfterRegistration;
16655
+ if (poolingPendingAfterRegistration) {
16656
+ retryDelay = 60000;
16657
+ reason = "pooling metadata unavailable";
16658
+ } else if (!complete && outcome.status !== "busy" && outcome.status !== "aborted") {
16518
16659
  retryDelay = 60000;
16519
16660
  if (outcome.status === "nothing" || outcome.status === "done")
16520
16661
  reason = "deferred";
@@ -16921,7 +17062,7 @@ async function maybeDeliverChannel2(sessionId, deps) {
16921
17062
  return false;
16922
17063
  }
16923
17064
  const evaluation = evaluateChannel2(deps.baseline);
16924
- sessionLog2(sessionId, formatChannel2Evaluation(evaluation, { leaseBefore: "pending", leaseAfter: "pending" }));
17065
+ logNudgeEvaluation(sessionId, "delivery", formatChannel2Evaluation(evaluation, { leaseBefore: "pending", leaseAfter: "pending" }));
16925
17066
  if (deps.directiveText === undefined && !evaluation.evaluable) {
16926
17067
  return false;
16927
17068
  }
@@ -20330,6 +20471,7 @@ function beginSystemDateRequest(history, sessionId, stage, turnId, identity) {
20330
20471
  systemDone: false,
20331
20472
  messagesSeen: false,
20332
20473
  permitted: undefined,
20474
+ signedThinkingKept: undefined,
20333
20475
  ambiguous: identity === undefined && (turnId === undefined || sameTurn)
20334
20476
  };
20335
20477
  const blocked = [...requests.values()].filter((candidate) => !candidate.explicit && candidate.ambiguous && !(candidate.systemSeen && candidate.messagesSeen) && candidate.turnId === turnId).length;
@@ -20352,6 +20494,10 @@ function systemDateRefreshPermission(history, request) {
20352
20494
  const current = state(history, request);
20353
20495
  return current?.ambiguous ? undefined : current?.permitted;
20354
20496
  }
20497
+ function systemDateSignedThinkingKept(history, request) {
20498
+ const current = state(history, request);
20499
+ return current?.ambiguous ? undefined : current?.signedThinkingKept;
20500
+ }
20355
20501
  function waitForSystemDateRefresh(history, request, apply) {
20356
20502
  const current = state(history, request);
20357
20503
  if (!current)
@@ -20366,7 +20512,7 @@ function retire(history, current) {
20366
20512
  if (unpairable) {
20367
20513
  const apply = current.waiting;
20368
20514
  current.waiting = undefined;
20369
- apply?.(false);
20515
+ apply?.(false, undefined);
20370
20516
  }
20371
20517
  const channel = channels.get(history);
20372
20518
  const requests = channel?.get(current.sessionId);
@@ -20374,14 +20520,15 @@ function retire(history, current) {
20374
20520
  if (requests?.size === 0)
20375
20521
  channel?.delete(current.sessionId);
20376
20522
  }
20377
- function finishSystemDateRefresh(history, request, permitted) {
20523
+ function finishSystemDateRefresh(history, request, permitted, signedThinkingKept) {
20378
20524
  const current = state(history, request);
20379
20525
  if (!current)
20380
20526
  return;
20381
20527
  current.permitted = current.ambiguous ? false : permitted;
20528
+ current.signedThinkingKept = current.ambiguous ? undefined : signedThinkingKept;
20382
20529
  const apply = current.waiting;
20383
20530
  current.waiting = undefined;
20384
- apply?.(current.permitted);
20531
+ apply?.(current.permitted, current.signedThinkingKept);
20385
20532
  retire(history, current);
20386
20533
  }
20387
20534
  function finishSystemDateHook(history, request) {
@@ -23878,8 +24025,8 @@ async function runCompartmentPhaseImpl(args) {
23878
24025
  }
23879
24026
  return "completed";
23880
24027
  }
23881
- if (!historianRunnable && args.sessionMeta.compartmentInProgress) {
23882
- sessionLog2(args.sessionId, "transform: historian disabled; clearing stale compartmentInProgress flag");
24028
+ if ((!historianRunnable || !args.canRunCompartments && !getActiveCompartmentRun(args.sessionId)) && args.sessionMeta.compartmentInProgress) {
24029
+ sessionLog2(args.sessionId, "transform: historian unavailable; clearing stale compartmentInProgress flag");
23883
24030
  updateSessionMeta(args.db, args.sessionId, { compartmentInProgress: false });
23884
24031
  compartmentInProgress = false;
23885
24032
  }
@@ -24139,8 +24286,10 @@ function createTransform(deps) {
24139
24286
  const loadedSessions = new Set;
24140
24287
  const prefixHoldLogTurnIds = new Map;
24141
24288
  const thinkingFitRetries = new Set;
24289
+ const compactionModeTransitionPending = new Set;
24142
24290
  const clearSessionLogState = (sessionId) => {
24143
24291
  prefixHoldLogTurnIds.delete(sessionId);
24292
+ clearDiagnosticLogState(sessionId);
24144
24293
  };
24145
24294
  const unmanagedOverWindowSessions = new Set;
24146
24295
  const rustModeTransform = deps.transformMode === "rust" && deps.rustModeModuleClient ? createRustModeTransform(deps, {
@@ -24189,6 +24338,11 @@ function createTransform(deps) {
24189
24338
  const tLkgEntry = performance.now();
24190
24339
  const lkgInput = deps.transformMode === "rust" ? [] : projectEntry(sessionId, messages);
24191
24340
  const recovery = deps.compactionOff || deps.transformMode === "rust" ? {} : readLkgRecoveryPrefix(sessionId, lkgInput, messages, deps.db);
24341
+ const persistedUntaggedInputIds = deps.compactionOff || deps.transformMode === "rust" ? [] : readPersistedLkgUntaggedInputIds(deps.db, sessionId);
24342
+ const untaggedReplayIds = new Set([
24343
+ ...recovery.prefix?.untaggedInputIds ?? [],
24344
+ ...persistedUntaggedInputIds
24345
+ ]);
24192
24346
  logTransformTiming(sessionId, "lkg.entryProjection", tLkgEntry, deps.transformMode === "rust" || !entryReuse ? undefined : `reused=${entryReuse.reused} retained=${entryReuse.retained} retainedBytes=${entryReuse.retainedBytes}`);
24193
24347
  const resolvedSessionId = sessionId;
24194
24348
  const runNotificationParams = (sid) => {
@@ -24276,6 +24430,7 @@ function createTransform(deps) {
24276
24430
  const hasTransitionEffects = transition.recordToWrite !== null || transition.notice !== null || transition.invalidatedM0Baseline || transition.clearedCompartmentInProgress || transition.historianCatchUpSignaled;
24277
24431
  if (hasTransitionEffects) {
24278
24432
  if (transition.invalidatedM0Baseline) {
24433
+ compactionModeTransitionPending.add(sessionId);
24279
24434
  sessionMeta = {
24280
24435
  ...sessionMeta,
24281
24436
  cachedM0Bytes: null,
@@ -24608,6 +24763,8 @@ function createTransform(deps) {
24608
24763
  contextLimit: boundaryContextLimit
24609
24764
  });
24610
24765
  let _boundarySnapshotCache;
24766
+ if (fullFeatureMode && !compactionOff)
24767
+ maintainExecuteFloorMark(db, sessionId, currentTurnId, boundaryUsageForProtectedTail.percentage < boundaryExecuteThreshold);
24611
24768
  const getRunnableBoundaryForCompartment = (emergencyTailScale) => {
24612
24769
  if (!canRunCompartments)
24613
24770
  return null;
@@ -24733,8 +24890,9 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
24733
24890
  recordedSessionProjectIdentity.set(sessionId, sessionIdentityForBinding);
24734
24891
  }
24735
24892
  const taggerFloor = compactionOff ? 0 : deriveTaggerLoadFloor(messages, sessionId, db);
24736
- if (!compactionOff && taggerFloor === 0 && messages.length > 0) {
24737
- sessionLog2(sessionId, `tag floor: 0 (full-scan fallback) — no leading wire message resolved a tag across ${messages.length} msgs`);
24893
+ const tagFloorMode = compactionOff || messages.length === 0 ? "inactive" : taggerFloor === 0 ? "fallback" : "scoped";
24894
+ if (diagnosticStateChanged(sessionId, "tag-floor", tagFloorMode) && tagFloorMode !== "inactive") {
24895
+ sessionLog2(sessionId, taggerFloor === 0 ? `tag floor: 0 (full-scan fallback) — no scoped floor above the safety margin across ${messages.length} msgs` : `tag floor: ${taggerFloor} (scoped load)`);
24738
24896
  }
24739
24897
  const ownerRatio = sessionDecisionCalibration(db, sessionId).proseRatio;
24740
24898
  noteTransformPassForExactOrdinalReads(sessionId);
@@ -24771,7 +24929,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
24771
24929
  idleExpiry: false,
24772
24930
  emergency: contextUsageEarly.percentage >= forceMaterializationPercentage
24773
24931
  }
24774
- }, pendingDropEligibility.read(sessionId, dropProjectionKey()));
24932
+ }, pendingDropEligibility.read(sessionId, dropProjectionKey()), schedulerDecision === "execute");
24775
24933
  if (triggerResult.shouldFire) {
24776
24934
  sessionLog2(sessionId, `compartment trigger: firing (reason=${triggerResult.reason})`);
24777
24935
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
@@ -24822,10 +24980,11 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
24822
24980
  let taggingSucceeded = false;
24823
24981
  let recoveryBatch = null;
24824
24982
  let recoveryNormalized = false;
24825
- const normalizeRecoveryTail = recovery.prefix ? () => {
24983
+ const untaggedReplayTailServed = !!recovery.prefix || untaggedReplayIds.size > 0 && messages.some((message) => untaggedReplayIds.has(message.info.id ?? ""));
24984
+ const normalizeRecoveryTail = untaggedReplayTailServed ? () => {
24826
24985
  if (recoveryNormalized)
24827
24986
  return;
24828
- const tail = messages.filter((message) => recovery.prefix?.untaggedInputIds.has(message.info.id ?? ""));
24987
+ const tail = messages.filter((message) => untaggedReplayIds.has(message.info.id ?? ""));
24829
24988
  const tagged = tagMessages(sessionId, tail, deps.tagger, db, {
24830
24989
  skipPrefixInjection: !ctxReduceCallable,
24831
24990
  servedMessages: messages,
@@ -24851,7 +25010,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
24851
25010
  const messagesForTagging = messagesBeforeInitialPrepare && hiddenMessagesAtCompactionSeam.length > 0 ? messagesBeforeInitialPrepare : messages;
24852
25011
  const canAdoptScopedToolSweep = isCacheBusting || canConsumeDeferredEarly;
24853
25012
  const scopedToolSweep = useScopedToolSweep(db, sessionId, canAdoptScopedToolSweep) ? true : createPreAdoptionToolSweepResolver(db, sessionId);
24854
- const result = tagMessages(sessionId, recovery.prefix ? messagesForTagging.filter((message) => !recovery.prefix?.untaggedInputIds.has(message.info.id ?? "")) : messagesForTagging, deps.tagger, db, {
25013
+ const result = tagMessages(sessionId, untaggedReplayIds.size > 0 ? messagesForTagging.filter((message) => !untaggedReplayIds.has(message.info.id ?? "")) : messagesForTagging, deps.tagger, db, {
24855
25014
  skipPrefixInjection,
24856
25015
  scopedToolSweep,
24857
25016
  servedMessages: messages,
@@ -25141,6 +25300,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25141
25300
  activeThinkingPrefixHold,
25142
25301
  directoryPrefixHold: unresolvedDirectoryHold,
25143
25302
  forceSignedRebuildForFit: thinkingFitRetries.has(sessionId) || !!recovery.rebuildReason,
25303
+ compactionModeTransition: compactionModeTransitionPending.has(sessionId),
25144
25304
  readLastServedMessages: () => {
25145
25305
  const slot = getInMemorySlot(sessionId) ?? loadPersistedLkgSlot(db, sessionId);
25146
25306
  try {
@@ -25198,6 +25358,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25198
25358
  hardSignals: m0HardSignals
25199
25359
  }
25200
25360
  });
25361
+ compactionModeTransitionPending.delete(sessionId);
25201
25362
  if (recovery.prefix && !recoveryNormalized) {
25202
25363
  const priorIds = new Set(recovery.prefix.inputs.map((input) => input.id));
25203
25364
  const newIds = new Set(lkgInput.flatMap((input) => input.id && !priorIds.has(input.id) ? [input.id] : []));
@@ -25209,7 +25370,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25209
25370
  postTransformResult.bustedThisPass = true;
25210
25371
  passOutcome.markFinalized();
25211
25372
  const finalWireTail = describeFinalWireTail(messages);
25212
- const signedFitPreviouslyRefused = !compactionOff && getMergedReasoningStrippedIds(db, sessionId).has(SIGNED_FIT_REFUSED_MARKER);
25373
+ const signedFitPreviouslyRefused = !compactionOff && activeThinkingPrefixHold && getMergedReasoningStrippedIds(db, sessionId).has(SIGNED_FIT_REFUSED_MARKER);
25213
25374
  let finalWireEstimate;
25214
25375
  if (postTransformResult.bustedThisPass) {
25215
25376
  try {
@@ -25370,7 +25531,13 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25370
25531
  if (!finalWireEstimate) {
25371
25532
  sessionLog2(sessionId, `transform: final-wire telemetry estimate=unavailable trusted=false conversation=unknown tools=unknown system=unknown toolDefinitions=unknown tail=${finalWireTail}`);
25372
25533
  }
25373
- finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold && postTransformResult.openTurnSignedThinkingKept !== true || postTransformResult.thinkingReleasedForFit === true);
25534
+ if (!compactionOff) {
25535
+ const stillUntagged = untaggedReplayTailServed && !recoveryNormalized ? [...untaggedReplayIds] : [];
25536
+ if (JSON.stringify([...new Set(stillUntagged)].sort()) !== JSON.stringify([...new Set(persistedUntaggedInputIds)].sort()) && !persistLkgUntaggedInputIds(db, sessionId, stillUntagged))
25537
+ throw new Error("Cannot persist the last-good untagged-message record");
25538
+ }
25539
+ const signedThinkingServed = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID) && servesThinkingBlock2(messages, modelForBudget?.providerID, modelForBudget?.modelID);
25540
+ finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold && !signedThinkingServed || postTransformResult.thinkingReleasedForFit === true, signedThinkingServed);
25374
25541
  if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
25375
25542
  recordHeldHeadForRequest(sessionId, currentLkgRequestIdentity(sessionId), (ownsHistory) => deferDeliveredSystemRefresh(deps, sessionId, ownsHistory));
25376
25543
  }
@@ -25528,7 +25695,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25528
25695
  postReduceGraceBaselineU: channel1State.postReduceGraceBaselineU,
25529
25696
  postReduceGracePreLevel: channel1State.postReduceGracePreLevel
25530
25697
  });
25531
- sessionLog2(sessionId, formatChannel1Evaluation(channel1Decision));
25698
+ logNudgeEvaluation(sessionId, "transform", formatChannel1Evaluation(channel1Decision));
25532
25699
  const channel2Evaluation = evaluateChannel2(channelBaseline);
25533
25700
  const leaseBefore = getChannel2NudgeState(db, sessionId);
25534
25701
  if (channelBaseline.evaluable && !channelBaseline.generationInvalidated && !channelBaseline.reducedSinceRefresh) {
@@ -25539,7 +25706,7 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
25539
25706
  }
25540
25707
  }
25541
25708
  const leaseAfter = getChannel2NudgeState(db, sessionId);
25542
- sessionLog2(sessionId, formatChannel2Evaluation(channel2Evaluation, {
25709
+ logNudgeEvaluation(sessionId, "transform", formatChannel2Evaluation(channel2Evaluation, {
25543
25710
  leaseBefore,
25544
25711
  leaseAfter,
25545
25712
  gateHoldReason: channelBaseline.reducedSinceRefresh ? "recent-reduce-refresh" : undefined
@@ -25808,6 +25975,35 @@ function describeSystemPromptChange(previous, current) {
25808
25975
  return `presetChanged=${previous ? previous.preset !== current.preset : "unknown"} elements=[${elements.join("; ")}]`;
25809
25976
  }
25810
25977
 
25978
+ // src/hooks/magic-context/system-prompt-sticky-date.ts
25979
+ var STICKY_DATE_KEY = "systemPromptStickyDate";
25980
+ function readPersistedSystemPromptStickyDate(db, sessionId) {
25981
+ try {
25982
+ const saved = readReplayEnvelope(db, sessionId, "read")[STICKY_DATE_KEY];
25983
+ return typeof saved === "string" && saved.length > 0 ? saved : undefined;
25984
+ } catch (error) {
25985
+ sessionLog2(sessionId, "system prompt sticky date record unreadable:", error);
25986
+ return;
25987
+ }
25988
+ }
25989
+ function persistSystemPromptStickyDate(db, sessionId, stickyDate) {
25990
+ try {
25991
+ const written = updateReplayDocument(db, sessionId, (doc) => {
25992
+ if (doc[STICKY_DATE_KEY] === stickyDate)
25993
+ return false;
25994
+ doc.version = 2;
25995
+ doc[STICKY_DATE_KEY] = stickyDate;
25996
+ return true;
25997
+ });
25998
+ if (!written)
25999
+ sessionLog2(sessionId, "system prompt sticky date record not written");
26000
+ return written;
26001
+ } catch (error) {
26002
+ sessionLog2(sessionId, "system prompt sticky date record write failed:", error);
26003
+ return false;
26004
+ }
26005
+ }
26006
+
25811
26007
  // src/hooks/magic-context/system-prompt-hash.ts
25812
26008
  var MAGIC_CONTEXT_MARKER = "## Magic Context";
25813
26009
  var SYSTEM_PROMPT_GUIDANCE_SEPARATOR = `
@@ -25830,6 +26026,15 @@ function createSystemPromptHashHandler(deps) {
25830
26026
  });
25831
26027
  const guidanceEpochs = createPromptSurfaceGuidanceEpochCache(promptSurfaceRuntime);
25832
26028
  const stickyDateBySession = new Map;
26029
+ const recordedStickyDateBySession = new Map;
26030
+ const recordedStickyDate = (sessionId) => {
26031
+ let recorded = recordedStickyDateBySession.get(sessionId);
26032
+ if (recorded === undefined) {
26033
+ recorded = readPersistedSystemPromptStickyDate(deps.db, sessionId) ?? null;
26034
+ recordedStickyDateBySession.set(sessionId, recorded);
26035
+ }
26036
+ return recorded ?? undefined;
26037
+ };
25833
26038
  const diagnosticPrompts = new Map;
25834
26039
  const processSystemPrompt = async (input, output) => {
25835
26040
  const sessionId = input.sessionID;
@@ -25897,20 +26102,47 @@ function createSystemPromptHashHandler(deps) {
25897
26102
  return;
25898
26103
  const previousHash = sessionMetaEarly?.systemPromptHash ?? "";
25899
26104
  const hasPersistedHash = previousHash !== "" && previousHash !== "0";
25900
- if (!hasPersistedHash)
25901
- stickyDateBySession.delete(sessionId);
25902
- const stickyDate = stickyDateBySession.get(sessionId);
26105
+ const prefixBoundModel = isPrefixBoundThinkingModel(liveModel?.providerID, liveModel?.modelID);
26106
+ let stickyDate = stickyDateBySession.get(sessionId);
26107
+ if (!hasPersistedHash) {
26108
+ const previous = stickyDate ?? recordedStickyDate(sessionId);
26109
+ const live = systemPromptDates(liveSystemContent).live;
26110
+ const fieldCount = (dates) => dates === undefined ? 0 : JSON.parse(dates).length;
26111
+ stickyDate = (!modelKey || prefixBoundModel) && previous !== undefined && live !== undefined && fieldCount(previous) === fieldCount(live) ? previous : undefined;
26112
+ if (stickyDate === undefined)
26113
+ stickyDateBySession.delete(sessionId);
26114
+ else
26115
+ stickyDateBySession.set(sessionId, stickyDate);
26116
+ }
26117
+ if (stickyDate === undefined && hasPersistedHash) {
26118
+ const recorded = recordedStickyDate(sessionId);
26119
+ const live = systemPromptDates(liveSystemContent).live;
26120
+ if (recorded !== undefined && live !== undefined && recorded !== live && systemPromptFingerprint(systemPromptDates(liveSystemContent, recorded).stable, promptSurface.preset) === previousHash) {
26121
+ stickyDate = recorded;
26122
+ stickyDateBySession.set(sessionId, recorded);
26123
+ sessionLog2(sessionId, `system prompt date restored after restart: real=${live}, using=${recorded}`);
26124
+ }
26125
+ }
26126
+ const setStickyDate = (value) => {
26127
+ stickyDateBySession.set(sessionId, value);
26128
+ if (value !== recordedStickyDate(sessionId)) {
26129
+ if (persistSystemPromptStickyDate(deps.db, sessionId, value))
26130
+ recordedStickyDateBySession.set(sessionId, value);
26131
+ }
26132
+ };
25903
26133
  const dates = systemPromptDates(liveSystemContent, stickyDate);
25904
26134
  const currentDate = dates.live;
25905
26135
  const stableCandidate = dates.stable;
25906
26136
  const stableCandidateHash = systemPromptFingerprint(stableCandidate, promptSurface.preset);
25907
26137
  const contentOrPresetChanged = hasPersistedHash && stableCandidateHash !== previousHash;
25908
26138
  const rewritePermission = systemDateRefreshPermission(deps.historyRefreshSessions, dateRequest);
26139
+ const signedThinkingKept = systemDateSignedThinkingKept(deps.historyRefreshSessions, dateRequest);
26140
+ const systemDateMayMove = (rewrite, keptSignedThinking) => (rewrite || idleCacheExpired) && keptSignedThinking !== true;
25909
26141
  let deferredDateRefresh = false;
25910
- if (currentDate && stickyDate && currentDate !== stickyDate && isCacheBusting && !idleCacheExpired && !contentOrPresetChanged && !requestMessagesFinal) {
26142
+ if (currentDate && stickyDate && currentDate !== stickyDate && (idleCacheExpired ? prefixBoundModel : isCacheBusting) && !contentOrPresetChanged && !requestMessagesFinal) {
25911
26143
  const liveElements = [...output.system];
25912
- deferredDateRefresh = waitForSystemDateRefresh(deps.historyRefreshSessions, dateRequest, (permitted) => {
25913
- if (!permitted) {
26144
+ deferredDateRefresh = waitForSystemDateRefresh(deps.historyRefreshSessions, dateRequest, (permitted, keptSignedThinking) => {
26145
+ if (!systemDateMayMove(permitted, keptSignedThinking)) {
25914
26146
  deps.systemPromptRefreshSessions.add(sessionId);
25915
26147
  return;
25916
26148
  }
@@ -25923,7 +26155,7 @@ function createSystemPromptHashHandler(deps) {
25923
26155
  cachedM0SystemHash: hash,
25924
26156
  systemPromptTokens: estimateTokens(content)
25925
26157
  });
25926
- stickyDateBySession.set(sessionId, currentDate);
26158
+ setStickyDate(currentDate);
25927
26159
  output.system.splice(0, output.system.length, ...liveElements);
25928
26160
  publishSystemDateOutput(output.system);
25929
26161
  deps.systemPromptRefreshSessions.delete(sessionId);
@@ -25934,12 +26166,12 @@ function createSystemPromptHashHandler(deps) {
25934
26166
  }
25935
26167
  });
25936
26168
  }
25937
- const dateMayAdvance = idleCacheExpired || contentOrPresetChanged || isCacheBusting && !deferredDateRefresh && (dateRequest ? rewritePermission === true : rewritePermission !== false);
26169
+ const dateMayAdvance = contentOrPresetChanged || !deferredDateRefresh && systemDateMayMove(isCacheBusting && (dateRequest ? rewritePermission === true : rewritePermission !== false), signedThinkingKept);
25938
26170
  if (currentDate && !stickyDate) {
25939
- stickyDateBySession.set(sessionId, currentDate);
26171
+ setStickyDate(currentDate);
25940
26172
  } else if (currentDate && stickyDate && currentDate !== stickyDate) {
25941
26173
  if (dateMayAdvance) {
25942
- stickyDateBySession.set(sessionId, currentDate);
26174
+ setStickyDate(currentDate);
25943
26175
  sessionLog2(sessionId, `system prompt date updated: ${stickyDate} → ${currentDate} (cache-busting pass)`);
25944
26176
  } else {
25945
26177
  let offset = 0;
@@ -25997,7 +26229,7 @@ function createSystemPromptHashHandler(deps) {
25997
26229
  sessionLog2(sessionId, "system prompt meta persist failed (fail-open):", error);
25998
26230
  }
25999
26231
  }
26000
- if (isCacheBusting && !deferredDateRefresh && (contentOrPresetChanged || !currentDate || currentDate === stickyDate || !dateRequest || rewritePermission === true)) {
26232
+ if (isCacheBusting && !deferredDateRefresh && (contentOrPresetChanged || !currentDate || currentDate === stickyDate || !dateRequest || rewritePermission === true && signedThinkingKept !== true)) {
26001
26233
  deps.systemPromptRefreshSessions.delete(sessionId);
26002
26234
  }
26003
26235
  };
@@ -26012,6 +26244,7 @@ function createSystemPromptHashHandler(deps) {
26012
26244
  handler,
26013
26245
  clearSession: (sessionId) => {
26014
26246
  diagnosticPrompts.delete(sessionId);
26247
+ recordedStickyDateBySession.delete(sessionId);
26015
26248
  clearSystemDateRefresh(deps.historyRefreshSessions, sessionId);
26016
26249
  guidanceEpochs.clear(sessionId);
26017
26250
  clearSystemPromptHashSession(sessionId, {
@@ -26338,7 +26571,8 @@ function tryMessagesTransformLkgReplay(args) {
26338
26571
  sessionId,
26339
26572
  entry,
26340
26573
  messages: replay.messages,
26341
- ...keys
26574
+ ...keys,
26575
+ db
26342
26576
  }))
26343
26577
  return false;
26344
26578
  retirePendingSystemPromptDelivery(sessionId);
@@ -26594,8 +26828,17 @@ function guardSubagentTools(tools, db, isInternalChild) {
26594
26828
  function hideSubagentTools(draft, db) {
26595
26829
  if (!getOrCreateSessionMeta(db, draft.sessionID).isSubagent)
26596
26830
  return;
26831
+ removePrimaryOnlyTools(draft.tools);
26832
+ }
26833
+ function removePrimaryOnlyTools(tools) {
26597
26834
  for (const id of PRIMARY_ONLY_TOOLS)
26598
- delete draft.tools[id];
26835
+ delete tools[id];
26836
+ }
26837
+ function storedSubagentMode(db, sessionId) {
26838
+ const row = db.prepare("SELECT is_subagent FROM session_meta WHERE session_id = ?").get(sessionId);
26839
+ if (!row || typeof row.is_subagent !== "number")
26840
+ return;
26841
+ return row.is_subagent === 1;
26599
26842
  }
26600
26843
 
26601
26844
  // src/tools/ctx-expand/tools.ts
@@ -26970,6 +27213,7 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
26970
27213
  }
26971
27214
 
26972
27215
  // src/tools/ctx-expand/tools.ts
27216
+ var CTX_EXPAND_RUST_TAG_REFUSAL = "Tag lookup isn't available on this session: its §N§ tags are numbered by the Rust transform engine and ctx_expand cannot resolve those numbers, so no content was returned. Expand by message instead: ctx_expand(message=<ordinal>) or ctx_expand(start=<ordinal>, end=<ordinal>), using ordinals from a <session-history> heading or a ctx_search hit.";
26973
27217
  var ctxExpandArgsShape = {
26974
27218
  tag: tool.schema.union([tool.schema.number(), tool.schema.string()]).optional().describe("Tag number from a §N§ tag or a [dropped §N§] placeholder, not a message ordinal. Returns that one item in full. Use alone."),
26975
27219
  start: tool.schema.number().optional().describe("First message ordinal of the range (a <session-history> heading's start, or a ctx_search hit), not a tag number."),
@@ -26992,9 +27236,12 @@ function createCtxExpandTool(deps) {
26992
27236
  message: "number"
26993
27237
  });
26994
27238
  const sessionId = toolContext.sessionID;
27239
+ const mode = resolveCtxExpandMode(args, "positive");
27240
+ if (mode.kind === "tag" && deps.transformMode === "rust") {
27241
+ return CTX_EXPAND_RUST_TAG_REFUSAL;
27242
+ }
26995
27243
  if (!await prepareRawSessionOrdinals2(sessionId))
26996
27244
  return "Session ordinals are warming in the background. Retry ctx_expand shortly; no approximate ordinal was served.";
26997
- const mode = resolveCtxExpandMode(args, "positive");
26998
27245
  if (mode.kind === "error") {
26999
27246
  return mode.message;
27000
27247
  }
@@ -28599,7 +28846,7 @@ function createCtxReduceTool(deps) {
28599
28846
  args = unwrapImitatedReducedArgs(args, ["drop"], { drop: "string" });
28600
28847
  const sessionId = toolContext.sessionID;
28601
28848
  if (!args.drop) {
28602
- return "Error: 'drop' must be provided.";
28849
+ return `Error: 'drop' must be provided as a string of tag numbers, for example {"drop": "3-5,8"}.`;
28603
28850
  }
28604
28851
  const rustReduce = deps.rustToolBackends?.reduce;
28605
28852
  if (rustReduce) {
@@ -28887,6 +29134,7 @@ function createCtxSearchTool(deps) {
28887
29134
  explicitSearch: true,
28888
29135
  rerankConnectionFile: deps.rerankConnectionFile,
28889
29136
  searchMessageHistory: (request) => searchMessageHistoryOffThread(deps.db, request),
29137
+ signal: toolContext.abort,
28890
29138
  ...dateRange
28891
29139
  });
28892
29140
  return formatSearchResults2(query, results, toolContext.sessionID, diagnostics);
@@ -29435,4 +29683,4 @@ function applyHiddenSubagentTemperature(input, output, log) {
29435
29683
  output.temperature = temperature;
29436
29684
  }
29437
29685
 
29438
- export { logConfigDependencyNotesOnce, openOpenCodeDb, DREAMER_SYSTEM_PROMPT, runSessionProjectBackfill, SMART_NOTE_COMPILER_SYSTEM_PROMPT, createLiveSessionState, RETROSPECTIVE_MAX_USER_MESSAGE_CHARS, RETROSPECTIVE_MESSAGE_TRUNCATION_MARKER, OpenCodeRetrospectiveRawProvider, createDreamTaskExecutor, runManualDream, runDueTasksForProject, scheduleClearAndReindex, startDreamScheduleTimer, createDreamTimerModuleClient, ensureProjectRegisteredFromOpenCodeDirectory, recordOpenCodeProvenInputFloor, resolveOpenCodeProvenInputFloor, resolveContextWindowGeometry, resolveContextLimit, resolveExecuteThresholdDetail, resolveModelKey, resolveSessionId, createScheduler, describeStorageUnavailability, resolveSessionCacheTtl, runEmbedHistoryDrain, pauseEmbedHistoryDrain, formatEmbedStatusText, getSessionProperties, getSessionCreatedInfo, getMessageUpdatedAssistantInfo, getMessageUpdatedInfo, getSessionErrorInfo, getMessageRemovedInfo, summarizeManualDream, createMagicContextCommandHandler, getLiveNotificationParams, createChatMessageHook, createEventHook, createCommandExecuteBeforeHook, createToolExecuteAfterHook, recordHiddenVariantWarning, buildStatusDetail, isDebugRpcEnabled, registerRpcHandlers, maybeAutoEmbedSessionBackfill, clearTransformDecisionSession, scheduleOpenCodeTransformDecisionWrite, stageOpenCodeV2TransformDecision, bindOpenCodeV2TransformDecision, maybeDeliverChannel2, armLatestThinkingRecovery, armBindingRecoverySafely, armLatestThinkingRecoveryFromError, createM0RenderOptions, lkgReplayLimit, measureLkgReplay, STORAGE_BUSY_MESSAGE, StorageBusyRefusalError, bindSystemDateRequestIdentity, bindSystemDateOutput, registerSystemDateRefresh, rustWrapupHistorianFields, UnmanagedOverWindowError, UnresolvedHistoryBoundaryError, clearMessageTokensCache, createTransform, createSubcModuleClient, createModuleToolBackends, createRustRefusalRecovery, createSystemPromptHashHandler, tryMessagesTransformLkgReplay, createMessagesTransformHandler, primaryOnlyToolIds, subagentToolRefusal, guardSubagentTools, hideSubagentTools, createCtxExpandTools, CTX_MEMORY_LIST_TOOL_NAME, CTX_MEMORY_ACTIONS, createCtxMemoryTools, createCtxMemoryListTools, CTX_NOTE_DESCRIPTION, withoutSmartNoteText, createCtxNoteTools, createCtxReduceTools, createCtxSearchTools, parameterDescriptionsFor, applyJsonSchemaParameterDescriptions, MagicContextRpcServer, subagentTemperature, applyHiddenSubagentTemperature };
29686
+ export { logConfigDependencyNotesOnce, openOpenCodeDb, DREAMER_SYSTEM_PROMPT, runSessionProjectBackfill, SMART_NOTE_COMPILER_SYSTEM_PROMPT, createLiveSessionState, RETROSPECTIVE_MAX_USER_MESSAGE_CHARS, RETROSPECTIVE_MESSAGE_TRUNCATION_MARKER, OpenCodeRetrospectiveRawProvider, createDreamTaskExecutor, runManualDream, runDueTasksForProject, scheduleClearAndReindex, startDreamScheduleTimer, createDreamTimerModuleClient, ensureProjectRegisteredFromOpenCodeDirectory, recordOpenCodeProvenInputFloor, resolveOpenCodeProvenInputFloor, resolveContextWindowGeometry, resolveContextLimit, resolveExecuteThresholdDetail, resolveModelKey, resolveSessionId, createScheduler, describeStorageUnavailability, resolveSessionCacheTtl, runEmbedHistoryDrain, pauseEmbedHistoryDrain, formatEmbedStatusText, getSessionProperties, getSessionCreatedInfo, getMessageUpdatedAssistantInfo, getMessageUpdatedInfo, getSessionErrorInfo, getMessageRemovedInfo, summarizeManualDream, createMagicContextCommandHandler, getLiveNotificationParams, createChatMessageHook, createEventHook, createCommandExecuteBeforeHook, createToolExecuteAfterHook, recordHiddenVariantWarning, buildStatusDetail, isDebugRpcEnabled, registerRpcHandlers, maybeAutoEmbedSessionBackfill, clearTransformDecisionSession, scheduleOpenCodeTransformDecisionWrite, stageOpenCodeV2TransformDecision, bindOpenCodeV2TransformDecision, maybeDeliverChannel2, armLatestThinkingRecovery, armBindingRecoverySafely, armLatestThinkingRecoveryFromError, createM0RenderOptions, lkgReplayLimit, measureLkgReplay, STORAGE_BUSY_MESSAGE, StorageBusyRefusalError, bindSystemDateRequestIdentity, bindSystemDateOutput, registerSystemDateRefresh, rustWrapupHistorianFields, UnmanagedOverWindowError, UnresolvedHistoryBoundaryError, clearMessageTokensCache, createTransform, createSubcModuleClient, createModuleToolBackends, createRustRefusalRecovery, createSystemPromptHashHandler, tryMessagesTransformLkgReplay, createMessagesTransformHandler, primaryOnlyToolIds, subagentToolRefusal, guardSubagentTools, hideSubagentTools, removePrimaryOnlyTools, storedSubagentMode, createCtxExpandTools, CTX_MEMORY_LIST_TOOL_NAME, CTX_MEMORY_ACTIONS, createCtxMemoryTools, createCtxMemoryListTools, CTX_NOTE_DESCRIPTION, withoutSmartNoteText, createCtxNoteTools, createCtxReduceTools, createCtxSearchTools, parameterDescriptionsFor, applyJsonSchemaParameterDescriptions, MagicContextRpcServer, subagentTemperature, applyHiddenSubagentTemperature };