@parcha/agentrun-serve 0.1.0-beta.43 → 0.1.0-beta.45

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 (388) hide show
  1. package/CHANGELOG.md +231 -0
  2. package/README.md +580 -320
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +92 -22
  28. package/dist/composio-preset.d.ts +4 -3
  29. package/dist/composio-preset.js +81 -11
  30. package/dist/composio-triggers.d.ts +34 -2
  31. package/dist/composio-triggers.js +261 -31
  32. package/dist/computer-attach.d.ts +40 -5
  33. package/dist/computer-attach.js +130 -15
  34. package/dist/computer-keys.d.ts +3 -0
  35. package/dist/computer-keys.js +7 -1
  36. package/dist/computer-live.js +3 -2
  37. package/dist/computer-lost.d.ts +11 -0
  38. package/dist/computer-lost.js +19 -0
  39. package/dist/computer-record.d.ts +10 -2
  40. package/dist/computer-record.js +50 -18
  41. package/dist/computer-setting.d.ts +1 -0
  42. package/dist/computer-setting.js +2 -2
  43. package/dist/computers.d.ts +21 -10
  44. package/dist/computers.js +39 -28
  45. package/dist/console/assets/index-3O2Yl6hZ.js +701 -0
  46. package/dist/console/assets/index-DaFsZuzQ.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decisions.d.ts +1 -1
  49. package/dist/dial-relay.d.ts +29 -0
  50. package/dist/dial-relay.js +94 -0
  51. package/dist/email/tools.js +10 -5
  52. package/dist/env-proxy.d.ts +2 -0
  53. package/dist/env-proxy.js +35 -0
  54. package/dist/errors.d.ts +4 -1
  55. package/dist/errors.js +10 -4
  56. package/dist/faux-computers.d.ts +8 -2
  57. package/dist/faux-computers.js +83 -6
  58. package/dist/harness-archive.d.ts +67 -0
  59. package/dist/harness-archive.js +177 -0
  60. package/dist/harness-goose.d.ts +34 -0
  61. package/dist/harness-goose.js +87 -0
  62. package/dist/harness-install.d.ts +21 -0
  63. package/dist/harness-install.js +24 -11
  64. package/dist/harness-opencode/adapter.js +1 -1
  65. package/dist/harness-table.d.ts +59 -3
  66. package/dist/harness-table.js +119 -14
  67. package/dist/harness.d.ts +17 -1
  68. package/dist/harness.js +22 -11
  69. package/dist/host.d.ts +12 -10
  70. package/dist/host.js +19 -16
  71. package/dist/import-worker.d.ts +3 -0
  72. package/dist/import-worker.js +7 -5
  73. package/dist/import.d.ts +22 -1
  74. package/dist/import.js +141 -28
  75. package/dist/key-check.js +3 -0
  76. package/dist/learn/audit.d.ts +6 -6
  77. package/dist/learn/audit.js +3 -7
  78. package/dist/learn/check.d.ts +26 -89
  79. package/dist/learn/check.js +58 -336
  80. package/dist/learn/commit.d.ts +63 -90
  81. package/dist/learn/commit.js +124 -316
  82. package/dist/learn/compile.d.ts +53 -50
  83. package/dist/learn/compile.js +88 -103
  84. package/dist/learn/corrections.d.ts +13 -0
  85. package/dist/learn/corrections.js +23 -0
  86. package/dist/learn/delete.d.ts +17 -0
  87. package/dist/learn/delete.js +42 -0
  88. package/dist/learn/folder.d.ts +35 -47
  89. package/dist/learn/folder.js +118 -134
  90. package/dist/learn/index.d.ts +3 -5
  91. package/dist/learn/index.js +6 -9
  92. package/dist/learn/learning.sh +45 -15
  93. package/dist/learn/promote.d.ts +20 -2
  94. package/dist/learn/promote.js +17 -4
  95. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +34 -38
  96. package/dist/learn/{skills.js → workflow-draft.js} +65 -59
  97. package/dist/learn/workflow-nodes.d.ts +22 -1
  98. package/dist/learn/workflow-nodes.js +29 -10
  99. package/dist/learned-workflow.js +2 -2
  100. package/dist/learning-cost.d.ts +127 -13
  101. package/dist/learning-cost.js +142 -10
  102. package/dist/learning-routes.d.ts +99 -170
  103. package/dist/learning-routes.js +199 -420
  104. package/dist/learning-run.d.ts +19 -40
  105. package/dist/learning-run.js +23 -93
  106. package/dist/learning-setting.d.ts +4 -4
  107. package/dist/learning-setting.js +6 -6
  108. package/dist/learning-words.d.ts +28 -74
  109. package/dist/learning-words.js +64 -162
  110. package/dist/learning.d.ts +62 -393
  111. package/dist/learning.js +101 -651
  112. package/dist/listen-first.d.ts +30 -0
  113. package/dist/listen-first.js +115 -0
  114. package/dist/live-reach.d.ts +25 -2
  115. package/dist/live-reach.js +46 -4
  116. package/dist/llms.txt +2 -1
  117. package/dist/local-models.d.ts +3 -11
  118. package/dist/local-models.js +5 -6
  119. package/dist/mcp-servers-store.d.ts +16 -16
  120. package/dist/model-form.js +6 -5
  121. package/dist/model.d.ts +12 -4
  122. package/dist/model.js +41 -16
  123. package/dist/native/binding.js +1 -1
  124. package/dist/native/connection.js +1 -1
  125. package/dist/native/discovery.js +1 -1
  126. package/dist/native/instructions.d.ts +3 -0
  127. package/dist/native/instructions.js +5 -3
  128. package/dist/native/remote-worker-bridge.js +9 -43
  129. package/dist/native/remote.d.ts +8 -15
  130. package/dist/native/remote.js +3 -3
  131. package/dist/native/schema.js +1 -1
  132. package/dist/native/types.d.ts +2 -2
  133. package/dist/openapi.js +375 -347
  134. package/dist/owner.d.ts +8 -0
  135. package/dist/owner.js +11 -0
  136. package/dist/paid-calls.d.ts +14 -0
  137. package/dist/paid-calls.js +31 -1
  138. package/dist/particle-provider.d.ts +11 -0
  139. package/dist/particle-provider.js +135 -0
  140. package/dist/place.d.ts +8 -3
  141. package/dist/place.js +13 -9
  142. package/dist/port-models.d.ts +12 -4
  143. package/dist/port-models.js +28 -11
  144. package/dist/print.d.ts +27 -0
  145. package/dist/print.js +21 -0
  146. package/dist/provider.d.ts +7 -0
  147. package/dist/provider.js +30 -2
  148. package/dist/reflect-range.js +2 -3
  149. package/dist/run-launch.d.ts +14 -28
  150. package/dist/run-launch.js +9 -12
  151. package/dist/run-learning-served.d.ts +16 -90
  152. package/dist/run-listing.d.ts +34 -0
  153. package/dist/run-listing.js +128 -0
  154. package/dist/run-model-key.d.ts +64 -0
  155. package/dist/run-model-key.js +147 -0
  156. package/dist/run-timeline-served.js +5 -3
  157. package/dist/run-trace.d.ts +97 -0
  158. package/dist/run-trace.js +253 -0
  159. package/dist/run-view.d.ts +15 -0
  160. package/dist/run-view.js +9 -0
  161. package/dist/runnable.js +2 -1
  162. package/dist/runner/adapter-loop.d.ts +14 -6
  163. package/dist/runner/adapter-loop.js +25 -14
  164. package/dist/runner/adapter-run-spec.d.ts +22 -7
  165. package/dist/runner/adapter-run-spec.js +130 -77
  166. package/dist/runner/adapters/index.d.ts +4 -2
  167. package/dist/runner/adapters/index.js +35 -4
  168. package/dist/runner/adapters/pi.d.ts +4 -12
  169. package/dist/runner/adapters/pi.js +2 -2
  170. package/dist/runner/audit.d.ts +5 -1
  171. package/dist/runner/audit.js +31 -12
  172. package/dist/runner/beside.d.ts +7 -2
  173. package/dist/runner/beside.js +41 -9
  174. package/dist/runner/claim-secrets.d.ts +66 -1
  175. package/dist/runner/claim-secrets.js +136 -3
  176. package/dist/runner/cli-run-spec.d.ts +2 -1
  177. package/dist/runner/cli-run-spec.js +82 -59
  178. package/dist/runner/commands.d.ts +3 -6
  179. package/dist/runner/conformance/harness.d.ts +6 -0
  180. package/dist/runner/conformance/harness.js +16 -5
  181. package/dist/runner/dispatch.d.ts +2 -2
  182. package/dist/runner/end-of-run.d.ts +6 -14
  183. package/dist/runner/end-of-run.js +8 -33
  184. package/dist/runner/feedback-round.d.ts +5 -4
  185. package/dist/runner/feedback-round.js +14 -10
  186. package/dist/runner/github-app.js +3 -1
  187. package/dist/runner/harness-loops.d.ts +0 -8
  188. package/dist/runner/harness-loops.js +30 -56
  189. package/dist/runner/held.d.ts +170 -0
  190. package/dist/runner/held.js +57 -0
  191. package/dist/runner/journal-kinds.d.ts +7 -3
  192. package/dist/runner/journal-kinds.js +2 -3
  193. package/dist/runner/learned-first.d.ts +40 -0
  194. package/dist/runner/learned-first.js +32 -0
  195. package/dist/runner/learning-end.d.ts +77 -66
  196. package/dist/runner/learning-end.js +250 -299
  197. package/dist/runner/learning-seed.d.ts +15 -33
  198. package/dist/runner/learning-seed.js +24 -45
  199. package/dist/runner/loop-contract.d.ts +8 -3
  200. package/dist/runner/loop-contract.js +4 -0
  201. package/dist/runner/loop.js +6 -2
  202. package/dist/runner/main.d.ts +18 -9
  203. package/dist/runner/main.js +82 -22
  204. package/dist/runner/mcp-run.d.ts +11 -0
  205. package/dist/runner/mcp-run.js +67 -0
  206. package/dist/runner/memory-claim.d.ts +14 -6
  207. package/dist/runner/memory-claim.js +18 -9
  208. package/dist/runner/model-route.d.ts +7 -4
  209. package/dist/runner/model-route.js +22 -10
  210. package/dist/runner/native-loop.d.ts +0 -7
  211. package/dist/runner/native-loop.js +9 -101
  212. package/dist/runner/promotion.d.ts +13 -6
  213. package/dist/runner/promotion.js +63 -17
  214. package/dist/runner/reflect-hook.d.ts +64 -91
  215. package/dist/runner/reflect-hook.js +112 -206
  216. package/dist/runner/run-channel.d.ts +43 -0
  217. package/dist/runner/run-channel.js +467 -0
  218. package/dist/runner/run-child-host.d.ts +169 -0
  219. package/dist/runner/run-child-host.js +1222 -0
  220. package/dist/runner/run-child.d.ts +1 -0
  221. package/dist/runner/run-child.js +254 -0
  222. package/dist/runner/run-errors.d.ts +2 -0
  223. package/dist/runner/run-errors.js +20 -0
  224. package/dist/runner/runner.js +58 -9
  225. package/dist/runner/sdk-ask.d.ts +78 -0
  226. package/dist/runner/sdk-ask.js +158 -0
  227. package/dist/runner/sdk-loop.d.ts +2 -4
  228. package/dist/runner/sdk-loop.js +29 -49
  229. package/dist/runner/store-secrets.d.ts +5 -3
  230. package/dist/runner/store-secrets.js +14 -6
  231. package/dist/runner/workflow-first.d.ts +5 -0
  232. package/dist/runner/workflow-first.js +4 -0
  233. package/dist/runner/workflow-spec.js +17 -4
  234. package/dist/runs-over-store.d.ts +21 -32
  235. package/dist/runs-over-store.js +44 -41
  236. package/dist/sdk/runs.d.ts +6 -11
  237. package/dist/sdk/runs.js +20 -41
  238. package/dist/sdk/schema.js +3 -4
  239. package/dist/sdk/workflows.d.ts +1 -1
  240. package/dist/seal-key.d.ts +5 -0
  241. package/dist/seal-key.js +7 -0
  242. package/dist/secrets.d.ts +3 -0
  243. package/dist/secrets.js +16 -3
  244. package/dist/server.d.ts +119 -83
  245. package/dist/server.js +1121 -419
  246. package/dist/sign-ins-store.d.ts +8 -0
  247. package/dist/sign-ins-store.js +36 -1
  248. package/dist/skills.js +1 -1
  249. package/dist/store/index.d.ts +3 -3
  250. package/dist/store/index.js +2 -2
  251. package/dist/store/journal/storage.js +3 -0
  252. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  253. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  254. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  255. package/dist/store/schema.d.ts +53 -4
  256. package/dist/store/schema.js +137 -6
  257. package/dist/store/seal.d.ts +20 -2
  258. package/dist/store/seal.js +24 -8
  259. package/dist/store/sqlite/connection.d.ts +2 -0
  260. package/dist/store/sqlite/connection.js +3 -1
  261. package/dist/store/sqlite/run-launch.d.ts +4 -1
  262. package/dist/store/sqlite/run-launch.js +12 -0
  263. package/dist/store/sqlite/run-patch.d.ts +0 -17
  264. package/dist/store/sqlite/run-patch.js +4 -33
  265. package/dist/store/sqlite/store.d.ts +3 -2
  266. package/dist/store/sqlite/store.js +360 -75
  267. package/dist/store/sqlite/worker.js +25 -0
  268. package/dist/store/store.d.ts +231 -39
  269. package/dist/store/store.js +25 -3
  270. package/dist/store-reads/analytics.js +11 -1
  271. package/dist/store-reads/learning.d.ts +131 -194
  272. package/dist/store-reads/learning.js +292 -301
  273. package/dist/store-reads/loop.d.ts +0 -1
  274. package/dist/store-reads/loop.js +1 -1
  275. package/dist/store-reads/stats.js +13 -3
  276. package/dist/store-view.d.ts +34 -2
  277. package/dist/store-view.js +108 -41
  278. package/dist/telemetry.d.ts +59 -0
  279. package/dist/telemetry.js +153 -0
  280. package/dist/template-eval.d.ts +3 -6
  281. package/dist/template-eval.js +22 -36
  282. package/dist/templates.d.ts +2 -1
  283. package/dist/templates.js +6 -3
  284. package/dist/timeline/index.d.ts +1 -1
  285. package/dist/timeline/index.js +1 -1
  286. package/dist/timeline/timeline.d.ts +5 -1
  287. package/dist/timeline/timeline.js +16 -0
  288. package/dist/tool-gate.d.ts +0 -7
  289. package/dist/tool-gate.js +1 -15
  290. package/dist/tool-keys-store.d.ts +1 -1
  291. package/dist/tool-keys.d.ts +6 -4
  292. package/dist/tool-keys.js +12 -6
  293. package/dist/tool-plane.d.ts +12 -12
  294. package/dist/tools.d.ts +13 -13
  295. package/dist/tools.js +29 -9
  296. package/dist/trigger-adapter.d.ts +3 -0
  297. package/dist/trigger-adapters.d.ts +4 -0
  298. package/dist/trigger-adapters.js +13 -0
  299. package/dist/trigger-composio.d.ts +58 -1
  300. package/dist/trigger-composio.js +160 -6
  301. package/dist/triggers.d.ts +64 -5
  302. package/dist/triggers.js +141 -17
  303. package/dist/validate.d.ts +11 -7
  304. package/dist/validate.js +9 -8
  305. package/dist/webhooks.d.ts +4 -1
  306. package/dist/webhooks.js +11 -4
  307. package/dist/workspace/agent-computer.d.ts +2 -0
  308. package/dist/workspace/agent-computer.js +2 -0
  309. package/dist/workspace/archil-claim.d.ts +7 -0
  310. package/dist/workspace/archil-claim.js +29 -0
  311. package/dist/workspace/archil.d.ts +9 -1
  312. package/dist/workspace/archil.js +165 -3
  313. package/dist/workspace/attach.d.ts +3 -1
  314. package/dist/workspace/attach.js +2 -0
  315. package/dist/workspace/attached-computers.d.ts +16 -5
  316. package/dist/workspace/attached-computers.js +25 -9
  317. package/dist/workspace/computer-deps.js +1 -1
  318. package/dist/workspace/computer-for-claim.d.ts +22 -8
  319. package/dist/workspace/computer-for-claim.js +339 -46
  320. package/dist/workspace/computer-hold.js +2 -1
  321. package/dist/workspace/computer-kept.d.ts +11 -1
  322. package/dist/workspace/computer-kept.js +24 -3
  323. package/dist/workspace/resolve-computer.d.ts +41 -21
  324. package/dist/workspace/resolve-computer.js +172 -64
  325. package/dist/workspace/revision-skills.d.ts +1 -2
  326. package/dist/workspace/revision-skills.js +3 -4
  327. package/dist/workspace/run-workspace.d.ts +1 -1
  328. package/dist/workspace/run-workspace.js +5 -0
  329. package/dist/workspace/synced-folder.d.ts +85 -0
  330. package/dist/workspace/synced-folder.js +230 -0
  331. package/dist/workspace/workspace.d.ts +4 -0
  332. package/launcher/agentrun-serve +1 -1
  333. package/package.json +10 -9
  334. package/templates/README.md +7 -7
  335. package/templates/inbound-lead/agent.md +3 -3
  336. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  337. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  338. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  339. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  340. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  341. package/templates/inbound-lead/lead.schema.json +6 -5
  342. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  343. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  344. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  345. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  346. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  347. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  348. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  349. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  350. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  351. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  352. package/dist/console/assets/index-BrcDSBD8.css +0 -1
  353. package/dist/console/assets/index-Bz6IWncl.js +0 -711
  354. package/dist/learn/grade.d.ts +0 -138
  355. package/dist/learn/grade.js +0 -682
  356. package/dist/learn/notes.d.ts +0 -81
  357. package/dist/learn/notes.js +0 -178
  358. package/dist/learn/reflect.d.ts +0 -77
  359. package/dist/learn/reflect.js +0 -228
  360. package/dist/learn/relevance.d.ts +0 -24
  361. package/dist/learn/relevance.js +0 -91
  362. package/dist/learn/seed-check.d.ts +0 -74
  363. package/dist/learn/seed-check.js +0 -103
  364. package/dist/learning-batch.d.ts +0 -291
  365. package/dist/learning-batch.js +0 -600
  366. package/dist/learning-evals.d.ts +0 -33
  367. package/dist/learning-evals.js +0 -98
  368. package/dist/native/context.d.ts +0 -6
  369. package/dist/native/context.js +0 -22
  370. package/dist/propose.d.ts +0 -52
  371. package/dist/propose.js +0 -224
  372. package/dist/runner/learning-ask.d.ts +0 -47
  373. package/dist/runner/learning-ask.js +0 -128
  374. package/dist/runner/learning-dispatch.d.ts +0 -45
  375. package/dist/runner/learning-dispatch.js +0 -99
  376. package/dist/runner/learning-factory.d.ts +0 -16
  377. package/dist/runner/learning-factory.js +0 -50
  378. package/dist/runner/learning-loop.d.ts +0 -273
  379. package/dist/runner/learning-loop.js +0 -521
  380. package/dist/usage.d.ts +0 -11
  381. package/dist/usage.js +0 -11
  382. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  383. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  384. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  385. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  386. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  387. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  388. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -1,44 +1,42 @@
