@openrig/cli 0.7.25 → 0.7.26

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