@animalabs/agent-framework 0.32.0 → 0.34.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 (368) hide show
  1. package/README.md +340 -22
  2. package/dist/src/admission/admit.d.ts +18 -0
  3. package/dist/src/admission/admit.d.ts.map +1 -1
  4. package/dist/src/admission/admit.js +16 -3
  5. package/dist/src/admission/admit.js.map +1 -1
  6. package/dist/src/agent.d.ts +208 -80
  7. package/dist/src/agent.d.ts.map +1 -1
  8. package/dist/src/agent.js +345 -113
  9. package/dist/src/agent.js.map +1 -1
  10. package/dist/src/api/mcp-server-core.d.ts.map +1 -1
  11. package/dist/src/api/mcp-server-core.js +50 -12
  12. package/dist/src/api/mcp-server-core.js.map +1 -1
  13. package/dist/src/api/server.d.ts.map +1 -1
  14. package/dist/src/api/server.js +4 -20
  15. package/dist/src/api/server.js.map +1 -1
  16. package/dist/src/append-all.d.ts +5 -0
  17. package/dist/src/append-all.d.ts.map +1 -0
  18. package/dist/src/append-all.js +8 -0
  19. package/dist/src/append-all.js.map +1 -0
  20. package/dist/src/code-execution/isolate/scripts.d.ts +12 -8
  21. package/dist/src/code-execution/isolate/scripts.d.ts.map +1 -1
  22. package/dist/src/code-execution/isolate/scripts.js +24 -0
  23. package/dist/src/code-execution/isolate/scripts.js.map +1 -1
  24. package/dist/src/config-checks.d.ts +7 -0
  25. package/dist/src/config-checks.d.ts.map +1 -1
  26. package/dist/src/config-checks.js +14 -0
  27. package/dist/src/config-checks.js.map +1 -1
  28. package/dist/src/context-manager-errors.d.ts +25 -0
  29. package/dist/src/context-manager-errors.d.ts.map +1 -0
  30. package/dist/src/context-manager-errors.js +31 -0
  31. package/dist/src/context-manager-errors.js.map +1 -0
  32. package/dist/src/context-options.d.ts +70 -0
  33. package/dist/src/context-options.d.ts.map +1 -0
  34. package/dist/src/context-options.js +90 -0
  35. package/dist/src/context-options.js.map +1 -0
  36. package/dist/src/cut-off-round.js +4 -4
  37. package/dist/src/deferred-import.d.ts +93 -0
  38. package/dist/src/deferred-import.d.ts.map +1 -0
  39. package/dist/src/deferred-import.js +177 -0
  40. package/dist/src/deferred-import.js.map +1 -0
  41. package/dist/src/dendrite/audience.d.ts +223 -0
  42. package/dist/src/dendrite/audience.d.ts.map +1 -0
  43. package/dist/src/dendrite/audience.js +202 -0
  44. package/dist/src/dendrite/audience.js.map +1 -0
  45. package/dist/src/dendrite/index.d.ts +5 -3
  46. package/dist/src/dendrite/index.d.ts.map +1 -1
  47. package/dist/src/dendrite/index.js +2 -1
  48. package/dist/src/dendrite/index.js.map +1 -1
  49. package/dist/src/dendrite/presets.d.ts +10 -5
  50. package/dist/src/dendrite/presets.d.ts.map +1 -1
  51. package/dist/src/dendrite/presets.js +17 -5
  52. package/dist/src/dendrite/presets.js.map +1 -1
  53. package/dist/src/dendrite/registry.d.ts +62 -7
  54. package/dist/src/dendrite/registry.d.ts.map +1 -1
  55. package/dist/src/dendrite/registry.js +183 -12
  56. package/dist/src/dendrite/registry.js.map +1 -1
  57. package/dist/src/dendrite/types.d.ts +91 -8
  58. package/dist/src/dendrite/types.d.ts.map +1 -1
  59. package/dist/src/failure-text.d.ts +36 -0
  60. package/dist/src/failure-text.d.ts.map +1 -0
  61. package/dist/src/failure-text.js +89 -0
  62. package/dist/src/failure-text.js.map +1 -0
  63. package/dist/src/foreign-rounds.d.ts +69 -0
  64. package/dist/src/foreign-rounds.d.ts.map +1 -0
  65. package/dist/src/foreign-rounds.js +152 -0
  66. package/dist/src/foreign-rounds.js.map +1 -0
  67. package/dist/src/framework.d.ts +2064 -842
  68. package/dist/src/framework.d.ts.map +1 -1
  69. package/dist/src/framework.js +8586 -3739
  70. package/dist/src/framework.js.map +1 -1
  71. package/dist/src/gate/event-gate.d.ts +125 -21
  72. package/dist/src/gate/event-gate.d.ts.map +1 -1
  73. package/dist/src/gate/event-gate.js +487 -72
  74. package/dist/src/gate/event-gate.js.map +1 -1
  75. package/dist/src/gate/index.d.ts +1 -1
  76. package/dist/src/gate/index.d.ts.map +1 -1
  77. package/dist/src/gate/index.js.map +1 -1
  78. package/dist/src/gate/reply-judge.d.ts +4 -0
  79. package/dist/src/gate/reply-judge.d.ts.map +1 -1
  80. package/dist/src/gate/reply-judge.js +12 -3
  81. package/dist/src/gate/reply-judge.js.map +1 -1
  82. package/dist/src/gate/rule-scope.d.ts +30 -0
  83. package/dist/src/gate/rule-scope.d.ts.map +1 -0
  84. package/dist/src/gate/rule-scope.js +41 -0
  85. package/dist/src/gate/rule-scope.js.map +1 -0
  86. package/dist/src/gate/suppress-script-worker.d.ts +2 -0
  87. package/dist/src/gate/suppress-script-worker.d.ts.map +1 -0
  88. package/dist/src/gate/suppress-script-worker.js +103 -0
  89. package/dist/src/gate/suppress-script-worker.js.map +1 -0
  90. package/dist/src/gate/suppress-scripts.d.ts +105 -0
  91. package/dist/src/gate/suppress-scripts.d.ts.map +1 -0
  92. package/dist/src/gate/suppress-scripts.js +403 -0
  93. package/dist/src/gate/suppress-scripts.js.map +1 -0
  94. package/dist/src/gate/suppression-review.d.ts +143 -0
  95. package/dist/src/gate/suppression-review.d.ts.map +1 -0
  96. package/dist/src/gate/suppression-review.js +463 -0
  97. package/dist/src/gate/suppression-review.js.map +1 -0
  98. package/dist/src/gate/suppression-stats.d.ts +125 -0
  99. package/dist/src/gate/suppression-stats.d.ts.map +1 -0
  100. package/dist/src/gate/suppression-stats.js +214 -0
  101. package/dist/src/gate/suppression-stats.js.map +1 -0
  102. package/dist/src/gate/types.d.ts +142 -7
  103. package/dist/src/gate/types.d.ts.map +1 -1
  104. package/dist/src/gate/wake-onboarding.d.ts +119 -0
  105. package/dist/src/gate/wake-onboarding.d.ts.map +1 -0
  106. package/dist/src/gate/wake-onboarding.js +277 -0
  107. package/dist/src/gate/wake-onboarding.js.map +1 -0
  108. package/dist/src/heartbeat/heartbeat.js +1 -1
  109. package/dist/src/heartbeat/heartbeat.js.map +1 -1
  110. package/dist/src/held-writes.d.ts +31 -23
  111. package/dist/src/held-writes.d.ts.map +1 -1
  112. package/dist/src/held-writes.js +44 -59
  113. package/dist/src/held-writes.js.map +1 -1
  114. package/dist/src/index.d.ts +6 -2
  115. package/dist/src/index.d.ts.map +1 -1
  116. package/dist/src/index.js +4 -0
  117. package/dist/src/index.js.map +1 -1
  118. package/dist/src/inference-bounds.d.ts +2 -1
  119. package/dist/src/inference-bounds.d.ts.map +1 -1
  120. package/dist/src/inference-bounds.js +9 -6
  121. package/dist/src/inference-bounds.js.map +1 -1
  122. package/dist/src/jsonrpc-envelope.d.ts +69 -0
  123. package/dist/src/jsonrpc-envelope.d.ts.map +1 -0
  124. package/dist/src/jsonrpc-envelope.js +66 -0
  125. package/dist/src/jsonrpc-envelope.js.map +1 -0
  126. package/dist/src/mcpl/channel-registry.d.ts +188 -28
  127. package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
  128. package/dist/src/mcpl/channel-registry.js +426 -70
  129. package/dist/src/mcpl/channel-registry.js.map +1 -1
  130. package/dist/src/mcpl/checkpoint-manager.d.ts +2 -4
  131. package/dist/src/mcpl/checkpoint-manager.d.ts.map +1 -1
  132. package/dist/src/mcpl/checkpoint-manager.js.map +1 -1
  133. package/dist/src/mcpl/feature-set-manager.d.ts +2 -4
  134. package/dist/src/mcpl/feature-set-manager.d.ts.map +1 -1
  135. package/dist/src/mcpl/feature-set-manager.js.map +1 -1
  136. package/dist/src/mcpl/inbound-source.d.ts +2 -1
  137. package/dist/src/mcpl/inbound-source.d.ts.map +1 -1
  138. package/dist/src/mcpl/inbound-source.js +2 -1
  139. package/dist/src/mcpl/inbound-source.js.map +1 -1
  140. package/dist/src/mcpl/inference-router.d.ts +6 -6
  141. package/dist/src/mcpl/inference-router.d.ts.map +1 -1
  142. package/dist/src/mcpl/inference-router.js.map +1 -1
  143. package/dist/src/mcpl/modern-connection.d.ts +109 -15
  144. package/dist/src/mcpl/modern-connection.d.ts.map +1 -1
  145. package/dist/src/mcpl/modern-connection.js +593 -86
  146. package/dist/src/mcpl/modern-connection.js.map +1 -1
  147. package/dist/src/mcpl/protocol-family.d.ts +3 -1
  148. package/dist/src/mcpl/protocol-family.d.ts.map +1 -1
  149. package/dist/src/mcpl/protocol-family.js +15 -9
  150. package/dist/src/mcpl/protocol-family.js.map +1 -1
  151. package/dist/src/mcpl/push-coalescer.d.ts +132 -22
  152. package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
  153. package/dist/src/mcpl/push-coalescer.js +105 -15
  154. package/dist/src/mcpl/push-coalescer.js.map +1 -1
  155. package/dist/src/mcpl/push-handler.d.ts +9 -7
  156. package/dist/src/mcpl/push-handler.d.ts.map +1 -1
  157. package/dist/src/mcpl/push-handler.js.map +1 -1
  158. package/dist/src/mcpl/server-connection.d.ts +50 -28
  159. package/dist/src/mcpl/server-connection.d.ts.map +1 -1
  160. package/dist/src/mcpl/server-connection.js +165 -72
  161. package/dist/src/mcpl/server-connection.js.map +1 -1
  162. package/dist/src/mcpl/tool-classes.d.ts.map +1 -1
  163. package/dist/src/mcpl/tool-classes.js +3 -0
  164. package/dist/src/mcpl/tool-classes.js.map +1 -1
  165. package/dist/src/mcpl/tool-presence.d.ts.map +1 -1
  166. package/dist/src/mcpl/tool-presence.js +10 -6
  167. package/dist/src/mcpl/tool-presence.js.map +1 -1
  168. package/dist/src/mcpl/toolset-host.d.ts.map +1 -1
  169. package/dist/src/mcpl/toolset-host.js +7 -6
  170. package/dist/src/mcpl/toolset-host.js.map +1 -1
  171. package/dist/src/mcpl/toolsets-module.d.ts.map +1 -1
  172. package/dist/src/mcpl/toolsets-module.js +2 -1
  173. package/dist/src/mcpl/toolsets-module.js.map +1 -1
  174. package/dist/src/mcpl/types.d.ts +33 -6
  175. package/dist/src/mcpl/types.d.ts.map +1 -1
  176. package/dist/src/mcpl/types.js.map +1 -1
  177. package/dist/src/module-registry.d.ts +24 -1
  178. package/dist/src/module-registry.d.ts.map +1 -1
  179. package/dist/src/module-registry.js +68 -18
  180. package/dist/src/module-registry.js.map +1 -1
  181. package/dist/src/modules/discord/index.d.ts +45 -8
  182. package/dist/src/modules/discord/index.d.ts.map +1 -1
  183. package/dist/src/modules/discord/index.js +238 -87
  184. package/dist/src/modules/discord/index.js.map +1 -1
  185. package/dist/src/modules/health/index.js +2 -2
  186. package/dist/src/modules/health/index.js.map +1 -1
  187. package/dist/src/modules/history/index.d.ts +59 -0
  188. package/dist/src/modules/history/index.d.ts.map +1 -1
  189. package/dist/src/modules/history/index.js +432 -67
  190. package/dist/src/modules/history/index.js.map +1 -1
  191. package/dist/src/modules/history/semantic.d.ts +6 -5
  192. package/dist/src/modules/history/semantic.d.ts.map +1 -1
  193. package/dist/src/modules/history/semantic.js +18 -25
  194. package/dist/src/modules/history/semantic.js.map +1 -1
  195. package/dist/src/modules/workspace/disk-agreement.d.ts +1 -1
  196. package/dist/src/modules/workspace/disk-agreement.js +1 -1
  197. package/dist/src/modules/workspace/index.d.ts +28 -7
  198. package/dist/src/modules/workspace/index.d.ts.map +1 -1
  199. package/dist/src/modules/workspace/index.js +80 -25
  200. package/dist/src/modules/workspace/index.js.map +1 -1
  201. package/dist/src/modules/workspace/observe.d.ts.map +1 -1
  202. package/dist/src/modules/workspace/observe.js +2 -1
  203. package/dist/src/modules/workspace/observe.js.map +1 -1
  204. package/dist/src/modules/workspace/reconcile.d.ts.map +1 -1
  205. package/dist/src/modules/workspace/reconcile.js +3 -2
  206. package/dist/src/modules/workspace/reconcile.js.map +1 -1
  207. package/dist/src/notice-tags.d.ts +20 -9
  208. package/dist/src/notice-tags.d.ts.map +1 -1
  209. package/dist/src/notice-tags.js +20 -9
  210. package/dist/src/notice-tags.js.map +1 -1
  211. package/dist/src/operator-log.d.ts +36 -3
  212. package/dist/src/operator-log.d.ts.map +1 -1
  213. package/dist/src/operator-log.js +2 -2
  214. package/dist/src/operator-log.js.map +1 -1
  215. package/dist/src/presentation.d.ts +747 -0
  216. package/dist/src/presentation.d.ts.map +1 -0
  217. package/dist/src/presentation.js +1437 -0
  218. package/dist/src/presentation.js.map +1 -0
  219. package/dist/src/prose-drafts.d.ts +15 -11
  220. package/dist/src/prose-drafts.d.ts.map +1 -1
  221. package/dist/src/prose-drafts.js +16 -12
  222. package/dist/src/prose-drafts.js.map +1 -1
  223. package/dist/src/read-marks.d.ts +192 -0
  224. package/dist/src/read-marks.d.ts.map +1 -0
  225. package/dist/src/read-marks.js +242 -0
  226. package/dist/src/read-marks.js.map +1 -0
  227. package/dist/src/reasoning-loss.d.ts +5 -0
  228. package/dist/src/reasoning-loss.d.ts.map +1 -0
  229. package/dist/src/reasoning-loss.js +8 -0
  230. package/dist/src/reasoning-loss.js.map +1 -0
  231. package/dist/src/recovery/offline-branch.d.ts +91 -6
  232. package/dist/src/recovery/offline-branch.d.ts.map +1 -1
  233. package/dist/src/recovery/offline-branch.js +277 -32
  234. package/dist/src/recovery/offline-branch.js.map +1 -1
  235. package/dist/src/recovery/recover-cli.js +24 -4
  236. package/dist/src/recovery/recover-cli.js.map +1 -1
  237. package/dist/src/send-tools.d.ts +5 -9
  238. package/dist/src/send-tools.d.ts.map +1 -1
  239. package/dist/src/send-tools.js +40 -7
  240. package/dist/src/send-tools.js.map +1 -1
  241. package/dist/src/sent-rows.js +1 -1
  242. package/dist/src/stored-injections.d.ts +2 -2
  243. package/dist/src/stored-injections.js +2 -2
  244. package/dist/src/stored-removal.d.ts +17 -4
  245. package/dist/src/stored-removal.d.ts.map +1 -1
  246. package/dist/src/stored-removal.js +29 -5
  247. package/dist/src/stored-removal.js.map +1 -1
  248. package/dist/src/supplied-text.d.ts +1 -1
  249. package/dist/src/supplied-text.js +3 -3
  250. package/dist/src/supplied-text.js.map +1 -1
  251. package/dist/src/thinking-drops.d.ts +2 -0
  252. package/dist/src/thinking-drops.d.ts.map +1 -1
  253. package/dist/src/thinking-drops.js.map +1 -1
  254. package/dist/src/tool-presentation.d.ts.map +1 -1
  255. package/dist/src/tool-presentation.js +38 -9
  256. package/dist/src/tool-presentation.js.map +1 -1
  257. package/dist/src/tool-result-guard.d.ts +12 -1
  258. package/dist/src/tool-result-guard.d.ts.map +1 -1
  259. package/dist/src/tool-result-guard.js +42 -8
  260. package/dist/src/tool-result-guard.js.map +1 -1
  261. package/dist/src/tune-out/coordinator.d.ts +1170 -81
  262. package/dist/src/tune-out/coordinator.d.ts.map +1 -1
  263. package/dist/src/tune-out/coordinator.js +3732 -369
  264. package/dist/src/tune-out/coordinator.js.map +1 -1
  265. package/dist/src/tune-out/tools.d.ts +114 -17
  266. package/dist/src/tune-out/tools.d.ts.map +1 -1
  267. package/dist/src/tune-out/tools.js +89 -28
  268. package/dist/src/tune-out/tools.js.map +1 -1
  269. package/dist/src/tune-out/window-anchor.d.ts +143 -0
  270. package/dist/src/tune-out/window-anchor.d.ts.map +1 -0
  271. package/dist/src/tune-out/window-anchor.js +202 -0
  272. package/dist/src/tune-out/window-anchor.js.map +1 -0
  273. package/dist/src/types/agent.d.ts +121 -25
  274. package/dist/src/types/agent.d.ts.map +1 -1
  275. package/dist/src/types/events.d.ts +2 -0
  276. package/dist/src/types/events.d.ts.map +1 -1
  277. package/dist/src/types/framework.d.ts +72 -17
  278. package/dist/src/types/framework.d.ts.map +1 -1
  279. package/dist/src/types/inference-log.d.ts +1 -0
  280. package/dist/src/types/inference-log.d.ts.map +1 -1
  281. package/dist/src/types/module.d.ts +180 -69
  282. package/dist/src/types/module.d.ts.map +1 -1
  283. package/dist/src/types/trace.d.ts +573 -39
  284. package/dist/src/types/trace.d.ts.map +1 -1
  285. package/package.json +4 -4
  286. package/src/admission/admit.ts +32 -3
  287. package/src/agent.ts +392 -132
  288. package/src/api/mcp-server-core.ts +54 -17
  289. package/src/api/server.ts +4 -23
  290. package/src/append-all.ts +6 -0
  291. package/src/code-execution/isolate/scripts.ts +28 -3
  292. package/src/config-checks.ts +14 -0
  293. package/src/context-manager-errors.ts +37 -0
  294. package/src/context-options.ts +106 -0
  295. package/src/cut-off-round.ts +4 -4
  296. package/src/deferred-import.ts +239 -0
  297. package/src/dendrite/audience.ts +315 -0
  298. package/src/dendrite/index.ts +14 -2
  299. package/src/dendrite/presets.ts +18 -6
  300. package/src/dendrite/registry.ts +213 -14
  301. package/src/dendrite/types.ts +92 -8
  302. package/src/failure-text.ts +88 -0
  303. package/src/foreign-rounds.ts +199 -0
  304. package/src/framework.ts +8796 -3813
  305. package/src/gate/event-gate.ts +518 -91
  306. package/src/gate/index.ts +3 -0
  307. package/src/gate/reply-judge.ts +12 -3
  308. package/src/gate/rule-scope.ts +45 -0
  309. package/src/gate/suppress-script-worker.ts +89 -0
  310. package/src/gate/suppress-scripts.ts +414 -0
  311. package/src/gate/suppression-review.ts +517 -0
  312. package/src/gate/suppression-stats.ts +314 -0
  313. package/src/gate/types.ts +148 -7
  314. package/src/gate/wake-onboarding.ts +309 -0
  315. package/src/heartbeat/heartbeat.ts +1 -1
  316. package/src/held-writes.ts +49 -60
  317. package/src/index.ts +10 -2
  318. package/src/inference-bounds.ts +11 -6
  319. package/src/jsonrpc-envelope.ts +81 -0
  320. package/src/mcpl/channel-registry.ts +513 -116
  321. package/src/mcpl/checkpoint-manager.ts +3 -2
  322. package/src/mcpl/feature-set-manager.ts +2 -1
  323. package/src/mcpl/inbound-source.ts +2 -1
  324. package/src/mcpl/inference-router.ts +7 -4
  325. package/src/mcpl/modern-connection.ts +629 -91
  326. package/src/mcpl/protocol-family.ts +15 -9
  327. package/src/mcpl/push-coalescer.ts +193 -34
  328. package/src/mcpl/push-handler.ts +10 -5
  329. package/src/mcpl/server-connection.ts +169 -75
  330. package/src/mcpl/tool-classes.ts +3 -0
  331. package/src/mcpl/tool-presence.ts +10 -5
  332. package/src/mcpl/toolset-host.ts +7 -6
  333. package/src/mcpl/toolsets-module.ts +2 -1
  334. package/src/mcpl/types.ts +33 -6
  335. package/src/module-registry.ts +73 -17
  336. package/src/modules/discord/index.ts +230 -82
  337. package/src/modules/health/index.ts +2 -2
  338. package/src/modules/history/index.ts +439 -70
  339. package/src/modules/history/semantic.ts +18 -24
  340. package/src/modules/workspace/disk-agreement.ts +1 -1
  341. package/src/modules/workspace/index.ts +89 -26
  342. package/src/modules/workspace/observe.ts +2 -1
  343. package/src/modules/workspace/reconcile.ts +3 -2
  344. package/src/notice-tags.ts +21 -9
  345. package/src/operator-log.ts +36 -3
  346. package/src/presentation.ts +1678 -0
  347. package/src/prose-drafts.ts +16 -12
  348. package/src/read-marks.ts +328 -0
  349. package/src/reasoning-loss.ts +7 -0
  350. package/src/recovery/offline-branch.ts +350 -35
  351. package/src/recovery/recover-cli.ts +23 -4
  352. package/src/send-tools.ts +40 -7
  353. package/src/sent-rows.ts +1 -1
  354. package/src/stored-injections.ts +2 -2
  355. package/src/stored-removal.ts +31 -7
  356. package/src/supplied-text.ts +3 -3
  357. package/src/thinking-drops.ts +2 -0
  358. package/src/tool-presentation.ts +34 -9
  359. package/src/tool-result-guard.ts +41 -7
  360. package/src/tune-out/coordinator.ts +4121 -472
  361. package/src/tune-out/tools.ts +162 -44
  362. package/src/tune-out/window-anchor.ts +277 -0
  363. package/src/types/agent.ts +122 -25
  364. package/src/types/events.ts +2 -0
  365. package/src/types/framework.ts +73 -17
  366. package/src/types/inference-log.ts +1 -0
  367. package/src/types/module.ts +181 -68
  368. package/src/types/trace.ts +607 -43
@@ -0,0 +1,1678 @@
1
+ /**
2
+ * The presentation index (#291): which stored rows each agent's window
3
+ * holds, and when a row enters it.
4
+ *
5
+ * The store's record keeps every write in the order it arrived. An agent's
6
+ * window is another order over the same rows: the rows presented to it, in
7
+ * the order its requests carry them (context-manager's window index,
8
+ * `presentRows`; a row presented at rest is in the window before a request
9
+ * has carried it). While one agent writes one slot, and nothing else writes
10
+ * it during that agent's turns, the two orders are the same. Once others
11
+ * write it during a turn (another agent sharing the slot, a module), or one
12
+ * agent reads another's, they differ: a row
13
+ * another agent stored during my turn sits inside my turn in the record, but
14
+ * my requests carried it only at my next tool boundary or turn start, so a
15
+ * compile that sent it where the record has it would change my turn's prefix
16
+ * (the prompt cache misses, and a reply's signed thinking is sent under a
17
+ * prefix it wasn't minted under).
18
+ *
19
+ * This module decides who each stored row is presented to and when, through
20
+ * each live agent's own context manager. It reads the row's audience stamp
21
+ * (dendrite/audience.ts), the slot the row is stored in, and the registry's
22
+ * slots and observe edges (bearingOf), and presents:
23
+ *
24
+ * - an agent's own rows as they are written, through the own-row sink
25
+ * (storeOwnRow, Agent and ToolResultGuard call it once the row is stored),
26
+ * or at its next presentation point when a writer held one back;
27
+ * - another writer's rows meant for it (arrivals) at its turn start, at its
28
+ * tool boundary as a prefix the live stream can carry, at its turn's end,
29
+ * and at once while it has no turn alive (present at rest);
30
+ * - nothing of others' while the host is quiesced (frozen) or under a
31
+ * surgery hold, which freeze every window but for an agent's own rows (a
32
+ * hold by its own refusals: under it every agent is turn-alive and no
33
+ * turn starts);
34
+ * - the arrivals a rollback's cut took out of an agent's window only at its
35
+ * next turn start (holdUntilStart), so the cut holds until it speaks.
36
+ *
37
+ * Arrivals are read from the index itself (getUnpresentedMessages filtered
38
+ * by bearingOf), never from the store's head: a crashed turn's arrivals and
39
+ * rows imported at boot are arrivals by construction. A shared derivation's
40
+ * inheritance isn't an arrival: it reaches the child through the window it
41
+ * was derived with, and bearingOf reads an unstamped row at or before the
42
+ * derivation's checkpoint (derivedAt) as elsewhere. The one scalar kept is
43
+ * a memo of where a scan may start, reset whenever the branch, the index
44
+ * length or the reader's facts moved under it.
45
+ *
46
+ * The module presents only for an agent it has taken on (adopt) whose
47
+ * manager is in presented mode: it never calls presentRows on a manager in
48
+ * legacy mode but for the deliberate write-down at adopt, and again at a
49
+ * rebase after the store's branch moved to a branch whose window index for
50
+ * that manager was never written (one made before the write-down), since
51
+ * any presentRows there writes the whole record down and switches the mode.
52
+ * The rows of the record the write-down took in that carry an audience
53
+ * stamp and are elsewhere to the agent (another agent's own rows, mail
54
+ * stamped for others, a held row) are then taken out (retractForeign), so a
55
+ * window written down after other agents' windows holds only the rows an
56
+ * earlier release stored unstamped and the agent's own and its arrivals
57
+ * (decision 1).
58
+ * Nothing in it throws into a writer: a failed presentation is traced and
59
+ * its rows stay out of the window for the next point. A fresh turn start's
60
+ * also fails the start (presentAtStart).
61
+ *
62
+ * It never imports framework.ts, which imports it.
63
+ */
64
+ import type { ContentBlock } from '@animalabs/membrane';
65
+ import { continuesBody, MessageStore, type ContextManager, type MessageId, type MessageMetadata, type StoredMessage } from '@animalabs/context-manager';
66
+ import { isReasoningLoss } from './reasoning-loss.js';
67
+ import { audienceOf, heldFromResidents, observedRowFor, suppressedRow } from './dendrite/audience.js';
68
+ import { sameSlot, type AgentRegistry } from './dendrite/registry.js';
69
+ import type { AgentName, AgentRecord, MessageSlotRef, ObserveEdge } from './dendrite/types.js';
70
+ import type { WindowOrdinal } from './read-marks.js';
71
+ import { isAnotherAgentsInjection } from './stored-injections.js';
72
+ import { nameAsStored } from './text-as-stored.js';
73
+ import type { PresentationRetractReason, TraceEventInput } from './types/trace.js';
74
+
75
+ export { heldFromResidents, suppressedRow } from './dendrite/audience.js';
76
+
77
+ // ============================================================================
78
+ // Pure pieces the tool boundary and the drain share
79
+ // ============================================================================
80
+
81
+ /** Whether a stored row can join a live stream at a tool boundary: no tool
82
+ * blocks (the membrane's tool cycle) and not named as the agent itself (it
83
+ * would render as an assistant turn, a prefill). The #286 cut. */
84
+ export function isInjectableMidTurn(msg: { participant: string; content: ContentBlock[] }, agent: { isOwnParticipant(participant: string): boolean }): boolean {
85
+ // Exact, as membrane's role test is: a participant the request assigns
86
+ // the assistant role (the agent's name, and for a derived agent the
87
+ // voice it inherited) renders as the assistant. It's the name as sent,
88
+ // which the boundary takes as the store keeps it.
89
+ return !agent.isOwnParticipant(nameAsStored(msg.participant))
90
+ && !msg.content.some((b) => b.type === 'tool_use' || b.type === 'tool_result');
91
+ }
92
+
93
+ /** What later compiles render from the store for the copies of one write
94
+ * that landed: one copy as it is, and two or more, the shards of a sharded
95
+ * body, as context-manager's autobiographical strategy (the one that
96
+ * shards on ingest) joins a body's consecutive shards: their non-text
97
+ * blocks, then one text block of their joined text. The join is that
98
+ * strategy's `mergeAdjacentBodyGroupRaw`, which context-manager doesn't
99
+ * export, so the rule is copied here. */
100
+ export function asCompiled(landed: ReadonlyArray<{ content: ContentBlock[] }>): ContentBlock[] {
101
+ if (landed.length === 1) return landed[0]!.content;
102
+ const blocks = landed.flatMap((m) => m.content);
103
+ const text = blocks.filter((b) => b.type === 'text').map((b) => (b as { text: string }).text).join('');
104
+ return [...blocks.filter((b) => b.type !== 'text'), { type: 'text', text } as ContentBlock];
105
+ }
106
+
107
+ // ============================================================================
108
+ // Positions in a window
109
+ // ============================================================================
110
+
111
+ /** A place in one agent's window on one branch: an index ordinal
112
+ * (ContextManager.ordinalOf, indexLength), never a store sequence. */
113
+ export type Position = WindowOrdinal;
114
+
115
+ /** Where an agent's window stood: its branch and its index length then. */
116
+ export interface WindowMark {
117
+ readonly branch: string;
118
+ readonly position: Position;
119
+ }
120
+
121
+ /** The row's place in `cm`'s window, or undefined for a row out of it (and every row in legacy mode). */
122
+ export function positionIn(cm: Pick<ContextManager, 'ordinalOf'>, id: MessageId): Position | undefined {
123
+ return cm.ordinalOf(id) as Position | undefined;
124
+ }
125
+
126
+ /** The place the next row presented in `cm`'s window will take (its index length, exclusive; 0 in legacy mode). */
127
+ export function windowEnd(cm: Pick<ContextManager, 'indexLength'>): Position {
128
+ return cm.indexLength() as Position;
129
+ }
130
+
131
+ /** Where `cm`'s window stands now, or null in legacy mode, where the window is the record and has no index. */
132
+ export function windowMarkOf(cm: Pick<ContextManager, 'windowMode' | 'indexLength' | 'currentBranch'>): WindowMark | null {
133
+ if (cm.windowMode() !== 'presented') return null;
134
+ return { branch: cm.currentBranch().name, position: windowEnd(cm) };
135
+ }
136
+
137
+ // ============================================================================
138
+ // The audience rule
139
+ // ============================================================================
140
+
141
+ /**
142
+ * What a row in one agent's merged record is to that agent: its own row,
143
+ * an arrival (a row meant for it that another writer stored), or elsewhere
144
+ * (a row it is never presented: another agent's own round, mail for a
145
+ * co-resident, a held row for a resident, a row a suppress rule hid).
146
+ */
147
+ export type Bearing = 'own' | 'arrival' | 'elsewhere';
148
+
149
+ /** A slot an agent observes: the slot its edge reads, the edge, and the slot's owners. */
150
+ export interface ObservedSlot {
151
+ readonly slot: MessageSlotRef;
152
+ readonly edge: ObserveEdge;
153
+ readonly owners: readonly AgentName[];
154
+ }
155
+
156
+ /** What bearingOf needs to know of a reader, read from the registry (readerFacts). */
157
+ export interface ReaderFacts {
158
+ readonly name: AgentName;
159
+ /** The slot its own rows are stored in (registry.ownSlotOf). */
160
+ readonly ownSlot: MessageSlotRef | undefined;
161
+ /** The slots it observes, each through its edge. */
162
+ readonly observed: readonly ObservedSlot[];
163
+ /** Whether its window leaves held rows out: an agent whose own slot is the
164
+ * residents' slot, on the host's branch or a branch of its own (a shared
165
+ * fork, which carries the residents' view filter). */
166
+ readonly hidesHeld: boolean;
167
+ /** For a shared derivation, the parent's checkpoint: a row with no stamp
168
+ * at or before it is the parent's inheritance, not the child's arrival. */
169
+ readonly derivedAt?: number;
170
+ }
171
+
172
+ /** The registry queries readerFacts reads. */
173
+ export type ReaderRegistry = Pick<AgentRegistry, 'get' | 'ownSlotOf' | 'observedSlotOf' | 'slotOwners'>;
174
+
175
+ /** A reader's facts as the registry has them now. An agent it doesn't know has no slot and observes nothing. */
176
+ export function readerFacts(registry: ReaderRegistry, name: AgentName): ReaderFacts {
177
+ return factsOf(registry, name, registry.get(name), registry.ownSlotOf(name));
178
+ }
179
+
180
+ /**
181
+ * A reader's facts as the registry recorded them: its live record, else its
182
+ * newest ended one (registry.inspect). For a reader that has left, as a
183
+ * released fork or run has by the time its window is read for what it
184
+ * never read (AgentFramework.releasedWindow): readerFacts reads live
185
+ * records only, and would know nothing of it.
186
+ */
187
+ export function recordedReaderFacts(
188
+ registry: Pick<AgentRegistry, 'inspect' | 'observedSlotOf' | 'slotOwners'>,
189
+ name: AgentName,
190
+ ): ReaderFacts {
191
+ const record = registry.inspect(name);
192
+ return factsOf(registry, name, record, record?.ownSlot ? { ...record.ownSlot } : undefined);
193
+ }
194
+
195
+ /** A reader's facts from its record and its own slot (readerFacts, recordedReaderFacts). */
196
+ function factsOf(
197
+ registry: Pick<AgentRegistry, 'observedSlotOf' | 'slotOwners'>,
198
+ name: AgentName,
199
+ record: AgentRecord | undefined,
200
+ ownSlot: MessageSlotRef | undefined,
201
+ ): ReaderFacts {
202
+ const observed: ObservedSlot[] = [];
203
+ for (const edge of record?.relationships.observes ?? []) {
204
+ const slot = registry.observedSlotOf(edge);
205
+ if (slot) observed.push({ slot, edge, owners: registry.slotOwners(slot) });
206
+ }
207
+ const derivedAt = record?.inherit?.mode === 'shared' ? record.inherit.atSequence : undefined;
208
+ return {
209
+ name,
210
+ ownSlot,
211
+ observed,
212
+ hidesHeld: ownSlot?.namespace === null,
213
+ ...(derivedAt !== undefined ? { derivedAt } : {}),
214
+ };
215
+ }
216
+
217
+ /**
218
+ * Where a row bearingOf weighs is stored, as its caller read it: `'own'`,
219
+ * the reader's own slot (the own message store of its context, which
220
+ * getMessage and getAllMessages read), or another slot by its ref (an
221
+ * auxiliary view of its context, by namespace, or the own slot of the
222
+ * agent that wrote the row: slotOfRow, afterStore).
223
+ */
224
+ export type RowSlot = 'own' | MessageSlotRef;
225
+
226
+ /**
227
+ * What one row is to one reader, from the row's stamp, the reader's facts,
228
+ * and `slot`, the slot the row is stored in: the reader's own (`'own'`, or
229
+ * a ref sameSlot as its `ownSlot`), else a slot it may observe. undefined,
230
+ * a slot its caller couldn't name, is elsewhere.
231
+ *
232
+ * A legacy reasoning-loss notice or a row a suppress rule hid
233
+ * (suppressedRow) is elsewhere to every reader,
234
+ * in any slot: no view the framework sets renders it.
235
+ *
236
+ * In its own slot, with `stamp = audienceOf(metadata)`:
237
+ * - its own row (`ownRowOf` names it): own;
238
+ * - another agent's own row: an arrival when one of the reader's edges
239
+ * names that agent and reads this slot (observesOwnRows: a resident's
240
+ * `AgentConfig.observes`, the relationship decision 1 says another
241
+ * agent's rounds reach an agent only through), unless it is that agent's
242
+ * stored context injection, which the reader's view leaves out;
243
+ * elsewhere otherwise, as it is for every resident by default;
244
+ * - a row whose audience names it: an arrival, unless it is held and the
245
+ * reader leaves held rows out, or it is another agent's stored injection,
246
+ * which the reader's view leaves out too (what the reader's own view
247
+ * leaves out is never its arrival: main's #853 asks that view, agentSees,
248
+ * at a tool boundary);
249
+ * - a row stamped otherwise (mail for a co-resident, a held row): elsewhere;
250
+ * - a row with no stamp (stored by a host's writer that doesn't stamp): an
251
+ * arrival for the slot's owners, as it reads today, unless it is a shared
252
+ * derivation's inheritance (at or before `derivedAt`), held for a reader
253
+ * that leaves held rows out, or another agent's stored injection.
254
+ *
255
+ * In another slot: an arrival when an edge of the reader's that reads that
256
+ * slot shows it, by that edge's rules and that slot's owners
257
+ * (observedRowFor); elsewhere when none does, or the reader has no edge on
258
+ * the slot. A pure function of its arguments: it runs for a released agent,
259
+ * which has no live manager, too.
260
+ */
261
+ export function bearingOf(
262
+ row: Pick<StoredMessage, 'sequence' | 'participant' | 'metadata'>,
263
+ reader: ReaderFacts,
264
+ slot: RowSlot | undefined,
265
+ ): Bearing {
266
+ const metadata = row.metadata as Record<string, unknown> | undefined;
267
+ if (slot === undefined) return 'elsewhere';
268
+ if (isReasoningLoss(metadata) || suppressedRow(metadata)) return 'elsewhere';
269
+ if (slot !== 'own' && !sameSlot(slot, reader.ownSlot)) {
270
+ const shown = reader.observed.some((seen) => sameSlot(seen.slot, slot)
271
+ && observedRowFor(seen.edge, row, { observer: reader.name, owners: seen.owners }));
272
+ return shown ? 'arrival' : 'elsewhere';
273
+ }
274
+ const stamp = audienceOf(metadata);
275
+ if (stamp) {
276
+ if (stamp.ownRowOf !== undefined) {
277
+ if (stamp.ownRowOf === reader.name) return 'own';
278
+ return observesInOwnSlot(reader, stamp.ownRowOf) && !isAnotherAgentsInjection(metadata, reader.name) ? 'arrival' : 'elsewhere';
279
+ }
280
+ if (!stamp.audience.includes(reader.name)) return 'elsewhere';
281
+ if (isAnotherAgentsInjection(metadata, reader.name)) return 'elsewhere';
282
+ return reader.hidesHeld && heldFromResidents(metadata) ? 'elsewhere' : 'arrival';
283
+ }
284
+ if (reader.derivedAt !== undefined && row.sequence <= reader.derivedAt) return 'elsewhere';
285
+ if (reader.hidesHeld && heldFromResidents(metadata)) return 'elsewhere';
286
+ if (isAnotherAgentsInjection(metadata, reader.name)) return 'elsewhere';
287
+ return 'arrival';
288
+ }
289
+
290
+ /** Whether one of the reader's edges names `owner` and reads the reader's own slot: a co-resident it observes. */
291
+ function observesInOwnSlot(reader: ReaderFacts, owner: AgentName): boolean {
292
+ return reader.observed.some((seen) => seen.edge.agent === owner && sameSlot(seen.slot, reader.ownSlot));
293
+ }
294
+
295
+ /**
296
+ * Whether a reader is shown `owner`'s own rows through an observe edge, as
297
+ * bearingOf reads its edges: an edge on another slot that `owner` owns, or
298
+ * an edge that names `owner` and reads the reader's own slot (a resident
299
+ * observing a co-resident, AgentConfig.observes). An edge on the reader's
300
+ * own slot shows only the agent it names, though every resident owns that
301
+ * slot.
302
+ */
303
+ export function observesOwnRows(reader: ReaderFacts, owner: AgentName): boolean {
304
+ return reader.observed.some((seen) => (sameSlot(seen.slot, reader.ownSlot)
305
+ ? seen.edge.agent === owner
306
+ : seen.owners.includes(owner)));
307
+ }
308
+
309
+ /**
310
+ * The slots besides its own a reader's context merges into its record: the
311
+ * slots its edges read on its context's branch (no `branch` of their own),
312
+ * each once. The framework opens an observer's context with one auxiliary
313
+ * view per such slot (createSubconsciousAgent, reopenAgentContext); a slot
314
+ * on a branch of its own (a shared fork's) can't be merged so.
315
+ */
316
+ function mergedSlotsOf(reader: ReaderFacts): MessageSlotRef[] {
317
+ const slots: MessageSlotRef[] = [];
318
+ for (const { slot } of reader.observed) {
319
+ if (slot.branch !== undefined || sameSlot(slot, reader.ownSlot)) continue;
320
+ if (!slots.some((s) => sameSlot(s, slot))) slots.push(slot);
321
+ }
322
+ return slots;
323
+ }
324
+
325
+ /**
326
+ * Whether a row stamped for `audience` and stored in `slot` is meant only for
327
+ * agents that can't read it: its audience names someone, and none of them
328
+ * reads the slot, as an owner or through an observe edge (registry
329
+ * readersOf). Such a row is stored as named, never widened (no window
330
+ * presents it by its audience), and traced as a routing fault. A row whose
331
+ * audience names an observer of the slot is no fault: its edge shows it
332
+ * (observedRowFor), as one naming an owner is presented in that owner's
333
+ * window.
334
+ */
335
+ export function audienceFault(
336
+ audience: readonly AgentName[],
337
+ slot: MessageSlotRef | undefined,
338
+ registry: Pick<AgentRegistry, 'readersOf'>,
339
+ ): boolean {
340
+ if (audience.length === 0 || slot === undefined) return false;
341
+ const readers = registry.readersOf(slot);
342
+ return !audience.some((name) => readers.includes(name));
343
+ }
344
+
345
+ // ============================================================================
346
+ // The presentation module
347
+ // ============================================================================
348
+
349
+ /** Where one presentation into an agent's window happened. */
350
+ export type PresentationOccasion =
351
+ /** An agent's own row, presented as it was stored. */
352
+ | 'write'
353
+ /** A turn's start, before its compile: its own rows and its arrivals. */
354
+ | 'turn-start'
355
+ /** A start's assembly of a wake's own rows, before its compile. */
356
+ | 'assembly'
357
+ /** The backstop before every compile: its own rows only. */
358
+ | 'compile'
359
+ /** A tool boundary: the round's rows, then a prefix of its arrivals. */
360
+ | 'tool-boundary'
361
+ /** The check before a boundary hands the stream its rows. */
362
+ | 'hand-off'
363
+ /** A turn's end. */
364
+ | 'turn-end'
365
+ /** An agent with no turn alive, presented a row at its write, or at boot. */
366
+ | 'at-rest'
367
+ /** Rows handed a reader fork as framing. */
368
+ | 'framing'
369
+ /** An agent taken on: its window written down and its own rows repaired. */
370
+ | 'adopt'
371
+ /** The store's branch moved under a live agent (rebase): its window on the
372
+ * new branch written down, where that branch had none, and its own rows
373
+ * repaired. */
374
+ | 'rebase';
375
+
376
+ /** A context manager as the module uses it. */
377
+ export type WindowManager = Pick<ContextManager,
378
+ 'presentRows' | 'retractRows' | 'getUnpresentedMessages' | 'getPresentedMessages' | 'ordinalOf' | 'indexLength' | 'windowStatusOf'
379
+ | 'windowMode' | 'getMessage' | 'currentBranch' | 'isClosed' | 'retractRemoved' | 'retractAbsentRows' | 'getStore'>;
380
+
381
+ /** An agent as the module presents to it. The framework's Agent is one. */
382
+ export interface PresentedAgent {
383
+ readonly name: AgentName;
384
+ getContextManager(): WindowManager;
385
+ isOwnParticipant(participant: string): boolean;
386
+ /** Where the agent tells of its own rows once they are stored (Agent.setOwnRowSink). */
387
+ setOwnRowSink?(sink: ((ids: readonly MessageId[]) => void) | undefined): void;
388
+ }
389
+
390
+ /** The traces the module emits, as a host passes them on. */
391
+ export type PresentationTrace = Extract<TraceEventInput, { type: `presentation:${string}` }>;
392
+
393
+ /** What the module reads of its host (the framework). */
394
+ export interface PresentationHost {
395
+ /** Every agent registered now, a shared fork on its own branch included. */
396
+ liveAgents(): Iterable<PresentedAgent>;
397
+ readonly registry: Pick<AgentRegistry, 'get' | 'ownSlotOf' | 'observedSlotOf' | 'readersOf' | 'slotOwners'>;
398
+ /**
399
+ * Whether the agent's logical turn is alive: a turn token, a continuation
400
+ * or retry on its way, a live stream, or a tool cycle pending. Nothing but
401
+ * its own rows and its boundary's arrivals is presented to it then.
402
+ */
403
+ turnAlive(name: AgentName): boolean;
404
+ /**
405
+ * Whether others' rows are frozen out of every window: the host
406
+ * quiesced, or booting until create()'s pass over the windows. Own rows
407
+ * still present. A surgery's hold isn't asked here: its
408
+ * own refusals keep every point that reads this from being reached under
409
+ * it (the framework's `frozen`, where the host is built).
410
+ */
411
+ frozen(): boolean;
412
+ emitTrace(event: PresentationTrace): void;
413
+ }
414
+
415
+ /** A row a tool boundary presented for the live stream to carry: one per body, by the id that names it. */
416
+ export interface HeardRow {
417
+ readonly id: MessageId;
418
+ readonly participant: string;
419
+ /** The body as the store holds it, a sharded one's shards joined as compiles join them (asCompiled). */
420
+ readonly content: ContentBlock[];
421
+ readonly metadata?: MessageMetadata;
422
+ }
423
+
424
+ /** What a tool boundary presented beyond the round's own rows. */
425
+ export interface BoundaryPresentation {
426
+ /** The rows the stream carries next, in window order. */
427
+ readonly heard: readonly HeardRow[];
428
+ /** The first row the stream can't carry, where the rows presented stop. */
429
+ readonly cutAt?: MessageId;
430
+ }
431
+
432
+ /**
433
+ * An agent holding a row: in its window, at a place (`'window'`); in a
434
+ * window that is still the whole record (`'legacy'`), which holds every row
435
+ * its merged record does; or handed it as a reader fork's framing
436
+ * (`'framing'`).
437
+ */
438
+ export type Holder =
439
+ | { readonly agent: AgentName; readonly via: 'window'; readonly position: Position }
440
+ | { readonly agent: AgentName; readonly via: 'legacy' }
441
+ | { readonly agent: AgentName; readonly via: 'framing' };
442
+
443
+ /** What a presentation listener hears: the rows that entered one agent's window, in order, and where. */
444
+ export interface PresentedEvent {
445
+ readonly agentName: AgentName;
446
+ readonly occasion: PresentationOccasion;
447
+ readonly rows: readonly StoredMessage[];
448
+ }
449
+
450
+ /** One body of the agent's pending rows: its unpresented shards in record order, and what it is to the agent. */
451
+ interface PendingBody {
452
+ readonly shards: StoredMessage[];
453
+ readonly bearing: 'own' | 'arrival';
454
+ readonly unstamped: boolean;
455
+ }
456
+
457
+ /** Where a scan of one manager's unpresented rows may start: every one at or below `scanFrom` was elsewhere. */
458
+ interface ScanMemo {
459
+ generation: number;
460
+ branch: string;
461
+ length: number;
462
+ facts: string;
463
+ scanFrom: number;
464
+ /** The same for a scan at rest that leaves a rollback's held arrivals out (pending's `atRest`, a hold in force):
465
+ * every row at or below it was elsewhere or held. A held arrival doesn't hold it back, as one does `scanFrom`,
466
+ * so such a scan doesn't walk every row stored since the arrival until the agent's next start. */
467
+ heldScanFrom?: number;
468
+ }
469
+
470
+ /** What adopt left for one manager. */
471
+ interface Adopted {
472
+ /** Set when the window couldn't be written down: the agent stays in legacy mode for this process. */
473
+ pinnedLegacy?: string;
474
+ /** Set while taking out the rows a write-down took in that aren't the agent's (retractForeign) has failed:
475
+ * tried again at its next turn start or point at rest until it succeeds. */
476
+ retractPending?: true;
477
+ }
478
+
479
+ const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
480
+
481
+ /**
482
+ * The presentation index's decisions, over each live agent's context
483
+ * manager. The framework constructs it in create() and calls it at each
484
+ * presentation point.
485
+ */
486
+ export class AgentPresentation {
487
+ private readonly adopted = new WeakMap<WindowManager, Adopted>();
488
+ private readonly memos = new WeakMap<WindowManager, ScanMemo>();
489
+ /** Bumped when a registration may have changed what a row is to someone: every memo is then stale. */
490
+ private generation = 0;
491
+ /** Rows handed each reader fork as framing (noteFramed), in memory. */
492
+ private readonly framed = new Map<AgentName, Set<MessageId>>();
493
+ /** Reader forks whose framing may not all be in their window yet: framed before they were taken on, or whose framing's presentation failed. */
494
+ private readonly framedPending = new Set<AgentName>();
495
+ private readonly listeners = new Map<AgentName, Set<(event: PresentedEvent) => void>>();
496
+ /** Own rows whose presentation at their write failed, per manager (presentOwn), until they enter its window. */
497
+ private readonly failedOwn = new WeakMap<WindowManager, Set<MessageId>>();
498
+ /** Arrivals a rollback took out of each manager's window, kept out of it at rest until the agent's next turn start (holdUntilStart), on the branch the rollback left the store on. */
499
+ private readonly heldUntilStart = new WeakMap<WindowManager, { branch: string; ids: Set<MessageId> }>();
500
+ /** Agents the boot's pass at rest left out (repairAndRest's `restExcept`): no point at rest presents their arrivals until their next turn start. */
501
+ private readonly restWithheld = new Set<AgentName>();
502
+ /** Read-only handles on the slots a manager merges, by namespace (slotOfRow): made only for a reader whose context merges more than one. */
503
+ private readonly slotReaders = new WeakMap<WindowManager, Map<string | null, MessageStore>>();
504
+
505
+ constructor(private readonly host: PresentationHost) {}
506
+
507
+ // --------------------------------------------------------------------------
508
+ // Taking agents on
509
+ // --------------------------------------------------------------------------
510
+
511
+ /** Take on every live agent (adopt), then present what each is owed at rest (repairAndRest). */
512
+ boot(): void {
513
+ for (const agent of this.host.liveAgents()) this.adopt(agent);
514
+ this.repairAndRest();
515
+ }
516
+
517
+ /**
518
+ * Take an agent on. Once per manager object: a manager in legacy mode has
519
+ * its window written down (presentRows([]), which also finishes a
520
+ * write-down cut short), the stamped rows it took in that are elsewhere to
521
+ * the agent are taken out (retractForeign; where that fails, at the
522
+ * agent's next turn start or point at rest), and the agent's own rows
523
+ * stored and not in its window are presented to it, in record order (an
524
+ * undone turn's rows are not: getUnpresentedMessages leaves them out). A
525
+ * window that can't be
526
+ * written down (another version's index format, or a failed write; not a
527
+ * write-down that threw once its record was written, which reads as
528
+ * presented: writeDown) leaves the agent in legacy mode, traced once,
529
+ * until a move of the store's branch writes its window down on the new
530
+ * branch (rebase): its window is the whole record, as before the index.
531
+ * Then, every time, the agent's own-row sink is installed, one left in
532
+ * legacy mode's too, so the other readers of its slot hear of its rows
533
+ * (presentOwn), and every scan memo is dropped, since a registration can
534
+ * change who reads a slot.
535
+ */
536
+ adopt(agent: PresentedAgent): void {
537
+ const cm = agent.getContextManager();
538
+ this.generation++;
539
+ let state = this.adopted.get(cm);
540
+ if (!state) {
541
+ state = {};
542
+ this.adopted.set(cm, state);
543
+ this.writeDown(agent, state, 'adopt');
544
+ if (!state.pinnedLegacy) {
545
+ this.retractForeign(agent, 'adopt');
546
+ this.repair(agent);
547
+ // A reader fork is framed before it is taken on (noteFramed at its
548
+ // derivation, adopt at its run's registration): the held rows it was
549
+ // handed enter its window now, after its framing row.
550
+ this.presentFramed(agent);
551
+ }
552
+ }
553
+ // In legacy mode too: presentOwn presents nothing for it, and tells the
554
+ // other readers of its slot of its rows (afterStore).
555
+ agent.setOwnRowSink?.((ids) => this.presentOwn(agent, ids));
556
+ }
557
+
558
+ /**
559
+ * The store's branch moved under an agent taken on (a host's switchBranch,
560
+ * a rollback's or a suppression's switch, a failed surgery's restore).
561
+ * Its manager's window index is the new branch's: on a branch made before
562
+ * the agent's write-down (every branch an earlier release's store holds,
563
+ * or a rollback into rows the write-down presented, which branchAt cuts
564
+ * at their own sequence) there is none, and the window would be the
565
+ * whole record for the rest of the process. So, as at adopt, such a
566
+ * window is written down (presentRows([]), traced as presented at
567
+ * `'rebase'`), the stamped rows it took in that are elsewhere to the
568
+ * agent, a co-resident's own rows presented on the old branch among them,
569
+ * are taken out (retractForeign), and the agent's own rows stored and not
570
+ * in its window are presented to it (the own-row sweep). A window that is presented on the
571
+ * new branch is presented again for an agent left in legacy mode by an
572
+ * earlier branch, its own-row sink installed. A window that can't be
573
+ * written down, or a manager whose strategy couldn't follow the move
574
+ * (`failure`, from its re-initialization by the framework, #353), leaves
575
+ * the agent in legacy mode until the next move, traced as
576
+ * presentation:failed at `'rebase'`. Arrivals aren't presented here: the
577
+ * framework's surgery release presents what each agent is owed. Never
578
+ * throws.
579
+ */
580
+ rebase(agent: PresentedAgent, failure?: unknown): void {
581
+ const cm = agent.getContextManager();
582
+ const state = this.adopted.get(cm);
583
+ if (!state) return;
584
+ this.generation++;
585
+ this.memos.delete(cm);
586
+ try {
587
+ if (failure !== undefined) {
588
+ state.pinnedLegacy = describe(failure);
589
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion: 'rebase', error: state.pinnedLegacy, legacy: true });
590
+ return;
591
+ }
592
+ if (cm.isClosed()) return;
593
+ delete state.pinnedLegacy;
594
+ if (!this.writeDown(agent, state, 'rebase')) return;
595
+ agent.setOwnRowSink?.((ids) => this.presentOwn(agent, ids));
596
+ this.retractForeign(agent, 'rebase');
597
+ this.repair(agent, 'rebase');
598
+ // A reader fork's framing that its window doesn't hold on this branch.
599
+ this.presentFramed(agent);
600
+ } catch (error) {
601
+ state.pinnedLegacy = describe(error);
602
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion: 'rebase', error: state.pinnedLegacy, legacy: true });
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Write `agent`'s window down where its manager is in legacy mode
608
+ * (presentRows([]), which also finishes a write-down cut short), and say
609
+ * whether the window is presented after it. A write-down that fails, or
610
+ * leaves the manager in legacy mode, pins the agent in legacy mode
611
+ * (`state.pinnedLegacy`), traced as presentation:failed at `occasion`
612
+ * with `legacy`, which the host logs and alerts. A
613
+ * write-down that throws once its record is written (the store's own work
614
+ * after a write, such as a snapshot, failing) has written the window
615
+ * down: the manager reads its index again after any throw, so a window
616
+ * that reads as presented then is taken as one, and the agent is
617
+ * presented for, with a log line. A write-down at a rebase is traced as
618
+ * presented, with the bodies the window holds; a read for that trace
619
+ * which throws is logged and the trace skipped, the window presented.
620
+ */
621
+ private writeDown(agent: PresentedAgent, state: Adopted, occasion: 'adopt' | 'rebase'): boolean {
622
+ const cm = agent.getContextManager();
623
+ let wrote = false;
624
+ if (cm.windowMode() === 'legacy') {
625
+ try {
626
+ cm.presentRows([]);
627
+ wrote = true;
628
+ } catch (error) {
629
+ if (!readsPresented(cm)) {
630
+ state.pinnedLegacy = describe(error);
631
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion, error: state.pinnedLegacy, legacy: true });
632
+ return false;
633
+ }
634
+ console.warn(`[presentation] ${agent.name}: writing its window down at ${occasion} threw after the window was written (${describe(error)}); its window is presented`);
635
+ wrote = true;
636
+ }
637
+ }
638
+ if (cm.windowMode() !== 'presented') {
639
+ state.pinnedLegacy = 'the window is not in presented mode after its write-down';
640
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion, error: state.pinnedLegacy, legacy: true });
641
+ return false;
642
+ }
643
+ if (wrote && occasion === 'rebase') {
644
+ // The trace's read is the trace's: a throw there leaves the window
645
+ // presented, as written down, and skips the trace.
646
+ let count = 0;
647
+ try {
648
+ count = bodyHeadCount(cm.getPresentedMessages());
649
+ } catch (error) {
650
+ console.error(`[presentation] ${agent.name}: its window was written down at ${occasion}, and reading it back for the trace failed (${describe(error)}); its window is presented, and the write-down isn't traced`);
651
+ }
652
+ if (count > 0) this.host.emitTrace({ type: 'presentation:presented', agentName: agent.name, occasion, count });
653
+ }
654
+ return true;
655
+ }
656
+
657
+ /**
658
+ * Take out of the agent's window the rows a write-down from the record
659
+ * took in that aren't its (decision 1): each row that carries an audience
660
+ * stamp and that bearingOf reads as elsewhere to the agent, such as
661
+ * another agent's own row, mail stamped for a co-resident, or a held row
662
+ * for a window that leaves held rows out. Each leaves its place as a plain
663
+ * retraction does, so it reads as arrived, and it stays elsewhere, so no
664
+ * later point presents it. Two kinds of row stay: an unstamped row, which
665
+ * a release before the stamp stored and the write-down migrates whole,
666
+ * and a shared derivation's inheritance (at or before its checkpoint),
667
+ * which is the child's history. Nothing is taken out for an agent the
668
+ * registry has no slot for. Run at every adopt and rebase, not only
669
+ * after a write-down this process made, so a window whose write-down
670
+ * landed and whose retraction didn't (a crash between the two records, a
671
+ * failed write) is repaired the next time it is taken on. Rows are
672
+ * weighed by the agent's relationships now, not by those they entered
673
+ * under, so a row the module presented is taken out too where it is
674
+ * elsewhere to the agent now: an observed agent's own row, presented
675
+ * through an observe edge the agent no longer has (a restart whose
676
+ * configuration dropped it). A reader fork's framing is passed over. Traced as
677
+ * presentation:retracted, reason `elsewhere`; a failure is traced as
678
+ * presentation:failed at `occasion`, and the rows stay in the window
679
+ * until the agent's next turn start or point at rest takes them out
680
+ * (`retractPending`, tried there until it succeeds), or the next adopt or
681
+ * rebase; a fresh turn start that can't take them out fails
682
+ * (presentAtStart). Never throws.
683
+ */
684
+ private retractForeign(agent: PresentedAgent, occasion: PresentationOccasion): void {
685
+ const cm = agent.getContextManager();
686
+ const state = this.adopted.get(cm);
687
+ try {
688
+ if (!this.presenting(agent)) return;
689
+ const foreign = this.foreignRows(agent);
690
+ if (foreign.length > 0) {
691
+ cm.retractRows(foreign);
692
+ this.memos.delete(cm);
693
+ this.host.emitTrace({ type: 'presentation:retracted', agentName: agent.name, messageIds: foreign, reason: 'elsewhere' });
694
+ }
695
+ if (state) delete state.retractPending;
696
+ } catch (error) {
697
+ if (state) state.retractPending = true;
698
+ console.error(`[presentation] ${agent.name}: taking the rows that aren't its out of its window at ${occasion} failed; they stay in it, and no turn of its starts, until its next turn start or point at rest takes them out:`, error);
699
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion, error: describe(error) });
700
+ }
701
+ }
702
+
703
+ /** The rows of the agent's window retractForeign takes out, each body by its first shard; none for an agent the registry has no slot for. */
704
+ private foreignRows(agent: PresentedAgent): MessageId[] {
705
+ const cm = agent.getContextManager();
706
+ const facts = readerFacts(this.host.registry, agent.name);
707
+ // An agent the registry doesn't know has no slot to weigh a row by.
708
+ if (facts.ownSlot === undefined) return [];
709
+ const framed = this.framed.get(agent.name);
710
+ const window = cm.getPresentedMessages();
711
+ const foreign: MessageId[] = [];
712
+ for (let i = 0; i < window.length; i++) {
713
+ const row = window[i]!;
714
+ // A body is taken out whole by its first shard.
715
+ if (i > 0 && continuesBody(window[i - 1], row)) continue;
716
+ if (audienceOf(row.metadata) === undefined || framed?.has(row.id)) continue;
717
+ if (facts.derivedAt !== undefined && row.sequence <= facts.derivedAt) continue;
718
+ if (bearingOf(row, facts, this.slotOfRow(cm, facts, row.id)) === 'elsewhere') foreign.push(row.id);
719
+ }
720
+ return foreign;
721
+ }
722
+
723
+ /** retractForeign again, where it failed before (`retractPending`). */
724
+ private retryRetraction(agent: PresentedAgent, occasion: PresentationOccasion): void {
725
+ if (this.adopted.get(agent.getContextManager())?.retractPending) this.retractForeign(agent, occasion);
726
+ }
727
+
728
+ /** Let an agent go: its sink off, and what the module kept for it (its memo, its framing, its held arrivals) dropped. */
729
+ forget(agent: PresentedAgent): void {
730
+ agent.setOwnRowSink?.(undefined);
731
+ const cm = agent.getContextManager();
732
+ this.adopted.delete(cm);
733
+ this.memos.delete(cm);
734
+ this.failedOwn.delete(cm);
735
+ this.heldUntilStart.delete(cm);
736
+ this.slotReaders.delete(cm);
737
+ this.framed.delete(agent.name);
738
+ this.framedPending.delete(agent.name);
739
+ this.restWithheld.delete(agent.name);
740
+ this.generation++;
741
+ }
742
+
743
+ /**
744
+ * For every live agent the module presents to and whose turn isn't alive:
745
+ * its own rows stored and not in its window (the own-row sweep, traced as
746
+ * presentation:repaired), then whatever it is owed at rest (presentAtEnd).
747
+ * Boot runs it once every agent is taken on and the stored rows are in,
748
+ * whether or not an adopt repaired anything. An agent in `restExcept` has
749
+ * its own rows swept and nothing else: the boot couldn't read what it is
750
+ * owed to ask the wakes its rows owe, so they stay out of its window until
751
+ * its next turn start, which no wake was asked for. Until then no point at
752
+ * rest presents its arrivals (a row stored for it while it is idle, a
753
+ * turn's end), only its own rows, so a later boot finds them out of its
754
+ * window and reads them again.
755
+ */
756
+ repairAndRest(options: { restExcept?: ReadonlySet<AgentName> } = {}): void {
757
+ for (const name of options.restExcept ?? []) this.restWithheld.add(name);
758
+ for (const agent of this.host.liveAgents()) {
759
+ if (!this.presenting(agent) || this.host.turnAlive(agent.name)) continue;
760
+ this.repair(agent);
761
+ if (!options.restExcept?.has(agent.name)) this.presentAtRest(agent, 'at-rest');
762
+ }
763
+ }
764
+
765
+ /** Whether the module presents for this agent: taken on, its manager open and in presented mode. */
766
+ presenting(agent: PresentedAgent): boolean {
767
+ const cm = agent.getContextManager();
768
+ const state = this.adopted.get(cm);
769
+ return !!state && !state.pinnedLegacy && !cm.isClosed() && cm.windowMode() === 'presented';
770
+ }
771
+
772
+ // --------------------------------------------------------------------------
773
+ // Presentation points
774
+ // --------------------------------------------------------------------------
775
+
776
+ /**
777
+ * Present the agent's own rows now, in the order given, those not in its
778
+ * window yet, even while the host is frozen; then tell the other readers
779
+ * of its slot (afterStore), whatever became of that: a presentation that
780
+ * threw, or an agent the module doesn't present for (a failed rebase
781
+ * leaves its sink on). The own-row sink calls it. It is for a row the
782
+ * agent's stream carries (its round, its results, a notice injected at its
783
+ * boundary), one written before its next compile or after its stream's
784
+ * last request, or one written while it has no turn alive: any other row
785
+ * would enter a live window its requests don't carry, so its writer holds
786
+ * it back (storeOwnRow's `present: false`) for the next point's sweep.
787
+ *
788
+ * An own row whose presentation here failed (a transient store error) is
789
+ * kept, and presented ahead of the rows given at the agent's next call,
790
+ * in record order, while it is still out of the window: its window's
791
+ * ordinals never move, so a row written after it and presented first
792
+ * would stay ahead of it for good (a round's results ahead of its reply,
793
+ * which every later compile would send so). It is kept until the agent's
794
+ * next turn start or tool boundary, whose own-row sweep presents it by
795
+ * that point's rule, or leaves it for the next point when that fails
796
+ * too: a request compiled, or a stream handed its rows, without it
797
+ * mustn't find it in the window ahead of a reply it didn't come before.
798
+ * A row its writer held back is never kept: it waits for the next point's
799
+ * sweep. Never throws.
800
+ */
801
+ presentOwn(agent: PresentedAgent, ids: ReadonlyArray<MessageId | undefined>): void {
802
+ const cm = agent.getContextManager();
803
+ // Every row this call tries, the ones an earlier failed write kept
804
+ // among them, from before the first read: a read that throws keeps them
805
+ // all (keepFailedOwn), so none of them is put behind the rows written
806
+ // after it.
807
+ let tried: readonly MessageId[] = unique([...(this.failedOwn.get(cm) ?? []), ...ids]);
808
+ try {
809
+ if (this.presenting(agent)) {
810
+ tried = unique([...this.failedOwnOf(agent), ...ids]).filter((id) => cm.ordinalOf(id) === undefined);
811
+ this.present(agent, tried, 'write');
812
+ this.keepFailedOwn(agent, tried);
813
+ }
814
+ } catch (error) {
815
+ this.failed(agent, 'write', error);
816
+ this.keepFailedOwn(agent, tried);
817
+ }
818
+ this.afterStore(agent, ids);
819
+ }
820
+
821
+ /**
822
+ * Rows `writer` just stored, in its own slot: each other reader of that
823
+ * slot (its owners and its observers) whose turn isn't alive, and the
824
+ * writer itself, is presented what it is owed at once, when one of the
825
+ * rows is its own or an arrival for it (present at rest). A reader with a
826
+ * turn alive takes them at its next point. Frozen, only own rows present.
827
+ * The module needn't present for the writer: one left in legacy mode
828
+ * tells the readers of its slot too. Each reader is weighed apart, so one
829
+ * whose window can't be read is traced and the others are still told.
830
+ * Never throws.
831
+ */
832
+ afterStore(writer: PresentedAgent, ids: ReadonlyArray<MessageId | undefined>): void {
833
+ try {
834
+ const stored = unique(ids);
835
+ if (stored.length === 0) return;
836
+ const writerCm = writer.getContextManager();
837
+ const rows = stored.map((id) => writerCm.getMessage(id)).filter((row): row is StoredMessage => row !== null);
838
+ const slot = this.host.registry.ownSlotOf(writer.name);
839
+ const readers = new Set<AgentName>([writer.name, ...(slot ? this.host.registry.readersOf(slot) : [])]);
840
+ for (const reader of [...this.host.liveAgents()]) {
841
+ if (!readers.has(reader.name)) continue;
842
+ try {
843
+ if (!this.presenting(reader) || this.host.turnAlive(reader.name)) continue;
844
+ const facts = readerFacts(this.host.registry, reader.name);
845
+ // The rows are in the writer's own slot: the reader's own when it
846
+ // is the writer or shares that slot (bearingOf compares the ref),
847
+ // else a slot it observes, weighed by its edges on that slot.
848
+ const from: RowSlot | undefined = reader === writer ? 'own' : slot;
849
+ // A row the writer's own slot doesn't hold (none found) can't be
850
+ // weighed here; the reader's own scan weighs it.
851
+ const owed = rows.length < stored.length || rows.some((row) => bearingOf(row, facts, from) !== 'elsewhere');
852
+ if (owed) this.presentAtRest(reader, 'at-rest');
853
+ } catch (error) {
854
+ this.failed(reader, 'at-rest', error);
855
+ }
856
+ }
857
+ } catch (error) {
858
+ this.failed(writer, 'at-rest', error);
859
+ }
860
+ }
861
+
862
+ /**
863
+ * A turn's start, before its compile. `'turn-start'` (a fresh start) and
864
+ * `'assembly'` (the rows a wake assembled for it) present, in one call and
865
+ * record order, the agent's own rows not in its window and its arrivals
866
+ * (none while frozen); `'compile'`, the backstop before every compile,
867
+ * fresh or resumed, its own rows only. Returns the arrivals presented, one
868
+ * per body, for the start to weigh. A fresh start ends a rollback's hold
869
+ * on the arrivals its cut returned (holdUntilStart): they enter with the
870
+ * rest, in record order, and the hold ends once they have, so a start
871
+ * that fails keeps it, and so does one while frozen, which presents no
872
+ * arrival; so does an agent the boot's pass at rest left out
873
+ * (repairAndRest's `restExcept`). A fresh start's presentation that fails (a read
874
+ * of the window or the record that throws, or a write of the window that
875
+ * leaves a row out) is traced, and then throws, so the start fails rather
876
+ * than compile without what it was started for, which waits outside the
877
+ * window for the next point. So does a fresh start where rows a
878
+ * write-down took in that aren't the agent's are still in its window
879
+ * (retractForeign failed again here), rather than compile with them. The
880
+ * backstop's is traced, and its compile goes on.
881
+ */
882
+ presentAtStart(agent: PresentedAgent, occasion: 'turn-start' | 'assembly' | 'compile'): StoredMessage[] {
883
+ if (!this.presenting(agent)) return [];
884
+ const cm = agent.getContextManager();
885
+ const fresh = occasion !== 'compile';
886
+ // The sweep below decides the own rows a failed write left (presentOwn):
887
+ // the backstop's at once, as its compile goes on whatever it presents; a
888
+ // fresh start's once it hasn't thrown, so the next own row's write still
889
+ // puts them first after a start that presented nothing. Only those kept
890
+ // before it: a listener of its presentation, which runs inside it, may
891
+ // store an own row whose presentation fails, kept by that nested write.
892
+ if (!fresh) this.failedOwn.delete(cm);
893
+ const keptBefore = fresh ? new Set(this.failedOwn.get(cm) ?? []) : undefined;
894
+ // A fresh start is where rows a write-down took in that aren't the
895
+ // agent's, whose retraction failed, leave before its compile, and a
896
+ // reader fork's framing whose presentation failed enters.
897
+ if (fresh) {
898
+ this.retryRetraction(agent, occasion);
899
+ if (this.adopted.get(cm)?.retractPending) {
900
+ throw new Error(`${agent.name}'s turn start could not take the rows that aren't its out of its window (at ${occasion}); they stay in it, and it doesn't compile, until a later point takes them out`);
901
+ }
902
+ }
903
+ if (fresh && this.framedPending.has(agent.name)) this.presentFramed(agent);
904
+ // A rollback's returned arrivals enter here (holdUntilStart): the hold
905
+ // is left out of this presentation, and ends once it hasn't failed, at a
906
+ // start that could present arrivals (none while frozen).
907
+ const withArrivals = fresh && !this.host.frozen();
908
+ const { arrivals, failure } = this.presentPending(agent, occasion, withArrivals, false,
909
+ fresh ? "the start fails, and what it didn't present waits for the next point" : undefined);
910
+ if (fresh && failure !== undefined) {
911
+ throw new Error(`${agent.name}'s turn start could not present what it is owed (at ${occasion}): ${describe(failure)}`, { cause: failure });
912
+ }
913
+ if (keptBefore) {
914
+ const keptMeanwhile = [...(this.failedOwn.get(cm) ?? [])].filter((id) => !keptBefore.has(id));
915
+ if (keptMeanwhile.length > 0) this.failedOwn.set(cm, new Set(keptMeanwhile));
916
+ else this.failedOwn.delete(cm);
917
+ }
918
+ if (withArrivals) {
919
+ this.heldUntilStart.delete(cm);
920
+ this.restWithheld.delete(agent.name);
921
+ }
922
+ return arrivals;
923
+ }
924
+
925
+ /**
926
+ * A tool boundary. First the round's own rows on the wire (`wire`: its
927
+ * reply, its results, a clock row due), those not in the window yet, in
928
+ * order; if that fails, nothing more. Then, unless the host is frozen or
929
+ * the stream can't carry injected rows (`injects` false), the agent's own
930
+ * rows not in its window and its arrivals, by bodies in record order, up
931
+ * to the first body the stream can't carry (isInjectableMidTurn: a tool
932
+ * block, or a row named as the agent), presented in one call: each body
933
+ * whole, named by its first shard not in the window. Those are what the
934
+ * stream carries next (`heard`); the cut body and those after it wait for
935
+ * the turn's end. A presentation cut short hears only the bodies wholly in
936
+ * the window. A read of the window or the record that throws is traced as
937
+ * presentation:failed, and the stream hears nothing: what wasn't presented
938
+ * waits for the next point, and the hand-off that follows checks the
939
+ * window as it then stands. Never throws, so the boundary goes on to hand
940
+ * the stream its results.
941
+ */
942
+ presentAtBoundary(agent: PresentedAgent, wire: ReadonlyArray<MessageId | undefined>, options: { injects: boolean }): BoundaryPresentation {
943
+ try {
944
+ if (!this.presenting(agent)) return { heard: [] };
945
+ const cm = agent.getContextManager();
946
+ const missing = unique(wire).filter((id) => cm.ordinalOf(id) === undefined);
947
+ // The round's rows are presented here, in order, and the own rows a
948
+ // failed write left (presentOwn) are this boundary's to sweep, or the
949
+ // next point's: none is put ahead of the next round's reply.
950
+ this.failedOwn.delete(cm);
951
+ if (missing.length > 0 && this.present(agent, missing, 'tool-boundary').error !== undefined) return { heard: [] };
952
+ if (this.host.frozen() || !options.injects) return { heard: [] };
953
+ const bodies = this.pending(agent, true);
954
+ const cut = bodies.findIndex((body) => body.shards.some((shard) => !isInjectableMidTurn(shard, agent)));
955
+ const prefix = cut === -1 ? bodies : bodies.slice(0, cut);
956
+ const cutAt = cut === -1 ? undefined : bodies[cut]!.shards[0]!.id;
957
+ const { entered } = this.present(agent, prefix.map((body) => body.shards[0]!.id), 'tool-boundary', {
958
+ unstamped: prefix.filter((body) => body.unstamped).length,
959
+ ...(cutAt !== undefined ? { cutAt } : {}),
960
+ }, prefix);
961
+ const heard = prefix
962
+ .filter((body) => entered.has(body.shards[0]!.id) && body.shards.every((shard) => cm.ordinalOf(shard.id) !== undefined))
963
+ .map((body): HeardRow => {
964
+ const head = body.shards[0]!;
965
+ return {
966
+ id: head.id,
967
+ participant: head.participant,
968
+ content: asCompiled(body.shards),
969
+ ...(head.metadata !== undefined ? { metadata: head.metadata } : {}),
970
+ };
971
+ });
972
+ return { heard, ...(cutAt !== undefined ? { cutAt } : {}) };
973
+ } catch (error) {
974
+ this.failed(agent, 'tool-boundary', error);
975
+ return { heard: [] };
976
+ }
977
+ }
978
+
979
+ /**
980
+ * A turn's end, and an agent at rest: when its logical turn isn't alive,
981
+ * its own rows not in its window and its arrivals (none while frozen), in
982
+ * one call and record order. Nothing while the turn is alive. Idempotent.
983
+ * Returns the arrivals presented, one per body.
984
+ */
985
+ presentAtEnd(agent: PresentedAgent): StoredMessage[] {
986
+ return this.presentAtRest(agent, 'turn-end');
987
+ }
988
+
989
+ /**
990
+ * The rows a rollback's branch cut took out of the agent's window and
991
+ * kept in the record (its `returnedToArrivals`, #291): they are arrivals
992
+ * again, and wait outside the window until the agent's next turn start
993
+ * (presentAtStart's `'turn-start'` or `'assembly'`), which presents them
994
+ * with whatever else it is owed, in record order (a start that fails
995
+ * keeps them held). Until then no point at
996
+ * rest presents them: not the surgery's release, a resume, a turn's end
997
+ * or a row stored for the agent while it is idle, so the cut the
998
+ * operator made is what the agent's window holds until it speaks again.
999
+ * A tool boundary isn't held back (a turn alive started since). An own
1000
+ * row among them isn't held: own rows enter at every point, as ever. The
1001
+ * hold is the branch's the store is on (the rollback's): on another
1002
+ * branch the same stored rows are arrivals as any, so a later move of the
1003
+ * store's branch, a suppression or rollback through another agent
1004
+ * included, ends it there, and back on this one they are held again until
1005
+ * the agent's next turn start. In memory: a restart presents them at its
1006
+ * pass at rest, or, where it boots quiesced, at the resume (a frozen pass
1007
+ * presents no arrival), and an agent let go (forget)
1008
+ * drops them. Rows given again on the same branch add to those held, and
1009
+ * on another replace them. Never throws.
1010
+ */
1011
+ holdUntilStart(agent: PresentedAgent, ids: readonly MessageId[]): void {
1012
+ const named = unique(ids);
1013
+ if (named.length === 0) return;
1014
+ const cm = agent.getContextManager();
1015
+ try {
1016
+ const branch = cm.currentBranch().name;
1017
+ const held = this.heldUntilStart.get(cm);
1018
+ const kept = held?.branch === branch ? held.ids : new Set<MessageId>();
1019
+ for (const id of named) kept.add(id);
1020
+ this.heldUntilStart.set(cm, { branch, ids: kept });
1021
+ // A scan at rest that left an earlier hold's rows out may have passed them.
1022
+ this.memos.delete(cm);
1023
+ } catch (error) {
1024
+ console.error(`[presentation] ${agent.name}: could not hold ${named.length} row(s) out of its window until its next turn start; they enter at its next presentation point:`, error);
1025
+ }
1026
+ }
1027
+
1028
+ /**
1029
+ * The check before a tool boundary hands the stream its rows: `sent` (the
1030
+ * round's reply, its results and the injected rows, in the order the
1031
+ * stream is given them) not yet in the window are presented, in order,
1032
+ * and the window's newest bodies must then be exactly those rows. On a
1033
+ * mismatch it traces presentation:hand-off-mismatch and the rows are not
1034
+ * vouched for, so the stream's later thinking is left out at the next
1035
+ * compile rather than sent under a prefix its window doesn't hold. An
1036
+ * agent the module doesn't present for is vouched for as before. A read
1037
+ * of the window that throws is traced as presentation:failed, and the
1038
+ * rows are not vouched for: the check couldn't be made. Never throws.
1039
+ */
1040
+ handOff(agent: PresentedAgent, sent: ReadonlyArray<MessageId | undefined>): { vouched: boolean } {
1041
+ try {
1042
+ if (!this.presenting(agent)) return { vouched: true };
1043
+ const cm = agent.getContextManager();
1044
+ const expected = unique(sent);
1045
+ if (expected.length === 0) return { vouched: true };
1046
+ const missing = expected.filter((id) => cm.ordinalOf(id) === undefined);
1047
+ if (missing.length > 0 && this.present(agent, missing, 'hand-off').error !== undefined) {
1048
+ this.host.emitTrace({ type: 'presentation:hand-off-mismatch', agentName: agent.name, expected, tail: lastBodyHeads(cm.getPresentedMessages(), expected.length) });
1049
+ return { vouched: false };
1050
+ }
1051
+ const tail = lastBodyHeads(cm.getPresentedMessages(), expected.length);
1052
+ if (tail.length !== expected.length || tail.some((id, i) => id !== expected[i])) {
1053
+ this.host.emitTrace({ type: 'presentation:hand-off-mismatch', agentName: agent.name, expected, tail });
1054
+ return { vouched: false };
1055
+ }
1056
+ return { vouched: true };
1057
+ } catch (error) {
1058
+ this.failed(agent, 'hand-off', error);
1059
+ return { vouched: false };
1060
+ }
1061
+ }
1062
+
1063
+ /** A read of the agent's arrivals not yet presented, one per body, in record order (for previews and a release). */
1064
+ arrivalsOf(agent: PresentedAgent): StoredMessage[] {
1065
+ if (!this.presenting(agent)) return [];
1066
+ return this.pending(agent, true).filter((body) => body.bearing === 'arrival').map((body) => body.shards[0]!);
1067
+ }
1068
+
1069
+ /**
1070
+ * A reader fork was handed held rows as framing (AF-5): those not in its
1071
+ * window yet are presented there, when the module presents for it, and
1072
+ * the fork counts as holding every one of them (holders, `'framing'`),
1073
+ * however its window filters held rows, until it is let go (forget). A
1074
+ * fork framed before it is taken on has them presented at its adopt. Its
1075
+ * window's filter (the residents', which a reader fork inherits) keeps
1076
+ * them out of its compiles, as it keeps all held traffic; its framing row
1077
+ * shows them where the framing puts them (the default's does); nothing
1078
+ * else of its window moves. Rows whose presentation fails enter at the
1079
+ * fork's next turn start, or after a move of the store's branch (rebase).
1080
+ */
1081
+ noteFramed(agent: PresentedAgent, rowIds: readonly MessageId[]): void {
1082
+ const set = this.framed.get(agent.name) ?? new Set<MessageId>();
1083
+ for (const id of rowIds) set.add(id);
1084
+ this.framed.set(agent.name, set);
1085
+ this.framedPending.add(agent.name);
1086
+ this.presentFramed(agent);
1087
+ }
1088
+
1089
+ /**
1090
+ * Drop the rows a reader fork was handed as framing (noteFramed) when the
1091
+ * fork is never taken on, so never let go (forget): one its run refused
1092
+ * before registering it (the host quiesced or stopping, a surgery holding
1093
+ * the store). Nothing for a name handed none.
1094
+ */
1095
+ forgetFramed(agent: AgentName): void {
1096
+ this.framed.delete(agent);
1097
+ this.framedPending.delete(agent);
1098
+ }
1099
+
1100
+ /**
1101
+ * The rows the agent is owed and its window doesn't hold yet, one per
1102
+ * body (its first shard not in the window), in record order: its own rows
1103
+ * and its arrivals, frozen or not, whatever its turn. None for an agent the
1104
+ * module doesn't present for. The subconscious's window start is fixed
1105
+ * once no row it is owed stored before the start is among them.
1106
+ */
1107
+ owedOf(agent: PresentedAgent): StoredMessage[] {
1108
+ if (!this.presenting(agent)) return [];
1109
+ return this.pending(agent, true).map((body) => body.shards[0]!);
1110
+ }
1111
+
1112
+ /**
1113
+ * Whether a row just stored in the agent's own slot, and presented at
1114
+ * rest by afterStore if at all, is out of its window though the agent is
1115
+ * owed it (its own row, or an arrival): a presentation that failed, or
1116
+ * the host's freeze, kept it out. A row that is nothing to the agent (held
1117
+ * from a resident, stamped for another) isn't. Yes where the window can't
1118
+ * be read to tell; no for an agent the module doesn't present for.
1119
+ */
1120
+ notPresented(agent: PresentedAgent, id: MessageId): boolean {
1121
+ try {
1122
+ if (!this.presenting(agent)) return false;
1123
+ const cm = agent.getContextManager();
1124
+ if (cm.windowStatusOf(id) !== 'out') return false;
1125
+ const row = cm.getMessage(id);
1126
+ return row === null || bearingOf(row, readerFacts(this.host.registry, agent.name), 'own') !== 'elsewhere';
1127
+ } catch {
1128
+ return true;
1129
+ }
1130
+ }
1131
+
1132
+ // --------------------------------------------------------------------------
1133
+ // Reads
1134
+ // --------------------------------------------------------------------------
1135
+
1136
+ /**
1137
+ * Every live agent holding a row: each whose window has it at a place,
1138
+ * leaving out one whose window leaves held rows out when the row is held
1139
+ * (a window written down from the record took in those an earlier release
1140
+ * stored, before the audience stamp; retractForeign takes out the rest),
1141
+ * and every one when a suppress rule hid the row, which no view renders;
1142
+ * each whose window
1143
+ * is still the whole record and whose record holds it; and each reader fork
1144
+ * handed it as framing.
1145
+ */
1146
+ holders(rowId: MessageId): Holder[] {
1147
+ const holders: Holder[] = [];
1148
+ const inWindow = new Set<AgentName>();
1149
+ for (const agent of this.host.liveAgents()) {
1150
+ const cm = agent.getContextManager();
1151
+ if (cm.isClosed()) continue;
1152
+ if (this.adopted.get(cm)?.pinnedLegacy || cm.windowMode() !== 'presented') {
1153
+ if (cm.getMessage(rowId) !== null || cm.getPresentedMessages().some((m) => m.id === rowId)) {
1154
+ holders.push({ agent: agent.name, via: 'legacy' });
1155
+ }
1156
+ continue;
1157
+ }
1158
+ const position = positionIn(cm, rowId);
1159
+ if (position === undefined) continue;
1160
+ const metadata = cm.getMessage(rowId)?.metadata as Record<string, unknown> | undefined;
1161
+ if (suppressedRow(metadata)) continue;
1162
+ if (readerFacts(this.host.registry, agent.name).hidesHeld && heldFromResidents(metadata)) continue;
1163
+ holders.push({ agent: agent.name, via: 'window', position });
1164
+ inWindow.add(agent.name);
1165
+ }
1166
+ for (const [agent, ids] of this.framed) {
1167
+ if (ids.has(rowId) && !inWindow.has(agent)) holders.push({ agent, via: 'framing' });
1168
+ }
1169
+ return holders;
1170
+ }
1171
+
1172
+ /**
1173
+ * Rows removed from the record through `remover` (a context manager of a
1174
+ * live agent's, or one opened apart from them), taken out of every other
1175
+ * live agent's window that still holds them: context-manager tombstones a
1176
+ * removal in the remover's own window only, and another window on the
1177
+ * same slot, or merging it, keeps the row's place (CM-T) while its listing
1178
+ * and its compile leave the row out. Each row leaves at its own place, so
1179
+ * no other row's place moves, and a cursor or watermark kept by place
1180
+ * stays good. A window on a branch whose record still holds the row (a
1181
+ * fork, a derived agent's view made before the removal) keeps it, as does
1182
+ * a window that is still the record, which is never written to here
1183
+ * (context-manager's retractRemoved passes over both). Each window's rows
1184
+ * taken out are traced (presentation:retracted, with `reason`), and a
1185
+ * window that couldn't be repaired is logged and passed by: the removal
1186
+ * stands. `ids` names every row removed, a body by each of its shards.
1187
+ * Returns what left each window. Never throws.
1188
+ */
1189
+ retractRemoved(remover: WindowManager | undefined, ids: readonly MessageId[], reason: PresentationRetractReason): Array<{ agent: AgentName; ids: MessageId[] }> {
1190
+ const named = unique(ids).filter((id) => id !== '');
1191
+ if (named.length === 0) return [];
1192
+ const visited = new Set<WindowManager>(remover ? [remover] : []);
1193
+ const out: Array<{ agent: AgentName; ids: MessageId[] }> = [];
1194
+ for (const agent of this.host.liveAgents()) {
1195
+ const cm = agent.getContextManager();
1196
+ if (visited.has(cm)) continue;
1197
+ visited.add(cm);
1198
+ try {
1199
+ // A window that is still the record holds no place for the row:
1200
+ // checked here as well as by the call, which writes nothing then.
1201
+ if (cm.isClosed() || cm.windowMode() !== 'presented') continue;
1202
+ const taken = cm.retractRemoved(named);
1203
+ if (taken.length === 0) continue;
1204
+ out.push({ agent: agent.name, ids: taken });
1205
+ this.host.emitTrace({ type: 'presentation:retracted', agentName: agent.name, messageIds: taken, reason });
1206
+ } catch (error) {
1207
+ console.error(`[presentation] could not take ${named.length} removed row(s) out of ${agent.name}'s window (${reason}); the removal stands: ${describe(error)}`);
1208
+ }
1209
+ }
1210
+ return out;
1211
+ }
1212
+
1213
+ /**
1214
+ * At boot, after every live agent is taken on: take out of each window
1215
+ * the module presents for every row it holds that its record no longer
1216
+ * does (context-manager's retractAbsentRows), as retractRemoved takes out
1217
+ * the rows a live removal named. These are rows removed where no live
1218
+ * context heard it: by an offline recovery's suppressions, with the host
1219
+ * stopped, through the one context it opened, and removals whose own
1220
+ * tombstone failed. Traced as presentation:retracted with `boot`; a
1221
+ * window that couldn't be repaired is logged and passed by. Each agent's
1222
+ * context is open with every slot it merges by then, so a row of a slot
1223
+ * it merges isn't taken for removed. Never throws.
1224
+ */
1225
+ retractAbsentRows(): Array<{ agent: AgentName; ids: MessageId[] }> {
1226
+ const out: Array<{ agent: AgentName; ids: MessageId[] }> = [];
1227
+ const visited = new Set<WindowManager>();
1228
+ for (const agent of this.host.liveAgents()) {
1229
+ const cm = agent.getContextManager();
1230
+ if (visited.has(cm)) continue;
1231
+ visited.add(cm);
1232
+ try {
1233
+ if (!this.presenting(agent)) continue;
1234
+ const taken = cm.retractAbsentRows();
1235
+ if (taken.length === 0) continue;
1236
+ out.push({ agent: agent.name, ids: taken });
1237
+ this.host.emitTrace({ type: 'presentation:retracted', agentName: agent.name, messageIds: taken, reason: 'boot' });
1238
+ } catch (error) {
1239
+ console.error(`[presentation] could not take removed rows out of ${agent.name}'s window at boot: ${describe(error)}`);
1240
+ }
1241
+ }
1242
+ return out;
1243
+ }
1244
+
1245
+ /** Whether a reader fork was handed the row as framing (noteFramed), and
1246
+ * hasn't been let go since, whether or not its window holds the row. */
1247
+ framedToAny(rowId: MessageId): boolean {
1248
+ for (const ids of this.framed.values()) if (ids.has(rowId)) return true;
1249
+ return false;
1250
+ }
1251
+
1252
+ /** Whether any live agent but `except` holds the row in a window or as framing: a window that is still the record doesn't count. */
1253
+ presentedToAnyone(rowId: MessageId, options: { except?: AgentName } = {}): boolean {
1254
+ return this.holders(rowId).some((h) => h.via !== 'legacy' && h.agent !== options.except);
1255
+ }
1256
+
1257
+ /** The rows of the agent's window at or after `mark`, in window order; none in legacy mode. */
1258
+ presentedSince(agent: PresentedAgent, mark: Position): StoredMessage[] {
1259
+ const cm = agent.getContextManager();
1260
+ if (cm.windowMode() !== 'presented') return [];
1261
+ return cm.getPresentedMessages().filter((m) => (cm.ordinalOf(m.id) ?? -1) >= mark);
1262
+ }
1263
+
1264
+ /** Hear each presentation into the named agent's window, after its rows entered. Returns the unsubscribe. */
1265
+ onPresented(agentName: AgentName, listener: (event: PresentedEvent) => void): () => void {
1266
+ const set = this.listeners.get(agentName) ?? new Set();
1267
+ set.add(listener);
1268
+ this.listeners.set(agentName, set);
1269
+ return () => {
1270
+ set.delete(listener);
1271
+ if (set.size === 0 && this.listeners.get(agentName) === set) this.listeners.delete(agentName);
1272
+ };
1273
+ }
1274
+
1275
+ /**
1276
+ * A write's stamp, checked as it is stored through `deliveredTo`'s
1277
+ * context: an audience none of whose agents reads that slot is traced
1278
+ * (presentation:unreadable-audience), once for the write. The row is
1279
+ * stored as named.
1280
+ */
1281
+ checkAudience(metadata: MessageMetadata | undefined, deliveredTo: AgentName): void {
1282
+ const stamp = audienceOf(metadata);
1283
+ if (!stamp) return;
1284
+ const slot = this.host.registry.ownSlotOf(deliveredTo);
1285
+ if (!slot || !audienceFault(stamp.audience, slot, this.host.registry)) return;
1286
+ this.host.emitTrace({ type: 'presentation:unreadable-audience', audience: stamp.audience, slot, deliveredTo });
1287
+ }
1288
+
1289
+ // --------------------------------------------------------------------------
1290
+ // Internals
1291
+ // --------------------------------------------------------------------------
1292
+
1293
+ /**
1294
+ * The own rows whose presentation at their write failed (presentOwn) and
1295
+ * that are still out of the agent's window, in record order. A row that
1296
+ * entered by another point since, was undone, or left the record (a
1297
+ * branch move, a removal) is dropped.
1298
+ */
1299
+ private failedOwnOf(agent: PresentedAgent): MessageId[] {
1300
+ const cm = agent.getContextManager();
1301
+ const kept = this.failedOwn.get(cm);
1302
+ if (!kept || kept.size === 0) return [];
1303
+ const owed: Array<{ id: MessageId; sequence: number }> = [];
1304
+ for (const id of kept) {
1305
+ const row = cm.windowStatusOf(id) === 'out' ? cm.getMessage(id) : null;
1306
+ if (row) owed.push({ id, sequence: row.sequence });
1307
+ }
1308
+ if (owed.length === 0) this.failedOwn.delete(cm);
1309
+ return owed.sort((a, b) => a.sequence - b.sequence).map((row) => row.id);
1310
+ }
1311
+
1312
+ /**
1313
+ * Keep, of the own rows presentOwn tried, those still out of the window,
1314
+ * for its next call; forget the rest. Rows kept meanwhile that this call
1315
+ * didn't try stay kept: a listener of its presentation, which runs
1316
+ * inside it, may have stored an own row whose presentation failed, kept
1317
+ * by that nested call.
1318
+ */
1319
+ private keepFailedOwn(agent: PresentedAgent, tried: readonly MessageId[]): void {
1320
+ const cm = agent.getContextManager();
1321
+ const triedHere = new Set(tried);
1322
+ const keptMeanwhile = [...(this.failedOwn.get(cm) ?? [])].filter((id) => !triedHere.has(id));
1323
+ let keep: MessageId[];
1324
+ try {
1325
+ keep = [...tried, ...keptMeanwhile].filter((id) => cm.ordinalOf(id) === undefined);
1326
+ } catch {
1327
+ // A window that can't be read now: keep every row tried.
1328
+ keep = [...tried, ...keptMeanwhile];
1329
+ }
1330
+ if (keep.length > 0) this.failedOwn.set(cm, new Set(keep));
1331
+ else this.failedOwn.delete(cm);
1332
+ }
1333
+
1334
+ /** presentAtEnd under a named occasion; a rollback's held arrivals wait (holdUntilStart), and so do all of an agent's the boot left out (restWithheld). */
1335
+ private presentAtRest(agent: PresentedAgent, occasion: 'turn-end' | 'at-rest'): StoredMessage[] {
1336
+ if (!this.presenting(agent) || this.host.turnAlive(agent.name)) return [];
1337
+ this.retryRetraction(agent, occasion);
1338
+ return this.presentPending(agent, occasion, !this.host.frozen() && !this.restWithheld.has(agent.name), true).arrivals;
1339
+ }
1340
+
1341
+ /** The rows the agent was handed as framing (noteFramed) that its window doesn't hold yet, presented in the order handed. */
1342
+ private presentFramed(agent: PresentedAgent): void {
1343
+ const framed = this.framed.get(agent.name);
1344
+ if (!framed || framed.size === 0) {
1345
+ this.framedPending.delete(agent.name);
1346
+ return;
1347
+ }
1348
+ try {
1349
+ if (!this.presenting(agent)) return;
1350
+ const cm = agent.getContextManager();
1351
+ // presentRows refuses a row the window holds already, and a reader
1352
+ // fork derived from a presented window holds those rows its parent's
1353
+ // window was written down with.
1354
+ const unpresented = new Set(cm.getUnpresentedMessages().map((m) => m.id));
1355
+ const { error } = this.present(agent, [...framed].filter((id) => unpresented.has(id)), 'framing');
1356
+ // Pending until a presentation of them doesn't fail: the fork's next
1357
+ // turn start tries again (presentAtStart).
1358
+ if (error === undefined) this.framedPending.delete(agent.name);
1359
+ } catch (error) {
1360
+ this.failed(agent, 'framing', error);
1361
+ }
1362
+ }
1363
+
1364
+ /** The own-row sweep: the agent's own rows not in its window, presented in record order, traced as a repair. */
1365
+ private repair(agent: PresentedAgent, occasion: 'adopt' | 'rebase' = 'adopt'): void {
1366
+ try {
1367
+ const own = this.pending(agent, false);
1368
+ if (own.length === 0) return;
1369
+ const { entered } = this.present(agent, own.map((body) => body.shards[0]!.id), occasion, undefined, own, true);
1370
+ if (entered.size > 0) this.host.emitTrace({ type: 'presentation:repaired', agentName: agent.name, count: entered.size });
1371
+ } catch (error) {
1372
+ this.failed(agent, occasion, error);
1373
+ }
1374
+ }
1375
+
1376
+ /**
1377
+ * Present the agent's own pending rows, and its arrivals when `arrivals`
1378
+ * (but those a rollback holds for its next start, with `atRest`), in one
1379
+ * call; return the arrivals that entered whole, and the error when the
1380
+ * presentation failed: a read that threw, or a write that left a row it
1381
+ * named out. `next` is what the failure's log says becomes of its rows.
1382
+ */
1383
+ private presentPending(
1384
+ agent: PresentedAgent,
1385
+ occasion: PresentationOccasion,
1386
+ arrivals: boolean,
1387
+ atRest = false,
1388
+ next?: string,
1389
+ ): { arrivals: StoredMessage[]; failure?: unknown } {
1390
+ try {
1391
+ const cm = agent.getContextManager();
1392
+ const bodies = this.pending(agent, arrivals, atRest);
1393
+ if (bodies.length === 0) return { arrivals: [] };
1394
+ const heads = bodies.map((body) => body.shards[0]!.id);
1395
+ const { entered, error } = this.present(agent, heads, occasion, {
1396
+ unstamped: bodies.filter((body) => body.unstamped).length,
1397
+ ...(next !== undefined ? { next } : {}),
1398
+ }, bodies);
1399
+ return {
1400
+ arrivals: bodies
1401
+ .filter((body) => body.bearing === 'arrival' && entered.has(body.shards[0]!.id)
1402
+ && body.shards.every((shard) => cm.ordinalOf(shard.id) !== undefined))
1403
+ .map((body) => body.shards[0]!),
1404
+ ...(error !== undefined && heads.some((id) => !entered.has(id)) ? { failure: error } : {}),
1405
+ };
1406
+ } catch (error) {
1407
+ this.failed(agent, occasion, error, undefined, next);
1408
+ return { arrivals: [], failure: error };
1409
+ }
1410
+ }
1411
+
1412
+ /**
1413
+ * The agent's pending bodies, in record order: its own rows not in its
1414
+ * window, and its arrivals when `arrivals`, leaving out, with `atRest`,
1415
+ * an arrival a rollback holds for the agent's next start (any shard of
1416
+ * its body held). A body is its run of unpresented shards
1417
+ * (continuesBody), weighed by its first.
1418
+ */
1419
+ private pending(agent: PresentedAgent, arrivals: boolean, atRest = false): PendingBody[] {
1420
+ const cm = agent.getContextManager();
1421
+ const facts = readerFacts(this.host.registry, agent.name);
1422
+ const factsKey = JSON.stringify(facts);
1423
+ const branch = cm.currentBranch().name;
1424
+ // A rollback's hold is its branch's: on another the rows are arrivals as any.
1425
+ const hold = atRest ? this.heldUntilStart.get(cm) : undefined;
1426
+ const held = hold?.branch === branch && hold.ids.size > 0 ? hold.ids : undefined;
1427
+ const length = cm.indexLength();
1428
+ let memo = this.memos.get(cm);
1429
+ if (!memo || memo.generation !== this.generation || memo.branch !== branch || memo.length !== length || memo.facts !== factsKey) {
1430
+ memo = { generation: this.generation, branch, length, facts: factsKey, scanFrom: -Infinity };
1431
+ this.memos.set(cm, memo);
1432
+ }
1433
+ // Every unpresented row at or below the memo's mark was elsewhere, so the
1434
+ // listing starts after it (context-manager finds the place by a search):
1435
+ // a scan walks the rows stored since, not every row of others' the
1436
+ // record holds. A scan that leaves held arrivals out may start at its own
1437
+ // mark too, which held rows don't hold back (heldScanFrom).
1438
+ const from = held ? Math.max(memo.scanFrom, memo.heldScanFrom ?? -Infinity) : memo.scanFrom;
1439
+ const unpresented = from === -Infinity
1440
+ ? cm.getUnpresentedMessages()
1441
+ : cm.getUnpresentedMessages({ afterSequence: from });
1442
+ const bodies: PendingBody[] = [];
1443
+ let firstOwed: number | undefined;
1444
+ let newest = from;
1445
+ let i = 0;
1446
+ while (i < unpresented.length) {
1447
+ const start = i;
1448
+ i++;
1449
+ while (i < unpresented.length && continuesBody(unpresented[i - 1], unpresented[i])) i++;
1450
+ const head = unpresented[start]!;
1451
+ newest = Math.max(newest, unpresented[i - 1]!.sequence);
1452
+ if (head.sequence <= from) continue;
1453
+ const bearing = bearingOf(head, facts, this.slotOfRow(cm, facts, head.id));
1454
+ if (bearing === 'elsewhere') continue;
1455
+ // A held arrival is still owed, and every scan but this one counts it
1456
+ // (firstOwed, in `scanFrom`), so a scan that presents it, or counts
1457
+ // what is owed, starts at or before it; this one passes it over.
1458
+ const isHeld = bearing === 'arrival' && held !== undefined
1459
+ && unpresented.slice(start, i).some((shard) => held.has(shard.id));
1460
+ if (!isHeld) firstOwed ??= head.sequence;
1461
+ if (isHeld || (bearing === 'arrival' && !arrivals)) continue;
1462
+ bodies.push({ shards: unpresented.slice(start, i), bearing, unstamped: audienceOf(head.metadata) === undefined });
1463
+ }
1464
+ const next = firstOwed !== undefined ? Math.max(from, firstOwed - 1) : newest;
1465
+ if (held) memo.heldScanFrom = next;
1466
+ else memo.scanFrom = next;
1467
+ return bodies;
1468
+ }
1469
+
1470
+ /**
1471
+ * The slot of `cm`'s record a row is stored in, for bearingOf: its own
1472
+ * (`'own'`, which getMessage reads), else the merged slot that holds it
1473
+ * (mergedSlotsOf). The record holds the context's own slot and one
1474
+ * auxiliary view per merged slot, so a row not in its own is in the one
1475
+ * merged slot when there is one; when there are more, each is asked, by
1476
+ * a read-only handle on it over the manager's store, which follows its
1477
+ * branch and its writes as the manager's own views do. undefined for a
1478
+ * row in none of them (a slot the reader has no edge on).
1479
+ */
1480
+ private slotOfRow(cm: WindowManager, facts: ReaderFacts, id: MessageId): RowSlot | undefined {
1481
+ if (cm.getMessage(id) !== null) return 'own';
1482
+ const merged = mergedSlotsOf(facts);
1483
+ if (merged.length <= 1) return merged[0];
1484
+ let readers = this.slotReaders.get(cm);
1485
+ if (!readers) {
1486
+ readers = new Map();
1487
+ this.slotReaders.set(cm, readers);
1488
+ }
1489
+ for (const slot of merged) {
1490
+ let reader = readers.get(slot.namespace);
1491
+ if (!reader) {
1492
+ reader = new MessageStore(cm.getStore(), slot.namespace === null ? {} : { namespace: slot.namespace });
1493
+ readers.set(slot.namespace, reader);
1494
+ }
1495
+ if (reader.sequenceOf(id) !== undefined) return slot;
1496
+ }
1497
+ return undefined;
1498
+ }
1499
+
1500
+ /**
1501
+ * One presentRows call for `ids` in the agent's window: every row named
1502
+ * counts once it returns (it refuses a row already in the window, and
1503
+ * returns one ordinal per row named); on a throw, the rows that entered
1504
+ * before it count, as far as the window can be read then, and the
1505
+ * failure is traced. Traces what entered and tells the listeners.
1506
+ */
1507
+ private present(
1508
+ agent: PresentedAgent,
1509
+ ids: readonly MessageId[],
1510
+ occasion: PresentationOccasion,
1511
+ extra?: { unstamped?: number; cutAt?: MessageId; next?: string },
1512
+ bodies?: readonly PendingBody[],
1513
+ quiet = false,
1514
+ ): { entered: Set<MessageId>; error?: unknown } {
1515
+ if (ids.length === 0) return { entered: new Set() };
1516
+ const cm = agent.getContextManager();
1517
+ const lengthBefore = cm.indexLength();
1518
+ let error: unknown;
1519
+ let entered: Set<MessageId>;
1520
+ try {
1521
+ cm.presentRows(ids);
1522
+ // Read from the write's return, not the window: a read that throws
1523
+ // now mustn't keep rows the store holds from being traced and told.
1524
+ entered = new Set(ids);
1525
+ } catch (thrown) {
1526
+ error = thrown;
1527
+ try {
1528
+ entered = new Set(ids.filter((id) => cm.ordinalOf(id) !== undefined));
1529
+ } catch (readError) {
1530
+ console.error(`[presentation] ${agent.name}'s window couldn't be read after a failed presentation, so none of it is counted as entered:`, readError);
1531
+ entered = new Set();
1532
+ }
1533
+ }
1534
+ const memo = this.memos.get(cm);
1535
+ if (memo && memo.length === lengthBefore) {
1536
+ try {
1537
+ memo.length = cm.indexLength();
1538
+ } catch {
1539
+ // The scan's memo can't be moved past the rows: the next scan reads them again.
1540
+ this.memos.delete(cm);
1541
+ }
1542
+ }
1543
+ if (error !== undefined) this.failed(agent, occasion, error, ids.filter((id) => !entered.has(id)), extra?.next);
1544
+ if (entered.size > 0) {
1545
+ if (!quiet) {
1546
+ const unstamped = extra?.unstamped !== undefined && bodies
1547
+ ? bodies.filter((body) => body.unstamped && entered.has(body.shards[0]!.id)).length
1548
+ : 0;
1549
+ this.host.emitTrace({
1550
+ type: 'presentation:presented',
1551
+ agentName: agent.name,
1552
+ occasion,
1553
+ count: entered.size,
1554
+ ...(extra?.cutAt !== undefined ? { cutAt: extra.cutAt } : {}),
1555
+ ...(unstamped > 0 ? { unstamped } : {}),
1556
+ });
1557
+ }
1558
+ this.tell(agent, occasion, ids, entered, bodies);
1559
+ }
1560
+ return { entered, ...(error !== undefined ? { error } : {}) };
1561
+ }
1562
+
1563
+ /**
1564
+ * Tell the agent's listeners of the rows that entered its window, in
1565
+ * order, each body as the window holds it. Where the window can't be
1566
+ * read for that, they are told of each entered row by its first shard
1567
+ * (a body's later shards left out), and that is logged: the rows are in
1568
+ * the window whatever the read, so the listeners (noteArrival, the
1569
+ * subconscious's anchor) still hear them.
1570
+ */
1571
+ private tell(
1572
+ agent: PresentedAgent,
1573
+ occasion: PresentationOccasion,
1574
+ ids: readonly MessageId[],
1575
+ entered: ReadonlySet<MessageId>,
1576
+ bodies?: readonly PendingBody[],
1577
+ ): void {
1578
+ const listeners = this.listeners.get(agent.name);
1579
+ if (!listeners || listeners.size === 0) return;
1580
+ const cm = agent.getContextManager();
1581
+ const byHead = new Map((bodies ?? []).map((body) => [body.shards[0]!.id, body.shards] as const));
1582
+ let window: StoredMessage[] | undefined;
1583
+ const named = ids.filter((id) => entered.has(id));
1584
+ let rows: StoredMessage[];
1585
+ try {
1586
+ rows = named.flatMap((id) => {
1587
+ const shards = byHead.get(id);
1588
+ if (shards) return shards.filter((shard) => cm.ordinalOf(shard.id) !== undefined);
1589
+ // A row named alone (an own row at its write): its body as the window now holds it.
1590
+ window ??= cm.getPresentedMessages();
1591
+ const at = window.findIndex((m) => m.id === id);
1592
+ if (at === -1) return [];
1593
+ let end = at + 1;
1594
+ while (end < window.length && continuesBody(window[end - 1], window[end])) end++;
1595
+ return window.slice(at, end);
1596
+ });
1597
+ } catch (error) {
1598
+ console.error(`[presentation] ${agent.name}'s window couldn't be read to tell its listeners which rows entered it, so they are told of each by its first shard:`, error);
1599
+ rows = named.flatMap((id) => {
1600
+ const head = byHead.get(id)?.[0];
1601
+ if (head) return [head];
1602
+ try {
1603
+ const row = cm.getMessage(id);
1604
+ return row ? [row] : [];
1605
+ } catch {
1606
+ return [];
1607
+ }
1608
+ });
1609
+ }
1610
+ for (const listener of [...listeners]) {
1611
+ try {
1612
+ listener({ agentName: agent.name, occasion, rows });
1613
+ } catch (error) {
1614
+ console.error(`[presentation] a listener of ${agent.name}'s window failed:`, error);
1615
+ }
1616
+ }
1617
+ }
1618
+
1619
+ /**
1620
+ * A presentation that failed, logged and traced (presentation:failed):
1621
+ * `ids` are the rows it named that didn't enter the window (a body by
1622
+ * the id that names it), where they are known, and `next` says what
1623
+ * becomes of them.
1624
+ */
1625
+ private failed(
1626
+ agent: PresentedAgent,
1627
+ occasion: PresentationOccasion,
1628
+ error: unknown,
1629
+ ids?: readonly MessageId[],
1630
+ next = "what it didn't present waits for the next point",
1631
+ ): void {
1632
+ const left = ids !== undefined && ids.length > 0 ? [...ids] : undefined;
1633
+ const named = left
1634
+ ? ` ${left.length} row${left.length === 1 ? '' : 's'} (${left.slice(0, 10).join(', ')}${left.length > 10 ? ', …' : ''})`
1635
+ : '';
1636
+ console.error(`[presentation] ${agent.name}: presenting${named} at ${occasion} failed; ${next}:`, error);
1637
+ this.host.emitTrace({
1638
+ type: 'presentation:failed', agentName: agent.name, occasion, error: describe(error), ...(left ? { messageIds: left } : {}),
1639
+ });
1640
+ }
1641
+ }
1642
+
1643
+ /** Whether `cm`'s window reads as presented; a mode that can't be read is not. */
1644
+ function readsPresented(cm: Pick<WindowManager, 'windowMode'>): boolean {
1645
+ try {
1646
+ return cm.windowMode() === 'presented';
1647
+ } catch {
1648
+ return false;
1649
+ }
1650
+ }
1651
+
1652
+ /** The defined ids, each once, in order. */
1653
+ function unique(ids: ReadonlyArray<MessageId | undefined>): MessageId[] {
1654
+ const seen = new Set<MessageId>();
1655
+ const out: MessageId[] = [];
1656
+ for (const id of ids) {
1657
+ if (id === undefined || seen.has(id)) continue;
1658
+ seen.add(id);
1659
+ out.push(id);
1660
+ }
1661
+ return out;
1662
+ }
1663
+
1664
+ /** How many bodies a window holds, a sharded one counted once. */
1665
+ function bodyHeadCount(window: readonly StoredMessage[]): number {
1666
+ let count = 0;
1667
+ for (let i = 0; i < window.length; i++) if (i === 0 || !continuesBody(window[i - 1], window[i])) count++;
1668
+ return count;
1669
+ }
1670
+
1671
+ /** The ids of the last `count` bodies of a window, by their first shards, in window order. */
1672
+ function lastBodyHeads(window: readonly StoredMessage[], count: number): MessageId[] {
1673
+ const heads: MessageId[] = [];
1674
+ for (let i = window.length - 1; i >= 0 && heads.length < count; i--) {
1675
+ if (i === 0 || !continuesBody(window[i - 1], window[i])) heads.unshift(window[i]!.id);
1676
+ }
1677
+ return heads;
1678
+ }