1
- // A run's learning end, from the one store: what its end-of-run turn kept (learning_proposals) and the end of the
2
- // learning run queued with it, which grades and merges it on the runner (runner/learning-loop.ts), read from that
3
- // run's row and journal. It gives the fields the server's own grade set on a run's learning (learning.ts Learning) and
4
- // the run's view, its whole learning, its learning ledger line, /v2/usage and /v2/stats read: how it ended and why, in
5
- // a person's words, the verdict, what it merged, learned, held for the owner's OK and lost, what the checks left out,
6
- // and what the grade spent. What the server keeps on a run before its end (what it was given and read, its seed's
7
- // notes, its answer's time and costs) is the run's, not this.
8
- import { posix } from "node:path";
1
+ // A run's learning end, from the one store: what its end-of-run turn kept beside the run's end (learning_proposals:
2
+ // merged with the commit it wrote, or dropped with its reason), as runner/reflect-hook.ts writes it in the run's end
3
+ // commit. It gives the run's learning (learning.ts Learning) to the run's view, its whole learning, /v2/usage and /v2/stats:
4
+ // how it ended and why, in a person's words, what it merged and held for the owner's OK, what the checks left out, and
5
+ // what its compile turn cost. What the server keeps on a run before its end (its seed, its answer's time and costs) is
6
+ // the run's launch's and journal's, not this.
9
7
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
10
8
  import { currentLearning, holdsForOk, LEARNING_REASONS } from "../learning.js";
11
9
  import { runLearningBody } from "../learning-routes.js";
12
10
  import { learningStartOf, learningStartOfStored, readLaunchBody, seedFailed } from "../run-launch.js";
13
11
  import { said, STOPPED } from "../learning-words.js";
14
- import { learningImpact, noteRuns, notesRead } from "../learning-run.js";
15
- import { costSummary, RUN_PATHS, runCostOf } from "../learning-cost.js";
12
+ import { learningImpact } from "../learning-run.js";
13
+ import { amortize, billOf, costSummary, JOB_PATHS, noiseOff, RUN_PATHS, runCostOf, SERVED_PATHS, tookOverOf } from "../learning-cost.js";
14
+ import { COMPILE_AFTER_DEFAULT } from "../learning-setting.js";
16
15
  import { modelsOwn, runPathOf, workflowNameOf } from "../runner/learning-end.js";
17
16
  import { feedbackStatus } from "../runner/feedback-round.js";
18
- import { PAST_RUNS, servedAnswerOf, servedAnswerStands, servedOf, workflowCostsOf } from "../runner/workflow-first.js";
17
+ import { costStopOf, PAST_RUNS, servedAnswerOf, servedAnswerStands, servedOf, workflowCostsOf } from "../runner/workflow-first.js";
19
18
  import { reflects } from "../reflect-range.js";
