@parcha/agentrun-serve 0.1.0-beta.44 → 0.1.0-beta.46

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 (350) hide show
  1. package/CHANGELOG.md +148 -5
  2. package/README.md +385 -305
  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 +62 -19
  28. package/dist/composio-preset.js +69 -7
  29. package/dist/composio-triggers.d.ts +14 -0
  30. package/dist/composio-triggers.js +79 -15
  31. package/dist/computer-attach.d.ts +40 -5
  32. package/dist/computer-attach.js +130 -15
  33. package/dist/computer-keys.d.ts +3 -0
  34. package/dist/computer-keys.js +7 -1
  35. package/dist/computer-live.js +3 -2
  36. package/dist/computers.d.ts +21 -10
  37. package/dist/computers.js +39 -28
  38. package/dist/console/assets/index-C2MYaUBa.css +1 -0
  39. package/dist/console/assets/index-CZZeCReB.js +701 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/decisions.d.ts +1 -1
  42. package/dist/dial-relay.d.ts +29 -0
  43. package/dist/dial-relay.js +94 -0
  44. package/dist/email/tools.js +10 -5
  45. package/dist/env-proxy.d.ts +2 -0
  46. package/dist/env-proxy.js +35 -0
  47. package/dist/errors.d.ts +3 -1
  48. package/dist/errors.js +7 -4
  49. package/dist/faux-computers.d.ts +8 -2
  50. package/dist/faux-computers.js +83 -6
  51. package/dist/harness-archive.d.ts +67 -0
  52. package/dist/harness-archive.js +177 -0
  53. package/dist/harness-goose.d.ts +34 -0
  54. package/dist/harness-goose.js +87 -0
  55. package/dist/harness-install.d.ts +21 -0
  56. package/dist/harness-install.js +24 -11
  57. package/dist/harness-opencode/adapter.js +1 -1
  58. package/dist/harness-table.d.ts +9 -1
  59. package/dist/harness-table.js +20 -3
  60. package/dist/harness.d.ts +1 -2
  61. package/dist/harness.js +3 -4
  62. package/dist/host.js +2 -1
  63. package/dist/import.d.ts +10 -0
  64. package/dist/import.js +28 -8
  65. package/dist/key-check.js +3 -0
  66. package/dist/learn/audit.d.ts +6 -6
  67. package/dist/learn/audit.js +3 -7
  68. package/dist/learn/check.d.ts +23 -89
  69. package/dist/learn/check.js +57 -335
  70. package/dist/learn/commit.d.ts +63 -90
  71. package/dist/learn/commit.js +124 -316
  72. package/dist/learn/compile.d.ts +53 -50
  73. package/dist/learn/compile.js +89 -104
  74. package/dist/learn/corrections.d.ts +13 -0
  75. package/dist/learn/corrections.js +23 -0
  76. package/dist/learn/delete.d.ts +5 -5
  77. package/dist/learn/delete.js +8 -10
  78. package/dist/learn/folder.d.ts +35 -47
  79. package/dist/learn/folder.js +118 -134
  80. package/dist/learn/index.d.ts +3 -5
  81. package/dist/learn/index.js +6 -9
  82. package/dist/learn/learning.sh +45 -15
  83. package/dist/learn/promote.d.ts +23 -5
  84. package/dist/learn/promote.js +40 -2
  85. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
  86. package/dist/learn/{skills.js → workflow-draft.js} +48 -58
  87. package/dist/learn/workflow-nodes.js +1 -1
  88. package/dist/learned-workflow.js +2 -2
  89. package/dist/learning-cost.d.ts +38 -24
  90. package/dist/learning-cost.js +41 -24
  91. package/dist/learning-routes.d.ts +91 -170
  92. package/dist/learning-routes.js +183 -421
  93. package/dist/learning-run.d.ts +19 -40
  94. package/dist/learning-run.js +23 -93
  95. package/dist/learning-setting.d.ts +21 -10
  96. package/dist/learning-setting.js +47 -11
  97. package/dist/learning-words.d.ts +28 -74
  98. package/dist/learning-words.js +64 -162
  99. package/dist/learning.d.ts +61 -392
  100. package/dist/learning.js +101 -651
  101. package/dist/live-reach.d.ts +25 -2
  102. package/dist/live-reach.js +46 -4
  103. package/dist/llms.txt +1 -1
  104. package/dist/local-models.d.ts +3 -11
  105. package/dist/local-models.js +5 -6
  106. package/dist/mcp-servers-store.d.ts +4 -4
  107. package/dist/model-form.js +6 -5
  108. package/dist/model.d.ts +4 -0
  109. package/dist/model.js +26 -9
  110. package/dist/native/binding.js +1 -1
  111. package/dist/native/connection.js +1 -1
  112. package/dist/native/discovery.js +1 -1
  113. package/dist/native/instructions.d.ts +3 -0
  114. package/dist/native/instructions.js +5 -3
  115. package/dist/native/remote-worker-bridge.js +9 -43
  116. package/dist/native/remote.d.ts +8 -15
  117. package/dist/native/remote.js +3 -3
  118. package/dist/native/schema.js +1 -1
  119. package/dist/native/types.d.ts +2 -2
  120. package/dist/openapi.js +273 -319
  121. package/dist/paid-calls.d.ts +8 -0
  122. package/dist/paid-calls.js +20 -0
  123. package/dist/particle-provider.d.ts +11 -0
  124. package/dist/particle-provider.js +135 -0
  125. package/dist/port-models.d.ts +12 -4
  126. package/dist/port-models.js +28 -11
  127. package/dist/print.d.ts +27 -0
  128. package/dist/print.js +21 -0
  129. package/dist/provider.d.ts +7 -0
  130. package/dist/provider.js +15 -1
  131. package/dist/reflect-range.js +2 -3
  132. package/dist/run-launch.d.ts +14 -28
  133. package/dist/run-launch.js +9 -12
  134. package/dist/run-learning-served.d.ts +15 -89
  135. package/dist/run-listing.d.ts +34 -0
  136. package/dist/run-listing.js +128 -0
  137. package/dist/run-model-key.js +1 -1
  138. package/dist/run-timeline-served.js +5 -3
  139. package/dist/run-trace.d.ts +97 -0
  140. package/dist/run-trace.js +253 -0
  141. package/dist/run-view.d.ts +15 -0
  142. package/dist/run-view.js +9 -0
  143. package/dist/runnable.js +2 -1
  144. package/dist/runner/adapter-loop.d.ts +8 -6
  145. package/dist/runner/adapter-loop.js +16 -12
  146. package/dist/runner/adapter-run-spec.d.ts +16 -4
  147. package/dist/runner/adapter-run-spec.js +64 -58
  148. package/dist/runner/adapters/index.js +22 -0
  149. package/dist/runner/adapters/pi.d.ts +4 -12
  150. package/dist/runner/adapters/pi.js +2 -2
  151. package/dist/runner/audit.d.ts +1 -1
  152. package/dist/runner/audit.js +30 -13
  153. package/dist/runner/beside.d.ts +6 -2
  154. package/dist/runner/beside.js +38 -9
  155. package/dist/runner/claim-secrets.d.ts +18 -2
  156. package/dist/runner/claim-secrets.js +42 -18
  157. package/dist/runner/cli-run-spec.js +55 -51
  158. package/dist/runner/conformance/harness.d.ts +6 -0
  159. package/dist/runner/conformance/harness.js +35 -13
  160. package/dist/runner/conformance/subject.d.ts +6 -0
  161. package/dist/runner/dispatch.d.ts +2 -2
  162. package/dist/runner/end-of-run.d.ts +6 -14
  163. package/dist/runner/end-of-run.js +8 -33
  164. package/dist/runner/feedback-round.d.ts +2 -2
  165. package/dist/runner/feedback-round.js +7 -7
  166. package/dist/runner/github-app.js +3 -1
  167. package/dist/runner/harness-loops.d.ts +0 -8
  168. package/dist/runner/harness-loops.js +11 -59
  169. package/dist/runner/held.d.ts +170 -0
  170. package/dist/runner/held.js +57 -0
  171. package/dist/runner/journal-kinds.d.ts +2 -3
  172. package/dist/runner/journal-kinds.js +2 -3
  173. package/dist/runner/learned-first.d.ts +40 -0
  174. package/dist/runner/learned-first.js +32 -0
  175. package/dist/runner/learning-end.d.ts +77 -69
  176. package/dist/runner/learning-end.js +250 -303
  177. package/dist/runner/learning-seed.d.ts +15 -33
  178. package/dist/runner/learning-seed.js +24 -45
  179. package/dist/runner/loop-contract.d.ts +2 -3
  180. package/dist/runner/main.d.ts +17 -9
  181. package/dist/runner/main.js +82 -20
  182. package/dist/runner/mcp-run.d.ts +11 -0
  183. package/dist/runner/mcp-run.js +67 -0
  184. package/dist/runner/memory-claim.d.ts +10 -5
  185. package/dist/runner/memory-claim.js +12 -6
  186. package/dist/runner/model-route.d.ts +7 -4
  187. package/dist/runner/model-route.js +22 -10
  188. package/dist/runner/native-loop.d.ts +0 -7
  189. package/dist/runner/native-loop.js +9 -101
  190. package/dist/runner/promotion.d.ts +12 -8
  191. package/dist/runner/promotion.js +37 -28
  192. package/dist/runner/reflect-hook.d.ts +64 -95
  193. package/dist/runner/reflect-hook.js +112 -225
  194. package/dist/runner/run-channel.d.ts +43 -0
  195. package/dist/runner/run-channel.js +467 -0
  196. package/dist/runner/run-child-host.d.ts +169 -0
  197. package/dist/runner/run-child-host.js +1230 -0
  198. package/dist/runner/run-child.d.ts +1 -0
  199. package/dist/runner/run-child.js +254 -0
  200. package/dist/runner/run-errors.d.ts +2 -0
  201. package/dist/runner/run-errors.js +20 -0
  202. package/dist/runner/runner.js +1 -5
  203. package/dist/runner/sdk-ask.d.ts +78 -0
  204. package/dist/runner/sdk-ask.js +158 -0
  205. package/dist/runner/sdk-loop.d.ts +2 -4
  206. package/dist/runner/sdk-loop.js +29 -49
  207. package/dist/runner/store-secrets.d.ts +5 -3
  208. package/dist/runner/store-secrets.js +5 -1
  209. package/dist/runner/workflow-first.d.ts +5 -0
  210. package/dist/runner/workflow-first.js +4 -0
  211. package/dist/runner/workflow-spec.js +7 -2
  212. package/dist/runs-over-store.d.ts +16 -28
  213. package/dist/runs-over-store.js +31 -38
  214. package/dist/sdk/runs.d.ts +6 -11
  215. package/dist/sdk/runs.js +20 -41
  216. package/dist/sdk/schema.js +3 -4
  217. package/dist/seal-key.d.ts +5 -0
  218. package/dist/seal-key.js +7 -0
  219. package/dist/secrets.d.ts +3 -0
  220. package/dist/secrets.js +16 -3
  221. package/dist/server.d.ts +55 -33
  222. package/dist/server.js +689 -322
  223. package/dist/sign-ins-store.d.ts +8 -0
  224. package/dist/sign-ins-store.js +36 -1
  225. package/dist/skills.js +1 -1
  226. package/dist/store/index.d.ts +2 -2
  227. package/dist/store/index.js +1 -1
  228. package/dist/store/journal/storage.js +3 -0
  229. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  230. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  231. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  232. package/dist/store/schema.d.ts +53 -4
  233. package/dist/store/schema.js +137 -6
  234. package/dist/store/sqlite/connection.d.ts +2 -0
  235. package/dist/store/sqlite/connection.js +3 -1
  236. package/dist/store/sqlite/run-patch.d.ts +0 -17
  237. package/dist/store/sqlite/run-patch.js +4 -33
  238. package/dist/store/sqlite/store.js +246 -63
  239. package/dist/store/sqlite/worker.js +25 -0
  240. package/dist/store/store.d.ts +193 -36
  241. package/dist/store/store.js +25 -3
  242. package/dist/store-reads/learning.d.ts +102 -204
  243. package/dist/store-reads/learning.js +159 -321
  244. package/dist/store-reads/loop.d.ts +0 -1
  245. package/dist/store-reads/loop.js +1 -1
  246. package/dist/store-view.d.ts +29 -1
  247. package/dist/store-view.js +97 -31
  248. package/dist/template-eval.d.ts +3 -6
  249. package/dist/template-eval.js +22 -36
  250. package/dist/templates.d.ts +8 -4
  251. package/dist/templates.js +44 -6
  252. package/dist/timeline/index.d.ts +1 -1
  253. package/dist/timeline/index.js +1 -1
  254. package/dist/timeline/timeline.d.ts +5 -1
  255. package/dist/timeline/timeline.js +16 -0
  256. package/dist/tool-gate.d.ts +0 -7
  257. package/dist/tool-gate.js +1 -15
  258. package/dist/tool-keys-store.d.ts +1 -1
  259. package/dist/tool-keys.d.ts +6 -4
  260. package/dist/tool-keys.js +12 -6
  261. package/dist/tools.d.ts +2 -2
  262. package/dist/tools.js +11 -4
  263. package/dist/triggers.d.ts +65 -6
  264. package/dist/triggers.js +125 -19
  265. package/dist/validate.js +1 -1
  266. package/dist/webhooks.d.ts +7 -2
  267. package/dist/webhooks.js +12 -5
  268. package/dist/workspace/agent-computer.d.ts +2 -0
  269. package/dist/workspace/agent-computer.js +2 -0
  270. package/dist/workspace/archil-claim.d.ts +7 -0
  271. package/dist/workspace/archil-claim.js +29 -0
  272. package/dist/workspace/archil.d.ts +9 -1
  273. package/dist/workspace/archil.js +165 -3
  274. package/dist/workspace/attach.d.ts +3 -1
  275. package/dist/workspace/attach.js +2 -0
  276. package/dist/workspace/attached-computers.d.ts +16 -5
  277. package/dist/workspace/attached-computers.js +25 -9
  278. package/dist/workspace/computer-deps.js +1 -1
  279. package/dist/workspace/computer-for-claim.d.ts +7 -3
  280. package/dist/workspace/computer-for-claim.js +119 -22
  281. package/dist/workspace/computer-hold.js +2 -1
  282. package/dist/workspace/computer-kept.d.ts +11 -1
  283. package/dist/workspace/computer-kept.js +24 -3
  284. package/dist/workspace/resolve-computer.d.ts +33 -19
  285. package/dist/workspace/resolve-computer.js +172 -64
  286. package/dist/workspace/revision-skills.d.ts +1 -2
  287. package/dist/workspace/revision-skills.js +3 -4
  288. package/dist/workspace/run-workspace.d.ts +1 -1
  289. package/dist/workspace/run-workspace.js +5 -0
  290. package/dist/workspace/synced-folder.d.ts +85 -0
  291. package/dist/workspace/synced-folder.js +230 -0
  292. package/dist/workspace/workspace.d.ts +4 -0
  293. package/launcher/agentrun-serve +1 -1
  294. package/package.json +10 -10
  295. package/templates/README.md +8 -8
  296. package/templates/inbound-lead/agent.md +5 -4
  297. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  298. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  299. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  300. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  301. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  302. package/templates/inbound-lead/lead.schema.json +6 -5
  303. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  304. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  305. package/templates/kyb/agent.md +2 -1
  306. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  307. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  308. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  309. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  310. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  311. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  312. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  313. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  314. package/dist/console/assets/index-BUktRvS-.css +0 -1
  315. package/dist/console/assets/index-nB9kTfIN.js +0 -711
  316. package/dist/learn/grade.d.ts +0 -138
  317. package/dist/learn/grade.js +0 -682
  318. package/dist/learn/notes.d.ts +0 -81
  319. package/dist/learn/notes.js +0 -178
  320. package/dist/learn/reflect.d.ts +0 -77
  321. package/dist/learn/reflect.js +0 -228
  322. package/dist/learn/relevance.d.ts +0 -24
  323. package/dist/learn/relevance.js +0 -91
  324. package/dist/learn/seed-check.d.ts +0 -74
  325. package/dist/learn/seed-check.js +0 -103
  326. package/dist/learning-batch.d.ts +0 -291
  327. package/dist/learning-batch.js +0 -600
  328. package/dist/learning-evals.d.ts +0 -35
  329. package/dist/learning-evals.js +0 -99
  330. package/dist/native/context.d.ts +0 -6
  331. package/dist/native/context.js +0 -22
  332. package/dist/propose.d.ts +0 -52
  333. package/dist/propose.js +0 -224
  334. package/dist/runner/learning-ask.d.ts +0 -47
  335. package/dist/runner/learning-ask.js +0 -128
  336. package/dist/runner/learning-dispatch.d.ts +0 -45
  337. package/dist/runner/learning-dispatch.js +0 -99
  338. package/dist/runner/learning-factory.d.ts +0 -16
  339. package/dist/runner/learning-factory.js +0 -50
  340. package/dist/runner/learning-loop.d.ts +0 -273
  341. package/dist/runner/learning-loop.js +0 -521
  342. package/dist/usage.d.ts +0 -11
  343. package/dist/usage.js +0 -11
  344. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  345. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  346. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  347. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  348. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  349. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  350. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -16,13 +16,16 @@
