@openrig/cli 0.7.25 → 0.7.26

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 (479) hide show
  1. package/README.md +7 -7
  2. package/daemon/assets/claude-hook-bridge.d.cts +9 -2
  3. package/daemon/assets/claude-permission-policies.cjs +18 -1
  4. package/daemon/assets/claude-permission-policies.d.cts +1 -0
  5. package/daemon/assets/claude-team-permissions.cjs +22 -1
  6. package/daemon/assets/guidance/openrig-context-entry.md +4 -5
  7. package/daemon/assets/guidance/openrig-start.md +3 -0
  8. package/daemon/assets/plugins/openrig/.claude-plugin/plugin.json +1 -1
  9. package/daemon/assets/plugins/openrig/.codex-plugin/plugin.json +1 -1
  10. package/daemon/assets/plugins/openrig/.cursor-plugin/plugin.json +1 -1
  11. package/daemon/assets/plugins/openrig/README.md +5 -3
  12. package/daemon/assets/plugins/openrig/plugin.json +1 -1
  13. package/daemon/assets/plugins/openrig/skills/working-with-an-openrig-team/SKILL.md +15 -5
  14. package/daemon/assets/plugins/openrig-codex/.codex-plugin/plugin.json +1 -1
  15. package/daemon/assets/plugins/openrig-codex/skills/working-with-an-openrig-team/SKILL.md +15 -5
  16. package/daemon/assets/plugins/openrig-core/.claude-plugin/plugin.json +1 -1
  17. package/daemon/assets/plugins/openrig-core/.codex-plugin/plugin.json +1 -1
  18. package/daemon/assets/plugins/openrig-core/skills/openrig-user/SKILL.md +23 -6
  19. package/daemon/assets/plugins/openrig-core/skills/session-compaction-and-restore/SKILL.md +5 -2
  20. package/daemon/assets/skills/rigs/SKILL.md +90 -33
  21. package/daemon/assets/skills/rigs/references/installing-for-someone.md +1 -1
  22. package/daemon/context-packs/help/manifest.yaml +1 -1
  23. package/daemon/context-packs/onboarding-width/manifest.yaml +1 -1
  24. package/daemon/context-packs/onboarding-width/public-what-you-can-do.md +82 -20
  25. package/daemon/context-packs/reference/getting-started.md +63 -11
  26. package/daemon/context-packs/reference/manifest.yaml +1 -1
  27. package/daemon/context-packs/reference/rig-spec.md +40 -14
  28. package/daemon/context-packs/reference/whats-new.md +102 -12
  29. package/daemon/context-packs/skills/agent-operated-software/manifest.yaml +1 -1
  30. package/daemon/context-packs/skills/agent-operated-workflows/manifest.yaml +1 -1
  31. package/daemon/context-packs/skills/applying-a-permission-policy/manifest.yaml +1 -1
  32. package/daemon/context-packs/skills/claude-compaction-restore/manifest.yaml +1 -1
  33. package/daemon/context-packs/skills/core/agent-starters/manifest.yaml +1 -1
  34. package/daemon/context-packs/skills/core/agent-startup-and-context-ingestion/manifest.yaml +1 -1
  35. package/daemon/context-packs/skills/core/cross-host-rig-commands/SKILL.md +9 -1
  36. package/daemon/context-packs/skills/core/cross-host-rig-commands/manifest.yaml +1 -1
  37. package/daemon/context-packs/skills/core/human-in-the-loop/manifest.yaml +1 -1
  38. package/daemon/context-packs/skills/core/messaging-the-human/manifest.yaml +1 -1
  39. package/daemon/context-packs/skills/core/openrig-architect/manifest.yaml +1 -1
  40. package/daemon/context-packs/skills/core/openrig-cmux/manifest.yaml +1 -1
  41. package/daemon/context-packs/skills/core/openrig-herdr/manifest.yaml +1 -1
  42. package/daemon/context-packs/skills/core/openrig-skills/manifest.yaml +1 -1
  43. package/daemon/context-packs/skills/core/openrig-software-factory/manifest.yaml +1 -1
  44. package/daemon/context-packs/skills/core/openrig-upgrade/manifest.yaml +1 -1
  45. package/daemon/context-packs/skills/core/rig-bundles-and-shareable-artifacts/manifest.yaml +1 -1
  46. package/daemon/context-packs/skills/core/rig-lifecycle/manifest.yaml +1 -1
  47. package/daemon/context-packs/skills/core/session-source-fork/manifest.yaml +1 -1
  48. package/daemon/context-packs/skills/core/specification-system/manifest.yaml +1 -1
  49. package/daemon/context-packs/skills/core/topology-mutation-and-seat-management/manifest.yaml +1 -1
  50. package/daemon/context-packs/skills/core/watchdog/manifest.yaml +1 -1
  51. package/daemon/context-packs/skills/core/working-with-an-openrig-team/SKILL.md +15 -5
  52. package/daemon/context-packs/skills/core/working-with-an-openrig-team/manifest.yaml +1 -1
  53. package/daemon/context-packs/skills/delegating-work/manifest.yaml +1 -1
  54. package/daemon/context-packs/skills/forming-an-openrig-mental-model/manifest.yaml +1 -1
  55. package/daemon/context-packs/skills/loading-addressable-markdown/manifest.yaml +1 -1
  56. package/daemon/context-packs/skills/mission-slice-sop/manifest.yaml +1 -1
  57. package/daemon/context-packs/skills/openrig-operating-model/manifest.yaml +1 -1
  58. package/daemon/context-packs/skills/openrig-user/SKILL.md +23 -6
  59. package/daemon/context-packs/skills/openrig-user/manifest.yaml +1 -1
  60. package/daemon/context-packs/skills/orienting-to-an-inherited-seat/manifest.yaml +1 -1
  61. package/daemon/context-packs/skills/pm/backlog-capture/manifest.yaml +1 -1
  62. package/daemon/context-packs/skills/pm/context-builder/manifest.yaml +1 -1
  63. package/daemon/context-packs/skills/pm/exec-summary/manifest.yaml +1 -1
  64. package/daemon/context-packs/skills/pm/office-hours/manifest.yaml +1 -1
  65. package/daemon/context-packs/skills/pm/plan-review/manifest.yaml +1 -1
  66. package/daemon/context-packs/skills/pm/requirements-writer/manifest.yaml +1 -1
  67. package/daemon/context-packs/skills/pm/ui-mockup/manifest.yaml +1 -1
  68. package/daemon/context-packs/skills/pods/development-team/manifest.yaml +1 -1
  69. package/daemon/context-packs/skills/pods/orchestration-team/manifest.yaml +1 -1
  70. package/daemon/context-packs/skills/pods/oversight-team/manifest.yaml +1 -1
  71. package/daemon/context-packs/skills/pods/review-team/manifest.yaml +1 -1
  72. package/daemon/context-packs/skills/process/agent-browser/manifest.yaml +1 -1
  73. package/daemon/context-packs/skills/process/context-engineering/manifest.yaml +1 -1
  74. package/daemon/context-packs/skills/process/dogfood/manifest.yaml +1 -1
  75. package/daemon/context-packs/skills/process/frontend-design/manifest.yaml +1 -1
  76. package/daemon/context-packs/skills/process/systematic-debugging/manifest.yaml +1 -1
  77. package/daemon/context-packs/skills/process/test-driven-development/manifest.yaml +1 -1
  78. package/daemon/context-packs/skills/process/verification-before-completion/manifest.yaml +1 -1
  79. package/daemon/context-packs/skills/queue-handoff/manifest.yaml +1 -1
  80. package/daemon/context-packs/skills/refocusing/manifest.yaml +1 -1
  81. package/daemon/context-packs/skills/retiring-and-inheriting-a-seat/manifest.yaml +1 -1
  82. package/daemon/context-packs/skills/seat-continuity-and-handover/manifest.yaml +1 -1
  83. package/daemon/context-packs/skills/session-compaction-and-restore/SKILL.md +5 -2
  84. package/daemon/context-packs/skills/session-compaction-and-restore/manifest.yaml +1 -1
  85. package/daemon/context-packs/skills/software-for-agents/manifest.yaml +1 -1
  86. package/daemon/context-packs/world-example/manifest.yaml +1 -1
  87. package/daemon/context-packs/world-public/manifest.yaml +1 -1
  88. package/daemon/dist/adapters/claude-code-adapter.d.ts.map +1 -1
  89. package/daemon/dist/adapters/claude-code-adapter.js +10 -4
  90. package/daemon/dist/adapters/claude-code-adapter.js.map +1 -1
  91. package/daemon/dist/adapters/claude-resume.d.ts +2 -0
  92. package/daemon/dist/adapters/claude-resume.d.ts.map +1 -1
  93. package/daemon/dist/adapters/claude-resume.js +24 -6
  94. package/daemon/dist/adapters/claude-resume.js.map +1 -1
  95. package/daemon/dist/adapters/kernel-authority.d.ts.map +1 -1
  96. package/daemon/dist/adapters/kernel-authority.js +3 -1
  97. package/daemon/dist/adapters/kernel-authority.js.map +1 -1
  98. package/daemon/dist/adapters/pi-runner.d.ts.map +1 -1
  99. package/daemon/dist/adapters/pi-runner.js +9 -0
  100. package/daemon/dist/adapters/pi-runner.js.map +1 -1
  101. package/daemon/dist/adapters/pi-session-cwd.d.ts +26 -0
  102. package/daemon/dist/adapters/pi-session-cwd.d.ts.map +1 -0
  103. package/daemon/dist/adapters/pi-session-cwd.js +89 -0
  104. package/daemon/dist/adapters/pi-session-cwd.js.map +1 -0
  105. package/daemon/dist/adapters/shell-quote.d.ts +2 -0
  106. package/daemon/dist/adapters/shell-quote.d.ts.map +1 -1
  107. package/daemon/dist/adapters/shell-quote.js +43 -0
  108. package/daemon/dist/adapters/shell-quote.js.map +1 -1
  109. package/daemon/dist/adapters/tmux-credential-env.d.ts +15 -2
  110. package/daemon/dist/adapters/tmux-credential-env.d.ts.map +1 -1
  111. package/daemon/dist/adapters/tmux-credential-env.js +82 -2
  112. package/daemon/dist/adapters/tmux-credential-env.js.map +1 -1
  113. package/daemon/dist/adapters/tmux-exec.d.ts.map +1 -1
  114. package/daemon/dist/adapters/tmux-exec.js +2 -6
  115. package/daemon/dist/adapters/tmux-exec.js.map +1 -1
  116. package/daemon/dist/adapters/tmux.d.ts.map +1 -1
  117. package/daemon/dist/adapters/tmux.js +5 -3
  118. package/daemon/dist/adapters/tmux.js.map +1 -1
  119. package/daemon/dist/bind-plan-surface.d.ts +3 -0
  120. package/daemon/dist/bind-plan-surface.d.ts.map +1 -0
  121. package/daemon/dist/bind-plan-surface.js +5 -0
  122. package/daemon/dist/bind-plan-surface.js.map +1 -0
  123. package/daemon/dist/build-info.js +3 -3
  124. package/daemon/dist/db/migrations/202_network_requester_questions.d.ts +4 -0
  125. package/daemon/dist/db/migrations/202_network_requester_questions.d.ts.map +1 -0
  126. package/daemon/dist/db/migrations/202_network_requester_questions.js +10 -0
  127. package/daemon/dist/db/migrations/202_network_requester_questions.js.map +1 -0
  128. package/daemon/dist/db/migrations/203_outbox_runner_receipts_index.d.ts +3 -0
  129. package/daemon/dist/db/migrations/203_outbox_runner_receipts_index.d.ts.map +1 -0
  130. package/daemon/dist/db/migrations/203_outbox_runner_receipts_index.js +22 -0
  131. package/daemon/dist/db/migrations/203_outbox_runner_receipts_index.js.map +1 -0
  132. package/daemon/dist/domain/agent-activity-store.d.ts +4 -0
  133. package/daemon/dist/domain/agent-activity-store.d.ts.map +1 -1
  134. package/daemon/dist/domain/agent-activity-store.js +16 -0
  135. package/daemon/dist/domain/agent-activity-store.js.map +1 -1
  136. package/daemon/dist/domain/agent-images/agent-image-destination.d.ts +15 -0
  137. package/daemon/dist/domain/agent-images/agent-image-destination.d.ts.map +1 -0
  138. package/daemon/dist/domain/agent-images/agent-image-destination.js +79 -0
  139. package/daemon/dist/domain/agent-images/agent-image-destination.js.map +1 -0
  140. package/daemon/dist/domain/agent-images/agent-image-library-service.d.ts.map +1 -1
  141. package/daemon/dist/domain/agent-images/agent-image-library-service.js +9 -1
  142. package/daemon/dist/domain/agent-images/agent-image-library-service.js.map +1 -1
  143. package/daemon/dist/domain/bootstrap-orchestrator.d.ts +4 -3
  144. package/daemon/dist/domain/bootstrap-orchestrator.d.ts.map +1 -1
  145. package/daemon/dist/domain/bootstrap-orchestrator.js +55 -11
  146. package/daemon/dist/domain/bootstrap-orchestrator.js.map +1 -1
  147. package/daemon/dist/domain/bundle-content-routing.d.ts +7 -0
  148. package/daemon/dist/domain/bundle-content-routing.d.ts.map +1 -1
  149. package/daemon/dist/domain/bundle-content-routing.js +20 -15
  150. package/daemon/dist/domain/bundle-content-routing.js.map +1 -1
  151. package/daemon/dist/domain/claude-compaction-enforcer.js +3 -3
  152. package/daemon/dist/domain/claude-compaction-enforcer.js.map +1 -1
  153. package/daemon/dist/domain/claude-continuation-launch.d.ts +19 -2
  154. package/daemon/dist/domain/claude-continuation-launch.d.ts.map +1 -1
  155. package/daemon/dist/domain/claude-continuation-launch.js +143 -3
  156. package/daemon/dist/domain/claude-continuation-launch.js.map +1 -1
  157. package/daemon/dist/domain/claude-managed-launch.d.ts +22 -5
  158. package/daemon/dist/domain/claude-managed-launch.d.ts.map +1 -1
  159. package/daemon/dist/domain/claude-managed-launch.js +41 -5
  160. package/daemon/dist/domain/claude-managed-launch.js.map +1 -1
  161. package/daemon/dist/domain/claude-permission-rules.d.ts +3 -1
  162. package/daemon/dist/domain/claude-permission-rules.d.ts.map +1 -1
  163. package/daemon/dist/domain/claude-permission-rules.js +8 -7
  164. package/daemon/dist/domain/claude-permission-rules.js.map +1 -1
  165. package/daemon/dist/domain/claude-seat-token.d.ts +23 -1
  166. package/daemon/dist/domain/claude-seat-token.d.ts.map +1 -1
  167. package/daemon/dist/domain/claude-seat-token.js +49 -7
  168. package/daemon/dist/domain/claude-seat-token.js.map +1 -1
  169. package/daemon/dist/domain/codex-auth.d.ts +34 -0
  170. package/daemon/dist/domain/codex-auth.d.ts.map +1 -1
  171. package/daemon/dist/domain/codex-auth.js +212 -0
  172. package/daemon/dist/domain/codex-auth.js.map +1 -1
  173. package/daemon/dist/domain/community-harness-launch-result.d.ts +9 -0
  174. package/daemon/dist/domain/community-harness-launch-result.d.ts.map +1 -1
  175. package/daemon/dist/domain/community-harness-launch-result.js +14 -2
  176. package/daemon/dist/domain/community-harness-launch-result.js.map +1 -1
  177. package/daemon/dist/domain/compaction-restore-notice.d.ts.map +1 -1
  178. package/daemon/dist/domain/compaction-restore-notice.js +4 -2
  179. package/daemon/dist/domain/compaction-restore-notice.js.map +1 -1
  180. package/daemon/dist/domain/crash-cart-detect.d.ts +7 -0
  181. package/daemon/dist/domain/crash-cart-detect.d.ts.map +1 -1
  182. package/daemon/dist/domain/crash-cart-detect.js +10 -5
  183. package/daemon/dist/domain/crash-cart-detect.js.map +1 -1
  184. package/daemon/dist/domain/crash-cart-discovery.d.ts +9 -16
  185. package/daemon/dist/domain/crash-cart-discovery.d.ts.map +1 -1
  186. package/daemon/dist/domain/crash-cart-discovery.js +22 -40
  187. package/daemon/dist/domain/crash-cart-discovery.js.map +1 -1
  188. package/daemon/dist/domain/crash-cart-emit.d.ts +1 -1
  189. package/daemon/dist/domain/crash-cart-emit.d.ts.map +1 -1
  190. package/daemon/dist/domain/crash-cart-emit.js +4 -0
  191. package/daemon/dist/domain/crash-cart-emit.js.map +1 -1
  192. package/daemon/dist/domain/cwd-resolution.d.ts +12 -1
  193. package/daemon/dist/domain/cwd-resolution.d.ts.map +1 -1
  194. package/daemon/dist/domain/cwd-resolution.js +39 -2
  195. package/daemon/dist/domain/cwd-resolution.js.map +1 -1
  196. package/daemon/dist/domain/draft-held-reoffer.d.ts +17 -1
  197. package/daemon/dist/domain/draft-held-reoffer.d.ts.map +1 -1
  198. package/daemon/dist/domain/draft-held-reoffer.js +76 -0
  199. package/daemon/dist/domain/draft-held-reoffer.js.map +1 -1
  200. package/daemon/dist/domain/gateway/destination-resolver.d.ts +4 -0
  201. package/daemon/dist/domain/gateway/destination-resolver.d.ts.map +1 -1
  202. package/daemon/dist/domain/gateway/destination-resolver.js +9 -3
  203. package/daemon/dist/domain/gateway/destination-resolver.js.map +1 -1
  204. package/daemon/dist/domain/gateway/slack/queue-access.js +1 -1
  205. package/daemon/dist/domain/gateway/slack/queue-access.js.map +1 -1
  206. package/daemon/dist/domain/managed-restore-read-access.d.ts +6 -2
  207. package/daemon/dist/domain/managed-restore-read-access.d.ts.map +1 -1
  208. package/daemon/dist/domain/managed-restore-read-access.js +29 -3
  209. package/daemon/dist/domain/managed-restore-read-access.js.map +1 -1
  210. package/daemon/dist/domain/mission-control/notification-adapter-from-env.d.ts +8 -0
  211. package/daemon/dist/domain/mission-control/notification-adapter-from-env.d.ts.map +1 -0
  212. package/daemon/dist/domain/mission-control/notification-adapter-from-env.js +17 -0
  213. package/daemon/dist/domain/mission-control/notification-adapter-from-env.js.map +1 -0
  214. package/daemon/dist/domain/model-divergence/codex-thread-homes.d.ts +12 -0
  215. package/daemon/dist/domain/model-divergence/codex-thread-homes.d.ts.map +1 -0
  216. package/daemon/dist/domain/model-divergence/codex-thread-homes.js +19 -0
  217. package/daemon/dist/domain/model-divergence/codex-thread-homes.js.map +1 -0
  218. package/daemon/dist/domain/network/hub-client.d.ts +14 -4
  219. package/daemon/dist/domain/network/hub-client.d.ts.map +1 -1
  220. package/daemon/dist/domain/network/hub-client.js +26 -9
  221. package/daemon/dist/domain/network/hub-client.js.map +1 -1
  222. package/daemon/dist/domain/network/network-connector.d.ts +2 -0
  223. package/daemon/dist/domain/network/network-connector.d.ts.map +1 -1
  224. package/daemon/dist/domain/network/network-connector.js +162 -16
  225. package/daemon/dist/domain/network/network-connector.js.map +1 -1
  226. package/daemon/dist/domain/network/network-requests.d.ts +4 -1
  227. package/daemon/dist/domain/network/network-requests.d.ts.map +1 -1
  228. package/daemon/dist/domain/network/network-requests.js +141 -14
  229. package/daemon/dist/domain/network/network-requests.js.map +1 -1
  230. package/daemon/dist/domain/node-inventory.d.ts.map +1 -1
  231. package/daemon/dist/domain/node-inventory.js +13 -0
  232. package/daemon/dist/domain/node-inventory.js.map +1 -1
  233. package/daemon/dist/domain/outbox-handler.d.ts +9 -0
  234. package/daemon/dist/domain/outbox-handler.d.ts.map +1 -1
  235. package/daemon/dist/domain/outbox-handler.js +23 -5
  236. package/daemon/dist/domain/outbox-handler.js.map +1 -1
  237. package/daemon/dist/domain/permission-account.d.ts.map +1 -1
  238. package/daemon/dist/domain/permission-account.js +4 -0
  239. package/daemon/dist/domain/permission-account.js.map +1 -1
  240. package/daemon/dist/domain/policies/parked-owner-consumer.d.ts.map +1 -1
  241. package/daemon/dist/domain/policies/parked-owner-consumer.js +6 -0
  242. package/daemon/dist/domain/policies/parked-owner-consumer.js.map +1 -1
  243. package/daemon/dist/domain/policies/seat-pool.d.ts +2 -1
  244. package/daemon/dist/domain/policies/seat-pool.d.ts.map +1 -1
  245. package/daemon/dist/domain/policies/seat-pool.js.map +1 -1
  246. package/daemon/dist/domain/profile-resolver.d.ts +2 -0
  247. package/daemon/dist/domain/profile-resolver.d.ts.map +1 -1
  248. package/daemon/dist/domain/profile-resolver.js +10 -4
  249. package/daemon/dist/domain/profile-resolver.js.map +1 -1
  250. package/daemon/dist/domain/provider/assignment-apply.d.ts.map +1 -1
  251. package/daemon/dist/domain/provider/assignment-apply.js +2 -1
  252. package/daemon/dist/domain/provider/assignment-apply.js.map +1 -1
  253. package/daemon/dist/domain/provider/claude-seat-switch.d.ts.map +1 -1
  254. package/daemon/dist/domain/provider/claude-seat-switch.js +11 -3
  255. package/daemon/dist/domain/provider/claude-seat-switch.js.map +1 -1
  256. package/daemon/dist/domain/provider/provider-service.d.ts +4 -3
  257. package/daemon/dist/domain/provider/provider-service.d.ts.map +1 -1
  258. package/daemon/dist/domain/queue-repository.d.ts +26 -7
  259. package/daemon/dist/domain/queue-repository.d.ts.map +1 -1
  260. package/daemon/dist/domain/queue-repository.js +159 -37
  261. package/daemon/dist/domain/queue-repository.js.map +1 -1
  262. package/daemon/dist/domain/queue-stuck-sweep.d.ts.map +1 -1
  263. package/daemon/dist/domain/queue-stuck-sweep.js +1826 -1821
  264. package/daemon/dist/domain/queue-stuck-sweep.js.map +1 -1
  265. package/daemon/dist/domain/queue-waiting.d.ts +9 -0
  266. package/daemon/dist/domain/queue-waiting.d.ts.map +1 -1
  267. package/daemon/dist/domain/queue-waiting.js.map +1 -1
  268. package/daemon/dist/domain/queue-wake-ladder.d.ts +6 -1
  269. package/daemon/dist/domain/queue-wake-ladder.d.ts.map +1 -1
  270. package/daemon/dist/domain/queue-wake-ladder.js +29 -12
  271. package/daemon/dist/domain/queue-wake-ladder.js.map +1 -1
  272. package/daemon/dist/domain/restore-orchestrator.d.ts.map +1 -1
  273. package/daemon/dist/domain/restore-orchestrator.js +4 -0
  274. package/daemon/dist/domain/restore-orchestrator.js.map +1 -1
  275. package/daemon/dist/domain/rigspec-exporter.d.ts +2 -0
  276. package/daemon/dist/domain/rigspec-exporter.d.ts.map +1 -1
  277. package/daemon/dist/domain/rigspec-exporter.js +38 -2
  278. package/daemon/dist/domain/rigspec-exporter.js.map +1 -1
  279. package/daemon/dist/domain/rigspec-instantiator.d.ts +4 -1
  280. package/daemon/dist/domain/rigspec-instantiator.d.ts.map +1 -1
  281. package/daemon/dist/domain/rigspec-instantiator.js +32 -13
  282. package/daemon/dist/domain/rigspec-instantiator.js.map +1 -1
  283. package/daemon/dist/domain/rigspec-preflight.d.ts +3 -0
  284. package/daemon/dist/domain/rigspec-preflight.d.ts.map +1 -1
  285. package/daemon/dist/domain/rigspec-preflight.js +25 -7
  286. package/daemon/dist/domain/rigspec-preflight.js.map +1 -1
  287. package/daemon/dist/domain/runtime-adapter.d.ts +2 -0
  288. package/daemon/dist/domain/runtime-adapter.d.ts.map +1 -1
  289. package/daemon/dist/domain/runtime-adapter.js.map +1 -1
  290. package/daemon/dist/domain/seat-delivery-guard.d.ts +5 -0
  291. package/daemon/dist/domain/seat-delivery-guard.d.ts.map +1 -1
  292. package/daemon/dist/domain/seat-delivery-guard.js +13 -0
  293. package/daemon/dist/domain/seat-delivery-guard.js.map +1 -1
  294. package/daemon/dist/domain/seat-lifecycle-service.d.ts +18 -0
  295. package/daemon/dist/domain/seat-lifecycle-service.d.ts.map +1 -1
  296. package/daemon/dist/domain/seat-lifecycle-service.js +28 -1
  297. package/daemon/dist/domain/seat-lifecycle-service.js.map +1 -1
  298. package/daemon/dist/domain/seat-pool-dispatch-guard.d.ts +28 -0
  299. package/daemon/dist/domain/seat-pool-dispatch-guard.d.ts.map +1 -0
  300. package/daemon/dist/domain/seat-pool-dispatch-guard.js +123 -0
  301. package/daemon/dist/domain/seat-pool-dispatch-guard.js.map +1 -0
  302. package/daemon/dist/domain/seat-pool-executor.d.ts +5 -1
  303. package/daemon/dist/domain/seat-pool-executor.d.ts.map +1 -1
  304. package/daemon/dist/domain/seat-pool-executor.js +695 -95
  305. package/daemon/dist/domain/seat-pool-executor.js.map +1 -1
  306. package/daemon/dist/domain/seat-pool-slots.d.ts +68 -3
  307. package/daemon/dist/domain/seat-pool-slots.d.ts.map +1 -1
  308. package/daemon/dist/domain/seat-pool-slots.js +60 -8
  309. package/daemon/dist/domain/seat-pool-slots.js.map +1 -1
  310. package/daemon/dist/domain/seat-pool-spec.d.ts +4 -1
  311. package/daemon/dist/domain/seat-pool-spec.d.ts.map +1 -1
  312. package/daemon/dist/domain/seat-pool-spec.js +14 -2
  313. package/daemon/dist/domain/seat-pool-spec.js.map +1 -1
  314. package/daemon/dist/domain/seat-reaper-eligibility.d.ts.map +1 -1
  315. package/daemon/dist/domain/seat-reaper-eligibility.js +5 -2
  316. package/daemon/dist/domain/seat-reaper-eligibility.js.map +1 -1
  317. package/daemon/dist/domain/seat-restart-in-place.d.ts +2 -3
  318. package/daemon/dist/domain/seat-restart-in-place.d.ts.map +1 -1
  319. package/daemon/dist/domain/seat-restart-in-place.js +3 -43
  320. package/daemon/dist/domain/seat-restart-in-place.js.map +1 -1
  321. package/daemon/dist/domain/seat-startup-text.d.ts +159 -0
  322. package/daemon/dist/domain/seat-startup-text.d.ts.map +1 -0
  323. package/daemon/dist/domain/seat-startup-text.js +200 -0
  324. package/daemon/dist/domain/seat-startup-text.js.map +1 -0
  325. package/daemon/dist/domain/seat-status-service.d.ts +3 -0
  326. package/daemon/dist/domain/seat-status-service.d.ts.map +1 -1
  327. package/daemon/dist/domain/seat-status-service.js +1 -0
  328. package/daemon/dist/domain/seat-status-service.js.map +1 -1
  329. package/daemon/dist/domain/startup-orchestrator.d.ts +8 -20
  330. package/daemon/dist/domain/startup-orchestrator.d.ts.map +1 -1
  331. package/daemon/dist/domain/startup-orchestrator.js +93 -26
  332. package/daemon/dist/domain/startup-orchestrator.js.map +1 -1
  333. package/daemon/dist/domain/startup-submission-evidence.d.ts +3 -1
  334. package/daemon/dist/domain/startup-submission-evidence.d.ts.map +1 -1
  335. package/daemon/dist/domain/startup-submission-evidence.js +10 -0
  336. package/daemon/dist/domain/startup-submission-evidence.js.map +1 -1
  337. package/daemon/dist/domain/terminal/earlier-tile-attach-0724.d.ts +2 -0
  338. package/daemon/dist/domain/terminal/earlier-tile-attach-0724.d.ts.map +1 -0
  339. package/daemon/dist/domain/terminal/earlier-tile-attach-0724.js +54 -0
  340. package/daemon/dist/domain/terminal/earlier-tile-attach-0724.js.map +1 -0
  341. package/daemon/dist/domain/terminal/tile-attach.d.ts +4 -4
  342. package/daemon/dist/domain/terminal/tile-attach.d.ts.map +1 -1
  343. package/daemon/dist/domain/terminal/tile-attach.js +14 -8
  344. package/daemon/dist/domain/terminal/tile-attach.js.map +1 -1
  345. package/daemon/dist/domain/types.d.ts +19 -1
  346. package/daemon/dist/domain/types.d.ts.map +1 -1
  347. package/daemon/dist/domain/types.js.map +1 -1
  348. package/daemon/dist/domain/user-settings/settings-store.d.ts.map +1 -1
  349. package/daemon/dist/domain/user-settings/settings-store.js +1 -2
  350. package/daemon/dist/domain/user-settings/settings-store.js.map +1 -1
  351. package/daemon/dist/domain/watchdog-scheduler.d.ts +4 -0
  352. package/daemon/dist/domain/watchdog-scheduler.d.ts.map +1 -1
  353. package/daemon/dist/domain/watchdog-scheduler.js +14 -0
  354. package/daemon/dist/domain/watchdog-scheduler.js.map +1 -1
  355. package/daemon/dist/domain/workspace/project-registration.d.ts +5 -1
  356. package/daemon/dist/domain/workspace/project-registration.d.ts.map +1 -1
  357. package/daemon/dist/domain/workspace/project-registration.js +11 -7
  358. package/daemon/dist/domain/workspace/project-registration.js.map +1 -1
  359. package/daemon/dist/rig-lookup-surface.d.ts +2 -0
  360. package/daemon/dist/rig-lookup-surface.d.ts.map +1 -0
  361. package/daemon/dist/rig-lookup-surface.js +5 -0
  362. package/daemon/dist/rig-lookup-surface.js.map +1 -0
  363. package/daemon/dist/routes/network.d.ts.map +1 -1
  364. package/daemon/dist/routes/network.js +19 -1
  365. package/daemon/dist/routes/network.js.map +1 -1
  366. package/daemon/dist/routes/queue.js +1 -1
  367. package/daemon/dist/routes/queue.js.map +1 -1
  368. package/daemon/dist/routes/rigspec.d.ts.map +1 -1
  369. package/daemon/dist/routes/rigspec.js +4 -0
  370. package/daemon/dist/routes/rigspec.js.map +1 -1
  371. package/daemon/dist/routes/seat.d.ts.map +1 -1
  372. package/daemon/dist/routes/seat.js +8 -0
  373. package/daemon/dist/routes/seat.js.map +1 -1
  374. package/daemon/dist/routes/terminal-ws.d.ts +0 -5
  375. package/daemon/dist/routes/terminal-ws.d.ts.map +1 -1
  376. package/daemon/dist/routes/terminal-ws.js +0 -6
  377. package/daemon/dist/routes/terminal-ws.js.map +1 -1
  378. package/daemon/dist/routes/transport.js +1 -1
  379. package/daemon/dist/routes/transport.js.map +1 -1
  380. package/daemon/dist/server.d.ts +1 -1
  381. package/daemon/dist/server.d.ts.map +1 -1
  382. package/daemon/dist/server.js +3 -6
  383. package/daemon/dist/server.js.map +1 -1
  384. package/daemon/dist/startup.d.ts.map +1 -1
  385. package/daemon/dist/startup.js +33 -35
  386. package/daemon/dist/startup.js.map +1 -1
  387. package/daemon/docs/reference/agent-startup-guide.md +18 -0
  388. package/daemon/docs/reference/agent-state-taxonomy.md +8 -0
  389. package/daemon/docs/reference/daemon-http-clients.md +4 -0
  390. package/daemon/docs/reference/getting-started.md +63 -11
  391. package/daemon/docs/reference/hosted-members.md +1 -1
  392. package/daemon/docs/reference/network-connector.md +66 -1
  393. package/daemon/docs/reference/quickstart.md +4 -4
  394. package/daemon/docs/reference/rig-bundle.md +25 -0
  395. package/daemon/docs/reference/rig-spec.md +40 -14
  396. package/daemon/docs/reference/seat-delivery.md +11 -2
  397. package/daemon/docs/reference/seat-pools.md +119 -14
  398. package/daemon/docs/reference/seat-scaling.md +2 -1
  399. package/daemon/docs/reference/whats-new.md +102 -12
  400. package/daemon/specs/agents/development/implementer/guidance/role.md +11 -0
  401. package/daemon/specs/agents/development/qa/guidance/role.md +5 -0
  402. package/daemon/specs/agents/shared/skills/core/cross-host-rig-commands/SKILL.md +9 -1
  403. package/daemon/specs/agents/shared/skills/core/working-with-an-openrig-team/SKILL.md +15 -5
  404. package/daemon/specs/rigs/launch/kernel/agents/operator/agent/guidance/role.md +8 -3
  405. package/dist/build-info.js +3 -3
  406. package/dist/cli-error.d.ts +2 -0
  407. package/dist/cli-error.d.ts.map +1 -1
  408. package/dist/cli-error.js +25 -8
  409. package/dist/cli-error.js.map +1 -1
  410. package/dist/client.d.ts +1 -0
  411. package/dist/client.d.ts.map +1 -1
  412. package/dist/client.js +13 -0
  413. package/dist/client.js.map +1 -1
  414. package/dist/commands/auth.d.ts.map +1 -1
  415. package/dist/commands/auth.js +52 -1
  416. package/dist/commands/auth.js.map +1 -1
  417. package/dist/commands/crash-cart.d.ts.map +1 -1
  418. package/dist/commands/crash-cart.js +65 -17
  419. package/dist/commands/crash-cart.js.map +1 -1
  420. package/dist/commands/daemon.d.ts +7 -20
  421. package/dist/commands/daemon.d.ts.map +1 -1
  422. package/dist/commands/daemon.js +83 -50
  423. package/dist/commands/daemon.js.map +1 -1
  424. package/dist/commands/doctor.d.ts +26 -0
  425. package/dist/commands/doctor.d.ts.map +1 -1
  426. package/dist/commands/doctor.js +143 -1
  427. package/dist/commands/doctor.js.map +1 -1
  428. package/dist/commands/mcp.d.ts.map +1 -1
  429. package/dist/commands/mcp.js +4 -2
  430. package/dist/commands/mcp.js.map +1 -1
  431. package/dist/commands/network.d.ts +4 -0
  432. package/dist/commands/network.d.ts.map +1 -1
  433. package/dist/commands/network.js +78 -10
  434. package/dist/commands/network.js.map +1 -1
  435. package/dist/commands/provider.d.ts.map +1 -1
  436. package/dist/commands/provider.js +12 -4
  437. package/dist/commands/provider.js.map +1 -1
  438. package/dist/commands/ps.d.ts +8 -0
  439. package/dist/commands/ps.d.ts.map +1 -1
  440. package/dist/commands/ps.js +19 -3
  441. package/dist/commands/ps.js.map +1 -1
  442. package/dist/commands/queue-transfer.d.ts.map +1 -1
  443. package/dist/commands/queue-transfer.js +12 -6
  444. package/dist/commands/queue-transfer.js.map +1 -1
  445. package/dist/commands/queue.d.ts.map +1 -1
  446. package/dist/commands/queue.js +5 -4
  447. package/dist/commands/queue.js.map +1 -1
  448. package/dist/commands/seat.d.ts.map +1 -1
  449. package/dist/commands/seat.js +74 -6
  450. package/dist/commands/seat.js.map +1 -1
  451. package/dist/commands/setup.d.ts +34 -0
  452. package/dist/commands/setup.d.ts.map +1 -1
  453. package/dist/commands/setup.js +105 -17
  454. package/dist/commands/setup.js.map +1 -1
  455. package/dist/daemon-lifecycle.d.ts +46 -2
  456. package/dist/daemon-lifecycle.d.ts.map +1 -1
  457. package/dist/daemon-lifecycle.js +381 -174
  458. package/dist/daemon-lifecycle.js.map +1 -1
  459. package/dist/daemon-start-lock.d.ts +28 -0
  460. package/dist/daemon-start-lock.d.ts.map +1 -1
  461. package/dist/daemon-start-lock.js +107 -13
  462. package/dist/daemon-start-lock.js.map +1 -1
  463. package/dist/mcp-server.d.ts +1 -1
  464. package/dist/mcp-server.d.ts.map +1 -1
  465. package/dist/mcp-server.js +65 -1
  466. package/dist/mcp-server.js.map +1 -1
  467. package/dist/process-liveness.d.ts +21 -0
  468. package/dist/process-liveness.d.ts.map +1 -0
  469. package/dist/process-liveness.js +43 -0
  470. package/dist/process-liveness.js.map +1 -0
  471. package/dist/remote-host-ops.d.ts +1 -1
  472. package/dist/remote-host-ops.d.ts.map +1 -1
  473. package/dist/remote-host-ops.js +3 -14
  474. package/dist/remote-host-ops.js.map +1 -1
  475. package/dist/system-preflight.d.ts +9 -0
  476. package/dist/system-preflight.d.ts.map +1 -1
  477. package/dist/system-preflight.js +22 -7
  478. package/dist/system-preflight.js.map +1 -1
  479. package/package.json +4 -2
@@ -26,20 +26,41 @@ export function seatPoolStopReport(stop) {
26
26
  /** The queue's reroute actor and note, as the queue records a reroute (the queue's own rule for "was rerouted"). */
27
27
  const QUEUE_FALLBACK_ACTOR = "system:queue-fallback";
28
28
  const FALLBACK_NOTE = "fallback-routed: ";
29
+ /** The actor and note the queue records when a handover or a fresh launch releases the retiring occupant's claims back
30
+ * to pending (`releaseClaimsByGeneration`). */
31
+ const HANDOVER_RELEASE_ACTOR = "system";
32
+ const HANDOVER_RELEASE_NOTE = "released: claimant generation retired (seat handover)";
29
33
  /** No cut: list() keeps the newest rows first, so any limit would drop the oldest rows, which move first. */
30
34
  const ALL_ROWS = Number.MAX_SAFE_INTEGER;
31
35
  /** Refusals that mean the row moved on since it was read: skipped, never a failure. */
32
36
  const ROW_MOVED_ON = new Set(["fallback_state_mismatch", "fallback_destination_mismatch", "qitem_not_found"]);
37
+ /** Asks the guard about one move. A missing runner, or one that throws, is a guard error: the move goes ahead. */
38
+ async function askGuard(run, input) {
39
+ if (run === undefined)
40
+ return { verdict: "error", message: "no guard runner composed" };
41
+ try {
42
+ return await run(input);
43
+ }
44
+ catch (error) {
45
+ return { verdict: "error", message: error instanceof Error ? error.message : String(error) };
46
+ }
47
+ }
33
48
  /** A queue-only seat's cold watchdog reminder is about that seat, never its work (the stuck sweep's rule). */
34
49
  function isWatchdogReminder(row) {
35
50
  return row.sourceSession === "watchdog@system" && !!row.tags?.includes("watchdog") && row.tags.includes("queue-only");
36
51
  }
37
- /** When the row was last rerouted, from its transitions, or null when it never was. */
38
- function lastReroute(queueRepo, qitemId) {
52
+ /** When the row's waiting clock last restarted, from its transitions: its latest reroute or its latest release back to
53
+ * pending by a handover or a fresh launch, or null when neither happened. Only the queue's own records count (no
54
+ * identity provenance). */
55
+ function waitingRestartedAt(queueRepo, qitemId) {
39
56
  const transitions = queueRepo.transitionLog.listForQitem(qitemId);
40
57
  for (let i = transitions.length - 1; i >= 0; i--) {
41
58
  const t = transitions[i];
42
- if (t.actorSession === QUEUE_FALLBACK_ACTOR && t.transitionNote?.startsWith(FALLBACK_NOTE) && t.identityProvenance === null)
59
+ if (t.identityProvenance !== null)
60
+ continue;
61
+ if (t.actorSession === QUEUE_FALLBACK_ACTOR && t.transitionNote?.startsWith(FALLBACK_NOTE))
62
+ return t.ts;
63
+ if (t.state === "pending" && t.actorSession === HANDOVER_RELEASE_ACTOR && t.transitionNote === HANDOVER_RELEASE_NOTE)
43
64
  return t.ts;
44
65
  }
45
66
  return null;
@@ -56,7 +77,7 @@ export function seatPoolQueueEffects(queueRepo) {
56
77
  qitemId: row.qitemId,
57
78
  rawDestination: row.destinationSession,
58
79
  tags: row.tags ?? [],
59
- waitingSince: lastReroute(queueRepo, row.qitemId) ?? row.tsCreated,
80
+ waitingSince: waitingRestartedAt(queueRepo, row.qitemId) ?? row.tsCreated,
60
81
  }));
61
82
  },
62
83
  openRows: (sessionName) => queueRepo.listOpenObligations(sessionName, ALL_ROWS).length,
@@ -104,7 +125,9 @@ export function readSeatPoolAgents(deps, slots) {
104
125
  const latestSessionStatus = nodeId === null
105
126
  ? null
106
127
  : latestStatus.get(nodeId)?.status ?? null;
107
- const running = nodeId !== null && (latestSessionStatus === "running" || latestSessionStatus === "idle")
128
+ // A `live` slot with a reuse hold is not proven to run: it takes room, but it is not free and receives no row.
129
+ const heldLive = slot.phase === "live" && slot.reuseHold !== null;
130
+ const running = nodeId !== null && !heldLive && (latestSessionStatus === "running" || latestSessionStatus === "idle")
108
131
  && !deps.confirmedStopped(nodeId);
109
132
  const state = running ? deps.seatState(nodeId) : null;
110
133
  const idleAtPrompt = state?.activity === "idle-at-prompt" && state.needsInput.count === 0 && !state.backgroundWork;
@@ -168,12 +191,19 @@ function blockView(stored) {
168
191
  return { block: "none" };
169
192
  return "spec" in stored ? { block: "stored", spec: stored.spec } : { block: "unusable", error: stored.error };
170
193
  }
171
- /** Whether two stored specs are the same, field by field. */
194
+ /** Whether two stored specs are the same, field by field (the guard's argv item by item). */
172
195
  function sameSpec(a, b) {
173
196
  const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
174
- for (const key of keys)
175
- if (a[key] !== b[key])
197
+ for (const key of keys) {
198
+ const x = a[key];
199
+ const y = b[key];
200
+ if (Array.isArray(x) && Array.isArray(y)) {
201
+ if (x.length !== y.length || x.some((item, i) => item !== y[i]))
202
+ return false;
203
+ }
204
+ else if (x !== y)
176
205
  return false;
206
+ }
177
207
  return true;
178
208
  }
179
209
  function unreadableAdvisory(error) {
@@ -196,24 +226,83 @@ function slotRecord(text) {
196
226
  return null;
197
227
  }
198
228
  }
199
- /** A slot's attempt as its row records it. A comeback first: in flight until it settles, then `refused` with its code or
200
- * `running` with its snapshot. An add: an issued one with an `unknown` outcome is reported so, and a settled one by the
229
+ /** How a held `live` slot is reported, from its hold: `left_attached`, or `attention_required` (with the launch's status in
230
+ * `code` when it is another one, as a failure whose session still runs), with the hold's error. */
231
+ function heldLiveView(attemptId, hold) {
232
+ const code = typeof hold["code"] === "string" ? hold["code"] : "attention_required";
233
+ const status = code === "left_attached" ? "left_attached" : "attention_required";
234
+ return {
235
+ id: attemptId, status,
236
+ ...(code !== status ? { code } : {}),
237
+ ...(typeof hold["error"] === "string" ? { message: hold["error"] } : {}),
238
+ };
239
+ }
240
+ /** A slot's attempt as its row records it. A `live` slot that is held is reported from its hold. A comeback: in flight
241
+ * while its call runs in this process (`inFlightIds`; without it, every issued one), `unknown` once no call runs it,
242
+ * then by how it settled. An add: an issued one with an `unknown` outcome is reported so, and a settled one by the
201
243
  * status its outcome kept (a settled add with no such status settled running). */
202
- function attemptView(slot) {
244
+ function attemptView(slot, inFlightIds) {
203
245
  if (slot.attemptId === null || slot.attemptState === null)
204
246
  return undefined;
205
247
  const outcome = readAttemptOutcome(slot.attemptOutcome);
248
+ const text = (key) => (typeof outcome[key] === "string" ? { [key]: outcome[key] } : {});
249
+ if (slot.attemptState === "settled" && slot.phase === "live" && slot.reuseHold !== null) {
250
+ return heldLiveView(slot.attemptId, slotRecord(slot.reuseHold) ?? {});
251
+ }
252
+ // Put back in `adding` by a later session that has not settled: unknown, read again every cycle.
253
+ if (slot.attemptState === "issued" && outcome["reread"] === "session") {
254
+ const pending = slotRecord(JSON.stringify(outcome["pending"] ?? null)) ?? {};
255
+ return { id: slot.attemptId, status: "unknown", code: typeof pending["code"] === "string" ? pending["code"] : "later_session_not_settled",
256
+ ...(typeof pending["message"] === "string" ? { message: pending["message"] } : {}) };
257
+ }
258
+ if (slot.attemptState === "settled") {
259
+ const hold = slotRecord(slot.reuseHold);
260
+ // Held `drained` for a decision or a failure the launch (or a later restore) returned: not running, with that status.
261
+ if (slot.phase === "drained" && hold !== null && !("observed" in hold) && (hold["code"] === "awaiting-decision" || hold["code"] === "failed")) {
262
+ return { id: slot.attemptId, status: "not_running", code: hold["code"], ...(typeof hold["error"] === "string" ? { message: hold["error"] } : {}) };
263
+ }
264
+ // Settled by a later session on its node rather than by its call.
265
+ // Reported by what that session read when it settled the attempt, not by the slot's phase now (a normal drain later
266
+ // does not change how the attempt settled).
267
+ if (outcome["settledBy"] === "later_session") {
268
+ const later = slotRecord(JSON.stringify(outcome["later"] ?? null));
269
+ const ran = later !== null && typeof later["read"] === "string" ? later["read"] === "ready" : slot.phase === "live" && slot.reuseHold === null;
270
+ return ran
271
+ ? { id: slot.attemptId, status: "running", code: "later_session" }
272
+ : { id: slot.attemptId, status: "not_running", code: "later_session_absent" };
273
+ }
274
+ }
206
275
  if (slot.attemptKind === "comeback") {
207
- if (slot.attemptState !== "settled")
208
- return inFlight(slot.attemptId);
276
+ if (slot.attemptState !== "settled") {
277
+ if (inFlightIds === undefined || inFlightIds.has(slot.attemptId))
278
+ return inFlight(slot.attemptId);
279
+ return { id: slot.attemptId, status: "unknown", code: typeof outcome["code"] === "string" ? outcome["code"] : "no_outcome",
280
+ message: typeof outcome["message"] === "string" ? outcome["message"]
281
+ : "unknown: the comeback's launch is not running in this process and its result is not recorded" };
282
+ }
283
+ if (outcome["cancelled"] === true) {
284
+ return { id: slot.attemptId, status: "cancelled", message: CANCELLED_NOT_ISSUED, ...text("code") };
285
+ }
286
+ if (outcome["settledAs"] === "already_running")
287
+ return { id: slot.attemptId, status: "already_running" };
288
+ if (outcome["settledAs"] === "attention_required" || outcome["settledAs"] === "left_attached") {
289
+ return heldLiveView(slot.attemptId, { code: typeof outcome["status"] === "string" ? outcome["status"] : outcome["settledAs"],
290
+ ...(typeof outcome["error"] === "string" ? { error: outcome["error"] } : {}) });
291
+ }
292
+ if (outcome["settledAs"] === "not_running") {
293
+ return { id: slot.attemptId, status: "not_running", ...(typeof outcome["status"] === "string" ? { code: outcome["status"] } : {}),
294
+ ...(typeof outcome["error"] === "string" ? { message: outcome["error"] } : {}) };
295
+ }
209
296
  if (outcome["ok"] === false) {
210
297
  return { id: slot.attemptId, status: "refused", ...(typeof outcome["code"] === "string" ? { code: outcome["code"] } : {}) };
211
298
  }
212
299
  const selection = outcome["snapshotSelection"];
213
300
  return { id: slot.attemptId, status: "running", ...(selection ? { snapshotSelection: selection } : {}) };
214
301
  }
215
- const text = (key) => (typeof outcome[key] === "string" ? { [key]: outcome[key] } : {});
216
302
  if (slot.attemptState === "settled") {
303
+ if (outcome["status"] === "attention_required" || outcome["status"] === "left_attached") {
304
+ return heldLiveView(slot.attemptId, { code: typeof outcome["code"] === "string" ? outcome["code"] : outcome["status"], ...(typeof outcome["message"] === "string" ? { error: outcome["message"] } : {}) });
305
+ }
217
306
  if (outcome["status"] !== "not_running")
218
307
  return { id: slot.attemptId, status: "running" };
219
308
  return {
@@ -228,9 +317,9 @@ function attemptView(slot) {
228
317
  return inFlight(slot.attemptId);
229
318
  }
230
319
  /** The slots as reported: each one's attempt and, on a slot the pool does not bring back, its reuse hold, every cycle. */
231
- function slotsView(slots) {
320
+ function slotsView(slots, inFlightIds) {
232
321
  return slots.map((slot) => {
233
- const attempt = attemptView(slot);
322
+ const attempt = attemptView(slot, inFlightIds);
234
323
  return {
235
324
  slotNumber: slot.slotNumber,
236
325
  nodeId: slot.nodeId,
@@ -246,8 +335,9 @@ function slotsView(slots) {
246
335
  * reuse hold (a refusal is a `comeback` attempt; `holdComeback` keeps the slot's add attempt, which settled running) or
247
336
  * an `unknown` add (still `adding`). */
248
337
  function confirmedFailedAdd(slot) {
338
+ const outcome = readAttemptOutcome(slot.attemptOutcome);
249
339
  return slot.phase === "drained" && slot.attemptKind === "add" && slot.attemptState === "settled" && slot.attemptId !== null
250
- && slot.reuseHold !== null && readAttemptOutcome(slot.attemptOutcome)["status"] === "not_running";
340
+ && slot.reuseHold !== null && outcome["status"] === "not_running" && outcome["later"] === undefined;
251
341
  }
252
342
  /** The add's notes while a confirmed failed add holds the new number: that attempt, its slot and its evidence. */
253
343
  function failedAddHeld(slot) {
@@ -266,8 +356,10 @@ const COMEBACK_REFUSALS = new Set([
266
356
  "snapshot_not_found", "snapshot_wrong_rig", "snapshot_unusable", "no_matching_nodes", "selection_changed",
267
357
  ]);
268
358
  /** The model member's keys an agent does not take: it gets its own id and folder, no pool, no conversation of the
269
- * model's, and its own `keep_alive: false` (below). */
270
- const NOT_INHERITED = ["pool", "id", "label", "cwd", "session_source", "keep_alive"];
359
+ * model's, and its own `keep_alive: false` (below). Nor does it take the model's continuity strategy, mechanic or
360
+ * cold-start opt-in: its continuity comes from its own agent spec, and it isn't opted into cold start. */
361
+ const NOT_INHERITED = ["pool", "id", "label", "cwd", "session_source", "keep_alive", "compaction_strategy", "mechanic",
362
+ "cold_start"];
271
363
  function addCallOutcome(outcome) {
272
364
  if (!outcome.ok)
273
365
  return { ok: false, code: outcome.code, message: "message" in outcome ? outcome.message : outcome.errors.join("; ") };
@@ -279,9 +371,10 @@ function addCallOutcome(outcome) {
279
371
  }
280
372
  /**
281
373
  * The one rule an add with a node settles by, in the cycle that ran it and in a later cycle (or process) that reads it
282
- * again. Exited, or the node's executor confirmed stopped: not running, never retried. Running or idle with startup
283
- * `ready`: running, unless the call is known to have returned anything but a launch (a failed launch whose session
284
- * still runs is not settled here). Anything else (startup not ready, no session, another status): unknown.
374
+ * again. Exited, or the node's executor confirmed stopped: not running, never retried. Running or idle while the call is
375
+ * known to have returned anything but a launch (`attention_required`, `left_attached`, a failure): held `live`, reported
376
+ * by the launch's status (`left_attached`, else `attention_required`, with the status or code in `code`). Running or idle
377
+ * with startup `ready` after a launch: running. Anything else (startup not ready, no session, another status): unknown.
285
378
  */
286
379
  function classifyAdd(call, latest, confirmedStopped) {
287
380
  const failure = call === null ? {}
@@ -291,15 +384,25 @@ function classifyAdd(call, latest, confirmedStopped) {
291
384
  return { status: "not_running", observed: "exited", ...failure };
292
385
  if (confirmedStopped)
293
386
  return { status: "not_running", observed: "probe_absent", ...failure };
387
+ // The add said it needs attention or was left attached: held `live` whatever its session reads, since a pane may run.
388
+ if (call !== null && call.ok && (call.status === "attention_required" || call.status === "left_attached")) {
389
+ return { status: call.status, code: call.status, ...(call.error !== undefined ? { message: call.error } : {}) };
390
+ }
294
391
  if (latest === null)
295
392
  return { status: "unknown", code: "no_session", message: "unknown: the node has no session yet" };
296
393
  const evidence = `latest session ${latest.status}, startup ${latest.startupStatus ?? "unknown"}`;
297
394
  if (latest.status === "running" || latest.status === "idle") {
298
395
  if (call !== null && !(call.ok && call.status === "launched")) {
299
- return { status: "unknown", code: call.ok ? `node_${call.status}` : call.code, message: `unknown: the add returned ${call.ok ? call.status : call.code}; ${evidence}` };
396
+ const code = call.ok ? call.status : call.code;
397
+ const message = call.ok ? call.error : call.message;
398
+ return { status: code === "left_attached" ? "left_attached" : "attention_required", code, ...(message !== undefined ? { message } : {}) };
300
399
  }
301
400
  if (latest.startupStatus === "ready")
302
401
  return { status: "running", sessionId: latest.id };
402
+ // A startup that needs attention or failed while the session runs (the add's call not known, as after a restart).
403
+ if (latest.startupStatus === "attention_required" || latest.startupStatus === "failed") {
404
+ return { status: "attention_required", code: latest.startupStatus, message: `startup ${latest.startupStatus}; ${evidence}` };
405
+ }
303
406
  }
304
407
  return { status: "unknown", code: "not_settled", message: `unknown: ${evidence}` };
305
408
  }
@@ -357,6 +460,98 @@ function canonical(value) {
357
460
  function latestSession(db, nodeId) {
358
461
  return db.prepare("SELECT id, status FROM sessions WHERE node_id = ? ORDER BY created_at DESC, id DESC LIMIT 1").get(nodeId) ?? null;
359
462
  }
463
+ /** A node's latest session with its startup status, in the order the reader uses, leaving out a session a launch rolled
464
+ * back (`superseded`): that one was never the node's occupant. Null: none. */
465
+ function latestSessionView(db, nodeId) {
466
+ return db.prepare(`SELECT id, status, startup_status AS startupStatus FROM sessions WHERE node_id = ? AND status != 'superseded'
467
+ ORDER BY created_at DESC, id DESC LIMIT 1`).get(nodeId) ?? null;
468
+ }
469
+ /** A session by id as a later change reads it; null for null or an unknown id. */
470
+ function sessionViewOf(db, sessionId) {
471
+ if (sessionId === null)
472
+ return null;
473
+ return db.prepare("SELECT id, status, startup_status AS startupStatus FROM sessions WHERE id = ?").get(sessionId) ?? null;
474
+ }
475
+ /** The highest event seq of the node's rig; 0 when none. */
476
+ function rigEventSeq(db, nodeId) {
477
+ return db.prepare("SELECT MAX(seq) AS seq FROM events WHERE rig_id = (SELECT rig_id FROM nodes WHERE id = ?)").get(nodeId).seq ?? 0;
478
+ }
479
+ /** What a hold is measured from, kept on the slot row (`attempt_result`, marked `held`): the node's latest session as read
480
+ * when the hold was set, with its status and startup status (`sessionId: null` when the node has none), and the rig's
481
+ * event seq then. A later change is measured against it. */
482
+ function heldSession(nodeId, latest, eventSeq) {
483
+ return JSON.stringify({
484
+ held: true, nodeId, sessionId: latest?.id ?? null,
485
+ ...(latest !== null ? { status: latest.status, startupStatus: latest.startupStatus } : {}),
486
+ eventSeq,
487
+ });
488
+ }
489
+ /** What a hold is measured from, read back from the slot row; null when the row keeps none (an attempt's own result, or
490
+ * anything that does not read as one). */
491
+ function readHeldSession(text) {
492
+ const record = slotRecord(text);
493
+ if (record === null || record["held"] !== true)
494
+ return null;
495
+ const sessionId = record["sessionId"];
496
+ if (sessionId !== null && (typeof sessionId !== "string" || sessionId === ""))
497
+ return null;
498
+ return {
499
+ sessionId,
500
+ ...(typeof record["status"] === "string" ? { status: record["status"] } : {}),
501
+ startupStatus: typeof record["startupStatus"] === "string" ? record["startupStatus"] : null,
502
+ eventSeq: typeof record["eventSeq"] === "number" ? record["eventSeq"] : 0,
503
+ };
504
+ }
505
+ /** The status a held comeback settles with, from its launch's status for the node: a decision awaited, or a failure with
506
+ * no session running, holds it `drained` (`not_running`); attention, left attached, or a failure whose session still
507
+ * runs holds it `live`. Null for a status that runs, or one this does not settle. */
508
+ function heldComeback(nodeStatus, sessionRuns) {
509
+ if (nodeStatus === "awaiting-decision")
510
+ return { as: "not_running" };
511
+ if (nodeStatus === "attention_required")
512
+ return { as: "attention_required" };
513
+ if (nodeStatus === "left_attached")
514
+ return { as: "left_attached" };
515
+ if (nodeStatus === "failed")
516
+ return sessionRuns ? { as: "attention_required" } : { as: "not_running" };
517
+ return null;
518
+ }
519
+ /** A slot whose hold a later change on its node can end: a reuse hold on a `drained` or `live` slot with a node, and no
520
+ * attempt running. */
521
+ function isWatchedHold(slot) {
522
+ return slot.reuseHold !== null && slot.nodeId !== null && (slot.phase === "drained" || slot.phase === "live")
523
+ && (slot.attemptState === null || slot.attemptState === "settled");
524
+ }
525
+ /** The newest restore since `sinceSeq` (a whole-rig `restore.completed` or a `restore.subset_completed`) that names the
526
+ * node, with its status and error for it; null when none does. A payload that can't be read names no node. */
527
+ function restoreOf(db, nodeId, sinceSeq, snapshotId) {
528
+ // A comeback's own launch records only a `restore.subset_completed`; a later change also reads a whole-rig restore.
529
+ const events = db.prepare(`SELECT seq, type, payload FROM events WHERE rig_id = (SELECT rig_id FROM nodes WHERE id = ?)
530
+ AND type IN ('restore.subset_completed'${snapshotId === undefined ? ", 'restore.completed'" : ""}) AND seq > ? ORDER BY seq DESC`).all(nodeId, sinceSeq);
531
+ for (const event of events) {
532
+ let payload;
533
+ try {
534
+ payload = JSON.parse(event.payload);
535
+ }
536
+ catch {
537
+ continue;
538
+ }
539
+ if (snapshotId !== undefined && payload.snapshotId !== snapshotId)
540
+ continue;
541
+ const nodes = Array.isArray(payload.result?.nodes) ? payload.result.nodes : [];
542
+ const node = nodes.find((n) => n !== null && typeof n === "object" && n["nodeId"] === nodeId);
543
+ if (!node || typeof node["status"] !== "string")
544
+ continue;
545
+ const selection = payload.result?.snapshotSelection;
546
+ return {
547
+ seq: event.seq, status: node["status"],
548
+ ...(typeof node["error"] === "string" ? { error: node["error"] } : {}),
549
+ ...(selection && typeof selection.snapshotId === "string" && typeof selection.mode === "string"
550
+ ? { snapshotSelection: { snapshotId: selection.snapshotId, mode: selection.mode } } : {}),
551
+ };
552
+ }
553
+ return null;
554
+ }
360
555
  /** The spec the job was last ensured with (`context.pool`); null when it has none that reads. */
361
556
  function lastEnsuredSpec(context) {
362
557
  const read = parsePoolBlock(context["pool"]);
@@ -420,8 +615,17 @@ export function makeSeatPoolExecutor(deps) {
420
615
  };
421
616
  return deps.slots.settleAddNotRunning(add.slotId, add.attemptId, {
422
617
  outcome: JSON.stringify({ status: "not_running", ...seen, call }), hold: JSON.stringify(hold), at: at(),
618
+ result: heldSession(add.nodeId, latest, rigEventSeq(deps.db, add.nodeId)),
423
619
  }) ? entry({ id: add.attemptId, status: "not_running", ...seen }) : null;
424
620
  }
621
+ if (settlement.status === "attention_required" || settlement.status === "left_attached") {
622
+ // Held `live`: a session may run, so the slot takes room, but it is not free, receives no row and is never drained.
623
+ const hold = { code: settlement.code, ...(settlement.message !== undefined ? { error: settlement.message } : {}) };
624
+ return deps.slots.settleAddHeldLive(add.slotId, add.attemptId, {
625
+ outcome: JSON.stringify({ status: settlement.status, code: settlement.code, ...(settlement.message !== undefined ? { message: settlement.message } : {}), call }),
626
+ hold: JSON.stringify(hold), result: heldSession(add.nodeId, latest, rigEventSeq(deps.db, add.nodeId)), at: at(),
627
+ }) ? entry(heldLiveView(add.attemptId, hold)) : null;
628
+ }
425
629
  deps.slots.recordAttemptOutcome(add.slotId, add.attemptId, JSON.stringify({ status: "unknown", code: settlement.code, message: settlement.message, call }));
426
630
  return null;
427
631
  };
@@ -466,7 +670,10 @@ export function makeSeatPoolExecutor(deps) {
466
670
  : null;
467
671
  }
468
672
  const latest = operation.current.nodes.find((node) => node.id === slot.nodeId)?.latestSession ?? null;
469
- return settleWithNode({ slotId: slot.slotId, slotNumber: slot.slotNumber, logicalId, attemptId, nodeId: slot.nodeId }, keptCall(slot), latest);
673
+ // An add read with no session yet made none of its own: a session found now is someone else's, so the call that
674
+ // returned without one does not hold it. With still no session, the call is kept with its failure.
675
+ const call = latest !== null && readAttemptOutcome(slot.attemptOutcome)["code"] === "no_session" ? null : keptCall(slot);
676
+ return settleWithNode({ slotId: slot.slotId, slotNumber: slot.slotNumber, logicalId, attemptId, nodeId: slot.nodeId }, call, latest);
470
677
  };
471
678
  /** Why the model member gives no agent, read from the model node itself (the export leaves these out silently), or null. */
472
679
  const addRefusal = (rigId, modelNodeId) => {
@@ -582,6 +789,8 @@ export function makeSeatPoolExecutor(deps) {
582
789
  const comeback = async (request) => {
583
790
  const report = (entry) => settled.set(request.modelNodeId, [...(settled.get(request.modelNodeId) ?? []), entry]);
584
791
  const base = { slotNumber: request.slotNumber, logicalId: request.logicalId, nodeId: request.nodeId };
792
+ // Running in this process until it settles, whoever calls it: a cycle does not read it as left over meanwhile.
793
+ inFlightAttempts.add(request.attemptId);
585
794
  try {
586
795
  if (!deps.comeback) {
587
796
  report({ ...base, attempt: { ...inFlight(request.attemptId), code: "comeback_not_composed" } });
@@ -621,7 +830,7 @@ export function makeSeatPoolExecutor(deps) {
621
830
  const selection = launch.snapshotSelection
622
831
  ? { snapshotId: launch.snapshotSelection.snapshotId, mode: launch.snapshotSelection.mode }
623
832
  : undefined;
624
- const stored = JSON.stringify({
833
+ const storedOutcome = {
625
834
  ok: launch.ok && !threw,
626
835
  ...(launch.code !== undefined ? { code: launch.code } : {}),
627
836
  ...(launch.message !== undefined ? { message: launch.message } : {}),
@@ -629,7 +838,8 @@ export function makeSeatPoolExecutor(deps) {
629
838
  ...(node ? { nodeId: node.nodeId, status: node.status, ...(node.error ? { error: node.error } : {}) } : {}),
630
839
  ...(launch.alreadyRunning?.length ? { alreadyRunning: launch.alreadyRunning.map((n) => n.nodeId) } : {}),
631
840
  ...(selection ? { snapshotSelection: selection } : {}),
632
- });
841
+ };
842
+ const stored = JSON.stringify(storedOutcome);
633
843
  // Running, on the same node: settled, and the slot `live`.
634
844
  if (!threw && launch.ok && node && node.nodeId === request.nodeId && launchStatusIsRunning(node.status)) {
635
845
  const sessionId = latestSession(deps.db, request.nodeId)?.id ?? null;
@@ -640,10 +850,44 @@ export function makeSeatPoolExecutor(deps) {
640
850
  return;
641
851
  }
642
852
  }
853
+ // Launched on the same node and not running: held, and never launched again (a decision awaited, a failure with
854
+ // nothing running: `drained`; attention, left attached, a failure whose session still runs: `live`).
855
+ if (!threw && launch.ok && node && node.nodeId === request.nodeId) {
856
+ // The node's current state first, as for a leftover: a session that reads ready now (an agent someone recovered by
857
+ // hand while the launch ran) is not held from the launch's status.
858
+ const now = latestSessionView(deps.db, request.nodeId);
859
+ if (now !== null && readSession(request.nodeId, now) === "ready") {
860
+ if (deps.slots.settleIssuedByLater({
861
+ slotId: request.slotId, attemptId: request.attemptId, phase: "live", hold: null, result: null, at: at(),
862
+ outcome: JSON.stringify({ ...storedOutcome, settledBy: "later_session", later: { sessionId: now.id, read: "ready", at: at() } }),
863
+ }))
864
+ report({ ...base, attempt: { id: request.attemptId, status: "running", code: "later_session" }, ...warning });
865
+ return;
866
+ }
867
+ const held = settleHeldComeback(request, node.status, node.error, storedOutcome);
868
+ if (held === "moved_on")
869
+ return;
870
+ if (held !== "not_held") {
871
+ report({ ...base, attempt: held, ...warning });
872
+ return;
873
+ }
874
+ }
875
+ // No launch, and the node in `alreadyRunning`: a live session the pool did not start. `live`, with no hold and no
876
+ // session of the attempt's own; free only once idle at its prompt.
877
+ if (!threw && launch.ok && !launch.launched?.length && launch.alreadyRunning?.some((n) => n.nodeId === request.nodeId)) {
878
+ if (deps.slots.settleAdd(request.slotId, request.attemptId, {
879
+ outcome: JSON.stringify({ ...storedOutcome, settledAs: "already_running" }), result: null, at: at(),
880
+ })) {
881
+ report({ ...base, attempt: { id: request.attemptId, status: "already_running" }, ...warning });
882
+ }
883
+ return;
884
+ }
643
885
  // Refused before any launch: settled, `drained` again with the code as the reuse hold.
644
886
  if (!threw && !launch.ok && launch.code !== undefined && COMEBACK_REFUSALS.has(launch.code)) {
645
887
  const hold = JSON.stringify({ code: launch.code, snapshotId: request.snapshotId });
646
- if (deps.slots.settleComebackRefused(request.slotId, request.attemptId, { outcome: stored, hold })) {
888
+ if (deps.slots.settleComebackRefused(request.slotId, request.attemptId, {
889
+ outcome: stored, hold, result: heldSession(request.nodeId, latestSessionView(deps.db, request.nodeId), rigEventSeq(deps.db, request.nodeId)),
890
+ })) {
647
891
  report({
648
892
  ...base,
649
893
  attempt: { id: request.attemptId, status: "refused", code: launch.code, ...(launch.message ? { message: launch.message } : {}) },
@@ -652,9 +896,9 @@ export function makeSeatPoolExecutor(deps) {
652
896
  return;
653
897
  }
654
898
  }
655
- // Anything else (a launch that does not run, a live session, another refusal, a call that threw) is not settled
656
- // here: the attempt stays issued, with its outcome kept. Nothing is reported when its row went with a node deleted
657
- // by hand, or the attempt moved on.
899
+ // Anything else (another refusal, a launch on another node, a call that threw) is not settled here: the attempt
900
+ // stays issued, with its outcome kept, and later cycles report it `unknown` and read it again. Nothing is reported
901
+ // when its row went with a node deleted by hand, or the attempt moved on.
658
902
  if (!deps.slots.recordAttemptOutcome(request.slotId, request.attemptId, stored))
659
903
  return;
660
904
  const code = launch.code ?? (launch.alreadyRunning?.length ? "already_running" : node?.status ?? "no_launch_result");
@@ -667,6 +911,289 @@ export function makeSeatPoolExecutor(deps) {
667
911
  catch (error) {
668
912
  report({ ...base, attempt: { ...inFlight(request.attemptId), code: "settle_failed", message: errorMessage(error) } });
669
913
  }
914
+ finally {
915
+ inFlightAttempts.delete(request.attemptId);
916
+ }
917
+ };
918
+ /**
919
+ * An issued comeback whose launch on its node did not run, settled held from the launch's status for the node (from the
920
+ * call, or from the restore event a later cycle reads): `drained` (`not_running`) or `live` (`attention_required`,
921
+ * `left_attached`), with the status as the reuse hold's code, the launch's error and the snapshot. The hold is measured
922
+ * from the node's latest session now (or, with `measuredFrom`, from that session: null when there was none) and the
923
+ * rig's event seq. `not_held` for a status this does not settle; `moved_on` when the row no longer holds the issued
924
+ * attempt.
925
+ */
926
+ const settleHeldComeback = (attempt, nodeStatus, error, outcome, measuredFrom) => {
927
+ const latest = latestSessionView(deps.db, attempt.nodeId);
928
+ const from = measuredFrom === undefined ? latest : sessionViewOf(deps.db, measuredFrom.sessionId);
929
+ const held = heldComeback(nodeStatus, sessionRuns(attempt.nodeId, latest));
930
+ if (held === null)
931
+ return "not_held";
932
+ const hold = { code: nodeStatus, snapshotId: attempt.snapshotId, ...(error !== undefined ? { error } : {}) };
933
+ if (!deps.slots.settleComebackHeld(attempt.slotId, attempt.attemptId, {
934
+ phase: held.as === "not_running" ? "drained" : "live",
935
+ outcome: JSON.stringify({ ...outcome, settledAs: held.as }), hold: JSON.stringify(hold),
936
+ result: heldSession(attempt.nodeId, from, rigEventSeq(deps.db, attempt.nodeId)), at: at(),
937
+ }))
938
+ return "moved_on";
939
+ return held.as === "not_running"
940
+ ? { id: attempt.attemptId, status: "not_running", code: nodeStatus, ...(error !== undefined ? { message: error } : {}) }
941
+ : heldLiveView(attempt.attemptId, hold);
942
+ };
943
+ /** Whether the session runs: running or idle, and its node's executor not confirmed stopped. */
944
+ const sessionRuns = (nodeId, latest) => latest !== null && (latest.status === "running" || latest.status === "idle") && !deps.confirmedStopped(nodeId);
945
+ /** How a node's latest session reads for a later change: confirmed absent (exited, or its executor confirmed stopped),
946
+ * ready (running or idle with startup `ready`), needing attention (running with a startup that needs attention or
947
+ * failed), or anything else. */
948
+ const readSession = (nodeId, latest) => {
949
+ if (latest.status === "exited" || deps.confirmedStopped(nodeId))
950
+ return "absent";
951
+ const runs = latest.status === "running" || latest.status === "idle";
952
+ if (runs && latest.startupStatus === "ready")
953
+ return "ready";
954
+ if (runs && (latest.startupStatus === "attention_required" || latest.startupStatus === "failed"))
955
+ return "attention";
956
+ return "unknown";
957
+ };
958
+ /** Whether a session of the node reached startup `ready` after `sinceSessionId` (any, when null or unknown), in the
959
+ * order `latestSessionView` reads sessions (`created_at`, then `id`), so "later" means one thing. */
960
+ const laterReady = (nodeId, sinceSessionId) => deps.db.prepare(`SELECT 1 FROM sessions s WHERE s.node_id = ? AND s.startup_status = 'ready'
961
+ AND (NOT EXISTS (SELECT 1 FROM sessions WHERE id = ?)
962
+ OR (s.created_at, s.id) > (SELECT created_at, id FROM sessions WHERE id = ?)) LIMIT 1`).get(nodeId, sinceSessionId, sinceSessionId) !== undefined;
963
+ /** The hold a later attention reading gives: its startup status as the code, and the session. */
964
+ const attentionHold = (latest) => ({ code: latest.startupStatus === "failed" ? "failed" : "attention_required", sessionId: latest.id });
965
+ /**
966
+ * An issued attempt no call runs any more, settled by its node's latest session (a comeback cut off before its launch
967
+ * recorded anything, or a slot a later change left `unknown`): ready, the slot is `live` with no hold and no session of
968
+ * the attempt's own; confirmed absent, `drained` and eligible, unless the hold it had awaits a decision and no session
969
+ * reached `ready` since `since` (it is held again); needing attention, `live` and held; anything else is not settled.
970
+ * With `newerThan`, only a session other than that one counts. Returns what changed, or null.
971
+ */
972
+ const settleIssuedBySession = (modelNodeId, slot, opts) => {
973
+ const nodeId = slot.nodeId;
974
+ const latest = latestSessionView(deps.db, nodeId);
975
+ const logicalId = logicalIdOf(modelNodeId, slot.slotNumber);
976
+ const settledBy = (read) => JSON.stringify({
977
+ ...readAttemptOutcome(slot.attemptOutcome), settledBy: "later_session", later: { sessionId: latest?.id ?? null, read, at: at() },
978
+ });
979
+ // A held `live` slot put back in `adding` that settles `drained` is drained from now (the cooldown counts from it); a
980
+ // `drained` one keeps its drain's time.
981
+ const fromLive = readAttemptOutcome(slot.attemptOutcome)["reopenedFrom"] === "live";
982
+ // A restore since the slot was put back in `adding` that launched the node and did not run gives it that outcome,
983
+ // unless a session reads ready now.
984
+ const restore = opts.sinceSeq === undefined ? null : restoreOf(deps.db, nodeId, opts.sinceSeq);
985
+ if (restore !== null && !launchStatusIsRunning(restore.status) && (latest === null || readSession(nodeId, latest) !== "ready")) {
986
+ const held = heldComeback(restore.status, sessionRuns(nodeId, latest));
987
+ if (held !== null) {
988
+ const hold = { code: restore.status, ...(restore.error !== undefined ? { error: restore.error } : {}), restoreSeq: restore.seq };
989
+ const phase = held.as === "not_running" ? "drained" : "live";
990
+ return deps.slots.settleIssuedByLater({
991
+ slotId: slot.slotId, attemptId: slot.attemptId, phase, hold: JSON.stringify(hold), outcome: settledBy("restore"),
992
+ result: heldSession(nodeId, latest, restore.seq), at: at(), drainedNow: fromLive,
993
+ }) ? { slotNumber: slot.slotNumber, logicalId, nodeId, session: latest, read: "restore", restore: { seq: restore.seq, status: restore.status }, phase, reuseHold: hold } : null;
994
+ }
995
+ }
996
+ if (latest === null)
997
+ return null;
998
+ if (opts.newerThan !== undefined && latest.id === opts.newerThan)
999
+ return null;
1000
+ const read = readSession(nodeId, latest);
1001
+ if (read === "unknown")
1002
+ return null;
1003
+ const note = { slotNumber: slot.slotNumber, logicalId, nodeId, session: latest, read };
1004
+ const outcome = settledBy(read);
1005
+ const settle = (phase, hold, result) => deps.slots.settleIssuedByLater({ slotId: slot.slotId, attemptId: slot.attemptId, phase, hold: hold === null ? null : JSON.stringify(hold), outcome, result, at: at(), drainedNow: fromLive });
1006
+ if (read === "ready")
1007
+ return settle("live", null, null) ? { ...note, phase: "live" } : null;
1008
+ if (read === "attention") {
1009
+ const hold = attentionHold(latest);
1010
+ return settle("live", hold, heldSession(nodeId, latest, rigEventSeq(deps.db, nodeId))) ? { ...note, phase: "live", reuseHold: hold } : null;
1011
+ }
1012
+ const prior = slotRecord(slot.reuseHold);
1013
+ if (prior?.["code"] === "awaiting-decision" && !laterReady(nodeId, opts.since)) {
1014
+ return settle("drained", prior, heldSession(nodeId, latest, rigEventSeq(deps.db, nodeId))) ? { ...note, phase: "drained", reuseHold: prior } : null;
1015
+ }
1016
+ return settle("drained", null, null) ? { ...note, phase: "drained" } : null;
1017
+ };
1018
+ /**
1019
+ * An issued comeback no process runs any more (its launch was cut off by a daemon restart, or returned what it does not
1020
+ * settle), read again under the custody lease. The launch records a `restore.subset_completed` naming the node, for the
1021
+ * comeback's snapshot, before it returns, so the newest one after what the comeback was issued on settles it by the same
1022
+ * rule as the call: running (`live`, while its session runs), held, or not settled; the hold is measured from the
1023
+ * session the comeback was issued on, so a session someone started since is a later change. The node's current state
1024
+ * comes first: when its latest session reads ready, the slot is `live` with no hold, whatever the event recorded
1025
+ * (someone recovered the agent by hand before this read), with or without an event (a launch that found the agent
1026
+ * already running records none). Otherwise, with no such event, a session newer than that one settles it by the
1027
+ * later-change rule (`changes`). With neither, it stays issued and
1028
+ * `unknown`: it takes room and is never launched again. Nothing is written then.
1029
+ */
1030
+ const settleComebackLeftover = (modelNodeId, slot, changes) => {
1031
+ const attemptId = slot.attemptId;
1032
+ const nodeId = slot.nodeId;
1033
+ const logicalId = logicalIdOf(modelNodeId, slot.slotNumber);
1034
+ const entry = (attempt) => ({ slotNumber: slot.slotNumber, logicalId, nodeId, attempt });
1035
+ if (slot.attemptState === "reserved") {
1036
+ // A reservation is issued in the transaction that made it, so none is left behind; one that is goes back.
1037
+ const outcome = JSON.stringify({ ok: false, code: "interrupted_before_issue", launched: false, cancelled: true });
1038
+ return deps.slots.returnComebackToDrained(slot.slotId, attemptId, outcome)
1039
+ ? entry({ id: attemptId, status: "cancelled", message: CANCELLED_NOT_ISSUED, code: "interrupted_before_issue" })
1040
+ : null;
1041
+ }
1042
+ const basis = slotRecord(slot.attemptBasis);
1043
+ const snapshotId = typeof basis?.["snapshotId"] === "string" ? basis["snapshotId"] : null;
1044
+ const basisSession = typeof basis?.["sessionId"] === "string" ? basis["sessionId"] : null;
1045
+ const eventSeq = typeof basis?.["eventSeq"] === "number" ? basis["eventSeq"] : 0;
1046
+ if (snapshotId === null)
1047
+ return null;
1048
+ const event = restoreOf(deps.db, nodeId, eventSeq, snapshotId);
1049
+ const latest = latestSessionView(deps.db, nodeId);
1050
+ const readyNow = latest !== null && readSession(nodeId, latest) === "ready";
1051
+ if (event !== null) {
1052
+ const outcome = {
1053
+ ok: true, nodeId, status: event.status, ...(event.error !== undefined ? { error: event.error } : {}), fromEvent: event.seq,
1054
+ ...(event.snapshotSelection ? { snapshotSelection: event.snapshotSelection } : {}),
1055
+ };
1056
+ if (launchStatusIsRunning(event.status) && readyNow) {
1057
+ return deps.slots.settleAdd(slot.slotId, attemptId, { outcome: JSON.stringify(outcome), result: JSON.stringify({ nodeId, sessionId: latest.id }), at: at() })
1058
+ ? entry({ id: attemptId, status: "running", ...(event.snapshotSelection ? { snapshotSelection: event.snapshotSelection } : {}) })
1059
+ : null;
1060
+ }
1061
+ // The node's current state first: a session that reads ready now (an agent recovered by hand since the event) is
1062
+ // not held from the event's outcome; the later-change rule below settles it `live` with no hold.
1063
+ if (!launchStatusIsRunning(event.status) && !readyNow) {
1064
+ // An `awaiting-decision` launch was rolled back, so the node's latest session is someone else's: that hold is
1065
+ // measured from the session the comeback was issued on, and a session started since (not ready yet) is a later
1066
+ // change the next read takes. Any other status keeps the launch's own session as what the hold is measured from.
1067
+ const held = settleHeldComeback({ slotId: slot.slotId, attemptId, nodeId, snapshotId }, event.status, event.error, outcome, event.status === "awaiting-decision" ? { sessionId: basisSession } : undefined);
1068
+ if (typeof held !== "string")
1069
+ return entry(held);
1070
+ if (held === "moved_on")
1071
+ return null;
1072
+ }
1073
+ }
1074
+ if (readyNow) {
1075
+ // With or without an event, no `newerThan`: the session the comeback was issued on counts too, when it reads ready
1076
+ // now (a launch that found it already running records no event, and settles it `live` the same way).
1077
+ const change = settleIssuedBySession(modelNodeId, slot, { since: basisSession });
1078
+ if (change)
1079
+ changes.push(change);
1080
+ return null;
1081
+ }
1082
+ const change = settleIssuedBySession(modelNodeId, slot, { newerThan: basisSession, since: basisSession });
1083
+ if (change)
1084
+ changes.push(change);
1085
+ return null;
1086
+ };
1087
+ /**
1088
+ * The held slots of a model, read again under the custody lease. A hold ends only through a later change on the slot's
1089
+ * node, measured from what the hold kept: a restore since then that launched the node (a whole-rig `rig up`, or a
1090
+ * `rig launch --seats`) and did not run gives the slot that outcome (`drained` and held for a decision or a failure
1091
+ * with nothing running, `live` and held otherwise); otherwise a session newer than the kept one (which the pool did not
1092
+ * start: it never relaunches a held slot), or a new status or startup status on the kept session of a `live` slot
1093
+ * (`rig seat continue` reruns startup on the same session), is read: ready, the slot is `live` with no hold; confirmed
1094
+ * absent, `drained` and eligible, unless its hold awaits a decision and no session reached `ready` since the kept one,
1095
+ * when it stays held; needing attention, `live` and held; anything else puts the slot back in `adding` with its attempt
1096
+ * issued and `unknown`, read again every cycle. A `drained` slot's kept session ending again is no change: nothing ran
1097
+ * on it when the hold was set. A hold kept before what it is measured from was kept gets it now. No event is written.
1098
+ */
1099
+ const laterChanges = (modelNodeId) => {
1100
+ const out = [];
1101
+ for (const slot of deps.slots.forModel(modelNodeId)) {
1102
+ if (!isWatchedHold(slot))
1103
+ continue;
1104
+ const nodeId = slot.nodeId;
1105
+ const from = slot.phase;
1106
+ const latest = latestSessionView(deps.db, nodeId);
1107
+ const seen = readHeldSession(slot.attemptResult);
1108
+ if (seen === null) {
1109
+ deps.slots.recordHeldSession(slot.slotId, slot.attemptId, slot.attemptResult, heldSession(nodeId, latest, rigEventSeq(deps.db, nodeId)));
1110
+ continue;
1111
+ }
1112
+ const hold = slotRecord(slot.reuseHold) ?? { unreadable: slot.reuseHold };
1113
+ const logicalId = logicalIdOf(modelNodeId, slot.slotNumber);
1114
+ const later = (read, sessionId) => JSON.stringify({ ...readAttemptOutcome(slot.attemptOutcome), later: { sessionId, read, at: at() } });
1115
+ const change = (to, newHold, result, outcome) => deps.slots.changeHeld({
1116
+ slotId: slot.slotId, attemptId: slot.attemptId, from, to, hold: newHold === null ? null : JSON.stringify(newHold), outcome, result, at: at(),
1117
+ });
1118
+ const restore = restoreOf(deps.db, nodeId, seen.eventSeq);
1119
+ // A session that reads ready now wins over a restore outcome recorded before it.
1120
+ if (restore !== null && !launchStatusIsRunning(restore.status) && (latest === null || readSession(nodeId, latest) !== "ready")) {
1121
+ // The restore's own outcome for the node, as for a comeback's launch.
1122
+ const held = heldComeback(restore.status, sessionRuns(nodeId, latest));
1123
+ if (held !== null) {
1124
+ const newHold = { code: restore.status, ...(restore.error !== undefined ? { error: restore.error } : {}), restoreSeq: restore.seq };
1125
+ const to = held.as === "not_running" ? "drained" : "live";
1126
+ if (change(to, newHold, heldSession(nodeId, latest, restore.seq), later("restore", latest?.id ?? null))) {
1127
+ out.push({ slotNumber: slot.slotNumber, logicalId, nodeId, session: latest, read: "restore", restore: { seq: restore.seq, status: restore.status }, phase: to, reuseHold: newHold });
1128
+ }
1129
+ continue;
1130
+ }
1131
+ }
1132
+ const eventSeq = restore?.seq ?? seen.eventSeq;
1133
+ /** Nothing to end the hold: measured from now on from what was read. */
1134
+ const rebase = () => { if (eventSeq !== seen.eventSeq || latest?.id !== seen.sessionId)
1135
+ change(from, hold, heldSession(nodeId, latest, eventSeq), slot.attemptOutcome); };
1136
+ if (latest === null) {
1137
+ // A held `live` slot with no session row whose executor is now confirmed stopped: nothing runs, `drained` and eligible.
1138
+ if (from === "live" && deps.confirmedStopped(nodeId)) {
1139
+ if (change("drained", null, null, later("absent", null)))
1140
+ out.push({ slotNumber: slot.slotNumber, logicalId, nodeId, session: null, read: "absent", phase: "drained" });
1141
+ continue;
1142
+ }
1143
+ rebase();
1144
+ continue;
1145
+ }
1146
+ const newer = latest.id !== seen.sessionId;
1147
+ const statusChanged = !newer && seen.status !== undefined && (latest.status !== seen.status || latest.startupStatus !== seen.startupStatus);
1148
+ // A held `live` slot whose session's executor is now confirmed stopped: its session ended, even with a stale status.
1149
+ const probeAbsent = !newer && from === "live" && deps.confirmedStopped(nodeId);
1150
+ if (!newer && !statusChanged && !probeAbsent) {
1151
+ rebase();
1152
+ continue;
1153
+ }
1154
+ const read = readSession(nodeId, latest);
1155
+ // A held `drained` slot's own session: nothing ran on it when the hold was set, so only a resume of it (ready, or
1156
+ // needing attention) is a change; marked down, detached or stale, it is not.
1157
+ if (!newer && from === "drained" && read !== "ready" && read !== "attention") {
1158
+ rebase();
1159
+ continue;
1160
+ }
1161
+ const note = { slotNumber: slot.slotNumber, logicalId, nodeId, session: latest, read };
1162
+ if (read === "ready") {
1163
+ if (change("live", null, null, later(read, latest.id)))
1164
+ out.push({ ...note, phase: "live" });
1165
+ }
1166
+ else if (read === "absent") {
1167
+ if (hold["code"] === "awaiting-decision" && !laterReady(nodeId, seen.sessionId)) {
1168
+ // The decision is still awaited: the hold stays, measured from this session now.
1169
+ if (change(from, hold, heldSession(nodeId, latest, eventSeq), slot.attemptOutcome))
1170
+ out.push({ ...note, phase: from, reuseHold: hold });
1171
+ }
1172
+ else if (change("drained", null, null, later(read, latest.id))) {
1173
+ out.push({ ...note, phase: "drained" });
1174
+ }
1175
+ }
1176
+ else if (read === "attention") {
1177
+ const attention = attentionHold(latest);
1178
+ if (change("live", attention, heldSession(nodeId, latest, eventSeq), later(read, latest.id)))
1179
+ out.push({ ...note, phase: "live", reuseHold: attention });
1180
+ }
1181
+ else if (slot.attemptId !== null) {
1182
+ // Not settled yet (a startup still pending): counted as an unknown result, `adding` with its attempt issued, the
1183
+ // hold it had kept, and read again every cycle by its session.
1184
+ const outcome = JSON.stringify({
1185
+ ...readAttemptOutcome(slot.attemptOutcome), reread: "session", reopenedFrom: from, since: seen.sessionId, sinceSeq: eventSeq,
1186
+ pending: { code: "later_session_not_settled", message: `unknown: a later session on the node, ${latest.status}, startup ${latest.startupStatus ?? "unknown"}` },
1187
+ later: { sessionId: latest.id, read, at: at() },
1188
+ });
1189
+ if (deps.slots.reopenHeld({ slotId: slot.slotId, attemptId: slot.attemptId, from, outcome, at: at() }))
1190
+ out.push({ ...note, phase: "adding", reuseHold: hold });
1191
+ }
1192
+ else {
1193
+ out.push({ ...note, phase: from, reuseHold: hold });
1194
+ }
1195
+ }
1196
+ return out;
670
1197
  };
671
1198
  /** One call after another, each after the lease is released; the cycle does not wait for them. */
672
1199
  const startCalls = (calls) => {
@@ -705,14 +1232,13 @@ export function makeSeatPoolExecutor(deps) {
705
1232
  const held = found.cause === "node_gone"
706
1233
  ? { cause: "model node gone", message: "held: model node gone" }
707
1234
  : { cause: "model has no canonical session", message: "held: model has no canonical session" };
708
- return report({ modelNodeId: found.modelNodeId, slots: slotsView(deps.slots.forModel(found.modelNodeId)), held });
1235
+ return report({ modelNodeId: found.modelNodeId, slots: slotsView(deps.slots.forModel(found.modelNodeId), inFlightAttempts), held });
709
1236
  }
710
1237
  const { model, modelNodeId, rigId } = found;
711
- const slots = deps.slots.forModel(modelNodeId);
712
1238
  let block = blockView(deps.rigRepo.getNodePool(modelNodeId));
713
1239
  // The report reads the slot rows when it is built, not the snapshot the plan used: an add that settles while the cycle
714
1240
  // waits for custody is then reported the same way in `slots` and in `settled`.
715
- const base = () => ({ modelNodeId, ...block, slots: slotsView(deps.slots.forModel(modelNodeId)) });
1241
+ const base = () => ({ modelNodeId, ...block, slots: slotsView(deps.slots.forModel(modelNodeId), inFlightAttempts) });
716
1242
  if (!active())
717
1243
  return report({ ...base(), held: JOB_STOPPED });
718
1244
  if (block.block === "unusable")
@@ -725,6 +1251,26 @@ export function makeSeatPoolExecutor(deps) {
725
1251
  return report(base());
726
1252
  const spec = block.block === "stored" ? block.spec : { ...lastSpec, drain: true };
727
1253
  const removal = removed ? { removal: "the pool block was removed; draining with the spec last stored on the job" } : {};
1254
+ // A held slot, read again before the plan, under the custody lease, so the plan sees what a later change on its
1255
+ // node made of it. Only while a slot is held, and never while the pool is: a held pool changes nothing.
1256
+ let changes = [];
1257
+ if (deps.slots.forModel(modelNodeId).some(isWatchedHold)) {
1258
+ try {
1259
+ await deps.custody([modelNodeId], async () => {
1260
+ if (!active() || readSeatPoolHold(deps.db, rigId).stoppedSeq !== null)
1261
+ return;
1262
+ if (blockView(deps.rigRepo.getNodePool(modelNodeId)).block === "unusable")
1263
+ return;
1264
+ changes = laterChanges(modelNodeId);
1265
+ });
1266
+ }
1267
+ catch (error) {
1268
+ // A refused custody changes nothing here; the cycle's own lease below reports it.
1269
+ if (!(error instanceof DeliveryGuardError))
1270
+ throw error;
1271
+ }
1272
+ }
1273
+ const slots = deps.slots.forModel(modelNodeId);
728
1274
  // The plan is read outside the lease; the custody is for the hold check, the moves, the drain decisions and the
729
1275
  // add's reservation and issue. The add's call goes out after it.
730
1276
  const read = { ...readSeatPoolState(deps, model, slots), lastStepAt: lastDrainStep(slots) };
@@ -743,6 +1289,7 @@ export function makeSeatPoolExecutor(deps) {
743
1289
  const moved = [];
744
1290
  const skipped = [];
745
1291
  const failed = [];
1292
+ const guardErrors = [];
746
1293
  const drains = [];
747
1294
  const toDrain = [];
748
1295
  const restops = [];
@@ -798,10 +1345,24 @@ export function makeSeatPoolExecutor(deps) {
798
1345
  }
799
1346
  // An add attempt no process runs any more (a reservation never issued, or an issued add not in flight in this
800
1347
  // process: cut off by a daemon restart, or left unknown), settled from its row. One in flight here is left alone.
1348
+ // A comeback no process runs any more is read again the same way, from the event its launch records, or by a
1349
+ // later session on its node; a slot a later change left `unknown` is read again by its node's latest session.
801
1350
  for (const slot of deps.slots.forModel(modelNodeId)) {
802
- if (slot.phase !== "adding" || slot.attemptKind !== "add" || slot.attemptId === null || inFlightAttempts.has(slot.attemptId))
1351
+ if (slot.phase !== "adding" || slot.attemptId === null || inFlightAttempts.has(slot.attemptId))
803
1352
  continue;
804
- const entry = settleLeftover(modelNodeId, slot);
1353
+ const outcome = readAttemptOutcome(slot.attemptOutcome);
1354
+ if (outcome["reread"] === "session" && slot.nodeId !== null && slot.attemptState === "issued") {
1355
+ const change = settleIssuedBySession(modelNodeId, slot, {
1356
+ since: typeof outcome["since"] === "string" ? outcome["since"] : null,
1357
+ sinceSeq: typeof outcome["sinceSeq"] === "number" ? outcome["sinceSeq"] : undefined,
1358
+ });
1359
+ if (change)
1360
+ changes.push(change);
1361
+ continue;
1362
+ }
1363
+ const entry = slot.attemptKind === "add" ? settleLeftover(modelNodeId, slot)
1364
+ : slot.attemptKind === "comeback" && slot.nodeId !== null ? settleComebackLeftover(modelNodeId, slot, changes)
1365
+ : null;
805
1366
  if (entry)
806
1367
  reportSettled(modelNodeId, entry);
807
1368
  }
@@ -837,7 +1398,8 @@ export function makeSeatPoolExecutor(deps) {
837
1398
  if (spec.drain && deps.drain && !held && !blockChangedNow()) {
838
1399
  const current = deps.slots.forModel(modelNodeId);
839
1400
  const agentsNow = readSeatPoolAgents(deps, current);
840
- for (const slot of current.filter((s) => s.phase === "live" && s.nodeId !== null)) {
1401
+ // A held `live` slot is never drained by the pool: only a later change on its node ends its hold.
1402
+ for (const slot of current.filter((s) => s.phase === "live" && s.nodeId !== null && s.reuseHold === null)) {
841
1403
  const agent = agentsNow.find((a) => a.slotNumber === slot.slotNumber);
842
1404
  if (!agent || agent.nodeId === null || agent.sessionName === null || agent.running)
843
1405
  continue;
@@ -853,6 +1415,12 @@ export function makeSeatPoolExecutor(deps) {
853
1415
  gone.push({ slot, nodeId: agent.nodeId, session: agent.sessionName, sessionId });
854
1416
  }
855
1417
  }
1418
+ /** The block changed since the plan: this move and the rest are skipped. */
1419
+ const skipRest = (index) => {
1420
+ for (const rest of dispatches.slice(index)) {
1421
+ skipped.push({ qitemId: rest.qitemId, from: read.rawDestination.get(rest.qitemId), to: plannedTo(rest.slotNumber), code: "pool_block_changed" });
1422
+ }
1423
+ };
856
1424
  for (const [index, d] of dispatches.entries()) {
857
1425
  // A job stopped while an earlier move awaited: no later effect.
858
1426
  if (!active()) {
@@ -861,11 +1429,31 @@ export function makeSeatPoolExecutor(deps) {
861
1429
  }
862
1430
  const from = read.rawDestination.get(d.qitemId);
863
1431
  if (blockChangedNow()) {
864
- for (const rest of dispatches.slice(index)) {
865
- skipped.push({ qitemId: rest.qitemId, from: read.rawDestination.get(rest.qitemId), to: plannedTo(rest.slotNumber), code: "pool_block_changed" });
866
- }
1432
+ skipRest(index);
867
1433
  break;
868
1434
  }
1435
+ // The guard, under the block as planned. After its await, the job and the block are read again, and the checks
1436
+ // below run as they would without a guard.
1437
+ const guard = spec.dispatchGuard;
1438
+ if (guard !== undefined) {
1439
+ const to = plannedTo(d.slotNumber);
1440
+ const verdict = await askGuard(deps.dispatchGuard, { argv: guard, qitemId: d.qitemId, from, to });
1441
+ // A job stopped or a block changed while the guard ran ends the moves, whatever the old guard said.
1442
+ if (!active()) {
1443
+ held = JOB_STOPPED;
1444
+ break;
1445
+ }
1446
+ if (blockChangedNow()) {
1447
+ skipRest(index);
1448
+ break;
1449
+ }
1450
+ if (verdict.verdict === "veto") {
1451
+ skipped.push({ qitemId: d.qitemId, from, to, code: "guard_refused", ...(verdict.message ? { message: verdict.message } : {}) });
1452
+ continue;
1453
+ }
1454
+ if (verdict.verdict === "error")
1455
+ guardErrors.push({ qitemId: d.qitemId, from, to, code: "guard_error", message: verdict.message });
1456
+ }
869
1457
  // The agent again, just before the move: still free, no held message, no open row, not above max.
870
1458
  const agents = readSeatPoolAgents(deps, deps.slots.forModel(modelNodeId));
871
1459
  const agent = agents.find((a) => a.slotNumber === d.slotNumber);
@@ -981,14 +1569,49 @@ export function makeSeatPoolExecutor(deps) {
981
1569
  const cancelled = [];
982
1570
  /** A confirmed failed add met where a unit would take a new number: the add's notes name it. */
983
1571
  let failedAddNote;
984
- /** The rig hold read just before an issue, when it stopped the issue. */
985
- const heldAtIssue = (stopped) => {
986
- if (!active())
1572
+ /**
1573
+ * The re-check of a reservation just before its issue, add or comeback, with nothing awaited since it was made:
1574
+ * the job, the holds and the stored block again, then a new plan with the reservation counted. The cause that
1575
+ * cancels it (a stopped job, a `rig.stopped`, a lower `max`, `drain: true`, any other change to the block, or
1576
+ * surplus that reaches it), or null when it may be issued. A cause that holds the pool also sets the hold.
1577
+ */
1578
+ const recheckReservation = (slotNumber, comebackSession) => {
1579
+ if (!active()) {
987
1580
  held = JOB_STOPPED;
988
- else {
989
- hold = stopped;
990
- held = { cause: "rig stopped", seq: stopped.stoppedSeq, message: `held: rig stopped (event ${stopped.stoppedSeq})` };
1581
+ return "job_stopped";
1582
+ }
1583
+ const holdNow = readSeatPoolHold(deps.db, rigId);
1584
+ if (holdNow.stoppedSeq !== null) {
1585
+ hold = holdNow;
1586
+ held = {
1587
+ cause: "rig stopped", seq: holdNow.stoppedSeq, message: `held: rig stopped (event ${holdNow.stoppedSeq})`,
1588
+ ...(holdNow.seatsLaunchedSeq !== null
1589
+ ? { exit: `seats launched with \`rig launch --seats\` (event ${holdNow.seatsLaunchedSeq}) do not end the hold; run \`rig down\`, then \`rig up\`` }
1590
+ : {}),
1591
+ };
1592
+ return "rig_stopped";
1593
+ }
1594
+ const storedSpec = deps.rigRepo.getNodePool(modelNodeId);
1595
+ const specNow = storedSpec !== undefined && "spec" in storedSpec ? storedSpec.spec : null;
1596
+ if (blockChangedNow()) {
1597
+ if (specNow === null)
1598
+ return "pool_block_changed";
1599
+ return specNow.max < spec.max ? "max_lowered" : specNow.drain ? "drain" : "pool_block_changed";
1600
+ }
1601
+ const slotsNow = deps.slots.forModel(modelNodeId);
1602
+ const stateNow = readSeatPoolState(deps, model, slotsNow);
1603
+ // A comeback's reservation took its slot out of `drained`: the rows left with that agent still wait for it, and
1604
+ // count as work waiting, as they did in the plan.
1605
+ const pending = [...stateNow.pending];
1606
+ if (comebackSession) {
1607
+ for (const row of deps.queue.pendingRows(comebackSession)) {
1608
+ if (stateNow.rawDestination.has(row.qitemId))
1609
+ continue;
1610
+ pending.push({ qitemId: row.qitemId, destination: model.sessionName, waitingSince: row.waitingSince, tags: spec.dispatchTag ? [spec.dispatchTag] : row.tags });
1611
+ }
991
1612
  }
1613
+ const replan = planSeatPool(spec, { ...stateNow, pending, lastStepAt: lastDrainStep(slotsNow) }, deps.now().getTime());
1614
+ return replan.intents.some((i) => i.kind === "cancel" && i.slotNumber === slotNumber) ? "surplus" : null;
992
1615
  };
993
1616
  units: for (let unit = 0; unit < addIntent.count; unit++) {
994
1617
  if (!active()) {
@@ -1018,43 +1641,46 @@ export function makeSeatPoolExecutor(deps) {
1018
1641
  const hold = selection.conflict !== undefined
1019
1642
  ? { code: "conflicting_occupants", nodeId, snapshotId: selection.conflict.snapshotId, candidateIds: selection.conflict.candidateIds, read: selection.read, failed: selection.failed }
1020
1643
  : { code: "no_qualifying_snapshot", nodeId, read: selection.read, failed: selection.failed };
1021
- comebackNotes.push(deps.slots.holdComeback(slot.slotId, JSON.stringify(hold)) ? { ...note, hold } : { ...note, code: "slot_moved_on" });
1644
+ const measured = heldSession(nodeId, latestSessionView(deps.db, nodeId), rigEventSeq(deps.db, nodeId));
1645
+ comebackNotes.push(deps.slots.holdComeback(slot.slotId, JSON.stringify(hold), measured) ? { ...note, hold } : { ...note, code: "slot_moved_on" });
1022
1646
  continue;
1023
1647
  }
1024
1648
  const snapshotId = selection.chosen.id;
1025
1649
  const unknowns = selection.failed.flatMap((f) => (f.unknown ? [{ snapshotId: f.snapshotId, ...f.unknown }] : []));
1026
- // The reservation, on the slot's own row, with the chosen snapshot, and the issue: the job's state and the
1027
- // holds again, then the issued attempt and what it was issued on (the snapshot, the node's latest session and
1028
- // the rig's latest event), in one transaction. A comeback held or not issued is `drained` again in the same
1029
- // transaction, its row never removed; an unexpected error rolls it all back, so the slot stays `drained`
1030
- // with the attempt it had.
1650
+ // The reservation, on the slot's own row, with the chosen snapshot, and the issue: the re-check of the
1651
+ // reservation (as an add's), then the issued attempt and what it was issued on (the snapshot, the node's
1652
+ // latest session and the rig's latest event), in one transaction. A comeback the re-check cancels, or not
1653
+ // issued, is `drained` again in the same transaction, eligible, its row never removed, and never launched;
1654
+ // an unexpected error rolls it all back, so the slot stays `drained` with the attempt it had.
1031
1655
  const attemptId = randomUUID();
1032
1656
  const issueComeback = deps.db.transaction(() => {
1033
1657
  if (!deps.slots.reserveComeback({ slotId: slot.slotId, attemptId, snapshotId }))
1034
1658
  return { code: "slot_moved_on" };
1035
- const returnUnissued = (code, stopped) => {
1036
- deps.slots.returnComebackToDrained(slot.slotId, attemptId, JSON.stringify({ ok: false, code, launched: false }));
1037
- return { code, ...(stopped ? { stopped } : {}) };
1038
- };
1039
- const recheck = readSeatPoolHold(deps.db, rigId);
1040
- if (!active() || recheck.stoppedSeq !== null)
1041
- return returnUnissued("held", recheck);
1659
+ const cause = recheckReservation(slot.slotNumber, agentNode(deps.db, nodeId)?.sessionName ?? null);
1660
+ if (cause !== null) {
1661
+ deps.slots.returnComebackToDrained(slot.slotId, attemptId, JSON.stringify({ ok: false, code: cause, launched: false, cancelled: true }));
1662
+ return { code: cause, cancelled: true };
1663
+ }
1042
1664
  const eventSeq = deps.db.prepare("SELECT MAX(seq) AS seq FROM events WHERE rig_id = ?").get(rigId).seq;
1043
- const basis = JSON.stringify({ snapshotId, sessionId: latestSession(deps.db, nodeId)?.id ?? null, eventSeq });
1044
- if (!deps.slots.issueAttempt(slot.slotId, attemptId, basis))
1045
- return returnUnissued("slot_changed");
1665
+ const basis = JSON.stringify({ snapshotId, sessionId: latestSessionView(deps.db, nodeId)?.id ?? null, eventSeq });
1666
+ if (!deps.slots.issueAttempt(slot.slotId, attemptId, basis)) {
1667
+ deps.slots.returnComebackToDrained(slot.slotId, attemptId, JSON.stringify({ ok: false, code: "slot_changed", launched: false }));
1668
+ return { code: "slot_changed" };
1669
+ }
1046
1670
  return null;
1047
1671
  });
1048
1672
  const unissued = issueComeback();
1049
1673
  if (unissued !== null) {
1050
- if (unissued.stopped !== undefined) {
1051
- heldAtIssue(unissued.stopped);
1674
+ if (unissued.cancelled) {
1675
+ // Cancelled before its issue (`cancelled: not issued`): never launched, and this cycle's adds end.
1676
+ cancelled.push({ slotNumber: slot.slotNumber, logicalId, attempt: { id: attemptId, status: "cancelled", message: CANCELLED_NOT_ISSUED, code: unissued.code } });
1052
1677
  break units;
1053
1678
  }
1054
1679
  comebackNotes.push({ ...note, snapshotId, code: unissued.code });
1055
1680
  continue;
1056
1681
  }
1057
- // The request goes out only once its issue committed.
1682
+ // The request goes out only once its issue committed; its call runs in this process until it settles.
1683
+ inFlightAttempts.add(attemptId);
1058
1684
  comebacks.push({ jobId: job.jobId, modelNodeId, rigId, slotId: slot.slotId, slotNumber: slot.slotNumber, nodeId, logicalId, attemptId, snapshotId, cwdFromModel: spec.cwdTemplate === null });
1059
1685
  comebackNotes.push({ ...note, snapshotId, attempt: inFlight(attemptId), ...(unknowns.length ? { unknownOccupants: unknowns } : {}) });
1060
1686
  continue units;
@@ -1084,33 +1710,11 @@ export function makeSeatPoolExecutor(deps) {
1084
1710
  // A pool agent is never kept alive: a kept-alive agent would be relaunched against the pool's own stops. Leaving
1085
1711
  // the key out is not enough, since the add then resolves it from the agent spec's profile or defaults.
1086
1712
  const member = { id: memberId, ...inherited, cwd: folder ?? raw["cwd"], keep_alive: false };
1087
- // The re-check just before the issue, with nothing awaited since the reservation: the job, the holds and the
1088
- // stored block again, then a new plan with this reservation counted. A lower `max`, `drain: true`, any other
1089
- // change to the block, a hold, or surplus that reaches this reservation cancels it before any operation row
1090
- // or call, and ends this cycle's adds.
1091
- let stopped;
1092
- const recheck = () => {
1093
- if (!active())
1094
- return "job_stopped";
1095
- const holdNow = readSeatPoolHold(deps.db, rigId);
1096
- if (holdNow.stoppedSeq !== null) {
1097
- stopped = holdNow;
1098
- return "rig_stopped";
1099
- }
1100
- const storedSpec = deps.rigRepo.getNodePool(modelNodeId);
1101
- const specNow = storedSpec !== undefined && "spec" in storedSpec ? storedSpec.spec : null;
1102
- if (blockChangedNow()) {
1103
- if (specNow === null)
1104
- return "pool_block_changed";
1105
- return specNow.max < spec.max ? "max_lowered" : specNow.drain ? "drain" : "pool_block_changed";
1106
- }
1107
- const slotsNow = deps.slots.forModel(modelNodeId);
1108
- const replan = planSeatPool(spec, { ...readSeatPoolState(deps, model, slotsNow), lastStepAt: lastDrainStep(slotsNow) }, deps.now().getTime());
1109
- return replan.intents.some((i) => i.kind === "cancel" && i.slotNumber === slot.slotNumber) ? "surplus" : null;
1110
- };
1713
+ // The re-check just before the issue (recheckReservation): what cancels the reservation cancels it before any
1714
+ // operation row or call, and ends this cycle's adds.
1111
1715
  let cancelCause;
1112
1716
  try {
1113
- cancelCause = recheck();
1717
+ cancelCause = recheckReservation(slot.slotNumber);
1114
1718
  }
1115
1719
  catch (error) {
1116
1720
  // A re-check that fails leaves no reservation behind: the reserved row goes before its error is raised.
@@ -1129,12 +1733,6 @@ export function makeSeatPoolExecutor(deps) {
1129
1733
  else {
1130
1734
  notIssued.push({ slotNumber: slot.slotNumber, logicalId, code: "slot_changed" });
1131
1735
  }
1132
- if (cancelCause === "job_stopped")
1133
- held = JOB_STOPPED;
1134
- else if (stopped !== undefined) {
1135
- hold = stopped;
1136
- held = { cause: "rig stopped", seq: stopped.stoppedSeq, message: `held: rig stopped (event ${stopped.stoppedSeq})` };
1137
- }
1138
1736
  break;
1139
1737
  }
1140
1738
  // The issue: the issued attempt, what it was issued on and the operation id, in one transaction.
@@ -1510,9 +2108,11 @@ export function makeSeatPoolExecutor(deps) {
1510
2108
  ...(held ? { held } : {}),
1511
2109
  ...(advisory ? { advisory } : {}),
1512
2110
  ...(restore ? { restore } : {}),
2111
+ ...(changes.length ? { laterChanges: changes } : {}),
1513
2112
  ...(moved.length ? { moved } : {}),
1514
2113
  ...(skipped.length ? { skipped } : {}),
1515
2114
  ...(failed.length ? { failed } : {}),
2115
+ ...(guardErrors.length ? { guardErrors } : {}),
1516
2116
  ...(drains.length ? { drains } : {}),
1517
2117
  ...(addNotes && Object.keys(addNotes).length ? { add: addNotes } : {}),
1518
2118
  ...(custody ? { custody } : {}),