@cortexkit/opencode-magic-context 0.47.0 → 0.49.0

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 (425) hide show
  1. package/dist/agents/magic-context-prompt.d.ts +1 -1
  2. package/dist/agents/magic-context-prompt.d.ts.map +1 -1
  3. package/dist/{announcement-y35wzg2r.js → announcement-fp14dw0n.js} +3 -2
  4. package/dist/auto-search-worker.js +27 -30
  5. package/dist/config/index.d.ts.map +1 -1
  6. package/dist/config/mural-model-deprecation.d.ts +15 -0
  7. package/dist/config/mural-model-deprecation.d.ts.map +1 -0
  8. package/dist/config/project-security.d.ts +0 -3
  9. package/dist/config/project-security.d.ts.map +1 -1
  10. package/dist/config/schema/magic-context.d.ts +10 -6
  11. package/dist/config/schema/magic-context.d.ts.map +1 -1
  12. package/dist/{conflict-warning-hook-z44ynfz7.js → conflict-warning-hook-kzx4dmk1.js} +12 -10
  13. package/dist/{context-wq4ffwyb.js → context-nj5f293n.js} +2765 -1925
  14. package/dist/{derive-budgets-ke12jnnh.js → derive-budgets-qz5rrr08.js} +4 -3
  15. package/dist/embedding-activity-g1dhes6g.js +10 -0
  16. package/dist/embedding-backfill-aetxv1vt.js +21 -0
  17. package/dist/embedding-cache-mgyr73ef.js +16 -0
  18. package/dist/embedding-worker.js +11 -9
  19. package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
  20. package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts +1 -0
  21. package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts.map +1 -1
  22. package/dist/features/magic-context/dreamer/task-config.d.ts +3 -3
  23. package/dist/features/magic-context/dreamer/task-config.d.ts.map +1 -1
  24. package/dist/features/magic-context/dreamer/task-executor.d.ts +1 -1
  25. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  26. package/dist/features/magic-context/dreamer/task-registry.d.ts +1 -0
  27. package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
  28. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  29. package/dist/features/magic-context/git-commits/search-git-commits.d.ts +2 -0
  30. package/dist/features/magic-context/git-commits/search-git-commits.d.ts.map +1 -1
  31. package/dist/features/magic-context/message-index-async.d.ts +16 -3
  32. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  33. package/dist/features/magic-context/message-index-bounded.d.ts +17 -0
  34. package/dist/features/magic-context/message-index-bounded.d.ts.map +1 -0
  35. package/dist/features/magic-context/message-index.d.ts +7 -1
  36. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  37. package/dist/features/magic-context/mural/render-trigger.d.ts +7 -4
  38. package/dist/features/magic-context/mural/render-trigger.d.ts.map +1 -1
  39. package/dist/features/magic-context/pi-content-decisions.d.ts +7 -1
  40. package/dist/features/magic-context/pi-content-decisions.d.ts.map +1 -1
  41. package/dist/features/magic-context/search-rerank.d.ts +35 -0
  42. package/dist/features/magic-context/search-rerank.d.ts.map +1 -0
  43. package/dist/features/magic-context/search.d.ts +40 -0
  44. package/dist/features/magic-context/search.d.ts.map +1 -1
  45. package/dist/features/magic-context/session-activity.d.ts.map +1 -1
  46. package/dist/features/magic-context/smart-notes/runner.d.ts +1 -0
  47. package/dist/features/magic-context/smart-notes/runner.d.ts.map +1 -1
  48. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  49. package/dist/features/magic-context/storage-meta-persisted.d.ts +13 -2
  50. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  51. package/dist/features/magic-context/storage-meta-session.d.ts +7 -1
  52. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  53. package/dist/features/magic-context/storage-meta.d.ts +1 -1
  54. package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
  55. package/dist/features/magic-context/storage-session-tables.d.ts +2 -0
  56. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
  57. package/dist/features/magic-context/storage-tag-identity-revision.d.ts +50 -0
  58. package/dist/features/magic-context/storage-tag-identity-revision.d.ts.map +1 -0
  59. package/dist/features/magic-context/storage-tags.d.ts +153 -4
  60. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  61. package/dist/features/magic-context/storage.d.ts +1 -1
  62. package/dist/features/magic-context/storage.d.ts.map +1 -1
  63. package/dist/features/magic-context/subagent-token-capture.d.ts.map +1 -1
  64. package/dist/features/magic-context/tagger.d.ts +2 -0
  65. package/dist/features/magic-context/tagger.d.ts.map +1 -1
  66. package/dist/features/magic-context/transform-decision-log.d.ts +4 -1
  67. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  68. package/dist/harness-e4avh192.js +10 -0
  69. package/dist/hooks/magic-context/active-anthropic-turn.d.ts +2 -0
  70. package/dist/hooks/magic-context/active-anthropic-turn.d.ts.map +1 -1
  71. package/dist/hooks/magic-context/auto-search-deadline.d.ts.map +1 -1
  72. package/dist/hooks/magic-context/auto-search-replay.fixture.d.ts +24 -0
  73. package/dist/hooks/magic-context/auto-search-replay.fixture.d.ts.map +1 -0
  74. package/dist/hooks/magic-context/auto-search-runner.d.ts +1 -1
  75. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  76. package/dist/hooks/magic-context/auto-search-worker-client.d.ts +34 -3
  77. package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
  78. package/dist/hooks/magic-context/command-handler.d.ts +3 -0
  79. package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
  80. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  81. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  82. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  83. package/dist/hooks/magic-context/emergency-fail-closed.d.ts +28 -0
  84. package/dist/hooks/magic-context/emergency-fail-closed.d.ts.map +1 -1
  85. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  86. package/dist/hooks/magic-context/historian-host-runner.d.ts +8 -0
  87. package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
  88. package/dist/hooks/magic-context/hook.d.ts +3 -2
  89. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  90. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  91. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts +7 -0
  92. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts.map +1 -1
  93. package/dist/hooks/magic-context/lkg-persist.d.ts +4 -3
  94. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
  95. package/dist/hooks/magic-context/lkg-replay.d.ts +13 -8
  96. package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
  97. package/dist/hooks/magic-context/lkg-slot.d.ts +139 -2
  98. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  99. package/dist/hooks/magic-context/message-search-accepting-silent-worker.fixture.d.ts +2 -0
  100. package/dist/hooks/magic-context/message-search-accepting-silent-worker.fixture.d.ts.map +1 -0
  101. package/dist/hooks/magic-context/oc-stall-r2-warmup-worker.fixture.d.ts +2 -0
  102. package/dist/hooks/magic-context/oc-stall-r2-warmup-worker.fixture.d.ts.map +1 -0
  103. package/dist/hooks/magic-context/oc-stall-search-review.fixture.d.ts +2 -0
  104. package/dist/hooks/magic-context/oc-stall-search-review.fixture.d.ts.map +1 -0
  105. package/dist/hooks/magic-context/opencode1-to-model-messages.fixture.d.ts +63 -0
  106. package/dist/hooks/magic-context/opencode1-to-model-messages.fixture.d.ts.map +1 -0
  107. package/dist/hooks/magic-context/pass-outcome.d.ts +1 -0
  108. package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
  109. package/dist/hooks/magic-context/provider-visible-parts.d.ts +45 -0
  110. package/dist/hooks/magic-context/provider-visible-parts.d.ts.map +1 -0
  111. package/dist/hooks/magic-context/raw-ordinal-warmup-silent-worker.fixture.d.ts +2 -0
  112. package/dist/hooks/magic-context/raw-ordinal-warmup-silent-worker.fixture.d.ts.map +1 -0
  113. package/dist/hooks/magic-context/raw-ordinal-warmup-worker.d.ts +2 -0
  114. package/dist/hooks/magic-context/raw-ordinal-warmup-worker.d.ts.map +1 -0
  115. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts +87 -0
  116. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts.map +1 -0
  117. package/dist/hooks/magic-context/read-session-chunk.d.ts +19 -1
  118. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  119. package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
  120. package/dist/hooks/magic-context/read-session-formatting.d.ts +5 -0
  121. package/dist/hooks/magic-context/read-session-formatting.d.ts.map +1 -1
  122. package/dist/hooks/magic-context/read-session-raw.d.ts +118 -1
  123. package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
  124. package/dist/hooks/magic-context/read-session-true-raw-tokens.d.ts.map +1 -1
  125. package/dist/hooks/magic-context/reasoning-budget.d.ts.map +1 -1
  126. package/dist/hooks/magic-context/rust-mode-transform.d.ts +36 -0
  127. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  128. package/dist/hooks/magic-context/sentinel.d.ts +41 -1
  129. package/dist/hooks/magic-context/sentinel.d.ts.map +1 -1
  130. package/dist/hooks/magic-context/shared-compartment-boundaries.d.ts +8 -1
  131. package/dist/hooks/magic-context/shared-compartment-boundaries.d.ts.map +1 -1
  132. package/dist/hooks/magic-context/strict-thinking-prefix.d.ts +8 -0
  133. package/dist/hooks/magic-context/strict-thinking-prefix.d.ts.map +1 -0
  134. package/dist/hooks/magic-context/strip-content.d.ts +14 -2
  135. package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
  136. package/dist/hooks/magic-context/system-prompt-hash.d.ts +1 -0
  137. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  138. package/dist/hooks/magic-context/tag-messages.d.ts +8 -0
  139. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  140. package/dist/hooks/magic-context/tag-owner-warmup.d.ts +6 -0
  141. package/dist/hooks/magic-context/tag-owner-warmup.d.ts.map +1 -0
  142. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
  143. package/dist/hooks/magic-context/token-count-exact.d.ts +35 -0
  144. package/dist/hooks/magic-context/token-count-exact.d.ts.map +1 -0
  145. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +13 -0
  146. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  147. package/dist/hooks/magic-context/transform.d.ts +9 -2
  148. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  149. package/dist/hooks/magic-context/wrapup-orchestrator.d.ts.map +1 -1
  150. package/dist/{index-q6hef7fh.js → index-0sahzkwr.js} +6 -19
  151. package/dist/{index-k5bdx1bx.js → index-0w56v4fm.js} +3 -5
  152. package/dist/{index-5gq3b2ya.js → index-1bt88epp.js} +227 -205
  153. package/dist/{index-cwf6s3ay.js → index-1g30axtz.js} +3279 -2907
  154. package/dist/{index-5a2r0p9f.js → index-1r0k9js3.js} +20 -13
  155. package/dist/index-2bvekkfy.js +11 -0
  156. package/dist/{index-6d9e1m08.js → index-2jcbj7r1.js} +13301 -13225
  157. package/dist/index-2jgwttpt.js +3269 -0
  158. package/dist/index-4dhv7mqz.js +131 -0
  159. package/dist/{index-sj29b3z2.js → index-4mjhqadz.js} +3 -3
  160. package/dist/{index-0c82743p.js → index-57mrqed8.js} +17 -15
  161. package/dist/{index-b35pxds2.js → index-58e3y90n.js} +1 -18
  162. package/dist/index-7jzrrxap.js +931 -0
  163. package/dist/index-8ajstryz.js +18 -0
  164. package/dist/{index-sfpzqvdz.js → index-8cd2j99z.js} +2 -3
  165. package/dist/{index-6wkcswft.js → index-9qjqq45k.js} +29 -19
  166. package/dist/{index-adwfkpex.js → index-9rt53q79.js} +23 -23
  167. package/dist/index-b7mv1jx3.js +1060 -0
  168. package/dist/index-d9vfe7xq.js +16 -0
  169. package/dist/{index-gg8j07zz.js → index-ezmszwbd.js} +8 -6
  170. package/dist/index-fb3zxn06.js +13 -0
  171. package/dist/index-fr0wbhdn.js +43 -0
  172. package/dist/{index-mc22ayvf.js → index-ghc9f0n7.js} +11 -9
  173. package/dist/index-gzcmtmar.js +171 -0
  174. package/dist/{index-w2t4ah5j.js → index-h2py7207.js} +6762 -7400
  175. package/dist/index-h2wc01qk.js +120 -0
  176. package/dist/index-h5zfkjyk.js +1277 -0
  177. package/dist/{index-92bp57hg.js → index-ha87j7a8.js} +1343 -149
  178. package/dist/index-hj2q50k0.js +856 -0
  179. package/dist/{index-wx8a6bw3.js → index-kb9nn0a0.js} +270 -53
  180. package/dist/index-kmpvemph.js +1314 -0
  181. package/dist/index-kp5qe690.js +3030 -0
  182. package/dist/{index-m5fe6jch.js → index-kq57tdf0.js} +152 -2453
  183. package/dist/{v2/server-fq7kq32k.js → index-mfkzp7qj.js} +1 -16
  184. package/dist/{v2/server-njt3np1k.js → index-nm6a8xpd.js} +220 -961
  185. package/dist/{index-hybnrwq0.js → index-nsjyysj0.js} +137 -130
  186. package/dist/index-nydv6g8r.js +3569 -0
  187. package/dist/index-pavzsdc6.js +17 -0
  188. package/dist/index-peshmj6h.js +152 -0
  189. package/dist/index-pxwp2hjk.js +571 -0
  190. package/dist/{v2/server-yr3zj7e7.js → index-qt1qqasc.js} +6 -7
  191. package/dist/{v2/server-51dv1pr5.js → index-qx53vezw.js} +301 -27
  192. package/dist/{index-rrrsepyw.js → index-s4j7t92z.js} +90 -85
  193. package/dist/{index-9pk9exrb.js → index-stbr4ce6.js} +18 -18
  194. package/dist/{index-fzbvakh0.js → index-tqf7yg27.js} +3 -3
  195. package/dist/index-vkbqdnkj.js +2307 -0
  196. package/dist/{index-8da2zjhz.js → index-z1tjp257.js} +9 -7
  197. package/dist/index.d.ts.map +1 -1
  198. package/dist/index.js +608 -349
  199. package/dist/logger-ewak5q1s.js +20 -0
  200. package/dist/message-index-bounded-h0mrd4pr.js +124 -0
  201. package/dist/{v2/message-time-backfill-1f9tzvcs.js → message-time-backfill-8x06r9kx.js} +8 -6
  202. package/dist/migration-worker.js +25 -18
  203. package/dist/{model-resolution-xhfmyyvy.js → model-resolution-nx97z3x7.js} +1 -1
  204. package/dist/plugin/dream-timer.d.ts +1 -1
  205. package/dist/plugin/dream-timer.d.ts.map +1 -1
  206. package/dist/plugin/hooks/create-session-hooks.d.ts +3 -0
  207. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  208. package/dist/plugin/host-stall-profiler-report.d.ts +1 -66
  209. package/dist/plugin/host-stall-profiler-report.d.ts.map +1 -1
  210. package/dist/plugin/host-stall-profiler.d.ts +2 -95
  211. package/dist/plugin/host-stall-profiler.d.ts.map +1 -1
  212. package/dist/plugin/messages-transform.d.ts +0 -13
  213. package/dist/plugin/messages-transform.d.ts.map +1 -1
  214. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  215. package/dist/plugin/tool-registry.d.ts.map +1 -1
  216. package/dist/project-embedding-registry-rtt0djyb.js +88 -0
  217. package/dist/raw-ordinal-warmup-worker.js +60 -0
  218. package/dist/{read-session-chunk-4jey7hpt.js → read-session-chunk-ty89v75e.js} +17 -9
  219. package/dist/read-session-raw-8sjbc9h0.js +60 -0
  220. package/dist/recomp-orchestrator-4f1yyd1q.js +57 -0
  221. package/dist/{v2/safe-notification-target-eb1n1vfb.js → safe-notification-target-q0cyrx3x.js} +4 -2
  222. package/dist/search-pz4f4wge.js +45 -0
  223. package/dist/{v2/send-session-notification-c0wtscea.js → send-session-notification-38cd5dqt.js} +10 -7
  224. package/dist/shared/auto-search-lifecycle.d.ts +14 -0
  225. package/dist/shared/auto-search-lifecycle.d.ts.map +1 -1
  226. package/dist/shared/conflict-detector.d.ts.map +1 -1
  227. package/dist/shared/host-stall-profiler-bun.d.ts +46 -0
  228. package/dist/shared/host-stall-profiler-bun.d.ts.map +1 -0
  229. package/dist/shared/host-stall-profiler-common.d.ts +58 -0
  230. package/dist/shared/host-stall-profiler-common.d.ts.map +1 -0
  231. package/dist/shared/host-stall-profiler-node.d.ts +36 -0
  232. package/dist/shared/host-stall-profiler-node.d.ts.map +1 -0
  233. package/dist/shared/host-stall-profiler-report.d.ts +68 -0
  234. package/dist/shared/host-stall-profiler-report.d.ts.map +1 -0
  235. package/dist/shared/host-stall-profiler.d.ts +5 -0
  236. package/dist/shared/host-stall-profiler.d.ts.map +1 -0
  237. package/dist/shared/logger.d.ts.map +1 -1
  238. package/dist/shared/model-resolution.d.ts +2 -3
  239. package/dist/shared/model-resolution.d.ts.map +1 -1
  240. package/dist/shared/models-dev-temperature.d.ts +18 -0
  241. package/dist/shared/models-dev-temperature.d.ts.map +1 -0
  242. package/dist/shared/project-directory-key.d.ts +16 -0
  243. package/dist/shared/project-directory-key.d.ts.map +1 -1
  244. package/dist/shared/sqlite.d.ts +30 -0
  245. package/dist/shared/sqlite.d.ts.map +1 -1
  246. package/dist/shared/stable-json.d.ts.map +1 -1
  247. package/dist/shared/subagent-temperature.d.ts +46 -0
  248. package/dist/shared/subagent-temperature.d.ts.map +1 -0
  249. package/dist/shared/user-facing-codes.d.ts +0 -5
  250. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  251. package/dist/sqlite-context-pragmas-mv9jqwjh.js +6 -0
  252. package/dist/sqlite-mhjkerzq.js +46 -0
  253. package/dist/storage-memory-07fx57k6.js +71 -0
  254. package/dist/storage-tags-k0pda32s.js +133 -0
  255. package/dist/{task-config-v81k8jvk.js → task-config-cgpg0nvh.js} +2 -2
  256. package/dist/tools/ctx-expand/tools.d.ts.map +1 -1
  257. package/dist/tools/ctx-note/constants.d.ts +4 -0
  258. package/dist/tools/ctx-note/constants.d.ts.map +1 -1
  259. package/dist/tools/ctx-note/tools.d.ts +1 -0
  260. package/dist/tools/ctx-note/tools.d.ts.map +1 -1
  261. package/dist/tools/ctx-reduce/tools.d.ts.map +1 -1
  262. package/dist/tools/ctx-search/tools.d.ts.map +1 -1
  263. package/dist/tools/ctx-search/types.d.ts +1 -0
  264. package/dist/tools/ctx-search/types.d.ts.map +1 -1
  265. package/dist/tools/parameter-descriptions.d.ts +2 -2
  266. package/dist/tools/parameter-descriptions.d.ts.map +1 -1
  267. package/dist/{transform-postprocess-phase-z5hzpsxv.js → transform-postprocess-phase-tck4g20s.js} +35 -20
  268. package/dist/transformers-node-wasm.js +18415 -18415
  269. package/dist/v2/auto-search-worker.js +27 -30
  270. package/dist/v2/{context-14v1hr8b.js → context-crbt6p1y.js} +4708 -4218
  271. package/dist/v2/{derive-budgets-nc9avxz8.js → derive-budgets-fgej9j46.js} +4 -3
  272. package/dist/v2/embedding-activity-g1dhes6g.js +10 -0
  273. package/dist/v2/embedding-backfill-ph1qfyn3.js +21 -0
  274. package/dist/v2/embedding-cache-mgyr73ef.js +16 -0
  275. package/dist/v2/embedding-worker.js +12 -9
  276. package/dist/v2/fold/host-media.d.ts +4 -0
  277. package/dist/v2/fold/host-media.d.ts.map +1 -1
  278. package/dist/v2/fold/memory-cache.d.ts +70 -0
  279. package/dist/v2/fold/memory-cache.d.ts.map +1 -0
  280. package/dist/v2/fold/native-codec.d.ts +10 -0
  281. package/dist/v2/fold/native-codec.d.ts.map +1 -0
  282. package/dist/v2/fold/native-replay.d.ts +58 -0
  283. package/dist/v2/fold/native-replay.d.ts.map +1 -0
  284. package/dist/v2/fold/policy.d.ts +24 -0
  285. package/dist/v2/fold/policy.d.ts.map +1 -0
  286. package/dist/v2/harness-e4avh192.js +10 -0
  287. package/dist/v2/hidden-child-native.d.ts.map +1 -1
  288. package/dist/v2/hidden-completion.d.ts +7 -0
  289. package/dist/v2/hidden-completion.d.ts.map +1 -1
  290. package/dist/v2/hooks/context.d.ts +2 -2
  291. package/dist/v2/hooks/context.d.ts.map +1 -1
  292. package/dist/v2/hooks/dream-manual.d.ts +1 -1
  293. package/dist/v2/hooks/dream-manual.d.ts.map +1 -1
  294. package/dist/v2/hooks/dream-timer.d.ts.map +1 -1
  295. package/dist/v2/hooks/dream-trigger.d.ts +5 -3
  296. package/dist/v2/hooks/dream-trigger.d.ts.map +1 -1
  297. package/dist/v2/hooks/generate.d.ts +9 -2
  298. package/dist/v2/hooks/generate.d.ts.map +1 -1
  299. package/dist/v2/hooks/payload.d.ts.map +1 -1
  300. package/dist/v2/hooks/tools.d.ts.map +1 -1
  301. package/dist/v2/hooks/types.d.ts +6 -0
  302. package/dist/v2/hooks/types.d.ts.map +1 -1
  303. package/dist/v2/logger-pj02s7sr.js +19 -0
  304. package/dist/v2/message-index-bounded-xwqdywxg.js +123 -0
  305. package/dist/{message-time-backfill-r5epkzj3.js → v2/message-time-backfill-cje68egj.js} +7 -7
  306. package/dist/v2/migration-worker.js +24 -17
  307. package/dist/v2/{model-resolution-xhfmyyvy.js → model-resolution-nx97z3x7.js} +1 -1
  308. package/dist/v2/project-embedding-registry-d6m7tyxr.js +86 -0
  309. package/dist/v2/raw-ordinal-warmup-worker.js +60 -0
  310. package/dist/v2/{read-session-chunk-gyyv7w2r.js → read-session-chunk-8p5mdryx.js} +16 -8
  311. package/dist/v2/read-session-raw-j8dvp7f4.js +59 -0
  312. package/dist/v2/recomp-orchestrator-ckfgt6wq.js +57 -0
  313. package/dist/{safe-notification-target-43r8jsxw.js → v2/safe-notification-target-y3p1hce9.js} +3 -3
  314. package/dist/v2/search-ym8rehhz.js +45 -0
  315. package/dist/{send-session-notification-0m68ms3n.js → v2/send-session-notification-5m0yapqx.js} +9 -8
  316. package/dist/v2/{server-rz514f14.js → server-19zjmn02.js} +2044 -2060
  317. package/dist/v2/server-1tk82krw.js +796 -0
  318. package/dist/v2/server-2bvekkfy.js +11 -0
  319. package/dist/v2/{server-ajzeteqw.js → server-2ra6pwf3.js} +1 -18
  320. package/dist/v2/server-2s6ayq3t.js +1048 -0
  321. package/dist/v2/{server-fcdehk1s.js → server-2s9qz6n7.js} +4 -4
  322. package/dist/v2/server-3j4d00kf.js +171 -0
  323. package/dist/v2/{server-14vq4kpm.js → server-3t0q2cqx.js} +3 -3
  324. package/dist/v2/server-4dhv7mqz.js +131 -0
  325. package/dist/v2/server-4ez8mntn.js +3213 -0
  326. package/dist/v2/{server-6r257mf5.js → server-676xw7at.js} +3 -3
  327. package/dist/v2/{server-vs5gpnd4.js → server-6byqfbqf.js} +165 -145
  328. package/dist/v2/server-7ekna9zs.js +120 -0
  329. package/dist/v2/server-7h861yms.js +1272 -0
  330. package/dist/v2/server-7jzrrxap.js +931 -0
  331. package/dist/v2/server-8ajstryz.js +18 -0
  332. package/dist/v2/{server-sfpzqvdz.js → server-8cd2j99z.js} +2 -3
  333. package/dist/v2/{server-cpepxy2q.js → server-8k2agx29.js} +14 -12
  334. package/dist/v2/server-c5rrgrcd.js +3545 -0
  335. package/dist/v2/server-d9vfe7xq.js +16 -0
  336. package/dist/v2/server-fb3zxn06.js +13 -0
  337. package/dist/v2/server-fr0wbhdn.js +43 -0
  338. package/dist/v2/{server-y10vbq6y.js → server-hb6xhh9q.js} +11 -1053
  339. package/dist/v2/server-jvxzm1jy.js +3023 -0
  340. package/dist/v2/{server-wx8a6bw3.js → server-kb9nn0a0.js} +270 -53
  341. package/dist/{index-5eqk6z3s.js → v2/server-kzns2hbz.js} +301 -27
  342. package/dist/{index-rrbbspwh.js → v2/server-mfkzp7qj.js} +1 -16
  343. package/dist/v2/server-pavzsdc6.js +17 -0
  344. package/dist/v2/{server-vd4e7174.js → server-pj4pjv02.js} +21 -17
  345. package/dist/v2/{server-e0c1b7a7.js → server-q4ph9bwn.js} +1340 -148
  346. package/dist/{index-yr3zj7e7.js → v2/server-qt1qqasc.js} +6 -7
  347. package/dist/v2/{server-qdjnb2z1.js → server-r5p3b1wy.js} +11 -9
  348. package/dist/v2/{server-d0sraw7m.js → server-sa8jvrfc.js} +291 -286
  349. package/dist/v2/server-ss95ky04.js +1048 -0
  350. package/dist/v2/{server-1qbnzc80.js → server-t4k4qexw.js} +142 -150
  351. package/dist/{index-x3kwrmqk.js → v2/server-v4mewb78.js} +35 -792
  352. package/dist/v2/server-w32kmdez.js +154 -0
  353. package/dist/v2/{server-nf82q6pt.js → server-x4hscabv.js} +5547 -5449
  354. package/dist/v2/server-xwz4dqh9.js +569 -0
  355. package/dist/v2/{server-efhwzx05.js → server-ycw9qqcy.js} +23 -23
  356. package/dist/v2/{server-50hvkg3v.js → server-zm570tr2.js} +160 -158
  357. package/dist/v2/server-zp53y8js.js +1311 -0
  358. package/dist/v2/server.js +16 -14
  359. package/dist/v2/sqlite-context-pragmas-mv9jqwjh.js +6 -0
  360. package/dist/v2/sqlite-mhjkerzq.js +46 -0
  361. package/dist/v2/storage-memory-07fx57k6.js +71 -0
  362. package/dist/v2/storage-tags-8vw924zn.js +132 -0
  363. package/dist/v2/store-reader.d.ts +24 -2
  364. package/dist/v2/store-reader.d.ts.map +1 -1
  365. package/dist/v2/{task-config-tbndqyny.js → task-config-x0hq3qfd.js} +2 -2
  366. package/dist/v2/transformers-node-wasm.js +18415 -18415
  367. package/dist/v2/tui/index.d.ts.map +1 -1
  368. package/dist/v2/tui/types.d.ts +1 -10
  369. package/dist/v2/tui/types.d.ts.map +1 -1
  370. package/dist/v2/{wrapup-orchestrator-nbz854vc.js → wrapup-orchestrator-a7efxaax.js} +51 -30
  371. package/dist/wrapup-orchestrator-barbc6h9.js +44 -0
  372. package/package.json +4 -3
  373. package/src/agents/magic-context-prompt.ts +27 -2
  374. package/src/agents/smart-notes-enabled.test.ts +294 -0
  375. package/src/agents/smart-notes-on.golden.json +70 -0
  376. package/src/config/index.test.ts +67 -1
  377. package/src/config/index.ts +2 -0
  378. package/src/config/latch-permanence-guard.test.ts +4 -0
  379. package/src/config/mural-model-deprecation.ts +24 -0
  380. package/src/config/project-security.hostile-matrix.test.ts +4 -44
  381. package/src/config/project-security.test.ts +9 -14
  382. package/src/config/project-security.ts +13 -55
  383. package/src/config/schema/magic-context.test.ts +2 -2
  384. package/src/config/schema/magic-context.ts +16 -10
  385. package/src/features/magic-context/dreamer/task-registry.ts +6 -0
  386. package/src/shared/auto-search-lifecycle.ts +43 -0
  387. package/src/shared/conflict-detector.test.ts +56 -0
  388. package/src/shared/conflict-detector.ts +16 -5
  389. package/src/shared/host-stall-profiler-bun.ts +358 -0
  390. package/src/shared/host-stall-profiler-common.ts +159 -0
  391. package/src/shared/host-stall-profiler-node.test.ts +234 -0
  392. package/src/shared/host-stall-profiler-node.ts +274 -0
  393. package/src/shared/host-stall-profiler-report.ts +248 -0
  394. package/src/shared/host-stall-profiler.ts +57 -0
  395. package/src/shared/logger.test.ts +38 -0
  396. package/src/shared/logger.ts +10 -2
  397. package/src/shared/model-resolution.test.ts +54 -17
  398. package/src/shared/model-resolution.ts +6 -17
  399. package/src/shared/models-dev-temperature.ts +107 -0
  400. package/src/shared/project-directory-key.test.ts +59 -0
  401. package/src/shared/project-directory-key.ts +20 -0
  402. package/src/shared/sqlite.test.ts +52 -0
  403. package/src/shared/sqlite.ts +339 -23
  404. package/src/shared/stable-json-linear.test.ts +109 -0
  405. package/src/shared/stable-json.ts +37 -7
  406. package/src/shared/subagent-temperature.test.ts +270 -0
  407. package/src/shared/subagent-temperature.ts +110 -0
  408. package/src/shared/user-facing-codes.ts +2 -6
  409. package/src/shared/write-transaction-attribution.test.ts +2 -2
  410. package/src/v2/tui/host-contract.test.ts +41 -67
  411. package/src/v2/tui/index.ts +6 -214
  412. package/src/v2/tui/types.ts +5 -17
  413. package/dist/features/magic-context/checkout-claim-fake-subc.test-support.d.ts +0 -45
  414. package/dist/features/magic-context/checkout-claim-fake-subc.test-support.d.ts.map +0 -1
  415. package/dist/features/magic-context/checkout-claim.d.ts +0 -155
  416. package/dist/features/magic-context/checkout-claim.d.ts.map +0 -1
  417. package/dist/index-bb36vgr3.js +0 -6608
  418. package/dist/index-fnn5pjtt.js +0 -6554
  419. package/dist/recomp-orchestrator-rervg6q4.js +0 -42
  420. package/dist/v2/recomp-orchestrator-42vjba7p.js +0 -42
  421. package/dist/v2/server-3trjk1hx.js +0 -6360
  422. package/dist/v2/server-nm9n3aqq.js +0 -6461
  423. package/dist/wrapup-orchestrator-b2dztrar.js +0 -29
  424. /package/dist/{index-5prbx026.js → index-2pp04pmg.js} +0 -0
  425. /package/dist/v2/{index-5prbx026.js → index-2pp04pmg.js} +0 -0