16
16
  // - A snapshot that is not main's (a write that stopped between its compare and swap and its snapshot, or a hand commit
17
17
  // in a local folder) is rebuilt from main whole (learningRepair: the script's read, then its snapshot op), the next
18
18
  // time a write finds main moved under it.
19
- // The snapshot's shape is SNAPSHOT.md's, v1: what the learning routes and a run's seed read.
19
+ // The snapshot's shape is v1: what the learning routes and a run's seed read. The folder holds the owner's
20
+ // corrections (corrections.md, served whole), the compiled workflows (workflows/<name>/) and the host's audit ledger
21
+ // (audits.jsonl, never served to a run), nothing else.
20
22
  import { createHash, randomBytes } from "node:crypto";
21
23
  import { readFileSync } from "node:fs";
22
24
  import { isWorkspaceError, learningWorkspace as oneLearningWorkspace, } from "../workspace/index.js";
23
- import { INDEX_FILE, NOTE_FILE, parseNoteFile } from "./notes.js";
24
- import { learnedFront, learnedName, learnedStatus, retiredFrom, SKILLS_DIR, WORKFLOWS_DIR } from "./skills.js";
25
- /** The host's folder inside the learning folder: the snapshot, the diffs and the script. Never a note's, never seeded. */
25
+ import { CORRECTIONS_FILE } from "./corrections.js";
26
+ import { learnedFront, learnedStatus, retiredFrom, WORKFLOW_NAME, WORKFLOWS_DIR } from "./workflow-draft.js";
27
+ import { held, heldLearningFolder } from "../runner/held.js";
28
+ /** The host's folder inside the learning folder: the snapshot, the diffs and the script. Never learned, never seeded. */
26
29
  export const HOST_DIR = ".agentrun";
