@cortexkit/opencode-magic-context 0.43.2 → 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 (252) 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-hyk9y29x.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.map +1 -1
  15. package/dist/features/magic-context/dreamer/curate-category-rotation.d.ts.map +1 -1
  16. package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts.map +1 -1
  17. package/dist/features/magic-context/dreamer/failed-invocation-evidence.d.ts +13 -0
  18. package/dist/features/magic-context/dreamer/failed-invocation-evidence.d.ts.map +1 -0
  19. package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts.map +1 -1
  20. package/dist/features/magic-context/dreamer/lease.d.ts +5 -2
  21. package/dist/features/magic-context/dreamer/lease.d.ts.map +1 -1
  22. package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
  23. package/dist/features/magic-context/dreamer/memory-claim-safety.d.ts.map +1 -1
  24. package/dist/features/magic-context/dreamer/module-apply.d.ts +1 -0
  25. package/dist/features/magic-context/dreamer/module-apply.d.ts.map +1 -1
  26. package/dist/features/magic-context/dreamer/retrospective-learnings.d.ts.map +1 -1
  27. package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts +1 -1
  28. package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts.map +1 -1
  29. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  30. package/dist/features/magic-context/dreamer/task-scheduler.d.ts +2 -0
  31. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  32. package/dist/features/magic-context/dreamer/verify.d.ts +19 -0
  33. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  34. package/dist/features/magic-context/fail-closed-block.d.ts +7 -0
  35. package/dist/features/magic-context/fail-closed-block.d.ts.map +1 -1
  36. package/dist/features/magic-context/index.d.ts +1 -0
  37. package/dist/features/magic-context/index.d.ts.map +1 -1
  38. package/dist/features/magic-context/install-instance-id.d.ts +33 -0
  39. package/dist/features/magic-context/install-instance-id.d.ts.map +1 -0
  40. package/dist/features/magic-context/memory/constants.d.ts.map +1 -1
  41. package/dist/features/magic-context/memory/embedding-backfill.d.ts.map +1 -1
  42. package/dist/features/magic-context/memory/single-store-embedding-drain.d.ts +35 -0
  43. package/dist/features/magic-context/memory/single-store-embedding-drain.d.ts.map +1 -0
  44. package/dist/features/magic-context/memory/verification-paths.d.ts.map +1 -1
  45. package/dist/features/magic-context/message-index.d.ts +23 -0
  46. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  47. package/dist/features/magic-context/migrations.d.ts +7 -0
  48. package/dist/features/magic-context/migrations.d.ts.map +1 -1
  49. package/dist/features/magic-context/overflow-detection.d.ts +31 -8
  50. package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
  51. package/dist/features/magic-context/project-embedding-registry.d.ts +40 -1
  52. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  53. package/dist/features/magic-context/search.d.ts.map +1 -1
  54. package/dist/features/magic-context/session-decision-calibration.d.ts.map +1 -1
  55. package/dist/features/magic-context/storage-db.d.ts +1 -1
  56. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  57. package/dist/features/magic-context/storage-meta-persisted.d.ts +20 -5
  58. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  59. package/dist/features/magic-context/storage-meta.d.ts +1 -1
  60. package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
  61. package/dist/features/magic-context/storage-notes.d.ts +1 -0
  62. package/dist/features/magic-context/storage-notes.d.ts.map +1 -1
  63. package/dist/features/magic-context/storage-primers.d.ts.map +1 -1
  64. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  65. package/dist/features/magic-context/storage-unavailable-reason.d.ts +17 -0
  66. package/dist/features/magic-context/storage-unavailable-reason.d.ts.map +1 -0
  67. package/dist/features/magic-context/storage.d.ts +1 -1
  68. package/dist/features/magic-context/storage.d.ts.map +1 -1
  69. package/dist/features/magic-context/store-generation-rebase.d.ts +33 -1
  70. package/dist/features/magic-context/store-generation-rebase.d.ts.map +1 -1
  71. package/dist/features/magic-context/subagent-token-capture.d.ts.map +1 -1
  72. package/dist/features/magic-context/transform-decision-log.d.ts +1 -1
  73. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  74. package/dist/features/magic-context/types.d.ts +8 -3
  75. package/dist/features/magic-context/types.d.ts.map +1 -1
  76. package/dist/features/magic-context/user-memory/storage-user-memory.d.ts.map +1 -1
  77. package/dist/hooks/magic-context/apply-operations.d.ts +105 -9
  78. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  79. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  80. package/dist/hooks/magic-context/compartment-parser.d.ts +2 -0
  81. package/dist/hooks/magic-context/compartment-parser.d.ts.map +1 -1
  82. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +1 -0
  83. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  84. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  85. package/dist/hooks/magic-context/compartment-runner-partial-recomp.d.ts.map +1 -1
  86. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  87. package/dist/hooks/magic-context/compartment-runner-types.d.ts +2 -0
  88. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  89. package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
  90. package/dist/hooks/magic-context/context-limit-resolution.d.ts +31 -0
  91. package/dist/hooks/magic-context/context-limit-resolution.d.ts.map +1 -0
  92. package/dist/hooks/magic-context/embed-history-runner.d.ts +0 -1
  93. package/dist/hooks/magic-context/embed-history-runner.d.ts.map +1 -1
  94. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  95. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  96. package/dist/hooks/magic-context/format-embed-status.d.ts.map +1 -1
  97. package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
  98. package/dist/hooks/magic-context/historian-host-runner.d.ts +233 -0
  99. package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -0
  100. package/dist/hooks/magic-context/hook.d.ts +1 -3
  101. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  102. package/dist/hooks/magic-context/image-token-estimate.d.ts +9 -0
  103. package/dist/hooks/magic-context/image-token-estimate.d.ts.map +1 -1
  104. package/dist/hooks/magic-context/inject-compartments.d.ts +60 -1
  105. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  106. package/dist/hooks/magic-context/lkg-slot.d.ts +6 -0
  107. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  108. package/dist/hooks/magic-context/module-client.d.ts +21 -0
  109. package/dist/hooks/magic-context/module-client.d.ts.map +1 -0
  110. package/dist/hooks/magic-context/module-state-sync.d.ts +6 -2
  111. package/dist/hooks/magic-context/module-state-sync.d.ts.map +1 -1
  112. package/dist/hooks/magic-context/module-tool-backends.d.ts +47 -0
  113. package/dist/hooks/magic-context/module-tool-backends.d.ts.map +1 -0
  114. package/dist/hooks/magic-context/module-transport.d.ts +1 -1
  115. package/dist/hooks/magic-context/module-transport.d.ts.map +1 -1
  116. package/dist/hooks/magic-context/persist-filtered-noise.d.ts.map +1 -1
  117. package/dist/hooks/magic-context/read-session-chunk.d.ts +12 -0
  118. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  119. package/dist/hooks/magic-context/rust-mode-transform.d.ts +35 -0
  120. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  121. package/dist/hooks/magic-context/rust-refusal-recovery.d.ts +18 -0
  122. package/dist/hooks/magic-context/rust-refusal-recovery.d.ts.map +1 -1
  123. package/dist/hooks/magic-context/rust-served-m0.d.ts +20 -0
  124. package/dist/hooks/magic-context/rust-served-m0.d.ts.map +1 -0
  125. package/dist/hooks/magic-context/store-ahead-refusal.d.ts +40 -0
  126. package/dist/hooks/magic-context/store-ahead-refusal.d.ts.map +1 -0
  127. package/dist/hooks/magic-context/strip-content.d.ts +5 -5
  128. package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
  129. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  130. package/dist/hooks/magic-context/tag-messages.d.ts +19 -0
  131. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  132. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
  133. package/dist/hooks/magic-context/tool-drop-target.d.ts +14 -0
  134. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  135. package/dist/hooks/magic-context/tool-input-size.d.ts +21 -0
  136. package/dist/hooks/magic-context/tool-input-size.d.ts.map +1 -0
  137. package/dist/hooks/magic-context/tool-sweep-policy.d.ts.map +1 -1
  138. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +124 -11
  139. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  140. package/dist/hooks/magic-context/transform.d.ts +13 -0
  141. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  142. package/dist/{index-0ccmyzbj.js → index-01ft0h3p.js} +1 -1
  143. package/dist/{index-tdrv6nd0.js → index-2zf5fv89.js} +254 -61
  144. package/dist/{index-6j8th2hd.js → index-5f4qsnaq.js} +2 -2
  145. package/dist/{index-jgnag7sa.js → index-c906f3ff.js} +4 -4
  146. package/dist/{index-pa67brzn.js → index-cj5qe2nw.js} +3 -3
  147. package/dist/{index-febg06dy.js → index-dx0xnd4q.js} +1 -1
  148. package/dist/{index-bmzt6xgy.js → index-pye48m79.js} +1 -1
  149. package/dist/{index-g6hpfkqa.js → index-rdey8znw.js} +932 -261
  150. package/dist/{index-wgzyeyf5.js → index-tjq5jztd.js} +22 -6
  151. package/dist/{index-9r1cbh9e.js → index-v6wsttqt.js} +1 -1
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +3323 -1629
  154. package/dist/{message-time-backfill-0ccvyk9n.js → message-time-backfill-rm9wmcem.js} +3 -3
  155. package/dist/plugin/dream-timer.d.ts +2 -0
  156. package/dist/plugin/dream-timer.d.ts.map +1 -1
  157. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  158. package/dist/plugin/messages-transform.d.ts.map +1 -1
  159. package/dist/plugin/native-compaction-guard.d.ts +22 -0
  160. package/dist/plugin/native-compaction-guard.d.ts.map +1 -0
  161. package/dist/plugin/rpc-handlers.d.ts +11 -0
  162. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  163. package/dist/{read-session-chunk-53a7qbrh.js → read-session-chunk-ktz5zt70.js} +5 -3
  164. package/dist/{recomp-orchestrator-adsgqgse.js → recomp-orchestrator-ahekzt0s.js} +8 -8
  165. package/dist/{safe-notification-target-vrkjrbgb.js → safe-notification-target-6w0esgd6.js} +2 -2
  166. package/dist/{send-session-notification-e28r4xx2.js → send-session-notification-w7xbnrsm.js} +4 -4
  167. package/dist/shared/index.d.ts +1 -0
  168. package/dist/shared/index.d.ts.map +1 -1
  169. package/dist/shared/logger.d.ts.map +1 -1
  170. package/dist/shared/model-suggestion-retry.d.ts +13 -1
  171. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  172. package/dist/shared/prompt-async-transport.d.ts +25 -0
  173. package/dist/shared/prompt-async-transport.d.ts.map +1 -0
  174. package/dist/shared/rpc-server.d.ts +1 -0
  175. package/dist/shared/rpc-server.d.ts.map +1 -1
  176. package/dist/shared/rpc-types.d.ts +16 -0
  177. package/dist/shared/rpc-types.d.ts.map +1 -1
  178. package/dist/shared/rpc-utils.d.ts +3 -0
  179. package/dist/shared/rpc-utils.d.ts.map +1 -1
  180. package/dist/shared/sqlite-write-locker-test-support.d.ts +7 -0
  181. package/dist/shared/sqlite-write-locker-test-support.d.ts.map +1 -0
  182. package/dist/shared/status-summary.d.ts +9 -1
  183. package/dist/shared/status-summary.d.ts.map +1 -1
  184. package/dist/shared/tag-transcript.d.ts.map +1 -1
  185. package/dist/shared/user-facing-codes.d.ts +10 -5
  186. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  187. package/dist/shared/window-geometry.d.ts +6 -3
  188. package/dist/shared/window-geometry.d.ts.map +1 -1
  189. package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
  190. package/dist/tools/ctx-note/tools.d.ts.map +1 -1
  191. package/dist/tools/ctx-reduce/tools.d.ts.map +1 -1
  192. package/dist/tools/ctx-search/tools.d.ts.map +1 -1
  193. package/dist/v2/fold/boundary.d.ts +61 -0
  194. package/dist/v2/fold/boundary.d.ts.map +1 -0
  195. package/dist/v2/fold/restore.d.ts.map +1 -1
  196. package/dist/v2/hidden-completion.d.ts +16 -3
  197. package/dist/v2/hidden-completion.d.ts.map +1 -1
  198. package/dist/v2/hooks/context.d.ts +45 -14
  199. package/dist/v2/hooks/context.d.ts.map +1 -1
  200. package/dist/v2/hooks/hidden-child.d.ts +6 -0
  201. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  202. package/dist/v2/hooks/payload.d.ts.map +1 -1
  203. package/dist/v2/hooks/rpc-live-state.d.ts +1 -1
  204. package/dist/v2/hooks/rpc-live-state.d.ts.map +1 -1
  205. package/dist/v2/hooks/rust-mode.d.ts +47 -0
  206. package/dist/v2/hooks/rust-mode.d.ts.map +1 -0
  207. package/dist/v2/hooks/session-project-backfill.d.ts +15 -0
  208. package/dist/v2/hooks/session-project-backfill.d.ts.map +1 -0
  209. package/dist/v2/hooks/storage-gate.d.ts +42 -0
  210. package/dist/v2/hooks/storage-gate.d.ts.map +1 -0
  211. package/dist/v2/hooks/storage-notice.d.ts +29 -0
  212. package/dist/v2/hooks/storage-notice.d.ts.map +1 -0
  213. package/dist/v2/hooks/store.d.ts +16 -0
  214. package/dist/v2/hooks/store.d.ts.map +1 -1
  215. package/dist/v2/hooks/tools.d.ts +11 -2
  216. package/dist/v2/hooks/tools.d.ts.map +1 -1
  217. package/dist/v2/hooks/types.d.ts +4 -0
  218. package/dist/v2/hooks/types.d.ts.map +1 -1
  219. package/dist/v2/hooks/usage-persist.d.ts +31 -0
  220. package/dist/v2/hooks/usage-persist.d.ts.map +1 -0
  221. package/dist/v2/server.js +12216 -7963
  222. package/dist/v2/store-reader.d.ts +9 -0
  223. package/dist/v2/store-reader.d.ts.map +1 -1
  224. package/dist/wrapup-orchestrator-9srk0kjf.js +18 -0
  225. package/package.json +1 -1
  226. package/src/agents/magic-context-prompt.ts +3 -3
  227. package/src/config/index.ts +40 -0
  228. package/src/config/misplaced-agent-model.test.ts +61 -0
  229. package/src/config/project-security.test.ts +17 -0
  230. package/src/config/project-security.ts +28 -4
  231. package/src/config/schema/magic-context.ts +29 -2
  232. package/src/shared/index.ts +1 -0
  233. package/src/shared/logger.test.ts +63 -2
  234. package/src/shared/logger.ts +23 -5
  235. package/src/shared/model-suggestion-retry.test.ts +115 -4
  236. package/src/shared/model-suggestion-retry.ts +57 -12
  237. package/src/shared/prompt-async-transport.test.ts +217 -0
  238. package/src/shared/prompt-async-transport.ts +242 -0
  239. package/src/shared/prompt-surface-a1-golden.md +8 -8
  240. package/src/shared/rpc-server.ts +13 -1
  241. package/src/shared/rpc-types.ts +17 -0
  242. package/src/shared/rpc-utils.ts +28 -0
  243. package/src/shared/sqlite-transaction-mode-guard.test.ts +198 -0
  244. package/src/shared/sqlite-write-locker-test-support.ts +62 -0
  245. package/src/shared/status-detail-text.test.ts +23 -0
  246. package/src/shared/status-summary.ts +25 -1
  247. package/src/shared/tag-transcript.ts +82 -19
  248. package/src/shared/user-facing-codes.ts +12 -5
  249. package/src/shared/window-geometry.ts +6 -3
  250. package/dist/v2/hooks/provider-admission.d.ts +0 -22
  251. package/dist/v2/hooks/provider-admission.d.ts.map +0 -1
  252. package/dist/wrapup-orchestrator-8xzbpvm8.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,
@@ -52,11 +53,12 @@ import {
52
53
  readRawSessionMessageIdOrdinalsForRange2,
53
54
  hasRawSessionMessageById2,
54
55
  readRawSessionMessageOrdinalById2,
56
+ compareRawSessionMessageOrder2,
55
57
  getRawSessionMessageCount2,
56
58
  getRawSessionTagKeysThrough2,
57
59
  getLegacyProtectedTailStartOrdinal2,
58
60
  readSessionChunk2
59
- } from "./index-tdrv6nd0.js";
61
+ } from "./index-2zf5fv89.js";
60
62
  import {
61
63
  resolveOpenCodeDbPath,
62
64
  hasV1MessageTables,
@@ -71,7 +73,7 @@ import {
71
73
  closeQuietly,
72
74
  withReadOnlySessionDb,
73
75
  getMessageTimesFromOpenCodeDb
74
- } from "./index-bmzt6xgy.js";
76
+ } from "./index-pye48m79.js";
75
77
  import {
76
78
  piModelRefToCanonical,
77
79
  modelRefLookupOrder,
@@ -82,7 +84,7 @@ import {
82
84
  getSdkOutputLimit,
83
85
  deriveTriggerBudget2,
84
86
  producerSourceLocalBudget2
85
- } from "./index-0ccmyzbj.js";
87
+ } from "./index-01ft0h3p.js";
86
88
  import {
87
89
  createScanner,
88
90
  parseTree,
@@ -99,10 +101,10 @@ import {
99
101
  getErrorMessage,
100
102
  describeError,
101
103
  sendStatusNotification2
102
- } from "./index-jgnag7sa.js";
104
+ } from "./index-c906f3ff.js";
103
105
  import {
104
106
  logSlowWriteTransaction
105
- } from "./index-9r1cbh9e.js";
107
+ } from "./index-v6wsttqt.js";
106
108
 
107
109
  // src/config/schema/magic-context.ts
108
110
  import { homedir } from "node:os";
@@ -5533,6 +5535,7 @@ var AgentMetadataSchema = AgentOverrideConfigSchema.pick({
5533
5535
  maxTokens: true
5534
5536
  });
5535
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.`),
5536
5539
  opencode: DreamerOpenCodeHarnessBlockSchema.optional(),
5537
5540
  pi: DreamerPiHarnessBlockSchema.optional(),
5538
5541
  omp: DreamerOmpHarnessBlockSchema.optional(),
@@ -5543,6 +5546,10 @@ var HistorianConfigSchema = AgentMetadataSchema.extend({
5543
5546
  opencode: OpenCodeHarnessBlockSchema.optional(),
5544
5547
  pi: PiHarnessBlockSchema.optional(),
5545
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."),
5546
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)"),
5547
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: [])`)
5548
5555
  }).optional();
@@ -5556,7 +5563,7 @@ function expandConfigPath(value) {
5556
5563
  return trimmed;
5557
5564
  }
5558
5565
  var BaseEmbeddingConfigSchema = object({
5559
- 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."),
5560
5567
  fallback_provider: EmbeddingFallbackProviderSchema.optional().describe("Fallback provider for the Synapse lane. Required when provider is 'synapse'; local, openai-compatible, and off are valid."),
5561
5568
  model: string().optional().describe("Embedding model name. Required for openai-compatible, ignored for local."),
5562
5569
  endpoint: string().optional().describe("API endpoint URL. Required when provider is openai-compatible."),
@@ -5737,7 +5744,7 @@ var MagicContextConfigSchema = object({
5737
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.")
5738
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)."),
5739
5746
  memory: object({
5740
- 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."),
5741
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)"),
5742
5749
  auto_promote: boolean2().default(true).describe("Automatically promote eligible session facts into memory (default: true)"),
5743
5750
  retrieval_count_promotion_threshold: number2().min(1).default(3).describe("retrieval_count threshold for promoting memory to permanent status (min: 1, default: 3)"),
@@ -6029,7 +6036,7 @@ function transitionSessionHygieneUnits(db, sessionId, bustPermitted, calibration
6029
6036
  hygieneUnitsVersion: HYGIENE_PROVIDER_UNITS_VERSION
6030
6037
  });
6031
6038
  return HYGIENE_PROVIDER_UNITS_VERSION;
6032
- })();
6039
+ }).immediate();
6033
6040
  }
6034
6041
 
6035
6042
  // src/features/magic-context/protection-window.ts
@@ -6935,7 +6942,7 @@ function markProtectedTailPolicyV3Seeded(db, sessionId, priorBoundaryOrdinal) {
6935
6942
  WHERE session_id = ? AND protected_tail_policy_version < 3`).run(Math.max(1, Math.floor(priorBoundaryOrdinal)), sessionId);
6936
6943
  seeded = true;
6937
6944
  }
6938
- })();
6945
+ }).immediate();
6939
6946
  return { ...loadProtectedTailMeta(db, sessionId), seeded };
6940
6947
  }
6941
6948
  function recordProtectedTailPublicationFloor(db, sessionId, floorOrdinal) {
@@ -6945,7 +6952,7 @@ function recordProtectedTailPublicationFloor(db, sessionId, floorOrdinal) {
6945
6952
  SET prior_boundary_ordinal = MAX(COALESCE(prior_boundary_ordinal, 1), ?),
6946
6953
  recovery_no_eligible_head_count = 0
6947
6954
  WHERE session_id = ?`).run(Math.max(1, Math.floor(floorOrdinal)), sessionId);
6948
- })();
6955
+ }).immediate();
6949
6956
  }
6950
6957
  function recordProtectedTailNoEligibleHead(db, sessionId) {
6951
6958
  db.transaction(() => {
@@ -6953,14 +6960,14 @@ function recordProtectedTailNoEligibleHead(db, sessionId) {
6953
6960
  db.prepare(`UPDATE session_meta
6954
6961
  SET recovery_no_eligible_head_count = COALESCE(recovery_no_eligible_head_count, 0) + 1
6955
6962
  WHERE session_id = ?`).run(sessionId);
6956
- })();
6963
+ }).immediate();
6957
6964
  return loadProtectedTailMeta(db, sessionId).recoveryNoEligibleHeadCount;
6958
6965
  }
6959
6966
  function resetProtectedTailNoEligibleHead(db, sessionId) {
6960
6967
  db.transaction(() => {
6961
6968
  ensureSessionMetaRow(db, sessionId);
6962
6969
  db.prepare("UPDATE session_meta SET recovery_no_eligible_head_count = 0 WHERE session_id = ?").run(sessionId);
6963
- })();
6970
+ }).immediate();
6964
6971
  }
6965
6972
  var DRAIN_WINDOW_MS = 10 * 60 * 1000;
6966
6973
  var WRAPUP_IN_PROGRESS_TTL_MS = 5 * 60 * 1000;
@@ -7250,27 +7257,27 @@ function reserveProtectedTailDrainTokens(args) {
7250
7257
  reservation: { sessionId: args.sessionId, runId: args.runId, tokens: reserved },
7251
7258
  budgetState: budgetState(meta.protectedTailDrainTokens + reserved)
7252
7259
  };
7253
- })();
7260
+ }).immediate();
7254
7261
  return result;
7255
7262
  }
7256
7263
  function clearEmergencyDrainLatch(db, sessionId) {
7257
7264
  db.transaction(() => {
7258
7265
  ensureSessionMetaRow(db, sessionId);
7259
7266
  db.prepare("UPDATE session_meta SET emergency_drain_active = 0 WHERE session_id = ?").run(sessionId);
7260
- })();
7267
+ }).immediate();
7261
7268
  }
7262
7269
  function recordHistorianDrainFailure(db, sessionId, now) {
7263
7270
  const ts = now ?? Date.now();
7264
7271
  db.transaction(() => {
7265
7272
  ensureSessionMetaRow(db, sessionId);
7266
7273
  db.prepare("UPDATE session_meta SET historian_drain_failure_at = ? WHERE session_id = ?").run(ts, sessionId);
7267
- })();
7274
+ }).immediate();
7268
7275
  }
7269
7276
  function clearHistorianDrainFailure(db, sessionId) {
7270
7277
  db.transaction(() => {
7271
7278
  ensureSessionMetaRow(db, sessionId);
7272
7279
  db.prepare("UPDATE session_meta SET historian_drain_failure_at = 0 WHERE session_id = ?").run(sessionId);
7273
- })();
7280
+ }).immediate();
7274
7281
  }
7275
7282
  function rollbackProtectedTailDrainReservation(db, reservation) {
7276
7283
  if (!reservation || reservation.tokens <= 0)
@@ -7280,7 +7287,7 @@ function rollbackProtectedTailDrainReservation(db, reservation) {
7280
7287
  db.prepare(`UPDATE session_meta
7281
7288
  SET protected_tail_drain_tokens = MAX(0, COALESCE(protected_tail_drain_tokens, 0) - ?)
7282
7289
  WHERE session_id = ?`).run(reservation.tokens, reservation.sessionId);
7283
- })();
7290
+ }).immediate();
7284
7291
  }
7285
7292
  function getPersistedReasoningWatermark(db, sessionId) {
7286
7293
  const result = db.prepare("SELECT cleared_reasoning_through_tag FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7304,13 +7311,13 @@ function setEmergencyDropSample(db, sessionId, inputSample) {
7304
7311
  db.transaction(() => {
7305
7312
  ensureSessionMetaRow(db, sessionId);
7306
7313
  db.prepare("UPDATE session_meta SET last_emergency_input_sample = ? WHERE session_id = ?").run(Math.max(0, Math.round(inputSample)), sessionId);
7307
- })();
7314
+ }).immediate();
7308
7315
  }
7309
7316
  function clearEmergencyDropSample(db, sessionId) {
7310
7317
  db.transaction(() => {
7311
7318
  ensureSessionMetaRow(db, sessionId);
7312
7319
  db.prepare("UPDATE session_meta SET last_emergency_input_sample = 0 WHERE session_id = ?").run(sessionId);
7313
- })();
7320
+ }).immediate();
7314
7321
  }
7315
7322
  var EMPTY_CHANNEL1_NUDGE_STATE = { level: "", ordinal: 0 };
7316
7323
  function isLastNudgeUndroppedRow(row) {
@@ -7367,7 +7374,7 @@ function setLastNudgeUndropped(db, sessionId, value) {
7367
7374
  db.transaction(() => {
7368
7375
  ensureSessionMetaRow(db, sessionId);
7369
7376
  db.prepare("UPDATE session_meta SET last_nudge_undropped = ? WHERE session_id = ?").run(Math.max(0, Math.round(value)), sessionId);
7370
- })();
7377
+ }).immediate();
7371
7378
  }
7372
7379
  function getChannel1NudgeState(db, sessionId) {
7373
7380
  const result = db.prepare("SELECT last_nudge_level FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7377,7 +7384,7 @@ function setChannel1NudgeState(db, sessionId, value) {
7377
7384
  db.transaction(() => {
7378
7385
  ensureSessionMetaRow(db, sessionId);
7379
7386
  db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(value), sessionId);
7380
- })();
7387
+ }).immediate();
7381
7388
  }
7382
7389
  function markChannel1PostReduceGracePending(db, sessionId) {
7383
7390
  return db.transaction(() => {
@@ -7391,7 +7398,7 @@ function markChannel1PostReduceGracePending(db, sessionId) {
7391
7398
  };
7392
7399
  db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
7393
7400
  return next;
7394
- })();
7401
+ }).immediate();
7395
7402
  }
