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

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 (410) hide show
  1. package/CHANGELOG.md +418 -0
  2. package/README.md +325 -124
  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-BNhZs-jp.css +1 -0
  37. package/dist/console/assets/index-BQv5aOGB.js +700 -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 +84 -0
  44. package/dist/email/account.js +159 -0
  45. package/dist/email/answer.d.ts +10 -0
  46. package/dist/email/answer.js +182 -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 +380 -0
  53. package/dist/email/names.d.ts +20 -0
  54. package/dist/email/names.js +40 -0
  55. package/dist/email/routes.d.ts +9 -0
  56. package/dist/email/routes.js +50 -0
  57. package/dist/email/tools.d.ts +20 -0
  58. package/dist/email/tools.js +517 -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 +9 -2
  93. package/dist/learn/compile.js +52 -16
  94. package/dist/learn/grade.d.ts +4 -0
  95. package/dist/learn/grade.js +4 -1
  96. package/dist/learn/promote.d.ts +106 -51
  97. package/dist/learn/promote.js +82 -189
  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 +26 -8
  109. package/dist/learning-cost.js +17 -7
  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 +33 -2
  118. package/dist/local-models.js +43 -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 +1 -0
  164. package/dist/openapi.js +394 -85
  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 +7 -2
  170. package/dist/port-models.js +5 -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 +11 -0
  180. package/dist/refusal-words.js +13 -2
  181. package/dist/run-launch.d.ts +10 -1
  182. package/dist/run-launch.js +11 -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 +42 -35
  191. package/dist/run-view.js +79 -44
  192. package/dist/runnable.d.ts +13 -5
  193. package/dist/runnable.js +69 -60
  194. package/dist/runner/adapter-loop.d.ts +42 -11
  195. package/dist/runner/adapter-loop.js +651 -247
  196. package/dist/runner/adapter-run-spec.d.ts +37 -12
  197. package/dist/runner/adapter-run-spec.js +139 -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 +94 -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 +37 -13
  217. package/dist/runner/journal-kinds.js +9 -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 +12 -3
  237. package/dist/runner/model-route.js +139 -18
  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 +74 -8
  243. package/dist/runner/promotion.js +365 -124
  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 +554 -130
  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/index.d.ts +1 -1
  278. package/dist/store/native-command-owner.d.ts +10 -0
  279. package/dist/store/native-command-owner.js +47 -0
  280. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  281. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  282. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  283. package/dist/store/postgres/store.js +3 -0
  284. package/dist/store/schema.d.ts +7 -0
  285. package/dist/store/schema.js +20 -1
  286. package/dist/store/sqlite/run-patch.d.ts +8 -1
  287. package/dist/store/sqlite/run-patch.js +14 -3
  288. package/dist/store/sqlite/store.js +133 -18
  289. package/dist/store/store.d.ts +52 -7
  290. package/dist/store-reads/analytics.d.ts +7 -7
  291. package/dist/store-reads/analytics.js +23 -5
  292. package/dist/store-reads/cap.js +8 -6
  293. package/dist/store-reads/journal.d.ts +5 -0
  294. package/dist/store-reads/journal.js +85 -41
  295. package/dist/store-reads/learning.d.ts +85 -5
  296. package/dist/store-reads/learning.js +45 -17
  297. package/dist/store-reads/runs.d.ts +5 -0
  298. package/dist/store-reads/runs.js +3 -2
  299. package/dist/store-view.js +75 -21
  300. package/dist/template-eval.d.ts +73 -11
  301. package/dist/template-eval.js +535 -75
  302. package/dist/templates.d.ts +70 -20
  303. package/dist/templates.js +191 -34
  304. package/dist/text-urls.d.ts +38 -0
  305. package/dist/text-urls.js +170 -0
  306. package/dist/timeline/index.d.ts +3 -2
  307. package/dist/timeline/index.js +3 -2
  308. package/dist/timeline/labels.d.ts +5 -2
  309. package/dist/timeline/labels.js +29 -6
  310. package/dist/timeline/origin.d.ts +1 -1
  311. package/dist/timeline/origin.js +2 -2
  312. package/dist/timeline/render-text.js +1 -1
  313. package/dist/timeline/timeline.d.ts +66 -4
  314. package/dist/timeline/timeline.js +160 -30
  315. package/dist/timeline/util.d.ts +5 -0
  316. package/dist/timeline/util.js +44 -8
  317. package/dist/timeline/web-calls.d.ts +17 -0
  318. package/dist/timeline/web-calls.js +106 -0
  319. package/dist/tool-gate.d.ts +42 -42
  320. package/dist/tool-gate.js +97 -91
  321. package/dist/tool-list.d.ts +4 -1
  322. package/dist/tool-list.js +8 -1
  323. package/dist/tool-names.d.ts +18 -13
  324. package/dist/tool-names.js +19 -17
  325. package/dist/tool-plane.d.ts +17 -13
  326. package/dist/tool-plane.js +12 -5
  327. package/dist/tools.d.ts +44 -16
  328. package/dist/tools.js +28 -28
  329. package/dist/trigger-adapter.d.ts +85 -5
  330. package/dist/trigger-adapter.js +6 -0
  331. package/dist/trigger-adapters.js +3 -1
  332. package/dist/trigger-composio.d.ts +10 -0
  333. package/dist/trigger-composio.js +122 -0
  334. package/dist/trigger-email.d.ts +4 -0
  335. package/dist/trigger-email.js +228 -0
  336. package/dist/trigger-signatures.d.ts +6 -10
  337. package/dist/trigger-signatures.js +16 -16
  338. package/dist/trigger-targets.d.ts +1 -1
  339. package/dist/trigger-targets.js +4 -3
  340. package/dist/trigger-webhook.js +6 -4
  341. package/dist/triggers.d.ts +94 -9
  342. package/dist/triggers.js +263 -62
  343. package/dist/uploads.d.ts +9 -0
  344. package/dist/uploads.js +27 -0
  345. package/dist/validate.js +1 -7
  346. package/dist/web-fake.d.ts +56 -0
  347. package/dist/web-fake.js +102 -0
  348. package/dist/web-fetch-direct.d.ts +3 -0
  349. package/dist/web-fetch-direct.js +4 -1
  350. package/dist/web-fetch.d.ts +5 -1
  351. package/dist/web-fetch.js +8 -31
  352. package/dist/web-search.d.ts +51 -2
  353. package/dist/web-search.js +116 -18
  354. package/dist/webhooks.d.ts +2 -1
  355. package/dist/webhooks.js +5 -1
  356. package/dist/workflow/node-runner.js +10 -2
  357. package/dist/workspace/archil-claim.d.ts +3 -0
  358. package/dist/workspace/archil-claim.js +9 -2
  359. package/dist/workspace/computer-deps.d.ts +22 -9
  360. package/dist/workspace/computer-deps.js +78 -37
  361. package/dist/workspace/computer-for-claim.d.ts +54 -4
  362. package/dist/workspace/computer-for-claim.js +179 -39
  363. package/dist/workspace/computer-janitor.d.ts +10 -3
  364. package/dist/workspace/computer-janitor.js +96 -29
  365. package/dist/workspace/computer-kept.d.ts +82 -0
  366. package/dist/workspace/computer-kept.js +147 -0
  367. package/dist/workspace/computer-mcp.js +4 -3
  368. package/dist/workspace/computer-ports.d.ts +23 -3
  369. package/dist/workspace/computer-ports.js +115 -5
  370. package/dist/workspace/index.d.ts +1 -2
  371. package/dist/workspace/index.js +1 -2
  372. package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
  373. package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
  374. package/dist/workspace/resolve-computer.d.ts +15 -3
  375. package/dist/workspace/resolve-computer.js +10 -7
  376. package/dist/workspace/revision-skills.d.ts +6 -2
  377. package/dist/workspace/revision-skills.js +12 -5
  378. package/dist/workspace/run-end-computers.d.ts +30 -0
  379. package/dist/workspace/run-end-computers.js +137 -0
  380. package/dist/workspace/run-tools.d.ts +28 -29
  381. package/dist/workspace/run-tools.js +29 -30
  382. package/dist/wrap-up.d.ts +19 -5
  383. package/dist/wrap-up.js +31 -4
  384. package/package.json +13 -9
  385. package/skills/agentrun-serve/SKILL.md +248 -10
  386. package/templates/README.md +117 -23
  387. package/templates/TOOLS.md +168 -0
  388. package/templates/code-review/agent.md +18 -4
  389. package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
  390. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  391. package/templates/code-review/evals/other-repo/case.yaml +1 -1
  392. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  393. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  394. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  395. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  396. package/templates/code-review/skills/review/DEEP.md +2 -2
  397. package/templates/code-review/skills/review/REVIEWER.md +2 -2
  398. package/templates/code-review/skills/review/SKILL.md +7 -3
  399. package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
  400. package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
  401. package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
  402. package/templates/release-notes/evals/other-repo/case.yaml +1 -1
  403. package/dist/console/assets/index-CjqQirbo.css +0 -1
  404. package/dist/console/assets/index-b6-XY5A9.js +0 -576
  405. package/dist/host-calls.d.ts +0 -20
  406. package/dist/host-calls.js +0 -12
  407. package/dist/runner/adapters/pi-computer.d.ts +0 -9
  408. package/dist/runner/adapters/pi-computer.js +0 -51
  409. package/dist/workspace/computer-script.d.ts +0 -53
  410. 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, 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
+ * superseded, 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
72
  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"}.`);
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
  }
@@ -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
@@ -198,7 +205,8 @@ async function decide(deps, workflow, digest) {
198
205
  // A new revision. One challenger at a time: one still replaying is superseded by it when it is the newest revision (the
199
206
  // one the learning folder's main holds now); a run pinned to an older commit lays an older text, and starts nothing,
200
207
  // whenever it was launched.
201
- const rivals = replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest);
208
+ const records = await promotionsOf(store.settings, agentId);
209
+ const rivals = replayingOf(records, workflow.name, digest);
202
210
  if (rivals.length) {
203
211
  const newest = deps.newest ? await deps.newest(workflow.name) : undefined;
204
212
  if (newest !== digest) {
@@ -208,7 +216,8 @@ async function decide(deps, workflow, digest) {
208
216
  for (const rival of rivals)
209
217
  await supersede(deps, rival, digest);
210
218
  }
211
- const graded = await gradedInputs(deps, workflow);
219
+ // A new revision: no record of it, nothing owed, so the agent's newest REPLAY_INPUTS (the one picker, inputsFor).
220
+ const { graded } = await inputsFor(deps, workflow, digest, records, "held");
212
221
  if (graded.length < REPLAY_MIN) {
213
222
  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
223
  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);
@@ -216,24 +225,61 @@ async function decide(deps, workflow, digest) {
216
225
  log(`workflow-first: ${workflow.name} at ${digest}: ${reason}`);
217
226
  return;
218
227
  }
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);
228
+ const reserved = await reserve(deps, workflow, digest, graded, `replaying on the agent's last ${plural(graded.length, "graded input")} it fits`, (was) => was === undefined);
224
229
  if (!reserved.won) {
225
230
  const rival = reserved.record ? undefined : replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest)[0];
226
231
  if (rival)
227
232
  log(`workflow-first: ${workflow.name} at ${digest}: ${rival.digest} began replaying first; it does not serve this run`);
228
233
  return;
229
234
  }
230
- for (const [i, one] of graded.entries())
231
- await startReplay(deps, workflow, digest, one.grade.run, one.launch, ids[i]);
232
235
  log(`workflow-first: ${workflow.name} at ${digest} is new: replaying it on the agent's last ${plural(graded.length, "graded input")} before it serves`);
233
236
  }
237
+ /** Reserves a replay of `workflow` at `digest` on `graded`, then starts its runs: its replaying record names the replay
238
+ * runs it will start (their ids, and the replay's own, minted here), kept only when `still` holds of the digest's record
239
+ * now and no other revision of the workflow replays, in the one guarded write. Only the writer that kept it starts them:
240
+ * 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
241
+ * person's (askReplay) are this one reservation. `owed`: the held runs among `graded` it must answer on (heldOn). */
242
+ async function reserve(deps, workflow, digest, graded, reason, still, owed = []) {
243
+ const now = deps.now ?? Date.now;
244
+ const ids = graded.map(() => uuidv7());
245
+ const launch = replayLaunchOf(deps);
246
+ 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) && replayingOf(items, workflow.name, digest).length === 0);
247
+ if (reserved.won)
248
+ for (const [i, one] of graded.entries())
249
+ await startReplay(deps, workflow, digest, one.grade.run, one.launch, ids[i], launch);
250
+ return reserved;
251
+ }
252
+ /** The launch a replay's runs all run with (PromotionRecord.launch), chosen once by the claim or person reserving it:
253
+ * `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,
254
+ * and the claimed run as the one whose per_run MCP credentials its runs are handed, when the server can seal them. A
255
+ * person's ask claims no run, so an owner's replay runs are handed none. */
256
+ function replayLaunchOf(deps) {
257
+ const { launch } = deps;
258
+ const base = {
259
+ input: null,
260
+ title: "",
261
+ place: launch.place,
262
+ ...(launch.harness !== undefined ? { harness: launch.harness } : {}),
263
+ ...(launch.model ? { model: launch.model } : {}),
264
+ ...(launch.effort !== undefined ? { effort: launch.effort } : {}),
265
+ ...(launch.maxCostUsd !== undefined ? { maxCostUsd: launch.maxCostUsd } : {}),
266
+ ...(launch.plane ? { plane: launch.plane } : {}),
267
+ ...(launch.approvers !== undefined ? { approvers: launch.approvers } : {}),
268
+ ...(launch.documents !== undefined ? { documents: launch.documents } : {}),
269
+ ...(launch.boxAllow !== undefined ? { boxAllow: launch.boxAllow } : {}),
270
+ ...(launch.boxAllowSet ? { boxAllowSet: true } : {}),
271
+ ...(launch.learning ? { learning: launch.learning } : {}),
272
+ ...(launch.archilDisk ? { archilDisk: launch.archilDisk } : {}),
273
+ };
274
+ return { revision: deps.revisionId, body: launchBody(base), ...(deps.sealKey && deps.runId ? { handed_from: deps.runId } : {}) };
275
+ }
276
+ /** Whether `was`, a digest's newest record now, is still the replay `record` reserved: replaying, under the same replay
277
+ * id. A replay settled or superseded meanwhile, and a newer replay of the same revision its owner started since (a held
278
+ * revision may be replayed again), are not: an older replay's late decision never lands over a newer one. */
279
+ const sameReplay = (was, record) => was?.decided === "replaying" && was.replay_id === record.replay_id;
234
280
  /** 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. */
281
+ * while it is still that replay, sameReplay: a replay that settled first keeps its decision), then its replay runs not
282
+ * ended are cancelled (cancelUnended) by the claim whose write kept it. */
237
283
  async function supersede(deps, record, by) {
238
284
  const { store, agentId, log } = deps;
239
285
  const now = deps.now ?? Date.now;
@@ -241,8 +287,8 @@ async function supersede(deps, record, by) {
241
287
  const reason = `superseded by ${by}, a newer revision, while it replayed: its replay runs were cancelled`;
242
288
  const kept = await recordPromotion(store.settings, agentId, {
243
289
  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");
290
+ ...(runs.length ? { runs } : {}), ...(record.commit ? { commit: record.commit } : {}), ...(record.replay_id ? { replay_id: record.replay_id } : {}),
291
+ }, (was) => sameReplay(was, record));
246
292
  if (!kept.won)
247
293
  return;
248
294
  const cancelled = await cancelUnended(deps, record);
@@ -270,17 +316,26 @@ async function cancelUnended(deps, record) {
270
316
  }
271
317
  return cancelled;
272
318
  }
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) {
319
+ /** The paths a graded run a replay runs on took: the agent's (`agent`, or `handed_back`: the agent finished it), or a
320
+ * learned workflow's alone (`workflow`). Each has a recorded answer (the run's final answer, whoever wrote it) and its
321
+ * grade, which is what a replay scores against (answerCorrect); the path says only whose answer it was (agentRight: on a
322
+ * `workflow` run graded wrong the agent counts right); a replay run never is one. */
323
+ const REPLAYABLE = new Set(["agent", "handed_back", "workflow"]);
324
+ /** The agent's graded runs a replay runs on (REPLAYABLE), newest first: the runs `pick.of` names, then the newest
325
+ * `pick.n` (a run both name is taken once). Each with a launch read back, no uploaded file, an input `workflow` fits,
326
+ * never the run being claimed, nor an archived or imported one. */
327
+ async function gradedInputs(deps, workflow, pick) {
277
328
  const { resolveSchemaForWorkflow } = await import("@parcha/agentrun-dsl");
278
329
  const out = [];
279
- const grades = (await gradesOf(deps.store.settings, deps.agentId)).filter((grade) => grade.path === "agent" || grade.path === "handed_back");
330
+ const of = new Set(pick.of);
331
+ let newest = 0;
332
+ let named = 0;
333
+ const grades = (await gradesOf(deps.store.settings, deps.agentId)).filter((grade) => REPLAYABLE.has(grade.path));
280
334
  for (const grade of grades.reverse()) {
281
- if (out.length >= REPLAY_INPUTS)
335
+ if (newest >= pick.n && named >= of.size)
282
336
  break;
283
- if (grade.run === deps.runId)
337
+ const asked = of.has(grade.run);
338
+ if ((!asked && newest >= pick.n) || grade.run === deps.runId)
284
339
  continue;
285
340
  const row = await deps.store.runs.get(grade.run);
286
341
  if (!row || row.archivedAt !== null || row.importedFrom)
@@ -289,46 +344,56 @@ async function gradedInputs(deps, workflow) {
289
344
  if (!launch || launch.files?.length || launch.replay || !fits(workflow, launch.input, resolveSchemaForWorkflow))
290
345
  continue;
291
346
  out.push({ grade, launch });
347
+ if (asked)
348
+ named += 1;
349
+ if (newest < pick.n)
350
+ newest += 1;
292
351
  }
293
352
  return out;
294
353
  }
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)
354
+ /** What a replay of a revision owes before it may promote it: the served runs graded wrong it was held on
355
+ * (PromotionRecord.held_on), none when `record` owes none. Its replay puts each among its inputs (inputsFor), and its
356
+ * settle holds a replay that did not answer or hand back on each. */
357
+ const heldOn = (record) => record?.held_on ?? [];
358
+ /** The graded inputs a replay of `workflow` at `digest` runs on (gradedInputs), the one picker of both starts: always the
359
+ * served runs graded wrong its newest record holds it on (heldOn), then `held`, the inputs of its newest record that
360
+ * names any (a replay's), else, with none and nothing owed, the agent's newest REPLAY_INPUTS; or a number, the agent's
361
+ * newest that many. A claim's start (decide) is `held` on a revision with no record: the newest REPLAY_INPUTS. `owed`:
362
+ * the held runs among the picked; `named`: how many runs the records named (owed or decided on), picked or not. */
363
+ async function inputsFor(deps, workflow, digest, records, inputs) {
364
+ const held = heldOn(promotionOf(records, workflow.name, digest));
365
+ const last = inputs === "held" ? records.findLast((one) => one.workflow === workflow.name && one.digest === digest && (one.inputs?.length || one.replay?.of.length)) : undefined;
366
+ const of = [...new Set([...held, ...(last ? (last.inputs ?? last.replay.of) : [])])];
367
+ const n = typeof inputs === "number" ? inputs : of.length ? 0 : REPLAY_INPUTS;
368
+ const graded = await gradedInputs(deps, workflow, { of, n });
369
+ return { graded, owed: graded.filter((one) => held.includes(one.grade.run)).map((one) => one.grade.run), named: of.length };
370
+ }
371
+ /** The per_run MCP credentials run `launch.handed_from` was handed (its launch's sealed column, opened under the seal
372
+ * key), sealed for the replay run `id` alone, as the server's start seals a run's mcp_auth (store/seal.ts
373
+ * sealRunMcpAuth): the replay's claim reads them where any run's claim does (runner/mcp-claim.ts). None when the replay
374
+ * names no such run (an owner's), that run was handed none, or they do not open. Never written anywhere else, never
375
+ * logged. */
376
+ async function handedTo(deps, launch, id) {
377
+ const from = launch.handed_from;
378
+ if (!deps.sealKey || !from)
301
379
  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);
380
+ const sealed = await deps.store.runs.launch(from).then((one) => one.sealed ?? null, () => null);
381
+ const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, from, sealed);
304
382
  return handed && Object.keys(handed).length ? sealRunMcpAuth(deps.sealKey, id, handed) : undefined;
