@parcha/agentrun-serve 0.1.0-beta.51 → 0.1.0-beta.53

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 (322) hide show
  1. package/CHANGELOG.md +160 -1
  2. package/README.md +306 -36
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +14 -4
  5. package/dist/agent-delete.js +30 -58
  6. package/dist/agent-package.d.ts +71 -0
  7. package/dist/agent-package.js +345 -0
  8. package/dist/agents-store.d.ts +28 -18
  9. package/dist/agents-store.js +48 -34
  10. package/dist/api-only.d.ts +30 -8
  11. package/dist/api-only.js +40 -16
  12. package/dist/archil-routes.d.ts +1 -0
  13. package/dist/archil-routes.js +28 -2
  14. package/dist/claude-login.d.ts +1 -0
  15. package/dist/claude-login.js +1 -1
  16. package/dist/cli-learning/cli.d.ts +3 -0
  17. package/dist/cli-learning/cli.js +17 -3
  18. package/dist/cli-learning/connections.js +3 -2
  19. package/dist/cli-learning/schema.js +2 -1
  20. package/dist/cli.js +70 -7
  21. package/dist/composio-preset.d.ts +2 -1
  22. package/dist/composio-preset.js +4 -3
  23. package/dist/composio-triggers.d.ts +4 -0
  24. package/dist/composio-triggers.js +4 -1
  25. package/dist/computer-needs.d.ts +32 -0
  26. package/dist/computer-needs.js +80 -0
  27. package/dist/computer-setting.d.ts +9 -0
  28. package/dist/computer-setting.js +19 -1
  29. package/dist/computers.d.ts +6 -2
  30. package/dist/computers.js +2 -2
  31. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  32. package/dist/console/assets/index-DbilxljH.css +1 -0
  33. package/dist/console/index.html +2 -2
  34. package/dist/console-links.d.ts +1 -0
  35. package/dist/console-links.js +2 -0
  36. package/dist/env-switch.d.ts +14 -0
  37. package/dist/env-switch.js +23 -0
  38. package/dist/errors.d.ts +1 -0
  39. package/dist/errors.js +3 -0
  40. package/dist/eval-previous.js +4 -3
  41. package/dist/fal-price.d.ts +76 -0
  42. package/dist/fal-price.js +365 -0
  43. package/dist/handed-secret.d.ts +4 -0
  44. package/dist/handed-secret.js +10 -0
  45. package/dist/harness-archive.d.ts +15 -5
  46. package/dist/harness-archive.js +71 -34
  47. package/dist/harness-check.d.ts +2 -1
  48. package/dist/harness-check.js +36 -95
  49. package/dist/harness-egress.d.ts +23 -0
  50. package/dist/harness-egress.js +69 -0
  51. package/dist/harness-recipe-entry.d.ts +71 -0
  52. package/dist/harness-recipe-entry.js +184 -0
  53. package/dist/harness-recipe.d.ts +73 -6
  54. package/dist/harness-recipe.js +185 -31
  55. package/dist/harness-sign-in.d.ts +29 -0
  56. package/dist/harness-sign-in.js +122 -0
  57. package/dist/harness-table.d.ts +21 -0
  58. package/dist/harness-table.js +58 -3
  59. package/dist/harness-zip.d.ts +6 -0
  60. package/dist/harness-zip.js +203 -0
  61. package/dist/ids.d.ts +11 -0
  62. package/dist/ids.js +36 -0
  63. package/dist/learn/commit.d.ts +19 -1
  64. package/dist/learn/commit.js +160 -2
  65. package/dist/learn/compile.d.ts +13 -5
  66. package/dist/learn/compile.js +46 -15
  67. package/dist/learn/delete.d.ts +12 -6
  68. package/dist/learn/delete.js +17 -11
  69. package/dist/learn/folder.d.ts +16 -0
  70. package/dist/learn/folder.js +30 -4
  71. package/dist/learn/learning-of.d.ts +8 -0
  72. package/dist/learn/learning-of.js +8 -0
  73. package/dist/learn/learning.sh +29 -4
  74. package/dist/learn/promote.d.ts +51 -7
  75. package/dist/learn/promote.js +51 -8
  76. package/dist/learn/secrets.js +30 -7
  77. package/dist/learning-reset.d.ts +18 -0
  78. package/dist/learning-reset.js +115 -0
  79. package/dist/learning-routes.d.ts +23 -11
  80. package/dist/learning-routes.js +110 -20
  81. package/dist/learning-words.d.ts +5 -0
  82. package/dist/learning-words.js +5 -0
  83. package/dist/learning.d.ts +15 -10
  84. package/dist/learning.js +14 -8
  85. package/dist/llms.txt +1 -0
  86. package/dist/mcp-gateway.d.ts +39 -2
  87. package/dist/mcp-gateway.js +56 -12
  88. package/dist/mcp-pin-first.js +1 -1
  89. package/dist/mcp-probe.d.ts +3 -0
  90. package/dist/mcp-probe.js +7 -2
  91. package/dist/mcp-resources.d.ts +44 -0
  92. package/dist/mcp-resources.js +100 -0
  93. package/dist/mcp-servers-store.d.ts +17 -12
  94. package/dist/mcp-servers-store.js +2 -1
  95. package/dist/media-duration.d.ts +2 -0
  96. package/dist/media-duration.js +136 -0
  97. package/dist/model.d.ts +4 -4
  98. package/dist/model.js +6 -6
  99. package/dist/native/cli.js +9 -2
  100. package/dist/native/connection.d.ts +2 -2
  101. package/dist/native/connection.js +5 -2
  102. package/dist/native/discovery.d.ts +2 -0
  103. package/dist/native/discovery.js +10 -6
  104. package/dist/native/remote-worker-bridge.js +36 -4
  105. package/dist/native/remote.d.ts +18 -1
  106. package/dist/native/remote.js +126 -37
  107. package/dist/native/schema.d.ts +6 -0
  108. package/dist/native/schema.js +31 -6
  109. package/dist/native/source-account.d.ts +13 -0
  110. package/dist/native/source-account.js +114 -0
  111. package/dist/native/source-capture-hooks.d.ts +5 -0
  112. package/dist/native/source-capture-hooks.js +102 -0
  113. package/dist/native/source-mcp-selection.d.ts +13 -0
  114. package/dist/native/source-mcp-selection.js +72 -0
  115. package/dist/native/source-runtime-tools.d.ts +19 -0
  116. package/dist/native/source-runtime-tools.js +103 -0
  117. package/dist/native/source-snapshot-types.d.ts +138 -0
  118. package/dist/native/source-snapshot-types.js +12 -0
  119. package/dist/native/source-snapshot.d.ts +8 -0
  120. package/dist/native/source-snapshot.js +1201 -0
  121. package/dist/observation/learning.js +3 -2
  122. package/dist/openapi.js +211 -47
  123. package/dist/print.js +1 -1
  124. package/dist/provider.d.ts +8 -0
  125. package/dist/provider.js +14 -2
  126. package/dist/purged-workflow.d.ts +12 -0
  127. package/dist/purged-workflow.js +43 -0
  128. package/dist/refusal-words.d.ts +0 -3
  129. package/dist/refusal-words.js +0 -3
  130. package/dist/request-metadata.d.ts +20 -0
  131. package/dist/request-metadata.js +24 -0
  132. package/dist/run-keys.d.ts +46 -0
  133. package/dist/run-keys.js +109 -0
  134. package/dist/run-launch.d.ts +29 -5
  135. package/dist/run-launch.js +44 -4
  136. package/dist/run-learning-served.d.ts +2 -2
  137. package/dist/run-model-key.d.ts +2 -2
  138. package/dist/run-model-key.js +5 -5
  139. package/dist/run-secrets.d.ts +2 -0
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-usage.d.ts +48 -4
  142. package/dist/run-usage.js +156 -39
  143. package/dist/run-view.d.ts +18 -1
  144. package/dist/run-view.js +28 -8
  145. package/dist/runner/adapter-loop.d.ts +14 -4
  146. package/dist/runner/adapter-loop.js +150 -31
  147. package/dist/runner/adapter-run-spec.d.ts +1 -1
  148. package/dist/runner/adapter-run-spec.js +35 -22
  149. package/dist/runner/audit.d.ts +10 -3
  150. package/dist/runner/audit.js +30 -7
  151. package/dist/runner/beside.js +2 -1
  152. package/dist/runner/claim-secrets.d.ts +31 -4
  153. package/dist/runner/claim-secrets.js +43 -7
  154. package/dist/runner/cli-run-spec.d.ts +1 -1
  155. package/dist/runner/cli-run-spec.js +32 -20
  156. package/dist/runner/conformance/harness.js +4 -2
  157. package/dist/runner/dispatch.js +4 -2
  158. package/dist/runner/harness-loops.d.ts +6 -0
  159. package/dist/runner/harness-loops.js +16 -3
  160. package/dist/runner/held.d.ts +4 -0
  161. package/dist/runner/journal-kinds.d.ts +5 -0
  162. package/dist/runner/learned-first.d.ts +2 -0
  163. package/dist/runner/learned-first.js +1 -1
  164. package/dist/runner/learning-end.d.ts +9 -3
  165. package/dist/runner/learning-end.js +66 -29
  166. package/dist/runner/learning-seed.d.ts +9 -3
  167. package/dist/runner/learning-seed.js +2 -2
  168. package/dist/runner/main.d.ts +1 -0
  169. package/dist/runner/main.js +20 -13
  170. package/dist/runner/mcp-claim.js +7 -2
  171. package/dist/runner/mcp-run.d.ts +12 -0
  172. package/dist/runner/mcp-run.js +14 -1
  173. package/dist/runner/model-route.js +7 -4
  174. package/dist/runner/monid-run.js +9 -11
  175. package/dist/runner/project-checkpoint.d.ts +35 -0
  176. package/dist/runner/project-checkpoint.js +116 -0
  177. package/dist/runner/project-drain.d.ts +8 -0
  178. package/dist/runner/project-drain.js +25 -0
  179. package/dist/runner/project-host.d.ts +10 -0
  180. package/dist/runner/project-host.js +52 -0
  181. package/dist/runner/promotion.d.ts +51 -24
  182. package/dist/runner/promotion.js +206 -78
  183. package/dist/runner/redact.d.ts +13 -0
  184. package/dist/runner/redact.js +67 -1
  185. package/dist/runner/run-channel.d.ts +9 -0
  186. package/dist/runner/run-channel.js +15 -2
  187. package/dist/runner/run-child-host.d.ts +8 -4
  188. package/dist/runner/run-child-host.js +174 -42
  189. package/dist/runner/run-errors.js +2 -2
  190. package/dist/runner/runner-check.js +5 -2
  191. package/dist/runner/runner.js +41 -12
  192. package/dist/runner/sdk-loop.d.ts +2 -2
  193. package/dist/runner/sdk-loop.js +3 -3
  194. package/dist/runner/store-port.d.ts +3 -0
  195. package/dist/runner/store-secrets.js +7 -3
  196. package/dist/runner/workflow-first.d.ts +4 -0
  197. package/dist/runner/workflow-first.js +13 -0
  198. package/dist/runner/workflow-loop.d.ts +2 -1
  199. package/dist/runner/workflow-loop.js +2 -1
  200. package/dist/runner/workflow-spec.js +4 -4
  201. package/dist/runs-over-store.d.ts +39 -8
  202. package/dist/runs-over-store.js +147 -32
  203. package/dist/sdk/check.d.ts +6 -5
  204. package/dist/sdk/check.js +17 -16
  205. package/dist/sdk/runs.d.ts +11 -1
  206. package/dist/sdk/runs.js +185 -78
  207. package/dist/sdk/schema.js +12 -2
  208. package/dist/sdk/workflows.d.ts +1 -1
  209. package/dist/server.d.ts +68 -32
  210. package/dist/server.js +678 -124
  211. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  212. package/dist/source-sync/adoption.d.ts +15 -0
  213. package/dist/source-sync/adoption.js +36 -0
  214. package/dist/source-sync/auxiliary.d.ts +23 -0
  215. package/dist/source-sync/auxiliary.js +64 -0
  216. package/dist/source-sync/capture-git.d.ts +5 -0
  217. package/dist/source-sync/capture-git.js +272 -0
  218. package/dist/source-sync/capture-project.d.ts +53 -0
  219. package/dist/source-sync/capture-project.js +206 -0
  220. package/dist/source-sync/capture-refusal.d.ts +7 -0
  221. package/dist/source-sync/capture-refusal.js +16 -0
  222. package/dist/source-sync/capture.d.ts +11 -0
  223. package/dist/source-sync/capture.js +22 -0
  224. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  225. package/dist/source-sync/checkpoint-gate.js +52 -0
  226. package/dist/source-sync/checkpoints.d.ts +66 -0
  227. package/dist/source-sync/checkpoints.js +168 -0
  228. package/dist/source-sync/claim.d.ts +11 -0
  229. package/dist/source-sync/claim.js +48 -0
  230. package/dist/source-sync/destination.d.ts +47 -0
  231. package/dist/source-sync/destination.js +239 -0
  232. package/dist/source-sync/io.d.ts +15 -0
  233. package/dist/source-sync/io.js +52 -0
  234. package/dist/source-sync/local.d.ts +43 -0
  235. package/dist/source-sync/local.js +229 -0
  236. package/dist/source-sync/prepare.d.ts +59 -0
  237. package/dist/source-sync/prepare.js +93 -0
  238. package/dist/source-sync/projects.d.ts +61 -0
  239. package/dist/source-sync/projects.js +130 -0
  240. package/dist/source-sync/registry.d.ts +95 -0
  241. package/dist/source-sync/registry.js +226 -0
  242. package/dist/source-sync/service.d.ts +33 -0
  243. package/dist/source-sync/service.js +118 -0
  244. package/dist/source-sync/skill-edits.d.ts +12 -0
  245. package/dist/source-sync/skill-edits.js +122 -0
  246. package/dist/source-sync/snapshots.d.ts +48 -0
  247. package/dist/source-sync/snapshots.js +448 -0
  248. package/dist/source-sync/types.d.ts +9 -0
  249. package/dist/source-sync/types.js +14 -0
  250. package/dist/source-sync/workspace.d.ts +66 -0
  251. package/dist/source-sync/workspace.js +273 -0
  252. package/dist/store/agent-body.d.ts +8 -0
  253. package/dist/store/agent-body.js +20 -6
  254. package/dist/store/index.d.ts +2 -2
  255. package/dist/store/index.js +1 -1
  256. package/dist/store/journal/storage.d.ts +2 -0
  257. package/dist/store/journal/storage.js +2 -1
  258. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  259. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  260. package/dist/store/schema.d.ts +15 -1
  261. package/dist/store/schema.js +43 -4
  262. package/dist/store/seal.d.ts +5 -1
  263. package/dist/store/seal.js +12 -3
  264. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  265. package/dist/store/sqlite/project-checkpoints.js +70 -0
  266. package/dist/store/sqlite/run-launch.d.ts +14 -0
  267. package/dist/store/sqlite/run-launch.js +58 -7
  268. package/dist/store/sqlite/run-patch.d.ts +2 -1
  269. package/dist/store/sqlite/run-patch.js +4 -3
  270. package/dist/store/sqlite/store.js +319 -153
  271. package/dist/store/store-schema.js +2 -2
  272. package/dist/store/store.d.ts +173 -33
  273. package/dist/store/store.js +14 -1
  274. package/dist/store-reads/learning.d.ts +12 -8
  275. package/dist/store-reads/learning.js +33 -24
  276. package/dist/store-reads/loop.d.ts +4 -3
  277. package/dist/store-reads/loop.js +7 -5
  278. package/dist/store-view.d.ts +3 -1
  279. package/dist/store-view.js +17 -5
  280. package/dist/template-eval.js +4 -4
  281. package/dist/template-import.d.ts +10 -2
  282. package/dist/template-import.js +116 -13
  283. package/dist/templates.d.ts +29 -5
  284. package/dist/templates.js +68 -14
  285. package/dist/timeline/index.d.ts +1 -1
  286. package/dist/timeline/index.js +1 -1
  287. package/dist/timeline/labels.js +1 -1
  288. package/dist/timeline/timeline.d.ts +5 -0
  289. package/dist/timeline/timeline.js +8 -0
  290. package/dist/tool-plane.d.ts +12 -12
  291. package/dist/tools.d.ts +8 -8
  292. package/dist/tools.js +1 -1
  293. package/dist/trigger-launch-hook.d.ts +47 -0
  294. package/dist/trigger-launch-hook.js +90 -0
  295. package/dist/trigger-targets.d.ts +14 -1
  296. package/dist/trigger-targets.js +20 -0
  297. package/dist/triggers.d.ts +54 -5
  298. package/dist/triggers.js +143 -8
  299. package/dist/uploads-archil.js +2 -1
  300. package/dist/uploads.d.ts +0 -3
  301. package/dist/uploads.js +2 -11
  302. package/dist/validate.js +4 -1
  303. package/dist/web-save.d.ts +3 -0
  304. package/dist/web-save.js +17 -2
  305. package/dist/workspace/archil-exec.js +1 -1
  306. package/dist/workspace/archil.js +1 -1
  307. package/dist/workspace/computer-for-claim.d.ts +2 -0
  308. package/dist/workspace/computer-for-claim.js +43 -0
  309. package/dist/workspace/paths.d.ts +6 -0
  310. package/dist/workspace/paths.js +6 -0
  311. package/dist/workspace/resolve-computer.d.ts +1 -0
  312. package/dist/workspace/revision-skills.js +24 -11
  313. package/dist/workspace/run-tools.d.ts +2 -0
  314. package/dist/workspace/run-tools.js +8 -0
  315. package/dist/workspace/synced-folder.d.ts +3 -3
  316. package/dist/workspace/synced-folder.js +7 -6
  317. package/launcher/agentrun-serve +1 -1
  318. package/package.json +10 -10
  319. package/skills/agentrun-serve/SKILL.md +2 -1
  320. package/templates/README.md +5 -2
  321. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  322. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -10,10 +10,10 @@ import { DatabaseSync } from "node:sqlite";
10
10
  import { backfillNativeCommandOwners, nativeCommandOwner, validConnectorId } from '../native-command-owner.js';
11
11
  import { watchCommandsAt, wakeCommands } from "../command-wake.js";
12
12
  import { claimFence, storeNow } from "../fence.js";
13
- import { RunStorage } from "../journal/storage.js";
13
+ import { JOURNAL_FIRST_ID, RunStorage } from "../journal/storage.js";
14
14
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
15
- import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNNERS_ADDED, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
16
- import { AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, tombstoneMetrics, } from "../store.js";
15
+ import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
16
+ import { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, UPLOAD_PREFIX, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, tombstoneMetrics, } from "../store.js";
17
17
  /** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
18
18
  const madeOf = (body) => {
19
19
  for (const link of ["replay", "audit"]) {
@@ -33,9 +33,38 @@ import { cleanText, settledBody } from "../dialect.js";
33
33
  import { inMemory } from "./memory.js";
34
34
  import { Connection, DEFAULT_BUSY_TIMEOUT_MS } from "./connection.js";
35
35
  import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
36
- import { readLaunch, readLearningStarts, readUsageMetadata, writeLaunch, writeLaunchSealed } from "./run-launch.js";
36
+ import { launchDiskOf, readableJson, readLaunch, readLearningStarts, readSeededBefore, readUsageMetadata, writeLaunch, writeLaunchSealed } from "./run-launch.js";
37
37
  import { canonical } from "../agent-body.js";
38
+ import { readProjectCheckpoints } from "./project-checkpoints.js";
38
39
  import { aadOf, sealedAt } from "../seal.js";
40
+ /** Registry writers UPDATE/DELETE this same row, so a prepared cutover and a credential/catalog edit serialize. */
41
+ async function checkMcpGuards(tx, d, guards = []) {
42
+ const names = [...new Set(guards.map(guard => guard.name))].sort();
43
+ for (const name of names)
44
+ await d.lockRow(tx, "mcp_servers", "name", name);
45
+ for (const guard of guards) {
46
+ const row = await tx.get("SELECT url, auth, credential_changed_at, tools, sealed FROM mcp_servers WHERE name = ?", guard.name);
47
+ const sameSealed = row !== undefined && (row.sealed === null || guard.sealed === null
48
+ ? row.sealed === guard.sealed : Buffer.from(row.sealed).equals(Buffer.from(guard.sealed)));
49
+ if (!row || row.url !== guard.url || row.auth !== guard.auth || row.credential_changed_at !== guard.credentialChangedAt
50
+ || canonical(JSON.parse(row.tools)) !== canonical(guard.tools) || !sameSealed)
51
+ throw new StoreConstraint("An MCP server changed before the revision was saved. Prepare its tools and credentials again.");
52
+ }
53
+ }
54
+ /** Source authorization and admission share one transaction. Keep the settings locks before any agent/trigger/run
55
+ * lock, in stable key order, so revocation either commits first and refuses admission or follows its completed write. */
56
+ async function checkSettingsGuards(tx, guards = [], message = "The source grant changed before the write committed.", alsoLock = []) {
57
+ const byKey = new Map();
58
+ for (const guard of guards)
59
+ byKey.set(guard.key, [...(byKey.get(guard.key) ?? []), guard]);
60
+ for (const key of [...new Set([...byKey.keys(), ...alsoLock])].sort((a, b) => a.localeCompare(b))) {
61
+ const setting = await tx.get("UPDATE settings SET value = value WHERE key = ? RETURNING value", key);
62
+ const value = setting === undefined ? undefined : JSON.parse(setting.value);
63
+ if ((byKey.get(key) ?? []).some(guard => !value || Object.entries(guard.fields).some(([field, expected]) => JSON.stringify(value[field]) !== JSON.stringify(expected)))) {
64
+ throw new StoreConstraint(message);
65
+ }
66
+ }
67
+ }
39
68
  /** A claim's length when the caller names none. */
