@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.40

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 (423) hide show
  1. package/CHANGELOG.md +455 -0
  2. package/README.md +376 -125
  3. package/dist/adapters.d.ts +4 -1
  4. package/dist/adapters.js +4 -2
  5. package/dist/agent-rows.d.ts +0 -2
  6. package/dist/agents-store.d.ts +5 -5
  7. package/dist/agents-store.js +14 -14
  8. package/dist/bash-read-only.js +2 -1
  9. package/dist/cap-short.d.ts +12 -0
  10. package/dist/cap-short.js +60 -0
  11. package/dist/cap.d.ts +3 -10
  12. package/dist/cap.js +2 -5
  13. package/dist/catalog.d.ts +0 -5
  14. package/dist/catalog.js +1 -5
  15. package/dist/chatgpt-plan.d.ts +163 -0
  16. package/dist/chatgpt-plan.js +549 -0
  17. package/dist/cli.js +26 -6
  18. package/dist/composio-preset.d.ts +8 -0
  19. package/dist/composio-preset.js +8 -7
  20. package/dist/composio-triggers.d.ts +113 -0
  21. package/dist/composio-triggers.js +411 -0
  22. package/dist/computer-calls.js +2 -2
  23. package/dist/computer-commands.d.ts +2 -0
  24. package/dist/computer-commands.js +7 -3
  25. package/dist/computer-live.d.ts +7 -2
  26. package/dist/computer-live.js +9 -5
  27. package/dist/computer-routes.d.ts +2 -2
  28. package/dist/computer-routes.js +2 -2
  29. package/dist/computer-setting.d.ts +3 -3
  30. package/dist/computer-setting.js +5 -5
  31. package/dist/computer-view.d.ts +15 -0
  32. package/dist/computer-view.js +16 -2
  33. package/dist/computer-viewer.js +14 -1
  34. package/dist/computers.d.ts +5 -2
  35. package/dist/computers.js +9 -5
  36. package/dist/console/assets/index-B8Zn1Iqn.css +1 -0
  37. package/dist/console/assets/index-Jbxjcmdp.js +705 -0
  38. package/dist/console/index.html +2 -2
  39. package/dist/console-links.js +3 -3
  40. package/dist/decision-cap.d.ts +2 -5
  41. package/dist/decision-cap.js +3 -6
  42. package/dist/decision-rows.js +11 -11
  43. package/dist/email/account.d.ts +83 -0
  44. package/dist/email/account.js +159 -0
  45. package/dist/email/answer.d.ts +15 -0
  46. package/dist/email/answer.js +217 -0
  47. package/dist/email/email-faux.d.ts +95 -0
  48. package/dist/email/email-faux.js +849 -0
  49. package/dist/email/labels.d.ts +1 -0
  50. package/dist/email/labels.js +84 -0
  51. package/dist/email/mail.d.ts +186 -0
  52. package/dist/email/mail.js +373 -0
  53. package/dist/email/names.d.ts +50 -0
  54. package/dist/email/names.js +74 -0
  55. package/dist/email/routes.d.ts +10 -0
  56. package/dist/email/routes.js +50 -0
  57. package/dist/email/tools.d.ts +27 -0
  58. package/dist/email/tools.js +562 -0
  59. package/dist/environment.d.ts +17 -2
  60. package/dist/environment.js +36 -8
  61. package/dist/errors.d.ts +6 -0
  62. package/dist/errors.js +12 -0
  63. package/dist/eval-mailbox.d.ts +103 -0
  64. package/dist/eval-mailbox.js +236 -0
  65. package/dist/graph-view.d.ts +9 -2
  66. package/dist/graph-view.js +6 -2
  67. package/dist/harness-install.d.ts +28 -2
  68. package/dist/harness-install.js +147 -59
  69. package/dist/harness-opencode/adapter.js +2 -26
  70. package/dist/harness-opencode/facts.js +5 -2
  71. package/dist/harness-opencode/host/policy.d.ts +2 -0
  72. package/dist/harness-opencode/host/policy.js +10 -5
  73. package/dist/harness-opencode/index.d.ts +1 -1
  74. package/dist/harness-opencode/index.js +1 -1
  75. package/dist/harness-opencode/versions.d.ts +6 -0
  76. package/dist/harness-opencode/versions.js +6 -0
  77. package/dist/harness-table.js +8 -5
  78. package/dist/harness.d.ts +12 -0
  79. package/dist/harness.js +15 -3
  80. package/dist/hosted-search.d.ts +3 -1
  81. package/dist/hosted-search.js +51 -11
  82. package/dist/import-sources.d.ts +1 -1
  83. package/dist/import-sources.js +3 -3
  84. package/dist/import.d.ts +21 -0
  85. package/dist/import.js +186 -1
  86. package/dist/key-check.d.ts +0 -2
  87. package/dist/key-check.js +3 -4
  88. package/dist/key-refusal.d.ts +8 -2
  89. package/dist/key-refusal.js +16 -13
  90. package/dist/learn/check.d.ts +18 -3
  91. package/dist/learn/check.js +328 -3
  92. package/dist/learn/compile.d.ts +12 -4
  93. package/dist/learn/compile.js +57 -20
  94. package/dist/learn/grade.d.ts +4 -0
  95. package/dist/learn/grade.js +4 -1
  96. package/dist/learn/promote.d.ts +130 -64
  97. package/dist/learn/promote.js +113 -202
  98. package/dist/learn/refit.d.ts +21 -12
  99. package/dist/learn/refit.js +51 -23
  100. package/dist/learn/replay-calls.js +1 -1
  101. package/dist/learn/skills.d.ts +2 -7
  102. package/dist/learn/skills.js +28 -14
  103. package/dist/learned-nodes.d.ts +15 -7
  104. package/dist/learned-nodes.js +29 -5
  105. package/dist/learned-workflow.d.ts +41 -31
  106. package/dist/learned-workflow.js +122 -63
  107. package/dist/learning-batch.js +3 -3
  108. package/dist/learning-cost.d.ts +35 -8
  109. package/dist/learning-cost.js +27 -9
  110. package/dist/learning-routes.d.ts +2 -4
  111. package/dist/learning-routes.js +20 -3
  112. package/dist/learning-words.d.ts +1 -1
  113. package/dist/learning-words.js +4 -1
  114. package/dist/learning.d.ts +5 -5
  115. package/dist/link-check.d.ts +27 -0
  116. package/dist/link-check.js +164 -0
  117. package/dist/local-models.d.ts +39 -2
  118. package/dist/local-models.js +49 -5
  119. package/dist/mcp-pin-first.js +6 -0
  120. package/dist/mcp-secret-writes.js +3 -0
  121. package/dist/mcp-servers-store.d.ts +25 -16
  122. package/dist/mcp-servers-store.js +23 -3
  123. package/dist/model-form.d.ts +11 -0
  124. package/dist/model-form.js +17 -1
  125. package/dist/model.d.ts +26 -6
  126. package/dist/model.js +126 -18
  127. package/dist/monid.d.ts +26 -31
  128. package/dist/monid.js +84 -79
  129. package/dist/native/binding.d.ts +13 -0
  130. package/dist/native/binding.js +57 -0
  131. package/dist/native/cli.d.ts +2 -0
  132. package/dist/native/cli.js +48 -0
  133. package/dist/native/connection.d.ts +8 -0
  134. package/dist/native/connection.js +94 -0
  135. package/dist/native/context.d.ts +6 -0
  136. package/dist/native/context.js +22 -0
  137. package/dist/native/discovery.d.ts +27 -0
  138. package/dist/native/discovery.js +404 -0
  139. package/dist/native/environment.d.ts +4 -0
  140. package/dist/native/environment.js +18 -0
  141. package/dist/native/history.d.ts +20 -0
  142. package/dist/native/history.js +147 -0
  143. package/dist/native/instructions.d.ts +21 -0
  144. package/dist/native/instructions.js +173 -0
  145. package/dist/native/remote-worker-bridge.d.ts +3 -0
  146. package/dist/native/remote-worker-bridge.js +278 -0
  147. package/dist/native/remote.d.ts +187 -0
  148. package/dist/native/remote.js +492 -0
  149. package/dist/native/runtime.d.ts +17 -0
  150. package/dist/native/runtime.js +316 -0
  151. package/dist/native/runtimes.d.ts +66 -0
  152. package/dist/native/runtimes.js +41 -0
  153. package/dist/native/schema.d.ts +46 -0
  154. package/dist/native/schema.js +41 -0
  155. package/dist/native/types.d.ts +87 -0
  156. package/dist/native/types.js +1 -0
  157. package/dist/observation/http.d.ts +4 -0
  158. package/dist/observation/http.js +140 -0
  159. package/dist/observation/observer.d.ts +301 -0
  160. package/dist/observation/observer.js +919 -0
  161. package/dist/observation/schema.d.ts +52 -0
  162. package/dist/observation/schema.js +154 -0
  163. package/dist/openapi.d.ts +2 -1
  164. package/dist/openapi.js +404 -93
  165. package/dist/paid-calls.d.ts +8 -3
  166. package/dist/paid-calls.js +6 -2
  167. package/dist/place-offers.d.ts +4 -8
  168. package/dist/place-offers.js +4 -9
  169. package/dist/port-models.d.ts +10 -2
  170. package/dist/port-models.js +6 -2
  171. package/dist/print.d.ts +4 -2
  172. package/dist/print.js +4 -3
  173. package/dist/propose.d.ts +1 -2
  174. package/dist/propose.js +10 -1
  175. package/dist/provider.d.ts +5 -1
  176. package/dist/provider.js +8 -0
  177. package/dist/push-handler.d.ts +3 -2
  178. package/dist/push-handler.js +20 -6
  179. package/dist/refusal-words.d.ts +14 -0
  180. package/dist/refusal-words.js +16 -2
  181. package/dist/run-launch.d.ts +12 -1
  182. package/dist/run-launch.js +13 -4
  183. package/dist/run-learning-served.d.ts +75 -2
  184. package/dist/run-manifest.d.ts +3 -0
  185. package/dist/run-manifest.js +13 -1
  186. package/dist/run-reads-over-store.d.ts +3 -3
  187. package/dist/run-reads-over-store.js +13 -10
  188. package/dist/run-timeline-served.d.ts +3 -2
  189. package/dist/run-timeline-served.js +8 -9
  190. package/dist/run-view.d.ts +44 -38
  191. package/dist/run-view.js +93 -56
  192. package/dist/runnable.d.ts +13 -5
  193. package/dist/runnable.js +69 -60
  194. package/dist/runner/adapter-loop.d.ts +48 -13
  195. package/dist/runner/adapter-loop.js +691 -254
  196. package/dist/runner/adapter-run-spec.d.ts +38 -12
  197. package/dist/runner/adapter-run-spec.js +175 -106
  198. package/dist/runner/adapters/pi.d.ts +24 -0
  199. package/dist/runner/adapters/pi.js +59 -9
  200. package/dist/runner/beside.d.ts +3 -1
  201. package/dist/runner/beside.js +24 -8
  202. package/dist/runner/claim-secrets.d.ts +3 -1
  203. package/dist/runner/claim-secrets.js +28 -4
  204. package/dist/runner/cli-run-spec.d.ts +30 -0
  205. package/dist/runner/cli-run-spec.js +95 -50
  206. package/dist/runner/computer-channel.d.ts +5 -2
  207. package/dist/runner/computer-channel.js +3 -2
  208. package/dist/runner/computer-journal.d.ts +6 -0
  209. package/dist/runner/computer-journal.js +8 -10
  210. package/dist/runner/conformance/harness.js +6 -3
  211. package/dist/runner/end-of-run.d.ts +2 -0
  212. package/dist/runner/end-of-run.js +3 -1
  213. package/dist/runner/feedback-round.d.ts +40 -13
  214. package/dist/runner/feedback-round.js +64 -16
  215. package/dist/runner/harness-loops.js +17 -0
  216. package/dist/runner/journal-kinds.d.ts +59 -13
  217. package/dist/runner/journal-kinds.js +48 -5
  218. package/dist/runner/learning-dispatch.d.ts +3 -2
  219. package/dist/runner/learning-dispatch.js +6 -6
  220. package/dist/runner/learning-end.d.ts +4 -0
  221. package/dist/runner/learning-end.js +64 -36
  222. package/dist/runner/learning-factory.d.ts +3 -0
  223. package/dist/runner/learning-factory.js +8 -2
  224. package/dist/runner/learning-loop.d.ts +2 -0
  225. package/dist/runner/learning-loop.js +19 -4
  226. package/dist/runner/loop.d.ts +18 -0
  227. package/dist/runner/loop.js +34 -0
  228. package/dist/runner/main.d.ts +6 -1
  229. package/dist/runner/main.js +26 -4
  230. package/dist/runner/mcp-run.d.ts +4 -1
  231. package/dist/runner/mcp-run.js +11 -5
  232. package/dist/runner/meta-tools.d.ts +10 -3
  233. package/dist/runner/meta-tools.js +112 -36
  234. package/dist/runner/metrics.d.ts +80 -21
  235. package/dist/runner/metrics.js +114 -39
  236. package/dist/runner/model-route.d.ts +14 -3
  237. package/dist/runner/model-route.js +155 -19
  238. package/dist/runner/monid-run.d.ts +8 -6
  239. package/dist/runner/monid-run.js +117 -43
  240. package/dist/runner/native-loop.d.ts +11 -0
  241. package/dist/runner/native-loop.js +438 -0
  242. package/dist/runner/promotion.d.ts +76 -10
  243. package/dist/runner/promotion.js +476 -154
  244. package/dist/runner/redact.js +3 -0
  245. package/dist/runner/reflect-hook.js +9 -0
  246. package/dist/runner/runner.d.ts +7 -1
  247. package/dist/runner/runner.js +8 -4
  248. package/dist/runner/sdk-loop.d.ts +7 -0
  249. package/dist/runner/sdk-loop.js +470 -0
  250. package/dist/runner/spec-holds.d.ts +16 -2
  251. package/dist/runner/spec-holds.js +42 -14
  252. package/dist/runner/store-secrets.js +17 -2
  253. package/dist/runner/workflow-first.d.ts +30 -20
  254. package/dist/runner/workflow-first.js +22 -32
  255. package/dist/runner/workflow-loop.d.ts +1 -1
  256. package/dist/runner/workflow-loop.js +18 -12
  257. package/dist/runner/workflow-spec.d.ts +4 -1
  258. package/dist/runner/workflow-spec.js +56 -45
  259. package/dist/runs-over-store.d.ts +30 -2
  260. package/dist/runs-over-store.js +46 -14
  261. package/dist/sdk/runs.d.ts +115 -0
  262. package/dist/sdk/runs.js +422 -0
  263. package/dist/sdk/schema.d.ts +175 -0
  264. package/dist/sdk/schema.js +138 -0
  265. package/dist/sdk/workflows.d.ts +22 -0
  266. package/dist/sdk/workflows.js +39 -0
  267. package/dist/secrets.d.ts +2 -0
  268. package/dist/secrets.js +19 -1
  269. package/dist/server.d.ts +48 -32
  270. package/dist/server.js +568 -137
  271. package/dist/skill-route.d.ts +3 -0
  272. package/dist/skill-route.js +16 -0
  273. package/dist/skills/agentrun-serve/SKILL.md +368 -0
  274. package/dist/stats.d.ts +10 -10
  275. package/dist/store/agent-body.d.ts +12 -8
  276. package/dist/store/agent-body.js +9 -4
  277. package/dist/store/dialect.d.ts +3 -0
  278. package/dist/store/dialect.js +1 -0
  279. package/dist/store/index.d.ts +1 -1
  280. package/dist/store/native-command-owner.d.ts +10 -0
  281. package/dist/store/native-command-owner.js +47 -0
  282. package/dist/store/postgres/connection.d.ts +11 -5
  283. package/dist/store/postgres/connection.js +44 -17
  284. package/dist/store/postgres/dialect.js +5 -0
  285. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  286. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  287. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  288. package/dist/store/postgres/store.d.ts +7 -3
  289. package/dist/store/postgres/store.js +4 -0
  290. package/dist/store/schema.d.ts +7 -0
  291. package/dist/store/schema.js +20 -1
  292. package/dist/store/sqlite/connection.js +72 -8
  293. package/dist/store/sqlite/run-launch.d.ts +11 -0
  294. package/dist/store/sqlite/run-launch.js +8 -0
  295. package/dist/store/sqlite/run-patch.d.ts +8 -1
  296. package/dist/store/sqlite/run-patch.js +14 -3
  297. package/dist/store/sqlite/store.js +170 -34
  298. package/dist/store/sqlite/worker.d.ts +2 -0
  299. package/dist/store/sqlite/worker.js +13 -10
  300. package/dist/store/store.d.ts +67 -7
  301. package/dist/store-reads/analytics.d.ts +7 -7
  302. package/dist/store-reads/analytics.js +23 -5
  303. package/dist/store-reads/cap.js +8 -6
  304. package/dist/store-reads/journal.d.ts +5 -0
  305. package/dist/store-reads/journal.js +85 -41
  306. package/dist/store-reads/learning.d.ts +115 -18
  307. package/dist/store-reads/learning.js +170 -68
  308. package/dist/store-reads/runs.d.ts +5 -0
  309. package/dist/store-reads/runs.js +3 -2
  310. package/dist/store-view.js +75 -21
  311. package/dist/template-eval.d.ts +73 -11
  312. package/dist/template-eval.js +535 -75
  313. package/dist/templates.d.ts +84 -21
  314. package/dist/templates.js +254 -47
  315. package/dist/text-urls.d.ts +38 -0
  316. package/dist/text-urls.js +170 -0
  317. package/dist/timeline/index.d.ts +3 -2
  318. package/dist/timeline/index.js +3 -2
  319. package/dist/timeline/labels.d.ts +5 -2
  320. package/dist/timeline/labels.js +29 -6
  321. package/dist/timeline/origin.d.ts +1 -1
  322. package/dist/timeline/origin.js +2 -2
  323. package/dist/timeline/render-text.js +1 -1
  324. package/dist/timeline/timeline.d.ts +66 -4
  325. package/dist/timeline/timeline.js +160 -30
  326. package/dist/timeline/util.d.ts +5 -0
  327. package/dist/timeline/util.js +44 -8
  328. package/dist/timeline/web-calls.d.ts +17 -0
  329. package/dist/timeline/web-calls.js +106 -0
  330. package/dist/tool-gate.d.ts +46 -44
  331. package/dist/tool-gate.js +101 -92
  332. package/dist/tool-list.d.ts +4 -1
  333. package/dist/tool-list.js +8 -1
  334. package/dist/tool-names.d.ts +18 -13
  335. package/dist/tool-names.js +19 -17
  336. package/dist/tool-plane.d.ts +17 -13
  337. package/dist/tool-plane.js +12 -5
  338. package/dist/tools.d.ts +57 -16
  339. package/dist/tools.js +33 -28
  340. package/dist/trigger-adapter.d.ts +56 -5
  341. package/dist/trigger-adapter.js +6 -0
  342. package/dist/trigger-adapters.js +3 -1
  343. package/dist/trigger-composio.d.ts +10 -0
  344. package/dist/trigger-composio.js +122 -0
  345. package/dist/trigger-email.d.ts +4 -0
  346. package/dist/trigger-email.js +181 -0
  347. package/dist/trigger-signatures.d.ts +6 -10
  348. package/dist/trigger-signatures.js +16 -16
  349. package/dist/trigger-targets.d.ts +1 -1
  350. package/dist/trigger-targets.js +4 -3
  351. package/dist/trigger-webhook.js +6 -4
  352. package/dist/triggers.d.ts +105 -8
  353. package/dist/triggers.js +286 -62
  354. package/dist/uploads.d.ts +9 -0
  355. package/dist/uploads.js +27 -0
  356. package/dist/validate.js +1 -7
  357. package/dist/web-fake.d.ts +56 -0
  358. package/dist/web-fake.js +102 -0
  359. package/dist/web-fetch-direct.d.ts +3 -0
  360. package/dist/web-fetch-direct.js +4 -1
  361. package/dist/web-fetch.d.ts +5 -1
  362. package/dist/web-fetch.js +8 -31
  363. package/dist/web-search.d.ts +51 -2
  364. package/dist/web-search.js +116 -18
  365. package/dist/webhooks.d.ts +2 -1
  366. package/dist/webhooks.js +5 -1
  367. package/dist/workflow/decision-recovery.js +5 -2
  368. package/dist/workflow/decisions.d.ts +7 -0
  369. package/dist/workflow/node-runner.js +10 -2
  370. package/dist/workspace/archil-claim.d.ts +3 -0
  371. package/dist/workspace/archil-claim.js +9 -2
  372. package/dist/workspace/computer-deps.d.ts +22 -9
  373. package/dist/workspace/computer-deps.js +78 -37
  374. package/dist/workspace/computer-for-claim.d.ts +54 -4
  375. package/dist/workspace/computer-for-claim.js +179 -39
  376. package/dist/workspace/computer-janitor.d.ts +10 -3
  377. package/dist/workspace/computer-janitor.js +96 -29
  378. package/dist/workspace/computer-kept.d.ts +82 -0
  379. package/dist/workspace/computer-kept.js +147 -0
  380. package/dist/workspace/computer-mcp.js +4 -3
  381. package/dist/workspace/computer-ports.d.ts +23 -3
  382. package/dist/workspace/computer-ports.js +115 -5
  383. package/dist/workspace/index.d.ts +1 -2
  384. package/dist/workspace/index.js +1 -2
  385. package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
  386. package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
  387. package/dist/workspace/resolve-computer.d.ts +15 -3
  388. package/dist/workspace/resolve-computer.js +10 -7
  389. package/dist/workspace/revision-skills.d.ts +6 -2
  390. package/dist/workspace/revision-skills.js +12 -5
  391. package/dist/workspace/run-end-computers.d.ts +30 -0
  392. package/dist/workspace/run-end-computers.js +137 -0
  393. package/dist/workspace/run-tools.d.ts +28 -29
  394. package/dist/workspace/run-tools.js +29 -30
  395. package/dist/wrap-up.d.ts +19 -5
  396. package/dist/wrap-up.js +31 -4
  397. package/package.json +13 -9
  398. package/skills/agentrun-serve/SKILL.md +248 -10
  399. package/templates/README.md +117 -23
  400. package/templates/TOOLS.md +168 -0
  401. package/templates/code-review/agent.md +18 -4
  402. package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
  403. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  404. package/templates/code-review/evals/other-repo/case.yaml +1 -1
  405. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  406. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  407. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  408. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  409. package/templates/code-review/skills/review/DEEP.md +2 -2
  410. package/templates/code-review/skills/review/REVIEWER.md +2 -2
  411. package/templates/code-review/skills/review/SKILL.md +7 -3
  412. package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
  413. package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
  414. package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
  415. package/templates/release-notes/evals/other-repo/case.yaml +1 -1
  416. package/dist/console/assets/index-CjqQirbo.css +0 -1
  417. package/dist/console/assets/index-b6-XY5A9.js +0 -576
  418. package/dist/host-calls.d.ts +0 -20
  419. package/dist/host-calls.js +0 -12
  420. package/dist/runner/adapters/pi-computer.d.ts +0 -9
  421. package/dist/runner/adapters/pi-computer.js +0 -51
  422. package/dist/workspace/computer-script.d.ts +0 -53
  423. package/dist/workspace/computer-script.js +0 -172