305
383
  }
306
384
  /** 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);
385
+ * record names), with the replay's chosen `launch` (replayLaunchOf: its run launch, revision and handed credentials,
386
+ * handedTo), whichever claim creates it. False when a run by that id exists already: another claim created it (a
387
+ * relaunch and the reserving claim at once), and it is left to that one. */
388
+ async function startReplay(deps, workflow, digest, of, from, id, launch) {
389
+ const { store, agentId } = deps;
390
+ const base = readLaunchBody(launch.body);
391
+ if (!base)
392
+ throw new Error(`the launch of ${workflow.name} at ${digest}'s replay could not be read`);
393
+ const replay = { ...base, input: from.input, title: `Replay of ${workflow.name}: ${from.title}`.slice(0, 200), replay: { of, workflow: workflow.name, digest } };
394
+ const sealed = await handedTo(deps, launch, id);
330
395
  try {
331
- await store.runs.create({ id, agentId, revisionId: deps.revisionId }, { body: launchBody(replay), ...(sealed ? { sealed } : {}) });
396
+ await store.runs.create({ id, agentId, revisionId: launch.revision }, { body: launchBody(replay), ...(sealed ? { sealed } : {}) });
332
397
  return true;
333
398
  }
334
399
  catch (error) {
@@ -339,12 +404,15 @@ async function startReplay(deps, workflow, digest, of, from, id) {
339
404
  }
340
405
  /** Finishes a launch that was interrupted: `record`'s reserved replay runs still not created REPLAY_LAUNCH_GRACE_MS after
341
406
  * 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. */
407
+ * names for it (`inputs`), with the launch the record chose when it was reserved (`launch`: its model, revision and
408
+ * handed credentials, an owner's replay none), never this claim's: one replay runs on one set of settings. One whose
409
+ * graded run's launch can no longer be read stays missing: past the deadline it is counted as never started. How many
410
+ * this claim created. */
344
411
  async function relaunch(deps, workflow, digest, record) {
345
412
  const { store } = deps;
346
413
  const since = (deps.now ?? Date.now)() - Date.parse(record.at);
347
- if (since <= REPLAY_LAUNCH_GRACE_MS || since > REPLAY_DEADLINE_MS)
414
+ const launch = record.launch;
415
+ if (!launch || since <= REPLAY_LAUNCH_GRACE_MS || since > REPLAY_DEADLINE_MS)
348
416
  return 0;
349
417
  let made = 0;
350
418
  for (const [i, id] of (record.runs ?? []).entries()) {
@@ -352,7 +420,7 @@ async function relaunch(deps, workflow, digest, record) {
352
420
  if (!of || (await store.runs.get(id)))
353
421
  continue;
354
422
  const from = await store.runs.launch(of).then((one) => readLaunchBody(one.body), () => undefined);
355
- if (from && (await startReplay(deps, workflow, digest, of, from, id)))
423
+ if (from && (await startReplay(deps, workflow, digest, of, from, id, launch)))
356
424
  made += 1;
357
425
  }
358
426
  if (made)
@@ -371,43 +439,75 @@ async function answerOf(store, runId, context) {
371
439
  }
372
440
  }
373
441
  const metricsOf = (row) => (isObject(row?.metrics) ? row.metrics : {});
442
+ /** What a replay run did, read from its row alone: answered, handed back or skipped at a write once it ended as such; any
443
+ * other end, or one not ended (past the replay's deadline), failed: no evidence either way. */
444
+ const outcomeOf = (run) => {
445
+ const m = metricsOf(run);
446
+ return run.state === "ended" && (m.replay?.outcome === "answered" || m.replay?.outcome === "handed_back" || m.replay?.outcome === "skipped_write") ? m.replay.outcome : "failed";
447
+ };
448
+ const NO_OUTCOMES = { answered: 0, handed_back: 0, failed: 0, skipped_write: 0 };
449
+ /** How many of a replay's runs ended each way so far (ReplayOutcomes): one not ended counts only past the deadline
450
+ * (`late`), as failed; one never created, nothing. */
451
+ function outcomesOf(runs, late) {
452
+ const counts = { ...NO_OUTCOMES };
453
+ for (const run of runs)
454
+ if (run && (late || FINAL_STATES.includes(run.state)))
455
+ counts[outcomeOf(run)] += 1;
456
+ return counts;
457
+ }
458
+ /** What `record`'s replay runs cost together, at `now`: null while one's is unknown (one not created yet before the
459
+ * deadline, one not ended, one ended with no cost), whatever its grade; a run never created by the deadline spent nothing. */
460
+ function replayCost(runs, late) {
461
+ let cost = 0;
462
+ for (const run of runs) {
463
+ if (!run) {
464
+ if (!late)
465
+ return null;
466
+ continue;
467
+ }
468
+ if (!FINAL_STATES.includes(run.state) || run.costUsd === null)
469
+ return null;
470
+ cost += run.costUsd;
471
+ }
472
+ return Math.round(cost * 1e6) / 1e6;
473
+ }
374
474
  /** The replay's rows, once every replay run ended (or REPLAY_DEADLINE_MS passed: one not ended is failed, no evidence);
375
475
  * 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) {
476
+ * is a launch still under way, or one a later claim relaunches). With the rows it scores (`scored`, refitRowsOf: the ones
477
+ * its workflow answered or handed back), what the replay runs cost (replayCost), its runs' outcomes (outcomesOf), and how
478
+ * many reserved runs were never created by the deadline (`unstarted`). `partial`: the rows of the runs ended so far, at
479
+ * 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
480
+ * grade the agent's newer grades rolled out of those kept has none, and is counted (`outcomes`) but not scored. */
481
+ async function replayRows(deps, record, partial = false) {
379
482
  const { store, context } = deps;
380
483
  const now = (deps.now ?? Date.now)();
381
484
  const grades = new Map((await gradesOf(store.settings, deps.agentId)).map((grade) => [grade.run, grade]));
382
485
  const runs = await Promise.all((record.runs ?? []).map((id) => store.runs.get(id)));
383
486
  const late = now - Date.parse(record.at) > REPLAY_DEADLINE_MS;
384
- if (!late && runs.some((row) => !row || !FINAL_STATES.includes(row.state)))
487
+ if (!late && !partial && runs.some((row) => !row || !FINAL_STATES.includes(row.state)))
385
488
  return undefined;
386
489
  const rows = [];
387
- let cost = 0;
388
490
  for (const run of runs) {
389
- if (!run)
491
+ if (!run || (partial && !late && !FINAL_STATES.includes(run.state)))
390
492
  continue;
391
493
  const launch = await store.runs.launch(run.id).then((one) => readLaunchBody(one.body), () => undefined);
392
494
  const of = launch?.replay?.of;
393
495
  const grade = of ? grades.get(of) : undefined;
394
496
  if (!of || !grade)
395
497
  continue;
396
- const ended = FINAL_STATES.includes(run.state);
397
- cost = cost === null || !ended || run.costUsd === null ? null : cost + run.costUsd;
398
498
  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";
499
+ const outcome = outcomeOf(run);
400
500
  const stoppedAt = outcome === "skipped_write" ? m.replay?.skipped : undefined;
401
501
  rows.push({
402
502
  of,
403
- recorded: { answer: await answerOf(store, of, context), correct: grade.correct, ...(grade.expected ? { expected: grade.expected } : {}) },
503
+ recorded: { answer: await answerOf(store, of, context), correct: grade.correct, path: grade.path, ...(grade.expected ? { expected: grade.expected } : {}) },
404
504
  outcome,
405
- ...(stoppedAt && typeof stoppedAt.tool === "string" ? { skipped: { tool: stoppedAt.tool, ...(stoppedAt.unmarked === true ? { unmarked: true } : {}) } } : {}),
505
+ ...(stoppedAt ? { skipped: stoppedAt } : {}),
406
506
  answer: outcome === "answered" ? await answerOf(store, run.id, context) : null,
407
507
  guards: Array.isArray(m.guards) ? m.guards : [],
408
508
  });
409
509
  }
410
- return { rows, cost: cost === null ? null : Math.round(cost * 1e6) / 1e6, unstarted: runs.filter((row) => !row).length };
510
+ return { rows, scored: refitRowsOf(rows), cost: replayCost(runs, late), outcomes: outcomesOf(runs, late), unstarted: runs.filter((row) => !row).length };
411
511
  }
412
512
  /** A replaying digest's decision, once its replay runs ended: promote within the bar when it answered alone at least once,
413
513
  * else hold, then one refit (of its guards and recorded escalates). Undefined while a replay run is at work. */
@@ -421,12 +521,22 @@ async function settle(deps, workflow, digest, record) {
421
521
  // replay ran without, say) is no evidence either way, never the agent's answer in its name.
422
522
  // Skipped: the inputs whose workflow needed a write the graded run's recording does not have (learn/replay-calls.ts): a
423
523
  // 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);
524
+ const scored = read.scored;
525
+ const thresholds = thresholdsOf(workflow.workflow);
526
+ const score = scoreRows(scored, thresholds);
527
+ // A revision held on served runs graded wrong promotes only once its replay answered (or handed back) on each of them,
528
+ // 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
529
+ // pass on other inputs never puts it back, nor pays for repeating the wrong answers it was held on.
530
+ const owedRuns = heldOn(record);
531
+ const unanswered = owedRuns.filter((run) => !read.rows.some((row) => row.of === run && (row.outcome === "answered" || row.outcome === "handed_back")));
532
+ const owedScore = owedRuns.length ? scoreRows(scored.filter((row) => row.of !== undefined && owedRuns.includes(row.of)), thresholds) : undefined;
533
+ const owedWrong = owedScore !== undefined && owedScore.n > 0 && !withinBar(owedScore);
534
+ const passed = scored.length >= REPLAY_MIN && clears(score);
535
+ const ok = passed && !unanswered.length && !owedWrong;
427
536
  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;
537
+ // Its runs' outcomes, the one count the record keeps (a run whose grade rolled out of those kept counts too).
538
+ const { skipped_write: skipped, failed } = read.outcomes;
539
+ const ended = Object.values(read.outcomes).reduce((sum, one) => sum + one, 0);
430
540
  // Inputs stopped at an MCP tool its server listed with no readOnlyHint: the hold names those tools (the server may only
431
541
  // lack the hint); any other skip (a destructive tool, a built-in write) keeps the recording's words.
432
542
  const tools = skippedToolsOf(read.rows);
@@ -437,18 +547,29 @@ async function settle(deps, workflow, digest, record) {
437
547
  const aside = [...(failed ? [`${failed} failed: a step failed, no evidence either way`] : []), ...(skipped ? [`${skipped} skipped: ${skipWhy}`] : []),
438
548
  ...(read.unstarted ? [`${read.unstarted} never started by the replay's deadline`] : [])].join("; ");
439
549
  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`;
550
+ const reserved = record.runs?.length ?? 0;
551
+ const reason = reserved && read.unstarted === reserved
552
+ ? `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`
553
+ : ended && skipped === ended
554
+ ? 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`
555
+ : scored.length < REPLAY_MIN
556
+ ? `only ${plural(scored.length, "replay")} answered or handed back${aside ? ` (${aside})` : ""}, fewer than ${REPLAY_MIN}`
557
+ : 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`
558
+ : 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`
559
+ : ok ? `replayed ${said}: within ${PROMOTE_BAR * 100} pts`
560
+ : !answersAlone(score) ? `it handed back every one of its ${plural(score.n, "replayed input")}: it would never answer alone (${said})`
561
+ : `replayed ${said}: more than ${PROMOTE_BAR * 100} pts under the agent`;
562
+ // Promoted: named by the agent's newest grade (`since`), which every run it serves keeps, so a revision that served
563
+ // before (promoted, held, now replayed again) is checked only on the runs this promotion served, never again on the
564
+ // ones it was held on. Held: it still owes the runs it was held on.
565
+ const since = ok ? Math.max(0, ...(await gradesOf(store.settings, agentId)).map((grade) => grade.seq ?? 0)) : undefined;
566
+ const owed = heldOn(record);
447
567
  const decided = await recordPromotion(store.settings, agentId, {
448
568
  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");
569
+ replay: { ...score, of: read.rows.map((row) => row.of), cost_usd: read.cost, skipped_tools: tools, outcomes: read.outcomes }, ...(record.runs ? { runs: record.runs } : {}),
570
+ ...(record.commit ? { commit: record.commit } : seedOf(deps)), ...(record.replay_id ? { replay_id: record.replay_id } : {}),
571
+ ...(since !== undefined ? { since } : owed.length ? { held_on: owed } : {}),
572
+ }, (was) => sameReplay(was, record));
452
573
  // Another claim's decision came first: it logs, cancels and refits; this one reads it.
453
574
  if (!decided.won)
454
575
  return decided.record?.decided === "replaying" ? undefined : decided.record;
@@ -457,39 +578,42 @@ async function settle(deps, workflow, digest, record) {
457
578
  const cancelled = await cancelUnended(deps, record);
458
579
  if (cancelled)
459
580
  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) {
581
+ if (!ok && scored.length >= REPLAY_MIN && !unanswered.length && !owedWrong) {
461
582
  // 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);
583
+ // escalates recorded). One with neither changes nothing. Never one that still owes runs it was held on: a refit is
584
+ // promoted on all its rows, and they did not answer on those, or answered them under the bar.
585
+ await refitAndWrite(deps, workflow, digest, scored, "its replay held it");
464
586
  }
465
587
  return decided.record;
466
588
  }
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
589
  /** A serving digest, checked once per REFIT_EVERY more graded runs it served: its thresholds refit over those runs and its
473
590
  * 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. */
591
+ * more than PROMOTE_BAR under the agent's. The promotion it serves this run under (`record`, or the digest's newer
592
+ * promotion when one replaced it meanwhile), undefined when it does not serve it. */
475
593
  async function stillServing(deps, workflow, digest, record) {
476
594
  const { store, agentId, log } = deps;
477
595
  const now = deps.now ?? Date.now;
478
596
  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"));
597
+ // Only the grades of runs this promotion served (each keeps its `since`, Grade.promotion): promoted again after a hold,
598
+ // never the ones it was held on, nor a run served under the promotion before and graded after this one.
599
+ const served = grades.filter((grade) => grade.workflow === workflow.name && grade.digest === digest && (grade.path === "workflow" || grade.path === "handed_back") && grade.promotion === record.since);
600
+ // Each write is kept only while the promotion this check read is still the digest's (the same since): a check that read
601
+ // an older one, replaced meanwhile (held, replayed and promoted again), writes nothing over the newer one.
602
+ const same = (was) => was?.decided === "promote" && was.since === record.since;
480
603
  // New since the last check: by seq (putGrade), a cursor the trim of the kept grades never moves back.
481
604
  const checked = record.checked ?? 0;
482
605
  const through = Math.max(checked, ...served.map((grade) => grade.seq ?? 0));
483
606
  if (served.filter((grade) => (grade.seq ?? 0) > checked).length < REFIT_EVERY)
484
- return true;
607
+ return record;
608
+ const promoted = (one) => (one?.decided === "promote" ? one : undefined);
485
609
  // The agent's accuracy by hand: its newest graded runs on the agent path, else the replay's.
486
610
  const byHand = grades.filter((grade) => grade.path === "agent").slice(-REPLAY_INPUTS);
487
611
  const agentAcc = byHand.length ? byHand.filter((grade) => grade.correct).length / byHand.length : record.replay?.agent_acc;
488
612
  // Marked checked at this count first, so two claims never check the same window twice.
489
613
  // 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);
614
+ const marked = await recordPromotion(store.settings, agentId, { ...record, at: iso(now()), checked: through }, (was) => same(was) && (was?.checked ?? 0) === checked);
491
615
  if (!marked.won || agentAcc === undefined)
492
- return marked.record?.decided === "promote";
616
+ return promoted(marked.record);
493
617
  const rows = [];
494
618
  for (const grade of served) {
495
619
  const run = await store.runs.get(grade.run);
@@ -497,23 +621,27 @@ async function stillServing(deps, workflow, digest, record) {
497
621
  const guards = Array.isArray(m.guards) ? m.guards : [];
498
622
  rows.push(grade.path === "workflow" ? { guards, answered: true, wfCorrect: grade.correct, agentCorrect: agentAcc } : { guards, answered: false, wfCorrect: null, agentCorrect: grade.correct ? 1 : 0 });
499
623
  }
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);
624
+ const replayed = record.source === "replay" && record.runs?.length ? (await replayRows(deps, record))?.scored ?? [] : [];
625
+ const wrote = await refitAndWrite(deps, workflow, digest, [...rows, ...replayed], `${plural(served.length, "graded run")} it served`);
626
+ // What actually happened on the served runs: the recorded grades (a workflow-path grade is the workflow's answer, a
627
+ // handed-back one the agent's). Recorded, not rescored: the guards on a run may belong to other workflows the agent called
628
+ // after a hand-back, and rescoring over them would count a right answer as a hand-back at the agent's accuracy.
503
629
  const servedAcc = served.filter((grade) => grade.correct).length / served.length;
504
630
  if (!wrote && servedAcc < agentAcc - PROMOTE_BAR - 1e-9) {
505
631
  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");
632
+ // It keeps the served runs graded wrong it was held on, newest first: its next replay owes them (heldOn).
633
+ const wrong = served.filter((grade) => !grade.correct).map((grade) => grade.run).reverse().slice(0, REPLAY_INPUTS);
634
+ const held = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "hold", source: "graded", reason, held_on: wrong }, same);
507
635
  if (held.won)
508
636
  log(`workflow-first: ${workflow.name} at ${digest} held: ${reason}`);
509
- return held.record?.decided === "promote";
637
+ return promoted(held.record);
510
638
  }
511
- return true;
639
+ return marked.record;
512
640
  }
513
641
  /** One refit of `workflow` over `rows`; when it moves a guard and the rows clear the bar at the new thresholds, the new
514
642
  * text is written as a new revision (a merge from the claim's seed) and promoted with the rows' numbers. True when one
515
643
  * was written. */
516
- async function refitAndWrite(deps, workflow, digest, rows, why, replayed) {
644
+ async function refitAndWrite(deps, workflow, digest, rows, why) {
517
645
  if (!deps.commit || rows.length < REPLAY_MIN)
518
646
  return false;
519
647
  const now = deps.now ?? Date.now;
@@ -528,19 +656,132 @@ async function refitAndWrite(deps, workflow, digest, rows, why, replayed) {
528
656
  deps.log(`workflow-first: ${workflow.name}'s refit did not land on its learning folder; it keeps its thresholds`);
529
657
  return false;
530
658
  }
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
659
  await recordPromotion(deps.store.settings, deps.agentId, {
536
660
  workflow: workflow.name, digest: next, at: iso(now()), decided: "promote", source: "refit",
537
661
  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) },
662
+ replay: { ...scoreOf(refit), of: rows.flatMap((row) => (row.of === undefined ? [] : [row.of])) },
539
663
  refit: { from: digest, guards: refit.guards }, commit: landed,
540
664
  }, (was) => was === undefined);
541
665
  deps.log(`workflow-first: ${reason}; the new revision (${next}) serves from the next run`);
542
666
  return true;
543
667
  }
668
+ /** Why a replay a person asked for (askReplay) or read (replayView) was refused: `missing`, no such workflow, revision or
669
+ * replay of the agent (404); `conflict`, the revision cannot replay now (409), in words that say why. */
670
+ export class ReplayRefused extends Error {
671
+ kind;
672
+ constructor(kind, message) {
673
+ super(message);
674
+ this.kind = kind;
675
+ }
676
+ }
677
+ /** The text of `name` at `digest` and the learning commit it is read from: a commit a record of that digest names (newest
678
+ * first), else the folder's main. When neither holds it, whether the agent has a workflow by that name at all (`named`:
679
+ * a record names it, or main holds it). */
680
+ async function revisionOf(ask, records, name, digest) {
681
+ const folder = ask.folder();
682
+ let main;
683
+ try {
684
+ main = (await readSnapshot(folder.workspace))?.main;
685
+ }
686
+ finally {
687
+ await folder.end().catch(() => undefined);
688
+ }
689
+ const named = records.filter((one) => one.workflow === name && one.digest === digest && one.commit).map((one) => one.commit).reverse();
690
+ let onMain = false;
691
+ for (const commit of new Set([...named, ...(main ? [main] : [])])) {
692
+ const workflow = (await workflowsAt(ask, commit).catch(() => [])).find((one) => one.name === name);
693
+ if (workflow && workflowDigest(workflow) === digest)
694
+ return { workflow, commit };
695
+ if (commit === main)
696
+ onMain = workflow !== undefined;
697
+ }
698
+ return { named: onMain || records.some((one) => one.workflow === name) };
699
+ }
700
+ /** A replay of `name` at `digest` a person asked for: the claim path's replay (reserve, startReplay), on `inputs`: `held`,
701
+ * the graded runs its last replay or hold was decided on (else, with none, the agent's newest REPLAY_INPUTS), or a number,
702
+ * the agent's newest that many (each a graded input the workflow fits); with either, the served runs graded wrong it was
703
+ * held on (heldOn), which it promotes only once it answered on: the claim's picker (inputsFor). Its runs end as a claim's
704
+ * do, and it is decided by the claim path's settle: at a claim that lays the revision, or at its read (replayView).
705
+ * Refused (ReplayRefused): no such workflow or revision; one replaying already, or another revision of it replaying (one
706
+ * at a time); a promoted one (it serves already); fewer than REPLAY_MIN graded inputs it fits (a replay on fewer could
707
+ * only hold it: settle scores none of it), refused before anything is reserved; an agent that does not learn here. The
708
+ * replay's id and its inputs. */
709
+ export async function askReplay(ask, name, digest, inputs) {
710
+ const records = await promotionsOf(ask.store.settings, ask.agentId);
711
+ const found = await revisionOf(ask, records, name, digest);
712
+ if ("named" in found)
713
+ 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}.`);
714
+ const own = promotionOf(records, name, digest);
715
+ if (own?.decided === "replaying")
716
+ throw new ReplayRefused("conflict", `${name} at ${digest} is replaying already: read that replay, or wait for it to end.`);
717
+ if (own?.decided === "promote")
718
+ 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.`);
719
+ const rival = replayingOf(records, name, digest)[0];
720
+ if (rival)
721
+ throw new ReplayRefused("conflict", `${name} at ${rival.digest} is replaying: one revision of a workflow replays at a time. Ask again once it ends.`);
722
+ const { graded, owed, named } = await inputsFor({ store: ask.store, agentId: ask.agentId }, found.workflow, digest, records, inputs);
723
+ if (graded.length < REPLAY_MIN) {
724
+ 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";
725
+ 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)";
726
+ 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}.`);
727
+ }
728
+ const { launch, revisionId } = await ask.launchOf(graded[0].launch.input);
729
+ if (!launch.learning || launch.learning.notesOnly)
730
+ 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).`);
731
+ 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 } : {}) };
732
+ 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`;
733
+ // Kept only while the revision's newest record is still the one read here: each record write stamps a new `at`.
734
+ const reserved = await reserve(deps, found.workflow, digest, graded, said, (was) => was?.at === own?.at && was?.decided === own?.decided, owed);
735
+ if (!reserved.won || !reserved.record?.replay_id)
736
+ 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.`);
737
+ ask.log(`workflow-first: ${name} at ${digest}: ${said}`);
738
+ return { replay: reserved.record.replay_id, inputs: graded.length };
739
+ }
740
+ /** The claim's ports a replay's read settles it through (replayView), with the launch its record chose when it was
741
+ * reserved (PromotionRecord.launch, the one every replay run of it runs with): its revision, and its learning commit (a
742
+ * refit lands as a merge from it). Undefined when that launch cannot be read. */
743
+ function readPorts(ask, launch) {
744
+ const body = readLaunchBody(launch.body);
745
+ return body ? claimPromotion({ ...ask, revisionId: launch.revision, launch: body }) : undefined;
746
+ }
747
+ /** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (the claim path's settle)
748
+ * once its runs ended or its deadline passed: it writes only the decision. A read never starts a run: a replay whose
749
+ * launch was interrupted (reserved runs never created) reads running until its deadline, then is decided held, read as
750
+ * failed, its reason saying none of its runs started and to start it again with POST. So a replay of a revision no claim
751
+ * lays (an older, held one) is decided too, and never running forever. Once decided, it reads only its record. Refused
752
+ * (missing) when the agent has no such replay. */
753
+ export async function replayView(ask, name, digest, id) {
754
+ const find = async () => (await promotionsOf(ask.store.settings, ask.agentId)).findLast((one) => one.workflow === name && one.digest === digest && one.replay_id === id);
755
+ let record = await find();
756
+ if (!record)
757
+ throw new ReplayRefused("missing", `${name} at ${digest} has no replay ${id}.`);
758
+ const textOf = async (one) => (one.commit ? (await workflowsAt(ask, one.commit).catch(() => [])).find((text) => text.name === name && workflowDigest(text) === digest) : undefined);
759
+ let text = record.decided === "replaying" ? await textOf(record) : undefined;
760
+ const ports = record.decided === "replaying" && text && record.launch ? readPorts(ask, record.launch) : undefined;
761
+ if (ports && text) {
762
+ // Read back by its id: whatever settled it (this read, a claim, another read), never another replay's record.
763
+ await settle(ports, text, digest, record);
764
+ record = (await find()) ?? record;
765
+ }
766
+ const decided = record.decided === "replaying" ? undefined : record.decided;
767
+ const inputs = record.runs?.length ?? 0;
768
+ const said = decided ? { decided, reason: record.reason } : {};
769
+ const kept = record.replay && decided && decided !== "superseded" ? record.replay : undefined;
770
+ if (kept) {
771
+ // Decided: its record's numbers alone. With not one of its reserved runs ever created (none counted: a decided
772
+ // replay counted every run there was, and none is created after), nothing was replayed (settle's reason says so).
773
+ const outcomes = kept.outcomes ?? NO_OUTCOMES;
774
+ const neverStarted = inputs > 0 && Object.values(outcomes).every((count) => count === 0);
775
+ return { replay: id, workflow: name, digest, status: neverStarted ? "failed" : "done", inputs, outcomes, score: scoreOf(kept), cost_usd: kept.cost_usd ?? null, ...said };
776
+ }
777
+ const read = await replayRows(ask, record, true);
778
+ text ??= await textOf(record);
779
+ return {
780
+ replay: id, workflow: name, digest, status: decided === undefined ? "running" : decided === "superseded" ? "failed" : "done", inputs,
781
+ outcomes: read?.outcomes ?? NO_OUTCOMES,
782
+ score: scoreRows(read?.scored ?? [], text ? thresholdsOf(text.workflow) : new Map()), cost_usd: read?.cost ?? null, ...said,
783
+ };
784
+ }
544
785
  /** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the graded run's recorded calls, read from its journal
545
786
  * (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
787
  * they listed them) or the built-in list. Undefined for any other run. A recording that cannot be read is an empty one: