@openrig/cli 0.7.24 → 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 (1037) hide show
  1. package/README.md +7 -7
  2. package/daemon/assets/claude-hook-bridge.cjs +151 -37
  3. package/daemon/assets/claude-hook-bridge.d.cts +9 -2
  4. package/daemon/assets/claude-permission-policies.cjs +22 -1
  5. package/daemon/assets/claude-permission-policies.d.cts +2 -0
  6. package/daemon/assets/claude-statusline-context.cjs +14 -0
  7. package/daemon/assets/claude-team-permissions.cjs +54 -6
  8. package/daemon/assets/guidance/openrig-context-entry.md +4 -5
  9. package/daemon/assets/guidance/openrig-start.md +3 -0
  10. package/daemon/assets/plugins/openrig/.claude-plugin/plugin.json +2 -2
  11. package/daemon/assets/plugins/openrig/.codex-plugin/plugin.json +1 -1
  12. package/daemon/assets/plugins/openrig/.cursor-plugin/plugin.json +1 -1
  13. package/daemon/assets/plugins/openrig/README.md +33 -18
  14. package/daemon/assets/plugins/openrig/hooks/scripts/claude-hook-bridge.cjs +151 -37
  15. package/daemon/assets/plugins/openrig/plugin.json +1 -1
  16. package/daemon/assets/plugins/openrig/scripts/run-rig.cjs +16 -13
  17. package/daemon/assets/plugins/openrig/skills/working-with-an-openrig-team/SKILL.md +32 -19
  18. package/daemon/assets/plugins/openrig-codex/.codex-plugin/plugin.json +1 -1
  19. package/daemon/assets/plugins/openrig-codex/hooks/scripts/claude-hook-bridge.cjs +151 -37
  20. package/daemon/assets/plugins/openrig-codex/skills/working-with-an-openrig-team/SKILL.md +32 -19
  21. package/daemon/assets/plugins/openrig-core/.claude-plugin/plugin.json +1 -1
  22. package/daemon/assets/plugins/openrig-core/.codex-plugin/plugin.json +1 -1
  23. package/daemon/assets/plugins/openrig-core/hooks/scripts/permission-answer.cjs +3 -2
  24. package/daemon/assets/plugins/openrig-core/skills/openrig-user/SKILL.md +47 -14
  25. package/daemon/assets/plugins/openrig-core/skills/session-compaction-and-restore/SKILL.md +5 -2
  26. package/daemon/assets/skills/rigs/SKILL.md +99 -34
  27. package/daemon/assets/skills/rigs/references/installing-for-someone.md +1 -1
  28. package/daemon/context-packs/help/help.md +9 -0
  29. package/daemon/context-packs/help/manifest.yaml +1 -1
  30. package/daemon/context-packs/onboarding-width/manifest.yaml +1 -1
  31. package/daemon/context-packs/onboarding-width/public-what-you-can-do.md +179 -25
  32. package/daemon/context-packs/reference/getting-started.md +73 -11
  33. package/daemon/context-packs/reference/manifest.yaml +1 -1
  34. package/daemon/context-packs/reference/rig-spec.md +218 -23
  35. package/daemon/context-packs/reference/whats-new.md +190 -14
  36. package/daemon/context-packs/skills/agent-operated-software/manifest.yaml +1 -1
  37. package/daemon/context-packs/skills/agent-operated-workflows/manifest.yaml +1 -1
  38. package/daemon/context-packs/skills/applying-a-permission-policy/manifest.yaml +1 -1
  39. package/daemon/context-packs/skills/claude-compaction-restore/manifest.yaml +1 -1
  40. package/daemon/context-packs/skills/core/agent-starters/manifest.yaml +1 -1
  41. package/daemon/context-packs/skills/core/agent-startup-and-context-ingestion/manifest.yaml +1 -1
  42. package/daemon/context-packs/skills/core/cross-host-rig-commands/SKILL.md +9 -1
  43. package/daemon/context-packs/skills/core/cross-host-rig-commands/manifest.yaml +1 -1
  44. package/daemon/context-packs/skills/core/human-in-the-loop/manifest.yaml +1 -1
  45. package/daemon/context-packs/skills/core/messaging-the-human/manifest.yaml +1 -1
  46. package/daemon/context-packs/skills/core/openrig-architect/manifest.yaml +1 -1
  47. package/daemon/context-packs/skills/core/openrig-cmux/manifest.yaml +1 -1
  48. package/daemon/context-packs/skills/core/openrig-herdr/manifest.yaml +1 -1
  49. package/daemon/context-packs/skills/core/openrig-skills/manifest.yaml +1 -1
  50. package/daemon/context-packs/skills/core/openrig-software-factory/manifest.yaml +1 -1
  51. package/daemon/context-packs/skills/core/openrig-upgrade/manifest.yaml +1 -1
  52. package/daemon/context-packs/skills/core/rig-bundles-and-shareable-artifacts/manifest.yaml +1 -1
  53. package/daemon/context-packs/skills/core/rig-lifecycle/manifest.yaml +1 -1
  54. package/daemon/context-packs/skills/core/session-source-fork/manifest.yaml +1 -1
  55. package/daemon/context-packs/skills/core/specification-system/manifest.yaml +1 -1
  56. package/daemon/context-packs/skills/core/topology-mutation-and-seat-management/manifest.yaml +1 -1
  57. package/daemon/context-packs/skills/core/watchdog/manifest.yaml +1 -1
  58. package/daemon/context-packs/skills/core/working-with-an-openrig-team/SKILL.md +32 -19
  59. package/daemon/context-packs/skills/core/working-with-an-openrig-team/manifest.yaml +1 -1
  60. package/daemon/context-packs/skills/delegating-work/manifest.yaml +1 -1
  61. package/daemon/context-packs/skills/forming-an-openrig-mental-model/manifest.yaml +1 -1
  62. package/daemon/context-packs/skills/loading-addressable-markdown/manifest.yaml +1 -1
  63. package/daemon/context-packs/skills/mission-slice-sop/manifest.yaml +1 -1
  64. package/daemon/context-packs/skills/openrig-operating-model/manifest.yaml +1 -1
  65. package/daemon/context-packs/skills/openrig-user/SKILL.md +47 -14
  66. package/daemon/context-packs/skills/openrig-user/manifest.yaml +1 -1
  67. package/daemon/context-packs/skills/orienting-to-an-inherited-seat/manifest.yaml +1 -1
  68. package/daemon/context-packs/skills/pm/backlog-capture/manifest.yaml +1 -1
  69. package/daemon/context-packs/skills/pm/context-builder/manifest.yaml +1 -1
  70. package/daemon/context-packs/skills/pm/exec-summary/manifest.yaml +1 -1
  71. package/daemon/context-packs/skills/pm/office-hours/manifest.yaml +1 -1
  72. package/daemon/context-packs/skills/pm/plan-review/manifest.yaml +1 -1
  73. package/daemon/context-packs/skills/pm/requirements-writer/manifest.yaml +1 -1
  74. package/daemon/context-packs/skills/pm/ui-mockup/manifest.yaml +1 -1
  75. package/daemon/context-packs/skills/pods/development-team/manifest.yaml +1 -1
  76. package/daemon/context-packs/skills/pods/orchestration-team/manifest.yaml +1 -1
  77. package/daemon/context-packs/skills/pods/oversight-team/manifest.yaml +1 -1
  78. package/daemon/context-packs/skills/pods/review-team/manifest.yaml +1 -1
  79. package/daemon/context-packs/skills/process/agent-browser/manifest.yaml +1 -1
  80. package/daemon/context-packs/skills/process/context-engineering/manifest.yaml +1 -1
  81. package/daemon/context-packs/skills/process/dogfood/manifest.yaml +1 -1
  82. package/daemon/context-packs/skills/process/frontend-design/manifest.yaml +1 -1
  83. package/daemon/context-packs/skills/process/systematic-debugging/manifest.yaml +1 -1
  84. package/daemon/context-packs/skills/process/test-driven-development/manifest.yaml +1 -1
  85. package/daemon/context-packs/skills/process/verification-before-completion/manifest.yaml +1 -1
  86. package/daemon/context-packs/skills/queue-handoff/manifest.yaml +1 -1
  87. package/daemon/context-packs/skills/refocusing/manifest.yaml +1 -1
  88. package/daemon/context-packs/skills/retiring-and-inheriting-a-seat/manifest.yaml +1 -1
  89. package/daemon/context-packs/skills/seat-continuity-and-handover/manifest.yaml +1 -1
  90. package/daemon/context-packs/skills/session-compaction-and-restore/SKILL.md +5 -2
  91. package/daemon/context-packs/skills/session-compaction-and-restore/manifest.yaml +1 -1
  92. package/daemon/context-packs/skills/software-for-agents/manifest.yaml +1 -1
  93. package/daemon/context-packs/world-example/manifest.yaml +1 -1
  94. package/daemon/context-packs/world-public/manifest.yaml +1 -1
  95. package/daemon/dist/adapters/claude-code-adapter.d.ts.map +1 -1
  96. package/daemon/dist/adapters/claude-code-adapter.js +25 -8
  97. package/daemon/dist/adapters/claude-code-adapter.js.map +1 -1
  98. package/daemon/dist/adapters/claude-resume.d.ts +2 -0
  99. package/daemon/dist/adapters/claude-resume.d.ts.map +1 -1
  100. package/daemon/dist/adapters/claude-resume.js +44 -8
  101. package/daemon/dist/adapters/claude-resume.js.map +1 -1
  102. package/daemon/dist/adapters/codex-resume.d.ts +3 -0
  103. package/daemon/dist/adapters/codex-resume.d.ts.map +1 -1
  104. package/daemon/dist/adapters/codex-resume.js +7 -3
  105. package/daemon/dist/adapters/codex-resume.js.map +1 -1
  106. package/daemon/dist/adapters/codex-runtime-adapter.d.ts +49 -4
  107. package/daemon/dist/adapters/codex-runtime-adapter.d.ts.map +1 -1
  108. package/daemon/dist/adapters/codex-runtime-adapter.js +238 -25
  109. package/daemon/dist/adapters/codex-runtime-adapter.js.map +1 -1
  110. package/daemon/dist/adapters/community-harness-runtime-adapter.d.ts +12 -5
  111. package/daemon/dist/adapters/community-harness-runtime-adapter.d.ts.map +1 -1
  112. package/daemon/dist/adapters/community-harness-runtime-adapter.js +15 -5
  113. package/daemon/dist/adapters/community-harness-runtime-adapter.js.map +1 -1
  114. package/daemon/dist/adapters/kernel-authority.d.ts +2 -2
  115. package/daemon/dist/adapters/kernel-authority.d.ts.map +1 -1
  116. package/daemon/dist/adapters/kernel-authority.js +5 -3
  117. package/daemon/dist/adapters/kernel-authority.js.map +1 -1
  118. package/daemon/dist/adapters/pi-runner.d.ts.map +1 -1
  119. package/daemon/dist/adapters/pi-runner.js +9 -0
  120. package/daemon/dist/adapters/pi-runner.js.map +1 -1
  121. package/daemon/dist/adapters/pi-session-cwd.d.ts +26 -0
  122. package/daemon/dist/adapters/pi-session-cwd.d.ts.map +1 -0
  123. package/daemon/dist/adapters/pi-session-cwd.js +89 -0
  124. package/daemon/dist/adapters/pi-session-cwd.js.map +1 -0
  125. package/daemon/dist/adapters/shell-quote.d.ts +2 -0
  126. package/daemon/dist/adapters/shell-quote.d.ts.map +1 -1
  127. package/daemon/dist/adapters/shell-quote.js +43 -0
  128. package/daemon/dist/adapters/shell-quote.js.map +1 -1
  129. package/daemon/dist/adapters/tmux-credential-env.d.ts +15 -2
  130. package/daemon/dist/adapters/tmux-credential-env.d.ts.map +1 -1
  131. package/daemon/dist/adapters/tmux-credential-env.js +82 -2
  132. package/daemon/dist/adapters/tmux-credential-env.js.map +1 -1
  133. package/daemon/dist/adapters/tmux-exec.d.ts.map +1 -1
  134. package/daemon/dist/adapters/tmux-exec.js +2 -6
  135. package/daemon/dist/adapters/tmux-exec.js.map +1 -1
  136. package/daemon/dist/adapters/tmux.d.ts +31 -1
  137. package/daemon/dist/adapters/tmux.d.ts.map +1 -1
  138. package/daemon/dist/adapters/tmux.js +104 -8
  139. package/daemon/dist/adapters/tmux.js.map +1 -1
  140. package/daemon/dist/attention-surface.d.ts +5 -0
  141. package/daemon/dist/attention-surface.d.ts.map +1 -1
  142. package/daemon/dist/attention-surface.js.map +1 -1
  143. package/daemon/dist/bind-plan-surface.d.ts +3 -0
  144. package/daemon/dist/bind-plan-surface.d.ts.map +1 -0
  145. package/daemon/dist/bind-plan-surface.js +5 -0
  146. package/daemon/dist/bind-plan-surface.js.map +1 -0
  147. package/daemon/dist/build-info.js +3 -3
  148. package/daemon/dist/db/all-migrations.d.ts +4 -1
  149. package/daemon/dist/db/all-migrations.d.ts.map +1 -1
  150. package/daemon/dist/db/all-migrations.js +30 -393
  151. package/daemon/dist/db/all-migrations.js.map +1 -1
  152. package/daemon/dist/db/migrations/187_provider_account_refs.d.ts +8 -0
  153. package/daemon/dist/db/migrations/187_provider_account_refs.d.ts.map +1 -0
  154. package/daemon/dist/db/migrations/187_provider_account_refs.js +25 -0
  155. package/daemon/dist/db/migrations/187_provider_account_refs.js.map +1 -0
  156. package/daemon/dist/db/migrations/188_provider_account_assignments.d.ts +14 -0
  157. package/daemon/dist/db/migrations/188_provider_account_assignments.d.ts.map +1 -0
  158. package/daemon/dist/db/migrations/188_provider_account_assignments.js +45 -0
  159. package/daemon/dist/db/migrations/188_provider_account_assignments.js.map +1 -0
  160. package/daemon/dist/db/migrations/191_queue_transfer_activation.d.ts +3 -0
  161. package/daemon/dist/db/migrations/191_queue_transfer_activation.d.ts.map +1 -0
  162. package/daemon/dist/db/migrations/191_queue_transfer_activation.js +49 -0
  163. package/daemon/dist/db/migrations/191_queue_transfer_activation.js.map +1 -0
  164. package/daemon/dist/db/migrations/191_seat_reap_state.d.ts +3 -0
  165. package/daemon/dist/db/migrations/191_seat_reap_state.d.ts.map +1 -0
  166. package/daemon/dist/db/migrations/191_seat_reap_state.js +19 -0
  167. package/daemon/dist/db/migrations/191_seat_reap_state.js.map +1 -0
  168. package/daemon/dist/db/migrations/197_session_agent_activity_hooks.d.ts +3 -0
  169. package/daemon/dist/db/migrations/197_session_agent_activity_hooks.d.ts.map +1 -0
  170. package/daemon/dist/db/migrations/197_session_agent_activity_hooks.js +9 -0
  171. package/daemon/dist/db/migrations/197_session_agent_activity_hooks.js.map +1 -0
  172. package/daemon/dist/db/migrations/200_context_configured_budget.d.ts +3 -0
  173. package/daemon/dist/db/migrations/200_context_configured_budget.d.ts.map +1 -0
  174. package/daemon/dist/db/migrations/200_context_configured_budget.js +5 -0
  175. package/daemon/dist/db/migrations/200_context_configured_budget.js.map +1 -0
  176. package/daemon/dist/db/migrations/200_seat_cold_start_standby_stop.d.ts +3 -0
  177. package/daemon/dist/db/migrations/200_seat_cold_start_standby_stop.d.ts.map +1 -0
  178. package/daemon/dist/db/migrations/200_seat_cold_start_standby_stop.js +5 -0
  179. package/daemon/dist/db/migrations/200_seat_cold_start_standby_stop.js.map +1 -0
  180. package/daemon/dist/db/migrations/200_sessions_earlier_handover_origin.d.ts +11 -0
  181. package/daemon/dist/db/migrations/200_sessions_earlier_handover_origin.d.ts.map +1 -0
  182. package/daemon/dist/db/migrations/200_sessions_earlier_handover_origin.js +34 -0
  183. package/daemon/dist/db/migrations/200_sessions_earlier_handover_origin.js.map +1 -0
  184. package/daemon/dist/db/migrations/201_queue_transitions_archive_actor_index.d.ts +7 -0
  185. package/daemon/dist/db/migrations/201_queue_transitions_archive_actor_index.d.ts.map +1 -0
  186. package/daemon/dist/db/migrations/201_queue_transitions_archive_actor_index.js +12 -0
  187. package/daemon/dist/db/migrations/201_queue_transitions_archive_actor_index.js.map +1 -0
  188. package/daemon/dist/db/migrations/201_roster_event_index.d.ts +4 -0
  189. package/daemon/dist/db/migrations/201_roster_event_index.d.ts.map +1 -0
  190. package/daemon/dist/db/migrations/201_roster_event_index.js +9 -0
  191. package/daemon/dist/db/migrations/201_roster_event_index.js.map +1 -0
  192. package/daemon/dist/db/migrations/202_network_requester_questions.d.ts +4 -0
  193. package/daemon/dist/db/migrations/202_network_requester_questions.d.ts.map +1 -0
  194. package/daemon/dist/db/migrations/202_network_requester_questions.js +10 -0
  195. package/daemon/dist/db/migrations/202_network_requester_questions.js.map +1 -0
  196. package/daemon/dist/db/migrations/203_outbox_runner_receipts_index.d.ts +3 -0
  197. package/daemon/dist/db/migrations/203_outbox_runner_receipts_index.d.ts.map +1 -0
  198. package/daemon/dist/db/migrations/203_outbox_runner_receipts_index.js +22 -0
  199. package/daemon/dist/db/migrations/203_outbox_runner_receipts_index.js.map +1 -0
  200. package/daemon/dist/domain/activity-taxonomy.d.ts +16 -5
  201. package/daemon/dist/domain/activity-taxonomy.d.ts.map +1 -1
  202. package/daemon/dist/domain/activity-taxonomy.js +30 -5
  203. package/daemon/dist/domain/activity-taxonomy.js.map +1 -1
  204. package/daemon/dist/domain/agent-activity-store.d.ts +4 -0
  205. package/daemon/dist/domain/agent-activity-store.d.ts.map +1 -1
  206. package/daemon/dist/domain/agent-activity-store.js +21 -0
  207. package/daemon/dist/domain/agent-activity-store.js.map +1 -1
  208. package/daemon/dist/domain/agent-images/agent-image-destination.d.ts +15 -0
  209. package/daemon/dist/domain/agent-images/agent-image-destination.d.ts.map +1 -0
  210. package/daemon/dist/domain/agent-images/agent-image-destination.js +79 -0
  211. package/daemon/dist/domain/agent-images/agent-image-destination.js.map +1 -0
  212. package/daemon/dist/domain/agent-images/agent-image-library-service.d.ts.map +1 -1
  213. package/daemon/dist/domain/agent-images/agent-image-library-service.js +9 -1
  214. package/daemon/dist/domain/agent-images/agent-image-library-service.js.map +1 -1
  215. package/daemon/dist/domain/bootstrap-orchestrator.d.ts +4 -3
  216. package/daemon/dist/domain/bootstrap-orchestrator.d.ts.map +1 -1
  217. package/daemon/dist/domain/bootstrap-orchestrator.js +55 -11
  218. package/daemon/dist/domain/bootstrap-orchestrator.js.map +1 -1
  219. package/daemon/dist/domain/bundle-content-routing.d.ts +7 -0
  220. package/daemon/dist/domain/bundle-content-routing.d.ts.map +1 -1
  221. package/daemon/dist/domain/bundle-content-routing.js +20 -15
  222. package/daemon/dist/domain/bundle-content-routing.js.map +1 -1
  223. package/daemon/dist/domain/claude-compaction-enforcer.d.ts +40 -1
  224. package/daemon/dist/domain/claude-compaction-enforcer.d.ts.map +1 -1
  225. package/daemon/dist/domain/claude-compaction-enforcer.js +101 -11
  226. package/daemon/dist/domain/claude-compaction-enforcer.js.map +1 -1
  227. package/daemon/dist/domain/claude-continuation-launch.d.ts +19 -2
  228. package/daemon/dist/domain/claude-continuation-launch.d.ts.map +1 -1
  229. package/daemon/dist/domain/claude-continuation-launch.js +143 -3
  230. package/daemon/dist/domain/claude-continuation-launch.js.map +1 -1
  231. package/daemon/dist/domain/claude-managed-launch.d.ts +22 -5
  232. package/daemon/dist/domain/claude-managed-launch.d.ts.map +1 -1
  233. package/daemon/dist/domain/claude-managed-launch.js +41 -5
  234. package/daemon/dist/domain/claude-managed-launch.js.map +1 -1
  235. package/daemon/dist/domain/claude-permission-rules.d.ts +3 -1
  236. package/daemon/dist/domain/claude-permission-rules.d.ts.map +1 -1
  237. package/daemon/dist/domain/claude-permission-rules.js +8 -7
  238. package/daemon/dist/domain/claude-permission-rules.js.map +1 -1
  239. package/daemon/dist/domain/claude-seat-token.d.ts +25 -1
  240. package/daemon/dist/domain/claude-seat-token.d.ts.map +1 -1
  241. package/daemon/dist/domain/claude-seat-token.js +56 -9
  242. package/daemon/dist/domain/claude-seat-token.js.map +1 -1
  243. package/daemon/dist/domain/codex-auth.d.ts +34 -0
  244. package/daemon/dist/domain/codex-auth.d.ts.map +1 -1
  245. package/daemon/dist/domain/codex-auth.js +212 -0
  246. package/daemon/dist/domain/codex-auth.js.map +1 -1
  247. package/daemon/dist/domain/codex-member-permissions.d.ts +17 -0
  248. package/daemon/dist/domain/codex-member-permissions.d.ts.map +1 -1
  249. package/daemon/dist/domain/codex-member-permissions.js +80 -0
  250. package/daemon/dist/domain/codex-member-permissions.js.map +1 -1
  251. package/daemon/dist/domain/community-harness-launch-result.d.ts +9 -0
  252. package/daemon/dist/domain/community-harness-launch-result.d.ts.map +1 -1
  253. package/daemon/dist/domain/community-harness-launch-result.js +14 -2
  254. package/daemon/dist/domain/community-harness-launch-result.js.map +1 -1
  255. package/daemon/dist/domain/community-harness-presets.d.ts +15 -0
  256. package/daemon/dist/domain/community-harness-presets.d.ts.map +1 -1
  257. package/daemon/dist/domain/community-harness-presets.js +82 -48
  258. package/daemon/dist/domain/community-harness-presets.js.map +1 -1
  259. package/daemon/dist/domain/compaction-restore-notice.d.ts +33 -5
  260. package/daemon/dist/domain/compaction-restore-notice.d.ts.map +1 -1
  261. package/daemon/dist/domain/compaction-restore-notice.js +221 -48
  262. package/daemon/dist/domain/compaction-restore-notice.js.map +1 -1
  263. package/daemon/dist/domain/context-usage-store.d.ts +1 -0
  264. package/daemon/dist/domain/context-usage-store.d.ts.map +1 -1
  265. package/daemon/dist/domain/context-usage-store.js +34 -3
  266. package/daemon/dist/domain/context-usage-store.js.map +1 -1
  267. package/daemon/dist/domain/crash-cart-detect.d.ts +7 -0
  268. package/daemon/dist/domain/crash-cart-detect.d.ts.map +1 -1
  269. package/daemon/dist/domain/crash-cart-detect.js +10 -5
  270. package/daemon/dist/domain/crash-cart-detect.js.map +1 -1
  271. package/daemon/dist/domain/crash-cart-discovery.d.ts +9 -16
  272. package/daemon/dist/domain/crash-cart-discovery.d.ts.map +1 -1
  273. package/daemon/dist/domain/crash-cart-discovery.js +22 -40
  274. package/daemon/dist/domain/crash-cart-discovery.js.map +1 -1
  275. package/daemon/dist/domain/crash-cart-emit.d.ts +1 -1
  276. package/daemon/dist/domain/crash-cart-emit.d.ts.map +1 -1
  277. package/daemon/dist/domain/crash-cart-emit.js +4 -0
  278. package/daemon/dist/domain/crash-cart-emit.js.map +1 -1
  279. package/daemon/dist/domain/current-park-arm.d.ts +2 -0
  280. package/daemon/dist/domain/current-park-arm.d.ts.map +1 -1
  281. package/daemon/dist/domain/current-park-arm.js +5 -0
  282. package/daemon/dist/domain/current-park-arm.js.map +1 -1
  283. package/daemon/dist/domain/current-work.d.ts +16 -4
  284. package/daemon/dist/domain/current-work.d.ts.map +1 -1
  285. package/daemon/dist/domain/current-work.js +3 -6
  286. package/daemon/dist/domain/current-work.js.map +1 -1
  287. package/daemon/dist/domain/cwd-resolution.d.ts +12 -1
  288. package/daemon/dist/domain/cwd-resolution.d.ts.map +1 -1
  289. package/daemon/dist/domain/cwd-resolution.js +39 -2
  290. package/daemon/dist/domain/cwd-resolution.js.map +1 -1
  291. package/daemon/dist/domain/draft-aware-delivery.d.ts +17 -2
  292. package/daemon/dist/domain/draft-aware-delivery.d.ts.map +1 -1
  293. package/daemon/dist/domain/draft-aware-delivery.js +98 -9
  294. package/daemon/dist/domain/draft-aware-delivery.js.map +1 -1
  295. package/daemon/dist/domain/draft-held-reoffer.d.ts +61 -0
  296. package/daemon/dist/domain/draft-held-reoffer.d.ts.map +1 -0
  297. package/daemon/dist/domain/draft-held-reoffer.js +143 -0
  298. package/daemon/dist/domain/draft-held-reoffer.js.map +1 -0
  299. package/daemon/dist/domain/execution-view.d.ts +20 -0
  300. package/daemon/dist/domain/execution-view.d.ts.map +1 -1
  301. package/daemon/dist/domain/execution-view.js +50 -16
  302. package/daemon/dist/domain/execution-view.js.map +1 -1
  303. package/daemon/dist/domain/gateway/destination-resolver.d.ts +10 -2
  304. package/daemon/dist/domain/gateway/destination-resolver.d.ts.map +1 -1
  305. package/daemon/dist/domain/gateway/destination-resolver.js +26 -3
  306. package/daemon/dist/domain/gateway/destination-resolver.js.map +1 -1
  307. package/daemon/dist/domain/gateway/slack/inbound.d.ts.map +1 -1
  308. package/daemon/dist/domain/gateway/slack/inbound.js +5 -4
  309. package/daemon/dist/domain/gateway/slack/inbound.js.map +1 -1
  310. package/daemon/dist/domain/gateway/slack/queue-access.js +1 -1
  311. package/daemon/dist/domain/gateway/slack/queue-access.js.map +1 -1
  312. package/daemon/dist/domain/generated-file-hygiene.d.ts.map +1 -1
  313. package/daemon/dist/domain/generated-file-hygiene.js +35 -2
  314. package/daemon/dist/domain/generated-file-hygiene.js.map +1 -1
  315. package/daemon/dist/domain/graph-projection.d.ts +7 -1
  316. package/daemon/dist/domain/graph-projection.d.ts.map +1 -1
  317. package/daemon/dist/domain/graph-projection.js +2 -0
  318. package/daemon/dist/domain/graph-projection.js.map +1 -1
  319. package/daemon/dist/domain/health-context-samples.d.ts +23 -0
  320. package/daemon/dist/domain/health-context-samples.d.ts.map +1 -0
  321. package/daemon/dist/domain/health-context-samples.js +113 -0
  322. package/daemon/dist/domain/health-context-samples.js.map +1 -0
  323. package/daemon/dist/domain/health-detectors.d.ts +3 -0
  324. package/daemon/dist/domain/health-detectors.d.ts.map +1 -1
  325. package/daemon/dist/domain/health-detectors.js +8 -7
  326. package/daemon/dist/domain/health-detectors.js.map +1 -1
  327. package/daemon/dist/domain/home-isolation.d.ts.map +1 -1
  328. package/daemon/dist/domain/home-isolation.js +21 -8
  329. package/daemon/dist/domain/home-isolation.js.map +1 -1
  330. package/daemon/dist/domain/hook-bridge.d.ts +7 -5
  331. package/daemon/dist/domain/hook-bridge.d.ts.map +1 -1
  332. package/daemon/dist/domain/hook-bridge.js +12 -11
  333. package/daemon/dist/domain/hook-bridge.js.map +1 -1
  334. package/daemon/dist/domain/kernel-boot-tracker.d.ts +7 -5
  335. package/daemon/dist/domain/kernel-boot-tracker.d.ts.map +1 -1
  336. package/daemon/dist/domain/kernel-boot-tracker.js +11 -6
  337. package/daemon/dist/domain/kernel-boot-tracker.js.map +1 -1
  338. package/daemon/dist/domain/kernel-boot.d.ts.map +1 -1
  339. package/daemon/dist/domain/kernel-boot.js +6 -2
  340. package/daemon/dist/domain/kernel-boot.js.map +1 -1
  341. package/daemon/dist/domain/kernel-hook-review.d.ts +10 -2
  342. package/daemon/dist/domain/kernel-hook-review.d.ts.map +1 -1
  343. package/daemon/dist/domain/kernel-hook-review.js +18 -4
  344. package/daemon/dist/domain/kernel-hook-review.js.map +1 -1
  345. package/daemon/dist/domain/managed-restore-read-access.d.ts +6 -2
  346. package/daemon/dist/domain/managed-restore-read-access.d.ts.map +1 -1
  347. package/daemon/dist/domain/managed-restore-read-access.js +35 -4
  348. package/daemon/dist/domain/managed-restore-read-access.js.map +1 -1
  349. package/daemon/dist/domain/mission-control/audit-browse.d.ts.map +1 -1
  350. package/daemon/dist/domain/mission-control/audit-browse.js +1 -0
  351. package/daemon/dist/domain/mission-control/audit-browse.js.map +1 -1
  352. package/daemon/dist/domain/mission-control/mission-control-action-log.d.ts +3 -1
  353. package/daemon/dist/domain/mission-control/mission-control-action-log.d.ts.map +1 -1
  354. package/daemon/dist/domain/mission-control/mission-control-action-log.js +7 -0
  355. package/daemon/dist/domain/mission-control/mission-control-action-log.js.map +1 -1
  356. package/daemon/dist/domain/mission-control/mission-control-write-contract.d.ts +3 -0
  357. package/daemon/dist/domain/mission-control/mission-control-write-contract.d.ts.map +1 -1
  358. package/daemon/dist/domain/mission-control/mission-control-write-contract.js +56 -13
  359. package/daemon/dist/domain/mission-control/mission-control-write-contract.js.map +1 -1
  360. package/daemon/dist/domain/mission-control/notification-adapter-from-env.d.ts +8 -0
  361. package/daemon/dist/domain/mission-control/notification-adapter-from-env.d.ts.map +1 -0
  362. package/daemon/dist/domain/mission-control/notification-adapter-from-env.js +17 -0
  363. package/daemon/dist/domain/mission-control/notification-adapter-from-env.js.map +1 -0
  364. package/daemon/dist/domain/model-divergence/codex-thread-homes.d.ts +12 -0
  365. package/daemon/dist/domain/model-divergence/codex-thread-homes.d.ts.map +1 -0
  366. package/daemon/dist/domain/model-divergence/codex-thread-homes.js +19 -0
  367. package/daemon/dist/domain/model-divergence/codex-thread-homes.js.map +1 -0
  368. package/daemon/dist/domain/native-process-arguments.d.ts +6 -3
  369. package/daemon/dist/domain/native-process-arguments.d.ts.map +1 -1
  370. package/daemon/dist/domain/native-process-arguments.js +56 -23
  371. package/daemon/dist/domain/native-process-arguments.js.map +1 -1
  372. package/daemon/dist/domain/native-resume-probe.d.ts +9 -0
  373. package/daemon/dist/domain/native-resume-probe.d.ts.map +1 -1
  374. package/daemon/dist/domain/native-resume-probe.js +15 -1
  375. package/daemon/dist/domain/native-resume-probe.js.map +1 -1
  376. package/daemon/dist/domain/network/hub-client.d.ts +14 -4
  377. package/daemon/dist/domain/network/hub-client.d.ts.map +1 -1
  378. package/daemon/dist/domain/network/hub-client.js +26 -9
  379. package/daemon/dist/domain/network/hub-client.js.map +1 -1
  380. package/daemon/dist/domain/network/network-connector.d.ts +2 -0
  381. package/daemon/dist/domain/network/network-connector.d.ts.map +1 -1
  382. package/daemon/dist/domain/network/network-connector.js +162 -16
  383. package/daemon/dist/domain/network/network-connector.js.map +1 -1
  384. package/daemon/dist/domain/network/network-requests.d.ts +4 -1
  385. package/daemon/dist/domain/network/network-requests.d.ts.map +1 -1
  386. package/daemon/dist/domain/network/network-requests.js +141 -14
  387. package/daemon/dist/domain/network/network-requests.js.map +1 -1
  388. package/daemon/dist/domain/node-inventory.d.ts +47 -0
  389. package/daemon/dist/domain/node-inventory.d.ts.map +1 -1
  390. package/daemon/dist/domain/node-inventory.js +270 -158
  391. package/daemon/dist/domain/node-inventory.js.map +1 -1
  392. package/daemon/dist/domain/node-launcher.d.ts +1 -0
  393. package/daemon/dist/domain/node-launcher.d.ts.map +1 -1
  394. package/daemon/dist/domain/node-launcher.js +13 -5
  395. package/daemon/dist/domain/node-launcher.js.map +1 -1
  396. package/daemon/dist/domain/outbox-handler.d.ts +66 -0
  397. package/daemon/dist/domain/outbox-handler.d.ts.map +1 -1
  398. package/daemon/dist/domain/outbox-handler.js +117 -8
  399. package/daemon/dist/domain/outbox-handler.js.map +1 -1
  400. package/daemon/dist/domain/pane-cutover.d.ts +6 -2
  401. package/daemon/dist/domain/pane-cutover.d.ts.map +1 -1
  402. package/daemon/dist/domain/pane-cutover.js +14 -4
  403. package/daemon/dist/domain/pane-cutover.js.map +1 -1
  404. package/daemon/dist/domain/parked-owner-escalation.d.ts +1 -0
  405. package/daemon/dist/domain/parked-owner-escalation.d.ts.map +1 -1
  406. package/daemon/dist/domain/parked-owner-escalation.js +3 -1
  407. package/daemon/dist/domain/parked-owner-escalation.js.map +1 -1
  408. package/daemon/dist/domain/parked-query.js +1 -1
  409. package/daemon/dist/domain/parked-query.js.map +1 -1
  410. package/daemon/dist/domain/permission-account.d.ts.map +1 -1
  411. package/daemon/dist/domain/permission-account.js +20 -1
  412. package/daemon/dist/domain/permission-account.js.map +1 -1
  413. package/daemon/dist/domain/policies/idle-gate-qitem.d.ts +1 -0
  414. package/daemon/dist/domain/policies/idle-gate-qitem.d.ts.map +1 -1
  415. package/daemon/dist/domain/policies/idle-gate-qitem.js +1 -0
  416. package/daemon/dist/domain/policies/idle-gate-qitem.js.map +1 -1
  417. package/daemon/dist/domain/policies/parked-owner-consumer.d.ts +21 -0
  418. package/daemon/dist/domain/policies/parked-owner-consumer.d.ts.map +1 -1
  419. package/daemon/dist/domain/policies/parked-owner-consumer.js +185 -26
  420. package/daemon/dist/domain/policies/parked-owner-consumer.js.map +1 -1
  421. package/daemon/dist/domain/policies/seat-pool.d.ts +2 -1
  422. package/daemon/dist/domain/policies/seat-pool.d.ts.map +1 -1
  423. package/daemon/dist/domain/policies/seat-pool.js.map +1 -1
  424. package/daemon/dist/domain/policies/workflow-keepalive.d.ts +1 -0
  425. package/daemon/dist/domain/policies/workflow-keepalive.d.ts.map +1 -1
  426. package/daemon/dist/domain/policies/workflow-keepalive.js +4 -1
  427. package/daemon/dist/domain/policies/workflow-keepalive.js.map +1 -1
  428. package/daemon/dist/domain/profile-resolver.d.ts +2 -0
  429. package/daemon/dist/domain/profile-resolver.d.ts.map +1 -1
  430. package/daemon/dist/domain/profile-resolver.js +10 -4
  431. package/daemon/dist/domain/profile-resolver.js.map +1 -1
  432. package/daemon/dist/domain/project-lifecycle-compiler.d.ts.map +1 -1
  433. package/daemon/dist/domain/project-lifecycle-compiler.js +35 -1
  434. package/daemon/dist/domain/project-lifecycle-compiler.js.map +1 -1
  435. package/daemon/dist/domain/proof/judgments.d.ts +7 -0
  436. package/daemon/dist/domain/proof/judgments.d.ts.map +1 -1
  437. package/daemon/dist/domain/proof/judgments.js +18 -10
  438. package/daemon/dist/domain/proof/judgments.js.map +1 -1
  439. package/daemon/dist/domain/provider/assignment-apply.d.ts +85 -0
  440. package/daemon/dist/domain/provider/assignment-apply.d.ts.map +1 -0
  441. package/daemon/dist/domain/provider/assignment-apply.js +270 -0
  442. package/daemon/dist/domain/provider/assignment-apply.js.map +1 -0
  443. package/daemon/dist/domain/provider/assignment-plan.d.ts +150 -0
  444. package/daemon/dist/domain/provider/assignment-plan.d.ts.map +1 -0
  445. package/daemon/dist/domain/provider/assignment-plan.js +218 -0
  446. package/daemon/dist/domain/provider/assignment-plan.js.map +1 -0
  447. package/daemon/dist/domain/provider/claude-seat-switch.d.ts +1 -1
  448. package/daemon/dist/domain/provider/claude-seat-switch.d.ts.map +1 -1
  449. package/daemon/dist/domain/provider/claude-seat-switch.js +37 -6
  450. package/daemon/dist/domain/provider/claude-seat-switch.js.map +1 -1
  451. package/daemon/dist/domain/provider/provider-account-assignments.d.ts +64 -0
  452. package/daemon/dist/domain/provider/provider-account-assignments.d.ts.map +1 -0
  453. package/daemon/dist/domain/provider/provider-account-assignments.js +75 -0
  454. package/daemon/dist/domain/provider/provider-account-assignments.js.map +1 -0
  455. package/daemon/dist/domain/provider/provider-account-refs.d.ts +91 -0
  456. package/daemon/dist/domain/provider/provider-account-refs.d.ts.map +1 -0
  457. package/daemon/dist/domain/provider/provider-account-refs.js +164 -0
  458. package/daemon/dist/domain/provider/provider-account-refs.js.map +1 -0
  459. package/daemon/dist/domain/provider/provider-collect.d.ts +3 -1
  460. package/daemon/dist/domain/provider/provider-collect.d.ts.map +1 -1
  461. package/daemon/dist/domain/provider/provider-collect.js +2 -0
  462. package/daemon/dist/domain/provider/provider-collect.js.map +1 -1
  463. package/daemon/dist/domain/provider/provider-service-impl.d.ts +43 -1
  464. package/daemon/dist/domain/provider/provider-service-impl.d.ts.map +1 -1
  465. package/daemon/dist/domain/provider/provider-service-impl.js +376 -20
  466. package/daemon/dist/domain/provider/provider-service-impl.js.map +1 -1
  467. package/daemon/dist/domain/provider/provider-service.d.ts +82 -6
  468. package/daemon/dist/domain/provider/provider-service.d.ts.map +1 -1
  469. package/daemon/dist/domain/provider/provider-types.d.ts +40 -1
  470. package/daemon/dist/domain/provider/provider-types.d.ts.map +1 -1
  471. package/daemon/dist/domain/provider/usage-across-hosts.d.ts.map +1 -1
  472. package/daemon/dist/domain/provider/usage-across-hosts.js +13 -1
  473. package/daemon/dist/domain/provider/usage-across-hosts.js.map +1 -1
  474. package/daemon/dist/domain/ps-projection.d.ts +5 -3
  475. package/daemon/dist/domain/ps-projection.d.ts.map +1 -1
  476. package/daemon/dist/domain/ps-projection.js +10 -3
  477. package/daemon/dist/domain/ps-projection.js.map +1 -1
  478. package/daemon/dist/domain/queue-display.d.ts +7 -0
  479. package/daemon/dist/domain/queue-display.d.ts.map +1 -0
  480. package/daemon/dist/domain/queue-display.js +20 -0
  481. package/daemon/dist/domain/queue-display.js.map +1 -0
  482. package/daemon/dist/domain/queue-owner.d.ts +4 -2
  483. package/daemon/dist/domain/queue-owner.d.ts.map +1 -1
  484. package/daemon/dist/domain/queue-owner.js +7 -5
  485. package/daemon/dist/domain/queue-owner.js.map +1 -1
  486. package/daemon/dist/domain/queue-repository.d.ts +104 -24
  487. package/daemon/dist/domain/queue-repository.d.ts.map +1 -1
  488. package/daemon/dist/domain/queue-repository.js +600 -89
  489. package/daemon/dist/domain/queue-repository.js.map +1 -1
  490. package/daemon/dist/domain/queue-stuck-sweep.d.ts +4 -0
  491. package/daemon/dist/domain/queue-stuck-sweep.d.ts.map +1 -1
  492. package/daemon/dist/domain/queue-stuck-sweep.js +1890 -1817
  493. package/daemon/dist/domain/queue-stuck-sweep.js.map +1 -1
  494. package/daemon/dist/domain/queue-transfer-activation.d.ts +28 -0
  495. package/daemon/dist/domain/queue-transfer-activation.d.ts.map +1 -0
  496. package/daemon/dist/domain/queue-transfer-activation.js +187 -0
  497. package/daemon/dist/domain/queue-transfer-activation.js.map +1 -0
  498. package/daemon/dist/domain/queue-transfer-mapping.d.ts +31 -0
  499. package/daemon/dist/domain/queue-transfer-mapping.d.ts.map +1 -0
  500. package/daemon/dist/domain/queue-transfer-mapping.js +33 -0
  501. package/daemon/dist/domain/queue-transfer-mapping.js.map +1 -0
  502. package/daemon/dist/domain/queue-transfer-operation.d.ts +24 -0
  503. package/daemon/dist/domain/queue-transfer-operation.d.ts.map +1 -0
  504. package/daemon/dist/domain/queue-transfer-operation.js +41 -0
  505. package/daemon/dist/domain/queue-transfer-operation.js.map +1 -0
  506. package/daemon/dist/domain/queue-transfer-parse.d.ts +8 -0
  507. package/daemon/dist/domain/queue-transfer-parse.d.ts.map +1 -1
  508. package/daemon/dist/domain/queue-transfer-parse.js +16 -6
  509. package/daemon/dist/domain/queue-transfer-parse.js.map +1 -1
  510. package/daemon/dist/domain/queue-transfer-records.d.ts +160 -0
  511. package/daemon/dist/domain/queue-transfer-records.d.ts.map +1 -0
  512. package/daemon/dist/domain/queue-transfer-records.js +94 -0
  513. package/daemon/dist/domain/queue-transfer-records.js.map +1 -0
  514. package/daemon/dist/domain/queue-transfer-recovery.d.ts +40 -0
  515. package/daemon/dist/domain/queue-transfer-recovery.d.ts.map +1 -0
  516. package/daemon/dist/domain/queue-transfer-recovery.js +136 -0
  517. package/daemon/dist/domain/queue-transfer-recovery.js.map +1 -0
  518. package/daemon/dist/domain/queue-transfer-relinquish.d.ts +70 -0
  519. package/daemon/dist/domain/queue-transfer-relinquish.d.ts.map +1 -0
  520. package/daemon/dist/domain/queue-transfer-relinquish.js +204 -0
  521. package/daemon/dist/domain/queue-transfer-relinquish.js.map +1 -0
  522. package/daemon/dist/domain/queue-transfer-review.d.ts +1 -0
  523. package/daemon/dist/domain/queue-transfer-review.d.ts.map +1 -1
  524. package/daemon/dist/domain/queue-transfer-review.js +15 -13
  525. package/daemon/dist/domain/queue-transfer-review.js.map +1 -1
  526. package/daemon/dist/domain/queue-transfer-staging.d.ts +14 -0
  527. package/daemon/dist/domain/queue-transfer-staging.d.ts.map +1 -1
  528. package/daemon/dist/domain/queue-transfer-staging.js +9 -1
  529. package/daemon/dist/domain/queue-transfer-staging.js.map +1 -1
  530. package/daemon/dist/domain/queue-transfer-write.d.ts +14 -0
  531. package/daemon/dist/domain/queue-transfer-write.d.ts.map +1 -0
  532. package/daemon/dist/domain/queue-transfer-write.js +42 -0
  533. package/daemon/dist/domain/queue-transfer-write.js.map +1 -0
  534. package/daemon/dist/domain/queue-transition-log.d.ts +8 -0
  535. package/daemon/dist/domain/queue-transition-log.d.ts.map +1 -1
  536. package/daemon/dist/domain/queue-transition-log.js +27 -14
  537. package/daemon/dist/domain/queue-transition-log.js.map +1 -1
  538. package/daemon/dist/domain/queue-waiting.d.ts +10 -1
  539. package/daemon/dist/domain/queue-waiting.d.ts.map +1 -1
  540. package/daemon/dist/domain/queue-waiting.js +20 -14
  541. package/daemon/dist/domain/queue-waiting.js.map +1 -1
  542. package/daemon/dist/domain/queue-wake-ladder.d.ts +10 -3
  543. package/daemon/dist/domain/queue-wake-ladder.d.ts.map +1 -1
  544. package/daemon/dist/domain/queue-wake-ladder.js +60 -23
  545. package/daemon/dist/domain/queue-wake-ladder.js.map +1 -1
  546. package/daemon/dist/domain/queue-wake-repository.d.ts +1 -0
  547. package/daemon/dist/domain/queue-wake-repository.d.ts.map +1 -1
  548. package/daemon/dist/domain/queue-wake-repository.js +21 -19
  549. package/daemon/dist/domain/queue-wake-repository.js.map +1 -1
  550. package/daemon/dist/domain/receiver-context.d.ts +3 -2
  551. package/daemon/dist/domain/receiver-context.d.ts.map +1 -1
  552. package/daemon/dist/domain/receiver-context.js +5 -4
  553. package/daemon/dist/domain/receiver-context.js.map +1 -1
  554. package/daemon/dist/domain/reconciler.d.ts +2 -0
  555. package/daemon/dist/domain/reconciler.d.ts.map +1 -1
  556. package/daemon/dist/domain/reconciler.js +17 -1
  557. package/daemon/dist/domain/reconciler.js.map +1 -1
  558. package/daemon/dist/domain/relayed-answers.d.ts +1 -0
  559. package/daemon/dist/domain/relayed-answers.d.ts.map +1 -1
  560. package/daemon/dist/domain/relayed-answers.js.map +1 -1
  561. package/daemon/dist/domain/restore-check-service.d.ts.map +1 -1
  562. package/daemon/dist/domain/restore-check-service.js +9 -3
  563. package/daemon/dist/domain/restore-check-service.js.map +1 -1
  564. package/daemon/dist/domain/restore-orchestrator.d.ts +7 -0
  565. package/daemon/dist/domain/restore-orchestrator.d.ts.map +1 -1
  566. package/daemon/dist/domain/restore-orchestrator.js +54 -14
  567. package/daemon/dist/domain/restore-orchestrator.js.map +1 -1
  568. package/daemon/dist/domain/return-route.d.ts +4 -0
  569. package/daemon/dist/domain/return-route.d.ts.map +1 -1
  570. package/daemon/dist/domain/return-route.js +13 -0
  571. package/daemon/dist/domain/return-route.js.map +1 -1
  572. package/daemon/dist/domain/rig-mode/operating-posture.d.ts +3 -0
  573. package/daemon/dist/domain/rig-mode/operating-posture.d.ts.map +1 -1
  574. package/daemon/dist/domain/rig-mode/operating-posture.js +27 -8
  575. package/daemon/dist/domain/rig-mode/operating-posture.js.map +1 -1
  576. package/daemon/dist/domain/rig-status-compose.d.ts +3 -0
  577. package/daemon/dist/domain/rig-status-compose.d.ts.map +1 -1
  578. package/daemon/dist/domain/rig-status-compose.js +4 -1
  579. package/daemon/dist/domain/rig-status-compose.js.map +1 -1
  580. package/daemon/dist/domain/rig-teardown.d.ts.map +1 -1
  581. package/daemon/dist/domain/rig-teardown.js +3 -2
  582. package/daemon/dist/domain/rig-teardown.js.map +1 -1
  583. package/daemon/dist/domain/rigspec-exporter.d.ts +2 -0
  584. package/daemon/dist/domain/rigspec-exporter.d.ts.map +1 -1
  585. package/daemon/dist/domain/rigspec-exporter.js +38 -2
  586. package/daemon/dist/domain/rigspec-exporter.js.map +1 -1
  587. package/daemon/dist/domain/rigspec-instantiator.d.ts +4 -1
  588. package/daemon/dist/domain/rigspec-instantiator.d.ts.map +1 -1
  589. package/daemon/dist/domain/rigspec-instantiator.js +32 -13
  590. package/daemon/dist/domain/rigspec-instantiator.js.map +1 -1
  591. package/daemon/dist/domain/rigspec-preflight.d.ts +3 -0
  592. package/daemon/dist/domain/rigspec-preflight.d.ts.map +1 -1
  593. package/daemon/dist/domain/rigspec-preflight.js +25 -7
  594. package/daemon/dist/domain/rigspec-preflight.js.map +1 -1
  595. package/daemon/dist/domain/roster-ready-notice.d.ts +1 -1
  596. package/daemon/dist/domain/roster-ready-notice.d.ts.map +1 -1
  597. package/daemon/dist/domain/roster-ready-notice.js +2 -1
  598. package/daemon/dist/domain/roster-ready-notice.js.map +1 -1
  599. package/daemon/dist/domain/runner-permissions.d.ts +3 -2
  600. package/daemon/dist/domain/runner-permissions.d.ts.map +1 -1
  601. package/daemon/dist/domain/runner-permissions.js +30 -19
  602. package/daemon/dist/domain/runner-permissions.js.map +1 -1
  603. package/daemon/dist/domain/runtime-adapter.d.ts +2 -0
  604. package/daemon/dist/domain/runtime-adapter.d.ts.map +1 -1
  605. package/daemon/dist/domain/runtime-adapter.js.map +1 -1
  606. package/daemon/dist/domain/scope/manifest-editor.d.ts +35 -0
  607. package/daemon/dist/domain/scope/manifest-editor.d.ts.map +1 -0
  608. package/daemon/dist/domain/scope/manifest-editor.js +197 -0
  609. package/daemon/dist/domain/scope/manifest-editor.js.map +1 -0
  610. package/daemon/dist/domain/scope/mission-frontmatter.d.ts +9 -0
  611. package/daemon/dist/domain/scope/mission-frontmatter.d.ts.map +1 -0
  612. package/daemon/dist/domain/scope/mission-frontmatter.js +36 -0
  613. package/daemon/dist/domain/scope/mission-frontmatter.js.map +1 -0
  614. package/daemon/dist/domain/seat-activity-service.d.ts.map +1 -1
  615. package/daemon/dist/domain/seat-activity-service.js +53 -20
  616. package/daemon/dist/domain/seat-activity-service.js.map +1 -1
  617. package/daemon/dist/domain/seat-cold-start.d.ts +8 -2
  618. package/daemon/dist/domain/seat-cold-start.d.ts.map +1 -1
  619. package/daemon/dist/domain/seat-cold-start.js +75 -19
  620. package/daemon/dist/domain/seat-cold-start.js.map +1 -1
  621. package/daemon/dist/domain/seat-delivery-guard.d.ts +6 -1
  622. package/daemon/dist/domain/seat-delivery-guard.d.ts.map +1 -1
  623. package/daemon/dist/domain/seat-delivery-guard.js +23 -2
  624. package/daemon/dist/domain/seat-delivery-guard.js.map +1 -1
  625. package/daemon/dist/domain/seat-evidence.d.ts +13 -0
  626. package/daemon/dist/domain/seat-evidence.d.ts.map +1 -0
  627. package/daemon/dist/domain/seat-evidence.js +29 -0
  628. package/daemon/dist/domain/seat-evidence.js.map +1 -0
  629. package/daemon/dist/domain/seat-handover-service.d.ts +5 -1
  630. package/daemon/dist/domain/seat-handover-service.d.ts.map +1 -1
  631. package/daemon/dist/domain/seat-handover-service.js +49 -35
  632. package/daemon/dist/domain/seat-handover-service.js.map +1 -1
  633. package/daemon/dist/domain/seat-lifecycle-service.d.ts +26 -6
  634. package/daemon/dist/domain/seat-lifecycle-service.d.ts.map +1 -1
  635. package/daemon/dist/domain/seat-lifecycle-service.js +108 -17
  636. package/daemon/dist/domain/seat-lifecycle-service.js.map +1 -1
  637. package/daemon/dist/domain/seat-pool-dispatch-guard.d.ts +28 -0
  638. package/daemon/dist/domain/seat-pool-dispatch-guard.d.ts.map +1 -0
  639. package/daemon/dist/domain/seat-pool-dispatch-guard.js +123 -0
  640. package/daemon/dist/domain/seat-pool-dispatch-guard.js.map +1 -0
  641. package/daemon/dist/domain/seat-pool-executor.d.ts +64 -3
  642. package/daemon/dist/domain/seat-pool-executor.d.ts.map +1 -1
  643. package/daemon/dist/domain/seat-pool-executor.js +993 -102
  644. package/daemon/dist/domain/seat-pool-executor.js.map +1 -1
  645. package/daemon/dist/domain/seat-pool-slots.d.ts +90 -2
  646. package/daemon/dist/domain/seat-pool-slots.d.ts.map +1 -1
  647. package/daemon/dist/domain/seat-pool-slots.js +88 -3
  648. package/daemon/dist/domain/seat-pool-slots.js.map +1 -1
  649. package/daemon/dist/domain/seat-pool-spec.d.ts +4 -1
  650. package/daemon/dist/domain/seat-pool-spec.d.ts.map +1 -1
  651. package/daemon/dist/domain/seat-pool-spec.js +14 -2
  652. package/daemon/dist/domain/seat-pool-spec.js.map +1 -1
  653. package/daemon/dist/domain/seat-reaper-eligibility.d.ts +34 -0
  654. package/daemon/dist/domain/seat-reaper-eligibility.d.ts.map +1 -0
  655. package/daemon/dist/domain/seat-reaper-eligibility.js +30 -0
  656. package/daemon/dist/domain/seat-reaper-eligibility.js.map +1 -0
  657. package/daemon/dist/domain/seat-reaper-events.d.ts +31 -0
  658. package/daemon/dist/domain/seat-reaper-events.d.ts.map +1 -0
  659. package/daemon/dist/domain/seat-reaper-events.js +2 -0
  660. package/daemon/dist/domain/seat-reaper-events.js.map +1 -0
  661. package/daemon/dist/domain/seat-reaper-service.d.ts +59 -0
  662. package/daemon/dist/domain/seat-reaper-service.d.ts.map +1 -0
  663. package/daemon/dist/domain/seat-reaper-service.js +311 -0
  664. package/daemon/dist/domain/seat-reaper-service.js.map +1 -0
  665. package/daemon/dist/domain/seat-reaper-settings.d.ts +14 -0
  666. package/daemon/dist/domain/seat-reaper-settings.d.ts.map +1 -0
  667. package/daemon/dist/domain/seat-reaper-settings.js +32 -0
  668. package/daemon/dist/domain/seat-reaper-settings.js.map +1 -0
  669. package/daemon/dist/domain/seat-reaper-store.d.ts +19 -0
  670. package/daemon/dist/domain/seat-reaper-store.d.ts.map +1 -0
  671. package/daemon/dist/domain/seat-reaper-store.js +45 -0
  672. package/daemon/dist/domain/seat-reaper-store.js.map +1 -0
  673. package/daemon/dist/domain/seat-reaper-workspace.d.ts +4 -0
  674. package/daemon/dist/domain/seat-reaper-workspace.d.ts.map +1 -0
  675. package/daemon/dist/domain/seat-reaper-workspace.js +43 -0
  676. package/daemon/dist/domain/seat-reaper-workspace.js.map +1 -0
  677. package/daemon/dist/domain/seat-restart-in-place.d.ts +11 -3
  678. package/daemon/dist/domain/seat-restart-in-place.d.ts.map +1 -1
  679. package/daemon/dist/domain/seat-restart-in-place.js +39 -48
  680. package/daemon/dist/domain/seat-restart-in-place.js.map +1 -1
  681. package/daemon/dist/domain/seat-runtime-switch-service.d.ts.map +1 -1
  682. package/daemon/dist/domain/seat-runtime-switch-service.js +5 -7
  683. package/daemon/dist/domain/seat-runtime-switch-service.js.map +1 -1
  684. package/daemon/dist/domain/seat-skill-storage.d.ts.map +1 -1
  685. package/daemon/dist/domain/seat-skill-storage.js +27 -5
  686. package/daemon/dist/domain/seat-skill-storage.js.map +1 -1
  687. package/daemon/dist/domain/seat-standby.d.ts +13 -0
  688. package/daemon/dist/domain/seat-standby.d.ts.map +1 -0
  689. package/daemon/dist/domain/seat-standby.js +21 -0
  690. package/daemon/dist/domain/seat-standby.js.map +1 -0
  691. package/daemon/dist/domain/seat-startup-text.d.ts +159 -0
  692. package/daemon/dist/domain/seat-startup-text.d.ts.map +1 -0
  693. package/daemon/dist/domain/seat-startup-text.js +200 -0
  694. package/daemon/dist/domain/seat-startup-text.js.map +1 -0
  695. package/daemon/dist/domain/seat-status-service.d.ts +18 -0
  696. package/daemon/dist/domain/seat-status-service.d.ts.map +1 -1
  697. package/daemon/dist/domain/seat-status-service.js +25 -5
  698. package/daemon/dist/domain/seat-status-service.js.map +1 -1
  699. package/daemon/dist/domain/seat-structural-activity-service.d.ts +7 -0
  700. package/daemon/dist/domain/seat-structural-activity-service.d.ts.map +1 -1
  701. package/daemon/dist/domain/seat-structural-activity-service.js +16 -1
  702. package/daemon/dist/domain/seat-structural-activity-service.js.map +1 -1
  703. package/daemon/dist/domain/session-registry.d.ts +15 -3
  704. package/daemon/dist/domain/session-registry.d.ts.map +1 -1
  705. package/daemon/dist/domain/session-registry.js +52 -5
  706. package/daemon/dist/domain/session-registry.js.map +1 -1
  707. package/daemon/dist/domain/session-transport.d.ts +12 -5
  708. package/daemon/dist/domain/session-transport.d.ts.map +1 -1
  709. package/daemon/dist/domain/session-transport.js +129 -18
  710. package/daemon/dist/domain/session-transport.js.map +1 -1
  711. package/daemon/dist/domain/shared-conversation.d.ts.map +1 -1
  712. package/daemon/dist/domain/shared-conversation.js +3 -1
  713. package/daemon/dist/domain/shared-conversation.js.map +1 -1
  714. package/daemon/dist/domain/slices/slice-indexer.d.ts +2 -2
  715. package/daemon/dist/domain/slices/slice-indexer.d.ts.map +1 -1
  716. package/daemon/dist/domain/slices/slice-indexer.js +4 -15
  717. package/daemon/dist/domain/slices/slice-indexer.js.map +1 -1
  718. package/daemon/dist/domain/snapshot-capture.d.ts +4 -1
  719. package/daemon/dist/domain/snapshot-capture.d.ts.map +1 -1
  720. package/daemon/dist/domain/snapshot-capture.js +14 -18
  721. package/daemon/dist/domain/snapshot-capture.js.map +1 -1
  722. package/daemon/dist/domain/snapshot-repository.d.ts +37 -0
  723. package/daemon/dist/domain/snapshot-repository.d.ts.map +1 -1
  724. package/daemon/dist/domain/snapshot-repository.js +68 -0
  725. package/daemon/dist/domain/snapshot-repository.js.map +1 -1
  726. package/daemon/dist/domain/startup-orchestrator.d.ts +8 -20
  727. package/daemon/dist/domain/startup-orchestrator.d.ts.map +1 -1
  728. package/daemon/dist/domain/startup-orchestrator.js +94 -27
  729. package/daemon/dist/domain/startup-orchestrator.js.map +1 -1
  730. package/daemon/dist/domain/startup-submission-evidence.d.ts +4 -1
  731. package/daemon/dist/domain/startup-submission-evidence.d.ts.map +1 -1
  732. package/daemon/dist/domain/startup-submission-evidence.js +12 -1
  733. package/daemon/dist/domain/startup-submission-evidence.js.map +1 -1
  734. package/daemon/dist/domain/successor-session-launcher.d.ts +9 -5
  735. package/daemon/dist/domain/successor-session-launcher.d.ts.map +1 -1
  736. package/daemon/dist/domain/successor-session-launcher.js +17 -6
  737. package/daemon/dist/domain/successor-session-launcher.js.map +1 -1
  738. package/daemon/dist/domain/terminal/earlier-tile-attach-0724.d.ts +2 -0
  739. package/daemon/dist/domain/terminal/earlier-tile-attach-0724.d.ts.map +1 -0
  740. package/daemon/dist/domain/terminal/earlier-tile-attach-0724.js +54 -0
  741. package/daemon/dist/domain/terminal/earlier-tile-attach-0724.js.map +1 -0
  742. package/daemon/dist/domain/terminal/herdr-app-provider.d.ts +28 -3
  743. package/daemon/dist/domain/terminal/herdr-app-provider.d.ts.map +1 -1
  744. package/daemon/dist/domain/terminal/herdr-app-provider.js +216 -52
  745. package/daemon/dist/domain/terminal/herdr-app-provider.js.map +1 -1
  746. package/daemon/dist/domain/terminal/herdr-app-state.d.ts +7 -2
  747. package/daemon/dist/domain/terminal/herdr-app-state.d.ts.map +1 -1
  748. package/daemon/dist/domain/terminal/herdr-app-state.js.map +1 -1
  749. package/daemon/dist/domain/terminal/terminal-provider.d.ts +17 -0
  750. package/daemon/dist/domain/terminal/terminal-provider.d.ts.map +1 -1
  751. package/daemon/dist/domain/terminal/tile-attach.d.ts +4 -4
  752. package/daemon/dist/domain/terminal/tile-attach.d.ts.map +1 -1
  753. package/daemon/dist/domain/terminal/tile-attach.js +14 -8
  754. package/daemon/dist/domain/terminal/tile-attach.js.map +1 -1
  755. package/daemon/dist/domain/types.d.ts +71 -4
  756. package/daemon/dist/domain/types.d.ts.map +1 -1
  757. package/daemon/dist/domain/types.js.map +1 -1
  758. package/daemon/dist/domain/usage-samples-store.d.ts.map +1 -1
  759. package/daemon/dist/domain/usage-samples-store.js.map +1 -1
  760. package/daemon/dist/domain/user-settings/settings-store.d.ts +1 -1
  761. package/daemon/dist/domain/user-settings/settings-store.d.ts.map +1 -1
  762. package/daemon/dist/domain/user-settings/settings-store.js +45 -2
  763. package/daemon/dist/domain/user-settings/settings-store.js.map +1 -1
  764. package/daemon/dist/domain/view-projector.d.ts.map +1 -1
  765. package/daemon/dist/domain/view-projector.js +5 -2
  766. package/daemon/dist/domain/view-projector.js.map +1 -1
  767. package/daemon/dist/domain/watchdog-delivery.d.ts +3 -0
  768. package/daemon/dist/domain/watchdog-delivery.d.ts.map +1 -1
  769. package/daemon/dist/domain/watchdog-delivery.js +26 -4
  770. package/daemon/dist/domain/watchdog-delivery.js.map +1 -1
  771. package/daemon/dist/domain/watchdog-history-log.d.ts +10 -0
  772. package/daemon/dist/domain/watchdog-history-log.d.ts.map +1 -1
  773. package/daemon/dist/domain/watchdog-history-log.js +35 -1
  774. package/daemon/dist/domain/watchdog-history-log.js.map +1 -1
  775. package/daemon/dist/domain/watchdog-job-update.d.ts.map +1 -1
  776. package/daemon/dist/domain/watchdog-job-update.js +29 -4
  777. package/daemon/dist/domain/watchdog-job-update.js.map +1 -1
  778. package/daemon/dist/domain/watchdog-policy-engine.d.ts.map +1 -1
  779. package/daemon/dist/domain/watchdog-policy-engine.js +4 -1
  780. package/daemon/dist/domain/watchdog-policy-engine.js.map +1 -1
  781. package/daemon/dist/domain/watchdog-scheduler.d.ts +4 -0
  782. package/daemon/dist/domain/watchdog-scheduler.d.ts.map +1 -1
  783. package/daemon/dist/domain/watchdog-scheduler.js +14 -0
  784. package/daemon/dist/domain/watchdog-scheduler.js.map +1 -1
  785. package/daemon/dist/domain/workflow-role-context.d.ts.map +1 -1
  786. package/daemon/dist/domain/workflow-role-context.js +1 -0
  787. package/daemon/dist/domain/workflow-role-context.js.map +1 -1
  788. package/daemon/dist/domain/workflow-role-resolver.d.ts +3 -0
  789. package/daemon/dist/domain/workflow-role-resolver.d.ts.map +1 -1
  790. package/daemon/dist/domain/workflow-role-resolver.js +12 -6
  791. package/daemon/dist/domain/workflow-role-resolver.js.map +1 -1
  792. package/daemon/dist/domain/workspace/project-catalog.d.ts +7 -0
  793. package/daemon/dist/domain/workspace/project-catalog.d.ts.map +1 -1
  794. package/daemon/dist/domain/workspace/project-catalog.js +16 -9
  795. package/daemon/dist/domain/workspace/project-catalog.js.map +1 -1
  796. package/daemon/dist/domain/workspace/project-registration.d.ts +5 -1
  797. package/daemon/dist/domain/workspace/project-registration.d.ts.map +1 -1
  798. package/daemon/dist/domain/workspace/project-registration.js +11 -7
  799. package/daemon/dist/domain/workspace/project-registration.js.map +1 -1
  800. package/daemon/dist/index.d.ts +3 -0
  801. package/daemon/dist/index.d.ts.map +1 -1
  802. package/daemon/dist/index.js +14 -4
  803. package/daemon/dist/index.js.map +1 -1
  804. package/daemon/dist/middleware/auth-bearer-token.d.ts +8 -12
  805. package/daemon/dist/middleware/auth-bearer-token.d.ts.map +1 -1
  806. package/daemon/dist/middleware/auth-bearer-token.js +18 -36
  807. package/daemon/dist/middleware/auth-bearer-token.js.map +1 -1
  808. package/daemon/dist/queue-transfer-records-surface.d.ts +6 -0
  809. package/daemon/dist/queue-transfer-records-surface.d.ts.map +1 -0
  810. package/daemon/dist/queue-transfer-records-surface.js +6 -0
  811. package/daemon/dist/queue-transfer-records-surface.js.map +1 -0
  812. package/daemon/dist/rig-lookup-surface.d.ts +2 -0
  813. package/daemon/dist/rig-lookup-surface.d.ts.map +1 -0
  814. package/daemon/dist/rig-lookup-surface.js +5 -0
  815. package/daemon/dist/rig-lookup-surface.js.map +1 -0
  816. package/daemon/dist/routes/activity.d.ts.map +1 -1
  817. package/daemon/dist/routes/activity.js +4 -3
  818. package/daemon/dist/routes/activity.js.map +1 -1
  819. package/daemon/dist/routes/attention.d.ts.map +1 -1
  820. package/daemon/dist/routes/attention.js +3 -1
  821. package/daemon/dist/routes/attention.js.map +1 -1
  822. package/daemon/dist/routes/compaction.d.ts.map +1 -1
  823. package/daemon/dist/routes/compaction.js +2 -0
  824. package/daemon/dist/routes/compaction.js.map +1 -1
  825. package/daemon/dist/routes/mission-control.d.ts.map +1 -1
  826. package/daemon/dist/routes/mission-control.js +2 -1
  827. package/daemon/dist/routes/mission-control.js.map +1 -1
  828. package/daemon/dist/routes/missions.d.ts +3 -6
  829. package/daemon/dist/routes/missions.d.ts.map +1 -1
  830. package/daemon/dist/routes/missions.js +42 -76
  831. package/daemon/dist/routes/missions.js.map +1 -1
  832. package/daemon/dist/routes/network.d.ts.map +1 -1
  833. package/daemon/dist/routes/network.js +19 -1
  834. package/daemon/dist/routes/network.js.map +1 -1
  835. package/daemon/dist/routes/provider.d.ts.map +1 -1
  836. package/daemon/dist/routes/provider.js +156 -5
  837. package/daemon/dist/routes/provider.js.map +1 -1
  838. package/daemon/dist/routes/queue-transfer.d.ts +9 -0
  839. package/daemon/dist/routes/queue-transfer.d.ts.map +1 -0
  840. package/daemon/dist/routes/queue-transfer.js +109 -0
  841. package/daemon/dist/routes/queue-transfer.js.map +1 -0
  842. package/daemon/dist/routes/queue.d.ts.map +1 -1
  843. package/daemon/dist/routes/queue.js +80 -51
  844. package/daemon/dist/routes/queue.js.map +1 -1
  845. package/daemon/dist/routes/rigs.js +3 -0
  846. package/daemon/dist/routes/rigs.js.map +1 -1
  847. package/daemon/dist/routes/rigspec.d.ts.map +1 -1
  848. package/daemon/dist/routes/rigspec.js +4 -0
  849. package/daemon/dist/routes/rigspec.js.map +1 -1
  850. package/daemon/dist/routes/seat.d.ts.map +1 -1
  851. package/daemon/dist/routes/seat.js +19 -3
  852. package/daemon/dist/routes/seat.js.map +1 -1
  853. package/daemon/dist/routes/terminal-ws.d.ts +0 -5
  854. package/daemon/dist/routes/terminal-ws.d.ts.map +1 -1
  855. package/daemon/dist/routes/terminal-ws.js +0 -6
  856. package/daemon/dist/routes/terminal-ws.js.map +1 -1
  857. package/daemon/dist/routes/transport.js +1 -1
  858. package/daemon/dist/routes/transport.js.map +1 -1
  859. package/daemon/dist/scope-manifest-surface.d.ts +4 -0
  860. package/daemon/dist/scope-manifest-surface.d.ts.map +1 -0
  861. package/daemon/dist/scope-manifest-surface.js +4 -0
  862. package/daemon/dist/scope-manifest-surface.js.map +1 -0
  863. package/daemon/dist/server.d.ts +2 -1
  864. package/daemon/dist/server.d.ts.map +1 -1
  865. package/daemon/dist/server.js +6 -6
  866. package/daemon/dist/server.js.map +1 -1
  867. package/daemon/dist/startup.d.ts.map +1 -1
  868. package/daemon/dist/startup.js +126 -61
  869. package/daemon/dist/startup.js.map +1 -1
  870. package/daemon/docs/reference/agent-startup-guide.md +26 -4
  871. package/daemon/docs/reference/agent-state-taxonomy.md +22 -1
  872. package/daemon/docs/reference/claude-status-line.md +28 -0
  873. package/daemon/docs/reference/community-harness-examples/hermes/hermes.yaml +3 -0
  874. package/daemon/docs/reference/community-harness-examples/hermes/openrig-hermes-launch +10 -0
  875. package/daemon/docs/reference/community-harness-presets.md +79 -8
  876. package/daemon/docs/reference/daemon-http-clients.md +49 -2
  877. package/daemon/docs/reference/getting-started.md +73 -11
  878. package/daemon/docs/reference/harness-runner-contract.md +12 -4
  879. package/daemon/docs/reference/help.md +9 -0
  880. package/daemon/docs/reference/herdr-app.md +45 -4
  881. package/daemon/docs/reference/hosted-members.md +1 -1
  882. package/daemon/docs/reference/network-connector.md +66 -1
  883. package/daemon/docs/reference/pi-tool-selection-recovery.md +13 -29
  884. package/daemon/docs/reference/queue-transfer-activation.md +89 -0
  885. package/daemon/docs/reference/queue-transfer-staging.md +1 -1
  886. package/daemon/docs/reference/quickstart.md +4 -4
  887. package/daemon/docs/reference/refocus-channel.md +21 -0
  888. package/daemon/docs/reference/rig-bundle.md +25 -0
  889. package/daemon/docs/reference/rig-spec.md +218 -23
  890. package/daemon/docs/reference/scoped-operating-posture.md +6 -1
  891. package/daemon/docs/reference/sdlc-conventions.md +10 -4
  892. package/daemon/docs/reference/seat-delivery.md +108 -12
  893. package/daemon/docs/reference/seat-node-targeting.md +2 -2
  894. package/daemon/docs/reference/seat-pools.md +181 -18
  895. package/daemon/docs/reference/seat-scaling.md +137 -0
  896. package/daemon/docs/reference/whats-new.md +190 -14
  897. package/daemon/specs/agents/development/implementer/guidance/role.md +11 -0
  898. package/daemon/specs/agents/development/qa/guidance/role.md +5 -0
  899. package/daemon/specs/agents/shared/skills/core/cross-host-rig-commands/SKILL.md +9 -1
  900. package/daemon/specs/agents/shared/skills/core/working-with-an-openrig-team/SKILL.md +32 -19
  901. package/daemon/specs/rigs/launch/kernel/agents/operator/agent/guidance/role.md +8 -3
  902. package/dist/build-info.js +3 -3
  903. package/dist/cli-error.d.ts +2 -0
  904. package/dist/cli-error.d.ts.map +1 -1
  905. package/dist/cli-error.js +25 -8
  906. package/dist/cli-error.js.map +1 -1
  907. package/dist/client.d.ts +1 -0
  908. package/dist/client.d.ts.map +1 -1
  909. package/dist/client.js +13 -0
  910. package/dist/client.js.map +1 -1
  911. package/dist/commands/auth.d.ts.map +1 -1
  912. package/dist/commands/auth.js +52 -1
  913. package/dist/commands/auth.js.map +1 -1
  914. package/dist/commands/config.d.ts.map +1 -1
  915. package/dist/commands/config.js +3 -0
  916. package/dist/commands/config.js.map +1 -1
  917. package/dist/commands/crash-cart.d.ts.map +1 -1
  918. package/dist/commands/crash-cart.js +65 -17
  919. package/dist/commands/crash-cart.js.map +1 -1
  920. package/dist/commands/daemon.d.ts +7 -20
  921. package/dist/commands/daemon.d.ts.map +1 -1
  922. package/dist/commands/daemon.js +117 -46
  923. package/dist/commands/daemon.js.map +1 -1
  924. package/dist/commands/doctor.d.ts +26 -0
  925. package/dist/commands/doctor.d.ts.map +1 -1
  926. package/dist/commands/doctor.js +148 -2
  927. package/dist/commands/doctor.js.map +1 -1
  928. package/dist/commands/import.d.ts +5 -0
  929. package/dist/commands/import.d.ts.map +1 -1
  930. package/dist/commands/import.js +24 -4
  931. package/dist/commands/import.js.map +1 -1
  932. package/dist/commands/mcp.d.ts.map +1 -1
  933. package/dist/commands/mcp.js +4 -2
  934. package/dist/commands/mcp.js.map +1 -1
  935. package/dist/commands/network.d.ts +4 -0
  936. package/dist/commands/network.d.ts.map +1 -1
  937. package/dist/commands/network.js +78 -10
  938. package/dist/commands/network.js.map +1 -1
  939. package/dist/commands/provider.d.ts +5 -1
  940. package/dist/commands/provider.d.ts.map +1 -1
  941. package/dist/commands/provider.js +427 -17
  942. package/dist/commands/provider.js.map +1 -1
  943. package/dist/commands/ps.d.ts +16 -1
  944. package/dist/commands/ps.d.ts.map +1 -1
  945. package/dist/commands/ps.js +35 -4
  946. package/dist/commands/ps.js.map +1 -1
  947. package/dist/commands/queue-transfer.d.ts +10 -0
  948. package/dist/commands/queue-transfer.d.ts.map +1 -0
  949. package/dist/commands/queue-transfer.js +140 -0
  950. package/dist/commands/queue-transfer.js.map +1 -0
  951. package/dist/commands/queue.d.ts.map +1 -1
  952. package/dist/commands/queue.js +20 -6
  953. package/dist/commands/queue.js.map +1 -1
  954. package/dist/commands/scope.d.ts.map +1 -1
  955. package/dist/commands/scope.js +258 -17
  956. package/dist/commands/scope.js.map +1 -1
  957. package/dist/commands/seat.d.ts.map +1 -1
  958. package/dist/commands/seat.js +132 -23
  959. package/dist/commands/seat.js.map +1 -1
  960. package/dist/commands/setup.d.ts +34 -0
  961. package/dist/commands/setup.d.ts.map +1 -1
  962. package/dist/commands/setup.js +111 -18
  963. package/dist/commands/setup.js.map +1 -1
  964. package/dist/commands/terminal.d.ts +11 -0
  965. package/dist/commands/terminal.d.ts.map +1 -1
  966. package/dist/commands/terminal.js +10 -7
  967. package/dist/commands/terminal.js.map +1 -1
  968. package/dist/config-store.d.ts +9 -1
  969. package/dist/config-store.d.ts.map +1 -1
  970. package/dist/config-store.js +46 -0
  971. package/dist/config-store.js.map +1 -1
  972. package/dist/daemon-lifecycle.d.ts +53 -2
  973. package/dist/daemon-lifecycle.d.ts.map +1 -1
  974. package/dist/daemon-lifecycle.js +500 -192
  975. package/dist/daemon-lifecycle.js.map +1 -1
  976. package/dist/daemon-reachability.js +2 -2
  977. package/dist/daemon-reachability.js.map +1 -1
  978. package/dist/daemon-start-lock.d.ts +28 -0
  979. package/dist/daemon-start-lock.d.ts.map +1 -1
  980. package/dist/daemon-start-lock.js +107 -13
  981. package/dist/daemon-start-lock.js.map +1 -1
  982. package/dist/lib/seat-activity.d.ts +4 -1
  983. package/dist/lib/seat-activity.d.ts.map +1 -1
  984. package/dist/lib/seat-activity.js +4 -3
  985. package/dist/lib/seat-activity.js.map +1 -1
  986. package/dist/mcp-server.d.ts +2 -2
  987. package/dist/mcp-server.d.ts.map +1 -1
  988. package/dist/mcp-server.js +126 -27
  989. package/dist/mcp-server.js.map +1 -1
  990. package/dist/process-liveness.d.ts +21 -0
  991. package/dist/process-liveness.d.ts.map +1 -0
  992. package/dist/process-liveness.js +43 -0
  993. package/dist/process-liveness.js.map +1 -0
  994. package/dist/remote-host-ops.d.ts +1 -1
  995. package/dist/remote-host-ops.d.ts.map +1 -1
  996. package/dist/remote-host-ops.js +3 -14
  997. package/dist/remote-host-ops.js.map +1 -1
  998. package/dist/system-preflight.d.ts +9 -0
  999. package/dist/system-preflight.d.ts.map +1 -1
  1000. package/dist/system-preflight.js +27 -8
  1001. package/dist/system-preflight.js.map +1 -1
  1002. package/dist/tmux-health.d.ts +10 -1
  1003. package/dist/tmux-health.d.ts.map +1 -1
  1004. package/dist/tmux-health.js +31 -2
  1005. package/dist/tmux-health.js.map +1 -1
  1006. package/package.json +4 -2
  1007. package/scripts/check-abi.mjs +18 -2
  1008. package/tui/dist/attention/attention-model.d.ts +1 -1
  1009. package/tui/dist/attention/attention-model.d.ts.map +1 -1
  1010. package/tui/dist/attention/attention-model.js +6 -0
  1011. package/tui/dist/attention/attention-model.js.map +1 -1
  1012. package/tui/dist/daemon-client.d.ts +21 -2
  1013. package/tui/dist/daemon-client.d.ts.map +1 -1
  1014. package/tui/dist/daemon-client.js +36 -5
  1015. package/tui/dist/daemon-client.js.map +1 -1
  1016. package/tui/dist/hydrate.d.ts.map +1 -1
  1017. package/tui/dist/hydrate.js +6 -2
  1018. package/tui/dist/hydrate.js.map +1 -1
  1019. package/tui/dist/main.js +11 -8
  1020. package/tui/dist/main.js.map +1 -1
  1021. package/tui/dist/terminals/open-window.d.ts +9 -3
  1022. package/tui/dist/terminals/open-window.d.ts.map +1 -1
  1023. package/tui/dist/terminals/open-window.js +22 -4
  1024. package/tui/dist/terminals/open-window.js.map +1 -1
  1025. package/tui/dist/terminals/terminal-model.d.ts +3 -0
  1026. package/tui/dist/terminals/terminal-model.d.ts.map +1 -1
  1027. package/tui/dist/terminals/terminal-model.js +6 -1
  1028. package/tui/dist/terminals/terminal-model.js.map +1 -1
  1029. package/tui/dist/topology/glyphs.d.ts.map +1 -1
  1030. package/tui/dist/topology/glyphs.js +11 -1
  1031. package/tui/dist/topology/glyphs.js.map +1 -1
  1032. package/tui/dist/topology/graph-types.d.ts +8 -0
  1033. package/tui/dist/topology/graph-types.d.ts.map +1 -1
  1034. package/tui/dist/types.d.ts +3 -2
  1035. package/tui/dist/types.d.ts.map +1 -1
  1036. package/ui/dist/assets/{index-DG_7XFcL.js → index-D7OUklzs.js} +148 -148
  1037. package/ui/dist/index.html +1 -1
@@ -464,7 +464,7 @@ function isRosterNotice(item) {
464
464
  return isRosterReadyNotice({ qitem_id: item.qitemId, source_session: item.sourceSession });
465
465
  }
466
466
  /** Rows no finding is filed about: the sweep's own findings, which self-exclude by their stamp tag, and OpenRig's
467
- * roster-ready notice, which is information about the team, not work. Its wake is still retried like any row's. */
467
+ * roster-ready notice, which is information about the team, not work. Any already-owed wake keeps its recovery path. */
468
468
  function isSweepExempt(item) {
469
469
  return isFindingRow(item) || isRosterNotice(item);
470
470
  }
@@ -587,7 +587,37 @@ export function custodyHeadline(rowId, targets, ageMinutes) {
587
587
  ? `Custody not checked on host ${hosts.join(", ")} for ${rowId} (${ageMinutes} min)`
588
588
  : `Custody not checked: no successor of ${rowId} in this store (${ageMinutes} min)`;
589
589
  }
590
- function evidenceBody(db, c, personNotice = false) {
590
+ /** #331: what's already known about the seat a finding names, as it stood when the finding was written. These are
591
+ * observations for the reader to weigh, never a cause: an unread value is unknown, and a context percentage says whether
592
+ * it's used or remaining and when it was sampled, since a bare figure can't show a full context. Empty when nothing is
593
+ * read for findings or the destination isn't a seat. */
594
+ function seatEvidenceLines(session, read, now) {
595
+ if (!read)
596
+ return "";
597
+ let evidence;
598
+ try {
599
+ evidence = read(session);
600
+ }
601
+ catch {
602
+ evidence = { heldMessages: null, context: null };
603
+ }
604
+ if (!evidence)
605
+ return "";
606
+ const held = evidence.heldMessages === null ? "unknown (couldn't be read)"
607
+ : evidence.heldMessages === 0 ? "none" : `${evidence.heldMessages} (rig seat held-messages ${session})`;
608
+ const c = evidence.context;
609
+ const percent = (value) => `${Math.round(value * 10) / 10}%`;
610
+ const parts = c && c.availability === "known"
611
+ ? [c.usedPercentage !== null ? `${percent(c.usedPercentage)} used` : null, c.remainingPercentage !== null ? `${percent(c.remainingPercentage)} remaining` : null]
612
+ .filter((part) => part !== null)
613
+ : [];
614
+ const context = parts.length === 0 || !c ? `unknown${c?.reason ? ` (${c.reason})` : ""}`
615
+ : `${parts.join(", ")}, ${c.sampledAt ? `sampled ${c.sampledAt}` : "sample time unknown"}${c.source ? ` from ${c.source}` : ""}${c.fresh ? "" : ", not fresh"}`;
616
+ return `seat ${session} as known at ${now.toISOString()} (observations, not a diagnosis):\n` +
617
+ `- messages held for it: ${held}\n` +
618
+ `- context: ${context}\n`;
619
+ }
620
+ function evidenceBody(db, c, personNotice = false, seatEvidence = "") {
591
621
  if (c.verificationTargets?.length) {
592
622
  const checks = c.verificationTargets
593
623
  .map((target) => `- ${target}\n ${verificationCommand(target)}\n` +
@@ -612,6 +642,7 @@ function evidenceBody(db, c, personNotice = false) {
612
642
  `age: ${c.ageMinutes} min\n` +
613
643
  `last transition: ${lastTransitionLine(db, c.row.qitemId)}\n` +
614
644
  `why: ${c.why}\n` +
645
+ seatEvidence +
615
646
  (personNotice
616
647
  ? `This is a notice from OpenRig, not a task for you: ${c.row.qitemId} is waiting for ${c.row.destinationSession}, which couldn't ` +
617
648
  `be woken (why, above). It reaches ${c.row.destinationSession} only when a wake lands there, and the sweep closes this notice ` +
@@ -721,6 +752,30 @@ function polledBacklogText(member, rows, thresholdMinutes, checkIn, now) {
721
752
  `${BACKLOG_ROWS_PREFIX}${JSON.stringify(sorted.map((r) => r.qitemId))}`,
722
753
  };
723
754
  }
755
+ /** The standing notice for a person's own conversation at the address OpenRig issued it (#3964). OpenRig doesn't see the
756
+ * conversation's reads, so it says only what OpenRig knows: nobody has claimed these rows. Built from the rows' fixed facts. */
757
+ /** `attached`: a seat joined with `rig attach` as an external CLI, which reads its queue from the outside program it runs in. */
758
+ function conversationBacklogText(address, rows, thresholdMinutes, kind = "conversation") {
759
+ const { sorted, listed, count } = backlogListing(rows);
760
+ const attached = kind === "attached";
761
+ return {
762
+ summary: backlogTitle(`${address}'s work`, rows.length),
763
+ body: `STUCK SWEEP FINDING (unclaimed-backlog)\n` +
764
+ (attached
765
+ ? `seat: ${address} (a seat attached from an outside program with rig attach: no wake is sent to it, and it picks up ` +
766
+ `work when that program reads its own queue)\n`
767
+ : `conversation: ${address} (an address OpenRig issued to a person's own conversation, not a seat: no wake is sent to it, ` +
768
+ `and it picks up work when it reads its own queue)\n`) +
769
+ `unclaimed: ${count} (the threshold is ${thresholdMinutes} min)\n` +
770
+ `${listed.join("\n")}\n` +
771
+ `why: nobody has claimed these rows, and OpenRig can't tell whether ${attached ? "that program" : "the conversation"} has read them: only a claim shows ` +
772
+ `it picked one up. ${attached ? "Ask whoever runs that program to check it" : "Ask its person to check that conversation"}, or route the work to another seat. This one notice ` +
773
+ `stands for these rows instead of a finding per row, and follows them as they come and go.\n` +
774
+ `List them: rig queue list --destination ${address} --state pending\n` +
775
+ `The sweep closes this notice itself once every row it stands for is claimed, parked or closed.\n` +
776
+ `${BACKLOG_ROWS_PREFIX}${JSON.stringify(sorted.map((r) => r.qitemId))}`,
777
+ };
778
+ }
724
779
  /** The rows a standing notice's body says it stands for, or null when the line is missing or unreadable: unknown, which is
725
780
  * never read as "none". */
726
781
  function backlogRowsOf(body) {
@@ -772,594 +827,599 @@ function defaultIsQueueOnlySeat(db) {
772
827
  };
773
828
  }
774
829
  export async function runStuckSweep(deps) {
775
- const log = deps.log ?? ((line) => console.error(line));
776
- const status = deps.status;
777
- try {
778
- const now = deps.now ?? new Date();
779
- // One recovery index and one linked-successor read per stretch of the pass, instead of one json_each scan per
780
- // candidate and per custody row. Each is a snapshot that is only valid while no other code runs, so both are
781
- // dropped (and rebuilt on the next lookup) after every yield and every awaited write.
782
- const recoveries = createRecoveryLookup(deps.db);
783
- const isQueueOnlySeat = deps.isQueueOnlySeat ?? defaultIsQueueOnlySeat(deps.db);
784
- let successors = null;
785
- // Every yield and every awaited write lets other code run: indexes read before it are dropped, and `othersRan`
786
- // tells a list read before it that its rows need a fresh read.
787
- let othersRan = 0;
788
- /** Each seat's agent-seat reading (agentSeatNode, below), dropped with the indexes: another writer can declare a
789
- * seat's delegation parent while the pass yields or awaits a write. */
790
- const agentSeats = new Map();
791
- /** #2988: each seat's one declared delegation parent (parentNow, below), dropped with agentSeats. */
792
- const parentsNow = new Map();
793
- /** Hosted polling-member status (pollsForWork, below), dropped on every yield or awaited write. */
794
- const pollingMembers = new Map();
795
- /** Configured operator recovery seats (routeAroundMissing, below), dropped on every yield or awaited write. */
796
- let recoverySeats;
797
- const othersMayHaveRun = () => {
798
- othersRan++;
799
- recoveries.invalidate();
800
- successors?.invalidate();
801
- agentSeats.clear();
802
- parentsNow.clear();
803
- pollingMembers.clear();
804
- recoverySeats = undefined;
805
- };
806
- // A successor index whose build took at least half of a stretch that yielded by elapsed time is not rebuilt for
807
- // the rest of the pass: the yield drops it, the next stretch would pay the build again and end the same way after a
808
- // few rows, so the rows would pay about one build each instead of one per STUCK_SWEEP_YIELD_EVERY_ROWS. Those rows
809
- // ask their own narrow query (hasLinkedSuccessor), which costs less than a rebuilt index.
810
- let successorsPerRow = false;
811
- // A synchronous read with both indexes lent to what it calls deep inside (a getById's waiting view and handoff
812
- // advisory ask the same questions per row). Never spans an await: the lend ends when fn returns.
813
- const indexed = (fn) => recoveries.run(() => (successors && !successorsPerRow ? successors.run(fn) : fn()));
814
- // `if (dueToYield()) await yieldLoop();` and never a bare await per row: even an await that does not yield lets
815
- // queued microtasks (other requests' continuations) run and write between two rows the snapshot still covers.
816
- let rowsSinceYield = 0;
817
- let lastYieldAt = performance.now();
818
- const dueToYield = () => ++rowsSinceYield >= STUCK_SWEEP_YIELD_EVERY_ROWS || performance.now() - lastYieldAt >= STUCK_SWEEP_YIELD_AFTER_MS;
819
- const yieldLoop = async () => {
820
- const stretchMs = performance.now() - lastYieldAt;
821
- successorsPerRow ||= successors !== null && stretchMs >= STUCK_SWEEP_YIELD_AFTER_MS && 2 * successors.builtMs() >= stretchMs;
822
- rowsSinceYield = 0;
823
- await new Promise((resolve) => setImmediate(resolve));
824
- lastYieldAt = performance.now();
825
- othersMayHaveRun();
826
- };
827
- const suppressionMinutes = deps.ladderSuppressionMinutes ?? resolveLadderSuppressionMinutes();
828
- /** The dedup tags of the candidates the LADDER suppressed in this pass, and only those:
829
- * a row the ladder alone would have stopped. A finding for such a row stays open,
830
- * because the marker only ever stopped the re-report — it never resolved anything.
831
- * Other delivery/pickup findings still need source evidence before closure. */
832
- const suppressedTags = new Set();
833
- const ageMinutes = deps.unclaimedAgeMinutes ?? resolveStuckSweepUnclaimedAgeMinutes();
834
- const routeNotes = new Map();
835
- const routed = new Set();
836
- /** #2988: the row's route was its seat's one declared delegation parent (resolveEscalationOwner outcome "parent"). */
837
- const delegationParent = new Map();
838
- const resolveOrch = (session, row) => {
839
- if (hasConsumedEscalationHop(deps.db, row.qitemId)) {
840
- routeNotes.set(row.qitemId, "escalates_to one-hop delivery already used; existing fallback retained");
841
- return null;
842
- }
843
- if (deps.resolveOrchestrator)
844
- return deps.resolveOrchestrator(session);
845
- const route = resolveEscalationOwner(deps.db, session, target => deps.queueRepo.acceptsDestination(target));
846
- if (route.outcome !== "none" && route.outcome !== "parent")
847
- routeNotes.set(row.qitemId, route.reason);
848
- if (route.outcome === "routed")
849
- routed.add(row.qitemId);
850
- if (route.outcome === "parent" && route.owner)
851
- delegationParent.set(row.qitemId, route.owner);
852
- else
853
- delegationParent.delete(row.qitemId);
854
- return route.owner;
855
- };
856
- const isRegisteredHost = deps.isRegisteredHost ?? defaultIsRegisteredHost(log);
857
- const candidates = [];
858
- const deliveryHeld = (row) => deps.queueRepo.deliveryDrains.holds(row.destinationSession);
859
- const nowIso = now.toISOString();
860
- // SQLite's LIKE ignores ASCII case; the per-row rules below match the queries they stand in for.
861
- const startsWithCI = (value, prefix) => (value ?? "").toLowerCase().startsWith(prefix);
862
- // Each kind's rule for ONE row, applied to the row as it is now. The loops below enumerate the rows; the same
863
- // rules run again on a fresh read right before a finding is created (stillStuck), because a pass that yields
864
- // cannot trust what it read before the yield: a claim, a delivered wake, a moved deadline, a note or a new
865
- // successor may have landed since.
866
- // Half 1 — claimed-never-closed. The claimant holds the obligation; the finding
867
- // routes to them.
868
- const overdueCandidate = (row) => {
869
- if (isSweepExempt(row))
870
- return null;
871
- return {
872
- kind: "overdue-claim",
873
- row,
874
- route: row.destinationSession,
875
- ageMinutes: minutesSince(row.closureRequiredAt ?? row.claimedAt, now),
876
- evidenceAt: latestIso(lastMeaningfulTransition(deps.db, row.qitemId)?.at, row.closureRequiredAt, row.claimedAt),
877
- why: "claimed and past closure_required_at with no closure",
830
+ const run = async () => {
831
+ const log = deps.log ?? ((line) => console.error(line));
832
+ const status = deps.status;
833
+ try {
834
+ const now = deps.now ?? new Date();
835
+ // One recovery index and one linked-successor read per stretch of the pass, instead of one json_each scan per
836
+ // candidate and per custody row. Each is a snapshot that is only valid while no other code runs, so both are
837
+ // dropped (and rebuilt on the next lookup) after every yield and every awaited write.
838
+ const recoveries = createRecoveryLookup(deps.db);
839
+ const isQueueOnlySeat = deps.isQueueOnlySeat ?? defaultIsQueueOnlySeat(deps.db);
840
+ let successors = null;
841
+ // Every yield and every awaited write lets other code run: indexes read before it are dropped, and `othersRan`
842
+ // tells a list read before it that its rows need a fresh read.
843
+ let othersRan = 0;
844
+ /** Each seat's agent-seat reading (agentSeatNode, below), dropped with the indexes: another writer can declare a
845
+ * seat's delegation parent while the pass yields or awaits a write. */
846
+ const agentSeats = new Map();
847
+ /** #2988: each seat's one declared delegation parent (parentNow, below), dropped with agentSeats. */
848
+ const parentsNow = new Map();
849
+ /** Whether a destination polls for its work (pollsForWork, below), dropped on every yield or awaited write. */
850
+ const pollingMembers = new Map();
851
+ /** Configured operator recovery seats (routeAroundMissing, below), dropped on every yield or awaited write. */
852
+ let recoverySeats;
853
+ const othersMayHaveRun = () => {
854
+ othersRan++;
855
+ recoveries.invalidate();
856
+ successors?.invalidate();
857
+ agentSeats.clear();
858
+ parentsNow.clear();
859
+ pollingMembers.clear();
860
+ recoverySeats = undefined;
878
861
  };
879
- };
880
- // S04 seam — a claimed row with no later motion past the pickup threshold. The
881
- // pickup module remains the ONE derivation rule; this only enumerates and routes.
882
- const stalledCandidate = (qitemId) => {
883
- const row = indexed(() => deps.queueRepo.getById(qitemId, { waiting: false }));
884
- if (!row || isSweepExempt(row))
885
- return null;
886
- if ((row.state !== "pending" && row.state !== "in-progress") || !row.claimedAt)
887
- return null;
888
- const stalled = stalledPickupFinding(row);
889
- if (!stalled)
890
- return null;
891
- // Keep this null arm for the 0.5.7 mechanized-pull turn-end hook that knows the in-flight row;
892
- // it is the first honest row-scoped writer, and wiring reopens only in that slice.
893
- const evidenceAt = latestIso(lastMeaningfulTransition(deps.db, row.qitemId)?.at, row.lastHeartbeat, row.claimedAt);
894
- return {
895
- kind: stalled.kind,
896
- row,
897
- route: resolveOrch(stalled.target, row) ?? stalled.target,
898
- // The stall's own age: from the anchor the pickup decision uses, floored as its "why" counts, so a claim
899
- // parked and resumed doesn't count its parked time and the headline matches the why to the minute.
900
- ageMinutes: wholeMinutesSince(evidenceAt, now),
901
- evidenceAt,
902
- why: stalled.evidence,
862
+ // A successor index whose build took at least half of a stretch that yielded by elapsed time is not rebuilt for
863
+ // the rest of the pass: the yield drops it, the next stretch would pay the build again and end the same way after a
864
+ // few rows, so the rows would pay about one build each instead of one per STUCK_SWEEP_YIELD_EVERY_ROWS. Those rows
865
+ // ask their own narrow query (hasLinkedSuccessor), which costs less than a rebuilt index.
866
+ let successorsPerRow = false;
867
+ // A synchronous read with both indexes lent to what it calls deep inside (a getById's waiting view and handoff
868
+ // advisory ask the same questions per row). Never spans an await: the lend ends when fn returns.
869
+ const indexed = (fn) => recoveries.run(() => (successors && !successorsPerRow ? successors.run(fn) : fn()));
870
+ // `if (dueToYield()) await yieldLoop();` and never a bare await per row: even an await that does not yield lets
871
+ // queued microtasks (other requests' continuations) run and write between two rows the snapshot still covers.
872
+ let rowsSinceYield = 0;
873
+ let lastYieldAt = performance.now();
874
+ const dueToYield = () => ++rowsSinceYield >= STUCK_SWEEP_YIELD_EVERY_ROWS || performance.now() - lastYieldAt >= STUCK_SWEEP_YIELD_AFTER_MS;
875
+ const yieldLoop = async () => {
876
+ const stretchMs = performance.now() - lastYieldAt;
877
+ successorsPerRow ||= successors !== null && stretchMs >= STUCK_SWEEP_YIELD_AFTER_MS && 2 * successors.builtMs() >= stretchMs;
878
+ rowsSinceYield = 0;
879
+ await new Promise((resolve) => setImmediate(resolve));
880
+ lastYieldAt = performance.now();
881
+ othersMayHaveRun();
903
882
  };
904
- };
905
- // The timer delivered one transition-specific notice (or recorded a failed
906
- // attempt). This existing sweep owns its bounded recovery, not another full
907
- // packet or a parked-owner replay. A real owner response ends the occurrence.
908
- const waitCandidate = (jobId) => {
909
- const job = deps.db.prepare("SELECT spec_yaml FROM watchdog_jobs WHERE job_id = ? AND state = 'active' AND policy = 'periodic-reminder'")
910
- .get(jobId);
911
- const notice = job ? queueWaitNotice(job.spec_yaml) : null;
912
- if (!notice || now.getTime() - Date.parse(notice.at) <= resolvePickupThresholdMinutes() * 60_000)
913
- return null;
914
- const binding = deps.db.prepare("SELECT qitem_id FROM queue_transition_wakes WHERE wake_ref = ? AND phase = 'armed' ORDER BY transition_id DESC LIMIT 1").get(jobId);
915
- const row = binding ? indexed(() => deps.queueRepo.getById(binding.qitem_id, { waiting: false })) : null;
916
- if (!row || row.state !== "blocked" || deps.queueRepo.getParkWakeStatus(row.qitemId)?.ref !== jobId)
917
- return null;
918
- const response = lastMeaningfulTransition(deps.db, row.qitemId);
919
- if (response && Date.parse(response.at) > Date.parse(notice.at))
920
- return null;
921
- // A queue-only seat's wait notice (#3076) was noted on the row or became a queue row, with no nudge: held and
922
- // readable at the seat, for a person or its next turn, not stuck. A finding would be a poller compensating.
923
- if (isQueueOnlyDeliveryCode(notice.deliveryStatus))
924
- return null;
925
- const ownerActivity = deps.queueRepo.ownerActivity(row.destinationSession);
926
- if (ownerActivity?.activity === "working" && !ownerActivity.needsInput.count && notice.deliveryStatus === "ok")
927
- return null;
928
- return { kind: "unconsumed-wait", row, route: resolveOrch(row.destinationSession, row) ?? row.sourceSession,
929
- ageMinutes: minutesSince(notice.at, now), evidenceAt: notice.at, jobId,
930
- why: `wait notice delivery=${notice.deliveryStatus}; no later owner response; activity=${ownerActivity?.activity ?? "unknown"}; inspect exact blocker ${row.blockedOn}` };
931
- };
932
- // The parked policy stops repeating a positively no-input failure. Unhealthy blocked rows
933
- // have no retry ladder: the same sweep/recovery route owns their actionable disposition.
934
- const parkedCandidate = (qitemId) => {
935
- const row = indexed(() => deps.queueRepo.getById(qitemId, { waiting: false }));
936
- if (!row || isSweepExempt(row))
937
- return null;
938
- if (row.state !== "blocked" || !startsWithCI(row.lastNudgeResult, "failed:"))
939
- return null;
940
- const wake = deps.queueRepo.getParkWakeStatus(qitemId);
941
- if ((wake?.live === true && (!wake.unconsumed || wake.recoveryOwner === "queue-stuck-sweep"))
942
- || deps.queueRepo.parkWakeServedByOwnReminder(qitemId))
943
- return null;
944
- const transitions = deps.queueRepo.listTransitions(qitemId);
945
- const failure = currentParkedOwnerNoInputFailure(transitions);
946
- if (!failure)
947
- return null;
948
- // A queue-only agent seat (#3076) holds OpenRig's reminders on purpose, as the parked policy skips it: an earlier
949
- // refusal there is no input to fix, from the switch on, before that policy runs again.
950
- if (isQueueOnlySeat(row.destinationSession) && !isBoundTerminalSeat(deps.db, row.destinationSession))
951
- return null;
952
- // Another seat's incidental note is not the owner's response. This kind follows
953
- // the parked policy's owner-or-state-change rule, leaving other sweep kinds alone.
954
- if (transitions.some((t, i) => t.transitionId > (failure.transitionId ?? Number.POSITIVE_INFINITY)
955
- && (t.actorSession === row.destinationSession || t.state !== transitions[i - 1]?.state)))
956
- return null;
957
- return { kind: "parked-owner-no-input", row, route: resolveOrch(row.destinationSession, row) ?? row.sourceSession,
958
- ageMinutes: minutesSince(failure.ts, now), evidenceAt: failure.ts,
959
- why: `Automated parked-owner reminder refused before input (${failure.code}); repeated input stopped. Inspect the retained quota/guard or route terminal work to an agent. Original blocker remains ${row.blockedOn}` };
960
- };
961
- // Half 2 — sender-believed-delivered-never-woken. Nobody holds it (the wake failed),
962
- // so it routes to the destination's orchestrator when one is derivable. Rows with a
963
- // live S01 ladder are S01's territory; an exhausted ladder is the handback and lands
964
- // here exactly once (the dedup tag keeps it to one finding).
965
- // A wake recorded unroutable because the seat's pane wasn't bound yet (#2151). Once its binding exists, deliver the
966
- // row's own wake intent instead of reporting it: the intent is claimed and settled, so a startup drain doesn't send it
967
- // again, and one already in flight or settled isn't sent twice. The next tick reads the new result, so a failed send
968
- // is reported then. A row with a live retry ladder is left to the ladder.
969
- // The rule is shared with the reachable-seat retry; a live retry ladder is this sweep's own check.
970
- const wakeToRetry = (row) => deps.queueRepo.unroutableWakeRetryable(row, now)
971
- && !hasLiveLadder(deps.db, row.qitemId, now, suppressionMinutes);
972
- const isHumanNotice = (row) => row.deliveryOutcome === "never-posted" || row.deliveryOutcome === "transport-failed";
973
- // A hosted member with no wake trigger picks up its work by reading the queue: nothing can push work to it, by design.
974
- // Its rows' unroutable wakes aren't failed deliveries, so they get no finding each; work it leaves unclaimed past the
975
- // unclaimed age is listed in the member's one standing notice instead. Refreshed after every yield or awaited write.
976
- const pollsForWork = (session) => {
977
- let polls = pollingMembers.get(session);
978
- if (polls === undefined) {
979
- polls = deps.queueRepo.isHostedMember(session) && deps.queueRepo.classifyDestinationOf(session).class === "unroutable";
980
- pollingMembers.set(session, polls);
981
- }
982
- return polls;
983
- };
984
- const polledRow = (row) => recordsNoWakeRoute(row.lastNudgeResult) && pollsForWork(row.destinationSession);
985
- /** `row` comes from findUndelivered (it carries the delivery verdict). Call it after any wake retry the row needs. */
986
- const undeliveredCandidate = (row, recordSuppression) => {
987
- if (isSweepExempt(row))
988
- return null;
989
- const humanNotice = isHumanNotice(row);
990
- // A claim supersedes a retained failed wake, including on a row returned to
991
- // pending. Its pickup finding must not be replaced by that historical failure;
992
- // a separate human notification still needs its own delivery evidence.
993
- if (!humanNotice && row.claimedAt)
994
- return null;
995
- if (!humanNotice && deps.queueRepo.isLocalHumanDecisionWithoutGateway(row))
996
- return null;
997
- if (!humanNotice && polledRow(row))
998
- return null;
999
- const notification = humanNotice ? deps.queueRepo.transitionLog.latestOwnerNotificationForQitem(row.qitemId) : null;
1000
- const resolutionNotice = notification?.ownerNotificationKind === "human-decision-resolved";
1001
- // Match the notification source in slack/queue-access.ts, not the agent wake's escalator.
1002
- const noticeOwner = row.state === "blocked" || resolutionNotice ? row.destinationSession : row.sourceSession;
1003
- const noticeRecipient = resolutionNotice ? notification.actorSession : row.state === "blocked" ? row.blockedOn : row.destinationSession;
1004
- // Slack answered 2xx but its body couldn't be read (slack-delivery's POSSIBLY_POSTED_CLASS): it may be in Slack.
1005
- const possiblyPosted = humanNotice && /\bclass=possibly-posted\b/.test(row.deliveryFailureDetail ?? "");
1006
- const failure = possiblyPosted
1007
- ? `human notice may have posted to ${noticeRecipient}: Slack answered but its reply couldn't be read (${row.deliveryFailureDetail}); the gateway checks Slack for its marker before any resend`
1008
- : humanNotice
1009
- ? `human notice ${row.deliveryOutcome} to ${noticeRecipient}: ${row.deliveryFailureDetail}`
1010
- : `wake failed (${row.lastNudgeResult ?? "failed"})`;
1011
- // Quiet hours: a held, turned-back or released ask belongs to its window's release job, so a failed wake, or a post
1012
- // not yet made, isn't "nothing retried it". A release whose post failed is a failed delivery, and a hold with no
1013
- // live release job is orphaned: both stay findings, with their own reason.
1014
- const quiet = quietHoldCustody(deps.db, row.qitemId, now);
1015
- if (quiet && (quiet.state === "held" || quiet.state === "released"))
1016
- return null;
1017
- // The ladder check runs LAST, so only a row the ladder ALONE would have stopped counts
1018
- // as ladder-suppressed (#1419). Agent wake retries do not own the separate notice to a
1019
- // person: a human notice is never the ladder's to suppress.
1020
- if (!humanNotice && hasLiveLadder(deps.db, row.qitemId, now, suppressionMinutes)) {
1021
- if (recordSuppression)
1022
- suppressedTags.add(findingDedupTag("undelivered-wake", row.qitemId));
1023
- return null;
1024
- }
1025
- return {
1026
- kind: humanNotice ? "undelivered-human-notice" : "undelivered-wake",
1027
- row,
1028
- route: humanNotice ? noticeOwner : resolveOrch(row.destinationSession, row) ?? row.destinationSession,
1029
- ageMinutes: minutesSince(row.tsCreated, now),
1030
- evidenceAt: latestIso(row.tsUpdated, row.lastNudgeAttempt),
1031
- why: quiet?.state === "orphaned"
1032
- ? `held for quiet hours (window ${quiet.windowId}), but no release job is live for that window: nothing will release it (${failure})`
1033
- : quiet?.state === "release-failed"
1034
- ? `released after quiet hours; its post failed (${quiet.failure}); the release stays queued for redelivery`
1035
- : humanNotice
1036
- ? `${failure}; check human-notification delivery rather than retrying the agent wake`
1037
- : `${failure} and nothing retried it`,
883
+ const suppressionMinutes = deps.ladderSuppressionMinutes ?? resolveLadderSuppressionMinutes();
884
+ /** The dedup tags of the candidates the LADDER suppressed in this pass, and only those:
885
+ * a row the ladder alone would have stopped. A finding for such a row stays open,
886
+ * because the marker only ever stopped the re-report — it never resolved anything.
887
+ * Other delivery/pickup findings still need source evidence before closure. */
888
+ const suppressedTags = new Set();
889
+ const ageMinutes = deps.unclaimedAgeMinutes ?? resolveStuckSweepUnclaimedAgeMinutes();
890
+ const routeNotes = new Map();
891
+ const routed = new Set();
892
+ /** #2988: the row's route was its seat's one declared delegation parent (resolveEscalationOwner outcome "parent"). */
893
+ const delegationParent = new Map();
894
+ const resolveOrch = (session, row) => {
895
+ if (hasConsumedEscalationHop(deps.db, row.qitemId)) {
896
+ routeNotes.set(row.qitemId, "escalates_to one-hop delivery already used; existing fallback retained");
897
+ return null;
898
+ }
899
+ if (deps.resolveOrchestrator)
900
+ return deps.resolveOrchestrator(session);
901
+ const route = resolveEscalationOwner(deps.db, session, target => deps.queueRepo.acceptsDestination(target));
902
+ if (route.outcome !== "none" && route.outcome !== "parent")
903
+ routeNotes.set(row.qitemId, route.reason);
904
+ if (route.outcome === "routed")
905
+ routed.add(row.qitemId);
906
+ if (route.outcome === "parent" && route.owner)
907
+ delegationParent.set(row.qitemId, route.owner);
908
+ else
909
+ delegationParent.delete(row.qitemId);
910
+ return route.owner;
1038
911
  };
1039
- };
1040
- const undeliveredNow = (qitemId) => indexed(() => deps.queueRepo.findUndelivered({ qitemId, waiting: false }))[0];
1041
- // The A1 net — created-with-destination rows carrying real obligations, unclaimed past
1042
- // the config-keyed age. Parks (state=blocked) legitimately wait and never appear here;
1043
- // failed-nudge rows already surfaced in half 2; laddered rows are S01's.
1044
- const cutoff = new Date(now.getTime() - ageMinutes * 60_000).toISOString();
1045
- const unclaimedCandidate = (qitemId, recordSuppression) => {
1046
- const row = indexed(() => deps.queueRepo.getById(qitemId, { waiting: false }));
1047
- if (!row || isSweepExempt(row))
1048
- return null;
1049
- // The query's own predicate, on the row as it is now.
1050
- if (row.state !== "pending" || row.claimedAt || !row.destinationSession || row.tsCreated > cutoff
1051
- || startsWithCI(row.lastNudgeResult, "failed:"))
1052
- return null;
1053
- if (deps.queueRepo.isLocalHumanDecisionWithoutGateway(row))
1054
- return null;
1055
- const actionableAt = pendingSince(deps.db, row.qitemId) ?? row.tsCreated;
1056
- if (actionableAt > cutoff)
1057
- return null;
1058
- // #514 — an ask already posted to its registered human in the current delivery episode waits on
1059
- // that human; it is not stuck, and a finding would post the human again. Unposted, failed,
1060
- // legacy and non-human rows keep this net.
1061
- if (deps.queueRepo.humanNotificationPostedThisEpisode(row.qitemId))
1062
- return null;
1063
- // An ask placed on Steering without an alert waits on its person there by design; a finding would alert them.
1064
- if (deps.queueRepo.humanAskWithoutAlert(row.qitemId))
1065
- return null;
1066
- // Quiet hours: a held ask whose window's release job is live waits on that job, and one already released waits on
1067
- // its post; neither is stuck. A release whose post failed is reported once, by the undelivered-wake loop above. A
1068
- // hold with no live release job is stuck: nothing will ever release it.
1069
- const quiet = quietHoldCustody(deps.db, row.qitemId, now);
1070
- if (quiet && quiet.state !== "orphaned")
1071
- return null;
1072
- // An explicit informational update to a currently registered human is for reading, not an obligation to claim,
1073
- // unless its quiet-hours hold has been orphaned before release.
1074
- if (!quiet && deps.queueRepo.isRegisteredHumanUpdate(row))
1075
- return null;
1076
- // The seat's typing guard or interruption level held its wake on purpose: it's held and readable at the seat, not
1077
- // stuck. (A handed-off baton's one held notice is the wake ladder's.)
1078
- if (row.lastNudgeResult === "retained:typing_guard")
1079
- return null;
1080
- // A queue-only seat's cold watchdog reminder (#3076) waits, with no nudge, for a person or the seat's next turn:
1081
- // held and readable at the seat, not stuck. A finding would be a poller compensating for the level.
1082
- if (row.sourceSession === "watchdog@system" && row.tags?.includes("watchdog") && row.tags.includes("queue-only"))
1083
- return null;
1084
- // The ladder check runs LAST here too: a row the ladder alone would have stopped is
1085
- // ladder-suppressed, and its finding stays open (#1419).
1086
- if (hasLiveLadder(deps.db, row.qitemId, now, suppressionMinutes)) {
1087
- if (recordSuppression)
1088
- suppressedTags.add(findingDedupTag("unclaimed-obligation", row.qitemId));
1089
- return null;
1090
- }
1091
- return {
1092
- kind: "unclaimed-obligation",
1093
- row,
1094
- route: resolveOrch(row.destinationSession, row) ?? row.destinationSession,
1095
- ageMinutes: minutesSince(actionableAt, now),
1096
- evidenceAt: actionableAt,
1097
- why: quiet?.state === "orphaned"
1098
- ? `held for quiet hours (window ${quiet.windowId}) for ${minutesSince(actionableAt, now)} min, but no release job is live for that window: nothing will release it`
1099
- : `actionable with a destination and unclaimed for ${minutesSince(actionableAt, now)} min (threshold ${ageMinutes})${unreadableOwner(row.destinationSession) ? "; owner activity unknown (can't read the seat)" : ""}`,
912
+ const isRegisteredHost = deps.isRegisteredHost ?? defaultIsRegisteredHost(log);
913
+ const candidates = [];
914
+ const deliveryHeld = (row) => deps.queueRepo.deliveryDrains.holds(row.destinationSession);
915
+ const nowIso = now.toISOString();
916
+ // SQLite's LIKE ignores ASCII case; the per-row rules below match the queries they stand in for.
917
+ const startsWithCI = (value, prefix) => (value ?? "").toLowerCase().startsWith(prefix);
918
+ // Each kind's rule for ONE row, applied to the row as it is now. The loops below enumerate the rows; the same
919
+ // rules run again on a fresh read right before a finding is created (stillStuck), because a pass that yields
920
+ // cannot trust what it read before the yield: a claim, a delivered wake, a moved deadline, a note or a new
921
+ // successor may have landed since.
922
+ // Half 1 — claimed-never-closed. The claimant holds the obligation; the finding
923
+ // routes to them.
924
+ const overdueCandidate = (row) => {
925
+ if (isSweepExempt(row))
926
+ return null;
927
+ return {
928
+ kind: "overdue-claim",
929
+ row,
930
+ route: row.destinationSession,
931
+ ageMinutes: minutesSince(row.closureRequiredAt ?? row.claimedAt, now),
932
+ evidenceAt: latestIso(lastMeaningfulTransition(deps.db, row.qitemId)?.at, row.closureRequiredAt, row.claimedAt),
933
+ why: "claimed and past closure_required_at with no closure",
934
+ };
1100
935
  };
1101
- };
1102
- /** The seat's activity can't be read (no reading, or one that reads unknown): said in the finding, so an unreadable
1103
- * seat isn't taken for one ignoring its work. The stalled finding says the same (`queue-pickup.ts`). A person has no
1104
- * seat to read, so their row never says so; nor does a row whose destination can't be classified, since it may be a
1105
- * person's. A classification fault never stops the sweep. */
1106
- function unreadableOwner(session) {
1107
- try {
1108
- if (deps.queueRepo.isHumanDestination(session))
936
+ // S04 seam — a claimed row with no later motion past the pickup threshold. The
937
+ // pickup module remains the ONE derivation rule; this only enumerates and routes.
938
+ const stalledCandidate = (qitemId) => {
939
+ const row = indexed(() => deps.queueRepo.getById(qitemId, { waiting: false }));
940
+ if (!row || isSweepExempt(row))
941
+ return null;
942
+ if ((row.state !== "pending" && row.state !== "in-progress") || !row.claimedAt)
943
+ return null;
944
+ const stalled = stalledPickupFinding(row);
945
+ if (!stalled)
946
+ return null;
947
+ // Keep this null arm for the 0.5.7 mechanized-pull turn-end hook that knows the in-flight row;
948
+ // it is the first honest row-scoped writer, and wiring reopens only in that slice.
949
+ const evidenceAt = latestIso(lastMeaningfulTransition(deps.db, row.qitemId)?.at, row.lastHeartbeat, row.claimedAt);
950
+ return {
951
+ kind: stalled.kind,
952
+ row,
953
+ route: resolveOrch(stalled.target, row) ?? stalled.target,
954
+ // The stall's own age: from the anchor the pickup decision uses, floored as its "why" counts, so a claim
955
+ // parked and resumed doesn't count its parked time and the headline matches the why to the minute.
956
+ ageMinutes: wholeMinutesSince(evidenceAt, now),
957
+ evidenceAt,
958
+ why: stalled.evidence,
959
+ };
960
+ };
961
+ // The timer delivered one transition-specific notice (or recorded a failed
962
+ // attempt). This existing sweep owns its bounded recovery, not another full
963
+ // packet or a parked-owner replay. A real owner response ends the occurrence.
964
+ const waitCandidate = (jobId) => {
965
+ const job = deps.db.prepare("SELECT spec_yaml FROM watchdog_jobs WHERE job_id = ? AND state = 'active' AND policy = 'periodic-reminder'")
966
+ .get(jobId);
967
+ const notice = job ? queueWaitNotice(job.spec_yaml) : null;
968
+ if (!notice || now.getTime() - Date.parse(notice.at) <= resolvePickupThresholdMinutes() * 60_000)
969
+ return null;
970
+ const binding = deps.db.prepare("SELECT qitem_id FROM queue_transition_wakes WHERE wake_ref = ? AND phase = 'armed' ORDER BY transition_id DESC LIMIT 1").get(jobId);
971
+ const row = binding ? indexed(() => deps.queueRepo.getById(binding.qitem_id, { waiting: false })) : null;
972
+ if (!row || row.state !== "blocked" || deps.queueRepo.getParkWakeStatus(row.qitemId)?.ref !== jobId)
973
+ return null;
974
+ const response = lastMeaningfulTransition(deps.db, row.qitemId);
975
+ if (response && Date.parse(response.at) > Date.parse(notice.at))
976
+ return null;
977
+ // A queue-only seat's wait notice (#3076) was noted on the row or became a queue row, with no nudge: held and
978
+ // readable at the seat, for a person or its next turn, not stuck. A finding would be a poller compensating.
979
+ if (isQueueOnlyDeliveryCode(notice.deliveryStatus))
980
+ return null;
981
+ const ownerActivity = deps.queueRepo.ownerActivity(row.destinationSession);
982
+ if (ownerActivity?.activity === "working" && !ownerActivity.needsInput.count && notice.deliveryStatus === "ok")
983
+ return null;
984
+ return { kind: "unconsumed-wait", row, route: resolveOrch(row.destinationSession, row) ?? row.sourceSession,
985
+ ageMinutes: minutesSince(notice.at, now), evidenceAt: notice.at, jobId,
986
+ why: `wait notice delivery=${notice.deliveryStatus}; no later owner response; activity=${ownerActivity?.activity ?? "unknown"}; inspect exact blocker ${row.blockedOn}` };
987
+ };
988
+ // The parked policy stops repeating a positively no-input failure. Unhealthy blocked rows
989
+ // have no retry ladder: the same sweep/recovery route owns their actionable disposition.
990
+ const parkedCandidate = (qitemId) => {
991
+ const row = indexed(() => deps.queueRepo.getById(qitemId, { waiting: false }));
992
+ if (!row || isSweepExempt(row))
993
+ return null;
994
+ if (row.state !== "blocked" || !startsWithCI(row.lastNudgeResult, "failed:"))
995
+ return null;
996
+ const wake = deps.queueRepo.getParkWakeStatus(qitemId);
997
+ if ((wake?.live === true && (!wake.unconsumed || wake.recoveryOwner === "queue-stuck-sweep"))
998
+ || deps.queueRepo.parkWakeServedByOwnReminder(qitemId))
999
+ return null;
1000
+ const transitions = deps.queueRepo.listTransitions(qitemId);
1001
+ const failure = currentParkedOwnerNoInputFailure(transitions);
1002
+ if (!failure)
1003
+ return null;
1004
+ // A queue-only agent seat (#3076) holds OpenRig's reminders on purpose, as the parked policy skips it: an earlier
1005
+ // refusal there is no input to fix, from the switch on, before that policy runs again.
1006
+ if (isQueueOnlySeat(row.destinationSession) && !isBoundTerminalSeat(deps.db, row.destinationSession))
1007
+ return null;
1008
+ // Another seat's incidental note is not the owner's response. This kind follows
1009
+ // the parked policy's owner-or-state-change rule, leaving other sweep kinds alone.
1010
+ if (transitions.some((t, i) => t.transitionId > (failure.transitionId ?? Number.POSITIVE_INFINITY)
1011
+ && (t.actorSession === row.destinationSession || t.state !== transitions[i - 1]?.state)))
1012
+ return null;
1013
+ return { kind: "parked-owner-no-input", row, route: resolveOrch(row.destinationSession, row) ?? row.sourceSession,
1014
+ ageMinutes: minutesSince(failure.ts, now), evidenceAt: failure.ts,
1015
+ why: `Automated parked-owner reminder refused before input (${failure.code}); repeated input stopped. Inspect the retained quota/guard or route terminal work to an agent. Original blocker remains ${row.blockedOn}` };
1016
+ };
1017
+ // Half 2 — sender-believed-delivered-never-woken. Nobody holds it (the wake failed),
1018
+ // so it routes to the destination's orchestrator when one is derivable. Rows with a
1019
+ // live S01 ladder are S01's territory; an exhausted ladder is the handback and lands
1020
+ // here exactly once (the dedup tag keeps it to one finding).
1021
+ // A wake recorded unroutable because the seat's pane wasn't bound yet (#2151). Once its binding exists, deliver the
1022
+ // row's own wake intent instead of reporting it: the intent is claimed and settled, so a startup drain doesn't send it
1023
+ // again, and one already in flight or settled isn't sent twice. The next tick reads the new result, so a failed send
1024
+ // is reported then. A row with a live retry ladder is left to the ladder.
1025
+ // The rule is shared with the reachable-seat retry; a live retry ladder is this sweep's own check.
1026
+ const wakeToRetry = (row) => deps.queueRepo.unroutableWakeRetryable(row, now)
1027
+ && !hasLiveLadder(deps.db, row.qitemId, now, suppressionMinutes);
1028
+ const isHumanNotice = (row) => row.deliveryOutcome === "never-posted" || row.deliveryOutcome === "transport-failed";
1029
+ // A hosted member with no wake trigger picks up its work by reading the queue: nothing can push work to it, by design.
1030
+ // So does a person's own conversation at the address OpenRig issued it (#3964), through the openrig plugin's hooks or
1031
+ // its own check, and a seat joined with `rig attach` as an external CLI, through the outside program it runs in. Their
1032
+ // rows' unroutable wakes aren't failed deliveries, so they get no finding each; work left unclaimed past the unclaimed
1033
+ // age is listed in one standing notice per address instead. Refreshed after every yield or awaited write.
1034
+ const pollsForWork = (session) => {
1035
+ let polls = pollingMembers.get(session);
1036
+ if (polls === undefined) {
1037
+ polls = (deps.queueRepo.isHostedMember(session) || deps.queueRepo.isIssuedConversation(session)
1038
+ || deps.queueRepo.isExternalCliSeat(session))
1039
+ && deps.queueRepo.classifyDestinationOf(session).class === "unroutable";
1040
+ pollingMembers.set(session, polls);
1041
+ }
1042
+ return polls;
1043
+ };
1044
+ const polledRow = (row) => recordsNoWakeRoute(row.lastNudgeResult) && pollsForWork(row.destinationSession);
1045
+ /** `row` comes from findUndelivered (it carries the delivery verdict). Call it after any wake retry the row needs. */
1046
+ const undeliveredCandidate = (row, recordSuppression) => {
1047
+ if (isSweepExempt(row))
1048
+ return null;
1049
+ const humanNotice = isHumanNotice(row);
1050
+ // A claim supersedes a retained failed wake, including on a row returned to
1051
+ // pending. Its pickup finding must not be replaced by that historical failure;
1052
+ // a separate human notification still needs its own delivery evidence.
1053
+ if (!humanNotice && row.claimedAt)
1054
+ return null;
1055
+ if (!humanNotice && deps.queueRepo.isLocalHumanDecisionWithoutGateway(row))
1056
+ return null;
1057
+ if (!humanNotice && polledRow(row))
1058
+ return null;
1059
+ const notification = humanNotice ? deps.queueRepo.transitionLog.latestOwnerNotificationForQitem(row.qitemId) : null;
1060
+ const resolutionNotice = notification?.ownerNotificationKind === "human-decision-resolved";
1061
+ // Match the notification source in slack/queue-access.ts, not the agent wake's escalator.
1062
+ const noticeOwner = row.state === "blocked" || resolutionNotice ? row.destinationSession : row.sourceSession;
1063
+ const noticeRecipient = resolutionNotice ? notification.actorSession : row.state === "blocked" ? row.blockedOn : row.destinationSession;
1064
+ // Slack answered 2xx but its body couldn't be read (slack-delivery's POSSIBLY_POSTED_CLASS): it may be in Slack.
1065
+ const possiblyPosted = humanNotice && /\bclass=possibly-posted\b/.test(row.deliveryFailureDetail ?? "");
1066
+ const failure = possiblyPosted
1067
+ ? `human notice may have posted to ${noticeRecipient}: Slack answered but its reply couldn't be read (${row.deliveryFailureDetail}); the gateway checks Slack for its marker before any resend`
1068
+ : humanNotice
1069
+ ? `human notice ${row.deliveryOutcome} to ${noticeRecipient}: ${row.deliveryFailureDetail}`
1070
+ : `wake failed (${row.lastNudgeResult ?? "failed"})`;
1071
+ // Quiet hours: a held, turned-back or released ask belongs to its window's release job, so a failed wake, or a post
1072
+ // not yet made, isn't "nothing retried it". A release whose post failed is a failed delivery, and a hold with no
1073
+ // live release job is orphaned: both stay findings, with their own reason.
1074
+ const quiet = quietHoldCustody(deps.db, row.qitemId, now);
1075
+ if (quiet && (quiet.state === "held" || quiet.state === "released"))
1076
+ return null;
1077
+ // The ladder check runs LAST, so only a row the ladder ALONE would have stopped counts
1078
+ // as ladder-suppressed (#1419). Agent wake retries do not own the separate notice to a
1079
+ // person: a human notice is never the ladder's to suppress.
1080
+ if (!humanNotice && hasLiveLadder(deps.db, row.qitemId, now, suppressionMinutes)) {
1081
+ if (recordSuppression)
1082
+ suppressedTags.add(findingDedupTag("undelivered-wake", row.qitemId));
1083
+ return null;
1084
+ }
1085
+ return {
1086
+ kind: humanNotice ? "undelivered-human-notice" : "undelivered-wake",
1087
+ row,
1088
+ route: humanNotice ? noticeOwner : resolveOrch(row.destinationSession, row) ?? row.destinationSession,
1089
+ ageMinutes: minutesSince(row.tsCreated, now),
1090
+ evidenceAt: latestIso(row.tsUpdated, row.lastNudgeAttempt),
1091
+ why: quiet?.state === "orphaned"
1092
+ ? `held for quiet hours (window ${quiet.windowId}), but no release job is live for that window: nothing will release it (${failure})`
1093
+ : quiet?.state === "release-failed"
1094
+ ? `released after quiet hours; its post failed (${quiet.failure}); the release stays queued for redelivery`
1095
+ : humanNotice
1096
+ ? `${failure}; check human-notification delivery rather than retrying the agent wake`
1097
+ : `${failure} and nothing retried it`,
1098
+ };
1099
+ };
1100
+ const undeliveredNow = (qitemId) => indexed(() => deps.queueRepo.findUndelivered({ qitemId, waiting: false }))[0];
1101
+ // The A1 net — created-with-destination rows carrying real obligations, unclaimed past
1102
+ // the config-keyed age. Parks (state=blocked) legitimately wait and never appear here;
1103
+ // failed-nudge rows already surfaced in half 2; laddered rows are S01's.
1104
+ const cutoff = new Date(now.getTime() - ageMinutes * 60_000).toISOString();
1105
+ const unclaimedCandidate = (qitemId, recordSuppression) => {
1106
+ const row = indexed(() => deps.queueRepo.getById(qitemId, { waiting: false }));
1107
+ if (!row || isSweepExempt(row))
1108
+ return null;
1109
+ // The query's own predicate, on the row as it is now.
1110
+ if (row.state !== "pending" || row.claimedAt || !row.destinationSession || row.tsCreated > cutoff
1111
+ || startsWithCI(row.lastNudgeResult, "failed:"))
1112
+ return null;
1113
+ if (deps.queueRepo.isLocalHumanDecisionWithoutGateway(row))
1114
+ return null;
1115
+ const actionableAt = pendingSince(deps.db, row.qitemId) ?? row.tsCreated;
1116
+ if (actionableAt > cutoff)
1117
+ return null;
1118
+ // #514 — an ask already posted to its registered human in the current delivery episode waits on
1119
+ // that human; it is not stuck, and a finding would post the human again. Unposted, failed,
1120
+ // legacy and non-human rows keep this net.
1121
+ if (deps.queueRepo.humanNotificationPostedThisEpisode(row.qitemId))
1122
+ return null;
1123
+ // An ask placed on Steering without an alert waits on its person there by design; a finding would alert them.
1124
+ if (deps.queueRepo.humanAskWithoutAlert(row.qitemId))
1125
+ return null;
1126
+ // Quiet hours: a held ask whose window's release job is live waits on that job, and one already released waits on
1127
+ // its post; neither is stuck. A release whose post failed is reported once, by the undelivered-wake loop above. A
1128
+ // hold with no live release job is stuck: nothing will ever release it.
1129
+ const quiet = quietHoldCustody(deps.db, row.qitemId, now);
1130
+ if (quiet && quiet.state !== "orphaned")
1131
+ return null;
1132
+ // An explicit informational update to a currently registered human is for reading, not an obligation to claim,
1133
+ // unless its quiet-hours hold has been orphaned before release.
1134
+ if (!quiet && deps.queueRepo.isRegisteredHumanUpdate(row))
1135
+ return null;
1136
+ // The seat's typing guard or interruption level held its wake on purpose: it's held and readable at the seat, not
1137
+ // stuck. (A handed-off baton's one held notice is the wake ladder's.)
1138
+ if (row.lastNudgeResult === "retained:typing_guard")
1139
+ return null;
1140
+ // A queue-only seat's cold watchdog reminder (#3076) waits, with no nudge, for a person or the seat's next turn:
1141
+ // held and readable at the seat, not stuck. A finding would be a poller compensating for the level.
1142
+ if (row.sourceSession === "watchdog@system" && row.tags?.includes("watchdog") && row.tags.includes("queue-only"))
1143
+ return null;
1144
+ // The ladder check runs LAST here too: a row the ladder alone would have stopped is
1145
+ // ladder-suppressed, and its finding stays open (#1419).
1146
+ if (hasLiveLadder(deps.db, row.qitemId, now, suppressionMinutes)) {
1147
+ if (recordSuppression)
1148
+ suppressedTags.add(findingDedupTag("unclaimed-obligation", row.qitemId));
1149
+ return null;
1150
+ }
1151
+ return {
1152
+ kind: "unclaimed-obligation",
1153
+ row,
1154
+ route: resolveOrch(row.destinationSession, row) ?? row.destinationSession,
1155
+ ageMinutes: minutesSince(actionableAt, now),
1156
+ evidenceAt: actionableAt,
1157
+ why: quiet?.state === "orphaned"
1158
+ ? `held for quiet hours (window ${quiet.windowId}) for ${minutesSince(actionableAt, now)} min, but no release job is live for that window: nothing will release it`
1159
+ : `actionable with a destination and unclaimed for ${minutesSince(actionableAt, now)} min (threshold ${ageMinutes})${unreadableOwner(row.destinationSession) ? "; owner activity unknown (can't read the seat)" : ""}`,
1160
+ };
1161
+ };
1162
+ /** The seat's activity can't be read (no reading, or one that reads unknown): said in the finding, so an unreadable
1163
+ * seat isn't taken for one ignoring its work. The stalled finding says the same (`queue-pickup.ts`). A person has no
1164
+ * seat to read, so their row never says so; nor does a row whose destination can't be classified, since it may be a
1165
+ * person's. A classification fault never stops the sweep. */
1166
+ function unreadableOwner(session) {
1167
+ try {
1168
+ if (deps.queueRepo.isHumanDestination(session))
1169
+ return false;
1170
+ }
1171
+ catch {
1109
1172
  return false;
1173
+ }
1174
+ const activity = deps.queueRepo.ownerActivity(session)?.activity;
1175
+ return !activity || activity === "unknown";
1110
1176
  }
1111
- catch {
1112
- return false;
1113
- }
1114
- const activity = deps.queueRepo.ownerActivity(session)?.activity;
1115
- return !activity || activity === "unknown";
1116
- }
1117
- // The custody class — a terminal row whose closure names one or more successor
1118
- // qitems or seat-address targets (closure_reason = 'handed_off_to'). A local miss is
1119
- // never proof of absence: the successor may live in another registered host's database.
1120
- // Comma fan-out is checked member-by-member and only unresolved members are reported.
1121
- // Three dispositions satisfy a member without a local hit / check:
1122
- // (1) proof-at-write — a REGISTERED host qualifier whose successor id RECOMPUTES
1123
- // from this row's own (qitem_id, handed_off_to, host) through the same deterministic
1124
- // derivation the cross-host close uses. The close path records that key only AFTER
1125
- // its forwarded successor-create succeeded, and the generic update path (which
1126
- // accepts arbitrary closure targets) cannot accidentally synthesize the sha256-derived
1127
- // id — registered-host SYNTAX alone is never trusted;
1128
- // (2) linked local successor for seat targets — a row in the local store whose
1129
- // destination matches the target seat and carries this source row's lineage (either
1130
- // handed_off_from or chain_of_record); and
1131
- // (3) a durable `custody-verified:` transition note written on the source row by
1132
- // whoever performed the registered-host read (read from active + archived transitions).
1133
- // Historical source rows are never mutated by this detector — the disposition note is the
1134
- // verifier's act, not ours.
1135
- // Internal handoffs record handed_off_to. A generic reclose can retain an old
1136
- // owner, so skip only recorded handoffs whose current target still matches (#341).
1137
- // Closures outside the recent 24-hour window without open findings are skipped so upgrading
1138
- // a real queue history does not raise a flood of historical findings.
1139
- /** `recheck`: read live without the lent indexes, and don't log the registry fallback a second time. */
1140
- const custodyCandidate = (qitemId, hasSuccessor, recheck = false) => {
1141
- // A recheck reads live, without the lent indexes: one row's own queries cost less than a rebuilt successor index.
1142
- const row = recheck ? deps.queueRepo.getById(qitemId, { waiting: false }) : indexed(() => deps.queueRepo.getById(qitemId, { waiting: false }));
1143
- if (!row || isSweepExempt(row))
1144
- return null;
1145
- // The query's own predicate, on the row as it is now.
1146
- const closed = row.state === "done" || row.state === "canceled"
1147
- || (row.state === "handed-off" && (row.handedOffTo == null || (row.closureTarget ?? null) !== row.handedOffTo));
1148
- if (!closed || !(startsWithCI(row.closureTarget, "qitem-") || row.closureReason === "handed_off_to"))
1149
- return null;
1150
- // Local recorded targets were filtered in SQL; remote keys use the same
1151
- // derivation as the cross-host close, without reading successor history.
1152
- if (row.state === "handed-off" && matchesRecordedHandoffTarget(row.qitemId, row.handedOffTo, row.closureTarget))
1153
- return null;
1154
- const targets = (row.closureTarget ?? row.handedOffTo ?? "")
1155
- .split(",")
1156
- .map((target) => target.trim())
1157
- .filter(Boolean);
1158
- if (targets.length === 0 && row.closureReason === "handed_off_to") {
1159
- targets.push("(unspecified)");
1160
- }
1161
- const verified = custodyVerifiedTargets(deps.db, row.qitemId, targets);
1162
- const verificationTargets = targets.filter((target) => {
1163
- if (verified.has(target))
1164
- return false;
1165
- if (target.startsWith("qitem-")) {
1166
- const at = target.indexOf("@");
1167
- if (at !== -1) {
1168
- const hostId = target.slice(at + 1);
1169
- const successorId = target.slice(0, at);
1170
- return !(isRegisteredHost(hostId) &&
1171
- row.handedOffTo !== null &&
1172
- successorId === deriveCrossHostSuccessorId(row.qitemId, row.handedOffTo, hostId));
1177
+ // The custody class — a terminal row whose closure names one or more successor
1178
+ // qitems or seat-address targets (closure_reason = 'handed_off_to'). A local miss is
1179
+ // never proof of absence: the successor may live in another registered host's database.
1180
+ // Comma fan-out is checked member-by-member and only unresolved members are reported.
1181
+ // Three dispositions satisfy a member without a local hit / check:
1182
+ // (1) proof-at-write — a REGISTERED host qualifier whose successor id RECOMPUTES
1183
+ // from this row's own (qitem_id, handed_off_to, host) through the same deterministic
1184
+ // derivation the cross-host close uses. The close path records that key only AFTER
1185
+ // its forwarded successor-create succeeded, and the generic update path (which
1186
+ // accepts arbitrary closure targets) cannot accidentally synthesize the sha256-derived
1187
+ // id — registered-host SYNTAX alone is never trusted;
1188
+ // (2) linked local successor for seat targets — a row in the local store whose
1189
+ // destination matches the target seat and carries this source row's lineage (either
1190
+ // handed_off_from or chain_of_record); and
1191
+ // (3) a durable `custody-verified:` transition note written on the source row by
1192
+ // whoever performed the registered-host read (read from active + archived transitions).
1193
+ // Historical source rows are never mutated by this detector — the disposition note is the
1194
+ // verifier's act, not ours.
1195
+ // Internal handoffs record handed_off_to. A generic reclose can retain an old
1196
+ // owner, so skip only recorded handoffs whose current target still matches (#341).
1197
+ // Closures outside the recent 24-hour window without open findings are skipped so upgrading
1198
+ // a real queue history does not raise a flood of historical findings.
1199
+ /** `recheck`: read live without the lent indexes, and don't log the registry fallback a second time. */
1200
+ const custodyCandidate = (qitemId, hasSuccessor, recheck = false) => {
1201
+ // A recheck reads live, without the lent indexes: one row's own queries cost less than a rebuilt successor index.
1202
+ const row = recheck ? deps.queueRepo.getById(qitemId, { waiting: false }) : indexed(() => deps.queueRepo.getById(qitemId, { waiting: false }));
1203
+ if (!row || isSweepExempt(row))
1204
+ return null;
1205
+ // The query's own predicate, on the row as it is now.
1206
+ const closed = row.state === "done" || row.state === "canceled"
1207
+ || (row.state === "handed-off" && (row.handedOffTo == null || (row.closureTarget ?? null) !== row.handedOffTo));
1208
+ if (!closed || !(startsWithCI(row.closureTarget, "qitem-") || row.closureReason === "handed_off_to"))
1209
+ return null;
1210
+ // Local recorded targets were filtered in SQL; remote keys use the same
1211
+ // derivation as the cross-host close, without reading successor history.
1212
+ if (row.state === "handed-off" && matchesRecordedHandoffTarget(row.qitemId, row.handedOffTo, row.closureTarget))
1213
+ return null;
1214
+ const targets = (row.closureTarget ?? row.handedOffTo ?? "")
1215
+ .split(",")
1216
+ .map((target) => target.trim())
1217
+ .filter(Boolean);
1218
+ if (targets.length === 0 && row.closureReason === "handed_off_to") {
1219
+ targets.push("(unspecified)");
1220
+ }
1221
+ const verified = custodyVerifiedTargets(deps.db, row.qitemId, targets);
1222
+ const verificationTargets = targets.filter((target) => {
1223
+ if (verified.has(target))
1224
+ return false;
1225
+ if (target.startsWith("qitem-")) {
1226
+ const at = target.indexOf("@");
1227
+ if (at !== -1) {
1228
+ const hostId = target.slice(at + 1);
1229
+ const successorId = target.slice(0, at);
1230
+ return !(isRegisteredHost(hostId) &&
1231
+ row.handedOffTo !== null &&
1232
+ successorId === deriveCrossHostSuccessorId(row.qitemId, row.handedOffTo, hostId));
1233
+ }
1234
+ if (target === row.qitemId)
1235
+ return true;
1236
+ return !indexed(() => deps.queueRepo.getById(target, { waiting: false }));
1237
+ }
1238
+ try {
1239
+ return !hasSuccessor(row.qitemId, target);
1173
1240
  }
1174
- if (target === row.qitemId)
1241
+ catch {
1175
1242
  return true;
1176
- return !indexed(() => deps.queueRepo.getById(target, { waiting: false }));
1177
- }
1243
+ }
1244
+ });
1245
+ if (verificationTargets.length === 0)
1246
+ return null;
1247
+ let route = row.destinationSession;
1178
1248
  try {
1179
- return !hasSuccessor(row.qitemId, target);
1249
+ route = custodyFindingRoute(deps.db, deps.queueRepo, row);
1180
1250
  }
1181
- catch {
1182
- return true;
1251
+ catch (err) {
1252
+ if (!(err instanceof QueueRepositoryError) || err.code !== "human_registry_unavailable")
1253
+ throw err;
1254
+ // The registry may not exist before the first human is registered. Losing
1255
+ // owner refinement must not stop unrelated findings or their resolution.
1256
+ if (!recheck)
1257
+ log(`[stuck-sweep] keeping custody route for ${row.qitemId} at ${row.destinationSession}: ${err.message}`);
1183
1258
  }
1184
- });
1185
- if (verificationTargets.length === 0)
1186
- return null;
1187
- let route = row.destinationSession;
1188
- try {
1189
- route = custodyFindingRoute(deps.db, deps.queueRepo, row);
1190
- }
1191
- catch (err) {
1192
- if (!(err instanceof QueueRepositoryError) || err.code !== "human_registry_unavailable")
1193
- throw err;
1194
- // The registry may not exist before the first human is registered. Losing
1195
- // owner refinement must not stop unrelated findings or their resolution.
1196
- if (!recheck)
1197
- log(`[stuck-sweep] keeping custody route for ${row.qitemId} at ${row.destinationSession}: ${err.message}`);
1198
- }
1199
- return {
1200
- kind: "dangling-closure",
1201
- row,
1202
- route,
1203
- ageMinutes: minutesSince(row.tsUpdated, now),
1204
- evidenceAt: latestIso(row.tsUpdated),
1205
- why: `closed (${row.closureReason ?? "?"}) with successor custody that this local store cannot fully verify`,
1206
- verificationTargets,
1259
+ return {
1260
+ kind: "dangling-closure",
1261
+ row,
1262
+ route,
1263
+ ageMinutes: minutesSince(row.tsUpdated, now),
1264
+ evidenceAt: latestIso(row.tsUpdated),
1265
+ why: `closed (${row.closureReason ?? "?"}) with successor custody that this local store cannot fully verify`,
1266
+ verificationTargets,
1267
+ };
1207
1268
  };
1208
- };
1209
- const armedJobOf = (qitemId) => deps.db.prepare("SELECT wake_ref FROM queue_transition_wakes WHERE qitem_id = ? AND phase = 'armed' ORDER BY transition_id DESC LIMIT 1").get(qitemId)?.wake_ref;
1210
- /** A kind's rule, again, on the row as it is now (read live, without the lent indexes): the candidate it makes now,
1211
- * with its current route, reason and targets, or null when it no longer holds. */
1212
- const candidateNow = (kind, id, jobId) => {
1213
- switch (kind) {
1214
- case "overdue-claim": {
1215
- const row = deps.queueRepo.findOverdue({ now: nowIso, qitemId: id, waiting: false })[0];
1216
- return row ? overdueCandidate(row) : null;
1269
+ const armedJobOf = (qitemId) => deps.db.prepare("SELECT wake_ref FROM queue_transition_wakes WHERE qitem_id = ? AND phase = 'armed' ORDER BY transition_id DESC LIMIT 1").get(qitemId)?.wake_ref;
1270
+ /** A kind's rule, again, on the row as it is now (read live, without the lent indexes): the candidate it makes now,
1271
+ * with its current route, reason and targets, or null when it no longer holds. */
1272
+ const candidateNow = (kind, id, jobId) => {
1273
+ switch (kind) {
1274
+ case "overdue-claim": {
1275
+ const row = deps.queueRepo.findOverdue({ now: nowIso, qitemId: id, waiting: false })[0];
1276
+ return row ? overdueCandidate(row) : null;
1277
+ }
1278
+ case "stalled-after-claim": return stalledCandidate(id);
1279
+ case "unconsumed-wait": {
1280
+ const job = jobId ?? armedJobOf(id);
1281
+ const c = job ? waitCandidate(job) : null;
1282
+ return c?.row.qitemId === id ? c : null;
1283
+ }
1284
+ case "parked-owner-no-input": return parkedCandidate(id);
1285
+ case "undelivered-wake":
1286
+ case "undelivered-human-notice": {
1287
+ const row = undeliveredNow(id);
1288
+ // the wake retry already ran in this pass; a row that still needs it now was not woken by it
1289
+ const c = row ? undeliveredCandidate(row, false) : null;
1290
+ return c?.kind === kind ? c : null;
1291
+ }
1292
+ case "unclaimed-obligation": return unclaimedCandidate(id, false);
1293
+ case "dangling-closure": return custodyCandidate(id, (source, target) => hasLinkedSuccessor(deps.db, source, target), true);
1294
+ default: return null;
1217
1295
  }
1218
- case "stalled-after-claim": return stalledCandidate(id);
1219
- case "unconsumed-wait": {
1220
- const job = jobId ?? armedJobOf(id);
1221
- const c = job ? waitCandidate(job) : null;
1222
- return c?.row.qitemId === id ? c : null;
1296
+ };
1297
+ const freshCandidate = (kind, id, jobId) => {
1298
+ const candidate = candidateNow(kind, id, jobId);
1299
+ return candidate && !deliveryHeld(candidate.row) ? candidate : null;
1300
+ };
1301
+ /** Whether a kind's rule still holds now, leaving the routing notes (routeNotes, routed) as they were. */
1302
+ const ruleHolds = (kind, id, jobId, includeDrained = true) => {
1303
+ const notes = new Map(routeNotes);
1304
+ const wasRouted = new Set(routed);
1305
+ try {
1306
+ return !!(includeDrained ? candidateNow(kind, id, jobId) : freshCandidate(kind, id, jobId));
1223
1307
  }
1224
- case "parked-owner-no-input": return parkedCandidate(id);
1225
- case "undelivered-wake":
1226
- case "undelivered-human-notice": {
1227
- const row = undeliveredNow(id);
1228
- // the wake retry already ran in this pass; a row that still needs it now was not woken by it
1229
- const c = row ? undeliveredCandidate(row, false) : null;
1230
- return c?.kind === kind ? c : null;
1308
+ finally {
1309
+ routeNotes.clear();
1310
+ for (const [k, v] of notes)
1311
+ routeNotes.set(k, v);
1312
+ routed.clear();
1313
+ for (const k of wasRouted)
1314
+ routed.add(k);
1315
+ }
1316
+ };
1317
+ const stillStuck = (c) => ruleHolds(c.kind, c.row.qitemId, c.jobId, false);
1318
+ /** The kinds the resolution closes on "no longer detected" alone (the others need source evidence). */
1319
+ const resolvedByRule = new Set(["overdue-claim", "stalled-after-claim", "unconsumed-wait", "parked-owner-no-input", "dangling-closure"]);
1320
+ // The rows each rule looks at. The id lists are judged on a fresh getById per row; the two finders return whole
1321
+ // rows, which are read again by id once other code may have run since the list was read.
1322
+ const listedAt = othersRan;
1323
+ for (const listed of indexed(() => deps.queueRepo.findOverdue({ now: nowIso, waiting: false }))) {
1324
+ if (dueToYield())
1325
+ await yieldLoop();
1326
+ const row = listedAt !== othersRan ? indexed(() => deps.queueRepo.findOverdue({ now: nowIso, qitemId: listed.qitemId, waiting: false }))[0] : listed;
1327
+ const c = row ? overdueCandidate(row) : null;
1328
+ if (!c || deliveryHeld(c.row))
1329
+ continue;
1330
+ candidates.push(c);
1331
+ try {
1332
+ // Only a transition and an event: no index or listed row changes.
1333
+ deps.queueRepo.recordClosureOverdue(row.qitemId, { now: nowIso });
1334
+ }
1335
+ catch (err) {
1336
+ log(`[stuck-sweep] failed to record closure-overdue for ${row.qitemId}: ${err instanceof Error ? err.message : String(err)}`);
1231
1337
  }
1232
- case "unclaimed-obligation": return unclaimedCandidate(id, false);
1233
- case "dangling-closure": return custodyCandidate(id, (source, target) => hasLinkedSuccessor(deps.db, source, target), true);
1234
- default: return null;
1235
- }
1236
- };
1237
- const freshCandidate = (kind, id, jobId) => {
1238
- const candidate = candidateNow(kind, id, jobId);
1239
- return candidate && !deliveryHeld(candidate.row) ? candidate : null;
1240
- };
1241
- /** Whether a kind's rule still holds now, leaving the routing notes (routeNotes, routed) as they were. */
1242
- const ruleHolds = (kind, id, jobId, includeDrained = true) => {
1243
- const notes = new Map(routeNotes);
1244
- const wasRouted = new Set(routed);
1245
- try {
1246
- return !!(includeDrained ? candidateNow(kind, id, jobId) : freshCandidate(kind, id, jobId));
1247
1338
  }
1248
- finally {
1249
- routeNotes.clear();
1250
- for (const [k, v] of notes)
1251
- routeNotes.set(k, v);
1252
- routed.clear();
1253
- for (const k of wasRouted)
1254
- routed.add(k);
1339
+ for (const { qitem_id } of deps.db
1340
+ .prepare("SELECT qitem_id FROM queue_items WHERE state IN ('pending', 'in-progress') AND claimed_at IS NOT NULL")
1341
+ .all()) {
1342
+ if (dueToYield())
1343
+ await yieldLoop();
1344
+ const c = stalledCandidate(qitem_id);
1345
+ if (c && !deliveryHeld(c.row))
1346
+ candidates.push(c);
1255
1347
  }
1256
- };
1257
- const stillStuck = (c) => ruleHolds(c.kind, c.row.qitemId, c.jobId, false);
1258
- /** The kinds the resolution closes on "no longer detected" alone (the others need source evidence). */
1259
- const resolvedByRule = new Set(["overdue-claim", "stalled-after-claim", "unconsumed-wait", "parked-owner-no-input", "dangling-closure"]);
1260
- // The rows each rule looks at. The id lists are judged on a fresh getById per row; the two finders return whole
1261
- // rows, which are read again by id once other code may have run since the list was read.
1262
- const listedAt = othersRan;
1263
- for (const listed of indexed(() => deps.queueRepo.findOverdue({ now: nowIso, waiting: false }))) {
1264
- if (dueToYield())
1265
- await yieldLoop();
1266
- const row = listedAt !== othersRan ? indexed(() => deps.queueRepo.findOverdue({ now: nowIso, qitemId: listed.qitemId, waiting: false }))[0] : listed;
1267
- const c = row ? overdueCandidate(row) : null;
1268
- if (!c || deliveryHeld(c.row))
1269
- continue;
1270
- candidates.push(c);
1271
- try {
1272
- // Only a transition and an event: no index or listed row changes.
1273
- deps.queueRepo.recordClosureOverdue(row.qitemId, { now: nowIso });
1348
+ for (const { job_id } of deps.db.prepare("SELECT job_id FROM watchdog_jobs WHERE state = 'active' AND policy = 'periodic-reminder'")
1349
+ .all()) {
1350
+ if (dueToYield())
1351
+ await yieldLoop();
1352
+ const c = waitCandidate(job_id);
1353
+ if (c && !deliveryHeld(c.row))
1354
+ candidates.push(c);
1274
1355
  }
1275
- catch (err) {
1276
- log(`[stuck-sweep] failed to record closure-overdue for ${row.qitemId}: ${err instanceof Error ? err.message : String(err)}`);
1356
+ for (const { qitem_id } of deps.db.prepare("SELECT qitem_id FROM queue_items WHERE state='blocked' AND last_nudge_result LIKE 'failed:%'")
1357
+ .all()) {
1358
+ if (dueToYield())
1359
+ await yieldLoop();
1360
+ const c = parkedCandidate(qitem_id);
1361
+ if (c && !deliveryHeld(c.row))
1362
+ candidates.push(c);
1277
1363
  }
1278
- }
1279
- for (const { qitem_id } of deps.db
1280
- .prepare("SELECT qitem_id FROM queue_items WHERE state IN ('pending', 'in-progress') AND claimed_at IS NOT NULL")
1281
- .all()) {
1282
- if (dueToYield())
1283
- await yieldLoop();
1284
- const c = stalledCandidate(qitem_id);
1285
- if (c && !deliveryHeld(c.row))
1286
- candidates.push(c);
1287
- }
1288
- for (const { job_id } of deps.db.prepare("SELECT job_id FROM watchdog_jobs WHERE state = 'active' AND policy = 'periodic-reminder'")
1289
- .all()) {
1290
- if (dueToYield())
1291
- await yieldLoop();
1292
- const c = waitCandidate(job_id);
1293
- if (c && !deliveryHeld(c.row))
1294
- candidates.push(c);
1295
- }
1296
- for (const { qitem_id } of deps.db.prepare("SELECT qitem_id FROM queue_items WHERE state='blocked' AND last_nudge_result LIKE 'failed:%'")
1297
- .all()) {
1298
- if (dueToYield())
1299
- await yieldLoop();
1300
- const c = parkedCandidate(qitem_id);
1301
- if (c && !deliveryHeld(c.row))
1302
- candidates.push(c);
1303
- }
1304
- // The candidate ids are read without deriving any row (in yielding windows on a file database), and each row is
1305
- // derived by id between this pass's yields, so a long candidate set never runs as one synchronous read.
1306
- const undeliveredIds = await deps.queueRepo.undeliveredCandidateIds();
1307
- othersMayHaveRun();
1308
- for (const qitemId of undeliveredIds) {
1309
- if (dueToYield())
1310
- await yieldLoop();
1311
- let row = undeliveredNow(qitemId);
1312
- if (!row || isFindingRow(row) || deliveryHeld(row))
1313
- continue;
1314
- if (wakeToRetry(row)) {
1315
- await deps.queueRepo.deliverWakeForSuccessor(row.qitemId, row.destinationSession, true, row.sourceSession);
1316
- othersMayHaveRun();
1317
- // judged again on the row as the send (and anyone else during it) left it
1318
- row = undeliveredNow(row.qitemId);
1319
- if (!row || !recordsNoWakeRoute(row.lastNudgeResult))
1364
+ // The candidate ids are read without deriving any row (in yielding windows on a file database), and each row is
1365
+ // derived by id between this pass's yields, so a long candidate set never runs as one synchronous read.
1366
+ const undeliveredIds = await deps.queueRepo.undeliveredCandidateIds();
1367
+ othersMayHaveRun();
1368
+ for (const qitemId of undeliveredIds) {
1369
+ if (dueToYield())
1370
+ await yieldLoop();
1371
+ let row = undeliveredNow(qitemId);
1372
+ if (!row || isFindingRow(row) || deliveryHeld(row))
1320
1373
  continue;
1374
+ if (wakeToRetry(row)) {
1375
+ await deps.queueRepo.deliverWakeForSuccessor(row.qitemId, row.destinationSession, true, row.sourceSession);
1376
+ othersMayHaveRun();
1377
+ // judged again on the row as the send (and anyone else during it) left it
1378
+ row = undeliveredNow(row.qitemId);
1379
+ if (!row || !recordsNoWakeRoute(row.lastNudgeResult))
1380
+ continue;
1381
+ }
1382
+ const c = undeliveredCandidate(row, true);
1383
+ if (c && !deliveryHeld(c.row))
1384
+ candidates.push(c);
1321
1385
  }
1322
- const c = undeliveredCandidate(row, true);
1323
- if (c && !deliveryHeld(c.row))
1324
- candidates.push(c);
1325
- }
1326
- for (const { qitem_id } of deps.db
1327
- .prepare(`SELECT qitem_id FROM queue_items
1386
+ for (const { qitem_id } of deps.db
1387
+ .prepare(`SELECT qitem_id FROM queue_items
1328
1388
  WHERE state = 'pending'
1329
1389
  AND claimed_at IS NULL
1330
1390
  AND destination_session IS NOT NULL AND destination_session != ''
1331
1391
  AND ts_created <= ?
1332
1392
  AND (last_nudge_result IS NULL OR last_nudge_result NOT LIKE 'failed:%')`)
1333
- .all(cutoff)) {
1334
- if (dueToYield())
1335
- await yieldLoop();
1336
- const c = unclaimedCandidate(qitem_id, true);
1337
- if (c && !deliveryHeld(c.row))
1338
- candidates.push(c);
1339
- }
1340
- const custodyHours = deps.custodyWindowHours ?? STUCK_SWEEP_CUSTODY_WINDOW_HOURS;
1341
- const custodyCutoff = new Date(now.getTime() - custodyHours * 3_600_000).toISOString();
1342
- const openDanglingIds = [];
1343
- const danglingPrefix = "stuck-sweep:dangling-closure:";
1344
- for (const { tags } of deps.db
1345
- .prepare(`SELECT tags FROM queue_items WHERE state IN ('pending', 'in-progress', 'blocked') AND tags LIKE ?`)
1346
- .all(`%"${danglingPrefix}%`)) {
1347
- try {
1348
- for (const tag of JSON.parse(tags)) {
1349
- if (tag.startsWith(danglingPrefix)) {
1350
- openDanglingIds.push(tag.slice(danglingPrefix.length));
1393
+ .all(cutoff)) {
1394
+ if (dueToYield())
1395
+ await yieldLoop();
1396
+ const c = unclaimedCandidate(qitem_id, true);
1397
+ if (c && !deliveryHeld(c.row))
1398
+ candidates.push(c);
1399
+ }
1400
+ const custodyHours = deps.custodyWindowHours ?? STUCK_SWEEP_CUSTODY_WINDOW_HOURS;
1401
+ const custodyCutoff = new Date(now.getTime() - custodyHours * 3_600_000).toISOString();
1402
+ const openDanglingIds = [];
1403
+ const danglingPrefix = "stuck-sweep:dangling-closure:";
1404
+ for (const { tags } of deps.db
1405
+ .prepare(`SELECT tags FROM queue_items WHERE state IN ('pending', 'in-progress', 'blocked') AND tags LIKE ?`)
1406
+ .all(`%"${danglingPrefix}%`)) {
1407
+ try {
1408
+ for (const tag of JSON.parse(tags)) {
1409
+ if (tag.startsWith(danglingPrefix)) {
1410
+ openDanglingIds.push(tag.slice(danglingPrefix.length));
1411
+ }
1351
1412
  }
1352
1413
  }
1414
+ catch {
1415
+ // Skip malformed tags
1416
+ }
1353
1417
  }
1354
- catch {
1355
- // Skip malformed tags
1356
- }
1357
- }
1358
- const custodyRows = deps.db
1359
- .prepare(
1360
- // Bound candidates before checking state: including handed-off in the
1361
- // state index scan would otherwise revisit all historical atomic handoffs.
1362
- `WITH custody_candidates AS MATERIALIZED (
1418
+ const custodyRows = deps.db
1419
+ .prepare(
1420
+ // Bound candidates before checking state: including handed-off in the
1421
+ // state index scan would otherwise revisit all historical atomic handoffs.
1422
+ `WITH custody_candidates AS MATERIALIZED (
1363
1423
  SELECT qitem_id, state, handed_off_to, closure_target, closure_reason
1364
1424
  FROM queue_items WHERE ts_updated >= ?
1365
1425
  UNION
@@ -1370,866 +1430,875 @@ export async function runStuckSweep(deps) {
1370
1430
  WHERE (q.state IN ('done', 'canceled') OR (q.state = 'handed-off'
1371
1431
  AND (q.handed_off_to IS NULL OR q.closure_target IS NOT q.handed_off_to)))
1372
1432
  AND (q.closure_target LIKE 'qitem-%' OR q.closure_reason = 'handed_off_to')`)
1373
- .all(custodyCutoff, JSON.stringify(openDanglingIds));
1374
- successors = createLinkedSuccessorLookup(deps.db, custodyRows.map((r) => r.qitem_id));
1375
- const lookup = successors;
1376
- for (const { qitem_id } of custodyRows) {
1377
- if (dueToYield())
1378
- await yieldLoop();
1379
- const c = custodyCandidate(qitem_id, successorsPerRow
1380
- ? (source, target) => hasLinkedSuccessor(deps.db, source, target)
1381
- : (source, target) => lookup.has(source, target));
1382
- if (c && !deliveryHeld(c.row))
1383
- candidates.push(c);
1384
- }
1385
- // A finding for a confirmed-missing session goes to a live recovery seat when one is available,
1386
- // since nothing would ever wake the missing one (the ladder covers handed-off batons only): the
1387
- // operator agent, else the operator seat (the ladder's own floor, the person approvals use), else
1388
- // the stuck row's creator, skipping any that is unset, confirmed missing or this seat. When none
1389
- // qualifies, the finding stays addressed to the missing session and says so; it's never dropped.
1390
- // A live seat keeps its own.
1391
- const stoppedReason = (session) => {
1392
- const nodeId = resolveSessionNodeId(deps.db, session);
1393
- return nodeId === null ? null : nodeExecutorStoppedReason(deps.db, nodeId);
1394
- };
1395
- const sessionMissing = deps.sessionConfirmedMissing ?? ((session) => stoppedReason(session) !== null);
1396
- const routeAroundMissing = (c) => {
1397
- if (!sessionMissing(c.route))
1398
- return;
1399
- const stoppedDescription = stoppedReason(c.route) === "pane_exited"
1400
- ? "has a confirmed exited pane (pane_exited)" : "is confirmed missing (session_missing)";
1401
- recoverySeats ??= [(deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)(), (deps.resolveOperatorSeat ?? resolveOperatorSeat)()];
1402
- const choices = [...recoverySeats, c.row.sourceSession];
1403
- const chosen = choices.findIndex((seat) => !!seat && seat !== c.route && !sessionMissing(seat));
1404
- const floor = chosen < 0 ? null : choices[chosen];
1405
- if (!floor) {
1406
- c.why += `; ${c.route} ${stoppedDescription} and no live recovery seat is available (operator agent, operator seat and creator are each unset, missing or this seat; an operator agent setting that's unreadable or isn't an agent's session counts as unset), so this finding stays addressed to it`;
1407
- return;
1408
- }
1409
- // Name the rule that chose it, so whoever receives the finding knows why, and which setting to change.
1410
- c.why += `; ${c.route} ${stoppedDescription}, so this finding goes to ${floor}, ${RECOVERY_SEAT_RULES[chosen]}`;
1411
- c.route = floor;
1412
- };
1413
- // A destination its own wake found unroutable, and still is (no terminal, not a person: a hosted member, or a
1414
- // mistyped address), can't hear its finding either; a seat launched since its wake keeps its own. A hosted member
1415
- // OpenRig rings, whose work is still unclaimed (its ring failed, or it didn't pick the work up by the unclaimed
1416
- // age), goes the same way; one that claimed and stalled keeps its own finding, which rings it. Only a person can
1417
- // make a hosted member check its work, so the person goes first: the operator seat when it's a person's address,
1418
- // else the row's creator, else the operator agent, skipping any that is unset, this seat, confirmed missing,
1419
- // unroutable or a terminal seat itself. A bound terminal seat goes the same way: the queue wake types nothing into
1420
- // it, and nothing there can claim work.
1421
- const classOf = (seat) => deps.queueRepo.classifyDestinationOf(seat).class;
1422
- /** Who hears about work for a destination that can't hear it: the index into NO_WAKE_ROUTE_RULES and the seat, or -1. */
1423
- const noWakeRecipient = (destination, creator) => {
1424
- const operatorSeat = (deps.resolveOperatorSeat ?? resolveOperatorSeat)();
1425
- const person = operatorSeat && classOf(operatorSeat) === "gateway-routable" ? operatorSeat : null;
1426
- const choices = [person, creator, (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)()];
1427
- const chosen = choices.findIndex((seat) => !!seat && seat !== destination && !sessionMissing(seat) && classOf(seat) !== "unroutable"
1428
- && !isBoundTerminalSeat(deps.db, seat));
1429
- return { chosen, seat: chosen < 0 ? null : choices[chosen] };
1430
- };
1431
- /** The person (the operator seat when it's a person's address) or the operator agent: recipients that may see any row. */
1432
- const seesAnyRow = (seat) => {
1433
- const operatorSeat = (deps.resolveOperatorSeat ?? resolveOperatorSeat)();
1434
- if (operatorSeat === seat && classOf(seat) === "gateway-routable")
1435
- return true;
1436
- return (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)() === seat;
1437
- };
1438
- const routeAroundNoWake = (c) => {
1439
- if (c.route !== c.row.destinationSession)
1440
- return;
1441
- const destination = classOf(c.row.destinationSession);
1442
- const noRoute = destination === "unroutable" && recordsNoWakeRoute(c.row.lastNudgeResult);
1443
- const terminalSeat = destination === "pane-bound" && isBoundTerminalSeat(deps.db, c.row.destinationSession);
1444
- if (!noRoute && !terminalSeat && !(destination === "hosted" && !c.row.claimedAt))
1445
- return;
1446
- c.noWake = true;
1447
- const recipient = noWakeRecipient(c.route, c.row.sourceSession);
1448
- c.why += noRoute
1449
- ? `; ${c.route} has no wake route on this daemon (no terminal, not a person). If it's a hosted member, it sees this work only when it next checks, so ask it to; otherwise fix the address`
1450
- : terminalSeat
1451
- ? `; ${c.route} is a terminal seat; nothing there can claim this work, and no wake is typed into it. Route the work to an agent seat`
1452
- : `; ${c.route} is a hosted member. OpenRig rang its trigger (${c.row.lastNudgeResult ?? "no ring recorded"}), and it hasn't claimed this work. It sees work only when it checks, so ask it to`;
1453
- if (!recipient.seat) {
1454
- c.why += `. No person, creator or operator agent that can be reached is available, so this finding stays addressed to it`;
1455
- return;
1456
- }
1457
- c.why += `. This finding goes to ${recipient.seat}, ${NO_WAKE_ROUTE_RULES[recipient.chosen]}`;
1458
- c.route = recipient.seat;
1459
- };
1460
- for (const c of candidates) {
1461
- if (dueToYield())
1462
- await yieldLoop();
1463
- routeAroundMissing(c);
1464
- }
1465
- for (const c of candidates) {
1466
- if (dueToYield())
1467
- await yieldLoop();
1468
- routeAroundNoWake(c);
1469
- }
1470
- // Route: idempotent per (row, kind). An existing open finding refreshes its age; a
1471
- // new one is created durable + waking (the create path's default nudge).
1472
- const findings = [];
1473
- const liveDedupTags = new Set();
1474
- const candidateIds = new Set(candidates.map((c) => c.row.qitemId));
1475
- const drainDeferredIds = new Set();
1476
- const failedCreates = [];
1477
- const unknownRig = (err) => err instanceof QueueRepositoryError && err.code === "unknown_destination_rig";
1478
- const missingRig = (seat) => parseSessionName(seat).kind === "canonical" && !deps.queueRepo.acceptsDestination(seat);
1479
- const sourceAgent = (source, destination) => source !== destination && parseSessionName(source).kind === "canonical" && !isHumanSeatSessionRef(source)
1480
- && !isMachinerySession(source) && deps.queueRepo.acceptsDestination(source) && !sessionMissing(source)
1481
- && !deps.queueRepo.isHumanDestination(source) && !isBoundTerminalSeat(deps.db, source) ? source : null;
1482
- const gapNote = (source, destination) => `stuck-sweep routing gap: ${destination} references an unknown rig; no route to originating agent ${source}`;
1483
- const hasGap = deps.db.prepare(`SELECT 1 FROM queue_transitions WHERE qitem_id = ? AND actor_session = 'daemon@system' AND transition_note = ? LIMIT 1`);
1484
- const reportGap = (action) => {
1485
- const { row, kind, destination, findingQitemId = "" } = action;
1486
- const note = gapNote(row.sourceSession, destination);
1487
- if (!hasGap.get(row.qitemId, note)) {
1488
- // A same-state daemon note is bookkeeping, not work progress or a new recovery episode.
1489
- deps.queueRepo.transitionLog.append({ qitemId: row.qitemId, state: row.state, actorSession: "daemon@system", transitionNote: note });
1490
- log(`[stuck-sweep] ${row.qitemId}: ${note}`);
1433
+ .all(custodyCutoff, JSON.stringify(openDanglingIds));
1434
+ successors = createLinkedSuccessorLookup(deps.db, custodyRows.map((r) => r.qitem_id));
1435
+ const lookup = successors;
1436
+ for (const { qitem_id } of custodyRows) {
1437
+ if (dueToYield())
1438
+ await yieldLoop();
1439
+ const c = custodyCandidate(qitem_id, successorsPerRow
1440
+ ? (source, target) => hasLinkedSuccessor(deps.db, source, target)
1441
+ : (source, target) => lookup.has(source, target));
1442
+ if (c && !deliveryHeld(c.row))
1443
+ candidates.push(c);
1491
1444
  }
1492
- findings.push({ kind, qitemId: row.qitemId, findingQitemId, action: "unreported", destination });
1493
- };
1494
- const recordFailure = (context, err) => {
1495
- const message = `${context}: ${err instanceof Error ? err.message : String(err)}`;
1496
- log(`[stuck-sweep] ${message}`);
1497
- failedCreates.push(message);
1498
- };
1499
- // Selected by the finding tag alone: a handoff gives its successor an ordinary qitem id while keeping the tags, so
1500
- // an id-prefix filter would miss a finding handed to a source whose origin rig is later deleted.
1501
- const pendingFindings = deps.db.prepare(`
1502
- SELECT qitem_id, destination_session FROM queue_items
1503
- WHERE state = 'pending' AND claimed_at IS NULL AND tags LIKE ?`)
1504
- .all(`%"${STUCK_SWEEP_FINDING_TAG}"%`);
1505
- const perRowKinds = ["overdue-claim", "undelivered-wake", "undelivered-human-notice",
1506
- "unclaimed-obligation", "dangling-closure", "stalled-after-claim", "unconsumed-wait", "parked-owner-no-input"];
1507
- for (const ref of pendingFindings) {
1508
- if (dueToYield())
1509
- await yieldLoop();
1510
- if (!missingRig(ref.destination_session))
1511
- continue;
1512
- const row = indexed(() => deps.queueRepo.getById(ref.qitem_id, { waiting: false }));
1513
- if (!row || row.state !== "pending" || row.claimedAt || row.destinationSession !== ref.destination_session || deliveryHeld(row))
1514
- continue;
1515
- const kind = perRowKinds.find((kind) => kind === findingKindOf(row)?.replace(/^successor-verification-required$/, "dangling-closure"));
1516
- if (!kind || !isFindingRow(row))
1517
- continue;
1518
- const target = sourceAgent(row.sourceSession, row.destinationSession);
1519
- if (target) {
1520
- try {
1521
- const { created } = await deps.queueRepo.handoff({
1522
- qitemId: row.qitemId, fromSession: "stuck-sweep@system", toSession: target,
1523
- body: `${row.body}\n\nOriginal finding destination ${row.destinationSession} references a missing rig. This finding was handed back to the originating agent.`,
1524
- summary: row.summary, evidenceRef: row.evidenceRef, evidenceRefRoots: row.evidenceRefRoots,
1525
- });
1526
- othersMayHaveRun();
1527
- findings.push({ kind, qitemId: row.qitemId, findingQitemId: created.qitemId, action: "created" });
1528
- continue;
1529
- }
1530
- catch (err) {
1531
- othersMayHaveRun();
1532
- if (!unknownRig(err)) {
1533
- recordFailure(`orphaned finding ${row.qitemId} not handed off`, err);
1534
- continue;
1535
- }
1445
+ // A finding for a confirmed-missing session goes to a live recovery seat when one is available,
1446
+ // since nothing would ever wake the missing one (the ladder covers handed-off batons only): the
1447
+ // operator agent, else the operator seat (the ladder's own floor, the person approvals use), else
1448
+ // the stuck row's creator, skipping any that is unset, confirmed missing or this seat. When none
1449
+ // qualifies, the finding stays addressed to the missing session and says so; it's never dropped.
1450
+ // A live seat keeps its own.
1451
+ const stoppedReason = (session) => {
1452
+ const nodeId = resolveSessionNodeId(deps.db, session);
1453
+ return nodeId === null ? null : nodeExecutorStoppedReason(deps.db, nodeId);
1454
+ };
1455
+ const sessionMissing = deps.sessionConfirmedMissing ?? ((session) => stoppedReason(session) !== null);
1456
+ const routeAroundMissing = (c) => {
1457
+ if (!sessionMissing(c.route))
1458
+ return;
1459
+ const stoppedDescription = stoppedReason(c.route) === "pane_exited"
1460
+ ? "has a confirmed exited pane (pane_exited)" : "is confirmed missing (session_missing)";
1461
+ recoverySeats ??= [(deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)(), (deps.resolveOperatorSeat ?? resolveOperatorSeat)()];
1462
+ const choices = [...recoverySeats, c.row.sourceSession];
1463
+ const chosen = choices.findIndex((seat) => !!seat && seat !== c.route && !sessionMissing(seat));
1464
+ const floor = chosen < 0 ? null : choices[chosen];
1465
+ if (!floor) {
1466
+ c.why += `; ${c.route} ${stoppedDescription} and no live recovery seat is available (operator agent, operator seat and creator are each unset, missing or this seat; an operator agent setting that's unreadable or isn't an agent's session counts as unset), so this finding stays addressed to it`;
1467
+ return;
1536
1468
  }
1537
- }
1538
- reportGap({ row, kind, destination: row.destinationSession, findingQitemId: row.qitemId });
1539
- }
1540
- // #2430: an unclaimed row whose finding would go back to its own agent seat (no delegation parent and no escalates_to
1541
- // route declared) tells that seat nothing: it already holds the row. A seat that reads its rows without claiming
1542
- // them, a person's front door, got one such finding per row. Those rows share one standing notice per seat instead
1543
- // (below). A finding per row stays for a person's address or a terminal seat, for a declared route that failed (its
1544
- // finding names why, and a declared delegation parent with no session is one), and for a row that already has a
1545
- // recovery.
1546
- /** An agent seat's node: one whose runtime isn't a terminal, with no declared delegation parent, at an address that
1547
- * isn't a person's. An address the human registry can't classify counts as a person's. null for anything else. Read
1548
- * once per seat until other code may have run (agentSeats). */
1549
- const agentSeatNode = (session) => {
1550
- if (agentSeats.has(session))
1551
- return agentSeats.get(session);
1552
- const nodeId = resolveSessionNodeId(deps.db, session);
1553
- const node = nodeId ? deps.db.prepare(`SELECT n.logical_id AS logicalId, n.runtime AS runtime, r.name AS rig,
1554
- EXISTS (SELECT 1 FROM edges e WHERE e.target_id = n.id AND e.kind = 'delegates_to') AS parent
1555
- FROM nodes n JOIN rigs r ON r.id = n.rig_id WHERE n.id = ?`)
1556
- .get(nodeId) : undefined;
1557
- let agent = null;
1558
- try {
1559
- if (node && node.runtime !== "terminal" && !node.parent && !deps.queueRepo.isHumanDestination(session)) {
1560
- agent = { logicalId: node.logicalId, rig: node.rig };
1469
+ // Name the rule that chose it, so whoever receives the finding knows why, and which setting to change.
1470
+ c.why += `; ${c.route} ${stoppedDescription}, so this finding goes to ${floor}, ${RECOVERY_SEAT_RULES[chosen]}`;
1471
+ c.route = floor;
1472
+ };
1473
+ // A destination its own wake found unroutable, and still is (no terminal, not a person: a hosted member, or a
1474
+ // mistyped address), can't hear its finding either; a seat launched since its wake keeps its own. A hosted member
1475
+ // OpenRig rings, whose work is still unclaimed (its ring failed, or it didn't pick the work up by the unclaimed
1476
+ // age), goes the same way; one that claimed and stalled keeps its own finding, which rings it. Only a person can
1477
+ // make a hosted member check its work, so the person goes first: the operator seat when it's a person's address,
1478
+ // else the row's creator, else the operator agent, skipping any that is unset, this seat, confirmed missing,
1479
+ // unroutable or a terminal seat itself. A bound terminal seat goes the same way: the queue wake types nothing into
1480
+ // it, and nothing there can claim work.
1481
+ const classOf = (seat) => deps.queueRepo.classifyDestinationOf(seat).class;
1482
+ /** Who hears about work for a destination that can't hear it: the index into NO_WAKE_ROUTE_RULES and the seat, or -1. */
1483
+ const noWakeRecipient = (destination, creator) => {
1484
+ const operatorSeat = (deps.resolveOperatorSeat ?? resolveOperatorSeat)();
1485
+ const person = operatorSeat && classOf(operatorSeat) === "gateway-routable" ? operatorSeat : null;
1486
+ const choices = [person, creator, (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)()];
1487
+ const chosen = choices.findIndex((seat) => !!seat && seat !== destination && !sessionMissing(seat) && classOf(seat) !== "unroutable"
1488
+ && !isBoundTerminalSeat(deps.db, seat));
1489
+ return { chosen, seat: chosen < 0 ? null : choices[chosen] };
1490
+ };
1491
+ /** The person (the operator seat when it's a person's address) or the operator agent: recipients that may see any row. */
1492
+ const seesAnyRow = (seat) => {
1493
+ const operatorSeat = (deps.resolveOperatorSeat ?? resolveOperatorSeat)();
1494
+ if (operatorSeat === seat && classOf(seat) === "gateway-routable")
1495
+ return true;
1496
+ return (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)() === seat;
1497
+ };
1498
+ const routeAroundNoWake = (c) => {
1499
+ if (c.route !== c.row.destinationSession)
1500
+ return;
1501
+ const destination = classOf(c.row.destinationSession);
1502
+ const noRoute = destination === "unroutable" && recordsNoWakeRoute(c.row.lastNudgeResult);
1503
+ const terminalSeat = destination === "pane-bound" && isBoundTerminalSeat(deps.db, c.row.destinationSession);
1504
+ if (!noRoute && !terminalSeat && !(destination === "hosted" && !c.row.claimedAt))
1505
+ return;
1506
+ c.noWake = true;
1507
+ const recipient = noWakeRecipient(c.route, c.row.sourceSession);
1508
+ c.why += noRoute
1509
+ ? deps.queueRepo.isIssuedConversation(c.route)
1510
+ ? `; ${c.route} is an address OpenRig issued to a person's own conversation: no wake is sent to it, and OpenRig can't see its activity, so ask its person`
1511
+ : deps.queueRepo.isExternalCliSeat(c.route)
1512
+ ? `; ${c.route} is a seat attached from an outside program (rig attach): no wake is sent to it, and OpenRig can't see its activity, so ask whoever runs it`
1513
+ : `; ${c.route} has no wake route on this daemon (no terminal, not a person). If it's a hosted member, it sees this work only when it next checks, so ask it to; otherwise fix the address`
1514
+ : terminalSeat
1515
+ ? `; ${c.route} is a terminal seat; nothing there can claim this work, and no wake is typed into it. Route the work to an agent seat`
1516
+ : `; ${c.route} is a hosted member. OpenRig rang its trigger (${c.row.lastNudgeResult ?? "no ring recorded"}), and it hasn't claimed this work. It sees work only when it checks, so ask it to`;
1517
+ if (!recipient.seat) {
1518
+ c.why += `. No person, creator or operator agent that can be reached is available, so this finding stays addressed to it`;
1519
+ return;
1561
1520
  }
1521
+ c.why += `. This finding goes to ${recipient.seat}, ${NO_WAKE_ROUTE_RULES[recipient.chosen]}`;
1522
+ c.route = recipient.seat;
1523
+ };
1524
+ for (const c of candidates) {
1525
+ if (dueToYield())
1526
+ await yieldLoop();
1527
+ routeAroundMissing(c);
1562
1528
  }
1563
- catch { /* unclassifiable: a person's, as above */ }
1564
- agentSeats.set(session, agent);
1565
- return agent;
1566
- };
1567
- // A wake that failed at a live agent seat with no delegation parent or escalates_to made its finding that same seat's,
1568
- // so the finding's own wake went to the seat that had just failed to take one, onto whatever was in its input box.
1569
- // The row's creator can act on it (resend, reroute or ask), as the waiting and parked-owner findings already route;
1570
- // for a seat that sent itself the work, a row OpenRig's own machinery created, or a creator that is a bound terminal
1571
- // seat (nothing there can claim it, as for the no-wake rule), the operator agent can. A declared
1572
- // route that failed keeps its fallback, and a finding the two re-routes above moved keeps its recipient. A wake that
1573
- // found no route never reached the seat, so a seat launched since keeps its own finding, whose wake is the one it missed.
1574
- const routeAroundFailedWake = (c) => {
1575
- if (c.kind !== "undelivered-wake" || !startsWithCI(c.row.lastNudgeResult, "failed:") || c.noWake
1576
- || c.route !== c.row.destinationSession
1577
- || routeNotes.has(c.row.qitemId) || agentSeatNode(c.route) === null)
1578
- return;
1579
- const choices = [c.row.sourceSession, (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)()];
1580
- const chosen = choices.findIndex((seat) => !!seat && seat !== c.route && !isMachinerySession(seat)
1581
- && !sessionMissing(seat) && deps.queueRepo.acceptsDestination(seat) && !isBoundTerminalSeat(deps.db, seat));
1582
- if (chosen < 0) {
1583
- c.why += `; ${c.route} declares no delegation parent or escalates_to, and its creator and the operator agent (agents.operator_session) are each unset, missing, this seat, OpenRig's own machinery, a terminal seat or not an address this queue takes, so this finding stays addressed to it`;
1584
- return;
1585
- }
1586
- c.why += `; ${c.route} declares no delegation parent or escalates_to, so this finding goes to ${choices[chosen]}, ${FAILED_WAKE_ROUTE_RULES[chosen]}`;
1587
- c.route = choices[chosen];
1588
- if (chosen === 0)
1589
- c.failedWakeToCreator = true;
1590
- };
1591
- /** The three re-routes, in order, for one candidate. The third reads no earlier pass: a failed wake's finding is
1592
- * routed only here, on the row as it is right before the finding is created. */
1593
- const routeCandidate = (c) => { routeAroundMissing(c); routeAroundNoWake(c); routeAroundFailedWake(c); };
1594
- const selfRoutedUnclaimed = (c) => c.kind === "unclaimed-obligation"
1595
- && c.route === c.row.destinationSession && !routeNotes.has(c.row.qitemId) && agentSeatNode(c.route) !== null;
1596
- // A hosted member that polls for its work (no wake trigger) can't hear a finding, so each unclaimed row went to a
1597
- // person as a finding of its own. Those rows share one standing notice per member instead, unless a route the member
1598
- // declares (a delegation parent or escalates_to) takes them.
1599
- const polledUnclaimed = (c) => c.kind === "unclaimed-obligation" && c.noWake === true
1600
- && !routeNotes.has(c.row.qitemId) && polledRow(c.row);
1601
- // #2988: an unclaimed row whose finding goes to its seat's one declared delegation parent (a live seat the re-routes
1602
- // left in place) shares one standing notice per (parent, child seat) instead of a finding per row, each waking the
1603
- // parent. A route the row's seat declares otherwise (escalates_to, a consumed hop, a re-route) keeps a finding per row.
1604
- const parentRoutedUnclaimed = (c) => c.kind === "unclaimed-obligation" && c.noWake !== true
1605
- && c.route !== c.row.destinationSession && delegationParent.get(c.row.qitemId) === c.route
1606
- && !routeNotes.has(c.row.qitemId) && !routed.has(c.row.qitemId);
1607
- /** The standing notice a candidate belongs to (the seat or member it stands for, or the parent and child seat), or null
1608
- * for a finding of its own. */
1609
- const backlogKeyOf = (c) => polledUnclaimed(c) ? c.row.destinationSession : selfRoutedUnclaimed(c) ? c.route
1610
- : parentRoutedUnclaimed(c) ? `${c.row.destinationSession}${PARENT_BACKLOG_SEPARATOR}${c.route}` : null;
1611
- /** #2988's transition: an open per-row unclaimed finding the sweep filed to the parent before, for a row that now joins
1612
- * that parent's notice. It's folded in (closed, once the notice that takes its row is written) rather than kept
1613
- * beside the notice. Keyed by the row; the value is the per-row finding. */
1614
- const foldFrom = new Map();
1615
- /** The per-row finding this candidate's row would fold into a parent's notice, or null. */
1616
- const foldable = (c, shared) => {
1617
- // Only one nobody has taken up: a finding the parent claimed or parked is its work now, and stays as it is.
1618
- if (!shared || shared.state !== "pending" || !parentRoutedUnclaimed(c))
1619
- return null;
1620
- const finding = indexed(() => deps.queueRepo.getById(shared.qitemId, { waiting: false }));
1621
- return finding && isFindingRow(finding) && finding.state === "pending" && !finding.claimedAt
1622
- && finding.destinationSession === c.route
1623
- && (finding.tags ?? []).includes(findingDedupTag("unclaimed-obligation", c.row.qitemId)) ? finding.qitemId : null;
1624
- };
1625
- /** The batch successor index reads a seat's chained rows only from its oldest seat-naming source's creation, so its
1626
- * "no successor" is a candidate, not a verdict: a custody finding it would keep open is confirmed on the row as it is
1627
- * now, as a new one already is before it's created. Every one is confirmed, whatever the mode is now: a yield can
1628
- * switch the pass to per-row reads after the candidate came from the index. True when the row no longer qualifies,
1629
- * so nothing is kept. */
1630
- const keptOnBoundedRead = (c) => c.kind === "dangling-closure" && freshCandidate(c.kind, c.row.qitemId) === null;
1631
- const isHumanTarget = (session) => {
1632
- try {
1633
- return deps.queueRepo.isHumanDestination(session);
1634
- }
1635
- catch {
1636
- return true;
1637
- }
1638
- };
1639
- const sessionStoppedOrMissing = (session) => {
1640
- if (sessionMissing(session))
1641
- return true;
1642
- const row = deps.db.prepare("SELECT status FROM sessions WHERE session_name = ? ORDER BY id DESC LIMIT 1").get(session);
1643
- return !row || ["exited", "superseded", "detached"].includes(row.status);
1644
- };
1645
- const isUnreachableUnclaimed = (c) => c.kind === "unclaimed-obligation"
1646
- && c.route === c.row.destinationSession
1647
- && !routeNotes.has(c.row.qitemId)
1648
- && !polledRow(c.row)
1649
- && !isHumanTarget(c.row.destinationSession)
1650
- && (classOf(c.row.destinationSession) === "unroutable" || sessionMissing(c.row.destinationSession))
1651
- && sessionStoppedOrMissing(c.row.destinationSession);
1652
- const activeBacklogKeyOf = (c) => {
1653
- const key = backlogKeyOf(c);
1654
- if (!key)
1655
- return null;
1656
- return selfRoutedUnclaimed(c) && isUnreachableUnclaimed(c) ? null : key;
1657
- };
1658
- const unroutableGroups = new Map();
1659
- const enqueueUnroutable = (candidate) => {
1660
- const groupKey = `${candidate.row.sourceSession}${UNROUTABLE_NOTICE_SEPARATOR}${candidate.row.destinationSession}`;
1661
- const group = unroutableGroups.get(groupKey);
1662
- if (group)
1663
- group.rows.push(candidate);
1664
- else
1665
- unroutableGroups.set(groupKey, { source: candidate.row.sourceSession, destination: candidate.row.destinationSession, rows: [candidate] });
1666
- };
1667
- const unclaimedBacklog = new Map();
1668
- for (const c of [...new Map(candidates.map(c => [c.row.qitemId, c])).values()]) {
1669
- if (dueToYield())
1670
- await yieldLoop();
1671
- // #3315: a terminal server can be lost during the pass too, with no maintenance drain active.
1672
- if (deps.queueRepo.deliveryDrains.anyHeld()
1673
- && deliveryHeld(deps.queueRepo.getById(c.row.qitemId, { waiting: false }) ?? c.row)) {
1674
- drainDeferredIds.add(c.row.qitemId);
1675
- continue;
1676
- }
1677
- const dedupTag = findingDedupTag(c.kind, c.row.qitemId);
1678
- const shared = recoveries.find(c.row.qitemId);
1679
- const fold = foldable(c, shared);
1680
- const backlogKey = shared && !fold ? null : activeBacklogKeyOf(c);
1681
- if (backlogKey) {
1682
- if (fold)
1683
- foldFrom.set(c.row.qitemId, fold);
1684
- else
1685
- foldFrom.delete(c.row.qitemId);
1686
- const rows = unclaimedBacklog.get(backlogKey);
1687
- if (rows)
1688
- rows.push(c);
1689
- else
1690
- unclaimedBacklog.set(backlogKey, [c]);
1691
- continue;
1692
- }
1693
- if (!shared && isUnreachableUnclaimed(c)) {
1694
- enqueueUnroutable(c);
1695
- continue;
1696
- }
1697
- const sharedRow = shared ? indexed(() => deps.queueRepo.getById(shared.qitemId, { waiting: false })) : null;
1698
- // A later accepted deadline can expire after the previous finding closed.
1699
- // Its newer time is fresh evidence even when the pickup candidate wins this row.
1700
- // An OPEN recovery still owns custody.
1701
- const renewedDeadline = c.row.state === "in-progress" && sharedRow
1702
- && Date.parse(c.row.closureRequiredAt ?? "") <= now.getTime()
1703
- && !["pending", "in-progress", "blocked"].includes(sharedRow.state)
1704
- && evidenceIsNewer(c.row.closureRequiredAt ?? "", sharedRow.tsUpdated);
1705
- if (shared && !renewedDeadline) {
1706
- if (keptOnBoundedRead(c) && ["pending", "in-progress", "blocked"].includes(shared.state))
1707
- continue;
1708
- const existingTags = sharedRow?.tags ?? [];
1709
- for (const tag of existingTags)
1710
- if (tag.startsWith("stuck-sweep:"))
1711
- liveDedupTags.add(tag);
1712
- // Keep the original evidence as history, but do not leave it presented as
1713
- // the current reason when a different condition now owns this recovery.
1714
- // Only the sweep's own findings are mutable here, and only while they carry
1715
- // the title it wrote: other recovery rows that share custody, and a title a
1716
- // person or agent set, keep their author's text.
1717
- if (sharedRow && isFindingRow(sharedRow) && sweepTitled(sharedRow, c.row.qitemId)) {
1718
- const currentKind = findingKindOf(sharedRow);
1719
- const pickupOrDeadline = (kind) => kind === "stalled-after-claim" || kind === "overdue-claim";
1720
- const humanUpdateNotice = currentKind === "unclaimed-obligation"
1721
- && c.kind === "undelivered-human-notice"
1722
- && deps.queueRepo.isRegisteredHumanUpdate(c.row);
1723
- if (currentKind && currentKind !== c.kind && ((pickupOrDeadline(currentKind) && pickupOrDeadline(c.kind)) || humanUpdateNotice)
1724
- && stillStuck(c)) { // the new reason must still hold on the row as it is now
1725
- const marker = "\n\n--- Original finding (historical) ---\n";
1726
- const original = sharedRow.body.includes(marker) ? sharedRow.body.split(marker, 2)[1] : sharedRow.body;
1727
- const body = evidenceBody(deps.db, c) + marker + original;
1728
- const summary = findingTitle(c.kind, c.row.qitemId, c.ageMinutes);
1729
- deps.db.prepare("UPDATE queue_items SET body = ?, summary = ? WHERE qitem_id = ? AND body = ? AND summary = ? AND state IN ('pending', 'in-progress', 'blocked')")
1730
- .run(body, summary, shared.qitemId, sharedRow.body, sharedRow.summary);
1731
- }
1732
- }
1733
- if (["pending", "in-progress", "blocked"].includes(shared.state))
1734
- findings.push({ kind: c.kind, qitemId: c.row.qitemId, findingQitemId: shared.qitemId, action: "refreshed" });
1735
- continue;
1529
+ for (const c of candidates) {
1530
+ if (dueToYield())
1531
+ await yieldLoop();
1532
+ routeAroundNoWake(c);
1736
1533
  }
1737
- liveDedupTags.add(dedupTag);
1738
- const existing = deps.db
1739
- .prepare(
1740
- // The first term is implied by the second (its pattern starts with that literal); it lets
1741
- // the planner use idx_queue_items_recovery_tags (migration 099) instead of a full scan.
1742
- `SELECT qitem_id, source_session, state, ts_updated FROM queue_items
1743
- WHERE (tags LIKE '%"stuck-sweep:%') AND tags LIKE ? AND tags NOT LIKE '%"${BACKLOG_FOLDED_TAG}"%'
1744
- ORDER BY CASE WHEN state IN ('pending', 'in-progress', 'blocked') THEN 0 ELSE 1 END,
1745
- ts_updated DESC, ts_created DESC, qitem_id DESC
1746
- LIMIT 1`)
1747
- .get(`%"${dedupTag}"%`);
1748
- const existingIsOpen = existing && ["pending", "in-progress", "blocked"].includes(existing.state);
1749
- if (existing && existingIsOpen) {
1750
- if (keptOnBoundedRead(c)) {
1751
- liveDedupTags.delete(dedupTag);
1752
- continue;
1534
+ // Route: idempotent per (row, kind). An existing open finding refreshes its age; a
1535
+ // new one is created durable + waking (the create path's default nudge).
1536
+ const findings = [];
1537
+ const liveDedupTags = new Set();
1538
+ const candidateIds = new Set(candidates.map((c) => c.row.qitemId));
1539
+ const drainDeferredIds = new Set();
1540
+ const failedCreates = [];
1541
+ const unknownRig = (err) => err instanceof QueueRepositoryError && err.code === "unknown_destination_rig";
1542
+ const missingRig = (seat) => parseSessionName(seat).kind === "canonical" && !deps.queueRepo.acceptsDestination(seat);
1543
+ const sourceAgent = (source, destination) => source !== destination && parseSessionName(source).kind === "canonical" && !isHumanSeatSessionRef(source)
1544
+ && !isMachinerySession(source) && deps.queueRepo.acceptsDestination(source) && !sessionMissing(source)
1545
+ && !deps.queueRepo.isHumanDestination(source) && !isBoundTerminalSeat(deps.db, source) ? source : null;
1546
+ const gapNote = (source, destination) => `stuck-sweep routing gap: ${destination} references an unknown rig; no route to originating agent ${source}`;
1547
+ const hasGap = deps.db.prepare(`SELECT 1 FROM queue_transitions WHERE qitem_id = ? AND actor_session = 'daemon@system' AND transition_note = ? LIMIT 1`);
1548
+ const reportGap = (action) => {
1549
+ const { row, kind, destination, findingQitemId = "" } = action;
1550
+ const note = gapNote(row.sourceSession, destination);
1551
+ if (!hasGap.get(row.qitemId, note)) {
1552
+ // A same-state daemon note is bookkeeping, not work progress or a new recovery episode.
1553
+ deps.queueRepo.transitionLog.append({ qitemId: row.qitemId, state: row.state, actorSession: "daemon@system", transitionNote: note });
1554
+ log(`[stuck-sweep] ${row.qitemId}: ${note}`);
1753
1555
  }
1754
- // Age is derived at read time; an unchanged scan is not a transition.
1755
- findings.push({ kind: c.kind, qitemId: c.row.qitemId, findingQitemId: existing.qitem_id, action: "refreshed" });
1756
- }
1757
- else if (renewedDeadline || !existing || evidenceIsNewer(c.evidenceAt, existing.ts_updated)) {
1758
- // The row was found stuck before the pass's later yields and awaited writes: its rule runs again on the row as
1759
- // it is now, and a row that no longer qualifies gets no new finding (its dedup tag stays live this pass).
1760
- // the escalation note and hop recorded at listing belong to that route; keep only what this run records
1761
- routeNotes.delete(c.row.qitemId);
1762
- routed.delete(c.row.qitemId);
1763
- const now_ = freshCandidate(c.kind, c.row.qitemId, c.jobId);
1764
- if (!now_)
1765
- continue;
1766
- routeCandidate(now_); // its destination, reason and targets as they are now
1767
- if (!shared && !activeBacklogKeyOf(now_) && isUnreachableUnclaimed(now_)) {
1768
- enqueueUnroutable(now_);
1556
+ findings.push({ kind, qitemId: row.qitemId, findingQitemId, action: "unreported", destination });
1557
+ };
1558
+ const recordFailure = (context, err) => {
1559
+ const message = `${context}: ${err instanceof Error ? err.message : String(err)}`;
1560
+ log(`[stuck-sweep] ${message}`);
1561
+ failedCreates.push(message);
1562
+ };
1563
+ // Selected by the finding tag alone: a handoff gives its successor an ordinary qitem id while keeping the tags, so
1564
+ // an id-prefix filter would miss a finding handed to a source whose origin rig is later deleted.
1565
+ const pendingFindings = deps.db.prepare(`
1566
+ SELECT qitem_id, destination_session FROM queue_items
1567
+ WHERE state = 'pending' AND claimed_at IS NULL AND tags LIKE ?`)
1568
+ .all(`%"${STUCK_SWEEP_FINDING_TAG}"%`);
1569
+ const perRowKinds = ["overdue-claim", "undelivered-wake", "undelivered-human-notice",
1570
+ "unclaimed-obligation", "dangling-closure", "stalled-after-claim", "unconsumed-wait", "parked-owner-no-input"];
1571
+ for (const ref of pendingFindings) {
1572
+ if (dueToYield())
1573
+ await yieldLoop();
1574
+ if (!missingRig(ref.destination_session))
1769
1575
  continue;
1770
- }
1771
- // A person's own row (their answer or ask) waits on a live agent seat that only couldn't take a wake, and its
1772
- // finding comes back to them (routeAroundFailedWake). Nothing in it is theirs to do, so it reaches them as a notice
1773
- // from OpenRig: an update from the sweep, at the person's own address, never an ask from themselves. The other
1774
- // routes back to a creator (no wake route, a terminal seat, a missing seat) ask the person to act, and stay asks.
1775
- // When the person's address can't be read, the finding is written as before, so it's never lost.
1776
- let noticeTo = null;
1777
- if (c.kind === "undelivered-wake" && !now_.verificationTargets && now_.failedWakeToCreator && now_.route === now_.row.sourceSession) {
1778
- try {
1779
- const person = isHumanSeatSessionRef(now_.route) ? now_.route : deps.queueRepo.reachablePerson(now_.route);
1780
- noticeTo = person && isHumanSeatSessionRef(person) ? person : null;
1781
- }
1782
- catch {
1783
- noticeTo = null;
1784
- }
1785
- }
1786
- const personNotice = noticeTo !== null;
1787
- const input = {
1788
- // A finding folded into a parent's notice (#2988) holds its id without owning the row: a new one gets its own.
1789
- qitemId: freshRecoveryId(deps.db, c.row.qitemId, renewedDeadline ? c.row.closureRequiredAt : undefined),
1790
- // The detector is machinery, not a seat: the obligation's own creator is the
1791
- // finding's source (the workflow-exception precedent), except on a person's notice about their own row.
1792
- sourceSession: personNotice ? STUCK_SWEEP_SESSION : c.row.sourceSession,
1793
- destinationSession: noticeTo ?? now_.route,
1794
- body: evidenceBody(deps.db, now_, personNotice) + (routeNotes.has(c.row.qitemId) ? `\nescalation route: ${routeNotes.get(c.row.qitemId)}` : ""),
1795
- summary: now_.verificationTargets
1796
- ? custodyHeadline(c.row.qitemId, now_.verificationTargets, now_.ageMinutes)
1797
- : personNotice
1798
- ? personNoticeTitle(c.row.qitemId, now_.row.destinationSession, now_.ageMinutes)
1799
- : findingTitle(c.kind, c.row.qitemId, now_.ageMinutes),
1800
- ...(personNotice ? { humanIntent: "update" } : {}),
1801
- evidenceRef: `rig queue show ${c.row.qitemId}`,
1802
- tags: [STUCK_SWEEP_FINDING_TAG, dedupTag, recoveryTag(c.row.qitemId),
1803
- ...(routed.has(c.row.qitemId) || now_.row.tags?.includes(ESCALATION_HOP_TAG) ? [ESCALATION_HOP_TAG] : []),
1804
- ...(now_.row.tags ?? []).filter((tag) => /^(project|mission|slice):/.test(tag))],
1805
- // OpenRig's own finding, whoever created the stuck row.
1806
- wakeTrigger: "openrig",
1807
- };
1808
- const createFinding = async (payload) => {
1809
- const created = await deps.queueRepo.create(payload);
1810
- // An existing row with this id, same source and destination, comes back as an idempotent retry: a closed one is
1811
- // no finding for the row now, so it's reported, never counted as created.
1812
- if (!["pending", "in-progress", "blocked"].includes(created.state)) {
1813
- throw new Error(`${created.qitemId} already exists and is ${created.state}`);
1814
- }
1815
- findings.push({ kind: c.kind, qitemId: c.row.qitemId, findingQitemId: created.qitemId, action: "created" });
1816
- };
1817
- const failure = `${c.kind} finding for ${c.row.qitemId} to ${now_.route} not created`;
1818
- if (!missingRig(now_.route) && !(hasGap.get(c.row.qitemId, gapNote(now_.row.sourceSession, now_.route))
1819
- && !deps.queueRepo.acceptsDestination(now_.route))) {
1820
- try {
1821
- await createFinding(input);
1822
- othersMayHaveRun();
1823
- continue;
1824
- }
1825
- catch (err) {
1826
- othersMayHaveRun();
1827
- if (!unknownRig(err)) {
1828
- recordFailure(failure, err);
1829
- continue;
1830
- }
1831
- }
1832
- }
1833
- routeNotes.delete(c.row.qitemId);
1834
- routed.delete(c.row.qitemId);
1835
- const live = freshCandidate(c.kind, c.row.qitemId, c.jobId);
1836
- if (!live || deliveryHeld(live.row) || recoveries.find(c.row.qitemId))
1576
+ const row = indexed(() => deps.queueRepo.getById(ref.qitem_id, { waiting: false }));
1577
+ if (!row || row.state !== "pending" || row.claimedAt || row.destinationSession !== ref.destination_session || deliveryHeld(row))
1837
1578
  continue;
1838
- routeCandidate(live);
1839
- if (live.route !== now_.route)
1579
+ const kind = perRowKinds.find((kind) => kind === findingKindOf(row)?.replace(/^successor-verification-required$/, "dangling-closure"));
1580
+ if (!kind || !isFindingRow(row))
1840
1581
  continue;
1841
- const target = sourceAgent(live.row.sourceSession, now_.route);
1582
+ const target = sourceAgent(row.sourceSession, row.destinationSession);
1842
1583
  if (target) {
1843
1584
  try {
1844
- // To an agent: the finding as it always was, never a person's notice.
1845
- await createFinding({ ...input, destinationSession: target, sourceSession: c.row.sourceSession, humanIntent: undefined,
1846
- summary: personNotice ? findingTitle(c.kind, c.row.qitemId, now_.ageMinutes) : input.summary,
1847
- tags: input.tags.filter((tag) => tag !== ESCALATION_HOP_TAG || live.row.tags?.includes(tag)),
1848
- body: `${evidenceBody(deps.db, live)}\nOriginal finding destination ${now_.route} references a missing rig. This finding goes to the originating agent.` });
1585
+ const { created } = await deps.queueRepo.handoff({
1586
+ qitemId: row.qitemId, fromSession: "stuck-sweep@system", toSession: target,
1587
+ body: `${row.body}\n\nOriginal finding destination ${row.destinationSession} references a missing rig. This finding was handed back to the originating agent.`,
1588
+ summary: row.summary, evidenceRef: row.evidenceRef, evidenceRefRoots: row.evidenceRefRoots,
1589
+ });
1849
1590
  othersMayHaveRun();
1591
+ findings.push({ kind, qitemId: row.qitemId, findingQitemId: created.qitemId, action: "created" });
1850
1592
  continue;
1851
1593
  }
1852
1594
  catch (err) {
1853
1595
  othersMayHaveRun();
1854
1596
  if (!unknownRig(err)) {
1855
- recordFailure(`${failure} (source fallback to ${target})`, err);
1597
+ recordFailure(`orphaned finding ${row.qitemId} not handed off`, err);
1856
1598
  continue;
1857
1599
  }
1858
1600
  }
1859
1601
  }
1860
- reportGap({ row: live.row, kind: live.kind, destination: now_.route });
1602
+ reportGap({ row, kind, destination: row.destinationSession, findingQitemId: row.qitemId });
1861
1603
  }
1862
- }
1863
- // A seat's standing notice for those rows. It stands for every row it has listed until that row is resolved at its
1864
- // source (the evidence a finding per row needs to close: claimed, parked, closed) or gets a finding of its own, so a
1865
- // detection filter (a raised threshold, the wake ladder) never reads as done. While any is left it stays open and is
1866
- // rewritten in place; once none is, the sweep closes it. A closed notice, dismissed or resolved, holds back only the
1867
- // rows it stood for, each only until it has newer evidence than the close: any other row files a new notice. It wakes
1868
- // the seat once, when it's filed.
1869
- const backlogRow = (c) => ({ qitemId: c.row.qitemId, since: c.evidenceAt, from: c.row.sourceSession, summary: c.row.summary });
1870
- const backlogPrefix = unclaimedBacklogTag("");
1871
- const backlogSeats = new Set(unclaimedBacklog.keys());
1872
- for (const { tags } of deps.db.prepare(`SELECT tags FROM queue_items WHERE state IN ('pending', 'in-progress', 'blocked')
1873
- AND (tags LIKE '%"stuck-sweep:%') AND tags LIKE ?`).all(`%"${backlogPrefix}%`)) {
1874
- try {
1875
- for (const tag of JSON.parse(tags))
1876
- if (tag.startsWith(backlogPrefix))
1877
- backlogSeats.add(tag.slice(backlogPrefix.length));
1878
- }
1879
- catch { /* Skip malformed tags */ }
1880
- }
1881
- /** #2988: the one declared delegation parent a seat's rows go to now, or null (none, several, another route, or a
1882
- * resolver the caller supplied, whose outcome isn't known). Read once per seat until other code may have run. */
1883
- const parentNow = (seat) => {
1884
- if (deps.resolveOrchestrator)
1885
- return null;
1886
- if (!parentsNow.has(seat)) {
1887
- const route = resolveEscalationOwner(deps.db, seat, target => deps.queueRepo.acceptsDestination(target));
1888
- parentsNow.set(seat, route.outcome === "parent" ? route.owner : null);
1889
- }
1890
- return parentsNow.get(seat);
1891
- };
1892
- /** #2988: the open notice with this key lists the row (one actually written: a create that failed leaves the row
1893
- * where it was). */
1894
- const openNoticeLists = (tag, id) => {
1895
- const open = deps.db.prepare(`SELECT body FROM queue_items WHERE state IN ('pending', 'in-progress', 'blocked')
1896
- AND (tags LIKE '%"stuck-sweep:%') AND tags LIKE ? ESCAPE '\\' LIMIT 1`)
1897
- .get(`%"${tag.replace(/[\\%_]/g, (ch) => `\\${ch}`)}"%`);
1898
- return open ? backlogRowsOf(open.body)?.has(id) === true : false;
1899
- };
1900
- /** #2988: an open notice to this seat's delegation parent lists the row. */
1901
- const parentNoticeStandsFor = (seat, id) => {
1902
- const parent = parentNow(seat);
1903
- return parent ? openNoticeLists(parentBacklogTag(parent, seat), id) : false;
1904
- };
1905
- /** #2988: a row a parent's notice stands for no longer goes to that parent (another parent, none, or a used hop). The
1906
- * notice lets go of it only once something written stands for it where it goes now: the open notice it goes to lists
1907
- * it, or a closed one there holds it back this pass (a finding of its own lets go of it before this). Under a detection
1908
- * filter (a raised threshold, the wake ladder), or while that notice can't be written, nothing does, and the old notice
1909
- * keeps standing for it: a detection filter never reads as done. A pass files a seat's rows before it reads the notices no row goes to, so a
1910
- * row usually moves in one pass; at worst it is in both notices for one more. */
1911
- /** #2988: per notice key, the rows a closed notice held back this pass (below), so a notice a row leaves can tell. */
1912
- const heldBack = new Map();
1913
- const coveredElsewhere = (seat, id) => {
1914
- if (hasConsumedEscalationHop(deps.db, id))
1915
- return false;
1916
- const next = parentNow(seat);
1917
- const tag = next ? parentBacklogTag(next, seat) : unclaimedBacklogTag(seat);
1918
- // A closed notice there that holds the row back (dismissed by where it goes now) stands for it too.
1919
- return openNoticeLists(tag, id) || heldBack.get(tag)?.has(id) === true;
1920
- };
1921
- /** Closes the per-row findings a parent's notice now stands for (#2988's transition), once that notice is written. The
1922
- * rows and their findings were read before the pass yielded and awaited writes, so each fold rechecks, right before
1923
- * it writes and with nothing awaited in between, everything it rests on: the row still waits unclaimed at the
1924
- * seat, the seat's one declared delegation parent is still this parent (and the row's one hop unused), the
1925
- * finding is still the row's open recovery, nobody's taken it up, and the written notice is open and lists the
1926
- * row. Anything else, or anything it can't read, leaves the finding open and unmarked. */
1927
- const foldInto = async (noticeId, seat, parent, rowIds) => {
1928
- for (const id of rowIds) {
1929
- const findingId = foldFrom.get(id);
1930
- if (!findingId)
1931
- continue;
1932
- foldFrom.delete(id);
1604
+ // #2430: an unclaimed row whose finding would go back to its own agent seat (no delegation parent and no escalates_to
1605
+ // route declared) tells that seat nothing: it already holds the row. A seat that reads its rows without claiming
1606
+ // them, a person's front door, got one such finding per row. Those rows share one standing notice per seat instead
1607
+ // (below). A finding per row stays for a person's address or a terminal seat, for a declared route that failed (its
1608
+ // finding names why, and a declared delegation parent with no session is one), and for a row that already has a
1609
+ // recovery.
1610
+ /** An agent seat's node: one whose runtime isn't a terminal, with no declared delegation parent, at an address that
1611
+ * isn't a person's. An address the human registry can't classify counts as a person's. null for anything else. Read
1612
+ * once per seat until other code may have run (agentSeats). */
1613
+ const agentSeatNode = (session) => {
1614
+ if (agentSeats.has(session))
1615
+ return agentSeats.get(session);
1616
+ const nodeId = resolveSessionNodeId(deps.db, session);
1617
+ const node = nodeId ? deps.db.prepare(`SELECT n.logical_id AS logicalId, n.runtime AS runtime, r.name AS rig,
1618
+ EXISTS (SELECT 1 FROM edges e WHERE e.target_id = n.id AND e.kind = 'delegates_to') AS parent
1619
+ FROM nodes n JOIN rigs r ON r.id = n.rig_id WHERE n.id = ?`)
1620
+ .get(nodeId) : undefined;
1621
+ let agent = null;
1622
+ try {
1623
+ if (node && node.runtime !== "terminal" && !node.parent && !deps.queueRepo.isHumanDestination(session)) {
1624
+ agent = { logicalId: node.logicalId, rig: node.rig };
1625
+ }
1626
+ }
1627
+ catch { /* unclassifiable: a person's, as above */ }
1628
+ agentSeats.set(session, agent);
1629
+ return agent;
1630
+ };
1631
+ // A wake that failed at a live agent seat with no delegation parent or escalates_to made its finding that same seat's,
1632
+ // so the finding's own wake went to the seat that had just failed to take one, onto whatever was in its input box.
1633
+ // The row's creator can act on it (resend, reroute or ask), as the waiting and parked-owner findings already route;
1634
+ // for a seat that sent itself the work, a row OpenRig's own machinery created, or a creator that is a bound terminal
1635
+ // seat (nothing there can claim it, as for the no-wake rule), the operator agent can. A declared
1636
+ // route that failed keeps its fallback, and a finding the two re-routes above moved keeps its recipient. A wake that
1637
+ // found no route never reached the seat, so a seat launched since keeps its own finding, whose wake is the one it missed.
1638
+ const routeAroundFailedWake = (c) => {
1639
+ if (c.kind !== "undelivered-wake" || !startsWithCI(c.row.lastNudgeResult, "failed:") || c.noWake
1640
+ || c.route !== c.row.destinationSession
1641
+ || routeNotes.has(c.row.qitemId) || agentSeatNode(c.route) === null)
1642
+ return;
1643
+ const choices = [c.row.sourceSession, (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)()];
1644
+ const chosen = choices.findIndex((seat) => !!seat && seat !== c.route && !isMachinerySession(seat)
1645
+ && !sessionMissing(seat) && deps.queueRepo.acceptsDestination(seat) && !isBoundTerminalSeat(deps.db, seat));
1646
+ if (chosen < 0) {
1647
+ c.why += `; ${c.route} declares no delegation parent or escalates_to, and its creator and the operator agent (agents.operator_session) are each unset, missing, this seat, OpenRig's own machinery, a terminal seat or not an address this queue takes, so this finding stays addressed to it`;
1648
+ return;
1649
+ }
1650
+ c.why += `; ${c.route} declares no delegation parent or escalates_to, so this finding goes to ${choices[chosen]}, ${FAILED_WAKE_ROUTE_RULES[chosen]}`;
1651
+ c.route = choices[chosen];
1652
+ if (chosen === 0)
1653
+ c.failedWakeToCreator = true;
1654
+ };
1655
+ /** The three re-routes, in order, for one candidate. The third reads no earlier pass: a failed wake's finding is
1656
+ * routed only here, on the row as it is right before the finding is created. */
1657
+ const routeCandidate = (c) => { routeAroundMissing(c); routeAroundNoWake(c); routeAroundFailedWake(c); };
1658
+ const selfRoutedUnclaimed = (c) => c.kind === "unclaimed-obligation"
1659
+ && c.route === c.row.destinationSession && !routeNotes.has(c.row.qitemId) && agentSeatNode(c.route) !== null;
1660
+ // A hosted member that polls for its work (no wake trigger) can't hear a finding, so each unclaimed row went to a
1661
+ // person as a finding of its own. Those rows share one standing notice per member instead, unless a route the member
1662
+ // declares (a delegation parent or escalates_to) takes them.
1663
+ const polledUnclaimed = (c) => c.kind === "unclaimed-obligation" && c.noWake === true
1664
+ && !routeNotes.has(c.row.qitemId) && polledRow(c.row);
1665
+ // #2988: an unclaimed row whose finding goes to its seat's one declared delegation parent (a live seat the re-routes
1666
+ // left in place) shares one standing notice per (parent, child seat) instead of a finding per row, each waking the
1667
+ // parent. A route the row's seat declares otherwise (escalates_to, a consumed hop, a re-route) keeps a finding per row.
1668
+ const parentRoutedUnclaimed = (c) => c.kind === "unclaimed-obligation" && c.noWake !== true
1669
+ && c.route !== c.row.destinationSession && delegationParent.get(c.row.qitemId) === c.route
1670
+ && !routeNotes.has(c.row.qitemId) && !routed.has(c.row.qitemId);
1671
+ /** The standing notice a candidate belongs to (the seat or member it stands for, or the parent and child seat), or null
1672
+ * for a finding of its own. */
1673
+ const backlogKeyOf = (c) => polledUnclaimed(c) ? c.row.destinationSession : selfRoutedUnclaimed(c) ? c.route
1674
+ : parentRoutedUnclaimed(c) ? `${c.row.destinationSession}${PARENT_BACKLOG_SEPARATOR}${c.route}` : null;
1675
+ /** #2988's transition: an open per-row unclaimed finding the sweep filed to the parent before, for a row that now joins
1676
+ * that parent's notice. It's folded in (closed, once the notice that takes its row is written) rather than kept
1677
+ * beside the notice. Keyed by the row; the value is the per-row finding. */
1678
+ const foldFrom = new Map();
1679
+ /** The per-row finding this candidate's row would fold into a parent's notice, or null. */
1680
+ const foldable = (c, shared) => {
1681
+ // Only one nobody has taken up: a finding the parent claimed or parked is its work now, and stays as it is.
1682
+ if (!shared || shared.state !== "pending" || !parentRoutedUnclaimed(c))
1683
+ return null;
1684
+ const finding = indexed(() => deps.queueRepo.getById(shared.qitemId, { waiting: false }));
1685
+ return finding && isFindingRow(finding) && finding.state === "pending" && !finding.claimedAt
1686
+ && finding.destinationSession === c.route
1687
+ && (finding.tags ?? []).includes(findingDedupTag("unclaimed-obligation", c.row.qitemId)) ? finding.qitemId : null;
1688
+ };
1689
+ /** The batch successor index reads a seat's chained rows only from its oldest seat-naming source's creation, so its
1690
+ * "no successor" is a candidate, not a verdict: a custody finding it would keep open is confirmed on the row as it is
1691
+ * now, as a new one already is before it's created. Every one is confirmed, whatever the mode is now: a yield can
1692
+ * switch the pass to per-row reads after the candidate came from the index. True when the row no longer qualifies,
1693
+ * so nothing is kept. */
1694
+ const keptOnBoundedRead = (c) => c.kind === "dangling-closure" && freshCandidate(c.kind, c.row.qitemId) === null;
1695
+ const isHumanTarget = (session) => {
1696
+ try {
1697
+ return deps.queueRepo.isHumanDestination(session);
1698
+ }
1699
+ catch {
1700
+ return true;
1701
+ }
1702
+ };
1703
+ const sessionStoppedOrMissing = (session) => {
1704
+ if (sessionMissing(session))
1705
+ return true;
1706
+ const row = deps.db.prepare("SELECT status FROM sessions WHERE session_name = ? ORDER BY id DESC LIMIT 1").get(session);
1707
+ return !row || ["exited", "superseded", "detached"].includes(row.status);
1708
+ };
1709
+ const isUnreachableUnclaimed = (c) => c.kind === "unclaimed-obligation"
1710
+ && c.route === c.row.destinationSession
1711
+ && !routeNotes.has(c.row.qitemId)
1712
+ && !polledRow(c.row)
1713
+ && !isHumanTarget(c.row.destinationSession)
1714
+ && (classOf(c.row.destinationSession) === "unroutable" || sessionMissing(c.row.destinationSession))
1715
+ && sessionStoppedOrMissing(c.row.destinationSession);
1716
+ const activeBacklogKeyOf = (c) => {
1717
+ const key = backlogKeyOf(c);
1718
+ if (!key)
1719
+ return null;
1720
+ return selfRoutedUnclaimed(c) && isUnreachableUnclaimed(c) ? null : key;
1721
+ };
1722
+ const unroutableGroups = new Map();
1723
+ const enqueueUnroutable = (candidate) => {
1724
+ const groupKey = `${candidate.row.sourceSession}${UNROUTABLE_NOTICE_SEPARATOR}${candidate.row.destinationSession}`;
1725
+ const group = unroutableGroups.get(groupKey);
1726
+ if (group)
1727
+ group.rows.push(candidate);
1728
+ else
1729
+ unroutableGroups.set(groupKey, { source: candidate.row.sourceSession, destination: candidate.row.destinationSession, rows: [candidate] });
1730
+ };
1731
+ const unclaimedBacklog = new Map();
1732
+ for (const c of [...new Map(candidates.map(c => [c.row.qitemId, c])).values()]) {
1933
1733
  if (dueToYield())
1934
1734
  await yieldLoop();
1935
- const row = deps.queueRepo.getById(id, { waiting: false });
1936
- if (!row || row.state !== "pending" || row.claimedAt || row.destinationSession !== seat)
1735
+ // #3315: a terminal server can be lost during the pass too, with no maintenance drain active.
1736
+ if (deps.queueRepo.deliveryDrains.anyHeld()
1737
+ && deliveryHeld(deps.queueRepo.getById(c.row.qitemId, { waiting: false }) ?? c.row)) {
1738
+ drainDeferredIds.add(c.row.qitemId);
1937
1739
  continue;
1938
- if (deps.resolveOrchestrator || hasConsumedEscalationHop(deps.db, id))
1939
- continue;
1940
- // The whole rule that made the row's finding, on the row as it is now (a wake that failed meanwhile, a person's
1941
- // ask, a live ladder), not only its state.
1942
- if (!unclaimedCandidate(id, false))
1943
- continue;
1944
- const route = resolveEscalationOwner(deps.db, seat, target => deps.queueRepo.acceptsDestination(target));
1945
- if (route.outcome !== "parent" || route.owner !== parent)
1946
- continue;
1947
- const finding = deps.db.prepare("SELECT state, claimed_at, destination_session FROM queue_items WHERE qitem_id = ?").get(findingId);
1948
- if (!finding || finding.state !== "pending" || finding.claimed_at || finding.destination_session !== parent)
1740
+ }
1741
+ const dedupTag = findingDedupTag(c.kind, c.row.qitemId);
1742
+ const shared = recoveries.find(c.row.qitemId);
1743
+ const fold = foldable(c, shared);
1744
+ const backlogKey = shared && !fold ? null : activeBacklogKeyOf(c);
1745
+ if (backlogKey) {
1746
+ if (fold)
1747
+ foldFrom.set(c.row.qitemId, fold);
1748
+ else
1749
+ foldFrom.delete(c.row.qitemId);
1750
+ const rows = unclaimedBacklog.get(backlogKey);
1751
+ if (rows)
1752
+ rows.push(c);
1753
+ else
1754
+ unclaimedBacklog.set(backlogKey, [c]);
1949
1755
  continue;
1950
- if (findQueueRecovery(deps.db, id)?.qitemId !== findingId)
1756
+ }
1757
+ if (!shared && isUnreachableUnclaimed(c)) {
1758
+ enqueueUnroutable(c);
1951
1759
  continue;
1952
- // The notice still reaches the parent: one that changed hands (a handoff, a fallback) isn't the parent's signal.
1953
- const notice = deps.db.prepare("SELECT state, body, destination_session FROM queue_items WHERE qitem_id = ?").get(noticeId);
1954
- if (!notice || !["pending", "in-progress", "blocked"].includes(notice.state) || notice.destination_session !== parent
1955
- || backlogRowsOf(notice.body)?.has(id) !== true)
1760
+ }
1761
+ const sharedRow = shared ? indexed(() => deps.queueRepo.getById(shared.qitemId, { waiting: false })) : null;
1762
+ // A later accepted deadline can expire after the previous finding closed.
1763
+ // Its newer time is fresh evidence even when the pickup candidate wins this row.
1764
+ // An OPEN recovery still owns custody.
1765
+ const renewedDeadline = c.row.state === "in-progress" && sharedRow
1766
+ && Date.parse(c.row.closureRequiredAt ?? "") <= now.getTime()
1767
+ && !["pending", "in-progress", "blocked"].includes(sharedRow.state)
1768
+ && evidenceIsNewer(c.row.closureRequiredAt ?? "", sharedRow.tsUpdated);
1769
+ if (shared && !renewedDeadline) {
1770
+ if (keptOnBoundedRead(c) && ["pending", "in-progress", "blocked"].includes(shared.state))
1771
+ continue;
1772
+ const existingTags = sharedRow?.tags ?? [];
1773
+ for (const tag of existingTags)
1774
+ if (tag.startsWith("stuck-sweep:"))
1775
+ liveDedupTags.add(tag);
1776
+ // Keep the original evidence as history, but do not leave it presented as
1777
+ // the current reason when a different condition now owns this recovery.
1778
+ // Only the sweep's own findings are mutable here, and only while they carry
1779
+ // the title it wrote: other recovery rows that share custody, and a title a
1780
+ // person or agent set, keep their author's text.
1781
+ if (sharedRow && isFindingRow(sharedRow) && sweepTitled(sharedRow, c.row.qitemId)) {
1782
+ const currentKind = findingKindOf(sharedRow);
1783
+ const pickupOrDeadline = (kind) => kind === "stalled-after-claim" || kind === "overdue-claim";
1784
+ const humanUpdateNotice = currentKind === "unclaimed-obligation"
1785
+ && c.kind === "undelivered-human-notice"
1786
+ && deps.queueRepo.isRegisteredHumanUpdate(c.row);
1787
+ if (currentKind && currentKind !== c.kind && ((pickupOrDeadline(currentKind) && pickupOrDeadline(c.kind)) || humanUpdateNotice)
1788
+ && stillStuck(c)) { // the new reason must still hold on the row as it is now
1789
+ const marker = "\n\n--- Original finding (historical) ---\n";
1790
+ const original = sharedRow.body.includes(marker) ? sharedRow.body.split(marker, 2)[1] : sharedRow.body;
1791
+ const body = evidenceBody(deps.db, c, false, seatEvidenceLines(c.row.destinationSession, deps.seatEvidence, now)) + marker + original;
1792
+ const summary = findingTitle(c.kind, c.row.qitemId, c.ageMinutes);
1793
+ deps.db.prepare("UPDATE queue_items SET body = ?, summary = ? WHERE qitem_id = ? AND body = ? AND summary = ? AND state IN ('pending', 'in-progress', 'blocked')")
1794
+ .run(body, summary, shared.qitemId, sharedRow.body, sharedRow.summary);
1795
+ }
1796
+ }
1797
+ if (["pending", "in-progress", "blocked"].includes(shared.state))
1798
+ findings.push({ kind: c.kind, qitemId: c.row.qitemId, findingQitemId: shared.qitemId, action: "refreshed" });
1956
1799
  continue;
1957
- try {
1958
- // The mark and the close together: a close that fails leaves the finding open and unmarked, as it was.
1959
- deps.db.transaction(() => {
1960
- deps.db.prepare(`UPDATE queue_items SET tags = json_insert(tags, '$[#]', ?) WHERE qitem_id = ? AND json_valid(tags)
1961
- AND NOT EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)`).run(BACKLOG_FOLDED_TAG, findingId, BACKLOG_FOLDED_TAG);
1962
- deps.queueRepo.update({
1963
- qitemId: findingId,
1964
- actorSession: "stuck-sweep@system",
1965
- state: "done",
1966
- closureReason: "no-follow-on",
1967
- transitionNote: `stuck-sweep folded: unclaimed-obligation on ${id} into the standing unclaimed-backlog notice ${noticeId} for ${parent}, which now stands for this row`,
1968
- });
1969
- })();
1970
- findings.push({ kind: "unclaimed-obligation", qitemId: id, findingQitemId: findingId, action: "closed" });
1971
1800
  }
1972
- catch (err) {
1973
- const message = `unclaimed-obligation finding ${findingId} for ${id} not folded into ${noticeId}: ${err instanceof Error ? err.message : String(err)}`;
1974
- log(`[stuck-sweep] ${message}`);
1975
- failedCreates.push(message);
1801
+ liveDedupTags.add(dedupTag);
1802
+ const existing = deps.db
1803
+ .prepare(
1804
+ // The first term is implied by the second (its pattern starts with that literal); it lets
1805
+ // the planner use idx_queue_items_recovery_tags (migration 099) instead of a full scan.
1806
+ `SELECT qitem_id, source_session, state, ts_updated FROM queue_items
1807
+ WHERE (tags LIKE '%"stuck-sweep:%') AND tags LIKE ? AND tags NOT LIKE '%"${BACKLOG_FOLDED_TAG}"%'
1808
+ ORDER BY CASE WHEN state IN ('pending', 'in-progress', 'blocked') THEN 0 ELSE 1 END,
1809
+ ts_updated DESC, ts_created DESC, qitem_id DESC
1810
+ LIMIT 1`)
1811
+ .get(`%"${dedupTag}"%`);
1812
+ const existingIsOpen = existing && ["pending", "in-progress", "blocked"].includes(existing.state);
1813
+ if (existing && existingIsOpen) {
1814
+ if (keptOnBoundedRead(c)) {
1815
+ liveDedupTags.delete(dedupTag);
1816
+ continue;
1817
+ }
1818
+ // Age is derived at read time; an unchanged scan is not a transition.
1819
+ findings.push({ kind: c.kind, qitemId: c.row.qitemId, findingQitemId: existing.qitem_id, action: "refreshed" });
1820
+ }
1821
+ else if (renewedDeadline || !existing || evidenceIsNewer(c.evidenceAt, existing.ts_updated)) {
1822
+ // The row was found stuck before the pass's later yields and awaited writes: its rule runs again on the row as
1823
+ // it is now, and a row that no longer qualifies gets no new finding (its dedup tag stays live this pass).
1824
+ // the escalation note and hop recorded at listing belong to that route; keep only what this run records
1825
+ routeNotes.delete(c.row.qitemId);
1826
+ routed.delete(c.row.qitemId);
1827
+ const now_ = freshCandidate(c.kind, c.row.qitemId, c.jobId);
1828
+ if (!now_)
1829
+ continue;
1830
+ routeCandidate(now_); // its destination, reason and targets as they are now
1831
+ if (!shared && !activeBacklogKeyOf(now_) && isUnreachableUnclaimed(now_)) {
1832
+ enqueueUnroutable(now_);
1833
+ continue;
1834
+ }
1835
+ // A person's own row (their answer or ask) waits on a live agent seat that only couldn't take a wake, and its
1836
+ // finding comes back to them (routeAroundFailedWake). Nothing in it is theirs to do, so it reaches them as a notice
1837
+ // from OpenRig: an update from the sweep, at the person's own address, never an ask from themselves. The other
1838
+ // routes back to a creator (no wake route, a terminal seat, a missing seat) ask the person to act, and stay asks.
1839
+ // When the person's address can't be read, the finding is written as before, so it's never lost.
1840
+ let noticeTo = null;
1841
+ if (c.kind === "undelivered-wake" && !now_.verificationTargets && now_.failedWakeToCreator && now_.route === now_.row.sourceSession) {
1842
+ try {
1843
+ const person = isHumanSeatSessionRef(now_.route) ? now_.route : deps.queueRepo.reachablePerson(now_.route);
1844
+ noticeTo = person && isHumanSeatSessionRef(person) ? person : null;
1845
+ }
1846
+ catch {
1847
+ noticeTo = null;
1848
+ }
1849
+ }
1850
+ const personNotice = noticeTo !== null;
1851
+ const input = {
1852
+ // A finding folded into a parent's notice (#2988) holds its id without owning the row: a new one gets its own.
1853
+ qitemId: freshRecoveryId(deps.db, c.row.qitemId, renewedDeadline ? c.row.closureRequiredAt : undefined),
1854
+ // The detector is machinery, not a seat: the obligation's own creator is the
1855
+ // finding's source (the workflow-exception precedent), except on a person's notice about their own row.
1856
+ sourceSession: personNotice ? STUCK_SWEEP_SESSION : c.row.sourceSession,
1857
+ destinationSession: noticeTo ?? now_.route,
1858
+ body: evidenceBody(deps.db, now_, personNotice, seatEvidenceLines(now_.row.destinationSession, deps.seatEvidence, now))
1859
+ + (routeNotes.has(c.row.qitemId) ? `\nescalation route: ${routeNotes.get(c.row.qitemId)}` : ""),
1860
+ summary: now_.verificationTargets
1861
+ ? custodyHeadline(c.row.qitemId, now_.verificationTargets, now_.ageMinutes)
1862
+ : personNotice
1863
+ ? personNoticeTitle(c.row.qitemId, now_.row.destinationSession, now_.ageMinutes)
1864
+ : findingTitle(c.kind, c.row.qitemId, now_.ageMinutes),
1865
+ ...(personNotice ? { humanIntent: "update" } : {}),
1866
+ evidenceRef: `rig queue show ${c.row.qitemId}`,
1867
+ tags: [STUCK_SWEEP_FINDING_TAG, dedupTag, recoveryTag(c.row.qitemId),
1868
+ ...(routed.has(c.row.qitemId) || now_.row.tags?.includes(ESCALATION_HOP_TAG) ? [ESCALATION_HOP_TAG] : []),
1869
+ ...(now_.row.tags ?? []).filter((tag) => /^(project|mission|slice):/.test(tag))],
1870
+ // OpenRig's own finding, whoever created the stuck row.
1871
+ wakeTrigger: "openrig",
1872
+ };
1873
+ const createFinding = async (payload) => {
1874
+ const created = await deps.queueRepo.create(payload);
1875
+ // An existing row with this id, same source and destination, comes back as an idempotent retry: a closed one is
1876
+ // no finding for the row now, so it's reported, never counted as created.
1877
+ if (!["pending", "in-progress", "blocked"].includes(created.state)) {
1878
+ throw new Error(`${created.qitemId} already exists and is ${created.state}`);
1879
+ }
1880
+ findings.push({ kind: c.kind, qitemId: c.row.qitemId, findingQitemId: created.qitemId, action: "created" });
1881
+ };
1882
+ const failure = `${c.kind} finding for ${c.row.qitemId} to ${now_.route} not created`;
1883
+ if (!missingRig(now_.route) && !(hasGap.get(c.row.qitemId, gapNote(now_.row.sourceSession, now_.route))
1884
+ && !deps.queueRepo.acceptsDestination(now_.route))) {
1885
+ try {
1886
+ await createFinding(input);
1887
+ othersMayHaveRun();
1888
+ continue;
1889
+ }
1890
+ catch (err) {
1891
+ othersMayHaveRun();
1892
+ if (!unknownRig(err)) {
1893
+ recordFailure(failure, err);
1894
+ continue;
1895
+ }
1896
+ }
1897
+ }
1898
+ routeNotes.delete(c.row.qitemId);
1899
+ routed.delete(c.row.qitemId);
1900
+ const live = freshCandidate(c.kind, c.row.qitemId, c.jobId);
1901
+ if (!live || deliveryHeld(live.row) || recoveries.find(c.row.qitemId))
1902
+ continue;
1903
+ routeCandidate(live);
1904
+ if (live.route !== now_.route)
1905
+ continue;
1906
+ const target = sourceAgent(live.row.sourceSession, now_.route);
1907
+ if (target) {
1908
+ try {
1909
+ // To an agent: the finding as it always was, never a person's notice.
1910
+ await createFinding({ ...input, destinationSession: target, sourceSession: c.row.sourceSession, humanIntent: undefined,
1911
+ summary: personNotice ? findingTitle(c.kind, c.row.qitemId, now_.ageMinutes) : input.summary,
1912
+ tags: input.tags.filter((tag) => tag !== ESCALATION_HOP_TAG || live.row.tags?.includes(tag)),
1913
+ body: `${evidenceBody(deps.db, live, false, seatEvidenceLines(live.row.destinationSession, deps.seatEvidence, now))}\nOriginal finding destination ${now_.route} references a missing rig. This finding goes to the originating agent.` });
1914
+ othersMayHaveRun();
1915
+ continue;
1916
+ }
1917
+ catch (err) {
1918
+ othersMayHaveRun();
1919
+ if (!unknownRig(err)) {
1920
+ recordFailure(`${failure} (source fallback to ${target})`, err);
1921
+ continue;
1922
+ }
1923
+ }
1924
+ }
1925
+ reportGap({ row: live.row, kind: live.kind, destination: now_.route });
1976
1926
  }
1977
- othersMayHaveRun();
1978
1927
  }
1979
- };
1980
- for (const key of backlogSeats) {
1981
- if (dueToYield())
1982
- await yieldLoop();
1983
- const rows = unclaimedBacklog.get(key) ?? [];
1984
- const { seat, parent } = backlogKeyParts(key);
1985
- const tag = parent ? parentBacklogTag(parent, seat) : unclaimedBacklogTag(seat);
1986
- liveDedupTags.add(tag);
1987
- const node = agentSeatNode(seat);
1988
- // A polling member's notice says whether it's checking in; an agent seat's names the route to add instead; a
1989
- // parent's says whose backlog it is.
1990
- const polled = !parent && (rows.length > 0 ? rows.some(polledUnclaimed) : pollsForWork(seat));
1991
- const backlogText = (standsFor) => parent
1992
- ? parentBacklogText(seat, parent, standsFor, ageMinutes, parentNow(seat) === parent)
1993
- : polled
1994
- ? polledBacklogText(seat, standsFor, ageMinutes, deps.queueRepo.hostedMemberCheckIn(seat, now), now)
1995
- : unclaimedBacklogText(seat, standsFor, ageMinutes, node);
1996
- // A polling member's notice goes where its rows' findings went: the person, else their creator when they share one,
1997
- // else the operator agent. With none, it stays with the member, which reads it when it next checks. A parent's
1998
- // notice goes to the parent.
1999
- const recipientFor = (creators) => {
2000
- if (parent)
2001
- return parent;
2002
- if (!polled)
2003
- return seat;
2004
- const distinct = [...new Set(creators)];
2005
- return noWakeRecipient(seat, distinct.length === 1 ? distinct[0] : null).seat ?? seat;
2006
- };
2007
- /** Files a notice and wakes its recipient; its id, or null when deferred or when the create failed (reported in failedCreates). */
2008
- const fileNotice = async (text, recipient, creators = []) => {
2009
- if (deps.queueRepo.deliveryDrains.holds(seat))
2010
- return null;
1928
+ // A seat's standing notice for those rows. It stands for every row it has listed until that row is resolved at its
1929
+ // source (the evidence a finding per row needs to close: claimed, parked, closed) or gets a finding of its own, so a
1930
+ // detection filter (a raised threshold, the wake ladder) never reads as done. While any is left it stays open and is
1931
+ // rewritten in place; once none is, the sweep closes it. A closed notice, dismissed or resolved, holds back only the
1932
+ // rows it stood for, each only until it has newer evidence than the close: any other row files a new notice. It wakes
1933
+ // the seat once, when it's filed.
1934
+ const backlogRow = (c) => ({ qitemId: c.row.qitemId, since: c.evidenceAt, from: c.row.sourceSession, summary: c.row.summary });
1935
+ const backlogPrefix = unclaimedBacklogTag("");
1936
+ const backlogSeats = new Set(unclaimedBacklog.keys());
1937
+ for (const { tags } of deps.db.prepare(`SELECT tags FROM queue_items WHERE state IN ('pending', 'in-progress', 'blocked')
1938
+ AND (tags LIKE '%"stuck-sweep:%') AND tags LIKE ?`).all(`%"${backlogPrefix}%`)) {
2011
1939
  try {
2012
- const created = await deps.queueRepo.create({
2013
- // A notice about a seat's own rows comes from that seat, as a restore notice does; OpenRig wakes its recipient.
2014
- sourceSession: seat,
2015
- destinationSession: recipient,
2016
- body: text.body,
2017
- summary: text.summary,
2018
- evidenceRef: `rig queue list --destination ${seat} --state pending`,
2019
- tags: [STUCK_SWEEP_FINDING_TAG, tag,
2020
- ...(polled && recipient !== seat && creators.length > 0 && creators.every((c) => c === recipient)
2021
- ? [creatorMark(recipient)] : [])],
2022
- wakeTrigger: "openrig",
2023
- });
2024
- othersMayHaveRun();
2025
- findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: created.qitemId, action: "created" });
2026
- return created.qitemId;
1940
+ for (const tag of JSON.parse(tags))
1941
+ if (tag.startsWith(backlogPrefix))
1942
+ backlogSeats.add(tag.slice(backlogPrefix.length));
2027
1943
  }
2028
- catch (err) {
2029
- const message = `unclaimed-backlog notice for ${parent ? `${seat}, to its delegation parent ${parent},` : seat} not created: ${err instanceof Error ? err.message : String(err)}`;
2030
- othersMayHaveRun();
2031
- log(`[stuck-sweep] ${message}`);
2032
- failedCreates.push(message);
1944
+ catch { /* Skip malformed tags */ }
1945
+ }
1946
+ /** #2988: the one declared delegation parent a seat's rows go to now, or null (none, several, another route, or a
1947
+ * resolver the caller supplied, whose outcome isn't known). Read once per seat until other code may have run. */
1948
+ const parentNow = (seat) => {
1949
+ if (deps.resolveOrchestrator)
2033
1950
  return null;
1951
+ if (!parentsNow.has(seat)) {
1952
+ const route = resolveEscalationOwner(deps.db, seat, target => deps.queueRepo.acceptsDestination(target));
1953
+ parentsNow.set(seat, route.outcome === "parent" ? route.owner : null);
2034
1954
  }
1955
+ return parentsNow.get(seat);
2035
1956
  };
2036
- const last = deps.db
2037
- .prepare(
2038
- // The first term lets the planner use idx_queue_items_recovery_tags, as the finding lookup above does.
2039
- `SELECT qitem_id, state, ts_updated, summary, body, destination_session, tags FROM queue_items
1957
+ /** #2988: the open notice with this key lists the row (one actually written: a create that failed leaves the row
1958
+ * where it was). */
1959
+ const openNoticeLists = (tag, id) => {
1960
+ const open = deps.db.prepare(`SELECT body FROM queue_items WHERE state IN ('pending', 'in-progress', 'blocked')
1961
+ AND (tags LIKE '%"stuck-sweep:%') AND tags LIKE ? ESCAPE '\\' LIMIT 1`)
1962
+ .get(`%"${tag.replace(/[\\%_]/g, (ch) => `\\${ch}`)}"%`);
1963
+ return open ? backlogRowsOf(open.body)?.has(id) === true : false;
1964
+ };
1965
+ /** #2988: an open notice to this seat's delegation parent lists the row. */
1966
+ const parentNoticeStandsFor = (seat, id) => {
1967
+ const parent = parentNow(seat);
1968
+ return parent ? openNoticeLists(parentBacklogTag(parent, seat), id) : false;
1969
+ };
1970
+ /** #2988: a row a parent's notice stands for no longer goes to that parent (another parent, none, or a used hop). The
1971
+ * notice lets go of it only once something written stands for it where it goes now: the open notice it goes to lists
1972
+ * it, or a closed one there holds it back this pass (a finding of its own lets go of it before this). Under a detection
1973
+ * filter (a raised threshold, the wake ladder), or while that notice can't be written, nothing does, and the old notice
1974
+ * keeps standing for it: a detection filter never reads as done. A pass files a seat's rows before it reads the notices no row goes to, so a
1975
+ * row usually moves in one pass; at worst it is in both notices for one more. */
1976
+ /** #2988: per notice key, the rows a closed notice held back this pass (below), so a notice a row leaves can tell. */
1977
+ const heldBack = new Map();
1978
+ const coveredElsewhere = (seat, id) => {
1979
+ if (hasConsumedEscalationHop(deps.db, id))
1980
+ return false;
1981
+ const next = parentNow(seat);
1982
+ const tag = next ? parentBacklogTag(next, seat) : unclaimedBacklogTag(seat);
1983
+ // A closed notice there that holds the row back (dismissed by where it goes now) stands for it too.
1984
+ return openNoticeLists(tag, id) || heldBack.get(tag)?.has(id) === true;
1985
+ };
1986
+ /** Closes the per-row findings a parent's notice now stands for (#2988's transition), once that notice is written. The
1987
+ * rows and their findings were read before the pass yielded and awaited writes, so each fold rechecks, right before
1988
+ * it writes and with nothing awaited in between, everything it rests on: the row still waits unclaimed at the
1989
+ * seat, the seat's one declared delegation parent is still this parent (and the row's one hop unused), the
1990
+ * finding is still the row's open recovery, nobody's taken it up, and the written notice is open and lists the
1991
+ * row. Anything else, or anything it can't read, leaves the finding open and unmarked. */
1992
+ const foldInto = async (noticeId, seat, parent, rowIds) => {
1993
+ for (const id of rowIds) {
1994
+ const findingId = foldFrom.get(id);
1995
+ if (!findingId)
1996
+ continue;
1997
+ foldFrom.delete(id);
1998
+ if (dueToYield())
1999
+ await yieldLoop();
2000
+ const row = deps.queueRepo.getById(id, { waiting: false });
2001
+ if (!row || row.state !== "pending" || row.claimedAt || row.destinationSession !== seat)
2002
+ continue;
2003
+ if (deps.resolveOrchestrator || hasConsumedEscalationHop(deps.db, id))
2004
+ continue;
2005
+ // The whole rule that made the row's finding, on the row as it is now (a wake that failed meanwhile, a person's
2006
+ // ask, a live ladder), not only its state.
2007
+ if (!unclaimedCandidate(id, false))
2008
+ continue;
2009
+ const route = resolveEscalationOwner(deps.db, seat, target => deps.queueRepo.acceptsDestination(target));
2010
+ if (route.outcome !== "parent" || route.owner !== parent)
2011
+ continue;
2012
+ const finding = deps.db.prepare("SELECT state, claimed_at, destination_session FROM queue_items WHERE qitem_id = ?").get(findingId);
2013
+ if (!finding || finding.state !== "pending" || finding.claimed_at || finding.destination_session !== parent)
2014
+ continue;
2015
+ if (findQueueRecovery(deps.db, id)?.qitemId !== findingId)
2016
+ continue;
2017
+ // The notice still reaches the parent: one that changed hands (a handoff, a fallback) isn't the parent's signal.
2018
+ const notice = deps.db.prepare("SELECT state, body, destination_session FROM queue_items WHERE qitem_id = ?").get(noticeId);
2019
+ if (!notice || !["pending", "in-progress", "blocked"].includes(notice.state) || notice.destination_session !== parent
2020
+ || backlogRowsOf(notice.body)?.has(id) !== true)
2021
+ continue;
2022
+ try {
2023
+ // The mark and the close together: a close that fails leaves the finding open and unmarked, as it was.
2024
+ deps.db.transaction(() => {
2025
+ deps.db.prepare(`UPDATE queue_items SET tags = json_insert(tags, '$[#]', ?) WHERE qitem_id = ? AND json_valid(tags)
2026
+ AND NOT EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)`).run(BACKLOG_FOLDED_TAG, findingId, BACKLOG_FOLDED_TAG);
2027
+ deps.queueRepo.update({
2028
+ qitemId: findingId,
2029
+ actorSession: "stuck-sweep@system",
2030
+ state: "done",
2031
+ closureReason: "no-follow-on",
2032
+ transitionNote: `stuck-sweep folded: unclaimed-obligation on ${id} into the standing unclaimed-backlog notice ${noticeId} for ${parent}, which now stands for this row`,
2033
+ });
2034
+ })();
2035
+ findings.push({ kind: "unclaimed-obligation", qitemId: id, findingQitemId: findingId, action: "closed" });
2036
+ }
2037
+ catch (err) {
2038
+ const message = `unclaimed-obligation finding ${findingId} for ${id} not folded into ${noticeId}: ${err instanceof Error ? err.message : String(err)}`;
2039
+ log(`[stuck-sweep] ${message}`);
2040
+ failedCreates.push(message);
2041
+ }
2042
+ othersMayHaveRun();
2043
+ }
2044
+ };
2045
+ for (const key of backlogSeats) {
2046
+ if (dueToYield())
2047
+ await yieldLoop();
2048
+ const rows = unclaimedBacklog.get(key) ?? [];
2049
+ const { seat, parent } = backlogKeyParts(key);
2050
+ const tag = parent ? parentBacklogTag(parent, seat) : unclaimedBacklogTag(seat);
2051
+ liveDedupTags.add(tag);
2052
+ const node = agentSeatNode(seat);
2053
+ // A polling member's notice says whether it's checking in; an agent seat's names the route to add instead; a
2054
+ // parent's says whose backlog it is.
2055
+ const polled = !parent && (rows.length > 0 ? rows.some(polledUnclaimed) : pollsForWork(seat));
2056
+ const backlogText = (standsFor) => parent
2057
+ ? parentBacklogText(seat, parent, standsFor, ageMinutes, parentNow(seat) === parent)
2058
+ : polled && deps.queueRepo.isIssuedConversation(seat)
2059
+ ? conversationBacklogText(seat, standsFor, ageMinutes)
2060
+ : polled && deps.queueRepo.isExternalCliSeat(seat)
2061
+ ? conversationBacklogText(seat, standsFor, ageMinutes, "attached")
2062
+ : polled
2063
+ ? polledBacklogText(seat, standsFor, ageMinutes, deps.queueRepo.hostedMemberCheckIn(seat, now), now)
2064
+ : unclaimedBacklogText(seat, standsFor, ageMinutes, node);
2065
+ // A polling member's notice goes where its rows' findings went: the person, else their creator when they share one,
2066
+ // else the operator agent. With none, it stays with the member, which reads it when it next checks. A parent's
2067
+ // notice goes to the parent.
2068
+ const recipientFor = (creators) => {
2069
+ if (parent)
2070
+ return parent;
2071
+ if (!polled)
2072
+ return seat;
2073
+ const distinct = [...new Set(creators)];
2074
+ return noWakeRecipient(seat, distinct.length === 1 ? distinct[0] : null).seat ?? seat;
2075
+ };
2076
+ /** Files a notice and wakes its recipient; its id, or null when deferred or when the create failed (reported in failedCreates). */
2077
+ const fileNotice = async (text, recipient, creators = []) => {
2078
+ if (deps.queueRepo.deliveryDrains.holds(seat))
2079
+ return null;
2080
+ try {
2081
+ const created = await deps.queueRepo.create({
2082
+ // A notice about a seat's own rows comes from that seat, as a restore notice does; OpenRig wakes its recipient.
2083
+ sourceSession: seat,
2084
+ destinationSession: recipient,
2085
+ body: text.body,
2086
+ summary: text.summary,
2087
+ evidenceRef: `rig queue list --destination ${seat} --state pending`,
2088
+ tags: [STUCK_SWEEP_FINDING_TAG, tag,
2089
+ ...(polled && recipient !== seat && creators.length > 0 && creators.every((c) => c === recipient)
2090
+ ? [creatorMark(recipient)] : [])],
2091
+ wakeTrigger: "openrig",
2092
+ });
2093
+ othersMayHaveRun();
2094
+ findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: created.qitemId, action: "created" });
2095
+ return created.qitemId;
2096
+ }
2097
+ catch (err) {
2098
+ const message = `unclaimed-backlog notice for ${parent ? `${seat}, to its delegation parent ${parent},` : seat} not created: ${err instanceof Error ? err.message : String(err)}`;
2099
+ othersMayHaveRun();
2100
+ log(`[stuck-sweep] ${message}`);
2101
+ failedCreates.push(message);
2102
+ return null;
2103
+ }
2104
+ };
2105
+ const last = deps.db
2106
+ .prepare(
2107
+ // The first term lets the planner use idx_queue_items_recovery_tags, as the finding lookup above does.
2108
+ `SELECT qitem_id, state, ts_updated, summary, body, destination_session, tags FROM queue_items
2040
2109
  WHERE (tags LIKE '%"stuck-sweep:%') AND tags LIKE ? ESCAPE '\\'
2041
2110
  ORDER BY CASE WHEN state IN ('pending', 'in-progress', 'blocked') THEN 0 ELSE 1 END,
2042
2111
  ts_updated DESC, ts_created DESC, qitem_id DESC
2043
2112
  LIMIT 1`)
2044
- .get(`%"${tag.replace(/[\\%_]/g, (ch) => `\\${ch}`)}"%`);
2045
- if (deps.queueRepo.deliveryDrains.holds(seat)) {
2046
- // A hold is not completion. Keep the standing notice unless every named source has positively closed.
2047
- const sources = last ? backlogRowsOf(last.body) : null;
2048
- const unresolved = !sources || deps.db.prepare(`SELECT 1 FROM json_each(?) source
2113
+ .get(`%"${tag.replace(/[\\%_]/g, (ch) => `\\${ch}`)}"%`);
2114
+ if (deps.queueRepo.deliveryDrains.holds(seat)) {
2115
+ // A hold is not completion. Keep the standing notice unless every named source has positively closed.
2116
+ const sources = last ? backlogRowsOf(last.body) : null;
2117
+ const unresolved = !sources || deps.db.prepare(`SELECT 1 FROM json_each(?) source
2049
2118
  LEFT JOIN queue_items q ON q.qitem_id = source.value
2050
2119
  WHERE q.qitem_id IS NULL OR q.state IN ('pending', 'in-progress', 'blocked') LIMIT 1`)
2051
- .get(JSON.stringify([...sources])) !== undefined;
2052
- if (unresolved)
2053
- continue;
2054
- }
2055
- if (last && ["pending", "in-progress", "blocked"].includes(last.state)) {
2056
- const listedNow = new Set(rows.map((c) => c.row.qitemId));
2057
- // An unreadable list is rebuilt as every row still waiting unclaimed at the seat: all it could have stood for that
2058
- // nothing has resolved yet, and maybe more, never just the rows that qualify on this pass (review of #3049). From
2059
- // there the notice follows its rows as any other: it lets go of each one only as it's resolved or covered elsewhere.
2060
- // A member's notice the sweep marked as filed to the one creator of its rows only ever listed that creator's rows:
2061
- // the mark alone proves it, and it names that creator, whoever holds the notice now (any rewrite that brings in
2062
- // another creator's row drops it). Without the mark (an operator that is no longer recognized, an older notice,
2063
- // unreadable tags), it carries every unresolved row.
2064
- const readable = backlogRowsOf(last.body);
2065
- const onlyFrom = markedCreator(last.tags);
2066
- const stoodFor = readable ?? new Set(deps.db.prepare(`SELECT qitem_id FROM queue_items WHERE destination_session = ?
2120
+ .get(JSON.stringify([...sources])) !== undefined;
2121
+ if (unresolved)
2122
+ continue;
2123
+ }
2124
+ if (last && ["pending", "in-progress", "blocked"].includes(last.state)) {
2125
+ const listedNow = new Set(rows.map((c) => c.row.qitemId));
2126
+ // An unreadable list is rebuilt as every row still waiting unclaimed at the seat: all it could have stood for that
2127
+ // nothing has resolved yet, and maybe more, never just the rows that qualify on this pass (review of #3049). From
2128
+ // there the notice follows its rows as any other: it lets go of each one only as it's resolved or covered elsewhere.
2129
+ // A member's notice the sweep marked as filed to the one creator of its rows only ever listed that creator's rows:
2130
+ // the mark alone proves it, and it names that creator, whoever holds the notice now (any rewrite that brings in
2131
+ // another creator's row drops it). Without the mark (an operator that is no longer recognized, an older notice,
2132
+ // unreadable tags), it carries every unresolved row.
2133
+ const readable = backlogRowsOf(last.body);
2134
+ const onlyFrom = markedCreator(last.tags);
2135
+ const stoodFor = readable ?? new Set(deps.db.prepare(`SELECT qitem_id FROM queue_items WHERE destination_session = ?
2067
2136
  AND state = 'pending' AND claimed_at IS NULL AND (? IS NULL OR source_session = ?)
2068
2137
  AND NOT (json_valid(tags) AND EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?))`)
2069
- .all(seat, onlyFrom, onlyFrom, STUCK_SWEEP_FINDING_TAG).map((r) => r.qitem_id));
2070
- // #2988: rows this notice lets go of only because something else stands for them now (a finding of their own,
2071
- // another parent's or the seat's own notice, a temporary typing hold, or this pass's route for them). Nothing resolved them, so a notice the
2072
- // sweep closes doesn't hold them back: they leave its list before it closes.
2073
- const routedAway = new Set();
2074
- // Read within the sweep's bounded yield (a rebuilt list can be long); a notice changed meanwhile is left for the next pass.
2075
- const still = [];
2076
- let yielded = false;
2077
- for (const id of [...stoodFor].filter((x) => !listedNow.has(x))) {
2078
- if (dueToYield()) {
2079
- await yieldLoop();
2080
- yielded = true;
2138
+ .all(seat, onlyFrom, onlyFrom, STUCK_SWEEP_FINDING_TAG).map((r) => r.qitem_id));
2139
+ // #2988: rows this notice lets go of only because something else stands for them now (a finding of their own,
2140
+ // another parent's or the seat's own notice, a temporary typing hold, or this pass's route for them). Nothing resolved them, so a notice the
2141
+ // sweep closes doesn't hold them back: they leave its list before it closes.
2142
+ const routedAway = new Set();
2143
+ // Read within the sweep's bounded yield (a rebuilt list can be long); a notice changed meanwhile is left for the next pass.
2144
+ const still = [];
2145
+ let yielded = false;
2146
+ for (const id of [...stoodFor].filter((x) => !listedNow.has(x))) {
2147
+ if (dueToYield()) {
2148
+ await yieldLoop();
2149
+ yielded = true;
2150
+ }
2151
+ const row = indexed(() => deps.queueRepo.getById(id, { waiting: false }));
2152
+ // Gone, someone else's now, or resolved at its source.
2153
+ if (!row || row.destinationSession !== seat)
2154
+ continue;
2155
+ // A typing hold is temporary custody, not a dismissal of this work. Let the closed notice release the row:
2156
+ // when the hold clears, it can qualify again even without a newer pending timestamp or wake attempt.
2157
+ if (row.state === "pending" && !row.claimedAt && row.lastNudgeResult === "retained:typing_guard") {
2158
+ routedAway.add(id);
2159
+ continue;
2160
+ }
2161
+ if (deliveryResolutionEvidence(deps, "unclaimed-obligation", id, now))
2162
+ continue;
2163
+ // Held by a finding or recovery of its own (one actually written, so a create that failed this pass leaves the row
2164
+ // here): that finding holds it back from now on, a dismissed one too. The notice lets go of it rather than also
2165
+ // holding it once closed: a fold into a parent's notice (#2988) can release that finding's custody, and the row
2166
+ // must then be able to reach a notice again.
2167
+ if (recoveries.find(id)) {
2168
+ routedAway.add(id);
2169
+ continue;
2170
+ }
2171
+ // A parent's notice lets go of a row whose seat's delegation parent is now another seat (or none), or whose one
2172
+ // escalation hop is used; a seat's own notice, of a row its new parent's notice already stands for (#2988).
2173
+ if (parent
2174
+ ? (parentNow(seat) !== parent || hasConsumedEscalationHop(deps.db, id)) && coveredElsewhere(seat, id)
2175
+ : parentNoticeStandsFor(seat, id)) {
2176
+ routedAway.add(id);
2177
+ continue;
2178
+ }
2179
+ still.push({ qitemId: id, since: pendingSince(deps.db, id) ?? row.tsCreated, from: row.sourceSession, summary: row.summary });
2081
2180
  }
2082
- const row = indexed(() => deps.queueRepo.getById(id, { waiting: false }));
2083
- // Gone, someone else's now, or resolved at its source.
2084
- if (!row || row.destinationSession !== seat)
2085
- continue;
2086
- // A typing hold is temporary custody, not a dismissal of this work. Let the closed notice release the row:
2087
- // when the hold clears, it can qualify again even without a newer pending timestamp or wake attempt.
2088
- if (row.state === "pending" && !row.claimedAt && row.lastNudgeResult === "retained:typing_guard") {
2089
- routedAway.add(id);
2090
- continue;
2181
+ if (yielded) {
2182
+ const noticeNow = deps.db.prepare("SELECT state, body FROM queue_items WHERE qitem_id = ?").get(last.qitem_id);
2183
+ if (!noticeNow || !["pending", "in-progress", "blocked"].includes(noticeNow.state) || noticeNow.body !== last.body) {
2184
+ findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "refreshed" });
2185
+ continue;
2186
+ }
2091
2187
  }
2092
- if (deliveryResolutionEvidence(deps, "unclaimed-obligation", id, now))
2093
- continue;
2094
- // Held by a finding or recovery of its own (one actually written, so a create that failed this pass leaves the row
2095
- // here): that finding holds it back from now on, a dismissed one too. The notice lets go of it rather than also
2096
- // holding it once closed: a fold into a parent's notice (#2988) can release that finding's custody, and the row
2097
- // must then be able to reach a notice again.
2098
- if (recoveries.find(id)) {
2099
- routedAway.add(id);
2188
+ const standsFor = [...rows.map(backlogRow), ...still];
2189
+ if (standsFor.length === 0) {
2190
+ if (routedAway.size > 0 || !readable) {
2191
+ // Only the rows something resolved stay in the list the closed notice holds back. A notice whose list was
2192
+ // unreadable never knew its rows, so it holds none back.
2193
+ const kept = readable ? [...readable].filter((id) => !routedAway.has(id)) : [];
2194
+ const body = last.body.split("\n").filter((l) => !l.startsWith(BACKLOG_ROWS_PREFIX)).join("\n")
2195
+ + `\n${BACKLOG_ROWS_PREFIX}${JSON.stringify(kept)}`;
2196
+ deps.db.prepare("UPDATE queue_items SET body = ? WHERE qitem_id = ? AND body = ? AND state IN ('pending', 'in-progress', 'blocked')")
2197
+ .run(body, last.qitem_id, last.body);
2198
+ }
2199
+ await deps.queueRepo.update({
2200
+ qitemId: last.qitem_id,
2201
+ actorSession: "stuck-sweep@system",
2202
+ state: "done",
2203
+ closureReason: "no-follow-on",
2204
+ transitionNote: parent
2205
+ ? `stuck-sweep resolved: unclaimed-backlog on ${seat} for ${parent}: every row it stood for is claimed, parked, closed, temporarily held, has its own finding or no longer goes to ${parent}`
2206
+ : `stuck-sweep resolved: unclaimed-backlog on ${seat}: every row it stood for is claimed, parked, closed, temporarily held, has its own finding or is in its delegation parent's notice`,
2207
+ });
2208
+ othersMayHaveRun();
2209
+ findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "closed" });
2100
2210
  continue;
2101
2211
  }
2102
- // A parent's notice lets go of a row whose seat's delegation parent is now another seat (or none), or whose one
2103
- // escalation hop is used; a seat's own notice, of a row its new parent's notice already stands for (#2988).
2104
- if (parent
2105
- ? (parentNow(seat) !== parent || hasConsumedEscalationHop(deps.db, id)) && coveredElsewhere(seat, id)
2106
- : parentNoticeStandsFor(seat, id)) {
2107
- routedAway.add(id);
2212
+ // A notice that went to one of its rows' creators (no person reachable) shows that creator only rows it sent. When a
2213
+ // row from anyone else would join it, one notice for every row it stands for goes where a new notice would go now,
2214
+ // which wakes that recipient, and only then does this one close: a notice the sweep closed holds its rows back, so a
2215
+ // failed create leaves it open as it was (not rewritten), and the next pass tries again. A person, the operator
2216
+ // agent and the member see any of the rows.
2217
+ if (polled && last.destination_session !== seat && !seesAnyRow(last.destination_session)
2218
+ && standsFor.some((r) => r.from !== last.destination_session)) {
2219
+ const recipient = recipientFor(standsFor.map((r) => r.from));
2220
+ if (!(await fileNotice(backlogText(standsFor), recipient, standsFor.map((r) => r.from))))
2221
+ continue;
2222
+ await deps.queueRepo.update({
2223
+ qitemId: last.qitem_id,
2224
+ actorSession: "stuck-sweep@system",
2225
+ state: "done",
2226
+ closureReason: "no-follow-on",
2227
+ transitionNote: `stuck-sweep re-filed: unclaimed-backlog on ${seat}: a row it stands for didn't come from ${last.destination_session}, the creator it went to; one notice for every row went to ${recipient}`,
2228
+ });
2229
+ othersMayHaveRun();
2230
+ findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "closed" });
2108
2231
  continue;
2109
2232
  }
2110
- still.push({ qitemId: id, since: pendingSince(deps.db, id) ?? row.tsCreated, from: row.sourceSession, summary: row.summary });
2111
- }
2112
- if (yielded) {
2113
- const noticeNow = deps.db.prepare("SELECT state, body FROM queue_items WHERE qitem_id = ?").get(last.qitem_id);
2114
- if (!noticeNow || !["pending", "in-progress", "blocked"].includes(noticeNow.state) || noticeNow.body !== last.body) {
2115
- findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "refreshed" });
2116
- continue;
2233
+ // A creator's notice that now stands for another creator's row (its recipient sees any row) is no longer creator-only.
2234
+ if (onlyFrom !== null && standsFor.some((r) => r.from !== onlyFrom)) {
2235
+ deps.db.prepare(`UPDATE queue_items SET tags = (SELECT json_group_array(value) FROM json_each(tags)
2236
+ WHERE NOT (type = 'text' AND substr(value, 1, length(?)) = ?))
2237
+ WHERE qitem_id = ? AND json_valid(tags)`).run(BACKLOG_TO_CREATOR_PREFIX, BACKLOG_TO_CREATOR_PREFIX, last.qitem_id);
2117
2238
  }
2118
- }
2119
- const standsFor = [...rows.map(backlogRow), ...still];
2120
- if (standsFor.length === 0) {
2121
- if (routedAway.size > 0 || !readable) {
2122
- // Only the rows something resolved stay in the list the closed notice holds back. A notice whose list was
2123
- // unreadable never knew its rows, so it holds none back.
2124
- const kept = readable ? [...readable].filter((id) => !routedAway.has(id)) : [];
2125
- const body = last.body.split("\n").filter((l) => !l.startsWith(BACKLOG_ROWS_PREFIX)).join("\n")
2126
- + `\n${BACKLOG_ROWS_PREFIX}${JSON.stringify(kept)}`;
2127
- deps.db.prepare("UPDATE queue_items SET body = ? WHERE qitem_id = ? AND body = ? AND state IN ('pending', 'in-progress', 'blocked')")
2128
- .run(body, last.qitem_id, last.body);
2239
+ const text = backlogText(standsFor);
2240
+ let written = text.summary === last.summary && text.body === last.body;
2241
+ if (!written) {
2242
+ written = deps.db.prepare("UPDATE queue_items SET body = ?, summary = ? WHERE qitem_id = ? AND body = ? AND summary IS ? AND state IN ('pending', 'in-progress', 'blocked')")
2243
+ .run(text.body, text.summary, last.qitem_id, last.body, last.summary).changes === 1;
2129
2244
  }
2130
- await deps.queueRepo.update({
2131
- qitemId: last.qitem_id,
2132
- actorSession: "stuck-sweep@system",
2133
- state: "done",
2134
- closureReason: "no-follow-on",
2135
- transitionNote: parent
2136
- ? `stuck-sweep resolved: unclaimed-backlog on ${seat} for ${parent}: every row it stood for is claimed, parked, closed, temporarily held, has its own finding or no longer goes to ${parent}`
2137
- : `stuck-sweep resolved: unclaimed-backlog on ${seat}: every row it stood for is claimed, parked, closed, temporarily held, has its own finding or is in its delegation parent's notice`,
2138
- });
2139
- othersMayHaveRun();
2140
- findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "closed" });
2245
+ findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "refreshed" });
2246
+ if (parent && written)
2247
+ await foldInto(last.qitem_id, seat, parent, standsFor.map((r) => r.qitemId));
2141
2248
  continue;
2142
2249
  }
2143
- // A notice that went to one of its rows' creators (no person reachable) shows that creator only rows it sent. When a
2144
- // row from anyone else would join it, one notice for every row it stands for goes where a new notice would go now,
2145
- // which wakes that recipient, and only then does this one close: a notice the sweep closed holds its rows back, so a
2146
- // failed create leaves it open as it was (not rewritten), and the next pass tries again. A person, the operator
2147
- // agent and the member see any of the rows.
2148
- if (polled && last.destination_session !== seat && !seesAnyRow(last.destination_session)
2149
- && standsFor.some((r) => r.from !== last.destination_session)) {
2150
- const recipient = recipientFor(standsFor.map((r) => r.from));
2151
- if (!(await fileNotice(backlogText(standsFor), recipient, standsFor.map((r) => r.from))))
2152
- continue;
2153
- await deps.queueRepo.update({
2154
- qitemId: last.qitem_id,
2155
- actorSession: "stuck-sweep@system",
2156
- state: "done",
2157
- closureReason: "no-follow-on",
2158
- transitionNote: `stuck-sweep re-filed: unclaimed-backlog on ${seat}: a row it stands for didn't come from ${last.destination_session}, the creator it went to; one notice for every row went to ${recipient}`,
2159
- });
2160
- othersMayHaveRun();
2161
- findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "closed" });
2250
+ if (rows.length === 0)
2162
2251
  continue;
2163
- }
2164
- // A creator's notice that now stands for another creator's row (its recipient sees any row) is no longer creator-only.
2165
- if (onlyFrom !== null && standsFor.some((r) => r.from !== onlyFrom)) {
2166
- deps.db.prepare(`UPDATE queue_items SET tags = (SELECT json_group_array(value) FROM json_each(tags)
2167
- WHERE NOT (type = 'text' AND substr(value, 1, length(?)) = ?))
2168
- WHERE qitem_id = ? AND json_valid(tags)`).run(BACKLOG_TO_CREATOR_PREFIX, BACKLOG_TO_CREATOR_PREFIX, last.qitem_id);
2169
- }
2170
- const text = backlogText(standsFor);
2171
- let written = text.summary === last.summary && text.body === last.body;
2172
- if (!written) {
2173
- written = deps.db.prepare("UPDATE queue_items SET body = ?, summary = ? WHERE qitem_id = ? AND body = ? AND summary IS ? AND state IN ('pending', 'in-progress', 'blocked')")
2174
- .run(text.body, text.summary, last.qitem_id, last.body, last.summary).changes === 1;
2175
- }
2176
- findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "refreshed" });
2177
- if (parent && written)
2178
- await foldInto(last.qitem_id, seat, parent, standsFor.map((r) => r.qitemId));
2179
- continue;
2180
- }
2181
- if (rows.length === 0)
2182
- continue;
2183
- // Each row's rule again, on the row as it is now, as a finding per row is checked right before it's created.
2184
- const current = rows.flatMap((c) => {
2185
- routeNotes.delete(c.row.qitemId);
2186
- routed.delete(c.row.qitemId);
2187
- const now_ = freshCandidate(c.kind, c.row.qitemId);
2188
- if (now_)
2189
- routeCandidate(now_);
2190
- if (!now_ || activeBacklogKeyOf(now_) !== key) {
2191
- if (now_ && !recoveries.find(now_.row.qitemId) && !activeBacklogKeyOf(now_) && isUnreachableUnclaimed(now_)) {
2192
- enqueueUnroutable(now_);
2252
+ // Each row's rule again, on the row as it is now, as a finding per row is checked right before it's created.
2253
+ const current = rows.flatMap((c) => {
2254
+ routeNotes.delete(c.row.qitemId);
2255
+ routed.delete(c.row.qitemId);
2256
+ const now_ = freshCandidate(c.kind, c.row.qitemId);
2257
+ if (now_)
2258
+ routeCandidate(now_);
2259
+ if (!now_ || activeBacklogKeyOf(now_) !== key) {
2260
+ if (now_ && !recoveries.find(now_.row.qitemId) && !activeBacklogKeyOf(now_) && isUnreachableUnclaimed(now_)) {
2261
+ enqueueUnroutable(now_);
2262
+ }
2263
+ return [];
2193
2264
  }
2194
- return [];
2265
+ // A row held by a recovery stays out, unless that recovery is the per-row finding this notice folds in.
2266
+ const held = recoveries.find(now_.row.qitemId);
2267
+ return !held || (parent && foldFrom.get(now_.row.qitemId) === held.qitemId) ? [now_] : [];
2268
+ });
2269
+ if (current.length === 0)
2270
+ continue;
2271
+ // A closed notice whose list is unreadable holds back every row, each until it has newer evidence than the close.
2272
+ const covered = last ? backlogRowsOf(last.body) : null;
2273
+ if (last && !current.some((c) => (covered !== null && !covered.has(c.row.qitemId)) || evidenceIsNewer(c.evidenceAt, last.ts_updated))) {
2274
+ heldBack.set(tag, new Set(current.map((c) => c.row.qitemId)));
2275
+ continue;
2195
2276
  }
2196
- // A row held by a recovery stays out, unless that recovery is the per-row finding this notice folds in.
2197
- const held = recoveries.find(now_.row.qitemId);
2198
- return !held || (parent && foldFrom.get(now_.row.qitemId) === held.qitemId) ? [now_] : [];
2199
- });
2200
- if (current.length === 0)
2201
- continue;
2202
- // A closed notice whose list is unreadable holds back every row, each until it has newer evidence than the close.
2203
- const covered = last ? backlogRowsOf(last.body) : null;
2204
- if (last && !current.some((c) => (covered !== null && !covered.has(c.row.qitemId)) || evidenceIsNewer(c.evidenceAt, last.ts_updated))) {
2205
- heldBack.set(tag, new Set(current.map((c) => c.row.qitemId)));
2206
- continue;
2277
+ const filed = await fileNotice(backlogText(current.map(backlogRow)), recipientFor(current.map((c) => c.row.sourceSession)), current.map((c) => c.row.sourceSession));
2278
+ if (filed && parent)
2279
+ await foldInto(filed, seat, parent, current.map((c) => c.row.qitemId));
2207
2280
  }
2208
- const filed = await fileNotice(backlogText(current.map(backlogRow)), recipientFor(current.map((c) => c.row.sourceSession)), current.map((c) => c.row.sourceSession));
2209
- if (filed && parent)
2210
- await foldInto(filed, seat, parent, current.map((c) => c.row.qitemId));
2211
- }
2212
- // #514: create-once notices for unreachable unclaimed obligations, identified by STUCK_SWEEP_FINDING_TAG plus
2213
- // unroutableNoticeTag(source, destination) alone (matching unclaimed-backlog notices).
2214
- const reachableNoticeTarget = (seat, destination) => {
2215
- if (!seat || seat === destination || isMachinerySession(seat) || sessionMissing(seat)
2216
- || classOf(seat) === "unroutable" || isBoundTerminalSeat(deps.db, seat)
2217
- || !deps.queueRepo.acceptsDestination(seat))
2218
- return false;
2219
- if (!isHumanTarget(seat)) {
2220
- const latest = deps.db.prepare("SELECT status FROM sessions WHERE session_name = ? ORDER BY id DESC LIMIT 1").get(seat);
2221
- if (latest && ["exited", "superseded", "detached"].includes(latest.status))
2281
+ // #514: create-once notices for unreachable unclaimed obligations, identified by STUCK_SWEEP_FINDING_TAG plus
2282
+ // unroutableNoticeTag(source, destination) alone (matching unclaimed-backlog notices).
2283
+ const reachableNoticeTarget = (seat, destination) => {
2284
+ if (!seat || seat === destination || isMachinerySession(seat) || sessionMissing(seat)
2285
+ || classOf(seat) === "unroutable" || isBoundTerminalSeat(deps.db, seat)
2286
+ || !deps.queueRepo.acceptsDestination(seat))
2222
2287
  return false;
2223
- }
2224
- return true;
2225
- };
2226
- const unreachableNoticeTarget = (destination, source) => [source, (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)(), (deps.resolveOperatorSeat ?? resolveOperatorSeat)()]
2227
- .find((seat) => reachableNoticeTarget(seat, destination)) ?? null;
2228
- const findLatestNonSweepClosedUnroutable = (source, destination) => {
2229
- const closed = findUnroutableNotice(deps.db, source, destination, { states: ["done", "canceled"] });
2230
- if (!closed)
2231
- return null;
2232
- const latestClose = deps.db.prepare(`SELECT actor_session, closure_reason FROM (
2288
+ if (!isHumanTarget(seat)) {
2289
+ const latest = deps.db.prepare("SELECT status FROM sessions WHERE session_name = ? ORDER BY id DESC LIMIT 1").get(seat);
2290
+ if (latest && ["exited", "superseded", "detached"].includes(latest.status))
2291
+ return false;
2292
+ }
2293
+ return true;
2294
+ };
2295
+ const unreachableNoticeTarget = (destination, source) => [source, (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)(), (deps.resolveOperatorSeat ?? resolveOperatorSeat)()]
2296
+ .find((seat) => reachableNoticeTarget(seat, destination)) ?? null;
2297
+ const findLatestNonSweepClosedUnroutable = (source, destination) => {
2298
+ const closed = findUnroutableNotice(deps.db, source, destination, { states: ["done", "canceled"] });
2299
+ if (!closed)
2300
+ return null;
2301
+ const latestClose = deps.db.prepare(`SELECT actor_session, closure_reason FROM (
2233
2302
  SELECT transition_id, state, actor_session, closure_reason,
2234
2303
  LAG(state) OVER (ORDER BY transition_id) AS previous_state
2235
2304
  FROM (
@@ -2240,519 +2309,523 @@ export async function runStuckSweep(deps) {
2240
2309
  ) WHERE state IN ('done', 'canceled')
2241
2310
  AND (state IS NOT previous_state OR closure_reason IS NOT NULL)
2242
2311
  ORDER BY transition_id DESC LIMIT 1`).get(closed.qitemId, closed.qitemId);
2243
- return closed.state === "done"
2244
- && latestClose?.actor_session === "stuck-sweep@system"
2245
- && latestClose?.closure_reason === "no-follow-on"
2246
- ? null
2247
- : { qitemId: closed.qitemId, tsUpdated: closed.tsUpdated };
2248
- };
2249
- const recountQualifyingUnroutable = (rows, source, destination) => {
2250
- const current = [];
2251
- for (const c of rows) {
2252
- routeNotes.delete(c.row.qitemId);
2253
- routed.delete(c.row.qitemId);
2254
- delegationParent.delete(c.row.qitemId);
2255
- const now_ = freshCandidate("unclaimed-obligation", c.row.qitemId);
2256
- if (!now_ || now_.row.sourceSession !== source || now_.row.destinationSession !== destination)
2257
- continue;
2258
- routeAroundMissing(now_);
2259
- routeAroundNoWake(now_);
2260
- if (!recoveries.find(now_.row.qitemId) && !activeBacklogKeyOf(now_) && isUnreachableUnclaimed(now_)) {
2261
- current.push(now_);
2312
+ return closed.state === "done"
2313
+ && latestClose?.actor_session === "stuck-sweep@system"
2314
+ && latestClose?.closure_reason === "no-follow-on"
2315
+ ? null
2316
+ : { qitemId: closed.qitemId, tsUpdated: closed.tsUpdated };
2317
+ };
2318
+ const recountQualifyingUnroutable = (rows, source, destination) => {
2319
+ const current = [];
2320
+ for (const c of rows) {
2321
+ routeNotes.delete(c.row.qitemId);
2322
+ routed.delete(c.row.qitemId);
2323
+ delegationParent.delete(c.row.qitemId);
2324
+ const now_ = freshCandidate("unclaimed-obligation", c.row.qitemId);
2325
+ if (!now_ || now_.row.sourceSession !== source || now_.row.destinationSession !== destination)
2326
+ continue;
2327
+ routeAroundMissing(now_);
2328
+ routeAroundNoWake(now_);
2329
+ if (!recoveries.find(now_.row.qitemId) && !activeBacklogKeyOf(now_) && isUnreachableUnclaimed(now_)) {
2330
+ current.push(now_);
2331
+ }
2332
+ }
2333
+ return current;
2334
+ };
2335
+ class DuplicateOpenUnroutableNoticeError extends Error {
2336
+ existingQitemId;
2337
+ constructor(existingQitemId) {
2338
+ super(existingQitemId);
2339
+ this.existingQitemId = existingQitemId;
2262
2340
  }
2263
2341
  }
2264
- return current;
2265
- };
2266
- class DuplicateOpenUnroutableNoticeError extends Error {
2267
- existingQitemId;
2268
- constructor(existingQitemId) {
2269
- super(existingQitemId);
2270
- this.existingQitemId = existingQitemId;
2271
- }
2272
- }
2273
- class UnroutableNoticeSkippedError extends Error {
2274
- }
2275
- const recordUnroutableGap = (row, note, logLine, destination, findingQitemId = "") => {
2276
- if (!hasGap.get(row.qitemId, note)) {
2277
- // A same-state daemon note is bookkeeping, not work progress or a new recovery episode.
2278
- deps.queueRepo.transitionLog.append({ qitemId: row.qitemId, state: row.state, actorSession: "daemon@system", transitionNote: note });
2279
- log(logLine);
2342
+ class UnroutableNoticeSkippedError extends Error {
2280
2343
  }
2281
- findings.push({ kind: "unroutable-notice", qitemId: row.qitemId, findingQitemId, action: "unreported", destination });
2282
- };
2283
- const liveUnroutableTags = new Set();
2284
- const recoverOrphanedUnroutableNotice = async (noticeRow, source, destination, groupKey, tag, recordConcurrentRefresh) => {
2285
- const target = unreachableNoticeTarget(destination, source);
2286
- if (target) {
2287
- try {
2288
- const { created } = await deps.queueRepo.handoff({
2289
- qitemId: noticeRow.qitemId,
2290
- fromSession: "stuck-sweep@system",
2291
- toSession: target,
2292
- body: `${noticeRow.body}\n\nOriginal notice destination ${noticeRow.destinationSession} references a missing rig. This notice was handed off to ${target}.`,
2293
- summary: noticeRow.summary,
2294
- evidenceRef: noticeRow.evidenceRef,
2295
- });
2296
- othersMayHaveRun();
2297
- liveUnroutableTags.add(tag);
2298
- findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: created.qitemId, action: "created" });
2299
- return;
2344
+ const recordUnroutableGap = (row, note, logLine, destination, findingQitemId = "") => {
2345
+ if (!hasGap.get(row.qitemId, note)) {
2346
+ // A same-state daemon note is bookkeeping, not work progress or a new recovery episode.
2347
+ deps.queueRepo.transitionLog.append({ qitemId: row.qitemId, state: row.state, actorSession: "daemon@system", transitionNote: note });
2348
+ log(logLine);
2300
2349
  }
2301
- catch (err) {
2302
- othersMayHaveRun();
2303
- if (!unknownRig(err)) {
2304
- const latest = indexed(() => deps.queueRepo.getById(noticeRow.qitemId, { waiting: false }));
2305
- if (latest && ["pending", "in-progress", "blocked"].includes(latest.state)
2306
- && (latest.state !== "pending" || latest.claimedAt)) {
2307
- liveUnroutableTags.add(tag);
2308
- if (recordConcurrentRefresh) {
2309
- findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: latest.qitemId, action: "refreshed" });
2350
+ findings.push({ kind: "unroutable-notice", qitemId: row.qitemId, findingQitemId, action: "unreported", destination });
2351
+ };
2352
+ const liveUnroutableTags = new Set();
2353
+ const recoverOrphanedUnroutableNotice = async (noticeRow, source, destination, groupKey, tag, recordConcurrentRefresh) => {
2354
+ const target = unreachableNoticeTarget(destination, source);
2355
+ if (target) {
2356
+ try {
2357
+ const { created } = await deps.queueRepo.handoff({
2358
+ qitemId: noticeRow.qitemId,
2359
+ fromSession: "stuck-sweep@system",
2360
+ toSession: target,
2361
+ body: `${noticeRow.body}\n\nOriginal notice destination ${noticeRow.destinationSession} references a missing rig. This notice was handed off to ${target}.`,
2362
+ summary: noticeRow.summary,
2363
+ evidenceRef: noticeRow.evidenceRef,
2364
+ });
2365
+ othersMayHaveRun();
2366
+ liveUnroutableTags.add(tag);
2367
+ findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: created.qitemId, action: "created" });
2368
+ return;
2369
+ }
2370
+ catch (err) {
2371
+ othersMayHaveRun();
2372
+ if (!unknownRig(err)) {
2373
+ const latest = indexed(() => deps.queueRepo.getById(noticeRow.qitemId, { waiting: false }));
2374
+ if (latest && ["pending", "in-progress", "blocked"].includes(latest.state)
2375
+ && (latest.state !== "pending" || latest.claimedAt)) {
2376
+ liveUnroutableTags.add(tag);
2377
+ if (recordConcurrentRefresh) {
2378
+ findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: latest.qitemId, action: "refreshed" });
2379
+ }
2380
+ return;
2310
2381
  }
2382
+ recordFailure(`orphaned unroutable-notice ${noticeRow.qitemId} not handed off`, err);
2383
+ liveUnroutableTags.add(tag);
2311
2384
  return;
2312
2385
  }
2313
- recordFailure(`orphaned unroutable-notice ${noticeRow.qitemId} not handed off`, err);
2314
- liveUnroutableTags.add(tag);
2315
- return;
2316
2386
  }
2317
2387
  }
2318
- }
2319
- liveUnroutableTags.add(tag);
2320
- const note = `stuck-sweep routing gap: ${noticeRow.destinationSession} references an unknown rig; no reachable source, operator agent or operator seat for ${groupKey}`;
2321
- recordUnroutableGap(noticeRow, note, `[stuck-sweep] unreported #514 orphaned notice ${noticeRow.qitemId} at ${noticeRow.destinationSession}: no reachable source, operator agent or operator seat`, noticeRow.destinationSession, noticeRow.qitemId);
2322
- };
2323
- for (const [groupKey, group] of unroutableGroups) {
2324
- if (dueToYield())
2325
- await yieldLoop();
2326
- if (deps.queueRepo.deliveryDrains.holds(group.destination))
2327
- continue;
2328
- const liveRows = [];
2329
- let refreshYielded = false;
2330
- for (const c of group.rows) {
2331
- if (dueToYield()) {
2388
+ liveUnroutableTags.add(tag);
2389
+ const note = `stuck-sweep routing gap: ${noticeRow.destinationSession} references an unknown rig; no reachable source, operator agent or operator seat for ${groupKey}`;
2390
+ recordUnroutableGap(noticeRow, note, `[stuck-sweep] unreported #514 orphaned notice ${noticeRow.qitemId} at ${noticeRow.destinationSession}: no reachable source, operator agent or operator seat`, noticeRow.destinationSession, noticeRow.qitemId);
2391
+ };
2392
+ for (const [groupKey, group] of unroutableGroups) {
2393
+ if (dueToYield())
2332
2394
  await yieldLoop();
2333
- refreshYielded = true;
2334
- }
2335
- routeNotes.delete(c.row.qitemId);
2336
- routed.delete(c.row.qitemId);
2337
- delegationParent.delete(c.row.qitemId);
2338
- const now_ = freshCandidate("unclaimed-obligation", c.row.qitemId);
2339
- if (!now_ || now_.row.sourceSession !== group.source || now_.row.destinationSession !== group.destination)
2395
+ if (deps.queueRepo.deliveryDrains.holds(group.destination))
2340
2396
  continue;
2341
- routeAroundMissing(now_);
2342
- routeAroundNoWake(now_);
2343
- if (!recoveries.find(now_.row.qitemId) && !activeBacklogKeyOf(now_) && isUnreachableUnclaimed(now_)) {
2344
- liveRows.push(now_);
2397
+ const liveRows = [];
2398
+ let refreshYielded = false;
2399
+ for (const c of group.rows) {
2400
+ if (dueToYield()) {
2401
+ await yieldLoop();
2402
+ refreshYielded = true;
2403
+ }
2404
+ routeNotes.delete(c.row.qitemId);
2405
+ routed.delete(c.row.qitemId);
2406
+ delegationParent.delete(c.row.qitemId);
2407
+ const now_ = freshCandidate("unclaimed-obligation", c.row.qitemId);
2408
+ if (!now_ || now_.row.sourceSession !== group.source || now_.row.destinationSession !== group.destination)
2409
+ continue;
2410
+ routeAroundMissing(now_);
2411
+ routeAroundNoWake(now_);
2412
+ if (!recoveries.find(now_.row.qitemId) && !activeBacklogKeyOf(now_) && isUnreachableUnclaimed(now_)) {
2413
+ liveRows.push(now_);
2414
+ }
2345
2415
  }
2346
- }
2347
- if (deps.queueRepo.deliveryDrains.holds(group.destination) || liveRows.length === 0)
2348
- continue;
2349
- const tag = unroutableNoticeTag(group.source, group.destination);
2350
- const surviving = refreshYielded ? recountQualifyingUnroutable(liveRows, group.source, group.destination) : liveRows;
2351
- if (surviving.length === 0)
2352
- continue;
2353
- const openNotice = findUnroutableNotice(deps.db, group.source, group.destination);
2354
- if (openNotice) {
2355
- const noticeRow = indexed(() => deps.queueRepo.getById(openNotice.qitemId, { waiting: false }));
2356
- if (noticeRow && ["pending", "in-progress", "blocked"].includes(noticeRow.state)) {
2357
- if (noticeRow.state === "pending" && !noticeRow.claimedAt
2358
- && missingRig(noticeRow.destinationSession) && !deliveryHeld(noticeRow)) {
2359
- await recoverOrphanedUnroutableNotice(noticeRow, group.source, group.destination, groupKey, tag, true);
2416
+ if (deps.queueRepo.deliveryDrains.holds(group.destination) || liveRows.length === 0)
2417
+ continue;
2418
+ const tag = unroutableNoticeTag(group.source, group.destination);
2419
+ const surviving = refreshYielded ? recountQualifyingUnroutable(liveRows, group.source, group.destination) : liveRows;
2420
+ if (surviving.length === 0)
2421
+ continue;
2422
+ const openNotice = findUnroutableNotice(deps.db, group.source, group.destination);
2423
+ if (openNotice) {
2424
+ const noticeRow = indexed(() => deps.queueRepo.getById(openNotice.qitemId, { waiting: false }));
2425
+ if (noticeRow && ["pending", "in-progress", "blocked"].includes(noticeRow.state)) {
2426
+ if (noticeRow.state === "pending" && !noticeRow.claimedAt
2427
+ && missingRig(noticeRow.destinationSession) && !deliveryHeld(noticeRow)) {
2428
+ await recoverOrphanedUnroutableNotice(noticeRow, group.source, group.destination, groupKey, tag, true);
2429
+ continue;
2430
+ }
2431
+ liveUnroutableTags.add(tag);
2432
+ findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: noticeRow.qitemId, action: "refreshed" });
2360
2433
  continue;
2361
2434
  }
2435
+ }
2436
+ const dismissed = findLatestNonSweepClosedUnroutable(group.source, group.destination);
2437
+ if (dismissed && !surviving.some((c) => evidenceIsNewer(c.evidenceAt, dismissed.tsUpdated)))
2438
+ continue;
2439
+ const target = unreachableNoticeTarget(group.destination, group.source);
2440
+ if (!target) {
2362
2441
  liveUnroutableTags.add(tag);
2363
- findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: noticeRow.qitemId, action: "refreshed" });
2442
+ for (const c of surviving) {
2443
+ const note = `stuck-sweep routing gap: ${group.destination} unreachable; no reachable source, operator agent or operator seat`;
2444
+ recordUnroutableGap(c.row, note, `[stuck-sweep] unreported #514 unreachable row ${c.row.qitemId} at ${group.destination}: no reachable source, operator agent or operator seat`, group.destination);
2445
+ }
2364
2446
  continue;
2365
2447
  }
2366
- }
2367
- const dismissed = findLatestNonSweepClosedUnroutable(group.source, group.destination);
2368
- if (dismissed && !surviving.some((c) => evidenceIsNewer(c.evidenceAt, dismissed.tsUpdated)))
2369
- continue;
2370
- const target = unreachableNoticeTarget(group.destination, group.source);
2371
- if (!target) {
2372
- liveUnroutableTags.add(tag);
2373
- for (const c of surviving) {
2374
- const note = `stuck-sweep routing gap: ${group.destination} unreachable; no reachable source, operator agent or operator seat`;
2375
- recordUnroutableGap(c.row, note, `[stuck-sweep] unreported #514 unreachable row ${c.row.qitemId} at ${group.destination}: no reachable source, operator agent or operator seat`, group.destination);
2448
+ const text = unroutableNoticeText(group.source, group.destination, surviving.length);
2449
+ const createInput = {
2450
+ sourceSession: group.destination,
2451
+ destinationSession: target,
2452
+ body: text.body,
2453
+ summary: text.summary,
2454
+ evidenceRef: unroutableNoticeEvidenceRef(group.destination),
2455
+ tags: [STUCK_SWEEP_FINDING_TAG, tag],
2456
+ wakeTrigger: "openrig",
2457
+ };
2458
+ try {
2459
+ const created = await deps.queueRepo.create(createInput, () => {
2460
+ if (deps.queueRepo.deliveryDrains.holds(group.destination))
2461
+ throw new UnroutableNoticeSkippedError();
2462
+ const existing = findUnroutableNotice(deps.db, group.source, group.destination);
2463
+ if (existing)
2464
+ throw new DuplicateOpenUnroutableNoticeError(existing.qitemId);
2465
+ othersMayHaveRun();
2466
+ const recounted = recountQualifyingUnroutable(surviving, group.source, group.destination);
2467
+ if (recounted.length === 0)
2468
+ throw new UnroutableNoticeSkippedError();
2469
+ const latestDismissed = findLatestNonSweepClosedUnroutable(group.source, group.destination);
2470
+ if (latestDismissed && !recounted.some((c) => evidenceIsNewer(c.evidenceAt, latestDismissed.tsUpdated))) {
2471
+ throw new UnroutableNoticeSkippedError();
2472
+ }
2473
+ if (recounted.length !== surviving.length) {
2474
+ const refreshedText = unroutableNoticeText(group.source, group.destination, recounted.length);
2475
+ createInput.body = refreshedText.body;
2476
+ createInput.summary = refreshedText.summary;
2477
+ }
2478
+ });
2479
+ othersMayHaveRun();
2480
+ liveUnroutableTags.add(tag);
2481
+ findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: created.qitemId, action: "created" });
2376
2482
  }
2377
- continue;
2378
- }
2379
- const text = unroutableNoticeText(group.source, group.destination, surviving.length);
2380
- const createInput = {
2381
- sourceSession: group.destination,
2382
- destinationSession: target,
2383
- body: text.body,
2384
- summary: text.summary,
2385
- evidenceRef: unroutableNoticeEvidenceRef(group.destination),
2386
- tags: [STUCK_SWEEP_FINDING_TAG, tag],
2387
- wakeTrigger: "openrig",
2388
- };
2389
- try {
2390
- const created = await deps.queueRepo.create(createInput, () => {
2391
- if (deps.queueRepo.deliveryDrains.holds(group.destination))
2392
- throw new UnroutableNoticeSkippedError();
2393
- const existing = findUnroutableNotice(deps.db, group.source, group.destination);
2394
- if (existing)
2395
- throw new DuplicateOpenUnroutableNoticeError(existing.qitemId);
2483
+ catch (err) {
2396
2484
  othersMayHaveRun();
2397
- const recounted = recountQualifyingUnroutable(surviving, group.source, group.destination);
2398
- if (recounted.length === 0)
2399
- throw new UnroutableNoticeSkippedError();
2400
- const latestDismissed = findLatestNonSweepClosedUnroutable(group.source, group.destination);
2401
- if (latestDismissed && !recounted.some((c) => evidenceIsNewer(c.evidenceAt, latestDismissed.tsUpdated))) {
2402
- throw new UnroutableNoticeSkippedError();
2403
- }
2404
- if (recounted.length !== surviving.length) {
2405
- const refreshedText = unroutableNoticeText(group.source, group.destination, recounted.length);
2406
- createInput.body = refreshedText.body;
2407
- createInput.summary = refreshedText.summary;
2485
+ if (err instanceof DuplicateOpenUnroutableNoticeError) {
2486
+ liveUnroutableTags.add(tag);
2487
+ findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: err.existingQitemId, action: "refreshed" });
2488
+ continue;
2408
2489
  }
2409
- });
2410
- othersMayHaveRun();
2411
- liveUnroutableTags.add(tag);
2412
- findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: created.qitemId, action: "created" });
2413
- }
2414
- catch (err) {
2415
- othersMayHaveRun();
2416
- if (err instanceof DuplicateOpenUnroutableNoticeError) {
2417
- liveUnroutableTags.add(tag);
2418
- findings.push({ kind: "unroutable-notice", qitemId: groupKey, findingQitemId: err.existingQitemId, action: "refreshed" });
2419
- continue;
2490
+ if (err instanceof UnroutableNoticeSkippedError)
2491
+ continue;
2492
+ const message = `unroutable-notice for ${groupKey} not created: ${err instanceof Error ? err.message : String(err)}`;
2493
+ log(`[stuck-sweep] ${message}`);
2494
+ failedCreates.push(message);
2420
2495
  }
2421
- if (err instanceof UnroutableNoticeSkippedError)
2422
- continue;
2423
- const message = `unroutable-notice for ${groupKey} not created: ${err instanceof Error ? err.message : String(err)}`;
2424
- log(`[stuck-sweep] ${message}`);
2425
- failedCreates.push(message);
2426
- }
2427
- }
2428
- const inspectUnreachableUnclaimed = (row) => {
2429
- if (row.state !== "pending" || row.claimedAt || polledRow(row))
2430
- return "other";
2431
- if (classOf(row.destinationSession) !== "unroutable" && !sessionMissing(row.destinationSession))
2432
- return "other";
2433
- if (recoveries.find(row.qitemId))
2434
- return "recovery";
2435
- if (deliveryResolutionEvidence(deps, "unclaimed-obligation", row.qitemId, now))
2436
- return "delivery";
2437
- const savedNotes = new Map(routeNotes);
2438
- const savedRouted = new Set(routed);
2439
- const savedParents = new Map(delegationParent);
2440
- try {
2441
- const route = resolveOrch(row.destinationSession, row) ?? row.destinationSession;
2442
- const probe = { kind: "unclaimed-obligation", row, route, ageMinutes: 0, evidenceAt: row.tsCreated, why: "" };
2443
- routeAroundMissing(probe);
2444
- routeAroundNoWake(probe);
2445
- return !activeBacklogKeyOf(probe) && isUnreachableUnclaimed(probe) ? "live" : "other";
2446
- }
2447
- finally {
2448
- routeNotes.clear();
2449
- for (const [k, v] of savedNotes)
2450
- routeNotes.set(k, v);
2451
- routed.clear();
2452
- for (const k of savedRouted)
2453
- routed.add(k);
2454
- delegationParent.clear();
2455
- for (const [k, v] of savedParents)
2456
- delegationParent.set(k, v);
2457
2496
  }
2458
- };
2459
- const openUnroutableNotices = deps.db.prepare(`SELECT q.qitem_id, q.tags
2497
+ const inspectUnreachableUnclaimed = (row) => {
2498
+ if (row.state !== "pending" || row.claimedAt || polledRow(row))
2499
+ return "other";
2500
+ if (classOf(row.destinationSession) !== "unroutable" && !sessionMissing(row.destinationSession))
2501
+ return "other";
2502
+ if (recoveries.find(row.qitemId))
2503
+ return "recovery";
2504
+ if (deliveryResolutionEvidence(deps, "unclaimed-obligation", row.qitemId, now))
2505
+ return "delivery";
2506
+ const savedNotes = new Map(routeNotes);
2507
+ const savedRouted = new Set(routed);
2508
+ const savedParents = new Map(delegationParent);
2509
+ try {
2510
+ const route = resolveOrch(row.destinationSession, row) ?? row.destinationSession;
2511
+ const probe = { kind: "unclaimed-obligation", row, route, ageMinutes: 0, evidenceAt: row.tsCreated, why: "" };
2512
+ routeAroundMissing(probe);
2513
+ routeAroundNoWake(probe);
2514
+ return !activeBacklogKeyOf(probe) && isUnreachableUnclaimed(probe) ? "live" : "other";
2515
+ }
2516
+ finally {
2517
+ routeNotes.clear();
2518
+ for (const [k, v] of savedNotes)
2519
+ routeNotes.set(k, v);
2520
+ routed.clear();
2521
+ for (const k of savedRouted)
2522
+ routed.add(k);
2523
+ delegationParent.clear();
2524
+ for (const [k, v] of savedParents)
2525
+ delegationParent.set(k, v);
2526
+ }
2527
+ };
2528
+ const openUnroutableNotices = deps.db.prepare(`SELECT q.qitem_id, q.tags
2460
2529
  FROM queue_items q
2461
2530
  WHERE +q.state IN ('pending', 'in-progress', 'blocked')
2462
2531
  AND (q.tags LIKE '%"stuck-sweep:%')
2463
2532
  AND json_valid(q.tags)
2464
2533
  AND EXISTS (SELECT 1 FROM json_each(q.tags) j WHERE typeof(j.value) = 'text' AND j.value = ?)
2465
2534
  AND EXISTS (SELECT 1 FROM json_each(q.tags) j WHERE typeof(j.value) = 'text' AND substr(j.value, 1, length(?)) = ?)`).all(STUCK_SWEEP_FINDING_TAG, UNROUTABLE_NOTICE_PREFIX, UNROUTABLE_NOTICE_PREFIX);
2466
- for (const notice of openUnroutableNotices) {
2467
- if (dueToYield())
2468
- await yieldLoop();
2469
- const pair = parseUnroutableNoticeTags(notice.tags);
2470
- if (!pair)
2471
- continue;
2472
- const { source, dest } = pair;
2473
- const noticeTag = unroutableNoticeTag(source, dest);
2474
- if (liveUnroutableTags.has(noticeTag))
2475
- continue;
2476
- const key = `${source}${UNROUTABLE_NOTICE_SEPARATOR}${dest}`;
2477
- const hasOrdinaryPending = () => deps.db.prepare(`SELECT 1 FROM queue_items
2535
+ for (const notice of openUnroutableNotices) {
2536
+ if (dueToYield())
2537
+ await yieldLoop();
2538
+ const pair = parseUnroutableNoticeTags(notice.tags);
2539
+ if (!pair)
2540
+ continue;
2541
+ const { source, dest } = pair;
2542
+ const noticeTag = unroutableNoticeTag(source, dest);
2543
+ if (liveUnroutableTags.has(noticeTag))
2544
+ continue;
2545
+ const key = `${source}${UNROUTABLE_NOTICE_SEPARATOR}${dest}`;
2546
+ const hasOrdinaryPending = () => deps.db.prepare(`SELECT 1 FROM queue_items
2478
2547
  WHERE destination_session = ? AND source_session = ? AND state = 'pending' AND claimed_at IS NULL
2479
2548
  AND NOT (json_valid(tags) AND EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?))
2480
2549
  LIMIT 1`).get(dest, source, STUCK_SWEEP_FINDING_TAG) !== undefined;
2481
- const pendingRows = deps.db.prepare(`SELECT qitem_id FROM queue_items
2550
+ const pendingRows = deps.db.prepare(`SELECT qitem_id FROM queue_items
2482
2551
  WHERE destination_session = ? AND source_session = ? AND state = 'pending' AND claimed_at IS NULL
2483
2552
  AND NOT (json_valid(tags) AND EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?))`).all(dest, source, STUCK_SWEEP_FINDING_TAG);
2484
- const queryPendingMeta = () => deps.db.prepare(`SELECT qitem_id, ts_updated, last_nudge_result, tags,
2553
+ const queryPendingMeta = () => deps.db.prepare(`SELECT qitem_id, ts_updated, last_nudge_result, tags,
2485
2554
  COALESCE((SELECT MAX(t.transition_id) FROM queue_transitions t WHERE t.qitem_id = queue_items.qitem_id), 0) AS max_tid
2486
2555
  FROM queue_items
2487
2556
  WHERE destination_session = ? AND source_session = ? AND state = 'pending' AND claimed_at IS NULL
2488
2557
  AND NOT (json_valid(tags) AND EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?))`).all(dest, source, STUCK_SWEEP_FINDING_TAG);
2489
- const pairEnvKey = () => {
2490
- const recAgent = (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)() ?? "";
2491
- const opSeat = (deps.resolveOperatorSeat ?? resolveOperatorSeat)() ?? "";
2492
- const seatSummary = (seat) => seat ? `${seat}:${sessionMissing(seat)}:${classOf(seat)}:${isBoundTerminalSeat(deps.db, seat)}` : "";
2493
- const orch = deps.resolveOrchestrator
2494
- ? (deps.resolveOrchestrator(dest) ?? "")
2495
- : JSON.stringify(resolveEscalationOwner(deps.db, dest, (target) => deps.queueRepo.acceptsDestination(target)));
2496
- const agent = agentSeatNode(dest);
2497
- return JSON.stringify([
2498
- classOf(dest),
2499
- sessionMissing(dest),
2500
- stoppedReason(dest),
2501
- sessionStoppedOrMissing(dest),
2502
- isHumanTarget(dest),
2503
- pollsForWork(dest),
2504
- isBoundTerminalSeat(deps.db, dest),
2505
- orch,
2506
- agent ? `${agent.rig}:${agent.logicalId}` : "",
2507
- seatSummary(source),
2508
- seatSummary(recAgent),
2509
- seatSummary(opSeat),
2510
- ]);
2511
- };
2512
- const keepOpenOrphanedNotice = async () => {
2513
- if (deps.queueRepo.deliveryDrains.holds(dest))
2514
- return;
2515
- const noticeRow = indexed(() => deps.queueRepo.getById(notice.qitem_id, { waiting: false }));
2516
- if (!noticeRow || noticeRow.state !== "pending" || noticeRow.claimedAt)
2517
- return;
2518
- const liveTags = deps.db.prepare("SELECT tags FROM queue_items WHERE qitem_id = ?")
2519
- .get(noticeRow.qitemId);
2520
- const livePair = parseUnroutableNoticeTags(liveTags?.tags ?? null);
2521
- if (!livePair || livePair.source !== source || livePair.dest !== dest)
2522
- return;
2523
- if (!missingRig(noticeRow.destinationSession) || deliveryHeld(noticeRow))
2524
- return;
2525
- await recoverOrphanedUnroutableNotice(noticeRow, source, dest, key, noticeTag, false);
2526
- };
2527
- if (deps.queueRepo.deliveryDrains.holds(dest)) {
2528
- if (pendingRows.length > 0)
2529
- continue;
2530
- }
2531
- else {
2532
- let hasLivePending = false;
2533
- const inspected = new Map();
2534
- // Zero-yield fast path avoids pairEnvKey() and MAX(transition_id) queries until a yield actually fires.
2535
- const preYieldVerdicts = new Map();
2536
- let currentEnv = null;
2537
- let metaById = new Map();
2538
- let toScan = pendingRows;
2539
- for (let pass = 0;; pass++) {
2540
- let passYielded = false;
2541
- for (const pending of toScan) {
2542
- if (dueToYield()) {
2543
- if (currentEnv === null && preYieldVerdicts.size > 0) {
2544
- const preYieldEnv = pairEnvKey();
2545
- for (const meta of queryPendingMeta()) {
2546
- const skipReason = preYieldVerdicts.get(meta.qitem_id);
2547
- if (!skipReason)
2548
- continue;
2549
- inspected.set(meta.qitem_id, {
2550
- tsUpdated: meta.ts_updated,
2551
- lastNudgeResult: meta.last_nudge_result,
2552
- rawTags: meta.tags,
2553
- maxTid: meta.max_tid,
2554
- skipReason,
2555
- envKey: preYieldEnv,
2556
- });
2558
+ const pairEnvKey = () => {
2559
+ const recAgent = (deps.resolveRecoveryAgentSeat ?? resolveRecoveryAgentSeat)() ?? "";
2560
+ const opSeat = (deps.resolveOperatorSeat ?? resolveOperatorSeat)() ?? "";
2561
+ const seatSummary = (seat) => seat ? `${seat}:${sessionMissing(seat)}:${classOf(seat)}:${isBoundTerminalSeat(deps.db, seat)}` : "";
2562
+ const orch = deps.resolveOrchestrator
2563
+ ? (deps.resolveOrchestrator(dest) ?? "")
2564
+ : JSON.stringify(resolveEscalationOwner(deps.db, dest, (target) => deps.queueRepo.acceptsDestination(target)));
2565
+ const agent = agentSeatNode(dest);
2566
+ return JSON.stringify([
2567
+ classOf(dest),
2568
+ sessionMissing(dest),
2569
+ stoppedReason(dest),
2570
+ sessionStoppedOrMissing(dest),
2571
+ isHumanTarget(dest),
2572
+ pollsForWork(dest),
2573
+ isBoundTerminalSeat(deps.db, dest),
2574
+ orch,
2575
+ agent ? `${agent.rig}:${agent.logicalId}` : "",
2576
+ seatSummary(source),
2577
+ seatSummary(recAgent),
2578
+ seatSummary(opSeat),
2579
+ ]);
2580
+ };
2581
+ const keepOpenOrphanedNotice = async () => {
2582
+ if (deps.queueRepo.deliveryDrains.holds(dest))
2583
+ return;
2584
+ const noticeRow = indexed(() => deps.queueRepo.getById(notice.qitem_id, { waiting: false }));
2585
+ if (!noticeRow || noticeRow.state !== "pending" || noticeRow.claimedAt)
2586
+ return;
2587
+ const liveTags = deps.db.prepare("SELECT tags FROM queue_items WHERE qitem_id = ?")
2588
+ .get(noticeRow.qitemId);
2589
+ const livePair = parseUnroutableNoticeTags(liveTags?.tags ?? null);
2590
+ if (!livePair || livePair.source !== source || livePair.dest !== dest)
2591
+ return;
2592
+ if (!missingRig(noticeRow.destinationSession) || deliveryHeld(noticeRow))
2593
+ return;
2594
+ await recoverOrphanedUnroutableNotice(noticeRow, source, dest, key, noticeTag, false);
2595
+ };
2596
+ if (deps.queueRepo.deliveryDrains.holds(dest)) {
2597
+ if (pendingRows.length > 0)
2598
+ continue;
2599
+ }
2600
+ else {
2601
+ let hasLivePending = false;
2602
+ const inspected = new Map();
2603
+ // Zero-yield fast path avoids pairEnvKey() and MAX(transition_id) queries until a yield actually fires.
2604
+ const preYieldVerdicts = new Map();
2605
+ let currentEnv = null;
2606
+ let metaById = new Map();
2607
+ let toScan = pendingRows;
2608
+ for (let pass = 0;; pass++) {
2609
+ let passYielded = false;
2610
+ for (const pending of toScan) {
2611
+ if (dueToYield()) {
2612
+ if (currentEnv === null && preYieldVerdicts.size > 0) {
2613
+ const preYieldEnv = pairEnvKey();
2614
+ for (const meta of queryPendingMeta()) {
2615
+ const skipReason = preYieldVerdicts.get(meta.qitem_id);
2616
+ if (!skipReason)
2617
+ continue;
2618
+ inspected.set(meta.qitem_id, {
2619
+ tsUpdated: meta.ts_updated,
2620
+ lastNudgeResult: meta.last_nudge_result,
2621
+ rawTags: meta.tags,
2622
+ maxTid: meta.max_tid,
2623
+ skipReason,
2624
+ envKey: preYieldEnv,
2625
+ });
2626
+ }
2627
+ preYieldVerdicts.clear();
2628
+ }
2629
+ await yieldLoop();
2630
+ passYielded = true;
2631
+ if (deps.queueRepo.deliveryDrains.holds(dest)) {
2632
+ hasLivePending = hasOrdinaryPending();
2633
+ break;
2557
2634
  }
2558
- preYieldVerdicts.clear();
2635
+ currentEnv = pairEnvKey();
2636
+ metaById = new Map(queryPendingMeta().map((m) => [m.qitem_id, m]));
2559
2637
  }
2560
- await yieldLoop();
2561
- passYielded = true;
2562
- if (deps.queueRepo.deliveryDrains.holds(dest)) {
2563
- hasLivePending = hasOrdinaryPending();
2564
- break;
2638
+ const row = indexed(() => deps.queueRepo.getById(pending.qitem_id, { waiting: false }));
2639
+ if (!row) {
2640
+ preYieldVerdicts.delete(pending.qitem_id);
2641
+ inspected.delete(pending.qitem_id);
2642
+ continue;
2565
2643
  }
2566
- currentEnv = pairEnvKey();
2567
- metaById = new Map(queryPendingMeta().map((m) => [m.qitem_id, m]));
2568
- }
2569
- const row = indexed(() => deps.queueRepo.getById(pending.qitem_id, { waiting: false }));
2570
- if (!row) {
2571
- preYieldVerdicts.delete(pending.qitem_id);
2572
- inspected.delete(pending.qitem_id);
2573
- continue;
2574
- }
2575
- const verdict = inspectUnreachableUnclaimed(row);
2576
- if (verdict === "live") {
2577
- hasLivePending = true;
2578
- break;
2579
- }
2580
- if (row.state === "pending" && !row.claimedAt && row.sourceSession === source && row.destinationSession === dest) {
2581
- if (currentEnv === null) {
2582
- preYieldVerdicts.set(row.qitemId, verdict);
2644
+ const verdict = inspectUnreachableUnclaimed(row);
2645
+ if (verdict === "live") {
2646
+ hasLivePending = true;
2647
+ break;
2583
2648
  }
2584
- else {
2585
- const meta = metaById.get(row.qitemId);
2586
- if (meta) {
2587
- inspected.set(row.qitemId, {
2588
- tsUpdated: row.tsUpdated,
2589
- lastNudgeResult: row.lastNudgeResult ?? null,
2590
- rawTags: meta.tags,
2591
- maxTid: meta.max_tid,
2592
- skipReason: verdict,
2593
- envKey: currentEnv,
2594
- });
2649
+ if (row.state === "pending" && !row.claimedAt && row.sourceSession === source && row.destinationSession === dest) {
2650
+ if (currentEnv === null) {
2651
+ preYieldVerdicts.set(row.qitemId, verdict);
2595
2652
  }
2596
2653
  else {
2597
- inspected.delete(row.qitemId);
2654
+ const meta = metaById.get(row.qitemId);
2655
+ if (meta) {
2656
+ inspected.set(row.qitemId, {
2657
+ tsUpdated: row.tsUpdated,
2658
+ lastNudgeResult: row.lastNudgeResult ?? null,
2659
+ rawTags: meta.tags,
2660
+ maxTid: meta.max_tid,
2661
+ skipReason: verdict,
2662
+ envKey: currentEnv,
2663
+ });
2664
+ }
2665
+ else {
2666
+ inspected.delete(row.qitemId);
2667
+ }
2598
2668
  }
2599
2669
  }
2670
+ else {
2671
+ preYieldVerdicts.delete(pending.qitem_id);
2672
+ inspected.delete(pending.qitem_id);
2673
+ }
2600
2674
  }
2601
- else {
2602
- preYieldVerdicts.delete(pending.qitem_id);
2603
- inspected.delete(pending.qitem_id);
2675
+ if (hasLivePending || !passYielded)
2676
+ break;
2677
+ if (deps.queueRepo.deliveryDrains.holds(dest)) {
2678
+ hasLivePending = hasOrdinaryPending();
2679
+ break;
2604
2680
  }
2681
+ if (classOf(dest) !== "unroutable" && !sessionMissing(dest))
2682
+ break;
2683
+ const nowEnv = pairEnvKey();
2684
+ const currentPending = queryPendingMeta();
2685
+ const dirty = currentPending.filter((pending) => {
2686
+ const prev = inspected.get(pending.qitem_id);
2687
+ if (!prev)
2688
+ return true;
2689
+ if (prev.envKey !== nowEnv)
2690
+ return true;
2691
+ if (prev.tsUpdated !== pending.ts_updated)
2692
+ return true;
2693
+ if (prev.lastNudgeResult !== pending.last_nudge_result)
2694
+ return true;
2695
+ if (prev.rawTags !== pending.tags)
2696
+ return true;
2697
+ if (prev.maxTid !== pending.max_tid)
2698
+ return true;
2699
+ if (prev.skipReason === "recovery" && !recoveries.find(pending.qitem_id))
2700
+ return true;
2701
+ if (prev.skipReason === "delivery" && !deliveryResolutionEvidence(deps, "unclaimed-obligation", pending.qitem_id, now))
2702
+ return true;
2703
+ return false;
2704
+ });
2705
+ if (dirty.length === 0)
2706
+ break;
2707
+ if (pass >= 2) {
2708
+ hasLivePending = true;
2709
+ break;
2710
+ }
2711
+ currentEnv = nowEnv;
2712
+ metaById = new Map(dirty.map((m) => [m.qitem_id, m]));
2713
+ toScan = dirty;
2605
2714
  }
2606
- if (hasLivePending || !passYielded)
2607
- break;
2608
- if (deps.queueRepo.deliveryDrains.holds(dest)) {
2609
- hasLivePending = hasOrdinaryPending();
2610
- break;
2611
- }
2612
- if (classOf(dest) !== "unroutable" && !sessionMissing(dest))
2613
- break;
2614
- const nowEnv = pairEnvKey();
2615
- const currentPending = queryPendingMeta();
2616
- const dirty = currentPending.filter((pending) => {
2617
- const prev = inspected.get(pending.qitem_id);
2618
- if (!prev)
2619
- return true;
2620
- if (prev.envKey !== nowEnv)
2621
- return true;
2622
- if (prev.tsUpdated !== pending.ts_updated)
2623
- return true;
2624
- if (prev.lastNudgeResult !== pending.last_nudge_result)
2625
- return true;
2626
- if (prev.rawTags !== pending.tags)
2627
- return true;
2628
- if (prev.maxTid !== pending.max_tid)
2629
- return true;
2630
- if (prev.skipReason === "recovery" && !recoveries.find(pending.qitem_id))
2631
- return true;
2632
- if (prev.skipReason === "delivery" && !deliveryResolutionEvidence(deps, "unclaimed-obligation", pending.qitem_id, now))
2633
- return true;
2634
- return false;
2635
- });
2636
- if (dirty.length === 0)
2637
- break;
2638
- if (pass >= 2) {
2639
- hasLivePending = true;
2640
- break;
2715
+ if (hasLivePending) {
2716
+ await keepOpenOrphanedNotice();
2717
+ continue;
2641
2718
  }
2642
- currentEnv = nowEnv;
2643
- metaById = new Map(dirty.map((m) => [m.qitem_id, m]));
2644
- toScan = dirty;
2645
2719
  }
2646
- if (hasLivePending) {
2647
- await keepOpenOrphanedNotice();
2720
+ const liveNotice = deps.db.prepare("SELECT state, tags FROM queue_items WHERE qitem_id = ?").get(notice.qitem_id);
2721
+ if (!liveNotice || !["pending", "in-progress", "blocked"].includes(liveNotice.state))
2648
2722
  continue;
2649
- }
2723
+ const livePair = parseUnroutableNoticeTags(liveNotice.tags);
2724
+ if (!livePair || livePair.source !== source || livePair.dest !== dest)
2725
+ continue;
2726
+ if (deps.queueRepo.deliveryDrains.holds(dest) && hasOrdinaryPending())
2727
+ continue;
2728
+ await deps.queueRepo.update({
2729
+ qitemId: notice.qitem_id,
2730
+ actorSession: "stuck-sweep@system",
2731
+ state: "done",
2732
+ closureReason: "no-follow-on",
2733
+ transitionNote: `stuck-sweep resolved: unroutable-notice on ${key} no pending unreachable work from ${source} at ${dest}`,
2734
+ });
2735
+ othersMayHaveRun();
2736
+ findings.push({ kind: "unroutable-notice", qitemId: key, findingQitemId: notice.qitem_id, action: "closed" });
2650
2737
  }
2651
- const liveNotice = deps.db.prepare("SELECT state, tags FROM queue_items WHERE qitem_id = ?").get(notice.qitem_id);
2652
- if (!liveNotice || !["pending", "in-progress", "blocked"].includes(liveNotice.state))
2653
- continue;
2654
- const livePair = parseUnroutableNoticeTags(liveNotice.tags);
2655
- if (!livePair || livePair.source !== source || livePair.dest !== dest)
2656
- continue;
2657
- if (deps.queueRepo.deliveryDrains.holds(dest) && hasOrdinaryPending())
2658
- continue;
2659
- await deps.queueRepo.update({
2660
- qitemId: notice.qitem_id,
2661
- actorSession: "stuck-sweep@system",
2662
- state: "done",
2663
- closureReason: "no-follow-on",
2664
- transitionNote: `stuck-sweep resolved: unroutable-notice on ${key} no pending unreachable work from ${source} at ${dest}`,
2665
- });
2666
- othersMayHaveRun();
2667
- findings.push({ kind: "unroutable-notice", qitemId: key, findingQitemId: notice.qitem_id, action: "closed" });
2668
- }
2669
- // Resolution: an open finding whose underlying condition is no longer detected closes
2670
- // with its reason — the sweep cleans up after itself, no human unwind.
2671
- const openFindings = deps.db
2672
- .prepare(`SELECT qitem_id, tags FROM queue_items
2738
+ // Resolution: an open finding whose underlying condition is no longer detected closes
2739
+ // with its reason — the sweep cleans up after itself, no human unwind.
2740
+ const openFindings = deps.db
2741
+ .prepare(`SELECT qitem_id, tags FROM queue_items
2673
2742
  WHERE state IN ('pending', 'in-progress', 'blocked')
2674
2743
  AND tags LIKE ?`)
2675
- .all(`%"${STUCK_SWEEP_FINDING_TAG}"%`);
2676
- for (const f of openFindings) {
2677
- if (dueToYield())
2678
- await yieldLoop();
2679
- let tags = [];
2680
- try {
2681
- tags = JSON.parse(f.tags);
2682
- }
2683
- catch {
2684
- continue;
2685
- }
2686
- const dedupTag = tags.find((t) => t.startsWith("stuck-sweep:"));
2687
- if (!dedupTag || liveDedupTags.has(dedupTag))
2688
- continue;
2689
- const [, kind, stuckId] = dedupTag.match(/^stuck-sweep:([a-z-]+):(.+)$/) ?? [];
2690
- if (kind === "unroutable-notice")
2691
- continue;
2692
- // A retry marker only suppresses reporting. Other reporting filters (a new
2693
- // unconfirmed send, a fresh post window, or a larger unclaimed age) do not
2694
- // prove resolution either: delivery/pickup findings need source evidence.
2695
- if (suppressedTags.has(dedupTag))
2696
- continue;
2697
- // #2661: a claim working only on a grace (a background shell, a pending managed restore) is not resolved: the
2698
- // grace stops new detection, and an open stall recovery stays open, so the ceiling's expiry stays actionable.
2699
- if (kind === "stalled-after-claim" && stuckId && deps.queueRepo.getById(stuckId, { waiting: false })?.pickup?.grace)
2700
- continue;
2701
- let resolution = "no longer detected";
2702
- if (stuckId && (kind === "undelivered-wake" || kind === "undelivered-human-notice" || kind === "unclaimed-obligation")) {
2703
- const evidence = deliveryResolutionEvidence(deps, kind, stuckId, now);
2704
- if (!evidence)
2744
+ .all(`%"${STUCK_SWEEP_FINDING_TAG}"%`);
2745
+ for (const f of openFindings) {
2746
+ if (dueToYield())
2747
+ await yieldLoop();
2748
+ let tags = [];
2749
+ try {
2750
+ tags = JSON.parse(f.tags);
2751
+ }
2752
+ catch {
2705
2753
  continue;
2706
- resolution = evidence;
2707
- }
2708
- // The list was read before this loop's yields: the finding's owner may have closed it since (done -> done is
2709
- // refused, and would fail the whole pass).
2710
- const current = deps.db.prepare("SELECT state FROM queue_items WHERE qitem_id = ?").get(f.qitem_id);
2711
- if (!current || !["pending", "in-progress", "blocked"].includes(current.state))
2712
- continue;
2713
- // "No longer detected" rests on lists read before this loop's yields: a row that came back (blocked, then
2714
- // in-progress past its deadline) during the pass still holds, so its rule runs again on the row as it is now.
2715
- // A drain-deferred candidate likewise needs its live rule checked: deferral is not completion.
2716
- // (A row this pass did find, whose finding isn't live because another recovery now holds its custody, closes as
2717
- // the base closed it.)
2718
- if (kind && stuckId && resolvedByRule.has(kind) && (!candidateIds.has(stuckId) || drainDeferredIds.has(stuckId)) && ruleHolds(kind, stuckId))
2719
- continue;
2720
- await deps.queueRepo.update({
2721
- qitemId: f.qitem_id,
2722
- // The sweep performed this transition; ownership stays on the existing row.
2723
- actorSession: "stuck-sweep@system",
2724
- state: "done",
2725
- closureReason: "no-follow-on",
2726
- transitionNote: `stuck-sweep resolved: ${kind ?? "finding"} on ${stuckId ?? "row"} ${resolution}`,
2727
- });
2728
- othersMayHaveRun();
2729
- if (kind && stuckId) {
2730
- findings.push({
2731
- kind: kind,
2732
- qitemId: stuckId,
2733
- findingQitemId: f.qitem_id,
2734
- action: "closed",
2754
+ }
2755
+ const dedupTag = tags.find((t) => t.startsWith("stuck-sweep:"));
2756
+ if (!dedupTag || liveDedupTags.has(dedupTag))
2757
+ continue;
2758
+ const [, kind, stuckId] = dedupTag.match(/^stuck-sweep:([a-z-]+):(.+)$/) ?? [];
2759
+ if (kind === "unroutable-notice")
2760
+ continue;
2761
+ // A retry marker only suppresses reporting. Other reporting filters (a new
2762
+ // unconfirmed send, a fresh post window, or a larger unclaimed age) do not
2763
+ // prove resolution either: delivery/pickup findings need source evidence.
2764
+ if (suppressedTags.has(dedupTag))
2765
+ continue;
2766
+ // #2661: a claim working only on a grace (a background shell, a pending managed restore) is not resolved: the
2767
+ // grace stops new detection, and an open stall recovery stays open, so the ceiling's expiry stays actionable.
2768
+ if (kind === "stalled-after-claim" && stuckId && deps.queueRepo.getById(stuckId, { waiting: false })?.pickup?.grace)
2769
+ continue;
2770
+ let resolution = "no longer detected";
2771
+ if (stuckId && (kind === "undelivered-wake" || kind === "undelivered-human-notice" || kind === "unclaimed-obligation")) {
2772
+ const evidence = deliveryResolutionEvidence(deps, kind, stuckId, now);
2773
+ if (!evidence)
2774
+ continue;
2775
+ resolution = evidence;
2776
+ }
2777
+ // The list was read before this loop's yields: the finding's owner may have closed it since (done -> done is
2778
+ // refused, and would fail the whole pass).
2779
+ const current = deps.db.prepare("SELECT state FROM queue_items WHERE qitem_id = ?").get(f.qitem_id);
2780
+ if (!current || !["pending", "in-progress", "blocked"].includes(current.state))
2781
+ continue;
2782
+ // "No longer detected" rests on lists read before this loop's yields: a row that came back (blocked, then
2783
+ // in-progress past its deadline) during the pass still holds, so its rule runs again on the row as it is now.
2784
+ // A drain-deferred candidate likewise needs its live rule checked: deferral is not completion.
2785
+ // (A row this pass did find, whose finding isn't live because another recovery now holds its custody, closes as
2786
+ // the base closed it.)
2787
+ if (kind && stuckId && resolvedByRule.has(kind) && (!candidateIds.has(stuckId) || drainDeferredIds.has(stuckId)) && ruleHolds(kind, stuckId))
2788
+ continue;
2789
+ await deps.queueRepo.update({
2790
+ qitemId: f.qitem_id,
2791
+ // The sweep performed this transition; ownership stays on the existing row.
2792
+ actorSession: "stuck-sweep@system",
2793
+ state: "done",
2794
+ closureReason: "no-follow-on",
2795
+ transitionNote: `stuck-sweep resolved: ${kind ?? "finding"} on ${stuckId ?? "row"} ${resolution}`,
2735
2796
  });
2797
+ othersMayHaveRun();
2798
+ if (kind && stuckId) {
2799
+ findings.push({
2800
+ kind: kind,
2801
+ qitemId: stuckId,
2802
+ findingQitemId: f.qitem_id,
2803
+ action: "closed",
2804
+ });
2805
+ }
2806
+ }
2807
+ const undelivered = findings.filter((finding) => finding.action === "unreported").length;
2808
+ const counts = { ...findingCounts(deps.db, findings), undelivered };
2809
+ if (failedCreates.length > 0) {
2810
+ // Not a clean or complete pass: say so, while keeping the findings that were made.
2811
+ const error = failedCreates.join("; ");
2812
+ status?.record("failed", { error, ...counts });
2813
+ return { outcome: "failed", findings, error };
2736
2814
  }
2815
+ const outcome = undelivered > 0 ? "partial" : findings.length > 0 ? "findings" : "clean";
2816
+ status?.record(outcome, counts);
2817
+ return { outcome, findings };
2737
2818
  }
2738
- const undelivered = findings.filter((finding) => finding.action === "unreported").length;
2739
- const counts = { ...findingCounts(deps.db, findings), undelivered };
2740
- if (failedCreates.length > 0) {
2741
- // Not a clean or complete pass: say so, while keeping the findings that were made.
2742
- const error = failedCreates.join("; ");
2743
- status?.record("failed", { error, ...counts });
2744
- return { outcome: "failed", findings, error };
2819
+ catch (err) {
2820
+ const message = err instanceof Error ? err.message : String(err);
2821
+ // Loud, never silent: the failure lands on the log AND the status surface (healthz).
2822
+ log(`[stuck-sweep] SWEEP FAILED (skipping this tick loudly): ${message}`);
2823
+ status?.record("failed", { error: message });
2824
+ return { outcome: "failed", findings: [], error: message };
2745
2825
  }
2746
- const outcome = undelivered > 0 ? "partial" : findings.length > 0 ? "findings" : "clean";
2747
- status?.record(outcome, counts);
2748
- return { outcome, findings };
2749
- }
2750
- catch (err) {
2751
- const message = err instanceof Error ? err.message : String(err);
2752
- // Loud, never silent: the failure lands on the log AND the status surface (healthz).
2753
- log(`[stuck-sweep] SWEEP FAILED (skipping this tick loudly): ${message}`);
2754
- status?.record("failed", { error: message });
2755
- return { outcome: "failed", findings: [], error: message };
2756
- }
2826
+ };
2827
+ return typeof deps.queueRepo.withMemoizedHumanRegistry === "function"
2828
+ ? deps.queueRepo.withMemoizedHumanRegistry(run)
2829
+ : run();
2757
2830
  }
2758
2831
  //# sourceMappingURL=queue-stuck-sweep.js.map