@@ -6,11 +6,11 @@ import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
6
6
  import { isCliRecord, piShaped, runEntries, runTimeline } from "../store-reads/journal.js";
7
7
  import { recordedCalls, replayCalls, SKIPPED_WRITE, toolClassOf, toolWord, unmarkedWords } from "../learn/replay-calls.js";
8
8
  import { isObject } from "../validate.js";
9
- import { answersAlone, championOf, clears, gradesOf, PROMOTE_BAR, promotionOf, promotionsOf, recordPromotion, REFIT_EVERY, REPLAY_INPUTS, REPLAY_MIN, replayingOf, replayScore, answerCorrect, scoredRows, skippedToolsOf, thresholdsOf } from "../learn/promote.js";
9
+ import { answersAlone, championOf, clears, gradesOf, PROMOTE_BAR, PROMOTIONS_KEPT, promotionOf, promotionsOf, recordPromotion, REFIT_EVERY, REPLAY_INPUTS, REPLAY_MIN, replayingOf, scoreOf, skippedToolsOf, thresholdsOf, withinBar } from "../learn/promote.js";
10
10
  import { sendCommand } from "./commands.js";
11
11
  import { ClaimRefused } from "./loop-contract.js";
12
12
  import { readSnapshot } from "../learn/folder.js";