27
30
  export const SNAPSHOT_FILE = `${HOST_DIR}/snapshot.json`;
28
31
  export const DIFFS_DIR = `${HOST_DIR}/diffs`;
@@ -30,7 +33,7 @@ export const DIFFS_DIR = `${HOST_DIR}/diffs`;
30
33
  export const AUDITS_FILE = "audits.jsonl";
31
34
  /** The most changes the snapshot's log keeps, newest first; `log_more` says older exist. */
32
35
  export const LOG_KEEP = 200;
33
- /** A file main holds over this is no note and no learned file: a note is at most 4 KB (check.ts CAPS.note). */
36
+ /** A file main holds over this is no learned file: a workflow's file is at most 16 KB (check.ts CAPS.file). */
34
37
  export const FILE_CAP = 1 << 20;
35
38
  /** A diff's file whose patch is larger than this is withheld as too large (learning.sh PATCH_CAP). */
36
39
  export const PATCH_CAP = 64 * 1024;
@@ -50,17 +53,14 @@ export const blobOid = (bytes) => {
50
53
  const data = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : bytes;
51
54
  return createHash("sha1").update(`blob ${data.length}\0`).update(data).digest("hex");
52
55
  };
53
- const EMPTY_INDEX = { oid: blobOid(""), bytes: 0 };
54
- /** A key file of a learned item: a skill's SKILL.md, a draft's README.md (which says whether it waits). The file the
55
- * view names for it, which its `run` follows: a skill's SKILL.md, a draft's workflow.json. */
56
- const keyFile = (kind, name) => (kind === "skill" ? `${SKILLS_DIR}/${name}/SKILL.md` : `${WORKFLOWS_DIR}/${name}/README.md`);
57
- const viewFile = (kind, name) => (kind === "skill" ? `${SKILLS_DIR}/${name}/SKILL.md` : `${WORKFLOWS_DIR}/${name}/workflow.json`);
58
- /** The learned folder a path is in, by kind and name: `skills/<name>/...` or `workflows/<name>/...`; else undefined. */
56
+ /** A draft's key file, its README.md (which says whether it waits), and the file the view names for it, which its `run`
57
+ * follows: its workflow.json. */
58
+ const keyFile = (name) => `${WORKFLOWS_DIR}/${name}/README.md`;
59
+ const viewFile = (name) => `${WORKFLOWS_DIR}/${name}/workflow.json`;
60
+ /** The draft a path is in, by name: `workflows/<name>/...`; else undefined. */
59
61
  function folderOf(path) {
60
62
  const [top, name, ...rest] = path.split("/");
61
- if (!name || !rest.length)
62
- return undefined;
63
- return top === SKILLS_DIR ? { kind: "skill", name } : top === WORKFLOWS_DIR ? { kind: "workflow", name } : undefined;
63
+ return top === WORKFLOWS_DIR && name && rest.length ? name : undefined;
64
64
  }
65
65
  const byBytes = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
66
66
  /** What a commit's change was, as the view says it, or undefined for one that is neither: a person's names its kind in
@@ -73,29 +73,23 @@ function changeOf(commit) {
73
73
  return { kind, by: "person", at: commit.at };
74
74
  return undefined;
75
75
  }
76
- /** `path`'s history once `commit` changed it, from what it was before (newest first walks give none, then fill in
77
- * only what is missing: foldOlder). A person's action is the named file's alone; any other file their commit changed is
78
- * a note it superseded. */
79
- function changeFor(commit, path) {
76
+ /** A file's history once `commit` changed it, from what it was before (newest first walks give none, then fill in
77
+ * only what is missing: foldOlder). */
78
+ function foldNewer(before, commit) {
80
79
  const change = changeOf(commit);
81
- const named = change?.by === "person" ? commit.subject.slice(`learning: ${change.kind} by a person: `.length) : undefined;
82
- return named !== undefined && path !== named ? { kind: "superseded", by: "person", at: commit.at } : change;
83
- }
84
- function foldNewer(before, commit, path) {
85
- const change = changeFor(commit, path);
86
80
  const retire = change?.kind === "retired" ? change : before?.retire;
87
81
  const person = change?.by === "person" ? change : before?.person;
88
82
  return { at: commit.at, ...(change ? { last: change } : {}), ...(retire ? { retire } : {}), ...(person ? { person } : {}) };
89
83
  }
90
- function foldOlder(known, commit, path) {
91
- const change = changeFor(commit, path);
84
+ function foldOlder(known, commit) {
85
+ const change = changeOf(commit);
92
86
  if (!known.retire && change?.kind === "retired")
93
87
  known.retire = change;
94
88
  if (!known.person && change?.by === "person")
95
89
  known.person = change;
96
90
  }
97
91
  /** A commit's entry in the log, or undefined when it is no change: a run's merge (Run-Id) or a person's (Changed-By:
98
- * user), told by its trailers. A merge's reason is the grader's, the paragraphs before the trailers; a person's commit
92
+ * user), told by its trailers. A merge's reason is what it kept, the paragraphs before the trailers; a person's commit
99
93
  * has none, so its subject says what it did. */
100
94
  function changeEntry(commit, sha, files) {
101
95
  const runId = commit.runId.split(",")[0].trim();
@@ -108,19 +102,7 @@ function changeEntry(commit, sha, files) {
108
102
  }
109
103
  /** Whether a commit's message holds a line git's log of changes greps for: `Run-Id: ` or `Changed-By: user`. */
110
104
  const isChange = (commit) => `${commit.subject}\n${commit.body}`.split("\n").some((line) => line.startsWith("Run-Id: ") || line === "Changed-By: user");
111
- /** The view's order of notes: active first, then by their newest change (the commit's place, 0 the newest), then by
112
- * name. */
113
- const noteOrder = (a, b) => (a.status === "active" ? 0 : 1) - (b.status === "active" ? 0 : 1) || a.order - b.order || byBytes(a.file, b.file);
114
105
  const byName = (a, b) => byBytes(a.name, b.name);
115
- /** A note's entry, from its text, or undefined when it is no note (out of shape). */
116
- function noteEntry(file, text, oid, bytes, order, history) {
117
- if (!NOTE_FILE.test(file) || bytes > FILE_CAP)
118
- return undefined;
119
- const note = parseNoteFile(file, text);
120
- if (Array.isArray(note))
121
- return undefined;
122
- return { file, oid, bytes, name: note.name, description: note.description, type: note.type, status: note.status, origin: note.origin, supersedes: [...note.supersedes], superseded_by: note.superseded_by, ...(note.retired_from ? { retired_from: note.retired_from } : {}), order, history };
123
- }
124
106
  // ---------------------------------------------------------------------------------------------------------------------
125
107
  // A snapshot from main whole (the script's `read`): a folder whose snapshot is not main's.
126
108
  const utf8 = new TextDecoder("utf-8", { fatal: true });
@@ -206,9 +188,9 @@ export function snapshotOfRead(read) {
206
188
  order.set(file, i);
207
189
  const known = history.get(file);
208
190
  if (!known)
209
- history.set(file, foldNewer(undefined, commit, file));
191
+ history.set(file, foldNewer(undefined, commit));
210
192
  else
211
- foldOlder(known, commit, file);
193
+ foldOlder(known, commit);
212
194
  if (runId && !runs.has(file))
213
195
  runs.set(file, runId);
214
196
  }
@@ -226,52 +208,41 @@ export function snapshotOfRead(read) {
226
208
  const regular = (entry) => entry.type === "blob" && entry.mode === "100644";
227
209
  const orderOf = (path) => order.get(path) ?? Number.MAX_SAFE_INTEGER;
228
210
  const historyOf = (path) => history.get(path) ?? { at };
229
- const index = tree.find((entry) => entry.path === INDEX_FILE && regular(entry));
211
+ const corrections = tree.find((entry) => entry.path === CORRECTIONS_FILE && regular(entry));
230
212
  const audits = tree.find((entry) => entry.path === AUDITS_FILE && regular(entry));
231
- const notes = [];
232
213
  const folders = new Map();
233
214
  for (const entry of tree) {
234
- if (!entry.path.includes("/")) {
235
- const text = regular(entry) && entry.bytes <= FILE_CAP ? textOf(blobs.get(entry.oid)) : undefined;
236
- const note = text === undefined || entry.path === INDEX_FILE ? undefined : noteEntry(entry.path, text, entry.oid, entry.bytes, orderOf(entry.path), historyOf(entry.path));
237
- if (note)
238
- notes.push(note);
239
- continue;
240
- }
241
- const folder = folderOf(entry.path);
242
- if (!folder || entry.type !== "blob")
215
+ const name = folderOf(entry.path);
216
+ if (!name || entry.type !== "blob")
243
217
  continue;
244
- const key = `${folder.kind}/${folder.name}`;
245
- const known = folders.get(key) ?? folders.set(key, { ...folder, files: [], links: [] }).get(key);
218
+ const known = folders.get(name) ?? folders.set(name, { files: [], links: [] }).get(name);
246
219
  if (entry.mode === "120000")
247
220
  known.links.push(entry.path);
248
221
  else if (entry.mode === "100644" || entry.mode === "100755")
249
222
  known.files.push({ path: entry.path, oid: entry.oid, bytes: entry.bytes });
250
223
  }
251
- const skills = [];
252
224
  const workflows = [];
253
- for (const { kind, name, files, links } of folders.values()) {
254
- const item = learnedItem(kind, name, files, links, (path) => {
225
+ for (const [name, { files, links }] of folders) {
226
+ const item = learnedItem(name, files, links, (path) => {
255
227
  const entry = tree.find((one) => one.path === path);
256
228
  return entry && regular(entry) && entry.bytes <= FILE_CAP ? textOf(blobs.get(entry.oid)) : undefined;
257
229
  }, {
258
230
  order: Math.min(...files.map(({ path }) => orderOf(path))),
259
- history: historyOf(keyFile(kind, name)),
260
- run: runs.get(viewFile(kind, name)) ?? null,
231
+ history: historyOf(keyFile(name)),
232
+ run: runs.get(viewFile(name)) ?? null,
261
233
  });
262
234
  if (item)
263
- (kind === "skill" ? skills : workflows).push(item);
235
+ workflows.push(item);
264
236
  }
265
- return { v: 1, main, at, index: index ? { oid: index.oid, bytes: index.bytes } : EMPTY_INDEX, ...(audits ? { audits: { oid: audits.oid, bytes: audits.bytes } } : {}), notes: notes.sort(noteOrder), skills: skills.sort(byName), workflows: workflows.sort(byName), log, log_more: more };
237
+ return { v: 1, main, at, ...(corrections ? { corrections: { path: CORRECTIONS_FILE, oid: corrections.oid, bytes: corrections.bytes } } : {}), ...(audits ? { audits: { oid: audits.oid, bytes: audits.bytes } } : {}), workflows: workflows.sort(byName), log, log_more: more };
266
238
  }
267
- /** A learned item from its folder's files: listed when its folder is well named, its key file (SKILL.md, a draft's
268
- * README.md) is there and reads, and a draft has its workflow.json too, each of those a regular file under FILE_CAP
269
- * (only those are given their texts by `text`). */
270
- function learnedItem(kind, name, files, links, text, at, said) {
271
- if (!learnedName(kind, name))
239
+ /** A draft from its folder's files: listed when its folder is well named and its README.md and workflow.json are there,
240
+ * each a regular file under FILE_CAP (only those are given their texts by `text`), and its README.md reads. */
241
+ function learnedItem(name, files, links, text, at, said) {
242
+ if (!WORKFLOW_NAME.test(name))
272
243
  return undefined;
273
- const key = files.find(({ path }) => path === keyFile(kind, name));
274
- const shown = files.find(({ path }) => path === viewFile(kind, name));
244
+ const key = files.find(({ path }) => path === keyFile(name));
245
+ const shown = files.find(({ path }) => path === viewFile(name));
275
246
  if (!key || !shown || key.bytes > FILE_CAP || shown.bytes > FILE_CAP)
276
247
  return undefined;
277
248
  let fields = said;
@@ -285,7 +256,7 @@ function learnedItem(kind, name, files, links, text, at, said) {
285
256
  return { name, file: key.path, description: fields.description, status: fields.status, ...(fields.retired_from ? { retired_from: fields.retired_from } : {}), run: at.run, files: [...files].sort((a, b) => byBytes(a.path, b.path)), oid: key.oid, bytes: key.bytes, order: at.order, history: at.history, ...(links.length ? { links: [...links].sort(byBytes) } : {}) };
286
257
  }
287
258
  /** A commit's message and trailers, as git keeps them: a person's names their action and the file, with Changed-By (and
288
- * Approved-Via on an approval); a run's merge names the run, then the grader's reason, then its Run-Id. */
259
+ * Approved-Via on an approval); a run's merge names the run, then what it kept, then its Run-Id. */
289
260
  function messageOf(by) {
290
261
  const clean = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ");
291
262
  const paragraphs = (parts) => parts.map((part) => (part.endsWith("\n") ? part : `${part}\n`)).join("\n");
@@ -308,17 +279,16 @@ function messageOf(by) {
308
279
  }
309
280
  /** A time in whole seconds as every snapshot says a commit's time: UTC, ending "Z" (commitTime's form). */
310
281
  const isoSeconds = (seconds) => new Date(seconds * 1000).toISOString().replace(/\.\d{3}Z$/, "Z");
311
- /** Every path `snapshot` names a blob for: the index, each note, each learned folder's files. */
282
+ /** Every path `snapshot` names a blob for: corrections.md, the audit ledger and each draft's files. */
312
283
  function oidsOf(snapshot) {
313
284
  const out = new Map();
314
285
  if (!snapshot)
315
286
  return out;
316
- out.set(INDEX_FILE, snapshot.index.oid);
287
+ if (snapshot.corrections)
288
+ out.set(CORRECTIONS_FILE, snapshot.corrections.oid);
317
289
  if (snapshot.audits)
318
290
  out.set(AUDITS_FILE, snapshot.audits.oid);
319
- for (const note of snapshot.notes)
320
- out.set(note.file, note.oid);
321
- for (const item of [...snapshot.skills, ...snapshot.workflows])
291
+ for (const item of snapshot.workflows)
322
292
  for (const file of item.files)
323
293
  out.set(file.path, file.oid);
324
294
  return out;
@@ -330,56 +300,46 @@ export function nextSnapshot(before, change, seconds) {
330
300
  const message = messageOf(change?.by);
331
301
  const commit = { at: isoSeconds(seconds), ...message };
332
302
  const known = oidsOf(before);
333
- const writes = new Map((change?.writes ?? (change ? [] : [{ path: INDEX_FILE, text: "" }])).map(({ path, text }) => [path, { text, oid: blobOid(text), bytes: Buffer.byteLength(text, "utf8") }]));
303
+ const writes = new Map((change?.writes ?? []).map(({ path, text }) => [path, { text, oid: blobOid(text), bytes: Buffer.byteLength(text, "utf8") }]));
334
304
  const deletes = new Set(change?.deletes ?? []);
335
305
  const changed = [...new Set([...[...writes].filter(([path, { oid }]) => known.get(path) !== oid).map(([path]) => path), ...[...deletes].filter((path) => !writes.has(path))])].sort(byBytes);
336
306
  const touched = new Set(changed);
337
307
  const runId = commit.runId;
338
- const notes = (before?.notes ?? []).filter((note) => !touched.has(note.file)).map((note) => ({ ...note, order: note.order + 1 }));
339
- for (const path of changed) {
340
- const written = writes.get(path);
341
- if (!written || path.includes("/") || path === INDEX_FILE)
342
- continue;
343
- const old = before?.notes.find((note) => note.file === path);
344
- const note = noteEntry(path, written.text, written.oid, written.bytes, 0, foldNewer(old?.history, commit, path));
345
- if (note)
346
- notes.push(note);
347
- }
348
- const index = writes.has(INDEX_FILE) ? { oid: writes.get(INDEX_FILE).oid, bytes: writes.get(INDEX_FILE).bytes } : (before?.index ?? EMPTY_INDEX);
349
- const audits = writes.has(AUDITS_FILE) ? { oid: writes.get(AUDITS_FILE).oid, bytes: writes.get(AUDITS_FILE).bytes } : deletes.has(AUDITS_FILE) ? undefined : before?.audits;
350
- const learned = (kind, list) => {
351
- const hit = new Set(changed.map(folderOf).filter((folder) => folder?.kind === kind).map((folder) => folder.name));
352
- const out = list.filter((item) => !hit.has(item.name)).map((item) => ({ ...item, order: item.order + 1 }));
353
- for (const name of hit) {
354
- const old = list.find((item) => item.name === name);
355
- const prefix = `${kind === "skill" ? SKILLS_DIR : WORKFLOWS_DIR}/${name}/`;
356
- const files = new Map((old?.files ?? []).map((file) => [file.path, file]));
357
- for (const path of changed.filter((one) => one.startsWith(prefix))) {
358
- const written = writes.get(path);
359
- if (written)
360
- files.set(path, { path, oid: written.oid, bytes: written.bytes });
361
- else
362
- files.delete(path);
363
- }
364
- const key = keyFile(kind, name);
365
- const keyText = writes.get(key)?.text;
366
- // A link the change writes a file over, or deletes, is a link no more.
367
- const links = (old?.links ?? []).filter((path) => !writes.has(path) && !deletes.has(path));
368
- const item = learnedItem(kind, name, [...files.values()], links, (path) => writes.get(path)?.text, {
369
- order: 0,
370
- history: touched.has(key) ? foldNewer(old?.history, commit, key) : (old?.history ?? { at: commit.at }),
371
- run: runId && touched.has(viewFile(kind, name)) ? runId : (old?.run ?? null),
372
- }, keyText === undefined && old ? { description: old.description, status: old.status, ...(old.retired_from ? { retired_from: old.retired_from } : {}) } : undefined);
373
- if (item)
374
- out.push(item);
308
+ const written = writes.get(CORRECTIONS_FILE);
309
+ const corrections = written ? { path: CORRECTIONS_FILE, oid: written.oid, bytes: written.bytes } : deletes.has(CORRECTIONS_FILE) ? undefined : before?.corrections;
310
+ const ledger = writes.get(AUDITS_FILE);
311
+ const audits = ledger ? { oid: ledger.oid, bytes: ledger.bytes } : deletes.has(AUDITS_FILE) ? undefined : before?.audits;
312
+ const list = before?.workflows ?? [];
313
+ const hit = new Set(changed.map(folderOf).filter((name) => name !== undefined));
314
+ const workflows = list.filter((item) => !hit.has(item.name)).map((item) => ({ ...item, order: item.order + 1 }));
315
+ for (const name of hit) {
316
+ const old = list.find((item) => item.name === name);
317
+ const prefix = `${WORKFLOWS_DIR}/${name}/`;
318
+ const files = new Map((old?.files ?? []).map((file) => [file.path, file]));
319
+ for (const path of changed.filter((one) => one.startsWith(prefix))) {
320
+ const write = writes.get(path);
321
+ if (write)
322
+ files.set(path, { path, oid: write.oid, bytes: write.bytes });
323
+ else
324
+ files.delete(path);
375
325
  }
376
- return out.sort(byName);
377
- };
326
+ const key = keyFile(name);
327
+ const keyText = writes.get(key)?.text;
328
+ // A link the change writes a file over, or deletes, is a link no more.
329
+ const links = (old?.links ?? []).filter((path) => !writes.has(path) && !deletes.has(path));
330
+ const item = learnedItem(name, [...files.values()], links, (path) => writes.get(path)?.text, {
331
+ order: 0,
332
+ history: touched.has(key) ? foldNewer(old?.history, commit) : (old?.history ?? { at: commit.at }),
333
+ run: runId && touched.has(viewFile(name)) ? runId : (old?.run ?? null),
334
+ }, keyText === undefined && old ? { description: old.description, status: old.status, ...(old.retired_from ? { retired_from: old.retired_from } : {}) } : undefined);
335
+ if (item)
336
+ workflows.push(item);
337
+ }
378
338
  const entry = change && isChange(commit) ? changeEntry(commit, PLACEHOLDER, changed) : undefined;
379
339
  const log = [...(entry ? [entry] : []), ...(before?.log ?? [])];
380
340
  const snapshot = {
381
- v: 1, main: PLACEHOLDER, at: commit.at, index, ...(audits ? { audits } : {}),
382
- notes: notes.sort(noteOrder), skills: learned("skill", before?.skills ?? []), workflows: learned("workflow", before?.workflows ?? []),
341
+ v: 1, main: PLACEHOLDER, at: commit.at, ...(corrections ? { corrections } : {}), ...(audits ? { audits } : {}),
342
+ workflows: workflows.sort(byName),
383
343
  log: log.slice(0, LOG_KEEP), log_more: Boolean(before?.log_more) || log.length > LOG_KEEP,
384
344
  };
385
345
  return { snapshot, changed };
@@ -390,8 +350,14 @@ const withMain = (snapshot, main) => JSON.parse(JSON.stringify(snapshot).replace
390
350
  export function learningWorkspace(place) {
391
351
  if (folderTestHooks.workspace)
392
352
  return folderTestHooks.workspace(place);
353
+ // A run's own process never opens a learning folder itself: its runner does, the claim's agent's (held.ts).
354
+ if (held())
355
+ return heldLearningFolder();
393
356
  return oneLearningWorkspace(place);
394
357
  }
358
+ /** What a learning folder's script run is, as a runner checks one a run's process asks of it (run-child-host.ts): its
359
+ * argv, the script's own environment, its deadline. */
360
+ export const LEARNING_SCRIPT = { file: () => SCRIPT_FILE, env: () => scriptEnv(), timeoutMs: () => SCRIPT_TIMEOUT_MS, ensure: (ws) => ensureScript(ws) };
395
361
  /** A learning folder this server cannot read or write: a link in it (`link`, its words naming it), or a backend that
396
362
  * cannot answer. Fails closed: nothing learned is read, nothing is written. */
397
363
  export class FolderUnreadable extends Error {
@@ -426,8 +392,6 @@ export class FolderBusy extends Error {
426
392
  /** A body that is not the snapshot's blob: the snapshot is read again once. */
427
393
  class Mismatch extends Error {
428
394
  }
429
- /** Whether `error` is a body that was not the snapshot's blob (a reader holding an older snapshot meets it). */
430
- export const isBodyMismatch = (error) => error instanceof Mismatch;
431
395
  const isOidField = (value) => typeof value === "string" && /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(value);
432
396
  /** The folder's snapshot, or undefined when there is none (no main yet: the agent never learned). One that does not
433
397
  * read as v1 throws. */
@@ -442,9 +406,9 @@ export async function readSnapshot(ws) {
442
406
  throw folderFailure(error);
443
407
  }
444
408
  const value = JSON.parse(Buffer.from(bytes).toString("utf8"));
445
- if (value?.v !== 1 || !isOidField(value.main) || !Array.isArray(value.notes) || !Array.isArray(value.skills) || !Array.isArray(value.workflows) || !Array.isArray(value.log) || !isOidField(value.index?.oid))
409
+ if (value?.v !== 1 || !isOidField(value.main) || !Array.isArray(value.workflows) || !Array.isArray(value.log) || (value.corrections !== undefined && !isOidField(value.corrections?.oid)) || (value.audits !== undefined && !isOidField(value.audits?.oid)))
446
410
  throw new Error("the learning folder's snapshot is not one this server reads (v1)");
447
- return value;
411
+ return { v: 1, main: value.main, at: value.at, ...(value.corrections ? { corrections: value.corrections } : {}), ...(value.audits ? { audits: value.audits } : {}), workflows: value.workflows, log: value.log, log_more: value.log_more };
448
412
  }
449
413
  /** Bodies already checked, by blob id: an oid names its bytes, so one read is good for every snapshot naming it. */
450
414
  const bodies = new Map();
@@ -531,10 +495,24 @@ export async function readRunDiff(ws, run) {
531
495
  throw new Error(`the learning folder's diff of ${run} is not one this server reads (v1)`);
532
496
  return diff;
533
497
  }
534
- /** The notes of a snapshot as the learning modules take them (buildIndex, mergeProblems): their front matter, no body. */
535
- export const snapshotNotes = (snapshot) => (snapshot?.notes ?? []).map((note) => ({ file: note.file, name: note.name, description: note.description, type: note.type, status: note.status, origin: note.origin, superseded_by: note.superseded_by, supersedes: [...note.supersedes], retired_from: note.status === "retired" ? (note.retired_from ?? "pending") : null, keys: [], body: "" }));
536
- /** Every name at main's top a snapshot knows: the index, the notes, and the learned folders' tops. */
537
- export const topOf = (snapshot) => (snapshot ? [INDEX_FILE, ...snapshot.notes.map((note) => note.file), ...(snapshot.skills.length ? [SKILLS_DIR] : []), ...(snapshot.workflows.length ? [WORKFLOWS_DIR] : [])] : []);
498
+ /** Run `runId`'s merge of `round` (readRunDiff), or undefined when it never merged here. A stop between a merge's commit
499
+ * and its diff file leaves main and the run's ref moved with no diff: when main's log names the run and the round has no
500
+ * diff, the script's `merged` writes the diff from the run's ref (one exec), and it is read. */
501
+ export async function runMergeOf(ws, runId, round = 1) {
502
+ const key = runDiffKey(runId, round);
503
+ const kept = await readRunDiff(ws, key);
504
+ if (kept || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(key))
505
+ return kept;
506
+ const named = (await readSnapshot(ws))?.log.some(({ by }) => "run" in by && by.run === runId);
507
+ if (!named)
508
+ return undefined;
509
+ const done = await runScript(ws, ["merged", key]);
510
+ if (done.code === 1)
511
+ return undefined;
512
+ if (done.code !== 0)
513
+ throw failed("merged", done);
514
+ return readRunDiff(ws, key);
515
+ }
538
516
  // ---------------------------------------------------------------------------------------------------------------------
539
517
  // Writing: the script, one exec a write.
540
518
  /** The script, as checked in (learning.sh beside this file), and the name it is written under in the folder. */
@@ -646,7 +624,7 @@ export async function commitChange(ws, base, change) {
646
624
  // A change that changes nothing on main is no commit: main stays, and nothing is run.
647
625
  if (base && change && !changed.length)
648
626
  return { landed: true, main: base.main, snapshot: base };
649
- const writes = change?.writes ?? [{ path: INDEX_FILE, text: "" }];
627
+ const writes = change?.writes ?? [];
650
628
  for (const { path } of writes)
651
629
  checkPath(path);
652
630
  for (const path of [...(change?.deletes ?? []), ...(change?.absent ?? []), ...(change?.same ?? []).map(({ path }) => path)])
@@ -680,6 +658,8 @@ export async function commitChange(ws, base, change) {
680
658
  }
681
659
  if (result.code === 5 && /^[0-9a-f]{40,64}$/.test(said))
682
660
  return { unaligned: true, main: said };
661
+ if (result.code === 6 && run && /^[0-9a-f]{40,64}$/.test(said))
662
+ return { merged: said };
683
663
  throw failed(args[0], result);
684
664
  }
685
665
  /** The snapshot rebuilt from main whole, and the working tree brought in line: the script's `read`, then its `snapshot`
@@ -752,15 +732,7 @@ export async function learningRepair(ws) {
752
732
  }
753
733
  throw new Error("the learning folder's main kept moving while its snapshot was rebuilt");
754
734
  }
755
- /** Whether `main` holds anything at `path`, as git stores it (any mode, any type): what the snapshot leaves out (a file
756
- * that is no note) included. A read through the script. */
757
- export async function heldOnMain(ws, main, path) {
758
- const result = await runScript(ws, ["has", main, checkPath(path)]);
759
- if (result.code !== 0 && result.code !== 1)
760
- throw failed("has", result);
761
- return result.code === 0;
762
- }
763
- /** The folder's first commit when it has no main yet (an empty MEMORY.md, the host's), and main's commit: through the
735
+ /** The folder's first commit when it has no main yet (an empty tree, the host's), and main's commit: through the
764
736
  * script's init, which makes the repository where there is none. A main with no snapshot (an init that stopped
765
737
  * before it) is repaired. */
766
738
  export async function learningInit(ws) {
@@ -793,12 +765,22 @@ export class FolderRefused extends Error {
793
765
  this.same = refused.same;
794
766
  }
795
767
  }
768
+ /** A run's merge (its round) that is on main already, made by another call (a reclaimed run racing its first claim, or
769
+ * a retry after a stop past its commit): `merge`, its commit. Nothing was written. */
770
+ export class FolderMerged extends Error {
771
+ merge;
772
+ constructor(merge) {
773
+ super(`the run merged on the learning folder's main already, at ${merge}`);
774
+ this.name = "FolderMerged";
775
+ this.merge = merge;
776
+ }
777
+ }
796
778
  /**
797
779
  * A write to the folder's main: `compute` reads the snapshot and the bodies it needs (as readLearning gives them) and
798
780
  * says what to write, or nothing (its result stands alone). Committed by commitChange; a main that moved under it, or
799
781
  * a body that changed as it was read, computes it again on the folder as it is then (WRITE_TRIES in all). A folder with
800
782
  * no main yet is made first (learningInit). A snapshot that is not main's is rebuilt (learningRepair). Throws
801
- * FolderRefused when a precondition fails on main.
783
+ * FolderRefused when a precondition fails on main, and FolderMerged when a run's merge (its round) is there already.
802
784
  */
803
785
  export async function writeLearning(ws, compute, maxTries = WRITE_TRIES) {
804
786
  for (let tries = 0;; tries++) {
@@ -828,6 +810,8 @@ export async function writeLearning(ws, compute, maxTries = WRITE_TRIES) {
828
810
  return { result: out.result, main: done.main, snapshot: done.snapshot };
829
811
  if ("refused" in done)
830
812
  throw new FolderRefused(done.refused);
813
+ if ("merged" in done)
814
+ throw new FolderMerged(done.merged);
831
815
  if ("unaligned" in done) {
832
816
  const repaired = await learningRepair(ws);
833
817
  return { result: out.result, main: done.main, ...(repaired ? { snapshot: repaired } : {}) };
@@ -1,7 +1,5 @@
1
- export { CAPS, checkNote, checkProposal, mergeProblems, printable, supersededBy, unstorable, type Base, type Change, type CheckInput, type Problem, type ProposalCheck, type ProposedNote, type Rule } from "./check.js";
2
- export { GRADE_CAPS, GRADE_RUBRIC, gradedFiles, gradedItems, gradePrompt, parseVerdict, shortMessage, UNREADABLE_REASON, CONTRADICTED_REASON, CONTRADICTED_TWICE_REASON, CONTRADICTION_ASK, type GradeInput, type IndexEntry, type NoteText, type Verdict, type VerdictItem } from "./grade.js";
1
+ export { CAPS, checkDraft, printable, unstorable, type Change, type DraftCheckInput, type Problem, type Rule } from "./check.js";
2
+ export { CORRECTIONS_CAP, CORRECTIONS_FILE, correctionLine, correctionsProblems, problemWords } from "./corrections.js";
3
3
  export { hiddenCharacter } from "./invisible.js";
4
- export { ANSWER_MAX, NOTE_BLOCK, parseReflection, reflectAgain, reflectDryRun, reflectPrompt, SKILL_BLOCK, WORKFLOW_BLOCK, type LearnedBlock, type Reflection } from "./reflect.js";
5
- export { activeNotes, approve, buildIndex, INDEX_BYTES, INDEX_FILE, INDEX_LINES, indexLine, loadedIndex, mergedNote, NOTE_FILE, NOTE_ORIGINS, NOTE_STATUSES, NOTE_TYPES, parseNoteFile, restore, retire, supersede, type LearnedNote, type NoteOrigin, type NoteStatus, type NoteType } from "./notes.js";
6
4
  export { learnedSecretShapes, MIN_SECRET, PRINT_MAX, redactLearned, redactSecrets, secretShapes, valueMatcher } from "./secrets.js";
7
- export { decodedStrings, draftDryRun, draftFiles, draftProblems, DRY_RUN_FAILED, frontKeys, frontMatter, held, isHeld, LEARNED_KEYS, LEARNED_MAX_TURNS, learnedFront, learnedName, learnedPlace, learnedStatus, NO_TOOL_LIST, readmeOf, released, restorable, restoredLearned, retiredFrom, retiredLearned, servedSkill, servedSkills, setsStatus, SKILL_NAME, SKILLS_DIR, skillProblems, statusOnOneLine, UNCLEAR_FRONT, unclearFront, WORKFLOW_NAME, WORKFLOWS_DIR, type DraftDryRun, type DraftProblem, type DraftReader, type LearnedPlace } from "./skills.js";
5
+ export { decodedStrings, draftDryRun, draftFiles, draftProblems, DRY_RUN_FAILED, frontKeys, frontMatter, held, isHeld, LEARNED_KEYS, LEARNED_MAX_TURNS, learnedFront, learnedPlace, learnedStatus, NO_TOOL_LIST, readmeOf, released, restorable, restoredLearned, retiredFrom, retiredLearned, setsStatus, statusOnOneLine, UNCLEAR_FRONT, unclearFront, WORKFLOW_NAME, WORKFLOWS_DIR, type DraftDryRun, type DraftProblem, type DraftReader, type LearnedPlace } from "./workflow-draft.js";
@@ -1,11 +1,8 @@
1
- // The server's learning code, as one surface: the note format (notes.ts), a skill's and a workflow draft's (skills.ts),
2
- // the checker (check.ts), the end-of-run prompt (reflect.ts), the grade's rubric, prompt and verdict (grade.ts), and the
3
- // hidden-character and secret matchers they use (invisible.ts, secrets.ts). SPEC.md, beside it, is the learning folder's contract. The rest of the server imports it
4
- // from here.
5
- export { CAPS, checkNote, checkProposal, mergeProblems, printable, supersededBy, unstorable } from "./check.js";
6
- export { GRADE_CAPS, GRADE_RUBRIC, gradedFiles, gradedItems, gradePrompt, parseVerdict, shortMessage, UNREADABLE_REASON, CONTRADICTED_REASON, CONTRADICTED_TWICE_REASON, CONTRADICTION_ASK } from "./grade.js";
1
+ // The server's learning code, as one surface: a workflow draft's format and checks (workflow-draft.ts, check.ts), the
2
+ // owner's corrections (corrections.ts), and the hidden-character and secret matchers they use (invisible.ts,
3
+ // secrets.ts). SPEC.md, beside it, is the learning folder's contract. The rest of the server imports it from here.
4
+ export { CAPS, checkDraft, printable, unstorable } from "./check.js";
5
+ export { CORRECTIONS_CAP, CORRECTIONS_FILE, correctionLine, correctionsProblems, problemWords } from "./corrections.js";
7
6
  export { hiddenCharacter } from "./invisible.js";
8
- export { ANSWER_MAX, NOTE_BLOCK, parseReflection, reflectAgain, reflectDryRun, reflectPrompt, SKILL_BLOCK, WORKFLOW_BLOCK } from "./reflect.js";
9
- export { activeNotes, approve, buildIndex, INDEX_BYTES, INDEX_FILE, INDEX_LINES, indexLine, loadedIndex, mergedNote, NOTE_FILE, NOTE_ORIGINS, NOTE_STATUSES, NOTE_TYPES, parseNoteFile, restore, retire, supersede } from "./notes.js";
10
7
  export { learnedSecretShapes, MIN_SECRET, PRINT_MAX, redactLearned, redactSecrets, secretShapes, valueMatcher } from "./secrets.js";
11
- export { decodedStrings, draftDryRun, draftFiles, draftProblems, DRY_RUN_FAILED, frontKeys, frontMatter, held, isHeld, LEARNED_KEYS, LEARNED_MAX_TURNS, learnedFront, learnedName, learnedPlace, learnedStatus, NO_TOOL_LIST, readmeOf, released, restorable, restoredLearned, retiredFrom, retiredLearned, servedSkill, servedSkills, setsStatus, SKILL_NAME, SKILLS_DIR, skillProblems, statusOnOneLine, UNCLEAR_FRONT, unclearFront, WORKFLOW_NAME, WORKFLOWS_DIR } from "./skills.js";
8
+ export { decodedStrings, draftDryRun, draftFiles, draftProblems, DRY_RUN_FAILED, frontKeys, frontMatter, held, isHeld, LEARNED_KEYS, LEARNED_MAX_TURNS, learnedFront, learnedPlace, learnedStatus, NO_TOOL_LIST, readmeOf, released, restorable, restoredLearned, retiredFrom, retiredLearned, setsStatus, statusOnOneLine, UNCLEAR_FRONT, unclearFront, WORKFLOW_NAME, WORKFLOWS_DIR } from "./workflow-draft.js";
@@ -8,11 +8,15 @@
8
8
  # The host computes everything it can (the tree, the front matter, the history, the log, the snapshot) and hands it in;
9
9
  # this script does the git plumbing, the file writes and the atomic swap, in this order, and nothing else:
10
10
  # 1. the commit: `git fast-import` writes the blobs and ONE commit on a temporary ref, then
11
- # `update-ref refs/heads/main <new> <old>`, the compare and swap. A lost race exits 3 and writes nothing;
12
- # 2. the working tree brought in line with the new main (read-tree -u --reset);
13
- # 3. for a run's merge, `.agentrun/diffs/<run>.json`: each path's patch, parent against merge, as git diffs it;
11
+ # `update-ref refs/heads/main <new> <old>`, the compare and swap. A lost race exits 3 and writes nothing. A run's
12
+ # merge also creates `refs/agentrun/runs/<run>` in the same ref transaction, so a run (and round) merges once: a
13
+ # second merge of it, however it raced the first, exits 6 and writes nothing but the first one's diff file when a
14
+ # stop left it none;
15
+ # 2. for a run's merge, `.agentrun/diffs/<run>.json`: each path's patch, parent against merge, as git diffs it;
16
+ # 3. the working tree brought in line with the new main (read-tree -u --reset);
14
17
  # 4. `.agentrun/snapshot.json`, written to a temporary name and moved into place, LAST.
15
- # So a reader that finds snapshot.json finds every file it names at its main, or a newer one (a write in flight).
18
+ # So a reader that finds snapshot.json finds every file it names at its main, or a newer one (a write in flight). A stop
19
+ # between 1 and 2 leaves a run's ref with no diff file: `merged` (and a second merge's exit 6) writes it from the ref.
16
20
  #
17
21
  # Ops:
18
22
  # init make the folder a repository when it is not one, then commit as `commit` does with no parent;
@@ -21,7 +25,8 @@
21
25
  # snapshot <main> the working tree and snapshot.json written again at <main>, which must be main (else 3)
22
26
  # read [commit] main's (or <commit>'s) tree, its first-parent log and its blobs, for the host to build a
23
27
  # snapshot from; 1 when <commit> is not in the repository
24
- # has <main> <path> whether <main> holds anything at <path>, any mode, any type (0 yes, 1 no)
28
+ # merged <run> run <run>'s merge (its ref) on stdout, its diff file written from it when there is none; 1
29
+ # when the run never merged here
25
30
  # stdin, for init, commit and snapshot: header lines, a blank line, then (init and commit) a fast-import stream:
26
31
  # ref <name> the temporary ref the stream commits on (refs/agentrun/import-<hex>)
27
32
  # snapshot <json> snapshot.json, one line, where a \001M\001 stands for the new main
@@ -29,7 +34,8 @@
29
34
  # absent <path> <path> must not be on <old>, any mode, any type (else 4: "absent <path>" on stdout)
30
35
  # same <commit> <path> <path> must be the same on <commit> as on <old> (else 4: "same <path>" on stdout)
31
36
  # Exit: 0 done (the new main on stdout), 3 stale (main as it is on stdout), 4 a precondition failed, 5 main moved but
32
- # the files could not be brought in line (the new main on stdout; no snapshot written), else git's error on stderr.
37
+ # the files could not be brought in line (the new main on stdout; no snapshot written), 6 the run merged already (its
38
+ # merge on stdout), else git's error on stderr.
33
39
  set -u
34
40
  set -f
35
41
 
@@ -226,6 +232,16 @@ write_diff() {
226
232
  mv -f "$out" ".agentrun/diffs/$1.json" || die "the diff could not be moved into place"
227
233
  }
228
234
 
235
+ # Run $1's diff file, written from its merge $2 (its ref) when a stop between the merge and the diff left none: every
236
+ # path the merge changed against its parent (a run's merge has one). Ends the op: $old, $new and the header are reused.
237
+ diff_of_ref() {
238
+ [ -f ".agentrun/diffs/$1.json" ] && return 0
239
+ new=$2
240
+ old=$(g rev-parse -q --verify "$2^1^{commit}") || die "run $1's merge has no parent"
241
+ g diff-tree -r --no-renames --no-commit-id --name-only "$old" "$new" | sed 's/^/path /' > "$tmp/head" || die "git diff-tree failed"
242
+ write_diff "$1"
243
+ }
244
+
229
245
  commit() {
230
246
  take_stdin
231
247
  ref=$(sed -n 's/^ref //p' "$tmp/head")
@@ -251,7 +267,16 @@ commit() {
251
267
  paths_of "$new"
252
268
  fi
253
269
  no_links
254
- if ! g update-ref -m learning refs/heads/main "$new" "${old:-$ZERO}" 2> "$tmp/cas"; then
270
+ # One ref transaction: main's compare and swap and, for a run's merge, its run's ref made new (git refuses one that is
271
+ # there), both or neither.
272
+ printf 'update refs/heads/main %s %s\n' "$new" "${old:-$ZERO}" > "$tmp/refs"
273
+ [ -n "$run" ] && printf 'create refs/agentrun/runs/%s %s\n' "$run" "$new" >> "$tmp/refs"
274
+ if ! g update-ref -m learning --stdin < "$tmp/refs" 2> "$tmp/cas"; then
275
+ if [ -n "$run" ] && merged=$(g rev-parse -q --verify "refs/agentrun/runs/$run^{commit}" 2> /dev/null); then
276
+ diff_of_ref "$run" "$merged"
277
+ printf '%s\n' "$merged"
278
+ exit 6
279
+ fi
255
280
  cur=$(main_now)
256
281
  if [ "$cur" != "$old" ]; then
257
282
  printf '%s\n' "$cur"
@@ -260,12 +285,14 @@ commit() {
260
285
  cat "$tmp/cas" >&2
261
286
  exit 2
262
287
  fi
288
+ [ "${AGENTRUN_LEARNING_FAIL:-}" = before-diff ] && die "failed before the diff, as the test asked"
289
+ # The diff before the working tree: a merge whose files could not be brought in line (exit 5) keeps its diff.
290
+ [ -n "$run" ] && write_diff "$run"
263
291
  if ! check_out "$new"; then
264
292
  cat "$tmp/checkout" >&2
265
293
  printf '%s\n' "$new"
266
294
  exit 5
267
295
  fi
268
- [ -n "$run" ] && write_diff "$run"
269
296
  stage_snapshot "$new"
270
297
  place_snapshot
271
298
  printf '%s\n' "$new"
@@ -351,14 +378,17 @@ case $op in
351
378
  for path in "$@"; do printf '%s:%s\n' "$commit" "$path" >> "$tmp/want"; done
352
379
  g cat-file --batch < "$tmp/want" || die "cat-file failed"
353
380
  ;;
354
- has)
355
- main=${2:-}
356
- path=${3:-}
357
- hex40 "$main" || die "has takes a main"
358
- [ -n "$path" ] || die "has takes a path"
359
- g cat-file -e "$main:$path" 2> /dev/null || exit 1
381
+ merged)
382
+ run=${2:-}
383
+ case $run in
384
+ '' | *[!A-Za-z0-9._-]*) die "merged takes a run id" ;;
385
+ esac
386
+ [ -d "$GIT_DIR" ] || exit 1
387
+ merge=$(g rev-parse -q --verify "refs/agentrun/runs/$run^{commit}" 2> /dev/null) || exit 1
388
+ diff_of_ref "$run" "$merge"
389
+ printf '%s\n' "$merge"
360
390
  ;;
361
391
  *)
362
- die "no op $op: init, commit, snapshot, read, show or has"
392
+ die "no op $op: init, commit, snapshot, read, show or merged"
363
393
  ;;
364
394
  esac