40
69
  export const DEFAULT_LEASE_MS = 30_000;
41
70
  /** The store's file in its data directory: only the store names it. */
@@ -52,9 +81,11 @@ const listingBehind = (now) => ({
52
81
  params: (at) => [...at, ...at],
53
82
  });
54
83
  const FIRING_COLUMNS = "trigger_id, key, by, nominal_at, status, at, run_id, reason, error, count, attempts, retry_at, payload, attrs, notified, catch_up, paused, shown, waits_on";
84
+ /** A sent firing's retry_at is its startBy (settle's one exception), never a retry. */
55
85
  const firingOf = (r) => ({
56
86
  triggerId: r.trigger_id, key: r.key, by: r.by ?? "manual", nominalAt: r.nominal_at ?? r.at, status: r.status, at: r.at, runId: r.run_id, reason: r.reason,
57
- error: r.error === null ? null : JSON.parse(r.error), count: r.count, attempts: r.attempts, retryAt: r.retry_at, payload: r.payload,
87
+ error: r.error === null ? null : JSON.parse(r.error), count: r.count, attempts: r.attempts, retryAt: r.status === "sent" ? null : r.retry_at,
88
+ startBy: r.status === "sent" ? r.retry_at : null, payload: r.payload,
58
89
  attrs: r.attrs === null ? null : JSON.parse(r.attrs), notified: r.notified === 1, catchUp: r.catch_up === 1, paused: r.paused === 1, shown: r.shown !== 0, waitsOn: r.waits_on,
59
90
  });
60
91
  /** The trigger's patch as columns: name -> [column, value]. */
@@ -102,7 +133,7 @@ const claimableIn = (d, n) => ({
102
133
  (wake_at IS NOT NULL AND wake_at <= ${n.sql})
103
134
  OR EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind IN ('stop', 'cancel'))
104
135
  OR ((backoff_until IS NULL OR backoff_until <= ${n.sql}) AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL
105
- AND ${d.jsonNotFalse("commands.body", ["answers"])})))))`,
136
+ AND ${d.jsonNotFalse(readableJson(d, "commands.body"), ["answers"])})))))`,
106
137
  params: [...n.params, ...n.params, ...n.params, ...n.params, ...n.params],
107
138
  });
108
139
  /** What a claim sets: the next epoch, the runner and its lease (from `n`, the deadlines' clock, plus a lease in ms), running,
@@ -169,6 +200,10 @@ const mcpPinOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.mcp_pin), pinnedA
169
200
  const settingOf = (r) => ({ key: r.key, value: JSON.parse(r.value), updatedAt: r.updated_at });
170
201
  const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), updatedAt: r.updated_at });
171
202
  const orNull = (value) => (value === null ? null : Number(value));
203
+ const attemptOf = (r) => ({
204
+ runId: r.run_id, epoch: Number(r.epoch), turn: Number(r.turn), attempt: Number(r.attempt), cause: r.cause, cut: r.cut,
205
+ runner: r.runner, from: r.from_state, journalFrom: Number(r.journal_from), claimedAt: Number(r.claimed_at),
206
+ });
172
207
  const intervalOf = (r) => ({
173
208
  runId: r.run_id, provider: r.provider, providerId: r.provider_id, kind: r.kind, gpuType: r.gpu_type, gpuCount: orNull(r.gpu_count), cpus: orNull(r.cpus),
174
209
  memoryMb: orNull(r.memory_mb), diskGb: orNull(r.disk_gb), startedAt: Number(r.started_at), kept: Number(r.kept) === 1, endedAt: orNull(r.ended_at), bookedMs: Number(r.booked_ms),
@@ -210,6 +245,7 @@ export const SQLITE_RUNNER_NEEDS = [
210
245
  { table: "runners", columns: ["host"], why: "keep each runner's word that it is there and its relay in one table (runners)" },
211
246
  { table: "runners", columns: Object.keys(RUNNERS_ADDED), why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
212
247
  { table: "hand_backs", columns: ["run_id"], why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
248
+ { table: "run_attempts", columns: ["run_id"], why: "keep each claim's turn and attempt (run_attempts)" },
213
249
  ];
214
250
  /** What a runner of this build waits for on a file of this version (SQLITE_RUNNER_NEEDS' first missing column's `why`),
215
251
  * or undefined when it opens; `columnsOf` reads a table's columns. */
@@ -345,8 +381,9 @@ export async function openSqliteStore(options) {
345
381
  // in one durable write once the columns an earlier build of 11 lacked are in, every run behind until its lister builds
346
382
  // it. Version 12 names no minting runner on a machine's token and keeps no runner's relay: the server adds them
347
383
  // (schema.ts relayUpgrade). Version 13 keeps no purge time on a run or an agent: the server adds them (schema.ts
348
- // purgeUpgrade). A runner refuses 11, 12 and 13 until that server has.
349
- const upgrading = found === 11 || found === 12 || found === 13;
384
+ // purgeUpgrade). Version 14 keeps no disk on a run: the server adds it and writes each run's from its launch (schema.ts
385
+ // diskUpgrade). A runner refuses 11 to 14 until that server has.
386
+ const upgrading = found === 11 || found === 12 || found === 13 || found === 14;
350
387
  if (upgrading && role === "runner")
351
388
  throw new StoreAwaitsServer(`bring this store from version ${found} to ${SCHEMA_VERSION}`);
352
389
  if (found !== SCHEMA_VERSION && !upgrading)
@@ -402,6 +439,11 @@ export async function openSqliteStore(options) {
402
439
  if (role === "runner" && (Object.keys(RUNNERS_ADDED).some((column) => !runnerColumns.has(column)) || (await connection.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'hand_backs'")).length === 0)) {
403
440
  throw new StoreAwaitsServer("keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)");
404
441
  }
442
+ // A claim writes its turn and attempt (schema.ts RUN_ATTEMPTS) in its own transaction: a runner waits for the server
443
+ // that adds the table.
444
+ if (role === "runner" && (await connection.all("SELECT name FROM pragma_table_info('run_attempts')")).length === 0) {
445
+ throw new StoreAwaitsServer("keep each claim's turn and attempt (run_attempts)");
446
+ }
405
447
  // The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
406
448
  // migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
407
449
  // An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
@@ -436,6 +478,8 @@ export async function openSqliteStore(options) {
436
478
  // Nor any computer a run made (schema.ts COMPUTER_INTERVALS): a computer made before it has no row.
437
479
  { sql: COMPUTER_INTERVALS },
438
480
  { sql: COMPUTER_INTERVALS_RUN },
481
+ // Nor any claim's turn and attempt (schema.ts RUN_ATTEMPTS): a claim made before it has no row.
482
+ { sql: RUN_ATTEMPTS },
439
483
  { sql: NATIVE_COMMANDS_INDEX },
440
484
  ], { full: true });
441
485
  // A computer_intervals an earlier build of this version made has no disk or booked time (schema.ts
@@ -461,7 +505,9 @@ export async function openSqliteStore(options) {
461
505
  }
462
506
  if (upgrading) {
463
507
  const named = async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name));
464
- await connection.write(purgeUpgrade(await named("runs"), await named("agents")).map((sql) => ({ sql })), { full: true });
508
+ if (found !== 14)
509
+ await connection.write(purgeUpgrade(await named("runs"), await named("agents")).map((sql) => ({ sql })), { full: true });
510
+ await connection.write(diskUpgrade(await named("runs")).map((sql) => ({ sql })), { full: true });
465
511
  }
466
512
  }
467
513
  }
@@ -560,6 +606,8 @@ async function dropRunContent(tx, runId) {
560
606
  await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
561
607
  await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
562
608
  await tx.run("DELETE FROM hand_backs WHERE run_id = ?", runId);
609
+ // Its claims' attempts: what each cost is in its tombstone's money, and no read of a purged run splits it.
610
+ await tx.run("DELETE FROM run_attempts WHERE run_id = ?", runId);
563
611
  }
564
612
  /** An agent's own rows no tombstone keeps (its learning, its saved sign-ins and their tombstones), gone: what an agent's
565
613
  * purge (Agents.purge) and its delete (Agents.remove) both drop. */
@@ -568,14 +616,13 @@ async function dropAgentPrivate(tx, agentId) {
568
616
  await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
569
617
  await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
570
618
  }
571
- /** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite (and a purge, when its
572
- * checkpoint could not truncate the log) and removes once no file of the store keeps the bytes they replaced: a start
573
- * that finds it finishes the scrub. */
619
+ /** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite (and a purge before its
620
+ * transaction) and removes once no file of the store keeps the bytes they replaced: a start that finds it finishes the
621
+ * scrub. */
574
622
  const SCRUB_SUFFIX = ".scrub";
575
623
  /** How long the scrub's VACUUM waits, once its busy wait ran out on another connection's write, before its one retry. */
576
624
  const VACUUM_RETRY_MS = 400;
577
- /** The marker at `path`, written and synced (its directory too): before the rewrite it marks changes a byte, or once a
578
- * purge's checkpoint left the log. */
625
+ /** The marker at `path`, written and synced (its directory too): before the rewrite or purge it marks changes a byte. */
579
626
  function markScrub(path) {
580
627
  const fd = openSync(path, "w", 0o600);
581
628
  try {
@@ -608,6 +655,7 @@ class SqliteStore {
608
655
  sealedKeys;
609
656
  computerLedger;
610
657
  computerIntervals;
658
+ runAttempts;
611
659
  pairedComputers;
612
660
  mintedTokens;
613
661
  runners;
@@ -635,10 +683,10 @@ class SqliteStore {
635
683
  #released = new Map();
636
684
  /** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
637
685
  #scrubMarker;
638
- /** How many times a purge left the marker (#purged). The marker has two owners: secureRewrite removes it only when no
639
- * purge left it since the step that covers that purge's log (its own start, or the checkpoint it asked), so a marker a
640
- * purge left is never removed without a checkpoint that truncated the purge's frames. */
641
- #purgeMarks = 0;
686
+ /** How many times a purge (#purging) or a rewrite (secureRewrite) wrote the marker. The marker has many writers: each
687
+ * removes it only when no other wrote it since the step that covers that writer's log (its own start, or the checkpoint
688
+ * it asked), so a marker is never removed without a checkpoint that truncated every writer's frames. */
689
+ #scrubMarks = 0;
642
690
  constructor(db, now, origin, scrubMarker) {
643
691
  this.#db = db;
644
692
  this.#scrubMarker = scrubMarker;
@@ -659,18 +707,24 @@ class SqliteStore {
659
707
  throw new AgentPurged(agentId, agent.archived_at, agent.purged_at);
660
708
  return agent;
661
709
  };
662
- const insertRevision = async (tx, agentId, revision, at, ifCurrent) => {
710
+ const insertRevision = async (tx, agentId, revision, at, { ifCurrent, ifNoActiveRuns, advance } = {}) => {
663
711
  // The parent is the agent's current revision now (null for its first): the agent must exist, which its first revision
664
712
  // (create) and a later one (addRevision, upgrade) both guarantee before this. Held (a writer's row lock), so two
665
- // revisions added at once, by this server or another on the same store, never both name the same parent, and
713
+ // revisions advanced at once, by this server or another on the same store, never both name the same parent, and
666
714
  // `ifCurrent` is compared with what no other writer can move until this commits. Never one of a purged agent.
667
715
  const agent = await heldAgent(tx, agentId);
668
716
  if (!agent)
669
717
  throw new StoreConstraint(`no agent ${agentId}`);
670
718
  if (ifCurrent !== undefined && agent.current_revision !== ifCurrent)
671
719
  throw new RevisionMoved(agentId, agent.current_revision);
720
+ if (ifNoActiveRuns) {
721
+ const active = await tx.all("SELECT id FROM runs WHERE agent_id = ? AND state IN ('queued', 'running', 'parked') ORDER BY id", agentId);
722
+ if (active.length > 0)
723
+ throw new ActiveRuns(agentId, active.map(({ id }) => id));
724
+ }
672
725
  await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, created_at, mcp_pin, monid_pin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", revision.id, agentId, agent.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, revision.package === undefined ? null : json(revision.package), at, pinText(revision.mcpPin), pinText(revision.monidPin));
673
- await tx.run("UPDATE agents SET current_revision = ? WHERE id = ?", revision.id, agentId);
726
+ if (advance !== false)
727
+ await tx.run("UPDATE agents SET current_revision = ? WHERE id = ?", revision.id, agentId);
674
728
  };
675
729
  const writeScopes = async (tx, triggerId, scopes) => {
676
730
  await tx.run("DELETE FROM trigger_scopes WHERE trigger_id = ?", triggerId);
@@ -688,14 +742,20 @@ class SqliteStore {
688
742
  * takes it), so on Postgres a delete's archive that commits first is read here, and one that commits after waits for
689
743
  * this run to be in the store, where the delete's listing of the agent's runs finds it. A purged agent is refused too
690
744
  * (AgentPurged): it takes no run and no trigger. */
691
- const refuseDeleting = async (tx, agentId) => {
745
+ const refuseDeleting = async (tx, agentId, expectedCurrent) => {
692
746
  const agent = await heldAgent(tx, agentId);
693
747
  if (agent?.archived_at != null && agent.external_ref != null)
694
748
  throw new AgentDeleting(agentId);
749
+ if (expectedCurrent !== undefined) {
750
+ if (!agent)
751
+ throw new StoreConstraint(`no agent ${agentId}`);
752
+ if (agent.current_revision !== expectedCurrent)
753
+ throw new RevisionMoved(agentId, agent.current_revision);
754
+ }
695
755
  };
696
756
  /** The runs whose launch is made from run `runId` (madeOf: a replay of its input, an audit's shadow), by id. Every
697
757
  * launch is read (no index names its source): a purge's read, never a hot path. */
698
- const launchedFrom = async (ex, runId) => (await ex.all(`SELECT run_id AS id FROM run_launch WHERE (${d.jsonText("body", ["replay", "of"])} = ? OR ${d.jsonText("body", ["audit", "of"])} = ?) AND run_id <> ? ORDER BY run_id`, runId, runId, runId)).map((row) => row.id);
758
+ const launchedFrom = async (ex, runId) => (await ex.all(`SELECT run_id AS id FROM run_launch WHERE (${d.jsonText(readableJson(d, "body"), ["replay", "of"])} = ? OR ${d.jsonText(readableJson(d, "body"), ["audit", "of"])} = ?) AND run_id <> ? ORDER BY run_id`, runId, runId, runId)).map((row) => row.id);
699
759
  /** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
700
760
  * while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
701
761
  * distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
@@ -763,9 +823,11 @@ class SqliteStore {
763
823
  await writeScopes(tx, t.id, []);
764
824
  return off.map(({ id: triggerId, name }) => ({ id: triggerId, name })).sort((a, b) => a.name.localeCompare(b.name));
765
825
  }),
766
- addRevision: async ({ agentId, ifCurrent, description, ...revision }) => {
826
+ addRevision: async ({ agentId, ifCurrent, description, ifNoActiveRuns, settingsGuards, mcpGuards, advance, ...revision }) => {
767
827
  await db.transaction(async (tx) => {
768
- await insertRevision(tx, agentId, revision, now(), ifCurrent);
828
+ await checkSettingsGuards(tx, settingsGuards);
829
+ await checkMcpGuards(tx, d, mcpGuards);
830
+ await insertRevision(tx, agentId, revision, now(), { ifCurrent, ifNoActiveRuns, advance });
769
831
  // Under the row lock insertRevision took, after its ifCurrent passed: the revision and the description, or neither.
770
832
  if (description !== undefined)
771
833
  await tx.run("UPDATE agents SET description = ? WHERE id = ?", description, agentId);
@@ -822,31 +884,42 @@ class SqliteStore {
822
884
  await tx.run("DELETE FROM agents WHERE id = ?", agentId);
823
885
  });
824
886
  },
825
- purge: async (agentId) => {
826
- const purged = await db.transaction(async (tx) => {
827
- await d.lockRow(tx, "agents", "id", agentId);
828
- const agent = await tx.get("SELECT purged_at FROM agents WHERE id = ?", agentId);
829
- if (!agent || agent.purged_at !== null)
830
- return false;
831
- // Each run a tombstone first (Runs.purge): a run started past the delete's listing keeps the agent for the next one.
832
- const left = await tx.get("SELECT id FROM runs WHERE agent_id = ? AND purged_at IS NULL LIMIT 1", agentId);
833
- if (left)
834
- throw new StoreConstraint(`agent ${agentId} still has run ${left.id} not purged: each is purged first (runs.purge)`);
835
- const triggersLeft = await tx.all("SELECT id FROM triggers WHERE agent_id = ? ORDER BY id", agentId);
836
- if (triggersLeft.length)
837
- throw new TriggersLeft(agentId, triggersLeft.map((one) => one.id));
838
- await dropAgentPrivate(tx, agentId);
839
- // The answer a template apply kept under its key, which holds the agent as it was made.
840
- await tx.run(`DELETE FROM idempotency WHERE scope = 'templates.apply' AND ${d.jsonText("response", ["agentId"])} = ?`, agentId);
841
- // Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
842
- await tx.run("UPDATE revisions SET body = '{}', skills = NULL, package = NULL, note = NULL, mcp_pin = NULL, monid_pin = NULL WHERE agent_id = ?", agentId);
843
- // Its purge time last, in the same write as its name and description.
844
- await tx.run("UPDATE agents SET name = '', description = NULL, purged_at = ? WHERE id = ?", now(), agentId);
845
- return true;
846
- });
847
- if (purged)
848
- await this.#purged();
849
- },
887
+ purge: (agentId) => this.#purging(() => db.transaction(async (tx) => {
888
+ await d.lockRow(tx, "agents", "id", agentId);
889
+ const agent = await tx.get("SELECT purged_at FROM agents WHERE id = ?", agentId);
890
+ if (!agent || agent.purged_at !== null)
891
+ return false;
892
+ // Each run a tombstone first (Runs.purge): a run started past the delete's listing keeps the agent for the next one.
893
+ const left = await tx.get("SELECT id FROM runs WHERE agent_id = ? AND purged_at IS NULL LIMIT 1", agentId);
894
+ if (left)
895
+ throw new StoreConstraint(`agent ${agentId} still has run ${left.id} not purged: each is purged first (runs.purge)`);
896
+ const triggersLeft = await tx.all("SELECT id FROM triggers WHERE agent_id = ? ORDER BY id", agentId);
897
+ if (triggersLeft.length)
898
+ throw new TriggersLeft(agentId, triggersLeft.map((one) => one.id));
899
+ await dropAgentPrivate(tx, agentId);
900
+ // The answer a template apply kept under its key, which holds the agent as it was made.
901
+ await tx.run(`DELETE FROM idempotency WHERE scope = 'templates.apply' AND ${d.jsonText("response", ["agentId"])} = ?`, agentId);
902
+ // The uploads it was applied from, each gone unless another agent not purged was applied from it too: nothing
903
+ // else owns one, and a server that serves no template route (API-only) could never remove it. Each is held by its
904
+ // id, in order, before it is read: two purges of agents applied from one upload read it in turn, so the later
905
+ // reads the earlier's purge (committed) and removes the upload.
906
+ const packageId = (alias) => d.jsonText(`${alias}.package`, ["id"]);
907
+ const applied = (await tx.all(`SELECT DISTINCT ${packageId("r")} AS id FROM revisions r WHERE r.agent_id = ? AND r.package IS NOT NULL`, agentId))
908
+ .map((row) => row.id)
909
+ .filter((id) => id !== null && id.startsWith(UPLOAD_PREFIX))
910
+ .sort();
911
+ for (const id of applied) {
912
+ await d.lockKey(tx, `imported_templates:${id}`);
913
+ const kept = await tx.get(`SELECT r.id FROM revisions r JOIN agents a ON a.id = r.agent_id WHERE r.agent_id <> ? AND a.purged_at IS NULL AND ${packageId("r")} = ? LIMIT 1`, agentId, id);
914
+ if (!kept)
915
+ await tx.run("DELETE FROM imported_templates WHERE id = ?", id);
916
+ }
917
+ // Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
918
+ await tx.run("UPDATE revisions SET body = '{}', skills = NULL, package = NULL, note = NULL, mcp_pin = NULL, monid_pin = NULL WHERE agent_id = ?", agentId);
919
+ // Its purge time last, in the same write as its name and description.
920
+ await tx.run("UPDATE agents SET name = '', description = NULL, purged_at = ? WHERE id = ?", now(), agentId);
921
+ return true;
922
+ })),
850
923
  };
851
924
  this.templates = {
852
925
  apply: async (agent, revision, triggers, idempotencyKey) => db.transaction(async (tx) => {
@@ -976,13 +1049,18 @@ class SqliteStore {
976
1049
  if (!was)
977
1050
  return undefined;
978
1051
  const settled = change.status !== undefined && change.status !== "due";
979
- // Out of due, a firing keeps no retry, wait, payload or attrs, nor the reason its last try gave (unless it gives one).
1052
+ // Out of due, a firing keeps no retry, wait, payload or attrs (unless keepAttrs), nor the reason its last try gave
1053
+ // (unless it gives one). One exception: a sent firing keeps its startBy in retry_at (firingOf reads it back as
1054
+ // startBy, never as a retry), so no migration adds a column for it. Each column is set once: Postgres refuses an
1055
+ // update that names one twice.
980
1056
  const set = [];
981
1057
  if (change.status !== undefined)
982
1058
  set.push(["status", change.status]);
983
1059
  if (settled)
984
- set.push(["retry_at", null], ["waits_on", null], ["payload", null], ["attrs", null], ["reason", change.reason ?? null], ["attempts", change.attempts ?? 0]);
985
- else if (change.reason !== undefined)
1060
+ set.push(["retry_at", change.status === "sent" ? change.startBy ?? null : null], ["waits_on", null], ["payload", null], ["reason", change.reason ?? null], ["attempts", change.attempts ?? 0]);
1061
+ if (settled && !change.keepAttrs)
1062
+ set.push(["attrs", null]);
1063
+ if (!settled && change.reason !== undefined)
986
1064
  set.push(["reason", change.reason]);
987
1065
  if (change.runId !== undefined)
988
1066
  set.push(["run_id", change.runId]);
@@ -1034,7 +1112,7 @@ class SqliteStore {
1034
1112
  const firing = await tx.get("SELECT status FROM trigger_firings WHERE trigger_id = ? AND key = ?", triggerId, key);
1035
1113
  if (!firing || firing.status !== "due")
1036
1114
  return undefined;
1037
- const waiting = (await tx.get(`SELECT COUNT(*) AS n FROM commands WHERE run_id = ? AND taken_at IS NULL AND ${d.jsonText("body", ["origin", "trigger_id"])} = ?`, runId, triggerId)).n;
1115
+ const waiting = (await tx.get(`SELECT COUNT(*) AS n FROM commands WHERE run_id = ? AND taken_at IS NULL AND ${d.jsonText(readableJson(d, "body"), ["origin", "trigger_id"])} = ?`, runId, triggerId)).n;
1038
1116
  const clear = "retry_at = NULL, waits_on = NULL, payload = NULL, attrs = NULL, attempts = 0";
1039
1117
  if (waiting >= bound.max) {
1040
1118
  await tx.run(`UPDATE trigger_firings SET status = 'skipped', reason = ?, ${clear} WHERE trigger_id = ? AND key = ?`, bound.reason, triggerId, key);
@@ -1061,15 +1139,17 @@ class SqliteStore {
1061
1139
  WHERE f.status = 'due' AND f.waits_on IS NOT NULL ORDER BY f.at, f.${d.firingOrder}`)).map((r) => ({ ...firingOf(r), free: r.free === 1 || r.free === true })),
1062
1140
  soonest: async () => (await db.get("SELECT MIN(next_at) AS at FROM triggers WHERE enabled = 1 AND next_at IS NOT NULL"))?.at ?? null,
1063
1141
  activeRuns: async (triggerId) => (await db.get(`SELECT COUNT(*) AS n FROM trigger_firings f JOIN runs r ON r.id = f.run_id WHERE f.trigger_id = ? AND f.status = 'started' AND r.state NOT IN (${FINAL})`, triggerId)).n,
1064
- prune: async (triggerId, { history, dayMs, keepByKey, kept }) => db.transaction(async (tx) => {
1142
+ prune: async (triggerId, { history, dayMs, keepByKey, kept, now: clockNow }) => db.transaction(async (tx) => {
1065
1143
  const at = now();
1066
1144
  await d.lockRow(tx, "triggers", "id", triggerId);
1067
- // Past the newest `history` shown firings: never a due one, a failure not yet told, or a started one whose run
1068
- // has not ended. The rest leave the history: kept for their key's day when a sender's key names them, else gone.
1145
+ // Past the newest `history` shown firings: never a due one, a failure not yet told, a started one whose run has
1146
+ // not ended, or a sent one its host may still start (its startBy, in retry_at, not passed on the triggers'
1147
+ // clock). The rest leave the history: kept for their key's day when a sender's key names them, else gone.
1069
1148
  const old = await tx.all(`SELECT f.key, f.by FROM trigger_firings f LEFT JOIN runs r ON r.id = f.run_id
1070
1149
  WHERE f.trigger_id = ? AND f.shown = 1 AND f.status != 'due' AND NOT (f.status = 'failed' AND (f.notified IS NULL OR f.notified = 0))
1071
1150
  AND NOT (f.status = 'started' AND r.id IS NOT NULL AND r.state NOT IN (${FINAL}))
1072
- AND f.key NOT IN (SELECT key FROM trigger_firings WHERE trigger_id = ? AND shown = 1 ORDER BY at DESC, ${d.firingOrder} DESC LIMIT ?)`, triggerId, triggerId, history);
1151
+ AND NOT (f.status = 'sent' AND f.retry_at IS NOT NULL AND f.retry_at >= ?)
1152
+ AND f.key NOT IN (SELECT key FROM trigger_firings WHERE trigger_id = ? AND shown = 1 ORDER BY at DESC, ${d.firingOrder} DESC LIMIT ?)`, triggerId, clockNow, triggerId, history);
1073
1153
  for (const { key, by } of old) {
1074
1154
  if (keepByKey(by ?? "manual"))
1075
1155
  await tx.run("UPDATE trigger_firings SET shown = 0, payload = NULL, attrs = NULL WHERE trigger_id = ? AND key = ?", triggerId, key);
@@ -1105,10 +1185,19 @@ class SqliteStore {
1105
1185
  },
1106
1186
  fire: async (firing, run, { launch } = {}) => this.#queued(await db.transaction(async (tx) => {
1107
1187
  const at = now();
1188
+ await checkSettingsGuards(tx, run.settingsGuards);
1189
+ // Match archive's agent -> trigger order. Preparation may have raced a trigger move; never start a run for
1190
+ // its former agent merely because that agent's admission guards still pass.
1191
+ await refuseDeleting(tx, run.agentId, run.expectedCurrent);
1108
1192
  await d.lockRow(tx, "triggers", "id", firing.triggerId);
1193
+ const trigger = await tx.get("SELECT agent_id FROM triggers WHERE id = ?", firing.triggerId);
1194
+ if (!trigger)
1195
+ throw new StoreConstraint(`no trigger ${firing.triggerId}`);
1196
+ if (trigger.agent_id !== run.agentId)
1197
+ throw new StoreConstraint(`trigger ${firing.triggerId} no longer belongs to agent ${run.agentId}`);
1109
1198
  // Never a run of an archived agent: the archive's commit is read here, in the transaction that would start it.
1110
1199
  await refuseArchived(tx, run.agentId);
1111
- const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, started_at) VALUES (?, ?, ?, 'queued', 0, ?) RETURNING ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, at);
1200
+ const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, disk, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, launchDiskOf(launch), at);
1112
1201
  // The run's launch row lands with it, through the store's one writer, or neither does.
1113
1202
  if (launch)
1114
1203
  await writeLaunch(tx, run.id, launch, at);
@@ -1124,16 +1213,17 @@ class SqliteStore {
1124
1213
  })),
1125
1214
  };
1126
1215
  this.runs = {
1127
- create: async ({ id, agentId, revisionId, origin, labels }, launch) => {
1216
+ create: async ({ id, agentId, revisionId, origin, labels, expectedCurrent, settingsGuards, startedAt }, launch) => {
1128
1217
  // sign_in_handed is not written here: the runner writes it at its claim (runs.update under the epoch fence).
1129
- const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`;
1218
+ const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, disk, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?, ?) RETURNING ${RUN_COLUMNS}`;
1130
1219
  const labelled = labelsColumn(labels);
1131
1220
  // The run, its origin and its launch row in one transaction: the key -> run link holds even if the kept response
1132
1221
  // never lands, and a run never exists without the launch it was started with. Never a run of an agent being
1133
1222
  // deleted: its mark is read here, in the transaction that would start the run.
1134
1223
  return this.#queued(await db.transaction(async (tx) => {
1135
1224
  const at = now();
1136
- await refuseDeleting(tx, agentId);
1225
+ await checkSettingsGuards(tx, settingsGuards);
1226
+ await refuseDeleting(tx, agentId, expectedCurrent);
1137
1227
  // A run made from another (a replay of its input, an audit's shadow) never of a purged one: its source's row
1138
1228
  // held as its purge holds it, so either this commits first and the purge finds it (RunsMadeFromLeft), or the
1139
1229
  // purge does and this reads its purge time.
@@ -1144,7 +1234,7 @@ class SqliteStore {
1144
1234
  if (source && source.purged_at !== null)
1145
1235
  throw new RunPurged(of, id);
1146
1236
  }
1147
- const row = await tx.get(insert, id, agentId, revisionId, labelled, at);
1237
+ const row = await tx.get(insert, id, agentId, revisionId, labelled, launchDiskOf(launch), startedAt ?? at);
1148
1238
  if (origin)
1149
1239
  await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
1150
1240
  if (launch)
@@ -1153,7 +1243,7 @@ class SqliteStore {
1153
1243
  }));
1154
1244
  },
1155
1245
  createInline: async ({ agent, revision, run, launch }) => {
1156
- const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`;
1246
+ const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, disk, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?, ?) RETURNING ${RUN_COLUMNS}`;
1157
1247
  const made = await db.transaction(async (tx) => {
1158
1248
  const at = now();
1159
1249
  // Hold the external reference, so two first uses of the same expert serialize (SQLite's one writer already does).
@@ -1178,7 +1268,7 @@ class SqliteStore {
1178
1268
  await tx.run("UPDATE agents SET current_revision = ?, name = ?, description = ? WHERE id = ?", revisionId, agent.name, agent.description ?? null, mapped.id);
1179
1269
  }
1180
1270
  // The run, its origin and its launch, in the same transaction as the agent and the revision.
1181
- const row = await tx.get(insert, run.id, mapped.id, revisionId, labelsColumn(run.labels), at);
1271
+ const row = await tx.get(insert, run.id, mapped.id, revisionId, labelsColumn(run.labels), launchDiskOf(launch), at);
1182
1272
  if (run.origin)
1183
1273
  await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", run.origin.key, run.id, run.origin.fingerprint ?? null, at);
1184
1274
  await writeLaunch(tx, run.id, launch, at);
@@ -1192,8 +1282,10 @@ class SqliteStore {
1192
1282
  },
1193
1283
  launch: (runId) => readLaunch(db, runId),
1194
1284
  usageMetadata: (runId, options) => readUsageMetadata(db, runId, options),
1285
+ projectCheckpoints: (filter) => readProjectCheckpoints(db, filter),
1195
1286
  learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
1196
- list: async ({ agentId, revisionId, state, archived, labels, limit, purged = false }) => {
1287
+ seededBefore: (agentId, at) => readSeededBefore(db, agentId, at),
1288
+ list: async ({ agentId, revisionId, state, archived, labels, disk, limit, purged = false }) => {
1197
1289
  // A built-in learning run (a run's grade and merge, queued with its kept learning) is no run of a person's: no list,
1198
1290
  // count, stat or notice names it. A purged run is a tombstone: only the readers that sum or count ask for it.
1199
1291
  const where = [NOT_A_LEARNING_RUN, ...(purged ? [] : ["purged_at IS NULL"])];
@@ -1209,6 +1301,10 @@ class SqliteStore {
1209
1301
  // Each label, key and value bound as parameters (never spliced into a JSON path), all of them held.
1210
1302
  for (const [key, value] of Object.entries(labels ?? {}))
1211
1303
  (where.push(d.jsonObjectHas("labels")), params.push(key, value));
1304
+ if (disk === null)
1305
+ where.push("disk IS NULL");
1306
+ else if (disk !== undefined)
1307
+ (where.push("disk = ?"), params.push(disk));
1212
1308
  const bounded = typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0;
1213
1309
  if (bounded)
1214
1310
  params.push(limit);
@@ -1302,8 +1398,8 @@ class SqliteStore {
1302
1398
  const agentic = "COALESCE((SELECT kind FROM revisions WHERE revisions.id = runs.revision_id), 'agentic') = 'agentic'";
1303
1399
  const rows = await db.all(`SELECT id FROM runs WHERE ${COST_UNKNOWN}
1304
1400
  AND NOT (state = 'stopped' AND COALESCE(outcome, '') = 'stopped' AND ${agentic})
1305
- AND NOT (${agentic} AND EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${db.dialect.jsonText("run_launch.body", ["native"])} IS NOT NULL))
1306
- AND EXISTS (SELECT 1 FROM ${PI_TABLE.entries} AS entry WHERE entry.run_id = runs.id AND ${db.dialect.jsonText("entry.record", ["kind"])} = ?)
1401
+ AND NOT (${agentic} AND EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText(readableJson(d, "run_launch.body"), ["native"])} IS NOT NULL))
1402
+ AND EXISTS (SELECT 1 FROM ${PI_TABLE.entries} AS entry WHERE entry.run_id = runs.id AND ${d.jsonText(readableJson(d, "entry.record"), ["kind"])} = ?)
1307
1403
  ${after === undefined ? "" : "AND id > ? "}ORDER BY id LIMIT ?`, RUNNER_RECORDS.turn, ...(after === undefined ? [] : [after]), limit);
1308
1404
  return rows.map((row) => row.id);
1309
1405
  },
@@ -1334,55 +1430,51 @@ class SqliteStore {
1334
1430
  // Archiving an archived run keeps its first time: a second archive is a no-op, never a new time.
1335
1431
  await db.write([archived ? { sql: "UPDATE runs SET archived_at = COALESCE(archived_at, ?) WHERE id = ?", params: [now(), runId] } : { sql: "UPDATE runs SET archived_at = NULL WHERE id = ?", params: [runId] }]);
1336
1432
  },
1337
- every: async (agentId) => (await db.all("SELECT id, state, runner, purged_at FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId))
1338
- .map((row) => ({ id: row.id, state: row.state, runner: row.runner, purgedAt: row.purged_at ?? null })),
1433
+ every: async (agentId) => (await db.all("SELECT id, state, runner, purged_at, disk FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId))
1434
+ .map((row) => ({ id: row.id, state: row.state, runner: row.runner, purgedAt: row.purged_at ?? null, disk: row.disk ?? null })),
1339
1435
  madeFrom: async (runId) => {
1340
1436
  const learning = (await db.all("SELECT DISTINCT learning_run_id AS id FROM learning_proposals WHERE run_id = ? AND learning_run_id IS NOT NULL AND learning_run_id <> ?", runId, runId)).map((row) => row.id);
1341
1437
  return [...new Set([...(await launchedFrom(db, runId)), ...learning])].sort();
1342
1438
  },
1343
- purge: async (runId, kept) => {
1344
- const purged = await db.transaction(async (tx) => {
1345
- // Held as a run's end holds it: a write under a claim of it is either in before this, or finds it final.
1346
- await d.lockRow(tx, "runs", "id", runId, "update");
1347
- const run = await tx.get("SELECT state, runner, metrics, purged_at FROM runs WHERE id = ?", runId);
1348
- if (!run || run.purged_at !== null)
1349
- return false;
1350
- if (!FINAL_STATES.includes(run.state) || run.runner !== null)
1351
- throw new StoreConstraint(`run ${runId} is ${run.state}${run.runner === null ? "" : ` under ${run.runner}'s claim`}: only a final run no runner holds is purged`);
1352
- // A replay or shadow made from it after its purge read them (runs.create, under this row's lock) holds a copy of
1353
- // its input: each is purged first.
1354
- const left = [];
1355
- for (const id of await launchedFrom(tx, runId)) {
1356
- if ((await tx.get("SELECT purged_at FROM runs WHERE id = ?", id))?.purged_at === null)
1357
- left.push(id);
1358
- }
1359
- if (left.length)
1360
- throw new RunsMadeFromLeft(runId, left);
1361
- await dropRunContent(tx, runId);
1362
- // What names it, let go: a trigger's last run, the firing that started it (its key and status kept, so it never
1363
- // fires again; the event it was given, its payload and attributes, gone), a firing's wait behind it (the
1364
- // trigger's room is read again, as for a run that ended), the run a machine's token was minted for.
1365
- await tx.run("UPDATE triggers SET last_run_id = NULL WHERE last_run_id = ?", runId);
1366
- await tx.run("UPDATE trigger_firings SET run_id = NULL, payload = NULL, attrs = NULL WHERE run_id = ?", runId);
1367
- await tx.run("UPDATE trigger_firings SET waits_on = NULL WHERE waits_on = ?", runId);
1368
- await tx.run("UPDATE minted_tokens SET run = NULL WHERE run = ?", runId);
1369
- // Its kept learning: what its turn asked and answered and the proposal go; each row stays, with the proposal's
1370
- // state alone, as the learning meter (learning.spend) and the list's leaving out of learning runs read it.
1371
- for (const row of await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ?", runId)) {
1372
- const state = JSON.parse(row.proposal)?.state;
1373
- await tx.run("UPDATE learning_proposals SET turn = '{}', proposal = ? WHERE run_id = ? AND round = ?", json(typeof state === "string" ? { state } : {}), runId, row.round);
1374
- }
1375
- // Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
1376
- // read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
1377
- const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
1378
- await tx.run("UPDATE runs SET summary = NULL, labels = NULL, sign_in_handed = NULL, metrics = ? WHERE id = ?", json(metrics), runId);
1379
- // Its listing, and its purge time last: no list shows it, and no lister builds it again.
1380
- await tx.run("UPDATE runs SET listing = NULL, list_status = NULL, listing_mark = list_mark, listing_live = 0, listing_until = NULL, listing_flags = 0, purged_at = ? WHERE id = ?", now(), runId);
1381
- return true;
1382
- });
1383
- if (purged)
1384
- await this.#purged();
1385
- },
1439
+ purge: (runId, kept) => this.#purging(() => db.transaction(async (tx) => {
1440
+ // Held as a run's end holds it: a write under a claim of it is either in before this, or finds it final.
1441
+ await d.lockRow(tx, "runs", "id", runId, "update");
1442
+ const run = await tx.get("SELECT state, runner, metrics, purged_at FROM runs WHERE id = ?", runId);
1443
+ if (!run || run.purged_at !== null)
1444
+ return false;
1445
+ if (!FINAL_STATES.includes(run.state) || run.runner !== null)
1446
+ throw new StoreConstraint(`run ${runId} is ${run.state}${run.runner === null ? "" : ` under ${run.runner}'s claim`}: only a final run no runner holds is purged`);
1447
+ // A replay or shadow made from it after its purge read them (runs.create, under this row's lock) holds a copy of
1448
+ // its input: each is purged first.
1449
+ const left = [];
1450
+ for (const id of await launchedFrom(tx, runId)) {
1451
+ if ((await tx.get("SELECT purged_at FROM runs WHERE id = ?", id))?.purged_at === null)
1452
+ left.push(id);
1453
+ }
1454
+ if (left.length)
1455
+ throw new RunsMadeFromLeft(runId, left);
1456
+ await dropRunContent(tx, runId);
1457
+ // What names it, let go: a trigger's last run, the firing that started it (its key and status kept, so it never
1458
+ // fires again; the event it was given, its payload and attributes, gone), a firing's wait behind it (the
1459
+ // trigger's room is read again, as for a run that ended), the run a machine's token was minted for.
1460
+ await tx.run("UPDATE triggers SET last_run_id = NULL WHERE last_run_id = ?", runId);
1461
+ await tx.run("UPDATE trigger_firings SET run_id = NULL, payload = NULL, attrs = NULL WHERE run_id = ?", runId);
1462
+ await tx.run("UPDATE trigger_firings SET waits_on = NULL WHERE waits_on = ?", runId);
1463
+ await tx.run("UPDATE minted_tokens SET run = NULL WHERE run = ?", runId);
1464
+ // Its kept learning: what its turn asked and answered and the proposal go; each row stays, with the proposal's
1465
+ // state alone, as the learning meter (learning.spend) and the list's leaving out of learning runs read it.
1466
+ for (const row of await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ?", runId)) {
1467
+ const state = JSON.parse(row.proposal)?.state;
1468
+ await tx.run("UPDATE learning_proposals SET turn = '{}', proposal = ? WHERE run_id = ? AND round = ?", json(typeof state === "string" ? { state } : {}), runId, row.round);
1469
+ }
1470
+ // Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
1471
+ // read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
1472
+ const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
1473
+ await tx.run("UPDATE runs SET summary = NULL, labels = NULL, sign_in_handed = NULL, metrics = ? WHERE id = ?", json(metrics), runId);
1474
+ // Its listing, and its purge time last: no list shows it, and no lister builds it again.
1475
+ await tx.run("UPDATE runs SET listing = NULL, list_status = NULL, listing_mark = list_mark, listing_live = 0, listing_until = NULL, listing_flags = 0, purged_at = ? WHERE id = ?", now(), runId);
1476
+ return true;
1477
+ })),
1386
1478
  remove: async (runId) => {
1387
1479
  await db.transaction(async (tx) => {
1388
1480
  // Held as a run's end holds it: a write under a claim of it is either in before this, or finds no row.
@@ -1767,11 +1859,15 @@ class SqliteStore {
1767
1859
  return row === undefined ? undefined : JSON.parse(row.value);
1768
1860
  },
1769
1861
  // `was` is compared as the JSON text put wrote: a row read and parsed gives the same text back, its keys in order.
1770
- replaceIf: async (key, was, value, claim) => {
1862
+ replaceIf: async (key, was, value, claim, guards) => {
1771
1863
  const encoded = json(value);
1772
- if (claim)
1864
+ if (claim || guards !== undefined)
1773
1865
  return db.transaction(async (tx) => {
1774
- const at = await underClaim(tx, claim, now);
1866
+ // Include the destination in the same sorted lock set. Source revocation and a publication's pointer move
1867
+ // are ordered in one transaction; when also claimed, settings precede the run's claim lock.
1868
+ if (guards !== undefined)
1869
+ await checkSettingsGuards(tx, guards, undefined, [key]);
1870
+ const at = claim ? await underClaim(tx, claim, now) : now();
1775
1871
  return await tx.runCounted("UPDATE settings SET value = ?, connector_id = ?, updated_at = ? WHERE key = ? AND value = ?", encoded, nativeCommandOwner(key, encoded), at, key, json(was)) === 1;
1776
1872
  });
1777
1873
  const [result] = await db.write([{ sql: "UPDATE settings SET value = ?, connector_id = ?, updated_at = ? WHERE key = ? AND value = ?", params: [encoded, nativeCommandOwner(key, encoded), now(), key, json(was)] }]);
@@ -1886,6 +1982,19 @@ class SqliteStore {
1886
1982
  },
1887
1983
  forRun: async (runId) => (await db.all("SELECT run_id, provider, provider_id, kind, gpu_type, gpu_count, cpus, memory_mb, disk_gb, started_at, kept, ended_at, booked_ms FROM computer_intervals WHERE run_id = ? ORDER BY started_at, provider, provider_id", runId)).map(intervalOf),
1888
1984
  };
1985
+ this.runAttempts = {
1986
+ lapsed: async (runId, epoch) => {
1987
+ await db.transaction(async (tx) => {
1988
+ // Held as a claim holds it, from its UPDATE of the run to its attempt row: a takeover in flight writes its row
1989
+ // (with the cause it read) before this reads it, and one after this reads the cut. Never a cause left unsaid.
1990
+ await d.lockRow(tx, "runs", "id", runId);
1991
+ await tx.run("UPDATE run_attempts SET cut = 'lease_lapse' WHERE run_id = ? AND epoch = ? AND cut IS NULL", runId, epoch);
1992
+ // The claim that took the run over read the lapse as a crash, if it came first: this says what it was.
1993
+ await tx.run("UPDATE run_attempts SET cause = 'lease_lapse' WHERE run_id = ? AND cause = 'crash' AND epoch = (SELECT min(epoch) FROM run_attempts WHERE run_id = ? AND epoch > ?)", runId, runId, epoch);
1994
+ });
1995
+ },
1996
+ forRun: async (runId) => (await db.all("SELECT run_id, epoch, turn, attempt, cause, cut, runner, from_state, journal_from, claimed_at FROM run_attempts WHERE run_id = ? ORDER BY epoch", runId)).map(attemptOf),
1997
+ };
1889
1998
  const PAIRED = "SELECT id, name, hello, driver, labels, pairing_id, created_at, seen_at, revoked_at FROM paired_computers";
1890
1999
  this.pairedComputers = {
1891
2000
  addCode: async (id, codeSha256, expiresAt) => {
@@ -2001,6 +2110,7 @@ class SqliteStore {
2001
2110
  list: async () => (await db.all("SELECT id, source, sha, publisher, files, imported_at FROM imported_templates ORDER BY id")).map((row) => ({
2002
2111
  id: row.id, source: row.source, sha: row.sha, publisher: row.publisher, files: JSON.parse(row.files), importedAt: row.imported_at,
2003
2112
  })),
2113
+ ids: async () => (await db.all("SELECT id FROM imported_templates ORDER BY id")).map((row) => row.id),
2004
2114
  put: async ({ id, source, sha, publisher, files }) => {
2005
2115
  await db.write([{
2006
2116
  sql: "INSERT INTO imported_templates (id, source, sha, publisher, files, imported_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET source = excluded.source, sha = excluded.sha, publisher = excluded.publisher, files = excluded.files, imported_at = excluded.imported_at",
@@ -2201,30 +2311,52 @@ class SqliteStore {
2201
2311
  handedAny: async () => (await handedAnyIn(db))?.id,
2202
2312
  };
2203
2313
  }
2204
- /** After a purge committed (runs.purge, agents.purge), on a SQLite store with a file: a WAL checkpoint (TRUNCATE).
2205
- * secure_delete (worker.ts open) zeroed the purged bytes in the pages the purge wrote, but those pages are new frames
2206
- * in the WAL: the file keeps its earlier images of them, and the WAL its earlier frames, until a checkpoint copies the
2207
- * zeroed pages into the file and truncates the log. A reader in another connection (a runner's read, a backup) may hold
2208
- * the log back: the checkpoint waits PURGE_CHECKPOINT_BUSY_MS for it, not the connection's own busy wait, since every
2209
- * request of the store's one connection queues behind it (the purge already committed). One it held back (or that
2210
- * failed) leaves secureRewrite's marker, so the next start's scrub truncates the log, a crash between included. A marker
2211
- * that cannot be written (a full disk) throws, the purge committed: its caller answers it as the fault it is (a 500 the
2212
- * server logs), and drops what it served of the purged run all the same (agent-delete.ts purgeOneOrRefuse). */
2213
- async #purged() {
2314
+ /** A purge (runs.purge, agents.purge, `work` its transaction, true when it purged), on a SQLite store with a file:
2315
+ * secureRewrite's marker first, then the purge, then a WAL checkpoint (TRUNCATE). secure_delete (worker.ts open) zeroes
2316
+ * the purged bytes in the pages the purge writes, but those pages are new frames in the WAL: the file keeps its earlier
2317
+ * images of them, and the WAL its earlier frames, until a checkpoint copies the zeroed pages into the file and truncates
2318
+ * the log. The marker is written before any byte changes, as secureRewrite's is: one that cannot be written (a full
2319
+ * disk) throws with nothing purged, so the client's retry purges whole; a server that dies past it leaves it, and its
2320
+ * next start's scrub truncates the log. A reader in another connection (a runner's read, a backup) may hold the log
2321
+ * back: the checkpoint waits PURGE_CHECKPOINT_BUSY_MS for it, not the connection's own busy wait, since every request of
2322
+ * the store's one connection queues behind it. One it held back (or that failed) keeps the marker for the next start.
2323
+ * The marker goes once no file keeps what the purge changed (the log truncated, or nothing committed: a purge refused or
2324
+ * failed rolled back), under secureRewrite's own rule: only one that was not there before this purge wrote it (a
2325
+ * rewrite's or an earlier start's needs that start's VACUUM), and that no other writer wrote since (#scrubMarks). */
2326
+ async #purging(work) {
2214
2327
  const marker = this.#scrubMarker;
2215
2328
  const db = this.#db;
2216
2329
  if (marker === undefined || !(db instanceof Connection))
2217
- return;
2218
- const checkpoint = await db.checkpoint(PURGE_CHECKPOINT_BUSY_MS).catch(() => undefined);
2219
- if (checkpoint?.busy === 0)
2220
- return;
2221
- this.#purgeMarks++;
2330
+ return void (await work());
2331
+ const pending = existsSync(marker);
2332
+ const mine = ++this.#scrubMarks;
2222
2333
  try {
2223
2334
  markScrub(marker);
2224
2335
  }
2225
2336
  catch (error) {
2226
- throw new Error(`The purge committed, but its WAL checkpoint was held back and the scrub's marker could not be written (${error.message}): the log may keep the purged bytes until a later checkpoint truncates it.`, { cause: error });
2337
+ throw new Error(`The purge's scrub marker could not be written (${error.message}): nothing was purged.`, { cause: error });
2338
+ }
2339
+ const done = () => {
2340
+ if (pending || this.#scrubMarks !== mine)
2341
+ return;
2342
+ try {
2343
+ rmSync(marker, { force: true });
2344
+ }
2345
+ catch {
2346
+ // Left for the next start's scrub, which costs it a VACUUM: never a failure of a purge that committed.
2347
+ }
2348
+ };
2349
+ let purged;
2350
+ try {
2351
+ purged = await work();
2352
+ }
2353
+ catch (error) {
2354
+ done();
2355
+ throw error;
2227
2356
  }
2357
+ if (purged && (await db.checkpoint(PURGE_CHECKPOINT_BUSY_MS).catch(() => undefined))?.busy !== 0)
2358
+ return;
2359
+ done();
2228
2360
  }
2229
2361
  async secureRewrite(work, options = {}) {
2230
2362
  const marker = this.#scrubMarker;
@@ -2234,13 +2366,13 @@ class SqliteStore {
2234
2366
  // Written before any byte changes: a server that dies after the rewrite committed, and before the scrub below is done,
2235
2367
  // leaves it, and its next start scrubs though no row is left in the clear.
2236
2368
  const pending = existsSync(marker);
2237
- const purgesBefore = this.#purgeMarks;
2369
+ const mine = ++this.#scrubMarks;
2238
2370
  markScrub(marker);
2239
2371
  // secure_delete is on for the connection's whole life (worker.ts open): a rewritten row's old bytes are zeroed in its page.
2240
2372
  const rewritten = await work();
2241
- // Nothing rewritten, and the marker is this call's alone: no purge left it while the work ran (#purgeMarks). One that
2242
- // did needs the checkpoint below, or the next start's scrub.
2243
- if (rewritten === 0 && !pending && this.#purgeMarks === purgesBefore) {
2373
+ // Nothing rewritten, and the marker is this call's alone: no purge or other rewrite wrote it while the work ran
2374
+ // (#scrubMarks). One that did needs the checkpoint below, or the next start's scrub.
2375
+ if (rewritten === 0 && !pending && this.#scrubMarks === mine) {
2244
2376
  rmSync(marker, { force: true });
2245
2377
  return { rewritten };
2246
2378
  }
@@ -2258,12 +2390,12 @@ class SqliteStore {
2258
2390
  await new Promise((resolve) => setTimeout(resolve, VACUUM_RETRY_MS));
2259
2391
  await this.#db.all("VACUUM");
2260
2392
  });
2261
- const purgesBefore = this.#purgeMarks;
2393
+ const marksBefore = this.#scrubMarks;
2262
2394
  const checkpoint = await db.checkpoint();
2263
2395
  // A reader in another connection (a runner, a backup) held the log back: the old frames are there until a
2264
- // checkpoint is done, so the marker stays. So does one a purge left after this checkpoint was asked: its frames may
2265
- // be past it.
2266
- if (checkpoint?.busy !== 0 || this.#purgeMarks !== purgesBefore)
2396
+ // checkpoint is done, so the marker stays. So does one a purge or another rewrite wrote after this checkpoint was
2397
+ // asked: its frames may be past it.
2398
+ if (checkpoint?.busy !== 0 || this.#scrubMarks !== marksBefore)
2267
2399
  return { rewritten, left: "busy" };
2268
2400
  }
2269
2401
  catch (error) {
@@ -2308,9 +2440,48 @@ class SqliteStore {
2308
2440
  for (const { id } of picked)
2309
2441
  this.#released.delete(id);
2310
2442
  // A running run that still names its runner was taken from it: that runner's lease ran out mid-run (CLAIMABLE).
2311
- return picked.map(({ id, state, runner: held }) => ({ runId: id, runner, epoch: epochs.get(id), until: untils.get(id), from: state, ...(state === "running" && held !== null ? { lost: { runner: held } } : {}) }));
2443
+ const lostOf = (state, held) => (state === "running" && held !== null ? held : undefined);
2444
+ const attempts = await this.#attemptsAt(tx, runner, stamp, picked.map(({ id, state, runner: held }) => ({ runId: id, epoch: epochs.get(id), from: state, lost: lostOf(state, held) !== undefined })));
2445
+ return picked.map(({ id, state, runner: held }) => {
2446
+ const lost = lostOf(state, held);
2447
+ const at = attempts.get(id);
2448
+ return { runId: id, runner, epoch: epochs.get(id), until: untils.get(id), from: state, ...(lost !== undefined ? { lost: { runner: lost } } : {}), ...(at ? { turn: at.turn, attempt: at.attempt } : {}) };
2449
+ });
2312
2450
  });
2313
2451
  }
2452
+ /** Each claim's turn and attempt (run_attempts), written in the claim's transaction `tx`, in three statements for the
2453
+ * whole batch: the run's latest claim before it, and the run's next journal id now (no write under an older claim can
2454
+ * land after this one: each commit is fenced on the run's row, which this transaction holds). A claim that takes a run
2455
+ * still running from a claim that was cut (that claim's release said why, or its lease ran out) works that claim's turn
2456
+ * again, one attempt more; any other claim starts the run's next turn (a follow-up, a resume after a park, the first).
2457
+ * The cause is the cut claim's word, else a crash (a lease that ran out with no word), else a retry. Only when the
2458
+ * latest row is that cut claim's own: a claim moves the epoch one and a release one more, so the claim taken over is at
2459
+ * epoch - 1 (its lease ran out) or epoch - 2 (released). A row further back belongs to an earlier claim, past one that
2460
+ * wrote none (a runner of an earlier build, beside this server): that unrecorded claim's turn is not that row's, so this
2461
+ * claim starts a new turn, and nothing that row's claim did is read as redone. */
2462
+ async #attemptsAt(tx, runner, stamp, claims) {
2463
+ const out = new Map();
2464
+ if (claims.length === 0)
2465
+ return out;
2466
+ const ids = claims.map((claim) => claim.runId);
2467
+ const marks = ids.map(() => "?").join(", ");
2468
+ const before = new Map((await tx.all(`SELECT run_id, epoch, turn, attempt, cut FROM run_attempts a WHERE run_id IN (${marks}) AND epoch = (SELECT max(epoch) FROM run_attempts b WHERE b.run_id = a.run_id)`, ...ids)).map((row) => [row.run_id, row]));
2469
+ const next = new Map((await tx.all(`SELECT run_id, next_id FROM pi_metadata WHERE run_id IN (${marks})`, ...ids)).map((row) => [row.run_id, Number(row.next_id)]));
2470
+ const rows = [];
2471
+ for (const claim of claims) {
2472
+ const prev = before.get(claim.runId);
2473
+ // The claim taken over is the latest row's only at epoch - 1 (lost: no release moved it) or epoch - 2 (released, cut).
2474
+ const replaced = prev !== undefined && Number(prev.epoch) === claim.epoch - (claim.lost ? 1 : 2) ? prev : undefined;
2475
+ const redone = claim.from === "running" && replaced !== undefined && (claim.lost || replaced.cut !== null) ? replaced : undefined;
2476
+ const turn = prev === undefined ? 1 : Number(prev.turn) + (redone ? 0 : 1);
2477
+ const attempt = redone ? Number(redone.attempt) + 1 : 1;
2478
+ const cause = redone ? (redone.cut ?? (claim.lost ? "crash" : "retry")) : null;
2479
+ out.set(claim.runId, { turn, attempt });
2480
+ rows.push([claim.runId, claim.epoch, turn, attempt, cause, runner, claim.from, next.get(claim.runId) ?? JOURNAL_FIRST_ID]);
2481
+ }
2482
+ await tx.run(`INSERT INTO run_attempts (run_id, epoch, turn, attempt, cause, runner, from_state, journal_from, claimed_at) VALUES ${rows.map(() => `(?, ?, ?, ?, ?, ?, ?, ?, ${stamp.sql})`).join(", ")} ON CONFLICT (run_id, epoch) DO NOTHING`, ...rows.flatMap((row) => [...row, ...stamp.params]));
2483
+ return out;
2484
+ }
2314
2485
  /** Holds the run's row before a fenced write reads the store's clock: the lease is checked, and runs, from when the write
2315
2486
  * holds the row, never from before a wait for another writer (a no-op on SQLite, whose BEGIN IMMEDIATE already holds
2316
2487
  * the writer lock when the clock is read). */
@@ -2358,7 +2529,7 @@ class SqliteStore {
2358
2529
  // On the lease connection (TransactionOptions.lease): a runner whose loops hold every pool client still renews.
2359
2530
  }, { lease: true });
2360
2531
  }
2361
- async release(claim, { state, wakeAt = null, backoffUntil = null } = {}) {
2532
+ async release(claim, { state, wakeAt = null, backoffUntil = null, cut } = {}) {
2362
2533
  // The end commit is the one write that makes a run final (applyRunPatch: the leftover rows refused and the run_live
2363
2534
  // row deleted with it). A release never does: asked to, it is refused before anything is written.
2364
2535
  if (state !== undefined && FINAL_STATES.includes(state))
@@ -2388,6 +2559,9 @@ class SqliteStore {
2388
2559
  await tx.run(`DELETE FROM hand_backs WHERE at < ${now.sql} - ${this.#db.dialect.bigintParam}`, ...now.params, HAND_BACKS_KEPT_MS);
2389
2560
  await tx.run(`INSERT INTO hand_backs (run_id, runner, epoch, at) VALUES (?, ?, ?, ${now.sql})`, claim.runId, claim.runner, claim.epoch, ...now.params);
2390
2561
  }
2562
+ // Why the claim let its run go unfinished, on its own row, in the release's transaction: the next claim reads it.
2563
+ if (cut !== undefined)
2564
+ await tx.run("UPDATE run_attempts SET cut = ? WHERE run_id = ? AND epoch = ? AND cut IS NULL", cut, claim.runId, claim.epoch);
2391
2565
  }, { full: true });
2392
2566
  // The released claim's journal is dead (its epoch moved on): the store keeps it no longer, and refuses it from now.
2393
2567
  this.#journals.delete(journalKey(claim));
@@ -2492,15 +2666,7 @@ class SqliteStore {
2492
2666
  const at = this.#now();
2493
2667
  const state = run.state ?? "ended";
2494
2668
  return this.#db.transaction(async (tx) => {
2495
- for (const guard of [...(run.settingsGuards ?? [])].sort((a, b) => a.key.localeCompare(b.key))) {
2496
- // A no-op update takes the row's write lock on both SQLite and Postgres until the import commits. A source
2497
- // revoke/disconnect either commits first and refuses this write, or waits for this already-started import.
2498
- const setting = await tx.get("UPDATE settings SET value = value WHERE key = ? RETURNING value", guard.key);
2499
- const value = setting === undefined ? undefined : JSON.parse(setting.value);
2500
- if (!value || Object.entries(guard.fields).some(([field, expected]) => JSON.stringify(value[field]) !== JSON.stringify(expected))) {
2501
- throw new StoreConstraint("The source import grant changed before the history write committed.");
2502
- }
2503
- }
2669
+ await checkSettingsGuards(tx, run.settingsGuards, "The source import grant changed before the history write committed.");
2504
2670
  if (run.requireActiveAgent) {
2505
2671
  // Archive updates this same row. It either commits first and refuses this import, or waits for this
2506
2672
  // already-admitted history transaction; a read outside the transaction cannot establish that order.
@@ -2511,8 +2677,8 @@ class SqliteStore {
2511
2677
  // The ended run row, its launch row and its transcript's journal, all in this one transaction (the server's own
2512
2678
  // writer): a crash between them leaves nothing. The run is created at epoch 0 with no runner, and the journal's fence
2513
2679
  // passes for that one row, by the rowid its insert returned (the claim fence's inserted-here form).
2514
- const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, cost_usd, metrics, summary, outcome, imported_from, started_at, ended_at)
2515
- VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?) RETURNING ${this.#db.dialect.insertedRow} AS inserted_rowid, ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, state, run.costUsd ?? null, run.metrics === undefined || run.metrics === null ? null : json(run.metrics), run.summary ?? null, run.outcome ?? null, JSON.stringify(run.importedFrom), run.startedAt, run.endedAt ?? at);
2680
+ const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, cost_usd, metrics, summary, outcome, imported_from, disk, started_at, ended_at)
2681
+ VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING ${this.#db.dialect.insertedRow} AS inserted_rowid, ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, state, run.costUsd ?? null, run.metrics === undefined || run.metrics === null ? null : json(run.metrics), run.summary ?? null, run.outcome ?? null, JSON.stringify(run.importedFrom), launchDiskOf(run.launch), run.startedAt, run.endedAt ?? at);
2516
2682
  await writeLaunch(tx, run.id, run.launch, at);
2517
2683
  await new RunStorage(this.#db, { runId: run.id, epoch: 0 }, this.#now).applyIn(tx, run.transcript, row.inserted_rowid ?? "this-transaction");
2518
2684
  return runOf(row);