13
- import { refitGuards } from "../learn/refit.js";
13
+ import { refitGuards, refitRowsOf, scoreRows } from "../learn/refit.js";
14
14
  import { fits, servedOf, workflowDigest } from "./workflow-first.js";
15
15
  import { learningCommit } from "../learn/commit.js";
16
16
  import { recordOnly } from "../learn/promote.js";
@@ -29,7 +29,7 @@ export function claimPromotion(deps) {
29
29
  const seed = deps.launch.learning?.seed;
30
30
  return {
31
31
  ...deps,
32
- kept: async () => servedOf(await runEntries(deps.store, deps.runId, deps.context).catch(() => [])),
32
+ kept: async () => (deps.runId ? servedOf(await runEntries(deps.store, deps.runId, deps.context).catch(() => [])) : undefined),
33
33
  commit: async (files, reason, id) => {
34
34
  const folder = deps.folder();
35
35
  try {
@@ -57,18 +57,21 @@ export function claimPromotion(deps) {
57
57
  },
58
58
  };
59
59
  }
60
- /** A replay run's claim (launch.replay), once its first choice is made: refused (ClaimRefused: the run ends failed, no
61
- * agent turn, nothing sent) unless its revision's record still says replaying (it is reserved before its runs are
62
- * created), or has none (trimmed), and the claim laid that revision to serve it. A superseded, promoted or held revision's
63
- * replay run never runs (a cancel that never reached it included); one whose workflow is not laid at its digest (the
64
- * seed could not be read, the folder moved on) never falls to the agent's path. Any other run: nothing to check. */
65
- export async function replayClaimed(store, agentId, launch, choice) {
60
+ /** A replay run's claim (launch.replay) of run `runId`, once its first choice is made: refused (ClaimRefused: the run ends
61
+ * failed, no agent turn, nothing sent) unless its revision's record still says replaying and names it among its runs (it
62
+ * is reserved before its runs are created), or has none (trimmed), and the claim laid that revision to serve it. A
63
+ * promoted or held revision's replay run never runs (a cancel that never reached it included), nor an older
64
+ * replay's leftover once its revision replays again; one whose workflow is not laid at its digest (the seed could not be
65
+ * read, the folder moved on) never falls to the agent's path. Any other run: nothing to check. */
66
+ export async function replayClaimed(store, agentId, runId, launch, choice) {
66
67
  if (!launch.replay)
67
68
  return;
68
69
  const { workflow, digest } = launch.replay;
69
70
  const record = promotionOf(await promotionsOf(store.settings, agentId), workflow, digest);
70
71
  if (record && record.decided !== "replaying")
71
- throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision is ${record.decided === "superseded" ? `superseded by ${record.superseded_by ?? "a newer revision"}` : record.decided === "promote" ? "promoted already" : "held already"}.`);
72
+ throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision is ${record.decided === "skipped" ? `skipped for ${record.skipped_by ?? "a newer revision"}` : record.decided === "promote" ? "promoted already" : record.decided === "hold" ? "held already" : "queued, not replaying"}.`);
73
+ if (record && !record.runs?.includes(runId))
74
+ throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision replays again${record.replay_id ? ` (replay ${record.replay_id})` : ""}, and this run is not one of its runs.`);
72
75
  if (choice.serve?.replay !== true || choice.serve.name !== workflow)
73
76
  throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: its claim laid no workflow by that name at that digest. The agent was not asked.`);
74
77
  }
@@ -89,7 +92,7 @@ const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
89
92
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
90
93
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
91
94
  * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its promotion moved on (decide:
92
- * a replay started, settled or superseded, a dry-run promote), and then servingNow alone says who serves: the champion
95
+ * a replay started, queued or settled, a dry-run promote), and then servingNow alone says who serves: the champion
93
96
  * (championOf), the laid text when it is the champion, its own text read from its record's commit when not; undefined
94
97
  * when none serves (the agent takes the run). A digest's own record never says it serves. */
