@wjarka/cezarion 0.17.0-pr848.3486 → 0.18.0-dev.5793

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 (1392) hide show
  1. package/bin.js +2 -0
  2. package/cez.js +2 -0
  3. package/cezarion.js +2 -0
  4. package/dist/cez.js +2 -0
  5. package/dist/cezarion.js +2 -0
  6. package/dist/hsq.js +2 -0
  7. package/dist/index.js +1 -781
  8. package/dist/server/app-type.d.ts +1 -6
  9. package/dist/server/app-type.js +1 -2
  10. package/hsq.js +2 -0
  11. package/package.json +20 -59
  12. package/web/dist/assets/activity-motion-0wHCeUs7.css +1 -0
  13. package/web/dist/assets/activity-motion-2nE59DAT.js +2 -0
  14. package/web/dist/assets/activity-route-R9lPc2jy.js +1 -0
  15. package/web/dist/assets/agent-accounts-f1cxwgfz.js +18 -0
  16. package/web/dist/assets/alert-dialog-Dj464rjk.js +1 -0
  17. package/web/dist/assets/arrow-right-Dh_Lx3um.js +1 -0
  18. package/web/dist/assets/button-CHUAMTHK.js +3 -0
  19. package/web/dist/assets/centered-state-DGyy0SuA.js +1 -0
  20. package/web/dist/assets/cez-idle-EVoUsgU3.js +1 -0
  21. package/web/dist/assets/commit-diff-panel-BJyNYmCY.js +1 -0
  22. package/web/dist/assets/control-locations-C9II3kPz.js +1 -0
  23. package/web/dist/assets/design-icons-DmYTv2r1.js +1 -0
  24. package/web/dist/assets/diff-D_9MtICR.js +3 -0
  25. package/web/dist/assets/diff-controls-BR2uqhwG.js +1 -0
  26. package/web/dist/assets/diff-view-xRPxXHXl.js +11 -0
  27. package/web/dist/assets/dropdown-menu-DhrBcVgr.js +1 -0
  28. package/web/dist/assets/es2015-D345RR4o.js +41 -0
  29. package/web/dist/assets/file-preview-D08Kq15E.js +2 -0
  30. package/web/dist/assets/git-toolbar-D9taioU5.js +1 -0
  31. package/web/dist/assets/github-bv_pBGc5.js +1 -0
  32. package/web/dist/assets/github-sidebar-model-B0Ufci5S.js +1 -0
  33. package/web/dist/assets/global-activity-route-QxTPDyx-.js +1 -0
  34. package/web/dist/assets/hourglass-B0lPAJvT.js +1 -0
  35. package/web/dist/assets/{image-preview-C_t9q45f.js → image-preview-Cq1vDiEo.js} +1 -1
  36. package/web/dist/assets/index-B18AqW0Z.css +1 -0
  37. package/web/dist/assets/index-DgU3yYUl.js +14 -0
  38. package/web/dist/assets/index.global-D3Ga_D3Y.js +1 -0
  39. package/web/dist/assets/live-protocol-BVn0UA_g.js +64 -0
  40. package/web/dist/assets/live-refetch-BdnmTJ_8.js +1 -0
  41. package/web/dist/assets/{live-worker-BizfZSoh.ts → live-worker-BWdeGzQX.ts} +2 -1
  42. package/web/dist/assets/loader-circle-CZkGEdoI.js +1 -0
  43. package/web/dist/assets/markdown-D7DUNWcJ.js +6 -0
  44. package/web/dist/assets/mermaid.min-3O9YjB2l.js +1 -0
  45. package/web/dist/assets/message-square-B-MD-8rD.js +1 -0
  46. package/web/dist/assets/{nav-row-styles-AoIhhIwf.js → nav-row-styles-BZUUavOF.js} +1 -1
  47. package/web/dist/assets/popover-DRcRI46x.js +1 -0
  48. package/web/dist/assets/preview-pane-connected-cD-MTiVN.js +3 -0
  49. package/web/dist/assets/project-router-MMOk9VbW.js +1 -0
  50. package/web/dist/assets/project-scope-context-B3M-u8R0.js +4 -0
  51. package/web/dist/assets/queries-DORTKwyN.js +1 -0
  52. package/web/dist/assets/repo-git-E_4Ighvg.js +1 -0
  53. package/web/dist/assets/report-reader-XVNQsXB4.js +1 -0
  54. package/web/dist/assets/report-title-D4Mbu2Er.js +1 -0
  55. package/web/dist/assets/reports-B7QAzibP.css +1 -0
  56. package/web/dist/assets/reports-B_PVTBzP.js +1 -0
  57. package/web/dist/assets/run-header-wm0gSs6X.js +2 -0
  58. package/web/dist/assets/skill-empty-hint-YDmkqgo-.js +1 -0
  59. package/web/dist/assets/skills-D2RLxUIc.js +1 -0
  60. package/web/dist/assets/skills-DFBiAuJG.js +1 -0
  61. package/web/dist/assets/skills-workflows-C21NystW.css +1 -0
  62. package/web/dist/assets/sortable.esm-zp_qkYGV.js +5 -0
  63. package/web/dist/assets/tab-link-BvoGfK8S.js +1 -0
  64. package/web/dist/assets/task-changes-DNtkfFzQ.js +1 -0
  65. package/web/dist/assets/task-commits-CivO-OrN.js +1 -0
  66. package/web/dist/assets/task-files-dczkxV_G.js +1 -0
  67. package/web/dist/assets/task-github-item-DKV4yrcf.js +1 -0
  68. package/web/dist/assets/task-thread-DIaTTGEF.js +9 -0
  69. package/web/dist/assets/textarea-DlVUfdWG.js +1 -0
  70. package/web/dist/assets/thread-state-DIozHuHb.js +4 -0
  71. package/web/dist/assets/toaster-B1MyeHiE.js +1 -0
  72. package/web/dist/assets/use-hand-to-agent-state-D58ayxI4.js +1 -0
  73. package/web/dist/assets/useInfiniteQuery-BbYMWe23.js +1 -0
  74. package/web/dist/assets/useQuery-CqqnAJvu.js +1 -0
  75. package/web/dist/assets/workflows-YMEsGXeB.js +7 -0
  76. package/web/dist/assets/ws-BtSVmivO.js +1 -0
  77. package/web/dist/assets/zoomable-image-5pOUaPEg.js +1 -0
  78. package/web/dist/index.html +31 -15
  79. package/web/dist/live-worker.js +2 -2
  80. package/LICENSE +0 -22
  81. package/README.md +0 -1745
  82. package/dist/agent-config/account-identity.d.ts +0 -28
  83. package/dist/agent-config/account-identity.js +0 -131
  84. package/dist/agent-config/account-identity.js.map +0 -1
  85. package/dist/agent-config/catalog.d.ts +0 -70
  86. package/dist/agent-config/catalog.js +0 -383
  87. package/dist/agent-config/catalog.js.map +0 -1
  88. package/dist/agent-config/files.d.ts +0 -42
  89. package/dist/agent-config/files.js +0 -115
  90. package/dist/agent-config/files.js.map +0 -1
  91. package/dist/agent-config/model-settings/claude.d.ts +0 -2
  92. package/dist/agent-config/model-settings/claude.js +0 -11
  93. package/dist/agent-config/model-settings/claude.js.map +0 -1
  94. package/dist/agent-config/model-settings/codex.d.ts +0 -2
  95. package/dist/agent-config/model-settings/codex.js +0 -16
  96. package/dist/agent-config/model-settings/codex.js.map +0 -1
  97. package/dist/agent-config/model-settings/opencode.d.ts +0 -2
  98. package/dist/agent-config/model-settings/opencode.js +0 -8
  99. package/dist/agent-config/model-settings/opencode.js.map +0 -1
  100. package/dist/agent-config/model-settings/pi.d.ts +0 -2
  101. package/dist/agent-config/model-settings/pi.js +0 -38
  102. package/dist/agent-config/model-settings/pi.js.map +0 -1
  103. package/dist/agent-config/model-settings/shared.d.ts +0 -12
  104. package/dist/agent-config/model-settings/shared.js +0 -100
  105. package/dist/agent-config/model-settings/shared.js.map +0 -1
  106. package/dist/agent-config/model-settings/types.d.ts +0 -9
  107. package/dist/agent-config/model-settings/types.js +0 -2
  108. package/dist/agent-config/model-settings/types.js.map +0 -1
  109. package/dist/agent-config/models.d.ts +0 -9
  110. package/dist/agent-config/models.js +0 -40
  111. package/dist/agent-config/models.js.map +0 -1
  112. package/dist/agent-config/seed.d.ts +0 -15
  113. package/dist/agent-config/seed.js +0 -94
  114. package/dist/agent-config/seed.js.map +0 -1
  115. package/dist/agent-config/service.d.ts +0 -44
  116. package/dist/agent-config/service.js +0 -72
  117. package/dist/agent-config/service.js.map +0 -1
  118. package/dist/agent-config/validate.d.ts +0 -18
  119. package/dist/agent-config/validate.js +0 -82
  120. package/dist/agent-config/validate.js.map +0 -1
  121. package/dist/application-update/bin-recovery.d.ts +0 -5
  122. package/dist/application-update/bin-recovery.js +0 -96
  123. package/dist/application-update/bin-recovery.js.map +0 -1
  124. package/dist/application-update/discovery.d.ts +0 -22
  125. package/dist/application-update/discovery.js +0 -91
  126. package/dist/application-update/discovery.js.map +0 -1
  127. package/dist/application-update/helper.d.ts +0 -57
  128. package/dist/application-update/helper.js +0 -369
  129. package/dist/application-update/helper.js.map +0 -1
  130. package/dist/application-update/launcher.d.ts +0 -12
  131. package/dist/application-update/launcher.js +0 -59
  132. package/dist/application-update/launcher.js.map +0 -1
  133. package/dist/application-update/lock.d.ts +0 -4
  134. package/dist/application-update/lock.js +0 -70
  135. package/dist/application-update/lock.js.map +0 -1
  136. package/dist/application-update/npm-process.d.ts +0 -17
  137. package/dist/application-update/npm-process.js +0 -133
  138. package/dist/application-update/npm-process.js.map +0 -1
  139. package/dist/application-update/service.d.ts +0 -69
  140. package/dist/application-update/service.js +0 -456
  141. package/dist/application-update/service.js.map +0 -1
  142. package/dist/archive-on-merge-setting.d.ts +0 -15
  143. package/dist/archive-on-merge-setting.js +0 -14
  144. package/dist/archive-on-merge-setting.js.map +0 -1
  145. package/dist/artifacts/cli.d.ts +0 -9
  146. package/dist/artifacts/cli.js +0 -59
  147. package/dist/artifacts/cli.js.map +0 -1
  148. package/dist/artifacts/lifecycle.d.ts +0 -4
  149. package/dist/artifacts/lifecycle.js +0 -42
  150. package/dist/artifacts/lifecycle.js.map +0 -1
  151. package/dist/artifacts/resolve.d.ts +0 -18
  152. package/dist/artifacts/resolve.js +0 -103
  153. package/dist/artifacts/resolve.js.map +0 -1
  154. package/dist/artifacts/store.d.ts +0 -8
  155. package/dist/artifacts/store.js +0 -323
  156. package/dist/artifacts/store.js.map +0 -1
  157. package/dist/automations/automation-cli.d.ts +0 -59
  158. package/dist/automations/automation-cli.js +0 -509
  159. package/dist/automations/automation-cli.js.map +0 -1
  160. package/dist/automations/builtin-skill.d.ts +0 -7
  161. package/dist/automations/builtin-skill.js +0 -14
  162. package/dist/automations/builtin-skill.js.map +0 -1
  163. package/dist/automations/coordinator.d.ts +0 -33
  164. package/dist/automations/coordinator.js +0 -86
  165. package/dist/automations/coordinator.js.map +0 -1
  166. package/dist/automations/github-baseline.d.ts +0 -3
  167. package/dist/automations/github-baseline.js +0 -17
  168. package/dist/automations/github-baseline.js.map +0 -1
  169. package/dist/automations/github-poller.d.ts +0 -93
  170. package/dist/automations/github-poller.js +0 -303
  171. package/dist/automations/github-poller.js.map +0 -1
  172. package/dist/automations/prompts.d.ts +0 -12
  173. package/dist/automations/prompts.js +0 -160
  174. package/dist/automations/prompts.js.map +0 -1
  175. package/dist/automations/schedule-runner.d.ts +0 -149
  176. package/dist/automations/schedule-runner.js +0 -513
  177. package/dist/automations/schedule-runner.js.map +0 -1
  178. package/dist/automations/scheduler.d.ts +0 -87
  179. package/dist/automations/scheduler.js +0 -434
  180. package/dist/automations/scheduler.js.map +0 -1
  181. package/dist/automations/service.d.ts +0 -777
  182. package/dist/automations/service.js +0 -444
  183. package/dist/automations/service.js.map +0 -1
  184. package/dist/automations/store.d.ts +0 -160
  185. package/dist/automations/store.js +0 -738
  186. package/dist/automations/store.js.map +0 -1
  187. package/dist/automations/task-template.d.ts +0 -59
  188. package/dist/automations/task-template.js +0 -273
  189. package/dist/automations/task-template.js.map +0 -1
  190. package/dist/automations/tool-adapter.d.ts +0 -6
  191. package/dist/automations/tool-adapter.js +0 -108
  192. package/dist/automations/tool-adapter.js.map +0 -1
  193. package/dist/automations/types.d.ts +0 -1
  194. package/dist/automations/types.js +0 -2
  195. package/dist/automations/types.js.map +0 -1
  196. package/dist/autosave-cleanup.d.ts +0 -26
  197. package/dist/autosave-cleanup.js +0 -87
  198. package/dist/autosave-cleanup.js.map +0 -1
  199. package/dist/autosave-git.d.ts +0 -21
  200. package/dist/autosave-git.js +0 -204
  201. package/dist/autosave-git.js.map +0 -1
  202. package/dist/autosave-group.d.ts +0 -8
  203. package/dist/autosave-group.js +0 -61
  204. package/dist/autosave-group.js.map +0 -1
  205. package/dist/autosave-holders.d.ts +0 -34
  206. package/dist/autosave-holders.js +0 -204
  207. package/dist/autosave-holders.js.map +0 -1
  208. package/dist/autosave-windows.d.ts +0 -25
  209. package/dist/autosave-windows.js +0 -156
  210. package/dist/autosave-windows.js.map +0 -1
  211. package/dist/ci-wait/client.d.ts +0 -28
  212. package/dist/ci-wait/client.js +0 -105
  213. package/dist/ci-wait/client.js.map +0 -1
  214. package/dist/ci-wait/controller.d.ts +0 -780
  215. package/dist/ci-wait/controller.js +0 -334
  216. package/dist/ci-wait/controller.js.map +0 -1
  217. package/dist/ci-wait/errors.d.ts +0 -27
  218. package/dist/ci-wait/errors.js +0 -253
  219. package/dist/ci-wait/errors.js.map +0 -1
  220. package/dist/ci-wait/github.d.ts +0 -87
  221. package/dist/ci-wait/github.js +0 -278
  222. package/dist/ci-wait/github.js.map +0 -1
  223. package/dist/ci-wait/injection.d.ts +0 -3
  224. package/dist/ci-wait/injection.js +0 -26
  225. package/dist/ci-wait/injection.js.map +0 -1
  226. package/dist/ci-wait/mcp.d.ts +0 -3
  227. package/dist/ci-wait/mcp.js +0 -30
  228. package/dist/ci-wait/mcp.js.map +0 -1
  229. package/dist/ci-wait/resources.d.ts +0 -7
  230. package/dist/ci-wait/resources.js +0 -32
  231. package/dist/ci-wait/resources.js.map +0 -1
  232. package/dist/ci-wait/supervisor.d.ts +0 -29
  233. package/dist/ci-wait/supervisor.js +0 -260
  234. package/dist/ci-wait/supervisor.js.map +0 -1
  235. package/dist/ci-wait/tools.d.ts +0 -830
  236. package/dist/ci-wait/tools.js +0 -209
  237. package/dist/ci-wait/tools.js.map +0 -1
  238. package/dist/config.d.ts +0 -68
  239. package/dist/config.js +0 -209
  240. package/dist/config.js.map +0 -1
  241. package/dist/contract/active-provider.d.ts +0 -12
  242. package/dist/contract/agent-config.d.ts +0 -160
  243. package/dist/contract/agent-profiles.d.ts +0 -369
  244. package/dist/contract/application-update.d.ts +0 -32
  245. package/dist/contract/artifacts.d.ts +0 -83
  246. package/dist/contract/ask-schema.d.ts +0 -50
  247. package/dist/contract/ask.d.ts +0 -9
  248. package/dist/contract/attachments.d.ts +0 -35
  249. package/dist/contract/attention.d.ts +0 -91
  250. package/dist/contract/automation-requests.d.ts +0 -308
  251. package/dist/contract/automation-schedule.d.ts +0 -89
  252. package/dist/contract/automation-storage.d.ts +0 -512
  253. package/dist/contract/automations.d.ts +0 -1542
  254. package/dist/contract/ci-wait.d.ts +0 -222
  255. package/dist/contract/config-requests.d.ts +0 -36
  256. package/dist/contract/conversations.d.ts +0 -401
  257. package/dist/contract/defined.d.ts +0 -8
  258. package/dist/contract/delegation.d.ts +0 -2165
  259. package/dist/contract/discovery.d.ts +0 -228
  260. package/dist/contract/effort.d.ts +0 -18
  261. package/dist/contract/events.d.ts +0 -303
  262. package/dist/contract/github-requests.d.ts +0 -26
  263. package/dist/contract/github.d.ts +0 -732
  264. package/dist/contract/handoff.d.ts +0 -43
  265. package/dist/contract/health.d.ts +0 -124
  266. package/dist/contract/image-path.d.ts +0 -6
  267. package/dist/contract/index.d.ts +0 -59
  268. package/dist/contract/index.js +0 -6035
  269. package/dist/contract/live-coordination.d.ts +0 -158
  270. package/dist/contract/live-limits.d.ts +0 -8
  271. package/dist/contract/live.d.ts +0 -123
  272. package/dist/contract/pending-ask.d.ts +0 -58
  273. package/dist/contract/permissions.d.ts +0 -54
  274. package/dist/contract/preview.d.ts +0 -560
  275. package/dist/contract/project-limits.d.ts +0 -33
  276. package/dist/contract/projects.d.ts +0 -716
  277. package/dist/contract/provider-requests.d.ts +0 -77
  278. package/dist/contract/query-requests.d.ts +0 -52
  279. package/dist/contract/repo-requests.d.ts +0 -12
  280. package/dist/contract/repo.d.ts +0 -515
  281. package/dist/contract/run-labels.d.ts +0 -8
  282. package/dist/contract/run-limits.d.ts +0 -8
  283. package/dist/contract/run-predicates.d.ts +0 -32
  284. package/dist/contract/run-requests.d.ts +0 -33
  285. package/dist/contract/run-search.d.ts +0 -193
  286. package/dist/contract/runs.d.ts +0 -5711
  287. package/dist/contract/scheduled-tasks.d.ts +0 -187
  288. package/dist/contract/skills.d.ts +0 -56
  289. package/dist/contract/team-skill-ref.d.ts +0 -10
  290. package/dist/contract/tool-display.d.ts +0 -25
  291. package/dist/contract/ui-state-requests.d.ts +0 -60
  292. package/dist/contract/version.d.ts +0 -3
  293. package/dist/contract/voice.d.ts +0 -213
  294. package/dist/contract/waits.d.ts +0 -1367
  295. package/dist/contract/workflow-file.d.ts +0 -37
  296. package/dist/contract/workflow-requests.d.ts +0 -7
  297. package/dist/contract/workflows.d.ts +0 -250
  298. package/dist/contract/workspace.d.ts +0 -631
  299. package/dist/contract/zoned-time.d.ts +0 -26
  300. package/dist/core/agent-env.d.ts +0 -30
  301. package/dist/core/agent-env.js +0 -400
  302. package/dist/core/agent-env.js.map +0 -1
  303. package/dist/core/agent-model-policy.d.ts +0 -10
  304. package/dist/core/agent-model-policy.js +0 -36
  305. package/dist/core/agent-model-policy.js.map +0 -1
  306. package/dist/core/agent-profiles.d.ts +0 -50
  307. package/dist/core/agent-profiles.js +0 -105
  308. package/dist/core/agent-profiles.js.map +0 -1
  309. package/dist/core/agent-runner.d.ts +0 -394
  310. package/dist/core/agent-runner.js +0 -96
  311. package/dist/core/agent-runner.js.map +0 -1
  312. package/dist/core/ask.d.ts +0 -79
  313. package/dist/core/ask.js +0 -232
  314. package/dist/core/ask.js.map +0 -1
  315. package/dist/core/backend-detect.d.ts +0 -17
  316. package/dist/core/backend-detect.js +0 -209
  317. package/dist/core/backend-detect.js.map +0 -1
  318. package/dist/core/claude-cli-runner.d.ts +0 -72
  319. package/dist/core/claude-cli-runner.js +0 -910
  320. package/dist/core/claude-cli-runner.js.map +0 -1
  321. package/dist/core/claude-model-catalog.d.ts +0 -16
  322. package/dist/core/claude-model-catalog.js +0 -198
  323. package/dist/core/claude-model-catalog.js.map +0 -1
  324. package/dist/core/claude-stream.d.ts +0 -31
  325. package/dist/core/claude-stream.js +0 -68
  326. package/dist/core/claude-stream.js.map +0 -1
  327. package/dist/core/claude-ui-mapper.d.ts +0 -80
  328. package/dist/core/claude-ui-mapper.js +0 -696
  329. package/dist/core/claude-ui-mapper.js.map +0 -1
  330. package/dist/core/codex-app-server-runner.d.ts +0 -61
  331. package/dist/core/codex-app-server-runner.js +0 -1269
  332. package/dist/core/codex-app-server-runner.js.map +0 -1
  333. package/dist/core/codex-app-server-transport.d.ts +0 -52
  334. package/dist/core/codex-app-server-transport.js +0 -199
  335. package/dist/core/codex-app-server-transport.js.map +0 -1
  336. package/dist/core/codex-approvals.d.ts +0 -12
  337. package/dist/core/codex-approvals.js +0 -161
  338. package/dist/core/codex-approvals.js.map +0 -1
  339. package/dist/core/codex-model-catalog.d.ts +0 -10
  340. package/dist/core/codex-model-catalog.js +0 -110
  341. package/dist/core/codex-model-catalog.js.map +0 -1
  342. package/dist/core/codex-native-frames.d.ts +0 -10
  343. package/dist/core/codex-native-frames.js +0 -47
  344. package/dist/core/codex-native-frames.js.map +0 -1
  345. package/dist/core/codex-permissions.d.ts +0 -6
  346. package/dist/core/codex-permissions.js +0 -27
  347. package/dist/core/codex-permissions.js.map +0 -1
  348. package/dist/core/codex-stream-error.d.ts +0 -2
  349. package/dist/core/codex-stream-error.js +0 -12
  350. package/dist/core/codex-stream-error.js.map +0 -1
  351. package/dist/core/codex-turn-outcome.d.ts +0 -8
  352. package/dist/core/codex-turn-outcome.js +0 -30
  353. package/dist/core/codex-turn-outcome.js.map +0 -1
  354. package/dist/core/codex-ui-mapper.d.ts +0 -112
  355. package/dist/core/codex-ui-mapper.js +0 -808
  356. package/dist/core/codex-ui-mapper.js.map +0 -1
  357. package/dist/core/cursor-acp-runner.d.ts +0 -34
  358. package/dist/core/cursor-acp-runner.js +0 -777
  359. package/dist/core/cursor-acp-runner.js.map +0 -1
  360. package/dist/core/cursor-cli-flags.d.ts +0 -19
  361. package/dist/core/cursor-cli-flags.js +0 -47
  362. package/dist/core/cursor-cli-flags.js.map +0 -1
  363. package/dist/core/cursor-config-options.d.ts +0 -18
  364. package/dist/core/cursor-config-options.js +0 -31
  365. package/dist/core/cursor-config-options.js.map +0 -1
  366. package/dist/core/cursor-model-catalog.d.ts +0 -45
  367. package/dist/core/cursor-model-catalog.js +0 -300
  368. package/dist/core/cursor-model-catalog.js.map +0 -1
  369. package/dist/core/cursor-print-capabilities.d.ts +0 -16
  370. package/dist/core/cursor-print-capabilities.js +0 -141
  371. package/dist/core/cursor-print-capabilities.js.map +0 -1
  372. package/dist/core/cursor-print-process.d.ts +0 -31
  373. package/dist/core/cursor-print-process.js +0 -117
  374. package/dist/core/cursor-print-process.js.map +0 -1
  375. package/dist/core/cursor-print-runner.d.ts +0 -31
  376. package/dist/core/cursor-print-runner.js +0 -555
  377. package/dist/core/cursor-print-runner.js.map +0 -1
  378. package/dist/core/cursor-print-tool-catalog.d.ts +0 -10
  379. package/dist/core/cursor-print-tool-catalog.js +0 -91
  380. package/dist/core/cursor-print-tool-catalog.js.map +0 -1
  381. package/dist/core/cursor-print-ui-mapper.d.ts +0 -47
  382. package/dist/core/cursor-print-ui-mapper.js +0 -553
  383. package/dist/core/cursor-print-ui-mapper.js.map +0 -1
  384. package/dist/core/cursor-provider-error.d.ts +0 -33
  385. package/dist/core/cursor-provider-error.js +0 -68
  386. package/dist/core/cursor-provider-error.js.map +0 -1
  387. package/dist/core/cursor-runner.d.ts +0 -24
  388. package/dist/core/cursor-runner.js +0 -149
  389. package/dist/core/cursor-runner.js.map +0 -1
  390. package/dist/core/cursor-ui-mapper.d.ts +0 -29
  391. package/dist/core/cursor-ui-mapper.js +0 -275
  392. package/dist/core/cursor-ui-mapper.js.map +0 -1
  393. package/dist/core/defined.d.ts +0 -1
  394. package/dist/core/defined.js +0 -2
  395. package/dist/core/defined.js.map +0 -1
  396. package/dist/core/hook-items.d.ts +0 -14
  397. package/dist/core/hook-items.js +0 -13
  398. package/dist/core/hook-items.js.map +0 -1
  399. package/dist/core/host-model-catalog.d.ts +0 -7
  400. package/dist/core/host-model-catalog.js +0 -21
  401. package/dist/core/host-model-catalog.js.map +0 -1
  402. package/dist/core/input-submissions.d.ts +0 -14
  403. package/dist/core/input-submissions.js +0 -26
  404. package/dist/core/input-submissions.js.map +0 -1
  405. package/dist/core/managed-session.d.ts +0 -6
  406. package/dist/core/managed-session.js +0 -116
  407. package/dist/core/managed-session.js.map +0 -1
  408. package/dist/core/model-identity.d.ts +0 -108
  409. package/dist/core/model-identity.js +0 -137
  410. package/dist/core/model-identity.js.map +0 -1
  411. package/dist/core/model-presets.d.ts +0 -10
  412. package/dist/core/model-presets.js +0 -77
  413. package/dist/core/model-presets.js.map +0 -1
  414. package/dist/core/ndjson.d.ts +0 -6
  415. package/dist/core/ndjson.js +0 -23
  416. package/dist/core/ndjson.js.map +0 -1
  417. package/dist/core/omp-model-catalog.d.ts +0 -43
  418. package/dist/core/omp-model-catalog.js +0 -205
  419. package/dist/core/omp-model-catalog.js.map +0 -1
  420. package/dist/core/omp-runner.d.ts +0 -72
  421. package/dist/core/omp-runner.js +0 -832
  422. package/dist/core/omp-runner.js.map +0 -1
  423. package/dist/core/omp-ui-mapper.d.ts +0 -106
  424. package/dist/core/omp-ui-mapper.js +0 -856
  425. package/dist/core/omp-ui-mapper.js.map +0 -1
  426. package/dist/core/opencode-model-catalog.d.ts +0 -32
  427. package/dist/core/opencode-model-catalog.js +0 -215
  428. package/dist/core/opencode-model-catalog.js.map +0 -1
  429. package/dist/core/opencode-permissions.d.ts +0 -52
  430. package/dist/core/opencode-permissions.js +0 -101
  431. package/dist/core/opencode-permissions.js.map +0 -1
  432. package/dist/core/opencode-server-runner.d.ts +0 -61
  433. package/dist/core/opencode-server-runner.js +0 -1692
  434. package/dist/core/opencode-server-runner.js.map +0 -1
  435. package/dist/core/opencode-session-error.d.ts +0 -19
  436. package/dist/core/opencode-session-error.js +0 -42
  437. package/dist/core/opencode-session-error.js.map +0 -1
  438. package/dist/core/opencode-ui-mapper.d.ts +0 -137
  439. package/dist/core/opencode-ui-mapper.js +0 -768
  440. package/dist/core/opencode-ui-mapper.js.map +0 -1
  441. package/dist/core/pi-model-catalog.d.ts +0 -38
  442. package/dist/core/pi-model-catalog.js +0 -249
  443. package/dist/core/pi-model-catalog.js.map +0 -1
  444. package/dist/core/pi-rpc-turn.d.ts +0 -184
  445. package/dist/core/pi-rpc-turn.js +0 -380
  446. package/dist/core/pi-rpc-turn.js.map +0 -1
  447. package/dist/core/pi-rpc-wire.d.ts +0 -31
  448. package/dist/core/pi-rpc-wire.js +0 -88
  449. package/dist/core/pi-rpc-wire.js.map +0 -1
  450. package/dist/core/pi-runner.d.ts +0 -43
  451. package/dist/core/pi-runner.js +0 -592
  452. package/dist/core/pi-runner.js.map +0 -1
  453. package/dist/core/pi-ui-mapper.d.ts +0 -52
  454. package/dist/core/pi-ui-mapper.js +0 -373
  455. package/dist/core/pi-ui-mapper.js.map +0 -1
  456. package/dist/core/process-usage.d.ts +0 -74
  457. package/dist/core/process-usage.js +0 -218
  458. package/dist/core/process-usage.js.map +0 -1
  459. package/dist/core/provider-auth.d.ts +0 -168
  460. package/dist/core/provider-auth.js +0 -660
  461. package/dist/core/provider-auth.js.map +0 -1
  462. package/dist/core/provider-availability.d.ts +0 -3
  463. package/dist/core/provider-availability.js +0 -14
  464. package/dist/core/provider-availability.js.map +0 -1
  465. package/dist/core/runner-factory.d.ts +0 -11
  466. package/dist/core/runner-factory.js +0 -31
  467. package/dist/core/runner-factory.js.map +0 -1
  468. package/dist/core/runner-model-catalog.d.ts +0 -34
  469. package/dist/core/runner-model-catalog.js +0 -109
  470. package/dist/core/runner-model-catalog.js.map +0 -1
  471. package/dist/core/runner-runtime.d.ts +0 -40
  472. package/dist/core/runner-runtime.js +0 -88
  473. package/dist/core/runner-runtime.js.map +0 -1
  474. package/dist/core/runner-stderr.d.ts +0 -2
  475. package/dist/core/runner-stderr.js +0 -20
  476. package/dist/core/runner-stderr.js.map +0 -1
  477. package/dist/core/runner-tool-grants.d.ts +0 -21
  478. package/dist/core/runner-tool-grants.js +0 -64
  479. package/dist/core/runner-tool-grants.js.map +0 -1
  480. package/dist/core/secret-redaction.d.ts +0 -20
  481. package/dist/core/secret-redaction.js +0 -98
  482. package/dist/core/secret-redaction.js.map +0 -1
  483. package/dist/core/session-process.d.ts +0 -42
  484. package/dist/core/session-process.js +0 -360
  485. package/dist/core/session-process.js.map +0 -1
  486. package/dist/core/shell-env.d.ts +0 -17
  487. package/dist/core/shell-env.js +0 -51
  488. package/dist/core/shell-env.js.map +0 -1
  489. package/dist/core/ui-events.d.ts +0 -348
  490. package/dist/core/ui-events.js +0 -2
  491. package/dist/core/ui-events.js.map +0 -1
  492. package/dist/core/usage-limit.d.ts +0 -42
  493. package/dist/core/usage-limit.js +0 -152
  494. package/dist/core/usage-limit.js.map +0 -1
  495. package/dist/core/usage.d.ts +0 -11
  496. package/dist/core/usage.js +0 -15
  497. package/dist/core/usage.js.map +0 -1
  498. package/dist/core/v1-text-coalescer.d.ts +0 -36
  499. package/dist/core/v1-text-coalescer.js +0 -72
  500. package/dist/core/v1-text-coalescer.js.map +0 -1
  501. package/dist/data-gitignore.d.ts +0 -6
  502. package/dist/data-gitignore.js +0 -59
  503. package/dist/data-gitignore.js.map +0 -1
  504. package/dist/delegation/capacity.d.ts +0 -15
  505. package/dist/delegation/capacity.js +0 -30
  506. package/dist/delegation/capacity.js.map +0 -1
  507. package/dist/delegation/cli.d.ts +0 -5
  508. package/dist/delegation/cli.js +0 -559
  509. package/dist/delegation/cli.js.map +0 -1
  510. package/dist/delegation/context.d.ts +0 -40
  511. package/dist/delegation/context.js +0 -383
  512. package/dist/delegation/context.js.map +0 -1
  513. package/dist/delegation/conversation-send.d.ts +0 -63
  514. package/dist/delegation/conversation-send.js +0 -60
  515. package/dist/delegation/conversation-send.js.map +0 -1
  516. package/dist/delegation/conversations.d.ts +0 -1670
  517. package/dist/delegation/conversations.js +0 -277
  518. package/dist/delegation/conversations.js.map +0 -1
  519. package/dist/delegation/credentials.d.ts +0 -21
  520. package/dist/delegation/credentials.js +0 -66
  521. package/dist/delegation/credentials.js.map +0 -1
  522. package/dist/delegation/destroy-observation.d.ts +0 -42
  523. package/dist/delegation/destroy-observation.js +0 -115
  524. package/dist/delegation/destroy-observation.js.map +0 -1
  525. package/dist/delegation/effort.d.ts +0 -1
  526. package/dist/delegation/effort.js +0 -11
  527. package/dist/delegation/effort.js.map +0 -1
  528. package/dist/delegation/execution-identity.d.ts +0 -254
  529. package/dist/delegation/execution-identity.js +0 -250
  530. package/dist/delegation/execution-identity.js.map +0 -1
  531. package/dist/delegation/execution-settings.d.ts +0 -10
  532. package/dist/delegation/execution-settings.js +0 -65
  533. package/dist/delegation/execution-settings.js.map +0 -1
  534. package/dist/delegation/idle-test-app.d.ts +0 -4
  535. package/dist/delegation/idle-test-app.js +0 -185
  536. package/dist/delegation/idle-test-app.js.map +0 -1
  537. package/dist/delegation/input.d.ts +0 -12
  538. package/dist/delegation/input.js +0 -50
  539. package/dist/delegation/input.js.map +0 -1
  540. package/dist/delegation/park-notice.d.ts +0 -45
  541. package/dist/delegation/park-notice.js +0 -79
  542. package/dist/delegation/park-notice.js.map +0 -1
  543. package/dist/delegation/policy.d.ts +0 -22
  544. package/dist/delegation/policy.js +0 -95
  545. package/dist/delegation/policy.js.map +0 -1
  546. package/dist/delegation/process-liveness.d.ts +0 -98
  547. package/dist/delegation/process-liveness.js +0 -213
  548. package/dist/delegation/process-liveness.js.map +0 -1
  549. package/dist/delegation/provision.d.ts +0 -35
  550. package/dist/delegation/provision.js +0 -178
  551. package/dist/delegation/provision.js.map +0 -1
  552. package/dist/delegation/questions.d.ts +0 -24
  553. package/dist/delegation/questions.js +0 -55
  554. package/dist/delegation/questions.js.map +0 -1
  555. package/dist/delegation/readiness.d.ts +0 -13
  556. package/dist/delegation/readiness.js +0 -19
  557. package/dist/delegation/readiness.js.map +0 -1
  558. package/dist/delegation/results.d.ts +0 -13
  559. package/dist/delegation/results.js +0 -154
  560. package/dist/delegation/results.js.map +0 -1
  561. package/dist/delegation/retry-backoff.d.ts +0 -31
  562. package/dist/delegation/retry-backoff.js +0 -26
  563. package/dist/delegation/retry-backoff.js.map +0 -1
  564. package/dist/delegation/routes.d.ts +0 -1014
  565. package/dist/delegation/routes.js +0 -77
  566. package/dist/delegation/routes.js.map +0 -1
  567. package/dist/delegation/scratch-cleanup.d.ts +0 -28
  568. package/dist/delegation/scratch-cleanup.js +0 -145
  569. package/dist/delegation/scratch-cleanup.js.map +0 -1
  570. package/dist/delegation/service.d.ts +0 -284
  571. package/dist/delegation/service.js +0 -1046
  572. package/dist/delegation/service.js.map +0 -1
  573. package/dist/delegation/task-discovery.d.ts +0 -6
  574. package/dist/delegation/task-discovery.js +0 -23
  575. package/dist/delegation/task-discovery.js.map +0 -1
  576. package/dist/delegation/transport.d.ts +0 -992
  577. package/dist/delegation/transport.js +0 -22
  578. package/dist/delegation/transport.js.map +0 -1
  579. package/dist/delegation/wait.d.ts +0 -14
  580. package/dist/delegation/wait.js +0 -72
  581. package/dist/delegation/wait.js.map +0 -1
  582. package/dist/delegation/windows-test-app.d.ts +0 -5
  583. package/dist/delegation/windows-test-app.js +0 -63
  584. package/dist/delegation/windows-test-app.js.map +0 -1
  585. package/dist/delegation/windows-workspace-identity.d.ts +0 -3
  586. package/dist/delegation/windows-workspace-identity.js +0 -22
  587. package/dist/delegation/windows-workspace-identity.js.map +0 -1
  588. package/dist/delegation/workspace.d.ts +0 -33
  589. package/dist/delegation/workspace.js +0 -560
  590. package/dist/delegation/workspace.js.map +0 -1
  591. package/dist/detached-process.d.ts +0 -125
  592. package/dist/detached-process.js +0 -448
  593. package/dist/detached-process.js.map +0 -1
  594. package/dist/discovery/catalog.d.ts +0 -15
  595. package/dist/discovery/catalog.js +0 -31
  596. package/dist/discovery/catalog.js.map +0 -1
  597. package/dist/discovery/cli.d.ts +0 -8
  598. package/dist/discovery/cli.js +0 -106
  599. package/dist/discovery/cli.js.map +0 -1
  600. package/dist/git-diff-base.d.ts +0 -41
  601. package/dist/git-diff-base.js +0 -116
  602. package/dist/git-diff-base.js.map +0 -1
  603. package/dist/git-index-copy.d.ts +0 -4
  604. package/dist/git-index-copy.js +0 -10
  605. package/dist/git-index-copy.js.map +0 -1
  606. package/dist/git-refs.d.ts +0 -11
  607. package/dist/git-refs.js +0 -14
  608. package/dist/git-refs.js.map +0 -1
  609. package/dist/git-worktree-lock-helper.d.ts +0 -7
  610. package/dist/git-worktree-lock-helper.js +0 -158
  611. package/dist/git-worktree-lock-helper.js.map +0 -1
  612. package/dist/git-worktree-lock.d.ts +0 -17
  613. package/dist/git-worktree-lock.js +0 -90
  614. package/dist/git-worktree-lock.js.map +0 -1
  615. package/dist/git-worktree-release.d.ts +0 -20
  616. package/dist/git-worktree-release.js +0 -27
  617. package/dist/git-worktree-release.js.map +0 -1
  618. package/dist/git-worktree.d.ts +0 -154
  619. package/dist/git-worktree.js +0 -858
  620. package/dist/git-worktree.js.map +0 -1
  621. package/dist/handoff.d.ts +0 -72
  622. package/dist/handoff.js +0 -209
  623. package/dist/handoff.js.map +0 -1
  624. package/dist/index.d.ts +0 -2
  625. package/dist/index.js.map +0 -1
  626. package/dist/install-as-command.d.ts +0 -40
  627. package/dist/install-as-command.js +0 -52
  628. package/dist/install-as-command.js.map +0 -1
  629. package/dist/merge-observations.d.ts +0 -13
  630. package/dist/merge-observations.js +0 -55
  631. package/dist/merge-observations.js.map +0 -1
  632. package/dist/open-url.d.ts +0 -2
  633. package/dist/open-url.js +0 -10
  634. package/dist/open-url.js.map +0 -1
  635. package/dist/pack-check.d.ts +0 -17
  636. package/dist/pack-check.js +0 -27
  637. package/dist/pack-check.js.map +0 -1
  638. package/dist/paths.d.ts +0 -138
  639. package/dist/paths.js +0 -220
  640. package/dist/paths.js.map +0 -1
  641. package/dist/planner.d.ts +0 -28
  642. package/dist/planner.js +0 -271
  643. package/dist/planner.js.map +0 -1
  644. package/dist/preview/agent-address.d.ts +0 -34
  645. package/dist/preview/agent-address.js +0 -51
  646. package/dist/preview/agent-address.js.map +0 -1
  647. package/dist/preview/agent-marker.d.ts +0 -17
  648. package/dist/preview/agent-marker.js +0 -71
  649. package/dist/preview/agent-marker.js.map +0 -1
  650. package/dist/preview/browser-launch.d.ts +0 -27
  651. package/dist/preview/browser-launch.js +0 -53
  652. package/dist/preview/browser-launch.js.map +0 -1
  653. package/dist/preview/cdp-proxy.d.ts +0 -54
  654. package/dist/preview/cdp-proxy.js +0 -151
  655. package/dist/preview/cdp-proxy.js.map +0 -1
  656. package/dist/preview/cdp.d.ts +0 -49
  657. package/dist/preview/cdp.js +0 -167
  658. package/dist/preview/cdp.js.map +0 -1
  659. package/dist/preview/chromium.d.ts +0 -88
  660. package/dist/preview/chromium.js +0 -482
  661. package/dist/preview/chromium.js.map +0 -1
  662. package/dist/preview/dev-server.d.ts +0 -68
  663. package/dist/preview/dev-server.js +0 -317
  664. package/dist/preview/dev-server.js.map +0 -1
  665. package/dist/preview/host.d.ts +0 -206
  666. package/dist/preview/host.js +0 -929
  667. package/dist/preview/host.js.map +0 -1
  668. package/dist/preview/registration.d.ts +0 -68
  669. package/dist/preview/registration.js +0 -111
  670. package/dist/preview/registration.js.map +0 -1
  671. package/dist/preview/run-tools.d.ts +0 -9
  672. package/dist/preview/run-tools.js +0 -72
  673. package/dist/preview/run-tools.js.map +0 -1
  674. package/dist/preview/session.d.ts +0 -87
  675. package/dist/preview/session.js +0 -378
  676. package/dist/preview/session.js.map +0 -1
  677. package/dist/preview/url.d.ts +0 -6
  678. package/dist/preview/url.js +0 -17
  679. package/dist/preview/url.js.map +0 -1
  680. package/dist/process-wait/exit-file.d.ts +0 -29
  681. package/dist/process-wait/exit-file.js +0 -67
  682. package/dist/process-wait/exit-file.js.map +0 -1
  683. package/dist/process-wait/supervisor.d.ts +0 -30
  684. package/dist/process-wait/supervisor.js +0 -71
  685. package/dist/process-wait/supervisor.js.map +0 -1
  686. package/dist/release/manifests.d.ts +0 -103
  687. package/dist/release/manifests.js +0 -90
  688. package/dist/release/manifests.js.map +0 -1
  689. package/dist/release/snapshot.d.ts +0 -67
  690. package/dist/release/snapshot.js +0 -97
  691. package/dist/release/snapshot.js.map +0 -1
  692. package/dist/release/stable.d.ts +0 -38
  693. package/dist/release/stable.js +0 -55
  694. package/dist/release/stable.js.map +0 -1
  695. package/dist/runs/agent-tmpdir-removal.d.ts +0 -15
  696. package/dist/runs/agent-tmpdir-removal.js +0 -60
  697. package/dist/runs/agent-tmpdir-removal.js.map +0 -1
  698. package/dist/runs/agent-tmpdir.d.ts +0 -119
  699. package/dist/runs/agent-tmpdir.js +0 -829
  700. package/dist/runs/agent-tmpdir.js.map +0 -1
  701. package/dist/runs/arm-repo-handle.d.ts +0 -9
  702. package/dist/runs/arm-repo-handle.js +0 -45
  703. package/dist/runs/arm-repo-handle.js.map +0 -1
  704. package/dist/runs/auto-name.d.ts +0 -75
  705. package/dist/runs/auto-name.js +0 -179
  706. package/dist/runs/auto-name.js.map +0 -1
  707. package/dist/runs/client-request.d.ts +0 -11
  708. package/dist/runs/client-request.js +0 -26
  709. package/dist/runs/client-request.js.map +0 -1
  710. package/dist/runs/conversation-identity.d.ts +0 -19
  711. package/dist/runs/conversation-identity.js +0 -31
  712. package/dist/runs/conversation-identity.js.map +0 -1
  713. package/dist/runs/delegation-state.d.ts +0 -409
  714. package/dist/runs/delegation-state.js +0 -22
  715. package/dist/runs/delegation-state.js.map +0 -1
  716. package/dist/runs/event-history-agent-context.d.ts +0 -14
  717. package/dist/runs/event-history-agent-context.js +0 -105
  718. package/dist/runs/event-history-agent-context.js.map +0 -1
  719. package/dist/runs/event-history-context.d.ts +0 -15
  720. package/dist/runs/event-history-context.js +0 -109
  721. package/dist/runs/event-history-context.js.map +0 -1
  722. package/dist/runs/event-history.d.ts +0 -53
  723. package/dist/runs/event-history.js +0 -535
  724. package/dist/runs/event-history.js.map +0 -1
  725. package/dist/runs/history-compressor.d.ts +0 -29
  726. package/dist/runs/history-compressor.js +0 -116
  727. package/dist/runs/history-compressor.js.map +0 -1
  728. package/dist/runs/history-file.d.ts +0 -36
  729. package/dist/runs/history-file.js +0 -463
  730. package/dist/runs/history-file.js.map +0 -1
  731. package/dist/runs/history-stream.d.ts +0 -2
  732. package/dist/runs/history-stream.js +0 -62
  733. package/dist/runs/history-stream.js.map +0 -1
  734. package/dist/runs/legacy-index.d.ts +0 -49
  735. package/dist/runs/legacy-index.js +0 -155
  736. package/dist/runs/legacy-index.js.map +0 -1
  737. package/dist/runs/live-item-snapshots.d.ts +0 -13
  738. package/dist/runs/live-item-snapshots.js +0 -79
  739. package/dist/runs/live-item-snapshots.js.map +0 -1
  740. package/dist/runs/loaded-run-healing.d.ts +0 -3
  741. package/dist/runs/loaded-run-healing.js +0 -17
  742. package/dist/runs/loaded-run-healing.js.map +0 -1
  743. package/dist/runs/outcome-commit.d.ts +0 -98
  744. package/dist/runs/outcome-commit.js +0 -132
  745. package/dist/runs/outcome-commit.js.map +0 -1
  746. package/dist/runs/pull-requests.d.ts +0 -14
  747. package/dist/runs/pull-requests.js +0 -96
  748. package/dist/runs/pull-requests.js.map +0 -1
  749. package/dist/runs/raw-record.d.ts +0 -40
  750. package/dist/runs/raw-record.js +0 -133
  751. package/dist/runs/raw-record.js.map +0 -1
  752. package/dist/runs/retention.d.ts +0 -91
  753. package/dist/runs/retention.js +0 -182
  754. package/dist/runs/retention.js.map +0 -1
  755. package/dist/runs/review-gate.d.ts +0 -18
  756. package/dist/runs/review-gate.js +0 -21
  757. package/dist/runs/review-gate.js.map +0 -1
  758. package/dist/runs/run-claims.d.ts +0 -16
  759. package/dist/runs/run-claims.js +0 -24
  760. package/dist/runs/run-claims.js.map +0 -1
  761. package/dist/runs/run-database-peer-page.d.ts +0 -12
  762. package/dist/runs/run-database-peer-page.js +0 -25
  763. package/dist/runs/run-database-peer-page.js.map +0 -1
  764. package/dist/runs/run-database.d.ts +0 -383
  765. package/dist/runs/run-database.js +0 -1004
  766. package/dist/runs/run-database.js.map +0 -1
  767. package/dist/runs/run-index.d.ts +0 -26
  768. package/dist/runs/run-index.js +0 -212
  769. package/dist/runs/run-index.js.map +0 -1
  770. package/dist/runs/run-row.d.ts +0 -15
  771. package/dist/runs/run-row.js +0 -59
  772. package/dist/runs/run-row.js.map +0 -1
  773. package/dist/runs/run-summary-page.d.ts +0 -36
  774. package/dist/runs/run-summary-page.js +0 -46
  775. package/dist/runs/run-summary-page.js.map +0 -1
  776. package/dist/runs/run-title.d.ts +0 -8
  777. package/dist/runs/run-title.js +0 -28
  778. package/dist/runs/run-title.js.map +0 -1
  779. package/dist/runs/store-open-error.d.ts +0 -24
  780. package/dist/runs/store-open-error.js +0 -61
  781. package/dist/runs/store-open-error.js.map +0 -1
  782. package/dist/runs/store.d.ts +0 -3263
  783. package/dist/runs/store.js +0 -4647
  784. package/dist/runs/store.js.map +0 -1
  785. package/dist/runs/task-markers.d.ts +0 -29
  786. package/dist/runs/task-markers.js +0 -78
  787. package/dist/runs/task-markers.js.map +0 -1
  788. package/dist/runs/task-refs.d.ts +0 -39
  789. package/dist/runs/task-refs.js +0 -107
  790. package/dist/runs/task-refs.js.map +0 -1
  791. package/dist/runs/transcript-facts-fold.d.ts +0 -64
  792. package/dist/runs/transcript-facts-fold.js +0 -109
  793. package/dist/runs/transcript-facts-fold.js.map +0 -1
  794. package/dist/runs/transcript-facts-load.d.ts +0 -11
  795. package/dist/runs/transcript-facts-load.js +0 -66
  796. package/dist/runs/transcript-facts-load.js.map +0 -1
  797. package/dist/runs/transcript-facts-queue.d.ts +0 -30
  798. package/dist/runs/transcript-facts-queue.js +0 -227
  799. package/dist/runs/transcript-facts-queue.js.map +0 -1
  800. package/dist/runs/transcript-facts-worker.d.ts +0 -15
  801. package/dist/runs/transcript-facts-worker.js +0 -26
  802. package/dist/runs/transcript-facts-worker.js.map +0 -1
  803. package/dist/runs/transcript-facts.d.ts +0 -39
  804. package/dist/runs/transcript-facts.js +0 -186
  805. package/dist/runs/transcript-facts.js.map +0 -1
  806. package/dist/runs/ui-event-sink.d.ts +0 -56
  807. package/dist/runs/ui-event-sink.js +0 -188
  808. package/dist/runs/ui-event-sink.js.map +0 -1
  809. package/dist/runs/webhook.d.ts +0 -191
  810. package/dist/runs/webhook.js +0 -360
  811. package/dist/runs/webhook.js.map +0 -1
  812. package/dist/runs/worker-deletion-proof.d.ts +0 -13
  813. package/dist/runs/worker-deletion-proof.js +0 -13
  814. package/dist/runs/worker-deletion-proof.js.map +0 -1
  815. package/dist/runs/worker-execution.d.ts +0 -22
  816. package/dist/runs/worker-execution.js +0 -30
  817. package/dist/runs/worker-execution.js.map +0 -1
  818. package/dist/serve-boot.d.ts +0 -27
  819. package/dist/serve-boot.js +0 -85
  820. package/dist/serve-boot.js.map +0 -1
  821. package/dist/server/app-type.js.map +0 -1
  822. package/dist/server/archive-on-merge.d.ts +0 -35
  823. package/dist/server/archive-on-merge.js +0 -202
  824. package/dist/server/archive-on-merge.js.map +0 -1
  825. package/dist/server/capabilities.d.ts +0 -59
  826. package/dist/server/capabilities.js +0 -141
  827. package/dist/server/capabilities.js.map +0 -1
  828. package/dist/server/checkout-progress.d.ts +0 -10
  829. package/dist/server/checkout-progress.js +0 -27
  830. package/dist/server/checkout-progress.js.map +0 -1
  831. package/dist/server/checkout.d.ts +0 -129
  832. package/dist/server/checkout.js +0 -304
  833. package/dist/server/checkout.js.map +0 -1
  834. package/dist/server/cockpit-ownership.d.ts +0 -31
  835. package/dist/server/cockpit-ownership.js +0 -191
  836. package/dist/server/cockpit-ownership.js.map +0 -1
  837. package/dist/server/cold-repo-handles.d.ts +0 -14
  838. package/dist/server/cold-repo-handles.js +0 -78
  839. package/dist/server/cold-repo-handles.js.map +0 -1
  840. package/dist/server/completion-actions.d.ts +0 -30
  841. package/dist/server/completion-actions.js +0 -204
  842. package/dist/server/completion-actions.js.map +0 -1
  843. package/dist/server/create-project.d.ts +0 -71
  844. package/dist/server/create-project.js +0 -448
  845. package/dist/server/create-project.js.map +0 -1
  846. package/dist/server/forge/github-filters.d.ts +0 -22
  847. package/dist/server/forge/github-filters.js +0 -127
  848. package/dist/server/forge/github-filters.js.map +0 -1
  849. package/dist/server/forge/github-merge-requirements.d.ts +0 -18
  850. package/dist/server/forge/github-merge-requirements.js +0 -137
  851. package/dist/server/forge/github-merge-requirements.js.map +0 -1
  852. package/dist/server/forge/github.d.ts +0 -535
  853. package/dist/server/forge/github.js +0 -3200
  854. package/dist/server/forge/github.js.map +0 -1
  855. package/dist/server/forge/index.d.ts +0 -40
  856. package/dist/server/forge/index.js +0 -72
  857. package/dist/server/forge/index.js.map +0 -1
  858. package/dist/server/forge/types.d.ts +0 -244
  859. package/dist/server/forge/types.js +0 -2
  860. package/dist/server/forge/types.js.map +0 -1
  861. package/dist/server/fs-browse.d.ts +0 -80
  862. package/dist/server/fs-browse.js +0 -182
  863. package/dist/server/fs-browse.js.map +0 -1
  864. package/dist/server/git-changes.d.ts +0 -203
  865. package/dist/server/git-changes.js +0 -508
  866. package/dist/server/git-changes.js.map +0 -1
  867. package/dist/server/git.d.ts +0 -52
  868. package/dist/server/git.js +0 -170
  869. package/dist/server/git.js.map +0 -1
  870. package/dist/server/github.d.ts +0 -9
  871. package/dist/server/github.js +0 -8
  872. package/dist/server/github.js.map +0 -1
  873. package/dist/server/launch-key.d.ts +0 -5
  874. package/dist/server/launch-key.js +0 -31
  875. package/dist/server/launch-key.js.map +0 -1
  876. package/dist/server/live-routes.d.ts +0 -68
  877. package/dist/server/live-routes.js +0 -147
  878. package/dist/server/live-routes.js.map +0 -1
  879. package/dist/server/open-in-app.d.ts +0 -57
  880. package/dist/server/open-in-app.js +0 -177
  881. package/dist/server/open-in-app.js.map +0 -1
  882. package/dist/server/open-in-targets.d.ts +0 -42
  883. package/dist/server/open-in-targets.js +0 -110
  884. package/dist/server/open-in-targets.js.map +0 -1
  885. package/dist/server/open-in-terminal.d.ts +0 -73
  886. package/dist/server/open-in-terminal.js +0 -159
  887. package/dist/server/open-in-terminal.js.map +0 -1
  888. package/dist/server/pr.d.ts +0 -7
  889. package/dist/server/pr.js +0 -7
  890. package/dist/server/pr.js.map +0 -1
  891. package/dist/server/preview-cdp-socket.d.ts +0 -21
  892. package/dist/server/preview-cdp-socket.js +0 -112
  893. package/dist/server/preview-cdp-socket.js.map +0 -1
  894. package/dist/server/preview-socket.d.ts +0 -36
  895. package/dist/server/preview-socket.js +0 -126
  896. package/dist/server/preview-socket.js.map +0 -1
  897. package/dist/server/preview-sockets.d.ts +0 -14
  898. package/dist/server/preview-sockets.js +0 -18
  899. package/dist/server/preview-sockets.js.map +0 -1
  900. package/dist/server/project-context.d.ts +0 -192
  901. package/dist/server/project-context.js +0 -452
  902. package/dist/server/project-context.js.map +0 -1
  903. package/dist/server/provider-action-gate.d.ts +0 -5
  904. package/dist/server/provider-action-gate.js +0 -27
  905. package/dist/server/provider-action-gate.js.map +0 -1
  906. package/dist/server/provider-auth-runtime.d.ts +0 -32
  907. package/dist/server/provider-auth-runtime.js +0 -116
  908. package/dist/server/provider-auth-runtime.js.map +0 -1
  909. package/dist/server/repo-branch-forge.d.ts +0 -59
  910. package/dist/server/repo-branch-forge.js +0 -157
  911. package/dist/server/repo-branch-forge.js.map +0 -1
  912. package/dist/server/repo-branch-sweep.d.ts +0 -21
  913. package/dist/server/repo-branch-sweep.js +0 -64
  914. package/dist/server/repo-branch-sweep.js.map +0 -1
  915. package/dist/server/repo-branches.d.ts +0 -101
  916. package/dist/server/repo-branches.js +0 -803
  917. package/dist/server/repo-branches.js.map +0 -1
  918. package/dist/server/repo-pull.d.ts +0 -18
  919. package/dist/server/repo-pull.js +0 -96
  920. package/dist/server/repo-pull.js.map +0 -1
  921. package/dist/server/run-event-feed.d.ts +0 -20
  922. package/dist/server/run-event-feed.js +0 -190
  923. package/dist/server/run-event-feed.js.map +0 -1
  924. package/dist/server/server-deps.d.ts +0 -37
  925. package/dist/server/server-deps.js +0 -114
  926. package/dist/server/server-deps.js.map +0 -1
  927. package/dist/server/server.d.ts +0 -29583
  928. package/dist/server/server.js +0 -5456
  929. package/dist/server/server.js.map +0 -1
  930. package/dist/server/start-run-options.d.ts +0 -83
  931. package/dist/server/start-run-options.js +0 -111
  932. package/dist/server/start-run-options.js.map +0 -1
  933. package/dist/server/static-ui.d.ts +0 -49
  934. package/dist/server/static-ui.js +0 -98
  935. package/dist/server/static-ui.js.map +0 -1
  936. package/dist/server/upgrade-router.d.ts +0 -23
  937. package/dist/server/upgrade-router.js +0 -53
  938. package/dist/server/upgrade-router.js.map +0 -1
  939. package/dist/server/validators.d.ts +0 -80
  940. package/dist/server/validators.js +0 -85
  941. package/dist/server/validators.js.map +0 -1
  942. package/dist/server/ws.d.ts +0 -65
  943. package/dist/server/ws.js +0 -200
  944. package/dist/server/ws.js.map +0 -1
  945. package/dist/server/wsl.d.ts +0 -25
  946. package/dist/server/wsl.js +0 -92
  947. package/dist/server/wsl.js.map +0 -1
  948. package/dist/server-install/engine.d.ts +0 -47
  949. package/dist/server-install/engine.js +0 -317
  950. package/dist/server-install/engine.js.map +0 -1
  951. package/dist/server-install/npx-cache.d.ts +0 -36
  952. package/dist/server-install/npx-cache.js +0 -104
  953. package/dist/server-install/npx-cache.js.map +0 -1
  954. package/dist/server-install/platforms/macosx-ngrok.d.ts +0 -6
  955. package/dist/server-install/platforms/macosx-ngrok.js +0 -371
  956. package/dist/server-install/platforms/macosx-ngrok.js.map +0 -1
  957. package/dist/server-install/platforms/ubuntu-vps.d.ts +0 -54
  958. package/dist/server-install/platforms/ubuntu-vps.js +0 -1066
  959. package/dist/server-install/platforms/ubuntu-vps.js.map +0 -1
  960. package/dist/server-install/state.d.ts +0 -50
  961. package/dist/server-install/state.js +0 -180
  962. package/dist/server-install/state.js.map +0 -1
  963. package/dist/server-install/steps.d.ts +0 -108
  964. package/dist/server-install/steps.js +0 -332
  965. package/dist/server-install/steps.js.map +0 -1
  966. package/dist/server-install/strategies.d.ts +0 -4
  967. package/dist/server-install/strategies.js +0 -20
  968. package/dist/server-install/strategies.js.map +0 -1
  969. package/dist/server-install/types.d.ts +0 -284
  970. package/dist/server-install/types.js +0 -118
  971. package/dist/server-install/types.js.map +0 -1
  972. package/dist/server-install/ui.d.ts +0 -36
  973. package/dist/server-install/ui.js +0 -130
  974. package/dist/server-install/ui.js.map +0 -1
  975. package/dist/session-context.d.ts +0 -64
  976. package/dist/session-context.js +0 -264
  977. package/dist/session-context.js.map +0 -1
  978. package/dist/skills-provision.d.ts +0 -62
  979. package/dist/skills-provision.js +0 -325
  980. package/dist/skills-provision.js.map +0 -1
  981. package/dist/skills-remote.d.ts +0 -129
  982. package/dist/skills-remote.js +0 -782
  983. package/dist/skills-remote.js.map +0 -1
  984. package/dist/skills.d.ts +0 -71
  985. package/dist/skills.js +0 -249
  986. package/dist/skills.js.map +0 -1
  987. package/dist/subcommands.d.ts +0 -11
  988. package/dist/subcommands.js +0 -25
  989. package/dist/subcommands.js.map +0 -1
  990. package/dist/task-cli/cli.d.ts +0 -39
  991. package/dist/task-cli/cli.js +0 -721
  992. package/dist/task-cli/cli.js.map +0 -1
  993. package/dist/task-cli/discovery.d.ts +0 -25
  994. package/dist/task-cli/discovery.js +0 -98
  995. package/dist/task-cli/discovery.js.map +0 -1
  996. package/dist/task-cli/hint.d.ts +0 -20
  997. package/dist/task-cli/hint.js +0 -14
  998. package/dist/task-cli/hint.js.map +0 -1
  999. package/dist/task-cli/http.d.ts +0 -49
  1000. package/dist/task-cli/http.js +0 -109
  1001. package/dist/task-cli/http.js.map +0 -1
  1002. package/dist/task-cli/projections.d.ts +0 -68
  1003. package/dist/task-cli/projections.js +0 -76
  1004. package/dist/task-cli/projections.js.map +0 -1
  1005. package/dist/task-cli/watch.d.ts +0 -119
  1006. package/dist/task-cli/watch.js +0 -475
  1007. package/dist/task-cli/watch.js.map +0 -1
  1008. package/dist/ui-state.d.ts +0 -41
  1009. package/dist/ui-state.js +0 -90
  1010. package/dist/ui-state.js.map +0 -1
  1011. package/dist/update-check.d.ts +0 -2
  1012. package/dist/update-check.js +0 -26
  1013. package/dist/update-check.js.map +0 -1
  1014. package/dist/voice/decide.d.ts +0 -32
  1015. package/dist/voice/decide.js +0 -297
  1016. package/dist/voice/decide.js.map +0 -1
  1017. package/dist/voice/decision-log.d.ts +0 -52
  1018. package/dist/voice/decision-log.js +0 -107
  1019. package/dist/voice/decision-log.js.map +0 -1
  1020. package/dist/voice/engine.d.ts +0 -119
  1021. package/dist/voice/engine.js +0 -60
  1022. package/dist/voice/engine.js.map +0 -1
  1023. package/dist/voice/fake-engine.d.ts +0 -10
  1024. package/dist/voice/fake-engine.js +0 -192
  1025. package/dist/voice/fake-engine.js.map +0 -1
  1026. package/dist/voice/jev-engine.d.ts +0 -17
  1027. package/dist/voice/jev-engine.js +0 -110
  1028. package/dist/voice/jev-engine.js.map +0 -1
  1029. package/dist/voice/pending-ask.d.ts +0 -17
  1030. package/dist/voice/pending-ask.js +0 -50
  1031. package/dist/voice/pending-ask.js.map +0 -1
  1032. package/dist/voice/routes.d.ts +0 -115
  1033. package/dist/voice/routes.js +0 -91
  1034. package/dist/voice/routes.js.map +0 -1
  1035. package/dist/voice/sentence.d.ts +0 -21
  1036. package/dist/voice/sentence.js +0 -61
  1037. package/dist/voice/sentence.js.map +0 -1
  1038. package/dist/voice/thresholds.d.ts +0 -28
  1039. package/dist/voice/thresholds.js +0 -29
  1040. package/dist/voice/thresholds.js.map +0 -1
  1041. package/dist/webhooks/cli.d.ts +0 -18
  1042. package/dist/webhooks/cli.js +0 -145
  1043. package/dist/webhooks/cli.js.map +0 -1
  1044. package/dist/webhooks/prompt.d.ts +0 -5
  1045. package/dist/webhooks/prompt.js +0 -26
  1046. package/dist/webhooks/prompt.js.map +0 -1
  1047. package/dist/workflows/active-run.d.ts +0 -170
  1048. package/dist/workflows/active-run.js +0 -21
  1049. package/dist/workflows/active-run.js.map +0 -1
  1050. package/dist/workflows/attachment-path.d.ts +0 -6
  1051. package/dist/workflows/attachment-path.js +0 -40
  1052. package/dist/workflows/attachment-path.js.map +0 -1
  1053. package/dist/workflows/completion-policy.d.ts +0 -98
  1054. package/dist/workflows/completion-policy.js +0 -87
  1055. package/dist/workflows/completion-policy.js.map +0 -1
  1056. package/dist/workflows/continuation-admission.d.ts +0 -965
  1057. package/dist/workflows/continuation-admission.js +0 -265
  1058. package/dist/workflows/continuation-admission.js.map +0 -1
  1059. package/dist/workflows/execution-account.d.ts +0 -13
  1060. package/dist/workflows/execution-account.js +0 -18
  1061. package/dist/workflows/execution-account.js.map +0 -1
  1062. package/dist/workflows/grouped-command.d.ts +0 -31
  1063. package/dist/workflows/grouped-command.js +0 -143
  1064. package/dist/workflows/grouped-command.js.map +0 -1
  1065. package/dist/workflows/input-acknowledgement.d.ts +0 -203
  1066. package/dist/workflows/input-acknowledgement.js +0 -41
  1067. package/dist/workflows/input-acknowledgement.js.map +0 -1
  1068. package/dist/workflows/line-order.d.ts +0 -5
  1069. package/dist/workflows/line-order.js +0 -25
  1070. package/dist/workflows/line-order.js.map +0 -1
  1071. package/dist/workflows/load.d.ts +0 -17
  1072. package/dist/workflows/load.js +0 -61
  1073. package/dist/workflows/load.js.map +0 -1
  1074. package/dist/workflows/outcome-batches.d.ts +0 -32
  1075. package/dist/workflows/outcome-batches.js +0 -55
  1076. package/dist/workflows/outcome-batches.js.map +0 -1
  1077. package/dist/workflows/pasted-content.d.ts +0 -60
  1078. package/dist/workflows/pasted-content.js +0 -69
  1079. package/dist/workflows/pasted-content.js.map +0 -1
  1080. package/dist/workflows/question-routing.d.ts +0 -8
  1081. package/dist/workflows/question-routing.js +0 -20
  1082. package/dist/workflows/question-routing.js.map +0 -1
  1083. package/dist/workflows/run/attachment-writer.d.ts +0 -34
  1084. package/dist/workflows/run/attachment-writer.js +0 -98
  1085. package/dist/workflows/run/attachment-writer.js.map +0 -1
  1086. package/dist/workflows/run/auto-resume.d.ts +0 -91
  1087. package/dist/workflows/run/auto-resume.js +0 -248
  1088. package/dist/workflows/run/auto-resume.js.map +0 -1
  1089. package/dist/workflows/run/cezar-tools.d.ts +0 -45
  1090. package/dist/workflows/run/cezar-tools.js +0 -129
  1091. package/dist/workflows/run/cezar-tools.js.map +0 -1
  1092. package/dist/workflows/run/completion-gate.d.ts +0 -77
  1093. package/dist/workflows/run/completion-gate.js +0 -90
  1094. package/dist/workflows/run/completion-gate.js.map +0 -1
  1095. package/dist/workflows/run/compose.d.ts +0 -174
  1096. package/dist/workflows/run/compose.js +0 -391
  1097. package/dist/workflows/run/compose.js.map +0 -1
  1098. package/dist/workflows/run/constants.d.ts +0 -48
  1099. package/dist/workflows/run/constants.js +0 -49
  1100. package/dist/workflows/run/constants.js.map +0 -1
  1101. package/dist/workflows/run/continuation-acceptance.d.ts +0 -70
  1102. package/dist/workflows/run/continuation-acceptance.js +0 -198
  1103. package/dist/workflows/run/continuation-acceptance.js.map +0 -1
  1104. package/dist/workflows/run/continuation-session.d.ts +0 -128
  1105. package/dist/workflows/run/continuation-session.js +0 -581
  1106. package/dist/workflows/run/continuation-session.js.map +0 -1
  1107. package/dist/workflows/run/drop-active.d.ts +0 -4
  1108. package/dist/workflows/run/drop-active.js +0 -11
  1109. package/dist/workflows/run/drop-active.js.map +0 -1
  1110. package/dist/workflows/run/family-reconciler.d.ts +0 -74
  1111. package/dist/workflows/run/family-reconciler.js +0 -310
  1112. package/dist/workflows/run/family-reconciler.js.map +0 -1
  1113. package/dist/workflows/run/human-waits.d.ts +0 -91
  1114. package/dist/workflows/run/human-waits.js +0 -192
  1115. package/dist/workflows/run/human-waits.js.map +0 -1
  1116. package/dist/workflows/run/inbox-claims.d.ts +0 -38
  1117. package/dist/workflows/run/inbox-claims.js +0 -107
  1118. package/dist/workflows/run/inbox-claims.js.map +0 -1
  1119. package/dist/workflows/run/input-batch.d.ts +0 -15
  1120. package/dist/workflows/run/input-batch.js +0 -31
  1121. package/dist/workflows/run/input-batch.js.map +0 -1
  1122. package/dist/workflows/run/input-delivery.d.ts +0 -122
  1123. package/dist/workflows/run/input-delivery.js +0 -661
  1124. package/dist/workflows/run/input-delivery.js.map +0 -1
  1125. package/dist/workflows/run/input-receipts.d.ts +0 -65
  1126. package/dist/workflows/run/input-receipts.js +0 -222
  1127. package/dist/workflows/run/input-receipts.js.map +0 -1
  1128. package/dist/workflows/run/input-timers.d.ts +0 -10
  1129. package/dist/workflows/run/input-timers.js +0 -42
  1130. package/dist/workflows/run/input-timers.js.map +0 -1
  1131. package/dist/workflows/run/launch-context.d.ts +0 -64
  1132. package/dist/workflows/run/launch-context.js +0 -145
  1133. package/dist/workflows/run/launch-context.js.map +0 -1
  1134. package/dist/workflows/run/launch-settings.d.ts +0 -49
  1135. package/dist/workflows/run/launch-settings.js +0 -125
  1136. package/dist/workflows/run/launch-settings.js.map +0 -1
  1137. package/dist/workflows/run/maintenance-claims.d.ts +0 -47
  1138. package/dist/workflows/run/maintenance-claims.js +0 -83
  1139. package/dist/workflows/run/maintenance-claims.js.map +0 -1
  1140. package/dist/workflows/run/memory-guard.d.ts +0 -25
  1141. package/dist/workflows/run/memory-guard.js +0 -63
  1142. package/dist/workflows/run/memory-guard.js.map +0 -1
  1143. package/dist/workflows/run/opening.d.ts +0 -41
  1144. package/dist/workflows/run/opening.js +0 -92
  1145. package/dist/workflows/run/opening.js.map +0 -1
  1146. package/dist/workflows/run/pending-ask-facts.d.ts +0 -10
  1147. package/dist/workflows/run/pending-ask-facts.js +0 -19
  1148. package/dist/workflows/run/pending-ask-facts.js.map +0 -1
  1149. package/dist/workflows/run/prompts.d.ts +0 -74
  1150. package/dist/workflows/run/prompts.js +0 -140
  1151. package/dist/workflows/run/prompts.js.map +0 -1
  1152. package/dist/workflows/run/queued-input.d.ts +0 -108
  1153. package/dist/workflows/run/queued-input.js +0 -321
  1154. package/dist/workflows/run/queued-input.js.map +0 -1
  1155. package/dist/workflows/run/queued-revival.d.ts +0 -44
  1156. package/dist/workflows/run/queued-revival.js +0 -157
  1157. package/dist/workflows/run/queued-revival.js.map +0 -1
  1158. package/dist/workflows/run/repo-root-lease.d.ts +0 -34
  1159. package/dist/workflows/run/repo-root-lease.js +0 -70
  1160. package/dist/workflows/run/repo-root-lease.js.map +0 -1
  1161. package/dist/workflows/run/resolved-wait-input-batch.d.ts +0 -7
  1162. package/dist/workflows/run/resolved-wait-input-batch.js +0 -25
  1163. package/dist/workflows/run/resolved-wait-input-batch.js.map +0 -1
  1164. package/dist/workflows/run/run-cancel.d.ts +0 -36
  1165. package/dist/workflows/run/run-cancel.js +0 -126
  1166. package/dist/workflows/run/run-cancel.js.map +0 -1
  1167. package/dist/workflows/run/run-finish.d.ts +0 -68
  1168. package/dist/workflows/run/run-finish.js +0 -239
  1169. package/dist/workflows/run/run-finish.js.map +0 -1
  1170. package/dist/workflows/run/run-guards.d.ts +0 -14
  1171. package/dist/workflows/run/run-guards.js +0 -34
  1172. package/dist/workflows/run/run-guards.js.map +0 -1
  1173. package/dist/workflows/run/run-line.d.ts +0 -179
  1174. package/dist/workflows/run/run-line.js +0 -429
  1175. package/dist/workflows/run/run-line.js.map +0 -1
  1176. package/dist/workflows/run/run-recovery.d.ts +0 -117
  1177. package/dist/workflows/run/run-recovery.js +0 -442
  1178. package/dist/workflows/run/run-recovery.js.map +0 -1
  1179. package/dist/workflows/run/run-settlement.d.ts +0 -163
  1180. package/dist/workflows/run/run-settlement.js +0 -535
  1181. package/dist/workflows/run/run-settlement.js.map +0 -1
  1182. package/dist/workflows/run/run-skills.d.ts +0 -81
  1183. package/dist/workflows/run/run-skills.js +0 -178
  1184. package/dist/workflows/run/run-skills.js.map +0 -1
  1185. package/dist/workflows/run/run-start.d.ts +0 -64
  1186. package/dist/workflows/run/run-start.js +0 -177
  1187. package/dist/workflows/run/run-start.js.map +0 -1
  1188. package/dist/workflows/run/run-workspace.d.ts +0 -25
  1189. package/dist/workflows/run/run-workspace.js +0 -65
  1190. package/dist/workflows/run/run-workspace.js.map +0 -1
  1191. package/dist/workflows/run/session-events.d.ts +0 -144
  1192. package/dist/workflows/run/session-events.js +0 -262
  1193. package/dist/workflows/run/session-events.js.map +0 -1
  1194. package/dist/workflows/run/step-decisions.d.ts +0 -37
  1195. package/dist/workflows/run/step-decisions.js +0 -42
  1196. package/dist/workflows/run/step-decisions.js.map +0 -1
  1197. package/dist/workflows/run/step-loop.d.ts +0 -140
  1198. package/dist/workflows/run/step-loop.js +0 -490
  1199. package/dist/workflows/run/step-loop.js.map +0 -1
  1200. package/dist/workflows/run/step-session.d.ts +0 -64
  1201. package/dist/workflows/run/step-session.js +0 -280
  1202. package/dist/workflows/run/step-session.js.map +0 -1
  1203. package/dist/workflows/run/steps.d.ts +0 -13
  1204. package/dist/workflows/run/steps.js +0 -14
  1205. package/dist/workflows/run/steps.js.map +0 -1
  1206. package/dist/workflows/run/tracked-work.d.ts +0 -12
  1207. package/dist/workflows/run/tracked-work.js +0 -29
  1208. package/dist/workflows/run/tracked-work.js.map +0 -1
  1209. package/dist/workflows/run/turn-bookkeeping.d.ts +0 -67
  1210. package/dist/workflows/run/turn-bookkeeping.js +0 -174
  1211. package/dist/workflows/run/turn-bookkeeping.js.map +0 -1
  1212. package/dist/workflows/run/turn-markers.d.ts +0 -85
  1213. package/dist/workflows/run/turn-markers.js +0 -262
  1214. package/dist/workflows/run/turn-markers.js.map +0 -1
  1215. package/dist/workflows/run/turn-nudges.d.ts +0 -101
  1216. package/dist/workflows/run/turn-nudges.js +0 -245
  1217. package/dist/workflows/run/turn-nudges.js.map +0 -1
  1218. package/dist/workflows/run/turn-settler.d.ts +0 -166
  1219. package/dist/workflows/run/turn-settler.js +0 -492
  1220. package/dist/workflows/run/turn-settler.js.map +0 -1
  1221. package/dist/workflows/run/types.d.ts +0 -280
  1222. package/dist/workflows/run/types.js +0 -2
  1223. package/dist/workflows/run/types.js.map +0 -1
  1224. package/dist/workflows/run/usage-accounting.d.ts +0 -28
  1225. package/dist/workflows/run/usage-accounting.js +0 -158
  1226. package/dist/workflows/run/usage-accounting.js.map +0 -1
  1227. package/dist/workflows/run/wait-registry.d.ts +0 -132
  1228. package/dist/workflows/run/wait-registry.js +0 -405
  1229. package/dist/workflows/run/wait-registry.js.map +0 -1
  1230. package/dist/workflows/run/wait-watches.d.ts +0 -855
  1231. package/dist/workflows/run/wait-watches.js +0 -221
  1232. package/dist/workflows/run/wait-watches.js.map +0 -1
  1233. package/dist/workflows/run/wake-admission.d.ts +0 -160
  1234. package/dist/workflows/run/wake-admission.js +0 -404
  1235. package/dist/workflows/run/wake-admission.js.map +0 -1
  1236. package/dist/workflows/run/wake-ledger.d.ts +0 -61
  1237. package/dist/workflows/run/wake-ledger.js +0 -77
  1238. package/dist/workflows/run/wake-ledger.js.map +0 -1
  1239. package/dist/workflows/run/wake-retries.d.ts +0 -31
  1240. package/dist/workflows/run/wake-retries.js +0 -93
  1241. package/dist/workflows/run/wake-retries.js.map +0 -1
  1242. package/dist/workflows/run/worker-executions.d.ts +0 -54
  1243. package/dist/workflows/run/worker-executions.js +0 -149
  1244. package/dist/workflows/run/worker-executions.js.map +0 -1
  1245. package/dist/workflows/run/worker-orphans.d.ts +0 -91
  1246. package/dist/workflows/run/worker-orphans.js +0 -275
  1247. package/dist/workflows/run/worker-orphans.js.map +0 -1
  1248. package/dist/workflows/run/worker-questions.d.ts +0 -122
  1249. package/dist/workflows/run/worker-questions.js +0 -309
  1250. package/dist/workflows/run/worker-questions.js.map +0 -1
  1251. package/dist/workflows/run/workflow-position.d.ts +0 -18
  1252. package/dist/workflows/run/workflow-position.js +0 -88
  1253. package/dist/workflows/run/workflow-position.js.map +0 -1
  1254. package/dist/workflows/run/worktree-autosave.d.ts +0 -39
  1255. package/dist/workflows/run/worktree-autosave.js +0 -156
  1256. package/dist/workflows/run/worktree-autosave.js.map +0 -1
  1257. package/dist/workflows/run-scheduling.d.ts +0 -40
  1258. package/dist/workflows/run-scheduling.js +0 -84
  1259. package/dist/workflows/run-scheduling.js.map +0 -1
  1260. package/dist/workflows/run-states.d.ts +0 -191
  1261. package/dist/workflows/run-states.js +0 -318
  1262. package/dist/workflows/run-states.js.map +0 -1
  1263. package/dist/workflows/run.d.ts +0 -334
  1264. package/dist/workflows/run.js +0 -603
  1265. package/dist/workflows/run.js.map +0 -1
  1266. package/dist/workflows/turn-end.d.ts +0 -126
  1267. package/dist/workflows/turn-end.js +0 -78
  1268. package/dist/workflows/turn-end.js.map +0 -1
  1269. package/dist/workflows/types.d.ts +0 -83
  1270. package/dist/workflows/types.js +0 -192
  1271. package/dist/workflows/types.js.map +0 -1
  1272. package/dist/workflows/wait-scope.d.ts +0 -80
  1273. package/dist/workflows/wait-scope.js +0 -110
  1274. package/dist/workflows/wait-scope.js.map +0 -1
  1275. package/dist/workflows/waits.d.ts +0 -188
  1276. package/dist/workflows/waits.js +0 -287
  1277. package/dist/workflows/waits.js.map +0 -1
  1278. package/dist/workspace/agent-accounts.d.ts +0 -128
  1279. package/dist/workspace/agent-accounts.js +0 -280
  1280. package/dist/workspace/agent-accounts.js.map +0 -1
  1281. package/dist/workspace/agent-profiles.d.ts +0 -124
  1282. package/dist/workspace/agent-profiles.js +0 -190
  1283. package/dist/workspace/agent-profiles.js.map +0 -1
  1284. package/dist/workspace/config.d.ts +0 -181
  1285. package/dist/workspace/config.js +0 -389
  1286. package/dist/workspace/config.js.map +0 -1
  1287. package/dist/workspace/migrations.d.ts +0 -35
  1288. package/dist/workspace/migrations.js +0 -147
  1289. package/dist/workspace/migrations.js.map +0 -1
  1290. package/dist/workspace/projects-cli.d.ts +0 -25
  1291. package/dist/workspace/projects-cli.js +0 -172
  1292. package/dist/workspace/projects-cli.js.map +0 -1
  1293. package/dist/workspace/projects.d.ts +0 -129
  1294. package/dist/workspace/projects.js +0 -267
  1295. package/dist/workspace/projects.js.map +0 -1
  1296. package/dist/workspace/semaphore.d.ts +0 -145
  1297. package/dist/workspace/semaphore.js +0 -196
  1298. package/dist/workspace/semaphore.js.map +0 -1
  1299. package/dist/workspace/ui-state.d.ts +0 -36
  1300. package/dist/workspace/ui-state.js +0 -55
  1301. package/dist/workspace/ui-state.js.map +0 -1
  1302. package/dist/workspace/webhooks.d.ts +0 -40
  1303. package/dist/workspace/webhooks.js +0 -146
  1304. package/dist/workspace/webhooks.js.map +0 -1
  1305. package/dist/worktree-manifest.d.ts +0 -165
  1306. package/dist/worktree-manifest.js +0 -530
  1307. package/dist/worktree-manifest.js.map +0 -1
  1308. package/dist/worktree-setup.d.ts +0 -85
  1309. package/dist/worktree-setup.js +0 -164
  1310. package/dist/worktree-setup.js.map +0 -1
  1311. package/scripts/benchmark-run-store-fixture.ts +0 -432
  1312. package/scripts/benchmark-run-store.ts +0 -743
  1313. package/scripts/benchmark-stuck-destroys.ts +0 -143
  1314. package/scripts/check-pack.mjs +0 -48
  1315. package/scripts/inline-contract.mjs +0 -165
  1316. package/scripts/install-as-command.mjs +0 -122
  1317. package/scripts/measure-transcript-facts-health.mjs +0 -87
  1318. package/scripts/measure-transcript-facts-lag.mjs +0 -68
  1319. package/scripts/mock-autonomous.mjs +0 -11
  1320. package/scripts/mock-ci-tool.mjs +0 -111
  1321. package/scripts/mock-claude-model-refusal.mjs +0 -42
  1322. package/scripts/mock-claude.mjs +0 -1065
  1323. package/scripts/mock-codex-app-server.mjs +0 -905
  1324. package/scripts/mock-codex-coalesce-steer.mjs +0 -59
  1325. package/scripts/mock-codex-reverse-steer.mjs +0 -130
  1326. package/scripts/mock-cursor-acp.mjs +0 -423
  1327. package/scripts/mock-cursor-hang-stdin-late.mjs +0 -35
  1328. package/scripts/mock-cursor-hang-stdin.mjs +0 -30
  1329. package/scripts/mock-cursor-print.mjs +0 -256
  1330. package/scripts/mock-deferred-turn-start.mjs +0 -16
  1331. package/scripts/mock-delivery-control.d.mts +0 -23
  1332. package/scripts/mock-delivery-control.mjs +0 -80
  1333. package/scripts/mock-env-record.mjs +0 -11
  1334. package/scripts/mock-failure-control.d.mts +0 -13
  1335. package/scripts/mock-failure-control.mjs +0 -68
  1336. package/scripts/mock-multi-pr.mjs +0 -7
  1337. package/scripts/mock-nudge.mjs +0 -45
  1338. package/scripts/mock-omp-rpc.mjs +0 -779
  1339. package/scripts/mock-opencode-serve.mjs +0 -1230
  1340. package/scripts/mock-pi-rpc.mjs +0 -698
  1341. package/scripts/mock-runner-crash.mjs +0 -58
  1342. package/scripts/mock-session-context.d.mts +0 -5
  1343. package/scripts/mock-session-context.mjs +0 -56
  1344. package/scripts/mock-silent-tail.mjs +0 -85
  1345. package/scripts/mock-turn-messages.mjs +0 -5
  1346. package/scripts/omp-ci-wait.mjs +0 -29
  1347. package/scripts/omp-restrict-delegation.yml +0 -4
  1348. package/scripts/pi-ci-wait.mjs +0 -17
  1349. package/scripts/pi-default-tools.mjs +0 -22
  1350. package/scripts/pi-project-skills.mjs +0 -59
  1351. package/scripts/pi-retry-degraded-service.mjs +0 -16
  1352. package/scripts/probe-cursor-print.mjs +0 -627
  1353. package/scripts/seed-archive-profile.ts +0 -53
  1354. package/scripts/sync-readme.mjs +0 -20
  1355. package/scripts/test-process-usage.mjs +0 -47
  1356. package/scripts/transcript-facts-fixture.mjs +0 -53
  1357. package/scripts/voice-replay.ts +0 -50
  1358. package/scripts/windows-workspace-identity.cs +0 -208
  1359. package/scripts/windows-workspace-identity.ps1 +0 -10
  1360. package/web/dist/assets/alert-dialog-DfctKUMw.js +0 -1
  1361. package/web/dist/assets/button-CeupvoKG.js +0 -41
  1362. package/web/dist/assets/centered-state-DRV994qx.js +0 -1
  1363. package/web/dist/assets/cez-idle-D3aj_9lp.js +0 -1
  1364. package/web/dist/assets/diff-CMvwOEAq2.js +0 -3
  1365. package/web/dist/assets/diff-controls-DOUOXMFa.js +0 -1
  1366. package/web/dist/assets/diff-view-CeyiYVO0.js +0 -11
  1367. package/web/dist/assets/dropdown-menu-o5TscAn1.js +0 -6
  1368. package/web/dist/assets/git-toolbar-BXqnQi8K.js +0 -1
  1369. package/web/dist/assets/github-BK1vJWfx.js +0 -1
  1370. package/web/dist/assets/index-C3hy-aA5.css +0 -1
  1371. package/web/dist/assets/index-CvfFqahx.js +0 -34
  1372. package/web/dist/assets/lib-BQXq3kEf.js +0 -1
  1373. package/web/dist/assets/live-protocol-DhRssvhp.js +0 -64
  1374. package/web/dist/assets/play-CmVAj_fu.js +0 -1
  1375. package/web/dist/assets/popover-BhkASzoh.js +0 -1
  1376. package/web/dist/assets/preview-pane-connected-DYEO_KU8.js +0 -3
  1377. package/web/dist/assets/reference-chip-CwVbHR5t.js +0 -1
  1378. package/web/dist/assets/repo-git-CHmWZuZU.js +0 -1
  1379. package/web/dist/assets/run-header-BaMbZXjb.js +0 -2
  1380. package/web/dist/assets/skill-empty-hint-oOtzR3v0.js +0 -1
  1381. package/web/dist/assets/skills-DviK76JU.js +0 -1
  1382. package/web/dist/assets/status-dot-B_zxTP5h.js +0 -1
  1383. package/web/dist/assets/tab-link-I2OzEyyp.js +0 -1
  1384. package/web/dist/assets/task-changes--tIcV2If.js +0 -1
  1385. package/web/dist/assets/task-commits-BkgYMsVZ.js +0 -1
  1386. package/web/dist/assets/task-files-CfqI5Pd4.js +0 -2
  1387. package/web/dist/assets/task-github-item-CXv13eJx.js +0 -1
  1388. package/web/dist/assets/task-thread-DJfpoqYU.js +0 -9
  1389. package/web/dist/assets/thread-state-C_J5glQD.js +0 -4
  1390. package/web/dist/assets/use-hand-to-agent-state-C-_lVGuC.js +0 -1
  1391. package/web/dist/assets/workflows-9xLAxVoB.js +0 -7
  1392. package/web/dist/assets/zoomable-image-CxQSsfcn.js +0 -1
@@ -1,4647 +0,0 @@
1
- import { workerDeletionProof } from './worker-deletion-proof.js';
2
- import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
3
- export { parseStoredSummary } from './run-summary-page.js';
4
- import { defined } from '../core/defined.js';
5
- import { autosaveCleanupBlocker, clearAutosaveCleanup } from '../autosave-cleanup.js';
6
- import { EventEmitter } from 'node:events';
7
- import { workerEvidenceRunIds, workerExecutionSchema } from './worker-execution.js';
8
- import { agentTmpDirLocations, agentTmpDirMayExist, agentTmpDirOwnershipProven, removeAgentTmpDir } from './agent-tmpdir.js';
9
- import { removeArtifacts } from '../artifacts/lifecycle.js';
10
- import { randomUUID, createHash } from 'node:crypto';
11
- import { isDeepStrictEqual } from 'node:util';
12
- import { appendFileSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readSync, realpathSync, readdirSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
13
- import { join, resolve } from 'node:path';
14
- import { z } from 'zod';
15
- import { ciWaitSchema } from '../contract/index.js';
16
- import { workerWaitSchema } from '../contract/index.js';
17
- import { agentInputSchema, inboxClaimSchema, delegationStateSchema, workerCreationReceiptSchema, workerCollectedResultSchema, workerResultFileSchema, workerDestroyRetrySchema, } from '../contract/index.js';
18
- import { automationIdOf, stepStateSchema as contractStepStateSchema, queuedMessageSchema, toRunSummary, runRecordSchema as contractRunRecordSchema, runPullRequestSchema, mergedPullRequestSchema, } from '../contract/index.js';
19
- import { previewServerSchema } from '../contract/index.js';
20
- import { isUsageLimitHold, waitSchema, LAST_WAITS_LIMIT, TIMER_MAX_SECONDS, TIMER_MIN_SECONDS, WAIT_LIMIT, } from '../contract/index.js';
21
- import { engineOwnsRun, isSweepable } from '../contract/index.js';
22
- import { matchesRunSearch, sqlPrefilterTokens } from '../contract/index.js';
23
- import { storedDelegationStateSchema } from './delegation-state.js';
24
- import { HistoryCompressor } from './history-compressor.js';
25
- import { LiveItemSnapshots } from './live-item-snapshots.js';
26
- import { emptyFacts, stampOf, TranscriptFactsIndex } from './transcript-facts.js';
27
- import { hasPlainHistory, historyPaths, readHistoryText, readHistoryTextAsync, removeHistory, restoreHistory } from './history-file.js';
28
- import { workerExecutionIdentitySchema } from '../delegation/execution-identity.js';
29
- import { capacityError, workerCapacity } from '../delegation/capacity.js';
30
- import { inspectGeneration, isCurrentProcess, recordedProcessLive, processStartToken } from '../delegation/process-liveness.js';
31
- import { collectSecretValues, redactDeep, redactSecrets } from '../core/secret-redaction.js';
32
- // Pure, dependency-free reference helpers — the same sanity bound the marker parser applies.
33
- import { archivePullRequests, pullRequestKey, mergePullRequests } from './pull-requests.js';
34
- import { extractTaskRefs, isRepoScopedRef, MAX_REF, promptNamesRepo, refUrlRepo } from './task-refs.js';
35
- // Type-only module (zod + nothing else), so this cannot cycle back into the store.
36
- import { workflowDefSchema } from '../workflows/types.js';
37
- import { applyOutcomes } from './outcome-commit.js';
38
- import { assertConversationIdFree } from './conversation-identity.js';
39
- export { ConversationIdInUseError } from './conversation-identity.js';
40
- import { RUNNER_IDS } from '../core/agent-runner.js';
41
- import { ARCHIVED_ROOT, RUNS_DB_FILE, RUNS_IMPORT_COMPLETE_KEY, RunConflictError, RunDatabase, RunDatabaseBusyError, } from './run-database.js';
42
- import { restoreLostReferencedPullRequest } from './loaded-run-healing.js';
43
- import { encodeRunRow, isLiveRecord, isLiveStatus } from './run-row.js';
44
- import { collectRawExtras, encodeRawRecord } from './raw-record.js';
45
- import { assertNoLegacyCockpit, assertNoLegacyWriter, backUpLegacyIndex, LEGACY_INDEX_FILE, LegacyWriterError, readLegacyIndex } from './legacy-index.js';
46
- import { toRunStoreOpenError } from './store-open-error.js';
47
- import { claimOwnerLive, closeClaimSession, openClaimSession } from './run-claims.js';
48
- /**
49
- * A runner id as it may appear in a PERSISTED record, normalized to the three
50
- * ids the rest of cezar speaks (#547).
51
- *
52
- * `claude-cli` is the legacy spelling of `claude` — still a member of
53
- * `AgentBackend` and still accepted by `createRunner`, and accepted in `runs.json`. The enum
54
- * here once failed to accept it: the loader `safeParse`s the
55
- * WHOLE array, so one record carrying it would have dropped every run in the
56
- * file.
57
- *
58
- * Parse-and-fold rather than widen: the legacy id is accepted on the way in and
59
- * collapsed to `claude`, so no consumer, wire type or contract schema ever sees
60
- * a fourth runner. The narrowing is one-way and permanent (the index is
61
- * re-serialized from the parsed records), which is what "old run records
62
- * normalise identically to `claude`" in `core/model-identity.ts` has always
63
- * claimed. Use ONLY for read-back of stored state — request bodies, settings and
64
- * workflow step defs stay the three selectable ids (`RunnerId`), because nothing
65
- * should be able to ASK for the legacy spelling.
66
- */
67
- const storedRunnerSchema = z
68
- .enum([...RUNNER_IDS, 'claude-cli'])
69
- .transform((id) => (id === 'claude-cli' ? 'claude' : id));
70
- const stepStateSchema = contractStepStateSchema.extend({ backend: storedRunnerSchema.optional() });
71
- /** Exported for `./run-index.ts`, the read-only reader of the same records. Nothing else should
72
- * parse a stored run — see `reconcileLoadedRun` for why a second parser is a correctness risk. */
73
- export const runRecordSchema = contractRunRecordSchema.extend({
74
- delegation: storedDelegationStateSchema,
75
- lastWaitsError: contractRunRecordSchema.shape.lastWaitsError.catch(undefined),
76
- automaticWakes: contractRunRecordSchema.shape.automaticWakes.catch(undefined),
77
- waitDeliveryFailures: contractRunRecordSchema.shape.waitDeliveryFailures.catch(undefined),
78
- runner: storedRunnerSchema.optional(),
79
- notify: z.boolean().optional().catch(undefined),
80
- webhook: contractRunRecordSchema.shape.webhook.catch(undefined),
81
- destroyRetry: contractRunRecordSchema.shape.destroyRetry.catch(undefined),
82
- stopping: contractRunRecordSchema.shape.stopping.catch(undefined),
83
- hasPendingPermission: contractRunRecordSchema.shape.hasPendingPermission.catch(undefined),
84
- autoResumeAt: z.string().datetime().optional().catch(undefined),
85
- autoResumeAttempts: z.number().int().min(0).optional().catch(undefined),
86
- pullRequests: z.preprocess((value) => Array.isArray(value)
87
- ? value.flatMap((entry) => {
88
- const parsed = runPullRequestSchema.safeParse(entry);
89
- return parsed.success ? [parsed.data] : [];
90
- })
91
- : undefined, z.array(runPullRequestSchema).optional()),
92
- worktreeSetup: contractRunRecordSchema.shape.worktreeSetup.catch(undefined),
93
- archived: z.boolean().default(false),
94
- workflowDef: workflowDefSchema.optional().catch(undefined),
95
- steps: z.array(stepStateSchema),
96
- automation: contractRunRecordSchema.shape.automation.unwrap().extend({
97
- automationRevision: z.number().int().positive(),
98
- githubUrl: z.string().url(),
99
- }).optional(),
100
- automationTrigger: contractRunRecordSchema.shape.automationTrigger.unwrap().extend({
101
- automationRevision: z.number().int().positive(),
102
- }).optional(),
103
- /** The handoff file's autosave records (hearsay-tools/cezarion#1809); unreadable drops the field. */
104
- handoffRecords: contractRunRecordSchema.shape.handoffRecords.catch(undefined),
105
- });
106
- /** The keys an older record used for parks. Schema 4 reads the CI and monitoring ones into
107
- * `waits`; phase 4b (hearsay-tools/cezarion#1236) reads the pending-question summary into a human
108
- * wait. None is written again (spec 2026-10-17-unified-waits, § Compatibility). */
109
- const LEGACY_WAIT_KEYS = ['ciWait', 'lastCiWait', 'lastCiWaitError', 'monitoringWakeAt', 'monitoringWakeCapReached', 'activity', 'hasPendingHumanAsk'];
110
- const UNREADABLE_WAIT = 'Wait unavailable — a saved wait is unreadable; register a new wait.';
111
- /** A stored `waits`/`lastWaits` entry of kind `ci`, the kind `pr` replaced (hearsay-tools/cezarion#1425). */
112
- const isCiKindEntry = (entry) => !!entry && typeof entry === 'object' && entry.kind === 'ci';
113
- function hasCiKindEntries(row) {
114
- return ['waits', 'lastWaits'].some((key) => Array.isArray(row[key]) && row[key].some(isCiKindEntry));
115
- }
116
- function hasLegacyWaitFields(row) {
117
- return !!row && typeof row === 'object' && (LEGACY_WAIT_KEYS.some((key) => key in row) || hasCiKindEntries(row) || agentWorkerWaits(row).length > 0 || rootCompletion(row) !== undefined);
118
- }
119
- /** A root's stored `delegation.completion` (the old completion gate's marker), which schema 7 reads
120
- * into the list and drops (hearsay-tools/cezarion#1301). */
121
- function rootCompletion(row) {
122
- const delegation = row.delegation;
123
- if (!delegation || typeof delegation !== 'object' || delegation.role !== 'root')
124
- return undefined;
125
- const { completion } = delegation;
126
- return completion && typeof completion === 'object' ? completion : undefined;
127
- }
128
- /** The worker waits a record still holds in `delegation` (store schemas 6 and 7,
129
- * hearsay-tools/cezarion#1235, #1301), in the order they settled: `lastWait`, then `wait`. The
130
- * completion gate's wait, the one `delegation.completion.waitId` names, is flagged `completion`: it
131
- * was Cezar's own, not the agent's. A value that does not parse is left where it is, for the
132
- * delegation schema to quarantine as it always has. */
133
- function agentWorkerWaits(row) {
134
- const delegation = row.delegation;
135
- if (!delegation || typeof delegation !== 'object')
136
- return [];
137
- const { role } = delegation;
138
- if (role !== 'root' && role !== 'worker')
139
- return [];
140
- const waitId = rootCompletion(row)?.waitId;
141
- const found = [];
142
- for (const key of ['lastWait', 'wait']) {
143
- const parsed = workerWaitSchema.safeParse(delegation[key]);
144
- if (parsed.success)
145
- found.push({ key, wait: parsed.data, completion: waitId === parsed.data.id });
146
- }
147
- return found;
148
- }
149
- /** A legacy `CiWait` as a wait entry. Its wake input's id was the wait's own (`wakeId`, which
150
- * `run.ts` set to the wait id), so the entry keeps that id and delivery still finds the input. */
151
- export function ciWaitEntry(wait) {
152
- const { wakeId: _wakeId, phase, result, deliveredAt, ...identity } = wait;
153
- return {
154
- ...identity, kind: 'pr', source: 'agent', via: 'cezar_wait_for_ci',
155
- phase: phase === 'registered' || phase === 'parked' ? 'open' : phase === 'wake-pending' ? 'resolved' : phase === 'delivered' ? 'delivered' : 'cancelled',
156
- ...(result ? { result, resolvedAt: result.observedAt } : {}),
157
- ...(deliveredAt ? { deliveredAt } : {}),
158
- };
159
- }
160
- /**
161
- * A legacy agent `delegation.wait` as a worker wait entry (store schema 6, hearsay-tools/cezarion#1235),
162
- * judged from the wait alone: what became of its wake input is `upgradeLegacyWaits`' to apply.
163
- * `registered`/`parked` → open; `wake-pending` → resolved with its `outcome`/`timeout` reason, or
164
- * cancelled. Undefined for the `message` stand-in, which was never an agent's wait: a message no
165
- * longer resolves a wait, and its input still wakes the run on its own.
166
- *
167
- * Deterministic, never read from the clock: a row is upgraded on every read until open rewrites
168
- * it, and two reads must agree. A `WorkerWait` kept no registration time, so `timeoutSeconds` is
169
- * the 600 default, `registeredAt` is 600 s before the original deadline (kept as it was), and the
170
- * settled stamps come from the wait itself: `resolvedAt` is the latest observation it holds, else
171
- * its deadline, and `cancelledAt` is its deadline. `now` is only the fallback for a deadline that
172
- * does not read, which the wait schema never admits.
173
- */
174
- export function workerWaitEntry(wait, now) {
175
- if (wait.phase === 'wake-pending' && wait.reason === 'message')
176
- return undefined;
177
- const deadline = Date.parse(wait.deadline);
178
- const registeredAt = Number.isFinite(deadline) ? new Date(deadline - 600_000).toISOString() : now;
179
- const open = wait.phase !== 'wake-pending';
180
- // A pending wait from before reasons were recorded settled on its persisted observations, as
181
- // `reconcileWorkerWait` infers it: satisfied by them is an outcome, anything else its deadline.
182
- const satisfied = (ids, reported) => wait.mode === 'all' ? ids.every((id) => reported.includes(id)) : reported.length > 0;
183
- const inferred = wait.phase === 'wake-pending' && wait.reason === undefined
184
- ? (wait.requestIds ? satisfied(wait.requestIds, (wait.requestOutcomes ?? []).map((outcome) => outcome.requestId))
185
- : satisfied(wait.workerIds, (wait.outcomes ?? []).map((outcome) => outcome.workerId))) ? 'outcome' : 'timeout'
186
- : undefined;
187
- const reason = wait.reason === 'outcome' || wait.reason === 'timeout' ? wait.reason : inferred;
188
- const observed = [...(wait.outcomes ?? []), ...(wait.requestOutcomes ?? [])].map((outcome) => outcome.observedAt).sort().at(-1);
189
- const resolvedAt = reason === 'outcome' && observed ? observed : wait.deadline;
190
- return {
191
- id: wait.id, kind: 'worker', source: 'agent', via: 'cez-worker-wait', registeredAt, deadline: wait.deadline, timeoutSeconds: 600, turnId: 'upgraded',
192
- phase: open ? 'open' : reason ? 'resolved' : 'cancelled',
193
- ...(wait.mode ? { mode: wait.mode } : {}),
194
- ...(wait.requestIds
195
- ? { requestIds: wait.requestIds, requestOutcomes: wait.requestOutcomes ?? [] }
196
- : { workerIds: wait.workerIds, revisions: wait.revisions ?? [], outcomes: wait.outcomes }),
197
- ...(!open && reason ? { result: { reason }, resolvedAt } : {}),
198
- ...(!open && !reason ? { cancelledAt: wait.deadline } : {}),
199
- };
200
- }
201
- /** Whether a record is a root still parked on its workers: an open or resolved worker wait in the
202
- * list. Such a root has its pending human question re-read from the transcript before a manager
203
- * parks it. Every stored `delegation.wait`, the completion gate's included, is read into the list
204
- * on open (store schema 7, hearsay-tools/cezarion#1301), so the list is the only place to look. */
205
- export function holdsWorkerWait(run) {
206
- if (run.delegation?.role !== 'root')
207
- return false;
208
- return !!run.waits?.some((wait) => wait.kind === 'worker' && (wait.phase === 'open' || wait.phase === 'resolved'));
209
- }
210
- /** A stable id for the timer a legacy monitoring park becomes. The row keeps its legacy JSON
211
- * until it is next written, so every read of it must name the same wait. */
212
- function legacyTimerId(runId, wakeAt) {
213
- return legacyWaitId(`legacy-monitoring-timer:${String(runId)}:${wakeAt}`);
214
- }
215
- /** The human wait a stored pending-question summary becomes: one per run, the same on every read. */
216
- function legacyHumanWaitId(runId) {
217
- return legacyWaitId(`legacy-pending-ask:${String(runId)}`);
218
- }
219
- /** A name-based (version 5 shaped) UUID, so a row read twice upgrades to the same entry. */
220
- function legacyWaitId(name) {
221
- const hex = createHash('sha256').update(name).digest('hex');
222
- const variant = (8 | (Number.parseInt(hex[16], 16) & 3)).toString(16);
223
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
224
- }
225
- /**
226
- * Upgrade-on-read (store schema 4, spec 2026-10-17-unified-waits): read a schema-3 record's CI and
227
- * monitoring fields into its wait list, then delete them. Mutates `row`, before validation.
228
- *
229
- * - `ciWait`: `registered`/`parked` → an open `pr` checks wait, `wake-pending` → resolved (resolved when
230
- * its result was observed), `delivered`/`withdrawn` → `lastWaits` as delivered/cancelled.
231
- * - `lastCiWait` → `lastWaits`: `delivered` stays delivered, anything else was withdrawn intent and
232
- * reads as cancelled. `lastCiWaitError` → `lastWaitsError`.
233
- * - `activity: 'monitoring'` on a live run: with `monitoringWakeAt`, an open timer due then
234
- * (`seconds` is what remains, clamped to a timer's bounds); without one, no wait. Either way a
235
- * `running` run parks as `waiting`, its running step with it, as every waiting park writes it.
236
- * On a finished run the fields are stale and only dropped.
237
- * - `hasPendingHumanAsk: true` on a `waiting` run with no open human wait (phase 4b,
238
- * hearsay-tools/cezarion#1236): an open `human` wait, `ask-line`, with no `askSeq`. Recovery shows
239
- * it (`surfaceHumanWait`), which attaches it to the question still pending in the transcript
240
- * instead of raising a second card. Anywhere else the summary is dropped: the human wait it stood
241
- * beside since phase 2 already says the same.
242
- *
243
- * - `delegation.wait`/`lastWait` registered by the agent (store schema 6, hearsay-tools/cezarion#1235)
244
- * → `workerWaitEntry`, then settled by what became of the wake input (`wakeId`, else the wait's own
245
- * id): a wait whose input was delivered reads as delivered, a `wake-pending` one whose input is
246
- * still queued stays resolved and records it as `wakeInputId`, so it is delivered once, and a
247
- * `lastWait` that was never delivered reads as cancelled. The `message` stand-in is dropped. No
248
- * input is added or removed: a cancelled receipt's undelivered wake stays queued and is delivered
249
- * as an ordinary input. The completion gate's wait (store schema 7, hearsay-tools/cezarion#1301) becomes a
250
- * `source: 'cezar'`, `via: 'completion'` entry the same way, and `delegation.completion` is dropped. A current wait
251
- * (the stand-in included) whose wake a provider took on a `waiting` run is the old engine's crash
252
- * between the delivery checkpoint and the resume: the run reads `running`, so recovery resumes
253
- * it. A wake an inbox read acknowledged, or one beside a pending question, resumes nothing.
254
- *
255
- * - A `waits`/`lastWaits` entry of kind `ci` (hearsay-tools/cezarion#1425) → kind `pr` with
256
- * `until: 'checks'` and `wakeOnConflict: true`, what a `ci` wait did.
257
- *
258
- * An unreadable legacy CI wait gets the per-entry salvage `parseRunRecords` gives `waits`: it is
259
- * dropped, `lastWaitsError` says so, and the status is left alone. A `waiting` run with no open
260
- * wait reads as Needs you, which a human can resume.
261
- */
262
- /** A live run and its live step move from `from` to `to` together, as every park and resume writes them. */
263
- function setLiveStatus(row, from, to) {
264
- row.status = to;
265
- if (Array.isArray(row.steps))
266
- for (const step of row.steps) {
267
- if (step && typeof step === 'object' && step.status === from)
268
- step.status = to;
269
- }
270
- }
271
- const resumeParked = (row) => setLiveStatus(row, 'waiting', 'running');
272
- export function upgradeLegacyWaits(row) {
273
- if (!hasLegacyWaitFields(row))
274
- return;
275
- // Kind `ci` waited for checks and woke on a conflict (hearsay-tools/cezarion#1425).
276
- for (const key of ['waits', 'lastWaits']) {
277
- if (Array.isArray(row[key]))
278
- row[key] = row[key].map((entry) => isCiKindEntry(entry)
279
- ? { ...entry, kind: 'pr', until: 'checks', wakeOnConflict: true } : entry);
280
- }
281
- const opened = [];
282
- const settled = [];
283
- let unreadable = false;
284
- const legacyCi = (value, previous) => {
285
- if (value === undefined)
286
- return;
287
- const parsed = ciWaitSchema.safeParse(value);
288
- if (!parsed.success) {
289
- unreadable = true;
290
- return;
291
- }
292
- const entry = ciWaitEntry(parsed.data);
293
- if (previous && entry.phase !== 'delivered')
294
- entry.phase = 'cancelled';
295
- (entry.phase === 'open' || entry.phase === 'resolved' ? opened : settled).push(entry);
296
- };
297
- // The previous wait settled before the current one did, so it goes first.
298
- legacyCi(row.lastCiWait, true);
299
- legacyCi(row.ciWait, false);
300
- const agentWaits = agentWorkerWaits(row);
301
- if (agentWaits.length) {
302
- // The wait's own stamps decide every time the entry carries (`workerWaitEntry`), not the clock.
303
- const now = typeof row.createdAt === 'string' ? row.createdAt : new Date(0).toISOString();
304
- const inputs = Array.isArray(row.agentInputs) ? row.agentInputs : [];
305
- const current = agentWaits.find((found) => found.key === 'wait');
306
- // The old engine retired a delivered wake into `lastWait` with the resume: a current wait whose
307
- // wake a provider took on a `waiting` run is a crash between the two, and resumed. An inbox
308
- // read starts no provider turn, and a pending question still holds the run, as they did then.
309
- const interrupted = (key, input) => key === 'wait' && row.status === 'waiting' &&
310
- typeof input?.deliveredAt === 'string' && !input.inboxClaim?.acknowledgedAt && row.hasPendingHumanAsk !== true;
311
- for (const { key, wait, completion } of agentWaits) {
312
- // A wait that settles has its copy in `lastWait` too: it is the same wait.
313
- if (key === 'lastWait' && current?.wait.id === wait.id)
314
- continue;
315
- const input = inputs.find((candidate) => candidate.id === (wait.wakeId ?? wait.id));
316
- const entry = workerWaitEntry(wait, now);
317
- // Cezar's completion gate wait is its own: no agent registered it (hearsay-tools/cezarion#1301).
318
- // It keeps the deadline it always carried, with the 600 s default registration.
319
- if (entry && completion)
320
- Object.assign(entry, { source: 'cezar', via: 'completion', mode: 'all' });
321
- // The `message` stand-in becomes no entry, but its delivered message may be that crash too.
322
- if (!entry) {
323
- if (interrupted(key, input))
324
- resumeParked(row);
325
- continue;
326
- }
327
- const deliveredAt = typeof input?.deliveredAt === 'string' ? input.deliveredAt : undefined;
328
- if (entry.phase !== 'open' && deliveredAt) {
329
- Object.assign(entry, { phase: 'delivered', deliveredAt });
330
- if (interrupted(key, input))
331
- resumeParked(row);
332
- }
333
- else if (key === 'lastWait' && entry.phase !== 'cancelled')
334
- Object.assign(entry, { phase: 'cancelled', cancelledAt: wait.deadline });
335
- else if (entry.phase === 'resolved' && input)
336
- entry.wakeInputId = input.id;
337
- (entry.phase === 'open' || entry.phase === 'resolved' ? opened : settled).push(entry);
338
- }
339
- }
340
- const live = row.status === 'running' || row.status === 'queued' || row.status === 'waiting';
341
- if (row.activity === 'monitoring' && live) {
342
- const wakeAt = row.monitoringWakeAt;
343
- // Schema 3 read an unreadable deadline as none (`.catch(undefined)`): no wait.
344
- if (typeof wakeAt === 'string' && z.iso.datetime().safeParse(wakeAt).success) {
345
- const now = Date.now();
346
- const seconds = Math.min(TIMER_MAX_SECONDS, Math.max(TIMER_MIN_SECONDS, Math.round((Date.parse(wakeAt) - now) / 1000)));
347
- opened.push({
348
- id: legacyTimerId(row.id, wakeAt), kind: 'timer', source: 'agent', via: 'monitoring-line',
349
- registeredAt: new Date(now).toISOString(), deadline: wakeAt, phase: 'open', turnId: 'legacy', seconds,
350
- });
351
- }
352
- if (row.status === 'running')
353
- setLiveStatus(row, 'running', 'waiting');
354
- }
355
- const asksHuman = (entry) => !!entry && typeof entry === 'object' && entry.kind === 'human' && entry.phase === 'open';
356
- if (row.hasPendingHumanAsk === true && row.status === 'waiting' &&
357
- !(Array.isArray(row.waits) && row.waits.some(asksHuman)) && !opened.some(asksHuman)) {
358
- opened.push({
359
- id: legacyHumanWaitId(row.id), kind: 'human', source: 'agent', via: 'ask-line',
360
- registeredAt: typeof row.createdAt === 'string' && z.iso.datetime().safeParse(row.createdAt).success ? row.createdAt : new Date(0).toISOString(),
361
- phase: 'open', turnId: 'legacy',
362
- });
363
- }
364
- if (opened.length) {
365
- const current = Array.isArray(row.waits) ? row.waits : [];
366
- if (row.waits !== undefined && !Array.isArray(row.waits))
367
- unreadable = true;
368
- row.waits = [...current, ...opened.filter((wait) => !current.some((entry) => entry?.id === wait.id))];
369
- }
370
- if (settled.length) {
371
- const current = Array.isArray(row.lastWaits) ? row.lastWaits : [];
372
- if (row.lastWaits !== undefined && !Array.isArray(row.lastWaits))
373
- unreadable = true;
374
- row.lastWaits = [...settled, ...current].slice(-LAST_WAITS_LIMIT);
375
- }
376
- if (typeof row.lastCiWaitError === 'string' && row.lastWaitsError === undefined)
377
- row.lastWaitsError = row.lastCiWaitError;
378
- if (unreadable)
379
- row.lastWaitsError = UNREADABLE_WAIT;
380
- for (const key of LEGACY_WAIT_KEYS)
381
- delete row[key];
382
- if (agentWaits.length || rootCompletion(row)) {
383
- const delegation = { ...row.delegation };
384
- for (const { key } of agentWaits)
385
- delete delegation[key];
386
- delete delegation.completion;
387
- row.delegation = delegation;
388
- }
389
- }
390
- /** Read legacy wait fields into the wait list and salvage per entry, identically for live stores
391
- * and the read-only workspace index. */
392
- export function parseRunRecords(raw) {
393
- if (Array.isArray(raw))
394
- for (const row of raw) {
395
- if (!row || typeof row !== 'object')
396
- continue;
397
- upgradeLegacyWaits(row);
398
- // One unreadable wait must not evict the run, nor its readable siblings.
399
- for (const key of ['waits', 'lastWaits']) {
400
- if (row[key] === undefined)
401
- continue;
402
- const entries = Array.isArray(row[key]) ? row[key] : [];
403
- const readable = entries.filter((entry) => waitSchema.safeParse(entry).success);
404
- if (!Array.isArray(row[key]) || readable.length !== entries.length)
405
- row.lastWaitsError = UNREADABLE_WAIT;
406
- if (readable.length)
407
- row[key] = readable;
408
- else
409
- delete row[key];
410
- }
411
- // One unreadable registration must not evict the run, nor its readable siblings (#781).
412
- if (row.previewServers !== undefined) {
413
- if (Array.isArray(row.previewServers))
414
- row.previewServers = row.previewServers.filter((entry) => previewServerSchema.safeParse(entry).success);
415
- else
416
- delete row.previewServers;
417
- }
418
- }
419
- return z.array(runRecordSchema).safeParse(raw);
420
- }
421
- /** Just the `StoredRow` part of a `coldBase` entry. */
422
- function storedRow({ revision, seq, data, extras }) {
423
- return { revision, seq, data, extras };
424
- }
425
- /** One stored record (a row's `data`) through `parseRunRecords`' salvage and schema, with what the
426
- * schema dropped. Read after the salvage ran: what it removes (an unreadable CI wait, a preview
427
- * server entry) the runtime has decided to drop, and keeps dropping on the next write, as it always
428
- * has; only what the schema does not know is put back. */
429
- function decodeStoredRecord(raw) {
430
- const upgraded = hasLegacyWaitFields(raw);
431
- const parsed = parseRunRecords([raw]);
432
- if (!parsed.success)
433
- return undefined;
434
- const run = parsed.data[0];
435
- return { run, extras: collectRawExtras(raw, run), ...(upgraded ? { upgraded: true } : {}) };
436
- }
437
- /** One database row's `data` back into a record and its extras. Undefined when it does not parse:
438
- * one unreadable row costs that row only. */
439
- export function decodeRunRow(data) {
440
- try {
441
- return decodeStoredRecord(JSON.parse(data));
442
- }
443
- catch {
444
- return undefined;
445
- }
446
- }
447
- /** One database row's `data` back into a record, for a reader that never writes it back. */
448
- export function decodeRunRecord(data) {
449
- try {
450
- const parsed = parseRunRecords([JSON.parse(data)]);
451
- return parsed.success ? parsed.data[0] : undefined;
452
- }
453
- catch {
454
- return undefined;
455
- }
456
- }
457
- export { LEGACY_INDEX_BACKUP_FILE, LEGACY_INDEX_FILE } from './legacy-index.js';
458
- /** The pauses between open attempts while the database is busy, when `open` may wait (a boot):
459
- * about 3.5 s in all, with each attempt's own busy timeout. Long enough for another process to
460
- * finish importing a large `runs.json`. */
461
- const OPEN_RETRY_DELAYS_MS = [50, 100, 200, 400, 800, 1600];
462
- /** Block this thread for `ms`. Only `open` does, at boot, when there is nothing else to run. */
463
- function sleepSync(ms) {
464
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
465
- }
466
- /** Runs (and conversation roots, one family query each) the open-time facts warm-up enumerates
467
- * per event-loop turn (hearsay-tools/cezarion#949), so each slice stays a few milliseconds. */
468
- const WARM_IDS_PER_SLICE = 100;
469
- const MAX_RUNS_KEPT = 300;
470
- /** How many archived root runs the run lists carry per project (#864): `GET /run-summaries?archived=recent`
471
- * and `GET /workspace/runs-index`. Unarchived runs are never cut; older archived runs page in
472
- * through `GET /run-summaries/archived` and the workspace search. */
473
- export const ARCHIVED_WINDOW = 200;
474
- const PR_URL_RE = /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/;
475
- const ISSUE_URL_RE = /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/issues\/\d+/;
476
- // The transcript auto-link is convenience only (the cockpit's own `gh pr create` path sets the
477
- // URL authoritatively). Adopt a PR URL ONLY when the agent actually CREATED one — a task that
478
- // reviews or merely references an existing PR must not get mislabeled with its number (#fake-pr).
479
- const CREATED_PR_RE = /\b(?:gh\s+pr\s+create|pull\s*request\s+created|created\s+(?:a\s+)?(?:draft\s+)?(?:pr|pull\s*request)|opened\s+(?:a\s+)?(?:draft\s+)?pull\s*request)\b/i;
480
- /** Referenced-tier working-set cap (spec 2026-07-16-pr-autodiscovery): past
481
- * this many distinct PRs the conversation is a survey, not a subject. */
482
- const MAX_PR_CANDIDATES = 8;
483
- /**
484
- * Every scannable string of one persisted event: the v1 top-level fields plus
485
- * the protocol-v2 `item.*` content (nested — the reason v2 streams were
486
- * invisible to the janitor, #407). Reasoning items are skipped: thinking text
487
- * speculates about PRs the task never touches.
488
- */
489
- /**
490
- * Archiving IS resigning from a task, so an archived run can never carry a pending usage-limit
491
- * resume (spec 2026-08-03-auto-resume-after-usage-limit). The rule lives HERE rather than in the
492
- * archive route because the bulk "Archive finished" sweep never goes through that route, and a
493
- * user who archives fifty finished tasks has resigned from all fifty.
494
- *
495
- * The engine needs no telling: its timer re-reads the record before it fires and no sweep re-arms
496
- * an archived run, so a cleared field is the whole cancellation.
497
- */
498
- function clearPendingAutoResume(run) {
499
- // A withdrawn appointment settles the run failed with its kept error (hearsay-tools/cezarion#1236),
500
- // the state a usage-limited run was in before it waited.
501
- if (isUsageLimitHold(run)) {
502
- run.status = 'failed';
503
- run.finishedAt ??= new Date().toISOString();
504
- }
505
- run.autoResumeAt = undefined;
506
- run.autoResumeAttempts = undefined;
507
- }
508
- /**
509
- * The write rule (hearsay-tools/cezarion#1496): a resume time is the appointment of a `waiting`
510
- * run, so every commit takes it off a record that is not `waiting`. A copy, set to `undefined`
511
- * and never deleted: a caller may stage the held record itself. `autoResumeAttempts` stays, since
512
- * `MAX_AUTO_RESUMES` counts attempts across resumes.
513
- */
514
- function withoutStaleResumes(input) {
515
- let staged;
516
- for (const [id, run] of input) {
517
- if (run?.autoResumeAt === undefined || isUsageLimitHold(run))
518
- continue;
519
- (staged ??= new Map(input)).set(id, { ...run, autoResumeAt: undefined });
520
- }
521
- return staged ?? input;
522
- }
523
- /**
524
- * Archiving is resigning from a task, so it retires the pin too (#935) — a pin on a task the
525
- * user has filed away is stale by definition, and the archived view collapses into one bucket
526
- * anyway, so a surviving pin would be invisible state waiting to surprise whoever unarchives.
527
- *
528
- * Here rather than in the pin route for the same reason `clearPendingAutoResume` is here: the
529
- * bulk "Archive finished" sweep never goes through a route, and it has to obey the rule too.
530
- *
531
- * Deleted, not set to `false`: absent is what every reader treats as unpinned, and it is the
532
- * shape a cezar that has never heard of pins already writes.
533
- */
534
- function clearPin(run) {
535
- delete run.pinned;
536
- delete run.pinnedAt;
537
- }
538
- function eventTextFragments(event) {
539
- const fragments = [];
540
- for (const key of ['text', 'result', 'message']) {
541
- const value = event[key];
542
- if (typeof value === 'string')
543
- fragments.push(value);
544
- }
545
- const item = event.item;
546
- if (item && typeof item === 'object' && item.kind !== 'reasoning') {
547
- const it = item;
548
- for (const key of ['text', 'title', 'output']) {
549
- const value = it[key];
550
- if (typeof value === 'string')
551
- fragments.push(value);
552
- }
553
- if (typeof it.input === 'string') {
554
- fragments.push(it.input);
555
- }
556
- else if (it.input !== undefined) {
557
- try {
558
- fragments.push(JSON.stringify(it.input));
559
- }
560
- catch {
561
- // circular input — skip it
562
- }
563
- }
564
- }
565
- return fragments;
566
- }
567
- /**
568
- * Creation claims come from agent prose or cezar-rendered tool titles, never arbitrary tool
569
- * output/input. The claimed URL may still come from the event’s command result.
570
- */
571
- function eventCreationClaimFragments(event) {
572
- const fragments = [];
573
- const nested = event.item;
574
- if (event.parentItemId !== undefined || (nested && typeof nested === 'object' &&
575
- nested.parentItemId !== undefined))
576
- return fragments;
577
- // A `tool-result` event's `result` IS raw command output; on every other event the top-level
578
- // text is the agent's own.
579
- if (event.type !== 'tool-result') {
580
- for (const key of ['text', 'result', 'message']) {
581
- const value = event[key];
582
- if (typeof value === 'string')
583
- fragments.push(value);
584
- }
585
- }
586
- const item = event.item;
587
- if (item && typeof item === 'object') {
588
- const it = item;
589
- if (it.kind === 'message' && it.role === 'assistant' && typeof it.text === 'string') {
590
- fragments.push(it.text);
591
- }
592
- if (it.kind === 'tool' && typeof it.title === 'string')
593
- fragments.push(it.title);
594
- }
595
- return fragments;
596
- }
597
- /** Agent-authored event text, matching the trust boundary used by task markers.
598
- * Tool titles, inputs, and outputs remain visible to the referenced-URL tier,
599
- * but must never promote an issue into the shared `issueNumber` field (#538). */
600
- function eventAgentTextFragments(event) {
601
- const fragments = [];
602
- for (const key of ['text', 'result']) {
603
- const value = event[key];
604
- if (typeof value === 'string')
605
- fragments.push(value);
606
- }
607
- const item = event.item;
608
- if (item && typeof item === 'object') {
609
- const it = item;
610
- if (it.kind === 'message' && it.role === 'assistant' && typeof it.text === 'string') {
611
- fragments.push(it.text);
612
- }
613
- }
614
- return fragments;
615
- }
616
- /**
617
- * Resolve declarations and prompt-supported candidates without guessing through ambiguity. Apply
618
- * repository scope to the winner only; filtering candidates first could promote an otherwise
619
- * ambiguous reference.
620
- */
621
- function resolveReferencedRef(candidates, task, declared, handle) {
622
- const resolved = resolveCandidate(candidates, task, declared);
623
- if (resolved === undefined)
624
- return undefined;
625
- return isRepoScopedRef(resolved, task, handle) ? resolved : undefined;
626
- }
627
- /** Resolve prompt evidence before the repository veto — see `resolveReferencedRef`. */
628
- function resolveCandidate(candidates, task, declared) {
629
- if (declared !== undefined)
630
- return candidates.find((url) => url.endsWith(`/${declared}`));
631
- if (candidates.length === 1)
632
- return candidates[0];
633
- // Repository-qualified prompt URLs distinguish equal numbers in different repositories.
634
- // Extract whole references with the collectors' grammar so /42 cannot match /420.
635
- const promptUrls = new Set([
636
- ...task.matchAll(new RegExp(PR_URL_RE.source, 'g')),
637
- ...task.matchAll(new RegExp(ISSUE_URL_RE.source, 'g')),
638
- ].map((match) => match[0]));
639
- const exact = candidates.filter((url) => promptUrls.has(url));
640
- if (exact.length > 0)
641
- return exact.length === 1 ? exact[0] : undefined;
642
- const named = candidates.filter((url) => {
643
- const num = url.split('/').pop() ?? '';
644
- // `\d` boundaries only: they reject `170` inside `4170` yet still match a
645
- // number written as `#4170`, ` 4170`, or inside a pasted `…/pull/4170`.
646
- return num !== '' && new RegExp(`(?<!\\d)#?${num}(?!\\d)`).test(task);
647
- });
648
- return named.length === 1 ? named[0] : undefined;
649
- }
650
- /** The number a forge URL's last segment names (`…/pull/402` → 402), or undefined. */
651
- function refUrlNumber(url) {
652
- if (!url)
653
- return undefined;
654
- const n = Number(url.split('/').pop());
655
- return Number.isInteger(n) && n > 0 && n < MAX_REF ? n : undefined;
656
- }
657
- /**
658
- * Ignore a created-PR declaration when resolving the referenced subject, so a task can retain
659
- * both its original subject and its new PR.
660
- */
661
- function referencedPrDeclaration(run) {
662
- const declared = run.markerRefs?.pr;
663
- if (declared === undefined)
664
- return undefined;
665
- return declared === refUrlNumber(run.pullRequestUrl) ? undefined : declared;
666
- }
667
- /** Prompt attribution survives declarations of follow-up issues. Bare hashes become issues
668
- * only after an issue signal; explicit PR prompts never acquire an invented issue identity. */
669
- function originatingIssue(run) {
670
- // Only an issue-led subject is stable attribution. Mentions inside comparisons or
671
- // background instructions remain evidence, but an agent declaration may supersede them.
672
- const prompt = run.task.trimStart()
673
- .replace(/^(?:please\s+)?(?:(?:can|could|would|will)\s+you\s+|i\s+(?:want|would\s+like)\s+you\s+to\s+)/i, '')
674
- .replace(/^(?:please\s+)?(?:fix|resolve|address|implement|investigate|review|work(?:\s+on)?)\s+/i, '');
675
- const subject = /^(?:(?:the\s+)?(?:(?:github|fork|upstream)\s+)?issue\s*|(?:fork|upstream)\s+)?(?:https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/issues\/\d+|(?:[\w.-]+\/[\w.-]+)?#?\d+)\b/i.exec(prompt);
676
- if (!subject)
677
- return undefined;
678
- const refs = extractTaskRefs(subject[0]);
679
- return refs.issueNumber ?? ((run.issueNumber !== undefined || run.markerRefs?.issue !== undefined)
680
- ? refs.ambiguousNumber : undefined);
681
- }
682
- function referencedIssueDeclaration(run) {
683
- return run.markerRefs?.issue === undefined ? undefined : originatingIssue(run) ?? run.markerRefs.issue;
684
- }
685
- function resolveIssueReference(run, handle) {
686
- const declared = referencedIssueDeclaration(run);
687
- const candidates = run.referencedIssueCandidates ?? [];
688
- // Prompt URLs remain evidence even in legacy records without a candidate working set.
689
- const promptUrls = [...new Set([...run.task.matchAll(new RegExp(ISSUE_URL_RE.source, 'g'))]
690
- .map(match => match[0]).filter(url => refUrlNumber(url) === declared))];
691
- if (promptUrls.length > 1)
692
- return undefined;
693
- if (promptUrls.length === 1)
694
- return resolveReferencedRef(promptUrls, run.task, declared, handle);
695
- // A number cannot choose between two repositories' issues with that same number.
696
- if (declared !== undefined && new Set(candidates.filter(url => refUrlNumber(url) === declared)).size > 1) {
697
- return undefined;
698
- }
699
- return resolveReferencedRef(candidates, run.task, declared, handle);
700
- }
701
- function restoreOriginatingIssue(run) {
702
- const origin = originatingIssue(run);
703
- if (origin === undefined || run.markerRefs?.issue === undefined)
704
- return;
705
- run.issueNumber = origin;
706
- delete run.referencedIssueNumberSeeded;
707
- if (run.referencedIssueCandidates !== undefined || refUrlNumber(run.referencedIssueUrl) !== origin) {
708
- run.referencedIssueUrl = resolveIssueReference(run);
709
- }
710
- }
711
- /**
712
- * The PR URL a creation phrase *introduces*, or undefined. The created URL is
713
- * the first one at or after the `CREATED_PR_RE` phrase — a PR the same event
714
- * merely referenced *earlier* (e.g. the issue's own linked `…/pull/1`) must not
715
- * be mistaken for the one just created (#495). Falls back to the last URL
716
- * *before* the phrase for `gh` orderings that print the URL first. Selection
717
- * only — the caller decides whether creation phrasing is present.
718
- */
719
- function createdPrUrl(haystack) {
720
- const phrase = CREATED_PR_RE.exec(haystack);
721
- if (!phrase)
722
- return undefined;
723
- const after = PR_URL_RE.exec(haystack.slice(phrase.index));
724
- if (after)
725
- return after[0];
726
- let before;
727
- for (const m of haystack.slice(0, phrase.index).matchAll(new RegExp(PR_URL_RE.source, 'g'))) {
728
- before = m[0];
729
- }
730
- return before;
731
- }
732
- /** Associate one URL per claim; command outputs remain separate from authored claims. */
733
- function createdPrUrls(claim, haystack, toolOutput) {
734
- const phrases = [...claim.matchAll(new RegExp(CREATED_PR_RE.source, 'gi'))];
735
- if (!phrases.length)
736
- return [];
737
- const urls = phrases.flatMap((phrase, index) => {
738
- const preceding = claim.slice(index ? phrases[index - 1].index + phrases[index - 1][0].length : 0, phrase.index);
739
- const before = [...preceding.matchAll(new RegExp(PR_URL_RE.source, 'g'))].at(-1);
740
- // URL-first reports put only punctuation/whitespace between the URL and its claim.
741
- // An earlier URL followed by unrelated prose is still context, not a created resource.
742
- if (before && /^[\s:—–-]*(?:draft\s+)?$/i.test(preceding.slice(before.index + before[0].length)))
743
- return [before[0]];
744
- const after = PR_URL_RE.exec(claim.slice(phrase.index, phrases[index + 1]?.index))?.[0];
745
- return after ? [after] : [];
746
- });
747
- if (!urls.length && toolOutput !== undefined) {
748
- // gh prints one URL per successful command. Never promote more output links than commands.
749
- const outputs = [...toolOutput.matchAll(new RegExp(PR_URL_RE.source, 'g'))];
750
- urls.push(...outputs.slice(0, phrases.length).map(match => match[0]));
751
- }
752
- if (!urls.length && phrases.length === 1) {
753
- const url = createdPrUrl(`${claim} ${haystack}`);
754
- if (url)
755
- urls.push(url);
756
- }
757
- return [...new Set(urls)];
758
- }
759
- /**
760
- * Reconcile one record just read off disk with the fact that whichever process wrote it is gone.
761
- *
762
- * Mutates and returns `run`. Extracted from `RunStore.open` so the read-only index reader
763
- * (`./run-index.ts`) answers the SAME question about a `running` row on disk. Two parsers that
764
- * disagree here is a visible bug, not an internal one: the cockpit would show a task as running
765
- * in the ⌘K index and failed the moment you opened it.
766
- *
767
- * `keepLive` (#367): leave `queued`/`running`/`waiting` untouched so the caller can recover them
768
- * (RunManager.recover re-queues queued runs, resumes interrupted ones). Without it — one-shot CLI
769
- * paths that never recover, and the index reader, which has no manager at all — live-looking runs
770
- * are marked failed so no ghost stays behind.
771
- */
772
- export function reconcileLoadedRun(run, opts) {
773
- settleLoadedStop(run);
774
- restoreLoadedUsageLimitHold(run);
775
- failLoadedInterruptedRun(run, opts);
776
- clearLoadedStaleResume(run);
777
- restoreLostReferencedPullRequest(run, referencedPrDeclaration, resolveReferencedRef);
778
- restoreOriginatingIssue(run);
779
- // Repository scoping follows reconciliation: stores arm a handle asynchronously, while
780
- // the read-only index applies its cached handle to these fresh records (#97). This ordering
781
- // also scopes any referenced PR restored above without filtering candidate evidence first.
782
- return run;
783
- }
784
- function settleLoadedStop(run) {
785
- // An accepted Stop is durable intent, never an interrupted run to auto-resume.
786
- if (run.stopping) {
787
- run.status = 'cancelled';
788
- run.finishedAt ??= new Date().toISOString();
789
- for (const step of run.steps) {
790
- if (step.status === 'running' || step.status === 'waiting')
791
- step.status = 'cancelled';
792
- }
793
- }
794
- run.stopping = undefined;
795
- }
796
- function restoreLoadedUsageLimitHold(run) {
797
- // A usage-limited run is waiting for its resume (hearsay-tools/cezarion#1236, phase 4a). Rows a
798
- // schema-7 cezar wrote kept it failed with the appointment; they read as the waiting run they are.
799
- if (run.status === 'failed' && run.autoResumeAt !== undefined) {
800
- run.status = 'waiting';
801
- run.finishedAt = undefined;
802
- }
803
- }
804
- function failLoadedInterruptedRun(run, opts) {
805
- // A run that was live when the previous process exited can never finish —
806
- // surface that instead of a forever-"running" ghost. `review` survives
807
- // restarts on purpose: the gate is pure data (worktree + branch + record)
808
- // with no live process, so the diff panel, Send back (resume) and Draft PR
809
- // all still work.
810
- // A usage-limit hold runs no process, so no exit interrupted it: its appointment stands.
811
- if (!opts?.keepLive && engineOwnsRun(run)) {
812
- run.status = 'failed';
813
- run.error = 'interrupted — cezar process exited during the run';
814
- run.finishedAt = run.finishedAt ?? new Date().toISOString();
815
- for (const step of run.steps) {
816
- if (step.status === 'running' || step.status === 'waiting')
817
- step.status = 'failed';
818
- }
819
- }
820
- }
821
- function clearLoadedStaleResume(run) {
822
- // Open waits are left alone at every status: RunManager cancels them when a run ends (spec
823
- // 2026-10-17-unified-waits), and recovery reads the ones a crash left behind.
824
- // A pending usage-limit resume survives the restart on purpose (the wait can be
825
- // hours) — `RunManager.recover()` re-arms it from this field. It can only mean
826
- // anything on a `waiting` run, so anywhere else it is stale bookkeeping.
827
- if (run.status !== 'waiting')
828
- run.autoResumeAt = undefined;
829
- }
830
- /**
831
- * Settle an adopted dead owner’s live run without starting work. Untouched runs cancel; started
832
- * runs become interrupted. Stop explicitly cancels its target. Mutates run.
833
- */
834
- export function settleOrphanedRun(run, opts = {}) {
835
- if (opts.stop && (run.status === 'queued' || run.status === 'running' || run.status === 'waiting'))
836
- run.stopping = true;
837
- if (run.status === 'queued' && !run.startedAt && run.workflowDef !== undefined &&
838
- run.steps.every((step) => step.status === 'pending' && !step.startedAt && !step.sessionId)) {
839
- run.status = 'cancelled';
840
- run.finishedAt ??= new Date().toISOString();
841
- }
842
- return reconcileLoadedRun(run, { keepLive: false });
843
- }
844
- /**
845
- * Drop this run's referenced PR/issue if the project's handle proves it foreign and the prompt
846
- * does not corroborate it (#945). Returns whether anything changed.
847
- *
848
- * One-directional by construction: it only ever clears fields, so a record written by an older
849
- * cezar — or read by one after this ran — is never worse off, and a downgrade sees a record whose
850
- * format is untouched and whose cleared fields were already optional.
851
- */
852
- export function rescopeRun(run, handle) {
853
- let changed = false;
854
- if (handle && run.pullRequests) {
855
- const entries = run.pullRequests.map(entry => {
856
- if (entry.source !== 'declared' || !entry.url || isRepoScopedRef(entry.url, run.task, handle))
857
- return entry;
858
- // Revoke an uncorroborated URL, preserving the accepted declaration and its order.
859
- return { number: entry.number, source: entry.source };
860
- });
861
- const next = mergePullRequests(undefined, entries, `https://github.com/${handle.owner}/${handle.name}`);
862
- if (!isDeepStrictEqual(next, run.pullRequests)) {
863
- run.pullRequests = next;
864
- changed = true;
865
- }
866
- }
867
- if (run.referencedPullRequestUrl &&
868
- !isRepoScopedRef(run.referencedPullRequestUrl, run.task, handle)) {
869
- run.referencedPullRequestUrl = undefined;
870
- changed = true;
871
- }
872
- if (run.referencedIssueUrl &&
873
- !isRepoScopedRef(run.referencedIssueUrl, run.task, handle)) {
874
- run.referencedIssueUrl = undefined;
875
- changed = true;
876
- // Take back the number this janitor seeded from that very URL — the same revoke
877
- // `trackReferencedIssues` performs when ambiguity clears a resolution. A `prNumber`-style
878
- // number the prompt, namer or a marker owns is NOT ours to touch, which is exactly what
879
- // `referencedIssueNumberSeeded` records.
880
- if (run.referencedIssueNumberSeeded) {
881
- run.issueNumber = undefined;
882
- run.referencedIssueNumberSeeded = undefined;
883
- }
884
- }
885
- return changed;
886
- }
887
- /**
888
- * Every field `RunStore.open` may rewrite while loading a record: what `reconcileLoadedRun`
889
- * assigns. Compared before and after, it tells open() which rows normalization changed, so it
890
- * marks those dirty and no others. Edit it together with that function, or a normalized row stays unsaved (the store tests pin each field).
891
- */
892
- function loadNormalizedFields(run) {
893
- return JSON.stringify([
894
- run.stopping, run.status, run.finishedAt, run.error, run.autoResumeAt,
895
- run.referencedPullRequestUrl, run.pullRequests,
896
- run.issueNumber, run.referencedIssueUrl, run.referencedIssueNumberSeeded, run.hasPendingPermission, run.steps.map((step) => step.status),
897
- ]);
898
- }
899
- /** Test seam (#779): `beforeTransaction` runs once `runs.json` is read and parsed, before the
900
- * import asks for the write lock; `beforeCommit` runs inside the import transaction, after every
901
- * row is written and before the last check that no older cezar wrote `runs.json` meanwhile. */
902
- let legacyImportHook;
903
- export function __setLegacyImportHookForTests(hook) {
904
- legacyImportHook = hook;
905
- }
906
- /** `runs.json`'s records as rows, and how many of its entries were left out. Each row's `data` is
907
- * the record's own JSON as `runs.json` held it, so nothing this cezar's schema does not know is lost
908
- * (raw-record.ts); its summary and columns come from the parsed record, which is what decoding that
909
- * JSON gives back. An entry that does not parse is skipped and costs that entry only, as an
910
- * unreadable row does once it is in the database. Undefined when the file is not a JSON array. */
911
- function legacyIndexRows(bytes) {
912
- let raw;
913
- try {
914
- raw = JSON.parse(bytes.toString('utf8'));
915
- }
916
- catch {
917
- return undefined;
918
- }
919
- if (!Array.isArray(raw))
920
- return undefined;
921
- // A hand-edited index may repeat an id; the last one won when it loaded into a map, so it still does.
922
- const rows = new Map();
923
- let skipped = 0;
924
- for (const entry of raw) {
925
- // `parseRunRecords`' salvage rewrites top-level keys: the stored JSON is taken from a copy.
926
- const stored = entry !== null && typeof entry === 'object' && !Array.isArray(entry) ? { ...entry } : entry;
927
- const parsed = parseRunRecords([entry]);
928
- if (!parsed.success) {
929
- skipped += 1;
930
- continue;
931
- }
932
- const run = parsed.data[0];
933
- rows.set(run.id, encodeRunRow(run, JSON.stringify(stored)));
934
- }
935
- return { rows: [...rows.values()], skipped, total: raw.length };
936
- }
937
- /**
938
- * Import legacy rows and the completion marker atomically, once. Recheck live-writer evidence
939
- * before commit and preserve exact input bytes in a synced backup. Leave runs.json untouched;
940
- * invalid entries are skipped and reported.
941
- */
942
- function importLegacyIndex(db, dataDir) {
943
- assertNoLegacyCockpit(dataDir);
944
- const snapshot = readLegacyIndex(join(dataDir, LEGACY_INDEX_FILE));
945
- const parsed = snapshot ? legacyIndexRows(snapshot.bytes) : undefined;
946
- const rows = parsed?.rows ?? [];
947
- const skipped = parsed?.skipped ?? 0;
948
- const source = !snapshot ? 'none' : parsed ? LEGACY_INDEX_FILE : `${LEGACY_INDEX_FILE} (unparseable)`;
949
- assertNoLegacyWriter(dataDir, snapshot);
950
- legacyImportHook?.beforeTransaction?.();
951
- let backup;
952
- const commit = db.transaction({
953
- upserts: rows,
954
- deletes: [],
955
- onlyIfMetaAbsent: RUNS_IMPORT_COMPLETE_KEY,
956
- beforeCommit: () => {
957
- legacyImportHook?.beforeCommit?.();
958
- assertNoLegacyWriter(dataDir, snapshot);
959
- backup = snapshot ? backUpLegacyIndex(dataDir, snapshot) : undefined;
960
- const read = snapshot ? { bytes: snapshot.bytes.length, sha256: snapshot.sha256, backup } : {};
961
- return { [RUNS_IMPORT_COMPLETE_KEY]: JSON.stringify({ at: new Date().toISOString(), source, records: rows.length, ...(skipped > 0 ? { skipped } : {}), ...read }) };
962
- },
963
- });
964
- // Told once, by the import that committed: the marker means no later open reads runs.json again.
965
- if (commit.skipped || backup === undefined)
966
- return;
967
- const kept = `Its exact bytes are kept in ${join(dataDir, backup)}; https://github.com/hearsay-tools/cezarion/blob/main/docs/run-history-recovery.md says how to import it after a repair.`;
968
- if (!parsed)
969
- console.warn(`[cez] ${LEGACY_INDEX_FILE} could not be read; no run was imported, and this project starts with an empty history. ${kept}`);
970
- else if (skipped > 0)
971
- console.warn(`[cez] ${skipped} of ${parsed.total} runs in ${LEGACY_INDEX_FILE} could not be read and were not imported. ${kept}`);
972
- }
973
- /**
974
- * Finished rows whose stored summary an open-time normalization would still change: a referenced
975
- * PR an older cezar's created-PR declaration erased, or issue attribution displaced by a
976
- * follow-up declaration (see `reconcileLoadedRun`). Not live, so not
977
- * in the `live` column; open decodes these few and keeps the ones it actually repaired.
978
- */
979
- const LEGACY_REFERENCE_HEAL_SQL = "(json_extract(summary, '$.markerRefs.pr') IS NOT NULL AND json_extract(summary, '$.referencedPullRequestUrl') IS NULL)" +
980
- " OR (NOT EXISTS (SELECT 1 FROM meta WHERE key = 'issue-attribution:' || runs.id AND value = CAST(runs.revision AS TEXT)) AND json_extract(summary, '$.markerRefs.issue') IS NOT NULL)";
981
- /**
982
- * Rows whose record names the automation that launched it while the stored summary does not
983
- * (hearsay-tools/cezarion#1332): summaries a cezar wrote before `RunSummary.automationId`
984
- * existed. Open rewrites each one's summary once, so the sidebar's Automations tab classifies a
985
- * finished task nobody has opened since the upgrade. `instr` keeps the JSON parse off every
986
- * other row.
987
- */
988
- const AUTOMATION_ORIGIN_HEAL_SQL = "instr(data, '\"automation') > 0 AND json_extract(summary, '$.automationId') IS NULL" +
989
- " AND (json_extract(data, '$.automation.automationId') IS NOT NULL OR json_extract(data, '$.automationTrigger.automationId') IS NOT NULL)";
990
- /** Mark-all-read's rule (see `RunStore.markAllRead`) over the columns and the stored summary. */
991
- const MARK_ALL_READ_SQL = "archived = 0 AND status IN ('done', 'failed') AND finished_at IS NOT NULL" +
992
- " AND (json_extract(summary, '$.seenAt') IS NULL OR json_extract(summary, '$.seenAt') < finished_at)";
993
- /** History retention's candidates among the given ids (a JSON array): finished, without
994
- * delegation, and not pinned. */
995
- const RETENTION_CANDIDATES_SQL = "id IN (SELECT value FROM json_each(?)) AND status NOT IN ('queued', 'running', 'waiting')" +
996
- " AND parent_run_id IS NULL AND json_extract(summary, '$.delegation') IS NULL" +
997
- " AND json_extract(summary, '$.pinned') IS NOT 1";
998
- /** Rows whose stored summary names a referenced PR or issue: what a repository handle can veto. */
999
- const REFERENCED_SQL = "json_extract(summary, '$.referencedPullRequestUrl') IS NOT NULL OR json_extract(summary, '$.referencedIssueUrl') IS NOT NULL";
1000
- /** A record as a branch owner, or undefined when it owns no branch and created no PR: the
1001
- * projection `listBranchOwners` reads off a row's summary and columns, computed from memory. */
1002
- export function branchOwnerOf(run) {
1003
- const branch = encodeRunRow(run).branch;
1004
- if (!branch && run.pullRequestUrl === undefined)
1005
- return undefined;
1006
- return {
1007
- id: run.id, title: run.title, status: run.status, archived: run.archived, createdAt: run.createdAt,
1008
- ...(branch ? { branch } : {}),
1009
- ...(run.baseBranch === undefined ? {} : { baseBranch: run.baseBranch }),
1010
- ...(run.pullRequestUrl === undefined ? {} : { pullRequestUrl: run.pullRequestUrl }),
1011
- };
1012
- }
1013
- /** The one answer every control gives for a run another cezar process owns (`409 { error }`). */
1014
- export const RUN_IN_USE_ELSEWHERE = 'run is in use by another cezar process';
1015
- /** The answer for a run this process stopped writing after a conflicting write. */
1016
- export const RUN_QUARANTINED = 'run changed under this cezar process — restart cezar to reload it';
1017
- /** A write this store must not make: another process owns the run, its owner died with work
1018
- * still live (adopt it first), or a conflict quarantined it. Nothing was changed. */
1019
- export class RunWriteRefusedError extends Error {
1020
- runId;
1021
- ownership;
1022
- constructor(runId, ownership) {
1023
- super(ownership === 'quarantined' ? `${RUN_QUARANTINED}: ${runId}`
1024
- : ownership === 'orphaned' ? `run ${runId} belongs to a cezar process that exited; take it over before writing it`
1025
- : `${RUN_IN_USE_ELSEWHERE}: ${runId}`);
1026
- this.runId = runId;
1027
- this.ownership = ownership;
1028
- this.name = 'RunWriteRefusedError';
1029
- }
1030
- }
1031
- /** How many times open (or an adoption) tries to take its claims while another connection holds
1032
- * the write lock, each waiting out the 50 ms busy timeout: recovery cannot start without them. */
1033
- const ADOPT_CLAIM_ATTEMPTS = 10;
1034
- /** The `run_claims` family of a run: a worker's parent, else the run itself (`parent_run_id ?? id`). */
1035
- function familyKey(run) {
1036
- return run.delegation?.role === 'worker' ? run.delegation.parentRunId : run.id;
1037
- }
1038
- /** The same family, off a stored row's columns. */
1039
- function rowFamily(row) {
1040
- return row.parentRunId ?? row.id;
1041
- }
1042
- /** Make `target` hold exactly `source`'s fields, keeping the object every holder references. */
1043
- function replaceRecord(target, source) {
1044
- for (const key of Object.keys(target))
1045
- if (!(key in source))
1046
- delete target[key];
1047
- Object.assign(target, source);
1048
- }
1049
- /**
1050
- * A worker's destroy moving between two unfinished phases, and nothing else changing: nothing the
1051
- * family reconcile reads changed, so it may skip that pass (#880). The first request and the
1052
- * `complete` phase still reconcile: one changes delivery eligibility, the other settles requests.
1053
- */
1054
- function isDestroyProgress(before, after) {
1055
- if (before?.role !== 'worker' || after.role !== 'worker' || !before.destroy || !after.destroy)
1056
- return false;
1057
- if (before.destroy.phase === 'complete' || after.destroy.phase === 'complete')
1058
- return false;
1059
- return isDeepStrictEqual({ ...before, destroy: undefined }, { ...after, destroy: undefined });
1060
- }
1061
- /**
1062
- * Two collected worker results carry the same evidence: equal but for when they were observed and
1063
- * which snapshot file holds them, and, with `ignoreCleanup`, the cleanup phase. A retried destroy
1064
- * that observed nothing new then rewrites and fsyncs nothing (hearsay-tools/cezarion#879).
1065
- */
1066
- function sameWorkerResult(a, b, opts) {
1067
- const comparable = (value) => ({ ...value, observedAt: undefined, ...(opts.ignoreCleanup ? { cleanup: undefined } : {}),
1068
- diff: value.diff.state === 'available' ? { ...value.diff, snapshotId: undefined, path: undefined } : value.diff });
1069
- return isDeepStrictEqual(comparable(a), comparable(b));
1070
- }
1071
- /** NDJSON transcript text to events; a damaged line is skipped, never fatal. */
1072
- function parseEvents(raw) {
1073
- return raw
1074
- .split('\n')
1075
- .filter(Boolean)
1076
- .map((line) => {
1077
- try {
1078
- return JSON.parse(line);
1079
- }
1080
- catch {
1081
- return null;
1082
- }
1083
- })
1084
- .filter((e) => e !== null);
1085
- }
1086
- function newestFirst(a, b) {
1087
- if (a.createdAt !== b.createdAt)
1088
- return a.createdAt < b.createdAt ? 1 : -1;
1089
- return a.seq < b.seq ? -1 : a.seq > b.seq ? 1 : 0;
1090
- }
1091
- /** An archived page's cursor: the last row's order, opaque to clients. A held run with no row yet
1092
- * lists after every row (`seq` is infinite), which JSON cannot carry, so it travels as null. */
1093
- function encodeArchivedCursor(key) {
1094
- return Buffer.from(JSON.stringify({ c: key.createdAt, s: Number.isFinite(key.seq) ? key.seq : null })).toString('base64url');
1095
- }
1096
- function decodeArchivedCursor(cursor) {
1097
- try {
1098
- const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
1099
- if (typeof parsed !== 'object' || parsed === null)
1100
- return undefined;
1101
- const { c, s } = parsed;
1102
- if (typeof c !== 'string' || !(s === null || (typeof s === 'number' && Number.isInteger(s))))
1103
- return undefined;
1104
- return { createdAt: c, seq: s ?? Number.POSITIVE_INFINITY };
1105
- }
1106
- catch {
1107
- return undefined;
1108
- }
1109
- }
1110
- /** The items newest first, each by the order beside it. Stable: ties keep their input order. */
1111
- function sortNewestFirst(entries) {
1112
- return [...entries].sort(([, a], [, b]) => newestFirst(a, b)).map(([item]) => item);
1113
- }
1114
- /** The delegation family a run belongs to, by its root's id: a root is its own, a worker its
1115
- * parent's. Workers cannot delegate, so a family is one root and its direct workers, never more. */
1116
- function familyRootOf(run) {
1117
- if (run.delegation?.role === 'root')
1118
- return run.id;
1119
- if (run.delegation?.role === 'worker')
1120
- return run.delegation.parentRunId;
1121
- return undefined;
1122
- }
1123
- /** Tests freeze the copies of cold runs, so an in-place write to one throws instead of vanishing. */
1124
- function deepFreeze(value) {
1125
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
1126
- Object.freeze(value);
1127
- for (const child of Object.values(value))
1128
- deepFreeze(child);
1129
- }
1130
- return value;
1131
- }
1132
- const WORKER_PROCESS_CAP = 32;
1133
- const recordedProcessSchema = z.object({ pid: z.number().int().positive(), startToken: z.string().min(1).max(128).optional(),
1134
- pgid: z.number().int().positive().optional() }).strict();
1135
- const workerProcessRecordSchema = z.object({ generation: z.string().uuid(), controller: recordedProcessSchema,
1136
- processes: z.array(recordedProcessSchema).max(WORKER_PROCESS_CAP) }).strict();
1137
- const startToken = (pid) => { const token = processStartToken(pid); return token === undefined ? {} : { startToken: token }; };
1138
- /**
1139
- * Run rows in runs.db plus append-only NDJSON events and an in-process event bus. Hold live,
1140
- * pinned, related and unsettled records only. Optimistic writes debounce; durable commits
1141
- * publish after persistence. Family claims fence every write.
1142
- */
1143
- export class RunStore extends EventEmitter {
1144
- dataDir;
1145
- /** The held set: every record this store keeps in memory, by id. */
1146
- held = new Map();
1147
- /** Who holds a run beyond its record, by holder, so one holder's unpin never releases another. */
1148
- pins = new Map();
1149
- /** Staged ids while a durable commit installs and announces them: never evicted mid-commit. */
1150
- committing = new Set();
1151
- saveTimer = null;
1152
- /** `null` once the store is closed, and in a `RunStore.unavailable` store (nothing is written,
1153
- * nothing is evicted). */
1154
- db = null;
1155
- /** Why `open` failed, in a `RunStore.unavailable` store. */
1156
- openFailure;
1157
- /** Runs whose held record is ahead of its row; the next save or commit writes them. */
1158
- dirty = new Set();
1159
- /** Runs gone from memory whose rows the next save or commit deletes. */
1160
- deleted = new Set();
1161
- /** Deleted runs whose history files (events, handoff, images, artifacts) go once the delete of
1162
- * their row commits: until then a conflict can undo the delete and bring the row back. */
1163
- historyOwed = new Set();
1164
- /** The repository this project IS (#945), armed after `open()` by `setRepoHandle`. Undefined
1165
- * until it arrives and `null` when it cannot be known — both mean "unscoped", which is
1166
- * exactly the pre-#945 behavior. */
1167
- repoHandle;
1168
- /** `open()`'s `keepLive`, which a run read later from `runs.db` is reconciled with too. */
1169
- keepLive = false;
1170
- /** This store's identity in `run_claims`; undefined without a database. */
1171
- owner;
1172
- /** The families this store claims, with the generation each acquisition got. */
1173
- claimed = new Map();
1174
- /** Families judged free whose claim a busy database kept this store from taking: the next write
1175
- * of their rows takes it in its own transaction, if it is still as judged (null: absent). */
1176
- pendingClaims = new Map();
1177
- /** The revision and `data` of each held row (and pending deletion) as this store last read or
1178
- * wrote it: what a write is fenced against, and a conflict's "original". No entry: this store
1179
- * created the row and has not written it yet. `extras` is what that `data` holds beyond the
1180
- * schema, which the next write of the row puts back (raw-record.ts). */
1181
- base = new Map();
1182
- /** Rows read cold in the current synchronous turn, so a commit staged from one is fenced against
1183
- * the version it was computed from. `owned`: its family was already this store's when read.
1184
- * Cleared at the next microtask: no commit spans a turn. */
1185
- coldBase = new Map();
1186
- /** The family of each pending deletion, whose claim the deleting write is fenced against. */
1187
- deletedFamilies = new Map();
1188
- /** Rows a conflicting write excluded: this store refuses to write them until it is reopened. */
1189
- quarantined = new Set();
1190
- /** Rows whose `data` this store tried to decode and could not: left in the database untouched,
1191
- * and left out of the list rows from then on, as the cold reader leaves them out (run-index.ts). */
1192
- unreadable = new Set();
1193
- /** Background one-at-a-time compressor for archived transcripts (#818). */
1194
- compressor;
1195
- /** Transcript facts the delegation paths ask about, so they never re-read a transcript (#880). */
1196
- facts;
1197
- liveItems = new LiveItemSnapshots();
1198
- /** Capture both sources on the same synchronous sequence boundary before history IO. */
1199
- liveReadSnapshot(runId) {
1200
- return { events: this.liveItems.read(runId), throughSeq: this.seqs.get(runId) ?? Infinity };
1201
- }
1202
- constructor(dataDir) {
1203
- super();
1204
- this.dataDir = dataDir;
1205
- this.setMaxListeners(100);
1206
- this.facts = new TranscriptFactsIndex(dataDir);
1207
- this.compressor = new HistoryCompressor(dataDir, (id) => this.isHistoryCompressEligible(id), (id, plain, archive) => this.facts.adoptArchive(id, plain, stampOf(archive)));
1208
- }
1209
- /**
1210
- * Open the project's run store. See `reconcileLoadedRun` for what `keepLive` (#367) decides
1211
- * about live-looking rows.
1212
- *
1213
- * Reads `runs.db` once its import is complete. Before that, `runs.json` is imported into it in
1214
- * one transaction (`importLegacyIndex`) and left exactly as it was, for older cezars to read.
1215
- * Either way only the held set is decoded: the live rows (by the indexed `live` column), the
1216
- * few finished rows a normalization still repairs, and the delegation families of the live
1217
- * ones.
1218
- *
1219
- * A store that cannot be opened is never an empty one (#779, plan step 4): `open` throws a
1220
- * `RunStoreOpenError` naming the cause, and nothing is reset, restored or deleted. `retryBusy`
1221
- * waits out a busy database (and a cockpit that may still be importing) with growing pauses,
1222
- * about 3.5 s in all, before it gives up. Open is synchronous, so the wait blocks this thread:
1223
- * only a boot passes it, while nothing else runs yet. Without it a busy database fails after
1224
- * one busy timeout.
1225
- */
1226
- static open(dataDir, opts) {
1227
- const path = join(dataDir, RUNS_DB_FILE);
1228
- const delays = opts?.retryBusy ? OPEN_RETRY_DELAYS_MS : [];
1229
- const started = Date.now();
1230
- for (let attempt = 0;; attempt++) {
1231
- try {
1232
- return RunStore.openOnce(dataDir, path, opts?.keepLive === true, opts?.maintenance === true);
1233
- }
1234
- catch (error) {
1235
- const transient = error instanceof RunDatabaseBusyError || (error instanceof LegacyWriterError && error.reason === 'cockpit');
1236
- if (!transient || attempt >= delays.length) {
1237
- throw toRunStoreOpenError(error, path, attempt > 0 ? { waitedMs: Date.now() - started } : {});
1238
- }
1239
- sleepSync(delays[attempt]);
1240
- }
1241
- }
1242
- }
1243
- static openOnce(dataDir, path, keepLive, maintenance) {
1244
- mkdirSync(join(dataDir, 'runs'), { recursive: true });
1245
- const store = new RunStore(dataDir);
1246
- store.keepLive = keepLive;
1247
- const db = RunDatabase.open(path);
1248
- try {
1249
- if (db.getMeta(RUNS_IMPORT_COMPLETE_KEY) === undefined)
1250
- importLegacyIndex(db, dataDir);
1251
- store.db = db;
1252
- store.owner = openClaimSession();
1253
- if (!maintenance) {
1254
- store.loadHeldRows();
1255
- store.warmTranscriptFacts();
1256
- }
1257
- }
1258
- catch (error) {
1259
- if (store.owner) {
1260
- try {
1261
- db.releaseClaims(store.owner.session);
1262
- }
1263
- catch { /* the session closes below: its claims are provably dead */ }
1264
- closeClaimSession(store.owner.session);
1265
- }
1266
- store.owner = undefined;
1267
- store.db = null;
1268
- store.held.clear();
1269
- store.dirty.clear();
1270
- store.claimed.clear();
1271
- store.base.clear();
1272
- db.close();
1273
- throw error;
1274
- }
1275
- return store;
1276
- }
1277
- /**
1278
- * The store `serve` keeps for its boot project when `open` failed: no database, nothing held,
1279
- * and every attempt to create or save a run refused with `failure`. The cockpit answers every
1280
- * route of that project with `failure`'s message, and boot skips everything that would read
1281
- * its empty run list as "no runs" (orphan pruning, retention, recovery, scratch sweeps). The
1282
- * way out is a restart once the cause is gone.
1283
- */
1284
- static unavailable(dataDir, failure) {
1285
- const store = new RunStore(dataDir);
1286
- store.openFailure = failure;
1287
- return store;
1288
- }
1289
- /** Why this store has no database, when it is `RunStore.unavailable`'s: its runs are unknown,
1290
- * not absent. */
1291
- get unavailable() {
1292
- return this.openFailure;
1293
- }
1294
- /**
1295
- * Open-time load: the live rows, the finished rows a load normalization repairs, then the
1296
- * delegation families of the live ones. A row that does not parse is skipped and left in the
1297
- * database untouched; one warning says how many.
1298
- *
1299
- * Only rows this store can claim are loaded (#779, plan step 3). A live row whose family another
1300
- * live process claims — `serve`'s parked run, seen by a headless `cez run` — is that process's:
1301
- * it is not loaded, normalized or recovered here, and stays readable through `getRun` and the
1302
- * list rows. A live row nobody alive claims is taken over, as before: this open recovers it
1303
- * (`keepLive`) or settles it as interrupted.
1304
- */
1305
- loadHeldRows() {
1306
- let unreadable = 0;
1307
- const decode = (row) => {
1308
- const decoded = decodeRunRow(row.data);
1309
- if (!decoded) {
1310
- unreadable++;
1311
- this.unreadable.add(row.id);
1312
- }
1313
- return decoded;
1314
- };
1315
- const live = this.db.listLive();
1316
- const owned = this.claimFamilies(live.map(rowFamily), { allowLive: true, wait: true });
1317
- for (const row of live) {
1318
- if (!owned.has(rowFamily(row)))
1319
- continue;
1320
- const decoded = decode(row);
1321
- if (decoded)
1322
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive }, row);
1323
- }
1324
- const heal = this.db.listWhere(LEGACY_REFERENCE_HEAL_SQL).filter((row) => !this.held.has(row.id));
1325
- const healable = this.claimFamilies(heal.map(rowFamily));
1326
- for (const row of heal) {
1327
- if (!healable.has(rowFamily(row)))
1328
- continue;
1329
- const decoded = decode(row);
1330
- // Held only when the repair changed it: the next save writes it, then it leaves.
1331
- if (decoded) {
1332
- // Persist verification once even when legacy issue attribution was already correct.
1333
- const needsIssueCheck = decoded.run.markerRefs?.issue !== undefined &&
1334
- this.db.getMeta(`issue-attribution:${row.id}`) !== String(row.revision);
1335
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive, onlyIfChanged: !needsIssueCheck }, row);
1336
- if (needsIssueCheck)
1337
- this.dirty.add(row.id);
1338
- }
1339
- }
1340
- const stale = this.db.listWhere(AUTOMATION_ORIGIN_HEAL_SQL).filter((row) => !this.held.has(row.id));
1341
- const restamp = this.claimFamilies(stale.map(rowFamily));
1342
- for (const row of stale) {
1343
- if (!restamp.has(rowFamily(row)))
1344
- continue;
1345
- const decoded = decode(row);
1346
- // Nothing in the record changes, only its summary: held dirty, the next save rewrites it.
1347
- if (decoded) {
1348
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive }, row);
1349
- this.dirty.add(row.id);
1350
- }
1351
- }
1352
- for (const rootId of this.anchoredFamilies())
1353
- this.holdFamily(rootId, decode);
1354
- this.releaseUnheldClaims();
1355
- if (unreadable > 0)
1356
- console.warn(`[cez] ${unreadable} run(s) in ${RUNS_DB_FILE} could not be read; they are left in the database untouched.`);
1357
- }
1358
- /** Normalize a record just read from `row` (see `reconcileLoadedRun`) and hold it. Marks the row
1359
- * dirty only when normalization changed it, so the next save persists exactly the runs open()
1360
- * rewrote. A row read up from schema-3 wait fields counts as changed: its rewrite drops them
1361
- * and recomputes its summary and live column (`upgradeLegacyWaits`). The caller has claimed
1362
- * the row's family. */
1363
- adoptLoadedRun({ run, extras, upgraded }, opts, row) {
1364
- const before = loadNormalizedFields(run);
1365
- if (opts.settle)
1366
- settleOrphanedRun(run, { stop: opts.stop });
1367
- else
1368
- reconcileLoadedRun(run, opts);
1369
- const changed = upgraded === true || loadNormalizedFields(run) !== before;
1370
- if (opts.onlyIfChanged && !changed)
1371
- return;
1372
- this.held.set(run.id, run);
1373
- this.base.set(run.id, { revision: row.revision, seq: row.seq, data: row.data, extras });
1374
- if (changed)
1375
- this.dirty.add(run.id);
1376
- }
1377
- /**
1378
- * Hold one delegation family: its root and the root's direct workers, read through the
1379
- * `parent_run_id` index. No recursion: workers cannot delegate, so a worker's own id never
1380
- * names a family. The caller has claimed it. `settle` settles its live rows instead of keeping
1381
- * them for recovery (`settleOrphanedRun`); `stopId` is the run a Stop settles as cancelled.
1382
- */
1383
- holdFamily(rootId, decode = (row) => decodeRunRow(row.data), settle = false, stopId) {
1384
- const rows = [this.db.get(rootId), ...this.db.listByParent(rootId)];
1385
- for (const row of rows) {
1386
- if (!row || this.held.has(row.id) || this.deleted.has(row.id))
1387
- continue;
1388
- const decoded = decode(row);
1389
- if (decoded)
1390
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive, settle, stop: row.id === stopId }, row);
1391
- }
1392
- }
1393
- /**
1394
- * Make sure this store claims each of `families`, taking every one no live process holds, and
1395
- * return the ones it now holds. Liveness is judged here (`claimOwnerLive`), outside the write
1396
- * transaction; `takeClaims` then takes a claim only if it is still exactly what was judged.
1397
- *
1398
- * `allowLive` also takes a family that still has a live row although no live process owns it.
1399
- * Open and `adoptFamily` pass it, because recovery follows both, and so does a write moving a
1400
- * run this store holds into a new family (a worker quarantined to `invalid` becomes its own):
1401
- * an ordinary write must not quietly inherit a dead process's live run and leave it unrecovered.
1402
- * `wait` retries a busy database instead of leaving the claim to the next write: recovery
1403
- * cannot start without it.
1404
- */
1405
- claimFamilies(families, opts = {}) {
1406
- const owned = new Set();
1407
- const wanted = [];
1408
- for (const family of new Set(families)) {
1409
- if (this.claimed.has(family) || this.pendingClaims.has(family))
1410
- owned.add(family);
1411
- else
1412
- wanted.push(family);
1413
- }
1414
- if (!this.db || !this.owner || wanted.length === 0)
1415
- return owned;
1416
- const claims = this.db.getClaims(wanted);
1417
- const take = [];
1418
- for (const family of wanted) {
1419
- const claim = claims.get(family);
1420
- if (claim && claimOwnerLive(claim))
1421
- continue;
1422
- if (!opts.allowLive && this.db.familyHasLive(family))
1423
- continue;
1424
- take.push({ family, expect: claim ? { session: claim.session, generation: claim.generation } : null });
1425
- }
1426
- if (take.length === 0)
1427
- return owned;
1428
- let taken;
1429
- try {
1430
- taken = this.takeClaims(take, opts.wait ? ADOPT_CLAIM_ATTEMPTS : 1);
1431
- }
1432
- catch (error) {
1433
- if (!(error instanceof RunDatabaseBusyError))
1434
- throw error;
1435
- // Recovery follows an adoption, so it must hold the claim first: those families stay
1436
- // unclaimed and orphaned (a control or the next restart adopts them). A write does not wait:
1437
- // its next transaction takes the claim (`fence`), or meets whoever took it meanwhile.
1438
- if (opts.wait)
1439
- return owned;
1440
- for (const { family, expect } of take) {
1441
- this.pendingClaims.set(family, expect);
1442
- owned.add(family);
1443
- }
1444
- this.scheduleSave();
1445
- return owned;
1446
- }
1447
- for (const [family, generation] of taken) {
1448
- this.claimed.set(family, generation);
1449
- owned.add(family);
1450
- }
1451
- // A claim taken for a write that then changes nothing still leaves at the next sweep.
1452
- if (taken.size > 0)
1453
- this.scheduleSave();
1454
- return owned;
1455
- }
1456
- /** `takeClaims`, retried while another connection holds the write lock (each try waits out the
1457
- * busy timeout), then the busy error. */
1458
- takeClaims(take, attempts) {
1459
- for (let attempt = 1;; attempt++) {
1460
- try {
1461
- return this.db.takeClaims(this.owner, take);
1462
- }
1463
- catch (error) {
1464
- if (!(error instanceof RunDatabaseBusyError) || attempt >= attempts)
1465
- throw error;
1466
- }
1467
- }
1468
- }
1469
- /** Release the claim of every family with nothing left in memory, once nothing is pending: a
1470
- * failed save keeps its families claimed until it succeeds. A failed release retries at the
1471
- * next sweep; `close()` releases the rest. */
1472
- releaseUnheldClaims() {
1473
- if (!this.db || !this.owner || this.dirty.size > 0 || this.deleted.size > 0)
1474
- return;
1475
- const kept = new Set();
1476
- for (const run of this.held.values())
1477
- kept.add(familyKey(run));
1478
- // A claim never taken has nothing to release in the database.
1479
- for (const family of this.pendingClaims.keys())
1480
- if (!kept.has(family))
1481
- this.pendingClaims.delete(family);
1482
- const released = [...this.claimed.keys()].filter((family) => !kept.has(family));
1483
- if (released.length === 0)
1484
- return;
1485
- try {
1486
- this.db.releaseClaims(this.owner.session, released);
1487
- for (const family of released)
1488
- this.claimed.delete(family);
1489
- }
1490
- catch {
1491
- // Busy or failing: the next sweep tries again.
1492
- }
1493
- }
1494
- /**
1495
- * Who may change this run right now (see `RunOwnership`), or undefined when there is no such
1496
- * run. Read-only: nothing is claimed. Controls ask this first, so a run another process owns is
1497
- * refused with `RUN_IN_USE_ELSEWHERE` and a dead process's run is adopted before it is changed.
1498
- */
1499
- runOwnership(id) {
1500
- if (this.quarantined.has(id))
1501
- return 'quarantined';
1502
- const held = this.held.get(id);
1503
- if (!this.db)
1504
- return held ? 'held' : undefined;
1505
- const family = held ? familyKey(held) : this.deleted.has(id) ? undefined : this.db.familyOf(id);
1506
- if (family === undefined)
1507
- return undefined;
1508
- if (this.claimed.has(family) || this.pendingClaims.has(family))
1509
- return 'held';
1510
- const claim = this.db.getClaim(family);
1511
- if (claim && claimOwnerLive(claim))
1512
- return 'foreign';
1513
- // The same rule `claimFamilies` writes by: a dead owner left only settled runs → free.
1514
- return this.db.familyHasLive(family) ? 'orphaned' : 'free';
1515
- }
1516
- /** Why a control on this run must be refused here, or undefined when this store may change it. */
1517
- writeRefusal(id) {
1518
- const ownership = this.runOwnership(id);
1519
- if (ownership === 'quarantined')
1520
- return RUN_QUARANTINED;
1521
- return ownership === 'foreign' || ownership === 'orphaned' ? RUN_IN_USE_ELSEWHERE : undefined;
1522
- }
1523
- /**
1524
- * Claim an orphaned family and settle its live rows before a control acts. Stop cancels its
1525
- * target. Return the root id, or undefined for a live owner or missing run; adoption never
1526
- * resumes work.
1527
- */
1528
- adoptFamily(id, opts = {}) {
1529
- const family = this.db?.familyOf(id);
1530
- if (family === undefined || !this.claimFamilies([family], { allowLive: true, wait: true }).has(family))
1531
- return undefined;
1532
- this.holdFamily(family, undefined, true, opts.stop ? id : undefined);
1533
- return family;
1534
- }
1535
- /** Every run whose family another process owns — alive, or dead with a live run left to
1536
- * recover (cleanup keeps their scratch: it is theirs, or recovery's once someone adopts them).
1537
- * A dead owner's claim on a family with nothing live is no claim (see `runOwnership`). */
1538
- listForeignClaimedRunIds() {
1539
- const db = this.db, owner = this.owner;
1540
- if (!db || !owner)
1541
- return [];
1542
- const kept = new Set(db.listClaims().filter((claim) => claim.session !== owner.session &&
1543
- (claimOwnerLive(claim) || db.familyHasLive(claim.family))).map((claim) => claim.family));
1544
- return kept.size === 0 ? [] : db.listForeignClaimedIds(owner.session).filter((row) => kept.has(row.family)).map((row) => row.id);
1545
- }
1546
- /**
1547
- * Whether a held run anchors itself (and its family) in memory. Anything else held is a family
1548
- * member or a settled write, and leaves at the next sweep (`evictSettled`).
1549
- *
1550
- * The held set is: every run that is live (`isLiveRecord`), pinned by a RunManager (`pin`),
1551
- * dirty, or inside a durable commit; plus the whole delegation family (root and direct
1552
- * workers) of any such run. Families are held because the RunManager reads a live run's family
1553
- * on every run event — `GET /runs/:id/relationships`, the global `reconcileWorkerWaits` pass
1554
- * (about twenty call sites), completion blockers and conversations — and decoding a cold
1555
- * record costs about 200 µs (JSON.parse plus the schema). Measured on a copy of a real
1556
- * cockpit's `runs.json` (958 runs, 957 of them delegated): a running root with 26 workers
1557
- * paid about 5 ms per family read, and the live families together about 10 ms per global
1558
- * pass, all on the event loop. Holding them costs memory in proportion to active work, not to
1559
- * history.
1560
- */
1561
- isAnchor(id, run) {
1562
- return isLiveRecord(run) || this.pins.has(id) || this.dirty.has(id) || this.committing.has(id);
1563
- }
1564
- /** The family roots with an anchoring member in memory. */
1565
- anchoredFamilies() {
1566
- const roots = new Set();
1567
- for (const [id, run] of this.held) {
1568
- const root = familyRootOf(run);
1569
- if (root !== undefined && this.isAnchor(id, run))
1570
- roots.add(root);
1571
- }
1572
- return roots;
1573
- }
1574
- /** Drop every held run that is neither an anchor nor in an anchored family. A store without a
1575
- * database keeps everything: memory is the only copy it has. */
1576
- evictSettled() {
1577
- if (!this.db)
1578
- return;
1579
- const families = this.anchoredFamilies();
1580
- for (const [id, run] of this.held) {
1581
- if (this.isAnchor(id, run))
1582
- continue;
1583
- const root = familyRootOf(run);
1584
- if (root !== undefined && families.has(root))
1585
- continue;
1586
- this.held.delete(id);
1587
- this.base.delete(id);
1588
- }
1589
- this.releaseUnheldClaims();
1590
- }
1591
- /** A run read from `runs.db`, normalized like a loaded one (`reconcileLoadedRun`, then the
1592
- * repository scope) but held by nobody. Undefined when absent, deleted or unreadable. */
1593
- loadCold(id) {
1594
- if (!this.db || this.deleted.has(id))
1595
- return undefined;
1596
- const row = this.db.get(id);
1597
- return row ? this.decodeCold(row) : undefined;
1598
- }
1599
- decodeCold(row) {
1600
- const decoded = decodeRunRow(row.data);
1601
- if (!decoded) {
1602
- this.unreadable.add(row.id);
1603
- return undefined;
1604
- }
1605
- this.unreadable.delete(row.id);
1606
- const { run, extras } = decoded;
1607
- if (this.coldBase.size === 0)
1608
- queueMicrotask(() => this.coldBase.clear());
1609
- const family = rowFamily(row);
1610
- this.coldBase.set(row.id, { revision: row.revision, seq: row.seq, data: row.data, extras, owned: this.claimed.has(family) || this.pendingClaims.has(family) });
1611
- reconcileLoadedRun(run, { keepLive: this.keepLive });
1612
- rescopeRun(run, this.repoHandle);
1613
- return run;
1614
- }
1615
- /** Hold a run just decoded from its row: the object every later read and write shares. */
1616
- holdDecoded(run) {
1617
- const read = this.coldBase.get(run.id);
1618
- this.held.set(run.id, run);
1619
- if (read)
1620
- this.base.set(run.id, storedRow(read));
1621
- return run;
1622
- }
1623
- /**
1624
- * Bring a run into memory and return the held object: the record a write changes in place.
1625
- * It leaves again at the first sweep after its write settles, unless something anchors it.
1626
- * Its family is claimed first, then the row is read, so the version held is the claimed one;
1627
- * undefined while another process owns it (see `claimFamilies`).
1628
- */
1629
- hold(id) {
1630
- const held = this.held.get(id);
1631
- if (held)
1632
- return held;
1633
- const family = this.db && !this.deleted.has(id) ? this.db.familyOf(id) : undefined;
1634
- if (family === undefined || !this.claimFamilies([family]).has(family))
1635
- return undefined;
1636
- const run = this.loadCold(id);
1637
- if (!run)
1638
- return undefined;
1639
- this.holdDecoded(run);
1640
- this.scheduleSave();
1641
- return run;
1642
- }
1643
- /** The record a store write changes in place: held, or loaded to be. Undefined for a run this
1644
- * store may not write (another process's, or quarantined), so the write changes nothing. */
1645
- record(id) {
1646
- if (this.quarantined.has(id))
1647
- return undefined;
1648
- return this.held.get(id) ?? this.hold(id);
1649
- }
1650
- /** The current record for reading: the held object, the held copy of a run whose family is in
1651
- * memory, or else a fresh copy nobody holds. */
1652
- peek(id) {
1653
- const held = this.held.get(id);
1654
- if (held)
1655
- return held;
1656
- const run = this.loadCold(id);
1657
- return run && this.answerCold(run, false);
1658
- }
1659
- /**
1660
- * A run just read off its row, as reads answer it: held when its family is in memory (a live
1661
- * family's members are read on every run event), else a copy nobody holds — frozen under
1662
- * vitest when it leaves the store (`freeze`).
1663
- */
1664
- answerCold(run, freeze) {
1665
- const root = familyRootOf(run);
1666
- if (root !== undefined && this.anchoredFamilies().has(root))
1667
- return this.holdDecoded(run);
1668
- return freeze && process.env.VITEST ? deepFreeze(run) : run;
1669
- }
1670
- /** `getRun` for a row a query already read: the held object, else decoded from `row`. */
1671
- fromRow(row) {
1672
- const held = this.held.get(row.id);
1673
- if (held)
1674
- return held;
1675
- if (this.deleted.has(row.id))
1676
- return undefined;
1677
- const run = this.decodeCold(row);
1678
- return run && this.answerCold(run, true);
1679
- }
1680
- /** Whether the run exists, held or not, without decoding it. */
1681
- hasRun(id) {
1682
- return this.held.has(id) || (!!this.db && !this.deleted.has(id) && this.db.has(id));
1683
- }
1684
- /**
1685
- * Keep a run in memory for `holder` until `unpin(id, holder)`: a RunManager pins the runs it is
1686
- * executing (`active`) and the run a Continue is admitting (`continue`). A finished run is
1687
- * loaded. Pins are per holder, so releasing one never releases another. Returns the held record.
1688
- */
1689
- pin(id, holder) {
1690
- const run = this.record(id);
1691
- if (!run)
1692
- return undefined;
1693
- let holders = this.pins.get(id);
1694
- if (!holders)
1695
- this.pins.set(id, holders = new Set());
1696
- holders.add(holder);
1697
- return run;
1698
- }
1699
- /** Publish a run's current record again without a write: something read beside the record
1700
- * changed, such as the run leaving the manager's live registries, which a detail's finish
1701
- * verdict reads (hearsay-tools/cezarion#1301). */
1702
- republish(id) {
1703
- const run = this.peek(id);
1704
- if (run)
1705
- this.emit('run', run, 'live-release');
1706
- }
1707
- /** Release `holder`'s pin. The run leaves memory at the next sweep once nothing else holds it. */
1708
- unpin(id, holder) {
1709
- const holders = this.pins.get(id);
1710
- if (!holders?.delete(holder))
1711
- return;
1712
- if (holders.size === 0)
1713
- this.pins.delete(id);
1714
- this.sweepIfSettled([id]);
1715
- }
1716
- /**
1717
- * Set discovered repository identity without blocking boot. Recompute conclusions from retained
1718
- * evidence, including cold records; null retains unknown-handle behavior.
1719
- */
1720
- setRepoHandle(handle) {
1721
- this.repoHandle = handle;
1722
- if (!handle)
1723
- return; // nothing to prove foreign against
1724
- // `touch` per healed run: the cockpit is already live when the handle lands, so a corrected
1725
- // chip has to reach the open page over SSE, not just the next `runs.json` write.
1726
- let healed = false;
1727
- const own = `${handle.owner}/${handle.name}`.toLowerCase();
1728
- const foreign = (url) => url !== undefined && refUrlRepo(url) !== own;
1729
- const stored = this.db?.listWhere(REFERENCED_SQL).filter((row) => {
1730
- if (this.held.has(row.id) || this.deleted.has(row.id))
1731
- return false;
1732
- const summary = parseStoredSummary(row.summary);
1733
- return !summary || foreign(summary.referencedPullRequestUrl) || foreign(summary.referencedIssueUrl);
1734
- }) ?? [];
1735
- for (const run of [...this.held.values()]) {
1736
- if (rescopeRun(run, this.repoHandle)) {
1737
- this.touch(run);
1738
- healed = true;
1739
- }
1740
- }
1741
- // Only rows this store may write: another process's runs heal when their owner arms its handle.
1742
- const writable = this.claimFamilies(stored.map(rowFamily));
1743
- for (const row of stored) {
1744
- if (!writable.has(rowFamily(row)))
1745
- continue;
1746
- const run = this.decodeCold(row);
1747
- // `decodeCold` already scoped it with the handle just armed; write it when that changed it.
1748
- if (!run || !this.storedScopeDiffers(row, run))
1749
- continue;
1750
- this.holdDecoded(run);
1751
- this.touch(run);
1752
- healed = true;
1753
- }
1754
- // Discovery may finish after headless shutdown's final flush. Persist repairs now: the
1755
- // debounced save is unref'd, so it cannot keep the CLI alive once the lookup completes.
1756
- if (healed)
1757
- this.flush();
1758
- }
1759
- /** Whether the stored summary still names a reference the scoped record no longer has. */
1760
- storedScopeDiffers(row, run) {
1761
- const summary = parseStoredSummary(row.summary);
1762
- return summary?.referencedPullRequestUrl !== run.referencedPullRequestUrl ||
1763
- summary?.referencedIssueUrl !== run.referencedIssueUrl || summary?.issueNumber !== run.issueNumber;
1764
- }
1765
- /**
1766
- * The live set, newest first: runs whose record is live (`isLiveRecord`) or that a RunManager
1767
- * pins. Finished runs are not here — read one by id (`getRun`), by an indexed query
1768
- * (`listWorkersOf`, `findRunByClientRequestId`, `listRunsWithWorktree`,
1769
- * `listBranchOwners`), or as list rows (`listRunSummaries`).
1770
- */
1771
- listRuns() {
1772
- return sortNewestFirst([...this.held].filter(([id, run]) => isLiveRecord(run) || this.pins.has(id)).map(([, run]) => [run, this.listOrder(run)]));
1773
- }
1774
- /** Where a held run lists: its row's insertion order, or after every row while this store has
1775
- * not written it yet. The held set keeps such runs in creation order, and so does every list
1776
- * that sorts them in held-set order (`sortNewestFirst` is stable). */
1777
- listOrder(run) {
1778
- return { createdAt: run.createdAt, seq: this.base.get(run.id)?.seq ?? Number.POSITIVE_INFINITY };
1779
- }
1780
- /**
1781
- * EVERY run as a full record, newest first — decoded row by row. Only the legacy `GET /runs`
1782
- * (older clients; the cockpit reads `GET /run-summaries`) may call this: it is exactly the
1783
- * whole-history parse #779 exists to remove from everything else.
1784
- */
1785
- listAllRunsForLegacyRoute() {
1786
- const runs = new Map();
1787
- for (const row of this.db?.listAll() ?? []) {
1788
- if (this.deleted.has(row.id) || this.held.has(row.id))
1789
- continue;
1790
- const run = this.decodeCold(row);
1791
- if (run)
1792
- runs.set(row.id, [run, row]);
1793
- }
1794
- for (const [id, run] of this.held)
1795
- runs.set(id, [run, this.listOrder(run)]);
1796
- return sortNewestFirst(runs.values());
1797
- }
1798
- /** A bounded page of discoverable peer roots, including the current held overlay. */
1799
- listPeerTaskSummaries(options) {
1800
- return listPeerTaskSummaries({ db: this.db, held: this.held, skipped: this.deleted,
1801
- order: run => this.listOrder(run), cold: id => this.coldSummary(id) }, options);
1802
- }
1803
- /**
1804
- * Every run as its list row, newest first: the stored `summary` column, with each held run's
1805
- * own projection laid over it — a debounced save keeps memory up to 300 ms ahead of the row,
1806
- * and a run created since the last save has no row yet. `usage` is the caller's to attach.
1807
- *
1808
- * With `archivedWindow` (#864), the window the cockpit's lists read: every unarchived run, plus
1809
- * the newest `archivedWindow` archived ROOT runs, and whether older archived roots were left
1810
- * out. Archived workers are never in it (see `RunDatabase.listWindowSummaries`); with `roots`,
1811
- * no worker is — the runs index, whose readers list no workers. A held run
1812
- * lists by its record, so one archived or unarchived since the last save is ranked as it is now.
1813
- *
1814
- * A row this store found unreadable is left out, as the cold reader leaves out a row it had to
1815
- * decode and could not. A finished row nobody has decoded is served from its summary by both,
1816
- * which decodes nothing; reading it is what finds out (`isUnreadable`).
1817
- */
1818
- listRunSummaries(options = {}) {
1819
- const { archivedWindow, roots = false } = options;
1820
- // Every skipped row may be an archived root, so ask for that many more: one past the window
1821
- // after skipping is how "older ones were left out" is known without counting them.
1822
- const rows = (archivedWindow === undefined
1823
- ? this.db?.listSummaries()
1824
- : this.db?.listWindowSummaries(archivedWindow + 1 + this.deleted.size + this.unreadable.size + this.held.size, { roots })) ?? [];
1825
- const summaries = new Map();
1826
- for (const row of rows) {
1827
- if (this.deleted.has(row.id) || this.held.has(row.id) || this.unreadable.has(row.id))
1828
- continue;
1829
- const summary = parseStoredSummary(row.summary) ?? this.coldSummary(row.id);
1830
- if (summary)
1831
- summaries.set(row.id, [summary, row]);
1832
- }
1833
- for (const [id, run] of this.held) {
1834
- if (archivedWindow !== undefined && (run.archived || roots) && run.delegation?.role === 'worker')
1835
- continue;
1836
- summaries.set(id, [toRunSummary(run), this.listOrder(run)]);
1837
- }
1838
- const runs = sortNewestFirst(summaries.values());
1839
- if (archivedWindow === undefined)
1840
- return { runs, truncated: false };
1841
- let archived = 0;
1842
- const kept = runs.filter((run) => !run.archived || ++archived <= archivedWindow);
1843
- return { runs: kept, truncated: archived > archivedWindow };
1844
- }
1845
- /**
1846
- * One page of archived ROOT runs, newest first (#864): `GET /run-summaries/archived`, the
1847
- * archived runs past the window. Held runs list by their record, as in `listRunSummaries`.
1848
- * `before` is the previous page's `nextCursor`; with `q`, only runs `matchesRunQuery` keeps, and
1849
- * `total` counts those. `automationNames` lets `q` match a task by its automation's name, as the
1850
- * list's origin line shows it (hearsay-tools/cezarion#1616). A cursor this store did not write
1851
- * answers `{ error }`.
1852
- *
1853
- * Ranking reads every archived root's key (id, created_at, seq: no record, no summary), so the
1854
- * page and `total` agree with the held overlay; only the page's own rows are read in full.
1855
- */
1856
- listArchivedRuns(options) {
1857
- let after;
1858
- if (options.before !== undefined) {
1859
- after = decodeArchivedCursor(options.before);
1860
- if (!after)
1861
- return { error: 'before is not a cursor this server wrote' };
1862
- }
1863
- const q = options.q?.trim() ?? '';
1864
- const ranked = this.rankArchivedRows(q, options.automationNames);
1865
- this.overlayHeldArchived(ranked, q, options.automationNames);
1866
- const ordered = [...ranked.entries()].sort(([, a], [, b]) => newestFirst(a, b));
1867
- return this.archivedPage(ordered, after, options.limit);
1868
- }
1869
- /** The archived roots in `runs.db`, each by its key: every one without `q` (no record, no
1870
- * summary read), and with `q` the searched rows `matchesRunSearch` keeps, which carry the summary
1871
- * the search read. A deleted, held or unreadable run's row is left out; a held run joins in
1872
- * `overlayHeldArchived`. */
1873
- rankArchivedRows(q, automationNames) {
1874
- const skipped = (id) => this.deleted.has(id) || this.held.has(id) || this.unreadable.has(id);
1875
- const ranked = new Map();
1876
- if (q === '') {
1877
- for (const key of this.db?.listKeysWhere(ARCHIVED_ROOT) ?? [])
1878
- if (!skipped(key.id))
1879
- ranked.set(key.id, key);
1880
- }
1881
- else {
1882
- for (const row of this.db?.searchRootSummaries(sqlPrefilterTokens(q, { automationNames })) ?? []) {
1883
- if (skipped(row.id))
1884
- continue;
1885
- const summary = parseStoredSummary(row.summary) ?? this.coldSummary(row.id);
1886
- if (summary?.archived && matchesRunSearch(summary, q, { automationNames }))
1887
- ranked.set(row.id, { ...row, summary });
1888
- }
1889
- }
1890
- return ranked;
1891
- }
1892
- /** Lay the held archived roots over `ranked`, each by its record: it replaces its stored row
1893
- * (already left out of `ranked`), and with `q` it must match. A held worker never lists. */
1894
- overlayHeldArchived(ranked, q, automationNames) {
1895
- for (const [id, run] of this.held) {
1896
- if (!run.archived || run.delegation?.role === 'worker')
1897
- continue;
1898
- const summary = toRunSummary(run);
1899
- if (q === '' || matchesRunSearch(summary, q, { automationNames }))
1900
- ranked.set(id, { ...this.listOrder(run), summary });
1901
- }
1902
- }
1903
- /** The page of `ordered` after the cursor `after`: its summaries, the cursor of the next page,
1904
- * and `total`, the count of all of `ordered`. */
1905
- archivedPage(ordered, after, limit) {
1906
- const rest = after ? ordered.filter(([, key]) => newestFirst(key, after) > 0) : ordered;
1907
- const page = rest.slice(0, limit);
1908
- const runs = this.hydrateArchivedPage(page);
1909
- const last = page.at(-1)?.[1];
1910
- return {
1911
- runs,
1912
- nextCursor: last && rest.length > page.length ? encodeArchivedCursor(last) : null,
1913
- total: ordered.length,
1914
- };
1915
- }
1916
- /** The page's summaries: a ranked key's own, else its stored one, read for the rows that have
1917
- * none in a single query. A row whose stored summary does not fit the contract is projected from
1918
- * its record; a row that cannot be read at all is left out. */
1919
- hydrateArchivedPage(page) {
1920
- const cold = new Map((this.db?.getSummaries(page.filter(([, key]) => !key.summary).map(([id]) => id)) ?? [])
1921
- .map((row) => [row.id, parseStoredSummary(row.summary) ?? this.coldSummary(row.id)]));
1922
- return page.flatMap(([id, key]) => {
1923
- const summary = key.summary ?? cold.get(id);
1924
- return summary ? [summary] : [];
1925
- });
1926
- }
1927
- /**
1928
- * The ROOT runs, archived or not, that match `query` (`matchesRunSearch`), newest first: at most
1929
- * `limit`, and whether more matched. The owned half of the workspace search (#864); held runs
1930
- * match by their record.
1931
- */
1932
- searchRunSummaries(query, limit) {
1933
- const matched = new Map();
1934
- // Rows come newest first, so the newest `limit + 1` row matches are all a page can use; held
1935
- // runs, which may be newer than any row, are ranked in below.
1936
- this.db?.visitRootSummaries(sqlPrefilterTokens(query), (row) => {
1937
- if (this.deleted.has(row.id) || this.held.has(row.id) || this.unreadable.has(row.id))
1938
- return true;
1939
- const summary = parseStoredSummary(row.summary) ?? this.coldSummary(row.id);
1940
- if (summary && matchesRunSearch(summary, query))
1941
- matched.set(row.id, [summary, row]);
1942
- return matched.size <= limit;
1943
- });
1944
- for (const [id, run] of this.held) {
1945
- if (run.delegation?.role === 'worker')
1946
- continue;
1947
- const summary = toRunSummary(run);
1948
- if (matchesRunSearch(summary, query))
1949
- matched.set(id, [summary, this.listOrder(run)]);
1950
- }
1951
- const runs = sortNewestFirst(matched.values());
1952
- return { runs: runs.slice(0, limit), truncated: runs.length > limit };
1953
- }
1954
- /** A row whose stored summary does not fit the contract any more, projected from its record. */
1955
- coldSummary(id) {
1956
- const run = this.loadCold(id);
1957
- return run ? toRunSummary(run) : undefined;
1958
- }
1959
- /**
1960
- * The run, or undefined. A held run is the held object (writes install into it). Any other run
1961
- * is a fresh copy of its row each call, normalized like a loaded record — frozen under vitest —
1962
- * so changing it means a store method, never an assignment.
1963
- */
1964
- getRun(id) {
1965
- const held = this.held.get(id);
1966
- if (held)
1967
- return held;
1968
- const run = this.loadCold(id);
1969
- return run && this.answerCold(run, true);
1970
- }
1971
- /** Whether the run's row is in `runs.db` but its record could not be read here: what tells a
1972
- * run that cannot open from one that does not exist. Known once something tried to read it. */
1973
- isUnreadable(id) {
1974
- return this.unreadable.has(id) && !this.held.has(id) && !this.deleted.has(id);
1975
- }
1976
- /** The ids in memory right now: the held set, for diagnostics and the benchmark's heap pass. */
1977
- heldIds() {
1978
- return [...this.held.keys()];
1979
- }
1980
- /**
1981
- * The workers a root run owns, newest first, read off its own `receipts` (#659). Every
1982
- * `createOwnedRun` writes the receipt and the worker record in one transaction, and the
1983
- * receipt list is capped at 1,024 creations (#816), so this is a bounded lookup rather than a walk of the whole
1984
- * project index. An ordinary or worker run owns nothing and costs one map read; a receipt
1985
- * whose record has been deleted is skipped, never invented. A parent quarantined to
1986
- * `invalid` has no readable receipts and reports none, which is also what the cockpit
1987
- * assumes for that role.
1988
- */
1989
- listOwnedWorkers(parentId) {
1990
- const parent = this.getRun(parentId);
1991
- if (parent?.delegation?.role !== 'root')
1992
- return [];
1993
- const workers = [];
1994
- for (const receipt of parent.delegation.receipts) {
1995
- const worker = this.getRun(receipt.workerId);
1996
- if (worker?.delegation?.role === 'worker' && worker.delegation.parentRunId === parentId)
1997
- workers.push(worker);
1998
- }
1999
- return workers.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2000
- }
2001
- /** Every worker filed under `parentId` (the `parent_run_id` index plus memory), newest first:
2002
- * receipts or not, which is what the reconcile and deletion checks ask. */
2003
- listWorkersOf(parentId) {
2004
- const workers = new Map();
2005
- for (const run of this.held.values()) {
2006
- if (run.delegation?.role === 'worker' && run.delegation.parentRunId === parentId)
2007
- workers.set(run.id, [run, this.listOrder(run)]);
2008
- }
2009
- // Ids first: a live family's workers are usually all held, and then no record is read at all.
2010
- const cold = (this.db?.listIdsByParent(parentId) ?? []).filter((id) => !this.held.has(id) && !this.deleted.has(id));
2011
- for (const row of cold.length > 0 ? this.db.getMany(cold) : []) {
2012
- const run = this.fromRow(row);
2013
- if (run?.delegation?.role === 'worker' && run.delegation.parentRunId === parentId)
2014
- workers.set(row.id, [run, row]);
2015
- }
2016
- return sortNewestFirst(workers.values());
2017
- }
2018
- /** The id of every worker, held or stored, without decoding any (recovery's worker passes). */
2019
- listWorkerIds() {
2020
- const ids = new Set(this.db?.listWorkerIds() ?? []);
2021
- for (const id of this.deleted)
2022
- ids.delete(id);
2023
- for (const run of this.held.values())
2024
- if (run.delegation?.role === 'worker')
2025
- ids.add(run.id);
2026
- return [...ids];
2027
- }
2028
- /** The id of every run whose delegation is quarantined (`invalid`), held or stored: its stored
2029
- * summary says so, so nothing is decoded (scratch cleanup). */
2030
- listQuarantinedRunIds() {
2031
- const ids = new Set((this.db?.listKeysWhere("json_extract(summary, '$.delegation.role') = 'invalid'") ?? []).map((key) => key.id));
2032
- for (const id of this.deleted)
2033
- ids.delete(id);
2034
- for (const [id, run] of this.held) {
2035
- if (run.delegation?.role === 'invalid')
2036
- ids.add(id);
2037
- else
2038
- ids.delete(id);
2039
- }
2040
- return [...ids];
2041
- }
2042
- /** All retained tasks this automation started, including variants, finished and archived runs.
2043
- * Logs and receipts may compact independently. Read only matching keys in SQLite and overlay
2044
- * held records so a debounced provenance update or deletion is reflected immediately. */
2045
- countAutomationRuns(automationId) {
2046
- const where = "json_extract(data, '$.automation.automationId') = ? OR " +
2047
- "json_extract(data, '$.automationTrigger.automationId') = ?";
2048
- const ids = new Set((this.db?.listKeysWhere(where, [automationId, automationId]) ?? [])
2049
- .map((key) => key.id));
2050
- for (const id of this.deleted)
2051
- ids.delete(id);
2052
- for (const [id, run] of this.held) {
2053
- if (run.automation?.automationId === automationId || run.automationTrigger?.automationId === automationId)
2054
- ids.add(id);
2055
- else
2056
- ids.delete(id);
2057
- }
2058
- return ids.size;
2059
- }
2060
- /** First non-archived task referencing a project issue, including secondary references. */
2061
- findNonArchivedRunByIssue(repo, number) {
2062
- const url = `https://github.com/${repo}/issues/${number}`.toLowerCase();
2063
- const matches = (run) => {
2064
- if (run.archived)
2065
- return false;
2066
- const urls = [run.referencedIssueUrl, ...(run.referencedIssueCandidates ?? []),
2067
- ...(run.automation?.event.startsWith('issue.') ? [run.automation.githubUrl] : []),
2068
- ...[...run.task.matchAll(new RegExp(ISSUE_URL_RE.source, 'gi'))].map((match) => match[0])]
2069
- .filter((value) => value !== undefined)
2070
- .map((value) => value.replace(/\/+$/, '').toLowerCase())
2071
- .filter((value) => value.endsWith(`/issues/${number}`));
2072
- // The legacy issueNumber is display-only and cannot establish repository identity.
2073
- // Explicit task markers remain project-scoped unless a qualified URL contradicts them.
2074
- return urls.includes(url) || (urls.length === 0 && run.markerRefs?.issue === number);
2075
- };
2076
- for (const run of this.held.values())
2077
- if (matches(run))
2078
- return run.id;
2079
- // Secondary references are record-only: query them in SQLite rather than hydrating every
2080
- // finished transcript or relying on the slim summary's primary issue number.
2081
- const where = `archived = 0 AND (
2082
- json_extract(data, '$.issueNumber') = ? OR json_extract(data, '$.markerRefs.issue') = ?
2083
- OR lower(rtrim(json_extract(data, '$.referencedIssueUrl'), '/')) = ?
2084
- OR EXISTS (SELECT 1 FROM json_each(data, '$.referencedIssueCandidates') WHERE lower(rtrim(value, '/')) = ?)
2085
- OR (json_extract(data, '$.automation.event') LIKE 'issue.%' AND lower(rtrim(json_extract(data, '$.automation.githubUrl'), '/')) = ?)
2086
- OR instr(lower(json_extract(data, '$.task')), ?) > 0
2087
- )`;
2088
- for (const key of this.db?.listKeysWhere(where, [number, number, url, url, url, url]) ?? []) {
2089
- if (this.held.has(key.id) || this.deleted.has(key.id) || this.unreadable.has(key.id))
2090
- continue;
2091
- const run = this.getRun(key.id);
2092
- if (run && matches(run))
2093
- return key.id;
2094
- }
2095
- return undefined;
2096
- }
2097
- /**
2098
- * The runs automation receipts launched, by receipt id (`automation.receiptId` or
2099
- * `automationTrigger.receiptId`). Memory answers first; a receipt it does not know costs one
2100
- * pass over `runs.db` that reads the records' JSON in SQLite — only a crash leftover (a
2101
- * receipt still `reserved` at startup) ever asks.
2102
- */
2103
- findRunIdsByAutomationReceipt(receiptIds) {
2104
- const wanted = new Set(receiptIds);
2105
- const found = new Map();
2106
- const receiptOf = (run) => run.automation?.receiptId ?? run.automationTrigger?.receiptId;
2107
- for (const run of this.held.values()) {
2108
- const receipt = receiptOf(run);
2109
- if (receipt !== undefined && wanted.has(receipt))
2110
- found.set(receipt, run.id);
2111
- }
2112
- const missing = [...wanted].filter((receipt) => !found.has(receipt));
2113
- if (missing.length === 0 || !this.db)
2114
- return found;
2115
- const where = "json_extract(data, '$.automation.receiptId') IN (SELECT value FROM json_each(?))" +
2116
- " OR json_extract(data, '$.automationTrigger.receiptId') IN (SELECT value FROM json_each(?))";
2117
- for (const key of this.db.listKeysWhere(where, [JSON.stringify(missing), JSON.stringify(missing)])) {
2118
- if (this.held.has(key.id) || this.deleted.has(key.id))
2119
- continue;
2120
- const run = this.getRun(key.id);
2121
- const receipt = run && receiptOf(run);
2122
- if (receipt !== undefined && wanted.has(receipt) && !found.has(receipt))
2123
- found.set(receipt, key.id);
2124
- }
2125
- return found;
2126
- }
2127
- /** The id of every root whose delegation carries a conversation, held or stored: recovery's full
2128
- * reconcile pass (#661). Only roots' records are read, in SQLite. `naming` keeps the ledgers whose
2129
- * messages name that run id, filtered there too, so a deleted peer decodes no other root. */
2130
- listConversationRootIds(naming) {
2131
- const where = `json_extract(summary, '$.delegation.role') = 'root' AND json_extract(data, '$.delegation.conversation') IS NOT NULL${naming ? " AND instr(json_extract(data, '$.delegation.conversation.messages'), ?) > 0" : ''}`;
2132
- const ids = new Set((this.db?.listKeysWhere(where, naming ? [naming] : []) ?? []).map((key) => key.id));
2133
- for (const id of this.deleted)
2134
- ids.delete(id);
2135
- for (const [id, run] of this.held) {
2136
- if (run.delegation?.role === 'root' && run.delegation.conversation && (!naming || run.delegation.conversation.messages.some(message => [message.senderRunId, message.recipientRunId].includes(naming))))
2137
- ids.add(id);
2138
- else
2139
- ids.delete(id);
2140
- }
2141
- return [...ids];
2142
- }
2143
- /** The id of every run, held or stored, without decoding any (orphan-worktree sweeps). */
2144
- listRunIds() {
2145
- const ids = new Set(this.db?.listIds() ?? []);
2146
- for (const id of this.deleted)
2147
- ids.delete(id);
2148
- for (const id of this.held.keys())
2149
- ids.add(id);
2150
- return [...ids];
2151
- }
2152
- /** Runs with a materialized worktree directory (`worktreePath`, not reclaimed), most recently
2153
- * finished first, then newest first: worktree retention and the worktrees panel. */
2154
- listRunsWithWorktree() {
2155
- const runs = this.queryRuns(this.db?.listWithWorktree() ?? [], (run) => run.worktreePath !== undefined && run.worktreeReclaimedAt === undefined);
2156
- const recency = ([run]) => run.finishedAt ?? run.createdAt;
2157
- return runs.sort((a, b) => (recency(a) < recency(b) ? 1 : recency(a) > recency(b) ? -1 : newestFirst(a[1], b[1]))).map(([run]) => run);
2158
- }
2159
- /**
2160
- * Every run that owns a branch or names the PR it created, as the few fields branch cleanup and
2161
- * git-log attribution read (issue 08 §B3, §B5; a squash commit is attributed by its PR number):
2162
- * the stored summary plus the `branch` and `base_branch` columns, so a Git-tab request decodes
2163
- * no record. Held runs answer from memory.
2164
- */
2165
- listBranchOwners() {
2166
- const owners = new Map();
2167
- for (const row of this.db?.listBranchOwners("branch IS NOT NULL OR json_extract(summary, '$.pullRequestUrl') IS NOT NULL") ?? []) {
2168
- if (this.deleted.has(row.id) || this.held.has(row.id))
2169
- continue;
2170
- const summary = parseStoredSummary(row.summary);
2171
- owners.set(row.id, {
2172
- id: row.id, createdAt: row.createdAt, status: row.status, archived: row.archived,
2173
- ...(row.branch === null ? {} : { branch: row.branch }),
2174
- ...(row.baseBranch === null ? {} : { baseBranch: row.baseBranch }),
2175
- title: summary?.title ?? row.id,
2176
- ...(summary?.pullRequestUrl === undefined ? {} : { pullRequestUrl: summary.pullRequestUrl }),
2177
- });
2178
- }
2179
- for (const run of this.held.values()) {
2180
- const owner = branchOwnerOf(run);
2181
- if (owner)
2182
- owners.set(run.id, owner);
2183
- }
2184
- return [...owners.values()];
2185
- }
2186
- /** The rows a column query returned, as records, with memory laid over them: a held run
2187
- * answers from memory (matching `matches` there, not on its maybe-older row). */
2188
- queryRuns(rows, matches) {
2189
- const runs = new Map();
2190
- for (const run of this.held.values())
2191
- if (matches(run))
2192
- runs.set(run.id, [run, this.listOrder(run)]);
2193
- for (const row of rows) {
2194
- if (runs.has(row.id) || this.held.has(row.id) || this.deleted.has(row.id))
2195
- continue;
2196
- const run = this.fromRow(row);
2197
- if (run && matches(run))
2198
- runs.set(row.id, [run, row]);
2199
- }
2200
- return [...runs.values()];
2201
- }
2202
- /** The run an idempotent start already created (#504), archived or not. A deleted run is gone
2203
- * with its record, so a retry after deletion honestly creates a fresh one. */
2204
- findRunByClientRequestId(clientRequestId) {
2205
- for (const run of this.held.values())
2206
- if (run.clientRequestId === clientRequestId)
2207
- return run;
2208
- const row = this.db?.findByClientRequestId(clientRequestId);
2209
- if (!row || this.held.has(row.id))
2210
- return undefined;
2211
- const run = this.getRun(row.id);
2212
- return run?.clientRequestId === clientRequestId ? run : undefined;
2213
- }
2214
- createRun(input) {
2215
- if (this.openFailure)
2216
- throw this.openFailure;
2217
- const run = this.buildRun(input, randomUUID());
2218
- // A new family, so nobody else can hold it; claimed before anything (an NDJSON event) is written.
2219
- if (this.db && !this.claimFamilies([run.id]).has(run.id))
2220
- throw new RunWriteRefusedError(run.id, 'foreign');
2221
- this.held.set(run.id, run);
2222
- this.pruneOldRuns();
2223
- this.touch(run);
2224
- return run;
2225
- }
2226
- /** Build without publishing: owned creation must commit its receipt and run together. */
2227
- buildRun(input, id) {
2228
- const run = {
2229
- id,
2230
- // Scrubbed on the way in, exactly as `updateRun` scrubs it on the way
2231
- // through (#456 review) — a token pasted into the prompt otherwise sat
2232
- // verbatim in `runs.json` from creation. `task` is deliberately NOT
2233
- // scrubbed: it is the user's own prompt and is replayed into `{{task}}`
2234
- // when a queued run is revived after a restart (#367), so redacting it
2235
- // would corrupt the revived run.
2236
- title: this.redactText(input.title),
2237
- workflow: input.workflow,
2238
- task: input.task,
2239
- model: input.model,
2240
- systemPrompt: input.systemPrompt,
2241
- workflowDef: input.workflowDef === undefined ? undefined : workflowDefSchema.parse(input.workflowDef),
2242
- effort: input.effort,
2243
- runner: input.runner,
2244
- agentProfile: input.agentProfile,
2245
- autonomous: input.autonomous,
2246
- archiveWhenDone: input.archiveWhenDone,
2247
- autoMergePr: input.autoMergePr,
2248
- ...(input.notify ? { notify: true } : {}),
2249
- worktree: input.worktree,
2250
- groupId: input.groupId,
2251
- variant: input.variant,
2252
- ...(input.clientRequestId === undefined ? {} : { clientRequestId: input.clientRequestId, clientRequestHash: input.clientRequestHash }),
2253
- ...(input.automation ? { automation: input.automation } : {}),
2254
- ...(input.automationTrigger ? { automationTrigger: input.automationTrigger } : {}),
2255
- status: 'queued',
2256
- createdAt: new Date().toISOString(),
2257
- tokensUsed: 0,
2258
- archived: false,
2259
- steps: input.steps.map((s) => ({
2260
- ...s,
2261
- status: 'pending',
2262
- iterations: 0,
2263
- tokensUsed: 0,
2264
- })),
2265
- };
2266
- // A prompt that pastes a PR or issue URL is already about that item — seed
2267
- // both referenced tiers so queued runs can expose the reference before the
2268
- // first agent event (#407, #554).
2269
- this.trackReferencedPrs(run, input.task);
2270
- this.trackReferencedIssues(run, input.task);
2271
- return run;
2272
- }
2273
- /** Accept the family ledger and its recipient queue in a single durable index replacement. A new
2274
- * message (`message`, or the delivered input) whose ID is in use writes nothing; `recipientDelegation`
2275
- * makes a peer recipient with no delegation record a root task in the same write. */
2276
- commitConversation(rootId, conversation, delivery, message) {
2277
- const root = this.peek(rootId);
2278
- if (root?.delegation?.role !== 'root')
2279
- throw new Error('missing conversation root');
2280
- assertConversationIdFree(root, message ?? delivery?.input, id => this.peek(id), (runId, id) => this.hasProjection(runId, id));
2281
- const staged = new Map();
2282
- staged.set(rootId, { ...root, delegation: delegationStateSchema.parse({ ...root.delegation, conversation: { ...conversation,
2283
- messages: conversation.messages.map(message => ({ ...message, text: this.redactText(message.text) })),
2284
- } }) });
2285
- if (delivery) {
2286
- const recipient = staged.get(delivery.recipientRunId) ?? this.peek(delivery.recipientRunId);
2287
- if (!recipient)
2288
- throw new Error('missing conversation recipient');
2289
- const input = agentInputSchema.parse({ ...delivery.input, text: this.redactText(delivery.input.text) });
2290
- const delegation = !recipient.delegation && delivery.recipientDelegation ? { delegation: delegationStateSchema.parse(delivery.recipientDelegation) } : {};
2291
- staged.set(recipient.id, { ...recipient, ...delegation, agentInputs: [...(recipient.agentInputs ?? []), input] });
2292
- }
2293
- this.commitIndex(staged);
2294
- }
2295
- /** Crash recovery (#505): input a harness accepted but was never seen reading goes
2296
- * back to the queue. Returns the requeued IDs. */
2297
- requeueAwaitingReadInputs(id) {
2298
- const ids = (this.peek(id)?.agentInputs ?? []).filter(input => input.awaitingRead && input.deliveredAt && !input.consumedAt).map(input => input.id);
2299
- if (ids.length)
2300
- this.commitOutcome(id, { kind: 'requeued', inputIds: ids });
2301
- return ids;
2302
- }
2303
- /** Delivered, but the harness never confirmed reading it (#505): stop awaiting a read. */
2304
- commitAgentInputsUnconfirmed(id, ids) {
2305
- const run = this.peek(id);
2306
- if (!run?.agentInputs || !ids.length)
2307
- return;
2308
- this.commitAgentInputs(id, run.agentInputs.map(input => {
2309
- if (!ids.includes(input.id) || !input.awaitingRead)
2310
- return input;
2311
- const { awaitingRead: _awaiting, ...unconfirmed } = input;
2312
- return unconfirmed;
2313
- }));
2314
- }
2315
- /** Observable atomic input checkpoint for the queue itself: enqueue, retire, reorder. Delivery
2316
- * and reads are outcomes (`commitOutcome`). */
2317
- commitAgentInputs(id, inputs) {
2318
- const run = this.peek(id);
2319
- if (!run)
2320
- throw new Error('missing agent input target');
2321
- const agentInputs = inputs.map(input => agentInputSchema.parse(input));
2322
- // Receipts are outcomes (hearsay-tools/cezarion#1805): only `commitOutcome` writes them.
2323
- const stored = new Map((run.agentInputs ?? []).map(input => [input.id, input]));
2324
- if (agentInputs.some(input => input.deliveredAt !== stored.get(input.id)?.deliveredAt || input.consumedAt !== stored.get(input.id)?.consumedAt)) {
2325
- throw new Error('agent input receipts change only through commitOutcome');
2326
- }
2327
- const now = new Date().toISOString();
2328
- for (const input of run.agentInputs ?? []) {
2329
- const claim = input.inboxClaim;
2330
- if (!claim || claim.acknowledgedAt || claim.expiresAt <= now)
2331
- continue;
2332
- const matching = agentInputs.filter(next => next.id === input.id);
2333
- if (matching.length !== 1 || !isDeepStrictEqual(matching[0].inboxClaim, claim)) {
2334
- throw new Error('live inbox receipt changed');
2335
- }
2336
- }
2337
- this.commitIndex(new Map([[id, { ...run, agentInputs }]]));
2338
- }
2339
- /** Reserve only unread conversation inputs in one durable index replacement. */
2340
- claimInboxInputs(runId, ids, claim) {
2341
- const run = this.peek(runId);
2342
- if (!run)
2343
- throw new Error('missing inbox recipient');
2344
- const selected = z.array(z.uuid()).min(1).max(32).refine(values => new Set(values).size === values.length).parse(ids);
2345
- const receipt = inboxClaimSchema.parse({ ...claim, memberIds: selected });
2346
- if (receipt.acknowledgedAt || receipt.expiresAt <= new Date().toISOString())
2347
- throw new Error('inbox claim is not live');
2348
- const inputs = run.agentInputs ?? [];
2349
- if (inputs.some(input => input.inboxClaim?.receiptId === receipt.receiptId))
2350
- throw new Error('inbox receipt already exists');
2351
- for (const id of selected) {
2352
- const matching = inputs.filter(input => input.id === id);
2353
- if (matching.length !== 1 || matching[0]?.source !== 'agent' || !matching[0].conversation ||
2354
- matching[0].deliveredAt || (matching[0].inboxClaim && matching[0].inboxClaim.expiresAt > new Date().toISOString())) {
2355
- throw new Error('inbox input is not available');
2356
- }
2357
- }
2358
- const selectedIds = new Set(selected);
2359
- this.commitIndex(new Map([[runId, { ...run, agentInputs: inputs.map(input => selectedIds.has(input.id)
2360
- ? agentInputSchema.parse({ ...input, inboxClaim: receipt }) : input) }]]));
2361
- }
2362
- /** A receipt owns every matching input or none; exact ACK retries preserve the first timestamp. */
2363
- ackInboxInputs(runId, receiptId, generation, at) {
2364
- const run = this.peek(runId);
2365
- if (!run)
2366
- throw new Error('missing inbox recipient');
2367
- inboxClaimSchema.shape.receiptId.parse(receiptId);
2368
- inboxClaimSchema.shape.generation.parse(generation);
2369
- inboxClaimSchema.shape.expiresAt.parse(at);
2370
- const matching = (run.agentInputs ?? []).filter(input => input.inboxClaim?.receiptId === receiptId);
2371
- const receipt = matching[0]?.inboxClaim;
2372
- const memberIds = receipt?.memberIds;
2373
- if (!memberIds || matching.length !== memberIds.length ||
2374
- !memberIds.every(id => matching.some(input => input.id === id)) ||
2375
- matching.some(input => !isDeepStrictEqual(input.inboxClaim, receipt)) ||
2376
- matching.some(input => input.inboxClaim?.generation !== generation ||
2377
- input.source !== 'agent' || !input.conversation))
2378
- throw new Error('inbox receipt changed');
2379
- if (matching.every(input => input.inboxClaim?.acknowledgedAt && input.deliveredAt === input.inboxClaim.acknowledgedAt)) {
2380
- return 'already-acknowledged';
2381
- }
2382
- if (matching.some(input => input.deliveredAt || input.inboxClaim?.acknowledgedAt || input.inboxClaim.expiresAt <= at)) {
2383
- throw new Error('inbox receipt expired or displaced');
2384
- }
2385
- this.commitOutcome(runId, { kind: 'inbox-acknowledged', receiptId, at });
2386
- return 'acknowledged';
2387
- }
2388
- releaseInboxInputs(runId, receiptId, generation) {
2389
- const run = this.peek(runId);
2390
- if (!run)
2391
- throw new Error('missing inbox recipient');
2392
- inboxClaimSchema.shape.receiptId.parse(receiptId);
2393
- inboxClaimSchema.shape.generation.parse(generation);
2394
- const matching = (run.agentInputs ?? []).filter(input => input.inboxClaim?.receiptId === receiptId);
2395
- if (!matching.length || matching.some(input => input.inboxClaim?.generation !== generation ||
2396
- input.inboxClaim?.acknowledgedAt || input.deliveredAt))
2397
- throw new Error('inbox receipt changed');
2398
- this.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
2399
- if (input.inboxClaim?.receiptId !== receiptId)
2400
- return input;
2401
- const { inboxClaim: _claim, ...unclaimed } = input;
2402
- return agentInputSchema.parse(unclaimed);
2403
- }) }]]));
2404
- return 'released';
2405
- }
2406
- clearExpiredInboxClaims(runId, now) {
2407
- const run = this.peek(runId);
2408
- if (!run)
2409
- throw new Error('missing inbox recipient');
2410
- inboxClaimSchema.shape.expiresAt.parse(now);
2411
- if (!run.agentInputs?.some(input => input.inboxClaim && !input.inboxClaim.acknowledgedAt && input.inboxClaim.expiresAt <= now))
2412
- return;
2413
- this.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
2414
- if (!input.inboxClaim || input.inboxClaim.acknowledgedAt || input.inboxClaim.expiresAt > now)
2415
- return input;
2416
- const { inboxClaim: _claim, ...unclaimed } = input;
2417
- return agentInputSchema.parse(unclaimed);
2418
- }) }]]));
2419
- }
2420
- /**
2421
- * A wait and its wake input share one atomic index replacement (spec 2026-10-17-unified-waits).
2422
- * Upserts `wait` by id into `waits` and clears `lastWaitsError`; `input` is appended once (an
2423
- * input whose id is already queued stays as it is). Only an open or resolved wait is committed
2424
- * here: settling is an outcome (`commitOutcome`). A new open wait
2425
- * past `WAIT_LIMIT` open ones is refused, so the list stays bounded whatever the caller checked.
2426
- */
2427
- commitWait(id, wait, input) {
2428
- const run = this.peek(id);
2429
- if (!run)
2430
- throw new Error('missing wait target');
2431
- const entry = waitSchema.parse(wait);
2432
- if (entry.phase !== 'open' && entry.phase !== 'resolved')
2433
- throw new Error('a settled wait is committed through its delivery or cancellation');
2434
- const waits = run.waits ?? [];
2435
- const known = waits.some((row) => row.id === entry.id);
2436
- if (!known && entry.phase === 'open' && waits.filter((row) => row.phase === 'open').length >= WAIT_LIMIT) {
2437
- throw new Error(`open wait limit reached (${WAIT_LIMIT})`);
2438
- }
2439
- const agentInput = input ? agentInputSchema.parse(input) : undefined;
2440
- this.commitIndex(new Map([[id, { ...run, waits: known ? waits.map((row) => row.id === entry.id ? entry : row) : [...waits, entry], lastWaitsError: undefined,
2441
- ...(agentInput ? { agentInputs: run.agentInputs?.some((row) => row.id === agentInput.id)
2442
- ? run.agentInputs : [...(run.agentInputs ?? []), agentInput] } : {}) }]]));
2443
- }
2444
- /** A park that gives up its slot (hearsay-tools/cezarion#1235): the run and its step read
2445
- * `waiting`, committed at once instead of on the debounced save, so a refused write throws with
2446
- * nothing changed and the caller keeps the slot. */
2447
- commitParked(id, stepId) {
2448
- const run = this.peek(id);
2449
- if (!run)
2450
- return;
2451
- this.commitIndex(new Map([[id, { ...run, status: 'waiting', activity: undefined,
2452
- ...(stepId ? { steps: run.steps.map((step) => step.id === stepId ? { ...step, status: 'waiting' } : step) } : {}) }]]));
2453
- }
2454
- /** A usage-limit appointment withdrawn, committed at once instead of on the debounced save
2455
- * (hearsay-tools/cezarion#1236): a crash right after the withdrawal must not find it on disk,
2456
- * or recovery re-arms work the user cancelled. A run held for its resume settles `failed`. */
2457
- commitAutoResumeWithdrawal(id) {
2458
- const run = this.peek(id);
2459
- if (!run || (run.autoResumeAt === undefined && run.autoResumeAttempts === undefined))
2460
- return;
2461
- const held = isUsageLimitHold(run);
2462
- this.commitIndex(new Map([[id, { ...run, autoResumeAt: undefined, autoResumeAttempts: undefined,
2463
- ...(held ? { status: 'failed', finishedAt: new Date().toISOString() } : {}) }]]));
2464
- }
2465
- /** Legacy CI checkpoint over `commitWait`, kept until its callers move (unified waits, Task 4). */
2466
- commitCiWait(id, wait, input) {
2467
- this.commitWait(id, ciWaitEntry(ciWaitSchema.parse(wait)), input);
2468
- }
2469
- /** A human message beside a run's waits (hearsay-tools/cezarion#1235): accepted durably, and
2470
- * every wait stays. A lifecycle opening becomes
2471
- * the human's and keeps its wake text, so the message opens the continuation (and answers a
2472
- * pending question) and the owed results still reach the agent. */
2473
- commitHumanMessageBesideWaits(id, acceptedHumanMessage) {
2474
- const run = this.peek(id);
2475
- if (!run)
2476
- throw new Error('missing queued message target');
2477
- this.commitIndex(new Map([[id, { ...run, queuedMessages: [...(run.queuedMessages ?? []), queuedMessageSchema.parse(acceptedHumanMessage)],
2478
- ...(run.continuationMessage ? { continuationMessage: { ...run.continuationMessage, origin: 'human' } } : {}),
2479
- }]]));
2480
- }
2481
- /**
2482
- * The one write of a run outcome (hearsay-tools/cezarion#1805): an input or wait delivered, a wake
2483
- * charged, a wait settled, a question answered, staged by `applyOutcomes` with what it depends on
2484
- * (`deps`) and committed in one transaction, with every pending row. A crash keeps all of it or
2485
- * none. Nothing changes: nothing is written. Needs no live session: it reads the stored record.
2486
- *
2487
- * A refused write throws with nothing changed. `bestEffort` is for a cleanup path, which must
2488
- * never stop on it: it warns and applies the change in memory for the debounced save to retry.
2489
- * A conversation request outcome is the other sanctioned write: `commitConversation`.
2490
- */
2491
- commitOutcome(id, outcomes, deps = {}, opts = {}) {
2492
- const run = this.peek(id);
2493
- if (!run)
2494
- return { committed: false, answered: [] };
2495
- const staged = applyOutcomes(run, Array.isArray(outcomes) ? outcomes : [outcomes], deps);
2496
- if (!staged.changed)
2497
- return { committed: false, answered: [] };
2498
- try {
2499
- this.commitIndex(new Map([[id, staged.next]]));
2500
- }
2501
- catch (error) {
2502
- if (!opts.bestEffort)
2503
- throw error;
2504
- console.warn(`[cez] outcome checkpoint failed: ${error instanceof Error ? error.message : String(error)}`);
2505
- const live = this.record(id);
2506
- if (!live)
2507
- return { committed: false, answered: staged.answered };
2508
- for (const key of Object.keys(live))
2509
- if (!(key in staged.next))
2510
- delete live[key];
2511
- Object.assign(live, staged.next);
2512
- this.touch(live);
2513
- return { committed: false, answered: staged.answered };
2514
- }
2515
- return { committed: true, answered: staged.answered };
2516
- }
2517
- /** An acknowledged inactive-root Finish must survive the async diff and restart. */
2518
- commitRootFinishIntent(id) {
2519
- const run = this.peek(id);
2520
- if (run?.status !== 'waiting' || run.delegation?.role !== 'root')
2521
- throw new Error('root is not waiting');
2522
- if (run.delegation.finishRequestedAt)
2523
- return;
2524
- this.commitDelegation([{ id, delegation: { ...run.delegation, finishRequestedAt: new Date().toISOString() } }]);
2525
- }
2526
- /** Cancellation supersedes pending Finish in one durable checkpoint. Also
2527
- * repairs cancelled-plus-intent snapshots left by older controllers. */
2528
- commitRootFinishCancellation(id) {
2529
- const run = this.peek(id);
2530
- if (run?.delegation?.role !== 'root' || !run.delegation.finishRequestedAt ||
2531
- !['waiting', 'cancelled'].includes(run.status))
2532
- return false;
2533
- const { finishRequestedAt: _intent, ...delegation } = run.delegation;
2534
- this.commitIndex(new Map([[id, { ...run, delegation, status: 'cancelled', finishedAt: run.finishedAt ?? new Date().toISOString() }]]));
2535
- return true;
2536
- }
2537
- /** Publish terminal success and completed steps only after their atomic checkpoint.
2538
- * A concurrent explicit cancellation is never overwritten by the async diff. */
2539
- commitRootFinishSuccess(id, status) {
2540
- const run = this.peek(id);
2541
- if (run?.status !== 'waiting' || run.delegation?.role !== 'root' || !run.delegation.finishRequestedAt)
2542
- return false;
2543
- const { finishRequestedAt: _intent, ...delegation } = run.delegation;
2544
- const finishedAt = new Date().toISOString();
2545
- this.commitIndex(new Map([[id, { ...run, delegation, status, finishedAt, currentStepId: undefined, autoResumeAttempts: undefined,
2546
- activity: undefined,
2547
- steps: run.steps.map(step => step.status === 'waiting' || step.status === 'running'
2548
- ? { ...step, status: 'done', finishedAt: step.finishedAt ?? finishedAt } : step),
2549
- }]]));
2550
- return true;
2551
- }
2552
- /** Persist all authority patches before exposing any of them to the engine or subscribers. */
2553
- commitDelegation(patches) {
2554
- if (patches.length === 0)
2555
- return;
2556
- const staged = new Map();
2557
- let destroyProgress = true;
2558
- for (const patch of patches) {
2559
- const run = this.peek(patch.id);
2560
- if (!run || staged.has(patch.id))
2561
- throw new Error('missing or duplicate delegation patch target');
2562
- const delegation = delegationStateSchema.parse(patch.delegation);
2563
- if (!isDestroyProgress(run.delegation, delegation))
2564
- destroyProgress = false;
2565
- staged.set(patch.id, { ...run, delegation });
2566
- }
2567
- // In-process cause only: consumers can skip metadata replay when delegation
2568
- // is disabled without dropping real status or termination-proof notifications.
2569
- this.commitIndex(staged, destroyProgress ? 'delegation-destroy-progress' : 'delegation-checkpoint');
2570
- }
2571
- /** A pending destroy's automatic retry state, or its removal (hearsay-tools/cezarion#879). Kept on
2572
- * the record beside the strict delegation, so an older cezar strips it rather than quarantining the
2573
- * worker. Destroy progress: nothing the family reconcile reads changes. */
2574
- commitDestroyRetry(id, retry) {
2575
- const run = this.peek(id);
2576
- if (run?.delegation?.role !== 'worker' || !run.delegation.destroy)
2577
- throw new Error('missing pending destroy');
2578
- if (!retry && !run.destroyRetry)
2579
- return;
2580
- // An explicit `undefined`, not an omitted key: commitIndex assigns onto the live record.
2581
- this.commitIndex(new Map([[id, { ...run, destroyRetry: retry ? workerDestroyRetrySchema.parse(retry) : undefined }]]), 'delegation-destroy-progress');
2582
- }
2583
- /** Accepted execution revision is public lifecycle identity, separate from process generations. */
2584
- commitWorkerContinuation(id, patch, step, conversation) {
2585
- const run = this.peek(id);
2586
- if (run?.delegation?.role !== 'worker')
2587
- throw new Error('missing worker continuation target');
2588
- const delegation = delegationStateSchema.parse({ ...run.delegation,
2589
- executionRevision: (run.delegation.executionRevision ?? 0) + 1,
2590
- executionStartSeq: this.transcriptFacts(id).lastSeq,
2591
- });
2592
- const staged = new Map();
2593
- const next = { ...run, ...this.redactPatch(patch), delegation,
2594
- ...(step ? { steps: [...run.steps, { ...step, status: 'pending', iterations: 0, tokensUsed: 0 }] } : {}),
2595
- };
2596
- staged.set(id, next);
2597
- if (Object.prototype.hasOwnProperty.call(patch, 'archived'))
2598
- this.syncTranscriptForm(id, next.archived);
2599
- if (conversation) {
2600
- const root = this.peek(conversation.rootId);
2601
- if (root?.delegation?.role !== 'root' || run.delegation.parentRunId !== root.id)
2602
- throw new Error('missing conversation ownership');
2603
- staged.set(root.id, { ...root, delegation: delegationStateSchema.parse({ ...root.delegation, conversation: { ...conversation.state,
2604
- messages: conversation.state.messages.map(message => ({ ...message, text: this.redactText(message.text) })),
2605
- } }) });
2606
- const input = agentInputSchema.parse({ ...conversation.input, text: this.redactText(conversation.input.text) });
2607
- staged.set(id, { ...staged.get(id), agentInputs: [...(run.agentInputs ?? []), input] });
2608
- }
2609
- this.commitIndex(staged);
2610
- }
2611
- workerResultsDir(parentId) {
2612
- z.uuid().parse(parentId);
2613
- const dir = join(this.dataDir, 'runs', `${parentId}-worker-results`);
2614
- mkdirSync(dir, { recursive: true, mode: 0o700 });
2615
- if (realpathSync(dir) !== resolve(dir) || !lstatSync(dir).isDirectory())
2616
- throw new Error('worker result storage redirected');
2617
- return dir;
2618
- }
2619
- workerResultSnapshotPath(parentId, workerId, snapshotId) {
2620
- return join(this.dataDir, 'runs', `${z.uuid().parse(parentId)}-worker-results`, `${z.uuid().parse(workerId)}.${z.uuid().parse(snapshotId)}.json`);
2621
- }
2622
- readWorkerResultFile(parentId, workerId) {
2623
- const parent = this.peek(parentId);
2624
- if (parent?.delegation?.role !== 'root' || !parent.delegation.receipts.some(receipt => receipt.workerId === workerId))
2625
- return undefined;
2626
- const reference = parent.delegation.results?.find(result => result.workerId === workerId);
2627
- if (!reference)
2628
- return undefined;
2629
- try {
2630
- const path = join(this.workerResultsDir(parentId), `${z.uuid().parse(workerId)}.${z.uuid().parse(reference.snapshotId)}.json`);
2631
- const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
2632
- let raw;
2633
- try {
2634
- const info = fstatSync(fd);
2635
- if (!info.isFile() || info.size > 3_145_728)
2636
- return undefined;
2637
- raw = readFileSync(fd, 'utf8');
2638
- }
2639
- finally {
2640
- closeSync(fd);
2641
- }
2642
- const file = workerResultFileSchema.parse(JSON.parse(raw));
2643
- if (file.result.diff.state === 'available' && file.result.diff.path !== path)
2644
- return undefined;
2645
- if (file.result.parentRunId !== parentId || file.result.workerId !== workerId || file.result.workspace.ownerRunId !== workerId || file.result.revision !== reference.revision || file.result.observedAt !== reference.observedAt ||
2646
- (file.result.diff.state === 'available' && (file.result.diff.snapshotId !== reference.snapshotId || file.diffSnapshot === undefined)))
2647
- return undefined;
2648
- return file;
2649
- }
2650
- catch {
2651
- return undefined;
2652
- }
2653
- }
2654
- readWorkerResult(parentId, workerId) {
2655
- return this.readWorkerResultFile(parentId, workerId)?.result;
2656
- }
2657
- readWorkerResultDiff(parentId, workerId) {
2658
- return this.readWorkerResultFile(parentId, workerId)?.diffSnapshot;
2659
- }
2660
- /** Publish a pointer only after its redacted immutable snapshot reaches disk. Failed index writes retain the old evidence.
2661
- * A result whose evidence is already stored returns the stored one and writes nothing; `ignoreCleanup` is for a
2662
- * caller that only needs the payload durable, whatever cleanup phase the stored copy names. */
2663
- commitWorkerResult(parentId, value, diffSnapshot, opts = {}) {
2664
- const result = workerCollectedResultSchema.parse(this.redact({ type: 'worker-result', seq: 0, ts: value.observedAt, result: value }).result);
2665
- const parent = this.peek(parentId);
2666
- const worker = this.peek(result.workerId);
2667
- if (parent?.delegation?.role !== 'root' || result.parentRunId !== parentId ||
2668
- !parent.delegation.receipts.some(receipt => receipt.workerId === result.workerId))
2669
- throw new Error('missing result ownership');
2670
- if (worker && (worker.delegation?.role !== 'worker' || worker.delegation.parentRunId !== parentId ||
2671
- worker.delegation.workspace.ownerRunId !== worker.id || (worker.delegation.executionRevision ?? 0) !== result.revision || worker.status !== result.status))
2672
- throw new Error('worker result revision changed');
2673
- const old = parent.delegation.results?.find(entry => entry.workerId === result.workerId);
2674
- const stored = old && this.readWorkerResultFile(parentId, result.workerId);
2675
- if (stored && sameWorkerResult(stored.result, result, opts) &&
2676
- stored.diffSnapshot === (diffSnapshot === undefined ? undefined : this.redactText(diffSnapshot)))
2677
- return stored.result;
2678
- if ((!worker && !this.readWorkerResult(parentId, result.workerId)) || (old && (old.revision > result.revision || (old.revision === result.revision && old.observedAt > result.observedAt))))
2679
- throw new Error('worker result is obsolete');
2680
- const snapshotId = result.diff.state === 'available' ? result.diff.snapshotId : randomUUID();
2681
- if (result.diff.state === 'available')
2682
- result.diff.path = this.workerResultSnapshotPath(parentId, result.workerId, snapshotId);
2683
- if (result.diff.state === 'available' && diffSnapshot === undefined)
2684
- throw new Error('missing diff snapshot');
2685
- const file = workerResultFileSchema.parse({ result, ...(diffSnapshot === undefined ? {} : { diffSnapshot: this.redactText(diffSnapshot) }) });
2686
- const dir = this.workerResultsDir(parentId);
2687
- const path = join(dir, `${result.workerId}.${snapshotId}.json`);
2688
- if (existsSync(path))
2689
- throw new Error('worker result snapshot identity already exists');
2690
- const temp = `${path}.${randomUUID()}.tmp`;
2691
- try {
2692
- const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
2693
- try {
2694
- writeFileSync(fd, JSON.stringify(file));
2695
- fsyncSync(fd);
2696
- }
2697
- finally {
2698
- closeSync(fd);
2699
- }
2700
- renameSync(temp, path);
2701
- const reference = { workerId: result.workerId, revision: result.revision, observedAt: result.observedAt, snapshotId,
2702
- lastExecutionOutcome: result.lastExecutionOutcome,
2703
- ...(old ? { previous: old.revision === result.revision ? old.previous : { revision: old.revision, observedAt: old.observedAt, lastExecutionOutcome: old.lastExecutionOutcome } } : {}),
2704
- };
2705
- this.commitDelegation([{ id: parentId, delegation: { ...parent.delegation,
2706
- results: [...(parent.delegation.results ?? []).filter(entry => entry.workerId !== result.workerId), reference],
2707
- } }]);
2708
- }
2709
- catch (error) {
2710
- rmSync(temp, { force: true });
2711
- if (old?.snapshotId !== snapshotId)
2712
- rmSync(path, { force: true });
2713
- throw error;
2714
- }
2715
- // Keep the latest payload only; bounded previous outcome metadata lives in the pointer.
2716
- for (const name of readdirSync(dir))
2717
- if (name.startsWith(`${result.workerId}.`) && name !== `${result.workerId}.${snapshotId}.json`) {
2718
- try {
2719
- rmSync(join(dir, name), { force: true });
2720
- }
2721
- catch { /* retry on next collection */ }
2722
- }
2723
- return result;
2724
- }
2725
- /**
2726
- * requestHash is supplied only by the trusted service: hash the ORIGINAL normalized request,
2727
- * before resolving refs. A retry keeps the original worker and pinned SHA even if HEAD moved.
2728
- * workspace.ownerRunId is the trusted service's preallocated worker UUID.
2729
- */
2730
- createOwnedRun(input, parentId, requestId, worker, requestHash, executionIdentity = { kind: 'internal' }) {
2731
- const parent = this.peek(parentId);
2732
- const authority = delegationStateSchema.safeParse(parent?.delegation);
2733
- if (!parent || !authority.success || authority.data.role !== 'root' || authority.data.historyDeletion) {
2734
- throw new Error('invalid delegation parent');
2735
- }
2736
- // Validate retry identity independently of the newly proposed resource.
2737
- const identity = workerCreationReceiptSchema.pick({ requestId: true, requestHash: true })
2738
- .parse({ requestId, requestHash });
2739
- const receipt = authority.data.receipts.find(entry => entry.requestId === identity.requestId);
2740
- if (receipt) {
2741
- if (receipt.requestHash !== identity.requestHash)
2742
- throw new Error('request ID payload conflict');
2743
- const existing = this.peek(receipt.workerId);
2744
- const metadata = delegationStateSchema.safeParse(existing?.delegation);
2745
- if (!existing || !metadata.success || metadata.data.role !== 'worker' ||
2746
- metadata.data.parentRunId !== parentId || metadata.data.workspace.ownerRunId !== existing.id ||
2747
- existing.id === parentId)
2748
- throw new Error('invalid request receipt ownership');
2749
- return existing;
2750
- }
2751
- // #816: the same check the spawn policy makes, inside the receipt transaction, so no path
2752
- // writes a receipt past either limit.
2753
- const refusal = capacityError(workerCapacity(parent, id => this.peek(id)));
2754
- if (refusal)
2755
- throw new Error(refusal);
2756
- const metadata = delegationStateSchema.parse(worker);
2757
- if (metadata.role !== 'worker' || metadata.parentRunId !== parentId ||
2758
- metadata.workspace.ownerRunId === parentId || input.worktree === false) {
2759
- throw new Error('invalid worker ownership');
2760
- }
2761
- const workspace = metadata.workspace;
2762
- if (this.hasRun(workspace.ownerRunId))
2763
- throw new Error('worker run ID collision');
2764
- for (const run of this.held.values()) {
2765
- const owned = run.delegation?.role === 'worker' ? run.delegation.workspace : undefined;
2766
- if ((owned && (owned.resourceId === workspace.resourceId || owned.path === workspace.path ||
2767
- owned.branch === workspace.branch)) || run.worktreePath === workspace.path || run.branch === workspace.branch) {
2768
- throw new Error('worker resource ownership collision');
2769
- }
2770
- }
2771
- // Runs not in memory answer through the branch and worktree columns. A worker's planned
2772
- // branch is its `branch` column; its path and resource id derive from its own run id, which
2773
- // the id check above already proved unused.
2774
- if ((this.db?.findResourceHolders({ branch: workspace.branch, worktreePath: workspace.path }) ?? [])
2775
- .some((id) => !this.held.has(id) && !this.deleted.has(id)))
2776
- throw new Error('worker resource ownership collision');
2777
- const delegation = delegationStateSchema.parse({
2778
- ...authority.data,
2779
- receipts: [...authority.data.receipts, { ...identity, workerId: workspace.ownerRunId }],
2780
- });
2781
- const run = { ...this.buildRun(input, workspace.ownerRunId), delegation: metadata };
2782
- // This transaction precedes materialization. Every launch must rotate this
2783
- // generation to starting before touching the workspace or a session.
2784
- this.writeWorkerIdentity(run.id, workerExecutionIdentitySchema.parse(executionIdentity));
2785
- this.writeWorkerExecution(run.id, { generation: randomUUID(), phase: 'queued' }, true);
2786
- // No pruning here: deleting run history cannot be part of a proposed index transaction.
2787
- this.commitIndex(new Map([[parentId, { ...parent, delegation }], [run.id, run]]));
2788
- return run;
2789
- }
2790
- /**
2791
- * Durably replace or delete staged rows together with pending dirty rows. Persist before
2792
- * changing held objects or notifying subscribers. On failure retain all pending state; flush()
2793
- * remains best-effort.
2794
- */
2795
- commitIndex(input, source) {
2796
- const staged = this.prepareCompletionActions(withoutStaleResumes(input));
2797
- if (!this.db)
2798
- throw this.openFailure ?? new Error('runs database unavailable: nothing can be saved');
2799
- this.assertWritable(staged);
2800
- this.persist(staged);
2801
- // Preserve existing record references, but expose the entire transaction before its first event.
2802
- // A finished run joins the held set for the commit and leaves at the next sweep.
2803
- for (const [id, next] of staged) {
2804
- if (!next) {
2805
- this.held.delete(id);
2806
- continue;
2807
- }
2808
- this.committing.add(id);
2809
- const current = this.held.get(id);
2810
- if (current) {
2811
- for (const key of Object.keys(current)) {
2812
- if (!(key in next))
2813
- delete current[key];
2814
- }
2815
- Object.assign(current, next);
2816
- }
2817
- else
2818
- this.held.set(id, next);
2819
- }
2820
- try {
2821
- for (const id of staged.keys()) {
2822
- const run = this.held.get(id);
2823
- if (run)
2824
- this.emit('run', run, source);
2825
- else
2826
- this.emit('deleted', id);
2827
- }
2828
- }
2829
- finally {
2830
- for (const id of staged.keys())
2831
- this.committing.delete(id);
2832
- this.sweepIfSettled(staged.keys());
2833
- }
2834
- for (const [id, next] of staged)
2835
- if (next?.archived)
2836
- this.compressor.enqueue(id);
2837
- }
2838
- /** Completion and its intent/archive share the same committed rows, including root Finish. */
2839
- prepareCompletionActions(input) {
2840
- const staged = new Map(input);
2841
- for (const [id, candidate] of input) {
2842
- if (!candidate)
2843
- continue;
2844
- const previous = this.peek(id);
2845
- let next = candidate;
2846
- const changed = candidate.status === 'done' && !candidate.archived && (previous?.status !== 'done' ||
2847
- Boolean(previous.archiveWhenDone) !== Boolean(candidate.archiveWhenDone) ||
2848
- Boolean(previous.autoMergePr) !== Boolean(candidate.autoMergePr));
2849
- if (changed && (candidate.archiveWhenDone || candidate.autoMergePr)) {
2850
- next = { ...candidate, completionAction: { id: randomUUID(), phase: 'pending' } };
2851
- staged.set(id, next);
2852
- if (next.archiveWhenDone && !next.autoMergePr) {
2853
- const blocker = this.completionArchiveBlocker(next);
2854
- next.completionAction = { ...next.completionAction, phase: blocker ? 'blocked' : 'complete', ...(blocker ? { message: blocker } : {}) };
2855
- if (!blocker)
2856
- this.stageArchive(staged, next, true);
2857
- }
2858
- }
2859
- else if (candidate.status !== 'done' || (!candidate.archiveWhenDone && !candidate.autoMergePr)) {
2860
- if (candidate.completionAction)
2861
- staged.set(id, { ...candidate, completionAction: undefined });
2862
- }
2863
- }
2864
- return staged;
2865
- }
2866
- completionArchiveBlocker(root) {
2867
- const family = [root, ...this.listWorkersOf(root.id)];
2868
- for (const run of family) {
2869
- const facts = this.facts.peek(run.id);
2870
- if (!facts || !['done', 'review', 'failed', 'cancelled'].includes(run.status) || run.waits?.some(wait => wait.phase === 'open') ||
2871
- run.hasPendingPermission || facts.pendingAsk !== undefined)
2872
- return 'Task or worker work still needs attention. Open the task or archive manually.';
2873
- if (run.delegation?.role === 'invalid' || (run.delegation?.role === 'worker' && this.readWorkerExecution(run.id)?.phase !== 'complete'))
2874
- return 'Worker execution has not settled. Open the worker or archive manually.';
2875
- }
2876
- return undefined;
2877
- }
2878
- /** One archive write for manual actions, merge observations, completion, and sweeps.
2879
- * Archiving files history away; it never stops a process or removes a worktree. */
2880
- stageArchive(staged, root, archived) {
2881
- const ids = root.delegation?.role === 'worker' ? [root.id] :
2882
- [root.id, ...new Set([...(this.db?.listIdsByParent(root.id) ?? []), ...this.listWorkersOf(root.id).map(run => run.id)])];
2883
- const now = new Date().toISOString();
2884
- for (const id of ids) {
2885
- const member = staged.get(id) ?? this.peek(id);
2886
- if (!member)
2887
- continue;
2888
- if (!archived) {
2889
- this.compressor.cancel(id);
2890
- restoreHistory(this.dataDir, id);
2891
- }
2892
- const next = { ...member, archiveBlocker: undefined };
2893
- archiveFields(next, archived, now);
2894
- staged.set(id, next);
2895
- }
2896
- }
2897
- /** A bounded persisted queue also covers projects without a live RunManager. */
2898
- listCompletionCandidates(afterSeq = 0, limit = 32) {
2899
- return this.db?.listCompletionCandidates(afterSeq, limit) ?? [];
2900
- }
2901
- canCompleteAction(id, token) {
2902
- const run = this.record(id);
2903
- return Boolean(run && run.status === 'done' && !run.archived && (run.autoMergePr || run.archiveWhenDone) &&
2904
- run.completionAction?.id === token && run.completionAction.phase !== 'complete' && !this.writeRefusal(id));
2905
- }
2906
- claimCompletionAction(id, token) {
2907
- if (!this.canCompleteAction(id, token))
2908
- return false;
2909
- const run = this.record(id);
2910
- this.assertWritable(new Map([[id, run]]));
2911
- // A normal write may defer its claim until the transaction. A remote mutation
2912
- // needs the committed claim now, and must not act on a stale row read before it.
2913
- const claim = this.db?.getClaim(familyKey(run));
2914
- return Boolean(claim && claim.session === this.owner?.session &&
2915
- claim.generation === this.claimed.get(familyKey(run)) &&
2916
- this.db?.get(id)?.revision === this.base.get(id)?.revision);
2917
- }
2918
- completeAction(id, token, phase, message) {
2919
- const run = this.record(id);
2920
- if (!run || !this.canCompleteAction(id, token))
2921
- return false;
2922
- if (run.completionAction?.phase === phase && run.completionAction.message === message)
2923
- return true;
2924
- const next = { ...run, completionAction: { id: token, phase, ...(message ? { message } : {}) } };
2925
- const staged = new Map([[id, next]]);
2926
- if (phase === 'complete' && next.archiveWhenDone) {
2927
- const blocker = this.completionArchiveBlocker(next);
2928
- if (blocker)
2929
- next.completionAction = { id: token, phase: 'blocked', message: blocker };
2930
- else
2931
- this.stageArchive(staged, next, true);
2932
- }
2933
- this.commitIndex(staged);
2934
- return true;
2935
- }
2936
- /**
2937
- * Refuse (throwing, with nothing changed) a commit that stages a quarantined run, or a run whose
2938
- * family this store does not claim and cannot take: another process owns it, or a dead process
2939
- * left it live and it has not been adopted.
2940
- */
2941
- assertWritable(staged) {
2942
- const families = new Map();
2943
- const held = new Set();
2944
- for (const [id, next] of staged) {
2945
- if (this.quarantined.has(id))
2946
- throw new RunWriteRefusedError(id, 'quarantined');
2947
- const family = next ? familyKey(next) : this.familyOf(id);
2948
- families.set(id, family);
2949
- if (this.held.has(id))
2950
- held.add(family);
2951
- }
2952
- // A run this store holds may move to a new family; any other row is claimed as a plain write.
2953
- const owned = new Set([...this.claimFamilies(held, { allowLive: true }),
2954
- ...this.claimFamilies([...families.values()].filter((family) => !held.has(family)))]);
2955
- for (const [id, family] of families) {
2956
- if (!owned.has(family))
2957
- throw new RunWriteRefusedError(id, this.runOwnership(id) === 'orphaned' ? 'orphaned' : 'foreign');
2958
- }
2959
- }
2960
- /** The family of a run this store knows: held, else its row; a run nowhere is its own. */
2961
- familyOf(id) {
2962
- const held = this.held.get(id);
2963
- return held ? familyKey(held) : this.deletedFamilies.get(id) ?? this.db?.familyOf(id) ?? id;
2964
- }
2965
- /** Schedule the sweep that lets any of `ids` leave memory, when one of them now can. */
2966
- sweepIfSettled(ids) {
2967
- for (const id of ids) {
2968
- const run = this.held.get(id);
2969
- if (run && !this.isAnchor(id, run)) {
2970
- this.scheduleSave();
2971
- return;
2972
- }
2973
- }
2974
- }
2975
- updateRun(id, patch) {
2976
- const run = this.record(id);
2977
- if (!run)
2978
- return undefined;
2979
- if (Object.prototype.hasOwnProperty.call(patch, 'issueNumber')) {
2980
- delete run.referencedIssueNumberSeeded;
2981
- }
2982
- const normalized = { ...patch };
2983
- if (normalized.pullRequestUrl !== undefined) {
2984
- this.accumulatePullRequests(run, [run.pullRequestUrl, normalized.pullRequestUrl].flatMap((url) => {
2985
- const number = refUrlNumber(url);
2986
- if (number === undefined)
2987
- return [];
2988
- const parsed = runPullRequestSchema.safeParse({ number, url, source: 'created' });
2989
- return parsed.success ? [parsed.data] : [];
2990
- }));
2991
- }
2992
- // Waits are not cleared here: RunManager cancels them explicitly when a run ends (spec
2993
- // 2026-10-17-unified-waits), so a terminal patch never retires one as a side effect.
2994
- const archived = Object.prototype.hasOwnProperty.call(normalized, 'archived')
2995
- ? Boolean(normalized.archived)
2996
- : undefined;
2997
- if (archived !== undefined) {
2998
- delete normalized.archived;
2999
- delete normalized.archivedAt;
3000
- }
3001
- // Restore before mutating so a throw leaves status and archived unchanged (#818 S3).
3002
- if (archived === false)
3003
- restoreHistory(this.dataDir, id);
3004
- // Opted-in completion and the handoff's records (the file shows only committed ones) take this
3005
- // transaction. Default-off Finish keeps its best-effort write so a locked database cannot stop cleanup.
3006
- if ((normalized.status === 'done' && (run.archiveWhenDone || run.autoMergePr)) || normalized.handoffRecords !== undefined ||
3007
- normalized.archiveWhenDone !== undefined || normalized.autoMergePr !== undefined) {
3008
- const next = { ...run, ...this.redactPatch(normalized) };
3009
- if (archived !== undefined)
3010
- archiveFields(next, archived, new Date().toISOString());
3011
- this.commitIndex(new Map([[id, next]]));
3012
- return this.record(id);
3013
- }
3014
- Object.assign(run, this.redactPatch(normalized));
3015
- // The usage-limit resume is the appointment of a `waiting` run (hearsay-tools/cezarion#1236),
3016
- // so a run coming back to life or settling retires it. `commitIndex` applies the same rule to
3017
- // every commit (`withoutStaleResumes`); this debounced path mutates the held record without it.
3018
- if (run.status !== 'waiting')
3019
- run.autoResumeAt = undefined;
3020
- if (normalized.task !== undefined)
3021
- this.resolveEditedTaskRefs(run);
3022
- if (archived !== undefined)
3023
- this.applyArchived(run, archived);
3024
- else
3025
- this.touch(run);
3026
- return run;
3027
- }
3028
- /** Prompt edits can both revoke and restore a reference. Resolve the retained working sets
3029
- * before notifying readers, using the same ambiguity, marker and repository rules as events. */
3030
- resolveEditedTaskRefs(run) {
3031
- // An edited prompt is trusted evidence, just like the initial prompt. Collect its new
3032
- // URLs without discarding earlier evidence before applying the usual resolution rules.
3033
- if (PR_URL_RE.test(run.task))
3034
- this.trackReferencedPrs(run, run.task);
3035
- if (ISSUE_URL_RE.test(run.task))
3036
- this.trackReferencedIssues(run, run.task);
3037
- if (run.referencedPrCandidates !== undefined) {
3038
- run.referencedPullRequestUrl = resolveReferencedRef(run.referencedPrCandidates, run.task, referencedPrDeclaration(run), this.repoHandle);
3039
- }
3040
- if (run.referencedIssueCandidates !== undefined) {
3041
- run.referencedIssueUrl = resolveIssueReference(run, this.repoHandle);
3042
- const number = refUrlNumber(run.referencedIssueUrl);
3043
- if (run.referencedIssueNumberSeeded) {
3044
- // We may change only the number this janitor owns, including clearing an ambiguous one.
3045
- run.issueNumber = number;
3046
- if (number === undefined)
3047
- delete run.referencedIssueNumberSeeded;
3048
- }
3049
- else if (number !== undefined && run.issueNumber === undefined &&
3050
- run.markerRefs?.issue === undefined && ISSUE_URL_RE.test(run.task)) {
3051
- // A new seed still needs trusted prompt evidence; retained tool output alone is insufficient.
3052
- run.issueNumber = number;
3053
- run.referencedIssueNumberSeeded = true;
3054
- }
3055
- }
3056
- // Legacy records may carry a URL without a candidate array. Preserve that evidence when
3057
- // allowed, while still revoking a foreign URL the edited prompt no longer corroborates.
3058
- rescopeRun(run, this.repoHandle);
3059
- }
3060
- /**
3061
- * Scrub the free-text fields of a record patch (#427 review). Redacting only
3062
- * events left a hole: `titleSummary` is derived from the RAW first agent turn
3063
- * and `error` from raw process output, so a token the agent echoed was
3064
- * `[REDACTED]` in the NDJSON yet verbatim in `runs.json` — the file the "no
3065
- * secrets in state files" rule names explicitly. These three are the only
3066
- * patch fields carrying agent/process text; the rest are ids, enums, counters
3067
- * and URLs, and running the scrubber over them would only risk mangling them.
3068
- *
3069
- * `StepState.error` is the step-level counterpart and is scrubbed the same
3070
- * way in `updateStep` — `run.ts` feeds the SAME `err.message` string to both
3071
- * calls, so redacting only the run-level copy left the token verbatim one
3072
- * field away (#456 review).
3073
- */
3074
- redactPatch(patch) {
3075
- if (process.env.CEZ_REDACT_SECRETS === '0')
3076
- return patch;
3077
- const out = { ...patch };
3078
- for (const field of ['title', 'titleSummary', 'error']) {
3079
- const value = out[field];
3080
- if (typeof value === 'string')
3081
- out[field] = this.redactText(value);
3082
- }
3083
- return out;
3084
- }
3085
- /**
3086
- * Step-level counterpart of `redactPatch` (#456 review). `error` is the only
3087
- * free-text `StepState` field — it is set from raw `err.message` /process
3088
- * output (`workflows/run/step-loop.ts` `finishStep`), and `touch()` fans the whole record out
3089
- * over SSE, so an unscrubbed copy leaked to `runs.json` AND to the browser.
3090
- * The remaining fields are ids, enums, counters and timestamps.
3091
- */
3092
- redactStepPatch(patch) {
3093
- if (process.env.CEZ_REDACT_SECRETS === '0')
3094
- return patch;
3095
- if (typeof patch.error !== 'string')
3096
- return patch;
3097
- return { ...patch, error: this.redactText(patch.error) };
3098
- }
3099
- /** Append a step to an existing run (used by "Continue" — spec 003). */
3100
- addStep(runId, step) {
3101
- const run = this.record(runId);
3102
- if (!run || run.steps.some((s) => s.id === step.id))
3103
- return;
3104
- run.steps.push({ ...step, status: 'pending', iterations: 0, tokensUsed: 0 });
3105
- this.touch(run);
3106
- }
3107
- updateStep(runId, stepId, patch) {
3108
- const run = this.record(runId);
3109
- const step = run?.steps.find((s) => s.id === stepId);
3110
- if (!run || !step)
3111
- return;
3112
- Object.assign(step, this.redactStepPatch(patch));
3113
- run.tokensUsed = run.steps.reduce((sum, s) => sum + s.tokensUsed, 0);
3114
- const startedAgentSteps = run.steps.filter((candidate) => candidate.kind === 'agent' && candidate.iterations > 0);
3115
- const directionalComplete = startedAgentSteps.length > 0 &&
3116
- startedAgentSteps.every((candidate) => candidate.usageInvocationsStarted !== undefined &&
3117
- candidate.usageInvocationsObserved !== undefined &&
3118
- candidate.usageInvocationsObserved > 0 &&
3119
- candidate.usageInvocationsStarted === candidate.usageInvocationsObserved &&
3120
- candidate.usageTurnsStarted !== undefined &&
3121
- candidate.usageTurnsRecorded !== undefined &&
3122
- candidate.usageTurnsStarted > 0 &&
3123
- candidate.usageTurnsStarted === candidate.usageTurnsRecorded &&
3124
- candidate.inputTokens !== undefined &&
3125
- candidate.outputTokens !== undefined);
3126
- run.inputTokens = directionalComplete
3127
- ? startedAgentSteps.reduce((sum, candidate) => sum + (candidate.inputTokens ?? 0), 0)
3128
- : undefined;
3129
- run.outputTokens = directionalComplete
3130
- ? startedAgentSteps.reduce((sum, candidate) => sum + (candidate.outputTokens ?? 0), 0)
3131
- : undefined;
3132
- const cost = run.steps.reduce((sum, s) => sum + (s.costUsd ?? 0), 0);
3133
- run.costUsd = run.steps.some((step) => step.costUsd !== undefined) ? cost : undefined;
3134
- this.touch(run);
3135
- }
3136
- listArchiveOnMergeCandidates(afterSeq = 0, limit = 32) {
3137
- return this.db?.listArchiveOnMergeCandidates(afterSeq, limit) ?? [];
3138
- }
3139
- /** Use unnormalized persisted evidence: cold reads must not turn interrupted work into safety. */
3140
- archiveFamily(id, isActive) {
3141
- const ids = [id, ...new Set([...(this.db?.listIdsByParent(id) ?? []), ...this.listWorkersOf(id).map(run => run.id)])];
3142
- if (ids.length > 1025)
3143
- return undefined;
3144
- const family = [];
3145
- const block = (message, runId = id) => { this.setArchiveBlocker(id, { message, runId }); return undefined; };
3146
- for (const memberId of ids) {
3147
- const row = this.db?.get(memberId);
3148
- const raw = row ? JSON.parse(row.data) : this.held.get(memberId);
3149
- const decoded = decodeRunRow(JSON.stringify(raw));
3150
- if (!decoded)
3151
- return block('Task history is unavailable. Open the task or archive it manually.', memberId);
3152
- // Do not let the runtime schema's per-entry salvage hide malformed PR authority.
3153
- if (raw && typeof raw === 'object' && 'pullRequests' in raw &&
3154
- (!Array.isArray(raw.pullRequests) || raw.pullRequests.some(entry => !runPullRequestSchema.safeParse(entry).success)))
3155
- return block('PR associations are invalid. Check the task PRs or archive manually.', memberId);
3156
- const run = this.held.get(memberId) ?? decoded.run;
3157
- if (row && !this.held.has(memberId))
3158
- this.decodeCold(row); // records the synchronous write fence
3159
- if (this.deleted.has(memberId) || this.quarantined.has(memberId) || this.writeRefusal(memberId))
3160
- return block('Task history is owned elsewhere or cannot be changed. Retry after its owner stops.', memberId);
3161
- if (this.pins.has(memberId) || isActive(memberId) || isLiveRecord(run) || row?.live ||
3162
- !['review', 'done', 'failed', 'cancelled'].includes(run.status))
3163
- return block('Task work is still active. Wait for it to finish or archive manually.', memberId);
3164
- if (run.waits?.some(wait => wait.kind === 'human' && wait.phase === 'open') || run.hasPendingPermission)
3165
- return block('Task needs an answer or permission. Open it to respond, or archive manually.', memberId);
3166
- if (run.delegation?.role === 'invalid')
3167
- return block('Worker ownership is invalid. Inspect the task or archive manually.', memberId);
3168
- const facts = this.facts.peek(memberId);
3169
- if (!facts || facts.pendingAsk !== undefined)
3170
- return block('Task has an unanswered question or unread history. Open it to respond, or archive manually.', memberId);
3171
- if (run.delegation?.role === 'worker' && this.readWorkerExecution(memberId)?.phase !== 'complete')
3172
- return block('Worker execution has not settled. Open the worker or archive manually.', memberId);
3173
- // Process and scratch cleanup evidence protects deletion, not reversible filing.
3174
- family.push(run);
3175
- }
3176
- if (family[0]?.delegation?.role === 'worker' || family[0]?.archived)
3177
- return undefined;
3178
- return family;
3179
- }
3180
- /** Blockers are feedback, never archive authority or cleanup permission. */
3181
- setArchiveBlocker(id, blocker) {
3182
- const run = this.record(id);
3183
- if (!run || run.archived || isDeepStrictEqual(run.archiveBlocker, blocker))
3184
- return;
3185
- this.commitIndex(new Map([[id, { ...run, archiveBlocker: blocker }]]));
3186
- }
3187
- archiveMergeBlocker(snapshot, missing, repoBase) {
3188
- const url = `https://github.com/${missing.owner}/${missing.repo}/pull/${missing.number}`;
3189
- const family = [snapshot.rootId, ...(this.db?.listIdsByParent(snapshot.rootId) ?? [])].flatMap(id => {
3190
- const run = this.peek(id);
3191
- return run ? [run] : [];
3192
- });
3193
- const member = family.find(run => archivePullRequests([run], repoBase)?.some(pr => pullRequestKey(pr) === pullRequestKey(missing)));
3194
- this.setArchiveBlocker(snapshot.rootId, { message: `PR ${missing.owner}/${missing.repo}#${missing.number} is not confirmed merged. Check the PR association or archive manually.`,
3195
- runId: member?.id ?? snapshot.rootId, pullRequestUrl: url });
3196
- }
3197
- hasArchiveOnMergeAssociations(id) {
3198
- return this.db?.archiveFamilyHasPullRequests(id) ?? false;
3199
- }
3200
- async prepareArchiveOnMerge(id) {
3201
- const ids = [id, ...(this.db?.listIdsByParent(id) ?? [])];
3202
- if (ids.length > 1025)
3203
- return;
3204
- for (const memberId of ids)
3205
- await this.facts.ready(memberId);
3206
- }
3207
- archiveOnMergeSnapshot(id, repoBase, isActive = () => false) {
3208
- const family = this.archiveFamily(id, isActive);
3209
- if (!family)
3210
- return undefined;
3211
- return this.archiveSnapshot(family, repoBase);
3212
- }
3213
- archiveSnapshot(family, repoBase) {
3214
- const pullRequests = archivePullRequests(family, repoBase);
3215
- if (!pullRequests) {
3216
- this.setArchiveBlocker(family[0].id, { message: 'PR associations cannot be resolved. Check task and worker PRs, or archive manually.' });
3217
- return undefined;
3218
- }
3219
- const fingerprint = archiveDigest(pullRequests);
3220
- if (family[0].autoArchive?.fingerprint === fingerprint)
3221
- return undefined;
3222
- return { rootId: family[0].id, fingerprint, pullRequests, token: archiveDigest(family.map(({ archiveBlocker: _blocker, ...run }) => run)) };
3223
- }
3224
- /** No await between final revalidation and the fenced, all-or-nothing cascade. */
3225
- archiveAfterMerge(snapshot, observations, repoBase, isActive = () => false) {
3226
- const family = this.archiveFamily(snapshot.rootId, isActive);
3227
- if (!family)
3228
- return false;
3229
- const current = this.archiveSnapshot(family, repoBase);
3230
- if (!current || current.token !== snapshot.token || current.fingerprint !== snapshot.fingerprint)
3231
- return false;
3232
- const parsed = observations.map(observation => mergedPullRequestSchema.safeParse(observation));
3233
- if (parsed.some(result => !result.success))
3234
- return false;
3235
- const merged = parsed.flatMap(result => result.success ? [result.data] : []);
3236
- const byKey = new Map(merged.map(pr => [pullRequestKey(pr), pr]));
3237
- if (byKey.size !== current.pullRequests.length || current.pullRequests.some(pr => !byKey.has(pullRequestKey(pr))))
3238
- return false;
3239
- const restoredAt = Math.max(0, ...family.map(run => run.manualUnarchivedAt ? Date.parse(run.manualUnarchivedAt) : 0));
3240
- if (restoredAt && merged.every(pr => Date.parse(pr.mergedAt) <= restoredAt))
3241
- return false;
3242
- const now = new Date().toISOString();
3243
- if (merged.some(pr => Date.parse(pr.mergedAt) > Date.parse(now)))
3244
- return false;
3245
- const staged = new Map();
3246
- this.stageArchive(staged, family[0], true);
3247
- staged.get(snapshot.rootId).autoArchive = { reason: 'pull-requests-merged', archivedAt: now, fingerprint: current.fingerprint, pullRequests: merged };
3248
- this.commitIndex(staged);
3249
- for (const id of staged.keys())
3250
- this.compressor.enqueue(id);
3251
- return true;
3252
- }
3253
- setArchived(id, archived) {
3254
- const run = this.record(id);
3255
- if (!run)
3256
- return undefined;
3257
- this.applyArchivedCascade(run, archived);
3258
- return run;
3259
- }
3260
- /** Parent + owned workers; returns how many records flipped `archived`. */
3261
- applyArchivedCascade(run, archived) {
3262
- const staged = new Map();
3263
- this.stageArchive(staged, run, archived);
3264
- let changed = 0;
3265
- for (const [id, next] of staged) {
3266
- if (next && this.peek(id)?.archived !== archived)
3267
- changed++;
3268
- if (next)
3269
- next.completionAction = undefined; // an explicit filing/restoration retires pending work
3270
- }
3271
- this.commitIndex(staged);
3272
- return changed;
3273
- }
3274
- applyArchived(run, archived) {
3275
- const changed = run.archived !== archived;
3276
- // Transcript first: a restore throw aborts with the record unchanged (#818 S3).
3277
- this.syncTranscriptForm(run.id, archived);
3278
- archiveFields(run, archived, new Date().toISOString());
3279
- this.touch(run);
3280
- return changed;
3281
- }
3282
- /** Transcript form follows `archived`: enqueue compression, or restore the plain file now. */
3283
- syncTranscriptForm(id, archived) {
3284
- if (archived)
3285
- this.compressor.enqueue(id);
3286
- else {
3287
- this.compressor.cancel(id);
3288
- restoreHistory(this.dataDir, id);
3289
- }
3290
- }
3291
- /**
3292
- * Whether this store may compress `id`'s transcript: the run exists, is archived, is not in a
3293
- * live status (queued/running/waiting), and this process holds the family's claim in `claimed`
3294
- * (not merely `pendingClaims`). Two processes never both write a run (#779, #818 B1).
3295
- */
3296
- isHistoryCompressEligible(id) {
3297
- if (this.deleted.has(id))
3298
- return false;
3299
- try {
3300
- const run = this.held.get(id) ?? this.peek(id);
3301
- if (!run || run.archived !== true || isLiveStatus(run.status))
3302
- return false;
3303
- return this.holdsCompressClaim(id);
3304
- }
3305
- catch {
3306
- return false;
3307
- }
3308
- }
3309
- /** Take the family claim if free and require it to be in `this.claimed`, not only pending. */
3310
- holdsCompressClaim(id) {
3311
- const family = this.familyOf(id);
3312
- return this.claimFamilies([family]).has(family) && this.claimed.has(family);
3313
- }
3314
- /** Startup sweep: enqueue every archived non-live run that still has a plain transcript. */
3315
- compressArchivedHistory() {
3316
- try {
3317
- const ids = new Set();
3318
- for (const key of this.db?.listKeysWhere('archived = 1 AND live = 0') ?? []) {
3319
- if (!this.deleted.has(key.id))
3320
- ids.add(key.id);
3321
- }
3322
- for (const run of this.held.values()) {
3323
- if (run.archived && !isLiveStatus(run.status) && !this.deleted.has(run.id))
3324
- ids.add(run.id);
3325
- }
3326
- for (const id of ids) {
3327
- try {
3328
- const { plain } = historyPaths(this.dataDir, id);
3329
- // Claim only ids with work: a plain file to compress, including both-present leftovers.
3330
- if (!existsSync(plain))
3331
- continue;
3332
- if (!this.holdsCompressClaim(id))
3333
- continue;
3334
- if (hasPlainHistory(this.dataDir, id))
3335
- this.compressor.enqueue(id);
3336
- }
3337
- catch {
3338
- // Best effort: one id must not stop the sweep or boot (#818 S2).
3339
- }
3340
- }
3341
- }
3342
- catch {
3343
- // listKeysWhere / open-time fs: never throw out of boot.
3344
- }
3345
- }
3346
- /** Resolves when the transcript compressor is idle (tests, shutdown). */
3347
- historyIdle() {
3348
- return this.compressor.idle();
3349
- }
3350
- /** Pin one run to the top of this project's task list, or unpin it (#935). Mirrors
3351
- * `setArchived`: sets the fields, then persists + broadcasts via `touch`, so the updated
3352
- * record rides the existing `run` SSE with no new event. Idempotent — re-pinning a pinned
3353
- * run just re-stamps `pinnedAt`.
3354
- *
3355
- * Every active status is pinnable. Archived requests clear stale metadata instead, so a
3356
- * late click racing archive cannot leave a hidden pin that reappears on unarchive. */
3357
- setPinned(id, pinned) {
3358
- const run = this.record(id);
3359
- if (!run)
3360
- return undefined;
3361
- if (pinned && !run.archived) {
3362
- run.pinned = true;
3363
- run.pinnedAt = new Date().toISOString();
3364
- }
3365
- else {
3366
- clearPin(run);
3367
- }
3368
- this.touch(run);
3369
- return run;
3370
- }
3371
- /** Bulk-archive finished runs (#780). `isSweepable` decides which; `archived` counts every
3372
- * record that flipped (cascaded workers included), `ids` lists the top-level runs picked and
3373
- * `pinnedIds` the subset that carried a pin before `clearPin` dropped it. */
3374
- archiveFinished(scope, automation) {
3375
- let archived = 0;
3376
- // Snapshot first: cascade may archive still-live workers, mutating the held set, and the pin
3377
- // has to be read before `applyArchived` clears it. Runs not in memory are picked off their
3378
- // stored summary, which carries every field `isSweepable` reads.
3379
- const picked = [...this.held.values()].filter((run) => isSweepable({ ...run, automationId: automationIdOf(run) }, scope, automation))
3380
- .map((run) => [run, this.listOrder(run)]);
3381
- for (const row of this.db?.listWhere("archived = 0 AND status IN ('done', 'failed', 'cancelled') AND parent_run_id IS NULL") ?? []) {
3382
- if (this.held.has(row.id) || this.deleted.has(row.id))
3383
- continue;
3384
- const summary = parseStoredSummary(row.summary);
3385
- if (summary && isSweepable(summary, scope, automation))
3386
- picked.push([summary, row]);
3387
- }
3388
- // Another process's runs are not this store's to archive (#779, plan step 3): they stay out.
3389
- // A sweepable run is never a worker (`isSweepable`), so each is its own family.
3390
- const writable = this.claimFamilies(picked.map(([run]) => run.id));
3391
- const mine = sortNewestFirst(picked.filter(([run]) => writable.has(run.id)));
3392
- const ids = mine.map((run) => run.id);
3393
- const pinnedIds = mine.filter((run) => run.pinned).map((run) => run.id);
3394
- for (const id of ids) {
3395
- // Re-check: a prior cascade may already have archived this id.
3396
- const run = this.record(id);
3397
- if (!run || run.archived)
3398
- continue;
3399
- archived += this.applyArchivedCascade(run, true);
3400
- }
3401
- return { archived, ids, pinnedIds };
3402
- }
3403
- /** Mark one run as read (#unread-done-items): stamp the read receipt now. Mirrors
3404
- * `setArchived` — sets the field then persists + broadcasts via `touch`, so the
3405
- * updated record rides the existing `run` SSE with no new event. Idempotent by
3406
- * design: opening an already-read thread just re-stamps a later `seenAt`. */
3407
- setRead(id) {
3408
- const run = this.record(id);
3409
- if (!run)
3410
- return undefined;
3411
- run.seenAt = new Date().toISOString();
3412
- this.touch(run);
3413
- return run;
3414
- }
3415
- /** Mark one run as UNread (#775): drop the read receipt so the run rejoins the unread
3416
- * list. The inverse of `setRead` and, like it, `touch`es so the updated record rides the
3417
- * existing `run` SSE.
3418
- *
3419
- * Deleting the field rather than adding a "manually unread" flag is the whole point:
3420
- * absent `seenAt` is ALREADY what every reader treats as unread (`isUnread` in the
3421
- * cockpit's read-state.ts, and `markAllRead`'s clause-for-clause copy of it below), so
3422
- * clearing needs no new state and writes a shape any older cezar already parses.
3423
- *
3424
- * Deliberately unconditional: clearing a receipt is always a legal write, so this
3425
- * succeeds for an already-unread run (idempotent) and for statuses that can never wear
3426
- * the marker. WHETHER the action means anything for a given run is UI policy, and lives
3427
- * in the cockpit's `runActionFlags` — the same split the rest of the store keeps. */
3428
- setUnread(id) {
3429
- const run = this.record(id);
3430
- if (!run)
3431
- return undefined;
3432
- delete run.seenAt;
3433
- this.touch(run);
3434
- return run;
3435
- }
3436
- /**
3437
- * Stamp unread finished runs in bulk and return the count. Keep the rule aligned with cockpit
3438
- * isUnread: done/failed, finished since seen, not archived; cancelled and usage-limit waiting
3439
- * runs are excluded. `automation` narrows it to one origin, as in `archiveFinished`
3440
- * (hearsay-tools/cezarion#1616); absent stamps both.
3441
- */
3442
- markAllRead(automation) {
3443
- const now = new Date().toISOString();
3444
- let count = 0;
3445
- // Runs not in memory are picked by the same rule over their stored summary, then re-checked
3446
- // on the record before they are stamped.
3447
- const candidates = [...this.held.values()];
3448
- const stored = (this.db?.listWhere(MARK_ALL_READ_SQL) ?? []).filter((row) => !this.held.has(row.id) && !this.deleted.has(row.id));
3449
- // One claim transaction for them all; another process's runs are skipped (`record` refuses).
3450
- this.claimFamilies(stored.map(rowFamily));
3451
- for (const row of stored) {
3452
- const run = this.record(row.id);
3453
- if (run)
3454
- candidates.push(run);
3455
- }
3456
- for (const run of candidates) {
3457
- const unread = !run.archived &&
3458
- (run.status === 'done' || run.status === 'failed') &&
3459
- run.finishedAt !== undefined &&
3460
- (run.seenAt === undefined || run.seenAt < run.finishedAt);
3461
- if (!unread)
3462
- continue;
3463
- if (automation !== undefined && (automationIdOf(run) !== undefined) !== automation)
3464
- continue;
3465
- run.seenAt = now;
3466
- this.touch(run);
3467
- count++;
3468
- }
3469
- return count;
3470
- }
3471
- appendEvent(runId, event) {
3472
- const run = this.record(runId);
3473
- if (!run) {
3474
- const ownership = this.runOwnership(runId);
3475
- if (ownership === 'foreign' || ownership === 'orphaned' || ownership === 'quarantined')
3476
- throw new RunWriteRefusedError(runId, ownership);
3477
- throw new Error(`unknown run: ${runId}`);
3478
- }
3479
- const seq = this.nextSeq(runId);
3480
- // Scrub credentials before the event touches disk or the live wire (#427):
3481
- // tool-result output is persisted verbatim and served back over the API, so
3482
- // a secret in an agent's command output would otherwise land in `.ai/cezar/`.
3483
- const full = this.redact(defined({ ...event, seq, ts: new Date().toISOString() }));
3484
- // Sync append keeps event order without a write queue; local NDJSON
3485
- // appends at agent-event rates are effectively free.
3486
- if (!hasPlainHistory(this.dataDir, runId))
3487
- restoreHistory(this.dataDir, runId);
3488
- const line = `${JSON.stringify(full)}\n`;
3489
- appendFileSync(this.eventsPath(runId), line, 'utf8');
3490
- this.facts.append(runId, full, Buffer.byteLength(line));
3491
- this.maybeEnqueueHistoryCompress(run);
3492
- this.liveItems.observe(runId, full, false);
3493
- this.emit('event', { runId, event: full });
3494
- // The janitor trick: agents print the PR URL after `gh pr create` — the
3495
- // first one spotted in the transcript becomes the run's PR link. Scans v1
3496
- // fields AND nested v2 `item.*` content (#407). A URL without the created
3497
- // phrasing still feeds the referenced tier (the PR the task is about) —
3498
- // and the phrasing itself is only believed from a source that can speak
3499
- // FOR this run (`eventCreationClaimFragments`), never from quoted output.
3500
- const haystack = eventTextFragments(full).join(' ');
3501
- const agentHaystack = eventAgentTextFragments(full).join(' ');
3502
- // The creation CLAIM is read from a narrower source than the URL is
3503
- // (`eventCreationClaimFragments`), which is why the two are searched
3504
- // together rather than the haystack alone: the phrase must land in the
3505
- // trusted prefix, and the link may come from anywhere after it.
3506
- const claim = eventCreationClaimFragments(full).join(' ');
3507
- if (haystack.length > 0) {
3508
- let changed = false;
3509
- // One associated URL per trusted creation claim; replayed v1/v2 reports merge by identity.
3510
- const item = full.item;
3511
- const toolOutput = item?.kind === 'tool' && typeof item.output === 'string' ? item.output : undefined;
3512
- const created = createdPrUrls(claim, haystack, toolOutput);
3513
- for (const url of created) {
3514
- const number = refUrlNumber(url);
3515
- const parsed = runPullRequestSchema.safeParse({ number, url, source: 'created' });
3516
- if (!parsed.success)
3517
- continue;
3518
- changed = this.accumulatePullRequests(run, [parsed.data]) || changed;
3519
- if (!run.pullRequestUrl) {
3520
- run.pullRequestUrl = url;
3521
- changed = true;
3522
- }
3523
- }
3524
- if (created.length > 0) {
3525
- const resolved = resolveReferencedRef(run.referencedPrCandidates ?? [], run.task, referencedPrDeclaration(run), this.repoHandle);
3526
- if (resolved !== run.referencedPullRequestUrl) {
3527
- run.referencedPullRequestUrl = resolved;
3528
- changed = true;
3529
- }
3530
- }
3531
- else if (!run.pullRequestUrl && PR_URL_RE.test(haystack) && this.trackReferencedPrs(run, haystack)) {
3532
- changed = true;
3533
- }
3534
- // Issue links feed their own referenced tier regardless of PR state —
3535
- // a task that created a PR can still be ABOUT an issue
3536
- // (spec 2026-07-21-report-ref-discovery).
3537
- if (ISSUE_URL_RE.test(haystack) &&
3538
- this.trackReferencedIssues(run, haystack, agentHaystack)) {
3539
- changed = true;
3540
- }
3541
- if (changed)
3542
- this.touch(run);
3543
- }
3544
- return full;
3545
- }
3546
- /**
3547
- * Fold every PR URL in `haystack` into the run's referenced-tier working
3548
- * set and re-resolve `referencedPullRequestUrl` (spec
3549
- * 2026-07-16-pr-autodiscovery). Mutates the record in place — the caller
3550
- * owns persistence/fan-out — and reports whether anything changed.
3551
- */
3552
- trackReferencedPrs(run, haystack) {
3553
- const seen = new Set(run.referencedPrCandidates ?? []);
3554
- const before = seen.size;
3555
- for (const match of haystack.matchAll(new RegExp(PR_URL_RE.source, 'g'))) {
3556
- if (seen.size >= MAX_PR_CANDIDATES)
3557
- break;
3558
- seen.add(match[0]);
3559
- }
3560
- if (seen.size === before)
3561
- return false;
3562
- run.referencedPrCandidates = [...seen];
3563
- run.referencedPullRequestUrl = resolveReferencedRef(run.referencedPrCandidates, run.task, referencedPrDeclaration(run), this.repoHandle);
3564
- return true;
3565
- }
3566
- /**
3567
- * The issue-side mirror of `trackReferencedPrs` (spec
3568
- * 2026-07-21-report-ref-discovery): fold every issue URL in `haystack` into
3569
- * the working set and re-resolve `referencedIssueUrl`. An unambiguous
3570
- * resolution also seeds `issueNumber` when nothing owns that field yet —
3571
- * marker and namer both outrank this janitor and overwrite it freely.
3572
- */
3573
- trackReferencedIssues(run, haystack, seedHaystack = haystack) {
3574
- const seen = new Set(run.referencedIssueCandidates ?? []);
3575
- const before = seen.size;
3576
- for (const match of haystack.matchAll(new RegExp(ISSUE_URL_RE.source, 'g'))) {
3577
- if (seen.size >= MAX_PR_CANDIDATES)
3578
- break;
3579
- seen.add(match[0]);
3580
- }
3581
- const candidatesChanged = seen.size !== before;
3582
- if (candidatesChanged)
3583
- run.referencedIssueCandidates = [...seen];
3584
- const prev = run.referencedIssueUrl;
3585
- run.referencedIssueUrl = resolveIssueReference(run, this.repoHandle);
3586
- let numberChanged = false;
3587
- if (run.markerRefs?.issue === undefined && ISSUE_URL_RE.test(seedHaystack)) {
3588
- if (run.referencedIssueUrl && run.issueNumber === undefined) {
3589
- const n = Number(run.referencedIssueUrl.split('/').pop());
3590
- if (Number.isInteger(n) && n > 0) {
3591
- run.issueNumber = n;
3592
- run.referencedIssueNumberSeeded = true;
3593
- numberChanged = true;
3594
- }
3595
- }
3596
- else if (!run.referencedIssueUrl && prev && run.referencedIssueNumberSeeded) {
3597
- // Ambiguity revoked the resolution — take back the number this janitor
3598
- // seeded from it. No chip beats a wrong chip.
3599
- delete run.issueNumber;
3600
- delete run.referencedIssueNumberSeeded;
3601
- numberChanged = true;
3602
- }
3603
- }
3604
- return candidatesChanged || run.referencedIssueUrl !== prev || numberChanged;
3605
- }
3606
- /**
3607
- * Apply agent-declared reference markers (spec 2026-07-18-task-ref-markers).
3608
- * Marker values are authoritative for the display tier: they overwrite the
3609
- * regex/namer numbers unless the prompt identifies the originating issue, and a declared PR re-resolves the referenced URL
3610
- * against the candidate working set — including down to `undefined` when no
3611
- * candidate matches (a wrong chip is worse than no chip). The created tier
3612
- * (`pullRequestUrl`) is deliberately untouched.
3613
- *
3614
- * One declaration is NOT a statement about the referenced tier: the number of the PR this run
3615
- * itself created. See `referencedPrDeclaration` — the marker contract asks the agent to
3616
- * re-declare after it opens a PR, and taking that literally cost the task the PR it was about.
3617
- */
3618
- applyMarkerRefs(runId, refs) {
3619
- const run = this.record(runId);
3620
- if (!run || (refs.pr === undefined && refs.issue === undefined))
3621
- return run;
3622
- const numbers = [...new Set([...(run.markerRefs?.pr === undefined ? [] : [run.markerRefs.pr]),
3623
- ...(refs.prs ?? (refs.pr === undefined ? [] : [refs.pr]))])];
3624
- if (numbers.length)
3625
- this.accumulatePullRequests(run, numbers.flatMap((number) => {
3626
- const matches = (run.referencedPrCandidates ?? []).filter((url) => refUrlNumber(url) === number &&
3627
- (this.repoHandle ? isRepoScopedRef(url, run.task, this.repoHandle) : promptNamesRepo(url, run.task)));
3628
- const url = matches.length === 1 ? matches[0] : matches.length === 0 && this.repoHandle
3629
- ? `https://github.com/${this.repoHandle.owner}/${this.repoHandle.name}/pull/${number}` : undefined;
3630
- const parsed = runPullRequestSchema.safeParse({ number, ...(url ? { url } : {}), source: 'declared' });
3631
- return parsed.success ? [parsed.data] : [];
3632
- }));
3633
- run.markerRefs = {
3634
- ...run.markerRefs,
3635
- ...(refs.pr !== undefined ? { pr: refs.pr } : {}),
3636
- ...(refs.issue !== undefined ? { issue: refs.issue } : {}),
3637
- };
3638
- // `prNumber` is the about-PR as well (it is what paints a numeric-only chip), so a
3639
- // re-declaration naming the created PR only FILLS it — it never overwrites the number the
3640
- // task came in with, which is still the PR this task is about.
3641
- if (refs.pr !== undefined && (run.prNumber === undefined || refs.pr !== refUrlNumber(run.pullRequestUrl))) {
3642
- run.prNumber = refs.pr;
3643
- }
3644
- if (refs.issue !== undefined) {
3645
- run.issueNumber = originatingIssue(run) ?? refs.issue;
3646
- delete run.referencedIssueNumberSeeded;
3647
- }
3648
- if (run.markerRefs.pr !== undefined) {
3649
- run.referencedPullRequestUrl = resolveReferencedRef(run.referencedPrCandidates ?? [], run.task, referencedPrDeclaration(run), this.repoHandle);
3650
- }
3651
- if (run.markerRefs.issue !== undefined) {
3652
- run.referencedIssueUrl = resolveIssueReference(run, this.repoHandle);
3653
- }
3654
- this.touch(run);
3655
- return run;
3656
- }
3657
- /** Authoritative creation keeps the first scalar for publishing, plus every created identity. */
3658
- recordCreatedPr(runId, url) {
3659
- const run = this.record(runId);
3660
- const parsed = runPullRequestSchema.safeParse({ number: refUrlNumber(url), url, source: 'created' });
3661
- if (!run || !parsed.success)
3662
- return run;
3663
- let changed = this.accumulatePullRequests(run, [parsed.data]);
3664
- if (!run.pullRequestUrl) {
3665
- run.pullRequestUrl = url;
3666
- changed = true;
3667
- }
3668
- if (changed)
3669
- this.touch(run);
3670
- return run;
3671
- }
3672
- accumulatePullRequests(run, entries) {
3673
- const next = mergePullRequests(run.pullRequests, entries, this.repoHandle
3674
- ? `https://github.com/${this.repoHandle.owner}/${this.repoHandle.name}` : undefined);
3675
- if (isDeepStrictEqual(next, run.pullRequests))
3676
- return false;
3677
- run.pullRequests = next;
3678
- return true;
3679
- }
3680
- /**
3681
- * Fan an event out to live subscribers WITHOUT writing it to the NDJSON
3682
- * file — the channel for coalesced `item.delta` flushes (protocol-v2
3683
- * performance guardrail: raw deltas never hit disk; replay = the persisted
3684
- * snapshots). Stamped with `seq`/`ts` like persisted lines so the live
3685
- * wire keeps one ordering axis. Finite polling coalesces active item content
3686
- * into bounded in-memory snapshots on that clock; disk replay still has gaps
3687
- * (dedup compares with `>`).
3688
- */
3689
- emitEphemeral(runId, event) {
3690
- const full = this.redact({ ...event, seq: this.nextSeq(runId), ts: new Date().toISOString() });
3691
- this.liveItems.observe(runId, full, true);
3692
- this.emit('event', { runId, event: full });
3693
- return full;
3694
- }
3695
- /** Lazily-collected concrete secret values from the host env (#427). */
3696
- secretValues = null;
3697
- /** Controller-issued tokens never persist, including when host-secret redaction is disabled. */
3698
- sessionSecrets = new Set();
3699
- registerSessionSecret(value) { this.sessionSecrets.add(value); }
3700
- containsSessionSecret(value) { return [...this.sessionSecrets].some(secret => value.includes(secret)); }
3701
- /**
3702
- * Scrub known credential values / token shapes from an event before it is
3703
- * persisted or fanned out. On by default; `CEZ_REDACT_SECRETS=0` opts out.
3704
- */
3705
- redact(event) {
3706
- const safe = this.sessionSecrets.size ? redactDeep(event, [...this.sessionSecrets]) : event;
3707
- if (process.env.CEZ_REDACT_SECRETS === '0')
3708
- return safe;
3709
- return redactDeep(safe, this.hostSecrets());
3710
- }
3711
- /** Best-effort scrub of one free-text string bound for `runs.json`. Honors
3712
- * the `CEZ_REDACT_SECRETS=0` opt-out itself so every caller inherits it. */
3713
- redactText(text) {
3714
- const safe = this.sessionSecrets.size ? redactSecrets(text, [...this.sessionSecrets]) : text;
3715
- if (process.env.CEZ_REDACT_SECRETS === '0')
3716
- return safe;
3717
- return redactSecrets(safe, this.hostSecrets());
3718
- }
3719
- hostSecrets() {
3720
- if (this.secretValues === null)
3721
- this.secretValues = collectSecretValues();
3722
- return this.secretValues;
3723
- }
3724
- /** The run's indexed transcript facts (#880): a read-only view, never a transcript read once
3725
- * the run's index is loaded. An unreadable transcript answers as empty, as readEvents does. */
3726
- transcriptFacts(runId) {
3727
- return this.facts.get(runId) ?? emptyFacts();
3728
- }
3729
- /** The run's transcript facts when they are known: undefined when the transcript exists but its
3730
- * facts are not current or cannot be read, so a caller can tell "no ask" from "no evidence". */
3731
- knownTranscriptFacts(runId) {
3732
- return this.facts.peek(runId);
3733
- }
3734
- hasProjection(runId, projectionId) {
3735
- return this.transcriptFacts(runId).projectionIds.includes(projectionId);
3736
- }
3737
- factsWarming = Promise.resolve();
3738
- /** Indexed family enumeration, including members not yet flushed to SQLite. */
3739
- listFamilyRunIds(rootId) {
3740
- const ids = new Set([rootId, ...(this.db?.listIdsByParent(rootId) ?? [])]);
3741
- for (const [id, run] of this.held) {
3742
- if (familyRootOf(run) === rootId)
3743
- ids.add(id);
3744
- else if (id !== rootId)
3745
- ids.delete(id);
3746
- }
3747
- for (const id of this.deleted)
3748
- ids.delete(id);
3749
- return [...ids];
3750
- }
3751
- recoveryFactIds(familyRootId) {
3752
- if (familyRootId !== undefined)
3753
- return this.listFamilyRunIds(familyRootId);
3754
- const ids = new Set();
3755
- for (const [id, run] of this.held) {
3756
- if (!isLiveRecord(run))
3757
- continue;
3758
- const root = familyRootOf(run);
3759
- for (const member of root === undefined ? [id] : this.listFamilyRunIds(root))
3760
- ids.add(member);
3761
- }
3762
- return [...ids];
3763
- }
3764
- /** Readiness owns no run snapshot across an await: refresh only the currently held owner. */
3765
- async prepareTranscriptFacts(runIds) {
3766
- for (const id of new Set(runIds)) {
3767
- // Exact sidecars resolve immediately too: recovery must yield to timers/I/O between IDs.
3768
- await new Promise(resolve => setImmediate(resolve));
3769
- await this.facts.ready(id);
3770
- }
3771
- }
3772
- prepareRecoveryFacts(familyRootId) {
3773
- return this.prepareTranscriptFacts(this.recoveryFactIds(familyRootId));
3774
- }
3775
- /** Register IDs only here; the index yields between cache reads and off-loop rebuilds. */
3776
- warmTranscriptFacts() {
3777
- this.factsWarming = Promise.resolve().then(async () => {
3778
- if (!this.db)
3779
- return;
3780
- const ids = new Set(this.recoveryFactIds());
3781
- // hearsay-tools/cezarion#949: this microtask ends open()'s synchronous slice, and on a
3782
- // large history the JSON scan for conversation roots plus one family query per root cost
3783
- // as much again. Past one slice's worth of runs, yield before the scan and between root
3784
- // batches; a small store (every unit test) still registers in this one microtask.
3785
- const large = this.listRunIds().length > WARM_IDS_PER_SLICE;
3786
- const turn = async () => {
3787
- await new Promise(resolve => setImmediate(resolve));
3788
- return this.db !== null;
3789
- };
3790
- if (large && !await turn())
3791
- return;
3792
- const roots = this.listConversationRootIds();
3793
- for (let i = 0; i < roots.length; i++) {
3794
- if (large && i > 0 && i % WARM_IDS_PER_SLICE === 0 && !await turn())
3795
- return;
3796
- for (const id of this.listFamilyRunIds(roots[i]))
3797
- ids.add(id);
3798
- }
3799
- if (large && !await turn())
3800
- return;
3801
- // Re-list after the yields: a run deleted meanwhile must not be registered again.
3802
- const present = this.listRunIds();
3803
- if (large) {
3804
- const live = new Set(present);
3805
- for (const id of ids)
3806
- if (!live.has(id))
3807
- ids.delete(id);
3808
- }
3809
- for (const id of present)
3810
- ids.add(id);
3811
- await this.facts.warm(ids);
3812
- }).catch(() => undefined);
3813
- }
3814
- /** Resolves when the open-time warm-up is done (tests). */
3815
- factsWarmIdle() {
3816
- return this.factsWarming;
3817
- }
3818
- /** `readEvents` off the event loop (async read and async brotli), for collection paths. */
3819
- async readEventsAsync(runId) {
3820
- try {
3821
- const raw = await readHistoryTextAsync(this.dataDir, runId);
3822
- return raw === undefined ? [] : parseEvents(raw);
3823
- }
3824
- catch {
3825
- return [];
3826
- }
3827
- }
3828
- readEvents(runId) {
3829
- try {
3830
- const raw = readHistoryText(this.dataDir, runId);
3831
- if (raw === undefined)
3832
- return [];
3833
- return parseEvents(raw);
3834
- }
3835
- catch {
3836
- return [];
3837
- }
3838
- }
3839
- /** Private process-generation evidence; never part of run JSON or SSE. */
3840
- identityPath(id) {
3841
- return this.executionPath(id).replace(/\.execution\.json$/, '.identity.json');
3842
- }
3843
- readWorkerIdentity(id) {
3844
- try {
3845
- const fd = openSync(this.identityPath(id), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
3846
- try {
3847
- const info = fstatSync(fd);
3848
- if (!info.isFile() || info.size > 16384 || (info.mode & 0o077))
3849
- return undefined;
3850
- const buffer = Buffer.alloc(16385);
3851
- const count = readSync(fd, buffer, 0, buffer.length, 0);
3852
- return workerExecutionIdentitySchema.parse(JSON.parse(buffer.subarray(0, count).toString('utf8')));
3853
- }
3854
- finally {
3855
- closeSync(fd);
3856
- }
3857
- }
3858
- catch {
3859
- return undefined;
3860
- }
3861
- }
3862
- writeWorkerIdentity(id, identity) {
3863
- // Immutable acceptance evidence. An orphan from failed index publication cannot be adopted.
3864
- const fd = openSync(this.identityPath(id), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
3865
- try {
3866
- writeFileSync(fd, JSON.stringify(identity));
3867
- fsyncSync(fd);
3868
- }
3869
- finally {
3870
- closeSync(fd);
3871
- }
3872
- }
3873
- executionPath(id) {
3874
- z.string().uuid().parse(id);
3875
- const dir = join(this.dataDir, 'runs');
3876
- mkdirSync(dir, { recursive: true });
3877
- if (lstatSync(dir).isSymbolicLink() || realpathSync(dir) !== resolve(dir))
3878
- throw new Error('Unsafe execution directory');
3879
- return join(dir, `${id}.execution.json`);
3880
- }
3881
- readWorkerExecution(id) {
3882
- try {
3883
- const path = this.executionPath(id);
3884
- const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
3885
- try {
3886
- const info = fstatSync(fd);
3887
- if (!info.isFile() || info.size > 16384 || (info.mode & 0o077))
3888
- return undefined;
3889
- const buffer = Buffer.alloc(16385);
3890
- const count = readSync(fd, buffer, 0, buffer.length, 0);
3891
- return workerExecutionSchema.parse(JSON.parse(buffer.subarray(0, count).toString('utf8')));
3892
- }
3893
- finally {
3894
- closeSync(fd);
3895
- }
3896
- }
3897
- catch {
3898
- return undefined;
3899
- }
3900
- }
3901
- writeWorkerExecution(id, proof, fresh = false) {
3902
- const path = this.executionPath(id);
3903
- try {
3904
- const existing = lstatSync(path);
3905
- if (fresh || !existing.isFile() || existing.isSymbolicLink())
3906
- throw new Error('Unsafe execution checkpoint');
3907
- }
3908
- catch (error) {
3909
- if (error.code !== 'ENOENT')
3910
- throw error;
3911
- }
3912
- const temporary = `${path}.${randomUUID()}.tmp`;
3913
- const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
3914
- try {
3915
- writeFileSync(fd, JSON.stringify(proof));
3916
- fsyncSync(fd);
3917
- }
3918
- finally {
3919
- closeSync(fd);
3920
- }
3921
- try {
3922
- renameSync(temporary, path);
3923
- }
3924
- finally {
3925
- rmSync(temporary, { force: true });
3926
- }
3927
- }
3928
- /** Complete execution is not permission to reuse/delete persistent resources (#738).
3929
- * Synchronous, fresh and generation/resource fenced; callers hold admission off across awaits. */
3930
- workerResourcesSafe(id, generation, resourceId, admittingQueued = false) {
3931
- return this.workerResourceHolders(id, generation, resourceId, { admittingQueued }) === 'safe';
3932
- }
3933
- /** `workerResourcesSafe` with the refusal's live PIDs (empty when no PID explains it). */
3934
- workerResourceHolders(id, generation, resourceId, opts = {}) {
3935
- if (autosaveCleanupBlocker(this.dataDir, id))
3936
- return [];
3937
- const run = this.peek(id);
3938
- const proof = this.readWorkerExecution(id);
3939
- if (run?.delegation?.role !== 'worker' || run.delegation.workspace.ownerRunId !== id ||
3940
- run.delegation.workspace.resourceId !== resourceId || proof?.generation !== generation ||
3941
- (proof.phase !== 'complete' && !(opts.admittingQueued && proof.phase === 'queued')))
3942
- return [];
3943
- const record = this.readWorkerProcesses(id, generation);
3944
- if (record === 'unknown' || !agentTmpDirOwnershipProven(this.dataDir, id))
3945
- return [];
3946
- const paths = [run.delegation.workspace.path, ...agentTmpDirLocations(this.dataDir, id)];
3947
- // Nothing can be deleted/reused at an absent path. This lets explicit history deletion
3948
- // retire completed cleanup despite ambient denial, while recorded survivors/unknown evidence
3949
- // still block. Only ENOENT proves absence; existsSync would also hide access errors.
3950
- const absent = paths.every(path => {
3951
- try {
3952
- lstatSync(path);
3953
- return false;
3954
- }
3955
- catch (error) {
3956
- return error.code === 'ENOENT';
3957
- }
3958
- });
3959
- if (absent)
3960
- return record === 'absent' ||
3961
- ((!recordedProcessLive(record.controller) || isCurrentProcess(record.controller)) && !record.processes.some(recordedProcessLive)) ? 'safe' : [];
3962
- const probe = inspectGeneration({ ...(record === 'absent' ? {} : { record }), paths, cwds: opts.cwds });
3963
- return probe.liveness === 'gone' ? 'safe' : probe.controller !== undefined ? [probe.controller] : probe.pids;
3964
- }
3965
- /** Upgrade a legacy completed checkpoint while terminal task ownership is still known.
3966
- * No holder scan here: settlement and scheduling must never wait on cleanup proof. */
3967
- retainWorkerScratchCleanup(id) {
3968
- const run = this.peek(id), proof = this.readWorkerExecution(id);
3969
- if (run?.delegation?.role !== 'worker' || ['queued', 'running', 'waiting'].includes(run.status) || proof?.phase !== 'complete')
3970
- return;
3971
- const { resourceId, path } = run.delegation.workspace;
3972
- if (proof.scratchCleanup?.resourceId === resourceId && proof.scratchCleanup.path === path)
3973
- return;
3974
- this.writeWorkerExecution(id, { ...proof, scratchCleanup: { resourceId, path } });
3975
- }
3976
- /** Cleanup can outlive its index row, but never its generation or terminal task intent.
3977
- * `cwds` is the scratch reprobe tick's shared `/proc` snapshot (hearsay-tools/cezarion#879). */
3978
- workerScratchResourcesSafe(id, generation, resourceId, cwds) {
3979
- if (autosaveCleanupBlocker(this.dataDir, id))
3980
- return false;
3981
- const run = this.peek(id), proof = this.readWorkerExecution(id);
3982
- if (proof?.phase !== 'complete' || proof.generation !== generation || proof.scratchCleanup?.resourceId !== resourceId ||
3983
- (run && ['queued', 'running', 'waiting'].includes(run.status)))
3984
- return false;
3985
- if (run?.delegation?.role === 'worker')
3986
- return run.delegation.workspace.path === proof.scratchCleanup.path &&
3987
- this.workerResourceHolders(id, generation, resourceId, { cwds }) === 'safe';
3988
- // A valid different role contradicts the retained intent. Quarantined/missing metadata
3989
- // supplies no new authority; only the private terminal checkpoint authorizes scratch.
3990
- if (run && run.delegation?.role !== 'invalid')
3991
- return false;
3992
- const record = this.readWorkerProcesses(id, generation);
3993
- if (record === 'unknown' || !agentTmpDirOwnershipProven(this.dataDir, id))
3994
- return false;
3995
- return inspectGeneration({ ...(record === 'absent' ? {} : { record }),
3996
- paths: [proof.scratchCleanup.path, ...agentTmpDirLocations(this.dataDir, id)], cwds }).liveness === 'gone';
3997
- }
3998
- commitWorkerExecutionStart(id) {
3999
- const run = this.peek(id);
4000
- if (run?.delegation?.role !== 'worker' || run.delegation.destroy)
4001
- throw new Error('Worker cannot start');
4002
- const prior = this.readWorkerExecution(id);
4003
- if (prior?.abandoned)
4004
- throw new Error('Worker execution was abandoned; spawn a new worker instead of resuming it');
4005
- if (!prior || (prior.phase !== 'queued' && prior.phase !== 'complete')) {
4006
- throw new Error('Worker execution checkpoint does not prove safe admission');
4007
- }
4008
- if (!this.workerResourcesSafe(id, prior.generation, run.delegation.workspace.resourceId, true)) {
4009
- throw new Error('Worker resources may still be held by a process; reuse is not proven safe');
4010
- }
4011
- const generation = randomUUID();
4012
- // #469: the controller is durable before `starting`, so a crash leaves a provable generation.
4013
- this.writeWorkerProcesses(id, { generation, controller: { pid: process.pid, ...startToken(process.pid) }, processes: [] });
4014
- this.writeWorkerExecution(id, { generation, phase: 'starting' });
4015
- return generation;
4016
- }
4017
- /** Private process record (#469): which processes a generation spawned, never part of run JSON or SSE. */
4018
- processesPath(id) {
4019
- return this.executionPath(id).replace(/\.execution\.json$/, '.processes.json');
4020
- }
4021
- /** Tri-state: only ENOENT is `absent` (legacy, scan-only). A present record that is unreadable,
4022
- * wrongly permissioned, malformed or of another generation is `unknown`: never finalized or reaped. */
4023
- readWorkerProcesses(id, generation) {
4024
- try {
4025
- const fd = openSync(this.processesPath(id), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
4026
- try {
4027
- const info = fstatSync(fd);
4028
- if (!info.isFile() || info.size > 8192 || (info.mode & 0o077))
4029
- return 'unknown';
4030
- const buffer = Buffer.alloc(8193);
4031
- const count = readSync(fd, buffer, 0, buffer.length, 0);
4032
- const record = workerProcessRecordSchema.parse(JSON.parse(buffer.subarray(0, count).toString('utf8')));
4033
- return record.generation === generation ? record : 'unknown';
4034
- }
4035
- finally {
4036
- closeSync(fd);
4037
- }
4038
- }
4039
- catch (error) {
4040
- return error.code === 'ENOENT' ? 'absent' : 'unknown';
4041
- }
4042
- }
4043
- writeWorkerProcesses(id, record) {
4044
- const path = this.processesPath(id);
4045
- try {
4046
- const existing = lstatSync(path);
4047
- if (!existing.isFile() || existing.isSymbolicLink())
4048
- throw new Error('Unsafe process record');
4049
- }
4050
- catch (error) {
4051
- if (error.code !== 'ENOENT')
4052
- throw error;
4053
- }
4054
- const temporary = `${path}.${randomUUID()}.tmp`;
4055
- const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
4056
- try {
4057
- writeFileSync(fd, JSON.stringify(workerProcessRecordSchema.parse(record)));
4058
- fsyncSync(fd);
4059
- }
4060
- finally {
4061
- closeSync(fd);
4062
- }
4063
- try {
4064
- renameSync(temporary, path);
4065
- }
4066
- finally {
4067
- rmSync(temporary, { force: true });
4068
- }
4069
- }
4070
- /** Bound to the current generation. Past the cap the record never drops an entry: the
4071
- * working-directory scan is the remaining evidence. */
4072
- appendWorkerProcess(id, generation, pid, pgid) {
4073
- const record = this.readWorkerProcesses(id, generation);
4074
- if (typeof record === 'string' || this.readWorkerExecution(id)?.generation !== generation)
4075
- return false;
4076
- const entry = { pid, ...startToken(pid), ...(pgid === undefined ? {} : { pgid }) };
4077
- if (record.processes.some(known => known.pid === entry.pid && known.startToken === entry.startToken))
4078
- return true;
4079
- if (record.processes.length >= WORKER_PROCESS_CAP)
4080
- return false;
4081
- this.writeWorkerProcesses(id, { ...record, processes: [...record.processes, entry] });
4082
- return true;
4083
- }
4084
- commitWorkerExecutionComplete(id, generation) {
4085
- const proof = this.readWorkerExecution(id);
4086
- if (!proof || proof.generation !== generation)
4087
- return false;
4088
- if (proof.phase === 'queued' && this.peek(id)?.status !== 'cancelled')
4089
- return false;
4090
- try {
4091
- const run = this.peek(id);
4092
- if (run?.delegation?.role !== 'worker')
4093
- return false;
4094
- this.commitIndex(new Map([[id, run]]));
4095
- if (this.readWorkerExecution(id)?.generation !== generation)
4096
- return false;
4097
- this.writeWorkerExecution(id, { generation, phase: 'complete',
4098
- // Nothing abandons an execution any more (hearsay-tools/cezarion#889); keep a checkpoint that already was.
4099
- ...(proof.abandoned ? { abandoned: true } : {}),
4100
- ...(proof.phase === 'queued' || proof.neverMaterialized ? { neverMaterialized: true } : {}),
4101
- ...(!['queued', 'running', 'waiting'].includes(run.status) ? { scratchCleanup: {
4102
- resourceId: run.delegation.workspace.resourceId, path: run.delegation.workspace.path
4103
- } } : {}) });
4104
- // The earlier index event cannot attest exit: subscribers must observe the
4105
- // durable private proof before a terminal worker can satisfy a lifecycle wait.
4106
- this.emit('run', this.peek(id));
4107
- return true;
4108
- }
4109
- catch {
4110
- return false;
4111
- }
4112
- }
4113
- /** Cancellation must hit disk before queued no-start evidence authorizes cleanup. */
4114
- commitWorkerCancellation(id) {
4115
- const run = this.peek(id);
4116
- if (run?.delegation?.role !== 'worker')
4117
- throw new Error('Worker not found');
4118
- this.commitIndex(new Map([[id, { ...run, status: 'cancelled', finishedAt: new Date().toISOString() }]]));
4119
- }
4120
- /** Complete replacement evidence can stand in for absent child history, never for a present execution. */
4121
- readDeletedWorkerResult(parentId, workerId) {
4122
- if (this.hasRun(workerId))
4123
- return undefined;
4124
- const parent = this.peek(parentId);
4125
- if (parent?.delegation?.role !== 'root' || parent.delegation.historyDeletion)
4126
- return undefined;
4127
- const deletion = parent.delegation.receipts.find(receipt => receipt.workerId === workerId)?.deletion;
4128
- if (deletion?.phase !== 'complete')
4129
- return undefined;
4130
- const result = this.readWorkerResult(parentId, workerId);
4131
- return result?.settled && ['review', 'done', 'failed', 'cancelled'].includes(result.status) &&
4132
- result.cleanup === 'complete' && result.revision === deletion.revision &&
4133
- result.workspace.resourceId === deletion.resourceId ? result : undefined;
4134
- }
4135
- /** A deleted child's receipt replaces the private proof only after the deletion checkpoint. */
4136
- workerDeletionEvidence(id) {
4137
- const child = this.peek(id);
4138
- if (child?.delegation?.role !== 'worker' || child.delegation.workspace.ownerRunId !== id ||
4139
- child.delegation.destroy?.phase !== 'complete' || child.delegation.destroy.remaining.length ||
4140
- !['review', 'done', 'failed', 'cancelled'].includes(child.status))
4141
- return false;
4142
- return this.workerDeletionResult(id, child);
4143
- }
4144
- workerDeletionResult(id, child) {
4145
- const parent = this.peek(child.delegation.parentRunId);
4146
- if (parent?.delegation?.role !== 'root' || parent.delegation.historyDeletion)
4147
- return false;
4148
- const receipt = parent.delegation.receipts.find(entry => entry.workerId === id);
4149
- const result = this.readWorkerResult(parent.id, id);
4150
- if (!receipt || !result?.settled || result.cleanup !== 'complete' || result.status !== child.status ||
4151
- result.revision !== (child.delegation.executionRevision ?? 0))
4152
- return false;
4153
- const { state: _state, ...workspace } = result.workspace;
4154
- if (JSON.stringify(workspace) !== JSON.stringify(child.delegation.workspace))
4155
- return false;
4156
- return workerDeletionProof(receipt.deletion, result.revision, workspace.resourceId, {
4157
- readProof: () => this.readWorkerExecution(id), resourcesSafe: generation => this.workerResourcesSafe(id, generation, workspace.resourceId),
4158
- scratchMayExist: () => agentTmpDirMayExist(this.dataDir, id), executionExists: () => existsSync(this.executionPath(id)),
4159
- });
4160
- }
4161
- canDeleteRun(id) {
4162
- if (autosaveCleanupBlocker(this.dataDir, id))
4163
- return false;
4164
- const run = this.peek(id);
4165
- if (run?.delegation?.role === 'invalid')
4166
- return false;
4167
- if (run?.delegation?.role === 'worker')
4168
- return this.workerDeletionEvidence(id);
4169
- const privateWorkers = workerEvidenceRunIds(this.dataDir);
4170
- if (!privateWorkers || privateWorkers.includes(id))
4171
- return false;
4172
- if (run?.delegation?.role === 'root') {
4173
- if (run.delegation.finishRequestedAt && ['queued', 'running', 'waiting'].includes(run.status))
4174
- return false;
4175
- // Keep the parent's receipt and result ownership until each child history is explicitly removed.
4176
- if (this.listWorkersOf(id).length > 0)
4177
- return false;
4178
- return run.delegation.receipts.every(receipt => {
4179
- if (this.hasRun(receipt.workerId) || receipt.deletion?.phase !== 'complete')
4180
- return false;
4181
- // A pending parent deletion already validated the results before removing their bytes.
4182
- if (run.delegation?.role === 'root' && run.delegation.historyDeletion === 'pending')
4183
- return true;
4184
- return this.readDeletedWorkerResult(id, receipt.workerId) !== undefined;
4185
- });
4186
- }
4187
- return this.listWorkersOf(id).length === 0;
4188
- }
4189
- /** Delegated history deletion is synchronous and checkpointed; any failed byte/index removal remains retryable. */
4190
- deleteDelegatedRun(id) {
4191
- const run = this.peek(id);
4192
- try {
4193
- if (run.delegation?.role === 'worker') {
4194
- const parent = this.peek(run.delegation.parentRunId);
4195
- if (parent.delegation?.role !== 'root')
4196
- return false;
4197
- const receipt = parent.delegation.receipts.find(entry => entry.workerId === id);
4198
- const result = this.readWorkerResult(parent.id, id);
4199
- const deletion = receipt.deletion ?? { phase: 'pending', revision: result.revision,
4200
- resourceId: run.delegation.workspace.resourceId, generation: this.readWorkerExecution(id).generation };
4201
- this.commitDelegation([{ id: parent.id, delegation: { ...parent.delegation,
4202
- receipts: parent.delegation.receipts.map(entry => entry.workerId === id ? { ...entry, deletion } : entry),
4203
- } }]);
4204
- // Do not advertise artifact bytes as retained while interrupted deletion is in progress.
4205
- this.commitWorkerResult(parent.id, { ...result, observedAt: new Date().toISOString(),
4206
- diff: result.diff.state === 'available' ? { ...result.diff, snapshotId: randomUUID() } : result.diff,
4207
- artifacts: result.artifacts.state === 'available' ? { ...result.artifacts,
4208
- items: result.artifacts.items.map(item => ({ state: 'unavailable', reason: 'unreadable',
4209
- detail: 'History deletion is in progress', id: item.id, path: item.path })),
4210
- } : result.artifacts,
4211
- }, this.readWorkerResultDiff(parent.id, id));
4212
- this.removeRunHistoryBytes(id);
4213
- // Delete scratch while its generation evidence still exists; failed removal keeps it.
4214
- removeAgentTmpDir(this.dataDir, id);
4215
- if (agentTmpDirMayExist(this.dataDir, id))
4216
- return false;
4217
- // Private process/account evidence is now replaced by the exact parent receipt.
4218
- rmSync(this.identityPath(id), { force: true });
4219
- rmSync(this.processesPath(id), { force: true });
4220
- rmSync(this.executionPath(id), { force: true });
4221
- const retained = this.readWorkerResult(parent.id, id);
4222
- this.commitWorkerResult(parent.id, { ...retained, observedAt: new Date().toISOString(),
4223
- diff: retained.diff.state === 'available' ? { ...retained.diff, snapshotId: randomUUID() } : retained.diff,
4224
- artifacts: retained.artifacts.state === 'available' ? { ...retained.artifacts,
4225
- items: retained.artifacts.items.map(item => ({ state: 'deleted', reason: 'missing', id: item.id, path: item.path })),
4226
- } : retained.artifacts,
4227
- }, this.readWorkerResultDiff(parent.id, id));
4228
- this.commitIndex(new Map([[parent.id, { ...parent, delegation: { ...parent.delegation,
4229
- receipts: parent.delegation.receipts.map(entry => entry.workerId === id ? { ...entry, deletion: { ...deletion, phase: 'complete' } } : entry),
4230
- } }], [id, null]]));
4231
- }
4232
- else if (run.delegation?.role === 'root') {
4233
- this.commitDelegation([{ id, delegation: { ...run.delegation, historyDeletion: 'pending' } }]);
4234
- this.removeRunHistoryBytes(id);
4235
- rmSync(join(this.dataDir, 'runs', `${id}-worker-results`), { recursive: true, force: true });
4236
- this.commitIndex(new Map([[id, null]]));
4237
- }
4238
- else
4239
- return false;
4240
- removeAgentTmpDir(this.dataDir, id);
4241
- this.seqs.delete(id);
4242
- return true;
4243
- }
4244
- catch {
4245
- return false;
4246
- }
4247
- }
4248
- removeRunHistoryBytes(id) {
4249
- // Fixed owned paths only: never follow context descriptors supplied in persisted metadata.
4250
- z.uuid().parse(id);
4251
- const dir = join(this.dataDir, 'runs');
4252
- if (realpathSync(dir) !== resolve(dir))
4253
- throw new Error('History storage redirected');
4254
- this.facts.forget(id);
4255
- removeHistory(this.dataDir, id);
4256
- rmSync(this.handoffPath(id), { force: true });
4257
- rmSync(this.imagesDir(id), { recursive: true, force: true });
4258
- removeArtifacts(this.dataDir, id);
4259
- clearAutosaveCleanup(this.dataDir, id);
4260
- }
4261
- deleteRun(id) {
4262
- if (!this.canDeleteRun(id))
4263
- return false;
4264
- const run = this.peek(id);
4265
- if (run && this.db && (this.quarantined.has(id) || !this.claimFamilies([familyKey(run)]).size))
4266
- return false;
4267
- if (run?.delegation?.role === 'worker' || run?.delegation?.role === 'root')
4268
- return this.deleteDelegatedRun(id);
4269
- if (run)
4270
- clearAutosaveCleanup(this.dataDir, id);
4271
- const existed = run !== undefined;
4272
- this.held.delete(id);
4273
- if (existed) {
4274
- this.markDeleted(id, familyKey(run));
4275
- removeAgentTmpDir(this.dataDir, id);
4276
- this.seqs.delete(id);
4277
- this.scheduleSave();
4278
- this.emit('deleted', id);
4279
- }
4280
- return existed;
4281
- }
4282
- /** Write the pending rows out now (used on shutdown). */
4283
- flush() {
4284
- if (this.saveTimer) {
4285
- clearTimeout(this.saveTimer);
4286
- this.saveTimer = null;
4287
- }
4288
- this.saveNow();
4289
- }
4290
- // ---- internals -----------------------------------------------------------
4291
- seqs = new Map();
4292
- nextSeq(runId) {
4293
- const next = (this.seqs.get(runId) ?? this.rehydrateSeq(runId)) + 1;
4294
- this.seqs.set(runId, next);
4295
- return next;
4296
- }
4297
- /** After a restart the in-memory counter is empty while the run's NDJSON file
4298
- * keeps the history. Restarting from 1 would collide with the seqs a client
4299
- * already replayed — its `seq > maxSeq` dedup then silently drops every
4300
- * resumed event, even across a reload (the frozen-transcript symptom class
4301
- * of #424). One file read on the first post-restart append per run. */
4302
- rehydrateSeq(runId) {
4303
- return this.transcriptFacts(runId).lastSeq;
4304
- }
4305
- eventsPath(runId) {
4306
- return historyPaths(this.dataDir, runId).plain;
4307
- }
4308
- /** Same location `handoffPath()` in handoff.ts produces — inlined to keep
4309
- * the store free of upward imports. */
4310
- handoffPath(runId) {
4311
- return join(this.dataDir, 'runs', `${runId}.handoff.md`);
4312
- }
4313
- /** Agent screenshots persisted by the run manager (see persistImage). */
4314
- imagesDir(runId) {
4315
- return join(this.dataDir, 'runs', `${runId}-images`);
4316
- }
4317
- touch(run) {
4318
- this.dirty.add(run.id);
4319
- this.scheduleSave();
4320
- this.emit('run', run);
4321
- this.maybeEnqueueHistoryCompress(run);
4322
- }
4323
- /** Form follows archived: a terminal archived run with a plain transcript is queued again. */
4324
- maybeEnqueueHistoryCompress(run) {
4325
- if (run.archived && !isLiveStatus(run.status) && hasPlainHistory(this.dataDir, run.id)) {
4326
- this.compressor.enqueue(run.id);
4327
- }
4328
- }
4329
- /** The held record is gone; the next save or commit deletes its row, fenced by `family`'s claim
4330
- * and by the revision this store last saw (kept in `base` until the delete is written). */
4331
- markDeleted(id, family) {
4332
- this.liveItems.forget(id);
4333
- const read = this.coldBase.get(id);
4334
- if (!this.base.has(id) && read)
4335
- this.base.set(id, storedRow(read));
4336
- this.dirty.delete(id);
4337
- this.deleted.add(id);
4338
- this.deletedFamilies.set(id, family);
4339
- this.historyOwed.add(id);
4340
- }
4341
- /** A deleted run's history files, once the delete of its row has committed. Best effort, as
4342
- * deletion always was. */
4343
- removeOwedHistory(id) {
4344
- if (!this.historyOwed.delete(id))
4345
- return;
4346
- try {
4347
- this.facts.forget(id);
4348
- removeHistory(this.dataDir, id);
4349
- rmSync(this.handoffPath(id), { force: true });
4350
- rmSync(this.imagesDir(id), { recursive: true, force: true });
4351
- removeArtifacts(this.dataDir, id);
4352
- }
4353
- catch { /* best effort */ }
4354
- }
4355
- /**
4356
- * Count-based history retention: of the runs past the newest `MAX_RUNS_KEPT` unarchived ones,
4357
- * archive each finished run without delegation that is not pinned and whose family this store
4358
- * can claim. Ranked over the row keys (the `created_at` index, no record decoded) with memory
4359
- * laid over them, since a run created or archived since the last save has no row yet; the rows
4360
- * past the cut are then filtered in `runs.db`, so only real candidates decode. Archived runs
4361
- * are never deleted by retention — only an explicit delete, worker destruction, or history
4362
- * deletion removes a run.
4363
- */
4364
- pruneOldRuns() {
4365
- const ranked = new Map();
4366
- for (const key of this.db?.listKeysWhere('archived = ?', [0]) ?? []) {
4367
- if (!this.held.has(key.id) && !this.deleted.has(key.id))
4368
- ranked.set(key.id, key);
4369
- }
4370
- for (const run of this.held.values())
4371
- if (!run.archived)
4372
- ranked.set(run.id, { id: run.id, ...this.listOrder(run) });
4373
- const overflow = [...ranked.values()].sort(newestFirst).slice(MAX_RUNS_KEPT).map((key) => key.id);
4374
- if (overflow.length === 0)
4375
- return;
4376
- const stale = overflow.flatMap((id) => {
4377
- const run = this.held.get(id);
4378
- // Retention must not archive a live task between turns, a pinned run, or a delegation
4379
- // family whose history is promised until explicit deletion.
4380
- return run && !isLiveStatus(run.status) && !run.delegation && !run.pinned ? [id] : [];
4381
- });
4382
- const cold = overflow.filter((id) => !this.held.has(id));
4383
- if (cold.length > 0) {
4384
- // Another process's runs are its own to keep or archive (#779, plan step 3).
4385
- const rows = this.db.listWhere(RETENTION_CANDIDATES_SQL, [JSON.stringify(cold)]);
4386
- const writable = this.claimFamilies(rows.map(rowFamily));
4387
- for (const row of rows)
4388
- if (writable.has(rowFamily(row)))
4389
- stale.push(row.id);
4390
- }
4391
- for (const id of stale) {
4392
- const run = this.record(id);
4393
- if (!run || run.archived)
4394
- continue;
4395
- this.applyArchived(run, true);
4396
- removeAgentTmpDir(this.dataDir, id);
4397
- }
4398
- }
4399
- /** Debounced so token-usage updates don't rewrite a row per event. Nothing to schedule without
4400
- * a database: a `RunStore.unavailable` store, or a closed one, writes nothing. */
4401
- scheduleSave() {
4402
- if (this.saveTimer || !this.db)
4403
- return;
4404
- this.saveTimer = setTimeout(() => {
4405
- this.saveTimer = null;
4406
- this.saveNow();
4407
- }, 300);
4408
- this.saveTimer.unref?.();
4409
- }
4410
- /** The single database write, so a test can fail it the way a full disk would. */
4411
- writeIndex(changes) {
4412
- return this.db.transaction(changes);
4413
- }
4414
- /**
4415
- * Write `staged` plus everything still pending — dirty rows from memory, deletions — in one
4416
- * transaction, then clear the pending marks. Throws with nothing cleared when it fails.
4417
- * Never copies or sorts the whole store: the cost is the rows that changed.
4418
- *
4419
- * Fenced (#779, plan step 3): the transaction commits only if every family it writes still
4420
- * carries this store's claim and every row is at the revision this store last saw. Otherwise
4421
- * nothing is written and `handleConflicts` deals with the rows that changed under it.
4422
- */
4423
- persist(staged) {
4424
- const upserts = [];
4425
- const deletes = [];
4426
- const families = new Map();
4427
- const extras = new Map();
4428
- const encode = (run) => {
4429
- const encoded = encodeRawRecord(run, (this.base.get(run.id) ?? this.coldBase.get(run.id))?.extras);
4430
- extras.set(run.id, encoded.extras);
4431
- const projected = { ...run };
4432
- restoreOriginatingIssue(projected);
4433
- upserts.push({ ...encodeRunRow(run, encoded.data),
4434
- issueAttributionCurrent: isDeepStrictEqual(projected, run) });
4435
- };
4436
- for (const [id, next] of staged) {
4437
- if (next)
4438
- encode(next);
4439
- else
4440
- deletes.push(id);
4441
- families.set(id, next ? familyKey(next) : this.familyOf(id));
4442
- }
4443
- for (const id of this.dirty) {
4444
- const run = this.held.get(id);
4445
- if (!run || staged.has(id))
4446
- continue;
4447
- encode(run);
4448
- families.set(id, familyKey(run));
4449
- }
4450
- for (const id of this.deleted) {
4451
- if (staged.has(id))
4452
- continue;
4453
- deletes.push(id);
4454
- families.set(id, this.familyOf(id));
4455
- }
4456
- // A row's insertion order (`seq`) is the order this write inserts it in, and it is where the
4457
- // run lists among runs created in the same millisecond. Insert new runs in creation order (the
4458
- // held set's, then staged runs not held yet), whether staged or dirty brought them here.
4459
- if (upserts.filter((row) => !this.base.has(row.id)).length > 1) {
4460
- const created = new Map();
4461
- for (const id of [...this.held.keys(), ...staged.keys()])
4462
- if (!created.has(id))
4463
- created.set(id, created.size);
4464
- upserts.sort((a, b) => created.get(a.id) - created.get(b.id));
4465
- }
4466
- // A held run whose write moved it into a new family (a worker quarantined to `invalid`) takes
4467
- // that family's claim first; one it cannot take fails the fence below as claim-lost.
4468
- const moved = [...new Set(families.values())].filter((family) => !this.claimed.has(family) && !this.pendingClaims.has(family));
4469
- if (moved.length > 0)
4470
- this.claimFamilies(moved, { allowLive: true });
4471
- let commit;
4472
- try {
4473
- commit = this.writeIndex({ upserts, deletes, ...(this.owner ? { fence: this.fence(families) } : {}) });
4474
- }
4475
- catch (error) {
4476
- if (error instanceof RunConflictError)
4477
- this.handleConflicts(error, staged);
4478
- throw error;
4479
- }
4480
- for (const [family, generation] of commit.claims) {
4481
- this.claimed.set(family, generation);
4482
- this.pendingClaims.delete(family);
4483
- }
4484
- for (const row of upserts) {
4485
- this.base.set(row.id, { revision: commit.revisions.get(row.id), seq: commit.seqs.get(row.id), data: row.data, extras: extras.get(row.id) });
4486
- }
4487
- for (const id of deletes) {
4488
- this.liveItems.forget(id);
4489
- this.base.delete(id);
4490
- this.deletedFamilies.delete(id);
4491
- this.removeOwedHistory(id);
4492
- }
4493
- this.dirty.clear();
4494
- this.deleted.clear();
4495
- if (this.saveTimer) {
4496
- clearTimeout(this.saveTimer);
4497
- this.saveTimer = null;
4498
- }
4499
- }
4500
- /** What a write of these rows (id → family) must still find: this store's claims, at the
4501
- * generations it took them, and each row at the revision it last saw (none for a new row). */
4502
- fence(families) {
4503
- const claims = new Map();
4504
- const rows = new Map();
4505
- for (const [id, family] of families) {
4506
- const pending = this.pendingClaims.get(family);
4507
- // Generations start at 1, so an unclaimed family's 0 fails the fence as claim-lost.
4508
- claims.set(family, pending !== undefined ? { take: pending } : { generation: this.claimed.get(family) ?? 0 });
4509
- rows.set(id, { revision: (this.base.get(id) ?? this.coldBase.get(id))?.revision ?? null, family });
4510
- }
4511
- return { owner: this.owner, claims, rows };
4512
- }
4513
- /**
4514
- * Handle a fenced-write conflict. Save unexpected conflict evidence before clearing pending
4515
- * state or quarantining the row. If evidence persistence fails, retain pending writes. Other
4516
- * rows remain writable; stale unclaimed reads only fail their write.
4517
- */
4518
- handleConflicts(error, staged) {
4519
- const unexpected = error.conflicts.filter((conflict) => this.held.has(conflict.id) || this.deleted.has(conflict.id) || this.coldBase.get(conflict.id)?.owned === true);
4520
- if (unexpected.length === 0 || !this.db || !this.owner)
4521
- return;
4522
- const evidence = unexpected.map((conflict) => {
4523
- const seen = this.base.get(conflict.id) ?? this.coldBase.get(conflict.id);
4524
- const local = staged.has(conflict.id) ? staged.get(conflict.id) : this.deleted.has(conflict.id) ? null : this.held.get(conflict.id) ?? null;
4525
- return {
4526
- runId: conflict.id, reason: conflict.reason,
4527
- baseRevision: seen?.revision ?? null, baseData: seen?.data ?? null,
4528
- localData: local === null ? null : JSON.stringify(local), localDeleted: local === null,
4529
- currentRevision: conflict.current?.revision ?? null, currentData: conflict.current?.data ?? null,
4530
- };
4531
- });
4532
- let seqs;
4533
- try {
4534
- seqs = this.db.recordConflicts(this.owner.session, evidence);
4535
- }
4536
- catch (evidenceError) {
4537
- const message = evidenceError instanceof Error ? evidenceError.message : String(evidenceError);
4538
- console.error(`[cez] ${RUNS_DB_FILE}: could not record the conflicting write on ${unexpected.map((c) => c.id).join(', ')}; it stays pending: ${message}`);
4539
- return;
4540
- }
4541
- unexpected.forEach((conflict, index) => {
4542
- const family = this.familyOf(conflict.id);
4543
- this.liveItems.forget(conflict.id);
4544
- this.quarantined.add(conflict.id);
4545
- this.dirty.delete(conflict.id);
4546
- this.deleted.delete(conflict.id);
4547
- this.deletedFamilies.delete(conflict.id);
4548
- // The delete did not happen, so the history stays with the row.
4549
- this.historyOwed.delete(conflict.id);
4550
- if (conflict.reason === 'claim-lost') {
4551
- this.claimed.delete(family);
4552
- this.pendingClaims.delete(family);
4553
- }
4554
- const decoded = conflict.current ? decodeRunRow(conflict.current.data) : undefined;
4555
- const current = decoded?.run;
4556
- const held = this.held.get(conflict.id);
4557
- if (current && conflict.current) {
4558
- // The other writer's record as it stands, normalized only as a live owner's run would be.
4559
- reconcileLoadedRun(current, { keepLive: true });
4560
- rescopeRun(current, this.repoHandle);
4561
- if (held)
4562
- replaceRecord(held, current);
4563
- this.base.set(conflict.id, { revision: conflict.current.revision, seq: conflict.current.seq, data: conflict.current.data, extras: decoded.extras });
4564
- this.emit('run', held ?? current);
4565
- }
4566
- else {
4567
- this.held.delete(conflict.id);
4568
- this.base.delete(conflict.id);
4569
- this.emit('deleted', conflict.id);
4570
- }
4571
- console.error(`[cez] run ${conflict.id} was changed by another writer (${conflict.reason}); this process will not write it again until cezar restarts. Evidence: ${join(this.dataDir, RUNS_DB_FILE)}, table run_conflicts, seq ${seqs[index]}.`);
4572
- });
4573
- this.scheduleSave();
4574
- }
4575
- /** Write what is pending, then (unless closing) let every run whose write settled leave memory. */
4576
- saveNow(evict = true) {
4577
- if (!this.db)
4578
- return;
4579
- // A second attempt only after a conflict excluded its rows: the unrelated rest goes out at once.
4580
- for (let attempt = 0; attempt < 2 && (this.dirty.size > 0 || this.deleted.size > 0); attempt++) {
4581
- const quarantined = this.quarantined.size;
4582
- try {
4583
- this.persist(new Map());
4584
- }
4585
- catch (err) {
4586
- if (err instanceof RunConflictError && this.quarantined.size > quarantined)
4587
- continue;
4588
- // A pending save may outlive its directory; never recreate it or hide live-directory
4589
- // failures. The rows stay pending (and held), so the next save or commit retries them.
4590
- if (existsSync(this.dataDir)) {
4591
- const message = err instanceof Error ? err.message : String(err);
4592
- console.error(`[cez] failed to save ${RUNS_DB_FILE}: ${message}`);
4593
- }
4594
- break;
4595
- }
4596
- }
4597
- if (evict)
4598
- this.evictSettled();
4599
- }
4600
- /**
4601
- * Write what is pending and release the database (store disposal, process shutdown).
4602
- * Idempotent. A closed store keeps answering reads for what it holds — the final save evicts
4603
- * nothing — but cannot read `runs.db` any more, so a run that had already left memory reads as
4604
- * absent. It saves nothing more, and a durable commit on it throws.
4605
- */
4606
- close() {
4607
- this.liveItems.clear();
4608
- // Demand-bound feeds stop before storage disappears during project removal/shutdown.
4609
- this.emit('closed');
4610
- this.compressor.stop();
4611
- this.facts.stop();
4612
- this.facts.flush();
4613
- if (this.saveTimer) {
4614
- clearTimeout(this.saveTimer);
4615
- this.saveTimer = null;
4616
- }
4617
- this.saveNow(false);
4618
- if (this.db && this.owner) {
4619
- // Every claim goes with the store. Should the release fail, the claims stay until this
4620
- // process exits; from then on they are provably dead and the next opener takes them.
4621
- try {
4622
- this.db.releaseClaims(this.owner.session);
4623
- }
4624
- catch { /* see above */ }
4625
- }
4626
- this.claimed.clear();
4627
- this.pendingClaims.clear();
4628
- if (this.owner)
4629
- closeClaimSession(this.owner.session);
4630
- this.db?.close();
4631
- this.db = null;
4632
- }
4633
- }
4634
- function archiveDigest(value) {
4635
- return createHash('sha256').update(JSON.stringify(value)).digest('hex');
4636
- }
4637
- function archiveFields(run, archived, now) {
4638
- run.archived = archived;
4639
- run.archivedAt = archived ? now : undefined;
4640
- if (archived) {
4641
- clearPendingAutoResume(run);
4642
- clearPin(run);
4643
- }
4644
- else
4645
- run.manualUnarchivedAt = now;
4646
- }
4647
- //# sourceMappingURL=store.js.map