package/dist/index.js CHANGED
@@ -1,15 +1,17 @@
1
1
  import {
2
- setHarness,
2
+ setHarness2
3
+ } from "./index-pavzsdc6.js";
4
+ import {
3
5
  getOpenCodeStorageDir,
4
6
  getMagicContextStorageDir
5
- } from "./index-q6hef7fh.js";
7
+ } from "./index-0sahzkwr.js";
6
8
  import {
7
9
  registerStalePluginBuildHost,
8
10
  importPluginModule,
9
- log,
10
- sessionLog,
11
- flushLogger
12
- } from "./index-hybnrwq0.js";
11
+ log2,
12
+ sessionLog2,
13
+ flushLogger2
14
+ } from "./index-nsjyysj0.js";
13
15
  import {
14
16
  withContentLanguageDirective,
15
17
  string,
@@ -21,7 +23,7 @@ import {
21
23
  record,
22
24
  DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE,
23
25
  DEFAULT_HISTORIAN_TIMEOUT_MS
24
- } from "./index-m5fe6jch.js";
26
+ } from "./index-kq57tdf0.js";
25
27
  import {
26
28
  denyTaskRoutingToCallerAgents,
27
29
  buildHiddenAgentRegistrations,
@@ -74,18 +76,20 @@ import {
74
76
  noteLkgProviderResponse,
75
77
  registerLkgPersistence,
76
78
  dropSlot,
79
+ forgetUnpublishedAutoSearchNoHint,
77
80
  getOrCreateSessionMeta,
78
81
  updateSessionMeta,
79
82
  markSessionCleanupPending,
80
83
  clearSession,
81
84
  recordPromptSessionError,
85
+ CTX_NOTE_LIGHT_DESCRIPTION,
82
86
  createPromptSurfaceRuntime,
83
87
  setKeepSubagents,
84
88
  removeCompactionMarkerForSession,
85
89
  checkCompactionMarkerConsistency,
86
90
  clearInjectionCache,
87
91
  clearNoteNudgeTriggerOnly
88
- } from "./index-6d9e1m08.js";
92
+ } from "./index-2jcbj7r1.js";
89
93
  import"./index-sd3egckz.js";
90
94
  import {
91
95
  reloadWindowOverlay,
@@ -96,26 +100,21 @@ import {
96
100
  deriveHistorianChunkTokens2,
97
101
  resolveKnownHistorianContextLimit2,
98
102
  resolveHistorianContextLimit2
99
- } from "./index-0c82743p.js";
100
- import"./index-rrbbspwh.js";
103
+ } from "./index-57mrqed8.js";
104
+ import"./index-mfkzp7qj.js";
101
105
  import {
102
106
  resolveOpenCodeDbPath,
103
107
  openCodeDbPathExists,
104
108
  formatOpenCodeDbMissingBanner,
105
- claimOpenCodeDbDiagnosticOnce,
106
- closeQuietly
107
- } from "./index-b35pxds2.js";
108
- import"./index-wx8a6bw3.js";
109
+ claimOpenCodeDbDiagnosticOnce
110
+ } from "./index-58e3y90n.js";
111
+ import"./index-kb9nn0a0.js";
109
112
  import {
110
- createSubcCheckoutClaimGate,
111
- openCodeEventSessionId,
112
113
  openOpenCodeDb,
113
114
  DREAMER_SYSTEM_PROMPT,
114
115
  runSessionProjectBackfill,
115
116
  SMART_NOTE_COMPILER_SYSTEM_PROMPT,
116
117
  createLiveSessionState,
117
- getDefaultSubcConnectionFile,
118
- SubcModuleTransport,
119
118
  OpenCodeRetrospectiveRawProvider,
120
119
  createDreamTaskExecutor,
121
120
  runManualDream,
@@ -157,6 +156,7 @@ import {
157
156
  maybeDeliverChannel2,
158
157
  armLatestThinkingRecovery,
159
158
  armBindingRecoverySafely,
159
+ rustWrapupHistorianFields,
160
160
  clearMessageTokensCache,
161
161
  createTransform,
162
162
  createSubcModuleClient,
@@ -171,12 +171,14 @@ import {
171
171
  CTX_MEMORY_ACTIONS,
172
172
  createCtxMemoryTools,
173
173
  createCtxMemoryListTools,
174
+ withoutSmartNoteText,
174
175
  createCtxNoteTools,
175
176
  createCtxReduceTools,
176
177
  createCtxSearchTools,
177
178
  parameterDescriptionsFor,
178
- MagicContextRpcServer
179
- } from "./index-w2t4ah5j.js";
179
+ MagicContextRpcServer,
180
+ applyHiddenSubagentTemperature
181
+ } from "./index-h2py7207.js";
180
182
  import {
181
183
  formatFailClosedBlockingMessage,
182
184
  createFailClosedController,
@@ -191,7 +193,7 @@ import {
191
193
  openDatabaseAsync,
192
194
  isDatabasePersisted,
193
195
  getDatabasePersistenceError
194
- } from "./index-rrrsepyw.js";
196
+ } from "./index-s4j7t92z.js";
195
197
  import {
196
198
  setHomeProjectPermission,
197
199
  ProjectIdentityError,
@@ -202,28 +204,33 @@ import {
202
204
  beginBootQuietPeriod,
203
205
  bootQuietRemainingMs,
204
206
  scheduleAfterBootQuiet
205
- } from "./index-x3kwrmqk.js";
207
+ } from "./index-pxwp2hjk.js";
208
+ import {
209
+ deleteTemporalDecision
210
+ } from "./index-1bt88epp.js";
206
211
  import {
207
212
  observeSessionActivity,
208
213
  backfillSessionActivity,
214
+ deleteIndexedMessage
215
+ } from "./index-hj2q50k0.js";
216
+ import {
209
217
  recordSessionProjectIdentity,
210
- deleteIndexedMessage,
211
- getProjectEmbeddingSnapshot,
212
- getEmbeddingCoverageStatus,
213
- getAutoEmbeddingSessionCoverage
214
- } from "./index-fnn5pjtt.js";
218
+ getProjectEmbeddingSnapshot2,
219
+ getEmbeddingCoverageStatus2,
220
+ getAutoEmbeddingSessionCoverage2
221
+ } from "./index-kp5qe690.js";
222
+ import"./index-fb3zxn06.js";
223
+ import"./index-gzcmtmar.js";
224
+ import"./index-nm6a8xpd.js";
225
+ import"./index-fr0wbhdn.js";
226
+ import {
227
+ preloadTokenizer
228
+ } from "./index-qx53vezw.js";
215
229
  import {
216
- deleteTemporalDecision,
217
230
  getCurrentToolSetHash,
218
231
  recordToolDefinition
219
- } from "./index-5gq3b2ya.js";
220
- import {
221
- preloadTokenizer
222
- } from "./index-5eqk6z3s.js";
232
+ } from "./index-h2wc01qk.js";
223
233
  import {
224
- stripPersistedAssistantText,
225
- deleteTagsByMessageId,
226
- getMaxTagNumberBySession,
227
234
  invalidateTrueRawTokenCache,
228
235
  recordToolParameters,
229
236
  createDroppedInputToolExecuteBeforeHook,
@@ -233,60 +240,79 @@ import {
233
240
  detectOverflow,
234
241
  isAnthropicFamilyRoute,
235
242
  readRawSessionMessages2
236
- } from "./index-bb36vgr3.js";
243
+ } from "./index-2jgwttpt.js";
244
+ import"./index-vkbqdnkj.js";
245
+ import {
246
+ getDefaultSubcConnectionFile,
247
+ SubcModuleTransport
248
+ } from "./index-ha87j7a8.js";
249
+ import {
250
+ isEmbeddingHostBusy2
251
+ } from "./index-qt1qqasc.js";
252
+ import"./index-tqf7yg27.js";
237
253
  import {
238
- isEmbeddingHostBusy
239
- } from "./index-yr3zj7e7.js";
240
- import"./index-fzbvakh0.js";
254
+ registerExitAbort,
255
+ unregisterExitAbort,
256
+ forgetRawSessionOrdinalWatermark2
257
+ } from "./index-h5zfkjyk.js";
241
258
  import {
242
259
  observeOpenCodeTurnEvent,
243
260
  clearTrackedOpenCodeSession,
244
261
  findLastAssistantModelFromOpenCodeDb
245
- } from "./index-6wkcswft.js";
262
+ } from "./index-9qjqq45k.js";
246
263
  import {
247
264
  sendCommandResult2,
248
265
  sendStatusNotification2
249
- } from "./index-adwfkpex.js";
266
+ } from "./index-9rt53q79.js";
250
267
  import {
251
268
  detectConflicts,
252
269
  resolveCompactionForBoot
253
- } from "./index-8da2zjhz.js";
270
+ } from "./index-z1tjp257.js";
254
271
  import {
255
272
  sendConflictWarning2,
256
273
  cleanupConflictWarnings2
257
- } from "./index-9pk9exrb.js";
274
+ } from "./index-stbr4ce6.js";
258
275
  import"./index-1zx87sdm.js";
276
+ import {
277
+ stripPersistedAssistantText,
278
+ deleteTagsByMessageId2,
279
+ getMaxTagNumberBySession2
280
+ } from "./index-nydv6g8r.js";
259
281
  import {
260
282
  resolveHistorianModel2,
261
283
  resolveOpenCodeAgentOverrides2,
262
284
  resolveHistorianAgentOverrides2
263
- } from "./index-sfpzqvdz.js";
285
+ } from "./index-8cd2j99z.js";
264
286
  import {
265
287
  buildDreamTaskRuntimeConfigs2,
266
288
  userMemoryCollectionEnabled2
267
- } from "./index-mc22ayvf.js";
289
+ } from "./index-ghc9f0n7.js";
290
+ import"./index-b7mv1jx3.js";
291
+ import"./index-kmpvemph.js";
268
292
  import {
269
293
  pushNotification2
270
294
  } from "./index-x8a7jmkh.js";
271
- import"./index-92bp57hg.js";
295
+ import"./index-4dhv7mqz.js";
296
+ import"./index-peshmj6h.js";
297
+ import"./index-7jzrrxap.js";
272
298
  import {
273
299
  createTagger,
274
300
  cavemanWordRulesForLanguage,
275
301
  setCtxReduceRegisteredGlobally,
276
302
  clearToolPermissionDenied,
277
303
  resetDegradedCacheCount2
278
- } from "./index-cwf6s3ay.js";
304
+ } from "./index-1g30axtz.js";
279
305
  import {
280
306
  runManagedRecomp2
281
- } from "./index-gg8j07zz.js";
307
+ } from "./index-ezmszwbd.js";
282
308
  import {
283
309
  isValidSemver,
284
310
  compareSemverCore
285
- } from "./index-k5bdx1bx.js";
311
+ } from "./index-0w56v4fm.js";
286
312
  import"./index-fmsr7v69.js";
287
313
  import {
288
314
  runManagedWrapup2
289
- } from "./index-5a2r0p9f.js";
315
+ } from "./index-1r0k9js3.js";
290
316
  import {
291
317
  __toESM,
292
318
  __commonJS
@@ -303,7 +329,10 @@ import {
303
329
  import {
304
330
  piModelRefToCanonical
305
331
  } from "./index-avwt563y.js";
306
- import"./index-sj29b3z2.js";
332
+ import {
333
+ closeQuietly
334
+ } from "./index-8ajstryz.js";
335
+ import"./index-4mjhqadz.js";
307
336
 
308
337
  // ../../node_modules/.bun/esprima@4.0.1/node_modules/esprima/dist/esprima.js
309
338
  var require_esprima = __commonJS(function(exports, module) {
@@ -8359,9 +8388,9 @@ async function runDeferredV22Backfill(db, options = {}) {
8359
8388
  const status = updateFinalBackfillStatus(db);
8360
8389
  const failureCount = countFailures(db);
8361
8390
  if (failureCount > 0) {
8362
- log(`[v22-backfill] completed with ${failureCount} unresolved failure(s); run doctor --retry-v22-backfill`);
8391
+ log2(`[v22-backfill] completed with ${failureCount} unresolved failure(s); run doctor --retry-v22-backfill`);
8363
8392
  } else {
8364
- log(`[v22-backfill] completed; processed=${processedRows}, changed=${changedRows}`);
8393
+ log2(`[v22-backfill] completed; processed=${processedRows}, changed=${changedRows}`);
8365
8394
  }
8366
8395
  return {
8367
8396
  status,
@@ -8460,7 +8489,7 @@ var PackageJsonSchema = object({
8460
8489
 
8461
8490
  // src/hooks/auto-update-checker/checker.ts
8462
8491
  function warn(message) {
8463
- log(`WARN: ${message}`);
8492
+ log2(`WARN: ${message}`);
8464
8493
  }
8465
8494
  function isString(value) {
8466
8495
  return typeof value === "string";
@@ -8530,7 +8559,7 @@ function getWinningConfig(directory, surface) {
8530
8559
  const entries = getPluginEntries(parsed);
8531
8560
  if (entries.some((entry) => entry === PACKAGE_NAME || entry.startsWith(`${PACKAGE_NAME}@`))) {
8532
8561
  if (winner) {
8533
- log(`[auto-update-checker] ${surface} config ${winner.path} is shadowed by ${path}`);
8562
+ log2(`[auto-update-checker] ${surface} config ${winner.path} is shadowed by ${path}`);
8534
8563
  }
8535
8564
  winner = { path, entries };
8536
8565
  }
@@ -8830,7 +8859,7 @@ var DEFAULT_INIT_DELAY_MS = 5000;
8830
8859
  var PENDING_UPDATE_FILENAME = "pending-plugin-update.json";
8831
8860
  var PENDING_UPDATE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
8832
8861
  function warn2(message) {
8833
- log(`WARN: ${message}`);
8862
+ log2(`WARN: ${message}`);
8834
8863
  }
8835
8864
  function createAutoUpdateCheckerHook(ctx, options = {}) {
8836
8865
  const {
@@ -8873,7 +8902,7 @@ async function maybeRunCheck(ctx, options) {
8873
8902
  if (options.signal.aborted)
8874
8903
  return;
8875
8904
  if (!claimCheckSlot(options.storageDir, options.checkIntervalMs)) {
8876
- log("[auto-update-checker] Skipping check (another instance ran one recently)");
8905
+ log2("[auto-update-checker] Skipping check (another instance ran one recently)");
8877
8906
  return;
8878
8907
  }
8879
8908
  await runStartupCheck(ctx, options);
@@ -8937,7 +8966,7 @@ function consumePendingUpdateMarker(storageDir, loadedVersion) {
8937
8966
  const olderThanLoaded = typeof marker.version === "string" && typeof loadedVersion === "string" && (compareSemverCore(marker.version, loadedVersion) ?? 0) < 0;
8938
8967
  if (marker.version === loadedVersion && marker.spec === `${PACKAGE_NAME}@${loadedVersion}` && Array.isArray(marker.configPaths) && marker.configPaths.length === 2) {
8939
8968
  rmSync(path, { force: true });
8940
- log(`[auto-update-checker] Pending update applied: ${marker.spec}`);
8969
+ log2(`[auto-update-checker] Pending update applied: ${marker.spec}`);
8941
8970
  } else if (age > PENDING_UPDATE_MAX_AGE_MS || olderThanLoaded) {
8942
8971
  rmSync(path, { force: true });
8943
8972
  warn2("[auto-update-checker] Discarded stale or mismatched pending update marker");
@@ -8960,7 +8989,7 @@ async function runStartupCheck(ctx, options) {
8960
8989
  if (options.showStartupToast) {
8961
8990
  showToast(ctx, `Magic Context ${displayVersion} (dev)`, "Running in local development mode.", "info");
8962
8991
  }
8963
- log("[auto-update-checker] Local development mode");
8992
+ log2("[auto-update-checker] Local development mode");
8964
8993
  return;
8965
8994
  }
8966
8995
  if (options.showStartupToast) {
@@ -8973,19 +9002,19 @@ async function runBackgroundUpdateCheck(ctx, options) {
8973
9002
  return;
8974
9003
  const pluginInfo = findPluginEntry(ctx.directory);
8975
9004
  if (!pluginInfo) {
8976
- log("[auto-update-checker] Plugin not found in config");
9005
+ log2("[auto-update-checker] Plugin not found in config");
8977
9006
  return;
8978
9007
  }
8979
9008
  if (hasExplicitNonExactPluginVersion(pluginInfo.entry)) {
8980
9009
  if (pluginInfo.entry === `${PACKAGE_NAME}@latest`) {
8981
- log("[auto-update-checker] Explicit @latest leaves the active package unpinned; OpenCode may delete it mid-session.");
9010
+ log2("[auto-update-checker] Explicit @latest leaves the active package unpinned; OpenCode may delete it mid-session.");
8982
9011
  }
8983
9012
  return;
8984
9013
  }
8985
9014
  const cachedVersion = getCachedVersion(pluginInfo.entry);
8986
9015
  const currentVersion = cachedVersion ?? pluginInfo.pinnedVersion;
8987
9016
  if (!currentVersion) {
8988
- log("[auto-update-checker] No version found (cached or pinned)");
9017
+ log2("[auto-update-checker] No version found (cached or pinned)");
8989
9018
  return;
8990
9019
  }
8991
9020
  const channel = extractChannel(pluginInfo.pinnedVersion ?? currentVersion);
@@ -9000,22 +9029,22 @@ async function runBackgroundUpdateCheck(ctx, options) {
9000
9029
  return;
9001
9030
  }
9002
9031
  if (currentVersion === latestVersion) {
9003
- log(`[auto-update-checker] Already on latest version for channel: ${channel}`);
9032
+ log2(`[auto-update-checker] Already on latest version for channel: ${channel}`);
9004
9033
  return;
9005
9034
  }
9006
- log(`[auto-update-checker] Update available (${channel}): ${currentVersion} → ${latestVersion}`);
9035
+ log2(`[auto-update-checker] Update available (${channel}): ${currentVersion} → ${latestVersion}`);
9007
9036
  const updaterOwnedPin = pluginInfo.isPinned && isUpdaterPinnedSpec(readAutoUpdateCheckState(checkStatePath(options.storageDir)), pluginInfo.entry);
9008
9037
  if (pluginInfo.isPinned && !updaterOwnedPin) {
9009
9038
  showToast(ctx, `Magic Context ${latestVersion}`, `v${latestVersion} available. This version was pinned by you; update your OpenCode plugin config to upgrade.`, "info", 8000);
9010
- log("[auto-update-checker] Version was pinned by you; skipping auto-update");
9039
+ log2("[auto-update-checker] Version was pinned by you; skipping auto-update");
9011
9040
  return;
9012
9041
  }
9013
9042
  if (updaterOwnedPin) {
9014
- log("[auto-update-checker] Version was pinned by the updater; continuing auto-update");
9043
+ log2("[auto-update-checker] Version was pinned by the updater; continuing auto-update");
9015
9044
  }
9016
9045
  if (!options.autoUpdate) {
9017
9046
  showToast(ctx, `Magic Context ${latestVersion}`, `v${latestVersion} available. Auto-update is disabled.`, "info", 8000);
9018
- log("[auto-update-checker] Auto-update disabled, notification only");
9047
+ log2("[auto-update-checker] Auto-update disabled, notification only");
9019
9048
  return;
9020
9049
  }
9021
9050
  const preparedUpdate = await preparePluginUpdate(ctx.directory, pluginInfo, latestVersion, {
@@ -9025,7 +9054,7 @@ async function runBackgroundUpdateCheck(ctx, options) {
9025
9054
  writePendingUpdateMarker(options.storageDir, preparedUpdate, latestVersion);
9026
9055
  showToast(ctx, "Magic Context Update Ready", `v${currentVersion} → v${latestVersion}
9027
9056
  Restart OpenCode to apply.`, "success", 8000);
9028
- log(`[auto-update-checker] Update ready: ${currentVersion} → ${latestVersion}`);
9057
+ log2(`[auto-update-checker] Update ready: ${currentVersion} → ${latestVersion}`);
9029
9058
  return;
9030
9059
  }
9031
9060
  showToast(ctx, `Magic Context ${latestVersion}`, `v${latestVersion} available, but auto-update failed to update both plugin configs.`, "error", 8000);
@@ -9276,7 +9305,7 @@ function recordSwallowedWrite(error) {
9276
9305
  try {
9277
9306
  swallowedWriteCount++;
9278
9307
  lastErrorMessage = error instanceof Error ? error.message : String(error);
9279
- log("[magic-context] window report ledger write failed:", error);
9308
+ log2("[magic-context] window report ledger write failed:", error);
9280
9309
  } catch {}
9281
9310
  }
9282
9311
  function positiveFiniteNumber(value) {
@@ -9433,12 +9462,12 @@ function noteContextLimitResolution(sessionId, resolution) {
9433
9462
  const previous = lastResolutionBySession.get(sessionId);
9434
9463
  lastResolutionBySession.set(sessionId, resolution);
9435
9464
  if (!previous) {
9436
- sessionLog(sessionId, `context limit resolved: ${resolution.limit} for ${resolution.modelKey ?? "unknown model"} (catalog ${resolution.catalog ?? "unknown"}, overflow-detected ${resolution.detected}, proven accepted input ${resolution.provenFloor})`);
9465
+ sessionLog2(sessionId, `context limit resolved: ${resolution.limit} for ${resolution.modelKey ?? "unknown model"} (catalog ${resolution.catalog ?? "unknown"}, overflow-detected ${resolution.detected}, proven accepted input ${resolution.provenFloor})`);
9437
9466
  return;
9438
9467
  }
9439
9468
  const change = describeContextLimitChange(previous, resolution);
9440
9469
  if (change)
9441
- sessionLog(sessionId, change);
9470
+ sessionLog2(sessionId, change);
9442
9471
  }
9443
9472
 
9444
9473
  // src/hooks/magic-context/event-handler.ts
@@ -9472,16 +9501,16 @@ async function deliverChannel2IfPending(deps, sessionId) {
9472
9501
  deps.channel2DirectiveTextBySession?.delete(sessionId);
9473
9502
  }
9474
9503
  } catch (error) {
9475
- sessionLog(sessionId, "channel2 delivery wrapper failed (ignored):", error);
9504
+ sessionLog2(sessionId, "channel2 delivery wrapper failed (ignored):", error);
9476
9505
  }
9477
9506
  }
9478
9507
  function cleanupRemovedMessageState(deps, sessionId, messageId) {
9479
- return deps.db.transaction(() => {
9480
- const removedTagNumbers = deleteTagsByMessageId(deps.db, sessionId, messageId);
9508
+ const result = deps.db.transaction(() => {
9509
+ const removedTagNumbers = deleteTagsByMessageId2(deps.db, sessionId, messageId);
9481
9510
  deleteTemporalDecision(deps.db, sessionId, messageId);
9482
- sessionLog(sessionId, `event message.removed: deleted ${removedTagNumbers.length} tag(s) for message ${messageId}`);
9511
+ sessionLog2(sessionId, `event message.removed: deleted ${removedTagNumbers.length} tag(s) for message ${messageId}`);
9483
9512
  const strippedPlaceholderRemoved = removeStrippedPlaceholderId(deps.db, sessionId, messageId);
9484
- sessionLog(sessionId, strippedPlaceholderRemoved ? `event message.removed: removed ${messageId} from stripped placeholder ids` : `event message.removed: stripped placeholder ids unchanged for ${messageId}`);
9513
+ sessionLog2(sessionId, strippedPlaceholderRemoved ? `event message.removed: removed ${messageId} from stripped placeholder ids` : `event message.removed: stripped placeholder ids unchanged for ${messageId}`);
9485
9514
  const removedNoteNudgeAnchor = removeNoteNudgeAnchorByMessageId(deps.db, sessionId, messageId);
9486
9515
  const removedAutoSearchDecision = removeAutoSearchHintDecisionByMessageId(deps.db, sessionId, messageId);
9487
9516
  const persistedNoteNudge = getPersistedNoteNudge(deps.db, sessionId);
@@ -9490,22 +9519,24 @@ function cleanupRemovedMessageState(deps, sessionId, messageId) {
9490
9519
  clearNoteNudgeTriggerOnly(deps.db, sessionId);
9491
9520
  }
9492
9521
  const clearedNoteNudge = removedNoteNudgeAnchor || clearedNoteNudgeTrigger;
9493
- sessionLog(sessionId, clearedNoteNudge ? `event message.removed: pruned note nudge state for ${messageId}` : `event message.removed: note nudge state unchanged for ${messageId}`);
9494
- sessionLog(sessionId, removedAutoSearchDecision ? `event message.removed: pruned auto-search decision for ${messageId}` : `event message.removed: auto-search decision unchanged for ${messageId}`);
9522
+ sessionLog2(sessionId, clearedNoteNudge ? `event message.removed: pruned note nudge state for ${messageId}` : `event message.removed: note nudge state unchanged for ${messageId}`);
9523
+ sessionLog2(sessionId, removedAutoSearchDecision ? `event message.removed: pruned auto-search decision for ${messageId}` : `event message.removed: auto-search decision unchanged for ${messageId}`);
9495
9524
  const currentWatermark = getPersistedReasoningWatermark(deps.db, sessionId);
9496
- const maxRemainingTag = getMaxTagNumberBySession(deps.db, sessionId);
9525
+ const maxRemainingTag = getMaxTagNumberBySession2(deps.db, sessionId);
9497
9526
  if (currentWatermark > maxRemainingTag) {
9498
9527
  setPersistedReasoningWatermark(deps.db, sessionId, maxRemainingTag);
9499
- sessionLog(sessionId, `event message.removed: reset reasoning watermark ${currentWatermark}→${maxRemainingTag}`);
9528
+ sessionLog2(sessionId, `event message.removed: reset reasoning watermark ${currentWatermark}→${maxRemainingTag}`);
9500
9529
  } else {
9501
- sessionLog(sessionId, `event message.removed: reasoning watermark unchanged at ${currentWatermark} (max tag ${maxRemainingTag})`);
9530
+ sessionLog2(sessionId, `event message.removed: reasoning watermark unchanged at ${currentWatermark} (max tag ${maxRemainingTag})`);
9502
9531
  }
9503
9532
  const removedIndexedMessages = deleteIndexedMessage(deps.db, sessionId, messageId);
9504
- sessionLog(sessionId, `event message.removed: deleted ${removedIndexedMessages} indexed message row(s) for ${messageId}`);
9533
+ sessionLog2(sessionId, `event message.removed: deleted ${removedIndexedMessages} indexed message row(s) for ${messageId}`);
9505
9534
  return {
9506
9535
  clearedNoteNudge
9507
9536
  };
9508
9537
  }).immediate();
9538
+ forgetUnpublishedAutoSearchNoHint(sessionId, messageId);
9539
+ return result;
9509
9540
  }
9510
9541
  function createEventHandler2(deps) {
9511
9542
  const newestUsageMessageIdBySession = new Map;
@@ -9520,7 +9551,7 @@ function createEventHandler2(deps) {
9520
9551
  }
9521
9552
  if (deps.internalChildSessions && info.parentID.length > 0 && typeof info.title === "string" && info.title.startsWith(INTERNAL_CHILD_TITLE_PREFIX)) {
9522
9553
  deps.internalChildSessions.add(info.id);
9523
- sessionLog(info.id, `marked internal magic-context child (title="${info.title}") — exempt from transform + injection`);
9554
+ sessionLog2(info.id, `marked internal magic-context child (title="${info.title}") — exempt from transform + injection`);
9524
9555
  }
9525
9556
  try {
9526
9557
  if (info.directory) {
@@ -9533,7 +9564,7 @@ function createEventHandler2(deps) {
9533
9564
  cacheTtl: resolveSessionCacheTtl(deps.db, info.id, ttlConfig.cache_ttl, modelKey, ttlConfig.cacheTtlConfigured).value
9534
9565
  });
9535
9566
  } catch (error) {
9536
- sessionLog(info.id, "event session.created persistence failed:", error);
9567
+ sessionLog2(info.id, "event session.created persistence failed:", error);
9537
9568
  }
9538
9569
  return;
9539
9570
  }
@@ -9558,7 +9589,7 @@ function createEventHandler2(deps) {
9558
9589
  const model = findLastAssistantModelFromOpenCodeDb(errInfo.sessionID);
9559
9590
  if (deps.thinkingBindingRecoveryEnabled !== false && !deps.compactionOff && isPrefixBoundThinkingModel(model?.providerID, model?.modelID)) {
9560
9591
  armBindingRecoverySafely(deps.db, errInfo.sessionID);
9561
- sessionLog(errInfo.sessionID, `thinking binding recovery armed from session.error (provider paths: failing=${bindingMismatch.failingBlockPath ?? "?"} firstChanged=${bindingMismatch.firstChangedPath ?? "?"})`);
9592
+ sessionLog2(errInfo.sessionID, `thinking binding recovery armed from session.error (provider paths: failing=${bindingMismatch.failingBlockPath ?? "?"} firstChanged=${bindingMismatch.firstChangedPath ?? "?"})`);
9562
9593
  dropSlot(errInfo.sessionID, "thinking-binding-recovery-arm");
9563
9594
  deps.onSessionCacheInvalidated?.(errInfo.sessionID);
9564
9595
  }
@@ -9584,7 +9615,7 @@ function createEventHandler2(deps) {
9584
9615
  if (typeof detection.reportedLimit === "number" && detection.reportedLimit > 0) {
9585
9616
  recordDetectedContextLimit(deps.db, errInfo.sessionID, detection.reportedLimit, overflowModelKey, detection.reportedLimitProvenance);
9586
9617
  }
9587
- sessionLog(errInfo.sessionID, `overflow detected on subagent: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} — recorded limit only (subagents cannot run historian)`);
9618
+ sessionLog2(errInfo.sessionID, `overflow detected on subagent: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} — recorded limit only (subagents cannot run historian)`);
9588
9619
  return;
9589
9620
  }
9590
9621
  const existing = getOverflowState(deps.db, errInfo.sessionID);
@@ -9592,7 +9623,7 @@ function createEventHandler2(deps) {
9592
9623
  if (typeof detection.reportedLimit === "number" && detection.reportedLimit > 0) {
9593
9624
  recordDetectedContextLimit(deps.db, errInfo.sessionID, detection.reportedLimit, overflowModelKey, detection.reportedLimitProvenance);
9594
9625
  }
9595
- sessionLog(errInfo.sessionID, `overflow detected in compaction-off mode: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} — recorded limit only (recovery disarmed; native compaction owns the window)`);
9626
+ sessionLog2(errInfo.sessionID, `overflow detected in compaction-off mode: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} — recorded limit only (recovery disarmed; native compaction owns the window)`);
9596
9627
  return;
9597
9628
  }
9598
9629
  dropSlot(errInfo.sessionID, "overflow-recovery-arm");
@@ -9608,10 +9639,10 @@ function createEventHandler2(deps) {
9608
9639
  updatedAt: Date.now()
9609
9640
  });
9610
9641
  }
9611
- sessionLog(errInfo.sessionID, `overflow detected via session.error: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} (previousRecovery=${existing.needsEmergencyRecovery})`);
9642
+ sessionLog2(errInfo.sessionID, `overflow detected via session.error: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} (previousRecovery=${existing.needsEmergencyRecovery})`);
9612
9643
  deps.onSessionCacheInvalidated?.(errInfo.sessionID);
9613
9644
  } catch (error) {
9614
- sessionLog(errInfo.sessionID, "event session.error handling failed:", error);
9645
+ sessionLog2(errInfo.sessionID, "event session.error handling failed:", error);
9615
9646
  }
9616
9647
  return;
9617
9648
  }
@@ -9623,7 +9654,7 @@ function createEventHandler2(deps) {
9623
9654
  const time = rawInfo && typeof rawInfo === "object" && "time" in rawInfo ? rawInfo.time?.created : undefined;
9624
9655
  observeSessionActivity(deps.db, message.sessionID, typeof time === "number" ? time : Date.now());
9625
9656
  } catch (error) {
9626
- sessionLog(message.sessionID, "event message.updated activity persistence failed:", error);
9657
+ sessionLog2(message.sessionID, "event message.updated activity persistence failed:", error);
9627
9658
  }
9628
9659
  }
9629
9660
  const info = getMessageUpdatedAssistantInfo(input.event.properties);
@@ -9633,9 +9664,9 @@ function createEventHandler2(deps) {
9633
9664
  return;
9634
9665
  const sessionId = properties ? resolveSessionId(properties) : null;
9635
9666
  if (sessionId) {
9636
- sessionLog(sessionId, "event message.updated: no assistant info extracted from event");
9667
+ sessionLog2(sessionId, "event message.updated: no assistant info extracted from event");
9637
9668
  } else {
9638
- log("[magic-context] event message.updated: no assistant info extracted from event");
9669
+ log2("[magic-context] event message.updated: no assistant info extracted from event");
9639
9670
  }
9640
9671
  return;
9641
9672
  }
@@ -9674,11 +9705,11 @@ function createEventHandler2(deps) {
9674
9705
  if (bindingMismatch.isBindingMismatch && deps.thinkingBindingRecoveryEnabled !== false && !deps.compactionOff && isPrefixBoundThinkingModel(info.providerID, info.modelID)) {
9675
9706
  try {
9676
9707
  armBindingRecoverySafely(deps.db, info.sessionID);
9677
- sessionLog(info.sessionID, `thinking binding recovery armed from message.updated (provider paths: failing=${bindingMismatch.failingBlockPath ?? "?"} firstChanged=${bindingMismatch.firstChangedPath ?? "?"})`);
9708
+ sessionLog2(info.sessionID, `thinking binding recovery armed from message.updated (provider paths: failing=${bindingMismatch.failingBlockPath ?? "?"} firstChanged=${bindingMismatch.firstChangedPath ?? "?"})`);
9678
9709
  dropSlot(info.sessionID, "thinking-binding-recovery-arm");
9679
9710
  deps.onSessionCacheInvalidated?.(info.sessionID);
9680
9711
  } catch (error) {
9681
- sessionLog(info.sessionID, "event message.updated thinking binding recovery persistence failed:", error);
9712
+ sessionLog2(info.sessionID, "event message.updated thinking binding recovery persistence failed:", error);
9682
9713
  }
9683
9714
  }
9684
9715
  }
@@ -9704,12 +9735,12 @@ function createEventHandler2(deps) {
9704
9735
  if (typeof detection.reportedLimit === "number" && detection.reportedLimit > 0) {
9705
9736
  recordDetectedContextLimit(deps.db, info.sessionID, detection.reportedLimit, overflowModelKey, detection.reportedLimitProvenance);
9706
9737
  }
9707
- sessionLog(info.sessionID, `overflow detected on subagent via message.updated: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} — recorded limit only`);
9738
+ sessionLog2(info.sessionID, `overflow detected on subagent via message.updated: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} — recorded limit only`);
9708
9739
  } else if (deps.compactionOff) {
9709
9740
  if (typeof detection.reportedLimit === "number" && detection.reportedLimit > 0) {
9710
9741
  recordDetectedContextLimit(deps.db, info.sessionID, detection.reportedLimit, overflowModelKey, detection.reportedLimitProvenance);
9711
9742
  }
9712
- sessionLog(info.sessionID, `overflow detected in compaction-off mode via message.updated: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} — recorded limit only`);
9743
+ sessionLog2(info.sessionID, `overflow detected in compaction-off mode via message.updated: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"} — recorded limit only`);
9713
9744
  } else {
9714
9745
  dropSlot(info.sessionID, "overflow-recovery-arm");
9715
9746
  recordOverflowDetected(deps.db, info.sessionID, detection.reportedLimit, overflowModelKey, "provider_overflow", detection.reportedLimitProvenance, detection.reportedInputTokens);
@@ -9724,11 +9755,11 @@ function createEventHandler2(deps) {
9724
9755
  updatedAt: Date.now()
9725
9756
  });
9726
9757
  }
9727
- sessionLog(info.sessionID, `overflow detected via message.updated: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"}`);
9758
+ sessionLog2(info.sessionID, `overflow detected via message.updated: reportedLimit=${detection.reportedLimit ?? "unknown"} provenance=${detection.reportedLimitProvenance ?? "n/a"} pattern=${detection.matchedPattern ?? "n/a"}`);
9728
9759
  deps.onSessionCacheInvalidated?.(info.sessionID);
9729
9760
  }
9730
9761
  } catch (error) {
9731
- sessionLog(info.sessionID, "event message.updated overflow persistence failed:", error);
9762
+ sessionLog2(info.sessionID, "event message.updated overflow persistence failed:", error);
9732
9763
  }
9733
9764
  }
9734
9765
  }
@@ -9758,7 +9789,7 @@ function createEventHandler2(deps) {
9758
9789
  inputTokens: (info.tokens?.input ?? 0) + (info.tokens?.cache?.read ?? 0) + (info.tokens?.cache?.write ?? 0)
9759
9790
  });
9760
9791
  }
9761
- sessionLog(info.sessionID, `event message.updated: provider=${info.providerID} model=${info.modelID} hasUsageTokens=${hasUsageTokens} tokens.input=${info.tokens?.input} cache.read=${info.tokens?.cache?.read} cache.write=${info.tokens?.cache?.write} message.id=${info.messageID} session.id=${info.sessionID}`);
9792
+ sessionLog2(info.sessionID, `event message.updated: provider=${info.providerID} model=${info.modelID} hasUsageTokens=${hasUsageTokens} tokens.input=${info.tokens?.input} cache.read=${info.tokens?.cache?.read} cache.write=${info.tokens?.cache?.write} message.id=${info.messageID} session.id=${info.sessionID}`);
9762
9793
  const hasKnownUsage = hasUsageTokens || deps.contextUsageMap.has(info.sessionID);
9763
9794
  if (successfulCompletion && !hasUsageTokens) {
9764
9795
  try {
@@ -9770,11 +9801,11 @@ function createEventHandler2(deps) {
9770
9801
  });
9771
9802
  }
9772
9803
  } catch (error) {
9773
- sessionLog(info.sessionID, "event completion clock persistence failed:", error);
9804
+ sessionLog2(info.sessionID, "event completion clock persistence failed:", error);
9774
9805
  }
9775
9806
  }
9776
9807
  if (!hasKnownUsage) {
9777
- sessionLog(info.sessionID, "event message.updated: skipping — no usage tokens and no known usage");
9808
+ sessionLog2(info.sessionID, "event message.updated: skipping — no usage tokens and no known usage");
9778
9809
  return;
9779
9810
  }
9780
9811
  try {
@@ -9797,7 +9828,7 @@ function createEventHandler2(deps) {
9797
9828
  if (hasUsageTokens && aboveTrustedWall) {
9798
9829
  if (!usageAboveWallLogSeen.has(aboveWallLogKey)) {
9799
9830
  usageAboveWallLogSeen.add(aboveWallLogKey);
9800
- sessionLog(info.sessionID, `provider usage ${totalInputTokens} exceeds configured window ${trustedAbsoluteWall}; counted as real pressure against the configured limit`);
9831
+ sessionLog2(info.sessionID, `provider usage ${totalInputTokens} exceeds configured window ${trustedAbsoluteWall}; counted as real pressure against the configured limit`);
9801
9832
  }
9802
9833
  } else {
9803
9834
  usageAboveWallLogSeen.delete(aboveWallLogKey);
@@ -9812,7 +9843,7 @@ function createEventHandler2(deps) {
9812
9843
  const detectedLimitMatchesModel = rawOverflow.detectedContextLimitModelKey === null || modelKey !== undefined && rawOverflow.detectedContextLimitModelKey === modelKey;
9813
9844
  if (rawOverflow.detectedContextLimit > 0 && detectedLimitMatchesModel && pressureInputTokens > rawOverflow.detectedContextLimit) {
9814
9845
  clearDetectedContextLimit(deps.db, info.sessionID);
9815
- sessionLog(info.sessionID, `detected limit ${rawOverflow.detectedContextLimit} invalidated by a successful ${pressureInputTokens}-token request; using catalog/default`);
9846
+ sessionLog2(info.sessionID, `detected limit ${rawOverflow.detectedContextLimit} invalidated by a successful ${pressureInputTokens}-token request; using catalog/default`);
9816
9847
  deps.onSessionCacheInvalidated?.(info.sessionID);
9817
9848
  }
9818
9849
  }
@@ -9837,7 +9868,7 @@ function createEventHandler2(deps) {
9837
9868
  };
9838
9869
  const newestMessageId = newestUsageMessageIdBySession.get(info.sessionID);
9839
9870
  if (info.messageID !== undefined && newestMessageId !== undefined && info.messageID < newestMessageId) {
9840
- sessionLog(info.sessionID, `event message.updated: usage ${pressureInputTokens} from ${info.messageID} arrived after newer message ${newestMessageId}; keeping the newer reading`);
9871
+ sessionLog2(info.sessionID, `event message.updated: usage ${pressureInputTokens} from ${info.messageID} arrived after newer message ${newestMessageId}; keeping the newer reading`);
9841
9872
  return;
9842
9873
  }
9843
9874
  if (info.messageID !== undefined) {
@@ -9851,7 +9882,7 @@ function createEventHandler2(deps) {
9851
9882
  detected: getOverflowState(deps.db, info.sessionID, modelKey).detectedContextLimit,
9852
9883
  provenFloor: successfulUsageProof ? provenSafeInputTokens : observedSafeInputTokens
9853
9884
  });
9854
- sessionLog(info.sessionID, `event message.updated: totalInputTokens=${pressureInputTokens} contextLimit=${pressure.contextLimit} percentage=${pressure.percentage.toFixed(1)}%`);
9885
+ sessionLog2(info.sessionID, `event message.updated: totalInputTokens=${pressureInputTokens} contextLimit=${pressure.contextLimit} percentage=${pressure.percentage.toFixed(1)}%`);
9855
9886
  const entry = {
9856
9887
  usage: {
9857
9888
  percentage: pressure.percentage,
@@ -9865,7 +9896,7 @@ function createEventHandler2(deps) {
9865
9896
  const historianFailureState = getHistorianFailureState(deps.db, info.sessionID);
9866
9897
  if (historianFailureState.failureCount > 0 && pressure.percentage < 90) {
9867
9898
  clearHistorianFailureState(deps.db, info.sessionID);
9868
- sessionLog(info.sessionID, `event message.updated: cleared historian failure state at ${pressure.percentage.toFixed(1)}%`);
9899
+ sessionLog2(info.sessionID, `event message.updated: cleared historian failure state at ${pressure.percentage.toFixed(1)}%`);
9869
9900
  }
9870
9901
  return entry;
9871
9902
  };
@@ -9887,7 +9918,7 @@ function createEventHandler2(deps) {
9887
9918
  await refreshModelLimitsFromApi(deps.client);
9888
9919
  catalogLimit = readCatalogLimit();
9889
9920
  if (catalogLimit !== undefined && catalogLimit >= provenSafeInputTokens) {
9890
- sessionLog(info.sessionID, `models-dev-cache: regression recovered for ${info.providerID}/${info.modelID} via refresh (was=${oldLimit}, now=${catalogLimit})`);
9921
+ sessionLog2(info.sessionID, `models-dev-cache: regression recovered for ${info.providerID}/${info.modelID} via refresh (was=${oldLimit}, now=${catalogLimit})`);
9891
9922
  }
9892
9923
  }
9893
9924
  const refreshedUpdates = {};
@@ -9916,7 +9947,7 @@ function createEventHandler2(deps) {
9916
9947
  await refreshLimitsAfterRecording();
9917
9948
  }
9918
9949
  } catch (error) {
9919
- sessionLog(info.sessionID, "event message.updated persistence failed:", error);
9950
+ sessionLog2(info.sessionID, "event message.updated persistence failed:", error);
9920
9951
  }
9921
9952
  if ((info.finish === "stop" || info.finish === "tool-calls") && deps.client && deps.channel1StateBySession && !deps.compactionOff) {
9922
9953
  deliverChannel2IfPending(deps, info.sessionID);
@@ -9928,24 +9959,25 @@ function createEventHandler2(deps) {
9928
9959
  if (!info) {
9929
9960
  const sessionId = properties ? resolveSessionId(properties) : null;
9930
9961
  if (sessionId) {
9931
- sessionLog(sessionId, "event message.removed: no message removal info extracted from event");
9962
+ sessionLog2(sessionId, "event message.removed: no message removal info extracted from event");
9932
9963
  } else {
9933
- log("[magic-context] event message.removed: no message removal info extracted from event");
9964
+ log2("[magic-context] event message.removed: no message removal info extracted from event");
9934
9965
  }
9935
9966
  return;
9936
9967
  }
9937
9968
  dropSlot(info.sessionID, "message.removed");
9969
+ forgetRawSessionOrdinalWatermark2(info.sessionID);
9938
9970
  deps.onRustWireInvalidated?.(info.sessionID);
9939
- sessionLog(info.sessionID, `event message.removed: invalidating state for message ${info.messageID}`);
9971
+ sessionLog2(info.sessionID, `event message.removed: invalidating state for message ${info.messageID}`);
9940
9972
  try {
9941
9973
  cleanupRemovedMessageState(deps, info.sessionID, info.messageID);
9942
9974
  scheduleClearAndReindex(deps.db, info.sessionID, readRawSessionMessages2);
9943
9975
  deps.tagger.cleanup(info.sessionID);
9944
- sessionLog(info.sessionID, "event message.removed: invalidated tagger session cache");
9976
+ sessionLog2(info.sessionID, "event message.removed: invalidated tagger session cache");
9945
9977
  const markerState = getPersistedCompactionMarkerState(deps.db, info.sessionID);
9946
9978
  if (markerState && (markerState.boundaryMessageId === info.messageID || markerState.summaryMessageId === info.messageID)) {
9947
9979
  removeCompactionMarkerForSession(deps.db, info.sessionID);
9948
- sessionLog(info.sessionID, `event message.removed: cleared compaction marker (boundary or summary message removed)`);
9980
+ sessionLog2(info.sessionID, `event message.removed: cleared compaction marker (boundary or summary message removed)`);
9949
9981
  }
9950
9982
  clearMessageTokensCache(info.sessionID, info.messageID);
9951
9983
  invalidateTrueRawTokenCache({
@@ -9954,9 +9986,9 @@ function createEventHandler2(deps) {
9954
9986
  reason: "message.removed"
9955
9987
  });
9956
9988
  deps.onSessionCacheInvalidated?.(info.sessionID);
9957
- sessionLog(info.sessionID, "event message.removed: cleared session injection cache");
9989
+ sessionLog2(info.sessionID, "event message.removed: cleared session injection cache");
9958
9990
  } catch (error) {
9959
- sessionLog(info.sessionID, "event message.removed cleanup failed:", error);
9991
+ sessionLog2(info.sessionID, "event message.removed cleanup failed:", error);
9960
9992
  }
9961
9993
  return;
9962
9994
  }
@@ -9969,12 +10001,12 @@ function createEventHandler2(deps) {
9969
10001
  try {
9970
10002
  deps.compactionHandler.onCompacted(sessionId, deps.db);
9971
10003
  } catch (error) {
9972
- sessionLog(sessionId, "event session.compacted handling failed:", error);
10004
+ sessionLog2(sessionId, "event session.compacted handling failed:", error);
9973
10005
  }
9974
10006
  try {
9975
10007
  removeCompactionMarkerForSession(deps.db, sessionId);
9976
10008
  } catch (error) {
9977
- sessionLog(sessionId, "event session.compacted marker cleanup failed:", error);
10009
+ sessionLog2(sessionId, "event session.compacted marker cleanup failed:", error);
9978
10010
  }
9979
10011
  try {
9980
10012
  const pending = getPendingCompactionMarkerState(deps.db, sessionId);
@@ -9982,7 +10014,7 @@ function createEventHandler2(deps) {
9982
10014
  clearPendingCompactionMarkerStateIf(deps.db, sessionId, pending);
9983
10015
  }
9984
10016
  } catch (error) {
9985
- sessionLog(sessionId, "event session.compacted pending-marker cleanup failed:", error);
10017
+ sessionLog2(sessionId, "event session.compacted pending-marker cleanup failed:", error);
9986
10018
  }
9987
10019
  resetDegradedCacheCount2(sessionId);
9988
10020
  clearMessageTokensCache(sessionId);
@@ -10002,10 +10034,10 @@ function createEventHandler2(deps) {
10002
10034
  await deps.onSessionDeleted?.(sessionId);
10003
10035
  if (!rustCleanupPending || deps.rustSessionCleanup === true) {
10004
10036
  removeCompactionMarkerForSession(deps.db, sessionId);
10005
- clearSession(deps.db, sessionId, deps.rustSessionCleanup === true);
10037
+ clearSession(deps.db, sessionId, deps.rustSessionCleanup === true, true);
10006
10038
  }
10007
10039
  } catch (error) {
10008
- sessionLog(sessionId, "event session.deleted persistence failed:", error);
10040
+ sessionLog2(sessionId, "event session.deleted persistence failed:", error);
10009
10041
  }
10010
10042
  resetDegradedCacheCount2(sessionId);
10011
10043
  deps.onSessionCacheInvalidated?.(sessionId);
@@ -10074,7 +10106,7 @@ function notifyMagicContextDisabled(client, reason) {
10074
10106
  duration: 8000
10075
10107
  }
10076
10108
  }).catch((error) => {
10077
- log("[magic-context] failed to show disabled toast:", error);
10109
+ log2("[magic-context] failed to show disabled toast:", error);
10078
10110
  });
10079
10111
  }
10080
10112
  function createMagicContextHook(deps) {
@@ -10086,7 +10118,7 @@ function createMagicContextHook(deps) {
10086
10118
  if (!opened || !isDatabasePersisted(opened)) {
10087
10119
  const reason = describeStorageUnavailability((opened ? getDatabasePersistenceError(opened) : null) ?? "Failed to initialize the persistent SQLite database.");
10088
10120
  const detail = formatFailClosedBlockingMessage(reason);
10089
- log("[magic-context] disabling feature because persistent storage is unavailable:", detail);
10121
+ log2("[magic-context] disabling feature because persistent storage is unavailable:", detail);
10090
10122
  notifyMagicContextDisabled(deps.client, detail);
10091
10123
  recordHookInitFailure({ type: "storage", reason });
10092
10124
  return null;
@@ -10094,7 +10126,7 @@ function createMagicContextHook(deps) {
10094
10126
  db = opened;
10095
10127
  } catch (error) {
10096
10128
  const reason = getErrorMessage(error);
10097
- log("[magic-context] hook failed to open storage; disabling feature:", error);
10129
+ log2("[magic-context] hook failed to open storage; disabling feature:", error);
10098
10130
  notifyMagicContextDisabled(deps.client, reason);
10099
10131
  clearHookInitFailure();
10100
10132
  recordHookInitFailure({
@@ -10105,7 +10137,7 @@ function createMagicContextHook(deps) {
10105
10137
  }
10106
10138
  const projectPath = resolveProjectIdentityForSession(deps.directory, deps.config.allow_home_project);
10107
10139
  if (!projectPath) {
10108
- log("[magic-context] not binding a project identity for this directory");
10140
+ log2("[magic-context] not binding a project identity for this directory");
10109
10141
  clearHookInitFailure();
10110
10142
  recordHookInitFailure({ type: "no_project" });
10111
10143
  return null;
@@ -10113,7 +10145,7 @@ function createMagicContextHook(deps) {
10113
10145
  try {
10114
10146
  checkCompactionMarkerConsistency(db);
10115
10147
  } catch (error) {
10116
- log("[magic-context] startup compaction-marker consistency check failed:", error);
10148
+ log2("[magic-context] startup compaction-marker consistency check failed:", error);
10117
10149
  }
10118
10150
  let lastScheduleCheckMs = 0;
10119
10151
  let dreamQueueQuietScheduled = false;
@@ -10149,10 +10181,10 @@ function createMagicContextHook(deps) {
10149
10181
  deferredHistoryRefreshSessions.add(sid);
10150
10182
  deferredMaterializationSessions.add(sid);
10151
10183
  }
10152
- log(`[magic-context] rehydrated ${sessionsWithPending.length} session(s) with pending compaction-marker drain at hook init`);
10184
+ log2(`[magic-context] rehydrated ${sessionsWithPending.length} session(s) with pending compaction-marker drain at hook init`);
10153
10185
  }
10154
10186
  } catch (error) {
10155
- log("[magic-context] hook init: pending-marker rehydration failed:", error);
10187
+ log2("[magic-context] hook init: pending-marker rehydration failed:", error);
10156
10188
  }
10157
10189
  const lastHeuristicsTurnId = new Map;
10158
10190
  const commitSeenLastPass = new Map;
@@ -10184,7 +10216,7 @@ function createMagicContextHook(deps) {
10184
10216
  return;
10185
10217
  const notificationParams = getLiveNotificationParams(sessionId, liveModelBySession, variantBySession, agentBySession, (deps.sampleDreamConfig?.() ?? deps.config).toast_duration_ms);
10186
10218
  sendStatusNotification2(deps.client, sessionId, warning, notificationParams).catch((error) => {
10187
- log(`[magic-context] failed to send project identity warning for ${directory}: ${getErrorMessage(error)}`);
10219
+ log2(`[magic-context] failed to send project identity warning for ${directory}: ${getErrorMessage(error)}`);
10188
10220
  });
10189
10221
  };
10190
10222
  const dreamerRunnable = isDreamerRunnable(deps.config);
@@ -10265,7 +10297,7 @@ function createMagicContextHook(deps) {
10265
10297
  if (!sessionProjectIdentity)
10266
10298
  return "No project identity is bound for the home directory.";
10267
10299
  maybeSendProjectIdentitySessionWarning(sessionId, directory);
10268
- const coverage = getEmbeddingCoverageStatus(db, sessionProjectIdentity, sessionId);
10300
+ const coverage = getEmbeddingCoverageStatus2(db, sessionProjectIdentity, sessionId);
10269
10301
  const progress = recompProgressBySession.get(sessionId);
10270
10302
  const drainUi = getEmbedDrainUiStatus(sessionId, progress);
10271
10303
  return formatEmbedStatusText(coverage, {
@@ -10275,11 +10307,11 @@ function createMagicContextHook(deps) {
10275
10307
  });
10276
10308
  };
10277
10309
  const maybeAutoEmbedSession = (sessionId) => {
10278
- if (isEmbeddingHostBusy())
10310
+ if (isEmbeddingHostBusy2())
10279
10311
  return;
10280
10312
  const directory = sessionDirectoryBySession.get(sessionId) ?? deps.directory;
10281
10313
  const identity = resolveProjectIdentityForSession(directory, deps.config.allow_home_project);
10282
- const snapshot = identity ? getProjectEmbeddingSnapshot(identity) : undefined;
10314
+ const snapshot = identity ? getProjectEmbeddingSnapshot2(identity) : undefined;
10283
10315
  const embedIdentity = snapshot ? JSON.stringify([
10284
10316
  snapshot.providerIdentity,
10285
10317
  snapshot.chunkModelId,
@@ -10297,7 +10329,7 @@ function createMagicContextHook(deps) {
10297
10329
  (async () => {
10298
10330
  try {
10299
10331
  await new Promise((resolve) => setTimeout(resolve, 0));
10300
- if (isEmbeddingHostBusy()) {
10332
+ if (isEmbeddingHostBusy2()) {
10301
10333
  invalidateAutoEmbedSession(sessionId);
10302
10334
  return;
10303
10335
  }
@@ -10308,7 +10340,7 @@ function createMagicContextHook(deps) {
10308
10340
  return;
10309
10341
  }
10310
10342
  maybeSendProjectIdentitySessionWarning(sessionId, directory);
10311
- const coverage = await getAutoEmbeddingSessionCoverage(db, sessionProjectIdentity, sessionId);
10343
+ const coverage = await getAutoEmbeddingSessionCoverage2(db, sessionProjectIdentity, sessionId);
10312
10344
  if (!coverage.enabled) {
10313
10345
  invalidateAutoEmbedSession(sessionId);
10314
10346
  return;
@@ -10318,7 +10350,7 @@ function createMagicContextHook(deps) {
10318
10350
  return;
10319
10351
  await executeEmbedHistory(sessionId, { silent: true });
10320
10352
  } catch (error) {
10321
- log("[magic-context] auto-embed drain failed:", error);
10353
+ log2("[magic-context] auto-embed drain failed:", error);
10322
10354
  }
10323
10355
  })();
10324
10356
  };
@@ -10347,7 +10379,7 @@ function createMagicContextHook(deps) {
10347
10379
  variant: "warning",
10348
10380
  duration: 8000
10349
10381
  }
10350
- }).catch((error) => log(`[magic-context] rust park toast failed for ${sessionId}:`, error));
10382
+ }).catch((error) => log2(`[magic-context] rust park toast failed for ${sessionId}:`, error));
10351
10383
  };
10352
10384
  registerLkgPersistence(createDbLkgPersistence(db));
10353
10385
  const transform = createTransform({
@@ -10513,7 +10545,7 @@ function createMagicContextHook(deps) {
10513
10545
  return;
10514
10546
  }
10515
10547
  lastScheduleCheckMs = now;
10516
- const runtimeConfigs = buildDreamTaskRuntimeConfigs2(dreaming, "opencode", deps.config.language, sampledDream.mural?.model);
10548
+ const runtimeConfigs = buildDreamTaskRuntimeConfigs2(dreaming, "opencode", deps.config.language, deps.config.smart_notes?.enabled);
10517
10549
  const executor = createDreamTaskExecutor({
10518
10550
  client: deps.client,
10519
10551
  sessionDirectory: deps.directory,
@@ -10525,6 +10557,7 @@ function createMagicContextHook(deps) {
10525
10557
  userMemoryCollectionEnabled: userMemoryCollectionEnabled2(dreaming),
10526
10558
  language: deps.config.language,
10527
10559
  retinaHandoff: deps.config.smart_notes?.retina_handoff === true,
10560
+ smartNotesEnabled: deps.config.smart_notes?.enabled,
10528
10561
  transformMode: deps.config.transform_mode,
10529
10562
  moduleClient: rustModeModuleClient,
10530
10563
  onProgress: (progress, completedTask) => {
@@ -10542,10 +10575,11 @@ function createMagicContextHook(deps) {
10542
10575
  executor,
10543
10576
  projectMemoryEnabled: deps.config.memory?.enabled !== false
10544
10577
  }).catch((error) => {
10545
- log("[dreamer] scheduled task run failed:", error);
10578
+ log2("[dreamer] scheduled task run failed:", error);
10546
10579
  });
10547
10580
  };
10548
10581
  const commandHandler = createMagicContextCommandHandler({
10582
+ smartNotesEnabled: deps.config.smart_notes?.enabled,
10549
10583
  db,
10550
10584
  compactionOff,
10551
10585
  toastDurationMs: deps.config.toast_duration_ms,
@@ -10555,6 +10589,15 @@ function createMagicContextHook(deps) {
10555
10589
  historyBudgetPercentage: deps.config.history_budget_percentage,
10556
10590
  transformMode: deps.config.transform_mode,
10557
10591
  rustModeModuleClient,
10592
+ resolveRustWrapupHistorianFields: () => {
10593
+ const run = sampleHistorian();
10594
+ return rustWrapupHistorianFields({
10595
+ historianModel: run.model,
10596
+ fallbackModels: run.fallbackModels,
10597
+ timeoutMs: run.timeoutMs,
10598
+ maxOutputTokens: run.maxOutputTokens
10599
+ });
10600
+ },
10558
10601
  projectRoot: deps.directory,
10559
10602
  commitClusterTrigger: deps.config.commit_cluster_trigger,
10560
10603
  sampleCommitClusterTrigger: () => (deps.sampleHistorianConfig?.() ?? deps.config).commit_cluster_trigger,
@@ -10602,7 +10645,7 @@ function createMagicContextHook(deps) {
10602
10645
  return runManualDream({
10603
10646
  db,
10604
10647
  projectIdentity: projectPath,
10605
- tasks: buildDreamTaskRuntimeConfigs2(currentDreamer, "opencode", deps.config.language, sampledDream.mural?.model),
10648
+ tasks: buildDreamTaskRuntimeConfigs2(currentDreamer, "opencode", deps.config.language, deps.config.smart_notes?.enabled),
10606
10649
  executor: createDreamTaskExecutor({
10607
10650
  client: deps.client,
10608
10651
  sessionDirectory: deps.directory,
@@ -10616,6 +10659,7 @@ function createMagicContextHook(deps) {
10616
10659
  mural: sampledDream.mural,
10617
10660
  memoryInjectionBudgetTokens: deps.config.memory?.injection_budget_tokens,
10618
10661
  retinaHandoff: deps.config.smart_notes?.retina_handoff === true,
10662
+ smartNotesEnabled: deps.config.smart_notes?.enabled,
10619
10663
  transformMode: deps.config.transform_mode,
10620
10664
  moduleClient: rustModeModuleClient,
10621
10665
  onProgress: (progress, completedTask) => {
@@ -10634,6 +10678,7 @@ function createMagicContextHook(deps) {
10634
10678
  const systemPromptHash = createSystemPromptHashHandler({
10635
10679
  db,
10636
10680
  dreamerEnabled: dreamerRunnable,
10681
+ smartNotesEnabled: deps.config.smart_notes?.enabled,
10637
10682
  memoryEnabled: deps.config.memory?.enabled !== false,
10638
10683
  language: deps.config.language,
10639
10684
  promptSurface: deps.config.prompt_surface,
@@ -10759,7 +10804,7 @@ async function createMagicContextHookAsync(deps) {
10759
10804
  database = await openDatabaseAsync({ onBootTimings: deps.onStorageBootTimings });
10760
10805
  } catch (error) {
10761
10806
  const reason = getErrorMessage(error);
10762
- log("[magic-context] hook failed to open storage; disabling feature:", error);
10807
+ log2("[magic-context] hook failed to open storage; disabling feature:", error);
10763
10808
  notifyMagicContextDisabled(deps.client, reason);
10764
10809
  clearHookInitFailure();
10765
10810
  recordHookInitFailure({
@@ -10816,18 +10861,25 @@ async function createSessionHooksAsync(args) {
10816
10861
  };
10817
10862
  }
10818
10863
 
10819
- // src/plugin/host-stall-profiler.ts
10820
- import { chmodSync, existsSync as existsSync5, readdirSync, readFileSync as readFileSync5, unlinkSync } from "node:fs";
10864
+ // src/shared/host-stall-profiler.ts
10865
+ import * as path7 from "node:path";
10866
+
10867
+ // src/shared/host-stall-profiler-bun.ts
10868
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
10869
+ import * as path5 from "node:path";
10870
+
10871
+ // src/shared/host-stall-profiler-common.ts
10872
+ import { chmodSync, existsSync as existsSync5, readdirSync, unlinkSync } from "node:fs";
10821
10873
  import * as path4 from "node:path";
10822
10874
 
10823
- // src/plugin/host-stall-profiler-report.ts
10875
+ // src/shared/host-stall-profiler-report.ts
10824
10876
  import { readFileSync as readFileSync4 } from "node:fs";
10825
10877
  import * as path3 from "node:path";
10826
10878
  var MAX_STACK_DEPTH = 64;
10827
10879
  var TOP_STACK_COUNT = 30;
10828
10880
  var TOP_FRAME_COUNT = 30;
10829
10881
  var UNKNOWN_POSITION = 4294967295;
10830
- var BACKGROUND_OWNERS = new Set(["native", "runtime", "opencode"]);
10882
+ var BACKGROUND_OWNERS = new Set(["native", "runtime", "opencode", "pi", "omp"]);
10831
10883
  var packageNameCache = new Map;
10832
10884
  function urlToPath(url) {
10833
10885
  if (url.startsWith("file://")) {
@@ -10878,8 +10930,21 @@ function sourceOwner(sourceURL) {
10878
10930
  const filePath = urlToPath(sourceURL).replaceAll("\\", "/");
10879
10931
  const modules = [...filePath.matchAll(/\/node_modules\/((?:@[^/]+\/)?[^/]+)/g)];
10880
10932
  const innermost = modules.at(-1);
10881
- if (innermost)
10882
- return `npm:${innermost[1]}`;
10933
+ if (innermost) {
10934
+ const name = innermost[1];
10935
+ if (name === "@cortexkit/pi-magic-context")
10936
+ return `pkg:${name}`;
10937
+ if (/^@(?:earendil-works|mariozechner)\/pi-(?:coding-agent|agent-core|ai|tui)$/.test(name))
10938
+ return "pi";
10939
+ if (/^@oh-my-pi\/pi-(?:coding-agent|agent-core|ai|tui)$/.test(name))
10940
+ return "omp";
10941
+ return `npm:${name}`;
10942
+ }
10943
+ const extension = filePath.match(/\/(?:\.pi|\.omp)\/agent\/extensions\/([^/]+)/);
10944
+ if (extension) {
10945
+ const name = nearestPackageName(filePath);
10946
+ return name ? `pkg:${name}` : `extension:${extension[1]}`;
10947
+ }
10883
10948
  const pluginDir = filePath.match(/\/plugins?\/([^/]+)$/);
10884
10949
  if (pluginDir && /\/(?:\.?opencode)\/plugins?\//.test(filePath)) {
10885
10950
  return `plugin:${pluginDir[1]}`;
@@ -10971,39 +11036,33 @@ function aggregateTraces(traces) {
10971
11036
  };
10972
11037
  }
10973
11038
 
10974
- // src/plugin/host-stall-profiler.ts
11039
+ // src/shared/host-stall-profiler-common.ts
10975
11040
  var HOST_PROFILER_DIRNAME = "host-profiler";
10976
11041
  var HOST_PROFILER_ENABLE_FILENAME = "enable";
10977
- var SWITCH_POLL_MS = 30000;
11042
+ var SWITCH_POLL_MS = 5000;
10978
11043
  var WATCHDOG_INTERVAL_MS = 250;
10979
11044
  var DEFAULT_STALL_THRESHOLD_MS = 3000;
10980
11045
  var DEFAULT_SAMPLE_INTERVAL_MS = 10;
10981
11046
  var MAX_REPORT_FILES = 50;
10982
11047
  var MAX_SAMPLES_PER_WINDOW = 20000;
10983
- var MEMORY_SNAPSHOT_EVERY_TICKS = 4;
10984
- var CALIBRATION_CHUNK_MS = 3;
10985
- var CALIBRATION_MAX_CHUNKS = 30;
10986
- function clamp(value, min, max) {
10987
- return Math.min(max, Math.max(min, value));
10988
- }
11048
+ var PROFILE_WINDOW_MS = 1e4;
10989
11049
  function parseEnableFile(content) {
10990
11050
  const options = {
10991
11051
  thresholdMs: DEFAULT_STALL_THRESHOLD_MS,
10992
11052
  sampleIntervalMs: DEFAULT_SAMPLE_INTERVAL_MS
10993
11053
  };
10994
- const trimmed = content.trim();
10995
- if (trimmed === "")
11054
+ if (!content.trim())
10996
11055
  return { options, error: null };
10997
11056
  try {
10998
- const parsed = JSON.parse(trimmed);
11057
+ const parsed = JSON.parse(content);
10999
11058
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
11000
11059
  return { options, error: "enable file is not a JSON object" };
11001
11060
  }
11002
11061
  if (typeof parsed.threshold_ms === "number" && Number.isFinite(parsed.threshold_ms)) {
11003
- options.thresholdMs = clamp(parsed.threshold_ms, 500, 600000);
11062
+ options.thresholdMs = Math.min(600000, Math.max(500, parsed.threshold_ms));
11004
11063
  }
11005
11064
  if (typeof parsed.sample_interval_ms === "number" && Number.isFinite(parsed.sample_interval_ms)) {
11006
- options.sampleIntervalMs = clamp(parsed.sample_interval_ms, 1, 100);
11065
+ options.sampleIntervalMs = Math.min(100, Math.max(1, parsed.sample_interval_ms));
11007
11066
  }
11008
11067
  return { options, error: null };
11009
11068
  } catch (error) {
@@ -11013,6 +11072,66 @@ function parseEnableFile(content) {
11013
11072
  };
11014
11073
  }
11015
11074
  }
11075
+ function emitStallReport(deps, input) {
11076
+ const { traces, windowed, options, startMs, endMs } = input;
11077
+ const stride = windowed.length / MAX_SAMPLES_PER_WINDOW;
11078
+ const kept = windowed.length <= MAX_SAMPLES_PER_WINDOW ? windowed : Array.from({ length: MAX_SAMPLES_PER_WINDOW }, (_, i) => windowed[Math.floor(i * stride)]);
11079
+ const aggregate = aggregateTraces(kept);
11080
+ const gapMs = endMs - startMs;
11081
+ const endWallMs = deps.wallNow();
11082
+ const report = {
11083
+ kind: "magic-context-host-stall",
11084
+ schema_version: 1,
11085
+ pid: deps.pid,
11086
+ bun_version: deps.bunVersion,
11087
+ node_version: input.backend === "v8" ? process.versions.node : undefined,
11088
+ backend: input.backend,
11089
+ platform: process.platform,
11090
+ window: {
11091
+ start: new Date(endWallMs - gapMs).toISOString(),
11092
+ end: new Date(endWallMs).toISOString(),
11093
+ duration_ms: Math.round(gapMs),
11094
+ lag_ms: Math.round(gapMs - WATCHDOG_INTERVAL_MS),
11095
+ threshold_ms: options.thresholdMs
11096
+ },
11097
+ sampling: {
11098
+ interval_ms: options.sampleIntervalMs,
11099
+ samples_collected: traces.length,
11100
+ samples_in_window: windowed.length,
11101
+ samples_aggregated: kept.length,
11102
+ window_filter: input.windowFilter,
11103
+ note: aggregate.samples === 0 ? "No JavaScript samples in the window: the main thread was not executing inside the JavaScript VM (idle wait, process suspension, or native work outside any JS call)." : undefined
11104
+ },
11105
+ memory: { before: input.before, after: input.after },
11106
+ owners: aggregate.owners,
11107
+ top_frames: aggregate.top_frames,
11108
+ top_js_frames: aggregate.top_js_frames,
11109
+ top_stacks: aggregate.top_stacks
11110
+ };
11111
+ const dir = deps.profilerDir();
11112
+ ensureStorageDirectorySync(dir, true);
11113
+ chmodSync(dir, 448);
11114
+ const stamp = new Date(endWallMs).toISOString().replaceAll(":", "-");
11115
+ let name = `stall-${stamp}.json`;
11116
+ for (let n = 1;existsSync5(path4.join(dir, name)); n++)
11117
+ name = `stall-${stamp}-${n}.json`;
11118
+ const file = path4.join(dir, name);
11119
+ writeStorageFileAtomicSync(file, `${JSON.stringify(report, null, 2)}
11120
+ `, true);
11121
+ const reports = readdirSync(dir).filter((entry) => /^stall-.*\.json$/.test(entry)).sort();
11122
+ for (const stale of reports.slice(0, Math.max(0, reports.length - MAX_REPORT_FILES))) {
11123
+ try {
11124
+ unlinkSync(path4.join(dir, stale));
11125
+ } catch {}
11126
+ }
11127
+ const top = aggregate.owners[0];
11128
+ deps.log(`[magic-context] host stall profiler: ${Math.round(gapMs)}ms main-thread stall, ${aggregate.samples} samples, top owner ${top ? `${top.owner} (${top.percent}%)` : "none"} → ${file}`);
11129
+ }
11130
+
11131
+ // src/shared/host-stall-profiler-bun.ts
11132
+ var MEMORY_SNAPSHOT_EVERY_TICKS = 4;
11133
+ var CALIBRATION_CHUNK_MS = 3;
11134
+ var CALIBRATION_MAX_CHUNKS = 30;
11016
11135
  function asJscApi(module) {
11017
11136
  const candidate = module ?? null;
11018
11137
  for (const value of [candidate, candidate?.default]) {
@@ -11023,18 +11142,6 @@ function asJscApi(module) {
11023
11142
  }
11024
11143
  return null;
11025
11144
  }
11026
- function thin(items, limit) {
11027
- if (items.length <= limit)
11028
- return items;
11029
- const stride = items.length / limit;
11030
- const out = [];
11031
- for (let i = 0;i < limit; i++)
11032
- out.push(items[Math.floor(i * stride)]);
11033
- return out;
11034
- }
11035
- function reportFileStamp(epochMs) {
11036
- return new Date(epochMs).toISOString().replaceAll(":", "-");
11037
- }
11038
11145
  function createHostStallProfiler(deps) {
11039
11146
  let jsc = null;
11040
11147
  let unavailable = false;
@@ -11109,30 +11216,8 @@ function createHostStallProfiler(deps) {
11109
11216
  percent_available_memory_in_use: read(() => api.percentAvailableMemoryInUse?.() ?? null)
11110
11217
  };
11111
11218
  };
11112
- const writeReport = (report, endWallMs) => {
11113
- const dir = deps.profilerDir();
11114
- ensureStorageDirectorySync(dir, true);
11115
- chmodSync(dir, 448);
11116
- const stamp = reportFileStamp(endWallMs);
11117
- let name = `stall-${stamp}.json`;
11118
- for (let n = 1;existsSync5(path4.join(dir, name)); n++)
11119
- name = `stall-${stamp}-${n}.json`;
11120
- const finalPath = path4.join(dir, name);
11121
- writeStorageFileAtomicSync(finalPath, `${JSON.stringify(report, null, 2)}
11122
- `, true);
11123
- const reports = readdirSync(dir).filter((entry) => /^stall-.*\.json$/.test(entry)).sort();
11124
- for (const stale of reports.slice(0, Math.max(0, reports.length - MAX_REPORT_FILES))) {
11125
- try {
11126
- unlinkSync(path4.join(dir, stale));
11127
- } catch (error) {
11128
- logOnce("prune", "could not prune an old report", error);
11129
- }
11130
- }
11131
- return finalPath;
11132
- };
11133
11219
  const recordStall = (api, startMs, endMs, traces) => {
11134
11220
  const after = snapshot(api);
11135
- const gapMs = endMs - startMs;
11136
11221
  let windowed = traces;
11137
11222
  let windowFilter = "since-last-collection";
11138
11223
  if (clockOffsetMs !== null) {
@@ -11150,40 +11235,17 @@ function createHostStallProfiler(deps) {
11150
11235
  windowFilter = "since-last-collection (timestamp filter matched no sample)";
11151
11236
  }
11152
11237
  }
11153
- const kept = thin(windowed, MAX_SAMPLES_PER_WINDOW);
11154
- const aggregate = aggregateTraces(kept);
11155
- const endWallMs = deps.wallNow();
11156
- const startWallMs = endWallMs - gapMs;
11157
- const report = {
11158
- kind: "magic-context-host-stall",
11159
- schema_version: 1,
11160
- pid: deps.pid,
11161
- bun_version: deps.bunVersion,
11162
- platform: process.platform,
11163
- window: {
11164
- start: new Date(startWallMs).toISOString(),
11165
- end: new Date(endWallMs).toISOString(),
11166
- duration_ms: Math.round(gapMs),
11167
- lag_ms: Math.round(gapMs - WATCHDOG_INTERVAL_MS),
11168
- threshold_ms: options.thresholdMs
11169
- },
11170
- sampling: {
11171
- interval_ms: options.sampleIntervalMs,
11172
- samples_collected: traces.length,
11173
- samples_in_window: windowed.length,
11174
- samples_aggregated: kept.length,
11175
- window_filter: windowFilter,
11176
- note: aggregate.samples === 0 ? "No JavaScript samples in the window: the main thread was not executing inside the JavaScript VM (idle wait, process suspension, or native work outside any JS call)." : undefined
11177
- },
11178
- memory: { before: memoryBefore, after },
11179
- owners: aggregate.owners,
11180
- top_frames: aggregate.top_frames,
11181
- top_js_frames: aggregate.top_js_frames,
11182
- top_stacks: aggregate.top_stacks
11183
- };
11184
- const file = writeReport(report, endWallMs);
11185
- const top = aggregate.owners[0];
11186
- safeLog(`[magic-context] host stall profiler: ${Math.round(gapMs)}ms main-thread stall, ${aggregate.samples} samples, top owner ${top ? `${top.owner} (${top.percent}%)` : "none"} → ${file}`);
11238
+ emitStallReport(deps, {
11239
+ startMs,
11240
+ endMs,
11241
+ traces,
11242
+ windowed,
11243
+ windowFilter,
11244
+ options,
11245
+ before: memoryBefore,
11246
+ after,
11247
+ backend: "jsc"
11248
+ });
11187
11249
  memoryBefore = after;
11188
11250
  };
11189
11251
  const tick = () => {
@@ -11195,7 +11257,7 @@ function createHostStallProfiler(deps) {
11195
11257
  const startMs = lastTickAt;
11196
11258
  lastTickAt = now;
11197
11259
  const traces = drain(api);
11198
- if (now - startMs > options.thresholdMs) {
11260
+ if (now - startMs - WATCHDOG_INTERVAL_MS >= options.thresholdMs) {
11199
11261
  try {
11200
11262
  recordStall(api, startMs, now, traces);
11201
11263
  } catch (error) {
@@ -11265,8 +11327,8 @@ function createHostStallProfiler(deps) {
11265
11327
  if (unavailable)
11266
11328
  return;
11267
11329
  try {
11268
- const enablePath = path4.join(deps.profilerDir(), HOST_PROFILER_ENABLE_FILENAME);
11269
- if (!existsSync5(enablePath)) {
11330
+ const enablePath = path5.join(deps.profilerDir(), HOST_PROFILER_ENABLE_FILENAME);
11331
+ if (!existsSync6(enablePath)) {
11270
11332
  if (watchdog !== null)
11271
11333
  disable("enable file removed");
11272
11334
  return;
@@ -11283,7 +11345,7 @@ function createHostStallProfiler(deps) {
11283
11345
  return;
11284
11346
  }
11285
11347
  const api = await ensureJsc();
11286
- if (!api || watchdog !== null || !existsSync5(enablePath))
11348
+ if (!api || watchdog !== null || !existsSync6(enablePath))
11287
11349
  return;
11288
11350
  enable(api, parsed.options);
11289
11351
  } catch (error) {
@@ -11317,45 +11379,285 @@ function createHostStallProfiler(deps) {
11317
11379
  isUnavailable: () => unavailable
11318
11380
  };
11319
11381
  }
11320
- function hostStallProfilerDir() {
11321
- return path4.join(getMagicContextStorageDir(), HOST_PROFILER_DIRNAME);
11382
+
11383
+ // src/shared/host-stall-profiler-node.ts
11384
+ import { existsSync as existsSync7, readFileSync as readFileSync6 } from "node:fs";
11385
+ import * as path6 from "node:path";
11386
+ function v8ProfileTraces(profile, windowStartMs) {
11387
+ const nodes = new Map(profile.nodes.map((node) => [node.id, node]));
11388
+ const parents = new Map;
11389
+ for (const node of profile.nodes)
11390
+ for (const child of node.children ?? [])
11391
+ parents.set(child, node.id);
11392
+ const stacks = new Map;
11393
+ const stackFor = (id) => {
11394
+ const cached = stacks.get(id);
11395
+ if (cached)
11396
+ return cached;
11397
+ const frames = [];
11398
+ const seen = new Set;
11399
+ let next = id;
11400
+ while (next !== undefined && !seen.has(next)) {
11401
+ seen.add(next);
11402
+ const node = nodes.get(next);
11403
+ if (!node)
11404
+ break;
11405
+ const frame = node.callFrame;
11406
+ if (frame.functionName !== "(root)" && frame.functionName !== "(idle)") {
11407
+ frames.push({
11408
+ name: frame.functionName,
11409
+ sourceURL: frame.url || undefined,
11410
+ line: frame.lineNumber >= 0 ? frame.lineNumber + 1 : undefined,
11411
+ column: frame.columnNumber >= 0 ? frame.columnNumber + 1 : undefined
11412
+ });
11413
+ }
11414
+ next = parents.get(next);
11415
+ }
11416
+ stacks.set(id, frames);
11417
+ return frames;
11418
+ };
11419
+ let elapsedMicros = 0;
11420
+ return (profile.samples ?? []).flatMap((id, index) => {
11421
+ const delta = profile.timeDeltas?.[index];
11422
+ if (typeof delta !== "number" || !Number.isFinite(delta))
11423
+ return [];
11424
+ elapsedMicros += delta;
11425
+ return [{ timestamp: (windowStartMs + elapsedMicros / 1000) / 1000, frames: stackFor(id) }];
11426
+ });
11322
11427
  }
11323
- function defaultDeps() {
11428
+ function createNodeHostStallProfiler(deps) {
11429
+ let session = null;
11430
+ let pollTimer = null;
11431
+ let watchdog = null;
11432
+ let stopped = false;
11433
+ let unavailable = false;
11434
+ let options = {
11435
+ thresholdMs: DEFAULT_STALL_THRESHOLD_MS,
11436
+ sampleIntervalMs: DEFAULT_SAMPLE_INTERVAL_MS
11437
+ };
11438
+ let lastTickAt = 0;
11439
+ let windowStartMs = 0;
11440
+ let memoryBefore = null;
11441
+ let work = Promise.resolve();
11442
+ const logged = new Set;
11443
+ const safeLog = (message) => {
11444
+ try {
11445
+ deps.log(message);
11446
+ } catch {}
11447
+ };
11448
+ const fail = (key, error) => {
11449
+ if (logged.has(key))
11450
+ return;
11451
+ logged.add(key);
11452
+ safeLog(`[magic-context] host stall profiler: ${key}: ${error instanceof Error ? error.message : String(error)}`);
11453
+ };
11454
+ const post = (api, method, params = {}) => new Promise((resolve, reject) => {
11455
+ api.post(method, params, (error, result) => error ? reject(error) : resolve(result ?? {}));
11456
+ });
11457
+ const snapshot = () => {
11458
+ const memory = deps.memoryUsage();
11459
+ return {
11460
+ at: new Date(deps.wallNow()).toISOString(),
11461
+ heap_size_bytes: memory.heapUsed,
11462
+ rss_bytes: memory.rss,
11463
+ jsc_memory: null,
11464
+ percent_available_memory_in_use: null
11465
+ };
11466
+ };
11467
+ const disable = async (reason) => {
11468
+ if (watchdog !== null)
11469
+ deps.clearInterval(watchdog);
11470
+ watchdog = null;
11471
+ const api = session;
11472
+ session = null;
11473
+ memoryBefore = null;
11474
+ if (!api)
11475
+ return;
11476
+ try {
11477
+ await post(api, "Profiler.stop");
11478
+ } catch (error) {
11479
+ fail("stop failed", error);
11480
+ } finally {
11481
+ try {
11482
+ api.disconnect();
11483
+ } catch (error) {
11484
+ fail("disconnect failed", error);
11485
+ }
11486
+ }
11487
+ safeLog(`[magic-context] host stall profiler disabled: ${reason}`);
11488
+ };
11489
+ const startWindow = async (api) => {
11490
+ windowStartMs = deps.now();
11491
+ await post(api, "Profiler.start");
11492
+ };
11493
+ const tick = async () => {
11494
+ const api = session;
11495
+ if (!api || watchdog === null)
11496
+ return;
11497
+ const now = deps.now();
11498
+ const startMs = lastTickAt;
11499
+ lastTickAt = now;
11500
+ const stall = now - startMs - WATCHDOG_INTERVAL_MS >= options.thresholdMs;
11501
+ if (!stall && now - windowStartMs < PROFILE_WINDOW_MS)
11502
+ return;
11503
+ try {
11504
+ const { profile } = await post(api, "Profiler.stop");
11505
+ const profileStartMs = windowStartMs;
11506
+ if (session !== api || stopped)
11507
+ return;
11508
+ await startWindow(api);
11509
+ const after = snapshot();
11510
+ if (stall && profile) {
11511
+ const traces = v8ProfileTraces(profile, profileStartMs);
11512
+ const slackMs = 2 * options.sampleIntervalMs + 20;
11513
+ const windowed = traces.filter((trace) => {
11514
+ const at = (trace.timestamp ?? 0) * 1000;
11515
+ return at >= startMs - slackMs && at <= now + slackMs;
11516
+ });
11517
+ try {
11518
+ emitStallReport(deps, {
11519
+ startMs,
11520
+ endMs: now,
11521
+ traces,
11522
+ windowed,
11523
+ windowFilter: "timestamp",
11524
+ options,
11525
+ before: memoryBefore,
11526
+ after,
11527
+ backend: "v8"
11528
+ });
11529
+ } catch (error) {
11530
+ fail("could not write a stall report", error);
11531
+ }
11532
+ }
11533
+ memoryBefore = after;
11534
+ } catch (error) {
11535
+ fail("watchdog tick failed", error);
11536
+ await disable("sampling failed");
11537
+ }
11538
+ };
11539
+ const enqueue = (fn) => {
11540
+ work = work.then(fn).catch((error) => fail("profiler operation failed", error));
11541
+ return work;
11542
+ };
11543
+ const runCheck = async () => {
11544
+ if (stopped || unavailable)
11545
+ return;
11546
+ const enablePath = path6.join(deps.profilerDir(), HOST_PROFILER_ENABLE_FILENAME);
11547
+ if (!existsSync7(enablePath)) {
11548
+ await disable("enable file removed");
11549
+ return;
11550
+ }
11551
+ const parsed = parseEnableFile(readFileSync6(enablePath, "utf8"));
11552
+ if (parsed.error)
11553
+ fail("enable options", parsed.error);
11554
+ if (session && parsed.options.sampleIntervalMs === options.sampleIntervalMs) {
11555
+ options = parsed.options;
11556
+ return;
11557
+ }
11558
+ if (session)
11559
+ await disable("sample interval changed");
11560
+ options = parsed.options;
11561
+ try {
11562
+ const api = await deps.createSession();
11563
+ if (stopped || !existsSync7(enablePath))
11564
+ return;
11565
+ session = api;
11566
+ api.connect();
11567
+ await post(api, "Profiler.enable");
11568
+ await post(api, "Profiler.setSamplingInterval", {
11569
+ interval: Math.round(options.sampleIntervalMs * 1000)
11570
+ });
11571
+ await startWindow(api);
11572
+ if (stopped || !existsSync7(enablePath)) {
11573
+ await disable("enable file removed");
11574
+ return;
11575
+ }
11576
+ lastTickAt = deps.now();
11577
+ memoryBefore = snapshot();
11578
+ watchdog = deps.setInterval(() => {
11579
+ enqueue(tick);
11580
+ }, WATCHDOG_INTERVAL_MS);
11581
+ safeLog(`[magic-context] host stall profiler enabled: threshold ${options.thresholdMs}ms, sample interval ${options.sampleIntervalMs}ms, backend v8, rotation ${PROFILE_WINDOW_MS}ms, reports in ${deps.profilerDir()}`);
11582
+ } catch (error) {
11583
+ fail("could not start inspector profiler", error);
11584
+ await disable("inspector unavailable");
11585
+ unavailable = true;
11586
+ if (pollTimer !== null)
11587
+ deps.clearInterval(pollTimer);
11588
+ pollTimer = null;
11589
+ }
11590
+ };
11324
11591
  return {
11325
- profilerDir: hostStallProfilerDir,
11326
- loadJsc: () => import("bun:jsc"),
11327
- now: () => performance.now(),
11328
- wallNow: () => Date.now(),
11329
- setInterval: (callback, ms) => {
11330
- const handle = setInterval(callback, ms);
11331
- handle.unref?.();
11332
- return handle;
11592
+ start() {
11593
+ if (pollTimer !== null || unavailable)
11594
+ return;
11595
+ stopped = false;
11596
+ pollTimer = deps.setInterval(() => {
11597
+ enqueue(runCheck);
11598
+ }, SWITCH_POLL_MS);
11599
+ enqueue(runCheck);
11333
11600
  },
11334
- clearInterval: (handle) => clearInterval(handle),
11335
- rss: () => process.memoryUsage.rss(),
11336
- log,
11337
- pid: process.pid,
11338
- bunVersion: process.versions.bun ?? null
11601
+ checkNow: () => enqueue(runCheck),
11602
+ stop() {
11603
+ stopped = true;
11604
+ if (pollTimer !== null)
11605
+ deps.clearInterval(pollTimer);
11606
+ pollTimer = null;
11607
+ if (watchdog !== null)
11608
+ deps.clearInterval(watchdog);
11609
+ watchdog = null;
11610
+ enqueue(() => disable("stopped"));
11611
+ },
11612
+ isActive: () => watchdog !== null,
11613
+ isUnavailable: () => unavailable
11339
11614
  };
11340
11615
  }
11616
+
11617
+ // src/shared/host-stall-profiler.ts
11618
+ function hostStallProfilerDir() {
11619
+ return path7.join(getMagicContextStorageDir(), HOST_PROFILER_DIRNAME);
11620
+ }
11341
11621
  var PROCESS_PROFILER_KEY = Symbol.for("cortexkit.magic-context.host-stall-profiler");
11622
+ var jscModule = "bun:jsc";
11342
11623
  function startHostStallProfilerSwitch() {
11343
11624
  try {
11344
11625
  const holder = globalThis;
11345
11626
  if (holder[PROCESS_PROFILER_KEY])
11346
11627
  return;
11347
- const handle = createHostStallProfiler(defaultDeps());
11628
+ const deps = {
11629
+ profilerDir: hostStallProfilerDir,
11630
+ now: () => performance.now(),
11631
+ wallNow: () => Date.now(),
11632
+ setInterval: (callback, ms) => {
11633
+ const handle = setInterval(callback, ms);
11634
+ handle.unref?.();
11635
+ return handle;
11636
+ },
11637
+ clearInterval: (handle) => clearInterval(handle),
11638
+ rss: () => process.memoryUsage.rss(),
11639
+ log: log2,
11640
+ pid: process.pid,
11641
+ bunVersion: process.versions.bun ?? null
11642
+ };
11643
+ const handle = process.versions.bun ? createHostStallProfiler({ ...deps, loadJsc: () => import(jscModule) }) : createNodeHostStallProfiler({
11644
+ ...deps,
11645
+ createSession: async () => {
11646
+ const { Session } = await import("node:inspector");
11647
+ return new Session;
11648
+ },
11649
+ memoryUsage: () => process.memoryUsage()
11650
+ });
11348
11651
  holder[PROCESS_PROFILER_KEY] = handle;
11349
11652
  handle.start();
11350
11653
  } catch (error) {
11351
- log("[magic-context] host stall profiler: could not start the enable-file switch", error);
11654
+ log2("[magic-context] host stall profiler: could not start the enable-file switch", error);
11352
11655
  }
11353
11656
  }
11354
-
11355
11657
  // src/plugin/instance-disposal.ts
11356
- import path5 from "node:path";
11658
+ import path8 from "node:path";
11357
11659
  function isDisposedInstanceDirectory(ownDirectory, disposedDirectory) {
11358
- return path5.resolve(disposedDirectory) === path5.resolve(ownDirectory);
11660
+ return path8.resolve(disposedDirectory) === path8.resolve(ownDirectory);
11359
11661
  }
11360
11662
 
11361
11663
  // src/plugin/native-compaction-guard.ts
@@ -11364,7 +11666,7 @@ function disableNativeAutoCompaction(config) {
11364
11666
  if (target.compaction?.auto === false)
11365
11667
  return false;
11366
11668
  target.compaction = { ...target.compaction ?? {}, auto: false };
11367
- log("[magic-context] OpenCode auto-compaction was not disabled in any config layer; turned it off for this instance because Magic Context manages compaction");
11669
+ log2("[magic-context] OpenCode auto-compaction was not disabled in any config layer; turned it off for this instance because Magic Context manages compaction");
11368
11670
  return true;
11369
11671
  }
11370
11672
 
@@ -11435,7 +11737,7 @@ function createToolRegistry(args) {
11435
11737
  return {};
11436
11738
  }
11437
11739
  ensureProjectRegisteredFromOpenCodeDirectory(ctx.directory, db).catch((error) => {
11438
- log(`[magic-context] embedding registration skipped: ${getErrorMessage(error)}`);
11740
+ log2(`[magic-context] embedding registration skipped: ${getErrorMessage(error)}`);
11439
11741
  });
11440
11742
  const resolveProjectPath = (directory) => resolveProjectIdentityForSession(directory, pluginConfig.allow_home_project);
11441
11743
  const memoryEnabled = pluginConfig.memory?.enabled !== false;
@@ -11450,11 +11752,13 @@ function createToolRegistry(args) {
11450
11752
  ...createCtxNoteTools({
11451
11753
  db,
11452
11754
  dreamerEnabled: isDreamerRunnable(pluginConfig),
11755
+ smartNotesEnabled: pluginConfig.smart_notes?.enabled,
11453
11756
  resolveProjectPath,
11454
11757
  rustToolBackends
11455
11758
  }),
11456
11759
  ...createCtxSearchTools({
11457
11760
  db,
11761
+ rerankConnectionFile: pluginConfig.subc?.connection_file,
11458
11762
  resolveProjectPath,
11459
11763
  ensureProjectRegistered: ensureProjectRegisteredFromOpenCodeDirectory
11460
11764
  }),
@@ -11475,11 +11779,11 @@ function createToolRegistry(args) {
11475
11779
  const promptSurfaceRuntime = args.promptSurfaceRuntime ?? createPromptSurfaceRuntime({
11476
11780
  harness: "opencode",
11477
11781
  directory: ctx.directory,
11478
- warn: (message) => log(`[magic-context] config warning: ${message}`)
11782
+ warn: (message) => log2(`[magic-context] config warning: ${message}`)
11479
11783
  });
11480
11784
  const registration = promptSurfaceRuntime.resolveRegistration(args.registrationPromptSurface ?? pluginConfig.prompt_surface);
11481
11785
  const surfacedTools = Object.fromEntries(Object.entries(allTools).map(([toolId, definition]) => {
11482
- const parameterDescriptions = parameterDescriptionsFor(toolId, registration.preset);
11786
+ const parameterDescriptions = parameterDescriptionsFor(toolId, registration.preset, pluginConfig.smart_notes?.enabled);
11483
11787
  const argsWithPresetDescriptions = parameterDescriptions ? Object.fromEntries(Object.entries(definition.args).map(([name, schema]) => [
11484
11788
  name,
11485
11789
  parameterDescriptions[name] ? schema.describe(parameterDescriptions[name]) : schema
@@ -11489,7 +11793,7 @@ function createToolRegistry(args) {
11489
11793
  {
11490
11794
  ...definition,
11491
11795
  args: argsWithPresetDescriptions,
11492
- description: registration.descriptionFor(toolId, definition.description ?? "")
11796
+ description: toolId === "ctx_note" && pluginConfig.smart_notes?.enabled === false ? withoutSmartNoteText(registration.preset === "light" ? CTX_NOTE_LIGHT_DESCRIPTION : definition.description ?? "") : registration.descriptionFor(toolId, definition.description ?? "")
11493
11797
  }
11494
11798
  ];
11495
11799
  }));
@@ -11517,30 +11821,9 @@ function buildOpenCodeConfigWarningBanner(warnings, parseFailures, allParseFailu
11517
11821
  `);
11518
11822
  }
11519
11823
 
11520
- // src/shared/exit-abort-registry.ts
11521
- var controllers = new Set;
11522
- var listenerRegistered = false;
11523
- function abortAll() {
11524
- for (const controller of controllers) {
11525
- try {
11526
- controller.abort();
11527
- } catch {}
11528
- }
11529
- }
11530
- function registerExitAbort(controller) {
11531
- controllers.add(controller);
11532
- if (listenerRegistered)
11533
- return;
11534
- listenerRegistered = true;
11535
- process.once("exit", abortAll);
11536
- }
11537
- function unregisterExitAbort(controller) {
11538
- controllers.delete(controller);
11539
- }
11540
-
11541
11824
  // src/v2/hooks/update-check.ts
11542
- import { existsSync as existsSync6, readFileSync as readFileSync6 } from "node:fs";
11543
- import { dirname as dirname4, join as join7 } from "node:path";
11825
+ import { existsSync as existsSync8, readFileSync as readFileSync7 } from "node:fs";
11826
+ import { dirname as dirname4, join as join10 } from "node:path";
11544
11827
  import { fileURLToPath as fileURLToPath2 } from "node:url";
11545
11828
  var cachedPackageInfo;
11546
11829
  function packageInfo() {
@@ -11549,11 +11832,11 @@ function packageInfo() {
11549
11832
  let directory = dirname4(fileURLToPath2(import.meta.url));
11550
11833
  for (;; ) {
11551
11834
  try {
11552
- const pkg = JSON.parse(readFileSync6(join7(directory, "package.json"), "utf8"));
11835
+ const pkg = JSON.parse(readFileSync7(join10(directory, "package.json"), "utf8"));
11553
11836
  if (pkg.name === "@cortexkit/opencode-magic-context" && typeof pkg.version === "string") {
11554
11837
  cachedPackageInfo = {
11555
11838
  version: pkg.version,
11556
- development: existsSync6(join7(directory, "src/v2/server.ts"))
11839
+ development: existsSync8(join10(directory, "src/v2/server.ts"))
11557
11840
  };
11558
11841
  return cachedPackageInfo;
11559
11842
  }
@@ -11599,7 +11882,7 @@ function startUpdateChecks(context, check = (signal) => {
11599
11882
  }
11600
11883
  } catch (error) {
11601
11884
  if (!controller.signal.aborted)
11602
- log("[magic-context] v2 update check unavailable", error);
11885
+ log2("[magic-context] v2 update check unavailable", error);
11603
11886
  }
11604
11887
  })();
11605
11888
  return {
@@ -11620,16 +11903,16 @@ function isOpenCode2HostContext(context) {
11620
11903
  }
11621
11904
  async function setup(context) {
11622
11905
  if (!isOpenCode2HostContext(context)) {
11623
- log("v2 setup() called on a host without session.hook; v1 server lane owns this host, v2 lane inert");
11906
+ log2("v2 setup() called on a host without session.hook; v1 server lane owns this host, v2 lane inert");
11624
11907
  return async () => {};
11625
11908
  }
11626
- const { registerContext } = await import("./context-wq4ffwyb.js");
11627
- setHarness("opencode2");
11909
+ const { registerContext } = await import("./context-nj5f293n.js");
11910
+ setHarness2("opencode2");
11628
11911
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
11629
11912
  const duties = await registerContext(context);
11630
11913
  const checks = loadPluginConfigDetailed(context.location.directory).config.auto_update === false ? undefined : startUpdateChecks(context);
11631
- log("[magic-context] @cortexkit/opencode-magic-context v2 setup");
11632
- flushLogger();
11914
+ log2("[magic-context] @cortexkit/opencode-magic-context v2 setup");
11915
+ flushLogger2();
11633
11916
  return async () => {
11634
11917
  await checks?.dispose();
11635
11918
  await duties?.dispose();
@@ -11649,14 +11932,14 @@ var server = async (ctx) => {
11649
11932
  let rpcMs = 0;
11650
11933
  let hooksDeadlineReason = null;
11651
11934
  let deadlinePhase = null;
11652
- emitBootEnteringBreadcrumb(process.pid, ctx.directory, log, flushLogger);
11653
- setHarness("opencode");
11935
+ emitBootEnteringBreadcrumb(process.pid, ctx.directory, log2, flushLogger2);
11936
+ setHarness2("opencode");
11654
11937
  startHostStallProfilerSwitch();
11655
11938
  const configStartedAt = performance.now();
11656
11939
  beginBootQuietPeriod();
11657
11940
  const configMigrationWarnings = migrateMagicContextConfigLocations(ctx.directory, {
11658
- warn: (m) => log(`[magic-context] ${m}`),
11659
- info: (m) => log(`[magic-context] ${m}`)
11941
+ warn: (m) => log2(`[magic-context] ${m}`),
11942
+ info: (m) => log2(`[magic-context] ${m}`)
11660
11943
  });
11661
11944
  const loadedPluginConfig = loadPluginConfigDetailed(ctx.directory);
11662
11945
  const pluginConfig = loadedPluginConfig.config;
@@ -11667,7 +11950,7 @@ var server = async (ctx) => {
11667
11950
  const promptSurfaceRuntime = createPromptSurfaceRuntime({
11668
11951
  harness: "opencode",
11669
11952
  directory: ctx.directory,
11670
- warn: (message) => log(`[magic-context] config warning: ${message}`)
11953
+ warn: (message) => log2(`[magic-context] config warning: ${message}`)
11671
11954
  });
11672
11955
  if (configMigrationWarnings.length > 0) {
11673
11956
  pluginConfig.configWarnings = [
@@ -11685,7 +11968,7 @@ var server = async (ctx) => {
11685
11968
  registerExitAbort(autoUpdateAbort);
11686
11969
  if (pluginConfig.configWarnings?.length) {
11687
11970
  for (const w of pluginConfig.configWarnings) {
11688
- log(`[magic-context] config warning: ${w}`);
11971
+ log2(`[magic-context] config warning: ${w}`);
11689
11972
  }
11690
11973
  const allParseFailures = loadedPluginConfig.configParseFailures;
11691
11974
  const parseFailuresToShow = claimConfigParseFailuresOnce("opencode", allParseFailures);
@@ -11694,7 +11977,7 @@ var server = async (ctx) => {
11694
11977
  if (hasBannerEntries)
11695
11978
  setTimeout(async () => {
11696
11979
  try {
11697
- const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-0m68ms3n.js"));
11980
+ const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-38cd5dqt.js"));
11698
11981
  const clientWithSessions = ctx.client;
11699
11982
  const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
11700
11983
  const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
@@ -11708,10 +11991,10 @@ var server = async (ctx) => {
11708
11991
  const openCodeDbResolution = resolveOpenCodeDbPath();
11709
11992
  if (!openCodeDbPathExists(openCodeDbResolution) && claimOpenCodeDbDiagnosticOnce("boot-banner", openCodeDbResolution)) {
11710
11993
  const missingDbBanner = formatOpenCodeDbMissingBanner(openCodeDbResolution);
11711
- log(`[magic-context] opencode_db_missing path=${openCodeDbResolution.path} source=${openCodeDbResolution.source}`);
11994
+ log2(`[magic-context] opencode_db_missing path=${openCodeDbResolution.path} source=${openCodeDbResolution.source}`);
11712
11995
  setTimeout(async () => {
11713
11996
  try {
11714
- const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-0m68ms3n.js"));
11997
+ const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-38cd5dqt.js"));
11715
11998
  const clientWithSessions = ctx.client;
11716
11999
  const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
11717
12000
  const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
@@ -11728,7 +12011,7 @@ var server = async (ctx) => {
11728
12011
  const resolvedConfigTimeoutMs = Math.min(RESOLVED_CONFIG_TIMEOUT_MS, remainingBootBudgetMs(bootBudget));
11729
12012
  const resolvedCompaction = resolvedConfigTimeoutMs > 0 ? await resolveCompactionForBoot(ctx.client, resolvedConfigTimeoutMs) : null;
11730
12013
  if (resolvedCompaction === null) {
11731
- log("[magic-context] resolved-config fetch failed; using file-based compaction detection (the running server's resolved config may differ — `opencode debug config` is authoritative)");
12014
+ log2("[magic-context] resolved-config fetch failed; using file-based compaction detection (the running server's resolved config may differ — `opencode debug config` is authoritative)");
11732
12015
  }
11733
12016
  conflictResult = detectConflicts(ctx.directory, {
11734
12017
  compactionEnabled: isCompactionEnabled(pluginConfig),
@@ -11736,9 +12019,9 @@ var server = async (ctx) => {
11736
12019
  });
11737
12020
  if (conflictResult.hasConflict) {
11738
12021
  pluginConfig.enabled = false;
11739
- log(`[magic-context] disabled due to conflicts: ${conflictResult.reasons.join("; ")}`);
12022
+ log2(`[magic-context] disabled due to conflicts: ${conflictResult.reasons.join("; ")}`);
11740
12023
  } else {
11741
- log("[magic-context] no conflicts detected, plugin enabled");
12024
+ log2("[magic-context] no conflicts detected, plugin enabled");
11742
12025
  }
11743
12026
  }
11744
12027
  conflictMs = performance.now() - conflictStartedAt;
@@ -11754,7 +12037,7 @@ var server = async (ctx) => {
11754
12037
  rustModeModuleClient,
11755
12038
  promptSurfaceRuntime,
11756
12039
  onStorageBootTimings: (timings) => Object.assign(storageBootTimings, timings)
11757
- }), log);
12040
+ }), log2);
11758
12041
  const hooks = hooksPhase.status === "completed" ? hooksPhase.value : { magicContext: null, rustToolBackends: undefined };
11759
12042
  if (hooksPhase.status === "timed_out") {
11760
12043
  deadlinePhase = "hooks";
@@ -11772,7 +12055,7 @@ var server = async (ctx) => {
11772
12055
  const storageFailureReason = hooksDeadlineReason ? { kind: "storage_failure", cause: hooksDeadlineReason } : initFailure?.type === "storage" ? initFailure.reason : null;
11773
12056
  if (storageFailureReason) {
11774
12057
  failClosed.arm(storageFailureReason);
11775
- log(`[magic-context] fail-closed blocking armed (${storageFailureReason.kind}); primary sessions will error until storage recovers or the build is upgraded`);
12058
+ log2(`[magic-context] fail-closed blocking armed (${storageFailureReason.kind}); primary sessions will error until storage recovers or the build is upgraded`);
11776
12059
  }
11777
12060
  }
11778
12061
  if (hooksPhase.status === "timed_out") {
@@ -11782,7 +12065,7 @@ var server = async (ctx) => {
11782
12065
  magicContextRuntime.magicContext = late.magicContext;
11783
12066
  magicContextRuntime.rustToolBackends = late.rustToolBackends;
11784
12067
  failClosed.clear();
11785
- log("[magic-context] boot hooks phase settled after its deadline; Magic Context runtime installed and fail-closed cleared");
12068
+ log2("[magic-context] boot hooks phase settled after its deadline; Magic Context runtime installed and fail-closed cleared");
11786
12069
  });
11787
12070
  }
11788
12071
  const tryReopenStorage = async () => {
@@ -11804,10 +12087,10 @@ var server = async (ctx) => {
11804
12087
  magicContextRuntime.magicContext = reopened.magicContext;
11805
12088
  magicContextRuntime.rustToolBackends = reopened.rustToolBackends;
11806
12089
  failClosed.clear();
11807
- log("[magic-context] storage re-probe succeeded; Magic Context runtime restored");
12090
+ log2("[magic-context] storage re-probe succeeded; Magic Context runtime restored");
11808
12091
  return true;
11809
12092
  } catch (error) {
11810
- log(`[magic-context] storage re-probe failed: ${error}`);
12093
+ log2(`[magic-context] storage re-probe failed: ${error}`);
11811
12094
  return false;
11812
12095
  }
11813
12096
  };
@@ -11826,12 +12109,12 @@ var server = async (ctx) => {
11826
12109
  if (db && isDatabasePersisted(db)) {
11827
12110
  scheduleAfterBootQuiet(() => {
11828
12111
  runDeferredV22Backfill(db).catch((err) => {
11829
- log(`[v22-backfill] background runner failed: ${err}`);
12112
+ log2(`[v22-backfill] background runner failed: ${err}`);
11830
12113
  });
11831
12114
  });
11832
12115
  }
11833
12116
  } catch (err) {
11834
- log(`[v22-backfill] failed to start background runner: ${err}`);
12117
+ log2(`[v22-backfill] failed to start background runner: ${err}`);
11835
12118
  }
11836
12119
  }
11837
12120
  if (pluginConfig.enabled && magicContextRuntime.magicContext) {
@@ -11869,7 +12152,7 @@ var server = async (ctx) => {
11869
12152
  closeQuietly(ocDb);
11870
12153
  }
11871
12154
  })().catch((err) => {
11872
- log(`[session-projects] background runner failed: ${err}`);
12155
+ log2(`[session-projects] background runner failed: ${err}`);
11873
12156
  });
11874
12157
  }, 0);
11875
12158
  }
@@ -11881,7 +12164,7 @@ var server = async (ctx) => {
11881
12164
  const classifyModuleClient = createDreamTimerModuleClient(rustModeModuleClient);
11882
12165
  const timerProjectIdentity = resolveProjectIdentityForSession(ctx.directory, pluginConfig.allow_home_project);
11883
12166
  if (!timerProjectIdentity) {
11884
- log("[magic-context] dream timer skipped: no project identity is bound for this directory");
12167
+ log2("[magic-context] dream timer skipped: no project identity is bound for this directory");
11885
12168
  } else {
11886
12169
  const timerRegistration = {
11887
12170
  directory: ctx.directory,
@@ -11919,6 +12202,7 @@ var server = async (ctx) => {
11919
12202
  },
11920
12203
  mural: pluginConfig.mural,
11921
12204
  retinaHandoff: pluginConfig.smart_notes.retina_handoff,
12205
+ smartNotesEnabled: pluginConfig.smart_notes.enabled,
11922
12206
  gitCommitIndexing: pluginConfig.memory.git_commit_indexing?.enabled ? {
11923
12207
  enabled: true,
11924
12208
  since_days: pluginConfig.memory.git_commit_indexing.since_days,
@@ -11939,7 +12223,7 @@ var server = async (ctx) => {
11939
12223
  startDreamScheduleTimer(timerRegistration).then((stop) => {
11940
12224
  stopDreamTimerRegistration = stop;
11941
12225
  }).catch((err) => {
11942
- log(`[magic-context] dream timer registration failed (continuing without it): ${err}`);
12226
+ log2(`[magic-context] dream timer registration failed (continuing without it): ${err}`);
11943
12227
  });
11944
12228
  }, 0);
11945
12229
  }
@@ -11957,9 +12241,9 @@ var server = async (ctx) => {
11957
12241
  setTimeout(() => {
11958
12242
  const rpcStartedAt = performance.now();
11959
12243
  rpcServer?.start().then(() => {
11960
- log(`[magic-context] boot deferred phase: rpc=${Math.round(performance.now() - rpcStartedAt)}ms`);
12244
+ log2(`[magic-context] boot deferred phase: rpc=${Math.round(performance.now() - rpcStartedAt)}ms`);
11961
12245
  }).catch((err) => {
11962
- log(`[magic-context] RPC server failed to start: ${err}`);
12246
+ log2(`[magic-context] RPC server failed to start: ${err}`);
11963
12247
  });
11964
12248
  }, 0);
11965
12249
  rpcMs = performance.now() - rpcScheduledAt;
@@ -11979,21 +12263,21 @@ var server = async (ctx) => {
11979
12263
  });
11980
12264
  setTimeout(() => {
11981
12265
  rpcServer?.start().catch((err) => {
11982
- log(`[magic-context] debug-only RPC server failed to start: ${err}`);
12266
+ log2(`[magic-context] debug-only RPC server failed to start: ${err}`);
11983
12267
  });
11984
12268
  }, 0);
11985
12269
  }
11986
12270
  {
11987
12271
  const fence = getSchemaFenceRejection();
11988
12272
  if (fence) {
11989
- importPluginModule(() => import("./conflict-warning-hook-z44ynfz7.js")).then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence)).catch((error) => log("[magic-context] schema-fence warning unavailable:", error));
12273
+ importPluginModule(() => import("./conflict-warning-hook-kzx4dmk1.js")).then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence)).catch((error) => log2("[magic-context] schema-fence warning unavailable:", error));
11990
12274
  }
11991
12275
  }
11992
12276
  const serverUrl = ctx.serverUrl;
11993
12277
  const serverUrlStr = serverUrl instanceof URL ? serverUrl.toString().replace(/\/$/, "") : typeof serverUrl === "string" ? serverUrl.replace(/\/$/, "") : undefined;
11994
- importPluginModule(() => import("./send-session-notification-0m68ms3n.js")).then(({ setNotificationServerUrl }) => {
12278
+ importPluginModule(() => import("./send-session-notification-38cd5dqt.js")).then(({ setNotificationServerUrl }) => {
11995
12279
  setNotificationServerUrl(serverUrlStr);
11996
- }).catch((error) => log("[magic-context] notification transport unavailable:", error));
12280
+ }).catch((error) => log2("[magic-context] notification transport unavailable:", error));
11997
12281
  if (conflictResult?.hasConflict) {
11998
12282
  setTimeout(() => {
11999
12283
  sendConflictWarning2(ctx.client, ctx.directory, conflictResult);
@@ -12005,7 +12289,7 @@ var server = async (ctx) => {
12005
12289
  }
12006
12290
  if (pluginConfig.enabled && !conflictResult?.hasConflict) {
12007
12291
  setTimeout(() => {
12008
- importPluginModule(() => import("./announcement-y35wzg2r.js")).then(({
12292
+ importPluginModule(() => import("./announcement-fp14dw0n.js")).then(({
12009
12293
  shouldShowAnnouncement,
12010
12294
  ANNOUNCEMENT_VERSION,
12011
12295
  ANNOUNCEMENT_FEATURES,
@@ -12014,7 +12298,7 @@ var server = async (ctx) => {
12014
12298
  }) => {
12015
12299
  if (!shouldShowAnnouncement())
12016
12300
  return;
12017
- return importPluginModule(() => import("./conflict-warning-hook-z44ynfz7.js")).then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION, ANNOUNCEMENT_FEATURES, ANNOUNCEMENT_FOOTER, markAnnouncementSeen));
12301
+ return importPluginModule(() => import("./conflict-warning-hook-kzx4dmk1.js")).then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION, ANNOUNCEMENT_FEATURES, ANNOUNCEMENT_FOOTER, markAnnouncementSeen));
12018
12302
  }).catch(() => {});
12019
12303
  }, 8000);
12020
12304
  }
@@ -12024,7 +12308,7 @@ var server = async (ctx) => {
12024
12308
  const measuredStorageMs = storageBootTimings.openMs + storageBootTimings.guardMs + storageBootTimings.migrateMs;
12025
12309
  const hooksMs = Math.max(0, hooksPhase.elapsedMs - measuredStorageMs);
12026
12310
  const postMs = Math.max(0, performance.now() - postStartedAt - rpcMs);
12027
- log(formatBootPhaseDiagnostics({
12311
+ log2(formatBootPhaseDiagnostics({
12028
12312
  configMs,
12029
12313
  conflictMs,
12030
12314
  guardMs: storageBootTimings.guardMs,
@@ -12037,14 +12321,6 @@ var server = async (ctx) => {
12037
12321
  budgetMs: BOOT_SERVER_DEADLINE_MS,
12038
12322
  deadlinePhase
12039
12323
  }));
12040
- const checkoutClaimGate = pluginConfig.enabled ? createSubcCheckoutClaimGate("opencode", () => pluginConfig.subc?.connection_file ?? getDefaultSubcConnectionFile()) : undefined;
12041
- const isCheckoutClaimRefused = async (sessionId) => {
12042
- if (!checkoutClaimGate || !sessionId)
12043
- return false;
12044
- if (liveSessionState.internalChildSessions.has(sessionId))
12045
- return false;
12046
- return await checkoutClaimGate.refusal(sessionId, ctx.directory) !== null;
12047
- };
12048
12324
  return {
12049
12325
  tool: tools,
12050
12326
  event: createEventHandler({
@@ -12054,8 +12330,6 @@ var server = async (ctx) => {
12054
12330
  const properties = input.event.properties;
12055
12331
  if (properties.info?.id)
12056
12332
  dreamerCap.delete(properties.info.id);
12057
- } else if (await isCheckoutClaimRefused(openCodeEventSessionId(input.event))) {
12058
- return;
12059
12333
  }
12060
12334
  await magicContextRuntime.magicContext?.event?.(input);
12061
12335
  }
@@ -12081,36 +12355,25 @@ var server = async (ctx) => {
12081
12355
  try {
12082
12356
  magicContextRuntime.magicContext?.disposeRustAdapter?.();
12083
12357
  } catch {}
12084
- log("[magic-context] instance disposed — stopped RPC server, dream timer, auto-update, Rust replay registration");
12358
+ log2("[magic-context] instance disposed — stopped RPC server, dream timer, auto-update, Rust replay registration");
12085
12359
  }
12086
12360
  }),
12087
12361
  "chat.params": async (input, output) => {
12088
12362
  dreamerCap.apply(input, output);
12363
+ applyHiddenSubagentTemperature(input, output, log2);
12089
12364
  },
12090
12365
  "experimental.chat.messages.transform": createMessagesTransformHandler({
12091
12366
  magicContext: magicContextRuntime.magicContext,
12092
12367
  getMagicContext: () => magicContextRuntime.magicContext,
12093
12368
  failClosed,
12094
12369
  failClosedBlockingEnabled,
12095
- checkoutClaim: checkoutClaimGate ? {
12096
- gate: checkoutClaimGate,
12097
- projectRoot: ctx.directory,
12098
- onRefusal: async (sessionId, message) => {
12099
- const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-0m68ms3n.js"));
12100
- const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-z5hzpsxv.js"));
12101
- await sendStatusNotification(ctx.client, sessionId, message, {
12102
- toastDurationMs: 15000
12103
- });
12104
- await abortSessionFailClosed(ctx.client, sessionId);
12105
- }
12106
- } : undefined,
12107
12370
  compactionOff: !isCompactionEnabled(pluginConfig),
12108
12371
  internalChildSessions: liveSessionState.internalChildSessions,
12109
12372
  tryReopenStorage,
12110
12373
  rustReplayParticipant: () => magicContextRuntime.magicContext?.getRustReplayParticipant?.() ?? null,
12111
12374
  onStorageBusyRefusal: async (sessionId, message) => {
12112
- const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-0m68ms3n.js"));
12113
- const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-z5hzpsxv.js"));
12375
+ const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-38cd5dqt.js"));
12376
+ const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-tck4g20s.js"));
12114
12377
  await sendStatusNotification(ctx.client, sessionId, message, {
12115
12378
  toastDurationMs: 15000
12116
12379
  });
@@ -12118,8 +12381,6 @@ var server = async (ctx) => {
12118
12381
  }
12119
12382
  }),
12120
12383
  "experimental.chat.system.transform": async (input, output) => {
12121
- if (await isCheckoutClaimRefused(input.sessionID))
12122
- return;
12123
12384
  await magicContextRuntime.magicContext?.["experimental.chat.system.transform"]?.(input, output);
12124
12385
  },
12125
12386
  "command.execute.before": async (input, output) => {
@@ -12132,8 +12393,6 @@ var server = async (ctx) => {
12132
12393
  const modId = typed.model?.modelID;
12133
12394
  const agent = typed.agent;
12134
12395
  lastChatContext = provId && modId ? { providerID: provId, modelID: modId, agentName: agent || "default" } : null;
12135
- if (await isCheckoutClaimRefused(input.sessionID))
12136
- return;
12137
12396
  await magicContextRuntime.magicContext?.["chat.message"]?.(input, output);
12138
12397
  },
12139
12398
  "tool.definition": async (input, output) => {
@@ -12209,7 +12468,7 @@ var server = async (ctx) => {
12209
12468
  const internalAgentIds = registrations.map((registration) => registration.id);
12210
12469
  for (const reg of registrations) {
12211
12470
  if (typeof reg.prompt !== "string" || reg.prompt.length === 0) {
12212
- log(`[magic-context] skipping hidden agent '${reg.id}' — prompt unavailable at config time (dir=${ctx.directory}); will re-register on a later complete pass`);
12471
+ log2(`[magic-context] skipping hidden agent '${reg.id}' — prompt unavailable at config time (dir=${ctx.directory}); will re-register on a later complete pass`);
12213
12472
  continue;
12214
12473
  }
12215
12474
  agentConfigRecord[reg.id] = buildHiddenAgentConfig(reg.prompt, reg.allowedTools, reg.maxSteps, reg.overrides, reg.id, reg.lockPermissions === true, reg.description);
@@ -12218,7 +12477,7 @@ var server = async (ctx) => {
12218
12477
  config.agent = callerAgentConfig;
12219
12478
  } catch (error) {
12220
12479
  const e = error;
12221
- log(`[magic-context] config hook failed (commands/agents NOT registered; transform still active): ${e?.message ?? error}`, e?.stack ? { stackHead: e.stack.split(`
12480
+ log2(`[magic-context] config hook failed (commands/agents NOT registered; transform still active): ${e?.message ?? error}`, e?.stack ? { stackHead: e.stack.split(`
12222
12481
  `).slice(0, 6).join(`
12223
12482
  `) } : undefined);
12224
12483
  }