95
98
  export const promotionGate = (deps) => {
@@ -102,7 +105,7 @@ export const promotionGate = (deps) => {
102
105
  try {
103
106
  const kept = await keptFor(deps, workflow, digest);
104
107
  if (kept)
105
- return kept;
108
+ return { workflow: kept };
106
109
  await decide(deps, workflow, digest);
107
110
  return await servingNow(deps, workflow, digest, true);
108
111
  }
@@ -113,7 +116,8 @@ export const promotionGate = (deps) => {
113
116
  // The champion alone, for a laid revision that does not take the run's input (workflowFirstOf): nothing replays.
114
117
  const champion = async (workflow, digest) => {
115
118
  try {
116
- return (await keptFor(deps, workflow, digest)) ?? (await servingNow(deps, workflow, digest, false));
119
+ const kept = await keptFor(deps, workflow, digest);
120
+ return kept ? { workflow: kept } : await servingNow(deps, workflow, digest, false);
117
121
  }
118
122
  catch (error) {
119
123
  return failed(workflow, error);
@@ -126,8 +130,9 @@ export const promotionGate = (deps) => {
126
130
  * never serves again. The laid revision at `digest` when it is the champion and still serves after its graded check
127
131
  * (stillServing, a refit written as the next revision); `laid` false: it is not asked (the laid text does not take the
128
132
  * input). Another champion: its text at its record's commit (its digest checked), still serving after its graded check
129
- * with no refit (a refit written now would land over the laid revision on the folder's main). Undefined when none
130
- * serves: none promoted, the champion held, or its text cannot be read (the agent takes the run). */
133
+ * with no refit (a refit written now would land over the laid revision on the folder's main). With the champion's
134
+ * promotion (its since), which the run keeps (WorkflowFirst.promotion). Undefined when none serves: none promoted, the
135
+ * champion held, or its text cannot be read (the agent takes the run). */
131
136
  async function servingNow(deps, workflow, digest, laid) {
132
137
  const records = await promotionsOf(deps.store.settings, deps.agentId);
133
138
  const champion = championOf(records, workflow.name);
@@ -137,8 +142,9 @@ async function servingNow(deps, workflow, digest, laid) {
137
142
  deps.log(`workflow-first: ${workflow.name} at ${digest} was promoted, but the revision promoted after it is held; no revision serves, the agent takes this run`);
138
143
  return undefined;
139
144
  }
145
+ const serving = (text, under) => (under ? { workflow: text, ...(under.since !== undefined ? { promotion: under.since } : {}) } : undefined);
140
146
  if (champion.digest === digest)
141
- return laid && (await stillServing(deps, workflow, digest, champion)) ? workflow : undefined;
147
+ return laid ? serving(workflow, await stillServing(deps, workflow, digest, champion)) : undefined;
142
148
  if (!deps.champion)
143
149
  return undefined;
144
150
  const text = champion.commit ? await deps.champion(workflow.name, champion.commit).catch(() => undefined) : undefined;
@@ -146,10 +152,11 @@ async function servingNow(deps, workflow, digest, laid) {
146
152
  deps.log(`workflow-first: ${workflow.name}'s champion at ${champion.digest} could not be read from its learning commit; the agent takes this run`);
147
153
  return undefined;
148
154
  }
149
- if (!(await stillServing({ ...deps, commit: undefined }, text, champion.digest, champion)))
155
+ const under = await stillServing({ ...deps, commit: undefined }, text, champion.digest, champion);
156
+ if (!under)
150
157
  return undefined;
151
158
  deps.log(`workflow-first: ${workflow.name}'s champion at ${champion.digest} serves this run while ${digest} ${own?.decided === "promote" ? "is a revision promoted before it" : "is not promoted"}`);
152
- return text;
159
+ return serving(text, under);
153
160
  }
154
161
  /** A run already executing keeps its revision: when an earlier claim of it served `workflow` first (its WORKFLOW_FIRST
155
162
  * entry, answered or handed back: `deps.kept`), a re-claim serves the same digest, whoever the champion is now (the loop
@@ -172,8 +179,9 @@ async function keptFor(deps, workflow, digest) {
172
179
  deps.log(`workflow-first: ${workflow.name} at ${kept.digest} served this run on an earlier claim; it keeps that revision${kept.digest === digest ? "" : ` (its text could not be read: the laid ${digest} stands in, the kept outcome recovered as it is)`}`);
173
180
  return workflow;
174
181
  }
175
- /** Moves the laid revision's promotion on: a new digest is replayed (or promoted on its dry run), a replaying one
176
- * settled once its runs ended, a rival replay superseded. It decides nothing about who serves (servingNow does). */
182
+ /** Moves the laid revision's promotion on: a new digest is replayed (or promoted on its dry run), or queued while another
183
+ * replays; a replaying one settled once its runs ended; the replay ahead of a queued one settled, then the queued one
184
+ * started. It decides nothing about who serves (servingNow does). */
177
185
  async function decide(deps, workflow, digest) {
178
186
  const { store, agentId, log } = deps;
179
187
  const now = deps.now ?? Date.now;
@@ -184,8 +192,8 @@ async function decide(deps, workflow, digest) {
184
192
  log(`workflow-first: ${workflow.name} at ${digest} is held (${record.reason}); it does not serve this run`);
185
193
  return;
186
194
  }
187
- if (record?.decided === "superseded") {
188
- log(`workflow-first: ${workflow.name} at ${digest} was superseded by ${record.superseded_by ?? "a newer revision"} while it replayed; it does not serve this run`);
195
+ if (record?.decided === "skipped") {
196
+ log(`workflow-first: ${workflow.name} at ${digest} was skipped (${record.reason}); it does not serve this run`);
189
197
  return;
190
198
  }
191
199
  if (record?.decided === "replaying") {
@@ -195,61 +203,176 @@ async function decide(deps, workflow, digest) {
195
203
  log(`workflow-first: ${workflow.name} at ${digest} is replaying on ${plural(record.runs?.length ?? 0, "graded input")}; it does not serve this run`);
196
204
  return;
197
205
  }
198
- // A new revision. One challenger at a time: one still replaying is superseded by it when it is the newest revision (the
199
- // one the learning folder's main holds now); a run pinned to an older commit lays an older text, and starts nothing,
200
- // whenever it was launched.
201
- const rivals = replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest);
202
- if (rivals.length) {
206
+ // A new revision, or a queued one. One replay at a time, and a running replay finishes: the laid one moves only when it
207
+ // is the newest revision (the one the learning folder's main holds now); a run pinned to an older commit lays an older
208
+ // text and starts nothing, whenever it was launched (a queued one it lays is skipped for the newest). With the records at
209
+ // the trim's cap a revision with none may be one whose record the trim dropped (a skipped or held one): it starts only
210
+ // when it is the newest too, so a skipped draft never replays once its record is gone. `seen`, the queue as read before
211
+ // the newest check: every queue change below (queued, skips, a start) is one guarded write kept only while the queue
212
+ // is still that (sameQueue), so a claim that read an older main never skips a newer revision a later claim queued
213
+ // meanwhile.
214
+ const seen = await promotionsOf(store.settings, agentId);
215
+ let records = seen;
216
+ const ahead = [...replayingOf(records, workflow.name, digest), ...replayingOf(records, workflow.name, digest, "queued")];
217
+ const trimmed = records.length >= PROMOTIONS_KEPT;
218
+ if (ahead.length || record || trimmed) {
203
219
  const newest = deps.newest ? await deps.newest(workflow.name) : undefined;
204
- if (newest !== digest) {
205
- log(`workflow-first: ${workflow.name} at ${digest} is not the learning folder's newest revision of it (${newest ?? "unknown"}), and ${rivals[0].digest} replays; it does not serve this run`);
220
+ if (newest !== digest && (ahead.length || record || newest !== undefined)) {
221
+ if (record && newest !== undefined)
222
+ await skip(deps, record, newest);
223
+ else
224
+ log(`workflow-first: ${workflow.name} at ${digest} is not the learning folder's newest revision of it (${newest ?? "unknown"})${ahead[0] ? `, and ${ahead[0].digest} ${ahead[0].decided === "replaying" ? "replays" : "is queued"}` : ""}; it does not serve this run`);
206
225
  return;
207
226
  }
208
- for (const rival of rivals)
209
- await supersede(deps, rival, digest);
227
+ // The replay at work finishes: decided here once its runs ended (its verdict stands), never cancelled. While it
228
+ // runs, the laid revision is queued behind it.
229
+ for (const rival of replayingOf(records, workflow.name, digest))
230
+ await settleRival(deps, workflow.name, rival);
231
+ records = await promotionsOf(store.settings, agentId);
232
+ const running = replayingOf(records, workflow.name, digest)[0];
233
+ if (running)
234
+ return enqueue(deps, workflow, digest, record, running, seen);
210
235
  }
211
- const graded = await gradedInputs(deps, workflow);
236
+ // Its replay starts now, and only the newest queued revision replays next: any queued before it is skipped in the same
237
+ // write, and says so. Kept while its record is still none (or still the queued one read here) and the queue is still seen.
238
+ const older = replayingOf(seen, workflow.name, digest, "queued");
239
+ const skips = older.map((one) => skippedFor(deps, one, digest));
240
+ const fresh = (was, items) => ownStill(record)(was) && sameQueue(items, seen, workflow.name, digest);
241
+ const after = record ? `, queued since ${record.at} behind another revision's replay` : "";
242
+ const skipped = () => { for (const one of older)
243
+ log(`workflow-first: ${one.workflow} at ${one.digest} skipped: ${skips[0].reason}`); };
244
+ // No replay of it yet, nothing owed, so the agent's newest REPLAY_INPUTS (the one picker, inputsFor).
245
+ const { graded } = await inputsFor(deps, workflow, digest, records, "held");
212
246
  if (graded.length < REPLAY_MIN) {
213
247
  const reason = graded.length ? `${plural(graded.length, "graded input")} it fits, fewer than ${REPLAY_MIN}: promoted on its passing dry run` : `no graded input it fits: promoted on its passing dry run`;
214
- const kept = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "promote", source: "dry_run", reason, ...seedOf(deps) }, (was) => was === undefined);
215
- if (kept.won)
248
+ const kept = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "promote", source: "dry_run", reason, ...seedOf(deps) }, fresh, skips);
249
+ if (kept.won) {
250
+ skipped();
216
251
  log(`workflow-first: ${workflow.name} at ${digest}: ${reason}`);
252
+ }
217
253
  return;
218
254
  }
219
- // The challenger reserved first: its record names the replay runs it will start (their ids minted here), kept only when
220
- // this digest has none yet and no other revision of the workflow replays, in the one guarded write. Only the claim that
221
- // kept it starts them: a claim of the same digest, or of another revision, at once, starts none.
222
- const ids = graded.map(() => uuidv7());
223
- const reserved = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "replaying", source: "replay", reason: `replaying on the agent's last ${plural(graded.length, "graded input")} it fits`, runs: ids, inputs: graded.map((one) => one.grade.run), ...seedOf(deps) }, (was, items) => was === undefined && replayingOf(items, workflow.name, digest).length === 0);
255
+ const reserved = await reserve(deps, workflow, digest, graded, `replaying on the agent's last ${plural(graded.length, "graded input")} it fits${after}`, fresh, [], skips);
224
256
  if (!reserved.won) {
225
- const rival = reserved.record ? undefined : replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest)[0];
226
- if (rival)
227
- log(`workflow-first: ${workflow.name} at ${digest}: ${rival.digest} began replaying first; it does not serve this run`);
257
+ const rival = replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest)[0];
258
+ log(`workflow-first: ${workflow.name} at ${digest}: ${rival ? `${rival.digest} began replaying first` : "the queue moved since this claim read it (a claim that read a newer revision acted first)"}; it does not serve this run`);
228
259
  return;
229
260
  }
230
- for (const [i, one] of graded.entries())
231
- await startReplay(deps, workflow, digest, one.grade.run, one.launch, ids[i]);
232
- log(`workflow-first: ${workflow.name} at ${digest} is new: replaying it on the agent's last ${plural(graded.length, "graded input")} before it serves`);
261
+ skipped();
262
+ log(`workflow-first: ${workflow.name} at ${digest} is ${record ? "next" : "new"}: replaying it on the agent's last ${plural(graded.length, "graded input")} before it serves`);
233
263
  }
234
- /** Supersedes `record`, a revision still replaying, by the newer revision at `by`: its record decided superseded (kept only
235
- * while it still says replaying: a replay that settled first keeps its decision), then its replay runs not ended are
236
- * cancelled (cancelUnended) by the claim whose write kept it. */
237
- async function supersede(deps, record, by) {
264
+ /** Whether `was`, the laid revision's newest record now, is still `record`, the one its claim read: none, or the same
265
+ * queued record. */
266
+ const ownStill = (record) => (was) => (record ? was?.decided === "queued" && was.at === record.at : was === undefined);
267
+ /** The revisions of `name` other than `digest` queued in `records`, each by digest and when it was queued. */
268
+ const queueOf = (records, name, digest) => replayingOf(records, name, digest, "queued").map((one) => `${one.digest}@${one.at}`).sort().join(",");
269
+ /** Whether the queue in `items` (now, in the guarded write) is still the one in `seen` (read before the claim's newest
270
+ * check). Main only moves on, so a claim whose newest check read an older main read the records before any claim that
271
+ * read the newer main acted: when one did (queued its revision, skipped or started the one queued), the queue moved,
272
+ * and the stale claim's write is refused. A refused claim that was the newest after all (two read the same queue)
273
+ * changes nothing either; the next claim of the newest revision, which every new run lays, makes the change. */
274
+ const sameQueue = (items, seen, name, digest) => queueOf(items, name, digest) === queueOf(seen, name, digest);
275
+ /** Queues `workflow` at `digest`, the newest revision, behind `running`, the replay at work (a record of it already
276
+ * queued is left as it is), and skips each revision queued before it (only the newest queued one replays next), in one
277
+ * guarded write: kept only while its own record is still the one read and the queue is still `seen` (sameQueue). */
278
+ async function enqueue(deps, workflow, digest, record, running, seen) {
238
279
  const { store, agentId, log } = deps;
239
280
  const now = deps.now ?? Date.now;
240
- const runs = record.runs ?? [];
241
- const reason = `superseded by ${by}, a newer revision, while it replayed: its replay runs were cancelled`;
242
- const kept = await recordPromotion(store.settings, agentId, {
243
- workflow: record.workflow, digest: record.digest, at: iso(now()), decided: "superseded", source: "replay", reason, superseded_by: by,
244
- ...(runs.length ? { runs } : {}), ...(record.commit ? { commit: record.commit } : {}),
245
- }, (was) => was?.decided === "replaying");
246
- if (!kept.won)
281
+ const behind = `${running.digest}'s replay on ${plural(running.runs?.length ?? 0, "graded input")}`;
282
+ const reason = `queued behind ${behind}: a running replay finishes; the newest revision queued meanwhile replays next`;
283
+ const older = replayingOf(seen, workflow.name, digest, "queued");
284
+ const writes = [...(record ? [] : [{ workflow: workflow.name, digest, at: iso(now()), decided: "queued", source: "replay", reason, ...seedOf(deps) }]), ...older.map((one) => skippedFor(deps, one, digest))];
285
+ if (!writes.length) {
286
+ log(`workflow-first: ${workflow.name} at ${digest} is queued behind ${behind}; it does not serve this run`);
247
287
  return;
248
- const cancelled = await cancelUnended(deps, record);
249
- log(`workflow-first: ${record.workflow} at ${record.digest} superseded by ${by} while it replayed; ${plural(cancelled, "replay run")} cancelled`);
288
+ }
289
+ const kept = await recordPromotion(store.settings, agentId, writes[0], (_, items) => ownStill(record)(promotionOf(items, workflow.name, digest)) && sameQueue(items, seen, workflow.name, digest), writes.slice(1));
290
+ if (!kept.won) {
291
+ log(`workflow-first: ${workflow.name} at ${digest}: the queue moved since this claim read it (a claim that read a newer revision acted first); this claim changes nothing, and it does not serve this run`);
292
+ return;
293
+ }
294
+ log(`workflow-first: ${workflow.name} at ${digest} is ${record ? "queued" : "new: queued"} behind ${behind}; it replays once that one is decided`);
295
+ for (const one of older)
296
+ log(`workflow-first: ${one.workflow} at ${one.digest} skipped: ${writes.at(-1).reason}`);
297
+ }
298
+ /** `record`, a revision queued behind another's replay, skipped for `by`, a newer revision that came before its replay
299
+ * could start: it never replays and never serves. Never silent: the record names `by` and says why. */
300
+ function skippedFor(deps, record, by) {
301
+ const now = deps.now ?? Date.now;
302
+ const reason = `a newer draft ${by} arrived before its replay could start: only the newest queued revision replays next`;
303
+ return { workflow: record.workflow, digest: record.digest, at: iso(now()), decided: "skipped", source: "replay", reason, skipped_by: by, ...(record.commit ? { commit: record.commit } : {}) };
304
+ }
305
+ /** Skips the laid revision's own queued `record` for `by`, the newest revision (its claim laid an older text): kept only
306
+ * while it is still that queued record. */
307
+ async function skip(deps, record, by) {
308
+ const one = skippedFor(deps, record, by);
309
+ const kept = await recordPromotion(deps.store.settings, deps.agentId, one, (was) => was?.decided === "queued" && was.at === record.at);
310
+ if (kept.won)
311
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest} skipped: ${one.reason}`);
312
+ }
313
+ /** Decides `running`, the replay at work ahead of the laid (newest) revision, as a claim laying it would (relaunch, then
314
+ * settle) once its runs ended: its text read at its record's commit, its verdict standing (promote or hold) though a
315
+ * newer revision waits. No refit is written from it: the folder's main holds the newer revision, and a refit would land
316
+ * over it. Left replaying while a run of it is at work, or when its text cannot be read (its read, replayView, decides
317
+ * it then). */
318
+ async function settleRival(deps, name, running) {
319
+ const text = running.commit && deps.champion ? await deps.champion(name, running.commit).catch(() => undefined) : undefined;
320
+ if (!text || workflowDigest(text) !== running.digest) {
321
+ deps.log(`workflow-first: ${name} at ${running.digest} replays, and its text could not be read from its learning commit to decide it at this claim`);
322
+ return;
323
+ }
324
+ const ports = { ...deps, commit: undefined };
325
+ await relaunch(ports, text, running.digest, running);
326
+ const decided = await settle(ports, text, running.digest, running);
327
+ if (decided?.decided === "hold")
328
+ deps.log(`workflow-first: ${name} at ${running.digest} held with a newer revision waiting: no refit of it is written`);
329
+ }
330
+ /** Reserves a replay of `workflow` at `digest` on `graded`, then starts its runs: its replaying record names the replay
331
+ * runs it will start (their ids, and the replay's own, minted here), kept only when `still` holds of the digest's record
332
+ * now and no other revision of the workflow replays, in the one guarded write. Only the writer that kept it starts them:
333
+ * a claim of the same digest, or of another revision, or a person's ask, at once, starts none. A claim's (decide) and a
334
+ * person's (askReplay) are this one reservation. `owed`: the held runs among `graded` it must answer on (heldOn). `also`:
335
+ * records kept in the same write (a claim's skips of the revisions queued before it). */
336
+ async function reserve(deps, workflow, digest, graded, reason, still, owed = [], also = []) {
337
+ const now = deps.now ?? Date.now;
338
+ const ids = graded.map(() => uuidv7());
339
+ const launch = replayLaunchOf(deps);
340
+ const reserved = await recordPromotion(deps.store.settings, deps.agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "replaying", source: "replay", reason, runs: ids, inputs: graded.map((one) => one.grade.run), replay_id: uuidv7(), launch, ...seedOf(deps), ...(owed.length ? { held_on: owed } : {}) }, (was, items) => still(was, items) && replayingOf(items, workflow.name, digest).length === 0, also);
341
+ if (reserved.won)
342
+ for (const [i, one] of graded.entries())
343
+ await startReplay(deps, workflow, digest, one.grade.run, one.launch, ids[i], launch);
344
+ return reserved;
345
+ }
346
+ /** The launch a replay's runs all run with (PromotionRecord.launch), chosen once by the claim or person reserving it:
347
+ * `deps.launch` as a replay run takes it (a claim's claimed run's; a person's ask makes one now), the revision it runs,
348
+ * and the claimed run as the one whose per_run MCP credentials its runs are handed, when the server can seal them. A
349
+ * person's ask claims no run, so an owner's replay runs are handed none. */
350
+ function replayLaunchOf(deps) {
351
+ const { launch } = deps;
352
+ const base = {
353
+ input: null,
354
+ title: "",
355
+ place: launch.place,
356
+ ...(launch.harness !== undefined ? { harness: launch.harness } : {}),
357
+ ...(launch.model ? { model: launch.model } : {}),
358
+ ...(launch.effort !== undefined ? { effort: launch.effort } : {}),
359
+ ...(launch.maxCostUsd !== undefined ? { maxCostUsd: launch.maxCostUsd } : {}),
360
+ ...(launch.plane ? { plane: launch.plane } : {}),
361
+ ...(launch.approvers !== undefined ? { approvers: launch.approvers } : {}),
362
+ ...(launch.documents !== undefined ? { documents: launch.documents } : {}),
363
+ ...(launch.boxAllow !== undefined ? { boxAllow: launch.boxAllow } : {}),
364
+ ...(launch.boxAllowSet ? { boxAllowSet: true } : {}),
365
+ ...(launch.learning ? { learning: launch.learning } : {}),
366
+ ...(launch.archilDisk ? { archilDisk: launch.archilDisk } : {}),
367
+ };
368
+ return { revision: deps.revisionId, body: launchBody(base), ...(deps.sealKey && deps.runId ? { handed_from: deps.runId } : {}) };
250
369
  }
370
+ /** Whether `was`, a digest's newest record now, is still the replay `record` reserved: replaying, under the same replay
371
+ * id. A replay settled meanwhile, and a newer replay of the same revision its owner started since (a held revision may
372
+ * be replayed again), are not: an older replay's late decision never lands over a newer one. */
373
+ const sameReplay = (was, record) => was?.decided === "replaying" && was.replay_id === record.replay_id;
251
374
  /** Cancels each of `record`'s replay runs not ended, as a person's cancel is (an in-flight one stops, what it spent booked
252
- * on its row): once its revision is superseded, or decided with runs still at work. How many were sent their cancel. The
375
+ * on its row): once its replay is decided with runs still at work (past its deadline). How many were sent their cancel. The
253
376
  * record is the durable half: a cancel that is lost (a crash after the record, a write that fails) leaves a run whose
254
377
  * claim refuses it (replayClaimed: its revision no longer replays), so each cancel is tried and a failed one only logged. */
255
378
  async function cancelUnended(deps, record) {
@@ -270,17 +393,26 @@ async function cancelUnended(deps, record) {
270
393
  }
271
394
  return cancelled;
272
395
  }
273
- /** The agent's newest graded runs whose answer was the agent's (path `agent`, or `handed_back`: the agent finished it), at
274
- * most REPLAY_INPUTS, newest first: each with a launch read back, no uploaded file, an input `workflow` fits, never the
275
- * run being claimed, nor an archived or imported one. */
276
- async function gradedInputs(deps, workflow) {
396
+ /** The paths a graded run a replay runs on took: the agent's (`agent`, or `handed_back`: the agent finished it), or a
397
+ * learned workflow's alone (`workflow`). Each has a recorded answer (the run's final answer, whoever wrote it) and its
398
+ * grade, which is what a replay scores against (answerCorrect); the path says only whose answer it was (agentRight: on a
399
+ * `workflow` run graded wrong the agent counts right); a replay run never is one. */
400
+ const REPLAYABLE = new Set(["agent", "handed_back", "workflow"]);
401
+ /** The agent's graded runs a replay runs on (REPLAYABLE), newest first: the runs `pick.of` names, then the newest
402
+ * `pick.n` (a run both name is taken once). Each with a launch read back, no uploaded file, an input `workflow` fits,
403
+ * never the run being claimed, nor an archived or imported one. */
404
+ async function gradedInputs(deps, workflow, pick) {
277
405
  const { resolveSchemaForWorkflow } = await import("@parcha/agentrun-dsl");
278
406
  const out = [];
279
- const grades = (await gradesOf(deps.store.settings, deps.agentId)).filter((grade) => grade.path === "agent" || grade.path === "handed_back");
407
+ const of = new Set(pick.of);
408
+ let newest = 0;
409
+ let named = 0;
410
+ const grades = (await gradesOf(deps.store.settings, deps.agentId)).filter((grade) => REPLAYABLE.has(grade.path));
280
411
  for (const grade of grades.reverse()) {
281
- if (out.length >= REPLAY_INPUTS)
412
+ if (newest >= pick.n && named >= of.size)
282
413
  break;
283
- if (grade.run === deps.runId)
414
+ const asked = of.has(grade.run);
415
+ if ((!asked && newest >= pick.n) || grade.run === deps.runId)
284
416
  continue;
285
417
  const row = await deps.store.runs.get(grade.run);
286
418
  if (!row || row.archivedAt !== null || row.importedFrom)
@@ -289,46 +421,56 @@ async function gradedInputs(deps, workflow) {
289
421
  if (!launch || launch.files?.length || launch.replay || !fits(workflow, launch.input, resolveSchemaForWorkflow))
290
422
  continue;
291
423
  out.push({ grade, launch });
424
+ if (asked)
425
+ named += 1;
426
+ if (newest < pick.n)
427
+ newest += 1;
292
428
  }
293
429
  return out;
294
430
  }
295
- /** The per_run MCP credentials the claimed run was handed (its launch's sealed column, opened under the seal key), sealed
296
- * for the replay run `id` alone, as the server's start seals a run's mcp_auth (store/seal.ts sealRunMcpAuth): the replay's
297
- * claim reads them where any run's claim does (runner/mcp-claim.ts). None when the claimed run was handed none, or they
298
- * do not open. Never written anywhere else, never logged. */
299
- async function handedTo(deps, id) {
300
- if (!deps.sealKey)
431
+ /** What a replay of a revision owes before it may promote it: the served runs graded wrong it was held on
432
+ * (PromotionRecord.held_on), none when `record` owes none. Its replay puts each among its inputs (inputsFor), and its
433
+ * settle holds a replay that did not answer or hand back on each. */
434
+ const heldOn = (record) => record?.held_on ?? [];
435
+ /** The graded inputs a replay of `workflow` at `digest` runs on (gradedInputs), the one picker of both starts: always the
436
+ * served runs graded wrong its newest record holds it on (heldOn), then `held`, the inputs of its newest record that
437
+ * names any (a replay's), else, with none and nothing owed, the agent's newest REPLAY_INPUTS; or a number, the agent's
438
+ * newest that many. A claim's start (decide) is `held` on a revision with no record: the newest REPLAY_INPUTS. `owed`:
439
+ * the held runs among the picked; `named`: how many runs the records named (owed or decided on), picked or not. */
440
+ async function inputsFor(deps, workflow, digest, records, inputs) {
441
+ const held = heldOn(promotionOf(records, workflow.name, digest));
442
+ const last = inputs === "held" ? records.findLast((one) => one.workflow === workflow.name && one.digest === digest && (one.inputs?.length || one.replay?.of.length)) : undefined;
443
+ const of = [...new Set([...held, ...(last ? (last.inputs ?? last.replay.of) : [])])];
444
+ const n = typeof inputs === "number" ? inputs : of.length ? 0 : REPLAY_INPUTS;
445
+ const graded = await gradedInputs(deps, workflow, { of, n });
446
+ return { graded, owed: graded.filter((one) => held.includes(one.grade.run)).map((one) => one.grade.run), named: of.length };
447
+ }
448
+ /** The per_run MCP credentials run `launch.handed_from` was handed (its launch's sealed column, opened under the seal
449
+ * key), sealed for the replay run `id` alone, as the server's start seals a run's mcp_auth (store/seal.ts
450
+ * sealRunMcpAuth): the replay's claim reads them where any run's claim does (runner/mcp-claim.ts). None when the replay
451
+ * names no such run (an owner's), that run was handed none, or they do not open. Never written anywhere else, never
452
+ * logged. */
453
+ async function handedTo(deps, launch, id) {
454
+ const from = launch.handed_from;
455
+ if (!deps.sealKey || !from)
301
456
  return undefined;
302
- const sealed = await deps.store.runs.launch(deps.runId).then((one) => one.sealed ?? null, () => null);
303
- const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, deps.runId, sealed);
457
+ const sealed = await deps.store.runs.launch(from).then((one) => one.sealed ?? null, () => null);
458
+ const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, from, sealed);
304
459
  return handed && Object.keys(handed).length ? sealRunMcpAuth(deps.sealKey, id, handed) : undefined;
305
460
  }
306
461
  /** Starts the replay of `workflow` at `digest` on graded run `of` (its launch `from`) as run `id` (the id its reserved
307
- * record names), with the claimed run's handed credentials (handedTo). False when a run by that id exists already:
308
- * another claim created it (a relaunch and the reserving claim at once), and it is left to that one. */
309
- async function startReplay(deps, workflow, digest, of, from, id) {
310
- const { store, agentId, launch } = deps;
311
- const replay = {
312
- input: from.input,
313
- title: `Replay of ${workflow.name}: ${from.title}`.slice(0, 200),
314
- place: launch.place,
315
- ...(launch.harness !== undefined ? { harness: launch.harness } : {}),
316
- ...(launch.model ? { model: launch.model } : {}),
317
- ...(launch.effort !== undefined ? { effort: launch.effort } : {}),
318
- ...(launch.maxCostUsd !== undefined ? { maxCostUsd: launch.maxCostUsd } : {}),
319
- ...(launch.capMode !== undefined ? { capMode: launch.capMode } : {}),
320
- ...(launch.plane ? { plane: launch.plane } : {}),
321
- ...(launch.approvers !== undefined ? { approvers: launch.approvers } : {}),
322
- ...(launch.documents !== undefined ? { documents: launch.documents } : {}),
323
- ...(launch.boxAllow !== undefined ? { boxAllow: launch.boxAllow } : {}),
324
- ...(launch.boxAllowSet ? { boxAllowSet: true } : {}),
325
- ...(launch.learning ? { learning: launch.learning } : {}),
326
- ...(launch.archilDisk ? { archilDisk: launch.archilDisk } : {}),
327
- replay: { of, workflow: workflow.name, digest },
328
- };
329
- const sealed = await handedTo(deps, id);
462
+ * record names), with the replay's chosen `launch` (replayLaunchOf: its run launch, revision and handed credentials,
463
+ * handedTo), whichever claim creates it. False when a run by that id exists already: another claim created it (a
464
+ * relaunch and the reserving claim at once), and it is left to that one. */
465
+ async function startReplay(deps, workflow, digest, of, from, id, launch) {
466
+ const { store, agentId } = deps;
467
+ const base = readLaunchBody(launch.body);
468
+ if (!base)
469
+ throw new Error(`the launch of ${workflow.name} at ${digest}'s replay could not be read`);
470
+ const replay = { ...base, input: from.input, title: `Replay of ${workflow.name}: ${from.title}`.slice(0, 200), replay: { of, workflow: workflow.name, digest } };
471
+ const sealed = await handedTo(deps, launch, id);
330
472
  try {
331
- await store.runs.create({ id, agentId, revisionId: deps.revisionId }, { body: launchBody(replay), ...(sealed ? { sealed } : {}) });
473
+ await store.runs.create({ id, agentId, revisionId: launch.revision }, { body: launchBody(replay), ...(sealed ? { sealed } : {}) });
332
474
  return true;
333
475
  }
334
476
  catch (error) {
@@ -339,12 +481,15 @@ async function startReplay(deps, workflow, digest, of, from, id) {
339
481
  }
340
482
  /** Finishes a launch that was interrupted: `record`'s reserved replay runs still not created REPLAY_LAUNCH_GRACE_MS after
341
483
  * its reservation (and before its deadline) are created now, each under its reserved id on the graded run its record
342
- * names for it (`inputs`), with this claim's launch and handed credentials. One whose graded run's launch can no longer be
343
- * read stays missing: past the deadline it is counted as never started. How many this claim created. */
484
+ * names for it (`inputs`), with the launch the record chose when it was reserved (`launch`: its model, revision and
485
+ * handed credentials, an owner's replay none), never this claim's: one replay runs on one set of settings. One whose
486
+ * graded run's launch can no longer be read stays missing: past the deadline it is counted as never started. How many
487
+ * this claim created. */
344
488
  async function relaunch(deps, workflow, digest, record) {
345
489
  const { store } = deps;
346
490
  const since = (deps.now ?? Date.now)() - Date.parse(record.at);
347
- if (since <= REPLAY_LAUNCH_GRACE_MS || since > REPLAY_DEADLINE_MS)
491
+ const launch = record.launch;
492
+ if (!launch || since <= REPLAY_LAUNCH_GRACE_MS || since > REPLAY_DEADLINE_MS)
348
493
  return 0;
349
494
  let made = 0;
350
495
  for (const [i, id] of (record.runs ?? []).entries()) {
@@ -352,7 +497,7 @@ async function relaunch(deps, workflow, digest, record) {
352
497
  if (!of || (await store.runs.get(id)))
353
498
  continue;
354
499
  const from = await store.runs.launch(of).then((one) => readLaunchBody(one.body), () => undefined);
355
- if (from && (await startReplay(deps, workflow, digest, of, from, id)))
500
+ if (from && (await startReplay(deps, workflow, digest, of, from, id, launch)))
356
501
  made += 1;
357
502
  }
358
503
  if (made)
@@ -371,43 +516,75 @@ async function answerOf(store, runId, context) {
371
516
  }
372
517
  }
373
518
  const metricsOf = (row) => (isObject(row?.metrics) ? row.metrics : {});
519
+ /** What a replay run did, read from its row alone: answered, handed back or skipped at a write once it ended as such; any
520
+ * other end, or one not ended (past the replay's deadline), failed: no evidence either way. */
521
+ const outcomeOf = (run) => {
522
+ const m = metricsOf(run);
523
+ return run.state === "ended" && (m.replay?.outcome === "answered" || m.replay?.outcome === "handed_back" || m.replay?.outcome === "skipped_write") ? m.replay.outcome : "failed";
524
+ };
525
+ const NO_OUTCOMES = { answered: 0, handed_back: 0, failed: 0, skipped_write: 0 };
526
+ /** How many of a replay's runs ended each way so far (ReplayOutcomes): one not ended counts only past the deadline
527
+ * (`late`), as failed; one never created, nothing. */
528
+ function outcomesOf(runs, late) {
529
+ const counts = { ...NO_OUTCOMES };
530
+ for (const run of runs)
531
+ if (run && (late || FINAL_STATES.includes(run.state)))
532
+ counts[outcomeOf(run)] += 1;
533
+ return counts;
534
+ }
535
+ /** What `record`'s replay runs cost together, at `now`: null while one's is unknown (one not created yet before the
536
+ * deadline, one not ended, one ended with no cost), whatever its grade; a run never created by the deadline spent nothing. */
537
+ function replayCost(runs, late) {
538
+ let cost = 0;
539
+ for (const run of runs) {
540
+ if (!run) {
541
+ if (!late)
542
+ return null;
543
+ continue;
544
+ }
545
+ if (!FINAL_STATES.includes(run.state) || run.costUsd === null)
546
+ return null;
547
+ cost += run.costUsd;
548
+ }
549
+ return Math.round(cost * 1e6) / 1e6;
550
+ }
374
551
  /** The replay's rows, once every replay run ended (or REPLAY_DEADLINE_MS passed: one not ended is failed, no evidence);
375
552
  * undefined while one is at work or not created yet (its record is reserved before its runs are created: a run missing
376
- * is a launch still under way, or one a later claim finishes, relaunch). With what the replay runs cost (null when one's
377
- * is unknown), and how many reserved runs were never created by the deadline (`unstarted`). */
378
- async function replayRows(deps, record) {
553
+ * is a launch still under way, or one a later claim relaunches). With the rows it scores (`scored`, refitRowsOf: the ones
554
+ * its workflow answered or handed back), what the replay runs cost (replayCost), its runs' outcomes (outcomesOf), and how
555
+ * many reserved runs were never created by the deadline (`unstarted`). `partial`: the rows of the runs ended so far, at
556
+ * any time (a replay's read while it runs). A row needs its graded run's grade (what it is scored against): a run whose
557
+ * grade the agent's newer grades rolled out of those kept has none, and is counted (`outcomes`) but not scored. */
558
+ async function replayRows(deps, record, partial = false) {
379
559
  const { store, context } = deps;
380
560
  const now = (deps.now ?? Date.now)();
381
561
  const grades = new Map((await gradesOf(store.settings, deps.agentId)).map((grade) => [grade.run, grade]));
382
562
  const runs = await Promise.all((record.runs ?? []).map((id) => store.runs.get(id)));
383
563
  const late = now - Date.parse(record.at) > REPLAY_DEADLINE_MS;
384
- if (!late && runs.some((row) => !row || !FINAL_STATES.includes(row.state)))
564
+ if (!late && !partial && runs.some((row) => !row || !FINAL_STATES.includes(row.state)))
385
565
  return undefined;
386
566
  const rows = [];
387
- let cost = 0;
388
567
  for (const run of runs) {
389
- if (!run)
568
+ if (!run || (partial && !late && !FINAL_STATES.includes(run.state)))
390
569
  continue;
391
570
  const launch = await store.runs.launch(run.id).then((one) => readLaunchBody(one.body), () => undefined);
392
571
  const of = launch?.replay?.of;
393
572
  const grade = of ? grades.get(of) : undefined;
394
573
  if (!of || !grade)
395
574
  continue;
396
- const ended = FINAL_STATES.includes(run.state);
397
- cost = cost === null || !ended || run.costUsd === null ? null : cost + run.costUsd;
398
575
  const m = metricsOf(run);
399
- const outcome = ended && run.state === "ended" && (m.replay?.outcome === "answered" || m.replay?.outcome === "handed_back" || m.replay?.outcome === "skipped_write") ? m.replay.outcome : "failed";
576
+ const outcome = outcomeOf(run);
400
577
  const stoppedAt = outcome === "skipped_write" ? m.replay?.skipped : undefined;
401
578
  rows.push({
402
579
  of,
403
- recorded: { answer: await answerOf(store, of, context), correct: grade.correct, ...(grade.expected ? { expected: grade.expected } : {}) },
580
+ recorded: { answer: await answerOf(store, of, context), correct: grade.correct, path: grade.path, ...(grade.expected ? { expected: grade.expected } : {}) },
404
581
  outcome,
405
- ...(stoppedAt && typeof stoppedAt.tool === "string" ? { skipped: { tool: stoppedAt.tool, ...(stoppedAt.unmarked === true ? { unmarked: true } : {}) } } : {}),
582
+ ...(stoppedAt ? { skipped: stoppedAt } : {}),
406
583
  answer: outcome === "answered" ? await answerOf(store, run.id, context) : null,
407
584
  guards: Array.isArray(m.guards) ? m.guards : [],
408
585
  });
409
586
  }
410
- return { rows, cost: cost === null ? null : Math.round(cost * 1e6) / 1e6, unstarted: runs.filter((row) => !row).length };
587
+ return { rows, scored: refitRowsOf(rows), cost: replayCost(runs, late), outcomes: outcomesOf(runs, late), unstarted: runs.filter((row) => !row).length };
411
588
  }
412
589
  /** A replaying digest's decision, once its replay runs ended: promote within the bar when it answered alone at least once,
413
590
  * else hold, then one refit (of its guards and recorded escalates). Undefined while a replay run is at work. */
@@ -421,12 +598,22 @@ async function settle(deps, workflow, digest, record) {
421
598
  // replay ran without, say) is no evidence either way, never the agent's answer in its name.
422
599
  // Skipped: the inputs whose workflow needed a write the graded run's recording does not have (learn/replay-calls.ts): a
423
600
  // replay never runs one, so they are no evidence either, and never wrong.
424
- const scored = scoredRows(read.rows);
425
- const score = replayScore(scored, thresholdsOf(workflow.workflow));
426
- const ok = scored.length >= REPLAY_MIN && clears(score);
601
+ const scored = read.scored;
602
+ const thresholds = thresholdsOf(workflow.workflow);
603
+ const score = scoreRows(scored, thresholds);
604
+ // A revision held on served runs graded wrong promotes only once its replay answered (or handed back) on each of them,
605
+ // and is within the bar on them alone (the one scorer over their rows; a hand-back on each is the agent's, right): a
606
+ // pass on other inputs never puts it back, nor pays for repeating the wrong answers it was held on.
607
+ const owedRuns = heldOn(record);
608
+ const unanswered = owedRuns.filter((run) => !read.rows.some((row) => row.of === run && (row.outcome === "answered" || row.outcome === "handed_back")));
609
+ const owedScore = owedRuns.length ? scoreRows(scored.filter((row) => row.of !== undefined && owedRuns.includes(row.of)), thresholds) : undefined;
610
+ const owedWrong = owedScore !== undefined && owedScore.n > 0 && !withinBar(owedScore);
611
+ const passed = scored.length >= REPLAY_MIN && clears(score);
612
+ const ok = passed && !unanswered.length && !owedWrong;
427
613
  const pts = (value) => `${(value * 100).toFixed(1)}%`;
428
- const skipped = read.rows.filter((row) => row.outcome === "skipped_write").length;
429
- const failed = read.rows.length - scored.length - skipped;
614
+ // Its runs' outcomes, the one count the record keeps (a run whose grade rolled out of those kept counts too).
615
+ const { skipped_write: skipped, failed } = read.outcomes;
616
+ const ended = Object.values(read.outcomes).reduce((sum, one) => sum + one, 0);
430
617
  // Inputs stopped at an MCP tool its server listed with no readOnlyHint: the hold names those tools (the server may only
431
618
  // lack the hint); any other skip (a destructive tool, a built-in write) keeps the recording's words.
432
619
  const tools = skippedToolsOf(read.rows);
@@ -437,18 +624,29 @@ async function settle(deps, workflow, digest, record) {
437
624
  const aside = [...(failed ? [`${failed} failed: a step failed, no evidence either way`] : []), ...(skipped ? [`${skipped} skipped: ${skipWhy}`] : []),
438
625
  ...(read.unstarted ? [`${read.unstarted} never started by the replay's deadline`] : [])].join("; ");
439
626
  const said = `on ${plural(score.n, "graded input")}: the workflow ${pts(score.wf_acc)} (${score.handed_back} handed back, the agent's answer), the agent ${pts(score.agent_acc)}, ${score.delta >= 0 ? "+" : ""}${(score.delta * 100).toFixed(1)} pts${aside ? ` (${aside})` : ""}`;
440
- const reason = read.rows.length && skipped === read.rows.length
441
- ? hint ? `nothing was replayed on its ${plural(skipped, "graded input")}: ${skipWhy}` : `every one of its ${plural(skipped, "graded input")} ${SKIPPED_WRITE}: a replay never runs a write, so nothing was replayed`
442
- : scored.length < REPLAY_MIN
443
- ? `only ${plural(scored.length, "replay")} answered or handed back${aside ? ` (${aside})` : ""}, fewer than ${REPLAY_MIN}`
444
- : ok ? `replayed ${said}: within ${PROMOTE_BAR * 100} pts`
445
- : !answersAlone(score) ? `it handed back every one of its ${plural(score.n, "replayed input")}: it would never answer alone (${said})`
446
- : `replayed ${said}: more than ${PROMOTE_BAR * 100} pts under the agent`;
627
+ const reserved = record.runs?.length ?? 0;
628
+ const reason = reserved && read.unstarted === reserved
629
+ ? `none of its ${plural(reserved, "replay run")} started by the replay's deadline (its launch was interrupted: the server stopped after reserving it, say): nothing was replayed; start it again with POST .../learning/workflows/${workflow.name}/revisions/${digest}/replays`
630
+ : ended && skipped === ended
631
+ ? hint ? `nothing was replayed on its ${plural(skipped, "graded input")}: ${skipWhy}` : `every one of its ${plural(skipped, "graded input")} ${SKIPPED_WRITE}: a replay never runs a write, so nothing was replayed`
632
+ : scored.length < REPLAY_MIN
633
+ ? `only ${plural(scored.length, "replay")} answered or handed back${aside ? ` (${aside})` : ""}, fewer than ${REPLAY_MIN}`
634
+ : passed && unanswered.length ? `replayed ${said}, but it did not answer on ${plural(unanswered.length, "graded run")} it was held on (its held_on): it serves again only once a replay answers on them`
635
+ : passed && owedScore && owedWrong ? `replayed ${said}, but on the ${plural(owedScore.n, "graded run")} it was held on the workflow ${pts(owedScore.wf_acc)}, the agent ${pts(owedScore.agent_acc)}: more than ${PROMOTE_BAR * 100} pts under; it serves again only once it answers them right`
636
+ : ok ? `replayed ${said}: within ${PROMOTE_BAR * 100} pts`
637
+ : !answersAlone(score) ? `it handed back every one of its ${plural(score.n, "replayed input")}: it would never answer alone (${said})`
638
+ : `replayed ${said}: more than ${PROMOTE_BAR * 100} pts under the agent`;
639
+ // Promoted: named by the agent's newest grade (`since`), which every run it serves keeps, so a revision that served
640
+ // before (promoted, held, now replayed again) is checked only on the runs this promotion served, never again on the
641
+ // ones it was held on. Held: it still owes the runs it was held on.
642
+ const since = ok ? Math.max(0, ...(await gradesOf(store.settings, agentId)).map((grade) => grade.seq ?? 0)) : undefined;
643
+ const owed = heldOn(record);
447
644
  const decided = await recordPromotion(store.settings, agentId, {
448
645
  workflow: workflow.name, digest, at: iso(now()), decided: ok ? "promote" : "hold", source: "replay", reason,
449
- replay: { ...score, of: read.rows.map((row) => row.of), cost_usd: read.cost, skipped_write: skipped, skipped_tools: tools }, ...(record.runs ? { runs: record.runs } : {}),
450
- ...(record.commit ? { commit: record.commit } : seedOf(deps)),
451
- }, (was) => was?.decided === "replaying");
646
+ replay: { ...score, of: read.rows.map((row) => row.of), cost_usd: read.cost, skipped_tools: tools, outcomes: read.outcomes }, ...(record.runs ? { runs: record.runs } : {}),
647
+ ...(record.commit ? { commit: record.commit } : seedOf(deps)), ...(record.replay_id ? { replay_id: record.replay_id } : {}),
648
+ ...(since !== undefined ? { since } : owed.length ? { held_on: owed } : {}),
649
+ }, (was) => sameReplay(was, record));
452
650
  // Another claim's decision came first: it logs, cancels and refits; this one reads it.
453
651
  if (!decided.won)
454
652
  return decided.record?.decided === "replaying" ? undefined : decided.record;
@@ -457,39 +655,42 @@ async function settle(deps, workflow, digest, record) {
457
655
  const cancelled = await cancelUnended(deps, record);
458
656
  if (cancelled)
459
657
  log(`workflow-first: ${workflow.name} at ${digest}: ${plural(cancelled, "replay run")} still at work past the replay's deadline cancelled`);
460
- if (!ok && scored.length >= REPLAY_MIN) {
658
+ if (!ok && scored.length >= REPLAY_MIN && !unanswered.length && !owedWrong) {
461
659
  // Held: one refit over the replay's scored rows (each step's p known: its guards read record-only, its judge-driven
462
- // escalates recorded). One with neither changes nothing.
463
- await refitAndWrite(deps, workflow, digest, scored.map(replayRefitRow), "its replay held it", scored);
660
+ // escalates recorded). One with neither changes nothing. Never one that still owes runs it was held on: a refit is
661
+ // promoted on all its rows, and they did not answer on those, or answered them under the bar.
662
+ await refitAndWrite(deps, workflow, digest, scored, "its replay held it");
464
663
  }
465
664
  return decided.record;
466
665
  }
467
- /** A replayed input as a refit row: answered alone only when every guard read a p (record-only, none handed back). */
468
- const replayRefitRow = (row) => {
469
- const answered = row.outcome === "answered" && row.guards.every((guard) => guard.p !== null);
470
- return { guards: row.guards, answered, wfCorrect: answered ? answerCorrect(row.answer, row.recorded) : null, agentCorrect: row.recorded.correct ? 1 : 0 };
471
- };
472
666
  /** A serving digest, checked once per REFIT_EVERY more graded runs it served: its thresholds refit over those runs and its
473
667
  * replay's rows (a new revision when they move and still clear the bar), and held when its graded runs' accuracy fell
474
- * more than PROMOTE_BAR under the agent's. True: it still serves this run. */
668
+ * more than PROMOTE_BAR under the agent's. The promotion it serves this run under (`record`, or the digest's newer
669
+ * promotion when one replaced it meanwhile), undefined when it does not serve it. */
475
670
  async function stillServing(deps, workflow, digest, record) {
476
671
  const { store, agentId, log } = deps;
477
672
  const now = deps.now ?? Date.now;
478
673
  const grades = await gradesOf(store.settings, agentId);
479
- const served = grades.filter((grade) => grade.workflow === workflow.name && grade.digest === digest && (grade.path === "workflow" || grade.path === "handed_back"));
674
+ // Only the grades of runs this promotion served (each keeps its `since`, Grade.promotion): promoted again after a hold,
675
+ // never the ones it was held on, nor a run served under the promotion before and graded after this one.
676
+ const served = grades.filter((grade) => grade.workflow === workflow.name && grade.digest === digest && (grade.path === "workflow" || grade.path === "handed_back") && grade.promotion === record.since);
677
+ // Each write is kept only while the promotion this check read is still the digest's (the same since): a check that read
678
+ // an older one, replaced meanwhile (held, replayed and promoted again), writes nothing over the newer one.
679
+ const same = (was) => was?.decided === "promote" && was.since === record.since;
480
680
  // New since the last check: by seq (putGrade), a cursor the trim of the kept grades never moves back.
481
681
  const checked = record.checked ?? 0;
482
682
  const through = Math.max(checked, ...served.map((grade) => grade.seq ?? 0));
483
683
  if (served.filter((grade) => (grade.seq ?? 0) > checked).length < REFIT_EVERY)
484
- return true;
684
+ return record;
685
+ const promoted = (one) => (one?.decided === "promote" ? one : undefined);
485
686
  // The agent's accuracy by hand: its newest graded runs on the agent path, else the replay's.
486
687
  const byHand = grades.filter((grade) => grade.path === "agent").slice(-REPLAY_INPUTS);
487
688
  const agentAcc = byHand.length ? byHand.filter((grade) => grade.correct).length / byHand.length : record.replay?.agent_acc;
488
689
  // Marked checked at this count first, so two claims never check the same window twice.
489
690
  // Only the claim whose write marked it refits: one that lost the write reads the winner's record back, the same cursor.
490
- const marked = await recordPromotion(store.settings, agentId, { ...record, at: iso(now()), checked: through }, (was) => was?.decided === "promote" && (was.checked ?? 0) === checked);
691
+ const marked = await recordPromotion(store.settings, agentId, { ...record, at: iso(now()), checked: through }, (was) => same(was) && (was?.checked ?? 0) === checked);
491
692
  if (!marked.won || agentAcc === undefined)
492
- return marked.record?.decided === "promote";
693
+ return promoted(marked.record);
493
694
  const rows = [];
494
695
  for (const grade of served) {
495
696
  const run = await store.runs.get(grade.run);
@@ -497,23 +698,27 @@ async function stillServing(deps, workflow, digest, record) {
497
698
  const guards = Array.isArray(m.guards) ? m.guards : [];
498
699
  rows.push(grade.path === "workflow" ? { guards, answered: true, wfCorrect: grade.correct, agentCorrect: agentAcc } : { guards, answered: false, wfCorrect: null, agentCorrect: grade.correct ? 1 : 0 });
499
700
  }
500
- const replayed = record.source === "replay" && record.runs?.length ? scoredRows((await replayRows(deps, record))?.rows ?? []) : [];
501
- const all = [...rows, ...replayed.map(replayRefitRow)];
502
- const wrote = await refitAndWrite(deps, workflow, digest, all, `${plural(served.length, "graded run")} it served`, replayed);
701
+ const replayed = record.source === "replay" && record.runs?.length ? (await replayRows(deps, record))?.scored ?? [] : [];
702
+ const wrote = await refitAndWrite(deps, workflow, digest, [...rows, ...replayed], `${plural(served.length, "graded run")} it served`);
703
+ // What actually happened on the served runs: the recorded grades (a workflow-path grade is the workflow's answer, a
704
+ // handed-back one the agent's). Recorded, not rescored: the guards on a run may belong to other workflows the agent called
705
+ // after a hand-back, and rescoring over them would count a right answer as a hand-back at the agent's accuracy.
503
706
  const servedAcc = served.filter((grade) => grade.correct).length / served.length;
504
707
  if (!wrote && servedAcc < agentAcc - PROMOTE_BAR - 1e-9) {
505
708
  const reason = `${plural(served.length, "graded run")} it served were right ${(servedAcc * 100).toFixed(1)}% of the time, more than ${PROMOTE_BAR * 100} pts under the agent's ${(agentAcc * 100).toFixed(1)}% by hand`;
506
- const held = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "hold", source: "graded", reason }, (was) => was?.decided === "promote");
709
+ // It keeps the served runs graded wrong it was held on, newest first: its next replay owes them (heldOn).
710
+ const wrong = served.filter((grade) => !grade.correct).map((grade) => grade.run).reverse().slice(0, REPLAY_INPUTS);
711
+ const held = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "hold", source: "graded", reason, held_on: wrong }, same);
507
712
  if (held.won)
508
713
  log(`workflow-first: ${workflow.name} at ${digest} held: ${reason}`);
509
- return held.record?.decided === "promote";
714
+ return promoted(held.record);
510
715
  }
511
- return true;
716
+ return marked.record;
512
717
  }
513
718
  /** One refit of `workflow` over `rows`; when it moves a guard and the rows clear the bar at the new thresholds, the new
514
719
  * text is written as a new revision (a merge from the claim's seed) and promoted with the rows' numbers. True when one
515
720
  * was written. */
516
- async function refitAndWrite(deps, workflow, digest, rows, why, replayed) {
721
+ async function refitAndWrite(deps, workflow, digest, rows, why) {
517
722
  if (!deps.commit || rows.length < REPLAY_MIN)
518
723
  return false;
519
724
  const now = deps.now ?? Date.now;
@@ -528,19 +733,136 @@ async function refitAndWrite(deps, workflow, digest, rows, why, replayed) {
528
733
  deps.log(`workflow-first: ${workflow.name}'s refit did not land on its learning folder; it keeps its thresholds`);
529
734
  return false;
530
735
  }
531
- // What the new revision agrees on: its moved thresholds, and no row of a guard or escalate it switched off.
532
- const off = new Set(refit.guards.filter((one) => one.threshold === null).map((one) => one.node));
533
- const kept = replayed.map((row) => (off.size ? { ...row, guards: row.guards.filter((guard) => !off.has(guard.node)) } : row));
534
- const agree = kept.length ? replayScore(kept, new Map(refit.guards.flatMap((one) => (one.threshold === null ? [] : [[one.node, one.threshold]])))).agree : 0;
535
736
  await recordPromotion(deps.store.settings, deps.agentId, {
536
737
  workflow: workflow.name, digest: next, at: iso(now()), decided: "promote", source: "refit",
537
738
  reason: `${reason}: the workflow ${(refit.wf_acc * 100).toFixed(1)}%, the agent ${(refit.agent_acc * 100).toFixed(1)}% on those rows`,
538
- replay: { n: refit.n, agree, agent_acc: refit.agent_acc, wf_acc: refit.wf_acc, delta: refit.delta, handed_back: refit.handed_back, of: replayed.map((row) => row.of) },
739
+ replay: { ...scoreOf(refit), of: rows.flatMap((row) => (row.of === undefined ? [] : [row.of])) },
539
740
  refit: { from: digest, guards: refit.guards }, commit: landed,
540
741
  }, (was) => was === undefined);
541
742
  deps.log(`workflow-first: ${reason}; the new revision (${next}) serves from the next run`);
542
743
  return true;
543
744
  }
745
+ /** Why a replay a person asked for (askReplay) or read (replayView) was refused: `missing`, no such workflow, revision or
746
+ * replay of the agent (404); `conflict`, the revision cannot replay now (409), in words that say why. */
747
+ export class ReplayRefused extends Error {
748
+ kind;
749
+ constructor(kind, message) {
750
+ super(message);
751
+ this.kind = kind;
752
+ }
753
+ }
754
+ /** The text of `name` at `digest` and the learning commit it is read from: a commit a record of that digest names (newest
755
+ * first), else the folder's main. When neither holds it, whether the agent has a workflow by that name at all (`named`:
756
+ * a record names it, or main holds it). */
757
+ async function revisionOf(ask, records, name, digest) {
758
+ const folder = ask.folder();
759
+ let main;
760
+ try {
761
+ main = (await readSnapshot(folder.workspace))?.main;
762
+ }
763
+ finally {
764
+ await folder.end().catch(() => undefined);
765
+ }
766
+ const named = records.filter((one) => one.workflow === name && one.digest === digest && one.commit).map((one) => one.commit).reverse();
767
+ let onMain = false;
768
+ for (const commit of new Set([...named, ...(main ? [main] : [])])) {
769
+ const workflow = (await workflowsAt(ask, commit).catch(() => [])).find((one) => one.name === name);
770
+ if (workflow && workflowDigest(workflow) === digest)
771
+ return { workflow, commit };
772
+ if (commit === main)
773
+ onMain = workflow !== undefined;
774
+ }
775
+ return { named: onMain || records.some((one) => one.workflow === name) };
776
+ }
777
+ /** A replay of `name` at `digest` a person asked for: the claim path's replay (reserve, startReplay), on `inputs`: `held`,
778
+ * the graded runs its last replay or hold was decided on (else, with none, the agent's newest REPLAY_INPUTS), or a number,
779
+ * the agent's newest that many (each a graded input the workflow fits); with either, the served runs graded wrong it was
780
+ * held on (heldOn), which it promotes only once it answered on: the claim's picker (inputsFor). Its runs end as a claim's
781
+ * do, and it is decided by the claim path's settle: at a claim that lays the revision, or at its read (replayView).
782
+ * Refused (ReplayRefused): no such workflow or revision; one replaying already, or another revision of it replaying (one
783
+ * at a time, never queued by a person: a queued revision is one a run's claim found newest); a promoted one (it serves already); fewer than REPLAY_MIN graded inputs it fits (a replay on fewer could
784
+ * only hold it: settle scores none of it), refused before anything is reserved; an agent that does not learn here. The
785
+ * replay's id and its inputs. */
786
+ export async function askReplay(ask, name, digest, inputs) {
787
+ const records = await promotionsOf(ask.store.settings, ask.agentId);
788
+ const found = await revisionOf(ask, records, name, digest);
789
+ if ("named" in found)
790
+ throw new ReplayRefused("missing", found.named ? `The learned workflow ${name} has no revision ${digest}: no promotion record names it, and the learning folder's main holds another.` : `The agent has no learned workflow ${name}.`);
791
+ const own = promotionOf(records, name, digest);
792
+ if (own?.decided === "replaying")
793
+ throw new ReplayRefused("conflict", `${name} at ${digest} is replaying already: read that replay, or wait for it to end.`);
794
+ if (own?.decided === "promote")
795
+ throw new ReplayRefused("conflict", `${name} at ${digest} is promoted: it serves already. A replay checks a revision that does not serve yet, or was held.`);
796
+ const rival = replayingOf(records, name, digest)[0];
797
+ if (rival)
798
+ throw new ReplayRefused("conflict", `${name} at ${rival.digest} is replaying: one revision of a workflow replays at a time, and a running replay finishes. ${own?.decided === "queued" ? `${digest} is queued behind it: the next run's claim once it ends replays it, unless a newer revision comes first.` : "Ask again once it ends."}`);
799
+ const { graded, owed, named } = await inputsFor({ store: ask.store, agentId: ask.agentId }, found.workflow, digest, records, inputs);
800
+ if (graded.length < REPLAY_MIN) {
801
+ const among = typeof inputs === "number" ? `the agent's newest ${plural(inputs, "graded input")} it fits` : named ? `the ${plural(named, "graded input")} it was last decided or held on that are still graded and fit it` : "the agent's graded runs it fits";
802
+ const then = typeof inputs !== "number" && named ? "ask for a number of the agent's newest graded inputs instead" : "grade more of the agent's runs first (PUT /runs/{run_id}/grade)";
803
+ throw new ReplayRefused("conflict", `${name} at ${digest} replays on ${graded.length ? `only ${graded.length}` : "none"} of ${among}, fewer than ${REPLAY_MIN}: a replay on fewer could only hold it. Nothing was started: ${then}.`);
804
+ }
805
+ const { launch, revisionId } = await ask.launchOf(graded[0].launch.input);
806
+ if (!launch.learning || launch.learning.notesOnly)
807
+ throw new ReplayRefused("conflict", `A replay runs ${name} as a run of the agent that learns does, and the agent's runs do not take learned workflows here (its learning is off, notes only, or this server's is off).`);
808
+ const deps = { store: ask.store, agentId: ask.agentId, revisionId, launch: { ...launch, learning: { ...launch.learning, seed: found.commit } }, context: ask.context, log: ask.log, ...(ask.now ? { now: ask.now } : {}) };
809
+ const said = `replaying on ${plural(graded.length, "graded input")}${owed.length ? ` (the ${plural(owed.length, "served run")} graded wrong it was held on among them)` : ""}, as its owner asked`;
810
+ // Kept only while the revision's newest record is still the one read here: each record write stamps a new `at`.
811
+ const reserved = await reserve(deps, found.workflow, digest, graded, said, (was) => was?.at === own?.at && was?.decided === own?.decided, owed);
812
+ if (!reserved.won || !reserved.record?.replay_id)
813
+ throw new ReplayRefused("conflict", `${name} at ${digest} changed while this replay was asked for (another replay or decision came first): read its promotions and ask again.`);
814
+ ask.log(`workflow-first: ${name} at ${digest}: ${said}`);
815
+ return { replay: reserved.record.replay_id, inputs: graded.length };
816
+ }
817
+ /** The claim's ports a replay's read settles it through (replayView), with the launch its record chose when it was
818
+ * reserved (PromotionRecord.launch, the one every replay run of it runs with): its revision, and its learning commit (a
819
+ * refit lands as a merge from it). Undefined when that launch cannot be read. */
820
+ function readPorts(ask, launch) {
821
+ const body = readLaunchBody(launch.body);
822
+ return body ? claimPromotion({ ...ask, revisionId: launch.revision, launch: body }) : undefined;
823
+ }
824
+ /** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (the claim path's settle)
825
+ * once its runs ended or its deadline passed: it writes only the decision. A read never starts a run: a replay whose
826
+ * launch was interrupted (reserved runs never created) reads running until its deadline, then is decided held, read as
827
+ * failed, its reason saying none of its runs started and to start it again with POST. So a replay of a revision no claim
828
+ * lays (an older, held one) is decided too, and never running forever. Once decided, it reads only its record. Refused
829
+ * (missing) when the agent has no such replay. */
830
+ export async function replayView(ask, name, digest, id) {
831
+ const find = async () => (await promotionsOf(ask.store.settings, ask.agentId)).findLast((one) => one.workflow === name && one.digest === digest && one.replay_id === id);
832
+ let record = await find();
833
+ if (!record)
834
+ throw new ReplayRefused("missing", `${name} at ${digest} has no replay ${id}.`);
835
+ // A replay a newer draft cancelled (a beta.39 `superseded` record, read as skipped, promotionsOf): decided, never run to a verdict.
836
+ if (record.decided === "skipped")
837
+ return { replay: id, workflow: name, digest, status: "failed", inputs: record.runs?.length ?? 0, outcomes: NO_OUTCOMES, score: scoreRows([], new Map()), cost_usd: null, reason: record.reason };
838
+ const textOf = async (one) => (one.commit ? (await workflowsAt(ask, one.commit).catch(() => [])).find((text) => text.name === name && workflowDigest(text) === digest) : undefined);
839
+ let text = record.decided === "replaying" ? await textOf(record) : undefined;
840
+ const ports = record.decided === "replaying" && text && record.launch ? readPorts(ask, record.launch) : undefined;
841
+ if (ports && text) {
842
+ // Read back by its id: whatever settled it (this read, a claim, another read), never another replay's record.
843
+ await settle(ports, text, digest, record);
844
+ record = (await find()) ?? record;
845
+ }
846
+ // Only a replaying, promote or hold record carries a replay's id.
847
+ const decided = record.decided === "promote" || record.decided === "hold" ? record.decided : undefined;
848
+ const inputs = record.runs?.length ?? 0;
849
+ const said = decided ? { decided, reason: record.reason } : {};
850
+ const kept = record.replay && decided ? record.replay : undefined;
851
+ if (kept) {
852
+ // Decided: its record's numbers alone. With not one of its reserved runs ever created (none counted: a decided
853
+ // replay counted every run there was, and none is created after), nothing was replayed (settle's reason says so).
854
+ const outcomes = kept.outcomes ?? NO_OUTCOMES;
855
+ const neverStarted = inputs > 0 && Object.values(outcomes).every((count) => count === 0);
856
+ return { replay: id, workflow: name, digest, status: neverStarted ? "failed" : "done", inputs, outcomes, score: scoreOf(kept), cost_usd: kept.cost_usd ?? null, ...said };
857
+ }
858
+ const read = await replayRows(ask, record, true);
859
+ text ??= await textOf(record);
860
+ return {
861
+ replay: id, workflow: name, digest, status: decided === undefined ? "running" : "done", inputs,
862
+ outcomes: read?.outcomes ?? NO_OUTCOMES,
863
+ score: scoreRows(read?.scored ?? [], text ? thresholdsOf(text.workflow) : new Map()), cost_usd: read?.cost ?? null, ...said,
864
+ };
865
+ }
544
866
  /** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the graded run's recorded calls, read from its journal
545
867
  * (a CLI's record shaped as pi's), and each tool classed by the claim's MCP pin (`runId`'s, its servers' annotations as
546
868
  * they listed them) or the built-in list. Undefined for any other run. A recording that cannot be read is an empty one: