@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -0,0 +1,843 @@
1
+ /**
2
+ * The single-slot owner queue.
3
+ *
4
+ * Items have one origin each; the origin fixes the item's identity, what
5
+ * opens an episode and the only evidence that closes it. Every step is one
6
+ * row of the item transition table (README) and writes one `surface` record (or, for
7
+ * the three sending steps, an attempt record, the send, and an outcome
8
+ * record). Five counters are stored on every surface record and copied
9
+ * forward, so a restart reads them back rather than recounting.
10
+ *
11
+ * A "send" here is only a returned effect description: `{ op: 'send' }`.
12
+ */
13
+
14
+ import { sourceCaps } from './config.js'
15
+ import { effectiveState, sessionsOf } from './derive.js'
16
+ import { compareKeys } from './policy.js'
17
+ import { put } from './checks.js'
18
+ import { H } from './hash.js'
19
+ import { SENDING_STEPS, itemIds, ownerAckKey, sessionKey, surfaceKey, systemKey } from './keys.js'
20
+
21
+ const ZERO = Object.freeze({ presentation: 0, shows_counted: 0, reminders_used: 0, returns_used: 0, round_shows: 0 })
22
+ export const DISMISSABLE = new Set(['seed', 'issue', 'attention', 'gone'])
23
+ const OWNER_BLOCK_ORIGINS = new Set(['owner'])
24
+
25
+ function envOf(item) {
26
+ return item.session ? { source: item.session.source, native_id: item.session.native_id, incarnation: item.session.incarnation ?? null } : null
27
+ }
28
+
29
+ function body(item, step, phase, n, c, extra) {
30
+ return {
31
+ item_id: item.itemId,
32
+ item_kind: item.kind,
33
+ origin: item.origin,
34
+ episode: item.episode,
35
+ step,
36
+ n,
37
+ phase,
38
+ outcome: null,
39
+ presentation: c.presentation,
40
+ shows_counted: c.shows_counted,
41
+ reminders_used: c.reminders_used,
42
+ returns_used: c.returns_used,
43
+ round_shows: c.round_shows ?? 0,
44
+ fingerprint: item.fingerprint ?? null,
45
+ opened_by: item.openedBy ?? null,
46
+ reason: null,
47
+ report_id: item.reportId ?? null,
48
+ channel_ref: null,
49
+ resolution_evidence: null,
50
+ source: item.source ?? null,
51
+ // DESIGN-GAP (added field): an owner item's records all carry its live
52
+ // asks, so each states the content it was made with; without it two
53
+ // records of one step at one presentation could differ only in content
54
+ // the record does not show.
55
+ ...(item.asks?.size ? { asks: [...item.asks.values()] } : {}),
56
+ ...extra,
57
+ }
58
+ }
59
+
60
+ /** A step that sends nothing: one surface record with phase `none`. */
61
+ function* step(ctx, item, name, { ordCtx = {}, c = item.counters, extra = {}, now }) {
62
+ const ordinal = ctx.policy.surfaceOrdinal(name, { presentation: c.presentation, returns: c.returns_used, contentRef: item.contentRef, carryRef: item.carryRef, ...ordCtx })
63
+ const id = surfaceKey(item.itemId, item.episode, name, ordinal, 'none')
64
+ return yield put({ kind: 'surface', id, session: envOf(item), body: body(item, name, 'none', ordinal, c, extra) }, now)
65
+ }
66
+
67
+ /** A sending step: attempt record, the send, outcome record. */
68
+ function* sendStep(ctx, item, name, { ordCtx = {}, c, extra = {}, now }) {
69
+ if (!SENDING_STEPS.has(name)) throw new Error(`sendStep: ${name} does not send`)
70
+ const ordinal = ctx.policy.surfaceOrdinal(name, { presentation: c.presentation, returns: c.returns_used, ...ordCtx })
71
+ const attemptId = surfaceKey(item.itemId, item.episode, name, ordinal, 'attempt')
72
+ if (ctx.policy.attemptAlreadyRecorded(ctx.ledger, attemptId)) return { sent: false }
73
+ yield put({ kind: 'surface', id: attemptId, session: envOf(item), body: body(item, name, 'attempt', ordinal, c, extra) }, now)
74
+ const outcome = yield {
75
+ op: 'send',
76
+ effect: { attempt_id: attemptId, item_id: item.itemId, item_kind: item.kind, origin: item.origin, episode: item.episode, step: name, n: ordinal, session: envOf(item) },
77
+ }
78
+ const delivered = outcome === 'failed' ? 'failed' : 'delivered'
79
+ const outId = surfaceKey(item.itemId, item.episode, name, ordinal, 'outcome')
80
+ yield put({ kind: 'surface', id: outId, session: envOf(item), body: { ...body(item, name, 'outcome', ordinal, c, extra), outcome: delivered, attempt_id: attemptId } }, now)
81
+ return { sent: true }
82
+ }
83
+
84
+ /** Record an attempt that has no outcome as `delivery_unknown`; never re-send it. */
85
+ export function* sweepUnknownDeliveries(ctx, now) {
86
+ for (const a of ctx.state.attempts.values()) {
87
+ if (a.hasOutcome || a.unknown) continue
88
+ yield put({ kind: 'system', id: systemKey('delivery_unknown', [a.id]), body: { event: 'delivery_unknown', detail: { ids: [a.id] } } }, now)
89
+ }
90
+ }
91
+
92
+ function* raise(ctx, { itemId, kind, origin, session, source, ref, fingerprint, contentRef, contentAt = null, reportId, deadline, orderTime, closable = true, seed = null, condition, handoverOf, counters = ZERO, asks, ask, now }) {
93
+ const st = ctx.state
94
+ const existing = st.items.get(itemId)
95
+ if (!ctx.policy.mayOpenEpisode(existing, ref, origin)) return false
96
+ const item = {
97
+ itemId,
98
+ kind,
99
+ origin,
100
+ session,
101
+ source,
102
+ episode: (existing?.episode ?? 0) + 1,
103
+ counters: { ...counters },
104
+ openedBy: ref,
105
+ fingerprint,
106
+ reportId,
107
+ }
108
+ yield* step(ctx, item, 'queued', {
109
+ c: item.counters,
110
+ now,
111
+ extra: {
112
+ content_ref: contentRef ?? ref,
113
+ content_at: contentAt,
114
+ deadline: deadline ?? null,
115
+ order_time: orderTime ?? null,
116
+ closable,
117
+ seed,
118
+ ...(condition ? { condition } : {}),
119
+ ...(handoverOf ? { handover_of: handoverOf } : {}),
120
+ ...(asks ? { asks, ask } : {}),
121
+ },
122
+ })
123
+ return true
124
+ }
125
+
126
+ /**
127
+ * The verification of an acknowledgment, written once.
128
+ *
129
+ * DESIGN-GAP: two steps verify an acknowledgment, the tick that finds
130
+ * closing evidence (verified) and the tick that finds none (not verified),
131
+ * under one key. A crash after one of them wrote it and before its step, and
132
+ * a next tick in a later slot that finds the other answer, would rewrite it
133
+ * with another result: an idempotency_conflict. The model writes the
134
+ * verification once, whichever comes first, and never rewrites it; it is
135
+ * looked up like a recorded read. A later tick that finds the item still
136
+ * acknowledged does what the evidence then says, without a second record:
137
+ * closing evidence resolves it by the "any open, closing evidence" row, and
138
+ * no closing evidence completes the failed-verification step (returned or
139
+ * exhausted), which is sent at most once, as every send is. The item holds
140
+ * the slot as acknowledged until then, and no other item takes it.
141
+ *
142
+ * A recorded verification is the answer the first tick found, not the
143
+ * item's fate: a later tick may find the other answer. In one case the
144
+ * ledger therefore holds a "verified" record followed by a return: the
145
+ * tick that found closing evidence wrote "verified" and was killed before
146
+ * `resolved`, and before the next tick the session authored a new owner
147
+ * block, so that tick finds no closing evidence and returns the item, "not
148
+ * yet confirmed". It is what happens without any crash when a block clears
149
+ * and comes back between two ticks. Not chosen: resolving the item from the
150
+ * recorded verification and letting the new block open a new episode, which
151
+ * would close an item on evidence its own tick no longer sees.
152
+ */
153
+ function* verification(ctx, item, verified, now) {
154
+ const vk = ownerAckKey(item.itemId, item.episode, item.ack.ackRef, 'verify')
155
+ if (ctx.policy.reuseRecorded(ctx.state.index, vk, 'owner_ack')) return
156
+ yield put({ kind: 'owner_ack', id: vk, session: envOf(item), body: { item_id: item.itemId, episode: item.episode, ack_ref: item.ack.ackRef, phase: 'verify', intent: 'done', basis: 'owner_direct', verified } }, now)
157
+ }
158
+
159
+ function* resolve(ctx, item, { now, evidence, closingAsk }) {
160
+ yield* clearCarried(ctx, item, now)
161
+ if (item.state === 'acknowledged' && item.ack) yield* verification(ctx, item, true, now)
162
+ yield* step(ctx, item, 'resolved', { now, extra: { resolution_evidence: evidence ?? null, ...(closingAsk ? { closing_ask: closingAsk } : {}) } })
163
+ }
164
+
165
+ function* withdraw(ctx, item, { now, reason, closingAsk }) {
166
+ yield* clearCarried(ctx, item, now)
167
+ yield* step(ctx, item, 'withdrawn', { now, extra: { reason, ...(closingAsk ? { closing_ask: closingAsk } : {}) } })
168
+ }
169
+
170
+ function reportBody(st, id) {
171
+ return id ? (st.reports.get(id)?.body ?? null) : null
172
+ }
173
+
174
+ // ── conditions carried by an owner item ─────────────────────────────
175
+ //
176
+ // A condition is what an attention item would have said: the attention item
177
+ // it would be (session and report), the reference that would open it, the
178
+ // trigger and the time the condition began. An owner item carries a
179
+ // list of them as part of its content; each change is one `updated` step.
180
+
181
+ function openOwnerBlocks(st, sk) {
182
+ return [...st.items.values()].filter((it) => it.open && it.sk === sk && OWNER_BLOCK_ORIGINS.has(it.origin))
183
+ }
184
+
185
+ function carries(items, attentionId) {
186
+ return items.some((it) => it.carried.some((c) => c.attention_item === attentionId))
187
+ }
188
+
189
+ /** The trigger whose onset this is: a recheck's opening reference is the onset of the cycle that led to it. */
190
+ function triggerAt(st, sk, onset, trigger) {
191
+ if (trigger && trigger !== 'recheck') return trigger
192
+ for (const inv of st.investigations.values()) {
193
+ if (inv.sk === sk && inv.onset === onset && inv.trigger !== 'recheck') return inv.trigger
194
+ }
195
+ return trigger ?? null
196
+ }
197
+
198
+ function conditionOf(st, { attentionId, ref, root, reportId, sk, trigger, since, now }) {
199
+ return {
200
+ attention_item: attentionId,
201
+ opened_by: ref,
202
+ // The reference that first opened (or would have opened) the condition,
203
+ // kept through every merge and handover: the condition's identity.
204
+ root: root ?? ref,
205
+ report_id: reportId ?? null,
206
+ trigger: triggerAt(st, sk, ref, trigger),
207
+ since: since ?? st.checks.get(ref)?.body.checked_at ?? now,
208
+ }
209
+ }
210
+
211
+ /** The evidence that closes an attention item: a newer authored report than its own. */
212
+ function conditionResolved(st, sk, cond) {
213
+ const s = st.sessions.get(sk)
214
+ const latest = reportBody(st, s?.latestAuthored)
215
+ if (!latest) return false
216
+ const opening = reportBody(st, cond.report_id)
217
+ return !opening || latest.last_report_at > opening.last_report_at
218
+ }
219
+
220
+ /**
221
+ * One change to the conditions an owner item carries: `carry` adds
222
+ * one, `clear` drops one. It is the `updated` row of the transition table:
223
+ * it sends nothing, and from exhausted it queues the item again only if a
224
+ * counted show is left.
225
+ */
226
+ function* carryStep(ctx, item, { now, op, cond, path, from = null }) {
227
+ const cfg = ctx.state.config
228
+ const requeue = item.state === 'exhausted' && ctx.policy.requeueFromExhausted(item, cfg)
229
+ const carried = op === 'carry' ? [...item.carried, cond] : item.carried.filter((c) => c.attention_item !== cond.attention_item)
230
+ // A condition is carried at most once per episode and cleared at most once
231
+ // after that, so the change reference never repeats.
232
+ const changeRef = H('carried', op, cond.attention_item, cond.opened_by)
233
+ yield* step(ctx, item, 'updated', {
234
+ now,
235
+ ordCtx: { changeRef },
236
+ extra: { requeue, carry: { op, path, from, ...cond }, carried },
237
+ })
238
+ }
239
+
240
+ /**
241
+ * DESIGN-GAP: what becomes of a carried condition whose own closing evidence
242
+ * arrives while the owner item is still open. The model drops it from
243
+ * the content with another `updated` step, so the item names only what still
244
+ * holds; the dropped condition stays in the item's history.
245
+ */
246
+ function* clearCarried(ctx, item, now, { reason = 'resolved', all = false } = {}) {
247
+ if (!OWNER_BLOCK_ORIGINS.has(item.origin) || !item.carried?.length) return
248
+ for (const c of item.carried.slice()) {
249
+ if (all || conditionResolved(ctx.state, item.sk, c)) yield* carryStep(ctx, item, { now, op: 'clear', cond: c, path: reason })
250
+ }
251
+ }
252
+
253
+ /**
254
+ * An attention signal for a session. With no open owner item it raises
255
+ * the attention item, as it always did. With one, the condition is merged
256
+ * into that item instead, if the attention item would have been raised: it
257
+ * is not open, its opening reference is unused and was never carried, and
258
+ * its closing evidence has not arrived.
259
+ */
260
+ function* attentionSignal(ctx, sig, now) {
261
+ const st = ctx.state
262
+ const P = ctx.policy
263
+ const attentionId = itemIds.attention(sig.session, sig.reportId)
264
+ const consumed = st.carriedRefs.get(attentionId)?.has(sig.onset) ?? false
265
+ const obs = P.attentionBesideOwnerBlock === 'raise' ? [] : openOwnerBlocks(st, sig.sk)
266
+ const rep = reportBody(st, sig.reportId)
267
+ const condition = { trigger: triggerAt(st, sig.sk, sig.onset, sig.trigger), since: st.checks.get(sig.onset)?.body.checked_at ?? now, root: sig.onset }
268
+ if (obs.length === 0) {
269
+ if (consumed) return
270
+ yield* raise(ctx, {
271
+ itemId: attentionId,
272
+ kind: 'session_attention',
273
+ origin: 'attention',
274
+ session: sig.session,
275
+ source: sig.session.source,
276
+ ref: sig.onset,
277
+ reportId: sig.reportId,
278
+ orderTime: rep ? rep.last_report_at : now,
279
+ condition,
280
+ now,
281
+ })
282
+ return
283
+ }
284
+ if (P.attentionBesideOwnerBlock === 'drop') return
285
+ const existing = st.items.get(attentionId)
286
+ // An open attention item is merged by the reverse-order rule below.
287
+ if (existing?.open || consumed || !P.mayOpenEpisode(existing, sig.onset, 'attention')) return
288
+ if (carries(obs, attentionId)) return
289
+ const cond = conditionOf(st, { attentionId, ref: sig.onset, reportId: sig.reportId, sk: sig.sk, ...condition, now })
290
+ if (conditionResolved(st, sig.sk, cond)) return
291
+ yield* carryStep(ctx, obs[0], { now, op: 'carry', cond, path: 'signal' })
292
+ }
293
+
294
+ /**
295
+ * A condition that an owner item still carried when it closed: raised as its
296
+ * own attention item, as for a session with no open item, or carried on into
297
+ * the item's next episode if an ask opened one in the same tick. Runs in the
298
+ * tick that closed the item (a crash re-runs it there).
299
+ *
300
+ * DESIGN-GAP: an attention item withdrawn as merged has used its opening
301
+ * reference, and a new episode never opens on a used reference. Its
302
+ * condition is raised again under a reference derived from that one and the
303
+ * owner episode that carried it, which no other episode can use.
304
+ */
305
+ function* handOver(ctx, ho, cond, now) {
306
+ const st = ctx.state
307
+ const P = ctx.policy
308
+ const attentionId = cond.attention_item
309
+ const existing = st.items.get(attentionId)
310
+ if (existing?.open || conditionResolved(st, ho.sk, cond)) return
311
+ const obs = openOwnerBlocks(st, ho.sk)
312
+ if (obs.length > 0) {
313
+ if (carries(obs, attentionId)) return
314
+ const target = obs[0]
315
+ if (target.carriedEver.has(`${attentionId}|${cond.opened_by}`)) return
316
+ yield* carryStep(ctx, target, { now, op: 'carry', cond, path: 'handover', from: ho.key })
317
+ return
318
+ }
319
+ const ref = existing?.usedRefs.has(cond.opened_by) ? H(cond.opened_by, 'unmerged', ho.itemId, ho.episode) : cond.opened_by
320
+ const root = cond.root ?? cond.opened_by
321
+ const rep = reportBody(st, cond.report_id)
322
+ // DESIGN-GAP (counters): the episode continues the counters of the
323
+ // condition's previous attention episode. Reminders and the time limit
324
+ // count from this episode's own latest show or return, as for any episode:
325
+ // the previous show was made before the merge and is no anchor for a show
326
+ // not yet made. An owner deferral pending when the condition was merged
327
+ // does not survive it; deferrals keep their meaning within an episode.
328
+ const counters = (P.inheritCountersOnHandover && existing?.rootCounters.get(root)) || ZERO
329
+ yield* raise(ctx, {
330
+ itemId: attentionId,
331
+ kind: 'session_attention',
332
+ origin: 'attention',
333
+ session: ho.session,
334
+ source: ho.source,
335
+ ref,
336
+ reportId: cond.report_id,
337
+ orderTime: rep ? rep.last_report_at : now,
338
+ condition: { trigger: cond.trigger, since: cond.since, root },
339
+ handoverOf: ho.key,
340
+ counters,
341
+ now,
342
+ })
343
+ }
344
+
345
+ /** Per session of the source with an open owner item: drop what has ended; merge what is open beside it. */
346
+ function* reconcileOwnerBlocks(ctx, source, now) {
347
+ const st = ctx.state
348
+ const P = ctx.policy
349
+ for (const s of sessionsOf(st, source)) {
350
+ const obs = openOwnerBlocks(st, s.sk)
351
+ if (obs.length === 0) continue
352
+ for (const ob of obs) yield* clearCarried(ctx, ob, now)
353
+ if (P.attentionBesideOwnerBlock === 'raise' || !P.mergeOpenAttention) continue
354
+ // DESIGN-GAP (reverse order): an attention item already open when its
355
+ // session gets an owner item is withdrawn, reason `merged`, after
356
+ // its condition is carried on the owner item (carried first, so a
357
+ // crash between the two loses nothing).
358
+ for (const a of [...st.items.values()]) {
359
+ if (!a.open || a.origin !== 'attention' || a.sk !== s.sk) continue
360
+ const current = openOwnerBlocks(st, s.sk)
361
+ if (!carries(current, a.itemId)) {
362
+ const cond = conditionOf(st, { attentionId: a.itemId, ref: a.openedBy, root: a.root, reportId: a.reportId, sk: s.sk, trigger: a.condition?.trigger, since: a.condition?.since, now })
363
+ yield* carryStep(ctx, current[0], { now, op: 'carry', cond, path: 'open_attention' })
364
+ }
365
+ yield* withdraw(ctx, a, { now, reason: 'merged' })
366
+ }
367
+ }
368
+ }
369
+
370
+ // ── origins ────────────────────────────────────────────────────────────────
371
+
372
+ // ── the owner item and its asks ────────────────────────────────────────────
373
+ //
374
+ // One owner item per session. Its content lists each ask that is live: the
375
+ // declared block (an authored owner-block report) and the pending prompt.
376
+ // Each ask opens on its own reference and ends on its own evidence; the item
377
+ // opens with its first ask and closes with its last.
378
+
379
+ /** An ask as the per-origin rules see it (content change, prompt answer and lapse). */
380
+ function askView(ask) {
381
+ return { askKind: ask.kind, contentAt: ask.content_at ?? null, contentRef: ask.content_ref ?? ask.report_id ?? null, fingerprint: ask.fingerprint ?? null }
382
+ }
383
+
384
+ /** The open owner item carrying a live ask of this kind for the session, if any. */
385
+ function ownerWith(ctx, session, kind) {
386
+ const it = ctx.state.items.get(ctx.policy.ownerItemOf(session, kind))
387
+ return it?.open && it.asks.has(kind) ? it : null
388
+ }
389
+
390
+ function* askChange(ctx, item, { now, op, ask, asks, extra = {} }) {
391
+ // Each ask has its own opening reference, never reused on the item, so
392
+ // these change references never repeat when an ask leaves and another of
393
+ // its kind joins later.
394
+ const changeRef = H('ask', op, ask.kind, ask.opened_by, op === 'content' ? (ask.content_ref ?? ask.report_id) : null)
395
+ yield* step(ctx, item, 'updated', { now, ordCtx: { changeRef }, extra: { content_ref: changeRef, ask: { op, ...ask }, asks, ...extra } })
396
+ }
397
+
398
+ /**
399
+ * An ask arriving: it opens the item's episode, or joins the open item.
400
+ *
401
+ * DESIGN-GAP: what a new ask does in each state of the item. With a counted
402
+ * show left: an item holding the slot (active, or acknowledged and waiting
403
+ * for its verification) is shown again at once, and an acknowledgment
404
+ * pending then applies to the earlier content and is not verified; a queued
405
+ * item (behind another, preempted, or back from expiry) keeps its place and
406
+ * its next show is a counted one; a deferred or exhausted item is queued
407
+ * again, so the new ask cancels a deferral. With no counted show left, a
408
+ * prompt round is still owed one show (see `roundShow`); a declared ask only
409
+ * changes the content: nothing is sent and an exhausted item stays
410
+ * exhausted.
411
+ */
412
+ function* addAsk(ctx, session, ask, now) {
413
+ const st = ctx.state
414
+ const P = ctx.policy
415
+ const cfg = st.config
416
+ const id = P.ownerItemOf(session, ask.kind)
417
+ const it = st.items.get(id)
418
+ if (!P.mayAddAsk(it, ask.opened_by, ask.kind)) return
419
+ if (!it?.open) {
420
+ yield* raise(ctx, {
421
+ itemId: id,
422
+ kind: 'owner_block',
423
+ origin: 'owner',
424
+ session,
425
+ source: session.source,
426
+ ref: ask.opened_by,
427
+ contentRef: ask.opened_by,
428
+ contentAt: ask.content_at ?? null,
429
+ deadline: ask.deadline ?? null,
430
+ orderTime: ask.order_time,
431
+ reportId: ask.report_id ?? null,
432
+ asks: [ask],
433
+ ask: { op: 'open', ...ask },
434
+ now,
435
+ })
436
+ return
437
+ }
438
+ const show = P.newAskShows(it, cfg)
439
+ // With the counted shows used, a prompt round still earns its own show.
440
+ const round = !show && P.promptRoundShows(it, ask, cfg)
441
+ const holder = P.slotHolderStates.has(it.state)
442
+ yield* askChange(ctx, it, {
443
+ now,
444
+ op: 'join',
445
+ ask,
446
+ asks: [...it.asks.values(), ask],
447
+ extra: {
448
+ show_now: (show || round) && holder,
449
+ counted_next: show,
450
+ requeue: show && (it.state === 'exhausted' || it.state === 'deferred'),
451
+ ...(round ? { round_owed: P.showsPerRound } : {}),
452
+ },
453
+ })
454
+ }
455
+
456
+ /**
457
+ * The show a prompt round earns once the counted shows are used.
458
+ *
459
+ * DESIGN-GAP: a round's show, in each state of the item. Holding the slot
460
+ * (active, or acknowledged and waiting for its verification tick): shown at
461
+ * once, and the item keeps holding the slot as it did before. Queued (behind
462
+ * another item, preempted, back from expiry), deferred or exhausted: shown
463
+ * when the slot is free, in the item's own place in the order; the item
464
+ * then keeps its state, so a queued item with no counted show left is
465
+ * exhausted at the slot as usual, and a deferred one stays deferred. The
466
+ * show moves neither the reminder nor the time-limit clock, so it brings no
467
+ * reminder, return or expiry the item would not otherwise have had; a
468
+ * reminder still unused falls due when it would have anyway.
469
+ */
470
+ function* roundShow(ctx, it, now) {
471
+ const c = ctx.policy.roundShowCounters(it.counters)
472
+ yield* sendStep(ctx, it, 'shown', { c, now, extra: { counted: false, round: true } })
473
+ }
474
+
475
+ /** An ask ending: removed from the content (nothing sent), or, as the last ask, the item's closing step. */
476
+ function* endAsk(ctx, item, kind, { now, how, evidence = null }) {
477
+ const P = ctx.policy
478
+ if (P.closesOnAskEnd(item, kind)) {
479
+ if (how === 'lapsed') yield* withdraw(ctx, item, { now, reason: 'lapsed', closingAsk: kind })
480
+ else yield* resolve(ctx, item, { now, evidence, closingAsk: kind })
481
+ return
482
+ }
483
+ // DESIGN-GAP: an ask ending while another is live is a content change by
484
+ // removal. It does not queue an exhausted item again: there is less for
485
+ // the owner to do, not more.
486
+ const ask = item.asks.get(kind)
487
+ yield* askChange(ctx, item, { now, op: 'end', ask: { ...ask, how, evidence }, asks: [...item.asks.values()].filter((a) => a.kind !== kind), extra: { requeue: false } })
488
+ }
489
+
490
+ /** New content within a live ask (a new owner-block wording; a newer prompt): the `updated` row. */
491
+ function* changeAsk(ctx, item, ask, now) {
492
+ const requeue = item.state === 'exhausted' && ctx.policy.requeueFromExhausted(item, ctx.state.config)
493
+ yield* askChange(ctx, item, { now, op: 'content', ask, asks: [...item.asks.values()].map((a) => (a.kind === ask.kind ? ask : a)), extra: { requeue } })
494
+ }
495
+
496
+ /**
497
+ * The asks of each session of the source, in three passes: asks that end,
498
+ * then new content within live asks, then asks that arrive.
499
+ *
500
+ * DESIGN-GAP: when one tick both ends an item's last ask and brings a new
501
+ * one, the ending is taken first, so the new ask opens a new episode rather
502
+ * than keeping the old one open.
503
+ */
504
+ function* ownerAsks(ctx, source, now) {
505
+ const st = ctx.state
506
+ const P = ctx.policy
507
+ const cfg = st.config
508
+ for (const s of sessionsOf(st, source)) {
509
+ const latest = reportBody(st, s.latestAuthored)
510
+ const ob = latest ? P.isOwnerBlock(latest, cfg) : false
511
+ // DESIGN-GAP: whether a prompt is pending can only be read from a check
512
+ // that carried native state; an errored read says nothing either way.
513
+ // The model evaluates prompt asks only on such a check, so a source with
514
+ // no native state never has one.
515
+ const live = Boolean(s.cur && s.cur.nativeAvailable)
516
+ const pending = live ? [...s.cur.pending].map((ref) => s.prompts.get(ref)).filter((p) => p && p.status === 'pending') : []
517
+ pending.sort((a, b) => (a.raised_at ?? 0) - (b.raised_at ?? 0) || (a.ref < b.ref ? -1 : 1))
518
+ const lp = pending[pending.length - 1]
519
+
520
+ // Asks that end, each on its own evidence.
521
+ const d = ownerWith(ctx, s.session, 'declared')
522
+ if (d && P.declaredResolvedBy(latest, reportBody(st, d.asks.get('declared').opened_by), cfg)) {
523
+ yield* endAsk(ctx, d, 'declared', { now, how: 'resolved', evidence: s.latestAuthored })
524
+ }
525
+ const p = ownerWith(ctx, s.session, 'prompt')
526
+ if (p) {
527
+ const view = askView(p.asks.get('prompt'))
528
+ const cur = s.prompts.get(view.contentRef)
529
+ const answered = P.promptAnswered(view, cur, s.prompts, { livePending: live ? pending.length : null })
530
+ if (answered) yield* endAsk(ctx, p, 'prompt', { now, how: 'answered', evidence: answered })
531
+ else if (live && P.promptLapsed(view, cur, latest, { livePending: pending.length })) yield* endAsk(ctx, p, 'prompt', { now, how: 'lapsed' })
532
+ }
533
+
534
+ // New content within a live ask.
535
+ const d2 = ownerWith(ctx, s.session, 'declared')
536
+ if (d2 && ob) {
537
+ const ask = d2.asks.get('declared')
538
+ const fp = P.blockFingerprint(latest)
539
+ if (P.contentChanged(askView(ask), { fingerprint: fp, ref: s.latestAuthored, at: latest.last_report_at })) {
540
+ yield* changeAsk(ctx, d2, { ...ask, report_id: s.latestAuthored, fingerprint: fp, content_at: latest.last_report_at }, now)
541
+ }
542
+ }
543
+ const p2 = ownerWith(ctx, s.session, 'prompt')
544
+ if (p2 && live && lp) {
545
+ const ask = p2.asks.get('prompt')
546
+ if (P.contentChanged(askView(ask), { ref: lp.ref, at: lp.raised_at })) {
547
+ yield* changeAsk(ctx, p2, { ...ask, content_ref: lp.ref, content_at: lp.raised_at ?? null, deadline: lp.deadline ?? null }, now)
548
+ }
549
+ }
550
+
551
+ // Asks that arrive.
552
+ if (ob && !ownerWith(ctx, s.session, 'declared')) {
553
+ yield* addAsk(ctx, s.session, { kind: 'declared', opened_by: s.latestAuthored, report_id: s.latestAuthored, fingerprint: P.blockFingerprint(latest), content_at: latest.last_report_at, order_time: latest.last_report_at }, now)
554
+ }
555
+ if (lp && !ownerWith(ctx, s.session, 'prompt')) {
556
+ // The prompt's own id, or, for a prompt an earlier prompt ask of the
557
+ // item opened on, a reference derived from it (policy `promptAskRef`).
558
+ const opened = P.promptAskRef(st.items.get(P.ownerItemOf(s.session, 'prompt')), lp)
559
+ yield* addAsk(ctx, s.session, { kind: 'prompt', opened_by: opened, content_ref: lp.ref, content_at: lp.raised_at ?? null, deadline: lp.deadline ?? null, order_time: lp.raised_at ?? now }, now)
560
+ }
561
+ }
562
+ }
563
+
564
+ /** An owner item that a new ask found holding the slot is shown again at once (a counted show). */
565
+ function* showNewAsks(ctx, now) {
566
+ const st = ctx.state
567
+ const P = ctx.policy
568
+ const cfg = st.config
569
+ for (const it of openItems(st)) {
570
+ if (!it.showDue || !P.slotHolderStates.has(it.state)) continue
571
+ if (P.newAskShows(it, cfg)) {
572
+ const c = { ...it.counters, presentation: it.counters.presentation + 1, shows_counted: it.counters.shows_counted + 1 }
573
+ yield* sendStep(ctx, it, 'shown', { c, now, extra: { counted: true, new_ask: true } })
574
+ } else if (it.roundOwed > 0) {
575
+ yield* roundShow(ctx, it, now)
576
+ }
577
+ }
578
+ if (P.roundWaitsForSlot) return
579
+ // Only a broken rule reaches this: a round shown without waiting for the slot.
580
+ for (const it of openItems(st)) {
581
+ if (it.roundOwed > 0 && !P.slotHolderStates.has(it.state)) yield* roundShow(ctx, it, now)
582
+ }
583
+ }
584
+
585
+ function* attention(ctx, source, now, signals) {
586
+ const st = ctx.state
587
+ // Resolution first, so a session listed again closes its `gone` item before
588
+ // this tick's signals are applied.
589
+ for (const it of [...st.items.values()]) {
590
+ if (!it.open || it.source !== source || (it.origin !== 'attention' && it.origin !== 'gone')) continue
591
+ const s = st.sessions.get(it.sk)
592
+ if (!s) continue
593
+ if (it.origin === 'gone') {
594
+ if (s.listed && s.cur && s.cur.listed) yield* resolve(ctx, it, { now, evidence: s.cur.checkId })
595
+ continue
596
+ }
597
+ const latest = reportBody(st, s.latestAuthored)
598
+ const opening = reportBody(st, it.reportId)
599
+ if (latest && (!opening || latest.last_report_at > opening.last_report_at)) {
600
+ yield* resolve(ctx, it, { now, evidence: s.latestAuthored })
601
+ }
602
+ }
603
+ if (ctx.policy.handOverOnClose) {
604
+ for (const ho of [...st.handovers.values()]) {
605
+ if (ho.source !== source) continue
606
+ for (const c of ho.carried) yield* handOver(ctx, ho, c, now)
607
+ }
608
+ }
609
+ for (const sig of signals) {
610
+ if (sig.type === 'attention') {
611
+ yield* attentionSignal(ctx, sig, now)
612
+ } else if (sig.type === 'gone') {
613
+ const raised = yield* raise(ctx, {
614
+ itemId: itemIds.gone(sig.session),
615
+ kind: 'session_attention',
616
+ origin: 'gone',
617
+ session: sig.session,
618
+ source: sig.session.source,
619
+ ref: sig.onset,
620
+ reportId: sig.reportId,
621
+ orderTime: now,
622
+ now,
623
+ })
624
+ if (raised || st.items.get(itemIds.gone(sig.session))?.open) {
625
+ for (const it of [...st.items.values()]) {
626
+ if (it.open && it.origin === 'attention' && it.sk === sessionKey(sig.session)) {
627
+ yield* withdraw(ctx, it, { now, reason: 'superseded' })
628
+ }
629
+ }
630
+ // A condition carried for the session is superseded the same way.
631
+ for (const ob of openOwnerBlocks(st, sessionKey(sig.session))) yield* clearCarried(ctx, ob, now, { reason: 'superseded', all: true })
632
+ }
633
+ }
634
+ }
635
+ yield* reconcileOwnerBlocks(ctx, source, now)
636
+ }
637
+
638
+ function* outages(ctx, source, now, signals, tickId) {
639
+ const st = ctx.state
640
+ const id = itemIds.outage(source)
641
+ const it = st.items.get(id)
642
+ if (it?.open) {
643
+ const ok = sessionsOf(st, source).find((s) => s.cur && s.cur.tickId === tickId && (s.cur.outcome === 'ok' || s.cur.outcome === 'no_report'))
644
+ if (ok) {
645
+ yield* resolve(ctx, it, { now, evidence: ok.cur.checkId })
646
+ return
647
+ }
648
+ }
649
+ for (const sig of signals) {
650
+ if (sig.type !== 'outage') continue
651
+ yield* raise(ctx, { itemId: id, kind: 'source_unreachable', origin: 'outage', session: null, source, ref: sig.onset, orderTime: now, now })
652
+ }
653
+ }
654
+
655
+ function* seeds(ctx, now) {
656
+ const st = ctx.state
657
+ const all = sessionsOf(st, null)
658
+ for (const s of all) {
659
+ const latest = reportBody(st, s.latestAuthored)
660
+ const seed = latest?.seed_ref
661
+ const ids = new Set()
662
+ if (seed) ids.add(itemIds.seed(seed.scope, seed.session))
663
+ // An open seed item stays subject to its evidence even after the session
664
+ // that named it moved on to another line.
665
+ for (const it of st.items.values()) if (it.open && it.origin === 'seed' && it.sk === s.sk) ids.add(it.itemId)
666
+ for (const id of ids) {
667
+ const it = st.items.get(id)
668
+ const ref = it?.open ? it.seed : seed
669
+ if (!ref) continue
670
+ const evidence = all.find((t) => t.sk !== s.sk && t.scope != null && t.scope === ref.scope && t.firstReportAt != null && t.firstReportAt > ref.written_at)
671
+ if (it?.open) {
672
+ if (evidence) yield* resolve(ctx, it, { now, evidence: evidence.sk })
673
+ continue
674
+ }
675
+ if (evidence || id !== itemIds.seed(seed.scope, seed.session)) continue
676
+ yield* raise(ctx, {
677
+ itemId: id,
678
+ kind: 'session_request',
679
+ origin: 'seed',
680
+ session: s.session,
681
+ source: s.session.source,
682
+ ref: ref.written_at,
683
+ reportId: s.latestAuthored,
684
+ orderTime: ref.written_at,
685
+ // DESIGN-GAP: the rule for a source that gives no working directory
686
+ // does not say which source: the one that named the seed, or the one the
687
+ // seed will be pasted into. The model uses the naming session's.
688
+ closable: sourceCaps(st.config, s.session.source).scope,
689
+ seed: ref,
690
+ now,
691
+ })
692
+ }
693
+ }
694
+ }
695
+
696
+ // ── the slot ───────────────────────────────────────────────────────────────
697
+
698
+ function openItems(st) {
699
+ return [...st.items.values()].filter((it) => it.open)
700
+ }
701
+
702
+ function* verifyAcknowledged(ctx, { source, now, tickOpenSeq }) {
703
+ const st = ctx.state
704
+ const P = ctx.policy
705
+ for (const it of openItems(st)) {
706
+ if (it.state !== 'acknowledged' || !it.ack) continue
707
+ if (it.ack.seq >= tickOpenSeq) continue
708
+ // DESIGN-GAP: "next tick" is ambiguous when each source has its own
709
+ // ticks. The model verifies at the next tick of the item's own source,
710
+ // and at the next tick of any source for an item with none.
711
+ if (it.source != null && it.source !== source) continue
712
+ yield* verification(ctx, it, false, now)
713
+ const next = P.verifyFailedStep(it)
714
+ if (next === 'returned') {
715
+ const c = { ...it.counters, returns_used: it.counters.returns_used + 1 }
716
+ yield* sendStep(ctx, it, 'returned', { c, now, extra: { note: 'acknowledged, not yet confirmed' } })
717
+ } else {
718
+ yield* step(ctx, it, 'exhausted', { now })
719
+ }
720
+ }
721
+ }
722
+
723
+ function* activeTiming(ctx, now) {
724
+ const st = ctx.state
725
+ const P = ctx.policy
726
+ const cfg = st.config
727
+ const active = openItems(st).filter((it) => effectiveState(it, now) === 'active')
728
+ if (active.length === 0) return
729
+ const it = active[0]
730
+ if (P.expiryDue(it, now, cfg)) {
731
+ yield* step(ctx, it, 'expired', { now })
732
+ return
733
+ }
734
+ const queued = openItems(st)
735
+ .filter((x) => effectiveState(x, now) === 'queued')
736
+ .sort((a, b) => compareKeys(P.orderKey(a, now), P.orderKey(b, now)))
737
+ const challenger = queued.find((x) => P.preempts(x, it, now, cfg))
738
+ if (challenger) {
739
+ yield* step(ctx, it, 'preempted', { now, extra: { preempted_by: challenger.itemId } })
740
+ return
741
+ }
742
+ const k = P.reminderDue(it, now, cfg)
743
+ if (k != null) {
744
+ const c = { ...it.counters, reminders_used: P.remindersAfter(it, k) }
745
+ yield* sendStep(ctx, it, 'reminded', { c, ordCtx: { k }, now })
746
+ }
747
+ }
748
+
749
+ function* fillSlot(ctx, now) {
750
+ const st = ctx.state
751
+ const P = ctx.policy
752
+ const cfg = st.config
753
+ if (openItems(st).some((it) => P.slotHolderStates.has(effectiveState(it, now)))) return
754
+ const byOrder = (a, b) => compareKeys(P.orderKey(a, now), P.orderKey(b, now))
755
+ // Rounds owed to items that are not queued (deferred or exhausted) are
756
+ // shown first, in their order. They take no slot, so they are kept out of
757
+ // the pass below: an item at the head of it that is not queued would hide a
758
+ // still-queued preemptor from the preemptor-first rule.
759
+ const rounds = openItems(st).filter((it) => it.roundOwed > 0 && effectiveState(it, now) !== 'queued' && P.roundStillOwed(it, now)).sort(byOrder)
760
+ for (const it of rounds) {
761
+ yield* roundShow(ctx, it, now)
762
+ if (P.slotHolderStates.has(it.state)) return
763
+ }
764
+ const queue = openItems(st)
765
+ .filter((it) => effectiveState(it, now) === 'queued')
766
+ .sort(byOrder)
767
+ P.preemptorFirst(queue)
768
+ for (const it of queue) {
769
+ if (P.canShow(it, cfg)) {
770
+ const counted = P.showIsCounted(it)
771
+ const c = { ...it.counters, presentation: it.counters.presentation + 1, shows_counted: it.counters.shows_counted + (counted ? 1 : 0) }
772
+ yield* sendStep(ctx, it, 'shown', { c, now, extra: { counted } })
773
+ return
774
+ }
775
+ // A queued item with no counted show left: its round's show, if one is
776
+ // owed, then exhausted at the slot as usual.
777
+ if (it.roundOwed > 0 && P.roundStillOwed(it, now)) {
778
+ yield* roundShow(ctx, it, now)
779
+ if (P.slotHolderStates.has(it.state)) return
780
+ }
781
+ yield* step(ctx, it, 'exhausted', { now })
782
+ }
783
+ }
784
+
785
+ /** Plan the owner-queue part of one tick. */
786
+ export function* planQueue(ctx, { source, tickId, now, signals, tickOpenSeq }) {
787
+ yield* ownerAsks(ctx, source, now)
788
+ yield* attention(ctx, source, now, signals)
789
+ yield* outages(ctx, source, now, signals, tickId)
790
+ yield* seeds(ctx, now)
791
+ yield* showNewAsks(ctx, now)
792
+ yield* verifyAcknowledged(ctx, { source, now, tickOpenSeq })
793
+ yield* activeTiming(ctx, now)
794
+ yield* fillSlot(ctx, now)
795
+ }
796
+
797
+ /**
798
+ * Plan an owner action on one item: "done", a deferral to a time, or a
799
+ * dismissal. `ackRef` is the channel's own message id.
800
+ */
801
+ export function* planOwnerEvent(ctx, { itemId, intent, ackRef, until, now, basis = 'owner_direct' }) {
802
+ const st = ctx.state
803
+ yield* sweepUnknownDeliveries(ctx, now)
804
+ const it = st.items.get(itemId)
805
+ if (!it || !it.open) return { applied: false }
806
+ const ackKey = ownerAckKey(it.itemId, it.episode, ackRef, 'ack')
807
+ const resumed = st.index.has(ackKey)
808
+ const es = effectiveState(it, now)
809
+ const ack = () => put({ kind: 'owner_ack', id: ackKey, session: envOf(it), body: { item_id: it.itemId, episode: it.episode, ack_ref: ackRef, phase: 'ack', intent, basis, verified: null } }, now)
810
+ // DESIGN-GAP: the transition table gives owner actions only on an active item
811
+ // (and dismissal in any open state). "Done" or a deferral on a queued,
812
+ // deferred, acknowledged or exhausted item has no row; the model records
813
+ // nothing for it.
814
+ if (intent === 'done') {
815
+ if (es !== 'active' && !resumed) return { applied: false }
816
+ yield ack()
817
+ if (!it.closable) {
818
+ // The item origins: a seed whose scope cannot be read is closed by
819
+ // "done", labelled owner-stated and unverified. DESIGN-GAP: the table sends
820
+ // "done" to `acknowledged` for every item; the two rules conflict here.
821
+ yield* withdraw(ctx, it, { now, reason: 'owner_stated_unverified' })
822
+ }
823
+ return { applied: true }
824
+ }
825
+ if (intent === 'defer') {
826
+ if ((es !== 'active' && !resumed) || until == null) return { applied: false }
827
+ yield ack()
828
+ if (it.state !== 'deferred' || it.deferUntil !== until) {
829
+ // DESIGN-GAP: neither the `deferred` record nor the `owner_ack` body
830
+ // has a field for the time the item is deferred to, so the re-queue
831
+ // time is not derivable from the ledger. Added field `until`.
832
+ yield* step(ctx, it, 'deferred', { now, ordCtx: { ackRef }, extra: { until } })
833
+ }
834
+ return { applied: true }
835
+ }
836
+ if (intent === 'dismiss') {
837
+ if (!DISMISSABLE.has(it.origin)) return { applied: false }
838
+ yield ack()
839
+ yield* withdraw(ctx, it, { now, reason: 'dismissed' })
840
+ return { applied: true }
841
+ }
842
+ return { applied: false }
843
+ }