@wjarka/cezarion 0.17.0 → 0.18.0

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