20
- import { notesOf } from "../usage.js";
19
+ import { correctionCount } from "../learn/corrections.js";
21
20
  import { runEntries, runReflect, runTimeline, withoutFeedbackRounds } from "./journal.js";
22
21
  import { FINAL_STATES, StoreLaunchMissing } from "../store/store.js";
23
- import { journalEntries } from "../runner/journal-reader.js";
24
22
  import { KINDS } from "../runner/journal-kinds.js";
25
- import { keptOf, learnedOf, lostOf } from "../runner/learning-loop.js";
26
23
  import { promotedOf } from "../learn/compile.js";
27
24
  import { isShadowRun, shadowRunId } from "../learn/audit.js";
28
25
  import { championOf, checkShares, gradesOf, gradeView, promotionsOf } from "../learn/promote.js";
29
26
  const timeOf = (ms) => new Date(ms).toISOString();
30
27
  const usdOrNull = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
31
- /** What a kept row says of a run that looked back (learning-run.ts closeLearning's fields): none for one that did not. */
28
+ const textOrNull = (value) => (typeof value === "string" ? value : null);
29
+ /** What a kept row says of a run that looked back (its compile turn's figures): none for one that did not. */
32
30
  function answeredOf(row) {
33
31
  if (typeof row.answered_at !== "string")
34
32
  return {};
35
33
  return { answered_at: row.answered_at, job_cost_usd: usdOrNull(row.job_cost_usd), look_back_usd: usdOrNull(row.look_back_usd) };
36
34
  }
