@cortexkit/opencode-magic-context 0.43.1 → 0.44.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 (271) hide show
  1. package/README.md +18 -2
  2. package/dist/config/index.d.ts +13 -0
  3. package/dist/config/index.d.ts.map +1 -1
  4. package/dist/config/project-security.d.ts +6 -3
  5. package/dist/config/project-security.d.ts.map +1 -1
  6. package/dist/config/schema/magic-context.d.ts +27 -0
  7. package/dist/config/schema/magic-context.d.ts.map +1 -1
  8. package/dist/{conflict-warning-hook-956fkedc.js → conflict-warning-hook-48f7np9d.js} +5 -5
  9. package/dist/{derive-budgets-b8ybssh9.js → derive-budgets-8kgevxmx.js} +2 -2
  10. package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
  11. package/dist/features/magic-context/compartment-embedding.d.ts +3 -2
  12. package/dist/features/magic-context/compartment-embedding.d.ts.map +1 -1
  13. package/dist/features/magic-context/compartment-storage.d.ts.map +1 -1
  14. package/dist/features/magic-context/dreamer/classify.d.ts +12 -0
  15. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  16. package/dist/features/magic-context/dreamer/curate-category-rotation.d.ts.map +1 -1
  17. package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts.map +1 -1
  18. package/dist/features/magic-context/dreamer/failed-invocation-evidence.d.ts +13 -0
  19. package/dist/features/magic-context/dreamer/failed-invocation-evidence.d.ts.map +1 -0
  20. package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts.map +1 -1
  21. package/dist/features/magic-context/dreamer/lease.d.ts +5 -2
  22. package/dist/features/magic-context/dreamer/lease.d.ts.map +1 -1
  23. package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
  24. package/dist/features/magic-context/dreamer/memory-claim-safety.d.ts.map +1 -1
  25. package/dist/features/magic-context/dreamer/module-apply.d.ts +1 -0
  26. package/dist/features/magic-context/dreamer/module-apply.d.ts.map +1 -1
  27. package/dist/features/magic-context/dreamer/retrospective-learnings.d.ts.map +1 -1
  28. package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts +1 -1
  29. package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts.map +1 -1
  30. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  31. package/dist/features/magic-context/dreamer/task-scheduler.d.ts +2 -0
  32. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  33. package/dist/features/magic-context/dreamer/verify.d.ts +19 -0
  34. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  35. package/dist/features/magic-context/fail-closed-block.d.ts +7 -0
  36. package/dist/features/magic-context/fail-closed-block.d.ts.map +1 -1
  37. package/dist/features/magic-context/index.d.ts +1 -0
  38. package/dist/features/magic-context/index.d.ts.map +1 -1
  39. package/dist/features/magic-context/install-instance-id.d.ts +33 -0
  40. package/dist/features/magic-context/install-instance-id.d.ts.map +1 -0
  41. package/dist/features/magic-context/memory/constants.d.ts.map +1 -1
  42. package/dist/features/magic-context/memory/embedding-backfill.d.ts.map +1 -1
  43. package/dist/features/magic-context/memory/single-store-embedding-drain.d.ts +35 -0
  44. package/dist/features/magic-context/memory/single-store-embedding-drain.d.ts.map +1 -0
  45. package/dist/features/magic-context/memory/verification-paths.d.ts.map +1 -1
  46. package/dist/features/magic-context/message-index.d.ts +23 -0
  47. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  48. package/dist/features/magic-context/migrations.d.ts +7 -0
  49. package/dist/features/magic-context/migrations.d.ts.map +1 -1
  50. package/dist/features/magic-context/overflow-detection.d.ts +31 -8
  51. package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
  52. package/dist/features/magic-context/project-embedding-registry.d.ts +40 -1
  53. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  54. package/dist/features/magic-context/search.d.ts.map +1 -1
  55. package/dist/features/magic-context/session-decision-calibration.d.ts.map +1 -1
  56. package/dist/features/magic-context/storage-db.d.ts +1 -1
  57. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  58. package/dist/features/magic-context/storage-meta-persisted.d.ts +20 -5
  59. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  60. package/dist/features/magic-context/storage-meta.d.ts +1 -1
  61. package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
  62. package/dist/features/magic-context/storage-notes.d.ts +1 -0
  63. package/dist/features/magic-context/storage-notes.d.ts.map +1 -1
  64. package/dist/features/magic-context/storage-primers.d.ts.map +1 -1
  65. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  66. package/dist/features/magic-context/storage-unavailable-reason.d.ts +17 -0
  67. package/dist/features/magic-context/storage-unavailable-reason.d.ts.map +1 -0
  68. package/dist/features/magic-context/storage.d.ts +1 -1
  69. package/dist/features/magic-context/storage.d.ts.map +1 -1
  70. package/dist/features/magic-context/store-generation-rebase.d.ts +95 -2
  71. package/dist/features/magic-context/store-generation-rebase.d.ts.map +1 -1
  72. package/dist/features/magic-context/subagent-token-capture.d.ts.map +1 -1
  73. package/dist/features/magic-context/transform-decision-log.d.ts +1 -1
  74. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  75. package/dist/features/magic-context/types.d.ts +8 -3
  76. package/dist/features/magic-context/types.d.ts.map +1 -1
  77. package/dist/features/magic-context/user-memory/storage-user-memory.d.ts.map +1 -1
  78. package/dist/hooks/magic-context/apply-operations.d.ts +105 -9
  79. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  80. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  81. package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
  82. package/dist/hooks/magic-context/compartment-parser.d.ts +2 -0
  83. package/dist/hooks/magic-context/compartment-parser.d.ts.map +1 -1
  84. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +1 -0
  85. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  86. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts +6 -0
  87. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  88. package/dist/hooks/magic-context/compartment-runner-partial-recomp.d.ts.map +1 -1
  89. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  90. package/dist/hooks/magic-context/compartment-runner-types.d.ts +2 -0
  91. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  92. package/dist/hooks/magic-context/compartment-runner-validation.d.ts +7 -0
  93. package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
  94. package/dist/hooks/magic-context/context-limit-resolution.d.ts +31 -0
  95. package/dist/hooks/magic-context/context-limit-resolution.d.ts.map +1 -0
  96. package/dist/hooks/magic-context/ctx-reduce-availability.d.ts +60 -8
  97. package/dist/hooks/magic-context/ctx-reduce-availability.d.ts.map +1 -1
  98. package/dist/hooks/magic-context/embed-history-runner.d.ts +0 -1
  99. package/dist/hooks/magic-context/embed-history-runner.d.ts.map +1 -1
  100. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  101. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  102. package/dist/hooks/magic-context/format-embed-status.d.ts.map +1 -1
  103. package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
  104. package/dist/hooks/magic-context/historian-host-runner.d.ts +233 -0
  105. package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -0
  106. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  107. package/dist/hooks/magic-context/image-token-estimate.d.ts +9 -0
  108. package/dist/hooks/magic-context/image-token-estimate.d.ts.map +1 -1
  109. package/dist/hooks/magic-context/inject-compartments.d.ts +60 -1
  110. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  111. package/dist/hooks/magic-context/lkg-slot.d.ts +6 -0
  112. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  113. package/dist/hooks/magic-context/module-client.d.ts +21 -0
  114. package/dist/hooks/magic-context/module-client.d.ts.map +1 -0
  115. package/dist/hooks/magic-context/module-state-sync.d.ts +6 -2
  116. package/dist/hooks/magic-context/module-state-sync.d.ts.map +1 -1
  117. package/dist/hooks/magic-context/module-tool-backends.d.ts +47 -0
  118. package/dist/hooks/magic-context/module-tool-backends.d.ts.map +1 -0
  119. package/dist/hooks/magic-context/module-transport.d.ts +1 -1
  120. package/dist/hooks/magic-context/module-transport.d.ts.map +1 -1
  121. package/dist/hooks/magic-context/persist-filtered-noise.d.ts.map +1 -1
  122. package/dist/hooks/magic-context/read-session-chunk.d.ts +12 -0
  123. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  124. package/dist/hooks/magic-context/rust-mode-transform.d.ts +35 -0
  125. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  126. package/dist/hooks/magic-context/rust-refusal-recovery.d.ts +18 -0
  127. package/dist/hooks/magic-context/rust-refusal-recovery.d.ts.map +1 -1
  128. package/dist/hooks/magic-context/rust-served-m0.d.ts +20 -0
  129. package/dist/hooks/magic-context/rust-served-m0.d.ts.map +1 -0
  130. package/dist/hooks/magic-context/store-ahead-refusal.d.ts +40 -0
  131. package/dist/hooks/magic-context/store-ahead-refusal.d.ts.map +1 -0
  132. package/dist/hooks/magic-context/strip-content.d.ts +5 -5
  133. package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
  134. package/dist/hooks/magic-context/system-prompt-hash.d.ts +9 -0
  135. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  136. package/dist/hooks/magic-context/tag-messages.d.ts +19 -0
  137. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  138. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
  139. package/dist/hooks/magic-context/tool-drop-target.d.ts +14 -0
  140. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  141. package/dist/hooks/magic-context/tool-input-size.d.ts +21 -0
  142. package/dist/hooks/magic-context/tool-input-size.d.ts.map +1 -0
  143. package/dist/hooks/magic-context/tool-sweep-policy.d.ts.map +1 -1
  144. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +124 -11
  145. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  146. package/dist/hooks/magic-context/transform.d.ts +13 -0
  147. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  148. package/dist/{index-0ccmyzbj.js → index-01ft0h3p.js} +1 -1
  149. package/dist/{index-j7cnyvq1.js → index-2zf5fv89.js} +254 -61
  150. package/dist/{index-kpmmr8s0.js → index-5f4qsnaq.js} +2 -2
  151. package/dist/{index-yc81txp4.js → index-c906f3ff.js} +4 -4
  152. package/dist/{index-1gtwrdc4.js → index-cj5qe2nw.js} +3 -3
  153. package/dist/{index-febg06dy.js → index-dx0xnd4q.js} +1 -1
  154. package/dist/{index-v8qr6tt2.js → index-pye48m79.js} +3 -3
  155. package/dist/{index-7wpwr2e2.js → index-rdey8znw.js} +1175 -290
  156. package/dist/{index-wgzyeyf5.js → index-tjq5jztd.js} +22 -6
  157. package/dist/{index-9r1cbh9e.js → index-v6wsttqt.js} +1 -1
  158. package/dist/index.d.ts.map +1 -1
  159. package/dist/index.js +3546 -1642
  160. package/dist/{message-time-backfill-0ccvyk9n.js → message-time-backfill-rm9wmcem.js} +3 -3
  161. package/dist/plugin/dream-timer.d.ts +2 -0
  162. package/dist/plugin/dream-timer.d.ts.map +1 -1
  163. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  164. package/dist/plugin/messages-transform.d.ts.map +1 -1
  165. package/dist/plugin/native-compaction-guard.d.ts +22 -0
  166. package/dist/plugin/native-compaction-guard.d.ts.map +1 -0
  167. package/dist/plugin/rpc-handlers.d.ts +11 -0
  168. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  169. package/dist/{read-session-chunk-z7fv0qjv.js → read-session-chunk-ktz5zt70.js} +5 -3
  170. package/dist/{recomp-orchestrator-r00aa5t3.js → recomp-orchestrator-ahekzt0s.js} +8 -8
  171. package/dist/{safe-notification-target-vrkjrbgb.js → safe-notification-target-6w0esgd6.js} +2 -2
  172. package/dist/{send-session-notification-3warjyjp.js → send-session-notification-w7xbnrsm.js} +4 -4
  173. package/dist/shared/index.d.ts +1 -0
  174. package/dist/shared/index.d.ts.map +1 -1
  175. package/dist/shared/logger.d.ts.map +1 -1
  176. package/dist/shared/model-suggestion-retry.d.ts +13 -1
  177. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  178. package/dist/shared/opencode-db-path.d.ts.map +1 -1
  179. package/dist/shared/prompt-async-transport.d.ts +25 -0
  180. package/dist/shared/prompt-async-transport.d.ts.map +1 -0
  181. package/dist/shared/rpc-server.d.ts +1 -0
  182. package/dist/shared/rpc-server.d.ts.map +1 -1
  183. package/dist/shared/rpc-types.d.ts +16 -0
  184. package/dist/shared/rpc-types.d.ts.map +1 -1
  185. package/dist/shared/rpc-utils.d.ts +3 -0
  186. package/dist/shared/rpc-utils.d.ts.map +1 -1
  187. package/dist/shared/sqlite-write-locker-test-support.d.ts +7 -0
  188. package/dist/shared/sqlite-write-locker-test-support.d.ts.map +1 -0
  189. package/dist/shared/status-summary.d.ts +9 -1
  190. package/dist/shared/status-summary.d.ts.map +1 -1
  191. package/dist/shared/tag-transcript.d.ts.map +1 -1
  192. package/dist/shared/test-fake-executable.d.ts +38 -0
  193. package/dist/shared/test-fake-executable.d.ts.map +1 -0
  194. package/dist/shared/user-facing-codes.d.ts +20 -5
  195. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  196. package/dist/shared/window-geometry.d.ts +6 -3
  197. package/dist/shared/window-geometry.d.ts.map +1 -1
  198. package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
  199. package/dist/tools/ctx-note/tools.d.ts.map +1 -1
  200. package/dist/tools/ctx-reduce/tools.d.ts.map +1 -1
  201. package/dist/tools/ctx-search/tools.d.ts.map +1 -1
  202. package/dist/v2/fold/boundary.d.ts +61 -0
  203. package/dist/v2/fold/boundary.d.ts.map +1 -0
  204. package/dist/v2/fold/restore.d.ts.map +1 -1
  205. package/dist/v2/hidden-completion.d.ts +16 -3
  206. package/dist/v2/hidden-completion.d.ts.map +1 -1
  207. package/dist/v2/hooks/context.d.ts +45 -14
  208. package/dist/v2/hooks/context.d.ts.map +1 -1
  209. package/dist/v2/hooks/hidden-child.d.ts +6 -0
  210. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  211. package/dist/v2/hooks/payload.d.ts.map +1 -1
  212. package/dist/v2/hooks/refusal.d.ts +9 -1
  213. package/dist/v2/hooks/refusal.d.ts.map +1 -1
  214. package/dist/v2/hooks/restore-rows.d.ts +29 -0
  215. package/dist/v2/hooks/restore-rows.d.ts.map +1 -0
  216. package/dist/v2/hooks/rpc-live-state.d.ts +1 -1
  217. package/dist/v2/hooks/rpc-live-state.d.ts.map +1 -1
  218. package/dist/v2/hooks/rust-mode.d.ts +47 -0
  219. package/dist/v2/hooks/rust-mode.d.ts.map +1 -0
  220. package/dist/v2/hooks/session-project-backfill.d.ts +15 -0
  221. package/dist/v2/hooks/session-project-backfill.d.ts.map +1 -0
  222. package/dist/v2/hooks/storage-gate.d.ts +42 -0
  223. package/dist/v2/hooks/storage-gate.d.ts.map +1 -0
  224. package/dist/v2/hooks/storage-notice.d.ts +29 -0
  225. package/dist/v2/hooks/storage-notice.d.ts.map +1 -0
  226. package/dist/v2/hooks/store.d.ts +16 -0
  227. package/dist/v2/hooks/store.d.ts.map +1 -1
  228. package/dist/v2/hooks/tools.d.ts +11 -2
  229. package/dist/v2/hooks/tools.d.ts.map +1 -1
  230. package/dist/v2/hooks/types.d.ts +4 -0
  231. package/dist/v2/hooks/types.d.ts.map +1 -1
  232. package/dist/v2/hooks/update-check.d.ts +8 -0
  233. package/dist/v2/hooks/update-check.d.ts.map +1 -1
  234. package/dist/v2/hooks/usage-persist.d.ts +31 -0
  235. package/dist/v2/hooks/usage-persist.d.ts.map +1 -0
  236. package/dist/v2/server.js +12692 -8030
  237. package/dist/v2/store-reader.d.ts +17 -0
  238. package/dist/v2/store-reader.d.ts.map +1 -1
  239. package/dist/wrapup-orchestrator-9srk0kjf.js +18 -0
  240. package/package.json +1 -1
  241. package/src/agents/magic-context-prompt.ts +3 -3
  242. package/src/config/index.ts +40 -0
  243. package/src/config/misplaced-agent-model.test.ts +61 -0
  244. package/src/config/project-security.test.ts +17 -0
  245. package/src/config/project-security.ts +28 -4
  246. package/src/config/schema/magic-context.ts +29 -2
  247. package/src/shared/index.ts +1 -0
  248. package/src/shared/logger.test.ts +63 -2
  249. package/src/shared/logger.ts +23 -5
  250. package/src/shared/model-suggestion-retry.test.ts +115 -4
  251. package/src/shared/model-suggestion-retry.ts +57 -12
  252. package/src/shared/opencode-db-path.test.ts +18 -0
  253. package/src/shared/opencode-db-path.ts +5 -2
  254. package/src/shared/prompt-async-transport.test.ts +217 -0
  255. package/src/shared/prompt-async-transport.ts +242 -0
  256. package/src/shared/prompt-surface-a1-golden.md +8 -8
  257. package/src/shared/rpc-server.ts +13 -1
  258. package/src/shared/rpc-types.ts +17 -0
  259. package/src/shared/rpc-utils.ts +28 -0
  260. package/src/shared/sqlite-transaction-mode-guard.test.ts +198 -0
  261. package/src/shared/sqlite-write-locker-test-support.ts +62 -0
  262. package/src/shared/status-detail-text.test.ts +23 -0
  263. package/src/shared/status-summary.ts +25 -1
  264. package/src/shared/tag-transcript.ts +82 -19
  265. package/src/shared/test-fake-executable.test.ts +54 -0
  266. package/src/shared/test-fake-executable.ts +110 -0
  267. package/src/shared/user-facing-codes.ts +23 -5
  268. package/src/shared/window-geometry.ts +6 -3
  269. package/dist/v2/hooks/provider-admission.d.ts +0 -22
  270. package/dist/v2/hooks/provider-admission.d.ts.map +0 -1
  271. package/dist/wrapup-orchestrator-y0bs7t5a.js +0 -18
@@ -9,7 +9,7 @@ import {
9
9
  sanitizeDiagnosticText,
10
10
  log,
11
11
  sessionLog
12
- } from "./index-wgzyeyf5.js";
12
+ } from "./index-tjq5jztd.js";
13
13
  import {
14
14
  resolveDecisionCalibration,
15
15
  providerMass,
@@ -24,6 +24,7 @@ import {
24
24
  stableStringify,
25
25
  setDatabase,
26
26
  loadToolDefinitionMeasurements,
27
+ stripWellFormedLeadingTagPrefix,
27
28
  stripTagPrefix,
28
29
  peelLeadingMcTagNotation,
29
30
  isRecord,
@@ -51,11 +52,13 @@ import {
51
52
  getCachedAbsoluteMessageCount2,
52
53
  readRawSessionMessageIdOrdinalsForRange2,
53
54
  hasRawSessionMessageById2,
55
+ readRawSessionMessageOrdinalById2,
56
+ compareRawSessionMessageOrder2,
54
57
  getRawSessionMessageCount2,
55
58
  getRawSessionTagKeysThrough2,
56
59
  getLegacyProtectedTailStartOrdinal2,
57
60
  readSessionChunk2
58
- } from "./index-j7cnyvq1.js";
61
+ } from "./index-2zf5fv89.js";
59
62
  import {
60
63
  resolveOpenCodeDbPath,
61
64
  hasV1MessageTables,
@@ -70,7 +73,7 @@ import {
70
73
  closeQuietly,
71
74
  withReadOnlySessionDb,
72
75
  getMessageTimesFromOpenCodeDb
73
- } from "./index-v8qr6tt2.js";
76
+ } from "./index-pye48m79.js";
74
77
  import {
75
78
  piModelRefToCanonical,
76
79
  modelRefLookupOrder,
@@ -81,7 +84,7 @@ import {
81
84
  getSdkOutputLimit,
82
85
  deriveTriggerBudget2,
83
86
  producerSourceLocalBudget2
84
- } from "./index-0ccmyzbj.js";
87
+ } from "./index-01ft0h3p.js";
85
88
  import {
86
89
  createScanner,
87
90
  parseTree,
@@ -98,10 +101,10 @@ import {
98
101
  getErrorMessage,
99
102
  describeError,
100
103
  sendStatusNotification2
101
- } from "./index-yc81txp4.js";
104
+ } from "./index-c906f3ff.js";
102
105
  import {
103
106
  logSlowWriteTransaction
104
- } from "./index-9r1cbh9e.js";
107
+ } from "./index-v6wsttqt.js";
105
108
 
106
109
  // src/config/schema/magic-context.ts
107
110
  import { homedir } from "node:os";
@@ -5532,6 +5535,7 @@ var AgentMetadataSchema = AgentOverrideConfigSchema.pick({
5532
5535
  maxTokens: true
5533
5536
  });
5534
5537
  var DreamerConfigSchema = AgentMetadataSchema.extend({
5538
+ runner: _enum(["broca", "host"]).optional().describe(`Which side runs the dreamer completions the Rust module routes (classify-memories) in Rust transform mode: "host" runs them on this process's carrier, "broca" routes them to the Broca module. When unset, historian.runner applies, and when that is unset too the harness decides the same way it does for the historian. User-level config only.`),
5535
5539
  opencode: DreamerOpenCodeHarnessBlockSchema.optional(),
5536
5540
  pi: DreamerPiHarnessBlockSchema.optional(),
5537
5541
  omp: DreamerOmpHarnessBlockSchema.optional(),
@@ -5542,6 +5546,10 @@ var HistorianConfigSchema = AgentMetadataSchema.extend({
5542
5546
  opencode: OpenCodeHarnessBlockSchema.optional(),
5543
5547
  pi: PiHarnessBlockSchema.optional(),
5544
5548
  omp: OmpHarnessBlockSchema.optional(),
5549
+ runner: _enum(["broca", "host"]).optional().describe('Which side runs the historian completion in Rust transform mode: "host" queues it for this process to run on the configured historian model, "broca" routes it to the Broca module. When unset the harness decides: OpenCode 1 and OpenCode 2 use "host", Claude Code (through the Thalamus gateway, which has no host to run a completion) uses "broca". User-level config only — it decides whose provider account pays for the call.'),
5550
+ host_runner: object({
5551
+ enabled: boolean2().optional().describe("Whether this process answers historian runs queued for a claimant (default true). Setting it to false stops the pull loop without changing historian.runner, so an operator can take one machine out of the lane and leave the queued runs for another claimant or for the runner setting to be changed deliberately.")
5552
+ }).optional().describe("Controls for this process's historian pull loop, which answers runs the Rust module queues for the host runner (`historian.runner: \"host\"`, or unset on OpenCode 1 and OpenCode 2). User-level config only — it decides whether this machine's provider account is spent on folds."),
5545
5553
  two_pass: boolean2().default(false).describe("Run a second editor pass over historian output to clean low-signal U: lines and cross-compartment duplicates. Adds ~1 extra API call and ~1.3x cost per historian run. Useful for models without extended thinking support. (default: false)"),
5546
5554
  disallowed_tools: array(_enum(["*", "read", "aft_outline", "aft_zoom", "aft_search"])).default([]).describe(`OpenCode only. Tools to REMOVE from the historian's default allow-list [read, aft_outline, aft_zoom, aft_search]. Applies to both historian and historian-editor agents. Use ["*"] to strip all tool definitions from the model request — this prevents weak instruction-following models (e.g. mistral-small-latest) from entering tool-calling loops. Individual tool names remove just that tool. Note: a user-supplied historian.permission override can re-allow a tool that disallowed_tools removed — disallowed_tools sets the baseline, permission overrides take precedence. (default: [])`)
5547
5555
  }).optional();
@@ -5555,7 +5563,7 @@ function expandConfigPath(value) {
5555
5563
  return trimmed;
5556
5564
  }
5557
5565
  var BaseEmbeddingConfigSchema = object({
5558
- provider: _enum(["local", "openai-compatible", "off", "synapse"]).default("local").describe("Embedding provider. 'local' uses Xenova/all-MiniLM-L6-v2, 'openai-compatible' requires endpoint and model, 'synapse' uses the certified local Synapse lane with an explicit fallback provider, and 'off' disables embeddings."),
5566
+ provider: _enum(["local", "openai-compatible", "off", "synapse"]).default("local").describe("Embedding provider. 'local' uses Xenova/all-MiniLM-L6-v2, 'openai-compatible' requires endpoint and model, 'synapse' uses the certified local Synapse lane with an explicit fallback provider, and 'off' disables embeddings. Session history is embedded for semantic ctx_search whenever the provider is not 'off', regardless of memory.enabled; memories are embedded only while memory.enabled is true."),
5559
5567
  fallback_provider: EmbeddingFallbackProviderSchema.optional().describe("Fallback provider for the Synapse lane. Required when provider is 'synapse'; local, openai-compatible, and off are valid."),
5560
5568
  model: string().optional().describe("Embedding model name. Required for openai-compatible, ignored for local."),
5561
5569
  endpoint: string().optional().describe("API endpoint URL. Required when provider is openai-compatible."),
@@ -5736,7 +5744,7 @@ var MagicContextConfigSchema = object({
5736
5744
  min_chars: number2().min(100).max(1e4).default(500).describe("Text parts shorter than this (characters) stay untouched. Min 100, max 10000. Default: 500.")
5737
5745
  }).default({ enabled: false, min_chars: 500 }).describe("Age-tier caveman compression for long user/assistant text parts. Active for primary sessions when enabled; never for subagents. Oldest 20% of eligible tags (outside protected tail) go to ultra, next 20% to full, next 20% to lite, newest 40% untouched. Graduated from experimental.caveman_text_compression; opt-in, default off (lossy)."),
5738
5746
  memory: object({
5739
- enabled: boolean2().default(true).describe("Enable cross-session memory (default: true)"),
5747
+ enabled: boolean2().default(true).describe("Enable cross-session memory (default: true). Does not affect history embedding or semantic ctx_search over session history; set embedding.provider to 'off' to stop all embedding."),
5740
5748
  injection_budget_tokens: number2().min(500).max(20000).default(4000).describe("Token budget for memory injection on session start (min: 500, max: 20000, default: 4000)"),
5741
5749
  auto_promote: boolean2().default(true).describe("Automatically promote eligible session facts into memory (default: true)"),
5742
5750
  retrieval_count_promotion_threshold: number2().min(1).default(3).describe("retrieval_count threshold for promoting memory to permanent status (min: 1, default: 3)"),
@@ -6028,7 +6036,7 @@ function transitionSessionHygieneUnits(db, sessionId, bustPermitted, calibration
6028
6036
  hygieneUnitsVersion: HYGIENE_PROVIDER_UNITS_VERSION
6029
6037
  });
6030
6038
  return HYGIENE_PROVIDER_UNITS_VERSION;
6031
- })();
6039
+ }).immediate();
6032
6040
  }
6033
6041
 
6034
6042
  // src/features/magic-context/protection-window.ts
@@ -6934,7 +6942,7 @@ function markProtectedTailPolicyV3Seeded(db, sessionId, priorBoundaryOrdinal) {
6934
6942
  WHERE session_id = ? AND protected_tail_policy_version < 3`).run(Math.max(1, Math.floor(priorBoundaryOrdinal)), sessionId);
6935
6943
  seeded = true;
6936
6944
  }
6937
- })();
6945
+ }).immediate();
6938
6946
  return { ...loadProtectedTailMeta(db, sessionId), seeded };
6939
6947
  }
6940
6948
  function recordProtectedTailPublicationFloor(db, sessionId, floorOrdinal) {
@@ -6944,7 +6952,7 @@ function recordProtectedTailPublicationFloor(db, sessionId, floorOrdinal) {
6944
6952
  SET prior_boundary_ordinal = MAX(COALESCE(prior_boundary_ordinal, 1), ?),
6945
6953
  recovery_no_eligible_head_count = 0
6946
6954
  WHERE session_id = ?`).run(Math.max(1, Math.floor(floorOrdinal)), sessionId);
6947
- })();
6955
+ }).immediate();
6948
6956
  }
6949
6957
  function recordProtectedTailNoEligibleHead(db, sessionId) {
6950
6958
  db.transaction(() => {
@@ -6952,14 +6960,14 @@ function recordProtectedTailNoEligibleHead(db, sessionId) {
6952
6960
  db.prepare(`UPDATE session_meta
6953
6961
  SET recovery_no_eligible_head_count = COALESCE(recovery_no_eligible_head_count, 0) + 1
6954
6962
  WHERE session_id = ?`).run(sessionId);
6955
- })();
6963
+ }).immediate();
6956
6964
  return loadProtectedTailMeta(db, sessionId).recoveryNoEligibleHeadCount;
6957
6965
  }
6958
6966
  function resetProtectedTailNoEligibleHead(db, sessionId) {
6959
6967
  db.transaction(() => {
6960
6968
  ensureSessionMetaRow(db, sessionId);
6961
6969
  db.prepare("UPDATE session_meta SET recovery_no_eligible_head_count = 0 WHERE session_id = ?").run(sessionId);
6962
- })();
6970
+ }).immediate();
6963
6971
  }
6964
6972
  var DRAIN_WINDOW_MS = 10 * 60 * 1000;
6965
6973
  var WRAPUP_IN_PROGRESS_TTL_MS = 5 * 60 * 1000;
@@ -7249,27 +7257,27 @@ function reserveProtectedTailDrainTokens(args) {
7249
7257
  reservation: { sessionId: args.sessionId, runId: args.runId, tokens: reserved },
7250
7258
  budgetState: budgetState(meta.protectedTailDrainTokens + reserved)
7251
7259
  };
7252
- })();
7260
+ }).immediate();
7253
7261
  return result;
7254
7262
  }
7255
7263
  function clearEmergencyDrainLatch(db, sessionId) {
7256
7264
  db.transaction(() => {
7257
7265
  ensureSessionMetaRow(db, sessionId);
7258
7266
  db.prepare("UPDATE session_meta SET emergency_drain_active = 0 WHERE session_id = ?").run(sessionId);
7259
- })();
7267
+ }).immediate();
7260
7268
  }
7261
7269
  function recordHistorianDrainFailure(db, sessionId, now) {
7262
7270
  const ts = now ?? Date.now();
7263
7271
  db.transaction(() => {
7264
7272
  ensureSessionMetaRow(db, sessionId);
7265
7273
  db.prepare("UPDATE session_meta SET historian_drain_failure_at = ? WHERE session_id = ?").run(ts, sessionId);
7266
- })();
7274
+ }).immediate();
7267
7275
  }
7268
7276
  function clearHistorianDrainFailure(db, sessionId) {
7269
7277
  db.transaction(() => {
7270
7278
  ensureSessionMetaRow(db, sessionId);
7271
7279
  db.prepare("UPDATE session_meta SET historian_drain_failure_at = 0 WHERE session_id = ?").run(sessionId);
7272
- })();
7280
+ }).immediate();
7273
7281
  }
7274
7282
  function rollbackProtectedTailDrainReservation(db, reservation) {
7275
7283
  if (!reservation || reservation.tokens <= 0)
@@ -7279,7 +7287,7 @@ function rollbackProtectedTailDrainReservation(db, reservation) {
7279
7287
  db.prepare(`UPDATE session_meta
7280
7288
  SET protected_tail_drain_tokens = MAX(0, COALESCE(protected_tail_drain_tokens, 0) - ?)
7281
7289
  WHERE session_id = ?`).run(reservation.tokens, reservation.sessionId);
7282
- })();
7290
+ }).immediate();
7283
7291
  }
7284
7292
  function getPersistedReasoningWatermark(db, sessionId) {
7285
7293
  const result = db.prepare("SELECT cleared_reasoning_through_tag FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7303,13 +7311,13 @@ function setEmergencyDropSample(db, sessionId, inputSample) {
7303
7311
  db.transaction(() => {
7304
7312
  ensureSessionMetaRow(db, sessionId);
7305
7313
  db.prepare("UPDATE session_meta SET last_emergency_input_sample = ? WHERE session_id = ?").run(Math.max(0, Math.round(inputSample)), sessionId);
7306
- })();
7314
+ }).immediate();
7307
7315
  }
7308
7316
  function clearEmergencyDropSample(db, sessionId) {
7309
7317
  db.transaction(() => {
7310
7318
  ensureSessionMetaRow(db, sessionId);
7311
7319
  db.prepare("UPDATE session_meta SET last_emergency_input_sample = 0 WHERE session_id = ?").run(sessionId);
7312
- })();
7320
+ }).immediate();
7313
7321
  }
7314
7322
  var EMPTY_CHANNEL1_NUDGE_STATE = { level: "", ordinal: 0 };
7315
7323
  function isLastNudgeUndroppedRow(row) {
@@ -7366,7 +7374,7 @@ function setLastNudgeUndropped(db, sessionId, value) {
7366
7374
  db.transaction(() => {
7367
7375
  ensureSessionMetaRow(db, sessionId);
7368
7376
  db.prepare("UPDATE session_meta SET last_nudge_undropped = ? WHERE session_id = ?").run(Math.max(0, Math.round(value)), sessionId);
7369
- })();
7377
+ }).immediate();
7370
7378
  }
7371
7379
  function getChannel1NudgeState(db, sessionId) {
7372
7380
  const result = db.prepare("SELECT last_nudge_level FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7376,7 +7384,7 @@ function setChannel1NudgeState(db, sessionId, value) {
7376
7384
  db.transaction(() => {
7377
7385
  ensureSessionMetaRow(db, sessionId);
7378
7386
  db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(value), sessionId);
7379
- })();
7387
+ }).immediate();
7380
7388
  }
7381
7389
  function markChannel1PostReduceGracePending(db, sessionId) {
7382
7390
  return db.transaction(() => {
@@ -7390,7 +7398,7 @@ function markChannel1PostReduceGracePending(db, sessionId) {
7390
7398
  };
7391
7399
  db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
7392
7400
  return next;
7393
- })();
7401
+ }).immediate();
7394
7402
  }
7395
7403
  function captureChannel1PostReduceGraceBaseline(db, sessionId, measuredUndropped) {
7396
7404
  return db.transaction(() => {
@@ -7407,7 +7415,7 @@ function captureChannel1PostReduceGraceBaseline(db, sessionId, measuredUndropped
7407
7415
  };
7408
7416
  db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
7409
7417
  return next;
7410
- })();
7418
+ }).immediate();
7411
7419
  }
7412
7420
  function isChannel2StateRow(row) {
7413
7421
  return typeof row === "object" && row !== null && typeof row.channel2_nudge_state === "string";
@@ -7434,7 +7442,7 @@ function setChannel2NudgeState(db, sessionId, state) {
7434
7442
  ensureSessionMetaRow(db, sessionId);
7435
7443
  const claimedAt = state === "claimed" ? Date.now() : 0;
7436
7444
  db.prepare("UPDATE session_meta SET channel2_nudge_state = ?, channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = '' WHERE session_id = ?").run(state, claimedAt, sessionId);
7437
- })();
7445
+ }).immediate();
7438
7446
  }
7439
7447
  function casChannel2NudgeState(db, sessionId, from, to) {
7440
7448
  let changed = false;
@@ -7443,7 +7451,7 @@ function casChannel2NudgeState(db, sessionId, from, to) {
7443
7451
  const claimedAt = to === "claimed" ? Date.now() : 0;
7444
7452
  const result = db.prepare("UPDATE session_meta SET channel2_nudge_state = ?, channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = '' WHERE session_id = ? AND channel2_nudge_state = ?").run(to, claimedAt, sessionId, from);
7445
7453
  changed = (result.changes ?? 0) > 0;
7446
- })();
7454
+ }).immediate();
7447
7455
  return changed;
7448
7456
  }
7449
7457
  function claimChannel2NudgeState(db, sessionId, claimToken) {
@@ -7452,7 +7460,7 @@ function claimChannel2NudgeState(db, sessionId, claimToken) {
7452
7460
  ensureSessionMetaRow(db, sessionId);
7453
7461
  const result = db.prepare("UPDATE session_meta SET channel2_nudge_state = 'claimed', channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = ? WHERE session_id = ? AND channel2_nudge_state = 'pending'").run(Date.now(), claimToken, sessionId);
7454
7462
  changed = (result.changes ?? 0) > 0;
7455
- })();
7463
+ }).immediate();
7456
7464
  return changed;
7457
7465
  }
7458
7466
  function casChannel2NudgeClaim(db, sessionId, to, claimToken) {
@@ -7463,7 +7471,7 @@ function casChannel2NudgeClaim(db, sessionId, to, claimToken) {
7463
7471
  const nextClaimToken = to === "claimed" ? claimToken : "";
7464
7472
  const result = db.prepare("UPDATE session_meta SET channel2_nudge_state = ?, channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = ? WHERE session_id = ? AND channel2_nudge_state = 'claimed' AND channel2_nudge_claim_token = ?").run(to, claimedAt, nextClaimToken, sessionId, claimToken);
7465
7473
  changed = (result.changes ?? 0) > 0;
7466
- })();
7474
+ }).immediate();
7467
7475
  return changed;
7468
7476
  }
7469
7477
  function getPersistedNoteNudge(db, sessionId) {
@@ -7482,13 +7490,13 @@ function setPersistedNoteNudgeTrigger(db, sessionId, triggerMessageId = "") {
7482
7490
  db.transaction(() => {
7483
7491
  ensureSessionMetaRow(db, sessionId);
7484
7492
  db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 1, note_nudge_trigger_message_id = ? WHERE session_id = ?").run(triggerMessageId, sessionId);
7485
- })();
7493
+ }).immediate();
7486
7494
  }
7487
7495
  function setPersistedNoteNudgeTriggerMessageId(db, sessionId, triggerMessageId) {
7488
7496
  db.transaction(() => {
7489
7497
  ensureSessionMetaRow(db, sessionId);
7490
7498
  db.prepare("UPDATE session_meta SET note_nudge_trigger_message_id = ? WHERE session_id = ?").run(triggerMessageId, sessionId);
7491
- })();
7499
+ }).immediate();
7492
7500
  }
7493
7501
  function getNoteNudgeAnchors(db, sessionId) {
7494
7502
  const row = db.prepare("SELECT note_nudge_anchors FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7647,7 +7655,7 @@ function setPersistedTodoSyntheticAnchor(db, sessionId, callId, messageId, state
7647
7655
  db.transaction(() => {
7648
7656
  ensureSessionMetaRow(db, sessionId);
7649
7657
  db.prepare("UPDATE session_meta SET todo_synthetic_call_id = ?, todo_synthetic_anchor_message_id = ?, todo_synthetic_state_json = ? WHERE session_id = ?").run(callId, messageId, stateJson, sessionId);
7650
- })();
7658
+ }).immediate();
7651
7659
  }
7652
7660
  function clearPersistedTodoSyntheticAnchor(db, sessionId) {
7653
7661
  db.prepare("UPDATE session_meta SET todo_synthetic_call_id = '', todo_synthetic_anchor_message_id = '', todo_synthetic_state_json = '' WHERE session_id = ?").run(sessionId);
@@ -7667,7 +7675,7 @@ function setNoteLastReadAt(db, sessionId, at = Date.now()) {
7667
7675
  db.transaction(() => {
7668
7676
  ensureSessionMetaRow(db, sessionId);
7669
7677
  db.prepare("UPDATE session_meta SET note_last_read_at = ? WHERE session_id = ?").run(at, sessionId);
7670
- })();
7678
+ }).immediate();
7671
7679
  }
7672
7680
  function getHistorianFailureState(db, sessionId) {
7673
7681
  const result = db.prepare("SELECT historian_failure_count, historian_last_error, historian_last_failure_at FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7682,14 +7690,14 @@ function incrementHistorianFailure(db, sessionId, error) {
7682
7690
  db.prepare("UPDATE session_meta SET historian_failure_count = ?, historian_last_error = ?, historian_last_failure_at = ? WHERE session_id = ?").run(nextCount, error, Date.now(), sessionId);
7683
7691
  const reason = error.replace(/\s+/g, " ").trim().slice(0, 300);
7684
7692
  sessionLog(sessionId, `historian failure recorded: count=${nextCount} reason="${reason}"`);
7685
- })();
7693
+ }).immediate();
7686
7694
  return nextCount;
7687
7695
  }
7688
7696
  function clearHistorianFailureState(db, sessionId) {
7689
7697
  db.transaction(() => {
7690
7698
  ensureSessionMetaRow(db, sessionId);
7691
7699
  db.prepare("UPDATE session_meta SET historian_failure_count = 0, historian_last_error = NULL, historian_last_failure_at = NULL WHERE session_id = ?").run(sessionId);
7692
- })();
7700
+ }).immediate();
7693
7701
  }
7694
7702
  function normalizeDetectedLimitModelKey(modelKey) {
7695
7703
  return typeof modelKey === "string" && modelKey.length > 0 ? piModelRefToCanonical(modelKey) : null;
@@ -7767,7 +7775,7 @@ function recordOverflowDetected(db, sessionId, reportedLimit, modelKey, origin =
7767
7775
  const percentage = effectiveLimit > 0 ? reportedInputTokens / effectiveLimit * 100 : 100;
7768
7776
  db.prepare("UPDATE session_meta SET last_input_tokens = ?, last_context_percentage = MAX(last_context_percentage, ?), last_response_time = ? WHERE session_id = ?").run(reportedInputTokens, percentage, Date.now(), sessionId);
7769
7777
  }
7770
- })();
7778
+ }).immediate();
7771
7779
  }
7772
7780
  function recordDetectedContextLimit(db, sessionId, reportedLimit, modelKey, provenance = "unknown") {
7773
7781
  if (!(reportedLimit > 0))
@@ -7775,7 +7783,7 @@ function recordDetectedContextLimit(db, sessionId, reportedLimit, modelKey, prov
7775
7783
  db.transaction(() => {
7776
7784
  ensureSessionMetaRow(db, sessionId);
7777
7785
  db.prepare("UPDATE session_meta SET detected_context_limit = ?, detected_context_limit_model_key = ?, detected_context_limit_provenance = ?, observed_safe_input_tokens = 0, cache_alert_sent = 0 WHERE session_id = ?").run(reportedLimit, normalizeDetectedLimitModelKey(modelKey), normalizeContextLimitProvenance(provenance), sessionId);
7778
- })();
7786
+ }).immediate();
7779
7787
  }
7780
7788
  function clearEmergencyRecovery(db, sessionId) {
7781
7789
  db.transaction(() => {
@@ -7785,7 +7793,7 @@ function clearEmergencyRecovery(db, sessionId) {
7785
7793
  } catch {
7786
7794
  db.prepare("UPDATE session_meta SET needs_emergency_recovery = 0, emergency_recovery_origin = '' WHERE session_id = ?").run(sessionId);
7787
7795
  }
7788
- })();
7796
+ }).immediate();
7789
7797
  emergencyRecoveryArmedSessions.delete(sessionId);
7790
7798
  emergencyRecoveryArmedAtBySession.delete(sessionId);
7791
7799
  providerOverflowReconfirmedSessions.delete(sessionId);
@@ -7795,7 +7803,7 @@ function clearDetectedContextLimit(db, sessionId) {
7795
7803
  db.transaction(() => {
7796
7804
  ensureSessionMetaRow(db, sessionId);
7797
7805
  db.prepare("UPDATE session_meta SET detected_context_limit = 0, detected_context_limit_model_key = NULL, detected_context_limit_provenance = 'unknown' WHERE session_id = ?").run(sessionId);
7798
- })();
7806
+ }).immediate();
7799
7807
  }
7800
7808
  function parsePersistedCompactionMarkerState(raw, storedTargetEndMessageId) {
7801
7809
  if (!raw || raw.length === 0)
@@ -7822,7 +7830,7 @@ function setPersistedCompactionMarkerState(db, sessionId, state) {
7822
7830
  const previous = state === null ? getPersistedCompactionMarkerState(db, sessionId) ?? getDeferredClearedCompactionMarkerState(db, sessionId) : null;
7823
7831
  const json = state ? JSON.stringify(state) : previous ? JSON.stringify({ deferredClear: previous }) : "";
7824
7832
  db.prepare("UPDATE session_meta SET compaction_marker_state = ?, compaction_marker_target_end_message_id = ? WHERE session_id = ?").run(json, state?.targetEndMessageId ?? null, sessionId);
7825
- })();
7833
+ }).immediate();
7826
7834
  }
7827
7835
  function getDeferredClearedCompactionMarkerState(db, sessionId) {
7828
7836
  const row = db.prepare("SELECT compaction_marker_state FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7927,7 +7935,7 @@ function removeStrippedPlaceholderId(db, sessionId, messageId) {
7927
7935
  applyStrippedPlaceholderDelta(db, sessionId, { remove: [messageId] });
7928
7936
  return true;
7929
7937
  }
7930
- var NEWEST_REASONING_BEARING_ASSISTANT = "newest_reasoning_bearing_assistant";
7938
+ var THINKING_BINDING_RECOVERY_ALL_ASSISTANTS = "all_reasoning_bearing_assistants";
7931
7939
  var THINKING_BINDING_RECOVERY_FROZEN_PREFIX = "binding_mismatch:";
7932
7940
  function thinkingBindingRecoveryFrozenId(messageId) {
7933
7941
  return `${THINKING_BINDING_RECOVERY_FROZEN_PREFIX}${messageId}`;
@@ -7937,14 +7945,9 @@ function getThinkingBindingRecoveryTarget(db, sessionId) {
7937
7945
  const target = row?.thinking_binding_recovery_target;
7938
7946
  return typeof target === "string" && target.length > 0 ? target : null;
7939
7947
  }
7940
- function armThinkingBindingRecovery(db, sessionId, messageId) {
7948
+ function armThinkingBindingRecovery(db, sessionId) {
7941
7949
  ensureSessionMetaRow(db, sessionId);
7942
- const target = typeof messageId === "string" && messageId.length > 0 ? messageId : NEWEST_REASONING_BEARING_ASSISTANT;
7943
- if (target === NEWEST_REASONING_BEARING_ASSISTANT) {
7944
- db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ? AND COALESCE(thinking_binding_recovery_target, '') = ''").run(target, sessionId);
7945
- return;
7946
- }
7947
- db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(target, sessionId);
7950
+ db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(THINKING_BINDING_RECOVERY_ALL_ASSISTANTS, sessionId);
7948
7951
  }
7949
7952
  function clearThinkingBindingRecoveryIf(db, sessionId, expectedTarget) {
7950
7953
  const result = db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, expectedTarget);
@@ -8333,6 +8336,11 @@ var USER_FACING_FAILURES = {
8333
8336
  sentence: "Some finished background sessions could not be removed from this host.",
8334
8337
  action: "They are removed automatically the next time Magic Context runs inside a registered OpenCode service."
8335
8338
  },
8339
+ historian_saved_history_misaligned: {
8340
+ code: "MC-H03",
8341
+ sentence: "History compression is paused because this session's saved summaries no longer line up with its messages.",
8342
+ action: "Run /ctx-recomp to rebuild them."
8343
+ },
8336
8344
  recomp_unavailable: {
8337
8345
  code: "MC-R01",
8338
8346
  sentence: "History compression could not be rebuilt.",
@@ -8348,6 +8356,11 @@ var USER_FACING_FAILURES = {
8348
8356
  sentence: "Memory maintenance could not reach its model.",
8349
8357
  action: "Check the model connection, then run /ctx-dream again."
8350
8358
  },
8359
+ dream_step_limit: {
8360
+ code: "MC-D10",
8361
+ sentence: "Memory maintenance stopped at its hidden agent step limit.",
8362
+ action: "This task needs less work per run; changing the model connection will not help."
8363
+ },
8351
8364
  dream_empty_completion: {
8352
8365
  code: "MC-D03",
8353
8366
  sentence: "Memory maintenance received no usable response.",
@@ -8503,11 +8516,21 @@ var USER_FACING_FAILURES = {
8503
8516
  sentence: "History compression is paused while the engine syncs.",
8504
8517
  action: "Retry in a moment."
8505
8518
  },
8519
+ history_compression_needs_message: {
8520
+ code: "MC-C12",
8521
+ sentence: "History compression has not seen this session since Magic Context reconnected.",
8522
+ action: "Send a message in this session first, then run /ctx-wrapup again."
8523
+ },
8506
8524
  context_service_unavailable: {
8507
8525
  code: "MC-C10",
8508
8526
  sentence: "Magic Context is temporarily unavailable.",
8509
8527
  action: "Retry in a moment."
8510
8528
  },
8529
+ store_ahead_of_binary: {
8530
+ code: "MC-C13",
8531
+ sentence: "Magic Context refused to start: its store (store.db) was migrated by a newer ck-mc build than the one running.",
8532
+ action: "Update ck-mc, or roll back by restoring ck-mc together with context.db and store.db from the same backup."
8533
+ },
8511
8534
  compaction_marker_missing: {
8512
8535
  code: "MC-C11",
8513
8536
  sentence: "The history boundary marker is missing from the OpenCode store, so requests carry the full session.",
@@ -8523,11 +8546,6 @@ var USER_FACING_FAILURES = {
8523
8546
  sentence: "Memory authority is inconsistent between the host and module.",
8524
8547
  action: "Run `ck doctor drain-authority` before changing Rust mode."
8525
8548
  },
8526
- rust_mode_unsupported: {
8527
- code: "MC-S06",
8528
- sentence: "Experimental Rust transform mode is not available on this OpenCode host.",
8529
- action: 'Magic Context is running its TypeScript mode instead; set `transform_mode` to "ts" to stop requesting Rust.'
8530
- },
8531
8549
  dreamer_task_failing: {
8532
8550
  code: "MC-S05",
8533
8551
  sentence: "A background maintenance task keeps failing on its schedule.",
@@ -8562,6 +8580,7 @@ function capabilityRefusalCode(capability) {
8562
8580
  var DREAM_FAILURE_KEYS = {
8563
8581
  provider_timeout: "dream_provider_timeout",
8564
8582
  provider_error: "dream_provider_error",
8583
+ step_limit: "dream_step_limit",
8565
8584
  empty_completion: "dream_empty_completion",
8566
8585
  no_models: "dream_no_models",
8567
8586
  child_aborted: "dream_child_aborted",
@@ -8607,6 +8626,16 @@ function piHarnessKindFromExecutable(value) {
8607
8626
  }
8608
8627
 
8609
8628
  // src/shared/rpc-utils.ts
8629
+ var ownRpcServerInstanceIds = new Set;
8630
+ function registerOwnRpcServerInstance(instanceId) {
8631
+ ownRpcServerInstanceIds.add(instanceId);
8632
+ return () => {
8633
+ ownRpcServerInstanceIds.delete(instanceId);
8634
+ };
8635
+ }
8636
+ function isOwnRpcServerRecord(record) {
8637
+ return record.pid === process.pid && record.instance_id !== undefined && ownRpcServerInstanceIds.has(record.instance_id);
8638
+ }
8610
8639
  function projectHash(directory) {
8611
8640
  const normalized = directory.replace(/\/+$/, "");
8612
8641
  return createHash("sha256").update(normalized).digest("hex").slice(0, 16);
@@ -9404,7 +9433,7 @@ function updateSessionMeta(db, sessionId, updates) {
9404
9433
  db.transaction(() => {
9405
9434
  ensureSessionMetaRow(db, sessionId);
9406
9435
  db.prepare(`UPDATE session_meta SET ${setClauses.join(", ")} WHERE session_id = ?`).run(...values, sessionId);
9407
- })();
9436
+ }).immediate();
9408
9437
  }
9409
9438
  function advanceToolReclaimWatermark(db, sessionId, maxTagNumber) {
9410
9439
  if (maxTagNumber <= 0)
@@ -9412,7 +9441,7 @@ function advanceToolReclaimWatermark(db, sessionId, maxTagNumber) {
9412
9441
  db.transaction(() => {
9413
9442
  ensureSessionMetaRow(db, sessionId);
9414
9443
  db.prepare("UPDATE session_meta SET tool_reclaim_watermark = MAX(COALESCE(tool_reclaim_watermark, 0), ?) WHERE session_id = ?").run(maxTagNumber, sessionId);
9415
- })();
9444
+ }).immediate();
9416
9445
  }
9417
9446
  function rustCleanupHarness() {
9418
9447
  return `${getHarness()}:rust`;
@@ -9480,7 +9509,7 @@ function clearSession(db, sessionId, rustModuleCleanupAcknowledged = false) {
9480
9509
  deleteSessionScopedRows(db, [sessionId], undefined, {
9481
9510
  rustModuleCleanupAcknowledged
9482
9511
  });
9483
- })();
9512
+ }).immediate();
9484
9513
  logSlowWriteTransaction("clear-session", transactionStartedAt);
9485
9514
  }
9486
9515
  // src/features/magic-context/compartment-chunk-embedding.ts
@@ -11882,7 +11911,7 @@ function backfillMessageFtsRowidMapBatch(db, batchSize = MESSAGE_FTS_ROWID_MAP_B
11882
11911
  watermarkRowid,
11883
11912
  completed
11884
11913
  };
11885
- })();
11914
+ }).immediate();
11886
11915
  logSlowWriteTransaction("message_fts_rowid_backfill", transactionStartedAt);
11887
11916
  return progress;
11888
11917
  }
@@ -12554,7 +12583,7 @@ function replaceCompartmentChunkEmbeddings(db, rows) {
12554
12583
  for (const row of rows) {
12555
12584
  insert.run(row.compartmentId, row.sessionId, row.projectPath, getHarness(), row.window.windowIndex, row.window.startOrdinal, row.window.endOrdinal, row.window.chunkHash, row.modelId, row.vector.length, vectorBlob(row.vector), row.createdAt ?? now);
12556
12585
  }
12557
- })();
12586
+ }).immediate();
12558
12587
  invalidateDecodedSearchPools(db, ([sessionId, projectPath, cachedModelId]) => sessionId === rows[0].sessionId && projectPath === rows[0].projectPath && cachedModelId === modelId);
12559
12588
  }
12560
12589
  function loadCompartmentChunkEmbeddingsForSearch(db, sessionId, projectPath, modelId, dateRange = null) {
@@ -12635,7 +12664,7 @@ function renumberOneBasedChunkWindows(db, candidate, projectPath, modelId, windo
12635
12664
  throw new Error(`Failed to renumber compartment ${candidate.id} window ${window.windowIndex + 1}`);
12636
12665
  }
12637
12666
  }
12638
- })();
12667
+ }).immediate();
12639
12668
  invalidateDecodedSearchPools(db, ([sessionId, cachedProjectPath, cachedModelId]) => sessionId === candidate.sessionId && cachedProjectPath === projectPath && cachedModelId === modelId);
12640
12669
  }
12641
12670
  function classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens) {
@@ -12919,7 +12948,7 @@ function upsertCommits(db, projectPath, commits) {
12919
12948
  }
12920
12949
  }
12921
12950
  }
12922
- })();
12951
+ }).immediate();
12923
12952
  return { inserted, updated };
12924
12953
  }
12925
12954
  function getCommitCount(db, projectPath) {
@@ -14891,7 +14920,7 @@ function recordSessionProjectIdentity(db, sessionId, projectPath) {
14891
14920
  db.transaction(() => {
14892
14921
  getUpsertSessionProjectStatement(db).run(sessionId, harness, projectPath, now);
14893
14922
  getRepairSessionChunkProjectStatement(db).run(projectPath, sessionId, harness, projectPath, SESSION_CHUNK_REPAIR_BATCH_SIZE);
14894
- })();
14923
+ }).immediate();
14895
14924
  }
14896
14925
  function repairMisScopedCompartmentChunkEmbeddingsForProject(db, projectPath) {
14897
14926
  if (!projectPath)
@@ -15337,7 +15366,8 @@ function sameFeatures(a, b) {
15337
15366
  }
15338
15367
  function snapshotFor(registration) {
15339
15368
  const providerIsOn = registration.providerIdentity !== OFF_PROVIDER_IDENTITY;
15340
- const enabled = !registration.observationMode && providerIsOn && registration.features.memoryEnabled;
15369
+ const historyEnabled = !registration.observationMode && providerIsOn;
15370
+ const enabled = historyEnabled && registration.features.memoryEnabled;
15341
15371
  const gitCommitEnabled = !registration.observationMode && providerIsOn && registration.features.gitCommitEnabled;
15342
15372
  const configuredModel = "model" in registration.config && typeof registration.config.model === "string" ? registration.config.model.trim() : "";
15343
15373
  const synapseDescriptor = !registration.observationMode && registration.config.provider === "synapse" ? synapseDescriptorFromConfig(registration.config) : undefined;
@@ -15349,6 +15379,7 @@ function snapshotFor(registration) {
15349
15379
  generation: registration.generation,
15350
15380
  features: { ...registration.features },
15351
15381
  enabled,
15382
+ historyEnabled,
15352
15383
  gitCommitEnabled,
15353
15384
  modelId: registration.observationMode || !providerIsOn ? "off" : registration.modelId,
15354
15385
  chunkModelId: registration.observationMode || !providerIsOn ? "off" : registration.chunkModelId,
@@ -15426,10 +15457,8 @@ function recordActiveEmbeddingIdentity(db, projectIdentity, currentProviderIdent
15426
15457
  if (features.gitCommitEnabled) {
15427
15458
  recordScopeActiveIdentity(db, projectIdentity, "commit", currentProviderIdentity, now);
15428
15459
  }
15429
- if (features.memoryEnabled) {
15430
- repairMisScopedCompartmentChunkEmbeddingsForProject(db, projectIdentity);
15431
- recordScopeActiveIdentity(db, projectIdentity, "chunk", currentChunkIdentity, now);
15432
- }
15460
+ repairMisScopedCompartmentChunkEmbeddingsForProject(db, projectIdentity);
15461
+ recordScopeActiveIdentity(db, projectIdentity, "chunk", currentChunkIdentity, now);
15433
15462
  db.exec("COMMIT");
15434
15463
  logSlowWriteTransaction("embedding_identity_record", transactionStartedAt);
15435
15464
  } catch (error) {
@@ -15548,7 +15577,7 @@ function sweepStaleEmbeddingIdentitiesForProject(db, projectIdentity, now = Date
15548
15577
  },
15549
15578
  {
15550
15579
  scope: "chunk",
15551
- enabled: snapshot.enabled && snapshot.chunkModelId !== "off",
15580
+ enabled: snapshot.historyEnabled && snapshot.chunkModelId !== "off",
15552
15581
  currentModelId: snapshot.chunkModelId
15553
15582
  }
15554
15583
  ];
@@ -15688,7 +15717,7 @@ function registerProjectShadowEmbedding(db, projectIdentity, config, sourceDirec
15688
15717
  recordScopeActiveIdentity(db, projectIdentity, "commit", registration.modelId, now);
15689
15718
  recordScopeActiveIdentity(db, projectIdentity, "chunk", registration.chunkModelId, now);
15690
15719
  persistShadowDescriptor(db, registration);
15691
- })();
15720
+ }).immediate();
15692
15721
  maybeArmShadowBackfill(db, projectIdentity, registration, options.manualBackfill === true);
15693
15722
  return {
15694
15723
  projectIdentity,
@@ -15698,6 +15727,7 @@ function registerProjectShadowEmbedding(db, projectIdentity, config, sourceDirec
15698
15727
  generation,
15699
15728
  features: { memoryEnabled: true, gitCommitEnabled: true },
15700
15729
  enabled: true,
15730
+ historyEnabled: true,
15701
15731
  gitCommitEnabled: true,
15702
15732
  modelId: registration.modelId,
15703
15733
  chunkModelId: registration.chunkModelId,
@@ -15906,6 +15936,8 @@ function maybeArmShadowBackfill(db, projectIdentity, shadow, manualBackfill = fa
15906
15936
  const stallKey = `${projectIdentity}:${scope}`;
15907
15937
  if (primaryModelId === "off" || shadowModelId === "off")
15908
15938
  continue;
15939
+ if (scope === "memory" && !primary.features.memoryEnabled)
15940
+ continue;
15909
15941
  const batch = shadowBackfillCandidateBatch(db, projectIdentity, scope, primaryModelId, shadow, SHADOW_MAX_ITEMS_PER_TICK);
15910
15942
  const persisted = getPersistedShadowBackfillState(db, projectIdentity, scope, shadowModelId);
15911
15943
  if (batch.ids.length === 0) {
@@ -16042,7 +16074,7 @@ async function processShadowQueueItem(item) {
16042
16074
  hashGuardRejected = true;
16043
16075
  }
16044
16076
  }
16045
- })();
16077
+ }).immediate();
16046
16078
  return {
16047
16079
  writes,
16048
16080
  ...writes === 0 ? {
@@ -16076,7 +16108,7 @@ async function processShadowQueueItem(item) {
16076
16108
  saveCommitEmbedding(db, row.sha, vector, registration.modelId);
16077
16109
  writes += 1;
16078
16110
  }
16079
- })();
16111
+ }).immediate();
16080
16112
  return {
16081
16113
  writes,
16082
16114
  ...writes === 0 ? { refusalReason: embedded.refusalReason ?? "provider_returned_no_vectors" } : {}
@@ -16398,13 +16430,17 @@ function getLoadUnembeddedMemoriesStatement(db) {
16398
16430
  return stmt;
16399
16431
  }
16400
16432
  async function embedUnembeddedMemoriesForProject(db, projectIdentity, batchSize = 10) {
16433
+ const outcome = await embedUnembeddedMemoriesForProjectOutcome(db, projectIdentity, batchSize);
16434
+ return outcome.kind === "embedded" ? outcome.count : 0;
16435
+ }
16436
+ async function embedUnembeddedMemoriesForProjectOutcome(db, projectIdentity, batchSize = 10) {
16401
16437
  const snapshot = getProjectEmbeddingSnapshot(projectIdentity);
16402
16438
  if (!snapshot?.enabled)
16403
- return 0;
16439
+ return { kind: "disabled" };
16404
16440
  const normalizedBatchSize = Math.max(1, Math.floor(batchSize));
16405
16441
  const memories = getLoadUnembeddedMemoriesStatement(db).all(snapshot.modelId, projectIdentity, normalizedBatchSize).filter(isUnembeddedMemoryRow);
16406
16442
  if (memories.length === 0)
16407
- return 0;
16443
+ return { kind: "done" };
16408
16444
  try {
16409
16445
  const result = await embedItemsForProject(projectIdentity, memories.map((memory) => ({
16410
16446
  id: `memory:${memory.id}`,
@@ -16412,7 +16448,7 @@ async function embedUnembeddedMemoriesForProject(db, projectIdentity, batchSize
16412
16448
  contentSha256: contentSha256(memory.content)
16413
16449
  })), undefined, db, projectIdentity);
16414
16450
  if (!result)
16415
- return 0;
16451
+ return { kind: "unavailable" };
16416
16452
  let embeddedCount = 0;
16417
16453
  db.transaction(() => {
16418
16454
  for (const memory of memories) {
@@ -16423,12 +16459,12 @@ async function embedUnembeddedMemoriesForProject(db, projectIdentity, batchSize
16423
16459
  embeddedCount += 1;
16424
16460
  }
16425
16461
  }
16426
- })();
16462
+ }).immediate();
16427
16463
  enqueueShadowEmbeddingItems(projectIdentity, "memory", memories.filter((memory) => result.vectors.has(`memory:${memory.id}`)).map((memory) => String(memory.id)));
16428
- return embeddedCount;
16464
+ return { kind: "embedded", count: embeddedCount };
16429
16465
  } catch (error) {
16430
16466
  log("[magic-context] failed to proactively embed missing memories:", error);
16431
- return 0;
16467
+ return { kind: "failed", error };
16432
16468
  }
16433
16469
  }
16434
16470
  async function embedCommitBatch(db, projectIdentity, batchSize) {
@@ -16454,7 +16490,7 @@ async function embedCommitBatch(db, projectIdentity, batchSize) {
16454
16490
  saveCommitEmbedding(db, commit.sha, embedding, result.modelId);
16455
16491
  embeddedCount += 1;
16456
16492
  }
16457
- })();
16493
+ }).immediate();
16458
16494
  enqueueShadowEmbeddingItems(projectIdentity, "commit", commits.filter((commit) => result.vectors.has(`commit:${commit.sha}`)).map((commit) => commit.sha));
16459
16495
  return embeddedCount;
16460
16496
  }
@@ -16605,7 +16641,7 @@ async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates
16605
16641
  }
16606
16642
  async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, options) {
16607
16643
  const snapshot = getProjectEmbeddingSnapshot(projectIdentity);
16608
- if (!snapshot?.enabled || snapshot.chunkModelId === "off") {
16644
+ if (!snapshot?.historyEnabled || snapshot.chunkModelId === "off") {
16609
16645
  return { status: "disabled", embedded: 0, total: 0 };
16610
16646
  }
16611
16647
  recordSessionProjectIdentity(db, sessionId, projectIdentity);
@@ -16709,7 +16745,7 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
16709
16745
  }
16710
16746
  function getEmbeddingCoverageStatus(db, projectIdentity, sessionId) {
16711
16747
  const snapshot = getProjectEmbeddingSnapshot(projectIdentity);
16712
- if (!snapshot?.enabled || snapshot.chunkModelId === "off") {
16748
+ if (!snapshot?.historyEnabled || snapshot.chunkModelId === "off") {
16713
16749
  return {
16714
16750
  enabled: false,
16715
16751
  model: snapshot?.model ?? "off",
@@ -16722,7 +16758,7 @@ function getEmbeddingCoverageStatus(db, projectIdentity, sessionId) {
16722
16758
  };
16723
16759
  }
16724
16760
  const session = countSessionCompartmentEmbedCoverage(db, projectIdentity, sessionId, snapshot.chunkModelId, getProjectEmbeddingMaxInputTokens(projectIdentity));
16725
- const memories = getMemoryEmbedCoverage(db, projectIdentity, snapshot.modelId);
16761
+ const memories = snapshot.enabled ? getMemoryEmbedCoverage(db, projectIdentity, snapshot.modelId) : { embedded: 0, total: 0, memoryEnabled: false };
16726
16762
  const gitEnabled = snapshot.gitCommitEnabled;
16727
16763
  const commits = gitEnabled ? {
16728
16764
  embedded: countEmbeddedCommits(db, projectIdentity, snapshot.modelId),
@@ -16745,6 +16781,8 @@ function getEmbeddingCoverageStatus(db, projectIdentity, sessionId) {
16745
16781
  async function embedAndStoreCompartmentChunks(db, sessionId, projectPath, compartments) {
16746
16782
  if (compartments.length === 0)
16747
16783
  return;
16784
+ if (getProjectChunkEmbeddingModelId(projectPath) === "off")
16785
+ return;
16748
16786
  const maxInputTokens = getProjectEmbeddingMaxInputTokens(projectPath);
16749
16787
  for (const compartment of compartments) {
16750
16788
  try {
@@ -16941,7 +16979,7 @@ function appendCompartments(db, sessionId, compartments) {
16941
16979
  const now = Date.now();
16942
16980
  db.transaction(() => {
16943
16981
  insertCompartmentRows(db, sessionId, compartments, now);
16944
- })();
16982
+ }).immediate();
16945
16983
  }
16946
16984
  function buildCompartmentBlock(compartments, facts, memoryBlock, dateRanges) {
16947
16985
  const lines = [];
@@ -16987,7 +17025,7 @@ function saveRecompStagingPass(db, sessionId, passNumber, compartments, facts) {
16987
17025
  for (const f of facts) {
16988
17026
  factStmt.run(sessionId, f.category, f.content, passNumber, now, getHarness());
16989
17027
  }
16990
- })();
17028
+ }).immediate();
16991
17029
  }
16992
17030
  function getRecompStaging(db, sessionId) {
16993
17031
  const compartmentRows = db.prepare("SELECT * FROM recomp_compartments WHERE session_id = ? ORDER BY sequence ASC").all(sessionId).filter(isRecompCompartmentRow);
@@ -17025,7 +17063,7 @@ function clearRecompStaging(db, sessionId) {
17025
17063
  try {
17026
17064
  db.prepare("UPDATE session_meta SET recomp_partial_range_start = 0, recomp_partial_range_end = 0 WHERE session_id = ?").run(sessionId);
17027
17065
  } catch {}
17028
- })();
17066
+ }).immediate();
17029
17067
  }
17030
17068
  function getRecompPartialRange(db, sessionId) {
17031
17069
  try {
@@ -17265,16 +17303,21 @@ function normalizeSourceVersion(version) {
17265
17303
  return `string:${version}`;
17266
17304
  return "null";
17267
17305
  }
17268
- function getMessageSourceSnapshot(message) {
17306
+ function toMessageIndexSource(message) {
17269
17307
  const content = getIndexableContent(message.role, message.parts);
17270
17308
  return {
17309
+ id: message.id,
17271
17310
  ordinal: message.ordinal,
17311
+ role: message.role,
17312
+ createdAt: message.createdAt,
17272
17313
  sourceVersion: normalizeSourceVersion(message.version),
17273
17314
  contentHash: createHash9("sha256").update(content).digest("hex"),
17274
- role: message.role,
17275
17315
  content
17276
17316
  };
17277
17317
  }
17318
+ function getMessageSourceSnapshot(message) {
17319
+ return toMessageIndexSource(message);
17320
+ }
17278
17321
  function getMessageIndexSourceIdentity(message) {
17279
17322
  const source = getMessageSourceSnapshot(message);
17280
17323
  return JSON.stringify([
@@ -17291,8 +17334,10 @@ function isMessageIndexSourceCurrent(db, sessionId, message) {
17291
17334
  return row?.message_ordinal === source.ordinal && row.source_version === source.sourceVersion && row.normalized_content_hash === source.contentHash && row.role === source.role;
17292
17335
  }
17293
17336
  function setMessageSource(db, sessionId, message, now) {
17294
- const source = getMessageSourceSnapshot(message);
17295
- getUpsertMessageSourceStatement(db).run(sessionId, message.id, source.ordinal, source.sourceVersion, source.contentHash, source.role, getHarness(), now);
17337
+ return writeMessageSource(db, sessionId, getMessageSourceSnapshot(message), now);
17338
+ }
17339
+ function writeMessageSource(db, sessionId, source, now) {
17340
+ getUpsertMessageSourceStatement(db).run(sessionId, source.id, source.ordinal, source.sourceVersion, source.contentHash, source.role, getHarness(), now);
17296
17341
  return source.content;
17297
17342
  }
17298
17343
  function getLastIndexedOrdinal(db, sessionId) {
@@ -17344,7 +17389,7 @@ function clearIndexedMessages(db, sessionId) {
17344
17389
  const transactionStartedAt = performance.now();
17345
17390
  db.transaction(() => {
17346
17391
  clearIndexedMessagesInTransaction(db, sessionId);
17347
- })();
17392
+ }).immediate();
17348
17393
  logSlowWriteTransaction("message_index_clear", transactionStartedAt);
17349
17394
  }
17350
17395
  function getIndexableContent(role, parts) {
@@ -17417,6 +17462,12 @@ function indexSingleMessage(db, sessionId, message) {
17417
17462
  }
17418
17463
  }
17419
17464
  function indexMessagesAfterOrdinal(db, sessionId, messages, _lastIndexedOrdinal, finalWatermark = messages.length) {
17465
+ return indexItemsAfterOrdinal(db, sessionId, messages, finalWatermark, toMessageIndexSource);
17466
+ }
17467
+ function indexSourcesAfterOrdinal(db, sessionId, sources, finalWatermark) {
17468
+ return indexItemsAfterOrdinal(db, sessionId, sources, finalWatermark, (source) => source);
17469
+ }
17470
+ function indexItemsAfterOrdinal(db, sessionId, items, finalWatermark, toSource) {
17420
17471
  const now = Date.now();
17421
17472
  let inserted = 0;
17422
17473
  const transactionStartedAt = performance.now();
@@ -17437,21 +17488,22 @@ function indexMessagesAfterOrdinal(db, sessionId, messages, _lastIndexedOrdinal,
17437
17488
  getDeleteFtsMapRangeStatement(db).run(sessionId, dirtyFloor, finalWatermark);
17438
17489
  getDeleteMessageSourceRangeStatement(db).run(sessionId, dirtyFloor, finalWatermark);
17439
17490
  }
17440
- const messagesByOrdinal = new Map;
17441
- for (const message of messages) {
17442
- if (message.ordinal > effectiveWatermark && message.ordinal <= finalWatermark) {
17443
- messagesByOrdinal.set(message.ordinal, message);
17491
+ const itemsByOrdinal = new Map;
17492
+ for (const item of items) {
17493
+ if (item.ordinal > effectiveWatermark && item.ordinal <= finalWatermark) {
17494
+ itemsByOrdinal.set(item.ordinal, item);
17444
17495
  }
17445
17496
  }
17446
17497
  let coveredWatermark = effectiveWatermark;
17447
- while (coveredWatermark < finalWatermark && messagesByOrdinal.has(coveredWatermark + 1)) {
17498
+ while (coveredWatermark < finalWatermark && itemsByOrdinal.has(coveredWatermark + 1)) {
17448
17499
  coveredWatermark += 1;
17449
17500
  }
17450
17501
  for (let ordinal = effectiveWatermark + 1;ordinal <= coveredWatermark; ordinal++) {
17451
- const message = messagesByOrdinal.get(ordinal);
17452
- if (!message)
17502
+ const item = itemsByOrdinal.get(ordinal);
17503
+ if (!item)
17453
17504
  continue;
17454
- const content = setMessageSource(db, sessionId, message, now);
17505
+ const message = toSource(item);
17506
+ const content = writeMessageSource(db, sessionId, message, now);
17455
17507
  if (content.length === 0 || message.role !== "user" && message.role !== "assistant" || isMessageAlreadyIndexed(db, sessionId, message.id)) {
17456
17508
  continue;
17457
17509
  }
@@ -17474,22 +17526,6 @@ function indexMessagesAfterOrdinal(db, sessionId, messages, _lastIndexedOrdinal,
17474
17526
  }
17475
17527
  return inserted;
17476
17528
  }
17477
- function ensureMessagesIndexed(db, sessionId, readMessages) {
17478
- const messages = readMessages(sessionId);
17479
- if (messages.length === 0) {
17480
- clearIndexedMessages(db, sessionId);
17481
- return;
17482
- }
17483
- let lastIndexedOrdinal = getLastIndexedOrdinal(db, sessionId);
17484
- if (lastIndexedOrdinal > messages.length) {
17485
- clearIndexedMessages(db, sessionId);
17486
- lastIndexedOrdinal = 0;
17487
- }
17488
- if (lastIndexedOrdinal >= messages.length && getDirtyIndexFloor(db, sessionId) === null) {
17489
- return;
17490
- }
17491
- indexMessagesAfterOrdinal(db, sessionId, messages, lastIndexedOrdinal, messages.length);
17492
- }
17493
17529
  function harnessSupportsOpenCodeOrphanSweep(harness) {
17494
17530
  return harness === "opencode" || harness === "opencode2";
17495
17531
  }
@@ -17606,6 +17642,7 @@ function emptyOutcome(status, generation, previousGeneration) {
17606
17642
  previousGeneration,
17607
17643
  compartmentsRebased: 0,
17608
17644
  compartmentsUnresolved: 0,
17645
+ compartmentsDerived: 0,
17609
17646
  compartmentsResolvedAgain: 0,
17610
17647
  recompCompartmentsRebased: 0,
17611
17648
  recompCompartmentsUnresolved: 0,
@@ -17659,6 +17696,12 @@ function readCoordinateRebaseNotice(db, sessionId) {
17659
17696
  if (record.generation !== "v1" && record.generation !== "v2")
17660
17697
  return null;
17661
17698
  const count = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
17699
+ const ranges = (value) => Array.isArray(value) ? value.flatMap((entry) => {
17700
+ if (!entry || typeof entry !== "object")
17701
+ return [];
17702
+ const { sequence, start, end } = entry;
17703
+ return typeof sequence === "number" && typeof start === "number" && typeof end === "number" ? [{ sequence, start, end }] : [];
17704
+ }) : [];
17662
17705
  return {
17663
17706
  generation: record.generation,
17664
17707
  previousGeneration: record.previousGeneration === "v1" || record.previousGeneration === "v2" ? record.previousGeneration : null,
@@ -17667,7 +17710,10 @@ function readCoordinateRebaseNotice(db, sessionId) {
17667
17710
  discardedReductions: count(record.discardedReductions),
17668
17711
  droppedDepthRows: count(record.droppedDepthRows),
17669
17712
  healedGaps: count(record.healedGaps),
17670
- narrativeGaps: count(record.narrativeGaps)
17713
+ narrativeGaps: count(record.narrativeGaps),
17714
+ derivedCompartments: ranges(record.derivedCompartments),
17715
+ unresolvedCompartmentRanges: ranges(record.unresolvedCompartmentRanges),
17716
+ neighbourRecoveryAt: typeof record.neighbourRecoveryAt === "number" && Number.isFinite(record.neighbourRecoveryAt) ? record.neighbourRecoveryAt : null
17671
17717
  };
17672
17718
  } catch {
17673
17719
  return null;
@@ -17678,8 +17724,13 @@ function formatCoordinateRebaseNotice(notice) {
17678
17724
  if (notice.discardedReductions > 0) {
17679
17725
  parts.push(`${notice.discardedReductions} queued reduction${notice.discardedReductions === 1 ? " was" : "s were"} discarded because their targets merged in the host's store conversion`);
17680
17726
  }
17727
+ if (notice.derivedCompartments.length > 0) {
17728
+ const count = notice.derivedCompartments.length;
17729
+ parts.push(`${count} compartment${count === 1 ? " was" : "s were"} re-anchored from the compartments around ${count === 1 ? "it" : "them"} (${formatRangeNotes(notice.derivedCompartments)})`);
17730
+ }
17681
17731
  if (notice.unresolvedCompartments > 0) {
17682
- parts.push(`${notice.unresolvedCompartments} compartment${notice.unresolvedCompartments === 1 ? "" : "s"} could not be re-anchored and are excluded from range recovery`);
17732
+ const listed = notice.unresolvedCompartmentRanges.length > 0 ? ` (${formatRangeNotes(notice.unresolvedCompartmentRanges)})` : "";
17733
+ parts.push(`${notice.unresolvedCompartments} compartment${notice.unresolvedCompartments === 1 ? "" : "s"} could not be re-anchored and are excluded from range recovery${listed}`);
17683
17734
  }
17684
17735
  if (notice.droppedDepthRows > 0) {
17685
17736
  parts.push(`${notice.droppedDepthRows} compression-depth records were rebuilt from zero`);
@@ -17692,29 +17743,49 @@ function formatCoordinateRebaseNotice(notice) {
17692
17743
  }
17693
17744
  return parts.length === 0 ? null : parts.join("; ");
17694
17745
  }
17746
+ function formatRangeNotes(notes) {
17747
+ return notes.map((note) => `messages ${note.start}-${note.end}`).join(", ");
17748
+ }
17695
17749
  function isCompartmentCoordinateRow(row) {
17696
17750
  if (row === null || typeof row !== "object")
17697
17751
  return false;
17698
17752
  const candidate = row;
17699
17753
  return typeof candidate.id === "number" && typeof candidate.sequence === "number" && typeof candidate.start_message === "number" && typeof candidate.end_message === "number";
17700
17754
  }
17701
- function buildProjection(messages) {
17702
- const ordinalById = new Map;
17703
- const partCountById = new Map;
17704
- const nonNarrativeOrdinals = new Set;
17755
+ function emptyProjection() {
17756
+ return {
17757
+ ordinalById: new Map,
17758
+ partCountById: new Map,
17759
+ nonNarrativeOrdinals: new Set,
17760
+ messageCount: 0,
17761
+ indexSources: []
17762
+ };
17763
+ }
17764
+ function addToProjection(projection, messages, withIndexSources) {
17705
17765
  for (const message of messages) {
17706
- ordinalById.set(message.id, message.ordinal);
17707
- partCountById.set(message.id, Array.isArray(message.parts) ? message.parts.length : 0);
17766
+ projection.ordinalById.set(message.id, message.ordinal);
17767
+ projection.partCountById.set(message.id, Array.isArray(message.parts) ? message.parts.length : 0);
17708
17768
  if (isStrictGapHealingMessage(message))
17709
- nonNarrativeOrdinals.add(message.ordinal);
17769
+ projection.nonNarrativeOrdinals.add(message.ordinal);
17770
+ if (withIndexSources)
17771
+ projection.indexSources.push(toMessageIndexSource(message));
17710
17772
  }
17711
- return {
17712
- ordinalById,
17713
- partCountById,
17714
- nonNarrativeOrdinals,
17715
- messageCount: messages.length
17716
- };
17773
+ projection.messageCount += messages.length;
17717
17774
  }
17775
+ function readProjectionPages(args) {
17776
+ if (args.readMessagePages)
17777
+ return args.readMessagePages(args.sessionId);
17778
+ return [args.readMessages(args.sessionId)];
17779
+ }
17780
+ function* buildProjectionSteps(args, withIndexSources) {
17781
+ const projection = emptyProjection();
17782
+ for (const page of readProjectionPages(args)) {
17783
+ addToProjection(projection, page, withIndexSources);
17784
+ yield;
17785
+ }
17786
+ return projection;
17787
+ }
17788
+ var INDEX_REBUILD_CHUNK = 2000;
17718
17789
  function messageIdFromAnchorBlockId(anchorBlockId) {
17719
17790
  const hash = anchorBlockId.lastIndexOf("#");
17720
17791
  return hash > 0 ? anchorBlockId.slice(0, hash) : anchorBlockId;
@@ -17723,36 +17794,62 @@ function readCompartmentRows(db, table, sessionId) {
17723
17794
  return db.prepare(`SELECT id, sequence, start_message, end_message, start_message_id, end_message_id, rebase_status
17724
17795
  FROM ${table} WHERE session_id = ? ORDER BY sequence ASC`).all(sessionId).filter(isCompartmentCoordinateRow);
17725
17796
  }
17797
+ function resolveAnchor(messageId, resolveOrdinal) {
17798
+ return messageId && messageId.length > 0 ? resolveOrdinal(messageId) : undefined;
17799
+ }
17726
17800
  function planCompartments(rows, table, projection) {
17727
- return rows.map((row) => {
17728
- const previousStatus = row.rebase_status === "unresolved" ? "unresolved" : "ok";
17729
- const startId = row.start_message_id ?? "";
17730
- const endId = row.end_message_id ?? "";
17731
- const start = startId.length > 0 ? projection.ordinalById.get(startId) : undefined;
17732
- const end = endId.length > 0 ? projection.ordinalById.get(endId) : undefined;
17733
- if (start === undefined || end === undefined) {
17734
- return {
17735
- table,
17736
- id: row.id,
17737
- previousStart: row.start_message,
17738
- previousEnd: row.end_message,
17739
- start: row.start_message,
17740
- end: row.end_message,
17741
- status: "unresolved",
17742
- previousStatus
17743
- };
17744
- }
17745
- return {
17801
+ const resolveOrdinal = (messageId) => projection.ordinalById.get(messageId);
17802
+ return recoverFromNeighbours(rows, table, rows.map((row) => ({
17803
+ start: resolveAnchor(row.start_message_id, resolveOrdinal),
17804
+ end: resolveAnchor(row.end_message_id, resolveOrdinal)
17805
+ })));
17806
+ }
17807
+ function recoverFromNeighbours(rows, table, known) {
17808
+ const plans = rows.map((row, index) => {
17809
+ const own = known[index] ?? { start: undefined, end: undefined };
17810
+ const previousEnd = index === 0 ? 0 : known[index - 1]?.end;
17811
+ const nextStart = index === rows.length - 1 ? undefined : known[index + 1]?.start;
17812
+ const start = own.start ?? (previousEnd === undefined ? undefined : previousEnd + 1);
17813
+ const end = own.end ?? (nextStart === undefined ? undefined : nextStart - 1);
17814
+ const base = {
17746
17815
  table,
17747
17816
  id: row.id,
17817
+ sequence: row.sequence,
17748
17818
  previousStart: row.start_message,
17749
17819
  previousEnd: row.end_message,
17750
- start,
17751
- end,
17752
- status: "ok",
17753
- previousStatus
17820
+ previousStatus: row.rebase_status === "unresolved" ? "unresolved" : "ok"
17821
+ };
17822
+ if (start !== undefined && end !== undefined && start <= end) {
17823
+ return {
17824
+ ...base,
17825
+ start,
17826
+ end,
17827
+ status: "ok",
17828
+ derived: own.start === undefined || own.end === undefined
17829
+ };
17830
+ }
17831
+ return {
17832
+ ...base,
17833
+ start: start ?? row.start_message,
17834
+ end: end ?? row.end_message,
17835
+ status: "unresolved",
17836
+ derived: false
17754
17837
  };
17755
17838
  });
17839
+ for (let index = 0;index < plans.length; index += 1) {
17840
+ const plan = plans[index];
17841
+ if (plan?.status !== "unresolved")
17842
+ continue;
17843
+ const previous = plans[index - 1];
17844
+ const next = plans[index + 1];
17845
+ if (previous?.status === "ok" && plan.start <= previous.end) {
17846
+ plan.start = previous.end + 1;
17847
+ }
17848
+ if (next?.status === "ok" && plan.end >= next.start) {
17849
+ plan.end = next.start - 1;
17850
+ }
17851
+ }
17852
+ return plans;
17756
17853
  }
17757
17854
  function healNonNarrativeCompartmentGaps(plans, projection) {
17758
17855
  let healed = 0;
@@ -17783,7 +17880,10 @@ function healNonNarrativeCompartmentGaps(plans, projection) {
17783
17880
  return { healed, narrative };
17784
17881
  }
17785
17882
  function compartmentPlanChanges(plan) {
17786
- return plan.status !== plan.previousStatus || plan.status === "ok" && (plan.start !== plan.previousStart || plan.end !== plan.previousEnd);
17883
+ return plan.status !== plan.previousStatus || plan.start !== plan.previousStart || plan.end !== plan.previousEnd;
17884
+ }
17885
+ function rangeNotes(plans, predicate) {
17886
+ return plans.filter((plan) => plan.table === "compartments" && predicate(plan)).map((plan) => ({ sequence: plan.sequence, start: plan.start, end: plan.end }));
17787
17887
  }
17788
17888
  function planNotes(db, sessionId, projection) {
17789
17889
  const rows = db.prepare("SELECT id, anchor_ordinal, anchor_block_id FROM notes WHERE session_id = ? AND anchor_ordinal IS NOT NULL").all(sessionId);
@@ -17824,13 +17924,17 @@ function pruneShrunkPartEntries(db, sessionId, column, shrunk) {
17824
17924
  } catch {
17825
17925
  return 0;
17826
17926
  }
17827
- const isStale = (candidate) => shrunk.some(({ messageId, partCount }) => {
17828
- const prefix = `${messageId}:p`;
17829
- if (!candidate.startsWith(prefix))
17927
+ const partCountByMessage = new Map(shrunk.map((entry) => [entry.messageId, entry.partCount]));
17928
+ const isStale = (candidate) => {
17929
+ const marker = candidate.lastIndexOf(":p");
17930
+ if (marker < 0)
17830
17931
  return false;
17831
- const suffix = candidate.slice(prefix.length);
17832
- return /^\d+$/.test(suffix) && Number.parseInt(suffix, 10) >= partCount;
17833
- });
17932
+ const suffix = candidate.slice(marker + 2);
17933
+ if (!/^\d+$/.test(suffix))
17934
+ return false;
17935
+ const partCount = partCountByMessage.get(candidate.slice(0, marker));
17936
+ return partCount !== undefined && Number.parseInt(suffix, 10) >= partCount;
17937
+ };
17834
17938
  let dropped = 0;
17835
17939
  const pruneArray = (values) => values.filter((value) => {
17836
17940
  if (typeof value === "string" && isStale(value)) {
@@ -17861,7 +17965,50 @@ function pruneShrunkPartEntries(db, sessionId, column, shrunk) {
17861
17965
  db.prepare(`UPDATE session_meta SET ${column} = ? WHERE session_id = ?`).run(JSON.stringify(next), sessionId);
17862
17966
  return dropped;
17863
17967
  }
17864
- function rebaseSessionCoordinates(args) {
17968
+ var REBASE_SLICE_MS = 20;
17969
+ var rebasesInFlight = new WeakMap;
17970
+ async function rebaseSessionCoordinatesAsync(args) {
17971
+ let sessions = rebasesInFlight.get(args.db);
17972
+ if (!sessions) {
17973
+ sessions = new Map;
17974
+ rebasesInFlight.set(args.db, sessions);
17975
+ }
17976
+ const earlier = sessions.get(args.sessionId);
17977
+ if (earlier)
17978
+ await earlier.catch(() => {
17979
+ return;
17980
+ });
17981
+ const run = runSliced(args);
17982
+ sessions.set(args.sessionId, run);
17983
+ try {
17984
+ return await run;
17985
+ } finally {
17986
+ if (sessions.get(args.sessionId) === run)
17987
+ sessions.delete(args.sessionId);
17988
+ }
17989
+ }
17990
+ async function runSliced(args) {
17991
+ const steps = rebaseSteps(args);
17992
+ let finished = false;
17993
+ try {
17994
+ let sliceStartedAt = performance.now();
17995
+ for (;; ) {
17996
+ const step = steps.next();
17997
+ if (step.done) {
17998
+ finished = true;
17999
+ return step.value;
18000
+ }
18001
+ if (performance.now() - sliceStartedAt >= REBASE_SLICE_MS) {
18002
+ await new Promise((resolve) => setImmediate(resolve));
18003
+ sliceStartedAt = performance.now();
18004
+ }
18005
+ }
18006
+ } finally {
18007
+ if (!finished)
18008
+ steps.return(emptyOutcome("unchanged", args.generation, null));
18009
+ }
18010
+ }
18011
+ function* rebaseSteps(args) {
17865
18012
  const { db, sessionId, generation } = args;
17866
18013
  const startedAt = performance.now();
17867
18014
  if (!sessionIsOpenCodeOwned(db, sessionId)) {
@@ -17869,14 +18016,21 @@ function rebaseSessionCoordinates(args) {
17869
18016
  }
17870
18017
  const previousGeneration = readCoordinateGeneration(db, sessionId);
17871
18018
  if (previousGeneration === generation) {
17872
- return emptyOutcome("unchanged", generation, previousGeneration);
18019
+ const outcome = emptyOutcome("unchanged", generation, previousGeneration);
18020
+ const repair = repairStampedSessionOnce(db, sessionId, args);
18021
+ if (repair !== null && repair.rowsRewritten > 0) {
18022
+ outcome.status = "repaired";
18023
+ outcome.compartmentsDerived = repair.derived.length;
18024
+ outcome.compartmentsUnresolved = repair.unresolved.length;
18025
+ }
18026
+ return outcome;
17873
18027
  }
17874
18028
  const impliedGeneration = previousGeneration ?? generationImpliedByHarness(db, sessionId) ?? generation;
17875
18029
  if (impliedGeneration === generation) {
17876
18030
  stampGeneration(db, sessionId, generation, null);
17877
18031
  return emptyOutcome("stamped", generation, previousGeneration);
17878
18032
  }
17879
- const projection = buildProjection(args.readMessages(sessionId));
18033
+ const projection = yield* buildProjectionSteps(args, true);
17880
18034
  const outcome = emptyOutcome("rebased", generation, impliedGeneration);
17881
18035
  const compartmentRows = readCompartmentRows(db, "compartments", sessionId);
17882
18036
  const recompRows = readCompartmentRows(db, "recomp_compartments", sessionId);
@@ -17886,7 +18040,7 @@ function rebaseSessionCoordinates(args) {
17886
18040
  const recompGapResult = healNonNarrativeCompartmentGaps(recompPlans, projection);
17887
18041
  const notePlans = planNotes(db, sessionId, projection);
17888
18042
  const shrunkMessages = [];
17889
- const taggedMessageIds = db.prepare("SELECT DISTINCT message_id FROM tags WHERE session_id = ? AND type = 'message'").all(sessionId).flatMap((row) => typeof row.message_id === "string" ? [row.message_id] : []);
18043
+ const taggedMessageIds = new Set(db.prepare("SELECT message_id FROM tags WHERE session_id = ? AND type = 'message'").all(sessionId).flatMap((row) => typeof row.message_id === "string" ? [row.message_id] : []));
17890
18044
  const highestTaggedPartIndex = new Map;
17891
18045
  for (const contentId of taggedMessageIds) {
17892
18046
  const marker = contentId.lastIndexOf(":p");
@@ -17922,17 +18076,41 @@ function rebaseSessionCoordinates(args) {
17922
18076
  return emptyOutcome("stamped", generation, impliedGeneration);
17923
18077
  }
17924
18078
  db.exec("BEGIN IMMEDIATE");
17925
- let committed = false;
18079
+ let closed = false;
17926
18080
  try {
18081
+ if (readCoordinateGeneration(db, sessionId) !== previousGeneration) {
18082
+ db.exec("ROLLBACK");
18083
+ closed = true;
18084
+ return emptyOutcome("unchanged", generation, readCoordinateGeneration(db, sessionId));
18085
+ }
18086
+ clearCachedM0M1(db, sessionId);
18087
+ db.prepare("UPDATE session_meta SET system_prompt_hash = '' WHERE session_id = ?").run(sessionId);
18088
+ for (const column of [
18089
+ "stripped_placeholder_ids",
18090
+ "merged_reasoning_stripped_ids",
18091
+ "trailing_blank_decisions"
18092
+ ]) {
18093
+ outcome.frozenPartEntriesDropped += pruneShrunkPartEntries(db, sessionId, column, shrunkMessages);
18094
+ }
18095
+ const fold = foldShrunkPartTags(db, sessionId, shrunkMessages);
18096
+ outcome.partTagsFolded = fold.foldedTagNumbers.length;
18097
+ outcome.partTagsRekeyed = fold.rekeyedTagNumbers.length;
18098
+ outcome.queuedReductionsDiscarded = fold.discardedDropTagNumbers.length;
18099
+ const updateCompartment = {
18100
+ compartments: db.prepare("UPDATE compartments SET start_message = ?, end_message = ?, rebase_status = ? WHERE id = ?"),
18101
+ recomp_compartments: db.prepare("UPDATE recomp_compartments SET start_message = ?, end_message = ?, rebase_status = ? WHERE id = ?")
18102
+ };
17927
18103
  for (const plan of [...compartmentPlans, ...recompPlans]) {
17928
18104
  if (!compartmentPlanChanges(plan))
17929
18105
  continue;
17930
- db.prepare(`UPDATE ${plan.table} SET start_message = ?, end_message = ?, rebase_status = ? WHERE id = ?`).run(plan.start, plan.end, plan.status, plan.id);
18106
+ updateCompartment[plan.table].run(plan.start, plan.end, plan.status, plan.id);
17931
18107
  const rebased = plan.status === "ok" ? 1 : 0;
17932
18108
  const unresolved = plan.status === "unresolved" ? 1 : 0;
17933
18109
  if (plan.table === "compartments") {
17934
18110
  outcome.compartmentsRebased += rebased;
17935
18111
  outcome.compartmentsUnresolved += unresolved;
18112
+ if (rebased === 1 && plan.derived)
18113
+ outcome.compartmentsDerived += 1;
17936
18114
  if (rebased === 1 && plan.previousStatus === "unresolved")
17937
18115
  outcome.compartmentsResolvedAgain += 1;
17938
18116
  } else {
@@ -17940,8 +18118,9 @@ function rebaseSessionCoordinates(args) {
17940
18118
  outcome.recompCompartmentsUnresolved += unresolved;
17941
18119
  }
17942
18120
  }
18121
+ const updateNote = db.prepare("UPDATE notes SET anchor_ordinal = ? WHERE id = ? AND session_id = ?");
17943
18122
  for (const plan of movedNotes) {
17944
- db.prepare("UPDATE notes SET anchor_ordinal = ? WHERE id = ? AND session_id = ?").run(plan.ordinal, plan.id, sessionId);
18123
+ updateNote.run(plan.ordinal, plan.id, sessionId);
17945
18124
  if (plan.ordinal === null)
17946
18125
  outcome.notesCleared += 1;
17947
18126
  else
@@ -17968,19 +18147,6 @@ function rebaseSessionCoordinates(args) {
17968
18147
  db.prepare("DELETE FROM lkg_slots WHERE session_id = ?").run(sessionId);
17969
18148
  outcome.lkgSlotsDropped = lkgSlotCount;
17970
18149
  }
17971
- const fold = foldShrunkPartTags(db, sessionId, shrunkMessages);
17972
- outcome.partTagsFolded = fold.foldedTagNumbers.length;
17973
- outcome.partTagsRekeyed = fold.rekeyedTagNumbers.length;
17974
- outcome.queuedReductionsDiscarded = fold.discardedDropTagNumbers.length;
17975
- for (const column of [
17976
- "stripped_placeholder_ids",
17977
- "merged_reasoning_stripped_ids",
17978
- "trailing_blank_decisions"
17979
- ]) {
17980
- outcome.frozenPartEntriesDropped += pruneShrunkPartEntries(db, sessionId, column, shrunkMessages);
17981
- }
17982
- clearCachedM0M1(db, sessionId);
17983
- db.prepare("UPDATE session_meta SET system_prompt_hash = '' WHERE session_id = ?").run(sessionId);
17984
18150
  stampGeneration(db, sessionId, generation, {
17985
18151
  generation,
17986
18152
  previousGeneration: impliedGeneration,
@@ -17989,28 +18155,146 @@ function rebaseSessionCoordinates(args) {
17989
18155
  discardedReductions: outcome.queuedReductionsDiscarded,
17990
18156
  droppedDepthRows: outcome.compressionDepthRowsDropped,
17991
18157
  healedGaps: outcome.healedGaps,
17992
- narrativeGaps: outcome.narrativeGaps
18158
+ narrativeGaps: outcome.narrativeGaps,
18159
+ derivedCompartments: rangeNotes(compartmentPlans, (plan) => plan.status === "ok" && plan.derived),
18160
+ unresolvedCompartmentRanges: rangeNotes(compartmentPlans, (plan) => plan.status === "unresolved"),
18161
+ neighbourRecoveryAt: Date.now()
17993
18162
  });
17994
18163
  db.exec("COMMIT");
17995
- committed = true;
18164
+ closed = true;
17996
18165
  } finally {
17997
- if (!committed) {
18166
+ if (!closed) {
17998
18167
  try {
17999
18168
  db.exec("ROLLBACK");
18000
18169
  } catch {}
18001
18170
  }
18002
18171
  }
18003
18172
  if (outcome.indexRebuilt) {
18004
- ensureMessagesIndexed(db, sessionId, args.readMessages);
18173
+ const sources = projection.indexSources;
18174
+ for (let start = 0;start < sources.length; start += INDEX_REBUILD_CHUNK) {
18175
+ indexSourcesAfterOrdinal(db, sessionId, sources.slice(start, start + INDEX_REBUILD_CHUNK), sources.length);
18176
+ yield;
18177
+ }
18005
18178
  outcome.indexRowsRebuilt = countRows(db, "SELECT COUNT(*) AS count FROM message_history_source WHERE session_id = ?", sessionId);
18006
18179
  }
18007
18180
  sessionLog(sessionId, formatRebaseLogLine(outcome, performance.now() - startedAt));
18008
18181
  return outcome;
18009
18182
  }
18183
+ function recoverUnresolvedCompartments(args) {
18184
+ const { db, sessionId } = args;
18185
+ const rows = readCompartmentRows(db, "compartments", sessionId);
18186
+ const result = { rowsRewritten: 0, derived: [], unresolved: [] };
18187
+ if (!rows.some((row) => row.rebase_status === "unresolved"))
18188
+ return result;
18189
+ const known = rows.map((row) => {
18190
+ if (row.rebase_status !== "unresolved") {
18191
+ return { start: row.start_message, end: row.end_message };
18192
+ }
18193
+ return {
18194
+ start: resolveAnchor(row.start_message_id, args.resolveOrdinal),
18195
+ end: resolveAnchor(row.end_message_id, args.resolveOrdinal)
18196
+ };
18197
+ });
18198
+ const plans = recoverFromNeighbours(rows, "compartments", known);
18199
+ const wasUnresolved = (plan) => plan.previousStatus === "unresolved";
18200
+ result.derived = rangeNotes(plans, (plan) => wasUnresolved(plan) && plan.status === "ok" && plan.derived);
18201
+ result.unresolved = rangeNotes(plans, (plan) => plan.status === "unresolved");
18202
+ const changed = plans.filter(compartmentPlanChanges);
18203
+ const now = Date.now();
18204
+ db.exec("BEGIN IMMEDIATE");
18205
+ let committed = false;
18206
+ try {
18207
+ for (const plan of changed) {
18208
+ db.prepare("UPDATE compartments SET start_message = ?, end_message = ?, rebase_status = ? WHERE id = ?").run(plan.start, plan.end, plan.status, plan.id);
18209
+ }
18210
+ const previous = readCoordinateRebaseNotice(db, sessionId);
18211
+ const generation = previous?.generation ?? readCoordinateGeneration(db, sessionId);
18212
+ if (generation !== null) {
18213
+ const derivedSequences = new Set(result.derived.map((note) => note.sequence));
18214
+ const notice = {
18215
+ generation,
18216
+ previousGeneration: previous?.previousGeneration ?? null,
18217
+ at: previous?.at ?? now,
18218
+ unresolvedCompartments: result.unresolved.length,
18219
+ discardedReductions: previous?.discardedReductions ?? 0,
18220
+ droppedDepthRows: previous?.droppedDepthRows ?? 0,
18221
+ healedGaps: previous?.healedGaps ?? 0,
18222
+ narrativeGaps: previous?.narrativeGaps ?? 0,
18223
+ derivedCompartments: [
18224
+ ...(previous?.derivedCompartments ?? []).filter((note) => !derivedSequences.has(note.sequence)),
18225
+ ...result.derived
18226
+ ],
18227
+ unresolvedCompartmentRanges: result.unresolved,
18228
+ neighbourRecoveryAt: now
18229
+ };
18230
+ ensureSessionMetaRow(db, sessionId);
18231
+ db.prepare("UPDATE session_meta SET coordinate_rebase_notice = ? WHERE session_id = ?").run(JSON.stringify(notice), sessionId);
18232
+ }
18233
+ db.exec("COMMIT");
18234
+ committed = true;
18235
+ } finally {
18236
+ if (!committed) {
18237
+ try {
18238
+ db.exec("ROLLBACK");
18239
+ } catch {}
18240
+ }
18241
+ }
18242
+ result.rowsRewritten = changed.length;
18243
+ sessionLog(sessionId, `INFO compartment neighbour recovery (${args.reason}) rows_rewritten=${changed.length} ` + `derived=${result.derived.map((note) => `${note.start}-${note.end}`).join(",") || "none"} ` + `unresolved=${result.unresolved.map((note) => `${note.start}-${note.end}`).join(",") || "none"}`);
18244
+ return result;
18245
+ }
18246
+ var repairCheckedSessions = new WeakMap;
18247
+ function unresolvedRowBreaksTiling(rows) {
18248
+ let expectedStart = 1;
18249
+ for (let index = 0;index < rows.length; index += 1) {
18250
+ const row = rows[index];
18251
+ if (!row)
18252
+ continue;
18253
+ const broken = row.start_message !== expectedStart || row.end_message < row.start_message;
18254
+ const touchesUnresolved = row.rebase_status === "unresolved" || rows[index - 1]?.rebase_status === "unresolved";
18255
+ if (broken && touchesUnresolved)
18256
+ return true;
18257
+ expectedStart = row.end_message + 1;
18258
+ }
18259
+ return false;
18260
+ }
18261
+ function repairStampedSessionOnce(db, sessionId, readArgs) {
18262
+ let checked = repairCheckedSessions.get(db);
18263
+ if (!checked) {
18264
+ checked = new Set;
18265
+ repairCheckedSessions.set(db, checked);
18266
+ }
18267
+ if (checked.has(sessionId))
18268
+ return null;
18269
+ checked.add(sessionId);
18270
+ const rows = readCompartmentRows(db, "compartments", sessionId);
18271
+ if (!rows.some((row) => row.rebase_status === "unresolved"))
18272
+ return null;
18273
+ if (readCoordinateRebaseNotice(db, sessionId)?.neighbourRecoveryAt != null)
18274
+ return null;
18275
+ if (!unresolvedRowBreaksTiling(rows))
18276
+ return null;
18277
+ let ordinalById = null;
18278
+ return recoverUnresolvedCompartments({
18279
+ db,
18280
+ sessionId,
18281
+ resolveOrdinal: (messageId) => {
18282
+ if (ordinalById === null) {
18283
+ const projection = emptyProjection();
18284
+ for (const page of readProjectionPages(readArgs)) {
18285
+ addToProjection(projection, page, false);
18286
+ }
18287
+ ordinalById = projection.ordinalById;
18288
+ }
18289
+ return ordinalById.get(messageId);
18290
+ },
18291
+ reason: "stamped-session repair"
18292
+ });
18293
+ }
18010
18294
  function formatRebaseLogLine(outcome, elapsedMs) {
18011
18295
  const rowsRewritten = outcome.compartmentsRebased + outcome.recompCompartmentsRebased + outcome.notesRebased + outcome.notesCleared + (outcome.priorBoundaryRebased ? 1 : 0) + (outcome.recompPartialRangeRebased ? 1 : 0);
18012
18296
  const unresolved = outcome.compartmentsUnresolved + outcome.recompCompartmentsUnresolved;
18013
- return `INFO store-generation-rebase ${outcome.previousGeneration ?? "unrecorded"}->${outcome.generation} ` + `rows_rewritten=${rowsRewritten} unresolved=${unresolved} ` + `index_rows_rebuilt=${outcome.indexRowsRebuilt} drops_discarded=${outcome.queuedReductionsDiscarded} ` + `healed_gaps=${outcome.healedGaps} narrative_gaps=${outcome.narrativeGaps} ` + `ms=${Math.round(elapsedMs)} ` + `(chunk_windows_deleted=${outcome.chunkEmbeddingsDeleted} depth_rows_dropped=${outcome.compressionDepthRowsDropped} ` + `part_tags_folded=${outcome.partTagsFolded} lkg_slots_dropped=${outcome.lkgSlotsDropped} ` + `frozen_part_entries_dropped=${outcome.frozenPartEntriesDropped})`;
18297
+ return `INFO store-generation-rebase ${outcome.previousGeneration ?? "unrecorded"}->${outcome.generation} ` + `rows_rewritten=${rowsRewritten} unresolved=${unresolved} derived=${outcome.compartmentsDerived} ` + `index_rows_rebuilt=${outcome.indexRowsRebuilt} drops_discarded=${outcome.queuedReductionsDiscarded} ` + `healed_gaps=${outcome.healedGaps} narrative_gaps=${outcome.narrativeGaps} ` + `ms=${Math.round(elapsedMs)} ` + `(chunk_windows_deleted=${outcome.chunkEmbeddingsDeleted} depth_rows_dropped=${outcome.compressionDepthRowsDropped} ` + `part_tags_folded=${outcome.partTagsFolded} lkg_slots_dropped=${outcome.lkgSlotsDropped} ` + `frozen_part_entries_dropped=${outcome.frozenPartEntriesDropped})`;
18014
18298
  }
18015
18299
  function planPriorBoundary(db, sessionId, plans) {
18016
18300
  const row = db.prepare("SELECT prior_boundary_ordinal FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -18085,11 +18369,7 @@ var V2_MEMORY_CATEGORIES = [
18085
18369
  "NAMING"
18086
18370
  ];
18087
18371
  var PROMOTABLE_CATEGORIES = [
18088
- "PROJECT_RULES",
18089
- "ARCHITECTURE",
18090
- "CONSTRAINTS",
18091
- "CONFIG_VALUES",
18092
- "NAMING",
18372
+ ...V2_MEMORY_CATEGORIES,
18093
18373
  "ARCHITECTURE_DECISIONS",
18094
18374
  "CONFIG_DEFAULTS",
18095
18375
  "USER_PREFERENCES",
@@ -18099,11 +18379,7 @@ var PROMOTABLE_CATEGORIES = [
18099
18379
  "KNOWN_ISSUES"
18100
18380
  ];
18101
18381
  var CATEGORY_PRIORITY = [
18102
- "PROJECT_RULES",
18103
- "ARCHITECTURE",
18104
- "CONSTRAINTS",
18105
- "CONFIG_VALUES",
18106
- "NAMING",
18382
+ ...V2_MEMORY_CATEGORIES,
18107
18383
  "USER_DIRECTIVES",
18108
18384
  "USER_PREFERENCES",
18109
18385
  "CONFIG_DEFAULTS",
@@ -18236,7 +18512,7 @@ async function ensureMemoryEmbeddings(args) {
18236
18512
  staged.set(memory.id, { embedding, modelId: result.modelId });
18237
18513
  }
18238
18514
  }
18239
- })();
18515
+ }).immediate();
18240
18516
  const currentSnapshot = getProjectEmbeddingSnapshot(args.projectIdentity);
18241
18517
  if (!currentSnapshot || currentSnapshot.generation !== result.generation) {
18242
18518
  return args.existingEmbeddings;
@@ -19077,7 +19353,7 @@ async function embedAndStoreMemory(db, sessionId, projectPath, memoryId, content
19077
19353
  if (result) {
19078
19354
  db.transaction(() => {
19079
19355
  saveEmbeddingIfHashMatches(db, memoryId, result.vector, result.modelId, hashBeforeEmbed);
19080
- })();
19356
+ }).immediate();
19081
19357
  }
19082
19358
  } catch (error) {
19083
19359
  sessionLog(sessionId, `memory embedding failed for memory ${memoryId}:`, error);
@@ -19253,7 +19529,7 @@ async function runGit(cwd, args) {
19253
19529
  return String(result.stdout);
19254
19530
  } catch (error) {
19255
19531
  if (error.killed || error.code === "ETIMEDOUT") {
19256
- throw new Error(`Git verification command timed out after ${GIT_TIMEOUT_MS2}ms`, {
19532
+ throw new Error(`Git verification command git ${args.join(" ")} timed out after ${GIT_TIMEOUT_MS2}ms`, {
19257
19533
  cause: error
19258
19534
  });
19259
19535
  }
@@ -20889,7 +21165,8 @@ var TIER_OPEN_REGEXES = [
20889
21165
  ];
20890
21166
  var TIER_CLOSE_ANY_REGEX = /<\/p\d/;
20891
21167
  var TIER_OPEN_ANY_REGEX = /<p\d/;
20892
- var CATEGORY_BLOCK_REGEX = /<(PROJECT_RULES|ARCHITECTURE|CONSTRAINTS|CONFIG_VALUES|NAMING)>(.*?)<\/\1>/gs;
21168
+ var CATEGORY_BLOCK_REGEX = /<([A-Za-z_][A-Za-z0-9_-]*)>(.*?)<\/\1>/gs;
21169
+ var HISTORIAN_CATEGORIES = new Set(V2_MEMORY_CATEGORIES);
20893
21170
  var FACT_ITEM_REGEX = /^\s*\*\s*(.+)$/gm;
20894
21171
  var UNPROCESSED_REGEX = /<unprocessed_from>(\d+)<\/unprocessed_from>/;
20895
21172
  var USER_OBSERVATIONS_REGEX = /<user_observations>(.*?)<\/user_observations>/s;
@@ -20926,6 +21203,8 @@ function extractTiersFromInner(inner) {
20926
21203
  function parseCompartmentOutput(text) {
20927
21204
  const compartments = [];
20928
21205
  const facts = [];
21206
+ let droppedFactBlocks = 0;
21207
+ let droppedFacts = 0;
20929
21208
  for (const match of text.matchAll(COMPARTMENT_REGEX)) {
20930
21209
  const attrs = match[1];
20931
21210
  const inner = match[2];
@@ -20975,16 +21254,21 @@ function parseCompartmentOutput(text) {
20975
21254
  }
20976
21255
  }
20977
21256
  const factsBlockMatch = text.match(FACTS_BLOCK_REGEX);
20978
- const factsScope = factsBlockMatch ? factsBlockMatch[1] : text.replace(EVENTS_BLOCK_REGEX, "").replace(/<compartment\s+[^>]*?\s*>.*?<\/compartment>/gs, "");
21257
+ const factsScope = factsBlockMatch ? factsBlockMatch[1] : text.replace(EVENTS_BLOCK_REGEX, "").replace(/<compartment\s+[^>]*?\s*>.*?<\/compartment>/gs, "").replace(/<(meta|user_observations|primer_candidates)>.*?<\/\1>/gs, "").replace(/<\/?(?:output|compartments)>/g, "");
20979
21258
  for (const categoryMatch of factsScope.matchAll(CATEGORY_BLOCK_REGEX)) {
20980
21259
  const category = categoryMatch[1];
20981
21260
  const blockContent = categoryMatch[2];
20982
- for (const itemMatch of blockContent.matchAll(FACT_ITEM_REGEX)) {
20983
- const content = unescapeXml(itemMatch[1].trim());
20984
- if (content) {
20985
- facts.push({ category, content });
20986
- }
21261
+ const items = [...blockContent.matchAll(FACT_ITEM_REGEX)].map((match) => unescapeXml(match[1].trim())).filter(Boolean);
21262
+ if (!HISTORIAN_CATEGORIES.has(category)) {
21263
+ if (items.length === 0)
21264
+ continue;
21265
+ droppedFactBlocks++;
21266
+ droppedFacts += items.length;
21267
+ log(`[historian] Dropped <facts> category ${category} (${items.length} facts)`);
21268
+ continue;
20987
21269
  }
21270
+ for (const content of items)
21271
+ facts.push({ category, content });
20988
21272
  }
20989
21273
  const unprocessedMatch = text.match(UNPROCESSED_REGEX);
20990
21274
  const unprocessedFrom = unprocessedMatch ? parseInt(unprocessedMatch[1], 10) : null;
@@ -21022,7 +21306,16 @@ function parseCompartmentOutput(text) {
21022
21306
  }
21023
21307
  const events = parseEvents(text);
21024
21308
  compartments.sort((a, b) => a.startMessage - b.startMessage);
21025
- return { compartments, facts, events, unprocessedFrom, userObservations, primerCandidates };
21309
+ return {
21310
+ compartments,
21311
+ facts,
21312
+ droppedFactBlocks,
21313
+ droppedFacts,
21314
+ events,
21315
+ unprocessedFrom,
21316
+ userObservations,
21317
+ primerCandidates
21318
+ };
21026
21319
  }
21027
21320
  function parseEvents(text) {
21028
21321
  const blockMatch = text.match(EVENTS_BLOCK_REGEX);
@@ -23918,6 +24211,20 @@ var MIGRATIONS = [
23918
24211
  return;
23919
24212
  ensureColumn(db, "compartment_state_lease", "owner_pid", "INTEGER");
23920
24213
  }
24214
+ },
24215
+ {
24216
+ version: 91,
24217
+ description: "per-project embedding high-water mark for memories written outside this host",
24218
+ up(db) {
24219
+ db.exec(`
24220
+ CREATE TABLE IF NOT EXISTS memory_embedding_watermarks (
24221
+ project_path TEXT PRIMARY KEY,
24222
+ written_memory_id INTEGER NOT NULL DEFAULT 0,
24223
+ embedded_memory_id INTEGER NOT NULL DEFAULT 0,
24224
+ updated_at INTEGER NOT NULL DEFAULT 0
24225
+ );
24226
+ `);
24227
+ }
23921
24228
  }
23922
24229
  ];
23923
24230
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -24451,17 +24758,33 @@ function touch(sessionId, entry) {
24451
24758
  lkgHeapHolder.entries.delete(sessionId);
24452
24759
  lkgHeapHolder.entries.set(sessionId, entry);
24453
24760
  }
24454
- function captureSlot(sessionId, slot) {
24455
- if (slot.inputContentDigests.length !== slot.inputIdSeq.length || slot.inputContentDigests.some((digest) => digest.length === 0) || slot.inputContentSignatures !== undefined && (slot.inputContentSignatures.length !== slot.inputIdSeq.length || slot.inputContentSignatures.some((signature) => signature.length === 0))) {
24456
- return false;
24761
+ function lkgSlotRejection(sessionId, slot) {
24762
+ if (slot.inputContentDigests.length !== slot.inputIdSeq.length)
24763
+ return `digest_count=${slot.inputContentDigests.length} inputs=${slot.inputIdSeq.length}`;
24764
+ const emptyDigest = slot.inputContentDigests.findIndex((digest) => digest.length === 0);
24765
+ if (emptyDigest >= 0)
24766
+ return `empty_digest_at=${emptyDigest}`;
24767
+ if (slot.inputContentSignatures !== undefined) {
24768
+ if (slot.inputContentSignatures.length !== slot.inputIdSeq.length)
24769
+ return `signature_count=${slot.inputContentSignatures.length} inputs=${slot.inputIdSeq.length}`;
24770
+ const emptySignature = slot.inputContentSignatures.findIndex((signature) => signature.length === 0);
24771
+ if (emptySignature >= 0)
24772
+ return `empty_signature_at=${emptySignature}`;
24457
24773
  }
24458
24774
  const bytes = slotBytes(slot);
24459
24775
  if (bytes > LKG_SINGLE_SLOT_BYTES)
24460
- return false;
24776
+ return `slot_bytes=${bytes}`;
24461
24777
  const prior = lkgHeapHolder.entries.get(sessionId);
24462
24778
  if (prior?.slot.rowVersion !== undefined && slot.rowVersion !== undefined && (slot.rowVersion < prior.slot.rowVersion || slot.rowVersion === prior.slot.rowVersion && (slot.captureSequence ?? 0) < (prior.slot.captureSequence ?? 0))) {
24463
- return false;
24779
+ return `stale row_version=${slot.rowVersion}/${prior.slot.rowVersion} capture_sequence=${slot.captureSequence ?? 0}/${prior.slot.captureSequence ?? 0}`;
24464
24780
  }
24781
+ return null;
24782
+ }
24783
+ function captureSlot(sessionId, slot) {
24784
+ if (lkgSlotRejection(sessionId, slot) !== null)
24785
+ return false;
24786
+ const bytes = slotBytes(slot);
24787
+ const prior = lkgHeapHolder.entries.get(sessionId);
24465
24788
  if (prior)
24466
24789
  totalBytes -= prior.bytes;
24467
24790
  lkgHeapHolder.entries.delete(sessionId);
@@ -24870,7 +25193,9 @@ function formatFailClosedBlockingMessage(reason) {
24870
25193
  }
24871
25194
  return [
24872
25195
  `Magic Context cannot migrate the shared database (one database serves every project on this machine) because ${formatFailClosedBlockingProcesses(reason.blockingProcesses)} may be running an older Magic Context build that would fail against the migrated database.`,
25196
+ `The database is at upstream migration v${reason.persistedVersion}; this build needs v${reason.supportedVersion}.`,
24873
25197
  "Restart the blocking process — even one from a different project — and it will pick up the new build and migrate on start; or shut it down and retry.",
25198
+ "If that host loads a pinned or cached older Magic Context build, a restart alone is not enough: stop it or update its Magic Context build, then start this host once so it migrates the database with nothing older attached.",
24874
25199
  `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
24875
25200
  ].join(" ");
24876
25201
  }
@@ -24887,6 +25212,21 @@ function formatFailClosedBlockingMessage(reason) {
24887
25212
  `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
24888
25213
  ].join(" ");
24889
25214
  }
25215
+ function formatFailClosedBlockingSummary(reason) {
25216
+ if (reason.kind === "migration_guard") {
25217
+ if (reason.unreadableFile) {
25218
+ return `Magic Context cannot migrate the shared database from v${reason.persistedVersion} to v${reason.supportedVersion}: RPC discovery file ${reason.unreadableFile} could not be read, so an older host may still be attached.`;
25219
+ }
25220
+ const blockers = reason.blockingProcesses.filter((process2) => Number.isInteger(process2.pid) && process2.pid > 0).map((process2) => `${normalizeFailClosedProcessKind(process2)} (PID ${process2.pid})`);
25221
+ const named = blockers.length > 0 ? blockers.join(", ") : "a live process";
25222
+ return `Magic Context cannot migrate the shared database from v${reason.persistedVersion} to v${reason.supportedVersion} while ${named} may still run an older Magic Context build. Stop or update that host, then start this one once.`;
25223
+ }
25224
+ if (reason.kind === "schema_fence") {
25225
+ return `Magic Context cannot operate: the shared database is at v${reason.persistedVersion}, newer than this build supports (v${reason.supportedVersion}). Update and restart this host.`;
25226
+ }
25227
+ const cause = reason.cause.trim().length > 0 ? reason.cause.trim() : "unknown storage error";
25228
+ return `Magic Context cannot operate: persistent storage failed (${cause}).`;
25229
+ }
24890
25230
  function createFailClosedBlockingError(reason, options) {
24891
25231
  return new FailClosedBlockingError(formatFailClosedBlockingMessage(reason), reason, options);
24892
25232
  }
@@ -25248,7 +25588,7 @@ function getSchemaFenceRejection() {
25248
25588
  function getMigrationOnOpenRefusal() {
25249
25589
  return lastMigrationOnOpenRefusal;
25250
25590
  }
25251
- var LATEST_SUPPORTED_VERSION = 90;
25591
+ var LATEST_SUPPORTED_VERSION = 91;
25252
25592
  var BOOT_SQLITE_BUSY_TIMEOUT_MS = 5000;
25253
25593
  var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
25254
25594
  var defaultStoragePermissionFs = { chmodSync: chmodSync2, mkdirSync: mkdirSync3 };
@@ -25503,6 +25843,8 @@ function inspectRpcServerDiscovery(storageDir) {
25503
25843
  return junk;
25504
25844
  continue;
25505
25845
  }
25846
+ if (isOwnRpcServerRecord(record))
25847
+ continue;
25506
25848
  const liveness = isPidAlive(record.pid);
25507
25849
  if (liveness === "dead") {
25508
25850
  staleFiles.push(portFile);
@@ -25663,8 +26005,8 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
25663
26005
  { readRawSessionMessagePage, readRawSessionMessages },
25664
26006
  { startMessageTimeBackfill }
25665
26007
  ] = await Promise.all([
25666
- import("./read-session-chunk-z7fv0qjv.js"),
25667
- import("./message-time-backfill-0ccvyk9n.js")
26008
+ import("./read-session-chunk-ktz5zt70.js"),
26009
+ import("./message-time-backfill-rm9wmcem.js")
25668
26010
  ]);
25669
26011
  await startMessageTimeBackfill(db, Object.assign(readRawSessionMessages, {
25670
26012
  readPage: readRawSessionMessagePage
@@ -26246,6 +26588,15 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
26246
26588
  (id, cursor_session_id, cursor_ordinal, completed, updated_at)
26247
26589
  VALUES (1, '', 0, 0, 0);
26248
26590
 
26591
+ -- Highest memory id another writer (the Rust module in single-store mode) put
26592
+ -- into memories for a project, and how far this host has embedded. Migration v91.
26593
+ CREATE TABLE IF NOT EXISTS memory_embedding_watermarks (
26594
+ project_path TEXT PRIMARY KEY,
26595
+ written_memory_id INTEGER NOT NULL DEFAULT 0,
26596
+ embedded_memory_id INTEGER NOT NULL DEFAULT 0,
26597
+ updated_at INTEGER NOT NULL DEFAULT 0
26598
+ );
26599
+
26249
26600
  CREATE TABLE IF NOT EXISTS message_history_index (
26250
26601
  session_id TEXT PRIMARY KEY,
26251
26602
  last_indexed_ordinal INTEGER NOT NULL DEFAULT 0,
@@ -27325,7 +27676,19 @@ function noteCheckColumnsExist(db) {
27325
27676
  return false;
27326
27677
  }
27327
27678
  }
27679
+ var PENDING_SESSION_NOTE_HEAL = "UPDATE notes SET status = 'active', surface_condition = NULL WHERE type = 'session' AND status = 'pending' AND surface_condition IS NOT NULL";
27680
+ function healPendingSessionNotes(db) {
27681
+ try {
27682
+ db.prepare(`${PENDING_SESSION_NOTE_HEAL} AND NOT ${managedAuthorityNoteRow("notes")}`).run();
27683
+ } catch (error) {
27684
+ if (!(error instanceof Error) || !error.message.includes("no such table"))
27685
+ throw error;
27686
+ db.prepare(PENDING_SESSION_NOTE_HEAL).run();
27687
+ }
27688
+ }
27689
+ var SESSION_NOTE_CONDITION_ERROR = "Only a note created with a condition can have one. Write a new note with surface_condition, and dismiss this one.";
27328
27690
  function getNoteById(db, noteId) {
27691
+ healPendingSessionNotes(db);
27329
27692
  const row = db.prepare("SELECT * FROM notes WHERE id = ?").get(noteId);
27330
27693
  return isNoteRow(row) ? toNote(row) : null;
27331
27694
  }
@@ -27354,6 +27717,7 @@ function buildStatusClause(status) {
27354
27717
  };
27355
27718
  }
27356
27719
  function getNotes(db, options = {}) {
27720
+ healPendingSessionNotes(db);
27357
27721
  const clauses = [];
27358
27722
  const params = [];
27359
27723
  if (options.sessionId !== undefined) {
@@ -27405,6 +27769,9 @@ function updateNote(db, noteId, updates, scope) {
27405
27769
  if (!existing) {
27406
27770
  return null;
27407
27771
  }
27772
+ if (updates.surfaceCondition !== undefined && existing.type !== "smart") {
27773
+ return null;
27774
+ }
27408
27775
  const now = Date.now();
27409
27776
  const sets = ["updated_at = ?"];
27410
27777
  const params = [now];
@@ -27476,7 +27843,7 @@ function dismissNotes(db, noteIds, scope) {
27476
27843
  noteId,
27477
27844
  outcome: result.changes > 0 ? "dismissed" : "already_dismissed"
27478
27845
  };
27479
- }))();
27846
+ })).immediate();
27480
27847
  }
27481
27848
  function dismissNote(db, noteId, scope) {
27482
27849
  return dismissNotes(db, [noteId], scope)[0]?.outcome === "dismissed";
@@ -27754,7 +28121,7 @@ function insertPrimerCandidates(db, candidates) {
27754
28121
  if (typeof row?.id === "number")
27755
28122
  ids.push(row.id);
27756
28123
  }
27757
- })();
28124
+ }).immediate();
27758
28125
  return ids;
27759
28126
  }
27760
28127
  function updatePrimerCandidateEmbedding(db, candidateId, vector, modelId) {
@@ -27795,7 +28162,7 @@ function createPrimer(db, input) {
27795
28162
  source_candidate_ids, source_candidate_provenance, created_at, updated_at
27796
28163
  ) VALUES (?, ?, ?, ?, ?, 'active', ?, ?, NULL, ?, ?, ?, ?)`).run(input.projectPath, input.question, vectorBlob2(input.questionEmbedding), input.questionEmbeddingModelId ?? null, input.answer ?? "", input.totalSupport, input.lastObservedAt, JSON.stringify(sourceCandidateIds), serializePrimerSourceProvenance(sourceProvenance, sourceCandidateIds), now, now);
27797
28164
  return Number(info.lastInsertRowid);
27798
- })();
28165
+ }).immediate();
27799
28166
  }
27800
28167
  function updatePrimerSupport(db, input) {
27801
28168
  db.transaction(() => {
@@ -27821,7 +28188,7 @@ function updatePrimerSupport(db, input) {
27821
28188
  source_candidate_provenance = ?,
27822
28189
  updated_at = ?
27823
28190
  WHERE id = ?`).run(vectorBlob2(input.questionEmbedding), input.questionEmbeddingModelId ?? null, input.totalSupport, input.lastObservedAt, JSON.stringify(sourceCandidateIds), serializePrimerSourceProvenance(sourceProvenance, sourceCandidateIds), input.now ?? Date.now(), input.primerId);
27824
- })();
28191
+ }).immediate();
27825
28192
  }
27826
28193
  function updatePrimerAnswer(db, primerId, answer, refreshedAt = Date.now()) {
27827
28194
  db.prepare("UPDATE primers SET answer = ?, answer_refreshed_at = ?, updated_at = ? WHERE id = ?").run(answer, refreshedAt, refreshedAt, primerId);
@@ -27990,7 +28357,7 @@ function insertUserMemoryCandidates(db, candidates) {
27990
28357
  for (const c of candidates) {
27991
28358
  stmt.run(c.content, c.sessionId, c.sourceCompartmentStart ?? null, c.sourceCompartmentEnd ?? null, now);
27992
28359
  }
27993
- })();
28360
+ }).immediate();
27994
28361
  logSlowWriteTransaction("user_memory_candidate_insert", transactionStartedAt);
27995
28362
  }
27996
28363
  function getUserMemoryCandidates(db) {
@@ -28049,7 +28416,7 @@ function insertUserMemory(db, content, sourceCandidateIds) {
28049
28416
  (content, status, promoted_at, source_candidate_ids, source_candidate_provenance, created_at, updated_at)
28050
28417
  VALUES (?, 'active', ?, ?, ?, ?, ?)`).run(content, now, JSON.stringify(sourceCandidateIds), serializeUserMemorySourceProvenance(sourceProvenance, sourceCandidateIds), now, now);
28051
28418
  return Number(result.lastInsertRowid);
28052
- })();
28419
+ }).immediate();
28053
28420
  }
28054
28421
  function getActiveUserMemories(db) {
28055
28422
  const rows = db.prepare("SELECT id, content, status, promoted_at, source_candidate_ids, source_candidate_provenance, created_at, updated_at FROM user_memories WHERE status = 'active' ORDER BY promoted_at ASC, id ASC").all();
@@ -28130,7 +28497,9 @@ var OVERFLOW_PATTERNS = [
28130
28497
  /prompt too long; exceeded (?:max )?context length/i,
28131
28498
  /too large for model with \d+ maximum context length/i,
28132
28499
  /model_context_window_exceeded/i,
28133
- /context size has been exceeded/i
28500
+ /context size has been exceeded/i,
28501
+ /prepared prompt exceeds engine max_context/i,
28502
+ /prompt exceeds (?:the )?.{0,32}\bmax_context\b/i
28134
28503
  ];
28135
28504
  var LIMIT_EXTRACTION_PATTERNS = [
28136
28505
  { pattern: /maximum prompt length is (\d+)/i, provenance: "prompt_only" },
@@ -28151,11 +28520,15 @@ var LIMIT_EXTRACTION_PATTERNS = [
28151
28520
  pattern: />\s*(\d+)\s*(?:tokens?\s*)?(?:maximum|max|limit)\b/i,
28152
28521
  provenance: "prompt_only"
28153
28522
  },
28523
+ { pattern: /prepared prompt exceeds engine max_context\s+(\d+)/i, provenance: "unknown" },
28524
+ { pattern: /prompt exceeds (?:the )?.{0,32}\bmax_context\s+(\d+)/i, provenance: "unknown" },
28154
28525
  { pattern: /max(?:imum)?.*context.*?(\d+)/i, provenance: "unknown" }
28155
28526
  ];
28156
28527
  var MIN_PLAUSIBLE_LIMIT = 1024;
28157
28528
  var MAX_PLAUSIBLE_LIMIT = 1e7;
28158
28529
  var THINKING_BINDING_MISMATCH_PATTERN = /bound to a different conversation/i;
28530
+ var THINKING_BINDING_FAILING_PATH_PATTERN = /^\s*(messages\.\d+\.content\.\d+):/;
28531
+ var THINKING_BINDING_FIRST_CHANGED_PATTERN = /first at `?(messages\.\d+\.content\.\d+)`?/;
28159
28532
  function extractErrorMessage(error) {
28160
28533
  if (!error)
28161
28534
  return "";
@@ -28184,29 +28557,6 @@ function extractErrorMessage(error) {
28184
28557
  }
28185
28558
  return String(error);
28186
28559
  }
28187
- function extractThinkingBindingMessageId(error) {
28188
- if (!error || typeof error !== "object")
28189
- return;
28190
- const seen = new Set;
28191
- const queue = [error];
28192
- while (queue.length > 0) {
28193
- const current = queue.shift();
28194
- if (!current || seen.has(current))
28195
- continue;
28196
- seen.add(current);
28197
- const record = current;
28198
- for (const key of ["message_id", "messageID", "messageId"]) {
28199
- const value = record[key];
28200
- if (typeof value === "string" && value.length > 0)
28201
- return value;
28202
- }
28203
- for (const value of Object.values(record)) {
28204
- if (value && typeof value === "object")
28205
- queue.push(value);
28206
- }
28207
- }
28208
- return;
28209
- }
28210
28560
  function extractExplicitHttpStatus(error) {
28211
28561
  if (!error || typeof error !== "object")
28212
28562
  return;
@@ -28236,13 +28586,20 @@ function detectThinkingBindingMismatch(error) {
28236
28586
  if (explicitStatus !== undefined && explicitStatus !== 400 || !THINKING_BINDING_MISMATCH_PATTERN.test(message)) {
28237
28587
  return { isBindingMismatch: false };
28238
28588
  }
28239
- const messageId = extractThinkingBindingMessageId(error);
28589
+ const failingBlockPath = THINKING_BINDING_FAILING_PATH_PATTERN.exec(message)?.[1];
28590
+ const firstChangedPath = THINKING_BINDING_FIRST_CHANGED_PATTERN.exec(message)?.[1];
28240
28591
  return {
28241
28592
  isBindingMismatch: true,
28242
28593
  matchedPattern: "bound to a different conversation",
28243
- ...messageId ? { messageId } : {}
28594
+ ...failingBlockPath ? { failingBlockPath } : {},
28595
+ ...firstChangedPath ? { firstChangedPath } : {}
28244
28596
  };
28245
28597
  }
28598
+ function isPrefixBoundThinkingModel(providerID, modelID) {
28599
+ if (providerID?.toLowerCase() !== "anthropic" || !modelID)
28600
+ return false;
28601
+ return isFable51ThinkingBindingModel(providerID, modelID) || /(?:^|[-_.])opus[-_.]?5[-_.]5(?:$|[-_.])/i.test(modelID);
28602
+ }
28246
28603
  function isFable51ThinkingBindingModel(providerID, modelID) {
28247
28604
  if (providerID?.toLowerCase() !== "anthropic" || !modelID)
28248
28605
  return false;
@@ -28314,6 +28671,203 @@ function parseReportedLimit(message) {
28314
28671
  return;
28315
28672
  }
28316
28673
 
28674
+ // src/agents/dreamer.ts
28675
+ var DREAMER_AGENT = "dreamer";
28676
+ var DREAMER_RETROSPECTIVE_AGENT = "dreamer-retrospective";
28677
+ var DREAMER_PRIMER_INVESTIGATOR_AGENT = "dreamer-primer-investigator";
28678
+ var DREAMER_MEMORY_MAPPER_AGENT = "dreamer-memory-mapper";
28679
+ var DREAMER_CLASSIFIER_AGENT = "dreamer-classifier";
28680
+ var DREAMER_DOCS_AGENT = "dreamer-docs";
28681
+ var DREAMER_REVIEWER_AGENT = "dreamer-reviewer";
28682
+
28683
+ // src/hooks/magic-context/compartment-runner-types.ts
28684
+ class HiddenCompletionRefusal extends Error {
28685
+ code;
28686
+ terminal;
28687
+ constructor(code, message, terminal = false) {
28688
+ super(`${code}: ${message}`);
28689
+ this.code = code;
28690
+ this.terminal = terminal;
28691
+ this.name = "HiddenCompletionRefusal";
28692
+ }
28693
+ }
28694
+
28695
+ // src/v2/hooks/hidden-child.ts
28696
+ var HIDDEN_HISTORIAN_AGENT = "historian";
28697
+ var HIDDEN_DREAMER_AGENT = "dreamer-classifier";
28698
+ var HIDDEN_CURATE_AGENT = DREAMER_AGENT;
28699
+ var READ_TOOLS = ["read", "grep", "glob"];
28700
+ var AGENT_TOOLS = {
28701
+ [HIDDEN_HISTORIAN_AGENT]: [],
28702
+ [HIDDEN_DREAMER_AGENT]: [],
28703
+ [HIDDEN_CURATE_AGENT]: ["ctx_memory", "ctx_memory_list"],
28704
+ [DREAMER_MEMORY_MAPPER_AGENT]: READ_TOOLS,
28705
+ [DREAMER_PRIMER_INVESTIGATOR_AGENT]: [...READ_TOOLS, "ctx_search"],
28706
+ [DREAMER_RETROSPECTIVE_AGENT]: ["ctx_search"]
28707
+ };
28708
+ var AGENT_STEPS = {
28709
+ [HIDDEN_CURATE_AGENT]: 150,
28710
+ [DREAMER_MEMORY_MAPPER_AGENT]: 60,
28711
+ [DREAMER_DOCS_AGENT]: 60,
28712
+ [DREAMER_PRIMER_INVESTIGATOR_AGENT]: 40,
28713
+ [DREAMER_RETROSPECTIVE_AGENT]: 40
28714
+ };
28715
+ function hiddenAgentFor(identity) {
28716
+ if (identity.kind === "dreamer-task" && identity.agent === DREAMER_DOCS_AGENT)
28717
+ return DREAMER_MEMORY_MAPPER_AGENT;
28718
+ return identity.kind === "dreamer-task" && AGENT_TOOLS[identity.agent] ? identity.agent : identity.kind === "dreamer-task" ? HIDDEN_DREAMER_AGENT : HIDDEN_HISTORIAN_AGENT;
28719
+ }
28720
+ function hiddenToolLoop(identity) {
28721
+ return identity.kind === "dreamer-task" && AGENT_STEPS[identity.agent] !== undefined;
28722
+ }
28723
+ async function registerHiddenChildAgents(agent) {
28724
+ await agent.transform((editor) => {
28725
+ for (const id of Object.keys(AGENT_TOOLS)) {
28726
+ editor.update(id, (config) => {
28727
+ config.system = "Magic Context hidden completion carrier.";
28728
+ config.description = "Internal Magic Context hidden completion carrier.";
28729
+ config.mode = "primary";
28730
+ config.hidden = true;
28731
+ config.request.settings = {};
28732
+ config.request.headers = {};
28733
+ config.request.body = {};
28734
+ config.steps = AGENT_STEPS[id];
28735
+ config.permissions = [
28736
+ { action: "*", resource: "*", effect: "deny" },
28737
+ ...(AGENT_TOOLS[id] ?? []).map((tool) => ({
28738
+ action: tool,
28739
+ resource: "*",
28740
+ effect: "allow"
28741
+ }))
28742
+ ];
28743
+ });
28744
+ }
28745
+ });
28746
+ }
28747
+
28748
+ class HiddenAgentStepLimit extends Error {
28749
+ agent;
28750
+ cap;
28751
+ constructor(agent, cap) {
28752
+ super(`Hidden agent ${agent} exceeded its ${cap}-step limit`);
28753
+ this.name = "HiddenAgentStepLimit";
28754
+ this.agent = agent;
28755
+ this.cap = cap;
28756
+ }
28757
+ }
28758
+ function newestUserText(draft) {
28759
+ const message = draft.messages.at(-1);
28760
+ if (!message || message.role !== undefined && message.role !== "user")
28761
+ return;
28762
+ const content = message.content;
28763
+ if (typeof content === "string" && content.length > 0)
28764
+ return content;
28765
+ const parts = Array.isArray(content) ? content : Array.isArray(message.parts) ? message.parts : [];
28766
+ for (const part of parts) {
28767
+ if (!part || typeof part !== "object")
28768
+ continue;
28769
+ const record = part;
28770
+ if (typeof record.text !== "string" || record.text.length === 0)
28771
+ continue;
28772
+ if (record.type === undefined || record.type === "text" || record.type === "input_text") {
28773
+ return record.text;
28774
+ }
28775
+ }
28776
+ return;
28777
+ }
28778
+ function authoredOptions(attempt) {
28779
+ const cap = attempt.identity.maxOutputTokens;
28780
+ const temperature = attempt.request.body.temperature;
28781
+ return {
28782
+ ...typeof cap === "number" && Number.isFinite(cap) && cap > 0 ? { maxOutputTokens: cap, maxTokens: cap } : {},
28783
+ ...typeof temperature === "number" && Number.isFinite(temperature) ? { temperature } : {}
28784
+ };
28785
+ }
28786
+ function calibratedParts(attempt) {
28787
+ const parts = attempt.request.body.parts;
28788
+ if (!Array.isArray(parts) || parts.length === 0 || parts.some((part) => !part || typeof part !== "object" || part.type !== "text" || typeof part.text !== "string")) {
28789
+ throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Hidden completion accepts text-only calibrated prompts", true);
28790
+ }
28791
+ return parts.map((part) => ({ type: "text", text: part.text }));
28792
+ }
28793
+
28794
+ class HiddenChildHook {
28795
+ childIDs = new Set;
28796
+ attempts = new Map;
28797
+ active = new Map;
28798
+ registerChild(sessionID) {
28799
+ this.childIDs.add(sessionID);
28800
+ }
28801
+ registerAttempt(marker, attempt) {
28802
+ this.registerChild(attempt.childSessionId);
28803
+ attempt.marker = marker;
28804
+ this.attempts.set(marker, attempt);
28805
+ }
28806
+ releaseAttempt(marker) {
28807
+ const attempt = this.attempts.get(marker);
28808
+ this.attempts.delete(marker);
28809
+ if (attempt && this.active.get(attempt.childSessionId) === attempt) {
28810
+ this.active.delete(attempt.childSessionId);
28811
+ }
28812
+ }
28813
+ owns(sessionID) {
28814
+ return this.childIDs.has(sessionID);
28815
+ }
28816
+ apply(draft) {
28817
+ if (!this.owns(draft.sessionID))
28818
+ return false;
28819
+ const raw = newestUserText(draft);
28820
+ const stripped = raw === undefined ? undefined : stripWellFormedLeadingTagPrefix(raw);
28821
+ const attempt = (raw !== undefined ? this.attempts.get(raw) : undefined) ?? (stripped && stripped !== raw ? this.attempts.get(stripped) : undefined);
28822
+ const current = this.active.get(draft.sessionID);
28823
+ const selected = attempt ?? current;
28824
+ if (!selected || selected.childSessionId !== draft.sessionID || attempt && current && current !== attempt) {
28825
+ throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Refusing an unregistered prompt on a Magic Context hidden-run session", true);
28826
+ }
28827
+ if (selected.request.signal?.aborted) {
28828
+ throw new Error("Hidden completion prompt aborted");
28829
+ }
28830
+ if (!selected.shaped) {
28831
+ if (!attempt)
28832
+ throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Hidden child first step requires a registered marker", true);
28833
+ this.active.set(draft.sessionID, selected);
28834
+ }
28835
+ const steps = (selected.steps ?? 0) + 1;
28836
+ const cap = AGENT_STEPS[selected.identity.agent];
28837
+ if (cap !== undefined && steps > cap) {
28838
+ selected.stepLimit = new HiddenAgentStepLimit(selected.identity.agent, cap);
28839
+ throw selected.stepLimit;
28840
+ }
28841
+ selected.steps = steps;
28842
+ const system = typeof selected.request.body.system === "string" ? selected.request.body.system : selected.identity.system;
28843
+ draft.system = [{ type: "text", text: system }];
28844
+ if (!selected.shaped) {
28845
+ draft.messages = [{ role: "user", content: calibratedParts(selected) }];
28846
+ } else {
28847
+ let start = -1;
28848
+ draft.messages.forEach((message, index) => {
28849
+ const text = newestUserText({ ...draft, messages: [message] });
28850
+ if (text !== undefined && stripWellFormedLeadingTagPrefix(text) === selected.marker)
28851
+ start = index;
28852
+ });
28853
+ const first = draft.messages[start];
28854
+ if (!first) {
28855
+ throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Hidden child history does not contain this run's registered marker", true);
28856
+ }
28857
+ draft.messages = [
28858
+ { ...first, content: calibratedParts(selected) },
28859
+ ...draft.messages.slice(start + 1)
28860
+ ];
28861
+ }
28862
+ draft.options = authoredOptions(selected);
28863
+ const allowed = AGENT_TOOLS[hiddenAgentFor(selected.identity)] ?? [];
28864
+ draft.tools = Object.fromEntries(allowed.flatMap((id) => draft.tools[id] ? [[id, draft.tools[id]]] : []));
28865
+ selected.observedMessages = draft.messages;
28866
+ selected.shaped = true;
28867
+ return true;
28868
+ }
28869
+ }
28870
+
28317
28871
  // src/shared/assistant-message-extractor.ts
28318
28872
  function asSessionMessage(value) {
28319
28873
  if (!isRecord(value))
@@ -28412,6 +28966,14 @@ function copyPromptArgs(args, body) {
28412
28966
  return { ...args, body: { ...body } };
28413
28967
  }
28414
28968
  var promptFailureDetails = new WeakMap;
28969
+ function isHostTimeoutError(error) {
28970
+ return error !== null && typeof error === "object" && error.name === "TimeoutError";
28971
+ }
28972
+ function isPromptTimeoutError(error) {
28973
+ if (isHostTimeoutError(error))
28974
+ return true;
28975
+ return error instanceof Error && /^prompt timed out after \d+ms$/.test(error.message);
28976
+ }
28415
28977
  function getPromptFailureDetail(error) {
28416
28978
  return error !== null && typeof error === "object" ? promptFailureDetails.get(error) ?? null : null;
28417
28979
  }
@@ -28468,9 +29030,13 @@ function parseModelSuggestion(error) {
28468
29030
  suggestion: suggestionMatch[1].trim()
28469
29031
  };
28470
29032
  }
29033
+ function externalAbortMessage(signal) {
29034
+ const reason = signal.reason;
29035
+ return `prompt aborted by external signal${reason instanceof Error && /^lease_(?:lost|expired):/.test(reason.message) ? `: ${reason.message}` : ""}`;
29036
+ }
28471
29037
  async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
28472
29038
  if (signal?.aborted) {
28473
- throw new Error("prompt aborted by external signal");
29039
+ throw new Error(externalAbortMessage(signal));
28474
29040
  }
28475
29041
  const controller = new AbortController;
28476
29042
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
@@ -28490,7 +29056,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
28490
29056
  if (!transport || transport.childSessionId) {
28491
29057
  await abortChildRun(client, transport?.childSessionId ?? args.path.id);
28492
29058
  }
28493
- throw new Error("prompt aborted by external signal");
29059
+ throw new Error(externalAbortMessage(signal));
28494
29060
  }
28495
29061
  if (controller.signal.aborted) {
28496
29062
  if (!transport || transport.childSessionId) {
@@ -28498,6 +29064,11 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
28498
29064
  }
28499
29065
  throw new Error(`prompt timed out after ${timeoutMs}ms`);
28500
29066
  }
29067
+ if (isHostTimeoutError(error)) {
29068
+ if (!transport || transport.childSessionId) {
29069
+ await abortChildRun(client, transport?.childSessionId ?? args.path.id);
29070
+ }
29071
+ }
28501
29072
  throw error;
28502
29073
  } finally {
28503
29074
  clearTimeout(timeout);
@@ -28507,7 +29078,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
28507
29078
  if (!transport || transport.childSessionId) {
28508
29079
  await abortChildRun(client, transport?.childSessionId ?? args.path.id);
28509
29080
  }
28510
- throw new Error(signal?.aborted ? "prompt aborted by external signal" : `prompt timed out after ${timeoutMs}ms`);
29081
+ throw new Error(signal?.aborted ? externalAbortMessage(signal) : `prompt timed out after ${timeoutMs}ms`);
28511
29082
  }
28512
29083
  }
28513
29084
  async function abortChildRun(client, sessionId) {
@@ -28523,7 +29094,7 @@ async function abortChildRun(client, sessionId) {
28523
29094
  }
28524
29095
  }
28525
29096
  function isNonRetryable(error, externalSignal) {
28526
- if (externalSignal?.aborted)
29097
+ if (externalSignal?.aborted || error instanceof HiddenAgentStepLimit)
28527
29098
  return true;
28528
29099
  if (error instanceof Error) {
28529
29100
  if (error.name === "AbortError")
@@ -28533,6 +29104,8 @@ function isNonRetryable(error, externalSignal) {
28533
29104
  if (/^prompt timed out after \d+ms$/.test(error.message))
28534
29105
  return true;
28535
29106
  }
29107
+ if (isHostTimeoutError(error))
29108
+ return true;
28536
29109
  if (detectOverflow(error).isOverflow)
28537
29110
  return true;
28538
29111
  return false;
@@ -28545,11 +29118,14 @@ function shortErr(error) {
28545
29118
  }
28546
29119
  function classifyPromptFailure(error, phase, externalSignal) {
28547
29120
  const message = extractMessage(error);
29121
+ if (error instanceof HiddenAgentStepLimit)
29122
+ return "step_limit";
28548
29123
  if (externalSignal?.aborted || message === "prompt aborted by external signal") {
28549
29124
  return "child_aborted";
28550
29125
  }
28551
- if (/^prompt timed out after \d+ms$/.test(message))
29126
+ if (/^prompt timed out after \d+ms$/.test(message) || isHostTimeoutError(error)) {
28552
29127
  return "provider_timeout";
29128
+ }
28553
29129
  if (phase === "validation") {
28554
29130
  if (/returned no (?:assistant )?output|no assistant output/i.test(message)) {
28555
29131
  return "empty_completion";
@@ -28766,7 +29342,10 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
28766
29342
  }
28767
29343
  }
28768
29344
  log(`[${callContext}] all models exhausted; tried: ${failedAttempts.map((failure) => failure.attempt.label).join(", ")}; original error: ${shortErr(firstError)}; last error: ${shortErr(lastError)}`);
28769
- throwWithPromptFailure(firstError ?? lastError ?? new Error("All fallback models failed validation"), failedAttempts, args, timeoutMs, options.transport);
29345
+ const cause = lastError ?? firstError;
29346
+ const exhausted = cause instanceof Error ? cause : new Error(String(cause ?? "All fallback models failed validation"));
29347
+ exhausted.message = `All models exhausted (${failedAttempts.map((failure) => failure.attempt.label).join(", ")}): ${exhausted.message}`;
29348
+ throwWithPromptFailure(exhausted, failedAttempts, args, timeoutMs, options.transport);
28770
29349
  }
28771
29350
  // src/shared/normalize-sdk-response.ts
28772
29351
  function normalizeSDKResponse(response, fallback, options) {
@@ -28791,6 +29370,149 @@ function normalizeSDKResponse(response, fallback, options) {
28791
29370
  }
28792
29371
  return fallback;
28793
29372
  }
29373
+ // src/shared/prompt-async-transport.ts
29374
+ var DEFAULT_POLL_INTERVAL_MS = 1000;
29375
+ var DEFAULT_START_GRACE_MS = 30000;
29376
+ var MESSAGE_WINDOW = 20;
29377
+ function sessionApi(client) {
29378
+ return client?.session;
29379
+ }
29380
+ function supportsPromptAsync(client) {
29381
+ const session = sessionApi(client);
29382
+ return typeof session?.promptAsync === "function" && typeof session?.status === "function" && typeof session?.messages === "function";
29383
+ }
29384
+ function createPromptAsyncTransport(client, childSessionId, options = {}) {
29385
+ if (!supportsPromptAsync(client))
29386
+ return;
29387
+ return Object.assign((request) => promptAsyncAndWaitForIdle(client, request, options), { childSessionId });
29388
+ }
29389
+ function infoOf(message) {
29390
+ const info = message?.info;
29391
+ return info && typeof info === "object" ? info : {};
29392
+ }
29393
+ function messageId(message) {
29394
+ const id = infoOf(message).id;
29395
+ return typeof id === "string" ? id : null;
29396
+ }
29397
+ function isSettledAssistant(message) {
29398
+ const info = infoOf(message);
29399
+ if (info.role !== "assistant")
29400
+ return false;
29401
+ return info.time?.completed != null || info.error != null || info.finish != null;
29402
+ }
29403
+ function unwrapData(response) {
29404
+ if (response && typeof response === "object" && "data" in response) {
29405
+ return response.data;
29406
+ }
29407
+ return response;
29408
+ }
29409
+ function describeRejection(error) {
29410
+ if (error instanceof Error)
29411
+ return error.message;
29412
+ try {
29413
+ return JSON.stringify(error);
29414
+ } catch {
29415
+ return String(error);
29416
+ }
29417
+ }
29418
+ function abortError(signal) {
29419
+ return signal.reason ?? new Error("prompt_async wait aborted");
29420
+ }
29421
+ function sleep(ms, signal) {
29422
+ return new Promise((resolve, reject) => {
29423
+ if (signal?.aborted) {
29424
+ reject(abortError(signal));
29425
+ return;
29426
+ }
29427
+ const onAbort = () => {
29428
+ clearTimeout(timer);
29429
+ reject(abortError(signal));
29430
+ };
29431
+ const timer = setTimeout(() => {
29432
+ signal?.removeEventListener("abort", onAbort);
29433
+ resolve();
29434
+ }, ms);
29435
+ signal?.addEventListener("abort", onAbort, { once: true });
29436
+ });
29437
+ }
29438
+ async function readMessages(session, sessionId, directory, signal) {
29439
+ const response = await session.messages?.({
29440
+ path: { id: sessionId },
29441
+ query: { ...directory ? { directory } : {}, limit: MESSAGE_WINDOW },
29442
+ ...signal ? { signal } : {}
29443
+ });
29444
+ const data = unwrapData(response);
29445
+ return Array.isArray(data) ? data : [];
29446
+ }
29447
+ async function readStatus(session, sessionId, directory, signal) {
29448
+ try {
29449
+ const response = await session.status?.({
29450
+ ...directory ? { query: { directory } } : {},
29451
+ ...signal ? { signal } : {}
29452
+ });
29453
+ if (response && typeof response === "object" && "error" in response) {
29454
+ if (response.error)
29455
+ return null;
29456
+ }
29457
+ const data = unwrapData(response);
29458
+ if (!data || typeof data !== "object")
29459
+ return null;
29460
+ const entry = data[sessionId];
29461
+ const type = entry?.type;
29462
+ return typeof type === "string" ? type : "idle";
29463
+ } catch (error) {
29464
+ if (signal?.aborted)
29465
+ throw error;
29466
+ return null;
29467
+ }
29468
+ }
29469
+ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
29470
+ const session = sessionApi(client);
29471
+ if (!session || !supportsPromptAsync(client)) {
29472
+ throw new Error("prompt_async transport is unavailable on this client");
29473
+ }
29474
+ const sessionId = request.path.id;
29475
+ const directory = request.query?.directory;
29476
+ const dir = typeof directory === "string" ? directory : undefined;
29477
+ const signal = request.signal;
29478
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
29479
+ const startGraceMs = options.startGraceMs ?? DEFAULT_START_GRACE_MS;
29480
+ const baseline = new Set((await readMessages(session, sessionId, dir, signal)).map(messageId).filter((id) => id !== null));
29481
+ const sent = await session.promptAsync?.(request);
29482
+ if (sent && typeof sent === "object" && "error" in sent) {
29483
+ const rejection = sent.error;
29484
+ if (rejection)
29485
+ throw new Error(`prompt_async was rejected: ${describeRejection(rejection)}`);
29486
+ }
29487
+ const sentAt = Date.now();
29488
+ let sawBusy = false;
29489
+ for (;; ) {
29490
+ await sleep(pollIntervalMs, signal);
29491
+ const status = await readStatus(session, sessionId, dir, signal);
29492
+ if (status === "busy" || status === "retry") {
29493
+ sawBusy = true;
29494
+ continue;
29495
+ }
29496
+ if (status === null)
29497
+ continue;
29498
+ const messages = await readMessages(session, sessionId, dir, signal);
29499
+ const last = messages.at(-1);
29500
+ const lastId = messageId(last);
29501
+ if (last && lastId !== null && !baseline.has(lastId) && isSettledAssistant(last))
29502
+ return;
29503
+ const fresh = messages.some((message) => {
29504
+ const id = messageId(message);
29505
+ return id !== null && !baseline.has(id);
29506
+ });
29507
+ if (sawBusy && fresh)
29508
+ return;
29509
+ if (Date.now() - sentAt >= startGraceMs) {
29510
+ if (fresh)
29511
+ return;
29512
+ throw new Error(`prompt_async did not start a run in child session ${sessionId} within ${startGraceMs}ms`);
29513
+ }
29514
+ }
29515
+ }
28794
29516
  // src/shared/prompt-surface-runtime.ts
28795
29517
  import { existsSync as existsSync6, readFileSync as readFileSync5, statSync as statSync7 } from "node:fs";
28796
29518
  import { dirname as dirname4, isAbsolute as isAbsolute2, resolve as resolve2 } from "node:path";
@@ -29628,7 +30350,7 @@ function injectCompactionMarker(args) {
29628
30350
  time_created = excluded.time_created,
29629
30351
  time_updated = excluded.time_updated,
29630
30352
  data = excluded.data`).run(summaryPartId, summaryMsgId, args.sessionId, boundaryTime + 1, boundaryTime + 1, JSON.stringify({ type: "text", text: args.summaryText }));
29631
- })();
30353
+ }).immediate();
29632
30354
  log(`[magic-context] compaction-marker: injected boundary at user msg ${boundary.id} (ordinal ~${args.endOrdinal}), summary msg ${summaryMsgId}`);
29633
30355
  return {
29634
30356
  boundaryMessageId: boundary.id,
@@ -29721,7 +30443,7 @@ function removeForeignCompactionMarker(sessionId, marker, protectedSummaryMessag
29721
30443
  deleteMessage.run(sessionId, summaryMessageId);
29722
30444
  }
29723
30445
  db.prepare("DELETE FROM part WHERE session_id = ? AND id = ?").run(sessionId, marker.compactionPartId);
29724
- })();
30446
+ }).immediate();
29725
30447
  return true;
29726
30448
  } catch (error) {
29727
30449
  log(`[magic-context] compaction-marker: foreign-marker removal failed (${sessionId}, part ${marker.compactionPartId}): ${error instanceof Error ? error.message : String(error)}`);
@@ -29863,7 +30585,7 @@ function removeMcOwnedCompactionMarkers(sessionId, summaryText) {
29863
30585
  changed += deletePart.run(sessionId, partId).changes;
29864
30586
  }
29865
30587
  return changed;
29866
- })();
30588
+ }).immediate();
29867
30589
  if (rows > 0 || summaryIds.size > 0 || mcPartIds.length > 0) {
29868
30590
  removedLineages += 1;
29869
30591
  removedRows += rows;
@@ -29876,7 +30598,7 @@ function removeMcOwnedCompactionMarkers(sessionId, summaryText) {
29876
30598
  if (survivingPartsReferenceDeletion || messageFieldReferencesDeletion) {
29877
30599
  retainedLineages += 1;
29878
30600
  } else {
29879
- const rows = db.transaction(() => deleteSummaries(orphanSummaryIds))();
30601
+ const rows = db.transaction(() => deleteSummaries(orphanSummaryIds)).immediate();
29880
30602
  removedLineages += 1;
29881
30603
  removedRows += rows;
29882
30604
  }
@@ -29898,7 +30620,7 @@ function removeCompactionMarker(state) {
29898
30620
  db.prepare("DELETE FROM part WHERE id = ?").run(state.summaryPartId);
29899
30621
  db.prepare("DELETE FROM message WHERE id = ?").run(state.summaryMessageId);
29900
30622
  db.prepare("DELETE FROM part WHERE id = ?").run(state.compactionPartId);
29901
- })();
30623
+ }).immediate();
29902
30624
  return true;
29903
30625
  } catch (error) {
29904
30626
  log(`[magic-context] compaction-marker: removal failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -29920,7 +30642,7 @@ function persistMarkerStateAndDropReplacedTag(db, sessionId, state, replacedSumm
29920
30642
  if (replacedSummaryMessageId !== null) {
29921
30643
  dropMarkerSummaryTag(db, sessionId, replacedSummaryMessageId);
29922
30644
  }
29923
- })();
30645
+ }).immediate();
29924
30646
  logSlowWriteTransaction("marker-drain", transactionStartedAt);
29925
30647
  }
29926
30648
  function validatePendingTarget(db, sessionId, pending) {
@@ -31151,6 +31873,9 @@ function failedInvocationStatus(error) {
31151
31873
  const message = describeError(error).brief;
31152
31874
  if (/timed out after \d+ms|prompt timed out/i.test(message))
31153
31875
  return "timed_out";
31876
+ if (error !== null && typeof error === "object" && error.name === "TimeoutError") {
31877
+ return "timed_out";
31878
+ }
31154
31879
  if (/length-capped|no (?:assistant )?output|empty (?:assistant )?(?:output|text)/i.test(message)) {
31155
31880
  return "empty";
31156
31881
  }
@@ -31349,18 +32074,6 @@ async function createChildSessionWithFence(args) {
31349
32074
  });
31350
32075
  }
31351
32076
 
31352
- // src/hooks/magic-context/compartment-runner-types.ts
31353
- class HiddenCompletionRefusal extends Error {
31354
- code;
31355
- terminal;
31356
- constructor(code, message, terminal = false) {
31357
- super(`${code}: ${message}`);
31358
- this.code = code;
31359
- this.terminal = terminal;
31360
- this.name = "HiddenCompletionRefusal";
31361
- }
31362
- }
31363
-
31364
32077
  // src/hooks/magic-context/compartment-runner-mapping.ts
31365
32078
  function tierFieldsOf(c) {
31366
32079
  return {
@@ -31448,7 +32161,7 @@ function shouldDiscardLastHistorianCompartment(compartments, chunk) {
31448
32161
  function validateHistorianOutput(text, sessionId, chunk, _priorCompartments, sequenceOffset) {
31449
32162
  const parseStarted = startHistorianPublishStage(sessionId, "parse", `response_chars=${text.length}`);
31450
32163
  const parsed = parseCompartmentOutput(text);
31451
- finishHistorianPublishStage(sessionId, "parse", parseStarted, "completed", `compartments=${parsed.compartments.length}`);
32164
+ finishHistorianPublishStage(sessionId, "parse", parseStarted, "completed", `compartments=${parsed.compartments.length} dropped_fact_blocks=${parsed.droppedFactBlocks} dropped_facts=${parsed.droppedFacts}`);
31452
32165
  const validationStarted = startHistorianPublishStage(sessionId, "validate");
31453
32166
  const finish = (result) => {
31454
32167
  finishHistorianPublishStage(sessionId, "validate", validationStarted, result.ok ? "completed" : "failed", result.ok ? `compartments=${result.compartments.length}` : `reason=${JSON.stringify(result.error)}`);
@@ -31487,6 +32200,7 @@ function validateHistorianOutput(text, sessionId, chunk, _priorCompartments, seq
31487
32200
  ok: true,
31488
32201
  compartments: mapped.compartments,
31489
32202
  facts: parsed.facts,
32203
+ ...parsed.droppedFactBlocks > 0 ? { droppedFactBlocks: parsed.droppedFactBlocks, droppedFacts: parsed.droppedFacts } : {},
31490
32204
  userObservations: parsed.userObservations.length > 0 ? parsed.userObservations : undefined,
31491
32205
  primerCandidates: parsed.primerCandidates.length > 0 ? parsed.primerCandidates.slice(0, 1) : undefined,
31492
32206
  events: parsed.events.length > 0 ? parsed.events : undefined
@@ -31498,6 +32212,14 @@ function buildHistorianFailureNotice(failureCount, _lastError) {
31498
32212
  return [heading, "", renderUserFacingFailure("historian_unavailable")].join(`
31499
32213
  `);
31500
32214
  }
32215
+ function buildStoredCompartmentsInvalidNotice() {
32216
+ return [
32217
+ "## Magic Context — History compression",
32218
+ "",
32219
+ renderUserFacingFailure("historian_saved_history_misaligned")
32220
+ ].join(`
32221
+ `);
32222
+ }
31501
32223
  function buildHistorianRepairPrompt(originalPrompt, previousOutput, validationError, language) {
31502
32224
  const prompt = [
31503
32225
  originalPrompt,
@@ -31739,6 +32461,7 @@ function resolveHiddenCompletionExecutor(executor, client, db, directory, entryP
31739
32461
  return createV1HiddenCompletionExecutor(client, db, directory);
31740
32462
  }
31741
32463
  function createV1HiddenCompletionExecutor(client, db, directory) {
32464
+ const asyncChildren = new Set;
31742
32465
  return {
31743
32466
  capabilities: { tools: true, harness: "opencode" },
31744
32467
  async open(run) {
@@ -31755,11 +32478,17 @@ function createV1HiddenCompletionExecutor(client, db, directory) {
31755
32478
  preferResponseOnMissingData: true
31756
32479
  });
31757
32480
  const id = typeof created?.id === "string" ? created.id : "";
32481
+ if (id && run.kind === "dreamer-task")
32482
+ asyncChildren.add(id);
31758
32483
  return { id, childSessionId: id || undefined };
31759
32484
  },
31760
- async attempt(_handle, request) {
32485
+ async attempt(handle, request) {
31761
32486
  if (!client)
31762
32487
  throw new Error("Hidden completion client is unavailable");
32488
+ if (asyncChildren.has(handle.id) && supportsPromptAsync(client)) {
32489
+ await promptAsyncAndWaitForIdle(client, request);
32490
+ return;
32491
+ }
31763
32492
  await client.session.prompt(request);
31764
32493
  },
31765
32494
  async collect(handle, limit) {
@@ -31787,6 +32516,8 @@ function createV1HiddenCompletionExecutor(client, db, directory) {
31787
32516
  };
31788
32517
  },
31789
32518
  async close(handle, settlement) {
32519
+ if (handle?.id)
32520
+ asyncChildren.delete(handle.id);
31790
32521
  if (!client)
31791
32522
  return;
31792
32523
  await teardownChildSession({
@@ -31798,6 +32529,9 @@ function createV1HiddenCompletionExecutor(client, db, directory) {
31798
32529
  }
31799
32530
  };
31800
32531
  }
32532
+ function historianReasoningBudgetDiagnostic(outputTokens) {
32533
+ return `historian ran out of output budget while reasoning (length-capped at ${outputTokens} tokens, no text) — set historian.maxTokens or route historian.model to a low-reasoning lane/variant`;
32534
+ }
31801
32535
  async function runValidatedHistorianPass(args) {
31802
32536
  const firstRun = await runHistorianPrompt({
31803
32537
  ...args,
@@ -32024,14 +32758,14 @@ async function runHistorianPrompt(args) {
32024
32758
  }
32025
32759
  const backoffMs = getHistorianRetryBackoffMs(retryIndex);
32026
32760
  sessionLog(parentSessionId, `historian retry ${retryIndex + 1}/${MAX_HISTORIAN_RETRIES} after ${backoffMs}ms: ${errorMsg}`);
32027
- await sleep(backoffMs);
32761
+ await sleep2(backoffMs);
32028
32762
  }
32029
32763
  }
32030
32764
  completion = await executor.collect(handle, 50);
32031
32765
  const lengthCapped = completion.lengthCapped;
32032
32766
  const textResult = completion.text;
32033
32767
  const reasoningResult = textResult ? null : completion.reasoning;
32034
- const emptyError = !textResult && reasoningResult && lengthCapped ? `historian output length-capped at ${completion.usage.output} tokens (all reasoning, no text) — set historian.maxTokens or route historian.model to a low-reasoning lane/variant` : !textResult && !reasoningResult ? "Historian returned no assistant output." : !textResult ? "Historian returned reasoning but no assistant text." : lengthCapped ? "Historian returned length-capped output." : null;
32768
+ const emptyError = !textResult && reasoningResult && lengthCapped ? historianReasoningBudgetDiagnostic(completion.usage.output) : !textResult && !reasoningResult ? "Historian returned no assistant output." : !textResult ? "Historian returned reasoning but no assistant text." : lengthCapped ? "Historian returned length-capped output." : null;
32035
32769
  const invocationId = recordInvocation({
32036
32770
  status: emptyError ? "empty" : "completed",
32037
32771
  messages: completion.messages,
@@ -32161,7 +32895,7 @@ function isTransientHistorianPromptError(message) {
32161
32895
  "overloaded"
32162
32896
  ].some((token) => normalized.includes(token));
32163
32897
  }
32164
- function sleep(ms) {
32898
+ function sleep2(ms) {
32165
32899
  return new Promise((resolve) => {
32166
32900
  setTimeout(resolve, ms);
32167
32901
  });
@@ -34123,6 +34857,10 @@ function mustMaterialize(args) {
34123
34857
  if (hard.cacheExpired && hard.lastResponseTime > 0 && hard.lastResponseTime > (args.state.cachedM0MaterializedAt ?? 0)) {
34124
34858
  return withToolSetHashComparison({ value: true, reason: "ttl_idle" });
34125
34859
  }
34860
+ const hostCompaction = hard.hostCompaction;
34861
+ if (hostCompaction !== undefined && hostCompaction.completedAt > (args.state.cachedM0MaterializedAt ?? 0)) {
34862
+ return withToolSetHashComparison({ value: true, reason: "host_compaction" });
34863
+ }
34126
34864
  if (current.projectIdentity !== null) {
34127
34865
  const cachedProjectIdentity = args.state.cachedM0ProjectIdentity ?? null;
34128
34866
  if (cachedProjectIdentity === null) {
@@ -34640,6 +35378,11 @@ function materializeM0(options) {
34640
35378
  options.db.prepare("UPDATE session_meta SET memory_block_count = ?, memory_block_ids = ? WHERE session_id = ?").run(visibleMemoryIds.length, JSON.stringify(visibleMemoryIds), options.sessionId);
34641
35379
  const baselineEndMessageId = lastCompartmentBoundaryId(compartments);
34642
35380
  options.db.prepare("UPDATE session_meta SET cached_m0_last_baseline_end_message_id = ? WHERE session_id = ?").run(baselineEndMessageId, options.sessionId);
35381
+ options.onFoldCommit?.(options.db, {
35382
+ m0Bytes,
35383
+ m1Bytes,
35384
+ muralDataUrl: frozenMuralDataUrl ?? null
35385
+ });
34643
35386
  options.db.exec("COMMIT");
34644
35387
  logSlowWriteTransaction("opencode_materialize_cache", transactionStartedAt);
34645
35388
  options.state.cachedM0MuralDataUrl = frozenMuralDataUrl;
@@ -34819,6 +35562,15 @@ function parseMemoryBlockIds(raw) {
34819
35562
  return [];
34820
35563
  }
34821
35564
  }
35565
+ function hydrateCachedM0Mural(db, sessionId, state) {
35566
+ if (!state.cachedM0Bytes || state.cachedM0MuralDataUrl !== undefined)
35567
+ return;
35568
+ const row = readCachedM0M1Row(db, sessionId);
35569
+ if (row && bufferEqualsNullable(row.cached_m0_bytes, state.cachedM0Bytes)) {
35570
+ state.cachedM0MuralDataUrl = row.cached_m0_mural_data_url ?? null;
35571
+ state.cachedM0MuralHash = row.cached_m0_mural_hash ?? null;
35572
+ }
35573
+ }
34822
35574
  function readCachedM0M1Row(db, sessionId) {
34823
35575
  return db.prepare(`SELECT cached_m0_bytes, cached_m0_mural_data_url,
34824
35576
  cached_m0_mural_hash, cached_m1_bytes,
@@ -35071,6 +35823,114 @@ function findBoundaryIndex(sessionId, messages, boundaryId) {
35071
35823
  return -1;
35072
35824
  return messages.findIndex((message) => message.info.id === served);
35073
35825
  }
35826
+ var absentBoundaryEpisodeBySession = new BoundedSessionMap(INJECTION_CACHE_MAX);
35827
+ var precedesVerdictBySession = new BoundedSessionMap(INJECTION_CACHE_MAX);
35828
+ var precedesWindowLoggedBySession = new BoundedSessionMap(INJECTION_CACHE_MAX);
35829
+ function resetPrefixTrimFallbackState(sessionId) {
35830
+ absentBoundaryEpisodeBySession.delete(sessionId);
35831
+ precedesVerdictBySession.delete(sessionId);
35832
+ precedesWindowLoggedBySession.delete(sessionId);
35833
+ }
35834
+ function isHostCompactionHeadRow(message) {
35835
+ if (message.info.summary === true)
35836
+ return true;
35837
+ return message.parts.some((part) => part.type === "compaction");
35838
+ }
35839
+ function firstPersistedLiveId(messages) {
35840
+ for (const message of messages) {
35841
+ const id = message.info.id;
35842
+ if (typeof id !== "string" || id.length === 0)
35843
+ continue;
35844
+ if (isHostRenderedSystemMessage(message) || isHostCompactionHeadRow(message))
35845
+ continue;
35846
+ return id;
35847
+ }
35848
+ return null;
35849
+ }
35850
+ function textOfParts(parts) {
35851
+ return parts.map((part) => {
35852
+ const text = part.text;
35853
+ return typeof text === "string" ? text : "";
35854
+ }).join("");
35855
+ }
35856
+ function findHostCompactionWindow(messages, readMagicContextSummaryMessageId) {
35857
+ const persisted = [];
35858
+ for (const message of messages) {
35859
+ if (persisted.length === 2)
35860
+ break;
35861
+ const id = message.info.id;
35862
+ if (typeof id !== "string" || id.length === 0)
35863
+ continue;
35864
+ if (isHostRenderedSystemMessage(message))
35865
+ continue;
35866
+ persisted.push(message);
35867
+ }
35868
+ const [request, summary] = persisted;
35869
+ if (!request || !summary)
35870
+ return null;
35871
+ if (request.info.role !== "user" || !request.parts.some((part) => part.type === "compaction")) {
35872
+ return null;
35873
+ }
35874
+ const summaryInfo = summary.info;
35875
+ if (summaryInfo.role !== "assistant" || summaryInfo.summary !== true || summaryInfo.parentID !== request.info.id || !summaryInfo.finish || summaryInfo.error) {
35876
+ return null;
35877
+ }
35878
+ const summaryMessageId = summary.info.id;
35879
+ if (textOfParts(summary.parts).includes(MARKER_SUMMARY_TEXT))
35880
+ return null;
35881
+ if (summaryMessageId === readMagicContextSummaryMessageId())
35882
+ return null;
35883
+ const completedAt = typeof summaryInfo.time?.completed === "number" ? summaryInfo.time.completed : summaryInfo.time?.created;
35884
+ if (typeof completedAt !== "number" || !Number.isFinite(completedAt))
35885
+ return null;
35886
+ return {
35887
+ compactionMessageId: request.info.id,
35888
+ summaryMessageId,
35889
+ completedAt
35890
+ };
35891
+ }
35892
+ function boundaryPrecedesWindow(sessionId, boundary, firstLiveId) {
35893
+ const cached = precedesVerdictBySession.get(sessionId);
35894
+ if (cached && cached.boundary === boundary && cached.firstLiveId === firstLiveId) {
35895
+ return cached.precedes;
35896
+ }
35897
+ let order = null;
35898
+ try {
35899
+ order = compareRawSessionMessageOrder2(sessionId, boundary, firstLiveId);
35900
+ const served = resolveHostServedBoundaryId2(sessionId, boundary);
35901
+ if (order === null && served !== boundary) {
35902
+ order = compareRawSessionMessageOrder2(sessionId, served, firstLiveId);
35903
+ }
35904
+ } catch (error) {
35905
+ sessionLog(sessionId, `prefix trim: placing boundary ${boundary} failed:`, error);
35906
+ order = null;
35907
+ }
35908
+ const precedes = order !== null && order < 0;
35909
+ precedesVerdictBySession.set(sessionId, { boundary, firstLiveId, precedes });
35910
+ return precedes;
35911
+ }
35912
+ function classifyAbsentBoundary(options, messages, boundary) {
35913
+ const { sessionId } = options;
35914
+ const pass = options.isCacheBustingPass ? "priced" : "defer";
35915
+ const firstLiveId = firstPersistedLiveId(messages);
35916
+ if (firstLiveId !== null && boundaryPrecedesWindow(sessionId, boundary, firstLiveId)) {
35917
+ absentBoundaryEpisodeBySession.delete(sessionId);
35918
+ if (precedesWindowLoggedBySession.get(sessionId) !== boundary) {
35919
+ precedesWindowLoggedBySession.set(sessionId, boundary);
35920
+ sessionLog(sessionId, `prefix trim: boundary ${boundary} precedes the first remaining message ${firstLiveId}; rows between were cut with the summarized history or removed by reduction this pass; pass=${pass}; nothing to cut`);
35921
+ }
35922
+ return "boundary-precedes-window";
35923
+ }
35924
+ precedesWindowLoggedBySession.delete(sessionId);
35925
+ const current = absentBoundaryEpisodeBySession.get(sessionId);
35926
+ const episode = current && current.boundary === boundary ? current : { boundary, passes: 0 };
35927
+ episode.passes += 1;
35928
+ absentBoundaryEpisodeBySession.set(sessionId, episode);
35929
+ if (episode.passes === 1 || options.isCacheBustingPass) {
35930
+ sessionLog(sessionId, `prefix trim: boundary ${boundary} absent from current messages; pass=${pass}; no in-pass trim applied (degraded pass ${episode.passes}; ${firstLiveId === null ? "no persisted live message to compare with" : `boundary does not sort before the first live message ${firstLiveId}`}; whole window served until a cache-busting pass moves the boundary into the window)`);
35931
+ }
35932
+ return "refused";
35933
+ }
35074
35934
  function isSyntheticPrefixHead(message) {
35075
35935
  if (message.info.id !== undefined || message.info.role !== "user" || message.parts.length === 0) {
35076
35936
  return false;
@@ -35175,10 +36035,10 @@ function trimToPreparedPrefix(options, prepared) {
35175
36035
  const index = findBoundaryIndex(options.sessionId, options.messages, boundary);
35176
36036
  if (index >= 0) {
35177
36037
  options.messages.splice(0, index + 1);
36038
+ resetPrefixTrimFallbackState(options.sessionId);
35178
36039
  status = "applied";
35179
36040
  } else {
35180
- sessionLog(options.sessionId, `prefix trim: boundary ${boundary} absent from current messages; pass=${options.isCacheBustingPass ? "priced" : "defer"}; no in-pass trim applied`);
35181
- status = "refused";
36041
+ status = classifyAbsentBoundary(options, options.messages, boundary);
35182
36042
  }
35183
36043
  }
35184
36044
  }
@@ -35227,13 +36087,7 @@ function injectM0M1(options) {
35227
36087
  prefixTrimStatus
35228
36088
  };
35229
36089
  }
35230
- if (options.state.cachedM0Bytes && options.state.cachedM0MuralDataUrl === undefined) {
35231
- const row = readCachedM0M1Row(options.db, options.sessionId);
35232
- if (row && bufferEqualsNullable(row.cached_m0_bytes, options.state.cachedM0Bytes)) {
35233
- options.state.cachedM0MuralDataUrl = row.cached_m0_mural_data_url ?? null;
35234
- options.state.cachedM0MuralHash = row.cached_m0_mural_hash ?? null;
35235
- }
35236
- }
36090
+ hydrateCachedM0Mural(options.db, options.sessionId, options.state);
35237
36091
  if (!options.workspaceIdentitySet && options.projectPath) {
35238
36092
  options = {
35239
36093
  ...options,
@@ -35663,7 +36517,7 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
35663
36517
  }
35664
36518
  ]);
35665
36519
  return true;
35666
- })();
36520
+ }).immediate();
35667
36521
  if (saved)
35668
36522
  sessionLog(sessionId, `historian skipped ordinals ${start}-${eligibleEnd - 1}: all ${rows.length} raw rows excluded by chunk filters (no-content boundary marker)`);
35669
36523
  return saved;
@@ -38212,6 +39066,13 @@ function v2NonNarrativeStoredGapRanges(db, sessionId, compartments) {
38212
39066
  return safeRanges;
38213
39067
  }
38214
39068
  var lastHistorianAlertBySession = new Map;
39069
+ var STORED_COMPARTMENT_FAILURE_BACKOFF_MS = 30 * 60 * 1000;
39070
+ function storedCompartmentFailureBackingOff(db, sessionId, validationError, now = Date.now()) {
39071
+ if (getHistorianFailureState(db, sessionId).lastError !== validationError)
39072
+ return false;
39073
+ const failedAt = loadProtectedTailMeta(db, sessionId).historianDrainFailureAt;
39074
+ return failedAt > 0 && failedAt <= now && now - failedAt < STORED_COMPARTMENT_FAILURE_BACKOFF_MS;
39075
+ }
38215
39076
  function shouldSuppressHistorianAlert(sessionId) {
38216
39077
  const lastAlert = lastHistorianAlertBySession.get(sessionId);
38217
39078
  if (lastAlert && Date.now() - lastAlert < HISTORIAN_ALERT_COOLDOWN_MS) {
@@ -38334,13 +39195,37 @@ async function runCompartmentAgent(deps) {
38334
39195
  }
38335
39196
  return;
38336
39197
  }
38337
- const priorCompartments = getCompartments(db, sessionId);
38338
- const existingValidationError = validateStoredCompartments(priorCompartments, v2NonNarrativeStoredGapRanges(db, sessionId, priorCompartments));
39198
+ let priorCompartments = getCompartments(db, sessionId);
39199
+ let existingValidationError = validateStoredCompartments(priorCompartments, v2NonNarrativeStoredGapRanges(db, sessionId, priorCompartments));
39200
+ const unresolvedInvolved = existingValidationError !== null && priorCompartments.some((compartment) => compartment.rebaseStatus === "unresolved");
39201
+ if (unresolvedInvolved && existingValidationError && storedCompartmentFailureBackingOff(db, sessionId, existingValidationError)) {
39202
+ sessionLog(sessionId, `historian no-op: stored compartments still invalid ("${existingValidationError}"); backing off`);
39203
+ telemetry.status = "noop";
39204
+ telemetry.failureReason = `existing-validation backoff: ${existingValidationError}`;
39205
+ return;
39206
+ }
39207
+ if (unresolvedInvolved && existingValidationError) {
39208
+ const recovery = recoverUnresolvedCompartments({
39209
+ db,
39210
+ sessionId,
39211
+ resolveOrdinal: (messageId) => readRawSessionMessageOrdinalById2(sessionId, messageId) ?? undefined,
39212
+ reason: `historian pre-run check failed: ${existingValidationError}`
39213
+ });
39214
+ if (recovery.rowsRewritten > 0) {
39215
+ priorCompartments = getCompartments(db, sessionId);
39216
+ existingValidationError = validateStoredCompartments(priorCompartments, v2NonNarrativeStoredGapRanges(db, sessionId, priorCompartments));
39217
+ }
39218
+ }
38339
39219
  if (existingValidationError) {
38340
39220
  sessionLog(sessionId, `historian failure: source=existing-validation reason="${existingValidationError}"`);
38341
39221
  const failCount = incrementHistorianFailure(db, sessionId, existingValidationError);
38342
39222
  telemetry.failureReason = `existing-validation: ${existingValidationError}`;
38343
- await notifyHistorianIssue(buildHistorianFailureNotice(failCount, existingValidationError));
39223
+ if (unresolvedInvolved) {
39224
+ retainDrainReservationForRetryThrottle = true;
39225
+ await notifyHistorianIssue(buildStoredCompartmentsInvalidNotice());
39226
+ } else {
39227
+ await notifyHistorianIssue(buildHistorianFailureNotice(failCount, existingValidationError));
39228
+ }
38344
39229
  return;
38345
39230
  }
38346
39231
  const offset = priorCompartments.length > 0 ? priorCompartments[priorCompartments.length - 1].endMessage + 1 : 1;
@@ -38580,8 +39465,8 @@ ${chunkText}`,
38580
39465
  const discardedLast = persistedCompartments.length < emittedCompartments.length;
38581
39466
  const weakLookaheadFinalCompartment = forceKeepLastCompartmentForChunk;
38582
39467
  const skipUnanchoredPromotion = discardedLast || weakLookaheadFinalCompartment;
38583
- const embeddingActive = !!promotionDirectory && deps.memoryEnabled !== false;
38584
- const promotionActive = embeddingActive && deps.autoPromote !== false;
39468
+ const embeddingActive = !!promotionDirectory;
39469
+ const promotionActive = embeddingActive && deps.memoryEnabled !== false && deps.autoPromote !== false;
38585
39470
  const promotionProjectIdentity = promotionDirectory ? resolveProjectIdentity(promotionDirectory) : "";
38586
39471
  const publishableEvents = (validatedPass.events ?? []).filter((e) => {
38587
39472
  if (typeof e.atCompartment !== "number")
@@ -38961,7 +39846,7 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
38961
39846
  clearInjectionCache(sessionId);
38962
39847
  }
38963
39848
  promoted.facts;
38964
- if (deps.memoryEnabled !== false) {
39849
+ {
38965
39850
  const projectIdentity = resolveProjectIdentity(sessionDirectory);
38966
39851
  await deps.ensureProjectRegistered?.(sessionDirectory, db);
38967
39852
  const liveCompartments = getCompartments(db, sessionId);
@@ -39178,7 +40063,7 @@ Another process acquired the compartment-state lease before recomp could publish
39178
40063
  queueDropsForCompartmentalizedMessages(db, sessionId, lastCompartmentEnd, compartmentTagKeys);
39179
40064
  }
39180
40065
  deps.onCompartmentStatePublished?.(sessionId);
39181
- if (deps.memoryEnabled !== false) {
40066
+ {
39182
40067
  const projectIdentity = resolveProjectIdentity(sessionDirectory);
39183
40068
  await deps.ensureProjectRegistered?.(sessionDirectory, db);
39184
40069
  const liveCompartments = getCompartments(db, sessionId);
@@ -39340,7 +40225,7 @@ Could not acquire the compartment-state lease for this session.`;
39340
40225
  clearInjectionCache(sessionId);
39341
40226
  }
39342
40227
  deps.onCompartmentStatePublished?.(sessionId);
39343
- if (deps.memoryEnabled !== false) {
40228
+ {
39344
40229
  const projectIdentity = resolveProjectIdentity(sessionDirectory);
39345
40230
  const liveCompartments = getCompartments(db, sessionId);
39346
40231
  const chunksToEmbed = liveCompartments.map((c) => ({
@@ -39819,4 +40704,4 @@ ${failure}`;
39819
40704
  }
39820
40705
  }
39821
40706
 
39822
- export { withContentLanguageDirective, buildPrimaryLanguageDirective, setJsoncValue, removeJsoncValue, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, string, unknown, array, object, union, tuple, record, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolveModelConfigValue, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, PROTECTED_TOKENS_MIN, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, PER_HARNESS_MODEL_KEYS, ConfigProfilesSchema, MagicContextConfigSchema, LIVE_RELOAD_CONFIG_PATHS, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, directoryHasGitMetadata, describeUnresolvedProjectIdentity, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, observeAuthorityRouting, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, getMemoryMirrorStatus, takeMemoryEmbeddingInvalidatedProjects, moduleMemoryIdentityForHostId, hostMemoryIdentityForModuleId, applyMirroredNoteCompileFields, applyTargetedMemoryMirrorRow, drainMirrorPages, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, SocketClosedError, SocketTimeoutError, StaleRouteHandleError, SubcClient, isConsumerReconnectTransient, connectionFileExists, clampProducerAtomChars, producerInputTokenLimit, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, readFrozenMergedReasoningParts, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, getProtectionWindowForSession, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getDeferredClearedCompactionMarkerState, retireDeferredClearedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, NEWEST_REASONING_BEARING_ASSISTANT, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, replacePendingCompactionMarkerStateIf, clearPendingCompactionMarkerStateIf, getSessionsWithPendingMarker, setSessionWorkMetrics, getObservedEpochFloor, resolveEpochFloorForPass, BoundedSessionMap, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, captureSlot, getInMemorySlot, getSlot, dropSlot, noteEntry, getLkgSlotHeapStats, useScopedToolSweep, createPreAdoptionToolSweepResolver, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, getNoteByIdInScope, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNotes, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, HiddenCompletionRefusal, detectThinkingBindingMismatch, isFable51ThinkingBindingModel, detectOverflow, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, getPromptFailureDetail, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, ACTIVE_TOOL_IDS, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, renderUserFacingFailure, userFacingFailureCode, renderCapabilityRefusal, capabilityRefusalCode, renderDreamFailure, dreamFailureCode, renderEmbeddingFailure, getCompartmentEvents, SYNAPSE_DEFAULT_MODEL, toSynapseLaneDescriptor, formatSynapseLaneDescriptor, SynapseEmbeddingProvider, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, computeNormalizedHash, getLocalEmbeddingNativeMemoryStats, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, describeShadowBackfillWriteRefusal, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, unregisterProjectShadowEmbedding, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, failedInvocationStatus, recordChildInvocation, resolveHiddenCompletionExecutor, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMuralIdentity, getMural, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinates, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, modelKeyAcceptsImages, resolveMuralWire, extractM0Block, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, materializeM0, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, setRecompStarting2, setRecompTerminal2, runManagedRecomp2 };
40707
+ export { withContentLanguageDirective, buildPrimaryLanguageDirective, setJsoncValue, removeJsoncValue, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, string, unknown, array, object, union, tuple, record, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolveModelConfigValue, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, PROTECTED_TOKENS_MIN, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, PER_HARNESS_MODEL_KEYS, ConfigProfilesSchema, MagicContextConfigSchema, LIVE_RELOAD_CONFIG_PATHS, formatFailClosedBlockingMessage, formatFailClosedBlockingSummary, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, directoryHasGitMetadata, describeUnresolvedProjectIdentity, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, registerOwnRpcServerInstance, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, observeAuthorityRouting, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, getMemoryMirrorStatus, takeMemoryEmbeddingInvalidatedProjects, moduleMemoryIdentityForHostId, hostMemoryIdentityForModuleId, applyMirroredNoteCompileFields, applyTargetedMemoryMirrorRow, drainMirrorPages, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, SocketClosedError, SocketTimeoutError, StaleRouteHandleError, SubcClient, isConsumerReconnectTransient, connectionFileExists, USER_FACING_FAILURES, renderUserFacingFailure, userFacingFailureCode, renderCapabilityRefusal, capabilityRefusalCode, renderDreamFailure, dreamFailureCode, renderEmbeddingFailure, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLeaseBestEffort, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, readFrozenMergedReasoningParts, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, getProtectionWindowForSession, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getDeferredClearedCompactionMarkerState, retireDeferredClearedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, replacePendingCompactionMarkerStateIf, clearPendingCompactionMarkerStateIf, getSessionsWithPendingMarker, setSessionWorkMetrics, getObservedEpochFloor, resolveEpochFloorForPass, BoundedSessionMap, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, noteEntry, getLkgSlotHeapStats, useScopedToolSweep, createPreAdoptionToolSweepResolver, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, SESSION_NOTE_CONDITION_ERROR, getNoteByIdInScope, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNotes, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, createChildSessionWithFence, HiddenCompletionRefusal, detectThinkingBindingMismatch, isPrefixBoundThinkingModel, isFable51ThinkingBindingModel, detectOverflow, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, registerHiddenChildAgents, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, isPromptTimeoutError, getPromptFailureDetail, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, createPromptAsyncTransport, ACTIVE_TOOL_IDS, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, SYNAPSE_DEFAULT_MODEL, toSynapseLaneDescriptor, formatSynapseLaneDescriptor, SynapseEmbeddingProvider, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, computeNormalizedHash, getLocalEmbeddingNativeMemoryStats, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, describeShadowBackfillWriteRefusal, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, unregisterProjectShadowEmbedding, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, embedUnembeddedMemoriesForProjectOutcome, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, failedInvocationStatus, recordChildInvocation, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMuralIdentity, getMural, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, modelKeyAcceptsImages, resolveMuralWire, extractM0Block, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, materializeM0, hydrateCachedM0Mural, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, hasCompleteCachedM0M1, injectM0M1, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, setRecompStarting2, setRecompTerminal2, runManagedRecomp2 };