7396
7403
  function captureChannel1PostReduceGraceBaseline(db, sessionId, measuredUndropped) {
7397
7404
  return db.transaction(() => {
@@ -7408,7 +7415,7 @@ function captureChannel1PostReduceGraceBaseline(db, sessionId, measuredUndropped
7408
7415
  };
7409
7416
  db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
7410
7417
  return next;
7411
- })();
7418
+ }).immediate();
7412
7419
  }
7413
7420
  function isChannel2StateRow(row) {
7414
7421
  return typeof row === "object" && row !== null && typeof row.channel2_nudge_state === "string";
@@ -7435,7 +7442,7 @@ function setChannel2NudgeState(db, sessionId, state) {
7435
7442
  ensureSessionMetaRow(db, sessionId);
7436
7443
  const claimedAt = state === "claimed" ? Date.now() : 0;
7437
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);
7438
- })();
7445
+ }).immediate();
7439
7446
  }
7440
7447
  function casChannel2NudgeState(db, sessionId, from, to) {
7441
7448
  let changed = false;
@@ -7444,7 +7451,7 @@ function casChannel2NudgeState(db, sessionId, from, to) {
7444
7451
  const claimedAt = to === "claimed" ? Date.now() : 0;
7445
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);
7446
7453
  changed = (result.changes ?? 0) > 0;
7447
- })();
7454
+ }).immediate();
7448
7455
  return changed;
7449
7456
  }
7450
7457
  function claimChannel2NudgeState(db, sessionId, claimToken) {
@@ -7453,7 +7460,7 @@ function claimChannel2NudgeState(db, sessionId, claimToken) {
7453
7460
  ensureSessionMetaRow(db, sessionId);
7454
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);
7455
7462
  changed = (result.changes ?? 0) > 0;
7456
- })();
7463
+ }).immediate();
7457
7464
  return changed;
7458
7465
  }
7459
7466
  function casChannel2NudgeClaim(db, sessionId, to, claimToken) {
@@ -7464,7 +7471,7 @@ function casChannel2NudgeClaim(db, sessionId, to, claimToken) {
7464
7471
  const nextClaimToken = to === "claimed" ? claimToken : "";
7465
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);
7466
7473
  changed = (result.changes ?? 0) > 0;
7467
- })();
7474
+ }).immediate();
7468
7475
  return changed;
7469
7476
  }
7470
7477
  function getPersistedNoteNudge(db, sessionId) {
@@ -7483,13 +7490,13 @@ function setPersistedNoteNudgeTrigger(db, sessionId, triggerMessageId = "") {
7483
7490
  db.transaction(() => {
7484
7491
  ensureSessionMetaRow(db, sessionId);
7485
7492
  db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 1, note_nudge_trigger_message_id = ? WHERE session_id = ?").run(triggerMessageId, sessionId);
7486
- })();
7493
+ }).immediate();
7487
7494
  }
7488
7495
  function setPersistedNoteNudgeTriggerMessageId(db, sessionId, triggerMessageId) {
7489
7496
  db.transaction(() => {
7490
7497
  ensureSessionMetaRow(db, sessionId);
7491
7498
  db.prepare("UPDATE session_meta SET note_nudge_trigger_message_id = ? WHERE session_id = ?").run(triggerMessageId, sessionId);
7492
- })();
7499
+ }).immediate();
7493
7500
  }
7494
7501
  function getNoteNudgeAnchors(db, sessionId) {
7495
7502
  const row = db.prepare("SELECT note_nudge_anchors FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7648,7 +7655,7 @@ function setPersistedTodoSyntheticAnchor(db, sessionId, callId, messageId, state
7648
7655
  db.transaction(() => {
7649
7656
  ensureSessionMetaRow(db, sessionId);
7650
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);
7651
- })();
7658
+ }).immediate();
7652
7659
  }
7653
7660
  function clearPersistedTodoSyntheticAnchor(db, sessionId) {
7654
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);
@@ -7668,7 +7675,7 @@ function setNoteLastReadAt(db, sessionId, at = Date.now()) {
7668
7675
  db.transaction(() => {
7669
7676
  ensureSessionMetaRow(db, sessionId);
7670
7677
  db.prepare("UPDATE session_meta SET note_last_read_at = ? WHERE session_id = ?").run(at, sessionId);
7671
- })();
7678
+ }).immediate();
7672
7679
  }
7673
7680
  function getHistorianFailureState(db, sessionId) {
7674
7681
  const result = db.prepare("SELECT historian_failure_count, historian_last_error, historian_last_failure_at FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7683,14 +7690,14 @@ function incrementHistorianFailure(db, sessionId, error) {
7683
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);
7684
7691
  const reason = error.replace(/\s+/g, " ").trim().slice(0, 300);
7685
7692
  sessionLog(sessionId, `historian failure recorded: count=${nextCount} reason="${reason}"`);
7686
- })();
7693
+ }).immediate();
7687
7694
  return nextCount;
7688
7695
  }
7689
7696
  function clearHistorianFailureState(db, sessionId) {
7690
7697
  db.transaction(() => {
7691
7698
  ensureSessionMetaRow(db, sessionId);
7692
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);
7693
- })();
7700
+ }).immediate();
7694
7701
  }
7695
7702
  function normalizeDetectedLimitModelKey(modelKey) {
7696
7703
  return typeof modelKey === "string" && modelKey.length > 0 ? piModelRefToCanonical(modelKey) : null;
@@ -7768,7 +7775,7 @@ function recordOverflowDetected(db, sessionId, reportedLimit, modelKey, origin =
7768
7775
  const percentage = effectiveLimit > 0 ? reportedInputTokens / effectiveLimit * 100 : 100;
7769
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);
7770
7777
  }
7771
- })();
7778
+ }).immediate();
7772
7779
  }
7773
7780
  function recordDetectedContextLimit(db, sessionId, reportedLimit, modelKey, provenance = "unknown") {
7774
7781
  if (!(reportedLimit > 0))
@@ -7776,7 +7783,7 @@ function recordDetectedContextLimit(db, sessionId, reportedLimit, modelKey, prov
7776
7783
  db.transaction(() => {
7777
7784
  ensureSessionMetaRow(db, sessionId);
7778
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);
7779
- })();
7786
+ }).immediate();
7780
7787
  }
7781
7788
  function clearEmergencyRecovery(db, sessionId) {
7782
7789
  db.transaction(() => {
@@ -7786,7 +7793,7 @@ function clearEmergencyRecovery(db, sessionId) {
7786
7793
  } catch {
7787
7794
  db.prepare("UPDATE session_meta SET needs_emergency_recovery = 0, emergency_recovery_origin = '' WHERE session_id = ?").run(sessionId);
7788
7795
  }
7789
- })();
7796
+ }).immediate();
7790
7797
  emergencyRecoveryArmedSessions.delete(sessionId);
7791
7798
  emergencyRecoveryArmedAtBySession.delete(sessionId);
7792
7799
  providerOverflowReconfirmedSessions.delete(sessionId);
@@ -7796,7 +7803,7 @@ function clearDetectedContextLimit(db, sessionId) {
7796
7803
  db.transaction(() => {
7797
7804
  ensureSessionMetaRow(db, sessionId);
7798
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);
7799
- })();
7806
+ }).immediate();
7800
7807
  }
7801
7808
  function parsePersistedCompactionMarkerState(raw, storedTargetEndMessageId) {
7802
7809
  if (!raw || raw.length === 0)
@@ -7823,7 +7830,7 @@ function setPersistedCompactionMarkerState(db, sessionId, state) {
7823
7830
  const previous = state === null ? getPersistedCompactionMarkerState(db, sessionId) ?? getDeferredClearedCompactionMarkerState(db, sessionId) : null;
7824
7831
  const json = state ? JSON.stringify(state) : previous ? JSON.stringify({ deferredClear: previous }) : "";
7825
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);
7826
- })();
7833
+ }).immediate();
7827
7834
  }
7828
7835
  function getDeferredClearedCompactionMarkerState(db, sessionId) {
7829
7836
  const row = db.prepare("SELECT compaction_marker_state FROM session_meta WHERE session_id = ?").get(sessionId);
@@ -7928,7 +7935,7 @@ function removeStrippedPlaceholderId(db, sessionId, messageId) {
7928
7935
  applyStrippedPlaceholderDelta(db, sessionId, { remove: [messageId] });
7929
7936
  return true;
7930
7937
  }
7931
- var NEWEST_REASONING_BEARING_ASSISTANT = "newest_reasoning_bearing_assistant";
7938
+ var THINKING_BINDING_RECOVERY_ALL_ASSISTANTS = "all_reasoning_bearing_assistants";
7932
7939
  var THINKING_BINDING_RECOVERY_FROZEN_PREFIX = "binding_mismatch:";
7933
7940
  function thinkingBindingRecoveryFrozenId(messageId) {
7934
7941
  return `${THINKING_BINDING_RECOVERY_FROZEN_PREFIX}${messageId}`;
@@ -7938,14 +7945,9 @@ function getThinkingBindingRecoveryTarget(db, sessionId) {
7938
7945
  const target = row?.thinking_binding_recovery_target;
7939
7946
  return typeof target === "string" && target.length > 0 ? target : null;
7940
7947
  }
7941
- function armThinkingBindingRecovery(db, sessionId, messageId) {
7948
+ function armThinkingBindingRecovery(db, sessionId) {
7942
7949
  ensureSessionMetaRow(db, sessionId);
7943
- const target = typeof messageId === "string" && messageId.length > 0 ? messageId : NEWEST_REASONING_BEARING_ASSISTANT;
7944
- if (target === NEWEST_REASONING_BEARING_ASSISTANT) {
7945
- db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ? AND COALESCE(thinking_binding_recovery_target, '') = ''").run(target, sessionId);
7946
- return;
7947
- }
7948
- 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);
7949
7951
  }
7950
7952
  function clearThinkingBindingRecoveryIf(db, sessionId, expectedTarget) {
7951
7953
  const result = db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, expectedTarget);
@@ -8354,6 +8356,11 @@ var USER_FACING_FAILURES = {
8354
8356
  sentence: "Memory maintenance could not reach its model.",
8355
8357
  action: "Check the model connection, then run /ctx-dream again."
8356
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
+ },
8357
8364
  dream_empty_completion: {
8358
8365
  code: "MC-D03",
8359
8366
  sentence: "Memory maintenance received no usable response.",
@@ -8519,6 +8526,11 @@ var USER_FACING_FAILURES = {
8519
8526
  sentence: "Magic Context is temporarily unavailable.",
8520
8527
  action: "Retry in a moment."
8521
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
+ },
8522
8534
  compaction_marker_missing: {
8523
8535
  code: "MC-C11",
8524
8536
  sentence: "The history boundary marker is missing from the OpenCode store, so requests carry the full session.",
@@ -8534,11 +8546,6 @@ var USER_FACING_FAILURES = {
8534
8546
  sentence: "Memory authority is inconsistent between the host and module.",
8535
8547
  action: "Run `ck doctor drain-authority` before changing Rust mode."
8536
8548
  },
8537
- rust_mode_unsupported: {
8538
- code: "MC-S06",
8539
- sentence: "Experimental Rust transform mode is not available on this OpenCode host.",
8540
- action: 'Magic Context is running its TypeScript mode instead; set `transform_mode` to "ts" to stop requesting Rust.'
8541
- },
8542
8549
  dreamer_task_failing: {
8543
8550
  code: "MC-S05",
8544
8551
  sentence: "A background maintenance task keeps failing on its schedule.",
@@ -8573,6 +8580,7 @@ function capabilityRefusalCode(capability) {
8573
8580
  var DREAM_FAILURE_KEYS = {
8574
8581
  provider_timeout: "dream_provider_timeout",
8575
8582
  provider_error: "dream_provider_error",
8583
+ step_limit: "dream_step_limit",
8576
8584
  empty_completion: "dream_empty_completion",
8577
8585
  no_models: "dream_no_models",
8578
8586
  child_aborted: "dream_child_aborted",
@@ -8618,6 +8626,16 @@ function piHarnessKindFromExecutable(value) {
8618
8626
  }
8619
8627
 
8620
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
+ }
8621
8639
  function projectHash(directory) {
8622
8640
  const normalized = directory.replace(/\/+$/, "");
8623
8641
  return createHash("sha256").update(normalized).digest("hex").slice(0, 16);
@@ -9415,7 +9433,7 @@ function updateSessionMeta(db, sessionId, updates) {
9415
9433
  db.transaction(() => {
9416
9434
  ensureSessionMetaRow(db, sessionId);
9417
9435
  db.prepare(`UPDATE session_meta SET ${setClauses.join(", ")} WHERE session_id = ?`).run(...values, sessionId);
9418
- })();
9436
+ }).immediate();
9419
9437
  }
9420
9438
  function advanceToolReclaimWatermark(db, sessionId, maxTagNumber) {
9421
9439
  if (maxTagNumber <= 0)
@@ -9423,7 +9441,7 @@ function advanceToolReclaimWatermark(db, sessionId, maxTagNumber) {
9423
9441
  db.transaction(() => {
9424
9442
  ensureSessionMetaRow(db, sessionId);
9425
9443
  db.prepare("UPDATE session_meta SET tool_reclaim_watermark = MAX(COALESCE(tool_reclaim_watermark, 0), ?) WHERE session_id = ?").run(maxTagNumber, sessionId);
9426
- })();
9444
+ }).immediate();
9427
9445
  }
9428
9446
  function rustCleanupHarness() {
9429
9447
  return `${getHarness()}:rust`;
@@ -9491,7 +9509,7 @@ function clearSession(db, sessionId, rustModuleCleanupAcknowledged = false) {
9491
9509
  deleteSessionScopedRows(db, [sessionId], undefined, {
9492
9510
  rustModuleCleanupAcknowledged
9493
9511
  });
9494
- })();
9512
+ }).immediate();
9495
9513
  logSlowWriteTransaction("clear-session", transactionStartedAt);
9496
9514
  }
9497
9515
  // src/features/magic-context/compartment-chunk-embedding.ts
@@ -11893,7 +11911,7 @@ function backfillMessageFtsRowidMapBatch(db, batchSize = MESSAGE_FTS_ROWID_MAP_B
11893
11911
  watermarkRowid,
11894
11912
  completed
11895
11913
  };
11896
- })();
11914
+ }).immediate();
11897
11915
  logSlowWriteTransaction("message_fts_rowid_backfill", transactionStartedAt);
11898
11916
  return progress;
11899
11917
  }
@@ -12565,7 +12583,7 @@ function replaceCompartmentChunkEmbeddings(db, rows) {
12565
12583
  for (const row of rows) {
12566
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);
12567
12585
  }
12568
- })();
12586
+ }).immediate();
12569
12587
  invalidateDecodedSearchPools(db, ([sessionId, projectPath, cachedModelId]) => sessionId === rows[0].sessionId && projectPath === rows[0].projectPath && cachedModelId === modelId);
12570
12588
  }
12571
12589
  function loadCompartmentChunkEmbeddingsForSearch(db, sessionId, projectPath, modelId, dateRange = null) {
@@ -12646,7 +12664,7 @@ function renumberOneBasedChunkWindows(db, candidate, projectPath, modelId, windo
12646
12664
  throw new Error(`Failed to renumber compartment ${candidate.id} window ${window.windowIndex + 1}`);
12647
12665
  }
12648
12666
  }
12649
- })();
12667
+ }).immediate();
12650
12668
  invalidateDecodedSearchPools(db, ([sessionId, cachedProjectPath, cachedModelId]) => sessionId === candidate.sessionId && cachedProjectPath === projectPath && cachedModelId === modelId);
12651
12669
  }
12652
12670
  function classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens) {
@@ -12930,7 +12948,7 @@ function upsertCommits(db, projectPath, commits) {
12930
12948
  }
12931
12949
  }
12932
12950
  }
12933
- })();
12951
+ }).immediate();
12934
12952
  return { inserted, updated };
12935
12953
  }
12936
12954
  function getCommitCount(db, projectPath) {
@@ -14902,7 +14920,7 @@ function recordSessionProjectIdentity(db, sessionId, projectPath) {
14902
14920
  db.transaction(() => {
14903
14921
  getUpsertSessionProjectStatement(db).run(sessionId, harness, projectPath, now);
14904
14922
  getRepairSessionChunkProjectStatement(db).run(projectPath, sessionId, harness, projectPath, SESSION_CHUNK_REPAIR_BATCH_SIZE);
14905
- })();
14923
+ }).immediate();
14906
14924
  }
14907
14925
  function repairMisScopedCompartmentChunkEmbeddingsForProject(db, projectPath) {
14908
14926
  if (!projectPath)
@@ -15348,7 +15366,8 @@ function sameFeatures(a, b) {
15348
15366
  }
15349
15367
  function snapshotFor(registration) {
15350
15368
  const providerIsOn = registration.providerIdentity !== OFF_PROVIDER_IDENTITY;
15351
- const enabled = !registration.observationMode && providerIsOn && registration.features.memoryEnabled;
15369
+ const historyEnabled = !registration.observationMode && providerIsOn;
15370
+ const enabled = historyEnabled && registration.features.memoryEnabled;
15352
15371
  const gitCommitEnabled = !registration.observationMode && providerIsOn && registration.features.gitCommitEnabled;
15353
15372
  const configuredModel = "model" in registration.config && typeof registration.config.model === "string" ? registration.config.model.trim() : "";
15354
15373
  const synapseDescriptor = !registration.observationMode && registration.config.provider === "synapse" ? synapseDescriptorFromConfig(registration.config) : undefined;
@@ -15360,6 +15379,7 @@ function snapshotFor(registration) {
15360
15379
  generation: registration.generation,
15361
15380
  features: { ...registration.features },
15362
15381
  enabled,
15382
+ historyEnabled,
15363
15383
  gitCommitEnabled,
15364
15384
  modelId: registration.observationMode || !providerIsOn ? "off" : registration.modelId,
15365
15385
  chunkModelId: registration.observationMode || !providerIsOn ? "off" : registration.chunkModelId,
@@ -15437,10 +15457,8 @@ function recordActiveEmbeddingIdentity(db, projectIdentity, currentProviderIdent
15437
15457
  if (features.gitCommitEnabled) {
15438
15458
  recordScopeActiveIdentity(db, projectIdentity, "commit", currentProviderIdentity, now);
15439
15459
  }
15440
- if (features.memoryEnabled) {
15441
- repairMisScopedCompartmentChunkEmbeddingsForProject(db, projectIdentity);
15442
- recordScopeActiveIdentity(db, projectIdentity, "chunk", currentChunkIdentity, now);
15443
- }
15460
+ repairMisScopedCompartmentChunkEmbeddingsForProject(db, projectIdentity);
15461
+ recordScopeActiveIdentity(db, projectIdentity, "chunk", currentChunkIdentity, now);
15444
15462
  db.exec("COMMIT");
15445
15463
  logSlowWriteTransaction("embedding_identity_record", transactionStartedAt);
15446
15464
  } catch (error) {
@@ -15559,7 +15577,7 @@ function sweepStaleEmbeddingIdentitiesForProject(db, projectIdentity, now = Date
15559
15577
  },
15560
15578
  {
15561
15579
  scope: "chunk",
15562
- enabled: snapshot.enabled && snapshot.chunkModelId !== "off",
15580
+ enabled: snapshot.historyEnabled && snapshot.chunkModelId !== "off",
15563
15581
  currentModelId: snapshot.chunkModelId
15564
15582
  }
15565
15583
  ];
@@ -15699,7 +15717,7 @@ function registerProjectShadowEmbedding(db, projectIdentity, config, sourceDirec
15699
15717
  recordScopeActiveIdentity(db, projectIdentity, "commit", registration.modelId, now);
15700
15718
  recordScopeActiveIdentity(db, projectIdentity, "chunk", registration.chunkModelId, now);
15701
15719
  persistShadowDescriptor(db, registration);
15702
- })();
15720
+ }).immediate();
15703
15721
  maybeArmShadowBackfill(db, projectIdentity, registration, options.manualBackfill === true);
15704
15722
  return {
15705
15723
  projectIdentity,
@@ -15709,6 +15727,7 @@ function registerProjectShadowEmbedding(db, projectIdentity, config, sourceDirec
15709
15727
  generation,
15710
15728
  features: { memoryEnabled: true, gitCommitEnabled: true },
15711
15729
  enabled: true,
15730
+ historyEnabled: true,
15712
15731
  gitCommitEnabled: true,
15713
15732
  modelId: registration.modelId,
15714
15733
  chunkModelId: registration.chunkModelId,
@@ -15917,6 +15936,8 @@ function maybeArmShadowBackfill(db, projectIdentity, shadow, manualBackfill = fa
15917
15936
  const stallKey = `${projectIdentity}:${scope}`;
15918
15937
  if (primaryModelId === "off" || shadowModelId === "off")
15919
15938
  continue;
15939
+ if (scope === "memory" && !primary.features.memoryEnabled)
15940
+ continue;
15920
15941
  const batch = shadowBackfillCandidateBatch(db, projectIdentity, scope, primaryModelId, shadow, SHADOW_MAX_ITEMS_PER_TICK);
15921
15942
  const persisted = getPersistedShadowBackfillState(db, projectIdentity, scope, shadowModelId);
15922
15943
  if (batch.ids.length === 0) {
@@ -16053,7 +16074,7 @@ async function processShadowQueueItem(item) {
16053
16074
  hashGuardRejected = true;
16054
16075
  }
16055
16076
  }
16056
- })();
16077
+ }).immediate();
16057
16078
  return {
16058
16079
  writes,
16059
16080
  ...writes === 0 ? {
@@ -16087,7 +16108,7 @@ async function processShadowQueueItem(item) {
16087
16108
  saveCommitEmbedding(db, row.sha, vector, registration.modelId);
16088
16109
  writes += 1;
16089
16110
  }
16090
- })();
16111
+ }).immediate();
16091
16112
  return {
16092
16113
  writes,
16093
16114
  ...writes === 0 ? { refusalReason: embedded.refusalReason ?? "provider_returned_no_vectors" } : {}
@@ -16409,13 +16430,17 @@ function getLoadUnembeddedMemoriesStatement(db) {
16409
16430
  return stmt;
16410
16431
  }
16411
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) {
16412
16437
  const snapshot = getProjectEmbeddingSnapshot(projectIdentity);
16413
16438
  if (!snapshot?.enabled)
16414
- return 0;
16439
+ return { kind: "disabled" };
16415
16440
  const normalizedBatchSize = Math.max(1, Math.floor(batchSize));
16416
16441
  const memories = getLoadUnembeddedMemoriesStatement(db).all(snapshot.modelId, projectIdentity, normalizedBatchSize).filter(isUnembeddedMemoryRow);
16417
16442
  if (memories.length === 0)
16418
- return 0;
16443
+ return { kind: "done" };
16419
16444
  try {
16420
16445
  const result = await embedItemsForProject(projectIdentity, memories.map((memory) => ({
16421
16446
  id: `memory:${memory.id}`,
@@ -16423,7 +16448,7 @@ async function embedUnembeddedMemoriesForProject(db, projectIdentity, batchSize
16423
16448
  contentSha256: contentSha256(memory.content)
16424
16449
  })), undefined, db, projectIdentity);
16425
16450
  if (!result)
16426
- return 0;
16451
+ return { kind: "unavailable" };
16427
16452
  let embeddedCount = 0;
16428
16453
  db.transaction(() => {
16429
16454
  for (const memory of memories) {
@@ -16434,12 +16459,12 @@ async function embedUnembeddedMemoriesForProject(db, projectIdentity, batchSize
16434
16459
  embeddedCount += 1;
16435
16460
  }
16436
16461
  }
16437
- })();
16462
+ }).immediate();
16438
16463
  enqueueShadowEmbeddingItems(projectIdentity, "memory", memories.filter((memory) => result.vectors.has(`memory:${memory.id}`)).map((memory) => String(memory.id)));
16439
- return embeddedCount;
16464
+ return { kind: "embedded", count: embeddedCount };
16440
16465
  } catch (error) {
16441
16466
  log("[magic-context] failed to proactively embed missing memories:", error);
16442
- return 0;
16467
+ return { kind: "failed", error };
16443
16468
  }
16444
16469
  }
16445
16470
  async function embedCommitBatch(db, projectIdentity, batchSize) {
@@ -16465,7 +16490,7 @@ async function embedCommitBatch(db, projectIdentity, batchSize) {
16465
16490
  saveCommitEmbedding(db, commit.sha, embedding, result.modelId);
16466
16491
  embeddedCount += 1;
16467
16492
  }
16468
- })();
16493
+ }).immediate();
16469
16494
  enqueueShadowEmbeddingItems(projectIdentity, "commit", commits.filter((commit) => result.vectors.has(`commit:${commit.sha}`)).map((commit) => commit.sha));
16470
16495
  return embeddedCount;
16471
16496
  }
@@ -16616,7 +16641,7 @@ async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates
16616
16641
  }
16617
16642
  async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, options) {
16618
16643
  const snapshot = getProjectEmbeddingSnapshot(projectIdentity);
16619
- if (!snapshot?.enabled || snapshot.chunkModelId === "off") {
16644
+ if (!snapshot?.historyEnabled || snapshot.chunkModelId === "off") {
16620
16645
  return { status: "disabled", embedded: 0, total: 0 };
16621
16646
  }
16622
16647
  recordSessionProjectIdentity(db, sessionId, projectIdentity);
@@ -16720,7 +16745,7 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
16720
16745
  }
16721
16746
  function getEmbeddingCoverageStatus(db, projectIdentity, sessionId) {
16722
16747
  const snapshot = getProjectEmbeddingSnapshot(projectIdentity);
16723
- if (!snapshot?.enabled || snapshot.chunkModelId === "off") {
16748
+ if (!snapshot?.historyEnabled || snapshot.chunkModelId === "off") {
16724
16749
  return {
16725
16750
  enabled: false,
16726
16751
  model: snapshot?.model ?? "off",
@@ -16733,7 +16758,7 @@ function getEmbeddingCoverageStatus(db, projectIdentity, sessionId) {
16733
16758
  };
16734
16759
  }
16735
16760
  const session = countSessionCompartmentEmbedCoverage(db, projectIdentity, sessionId, snapshot.chunkModelId, getProjectEmbeddingMaxInputTokens(projectIdentity));
16736
- const memories = getMemoryEmbedCoverage(db, projectIdentity, snapshot.modelId);
16761
+ const memories = snapshot.enabled ? getMemoryEmbedCoverage(db, projectIdentity, snapshot.modelId) : { embedded: 0, total: 0, memoryEnabled: false };
16737
16762
  const gitEnabled = snapshot.gitCommitEnabled;
16738
16763
  const commits = gitEnabled ? {
16739
16764
  embedded: countEmbeddedCommits(db, projectIdentity, snapshot.modelId),
@@ -16756,6 +16781,8 @@ function getEmbeddingCoverageStatus(db, projectIdentity, sessionId) {
16756
16781
  async function embedAndStoreCompartmentChunks(db, sessionId, projectPath, compartments) {
16757
16782
  if (compartments.length === 0)
16758
16783
  return;
16784
+ if (getProjectChunkEmbeddingModelId(projectPath) === "off")
16785
+ return;
16759
16786
  const maxInputTokens = getProjectEmbeddingMaxInputTokens(projectPath);
16760
16787
  for (const compartment of compartments) {
16761
16788
  try {
@@ -16952,7 +16979,7 @@ function appendCompartments(db, sessionId, compartments) {
16952
16979
  const now = Date.now();
16953
16980
  db.transaction(() => {
16954
16981
  insertCompartmentRows(db, sessionId, compartments, now);
16955
- })();
16982
+ }).immediate();
16956
16983
  }
16957
16984
  function buildCompartmentBlock(compartments, facts, memoryBlock, dateRanges) {
16958
16985
  const lines = [];
@@ -16998,7 +17025,7 @@ function saveRecompStagingPass(db, sessionId, passNumber, compartments, facts) {
16998
17025
  for (const f of facts) {
16999
17026
  factStmt.run(sessionId, f.category, f.content, passNumber, now, getHarness());
17000
17027
  }
17001
- })();
17028
+ }).immediate();
17002
17029
  }
17003
17030
  function getRecompStaging(db, sessionId) {
17004
17031
  const compartmentRows = db.prepare("SELECT * FROM recomp_compartments WHERE session_id = ? ORDER BY sequence ASC").all(sessionId).filter(isRecompCompartmentRow);
@@ -17036,7 +17063,7 @@ function clearRecompStaging(db, sessionId) {
17036
17063
  try {
17037
17064
  db.prepare("UPDATE session_meta SET recomp_partial_range_start = 0, recomp_partial_range_end = 0 WHERE session_id = ?").run(sessionId);
17038
17065
  } catch {}
17039
- })();
17066
+ }).immediate();
17040
17067
  }
17041
17068
  function getRecompPartialRange(db, sessionId) {
17042
17069
  try {
@@ -17276,16 +17303,21 @@ function normalizeSourceVersion(version) {
17276
17303
  return `string:${version}`;
17277
17304
  return "null";
17278
17305
  }
17279
- function getMessageSourceSnapshot(message) {
17306
+ function toMessageIndexSource(message) {
17280
17307
  const content = getIndexableContent(message.role, message.parts);
17281
17308
  return {
17309
+ id: message.id,
17282
17310
  ordinal: message.ordinal,
17311
+ role: message.role,
17312
+ createdAt: message.createdAt,
17283
17313
  sourceVersion: normalizeSourceVersion(message.version),
17284
17314
  contentHash: createHash9("sha256").update(content).digest("hex"),
17285
- role: message.role,
17286
17315
  content
17287
17316
  };
17288
17317
  }
17318
+ function getMessageSourceSnapshot(message) {
17319
+ return toMessageIndexSource(message);
17320
+ }
17289
17321
  function getMessageIndexSourceIdentity(message) {
17290
17322
  const source = getMessageSourceSnapshot(message);
17291
17323
  return JSON.stringify([
@@ -17302,8 +17334,10 @@ function isMessageIndexSourceCurrent(db, sessionId, message) {
17302
17334
  return row?.message_ordinal === source.ordinal && row.source_version === source.sourceVersion && row.normalized_content_hash === source.contentHash && row.role === source.role;
17303
17335
  }
17304
17336
  function setMessageSource(db, sessionId, message, now) {
17305
- const source = getMessageSourceSnapshot(message);
17306
- 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);
17307
17341
  return source.content;
17308
17342
  }
17309
17343
  function getLastIndexedOrdinal(db, sessionId) {
@@ -17355,7 +17389,7 @@ function clearIndexedMessages(db, sessionId) {
17355
17389
  const transactionStartedAt = performance.now();
17356
17390
  db.transaction(() => {
17357
17391
  clearIndexedMessagesInTransaction(db, sessionId);
17358
- })();
17392
+ }).immediate();
17359
17393
  logSlowWriteTransaction("message_index_clear", transactionStartedAt);
17360
17394
  }
17361
17395
  function getIndexableContent(role, parts) {
@@ -17428,6 +17462,12 @@ function indexSingleMessage(db, sessionId, message) {
17428
17462
  }
17429
17463
  }
17430
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) {
17431
17471
  const now = Date.now();
17432
17472
  let inserted = 0;
17433
17473
  const transactionStartedAt = performance.now();
@@ -17448,21 +17488,22 @@ function indexMessagesAfterOrdinal(db, sessionId, messages, _lastIndexedOrdinal,
17448
17488
  getDeleteFtsMapRangeStatement(db).run(sessionId, dirtyFloor, finalWatermark);
17449
17489
  getDeleteMessageSourceRangeStatement(db).run(sessionId, dirtyFloor, finalWatermark);
17450
17490
  }
17451
- const messagesByOrdinal = new Map;
17452
- for (const message of messages) {
17453
- if (message.ordinal > effectiveWatermark && message.ordinal <= finalWatermark) {
17454
- 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);
17455
17495
  }
17456
17496
  }
17457
17497
  let coveredWatermark = effectiveWatermark;
17458
- while (coveredWatermark < finalWatermark && messagesByOrdinal.has(coveredWatermark + 1)) {
17498
+ while (coveredWatermark < finalWatermark && itemsByOrdinal.has(coveredWatermark + 1)) {
17459
17499
  coveredWatermark += 1;
17460
17500
  }
17461
17501
  for (let ordinal = effectiveWatermark + 1;ordinal <= coveredWatermark; ordinal++) {
17462
- const message = messagesByOrdinal.get(ordinal);
17463
- if (!message)
17502
+ const item = itemsByOrdinal.get(ordinal);
17503
+ if (!item)
17464
17504
  continue;
17465
- const content = setMessageSource(db, sessionId, message, now);
17505
+ const message = toSource(item);
17506
+ const content = writeMessageSource(db, sessionId, message, now);
17466
17507
  if (content.length === 0 || message.role !== "user" && message.role !== "assistant" || isMessageAlreadyIndexed(db, sessionId, message.id)) {
17467
17508
  continue;
17468
17509
  }
@@ -17485,22 +17526,6 @@ function indexMessagesAfterOrdinal(db, sessionId, messages, _lastIndexedOrdinal,
17485
17526
  }
17486
17527
  return inserted;
17487
17528
  }
17488
- function ensureMessagesIndexed(db, sessionId, readMessages) {
17489
- const messages = readMessages(sessionId);
17490
- if (messages.length === 0) {
17491
- clearIndexedMessages(db, sessionId);
17492
- return;
17493
- }
17494
- let lastIndexedOrdinal = getLastIndexedOrdinal(db, sessionId);
17495
- if (lastIndexedOrdinal > messages.length) {
17496
- clearIndexedMessages(db, sessionId);
17497
- lastIndexedOrdinal = 0;
17498
- }
17499
- if (lastIndexedOrdinal >= messages.length && getDirtyIndexFloor(db, sessionId) === null) {
17500
- return;
17501
- }
17502
- indexMessagesAfterOrdinal(db, sessionId, messages, lastIndexedOrdinal, messages.length);
17503
- }
17504
17529
  function harnessSupportsOpenCodeOrphanSweep(harness) {
17505
17530
  return harness === "opencode" || harness === "opencode2";
17506
17531
  }
@@ -17727,23 +17752,40 @@ function isCompartmentCoordinateRow(row) {
17727
17752
  const candidate = row;
17728
17753
  return typeof candidate.id === "number" && typeof candidate.sequence === "number" && typeof candidate.start_message === "number" && typeof candidate.end_message === "number";
17729
17754
  }
17730
- function buildProjection(messages) {
17731
- const ordinalById = new Map;
17732
- const partCountById = new Map;
17733
- 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) {
17734
17765
  for (const message of messages) {
17735
- ordinalById.set(message.id, message.ordinal);
17736
- 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);
17737
17768
  if (isStrictGapHealingMessage(message))
17738
- nonNarrativeOrdinals.add(message.ordinal);
17769
+ projection.nonNarrativeOrdinals.add(message.ordinal);
17770
+ if (withIndexSources)
17771
+ projection.indexSources.push(toMessageIndexSource(message));
17739
17772
  }
17740
- return {
17741
- ordinalById,
17742
- partCountById,
17743
- nonNarrativeOrdinals,
17744
- messageCount: messages.length
17745
- };
17773
+ projection.messageCount += messages.length;
17746
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;
17747
17789
  function messageIdFromAnchorBlockId(anchorBlockId) {
17748
17790
  const hash = anchorBlockId.lastIndexOf("#");
17749
17791
  return hash > 0 ? anchorBlockId.slice(0, hash) : anchorBlockId;
@@ -17882,13 +17924,17 @@ function pruneShrunkPartEntries(db, sessionId, column, shrunk) {
17882
17924
  } catch {
17883
17925
  return 0;
17884
17926
  }
17885
- const isStale = (candidate) => shrunk.some(({ messageId, partCount }) => {
17886
- const prefix = `${messageId}:p`;
17887
- 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)
17888
17931
  return false;
17889
- const suffix = candidate.slice(prefix.length);
17890
- return /^\d+$/.test(suffix) && Number.parseInt(suffix, 10) >= partCount;
17891
- });
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
+ };
17892
17938
  let dropped = 0;
17893
17939
  const pruneArray = (values) => values.filter((value) => {
17894
17940
  if (typeof value === "string" && isStale(value)) {
@@ -17919,7 +17965,50 @@ function pruneShrunkPartEntries(db, sessionId, column, shrunk) {
17919
17965
  db.prepare(`UPDATE session_meta SET ${column} = ? WHERE session_id = ?`).run(JSON.stringify(next), sessionId);
17920
17966
  return dropped;
17921
17967
  }
17922
- 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) {
17923
18012
  const { db, sessionId, generation } = args;
17924
18013
  const startedAt = performance.now();
17925
18014
  if (!sessionIsOpenCodeOwned(db, sessionId)) {
@@ -17928,7 +18017,7 @@ function rebaseSessionCoordinates(args) {
17928
18017
  const previousGeneration = readCoordinateGeneration(db, sessionId);
17929
18018
  if (previousGeneration === generation) {
17930
18019
  const outcome = emptyOutcome("unchanged", generation, previousGeneration);
17931
- const repair = repairStampedSessionOnce(db, sessionId, args.readMessages);
18020
+ const repair = repairStampedSessionOnce(db, sessionId, args);
17932
18021
  if (repair !== null && repair.rowsRewritten > 0) {
17933
18022
  outcome.status = "repaired";
17934
18023
  outcome.compartmentsDerived = repair.derived.length;
@@ -17941,7 +18030,7 @@ function rebaseSessionCoordinates(args) {
17941
18030
  stampGeneration(db, sessionId, generation, null);
17942
18031
  return emptyOutcome("stamped", generation, previousGeneration);
17943
18032
  }
17944
- const projection = buildProjection(args.readMessages(sessionId));
18033
+ const projection = yield* buildProjectionSteps(args, true);
17945
18034
  const outcome = emptyOutcome("rebased", generation, impliedGeneration);
17946
18035
  const compartmentRows = readCompartmentRows(db, "compartments", sessionId);
17947
18036
  const recompRows = readCompartmentRows(db, "recomp_compartments", sessionId);
@@ -17951,7 +18040,7 @@ function rebaseSessionCoordinates(args) {
17951
18040
  const recompGapResult = healNonNarrativeCompartmentGaps(recompPlans, projection);
17952
18041
  const notePlans = planNotes(db, sessionId, projection);
17953
18042
  const shrunkMessages = [];
17954
- 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] : []));
17955
18044
  const highestTaggedPartIndex = new Map;
17956
18045
  for (const contentId of taggedMessageIds) {
17957
18046
  const marker = contentId.lastIndexOf(":p");
@@ -17987,12 +18076,34 @@ function rebaseSessionCoordinates(args) {
17987
18076
  return emptyOutcome("stamped", generation, impliedGeneration);
17988
18077
  }
17989
18078
  db.exec("BEGIN IMMEDIATE");
17990
- let committed = false;
18079
+ let closed = false;
17991
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
+ };
17992
18103
  for (const plan of [...compartmentPlans, ...recompPlans]) {
17993
18104
  if (!compartmentPlanChanges(plan))
17994
18105
  continue;
17995
- 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);
17996
18107
  const rebased = plan.status === "ok" ? 1 : 0;
17997
18108
  const unresolved = plan.status === "unresolved" ? 1 : 0;
17998
18109
  if (plan.table === "compartments") {
@@ -18007,8 +18118,9 @@ function rebaseSessionCoordinates(args) {
18007
18118
  outcome.recompCompartmentsUnresolved += unresolved;
18008
18119
  }
18009
18120
  }
18121
+ const updateNote = db.prepare("UPDATE notes SET anchor_ordinal = ? WHERE id = ? AND session_id = ?");
18010
18122
  for (const plan of movedNotes) {
18011
- 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);
18012
18124
  if (plan.ordinal === null)
18013
18125
  outcome.notesCleared += 1;
18014
18126
  else
@@ -18035,19 +18147,6 @@ function rebaseSessionCoordinates(args) {
18035
18147
  db.prepare("DELETE FROM lkg_slots WHERE session_id = ?").run(sessionId);
18036
18148
  outcome.lkgSlotsDropped = lkgSlotCount;
18037
18149
  }
18038
- const fold = foldShrunkPartTags(db, sessionId, shrunkMessages);
18039
- outcome.partTagsFolded = fold.foldedTagNumbers.length;
18040
- outcome.partTagsRekeyed = fold.rekeyedTagNumbers.length;
18041
- outcome.queuedReductionsDiscarded = fold.discardedDropTagNumbers.length;
18042
- for (const column of [
18043
- "stripped_placeholder_ids",
18044
- "merged_reasoning_stripped_ids",
18045
- "trailing_blank_decisions"
18046
- ]) {
18047
- outcome.frozenPartEntriesDropped += pruneShrunkPartEntries(db, sessionId, column, shrunkMessages);
18048
- }
18049
- clearCachedM0M1(db, sessionId);
18050
- db.prepare("UPDATE session_meta SET system_prompt_hash = '' WHERE session_id = ?").run(sessionId);
18051
18150
  stampGeneration(db, sessionId, generation, {
18052
18151
  generation,
18053
18152
  previousGeneration: impliedGeneration,
@@ -18062,16 +18161,20 @@ function rebaseSessionCoordinates(args) {
18062
18161
  neighbourRecoveryAt: Date.now()
18063
18162
  });
18064
18163
  db.exec("COMMIT");
18065
- committed = true;
18164
+ closed = true;
18066
18165
  } finally {
18067
- if (!committed) {
18166
+ if (!closed) {
18068
18167
  try {
18069
18168
  db.exec("ROLLBACK");
18070
18169
  } catch {}
18071
18170
  }
18072
18171
  }
18073
18172
  if (outcome.indexRebuilt) {
18074
- 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
+ }
18075
18178
  outcome.indexRowsRebuilt = countRows(db, "SELECT COUNT(*) AS count FROM message_history_source WHERE session_id = ?", sessionId);
18076
18179
  }
18077
18180
  sessionLog(sessionId, formatRebaseLogLine(outcome, performance.now() - startedAt));
@@ -18155,7 +18258,7 @@ function unresolvedRowBreaksTiling(rows) {
18155
18258
  }
18156
18259
  return false;
18157
18260
  }
18158
- function repairStampedSessionOnce(db, sessionId, readMessages) {
18261
+ function repairStampedSessionOnce(db, sessionId, readArgs) {
18159
18262
  let checked = repairCheckedSessions.get(db);
18160
18263
  if (!checked) {
18161
18264
  checked = new Set;
@@ -18176,7 +18279,13 @@ function repairStampedSessionOnce(db, sessionId, readMessages) {
18176
18279
  db,
18177
18280
  sessionId,
18178
18281
  resolveOrdinal: (messageId) => {
18179
- ordinalById ??= buildProjection(readMessages(sessionId)).ordinalById;
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
+ }
18180
18289
  return ordinalById.get(messageId);
18181
18290
  },
18182
18291
  reason: "stamped-session repair"
@@ -18260,11 +18369,7 @@ var V2_MEMORY_CATEGORIES = [
18260
18369
  "NAMING"
18261
18370
  ];
18262
18371
  var PROMOTABLE_CATEGORIES = [
18263
- "PROJECT_RULES",
18264
- "ARCHITECTURE",
18265
- "CONSTRAINTS",
18266
- "CONFIG_VALUES",
18267
- "NAMING",
18372
+ ...V2_MEMORY_CATEGORIES,
18268
18373
  "ARCHITECTURE_DECISIONS",
18269
18374
  "CONFIG_DEFAULTS",
18270
18375
  "USER_PREFERENCES",
@@ -18274,11 +18379,7 @@ var PROMOTABLE_CATEGORIES = [
18274
18379
  "KNOWN_ISSUES"
18275
18380
  ];
18276
18381
  var CATEGORY_PRIORITY = [
18277
- "PROJECT_RULES",
18278
- "ARCHITECTURE",
18279
- "CONSTRAINTS",
18280
- "CONFIG_VALUES",
18281
- "NAMING",
18382
+ ...V2_MEMORY_CATEGORIES,
18282
18383
  "USER_DIRECTIVES",
18283
18384
  "USER_PREFERENCES",
18284
18385
  "CONFIG_DEFAULTS",
@@ -18411,7 +18512,7 @@ async function ensureMemoryEmbeddings(args) {
18411
18512
  staged.set(memory.id, { embedding, modelId: result.modelId });
18412
18513
  }
18413
18514
  }
18414
- })();
18515
+ }).immediate();
18415
18516
  const currentSnapshot = getProjectEmbeddingSnapshot(args.projectIdentity);
18416
18517
  if (!currentSnapshot || currentSnapshot.generation !== result.generation) {
18417
18518
  return args.existingEmbeddings;
@@ -19252,7 +19353,7 @@ async function embedAndStoreMemory(db, sessionId, projectPath, memoryId, content
19252
19353
  if (result) {
19253
19354
  db.transaction(() => {
19254
19355
  saveEmbeddingIfHashMatches(db, memoryId, result.vector, result.modelId, hashBeforeEmbed);
19255
- })();
19356
+ }).immediate();
19256
19357
  }
19257
19358
  } catch (error) {
19258
19359
  sessionLog(sessionId, `memory embedding failed for memory ${memoryId}:`, error);
@@ -19428,7 +19529,7 @@ async function runGit(cwd, args) {
19428
19529
  return String(result.stdout);
19429
19530
  } catch (error) {
19430
19531
  if (error.killed || error.code === "ETIMEDOUT") {
19431
- 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`, {
19432
19533
  cause: error
19433
19534
  });
19434
19535
  }
@@ -21064,7 +21165,8 @@ var TIER_OPEN_REGEXES = [
21064
21165
  ];
21065
21166
  var TIER_CLOSE_ANY_REGEX = /<\/p\d/;
21066
21167
  var TIER_OPEN_ANY_REGEX = /<p\d/;
21067
- 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);
21068
21170
  var FACT_ITEM_REGEX = /^\s*\*\s*(.+)$/gm;
21069
21171
  var UNPROCESSED_REGEX = /<unprocessed_from>(\d+)<\/unprocessed_from>/;
21070
21172
  var USER_OBSERVATIONS_REGEX = /<user_observations>(.*?)<\/user_observations>/s;
@@ -21101,6 +21203,8 @@ function extractTiersFromInner(inner) {
21101
21203
  function parseCompartmentOutput(text) {
21102
21204
  const compartments = [];
21103
21205
  const facts = [];
21206
+ let droppedFactBlocks = 0;
21207
+ let droppedFacts = 0;
21104
21208
  for (const match of text.matchAll(COMPARTMENT_REGEX)) {
21105
21209
  const attrs = match[1];
21106
21210
  const inner = match[2];
@@ -21150,16 +21254,21 @@ function parseCompartmentOutput(text) {
21150
21254
  }
21151
21255
  }
21152
21256
  const factsBlockMatch = text.match(FACTS_BLOCK_REGEX);
21153
- 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, "");
21154
21258
  for (const categoryMatch of factsScope.matchAll(CATEGORY_BLOCK_REGEX)) {
21155
21259
  const category = categoryMatch[1];
21156
21260
  const blockContent = categoryMatch[2];
21157
- for (const itemMatch of blockContent.matchAll(FACT_ITEM_REGEX)) {
21158
- const content = unescapeXml(itemMatch[1].trim());
21159
- if (content) {
21160
- facts.push({ category, content });
21161
- }
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;
21162
21269
  }
21270
+ for (const content of items)
21271
+ facts.push({ category, content });
21163
21272
  }
21164
21273
  const unprocessedMatch = text.match(UNPROCESSED_REGEX);
21165
21274
  const unprocessedFrom = unprocessedMatch ? parseInt(unprocessedMatch[1], 10) : null;
@@ -21197,7 +21306,16 @@ function parseCompartmentOutput(text) {
21197
21306
  }
21198
21307
  const events = parseEvents(text);
21199
21308
  compartments.sort((a, b) => a.startMessage - b.startMessage);
21200
- 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
+ };
21201
21319
  }
21202
21320
  function parseEvents(text) {
21203
21321
  const blockMatch = text.match(EVENTS_BLOCK_REGEX);
@@ -24093,6 +24211,20 @@ var MIGRATIONS = [
24093
24211
  return;
24094
24212
  ensureColumn(db, "compartment_state_lease", "owner_pid", "INTEGER");
24095
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
+ }
24096
24228
  }
24097
24229
  ];
24098
24230
  var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
@@ -24626,17 +24758,33 @@ function touch(sessionId, entry) {
24626
24758
  lkgHeapHolder.entries.delete(sessionId);
24627
24759
  lkgHeapHolder.entries.set(sessionId, entry);
24628
24760
  }
24629
- function captureSlot(sessionId, slot) {
24630
- 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))) {
24631
- 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}`;
24632
24773
  }
24633
24774
  const bytes = slotBytes(slot);
24634
24775
  if (bytes > LKG_SINGLE_SLOT_BYTES)
24635
- return false;
24776
+ return `slot_bytes=${bytes}`;
24636
24777
  const prior = lkgHeapHolder.entries.get(sessionId);
24637
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))) {
24638
- return false;
24779
+ return `stale row_version=${slot.rowVersion}/${prior.slot.rowVersion} capture_sequence=${slot.captureSequence ?? 0}/${prior.slot.captureSequence ?? 0}`;
24639
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);
24640
24788
  if (prior)
24641
24789
  totalBytes -= prior.bytes;
24642
24790
  lkgHeapHolder.entries.delete(sessionId);
@@ -25045,7 +25193,9 @@ function formatFailClosedBlockingMessage(reason) {
25045
25193
  }
25046
25194
  return [
25047
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}.`,
25048
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.",
25049
25199
  `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
25050
25200
  ].join(" ");
25051
25201
  }
@@ -25062,6 +25212,21 @@ function formatFailClosedBlockingMessage(reason) {
25062
25212
  `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
25063
25213
  ].join(" ");
25064
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
+ }
25065
25230
  function createFailClosedBlockingError(reason, options) {
25066
25231
  return new FailClosedBlockingError(formatFailClosedBlockingMessage(reason), reason, options);
25067
25232
  }
@@ -25423,7 +25588,7 @@ function getSchemaFenceRejection() {
25423
25588
  function getMigrationOnOpenRefusal() {
25424
25589
  return lastMigrationOnOpenRefusal;
25425
25590
  }
25426
- var LATEST_SUPPORTED_VERSION = 90;
25591
+ var LATEST_SUPPORTED_VERSION = 91;
25427
25592
  var BOOT_SQLITE_BUSY_TIMEOUT_MS = 5000;
25428
25593
  var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
25429
25594
  var defaultStoragePermissionFs = { chmodSync: chmodSync2, mkdirSync: mkdirSync3 };
@@ -25678,6 +25843,8 @@ function inspectRpcServerDiscovery(storageDir) {
25678
25843
  return junk;
25679
25844
  continue;
25680
25845
  }
25846
+ if (isOwnRpcServerRecord(record))
25847
+ continue;
25681
25848
  const liveness = isPidAlive(record.pid);
25682
25849
  if (liveness === "dead") {
25683
25850
  staleFiles.push(portFile);
@@ -25838,8 +26005,8 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
25838
26005
  { readRawSessionMessagePage, readRawSessionMessages },
25839
26006
  { startMessageTimeBackfill }
25840
26007
  ] = await Promise.all([
25841
- import("./read-session-chunk-53a7qbrh.js"),
25842
- import("./message-time-backfill-0ccvyk9n.js")
26008
+ import("./read-session-chunk-ktz5zt70.js"),
26009
+ import("./message-time-backfill-rm9wmcem.js")
25843
26010
  ]);
25844
26011
  await startMessageTimeBackfill(db, Object.assign(readRawSessionMessages, {
25845
26012
  readPage: readRawSessionMessagePage
@@ -26421,6 +26588,15 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
26421
26588
  (id, cursor_session_id, cursor_ordinal, completed, updated_at)
26422
26589
  VALUES (1, '', 0, 0, 0);
26423
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
+
26424
26600
  CREATE TABLE IF NOT EXISTS message_history_index (
26425
26601
  session_id TEXT PRIMARY KEY,
26426
26602
  last_indexed_ordinal INTEGER NOT NULL DEFAULT 0,
@@ -27500,7 +27676,19 @@ function noteCheckColumnsExist(db) {
27500
27676
  return false;
27501
27677
  }
27502
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.";
27503
27690
  function getNoteById(db, noteId) {
27691
+ healPendingSessionNotes(db);
27504
27692
  const row = db.prepare("SELECT * FROM notes WHERE id = ?").get(noteId);
27505
27693
  return isNoteRow(row) ? toNote(row) : null;
27506
27694
  }
@@ -27529,6 +27717,7 @@ function buildStatusClause(status) {
27529
27717
  };
27530
27718
  }
27531
27719
  function getNotes(db, options = {}) {
27720
+ healPendingSessionNotes(db);
27532
27721
  const clauses = [];
27533
27722
  const params = [];
27534
27723
  if (options.sessionId !== undefined) {
@@ -27580,6 +27769,9 @@ function updateNote(db, noteId, updates, scope) {
27580
27769
  if (!existing) {
27581
27770
  return null;
27582
27771
  }
27772
+ if (updates.surfaceCondition !== undefined && existing.type !== "smart") {
27773
+ return null;
27774
+ }
27583
27775
  const now = Date.now();
27584
27776
  const sets = ["updated_at = ?"];
27585
27777
  const params = [now];
@@ -27651,7 +27843,7 @@ function dismissNotes(db, noteIds, scope) {
27651
27843
  noteId,
27652
27844
  outcome: result.changes > 0 ? "dismissed" : "already_dismissed"
27653
27845
  };
27654
- }))();
27846
+ })).immediate();
27655
27847
  }
27656
27848
  function dismissNote(db, noteId, scope) {
27657
27849
  return dismissNotes(db, [noteId], scope)[0]?.outcome === "dismissed";
@@ -27929,7 +28121,7 @@ function insertPrimerCandidates(db, candidates) {
27929
28121
  if (typeof row?.id === "number")
27930
28122
  ids.push(row.id);
27931
28123
  }
27932
- })();
28124
+ }).immediate();
27933
28125
  return ids;
27934
28126
  }
27935
28127
  function updatePrimerCandidateEmbedding(db, candidateId, vector, modelId) {
@@ -27970,7 +28162,7 @@ function createPrimer(db, input) {
27970
28162
  source_candidate_ids, source_candidate_provenance, created_at, updated_at
27971
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);
27972
28164
  return Number(info.lastInsertRowid);
27973
- })();
28165
+ }).immediate();
27974
28166
  }
27975
28167
  function updatePrimerSupport(db, input) {
27976
28168
  db.transaction(() => {
@@ -27996,7 +28188,7 @@ function updatePrimerSupport(db, input) {
27996
28188
  source_candidate_provenance = ?,
27997
28189
  updated_at = ?
27998
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);
27999
- })();
28191
+ }).immediate();
28000
28192
  }
28001
28193
  function updatePrimerAnswer(db, primerId, answer, refreshedAt = Date.now()) {
28002
28194
  db.prepare("UPDATE primers SET answer = ?, answer_refreshed_at = ?, updated_at = ? WHERE id = ?").run(answer, refreshedAt, refreshedAt, primerId);
@@ -28165,7 +28357,7 @@ function insertUserMemoryCandidates(db, candidates) {
28165
28357
  for (const c of candidates) {
28166
28358
  stmt.run(c.content, c.sessionId, c.sourceCompartmentStart ?? null, c.sourceCompartmentEnd ?? null, now);
28167
28359
  }
28168
- })();
28360
+ }).immediate();
28169
28361
  logSlowWriteTransaction("user_memory_candidate_insert", transactionStartedAt);
28170
28362
  }
28171
28363
  function getUserMemoryCandidates(db) {
@@ -28224,7 +28416,7 @@ function insertUserMemory(db, content, sourceCandidateIds) {
28224
28416
  (content, status, promoted_at, source_candidate_ids, source_candidate_provenance, created_at, updated_at)
28225
28417
  VALUES (?, 'active', ?, ?, ?, ?, ?)`).run(content, now, JSON.stringify(sourceCandidateIds), serializeUserMemorySourceProvenance(sourceProvenance, sourceCandidateIds), now, now);
28226
28418
  return Number(result.lastInsertRowid);
28227
- })();
28419
+ }).immediate();
28228
28420
  }
28229
28421
  function getActiveUserMemories(db) {
28230
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();
@@ -28305,7 +28497,9 @@ var OVERFLOW_PATTERNS = [
28305
28497
  /prompt too long; exceeded (?:max )?context length/i,
28306
28498
  /too large for model with \d+ maximum context length/i,
28307
28499
  /model_context_window_exceeded/i,
28308
- /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
28309
28503
  ];
28310
28504
  var LIMIT_EXTRACTION_PATTERNS = [
28311
28505
  { pattern: /maximum prompt length is (\d+)/i, provenance: "prompt_only" },
@@ -28326,11 +28520,15 @@ var LIMIT_EXTRACTION_PATTERNS = [
28326
28520
  pattern: />\s*(\d+)\s*(?:tokens?\s*)?(?:maximum|max|limit)\b/i,
28327
28521
  provenance: "prompt_only"
28328
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" },
28329
28525
  { pattern: /max(?:imum)?.*context.*?(\d+)/i, provenance: "unknown" }
28330
28526
  ];
28331
28527
  var MIN_PLAUSIBLE_LIMIT = 1024;
28332
28528
  var MAX_PLAUSIBLE_LIMIT = 1e7;
28333
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+)`?/;
28334
28532
  function extractErrorMessage(error) {
28335
28533
  if (!error)
28336
28534
  return "";
@@ -28359,29 +28557,6 @@ function extractErrorMessage(error) {
28359
28557
  }
28360
28558
  return String(error);
28361
28559
  }
28362
- function extractThinkingBindingMessageId(error) {
28363
- if (!error || typeof error !== "object")
28364
- return;
28365
- const seen = new Set;
28366
- const queue = [error];
28367
- while (queue.length > 0) {
28368
- const current = queue.shift();
28369
- if (!current || seen.has(current))
28370
- continue;
28371
- seen.add(current);
28372
- const record = current;
28373
- for (const key of ["message_id", "messageID", "messageId"]) {
28374
- const value = record[key];
28375
- if (typeof value === "string" && value.length > 0)
28376
- return value;
28377
- }
28378
- for (const value of Object.values(record)) {
28379
- if (value && typeof value === "object")
28380
- queue.push(value);
28381
- }
28382
- }
28383
- return;
28384
- }
28385
28560
  function extractExplicitHttpStatus(error) {
28386
28561
  if (!error || typeof error !== "object")
28387
28562
  return;
@@ -28411,13 +28586,20 @@ function detectThinkingBindingMismatch(error) {
28411
28586
  if (explicitStatus !== undefined && explicitStatus !== 400 || !THINKING_BINDING_MISMATCH_PATTERN.test(message)) {
28412
28587
  return { isBindingMismatch: false };
28413
28588
  }
28414
- 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];
28415
28591
  return {
28416
28592
  isBindingMismatch: true,
28417
28593
  matchedPattern: "bound to a different conversation",
28418
- ...messageId ? { messageId } : {}
28594
+ ...failingBlockPath ? { failingBlockPath } : {},
28595
+ ...firstChangedPath ? { firstChangedPath } : {}
28419
28596
  };
28420
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
+ }
28421
28603
  function isFable51ThinkingBindingModel(providerID, modelID) {
28422
28604
  if (providerID?.toLowerCase() !== "anthropic" || !modelID)
28423
28605
  return false;
@@ -28489,6 +28671,203 @@ function parseReportedLimit(message) {
28489
28671
  return;
28490
28672
  }
28491
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
+
28492
28871
  // src/shared/assistant-message-extractor.ts
28493
28872
  function asSessionMessage(value) {
28494
28873
  if (!isRecord(value))
@@ -28587,6 +28966,14 @@ function copyPromptArgs(args, body) {
28587
28966
  return { ...args, body: { ...body } };
28588
28967
  }
28589
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
+ }
28590
28977
  function getPromptFailureDetail(error) {
28591
28978
  return error !== null && typeof error === "object" ? promptFailureDetails.get(error) ?? null : null;
28592
28979
  }
@@ -28643,9 +29030,13 @@ function parseModelSuggestion(error) {
28643
29030
  suggestion: suggestionMatch[1].trim()
28644
29031
  };
28645
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
+ }
28646
29037
  async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
28647
29038
  if (signal?.aborted) {
28648
- throw new Error("prompt aborted by external signal");
29039
+ throw new Error(externalAbortMessage(signal));
28649
29040
  }
28650
29041
  const controller = new AbortController;
28651
29042
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
@@ -28665,7 +29056,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
28665
29056
  if (!transport || transport.childSessionId) {
28666
29057
  await abortChildRun(client, transport?.childSessionId ?? args.path.id);
28667
29058
  }
28668
- throw new Error("prompt aborted by external signal");
29059
+ throw new Error(externalAbortMessage(signal));
28669
29060
  }
28670
29061
  if (controller.signal.aborted) {
28671
29062
  if (!transport || transport.childSessionId) {
@@ -28673,6 +29064,11 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
28673
29064
  }
28674
29065
  throw new Error(`prompt timed out after ${timeoutMs}ms`);
28675
29066
  }
29067
+ if (isHostTimeoutError(error)) {
29068
+ if (!transport || transport.childSessionId) {
29069
+ await abortChildRun(client, transport?.childSessionId ?? args.path.id);
29070
+ }
29071
+ }
28676
29072
  throw error;
28677
29073
  } finally {
28678
29074
  clearTimeout(timeout);
@@ -28682,7 +29078,7 @@ async function promptWithTimeout(client, args, timeoutMs, signal, transport) {
28682
29078
  if (!transport || transport.childSessionId) {
28683
29079
  await abortChildRun(client, transport?.childSessionId ?? args.path.id);
28684
29080
  }
28685
- 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`);
28686
29082
  }
28687
29083
  }
28688
29084
  async function abortChildRun(client, sessionId) {
@@ -28698,7 +29094,7 @@ async function abortChildRun(client, sessionId) {
28698
29094
  }
28699
29095
  }
28700
29096
  function isNonRetryable(error, externalSignal) {
28701
- if (externalSignal?.aborted)
29097
+ if (externalSignal?.aborted || error instanceof HiddenAgentStepLimit)
28702
29098
  return true;
28703
29099
  if (error instanceof Error) {
28704
29100
  if (error.name === "AbortError")
@@ -28708,6 +29104,8 @@ function isNonRetryable(error, externalSignal) {
28708
29104
  if (/^prompt timed out after \d+ms$/.test(error.message))
28709
29105
  return true;
28710
29106
  }
29107
+ if (isHostTimeoutError(error))
29108
+ return true;
28711
29109
  if (detectOverflow(error).isOverflow)
28712
29110
  return true;
28713
29111
  return false;
@@ -28720,11 +29118,14 @@ function shortErr(error) {
28720
29118
  }
28721
29119
  function classifyPromptFailure(error, phase, externalSignal) {
28722
29120
  const message = extractMessage(error);
29121
+ if (error instanceof HiddenAgentStepLimit)
29122
+ return "step_limit";
28723
29123
  if (externalSignal?.aborted || message === "prompt aborted by external signal") {
28724
29124
  return "child_aborted";
28725
29125
  }
28726
- if (/^prompt timed out after \d+ms$/.test(message))
29126
+ if (/^prompt timed out after \d+ms$/.test(message) || isHostTimeoutError(error)) {
28727
29127
  return "provider_timeout";
29128
+ }
28728
29129
  if (phase === "validation") {
28729
29130
  if (/returned no (?:assistant )?output|no assistant output/i.test(message)) {
28730
29131
  return "empty_completion";
@@ -28941,7 +29342,10 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
28941
29342
  }
28942
29343
  }
28943
29344
  log(`[${callContext}] all models exhausted; tried: ${failedAttempts.map((failure) => failure.attempt.label).join(", ")}; original error: ${shortErr(firstError)}; last error: ${shortErr(lastError)}`);
28944
- 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);
28945
29349
  }
28946
29350
  // src/shared/normalize-sdk-response.ts
28947
29351
  function normalizeSDKResponse(response, fallback, options) {
@@ -28966,6 +29370,149 @@ function normalizeSDKResponse(response, fallback, options) {
28966
29370
  }
28967
29371
  return fallback;
28968
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
+ }
28969
29516
  // src/shared/prompt-surface-runtime.ts
28970
29517
  import { existsSync as existsSync6, readFileSync as readFileSync5, statSync as statSync7 } from "node:fs";
28971
29518
  import { dirname as dirname4, isAbsolute as isAbsolute2, resolve as resolve2 } from "node:path";
@@ -29803,7 +30350,7 @@ function injectCompactionMarker(args) {
29803
30350
  time_created = excluded.time_created,
29804
30351
  time_updated = excluded.time_updated,
29805
30352
  data = excluded.data`).run(summaryPartId, summaryMsgId, args.sessionId, boundaryTime + 1, boundaryTime + 1, JSON.stringify({ type: "text", text: args.summaryText }));
29806
- })();
30353
+ }).immediate();
29807
30354
  log(`[magic-context] compaction-marker: injected boundary at user msg ${boundary.id} (ordinal ~${args.endOrdinal}), summary msg ${summaryMsgId}`);
29808
30355
  return {
29809
30356
  boundaryMessageId: boundary.id,
@@ -29896,7 +30443,7 @@ function removeForeignCompactionMarker(sessionId, marker, protectedSummaryMessag
29896
30443
  deleteMessage.run(sessionId, summaryMessageId);
29897
30444
  }
29898
30445
  db.prepare("DELETE FROM part WHERE session_id = ? AND id = ?").run(sessionId, marker.compactionPartId);
29899
- })();
30446
+ }).immediate();
29900
30447
  return true;
29901
30448
  } catch (error) {
29902
30449
  log(`[magic-context] compaction-marker: foreign-marker removal failed (${sessionId}, part ${marker.compactionPartId}): ${error instanceof Error ? error.message : String(error)}`);
@@ -30038,7 +30585,7 @@ function removeMcOwnedCompactionMarkers(sessionId, summaryText) {
30038
30585
  changed += deletePart.run(sessionId, partId).changes;
30039
30586
  }
30040
30587
  return changed;
30041
- })();
30588
+ }).immediate();
30042
30589
  if (rows > 0 || summaryIds.size > 0 || mcPartIds.length > 0) {
30043
30590
  removedLineages += 1;
30044
30591
  removedRows += rows;
@@ -30051,7 +30598,7 @@ function removeMcOwnedCompactionMarkers(sessionId, summaryText) {
30051
30598
  if (survivingPartsReferenceDeletion || messageFieldReferencesDeletion) {
30052
30599
  retainedLineages += 1;
30053
30600
  } else {
30054
- const rows = db.transaction(() => deleteSummaries(orphanSummaryIds))();
30601
+ const rows = db.transaction(() => deleteSummaries(orphanSummaryIds)).immediate();
30055
30602
  removedLineages += 1;
30056
30603
  removedRows += rows;
30057
30604
  }
@@ -30073,7 +30620,7 @@ function removeCompactionMarker(state) {
30073
30620
  db.prepare("DELETE FROM part WHERE id = ?").run(state.summaryPartId);
30074
30621
  db.prepare("DELETE FROM message WHERE id = ?").run(state.summaryMessageId);
30075
30622
  db.prepare("DELETE FROM part WHERE id = ?").run(state.compactionPartId);
30076
- })();
30623
+ }).immediate();
30077
30624
  return true;
30078
30625
  } catch (error) {
30079
30626
  log(`[magic-context] compaction-marker: removal failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -30095,7 +30642,7 @@ function persistMarkerStateAndDropReplacedTag(db, sessionId, state, replacedSumm
30095
30642
  if (replacedSummaryMessageId !== null) {
30096
30643
  dropMarkerSummaryTag(db, sessionId, replacedSummaryMessageId);
30097
30644
  }
30098
- })();
30645
+ }).immediate();
30099
30646
  logSlowWriteTransaction("marker-drain", transactionStartedAt);
30100
30647
  }
30101
30648
  function validatePendingTarget(db, sessionId, pending) {
@@ -31326,6 +31873,9 @@ function failedInvocationStatus(error) {
31326
31873
  const message = describeError(error).brief;
31327
31874
  if (/timed out after \d+ms|prompt timed out/i.test(message))
31328
31875
  return "timed_out";
31876
+ if (error !== null && typeof error === "object" && error.name === "TimeoutError") {
31877
+ return "timed_out";
31878
+ }
31329
31879
  if (/length-capped|no (?:assistant )?output|empty (?:assistant )?(?:output|text)/i.test(message)) {
31330
31880
  return "empty";
31331
31881
  }
@@ -31524,18 +32074,6 @@ async function createChildSessionWithFence(args) {
31524
32074
  });
31525
32075
  }
31526
32076
 
31527
- // src/hooks/magic-context/compartment-runner-types.ts
31528
- class HiddenCompletionRefusal extends Error {
31529
- code;
31530
- terminal;
31531
- constructor(code, message, terminal = false) {
31532
- super(`${code}: ${message}`);
31533
- this.code = code;
31534
- this.terminal = terminal;
31535
- this.name = "HiddenCompletionRefusal";
31536
- }
31537
- }
31538
-
31539
32077
  // src/hooks/magic-context/compartment-runner-mapping.ts
31540
32078
  function tierFieldsOf(c) {
31541
32079
  return {
@@ -31623,7 +32161,7 @@ function shouldDiscardLastHistorianCompartment(compartments, chunk) {
31623
32161
  function validateHistorianOutput(text, sessionId, chunk, _priorCompartments, sequenceOffset) {
31624
32162
  const parseStarted = startHistorianPublishStage(sessionId, "parse", `response_chars=${text.length}`);
31625
32163
  const parsed = parseCompartmentOutput(text);
31626
- 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}`);
31627
32165
  const validationStarted = startHistorianPublishStage(sessionId, "validate");
31628
32166
  const finish = (result) => {
31629
32167
  finishHistorianPublishStage(sessionId, "validate", validationStarted, result.ok ? "completed" : "failed", result.ok ? `compartments=${result.compartments.length}` : `reason=${JSON.stringify(result.error)}`);
@@ -31662,6 +32200,7 @@ function validateHistorianOutput(text, sessionId, chunk, _priorCompartments, seq
31662
32200
  ok: true,
31663
32201
  compartments: mapped.compartments,
31664
32202
  facts: parsed.facts,
32203
+ ...parsed.droppedFactBlocks > 0 ? { droppedFactBlocks: parsed.droppedFactBlocks, droppedFacts: parsed.droppedFacts } : {},
31665
32204
  userObservations: parsed.userObservations.length > 0 ? parsed.userObservations : undefined,
31666
32205
  primerCandidates: parsed.primerCandidates.length > 0 ? parsed.primerCandidates.slice(0, 1) : undefined,
31667
32206
  events: parsed.events.length > 0 ? parsed.events : undefined
@@ -31922,6 +32461,7 @@ function resolveHiddenCompletionExecutor(executor, client, db, directory, entryP
31922
32461
  return createV1HiddenCompletionExecutor(client, db, directory);
31923
32462
  }
31924
32463
  function createV1HiddenCompletionExecutor(client, db, directory) {
32464
+ const asyncChildren = new Set;
31925
32465
  return {
31926
32466
  capabilities: { tools: true, harness: "opencode" },
31927
32467
  async open(run) {
@@ -31938,11 +32478,17 @@ function createV1HiddenCompletionExecutor(client, db, directory) {
31938
32478
  preferResponseOnMissingData: true
31939
32479
  });
31940
32480
  const id = typeof created?.id === "string" ? created.id : "";
32481
+ if (id && run.kind === "dreamer-task")
32482
+ asyncChildren.add(id);
31941
32483
  return { id, childSessionId: id || undefined };
31942
32484
  },
31943
- async attempt(_handle, request) {
32485
+ async attempt(handle, request) {
31944
32486
  if (!client)
31945
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
+ }
31946
32492
  await client.session.prompt(request);
31947
32493
  },
31948
32494
  async collect(handle, limit) {
@@ -31970,6 +32516,8 @@ function createV1HiddenCompletionExecutor(client, db, directory) {
31970
32516
  };
31971
32517
  },
31972
32518
  async close(handle, settlement) {
32519
+ if (handle?.id)
32520
+ asyncChildren.delete(handle.id);
31973
32521
  if (!client)
31974
32522
  return;
31975
32523
  await teardownChildSession({
@@ -31981,6 +32529,9 @@ function createV1HiddenCompletionExecutor(client, db, directory) {
31981
32529
  }
31982
32530
  };
31983
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
+ }
31984
32535
  async function runValidatedHistorianPass(args) {
31985
32536
  const firstRun = await runHistorianPrompt({
31986
32537
  ...args,
@@ -32207,14 +32758,14 @@ async function runHistorianPrompt(args) {
32207
32758
  }
32208
32759
  const backoffMs = getHistorianRetryBackoffMs(retryIndex);
32209
32760
  sessionLog(parentSessionId, `historian retry ${retryIndex + 1}/${MAX_HISTORIAN_RETRIES} after ${backoffMs}ms: ${errorMsg}`);
32210
- await sleep(backoffMs);
32761
+ await sleep2(backoffMs);
32211
32762
  }
32212
32763
  }
32213
32764
  completion = await executor.collect(handle, 50);
32214
32765
  const lengthCapped = completion.lengthCapped;
32215
32766
  const textResult = completion.text;
32216
32767
  const reasoningResult = textResult ? null : completion.reasoning;
32217
- 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;
32218
32769
  const invocationId = recordInvocation({
32219
32770
  status: emptyError ? "empty" : "completed",
32220
32771
  messages: completion.messages,
@@ -32344,7 +32895,7 @@ function isTransientHistorianPromptError(message) {
32344
32895
  "overloaded"
32345
32896
  ].some((token) => normalized.includes(token));
32346
32897
  }
32347
- function sleep(ms) {
32898
+ function sleep2(ms) {
32348
32899
  return new Promise((resolve) => {
32349
32900
  setTimeout(resolve, ms);
32350
32901
  });
@@ -34306,6 +34857,10 @@ function mustMaterialize(args) {
34306
34857
  if (hard.cacheExpired && hard.lastResponseTime > 0 && hard.lastResponseTime > (args.state.cachedM0MaterializedAt ?? 0)) {
34307
34858
  return withToolSetHashComparison({ value: true, reason: "ttl_idle" });
34308
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
+ }
34309
34864
  if (current.projectIdentity !== null) {
34310
34865
  const cachedProjectIdentity = args.state.cachedM0ProjectIdentity ?? null;
34311
34866
  if (cachedProjectIdentity === null) {
@@ -34823,6 +35378,11 @@ function materializeM0(options) {
34823
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);
34824
35379
  const baselineEndMessageId = lastCompartmentBoundaryId(compartments);
34825
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
+ });
34826
35386
  options.db.exec("COMMIT");
34827
35387
  logSlowWriteTransaction("opencode_materialize_cache", transactionStartedAt);
34828
35388
  options.state.cachedM0MuralDataUrl = frozenMuralDataUrl;
@@ -35002,6 +35562,15 @@ function parseMemoryBlockIds(raw) {
35002
35562
  return [];
35003
35563
  }
35004
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
+ }
35005
35574
  function readCachedM0M1Row(db, sessionId) {
35006
35575
  return db.prepare(`SELECT cached_m0_bytes, cached_m0_mural_data_url,
35007
35576
  cached_m0_mural_hash, cached_m1_bytes,
@@ -35254,6 +35823,114 @@ function findBoundaryIndex(sessionId, messages, boundaryId) {
35254
35823
  return -1;
35255
35824
  return messages.findIndex((message) => message.info.id === served);
35256
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
+ }
35257
35934
  function isSyntheticPrefixHead(message) {
35258
35935
  if (message.info.id !== undefined || message.info.role !== "user" || message.parts.length === 0) {
35259
35936
  return false;
@@ -35358,10 +36035,10 @@ function trimToPreparedPrefix(options, prepared) {
35358
36035
  const index = findBoundaryIndex(options.sessionId, options.messages, boundary);
35359
36036
  if (index >= 0) {
35360
36037
  options.messages.splice(0, index + 1);
36038
+ resetPrefixTrimFallbackState(options.sessionId);
35361
36039
  status = "applied";
35362
36040
  } else {
35363
- sessionLog(options.sessionId, `prefix trim: boundary ${boundary} absent from current messages; pass=${options.isCacheBustingPass ? "priced" : "defer"}; no in-pass trim applied`);
35364
- status = "refused";
36041
+ status = classifyAbsentBoundary(options, options.messages, boundary);
35365
36042
  }
35366
36043
  }
35367
36044
  }
@@ -35410,13 +36087,7 @@ function injectM0M1(options) {
35410
36087
  prefixTrimStatus
35411
36088
  };
35412
36089
  }
35413
- if (options.state.cachedM0Bytes && options.state.cachedM0MuralDataUrl === undefined) {
35414
- const row = readCachedM0M1Row(options.db, options.sessionId);
35415
- if (row && bufferEqualsNullable(row.cached_m0_bytes, options.state.cachedM0Bytes)) {
35416
- options.state.cachedM0MuralDataUrl = row.cached_m0_mural_data_url ?? null;
35417
- options.state.cachedM0MuralHash = row.cached_m0_mural_hash ?? null;
35418
- }
35419
- }
36090
+ hydrateCachedM0Mural(options.db, options.sessionId, options.state);
35420
36091
  if (!options.workspaceIdentitySet && options.projectPath) {
35421
36092
  options = {
35422
36093
  ...options,
@@ -35846,7 +36517,7 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
35846
36517
  }
35847
36518
  ]);
35848
36519
  return true;
35849
- })();
36520
+ }).immediate();
35850
36521
  if (saved)
35851
36522
  sessionLog(sessionId, `historian skipped ordinals ${start}-${eligibleEnd - 1}: all ${rows.length} raw rows excluded by chunk filters (no-content boundary marker)`);
35852
36523
  return saved;
@@ -38794,8 +39465,8 @@ ${chunkText}`,
38794
39465
  const discardedLast = persistedCompartments.length < emittedCompartments.length;
38795
39466
  const weakLookaheadFinalCompartment = forceKeepLastCompartmentForChunk;
38796
39467
  const skipUnanchoredPromotion = discardedLast || weakLookaheadFinalCompartment;
38797
- const embeddingActive = !!promotionDirectory && deps.memoryEnabled !== false;
38798
- const promotionActive = embeddingActive && deps.autoPromote !== false;
39468
+ const embeddingActive = !!promotionDirectory;
39469
+ const promotionActive = embeddingActive && deps.memoryEnabled !== false && deps.autoPromote !== false;
38799
39470
  const promotionProjectIdentity = promotionDirectory ? resolveProjectIdentity(promotionDirectory) : "";
38800
39471
  const publishableEvents = (validatedPass.events ?? []).filter((e) => {
38801
39472
  if (typeof e.atCompartment !== "number")
@@ -39175,7 +39846,7 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
39175
39846
  clearInjectionCache(sessionId);
39176
39847
  }
39177
39848
  promoted.facts;
39178
- if (deps.memoryEnabled !== false) {
39849
+ {
39179
39850
  const projectIdentity = resolveProjectIdentity(sessionDirectory);
39180
39851
  await deps.ensureProjectRegistered?.(sessionDirectory, db);
39181
39852
  const liveCompartments = getCompartments(db, sessionId);
@@ -39392,7 +40063,7 @@ Another process acquired the compartment-state lease before recomp could publish
39392
40063
  queueDropsForCompartmentalizedMessages(db, sessionId, lastCompartmentEnd, compartmentTagKeys);
39393
40064
  }
39394
40065
  deps.onCompartmentStatePublished?.(sessionId);
39395
- if (deps.memoryEnabled !== false) {
40066
+ {
39396
40067
  const projectIdentity = resolveProjectIdentity(sessionDirectory);
39397
40068
  await deps.ensureProjectRegistered?.(sessionDirectory, db);
39398
40069
  const liveCompartments = getCompartments(db, sessionId);
@@ -39554,7 +40225,7 @@ Could not acquire the compartment-state lease for this session.`;
39554
40225
  clearInjectionCache(sessionId);
39555
40226
  }
39556
40227
  deps.onCompartmentStatePublished?.(sessionId);
39557
- if (deps.memoryEnabled !== false) {
40228
+ {
39558
40229
  const projectIdentity = resolveProjectIdentity(sessionDirectory);
39559
40230
  const liveCompartments = getCompartments(db, sessionId);
39560
40231
  const chunksToEmbed = liveCompartments.map((c) => ({
@@ -40033,4 +40704,4 @@ ${failure}`;
40033
40704
  }
40034
40705
  }
40035
40706
 
40036
- 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 };