37
- /** Agent `agentId`'s runs' records read at once, whatever their number: its runs' launches (Store.runs.launches) and every
38
- * round its runs' learning kept with the learning runs they name (Store.learning.kept), two reads beside `listed` (its
39
- * runs, as runs.list read them). Each answers as the store's per-run read does: a run of `listed` with no launch row is
40
- * StoreLaunchMissing, one that kept no learning has no round. A run not of `listed` is read from the store, but for an
41
- * audit's shadow run: `listed` is every run of the agent, its shadows among them. */
35
+ /** Agent `agentId`'s runs' records read at once, whatever their number: its runs' launches (Store.runs.learningStarts)
36
+ * and every round its runs' learning kept (Store.learning.kept), two reads beside `listed` (its runs, as runs.list read
37
+ * them). Each answers as the store's per-run read does: a run of `listed` with no launch row is StoreLaunchMissing, one
38
+ * that kept no learning has no round. A run not of `listed` is read from the store, but for an audit's shadow run:
39
+ * `listed` is every run of the agent, its shadows among them. */
42
40
  export async function agentRecordsOf(store, agentId, listed) {
43
41
  const [starts, kept] = await Promise.all([store.runs.learningStarts(agentId), store.learning.kept(agentId)]);
44
42
  const ours = new Set(listed.map((run) => run.id));
@@ -47,7 +45,7 @@ export async function agentRecordsOf(store, agentId, listed) {
47
45
  const rounds = new Map();
48
46
  for (const one of kept.proposals)
49
47
  rounds.set(one.runId, [...(rounds.get(one.runId) ?? []), one]);
50
- const rows = new Map([...listed, ...kept.learningRuns].map((run) => [run.id, run]));
48
+ const rows = new Map(listed.map((run) => [run.id, run]));
51
49
  return {
52
50
  runs: {
53
51
  launch: (runId) => store.runs.launch(runId),
@@ -72,79 +70,46 @@ export async function agentRecordsOf(store, agentId, listed) {
72
70
  },
73
71
  };
74
72
  }
75
- /** Run `runId`'s learning end (its newest round's, or round `round`'s); null when the run kept no learning. Proposed while its learning run has not ended. `records`: where its rows are read (the store's per-run reads by default). */
73
+ /** Run `runId`'s learning end (its newest round's, or round `round`'s); null when the run kept no learning. `records`:
74
+ * where its rows are read (the store's per-run reads by default). */
76
75
  export async function runLearningEnd(store, runId, round, records = store) {
77
76
  const kept = await records.learning.proposal(runId, round);
78
77
  if (!kept)
79
78
  return null;
80
79
  const row = (kept.proposal ?? {});
81
- return { ...(await endOfKept(store, kept, row, records)), ...answeredOf(row), ...compiledOf(row) };
80
+ return { ...endOfKept(kept.createdAt, row), ...answeredOf(row), ...compiledOf(row) };
82
81
  }
83
82
  /** What a kept row says of its compile turn (runner/reflect-hook.ts): the record, and a failed draft's errors; read as
84
83
  * untrusted, an entry out of shape left out. */
85
84
  function compiledOf(row) {
86
85
  const texts = (list) => (Array.isArray(list) ? list.filter((one) => typeof one === "string") : []);
87
- // The kept row's own (its proposal's `compiled` names only the workflow and its notes, for the merge).
88
- const { compiled: record, draft_errors } = row;
89
- const errors = texts(draft_errors);
86
+ const errors = texts(row.draft_errors);
90
87
  const out = errors.length ? { draft_errors: errors } : {};
88
+ const record = row.compiled;
91
89
  if (record && typeof record === "object" && typeof record.workflow === "string") {
92
- const { workflow, from_notes, attempts, digest } = record;
90
+ const { workflow, attempts, digest } = record;
93
91
  const tries = Array.isArray(attempts) ? attempts.filter((one) => one && typeof one === "object" && typeof one.ok === "boolean").map((one) => ({ ok: one.ok, errors: texts(one.errors) })) : [];
94
92
  // `promoted` is never kept: runLearningOverStore reads it from the agent's promotion records (promotedOf).
95
- out.compiled = { workflow, from_notes: texts(from_notes), attempts: tries, ...(typeof digest === "string" && /^[0-9a-f]{16}$/.test(digest) ? { digest } : {}) };
93
+ out.compiled = { workflow, attempts: tries, ...(typeof digest === "string" && /^[0-9a-f]{16}$/.test(digest) ? { digest } : {}) };
96
94
  }
97
95
  return out;
98
96
  }
99
- /** The learning end a kept row and its learning run's journal say. */
100
- async function endOfKept(store, kept, row, records = store) {
101
- const at = timeOf(kept.createdAt);
102
- // Dropped before it was proposed (a cut run, nothing to keep, the checks): its end is the kept row's.
103
- if (row.state !== "proposed" || !row.proposal) {
104
- return { state: "dropped", reason: (row.reason ?? null), detail: row.detail ?? null, at, ...(row.problems?.length ? { problems: row.problems } : {}) };
97
+ /** The learning end a kept row says, at the time it was kept: merged with its commit, else dropped with its reason. */
98
+ function endOfKept(createdAt, row) {
99
+ const at = timeOf(createdAt);
100
+ const problems = Array.isArray(row.problems) && row.problems.length ? { problems: row.problems } : {};
101
+ if (row.state === "merged" && typeof row.merged === "string") {
102
+ const corrections = typeof row.corrections === "number" && row.corrections > 0 ? { corrections: row.corrections } : {};
103
+ const workflows = Array.isArray(row.workflows) && row.workflows.length ? { workflows: row.workflows } : {};
104
+ return { state: "merged", reason: null, detail: textOrNull(row.detail), at, merged: row.merged, ...workflows, ...corrections, ...problems };
105
105
  }
106
- // What the checks left out goes with it to its end.
107
- const left = row.left?.length ? { problems: row.left } : {};
108
- const proposed = { state: "proposed", reason: null, detail: row.detail ?? null, at, ...left };
109
- if (!kept.learningRunId)
110
- return proposed;
111
- let learningRun = await records.runs.get(kept.learningRunId);
112
- const { merged, dropped, graded } = await learningEndEntries(store, kept.learningRunId, learningRun);
113
- if (!merged && !dropped)
114
- return proposed;
115
- // The loop saves its end entry and the learning run's end (state, ended_at) in one transaction, and the row was read
116
- // before the journal: an end the row had not seen landed between the two reads. The row read again from the store (past
117
- // any list read before) is the ended one, so the end is at its ended_at, never once at the proposal's time.
118
- if (!(learningRun && FINAL_STATES.includes(learningRun.state)))
119
- learningRun = await store.runs.get(kept.learningRunId);
120
- const endedAt = learningRun?.endedAt ? timeOf(learningRun.endedAt) : at;
121
- // What the grade spent: the graded entry's, or what a grade that failed spent before it did.
122
- const spent = graded ?? (dropped && "usd" in dropped ? { usd: dropped.usd ?? null, tokens: dropped.tokens ?? null } : undefined);
123
- const cost = spent ? { cost_usd: { grade: spent.usd }, tokens: { grade: spent.tokens ?? null } } : {};
124
- if (merged && graded) {
125
- // Each item as the merge settled it: its record's verdict (a note it left out is no longer kept, and says why). A merge
126
- // recorded with none (before the record kept it) reads no item decisions.
127
- const verdict = merged.verdict;
128
- const what = verdict ? learnedOf(keptOf(row.proposal, verdict), verdict) : { learned: [], pending: [], skills: [], workflows: [] };
129
- return {
130
- state: "merged", reason: null, detail: merged.detail, at: endedAt, ...left, ...(verdict ? { verdict } : {}), graded: { ...graded.graded }, ...cost, merged: merged.commit,
131
- learned: what.learned, ...(what.pending.length ? { pending: what.pending } : {}), ...(what.skills.length ? { skills: what.skills } : {}), ...(what.workflows.length ? { workflows: what.workflows } : {}),
132
- };
133
- }
134
- const reason = (dropped?.reason ?? null);
135
- const lost = reason === "grader" ? lostOf(row.proposal) : [];
136
- return {
137
- state: "dropped", reason, detail: dropped?.detail ?? null, at: endedAt,
138
- ...(dropped?.problems?.length ? { problems: [...dropped.problems] } : left),
139
- // The verdict, when one was given; the blobs it read only go with a merge (the server kept them for its merge alone).
140
- ...(graded ? { verdict: graded.verdict } : {}), ...cost, ...(lost.length ? { lost } : {}),
141
- };
106
+ return { state: "dropped", reason: textOrNull(row.reason), detail: textOrNull(row.detail), at, ...problems };
142
107
  }
143
108
  /** GET /stats's learning counts from the one store, over the runs `filter` picks as the analytics pick them (not archived,
144
109
  * their own or their agent's; started in [from, to); of `agent`): an agentic run with a learning end counts, its end
145
110
  * read as the run's view reads it (runLearningEnd). A workflow's run, and one with no learning, is not counted; nor is
146
- * one whose reason this server does not give (an older server's). An imported run keeps no learning in the store. Each
147
- * agent's runs' records are read at once (agentRecordsOf; `records`, already read for `filter.agent`), never a read a run. */
111
+ * one whose reason this server does not give. An imported run keeps no learning in the store. Each agent's runs'
112
+ * records are read at once (agentRecordsOf; `records`, already read for `filter.agent`), never a read a run. */
148
113
  export async function learningCountsOverStore(store, filter, records) {
149
114
  const from = filter.from === undefined ? -Infinity : Date.parse(filter.from);
150
115
  const to = filter.to === undefined ? Infinity : Date.parse(filter.to);
@@ -183,7 +148,7 @@ export async function learningCountsOverStore(store, filter, records) {
183
148
  if (workflow.get(run.revisionId))
184
149
  continue;
185
150
  const learning = await runLearningEnd(store, run.id, undefined, await recordsOf(run.agentId));
186
- // A reason this server does not give (an older server's) is not counted.
151
+ // A reason this server does not give is not counted.
187
152
  if (!learning || (learning.reason !== null && !LEARNING_REASONS.includes(learning.reason)))
188
153
  continue;
189
154
  out.runs += 1;
@@ -197,27 +162,22 @@ export async function learningCountsOverStore(store, filter, records) {
197
162
  return out;
198
163
  }
199
164
  /** What learning spent outside any run (GET /usage's `learning` meter) in [from, to) (ms), one entry per run whose
200
- * learning ended then, as the learning ledger's lines gave it: its agent, when its learning ended, and what its grade
201
- * cost: 0 for a run never graded, null when the grade's spend is unknown (a grade that failed), never $0 then. One read
202
- * of the store (Learning.spend), whatever the number of runs. */
165
+ * learning ended then: its agent, when its learning ended, and what it spent outside the run. One read of the store
166
+ * (Learning.spend), whatever the number of runs. */
203
167
  export async function learningSpendOverStore(store, window) {
204
168
  return (await store.learning.spend(window)).map((one) => ({ agent: one.agentId, at: timeOf(one.at), cost: one.costUsd }));
205
169
  }
206
- /** An agent's learning counts as its learning view gives them (GET /agents/{id}/learning, learning-run.ts ofAgent's
207
- * counts): how its runs that tried to learn fared, less `runs`, from the one store. Its notes' runs and its impact are
208
- * agentLearningOverStore's. */
170
+ /** An agent's learning counts as its learning view gives them (GET /agents/{id}/learning): how its runs that tried to
171
+ * learn fared, less `runs`, from the one store. */
209
172
  export async function agentLearningCountsOverStore(store, agentId, records) {
210
173
  const { runs: _, ...counts } = await learningCountsOverStore(store, { agent: agentId }, records);
211
174
  return counts;
212
175
  }
213
- /** Agent `agentId`'s learning view from the one store (GET /agents/{id}/learning, learning-run.ts ofAgent): its counts
214
- * (agentLearningCountsOverStore), each note's runs given it and that read it (noteRuns over notesOf), and what learning
215
- * changed (learningImpact), never a run's files. Each run's part is read from its launch (the notes it was given,
216
- * learningStartOf), its journal once final (the notes its job read, notesReadOf) and its learning end (when its job
217
- * answered and what it and looking back cost, its grade's cost). `seed_notes`, the notes a run started from, is its
218
- * launch's seedNotes: every note in its seed, before the budget picked the given ones (main's seed_notes). Its runs'
219
- * launches and learning are read at once (agentRecordsOf), and a settled run's journal once a server (settledCache):
220
- * a read a run only the first time it is seen. */
176
+ /** Agent `agentId`'s learning view from the one store (GET /agents/{id}/learning): its counts (agentLearningCountsOverStore)
177
+ * and what learning changed (learningImpact), never a run's files. Each run's part is read from its launch (the
178
+ * corrections and workflows it started from), its journal (the workflows its claims laid) and its learning end (when its
179
+ * job answered and what it and looking back cost). Its runs' launches and learning are read at once (agentRecordsOf),
180
+ * and a settled run's journal once a server (settledCache). */
221
181
  export async function agentLearningOverStore(store, agentId) {
222
182
  const listed = (await store.runs.list({ agentId })).filter((run) => run.agentId === agentId);
223
183
  const records = await agentRecordsOf(store, agentId, listed);
@@ -225,7 +185,6 @@ export async function agentLearningOverStore(store, agentId) {
225
185
  const kinds = new Map();
226
186
  const rows = [];
227
187
  const learnings = new Map();
228
- const files = [];
229
188
  for (const run of listed) {
230
189
  if (!kinds.has(run.revisionId))
231
190
  kinds.set(run.revisionId, (await store.agents.revision(run.revisionId))?.kind);
@@ -233,30 +192,28 @@ export async function agentLearningOverStore(store, agentId) {
233
192
  const started = await learningStartOfRun(records, run.id);
234
193
  // A run that only uses what its agent learned keeps no proposal: its end is its start's (usedOnly), as its run reads give it.
235
194
  const end = (await runLearningEnd(store, run.id, undefined, records)) ?? (started?.use ? usedOnly(started, final, timeOf(run.endedAt ?? run.startedAt)) : null);
236
- const { read, laid } = await journalReadsOf(store, run, started);
237
- if (started || end)
238
- files.push(notesOf({ given: started?.given ?? [], read }));
239
195
  // The row learningImpact reads (the file path's RunRow): an ended run is a completed one.
240
196
  rows.push({
241
197
  id: run.id, kind: kinds.get(run.revisionId) === "workflow" ? "workflow" : "agentic", state: run.state === "ended" ? "completed" : run.state,
242
198
  startedAt: new Date(run.startedAt).toISOString(), endedAt: run.endedAt === null ? null : new Date(run.endedAt).toISOString(),
243
199
  costUsd: run.costUsd, importedFrom: run.importedFrom, archivedAt: run.archivedAt === null ? null : new Date(run.archivedAt).toISOString(),
244
200
  });
245
- // What its claims laid of the skills and workflows it was offered (every learningLaid entry, laidOf): the run started
246
- // from those alone.
201
+ // The workflows its claims laid of those it was offered (every learningLaid entry, laidOf): the run started from those alone.
202
+ const laid = end && started?.workflows?.length ? await journalLaidOf(store, run) : undefined;
247
203
  learnings.set(run.id, end ? impactLearningOf(end, started, laid, await roundsSpendOf(records, run.id), run.costUsd) : null);
248
204
  }
249
- return { counts, impact: learningImpact(rows, (row) => learnings.get(row.id) ?? null), notes: noteRuns(files) };
205
+ return { counts, impact: learningImpact(rows, (row) => learnings.get(row.id) ?? null) };
250
206
  }
251
207
  /** Agent `agentId`'s cost per run from the one store (GET /agents/{id}/learning/cost, learning-cost.ts): each of its
252
- * agentic runs that ended (ended, stopped or failed), oldest first, numbered from 1, with its own cost and what learning
253
- * added for it (runCostOf over its row's cost and its learning's spend, learningSpendOf), the path it took and the learned workflow it ran
254
- * (its run record's, pathOfRow), and the learned revision it started from (its launch's seed); and what the series shows
255
- * (costSummary). A run still at work, an imported or archived one and a workflow revision's run are left out; a learning
256
- * run (a run's grade and merge) is no run of the list (the store lists none: NOT_A_LEARNING_RUN), and its cost is its
257
- * run's learning. A run that learns whose record names no path (its end's patch was late or failed, or no runner wrote
258
- * its end) is left out too and counted (`unknown_path_runs`): its path and cost are not known, never `agent` at $0.
259
- * `limit`: the latest runs shown, each keeping its number; the summary is over every run. */
208
+ * agentic runs that ended (ended, stopped or failed), oldest first, each run that does a job numbered from 1 (a replay
209
+ * none: the bill's numbering), with its own cost and what learning added for it (runCostOf over its row's cost and its
210
+ * learning's spend, learningSpendOf), the path it took and the learned workflow it ran (its run record's, pathOfRow), the
211
+ * revision of that workflow (metrics.workflow_digest) and whether an audit's shadow ran for it; and what
212
+ * the series shows (costSummary). A run still at work, an imported or archived one and a workflow revision's run are left
213
+ * out. A run that learns whose record names no path (its end's patch was late or failed, or no runner wrote its end) is
214
+ * left out too and counted (`unknown_path_runs`): its path and cost are not known, never `agent` at $0. `limit`: the
215
+ * latest runs shown, each keeping its number; the summary is over every run; `bill` is the owner's bill over all of
216
+ * them (billOf, with the revision ledger: agentLedgerOf). */
260
217
  export async function agentCostOverStore(store, agentId, limit = Infinity) {
261
218
  const kinds = new Map();
262
219
  const listed = (await store.runs.list({ agentId })).filter((run) => run.agentId === agentId);
@@ -264,26 +221,168 @@ export async function agentCostOverStore(store, agentId, limit = Infinity) {
264
221
  const records = await agentRecordsOf(store, agentId, listed);
265
222
  // An audit's shadow run is no run of the series: its cost is its served run's learning (allInOf).
266
223
  const ended = listed.filter((run) => FINAL_STATES.includes(run.state) && !run.importedFrom && run.archivedAt === null && !isShadowRun(run.id)).sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : 1));
267
- const runs = [];
224
+ const rows = [];
268
225
  let unknownPath = 0;
226
+ // One numbering, the bill's: the runs that do a job, 1 the first; a replay checks a revision and has none.
227
+ let jobs = 0;
269
228
  for (const run of ended) {
270
229
  if (!kinds.has(run.revisionId))
271
230
  kinds.set(run.revisionId, (await store.agents.revision(run.revisionId))?.kind);
272
231
  if (kinds.get(run.revisionId) === "workflow")
273
232
  continue;
274
233
  // A run that learns whose record names no path is left out and counted, never `agent` at $0.
275
- if (!pathOfRow(run.metrics, await learningStartOfRun(records, run.id))) {
234
+ const placed = pathOfRow(run.metrics, await learningStartOfRun(records, run.id));
235
+ if (!placed) {
276
236
  unknownPath += 1;
277
237
  continue;
278
238
  }
279
- runs.push(await costRunOf(records, run, runs.length + 1));
239
+ rows.push(await costRunOf(records, run, JOB_PATHS.includes(placed.path) ? (jobs += 1) : null));
280
240
  }
241
+ // Where each revision took over, over every run before the limit cuts the read (the first is the summary's takeover).
242
+ const runs = tookOverOf(rows);
281
243
  // Each learned workflow that ran first, where it stands against the money rule (workflow-first.ts workflowCostsOf), over
282
244
  // the runs the run's launch reads (pastRunsOverStore) at the all-in cost this series shows: a workflow over the line
283
245
  // shows `needs_revision` with its two numbers, so the page and the launch's decision agree.
284
246
  const workflows = workflowCostsOf(await pastRunsOverStore(store, agentId, new Map(runs.map((run) => [run.run_id, run.total_usd])), records));
285
- const replay = servingReplayOf(await promotionsOf(store.settings, agentId), runs);
286
- return { runs: runs.slice(Math.max(0, runs.length - limit)), summary: costSummary(runs, replay), total_runs: runs.length, unknown_cost_runs: runs.filter((run) => run.total_usd === null).length, unknown_path_runs: unknownPath, workflows };
247
+ const promotions = await promotionsOf(store.settings, agentId);
248
+ const replay = servingReplayOf(promotions, runs);
249
+ // The owner's bill: booked $, every run of the series (billOf), from the series' first run on a served path (the
250
+ // summary's takeover: read from the run rows by their place, as the promotion feed is trimmed and its oldest record need
251
+ // not be the first promotion), and each revision's compile and check over the served runs that carry it.
252
+ const ledger = await agentLedgerOf(records, promotions, listed);
253
+ const booked = billOf(runs);
254
+ // What no run carries is the booked total less every run's all-in (A8), so a revision whose records aged out of the
255
+ // feed lands here, never nowhere: unknown while any run's figures are.
256
+ let carried = 0;
257
+ for (const run of runs) {
258
+ const all = run.path === "replay" ? 0 : run.cost_upper_bound ? null : allInV2Of(run, ledger.compiles.get(run.run_id) ?? [], ledger.shares);
259
+ carried = carried === null || all === null ? null : noiseOff(carried + all);
260
+ }
261
+ const unattributed = booked.withheld > 0 || carried === null ? null : noiseOff(booked.booked_usd - carried);
262
+ const bill = { ...booked, revisions: ledger.revisions, unattributed_usd: unattributed, holds: holdsOf(promotions, runs) };
263
+ return { runs: runs.slice(Math.max(0, runs.length - limit)), summary: costSummary(runs, replay), total_runs: runs.length, unknown_cost_runs: runs.filter((run) => run.total_usd === null).length, unknown_path_runs: unknownPath, workflows, bill };
264
+ }
265
+ /** Each hold of the agent's learned workflows (its promotion records that say hold), placed on the series: at the first
266
+ * run that does a job from it on, by its number among them (the points' `n`), null when none has run since. */
267
+ function holdsOf(records, runs) {
268
+ const jobs = runs.filter((run) => JOB_PATHS.includes(run.path));
269
+ return records.filter((one) => one.decided === "hold").map((one) => {
270
+ const at = jobs.findIndex((run) => run.started_at >= one.at);
271
+ return { n: at < 0 ? null : at + 1, at: one.at, workflow: one.workflow, by: one.audit ? "audit" : one.check ? "check" : "dsl", reason: one.reason };
272
+ });
273
+ }
274
+ const metricOf = (row) => (row.metrics ?? {});
275
+ /** The revision a run ran (metrics.workflow and metrics.workflow_digest, workflow-first.ts pathMetrics), undefined when it
276
+ * names none: two workflows of the same text share a digest, so a revision is never its digest alone. */
277
+ const revisionOfRow = (row) => {
278
+ const { workflow, workflow_digest: digest } = metricOf(row);
279
+ return typeof workflow === "string" && typeof digest === "string" ? { workflow, digest } : undefined;
280
+ };
281
+ /** The compile turns run `runId`'s rounds asked, oldest first: none for a run that compiled nothing (a round whose step
282
+ * asked no model turn keeps `look_back_usd` 0, or none at all). */
283
+ async function compilesOf(store, runId) {
284
+ return (await roundsOf(store, runId)).flatMap((kept) => {
285
+ const row = (kept.proposal ?? {});
286
+ const { compiled, draft_errors } = compiledOf(row);
287
+ const usd = "look_back_usd" in row ? usdOrNull(row.look_back_usd) : 0;
288
+ // A compile turn that kept no draft (the cap stopped it, or a stop, a fault or an unreadable refuse list ended the step
289
+ // after an earlier claim asked it: runner/reflect-hook.ts `unasked`) spent with no revision to serve: its spend is
290
+ // unattributed, never its run's.
291
+ if (!compiled)
292
+ return usd === 0 ? [] : [{ workflow: null, digest: null, usd }];
293
+ return [{ workflow: compiled.workflow, digest: compiled.digest && !draft_errors?.length ? compiled.digest : null, usd }];
294
+ });
295
+ }
296
+ /** A run's v2 learning (A8): what learning cost for it as the cost series counts it (its compile turns, any follow-up
297
+ * round's turns and its audit shadow: `run.learning_usd`) less its compile turns (each its revision's), with its share of
298
+ * its revision's compile and check (`shares`: a missing entry is none, an unknown share stays unknown). Null while any
299
+ * part is unknown. */
300
+ function learningV2Of(run, compiles, shares) {
301
+ const compiled = compiles.reduce((sum, one) => (sum === null || one.usd === null ? null : sum + one.usd), 0);
302
+ const share = shares.has(run.run_id) ? shares.get(run.run_id) : 0;
303
+ if (run.learning_usd === null || compiled === null || share === null)
304
+ return null;
305
+ return noiseOff(Math.max(0, run.learning_usd - compiled) + share);
306
+ }
307
+ /** A run's v2 all-in: its own $ (the job's) and its v2 learning (learningV2Of); null when either is. */
308
+ function allInV2Of(run, compiles, shares) {
309
+ const learning = learningV2Of(run, compiles, shares);
310
+ return learning === null || run.cost_usd === null ? null : noiseOff(run.cost_usd + learning);
311
+ }
312
+ /** The agent's revision ledger (revisionLedgerOf) over `listed` (its runs, as runs.list read them): its ended runs that do
313
+ * a job or check one (no shadow, no imported or archived run), and the compile turns their rounds asked, by run. */
314
+ async function agentLedgerOf(records, promotions, listed) {
315
+ const rows = listed.filter((one) => FINAL_STATES.includes(one.state) && !one.importedFrom && one.archivedAt === null && !isShadowRun(one.id));
316
+ const compiles = new Map();
317
+ for (const row of rows) {
318
+ const asked = await compilesOf(records, row.id);
319
+ if (asked.length)
320
+ compiles.set(row.id, asked);
321
+ }
322
+ return { ...revisionLedgerOf(promotions, rows, [...compiles.values()].flat()), compiles };
323
+ }
324
+ /** Each revision of the agent's learned workflows (one per workflow and digest its promotion records name, in the order
325
+ * they were first recorded) with its learning spend, and what its served runs carry of it (amortize), over `rows`: the
326
+ * agent's ended runs that do a job or check one (no shadow, no imported or archived run). A revision is its workflow and
327
+ * its digest, never the digest alone: two workflows of the same text share a digest, and each pays its own way. Its
328
+ * spend is the compile turns that drafted it (`compiles` of its workflow at its digest: a recompile drafts a revision of
329
+ * its own) and its check (the replay runs that ran it: metrics.path `replay` of its workflow at its digest); unknown
330
+ * once a part's cost is (null, or only a bound). A compile whose drafts all failed drafted none: no revision carries it
331
+ * (the bill's unattributed does). It is spread over its first K served runs (`workflow` or `handed_back` of its workflow
332
+ * at its digest), K its check's compile_after; `state` from its newest record. */
333
+ export function revisionLedgerOf(records, rows, compiles = []) {
334
+ const ordered = [...rows].sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : 1));
335
+ const newest = new Map();
336
+ for (const record of records)
337
+ newest.set(`${record.workflow}\0${record.digest}`, record);
338
+ const sum = (parts) => (parts.some((one) => one === null) ? null : noiseOff(parts.reduce((total, one) => total + one, 0)));
339
+ const ran = (row, record) => { const at = revisionOfRow(row); return at?.workflow === record.workflow && at.digest === record.digest; };
340
+ const revisions = [...newest.values()].map((record) => {
341
+ const replays = ordered.filter((row) => metricOf(row).path === "replay" && ran(row, record));
342
+ const check = sum(replays.map((row) => (typeof row.costAtMostUsd === "number" ? null : row.costUsd)));
343
+ const compile = sum(compiles.filter((one) => one.workflow === record.workflow && one.digest === record.digest).map((one) => one.usd));
344
+ const state = record.decided === "replaying" ? "checking" : championOf(records, record.workflow)?.digest === record.digest ? "serving" : "stopped";
345
+ return { workflow: record.workflow, digest: record.digest, compile_usd: compile, check_usd: check, spend_usd: sum([compile, check]), k: record.check?.compile_after ?? COMPILE_AFTER_DEFAULT, state };
346
+ });
347
+ const served = ordered.flatMap((row) => {
348
+ const at = revisionOfRow(row);
349
+ return SERVED_PATHS.includes(metricOf(row).path) && at ? [{ run_id: row.id, ...at }] : [];
350
+ });
351
+ return amortize(revisions, served);
352
+ }
353
+ /** Run `runId`'s path and its costs as GET /runs/{id} shows them (A8): `path` its record's (metrics.path, RUN_PATHS:
354
+ * `agent` for a run that does not learn; null while it has not ended, for a workflow revision's run, and for a run that
355
+ * learns whose end named none); `usd` its own spend, the job's (runCostOf's `cost_usd`: its row's cost, `rowUsd` when
356
+ * given, less its compile turns; null while unknown); `learning_usd` what learning spent for it: its follow-up rounds'
357
+ * turns (learningSpendOf less its compile turns, each its revision's), its audit shadow's cost, and its share of its
358
+ * revision's compile and check (revisionLedgerOf); `all_in_usd` the two. A replay or a shadow run carries none: its
359
+ * spend is on the runs it serves, so its `learning_usd` and `all_in_usd` are 0, and the sum of every run's `all_in_usd`
360
+ * and the bill's `unattributed_usd` is the booked total. While the run is at work `usd` is `rowUsd` and the rest null;
361
+ * null while unknown (its shadow still at work, a compile's or a check's cost unknown), never $0. Undefined for an
362
+ * unknown run. */
363
+ export async function runAllInOverStore(store, runId, rowUsd) {
364
+ const run = await store.runs.get(runId);
365
+ if (!run)
366
+ return undefined;
367
+ const row = rowUsd === undefined ? (typeof run.costAtMostUsd === "number" ? null : run.costUsd) : rowUsd;
368
+ const ended = FINAL_STATES.includes(run.state);
369
+ const kind = (await store.agents.revision(run.revisionId))?.kind;
370
+ const started = kind === "workflow" ? undefined : await learningStartOfRun(store, run.id).catch(() => undefined);
371
+ const path = !ended || kind === "workflow" ? null : (pathOfRow(run.metrics, started)?.path ?? null);
372
+ if (!ended)
373
+ return { path, usd: row, learning_usd: null, all_in_usd: null };
374
+ const cost = runCostOf(row, await learningSpendOf(store, run.id, row), (await shadowSpendOf(store, run.id)).usd);
375
+ if (path === "replay" || path === "audit" || isShadowRun(run.id))
376
+ return { path, usd: cost.cost_usd, learning_usd: 0, all_in_usd: 0 };
377
+ // Its share of its revision's compile and check: a served run's, over the agent's ledger.
378
+ let shares = new Map();
379
+ if (path !== null && SERVED_PATHS.includes(path) && revisionOfRow(run)) {
380
+ const listed = (await store.runs.list({ agentId: run.agentId })).filter((one) => one.agentId === run.agentId);
381
+ shares = (await agentLedgerOf(await agentRecordsOf(store, run.agentId, listed), await promotionsOf(store.settings, run.agentId), listed)).shares;
382
+ }
383
+ const figures = { run_id: run.id, ...cost };
384
+ const compiles = await compilesOf(store, run.id);
385
+ return { path, usd: cost.cost_usd, learning_usd: learningV2Of(figures, compiles, shares), all_in_usd: allInV2Of(figures, compiles, shares) };
287
386
  }
288
387
  /** The check the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
289
388
  * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's check numbers
@@ -299,19 +398,16 @@ export function servingReplayOf(records, runs) {
299
398
  return { n: check.n, workflow_pct: Math.round(checkShares({ n: check.n, agreed, alone }).agreement * 1000) / 10, agent_pct: 100, cleared: true, agreed, alone, agree_min: check.agree_min };
300
399
  }
301
400
  /** What run `runId`'s learning spent, as its cost per run counts it, over every round a follow-up opened (roundsOf): what
302
- * it kept as it answered (`looked`: answeredOf), and its grades' spend (`grade`): each round's learning run's cost once
303
- * that run ended, stopped or failed (runner/learning-loop.ts keeps the grade's spend there, a paid grade a person stopped
304
- * included; null when one is unknown), 0 while it runs or when the round queued none. A run a follow-up opened again
305
- * (roundsSpendOf's figures): its job is what it had cost when its first round answered, and everything after (each
306
- * later round's follow-up turn and every round's look-back: feedback the run was given is learning, never the job) is
307
- * its look-back here, `rowUsd` (the run's row cost) less that job (roundsLooked). */
401
+ * it kept as it answered (answeredOf). A run a follow-up opened again (roundsSpendOf's figures): its job is what it had
402
+ * cost when its first round answered, and everything after (each later round's follow-up turn and every round's
403
+ * look-back: feedback the run was given is learning, never the job) is its look-back here, `rowUsd` (the run's row cost)
404
+ * less that job (roundsLooked). */
308
405
  export async function learningSpendOf(store, runId, rowUsd) {
309
406
  const rounds = await roundsOf(store, runId);
310
407
  if (!rounds.length)
311
- return { looked: null, grade: 0 };
312
- const spent = await roundsSpentOf(store, rounds);
313
- const more = roundsSpendIn(rounds, spent);
314
- return { looked: more ? roundsLooked(more, rowUsd) : answeredOf((rounds.at(-1).proposal ?? {})), grade: spent.grade };
408
+ return null;
409
+ const more = roundsSpendIn(rounds, roundsSpentOf(rounds));
410
+ return more ? roundsLooked(more, rowUsd) : answeredOf((rounds.at(-1).proposal ?? {}));
315
411
  }
316
412
  /** Every round run `runId` kept (one a follow-up opened again is a round past its first), oldest first: none when it kept
317
413
  * no learning. The store's proposal(runId) is the newest round alone; a read of what the run's learning did or spent
@@ -329,35 +425,27 @@ export async function roundsOf(store, runId) {
329
425
  out.push(newest);
330
426
  return out;
331
427
  }
332
- /** Over a run's rounds (roundsOf): the first round that answered (its job's own figures), every round's look-back added
333
- * up and every round's grade (each null once one round's is unknown). */
334
- async function roundsSpentOf(store, rounds) {
428
+ /** Over a run's rounds (roundsOf): the first round that answered (its job's own figures) and every round's look-back
429
+ * added up (null once one round's is unknown). */
430
+ function roundsSpentOf(rounds) {
335
431
  let first;
336
432
  let look = 0;
337
- let grade = 0;
338
433
  for (const kept of rounds) {
339
434
  const answered = answeredOf((kept.proposal ?? {}));
340
435
  if (!first && answered.answered_at !== undefined)
341
436
  first = answered;
342
437
  // A round that never looked back (no figures kept) added none.
343
438
  look = look === null || answered.look_back_usd === null ? null : look + (answered.look_back_usd ?? 0);
344
- const learningRun = kept.learningRunId ? await store.runs.get(kept.learningRunId) : undefined;
345
- const spent = learningRun && FINAL_STATES.includes(learningRun.state) ? (learningRun.costUsd ?? null) : 0;
346
- grade = grade === null || spent === null ? null : grade + spent;
347
439
  }
348
- return { first, look, grade };
440
+ return { first, look };
349
441
  }
350
- /** A run's own cost and what learning added for it (runCostOf): its row's cost, every round of its learning (a run a
351
- * follow-up opened again, a review's or a person's, learned in rounds: every round's look-back and grade, roundsSpendOf,
352
- * never the newest round's alone), else its one round's (learningSpendOf). `total_usd` is the run's all-in cost, the one
353
- * the cost page shows and the money rule reads (pastRunsOverStore); null when any part is unknown. */
442
+ /** A run's own cost and what learning added for it (runCostOf): its row's cost, every round of its learning
443
+ * (learningSpendOf) and its audit's shadow run (shadowSpendOf). `total_usd` is the run's all-in cost, the one the cost page shows and the money rule reads
444
+ * (pastRunsOverStore); null when any part is unknown. */
354
445
  export async function allInOf(store, run) {
355
- // Every round's (learningSpendOf over the rounds: what its row spent after its job answered is learning, roundsLooked).
356
- const { looked, grade } = await learningSpendOf(store, run.id, run.costUsd);
357
446
  // An audit's shadow run of it (runner/audit.ts) is its learning too (shadowSpendOf): unknown while it is queued or
358
447
  // running, never $0.
359
- const audited = (await shadowSpendOf(store, run.id)).usd;
360
- return runCostOf(run.costUsd, looked, grade === null || audited === null ? null : grade + audited);
448
+ return runCostOf(run.costUsd, await learningSpendOf(store, run.id, run.costUsd), (await shadowSpendOf(store, run.id)).usd);
361
449
  }
362
450
  /** What run `runId`'s audit shadow run (runner/audit.ts) adds to its all-in cost: `open` while it is queued or running
363
451
  * (its cost not known yet: `usd` null, never $0), else its cost once it ended, stopped or failed (null: unknown); 0 when
@@ -370,16 +458,20 @@ export async function shadowSpendOf(store, runId) {
370
458
  return { open: false, usd: 0 };
371
459
  return FINAL_STATES.includes(shadow.state) ? { open: false, usd: shadow.costUsd ?? null } : { open: true, usd: null };
372
460
  }
373
- /** One run of the cost series, as number `n` of it: its figures (allInOf) and its path (agentCostOverStore's loop body,
374
- * and a learning batch's row once the run's learning has settled). */
461
+ /** One run of the cost series, as number `n` of it (null for a replay): its figures (allInOf), its path, the workflow
462
+ * revision that ran it and whether an audit's shadow ran for it (agentCostOverStore's loop body); `took_over` is the
463
+ * series' (tookOverOf). */
375
464
  export async function costRunOf(store, run, n) {
376
465
  const started = await learningStartOfRun(store, run.id);
377
- // Its figures are what the batch reads: a run with no path named is placed as the agent's here, and left out by the series.
466
+ // A run with no path named is placed as the agent's here, and left out by the series.
378
467
  const { path, workflow } = pathOfRow(run.metrics, started) ?? { path: "agent", workflow: null };
379
468
  const { cost_usd, learning_usd, total_usd } = await allInOf(store, run);
380
469
  // The run row's stored bound (RunRow.costAtMostUsd, written with a null cost_usd): its cost counts a request cut at what its cap held.
381
470
  const cost_upper_bound = typeof run.costAtMostUsd === "number";
382
- return { n, run_id: run.id, started_at: new Date(run.startedAt).toISOString(), path, workflow, learned_revision: started?.seed ?? null, cost_usd, cost_upper_bound, learning_usd, total_usd };
471
+ // The revision its metrics name (pathMetrics): the bill's revisions are read the same way, offered or not.
472
+ const digest = path === "agent" ? null : revisionOfRow(run)?.digest ?? null;
473
+ const audited = (await store.runs.get(shadowRunId(run.id))) !== undefined;
474
+ return { n, run_id: run.id, started_at: new Date(run.startedAt).toISOString(), path, workflow, digest, audited, cost_usd, cost_upper_bound, learning_usd, total_usd };
383
475
  }
384
476
  /** The runs the money rule reads for agent `agentId` (runner/workflow-first.ts costLineOf), one set for the run's launch
385
477
  * and the cost page: of its newest PAST_RUNS runs, each that ended (ended, stopped or failed), is neither imported nor
@@ -388,7 +480,20 @@ export async function costRunOf(store, run, n) {
388
480
  export async function pastRunsOverStore(store, agentId, known, records = store) {
389
481
  const kinds = new Map();
390
482
  const kept = [];
391
- for (const run of await store.runs.list({ agentId, limit: PAST_RUNS })) {
483
+ const page = await store.runs.list({ agentId, limit: PAST_RUNS });
484
+ // Each run's audit shadow is read off the page (allInOf's shadowSpendOf): a shadow starts after the run it audits ends,
485
+ // so it is newer than that run and on the same page of the newest runs; one not on it was never started.
486
+ const shadows = new Map(page.filter((run) => isShadowRun(run.id)).map((run) => [run.id, run]));
487
+ const learningStart = records.runs.learningStart;
488
+ const paged = {
489
+ learning: records.learning,
490
+ runs: {
491
+ launch: (id) => records.runs.launch(id),
492
+ get: (id) => (isShadowRun(id) ? Promise.resolve(shadows.get(id)) : records.runs.get(id)),
493
+ ...(learningStart ? { learningStart: (id) => learningStart.call(records.runs, id) } : {}),
494
+ },
495
+ };
496
+ for (const run of page) {
392
497
  if (run.agentId !== agentId || !FINAL_STATES.includes(run.state) || run.importedFrom || run.archivedAt !== null || isShadowRun(run.id))
393
498
  continue;
394
499
  if (!kinds.has(run.revisionId))
@@ -399,10 +504,14 @@ export async function pastRunsOverStore(store, agentId, known, records = store)
399
504
  // A few reads a run, a batch at a time: a launch reads up to PAST_RUNS of them.
400
505
  const past = [];
401
506
  for (let at = 0; at < kept.length; at += 16) {
402
- past.push(...(await Promise.all(kept.slice(at, at + 16).map(async (run) => ({ metrics: run.metrics, startedAt: run.startedAt, allInUsd: known?.has(run.id) ? known.get(run.id) : (await allInOf(records, run)).total_usd })))));
507
+ past.push(...(await Promise.all(kept.slice(at, at + 16).map(async (run) => ({ metrics: run.metrics, startedAt: run.startedAt, allInUsd: known?.has(run.id) ? known.get(run.id) : (await allInOf(paged, run)).total_usd })))));
403
508
  }
404
509
  return past;
405
510
  }
511
+ /** The money rule's decision for agent `agentId` (runner/workflow-first.ts costStopOf) over the runs a run's launch reads
512
+ * (pastRunsOverStore), as the launch reads them: runs that can't be read now stop nothing (workflowFirstOf serves). What
513
+ * the promotions read and the learning view fold into each workflow's state (learn/promote.ts servingStateOf). */
514
+ export const costStopOverStore = async (store, agentId) => costStopOf(await pastRunsOverStore(store, agentId).catch(() => []));
406
515
  /** The path run `runId` took and the learned workflow it ran, the one classifier its run record keeps (metrics.path,
407
516
  * metrics.workflow, metrics.workflow_digest: workflow-first.ts pathMetrics, written at the run's end) and its cost per run
408
517
  * reads (pathOfRow). A run its learned workflow served first (its WORKFLOW_FIRST entry, servedOf): `workflow` when it
@@ -444,27 +553,18 @@ function pathOfRow(metrics, started) {
444
553
  const path = named ? m.path : "agent";
445
554
  return { path, workflow: path === "agent" || typeof m.workflow !== "string" ? null : offeredName(m.workflow, started?.workflows) };
446
555
  }
447
- /** What a run's journal tells the agent's learning view: the notes its job opened (`read`, once final) and what its
448
- * claims laid of the skills and workflows it was offered (`laid`). Read once for a settled run and kept by its epoch
449
- * (settledJournalReads), else read now. */
450
- async function journalReadsOf(store, run, started) {
451
- const final = FINAL_STATES.includes(run.state);
452
- const offered = !!(started?.skills?.length || started?.workflows?.length);
453
- const journal = async () => {
454
- const rows = final && started?.given.length ? await runTimeline(store, run.id, BACKGROUND_CONTEXT, { settled: final }) : [];
455
- const entries = offered ? await runEntries(store, run.id, BACKGROUND_CONTEXT) : [];
456
- return {
457
- read: final && started?.given.length ? notesReadOf(started.given, await runReflect(store, run.id, BACKGROUND_CONTEXT), rows) : [],
458
- laid: offered ? laidOf(entries) : undefined,
459
- };
460
- };
461
- return final ? settledJournalReads(store, run.id, run.epoch, journal) : journal();
556
+ /** What a run's claims laid of the workflows it was offered (laidOf over its journal): read once for a settled run and kept
557
+ * by its epoch (settledLaid), else read now. */
558
+ async function journalLaidOf(store, run) {
559
+ const read = async () => laidOf(await runEntries(store, run.id, BACKGROUND_CONTEXT));
560
+ return FINAL_STATES.includes(run.state) ? settledLaid(store, run.id, run.epoch, read) : read();
462
561
  }
463
562
  /** `name` when it is one of the learned workflows the run's launch offered, else null. */
464
563
  const offeredName = (name, offered) => (name !== null && offered?.includes(name) ? name : null);
465
564
  const SETTLED_READS_MAX = 4096;
466
- /** A cache of what a settled run's journal says, by store and run id with the run's epoch (see above), at most
467
- * SETTLED_READS_MAX runs a store, the oldest read dropped first. A read in flight is kept too, so two reads of the
565
+ /** A cache of what a settled run's journal says, by store and run id with the run's epoch: a claim and a run's end each
566
+ * move the epoch, and only a claim writes to its journal, so a settled run's reads hold until the next claim of it. At
567
+ * most SETTLED_READS_MAX runs a store, the oldest read dropped first. A read in flight is kept too, so two reads of the
468
568
  * agent at once (its page and its tab) walk a run's journal once; one that fails is dropped, for the next to read. */
469
569
  function settledCache() {
470
570
  const byStore = new WeakMap();
@@ -485,35 +585,19 @@ function settledCache() {
485
585
  return value;
486
586
  };
487
587
  }
488
- const settledJournalReads = settledCache();
489
- const settledLearningEnds = settledCache();
490
- /** Learning run `id`'s end entries (`run`: its row): read once it is final and kept (settledCache), so an agent's
491
- * learning view reads each of its learning runs' journals once, not at every read; read now while it runs. */
492
- async function learningEndEntries(store, id, run) {
493
- const read = async () => {
494
- const entries = await journalEntries(store.readJournal(id), BACKGROUND_CONTEXT);
495
- const dataOf = (kind) => entries.find((entry) => entry.kind === kind)?.data;
496
- return { merged: dataOf(KINDS.learningMerged), dropped: dataOf(KINDS.learningDropped), graded: dataOf(KINDS.learningGraded) };
497
- };
498
- return run && FINAL_STATES.includes(run.state) ? settledLearningEnds(store, id, run.epoch, read) : read();
499
- }
500
- /** What every claim of a run laid, from its learningLaid entries, each name once: a resumed claim finds an earlier
501
- * claim's skill folders there already and lays none of them again, though the run still has them. None laid when it has
502
- * no entry. */
588
+ const settledLaid = settledCache();
589
+ /** What every claim of a run laid, from its learningLaid entries, each name once. None laid when it has no entry. */
503
590
  export function laidOf(entries) {
504
- const names = (list) => (Array.isArray(list) ? list.filter((name) => typeof name === "string") : []);
505
- const skills = new Set();
506
591
  const workflows = new Set();
507
592
  for (const entry of entries) {
508
593
  if (entry.kind !== KINDS.learningLaid)
509
594
  continue;
510
- const data = (entry.data ?? {});
511
- for (const name of names(data.skills))
512
- skills.add(name);
513
- for (const name of names(data.workflows))
514
- workflows.add(name);
595
+ const list = (entry.data ?? {}).workflows;
596
+ for (const name of Array.isArray(list) ? list : [])
597
+ if (typeof name === "string")
598
+ workflows.add(name);
515
599
  }
516
- return { skills: [...skills], workflows: [...workflows] };
600
+ return { workflows: [...workflows] };
517
601
  }
518
602
  /** What a run with rounds (`rounds`) kept as it answered, as its cost per run and its impact both read it: its job is
519
603
  * what it had cost when its first round answered; everything its row (`rowUsd`) spent after that (each later round's
@@ -527,40 +611,29 @@ export function roundsLooked(rounds, rowUsd) {
527
611
  }
528
612
  export async function roundsSpendOf(store, runId) {
529
613
  const rounds = await roundsOf(store, runId);
530
- return rounds.length < 2 ? undefined : roundsSpendIn(rounds, await roundsSpentOf(store, rounds));
614
+ return rounds.length < 2 ? undefined : roundsSpendIn(rounds, roundsSpentOf(rounds));
531
615
  }
532
616
  /** The one reader of a run's rounds' spend (roundsSpendOf, learningSpendOf): undefined for fewer than two rounds, or when
533
617
  * the first one's answer time is unknown. */
534
- const roundsSpendIn = (rounds, { first, look, grade }) => rounds.length > 1 && first && typeof first.answered_at === "string" ? { answered_at: first.answered_at, job_cost_usd: first.job_cost_usd ?? null, look_back_usd: look, grade_usd: grade } : undefined;
535
- /** What a run's learning end tells its impact, as ofAgent's learningOf read a held run: how it ended and when, the notes
536
- * it started from; when its job answered and its costs once it looked back (a look-back of 0 for an ended one that did
537
- * not); its grade's cost once it ended (0 when nothing was graded). */
618
+ const roundsSpendIn = (rounds, { first, look }) => rounds.length > 1 && first && typeof first.answered_at === "string" ? { answered_at: first.answered_at, job_cost_usd: first.job_cost_usd ?? null, look_back_usd: look } : undefined;
619
+ /** What a run's learning end tells its impact: how it ended and when, the corrections and workflows it started from, when
620
+ * its job answered and its costs once it looked back (a look-back of 0 for an ended one that did not). */
538
621
  export function impactLearningOf(end, started, laid, rounds, rowUsd = null) {
539
622
  const over = end.state === "merged" || end.state === "dropped";
540
623
  // A run a follow-up opened again: its job answered at its first round's end, and all its row spent after (every later
541
- // round's follow-up turn and look-back) and every round's grade are its learning, as its cost per run reads them
542
- // (roundsLooked; the newest round's `job_cost_usd` also holds the earlier rounds' look-backs, never the job's own).
624
+ // round's follow-up turn and look-back) is its learning, as its cost per run reads it (roundsLooked).
543
625
  const looked = rounds ? roundsLooked(rounds, rowUsd) : end.answered_at !== undefined ? { answered_at: end.answered_at, job_cost_usd: end.job_cost_usd ?? null, look_back_usd: end.look_back_usd ?? null } : over ? { look_back_usd: 0 } : {};
626
+ const corrections = started ? correctionCount(started.section) : 0;
544
627
  return {
545
- state: end.state, reason: end.reason, at: end.at, ...(started?.seedNotes !== undefined ? { seed_notes: started.seedNotes } : {}),
546
- ...(laid?.skills.length ? { seed_skills: laid.skills.length } : {}), ...(laid?.workflows.length ? { seed_workflows: laid.workflows.length } : {}), ...looked,
547
- ...(over ? { grade_usd: rounds ? rounds.grade_usd : end.cost_usd ? end.cost_usd.grade : 0 } : {}),
628
+ state: end.state, reason: end.reason, at: end.at,
629
+ ...(corrections ? { seed_corrections: corrections } : {}), ...(laid?.workflows.length ? { seed_workflows: laid.workflows.length } : {}), ...looked,
548
630
  };
549
631
  }
550
- /** The notes a run's job read (learning-run.ts noteRead's rule, over the runner's journal rows): its own successful
551
- * `read` calls on a file of its copy of the folder, the end-of-run turn's (`reflect`) left out, keyed on the notes it was
552
- * `given` and named as given. A file it was not given (MEMORY.md, one it wrote, one not in its seed) is not one of them. */
553
- export function notesReadOf(given, reflect, rows) {
554
- if (!given?.length)
555
- return [];
556
- const names = new Map(given.map((note) => [note.file, note.name]));
557
- return notesRead(reflect, rows).flatMap((file) => (names.has(file) ? [{ file, name: names.get(file) }] : []));
558
- }
559
632
  /** learned_workflow by every name a harness calls it (runner/learning-end.ts LEARNED_NAMES). */
560
633
  const WORKFLOW_CALLS = new Set(["learned_workflow", "mcp__hands__learned_workflow"]);
561
634
  /** Each tool call of a run's journal, by its call's id: its tool and the arguments it was called with, as recorded (pi's
562
635
  * call in its assistant entry, a CLI harness's in its record's call start). A timeline row's input preview is cut and
563
- * for some tools absent, so what a call read or ran is read from these. */
636
+ * for some tools absent, so what a call ran is read from these. */
564
637
  export function callArgsOf(entries) {
565
638
  const out = new Map();
566
639
  const argsOf = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : {});
@@ -579,108 +652,29 @@ export function callArgsOf(entries) {
579
652
  }
580
653
  return out;
581
654
  }
582
- /** The plugin claude-agent serves a run's skills from (@parcha/agentrun-harness-claude CLAUDE_AGENT_SKILLS_PLUGIN): the
583
- * model loads each as `agentrun:<name>`, or by its bare name. */
584
- const CLAUDE_SKILLS_PLUGIN = "agentrun";
585
- /** The id ranges of a run's end-of-run turns, each from its prompt (an endOfRunTurn entry, `role: "person"`) to its
586
- * answer (`role: "model"`); one with no answer runs to the person's next message (a reopened run's follow-up), else to
587
- * the end. A reopened run has one per time it looked back. */
588
- function endOfRunTurns(entries) {
589
- const turns = [];
590
- let open;
591
- for (const entry of [...entries].filter((one) => one.id !== undefined).sort((a, b) => a.id - b.id)) {
592
- const role = entry.data?.role;
593
- if (entry.kind === KINDS.endOfRunTurn && role === "person")
594
- open ??= entry.id;
595
- else if (open !== undefined && ((entry.kind === KINDS.endOfRunTurn && role === "model") || (entry.kind === KINDS.message && role === "person"))) {
596
- turns.push([open, entry.id]);
597
- open = undefined;
598
- }
599
- }
600
- if (open !== undefined)
601
- turns.push([open, Number.POSITIVE_INFINITY]);
602
- return turns;
603
- }
604
- /** The skills a run's job loaded with a harness's own Skill tool (claude-agent's): a native call, which the CLI's session
605
- * records as a kernel step of its own (`kernel.start` named `tool.Skill`, keyed `tool:<call id>`, then its `kernel.end`)
606
- * and never as a host tool's call record, so no timeline row or callArgsOf entry has it. Each by the name the model
607
- * gave (`agentrun:<name>` or the bare one), only when its step completed, and only outside every end-of-run turn (a
608
- * reopened run's follow-up's loads are the job's). */
609
- export function nativeSkillLoads(entries) {
610
- const turns = endOfRunTurns(entries);
611
- const inTurn = (id) => id !== undefined && turns.some(([from, to]) => id >= from && id <= to);
612
- const asked = new Map();
613
- const loaded = [];
614
- for (const entry of entries) {
615
- if (inTurn(entry.id))
616
- continue;
617
- const data = (entry.data ?? {});
618
- if (entry.kind === "kernel.start" && data.name === "tool.Skill" && typeof data.stepId === "string") {
619
- const skill = data.input?.skill;
620
- if (typeof skill === "string")
621
- asked.set(data.stepId, skill);
622
- }
623
- else if (entry.kind === "kernel.end" && typeof data.stepId === "string" && data.status === "completed" && asked.has(data.stepId)) {
624
- loaded.push(asked.get(data.stepId));
625
- }
626
- }
627
- return loaded;
628
- }
629
- /** Whether a skill loaded by the name `asked` is skill `name`: by its plugin-qualified name or its bare one. */
630
- const loadsSkill = (asked, name) => asked === name || asked === `${CLAUDE_SKILLS_PLUGIN}:${name}`;
631
- /** Where a claim lays a learned skill's SKILL.md in the run's work (learning.ts RUN_SKILLS). */
632
- const laidSkillPath = (name) => `.agents/skills/${name}/SKILL.md`;
633
- /** Whether call `call` read skill `name`'s SKILL.md: the read hand on the path its claim laid it at (`.agents/skills/
634
- * <name>/SKILL.md` in the run's work, relative or absolute under it, never another file whose path ends the same way), a
635
- * CLI adapter's read_skill_file of the skill's SKILL.md, or a Skill tool call on the skill. */
636
- function readsSkill(call, name) {
637
- const text = (key) => (typeof call.args[key] === "string" ? call.args[key] : "");
638
- if (call.tool === "read" || call.tool === "mcp__hands__read") {
639
- const path = posix.normalize(text("path"));
640
- return path === laidSkillPath(name) || (path.startsWith("/") && path.endsWith(`/${laidSkillPath(name)}`));
641
- }
642
- if (call.tool === "read_skill_file")
643
- return text("skill") === name && posix.normalize(text("path")) === "SKILL.md";
644
- if (call.tool === "Skill")
645
- return [text("skill"), text("command"), text("name")].some((asked) => loadsSkill(asked, name));
646
- return false;
647
- }
648
- /** `laid`: what the run's claims laid (laidOf): a skill its launch offered but no claim laid (over the budget, or a name
649
- * the revision's own skill holds, whose copy is the one installed) is not the run's learned skill, whatever it read.
650
- * `loads`: the skills its job loaded with a harness's own Skill tool (nativeSkillLoads), each a read of its SKILL.md. */
651
- export function learnedUseOf(started, reflect, rows, args = new Map(), laid = { skills: [] }, loads = []) {
655
+ /** The learned workflows a run's job called (LearnedUse), over its timeline rows less the end-of-run turn's (`reflect`). */
656
+ export function learnedUseOf(reflect, rows, args = new Map()) {
652
657
  const job = rows.filter((row) => !reflects(reflect, row.id));
653
658
  const results = new Map(job.flatMap((row) => (row.kind === "tool_result" && row.tool_use_id ? [[row.tool_use_id, row.tool_status]] : [])));
654
659
  const models = modelsOwn(job);
655
- const calls = job.filter((row) => row.kind === "tool_use" && models(row) && row.tool_use_id).flatMap((row) => {
656
- const call = args.get(row.tool_use_id);
657
- return call ? [{ id: row.tool_use_id, ...call }] : [];
658
- });
659
- const installed = new Set(laid.skills);
660
- const skills = (started?.skills ?? []).filter((name) => installed.has(name)).map((name) => ({ name, read: calls.some((call) => results.get(call.id) === "success" && readsSkill(call, name)) || loads.some((asked) => loadsSkill(asked, name)) }));
661
660
  const workflows = new Map();
662
- for (const call of calls) {
663
- if (!WORKFLOW_CALLS.has(call.tool) || typeof call.args.name !== "string")
661
+ for (const row of job) {
662
+ if (row.kind !== "tool_use" || !models(row) || !row.tool_use_id)
663
+ continue;
664
+ const call = args.get(row.tool_use_id);
665
+ if (!call || !WORKFLOW_CALLS.has(call.tool) || typeof call.args.name !== "string")
664
666
  continue;
665
667
  const seen = workflows.get(call.args.name) ?? { calls: 0, failed: 0 };
666
668
  seen.calls += 1;
667
669
  // Only a result that says so: a call with no result yet (one still running) is no failure.
668
- if (results.get(call.id) === "failed")
670
+ if (results.get(row.tool_use_id) === "failed")
669
671
  seen.failed += 1;
670
672
  workflows.set(call.args.name, seen);
671
673
  }
672
- return { skills, workflows: [...workflows].map(([name, seen]) => ({ name, ...seen })) };
673
- }
674
- /** `end` with its run's given notes (from its launch's learning start) and the notes its job read. */
675
- export function withNotes(end, started, read) {
676
- return {
677
- ...end,
678
- ...(started ? { given: started.given.map((note) => ({ file: note.file, name: note.name })) } : {}),
679
- ...(read.length ? { read: [...read] } : {}),
680
- };
674
+ return { workflows: [...workflows].map(([name, seen]) => ({ name, ...seen })) };
681
675
  }
682
- /** Run `runId`'s learning start as its launch records it (run-launch.ts learningStartOf, the one reader): its given notes,
683
- * its seed sha and its # Learned section; undefined when the run does not learn or has no launch. */
676
+ /** Run `runId`'s learning start as its launch records it (run-launch.ts learningStartOf, the one reader): its seed sha,
677
+ * its # Learned section and its workflows; undefined when the run does not learn or has no launch. */
684
678
  async function learningStartOfRun(store, runId) {
685
679
  // The agent's narrow read (agentRecordsOf) answers when the run is in it; a missing launch reads as a run that does not learn.
686
680
  if (store.runs.learningStart)
@@ -692,19 +686,18 @@ async function learningStartOfRun(store, runId) {
692
686
  /** The learning of a run that only uses what its agent learned (`learning: "use"`): seeded while it runs, as a run that
693
687
  * learns is; dropped `use` once it ended, since it is never asked what to keep. */
694
688
  export function usedOnly(started, terminal, at) {
695
- // A start that could not be made (a folder unreadable or not copied) handed the run nothing: said so from its start, as
696
- // the end hook says it for a run that learns, never "seeded" and then `use`. No proposal is written for it.
689
+ // A start that could not be made (a folder unreadable) handed the run nothing: said so from its start, as the end hook
690
+ // says it for a run that learns, never "seeded" and then `use`. No proposal is written for it.
697
691
  if (seedFailed(started)) {
698
692
  const why = started.seedFailed === "unreadable" ? STOPPED.unreadable : started.seedFailed === "not_copied" ? STOPPED.notCopied : STOPPED.noSeed;
699
693
  return { state: "dropped", reason: "seed_failed", detail: said.stopped(why), at };
700
694
  }
701
- return terminal ? { state: "dropped", reason: "use", detail: said.use, at } : { state: "seeded", reason: null, detail: said.seeded(started.seedNotes ?? 0), at };
695
+ return terminal ? { state: "dropped", reason: "use", detail: said.use, at } : { state: "seeded", reason: null, detail: said.seeded(correctionCount(started.section), started.workflows?.length ?? 0), at };
702
696
  }
703
697
  /** GET /runs/{id}/learning from the one store, in the shape the route gives (learning-routes.ts runLearningBody): the
704
- * run's learning end (runLearningEnd), the notes it was given and the seed it started from as its launch records them,
705
- * what it held for its owner's OK as it stands on its agent's folder's main (`statuses`, learning-routes.ts statusesOf,
706
- * read only when it held something; none: as the merge wrote it), settled once the run is final. Null when the run kept
707
- * no learning. */
698
+ * run's learning end (runLearningEnd) and the seed it started from as its launch records it, what it held for its
699
+ * owner's OK as it stands on its agent's folder's main (`statuses`, learning-routes.ts statusesOf, read only when it held
700
+ * something; none: as the merge wrote it), settled once the run is final. Null when the run kept no learning. */
708
701
  export async function runLearningOverStore(store, runId, shown, secrets, statuses) {
709
702
  const started = await learningStartOfRun(store, runId);
710
703
  const row = await store.runs.get(runId);
@@ -720,12 +713,10 @@ export async function runLearningOverStore(store, runId, shown, secrets, statuse
720
713
  if (promoted !== undefined)
721
714
  end.compiled = { ...end.compiled, promoted };
722
715
  }
723
- const used = started?.given.length || started?.skills?.length || started?.workflows?.length;
716
+ const used = !!started?.workflows?.length;
724
717
  const [reflect, rows, entries] = used ? await Promise.all([runReflect(store, runId, BACKGROUND_CONTEXT), runTimeline(store, runId, BACKGROUND_CONTEXT, { settled }), runEntries(store, runId, BACKGROUND_CONTEXT)]) : [undefined, [], []];
725
- const read = started?.given.length ? notesReadOf(started.given, reflect, rows) : [];
726
- const learning = withNotes(end, started, read);
727
- const current = holdsForOk(learning) && row && statuses ? currentLearning(learning, await statuses(row.agentId)) : learning;
728
- const body = runLearningBody({ id: runId, learning: current, seed: started?.seed ?? null, settled, used: learnedUseOf(started, reflect, rows, callArgsOf(entries), laidOf(entries), nativeSkillLoads(entries)) }, shown, secrets);
718
+ const current = holdsForOk(end) && row && statuses ? currentLearning(end, await statuses(row.agentId)) : end;
719
+ const body = runLearningBody({ id: runId, learning: current, seed: started?.seed ?? null, settled, used: learnedUseOf(reflect, rows, callArgsOf(entries)) }, shown, secrets);
729
720
  // The run's own grade (PUT /runs/{id}/grade), as its agent keeps it and the PUT answered it, with the round it opened.
730
721
  // Never its `expected` (a person's words, uncut), nor its label (not kept). Its workflow's name is cut as every other
731
722
  // learning name is (`shown.name`): a secret registered after the grade never shows here.