@cortexkit/opencode-magic-context 0.45.0 → 0.46.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 (385) hide show
  1. package/README.md +26 -0
  2. package/dist/{announcement-f75t58v9.js → announcement-y35wzg2r.js} +1 -1
  3. package/dist/config/index.d.ts.map +1 -1
  4. package/dist/config/live-run-config.d.ts.map +1 -1
  5. package/dist/config/migrate-config-location.d.ts.map +1 -1
  6. package/dist/config/schema/magic-context.d.ts +10 -4
  7. package/dist/config/schema/magic-context.d.ts.map +1 -1
  8. package/dist/{conflict-warning-hook-5yrz2r24.js → conflict-warning-hook-7fj2b9jw.js} +6 -5
  9. package/dist/context-8dkpszy5.js +4483 -0
  10. package/dist/{derive-budgets-a63zsm5c.js → derive-budgets-7nj7r1rv.js} +2 -2
  11. package/dist/embedding-worker.js +4 -4
  12. package/dist/features/magic-context/checkout-claim-fake-subc.test-support.d.ts +45 -0
  13. package/dist/features/magic-context/checkout-claim-fake-subc.test-support.d.ts.map +1 -0
  14. package/dist/features/magic-context/checkout-claim.d.ts +155 -0
  15. package/dist/features/magic-context/checkout-claim.d.ts.map +1 -0
  16. package/dist/features/magic-context/compaction-marker.d.ts +20 -3
  17. package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
  18. package/dist/features/magic-context/compartment-storage.d.ts +23 -2
  19. package/dist/features/magic-context/compartment-storage.d.ts.map +1 -1
  20. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  21. package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts.map +1 -1
  22. package/dist/features/magic-context/dreamer/provider-output-failure.d.ts +6 -2
  23. package/dist/features/magic-context/dreamer/provider-output-failure.d.ts.map +1 -1
  24. package/dist/features/magic-context/dreamer/provider-output-failure.test-support.d.ts +30 -0
  25. package/dist/features/magic-context/dreamer/provider-output-failure.test-support.d.ts.map +1 -0
  26. package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts.map +1 -1
  27. package/dist/features/magic-context/dreamer/task-executor.d.ts +9 -0
  28. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  29. package/dist/features/magic-context/dreamer/task-gates.d.ts.map +1 -1
  30. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  31. package/dist/features/magic-context/dreamer/verify-diff.d.ts.map +1 -1
  32. package/dist/features/magic-context/dreamer/verify-gate.d.ts.map +1 -1
  33. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  34. package/dist/features/magic-context/git-commits/search-git-commits.d.ts.map +1 -1
  35. package/dist/features/magic-context/memory/embedding-local.d.ts.map +1 -1
  36. package/dist/features/magic-context/memory/project-identity-cache.d.ts.map +1 -1
  37. package/dist/features/magic-context/memory/storage-memory-verifications.d.ts.map +1 -1
  38. package/dist/features/magic-context/memory/storage-memory.d.ts +3 -0
  39. package/dist/features/magic-context/memory/storage-memory.d.ts.map +1 -1
  40. package/dist/features/magic-context/memory/verification-paths.d.ts +2 -2
  41. package/dist/features/magic-context/memory/verification-paths.d.ts.map +1 -1
  42. package/dist/features/magic-context/merged-reasoning-decisions.d.ts.map +1 -1
  43. package/dist/features/magic-context/message-index-async.d.ts +3 -3
  44. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  45. package/dist/features/magic-context/message-index.d.ts +2 -0
  46. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  47. package/dist/features/magic-context/migration-v95-perf-indexes.d.ts +12 -0
  48. package/dist/features/magic-context/migration-v95-perf-indexes.d.ts.map +1 -0
  49. package/dist/features/magic-context/migration-worker-client.d.ts +4 -4
  50. package/dist/features/magic-context/migration-worker-client.d.ts.map +1 -1
  51. package/dist/features/magic-context/migrations.d.ts +1 -0
  52. package/dist/features/magic-context/migrations.d.ts.map +1 -1
  53. package/dist/features/magic-context/mural/render-trigger.d.ts.map +1 -1
  54. package/dist/features/magic-context/mural/resolve-mural.d.ts +15 -4
  55. package/dist/features/magic-context/mural/resolve-mural.d.ts.map +1 -1
  56. package/dist/features/magic-context/mural/source-revision.d.ts +7 -0
  57. package/dist/features/magic-context/mural/source-revision.d.ts.map +1 -0
  58. package/dist/features/magic-context/mural/storage-mural-cues.d.ts.map +1 -1
  59. package/dist/features/magic-context/reclaim-protection.d.ts +15 -10
  60. package/dist/features/magic-context/reclaim-protection.d.ts.map +1 -1
  61. package/dist/features/magic-context/session-cache-ttl.d.ts +4 -2
  62. package/dist/features/magic-context/session-cache-ttl.d.ts.map +1 -1
  63. package/dist/features/magic-context/smart-notes/capabilities.d.ts +3 -0
  64. package/dist/features/magic-context/smart-notes/capabilities.d.ts.map +1 -1
  65. package/dist/features/magic-context/smart-notes/compiler.d.ts.map +1 -1
  66. package/dist/features/magic-context/smart-notes/github-token.d.ts +5 -0
  67. package/dist/features/magic-context/smart-notes/github-token.d.ts.map +1 -0
  68. package/dist/features/magic-context/smart-notes/runner.d.ts +1 -0
  69. package/dist/features/magic-context/smart-notes/runner.d.ts.map +1 -1
  70. package/dist/features/magic-context/smart-notes/sandbox-runner.d.ts +12 -0
  71. package/dist/features/magic-context/smart-notes/sandbox-runner.d.ts.map +1 -1
  72. package/dist/features/magic-context/smart-notes/ssrf-guard.d.ts +6 -0
  73. package/dist/features/magic-context/smart-notes/ssrf-guard.d.ts.map +1 -1
  74. package/dist/features/magic-context/smart-notes/storage.d.ts.map +1 -1
  75. package/dist/features/magic-context/smart-notes/types.d.ts +2 -0
  76. package/dist/features/magic-context/smart-notes/types.d.ts.map +1 -1
  77. package/dist/features/magic-context/storage-clone.d.ts.map +1 -1
  78. package/dist/features/magic-context/storage-db.d.ts +6 -9
  79. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  80. package/dist/features/magic-context/storage-meta-shared.d.ts +1 -1
  81. package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
  82. package/dist/features/magic-context/storage-ops.d.ts +8 -1
  83. package/dist/features/magic-context/storage-ops.d.ts.map +1 -1
  84. package/dist/features/magic-context/storage-replay-document.d.ts +7 -0
  85. package/dist/features/magic-context/storage-replay-document.d.ts.map +1 -1
  86. package/dist/features/magic-context/storage-schema-helpers.d.ts +2 -0
  87. package/dist/features/magic-context/storage-schema-helpers.d.ts.map +1 -1
  88. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
  89. package/dist/features/magic-context/storage-source.d.ts.map +1 -1
  90. package/dist/features/magic-context/storage-tags.d.ts +11 -3
  91. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  92. package/dist/features/magic-context/storage.d.ts +2 -2
  93. package/dist/features/magic-context/storage.d.ts.map +1 -1
  94. package/dist/features/magic-context/temporal-decisions.d.ts +10 -0
  95. package/dist/features/magic-context/temporal-decisions.d.ts.map +1 -0
  96. package/dist/features/magic-context/tool-definition-tokens.d.ts +2 -0
  97. package/dist/features/magic-context/tool-definition-tokens.d.ts.map +1 -1
  98. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  99. package/dist/features/magic-context/types.d.ts +7 -6
  100. package/dist/features/magic-context/types.d.ts.map +1 -1
  101. package/dist/features/magic-context/window-report-ledger.d.ts.map +1 -1
  102. package/dist/hooks/auto-update-checker/index.d.ts.map +1 -1
  103. package/dist/hooks/magic-context/apply-operations.d.ts +8 -0
  104. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  105. package/dist/hooks/magic-context/cache-busting-signals.d.ts +6 -3
  106. package/dist/hooks/magic-context/cache-busting-signals.d.ts.map +1 -1
  107. package/dist/hooks/magic-context/channel2-cycle.d.ts +2 -0
  108. package/dist/hooks/magic-context/channel2-cycle.d.ts.map +1 -1
  109. package/dist/hooks/magic-context/compaction-marker-manager.d.ts +7 -0
  110. package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
  111. package/dist/hooks/magic-context/compartment-prompt.d.ts +2 -2
  112. package/dist/hooks/magic-context/compartment-prompt.d.ts.map +1 -1
  113. package/dist/hooks/magic-context/compartment-render-epoch.d.ts +8 -0
  114. package/dist/hooks/magic-context/compartment-render-epoch.d.ts.map +1 -1
  115. package/dist/hooks/magic-context/compartment-runner-drop-queue.d.ts +18 -4
  116. package/dist/hooks/magic-context/compartment-runner-drop-queue.d.ts.map +1 -1
  117. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  118. package/dist/hooks/magic-context/compartment-runner-partial-recomp.d.ts.map +1 -1
  119. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  120. package/dist/hooks/magic-context/ctx-reduce-availability.d.ts +12 -0
  121. package/dist/hooks/magic-context/ctx-reduce-availability.d.ts.map +1 -1
  122. package/dist/hooks/magic-context/decision-calibration.d.ts +3 -0
  123. package/dist/hooks/magic-context/decision-calibration.d.ts.map +1 -1
  124. package/dist/hooks/magic-context/default-protection-pressure.test-support.d.ts +37 -0
  125. package/dist/hooks/magic-context/default-protection-pressure.test-support.d.ts.map +1 -0
  126. package/dist/hooks/magic-context/drop-stale-reduce-calls.d.ts +4 -0
  127. package/dist/hooks/magic-context/drop-stale-reduce-calls.d.ts.map +1 -1
  128. package/dist/hooks/magic-context/edit-marker.d.ts.map +1 -1
  129. package/dist/hooks/magic-context/emergency-drop.d.ts +2 -0
  130. package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
  131. package/dist/hooks/magic-context/emergency-fail-closed.d.ts +21 -1
  132. package/dist/hooks/magic-context/emergency-fail-closed.d.ts.map +1 -1
  133. package/dist/hooks/magic-context/event-handler.d.ts +5 -0
  134. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  135. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +30 -1
  136. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  137. package/dist/hooks/magic-context/heuristic-cleanup.d.ts +2 -0
  138. package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
  139. package/dist/hooks/magic-context/historian-prompt-fit.d.ts +4 -2
  140. package/dist/hooks/magic-context/historian-prompt-fit.d.ts.map +1 -1
  141. package/dist/hooks/magic-context/hook.d.ts +2 -1
  142. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  143. package/dist/hooks/magic-context/inject-compartments.d.ts +9 -10
  144. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  145. package/dist/hooks/magic-context/lkg-measured-request.d.ts +69 -0
  146. package/dist/hooks/magic-context/lkg-measured-request.d.ts.map +1 -0
  147. package/dist/hooks/magic-context/lkg-persist.d.ts +2 -0
  148. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
  149. package/dist/hooks/magic-context/lkg-replay-fit.d.ts +14 -0
  150. package/dist/hooks/magic-context/lkg-replay-fit.d.ts.map +1 -1
  151. package/dist/hooks/magic-context/lkg-replay.d.ts +10 -1
  152. package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
  153. package/dist/hooks/magic-context/lkg-slot.d.ts +4 -0
  154. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  155. package/dist/hooks/magic-context/module-state-sync.d.ts +2 -0
  156. package/dist/hooks/magic-context/module-state-sync.d.ts.map +1 -1
  157. package/dist/hooks/magic-context/module-transport.d.ts.map +1 -1
  158. package/dist/hooks/magic-context/module-wire.d.ts.map +1 -1
  159. package/dist/hooks/magic-context/note-nudger.d.ts +17 -5
  160. package/dist/hooks/magic-context/note-nudger.d.ts.map +1 -1
  161. package/dist/hooks/magic-context/read-session-chunk.d.ts +1 -1
  162. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  163. package/dist/hooks/magic-context/read-session-db.d.ts +1 -0
  164. package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
  165. package/dist/hooks/magic-context/read-session-formatting.d.ts +7 -0
  166. package/dist/hooks/magic-context/read-session-formatting.d.ts.map +1 -1
  167. package/dist/hooks/magic-context/read-session-raw.d.ts +4 -0
  168. package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
  169. package/dist/hooks/magic-context/read-session-true-raw-tokens.d.ts.map +1 -1
  170. package/dist/hooks/magic-context/recomp-orchestrator.d.ts +2 -0
  171. package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
  172. package/dist/hooks/magic-context/reference-retrieval.d.ts +27 -17
  173. package/dist/hooks/magic-context/reference-retrieval.d.ts.map +1 -1
  174. package/dist/hooks/magic-context/request-hook-order.d.ts +56 -0
  175. package/dist/hooks/magic-context/request-hook-order.d.ts.map +1 -0
  176. package/dist/hooks/magic-context/rust-mode-transform.d.ts +22 -3
  177. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  178. package/dist/hooks/magic-context/strip-content.d.ts +4 -2
  179. package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
  180. package/dist/hooks/magic-context/supersession-reclaim.d.ts +4 -0
  181. package/dist/hooks/magic-context/supersession-reclaim.d.ts.map +1 -1
  182. package/dist/hooks/magic-context/system-prompt-hash.d.ts +7 -0
  183. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  184. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts +12 -3
  185. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
  186. package/dist/hooks/magic-context/temporal-awareness.d.ts +6 -3
  187. package/dist/hooks/magic-context/temporal-awareness.d.ts.map +1 -1
  188. package/dist/hooks/magic-context/temporal-served-projection.d.ts +4 -0
  189. package/dist/hooks/magic-context/temporal-served-projection.d.ts.map +1 -0
  190. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  191. package/dist/hooks/magic-context/tool-reclaim.d.ts +2 -0
  192. package/dist/hooks/magic-context/tool-reclaim.d.ts.map +1 -1
  193. package/dist/hooks/magic-context/transform-message-helpers.d.ts +5 -0
  194. package/dist/hooks/magic-context/transform-message-helpers.d.ts.map +1 -1
  195. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +41 -17
  196. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  197. package/dist/hooks/magic-context/transform.d.ts +12 -0
  198. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  199. package/dist/hooks/magic-context/wrapup-orchestrator.d.ts.map +1 -1
  200. package/dist/{index-vvtfyw1z.js → index-0d3g3461.js} +5 -13
  201. package/dist/index-1bc61ans.js +154 -0
  202. package/dist/{index-n96ag4rk.js → index-1zx87sdm.js} +5 -1
  203. package/dist/{index-4krbw8z9.js → index-3h0ybwah.js} +608 -102
  204. package/dist/{index-gd5qx1j9.js → index-5eqk6z3s.js} +62 -1
  205. package/dist/index-5gq3b2ya.js +494 -0
  206. package/dist/{index-75zjgwga.js → index-7qw742ev.js} +1 -1
  207. package/dist/{index-f85teqck.js → index-8da2zjhz.js} +3 -256
  208. package/dist/{index-w9jwmntv.js → index-b35pxds2.js} +9 -1
  209. package/dist/{index-8fgkmxmy.js → index-e2dtv0ra.js} +4 -3
  210. package/dist/{v2/server-a4m2b1yv.js → index-fg34g6a5.js} +55 -1
  211. package/dist/{index-xgt9k6c6.js → index-j7fvnjye.js} +2 -1
  212. package/dist/{index-2aq21j41.js → index-k4404na5.js} +418 -127
  213. package/dist/{index-2ntg5sd4.js → index-k5bdx1bx.js} +9 -5
  214. package/dist/{index-bmzf7zxv.js → index-majxda46.js} +23 -5
  215. package/dist/{index-16ny736w.js → index-p821bjdb.js} +14406 -13726
  216. package/dist/{index-remp7e2g.js → index-q4yp4b52.js} +16 -1
  217. package/dist/index-qr6r7akd.js +28505 -0
  218. package/dist/{index-fr2z4qy8.js → index-r5hmbx3t.js} +132 -169
  219. package/dist/index-sfnj6h8h.js +259 -0
  220. package/dist/index-sj29b3z2.js +30 -0
  221. package/dist/{index-q7yesyk9.js → index-yasgb8ej.js} +23 -24
  222. package/dist/index.d.ts.map +1 -1
  223. package/dist/index.js +1983 -33118
  224. package/dist/{message-time-backfill-an311pmk.js → message-time-backfill-68gj6t3e.js} +2 -2
  225. package/dist/migration-worker.js +12 -7
  226. package/dist/plugin/dream-timer.d.ts +25 -1
  227. package/dist/plugin/dream-timer.d.ts.map +1 -1
  228. package/dist/plugin/hooks/create-session-hooks.d.ts +2 -1
  229. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  230. package/dist/plugin/messages-transform.d.ts +13 -0
  231. package/dist/plugin/messages-transform.d.ts.map +1 -1
  232. package/dist/plugin/rpc-handlers.d.ts +4 -0
  233. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  234. package/dist/plugin/subagent-tool-policy.d.ts +14 -0
  235. package/dist/plugin/subagent-tool-policy.d.ts.map +1 -0
  236. package/dist/plugin/tool-registry.d.ts +1 -0
  237. package/dist/plugin/tool-registry.d.ts.map +1 -1
  238. package/dist/{read-session-chunk-8rxs0tc9.js → read-session-chunk-egz7r68d.js} +8 -8
  239. package/dist/{recomp-orchestrator-nzamtw29.js → recomp-orchestrator-ejq7ex5d.js} +15 -15
  240. package/dist/{send-session-notification-nqpv7cne.js → send-session-notification-dyw42dtr.js} +4 -4
  241. package/dist/shared/announcement.d.ts.map +1 -1
  242. package/dist/shared/cache-ttl-display.d.ts +6 -4
  243. package/dist/shared/cache-ttl-display.d.ts.map +1 -1
  244. package/dist/shared/model-cache-ttl.d.ts +1 -1
  245. package/dist/shared/model-cache-ttl.d.ts.map +1 -1
  246. package/dist/shared/model-suggestion-retry.d.ts +2 -0
  247. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  248. package/dist/shared/models-dev-cache.d.ts.map +1 -1
  249. package/dist/shared/protected-tools-policy.d.ts +6 -0
  250. package/dist/shared/protected-tools-policy.d.ts.map +1 -0
  251. package/dist/shared/quota-diagnostic.d.ts +4 -0
  252. package/dist/shared/quota-diagnostic.d.ts.map +1 -0
  253. package/dist/shared/rpc-server.d.ts.map +1 -1
  254. package/dist/shared/sqlite-context-pragmas.d.ts +12 -0
  255. package/dist/shared/sqlite-context-pragmas.d.ts.map +1 -0
  256. package/dist/shared/sqlite-helpers.d.ts +9 -0
  257. package/dist/shared/sqlite-helpers.d.ts.map +1 -1
  258. package/dist/shared/sqlite.d.ts +10 -0
  259. package/dist/shared/sqlite.d.ts.map +1 -1
  260. package/dist/shared/status-summary.d.ts +1 -0
  261. package/dist/shared/status-summary.d.ts.map +1 -1
  262. package/dist/shared/status-view-check.d.ts.map +1 -1
  263. package/dist/shared/status-view.d.ts +4 -0
  264. package/dist/shared/status-view.d.ts.map +1 -1
  265. package/dist/shared/storage-permissions.d.ts +24 -0
  266. package/dist/shared/storage-permissions.d.ts.map +1 -1
  267. package/dist/shared/temporal-upgrade-fixture.d.ts +19 -0
  268. package/dist/shared/temporal-upgrade-fixture.d.ts.map +1 -0
  269. package/dist/shared/user-facing-codes.d.ts +5 -0
  270. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  271. package/dist/shared/write-transaction-timing.d.ts +8 -1
  272. package/dist/shared/write-transaction-timing.d.ts.map +1 -1
  273. package/dist/tools/ctx-expand/render.d.ts.map +1 -1
  274. package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
  275. package/dist/tools/ctx-reduce/constants.d.ts +2 -0
  276. package/dist/tools/ctx-reduce/constants.d.ts.map +1 -1
  277. package/dist/tools/ctx-reduce/tools.d.ts +4 -4
  278. package/dist/tools/ctx-reduce/tools.d.ts.map +1 -1
  279. package/dist/{transform-postprocess-phase-414phndq.js → transform-postprocess-phase-tz3pat2p.js} +15 -15
  280. package/dist/v2/context-8vgtb6sz.js +52166 -0
  281. package/dist/v2/{derive-budgets-v0krf3t7.js → derive-budgets-kdgp4s3r.js} +4 -3
  282. package/dist/v2/embedding-worker.js +6 -5
  283. package/dist/v2/fold/boundary.d.ts +2 -0
  284. package/dist/v2/fold/boundary.d.ts.map +1 -1
  285. package/dist/v2/fold/owner.d.ts.map +1 -1
  286. package/dist/v2/hooks/channel2.d.ts +2 -0
  287. package/dist/v2/hooks/channel2.d.ts.map +1 -1
  288. package/dist/v2/hooks/context.d.ts +2 -2
  289. package/dist/v2/hooks/context.d.ts.map +1 -1
  290. package/dist/v2/hooks/dream-timer.d.ts +39 -0
  291. package/dist/v2/hooks/dream-timer.d.ts.map +1 -0
  292. package/dist/v2/hooks/payload.d.ts.map +1 -1
  293. package/dist/v2/hooks/store.d.ts.map +1 -1
  294. package/dist/v2/hooks/tools.d.ts +1 -1
  295. package/dist/v2/hooks/tools.d.ts.map +1 -1
  296. package/dist/v2/hooks/update-check.d.ts.map +1 -1
  297. package/dist/v2/{message-time-backfill-0n93vrd7.js → message-time-backfill-r6qkem1x.js} +3 -3
  298. package/dist/v2/migration-worker.js +13 -8
  299. package/dist/v2/{read-session-chunk-hjza38hr.js → read-session-chunk-8vjp6581.js} +9 -9
  300. package/dist/v2/recomp-orchestrator-5xj0yzyk.js +39 -0
  301. package/dist/v2/{safe-notification-target-wtj0bbc2.js → safe-notification-target-eb1n1vfb.js} +2 -2
  302. package/dist/v2/{send-session-notification-mq9frrtm.js → send-session-notification-qs0j78v6.js} +6 -6
  303. package/dist/v2/server-14vq4kpm.js +30 -0
  304. package/dist/v2/server-1bc61ans.js +154 -0
  305. package/dist/v2/{server-n96ag4rk.js → server-1zx87sdm.js} +5 -1
  306. package/dist/v2/server-3n4q9xme.js +79 -0
  307. package/dist/v2/server-4663ejam.js +3351 -0
  308. package/dist/v2/{server-rhdgxp1t.js → server-51dv1pr5.js} +63 -2
  309. package/dist/v2/{server-5317ykaf.js → server-6r257mf5.js} +1 -1
  310. package/dist/v2/server-84w6rvvf.js +14 -0
  311. package/dist/v2/{server-qpg6wf72.js → server-ajzeteqw.js} +9 -1
  312. package/dist/{index-a4m2b1yv.js → v2/server-fg34g6a5.js} +55 -1
  313. package/dist/v2/{server-e36nf2p1.js → server-frbm99q5.js} +1595 -1599
  314. package/dist/v2/{server-remp7e2g.js → server-g0fjrkta.js} +16 -1
  315. package/dist/v2/{server-z19x7eqz.js → server-mcfawjgc.js} +4 -4
  316. package/dist/v2/server-p2en78c8.js +3892 -0
  317. package/dist/v2/{server-hfjfbg59.js → server-qp5hx1ad.js} +608 -105
  318. package/dist/v2/{server-c4g2y1z8.js → server-vnh7r35f.js} +2778 -5383
  319. package/dist/v2/server-vs5gpnd4.js +493 -0
  320. package/dist/v2/{server-w99cyt6a.js → server-wvjvfhck.js} +14 -6
  321. package/dist/v2/{server-v5xgft5v.js → server-xtp687da.js} +186 -3533
  322. package/dist/v2/{server-0jqw05sa.js → server-y8maxeft.js} +6 -84
  323. package/dist/v2/server.d.ts.map +1 -1
  324. package/dist/v2/server.js +104 -49288
  325. package/dist/v2/store-reader.d.ts +39 -1
  326. package/dist/v2/store-reader.d.ts.map +1 -1
  327. package/dist/v2/tool-result.d.ts +8 -0
  328. package/dist/v2/tool-result.d.ts.map +1 -0
  329. package/dist/v2/tui/index.d.ts.map +1 -1
  330. package/dist/v2/{wrapup-orchestrator-tbyx78dz.js → wrapup-orchestrator-r5t1pyj8.js} +20 -16
  331. package/dist/wrapup-orchestrator-kw3x3myw.js +26 -0
  332. package/package.json +22 -7
  333. package/src/config/index.ts +21 -4
  334. package/src/config/latch-permanence-guard.test.ts +6 -1
  335. package/src/config/live-run-config.ts +1 -0
  336. package/src/config/migrate-config-location.test.ts +31 -1
  337. package/src/config/migrate-config-location.ts +8 -41
  338. package/src/config/protected-tools.test.ts +70 -0
  339. package/src/config/raw-loader.test.ts +15 -0
  340. package/src/config/raw-loader.ts +1 -1
  341. package/src/config/removed-agent-source-fence.test.ts +10 -1
  342. package/src/config/schema/magic-context.test.ts +20 -1
  343. package/src/config/schema/magic-context.ts +21 -7
  344. package/src/shared/announcement.ts +6 -5
  345. package/src/shared/cache-ttl-display.test.ts +1 -1
  346. package/src/shared/cache-ttl-display.ts +17 -16
  347. package/src/shared/fold-render-lock-fence.test.ts +84 -0
  348. package/src/shared/fold-render-lock-fixtures.test.ts +276 -0
  349. package/src/shared/model-cache-ttl.test.ts +2 -2
  350. package/src/shared/model-cache-ttl.ts +8 -4
  351. package/src/shared/model-suggestion-retry.test.ts +104 -1
  352. package/src/shared/model-suggestion-retry.ts +63 -6
  353. package/src/shared/models-dev-cache.ts +3 -11
  354. package/src/shared/protected-tools-policy.ts +23 -0
  355. package/src/shared/quota-diagnostic.ts +9 -0
  356. package/src/shared/rpc-server.ts +6 -54
  357. package/src/shared/sqlite-context-pragmas.test.ts +105 -0
  358. package/src/shared/sqlite-context-pragmas.ts +24 -0
  359. package/src/shared/sqlite-helpers.ts +17 -0
  360. package/src/shared/sqlite.ts +75 -0
  361. package/src/shared/status-detail-text.test.ts +18 -1
  362. package/src/shared/status-summary.ts +11 -0
  363. package/src/shared/status-view-check.ts +5 -0
  364. package/src/shared/status-view.test.ts +11 -2
  365. package/src/shared/status-view.ts +12 -1
  366. package/src/shared/storage-permissions.test.ts +204 -0
  367. package/src/shared/storage-permissions.ts +192 -0
  368. package/src/shared/temporal-upgrade-fixture.ts +50 -0
  369. package/src/shared/user-facing-codes.ts +6 -0
  370. package/src/shared/write-transaction-timing.test.ts +39 -0
  371. package/src/shared/write-transaction-timing.ts +25 -1
  372. package/src/tui/dialogs/status-dialog-render.test.ts +1 -1
  373. package/src/tui/index.tsx +3 -1
  374. package/src/tui/startup-order.test.ts +16 -0
  375. package/src/tui-compiled/index.tsx +3 -1
  376. package/src/v2/tui/index.ts +9 -2
  377. package/dist/index-anq4nn6f.js +0 -131
  378. package/dist/index-e44zzy84.js +0 -10
  379. package/dist/index-x23gah8c.js +0 -16
  380. package/dist/v2/recomp-orchestrator-1aq7h44c.js +0 -36
  381. package/dist/v2/server-e44zzy84.js +0 -10
  382. package/dist/v2/server-fgmxwrgy.js +0 -16
  383. package/dist/v2/server-r7cmye3k.js +0 -131
  384. package/dist/wrapup-orchestrator-h28bqsy6.js +0 -26
  385. package/dist/v2/{server-ckpc8pxy.js → server-1qbnzc80.js} +8 -8
@@ -9,13 +9,20 @@ import {
9
9
  getMagicContextStorageDir,
10
10
  getLegacyOpenCodeMagicContextStorageDir
11
11
  } from "./index-q6hef7fh.js";
12
+ import {
13
+ ensureColumn,
14
+ healAllNullColumns,
15
+ installV95PerfSchema,
16
+ setDatabase,
17
+ loadToolDefinitionMeasurements
18
+ } from "./index-5gq3b2ya.js";
12
19
  import {
13
20
  resolveOpenCodeDbPath,
14
21
  hasV1MessageTables,
15
22
  openCodeDbPathExists,
16
23
  getOpenCodeDbProbeDescriptions,
17
24
  closeQuietly
18
- } from "./index-w9jwmntv.js";
25
+ } from "./index-b35pxds2.js";
19
26
  import {
20
27
  registerSlowWriteReporter,
21
28
  registerSqliteDiagnosticSink,
@@ -25,20 +32,22 @@ import {
25
32
  withoutSqliteTransformPass,
26
33
  isTransientSqliteError,
27
34
  withPrivilegedWriter
28
- } from "./index-a4m2b1yv.js";
29
- import {
30
- setDatabase,
31
- loadToolDefinitionMeasurements
32
- } from "./index-anq4nn6f.js";
35
+ } from "./index-fg34g6a5.js";
33
36
  import {
34
37
  getErrorMessage
35
38
  } from "./index-y8v6yerm.js";
36
39
  import {
37
- shouldEnforcePrivateStoragePermissions
38
- } from "./index-e44zzy84.js";
40
+ shouldEnforcePrivateStoragePermissions,
41
+ ensureStorageDirectorySync,
42
+ writeStorageFileSync,
43
+ writeStorageFileAtomicSync,
44
+ copyStorageFileSync,
45
+ copyStorageTreeSync,
46
+ tightenStorageTreeSync
47
+ } from "./index-1bc61ans.js";
39
48
  import {
40
49
  logSlowWriteTransaction
41
- } from "./index-x23gah8c.js";
50
+ } from "./index-sj29b3z2.js";
42
51
 
43
52
  // src/features/magic-context/fail-closed-block.ts
44
53
  var FAIL_CLOSED_DOCTOR_COMMAND = "npx @cortexkit/magic-context@latest doctor";
@@ -308,8 +317,8 @@ import { homedir } from "node:os";
308
317
  import path3 from "node:path";
309
318
 
310
319
  // src/features/magic-context/memory/project-identity-cache.ts
311
- import { createHash, randomUUID } from "node:crypto";
312
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
320
+ import { createHash } from "node:crypto";
321
+ import { readFileSync } from "node:fs";
313
322
  import path2 from "node:path";
314
323
 
315
324
  // src/shared/project-directory-key.ts
@@ -339,10 +348,7 @@ function cachePath(directory, storageDir = getMagicContextStorageDir()) {
339
348
  function rememberGitIdentity(directory, identity) {
340
349
  try {
341
350
  const destination = cachePath(directory);
342
- mkdirSync(path2.dirname(destination), { recursive: true });
343
- const temporary = `${destination}.${randomUUID()}.tmp`;
344
- writeFileSync(temporary, JSON.stringify({ directory: projectDirectoryKey(directory), identity }), { mode: 384 });
345
- renameSync(temporary, destination);
351
+ writeStorageFileAtomicSync(destination, JSON.stringify({ directory: projectDirectoryKey(directory), identity }));
346
352
  } catch {}
347
353
  }
348
354
  function readRememberedGitIdentity(directory, storageDir) {
@@ -1700,100 +1706,6 @@ function installCompartmentHistoryVersions(db) {
1700
1706
  }).immediate();
1701
1707
  }
1702
1708
 
1703
- // src/features/magic-context/storage-schema-helpers.ts
1704
- function ensureColumn(db, table, column, definition) {
1705
- if (!/^[a-z][a-z0-9_]*$/.test(table) || !/^[a-z][a-z0-9_]*$/.test(column) || !/^[A-Z0-9_"'(),[\]\s]+$/i.test(definition)) {
1706
- throw new Error(`Unsafe schema identifier: ${table}.${column} ${definition}`);
1707
- }
1708
- const rows = db.prepare(`PRAGMA table_info(${table})`).all();
1709
- if (rows.some((row) => row.name === column)) {
1710
- return;
1711
- }
1712
- try {
1713
- db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
1714
- } catch (err) {
1715
- const recheck = db.prepare(`PRAGMA table_info(${table})`).all();
1716
- if (recheck.some((row) => row.name === column)) {
1717
- return;
1718
- }
1719
- throw err;
1720
- }
1721
- }
1722
- function healAllNullColumns(db) {
1723
- const existingColumns = getSessionMetaColumns(db);
1724
- const fallbacks = [
1725
- ["cache_ttl", ""],
1726
- ["last_nudge_band", ""],
1727
- ["last_nudge_level", ""],
1728
- ["channel2_nudge_claim_token", ""],
1729
- ["last_transform_error", ""],
1730
- ["nudge_anchor_message_id", ""],
1731
- ["nudge_anchor_text", ""],
1732
- ["sticky_turn_reminder_text", ""],
1733
- ["sticky_turn_reminder_message_id", ""],
1734
- ["note_nudge_trigger_message_id", ""],
1735
- ["note_nudge_sticky_text", ""],
1736
- ["note_nudge_sticky_message_id", ""],
1737
- ["last_todo_state", ""],
1738
- ["todo_synthetic_call_id", ""],
1739
- ["todo_synthetic_anchor_message_id", ""],
1740
- ["todo_synthetic_state_json", ""],
1741
- ["system_prompt_hash", ""],
1742
- ["stripped_placeholder_ids", ""],
1743
- ["stale_reduce_stripped_ids", ""],
1744
- ["processed_image_stripped_ids", ""],
1745
- ["merged_reasoning_stripped_ids", ""],
1746
- ["thinking_binding_recovery_target", ""],
1747
- ["trailing_blank_decisions", ""],
1748
- ["memory_block_cache", ""],
1749
- ["memory_block_ids", ""],
1750
- ["compaction_marker_state", ""],
1751
- ["key_files", ""],
1752
- ["times_execute_threshold_reached", 0],
1753
- ["compartment_in_progress", 0],
1754
- ["historian_failure_count", 0],
1755
- ["cleared_reasoning_through_tag", 0],
1756
- ["memory_block_count", 0],
1757
- ["system_prompt_tokens", 0],
1758
- ["conversation_tokens", 0],
1759
- ["tool_call_tokens", 0],
1760
- ["note_nudge_trigger_pending", 0],
1761
- ["observed_safe_input_tokens", 0],
1762
- ["cache_alert_sent", 0],
1763
- ["new_work_tokens", 0],
1764
- ["total_input_tokens", 0],
1765
- ["last_emergency_input_sample", 0],
1766
- ["channel2_nudge_claimed_at", 0],
1767
- ["last_usage_context_limit", 0],
1768
- ["prior_boundary_ordinal", 1],
1769
- ["protected_tail_policy_version", 0],
1770
- ["protected_tail_drain_window_started_at", 0],
1771
- ["protected_tail_drain_tokens", 0],
1772
- ["recovery_no_eligible_head_count", 0],
1773
- ["force_emergency_bypass_window_start", 0],
1774
- ["force_emergency_bypass_used", 0],
1775
- ["emergency_drain_active", 0],
1776
- ["historian_drain_failure_at", 0]
1777
- ];
1778
- const presentFallbacks = fallbacks.filter(([column]) => existingColumns.has(column));
1779
- if (presentFallbacks.length > 0) {
1780
- const assignments = presentFallbacks.map(([column]) => `${column} = COALESCE(${column}, ?)`).join(", ");
1781
- const nullPredicate = presentFallbacks.map(([column]) => `${column} IS NULL`).join(" OR ");
1782
- db.prepare(`UPDATE session_meta SET ${assignments} WHERE ${nullPredicate}`).run(...presentFallbacks.map(([, fallback]) => fallback));
1783
- }
1784
- healMissingMemoryBlockIds(db, existingColumns);
1785
- }
1786
- function getSessionMetaColumns(db) {
1787
- const rows = db.prepare("PRAGMA table_info(session_meta)").all();
1788
- return new Set(rows.flatMap((row) => typeof row.name === "string" ? [row.name] : []));
1789
- }
1790
- function healMissingMemoryBlockIds(db, columns) {
1791
- if (!columns.has("memory_block_cache") || !columns.has("memory_block_ids") || !columns.has("memory_block_count")) {
1792
- return;
1793
- }
1794
- db.prepare("UPDATE session_meta SET memory_block_cache = '' WHERE memory_block_cache != '' AND (memory_block_ids IS NULL OR memory_block_ids = '') AND memory_block_count > 0").run();
1795
- }
1796
-
1797
1709
  // src/features/magic-context/workspaces.ts
1798
1710
  import { createHash as createHash4 } from "node:crypto";
1799
1711
  var VALID_SHARE_CATEGORIES = new Set(V2_MEMORY_CATEGORIES);
@@ -4405,6 +4317,13 @@ var MIGRATIONS = [
4405
4317
  splitLkgSlotPrefixes(db);
4406
4318
  splitReplayDecisions(db);
4407
4319
  }
4320
+ },
4321
+ {
4322
+ version: 95,
4323
+ description: "cover cleanup and retention reads, index git FTS rowids and store temporal replay decisions",
4324
+ up(db) {
4325
+ installV95PerfSchema(db, true);
4326
+ }
4408
4327
  }
4409
4328
  ];
4410
4329
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -4432,6 +4351,9 @@ function hasPendingMigrations(db) {
4432
4351
  return MIGRATIONS.some((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version));
4433
4352
  }
4434
4353
  var mainThreadMigrationBodies = 0;
4354
+ function getMainThreadMigrationBodyCount() {
4355
+ return mainThreadMigrationBodies;
4356
+ }
4435
4357
  function isSiblingMigrationConflict(db, error, version) {
4436
4358
  if (!(error instanceof Error))
4437
4359
  return false;
@@ -4546,11 +4468,7 @@ async function runMigrationsWithRetry(db, options = {}) {
4546
4468
 
4547
4469
  // src/features/magic-context/storage-db.ts
4548
4470
  import {
4549
- chmodSync,
4550
- copyFileSync,
4551
- cpSync,
4552
4471
  existsSync as existsSync3,
4553
- mkdirSync as mkdirSync2,
4554
4472
  readdirSync,
4555
4473
  readFileSync as readFileSync3,
4556
4474
  rmdirSync,
@@ -5284,8 +5202,20 @@ function inspectWindowsProcessesSync() {
5284
5202
  };
5285
5203
  }
5286
5204
 
5205
+ // src/shared/sqlite-context-pragmas.ts
5206
+ function configureContextDatabasePragmas(db, readonly = false) {
5207
+ const [row] = db.prepare(readonly ? "PRAGMA journal_mode" : "PRAGMA journal_mode=WAL").all();
5208
+ const mode = row?.journal_mode?.toLowerCase();
5209
+ if (mode === "memory" || readonly && mode !== "wal")
5210
+ return;
5211
+ if (mode !== "wal") {
5212
+ throw new Error(`context.db requires WAL before synchronous=NORMAL (got ${mode ?? "unknown"})`);
5213
+ }
5214
+ db.exec("PRAGMA synchronous=NORMAL");
5215
+ }
5216
+
5287
5217
  // src/features/magic-context/context-store-uuid.ts
5288
- import { randomUUID as randomUUID2 } from "node:crypto";
5218
+ import { randomUUID } from "node:crypto";
5289
5219
  function getContextStoreUuid(db) {
5290
5220
  const row = db.prepare("SELECT value FROM context_store_meta WHERE key = 'store_uuid'").get();
5291
5221
  return typeof row?.value === "string" && row.value.length > 0 ? row.value : null;
@@ -5294,7 +5224,7 @@ function ensureContextStoreUuid(db) {
5294
5224
  const existing = getContextStoreUuid(db);
5295
5225
  if (existing)
5296
5226
  return existing;
5297
- const minted = randomUUID2();
5227
+ const minted = randomUUID();
5298
5228
  withPrivilegedWriter(db, () => {
5299
5229
  db.transaction(() => {
5300
5230
  db.prepare("INSERT INTO context_store_meta(key, value) VALUES ('store_uuid', ?) ON CONFLICT(key) DO NOTHING").run(minted);
@@ -5551,6 +5481,9 @@ function startBootDeadline(timeoutMs, onDeferred) {
5551
5481
  }
5552
5482
 
5553
5483
  // src/features/magic-context/migration-worker-client.ts
5484
+ function workerStartError(detail) {
5485
+ return new Error(`the migration worker could not start (${detail}); reinstall or rebuild the plugin`);
5486
+ }
5554
5487
  function defaultWorkerEntry() {
5555
5488
  return new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./migration-worker.ts" : "./migration-worker.js", import.meta.url);
5556
5489
  }
@@ -5561,8 +5494,7 @@ function runMigrationsOffThread(data) {
5561
5494
  try {
5562
5495
  worker = new Worker(workerEntryOverride ?? defaultWorkerEntry(), { workerData: data });
5563
5496
  } catch (error) {
5564
- log(`[migrations] could not start the migration worker (${error instanceof Error ? error.message : String(error)}); applying migrations on the main thread`);
5565
- resolve("worker_unavailable");
5497
+ reject(workerStartError(error instanceof Error ? error.message : String(error)));
5566
5498
  return;
5567
5499
  }
5568
5500
  log(`[migrations] applying pending migrations on a worker thread: ${data.dbPath}`);
@@ -5586,14 +5518,14 @@ function runMigrationsOffThread(data) {
5586
5518
  };
5587
5519
  const unavailable = (detail) => {
5588
5520
  settle(() => {
5589
- log(`[migrations] the migration worker did not start (${detail}); applying migrations on the main thread`);
5590
- resolve("worker_unavailable");
5521
+ reject(workerStartError(detail));
5591
5522
  });
5592
5523
  };
5593
5524
  worker.on("message", (message) => {
5594
5525
  switch (message.type) {
5595
5526
  case "ready":
5596
5527
  ready = true;
5528
+ log(`[migrations] migration worker ready: ${data.dbPath}`);
5597
5529
  return;
5598
5530
  case "log":
5599
5531
  writeForwardedLogLine(message.line);
@@ -5603,9 +5535,17 @@ function runMigrationsOffThread(data) {
5603
5535
  setBusy(!message.waiting);
5604
5536
  return;
5605
5537
  case "done":
5538
+ if (!ready) {
5539
+ unavailable("reported completion before ready");
5540
+ return;
5541
+ }
5606
5542
  settle(() => resolve("migrated"));
5607
5543
  return;
5608
5544
  case "failed":
5545
+ if (!ready) {
5546
+ unavailable(message.message);
5547
+ return;
5548
+ }
5609
5549
  settle(() => reject(new Error(message.message)));
5610
5550
  return;
5611
5551
  }
@@ -5907,38 +5847,14 @@ function getSchemaFenceRejection() {
5907
5847
  function getMigrationOnOpenRefusal() {
5908
5848
  return lastMigrationOnOpenRefusal;
5909
5849
  }
5910
- var LATEST_SUPPORTED_VERSION = 94;
5850
+ var LATEST_SUPPORTED_VERSION = 95;
5911
5851
  var BOOT_SQLITE_BUSY_TIMEOUT_MS = 5000;
5912
- var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
5913
- var defaultStoragePermissionFs = { chmodSync, mkdirSync: mkdirSync2 };
5914
- var storagePermissionFs = defaultStoragePermissionFs;
5915
5852
  function ensureSecureStorageDir(dir) {
5916
- if (!shouldEnforcePrivateStoragePermissions()) {
5917
- storagePermissionFs.mkdirSync(dir, { recursive: true });
5918
- return;
5919
- }
5920
- storagePermissionFs.mkdirSync(dir, { recursive: true, mode: 448 });
5921
- if (!PERMISSIONS_ENFORCEABLE)
5922
- return;
5923
- try {
5924
- storagePermissionFs.chmodSync(dir, 448);
5925
- } catch (error) {
5926
- log(`[magic-context] could not restrict storage dir permissions on ${dir}: ${getErrorMessage(error)}`);
5927
- }
5853
+ ensureStorageDirectorySync(dir);
5928
5854
  }
5929
- function restrictDatabaseFilePermissions(dbPath) {
5930
- if (!PERMISSIONS_ENFORCEABLE || !shouldEnforcePrivateStoragePermissions())
5931
- return;
5932
- for (const suffix of ["", "-wal", "-shm"]) {
5933
- const file = `${dbPath}${suffix}`;
5934
- if (!existsSync3(file))
5935
- continue;
5936
- try {
5937
- storagePermissionFs.chmodSync(file, 384);
5938
- } catch (error) {
5939
- log(`[magic-context] could not restrict DB file permissions on ${file}: ${getErrorMessage(error)}`);
5940
- }
5941
- }
5855
+ function tightenStorageTree(dir) {
5856
+ const { failures } = tightenStorageTreeSync(dir);
5857
+ log(`[magic-context] storage permission tightening failures=${failures}`);
5942
5858
  }
5943
5859
  function resolveBootBusyTimeoutMs(value) {
5944
5860
  if (value === undefined)
@@ -5977,6 +5893,7 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
5977
5893
  try {
5978
5894
  const legacyDb = new Database(legacyDbPath);
5979
5895
  try {
5896
+ configureContextDatabasePragmas(legacyDb, true);
5980
5897
  legacyDb.exec("PRAGMA wal_checkpoint(TRUNCATE)");
5981
5898
  } finally {
5982
5899
  closeQuietly(legacyDb);
@@ -5989,7 +5906,7 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
5989
5906
  const dst = join2(targetDbDir, `context.db${suffix}`);
5990
5907
  if (existsSync3(src)) {
5991
5908
  try {
5992
- copyFileSync(src, dst);
5909
+ copyStorageFileSync(src, dst);
5993
5910
  } catch (error) {
5994
5911
  log(`[magic-context] failed to copy ${src}:`, getErrorMessage(error));
5995
5912
  }
@@ -5999,7 +5916,7 @@ function migrateLegacyStorageIfNeeded(targetDbPath, targetDbDir) {
5999
5916
  const targetModelsDir = join2(targetDbDir, "models");
6000
5917
  if (existsSync3(legacyModelsDir) && !existsSync3(targetModelsDir)) {
6001
5918
  try {
6002
- cpSync(legacyModelsDir, targetModelsDir, { recursive: true });
5919
+ copyStorageTreeSync(legacyModelsDir, targetModelsDir);
6003
5920
  } catch (error) {
6004
5921
  log("[magic-context] failed to copy embedding model cache:", getErrorMessage(error));
6005
5922
  }
@@ -6364,8 +6281,8 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
6364
6281
  startMessageFtsRowidMapBackfill(db).then(async () => {
6365
6282
  if (!readsOpenCodeStore)
6366
6283
  return;
6367
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-8rxs0tc9.js"));
6368
- const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-an311pmk.js"));
6284
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-egz7r68d.js"));
6285
+ const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-68gj6t3e.js"));
6369
6286
  await startMessageTimeBackfill(db, Object.assign(readRawSessionMessages, {
6370
6287
  readPage: readRawSessionMessagePage
6371
6288
  }));
@@ -6388,7 +6305,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
6388
6305
  }
6389
6306
  setDatabase(db);
6390
6307
  loadToolDefinitionMeasurements(db);
6391
- restrictDatabaseFilePermissions(dbPath);
6308
+ tightenStorageTree(dirname(dbPath));
6392
6309
  databases.set(dbPath, db);
6393
6310
  pathByDatabase.set(db, dbPath);
6394
6311
  persistenceByDatabase.set(db, true);
@@ -6401,7 +6318,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
6401
6318
  function initializeDatabase(db, busyTimeoutMs = BOOT_SQLITE_BUSY_TIMEOUT_MS) {
6402
6319
  db.exec(`PRAGMA busy_timeout=${resolveBootBusyTimeoutMs(busyTimeoutMs)}`);
6403
6320
  db.exec("PRAGMA foreign_keys=ON");
6404
- db.exec("PRAGMA journal_mode=WAL");
6321
+ configureContextDatabasePragmas(db);
6405
6322
  applySqliteTuningPragmas(db);
6406
6323
  db.exec(`
6407
6324
  CREATE TABLE IF NOT EXISTS tags (
@@ -6463,7 +6380,6 @@ function initializeDatabase(db, busyTimeoutMs = BOOT_SQLITE_BUSY_TIMEOUT_MS) {
6463
6380
  harness TEXT NOT NULL DEFAULT 'opencode',
6464
6381
  UNIQUE(session_id, sequence)
6465
6382
  );
6466
- CREATE INDEX IF NOT EXISTS idx_compartments_session ON compartments(session_id);
6467
6383
 
6468
6384
  CREATE TABLE IF NOT EXISTS compartment_chunk_embeddings (
6469
6385
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -6524,7 +6440,6 @@ function initializeDatabase(db, busyTimeoutMs = BOOT_SQLITE_BUSY_TIMEOUT_MS) {
6524
6440
  harness TEXT NOT NULL DEFAULT 'opencode',
6525
6441
  PRIMARY KEY(session_id, message_ordinal)
6526
6442
  );
6527
- CREATE INDEX IF NOT EXISTS idx_compression_depth_session ON compression_depth(session_id);
6528
6443
 
6529
6444
  CREATE TABLE IF NOT EXISTS session_facts (
6530
6445
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -6830,7 +6745,6 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
6830
6745
  stale_reason TEXT,
6831
6746
  PRIMARY KEY (project_path, path)
6832
6747
  );
6833
- CREATE INDEX IF NOT EXISTS idx_project_key_files_project ON project_key_files(project_path);
6834
6748
  CREATE INDEX IF NOT EXISTS idx_project_key_files_generated_at ON project_key_files(project_path, generated_at);
6835
6749
 
6836
6750
  CREATE TABLE IF NOT EXISTS project_key_files_version (
@@ -7215,10 +7129,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
7215
7129
  input_tokens INTEGER NOT NULL DEFAULT 0,
7216
7130
  PRIMARY KEY (session_id, harness, message_id)
7217
7131
  );
7218
- CREATE INDEX IF NOT EXISTS idx_transform_decisions_session_harness
7219
- ON transform_decisions(session_id, harness);
7220
7132
 
7221
- CREATE INDEX IF NOT EXISTS idx_tags_session_tag_number ON tags(session_id, tag_number);
7222
7133
  CREATE INDEX IF NOT EXISTS idx_tags_session_message_id ON tags(session_id, message_id);
7223
7134
 
7224
7135
  -- Clone/import paths can write tags before session bootstrap. Keep trigger-created
@@ -7264,9 +7175,7 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
7264
7175
  WHERE NEW.session_id != OLD.session_id
7265
7176
  ON CONFLICT(session_id) DO UPDATE SET tags_version = tags_version + 1;
7266
7177
  END;
7267
- CREATE INDEX IF NOT EXISTS idx_pending_ops_session ON pending_ops(session_id);
7268
7178
  CREATE INDEX IF NOT EXISTS idx_pending_ops_session_tag_id ON pending_ops(session_id, tag_id);
7269
- CREATE INDEX IF NOT EXISTS idx_source_contents_session ON source_contents(session_id);
7270
7179
 
7271
7180
  CREATE TABLE IF NOT EXISTS recomp_compartments (
7272
7181
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -7619,8 +7528,6 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
7619
7528
  input_tokens INTEGER NOT NULL DEFAULT 0,
7620
7529
  PRIMARY KEY (session_id, harness, message_id)
7621
7530
  );
7622
- CREATE INDEX IF NOT EXISTS idx_transform_decisions_session_harness
7623
- ON transform_decisions(session_id, harness);
7624
7531
  `);
7625
7532
  ensureColumn(db, "transform_decisions", "system_hash_prev", "TEXT");
7626
7533
  ensureColumn(db, "transform_decisions", "system_hash_new", "TEXT");
@@ -7642,12 +7549,26 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
7642
7549
  ON message_history_index(harness, session_id, updated_at);
7643
7550
  `);
7644
7551
  ensureColumn(db, "workspaces", "share_categories", `TEXT NOT NULL DEFAULT '["CONSTRAINTS"]'`);
7552
+ const version = getPersistedSchemaVersion(db);
7553
+ if (version === 0 || version >= 95)
7554
+ installV95PerfSchema(db, false, version === 0);
7645
7555
  }
7646
7556
  var CHANNEL2_CLAIM_TTL_MS = 10 * 60000;
7557
+ var channel2HealStatements = new WeakMap;
7647
7558
  function healWedgedChannel2Claims(db) {
7648
7559
  try {
7649
7560
  const staleBefore = Date.now() - CHANNEL2_CLAIM_TTL_MS;
7650
- db.prepare("UPDATE session_meta SET channel2_nudge_state = '', channel2_nudge_claimed_at = 0, channel2_nudge_claim_token = '' WHERE channel2_nudge_state = 'claimed' AND (channel2_nudge_claimed_at IS NULL OR channel2_nudge_claimed_at = 0 OR channel2_nudge_claimed_at <= ?)").run(staleBefore);
7561
+ let statements = channel2HealStatements.get(db);
7562
+ if (!statements) {
7563
+ const predicate = "channel2_nudge_state = 'claimed' AND (channel2_nudge_claimed_at IS NULL OR channel2_nudge_claimed_at = 0 OR channel2_nudge_claimed_at <= ?)";
7564
+ statements = {
7565
+ stale: db.prepare(`SELECT 1 FROM session_meta WHERE ${predicate} LIMIT 1`),
7566
+ heal: db.prepare(`UPDATE session_meta SET channel2_nudge_state = '', channel2_nudge_claimed_at = 0, channel2_nudge_claim_token = '' WHERE ${predicate}`)
7567
+ };
7568
+ channel2HealStatements.set(db, statements);
7569
+ }
7570
+ if (statements.stale.get(staleBefore))
7571
+ statements.heal.run(staleBefore);
7651
7572
  } catch {}
7652
7573
  }
7653
7574
  function openDatabase(dbPathOrOptions) {
@@ -7679,18 +7600,38 @@ function openDatabase(dbPathOrOptions) {
7679
7600
  migrateLegacyStorageIfNeeded(dbPath, dbDir);
7680
7601
  }
7681
7602
  ensureSecureStorageDir(dbDir);
7603
+ tightenStorageTree(dbDir);
7604
+ if (!existsSync3(dbPath) && shouldEnforcePrivateStoragePermissions()) {
7605
+ try {
7606
+ writeStorageFileSync(dbPath, new Uint8Array, { flag: "wx" });
7607
+ } catch (error) {
7608
+ if (error.code !== "EEXIST")
7609
+ throw error;
7610
+ }
7611
+ }
7682
7612
  db = new Database(dbPath);
7683
7613
  installBootBusyTimeout(db, dbPath, busyTimeoutMs, options?.onBootBusyTimeout);
7684
7614
  if (!enforceSchemaFence(db, dbPath, latestSupportedVersion)) {
7685
7615
  closeQuietly(db);
7686
7616
  return null;
7687
7617
  }
7618
+ if (options?.allowMigrations === false && hasPendingMigrations(db)) {
7619
+ log(`[magic-context] storage not ready: pending migrations at ${dbPath}; host callers must await the async opener`);
7620
+ closeQuietly(db);
7621
+ return null;
7622
+ }
7688
7623
  if (!enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)) {
7689
7624
  closeQuietly(db);
7690
7625
  return null;
7691
7626
  }
7692
7627
  initializeDatabase(db, busyTimeoutMs);
7693
- runMigrations(db);
7628
+ if (options?.allowMigrations === false) {
7629
+ if (hasPendingMigrations(db)) {
7630
+ closeQuietly(db);
7631
+ return null;
7632
+ }
7633
+ } else
7634
+ runMigrations(db);
7694
7635
  ensureContextStoreUuid(db);
7695
7636
  return finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion);
7696
7637
  } catch (error) {
@@ -7701,6 +7642,9 @@ function openDatabase(dbPathOrOptions) {
7701
7642
  throw new Error(`[magic-context] storage unavailable: ${detail}. Magic Context is disabled for this run; check log for details.`);
7702
7643
  }
7703
7644
  }
7645
+ function openCurrentDatabase(options = {}) {
7646
+ return openDatabase({ ...options, allowMigrations: false });
7647
+ }
7704
7648
  async function openDatabaseAsync(dbPathOrOptions) {
7705
7649
  const options = typeof dbPathOrOptions === "string" ? { dbPath: dbPathOrOptions } : dbPathOrOptions;
7706
7650
  const explicitDbPath = options?.dbPath !== undefined;
@@ -7728,8 +7672,12 @@ async function openDatabaseAsync(dbPathOrOptions) {
7728
7672
  const pending = pendingAsyncOpens.get(dbPath);
7729
7673
  if (pending)
7730
7674
  return pending;
7675
+ if (!isFileBackedPath(dbPath)) {
7676
+ throw new Error("async migration requires a file-backed database; use the explicit synchronous opener for in-memory or URI test databases");
7677
+ }
7731
7678
  const opening = (async () => {
7732
7679
  let db;
7680
+ const mainThreadBodiesBefore = getMainThreadMigrationBodyCount();
7733
7681
  const openStartedAt = performance.now();
7734
7682
  let openMs = 0;
7735
7683
  let guardMs = 0;
@@ -7740,6 +7688,15 @@ async function openDatabaseAsync(dbPathOrOptions) {
7740
7688
  if (!explicitDbPath)
7741
7689
  migrateLegacyStorageIfNeeded(dbPath, dbDir);
7742
7690
  ensureSecureStorageDir(dbDir);
7691
+ tightenStorageTree(dbDir);
7692
+ if (!existsSync3(dbPath) && shouldEnforcePrivateStoragePermissions()) {
7693
+ try {
7694
+ writeStorageFileSync(dbPath, new Uint8Array, { flag: "wx" });
7695
+ } catch (error) {
7696
+ if (error.code !== "EEXIST")
7697
+ throw error;
7698
+ }
7699
+ }
7743
7700
  db = new Database(dbPath);
7744
7701
  installBootBusyTimeout(db, dbPath, busyTimeoutMs, options?.onBootBusyTimeout);
7745
7702
  openMs = performance.now() - openStartedAt;
@@ -7757,15 +7714,20 @@ async function openDatabaseAsync(dbPathOrOptions) {
7757
7714
  }
7758
7715
  guardMs = performance.now() - guardStartedAt;
7759
7716
  migrateStartedAt = performance.now();
7760
- if (isFileBackedPath(dbPath) && hasPendingMigrations(db)) {
7717
+ if (hasPendingMigrations(db)) {
7761
7718
  await runMigrationsOffThread({
7762
7719
  dbPath,
7763
7720
  busyTimeoutMs,
7764
7721
  sqlitePragmaConfig: { ...sqlitePragmaConfig }
7765
7722
  });
7766
7723
  }
7724
+ if (hasPendingMigrations(db)) {
7725
+ throw new Error("the migration worker did not complete the pending migration; reinstall or rebuild the plugin");
7726
+ }
7767
7727
  initializeDatabase(db, busyTimeoutMs);
7768
- await runMigrationsWithRetry(db);
7728
+ if (hasPendingMigrations(db)) {
7729
+ throw new Error("storage initialization left a pending migration; reinstall or rebuild the plugin");
7730
+ }
7769
7731
  ensureContextStoreUuid(db);
7770
7732
  const opened = finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion);
7771
7733
  migrateMs = performance.now() - migrateStartedAt;
@@ -7777,6 +7739,7 @@ async function openDatabaseAsync(dbPathOrOptions) {
7777
7739
  log(`[magic-context] storage fatal: failed to open ${dbPath}: ${detail}`);
7778
7740
  throw new Error(`[magic-context] storage unavailable: ${detail}. Magic Context is disabled for this run; check log for details.`);
7779
7741
  } finally {
7742
+ log(`[migrations] async open main-thread migration-body count: ${getMainThreadMigrationBodyCount() - mainThreadBodiesBefore} (total=${getMainThreadMigrationBodyCount()}) path=${dbPath}`);
7780
7743
  if (openMs === 0)
7781
7744
  openMs = performance.now() - openStartedAt;
7782
7745
  if (guardStartedAt !== null && guardMs === 0) {
@@ -7807,4 +7770,4 @@ function getDatabasePersistenceError(db) {
7807
7770
  return persistenceErrorByDatabase.get(db) ?? null;
7808
7771
  }
7809
7772
 
7810
- export { FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, formatFailClosedBlockingSummary, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, canonicalProjectDirectory, setHomeProjectPermission, shouldSkipHomeProjectMemory, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, isUserHomeDirectory, resolveProjectIdentity, directoryHasGitMetadata, describeUnresolvedProjectIdentity, isUsableProjectIdentity, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, registerOwnRpcServerInstance, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, inspectProcessesAsync, recordMessageFtsRowid, recordIndexedMessageTime, messageFtsOrdinalRangeIsMapped, deleteUnmappedMessageFtsRows, layoutLkgPrefix, assembleLkgPrefix, startBootDeadline, V2_MEMORY_CATEGORIES, PROMOTABLE_CATEGORIES, CATEGORY_PRIORITY, getMemoryCategoryOrder, CATEGORY_DEFAULT_TTL, unescapeXml, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, managedAuthorityNoteRow, runMigrationsWithRetry, getUnconfirmedMigrationHolders, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, BOOT_SQLITE_BUSY_TIMEOUT_MS, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, initializeDatabase, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError };
7773
+ export { FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, formatFailClosedBlockingSummary, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, canonicalProjectDirectory, setHomeProjectPermission, shouldSkipHomeProjectMemory, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, isUserHomeDirectory, resolveProjectIdentity, directoryHasGitMetadata, describeUnresolvedProjectIdentity, isUsableProjectIdentity, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, registerOwnRpcServerInstance, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, inspectProcessesAsync, configureContextDatabasePragmas, recordMessageFtsRowid, recordIndexedMessageTime, messageFtsOrdinalRangeIsMapped, deleteUnmappedMessageFtsRows, layoutLkgPrefix, assembleLkgPrefix, startBootDeadline, V2_MEMORY_CATEGORIES, PROMOTABLE_CATEGORIES, CATEGORY_PRIORITY, getMemoryCategoryOrder, CATEGORY_DEFAULT_TTL, unescapeXml, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, managedAuthorityNoteRow, runMigrationsWithRetry, getUnconfirmedMigrationHolders, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, BOOT_SQLITE_BUSY_TIMEOUT_MS, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, initializeDatabase, openDatabase, openCurrentDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError };