@parcha/agentrun-serve 0.1.0-beta.48 → 0.1.0-beta.50

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 (170) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +236 -26
  3. package/dist/agent-delete.d.ts +36 -12
  4. package/dist/agent-delete.js +213 -30
  5. package/dist/agents-store.d.ts +6 -2
  6. package/dist/agents-store.js +18 -5
  7. package/dist/agents.d.ts +8 -1
  8. package/dist/agents.js +14 -4
  9. package/dist/answer-json.d.ts +2 -2
  10. package/dist/answer-json.js +3 -4
  11. package/dist/api-only.d.ts +7 -10
  12. package/dist/api-only.js +9 -11
  13. package/dist/archil-routes.d.ts +1 -1
  14. package/dist/archil-routes.js +4 -3
  15. package/dist/browser-sessions.d.ts +56 -0
  16. package/dist/browser-sessions.js +117 -0
  17. package/dist/compute-cost.d.ts +101 -0
  18. package/dist/compute-cost.js +250 -0
  19. package/dist/computer-routes.d.ts +4 -15
  20. package/dist/computer-routes.js +6 -10
  21. package/dist/console/assets/index-D0mr9wfZ.css +1 -0
  22. package/dist/console/assets/index-D7G6o-1E.js +720 -0
  23. package/dist/console/index.html +2 -2
  24. package/dist/errors.d.ts +4 -1
  25. package/dist/errors.js +15 -5
  26. package/dist/eval-previous.d.ts +52 -0
  27. package/dist/eval-previous.js +164 -0
  28. package/dist/file-types.d.ts +2 -0
  29. package/dist/file-types.js +3 -1
  30. package/dist/harness.js +2 -1
  31. package/dist/import.js +4 -3
  32. package/dist/learn/check.d.ts +16 -4
  33. package/dist/learn/check.js +30 -26
  34. package/dist/learn/promote.d.ts +7 -1
  35. package/dist/learn/promote.js +47 -0
  36. package/dist/learn/repick.d.ts +43 -0
  37. package/dist/learn/repick.js +202 -0
  38. package/dist/learn/workflow-draft.d.ts +4 -0
  39. package/dist/learn/workflow-draft.js +10 -7
  40. package/dist/learned-workflow.d.ts +2 -0
  41. package/dist/learned-workflow.js +19 -2
  42. package/dist/learning-setting.d.ts +13 -0
  43. package/dist/learning-setting.js +23 -1
  44. package/dist/llms.txt +1 -1
  45. package/dist/openapi.js +180 -14
  46. package/dist/paid-calls.d.ts +17 -7
  47. package/dist/paid-calls.js +15 -9
  48. package/dist/run-launch.d.ts +2 -2
  49. package/dist/run-launch.js +2 -1
  50. package/dist/run-learning-served.d.ts +1 -1
  51. package/dist/run-timeline-served.js +5 -3
  52. package/dist/run-usage.d.ts +125 -0
  53. package/dist/run-usage.js +394 -0
  54. package/dist/runner/adapter-loop.d.ts +4 -0
  55. package/dist/runner/adapter-loop.js +66 -21
  56. package/dist/runner/adapter-run-spec.d.ts +8 -3
  57. package/dist/runner/adapter-run-spec.js +13 -6
  58. package/dist/runner/big-writes.d.ts +33 -0
  59. package/dist/runner/big-writes.js +105 -0
  60. package/dist/runner/cli-run-spec.js +14 -6
  61. package/dist/runner/conformance/harness.d.ts +2 -0
  62. package/dist/runner/conformance/harness.js +18 -4
  63. package/dist/runner/feedback-round.d.ts +29 -1
  64. package/dist/runner/feedback-round.js +54 -3
  65. package/dist/runner/held.d.ts +4 -1
  66. package/dist/runner/journal-kinds.d.ts +3 -1
  67. package/dist/runner/learning-end.js +54 -18
  68. package/dist/runner/loop-contract.d.ts +3 -0
  69. package/dist/runner/metrics.d.ts +4 -0
  70. package/dist/runner/metrics.js +9 -0
  71. package/dist/runner/monid-run.js +2 -2
  72. package/dist/runner/promotion.js +8 -2
  73. package/dist/runner/reflect-hook.js +3 -2
  74. package/dist/runner/run-child-host.d.ts +15 -2
  75. package/dist/runner/run-child-host.js +24 -8
  76. package/dist/runner/run-child.js +3 -0
  77. package/dist/runner/save-slots.d.ts +9 -0
  78. package/dist/runner/save-slots.js +91 -0
  79. package/dist/runs-over-store.d.ts +3 -2
  80. package/dist/runs-over-store.js +9 -7
  81. package/dist/sdk/runs.d.ts +3 -4
  82. package/dist/sdk/runs.js +10 -7
  83. package/dist/sdk/runtimes.d.ts +19 -0
  84. package/dist/sdk/runtimes.js +23 -0
  85. package/dist/sdk/schema.d.ts +14 -8
  86. package/dist/sdk/schema.js +18 -6
  87. package/dist/server.d.ts +7 -3
  88. package/dist/server.js +223 -100
  89. package/dist/store/agent-body.d.ts +2 -3
  90. package/dist/store/agent-body.js +3 -2
  91. package/dist/store/index.d.ts +2 -2
  92. package/dist/store/index.js +1 -1
  93. package/dist/store/journal/storage.js +1 -1
  94. package/dist/store/open.d.ts +1 -1
  95. package/dist/store/open.js +1 -1
  96. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  97. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  98. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  99. package/dist/store/schema.d.ts +20 -1
  100. package/dist/store/schema.js +60 -5
  101. package/dist/store/sqlite/connection.d.ts +4 -1
  102. package/dist/store/sqlite/connection.js +5 -0
  103. package/dist/store/sqlite/run-patch.d.ts +8 -3
  104. package/dist/store/sqlite/run-patch.js +15 -7
  105. package/dist/store/sqlite/store.d.ts +2 -1
  106. package/dist/store/sqlite/store.js +279 -68
  107. package/dist/store/sqlite/worker.d.ts +9 -0
  108. package/dist/store/sqlite/worker.js +18 -1
  109. package/dist/store/store.d.ts +149 -9
  110. package/dist/store/store.js +63 -0
  111. package/dist/store-reads/analytics.js +2 -1
  112. package/dist/store-reads/cap.d.ts +17 -7
  113. package/dist/store-reads/cap.js +54 -4
  114. package/dist/store-reads/decisions.d.ts +21 -0
  115. package/dist/store-reads/decisions.js +22 -0
  116. package/dist/store-reads/journal.d.ts +8 -2
  117. package/dist/store-reads/journal.js +27 -8
  118. package/dist/store-reads/learning.d.ts +1 -1
  119. package/dist/store-reads/learning.js +5 -2
  120. package/dist/store-reads/runs.js +2 -0
  121. package/dist/store-reads/stats.js +4 -2
  122. package/dist/store-view.d.ts +12 -1
  123. package/dist/store-view.js +98 -38
  124. package/dist/template-eval.d.ts +15 -1
  125. package/dist/template-eval.js +92 -13
  126. package/dist/templates.d.ts +1 -1
  127. package/dist/templates.js +4 -3
  128. package/dist/timeline/labels.js +17 -0
  129. package/dist/tool-list.js +1 -0
  130. package/dist/tools.d.ts +6 -2
  131. package/dist/tools.js +22 -1
  132. package/dist/trigger-targets.d.ts +28 -9
  133. package/dist/trigger-targets.js +19 -16
  134. package/dist/triggers.d.ts +2 -1
  135. package/dist/triggers.js +5 -2
  136. package/dist/validate.d.ts +4 -2
  137. package/dist/validate.js +13 -3
  138. package/dist/viewer-credential.d.ts +3 -4
  139. package/dist/viewer-credential.js +6 -4
  140. package/dist/web-fake.d.ts +25 -0
  141. package/dist/web-fake.js +38 -1
  142. package/dist/web-save.d.ts +75 -0
  143. package/dist/web-save.js +235 -0
  144. package/dist/workspace/archil-claim.d.ts +5 -2
  145. package/dist/workspace/archil-claim.js +5 -2
  146. package/dist/workspace/archil-disk.d.ts +10 -1
  147. package/dist/workspace/archil-disk.js +19 -1
  148. package/dist/workspace/archil.d.ts +3 -0
  149. package/dist/workspace/archil.js +101 -16
  150. package/dist/workspace/computer-for-claim.d.ts +19 -1
  151. package/dist/workspace/computer-for-claim.js +88 -20
  152. package/dist/workspace/computer-intervals.d.ts +26 -0
  153. package/dist/workspace/computer-intervals.js +58 -0
  154. package/dist/workspace/computer-janitor.d.ts +7 -3
  155. package/dist/workspace/computer-janitor.js +14 -6
  156. package/dist/workspace/computer-kept.d.ts +7 -2
  157. package/dist/workspace/computer-kept.js +9 -2
  158. package/dist/workspace/pieced.d.ts +14 -0
  159. package/dist/workspace/pieced.js +23 -0
  160. package/dist/workspace/resolve-computer.d.ts +7 -4
  161. package/dist/workspace/resolve-computer.js +21 -32
  162. package/dist/workspace/run-disk.js +32 -12
  163. package/dist/workspace/run-end-computers.d.ts +1 -0
  164. package/dist/workspace/run-end-computers.js +4 -1
  165. package/dist/workspace/run-workspace.d.ts +1 -1
  166. package/dist/workspace/run-workspace.js +11 -6
  167. package/package.json +10 -10
  168. package/templates/README.md +36 -7
  169. package/dist/console/assets/index-CTGegcKt.css +0 -1
  170. package/dist/console/assets/index-D1Se6mgG.js +0 -715
@@ -12,8 +12,17 @@ import { watchCommandsAt, wakeCommands } from "../command-wake.js";
12
12
  import { claimFence, storeNow } from "../fence.js";
13
13
  import { RunStorage } from "../journal/storage.js";
14
14
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
15
- import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
16
- import { AgentArchived, AgentDeleting, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, 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, } from "../store.js";
15
+ import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, 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";
17
+ /** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
18
+ const madeOf = (body) => {
19
+ for (const link of ["replay", "audit"]) {
20
+ const of = body?.[link]?.of;
21
+ if (typeof of === "string")
22
+ return of;
23
+ }
24
+ return undefined;
25
+ };
17
26
  /** The seq a run-change cursor names (Runs.changedSince): only a cursor this store handed back, a whole number. */
18
27
  const seqOf = (cursor) => {
19
28
  if (!/^(0|[1-9][0-9]{0,15})$/.test(cursor))
@@ -68,7 +77,7 @@ function triggerSet(patch, at) {
68
77
  pairs.push(["updated_at", at]);
69
78
  return { set: pairs.map(([column]) => `${column} = ?`).join(", "), params: pairs.map(([, value]) => value) };
70
79
  }
71
- const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref";
80
+ const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref, purged_at";
72
81
  const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, package, created_at, external_version, mcp_pin, monid_pin";
73
82
  const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
74
83
  const TRIGGER_COLUMNS = "id, agent_id, name, enabled, source, target, next_at, last_run_id, catchup_window_s, failures_in_a_row, disabled, max_active_runs, created_at, updated_at, template_id";
@@ -111,7 +120,7 @@ async function underClaim(tx, claim, now) {
111
120
  throw new Fenced(claim.runId, claim.epoch);
112
121
  return at;
113
122
  }
114
- const agentOf = (r) => ({ id: r.id, name: r.name, description: r.description, currentRevision: r.current_revision, createdAt: r.created_at, archivedAt: r.archived_at, externalRef: r.external_ref });
123
+ const agentOf = (r) => ({ id: r.id, name: r.name, description: r.description, currentRevision: r.current_revision, createdAt: r.created_at, archivedAt: r.archived_at, externalRef: r.external_ref, purgedAt: r.purged_at ?? null });
115
124
  const revisionOf = (r) => ({
116
125
  id: r.id, agentId: r.agent_id, parent: r.parent_id, kind: r.kind, body: JSON.parse(r.body), skills: r.skills === null ? null : JSON.parse(r.skills),
117
126
  note: r.note, package: r.package === null ? null : JSON.parse(r.package), createdAt: r.created_at, externalVersion: r.external_version,
@@ -159,6 +168,11 @@ const mcpServerOf = (r, at = Number(r.read_at)) => ({
159
168
  const mcpPinOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.mcp_pin), pinnedAt: Number(r.created_at) });
160
169
  const settingOf = (r) => ({ key: r.key, value: JSON.parse(r.value), updatedAt: r.updated_at });
161
170
  const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), updatedAt: r.updated_at });
171
+ const orNull = (value) => (value === null ? null : Number(value));
172
+ const intervalOf = (r) => ({
173
+ 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
+ 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),
175
+ });
162
176
  const ledgerRowOf = (r) => ({ provider: r.provider, sessionId: r.session_id, labels: JSON.parse(r.labels), detail: JSON.parse(r.detail), updatedAt: r.updated_at });
163
177
  const pairedOf = (r) => ({ id: r.id, name: r.name, hello: JSON.parse(r.hello), driver: r.driver, labels: JSON.parse(r.labels), pairingId: r.pairing_id, createdAt: r.created_at, seenAt: r.seen_at, revokedAt: r.revoked_at });
164
178
  const mintedOf = (r) => ({ machine: r.machine, kind: r.kind, os: r.os, arch: r.arch, expiresAt: r.expires_at, revokedAt: r.revoked_at, createdAt: r.created_at, runner: r.runner, incarnation: r.incarnation, run: r.run, refused: r.refused });
@@ -307,8 +321,9 @@ export async function openSqliteStore(options) {
307
321
  // Version 11 (0.1.0-beta.44 and before) keeps no listing on a run's row: the server adds it (schema.ts listingUpgrade)
308
322
  // in one durable write once the columns an earlier build of 11 lacked are in, every run behind until its lister builds
309
323
  // it. Version 12 names no minting runner on a machine's token and keeps no runner's relay: the server adds them
310
- // (schema.ts relayUpgrade). A runner refuses 11 and 12 until that server has.
311
- const upgrading = found === SCHEMA_VERSION - 2 || found === SCHEMA_VERSION - 1;
324
+ // (schema.ts relayUpgrade). Version 13 keeps no purge time on a run or an agent: the server adds them (schema.ts
325
+ // purgeUpgrade). A runner refuses 11, 12 and 13 until that server has.
326
+ const upgrading = found === 11 || found === 12 || found === 13;
312
327
  if (upgrading && role === "runner")
313
328
  throw new StoreAwaitsServer(`bring this store from version ${found} to ${SCHEMA_VERSION}`);
314
329
  if (found !== SCHEMA_VERSION && !upgrading)
@@ -378,17 +393,30 @@ export async function openSqliteStore(options) {
378
393
  // dropped, its rows heartbeats that each relay's runner writes again within its renewal, so none is copied.
379
394
  { sql: "DROP TABLE IF EXISTS runner_relays" },
380
395
  { sql: RUNNERS },
396
+ // Nor any computer a run made (schema.ts COMPUTER_INTERVALS): a computer made before it has no row.
397
+ { sql: COMPUTER_INTERVALS },
398
+ { sql: COMPUTER_INTERVALS_RUN },
381
399
  { sql: NATIVE_COMMANDS_INDEX },
382
400
  ], { full: true });
401
+ // A computer_intervals an earlier build of this version made has no disk or booked time (schema.ts
402
+ // COMPUTER_INTERVALS_ADDED): each column added where missing, its rows' disk unknown (null) and booked time none.
403
+ const intervalColumns = new Set((await connection.all("SELECT name FROM pragma_table_info('computer_intervals')")).map((column) => column.name));
404
+ const missing = Object.entries(COMPUTER_INTERVALS_ADDED).filter(([column]) => !intervalColumns.has(column)).map(([, sql]) => ({ sql }));
405
+ if (missing.length > 0)
406
+ await connection.write(missing, { full: true });
383
407
  await backfillNativeCommandOwners(connection);
384
- if (found === SCHEMA_VERSION - 2) {
408
+ if (found === 11) {
385
409
  const present = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
386
410
  await connection.write(listingUpgrade(present).map((sql) => ({ sql })), { full: true });
387
411
  }
388
- if (upgrading) {
412
+ if (found === 11 || found === 12) {
389
413
  const minted = new Set((await connection.all("SELECT name FROM pragma_table_info('minted_tokens')")).map((column) => column.name));
390
414
  await connection.write(relayUpgrade(minted).map((sql) => ({ sql })), { full: true });
391
415
  }
416
+ if (upgrading) {
417
+ const named = async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name));
418
+ await connection.write(purgeUpgrade(await named("runs"), await named("agents")).map((sql) => ({ sql })), { full: true });
419
+ }
392
420
  }
393
421
  }
394
422
  catch (error) {
@@ -455,20 +483,49 @@ function readOnly(tx) {
455
483
  }
456
484
  /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
457
485
  * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
458
- * `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX). */
486
+ * `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX), and whose WAL a
487
+ * purge checkpoints. */
459
488
  export function storeOver(connection, now, file) {
460
489
  return new SqliteStore(connection, now, undefined, file === undefined ? undefined : `${file}${SCRUB_SUFFIX}`);
461
490
  }
462
- /** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite and removes once no
463
- * file of the store keeps the bytes it replaced: a start that finds it finishes the scrub. */
491
+ /** How long a purge's checkpoint waits for another connection's reader or writer before it leaves the log to the next
492
+ * start's scrub: short, since every other request of the store's connection queues behind it. */
493
+ const PURGE_CHECKPOINT_BUSY_MS = 20;
494
+ /** A run's content in every table that keeps it by the run's id, gone: what a run's purge (Runs.purge) and its delete
495
+ * (Runs.remove) both drop. A table added for a run's content goes here, so neither path leaves it behind. */
496
+ async function dropRunContent(tx, runId) {
497
+ for (const table of PI_TABLES)
498
+ await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
499
+ await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
500
+ await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
501
+ await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
502
+ await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
503
+ await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
504
+ await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
505
+ await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
506
+ await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
507
+ await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
508
+ await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
509
+ }
510
+ /** An agent's own rows no tombstone keeps (its learning, its saved sign-ins and their tombstones), gone: what an agent's
511
+ * purge (Agents.purge) and its delete (Agents.remove) both drop. */
512
+ async function dropAgentPrivate(tx, agentId) {
513
+ await tx.run("DELETE FROM learning WHERE agent_id = ?", agentId);
514
+ await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
515
+ await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
516
+ }
517
+ /** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite (and a purge, when its
518
+ * checkpoint could not truncate the log) and removes once no file of the store keeps the bytes they replaced: a start
519
+ * that finds it finishes the scrub. */
464
520
  const SCRUB_SUFFIX = ".scrub";
465
521
  /** How long the scrub's VACUUM waits, once its busy wait ran out on another connection's write, before its one retry. */
466
522
  const VACUUM_RETRY_MS = 400;
467
- /** The marker at `path`, written and synced (its directory too) before the rewrite it marks changes a byte. */
523
+ /** The marker at `path`, written and synced (its directory too): before the rewrite it marks changes a byte, or once a
524
+ * purge's checkpoint left the log. */
468
525
  function markScrub(path) {
469
526
  const fd = openSync(path, "w", 0o600);
470
527
  try {
471
- writeSync(fd, "agentrun-serve: a rewrite of a secret this store kept in the clear may have left its old bytes in the store's free pages; the next start scrubs them and removes this file.\n");
528
+ writeSync(fd, "agentrun-serve: a rewrite of a secret this store kept in the clear, or a purge, may have left old bytes in the store's free pages or its WAL; the next start scrubs them and removes this file.\n");
472
529
  fsyncSync(fd);
473
530
  }
474
531
  finally {
@@ -496,6 +553,7 @@ class SqliteStore {
496
553
  settings;
497
554
  sealedKeys;
498
555
  computerLedger;
556
+ computerIntervals;
499
557
  pairedComputers;
500
558
  mintedTokens;
501
559
  runners;
@@ -523,6 +581,10 @@ class SqliteStore {
523
581
  #released = new Map();
524
582
  /** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
525
583
  #scrubMarker;
584
+ /** How many times a purge left the marker (#purged). The marker has two owners: secureRewrite removes it only when no
585
+ * purge left it since the step that covers that purge's log (its own start, or the checkpoint it asked), so a marker a
586
+ * purge left is never removed without a checkpoint that truncated the purge's frames. */
587
+ #purgeMarks = 0;
526
588
  constructor(db, now, origin, scrubMarker) {
527
589
  this.#db = db;
528
590
  this.#scrubMarker = scrubMarker;
@@ -533,13 +595,22 @@ class SqliteStore {
533
595
  const clock = () => storeNow(d, now);
534
596
  this.#clock = clock;
535
597
  const insertAgent = (tx, agent, at) => tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?)", agent.id, agent.name, agent.description ?? null, at);
598
+ /** Agent `agentId`'s row, held (a writer's row lock, as its purge takes it), or undefined when there is none; refused
599
+ * (AgentPurged) once it is purged: a write that waited on the purge's lock reads its purge time, and one that took the
600
+ * lock first commits before the purge reads anything. */
601
+ const heldAgent = async (tx, agentId) => {
602
+ await d.lockRow(tx, "agents", "id", agentId);
603
+ const agent = await tx.get("SELECT current_revision, archived_at, external_ref, purged_at FROM agents WHERE id = ?", agentId);
604
+ if (agent && agent.purged_at != null)
605
+ throw new AgentPurged(agentId, agent.archived_at, agent.purged_at);
606
+ return agent;
607
+ };
536
608
  const insertRevision = async (tx, agentId, revision, at, ifCurrent) => {
537
609
  // The parent is the agent's current revision now (null for its first): the agent must exist, which its first revision
538
610
  // (create) and a later one (addRevision, upgrade) both guarantee before this. Held (a writer's row lock), so two
539
611
  // revisions added at once, by this server or another on the same store, never both name the same parent, and
540
- // `ifCurrent` is compared with what no other writer can move until this commits.
541
- await d.lockRow(tx, "agents", "id", agentId);
542
- const agent = await tx.get("SELECT current_revision FROM agents WHERE id = ?", agentId);
612
+ // `ifCurrent` is compared with what no other writer can move until this commits. Never one of a purged agent.
613
+ const agent = await heldAgent(tx, agentId);
543
614
  if (!agent)
544
615
  throw new StoreConstraint(`no agent ${agentId}`);
545
616
  if (ifCurrent !== undefined && agent.current_revision !== ifCurrent)
@@ -561,13 +632,16 @@ class SqliteStore {
561
632
  /** Refused (AgentDeleting) when agent `agentId` is being deleted: another system's agent with an archive time, which
562
633
  * only its delete writes (AgentDeleting). The agent's row is held first (a writer's row lock, as the archive's UPDATE
563
634
  * takes it), so on Postgres a delete's archive that commits first is read here, and one that commits after waits for
564
- * this run to be in the store, where the delete's listing of the agent's runs finds it. */
635
+ * 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
636
+ * (AgentPurged): it takes no run and no trigger. */
565
637
  const refuseDeleting = async (tx, agentId) => {
566
- await d.lockRow(tx, "agents", "id", agentId);
567
- const agent = await tx.get("SELECT archived_at, external_ref FROM agents WHERE id = ?", agentId);
638
+ const agent = await heldAgent(tx, agentId);
568
639
  if (agent?.archived_at != null && agent.external_ref != null)
569
640
  throw new AgentDeleting(agentId);
570
641
  };
642
+ /** The runs whose launch is made from run `runId` (madeOf: a replay of its input, an audit's shadow), by id. Every
643
+ * launch is read (no index names its source): a purge's read, never a hot path. */
644
+ 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);
571
645
  /** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
572
646
  * while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
573
647
  * distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
@@ -595,7 +669,11 @@ class SqliteStore {
595
669
  const handedAnyIn = (tx) => tx.get(`SELECT id FROM runs WHERE state = 'running' AND sign_in_handed IS NOT NULL AND ${d.jsonArrayLength("sign_in_handed")} > 0 LIMIT 1`);
596
670
  this.agents = {
597
671
  put: async ({ id, name, description = null }) => {
598
- await db.write([{ sql: "INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET name = excluded.name, description = excluded.description", params: [id, name, description, now()] }]);
672
+ await db.transaction(async (tx) => {
673
+ // Never a purged agent's name or description written back.
674
+ await heldAgent(tx, id);
675
+ await tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET name = excluded.name, description = excluded.description", id, name, description, now());
676
+ });
599
677
  },
600
678
  create: async (agent, firstRevision) => {
601
679
  await db.transaction(async (tx) => {
@@ -617,9 +695,11 @@ class SqliteStore {
617
695
  const row = await db.get(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE agent_id = ? AND external_version = ?`, agentId, version);
618
696
  return row && revisionOf(row);
619
697
  },
620
- list: async ({ archived = false } = {}) => (await db.all(`SELECT ${AGENT_COLUMNS} FROM agents WHERE archived_at IS ${archived ? "NOT NULL" : "NULL"} ORDER BY created_at, id`)).map(agentOf),
698
+ list: async ({ archived = false, purged = false } = {}) => (await db.all(`SELECT ${AGENT_COLUMNS} FROM agents WHERE archived_at IS ${archived ? "NOT NULL" : "NULL"}${purged ? "" : " AND purged_at IS NULL"} ORDER BY created_at, id`)).map(agentOf),
621
699
  archive: async (id, archived, why) => db.transaction(async (tx) => {
622
700
  const at = now();
701
+ // A purged agent stays as its purge left it: archived, never unarchived.
702
+ await heldAgent(tx, id);
623
703
  await tx.run("UPDATE agents SET archived_at = ? WHERE id = ?", archived ? at : null, id);
624
704
  if (!archived)
625
705
  return [];
@@ -638,7 +718,11 @@ class SqliteStore {
638
718
  });
639
719
  },
640
720
  setCurrent: async (agentId, revisionId) => {
641
- const changed = await db.transaction((tx) => tx.runCounted("UPDATE agents SET current_revision = ? WHERE id = ? AND EXISTS (SELECT 1 FROM revisions WHERE id = ? AND agent_id = ?)", revisionId, agentId, revisionId, agentId));
721
+ const changed = await db.transaction(async (tx) => {
722
+ // Never a purged agent's: its current revision stays the one its runs' tombstones read.
723
+ await heldAgent(tx, agentId);
724
+ return tx.runCounted("UPDATE agents SET current_revision = ? WHERE id = ? AND EXISTS (SELECT 1 FROM revisions WHERE id = ? AND agent_id = ?)", revisionId, agentId, revisionId, agentId);
725
+ });
642
726
  if (changed === 0)
643
727
  throw new StoreConstraint(`${revisionId} is not a revision of agent ${agentId}`);
644
728
  },
@@ -648,9 +732,16 @@ class SqliteStore {
648
732
  },
649
733
  revisions: async (agentId) => (await db.all(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE agent_id = ? ORDER BY created_at, id`, agentId)).map(revisionOf),
650
734
  // Written only while the revision has none (the one place a revision changes after its save), then read back in the
651
- // same transaction: the pin that stood, this one or another first run's.
735
+ // same transaction: the pin that stood, this one or another first run's. Never on a purged agent's revision (its purge
736
+ // cleared every pin): its agent's row held first, as the purge holds it, and none written once it is purged.
652
737
  pinOnce: async (revisionId, pin) => {
653
738
  const row = await db.transaction(async (tx) => {
739
+ const of = await tx.get("SELECT agent_id FROM revisions WHERE id = ?", revisionId);
740
+ if (!of)
741
+ return undefined;
742
+ await d.lockRow(tx, "agents", "id", of.agent_id);
743
+ if ((await tx.get("SELECT purged_at FROM agents WHERE id = ?", of.agent_id))?.purged_at != null)
744
+ return undefined;
654
745
  await tx.run("UPDATE revisions SET mcp_pin = ? WHERE id = ? AND mcp_pin IS NULL", pinText(pin), revisionId);
655
746
  return tx.get("SELECT mcp_pin FROM revisions WHERE id = ?", revisionId);
656
747
  });
@@ -669,9 +760,7 @@ class SqliteStore {
669
760
  if (left.length)
670
761
  throw new TriggersLeft(agentId, left.map((one) => one.id));
671
762
  await tx.run("DELETE FROM learning_proposals WHERE agent_id = ?", agentId);
672
- await tx.run("DELETE FROM learning WHERE agent_id = ?", agentId);
673
- await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
674
- await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
763
+ await dropAgentPrivate(tx, agentId);
675
764
  // Its revisions in one statement (a revision's parent is the same agent's, checked at the statement's end), the
676
765
  // agent's pointer at its current one cleared first.
677
766
  await tx.run("UPDATE agents SET current_revision = NULL WHERE id = ?", agentId);
@@ -679,6 +768,31 @@ class SqliteStore {
679
768
  await tx.run("DELETE FROM agents WHERE id = ?", agentId);
680
769
  });
681
770
  },
771
+ purge: async (agentId) => {
772
+ const purged = await db.transaction(async (tx) => {
773
+ await d.lockRow(tx, "agents", "id", agentId);
774
+ const agent = await tx.get("SELECT purged_at FROM agents WHERE id = ?", agentId);
775
+ if (!agent || agent.purged_at !== null)
776
+ return false;
777
+ // Each run a tombstone first (Runs.purge): a run started past the delete's listing keeps the agent for the next one.
778
+ const left = await tx.get("SELECT id FROM runs WHERE agent_id = ? AND purged_at IS NULL LIMIT 1", agentId);
779
+ if (left)
780
+ throw new StoreConstraint(`agent ${agentId} still has run ${left.id} not purged: each is purged first (runs.purge)`);
781
+ const triggersLeft = await tx.all("SELECT id FROM triggers WHERE agent_id = ? ORDER BY id", agentId);
782
+ if (triggersLeft.length)
783
+ throw new TriggersLeft(agentId, triggersLeft.map((one) => one.id));
784
+ await dropAgentPrivate(tx, agentId);
785
+ // The answer a template apply kept under its key, which holds the agent as it was made.
786
+ await tx.run(`DELETE FROM idempotency WHERE scope = 'templates.apply' AND ${d.jsonText("response", ["agentId"])} = ?`, agentId);
787
+ // Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
788
+ await tx.run("UPDATE revisions SET body = '{}', skills = NULL, package = NULL, note = NULL, mcp_pin = NULL, monid_pin = NULL WHERE agent_id = ?", agentId);
789
+ // Its purge time last, in the same write as its name and description.
790
+ await tx.run("UPDATE agents SET name = '', description = NULL, purged_at = ? WHERE id = ?", now(), agentId);
791
+ return true;
792
+ });
793
+ if (purged)
794
+ await this.#purged();
795
+ },
682
796
  };
683
797
  this.templates = {
684
798
  apply: async (agent, revision, triggers, idempotencyKey) => db.transaction(async (tx) => {
@@ -966,6 +1080,16 @@ class SqliteStore {
966
1080
  return this.#queued(await db.transaction(async (tx) => {
967
1081
  const at = now();
968
1082
  await refuseDeleting(tx, agentId);
1083
+ // A run made from another (a replay of its input, an audit's shadow) never of a purged one: its source's row
1084
+ // held as its purge holds it, so either this commits first and the purge finds it (RunsMadeFromLeft), or the
1085
+ // purge does and this reads its purge time.
1086
+ const of = launch ? madeOf(launch.body) : undefined;
1087
+ if (of !== undefined) {
1088
+ await d.lockRow(tx, "runs", "id", of);
1089
+ const source = await tx.get("SELECT purged_at FROM runs WHERE id = ?", of);
1090
+ if (source && source.purged_at !== null)
1091
+ throw new RunPurged(of, id);
1092
+ }
969
1093
  const row = await tx.get(insert, id, agentId, revisionId, labelled, at);
970
1094
  if (origin)
971
1095
  await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
@@ -1014,10 +1138,10 @@ class SqliteStore {
1014
1138
  },
1015
1139
  launch: (runId) => readLaunch(db, runId),
1016
1140
  learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
1017
- list: async ({ agentId, revisionId, state, archived, labels, limit }) => {
1141
+ list: async ({ agentId, revisionId, state, archived, labels, limit, purged = false }) => {
1018
1142
  // 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,
1019
- // count, stat or notice names it.
1020
- const where = [NOT_A_LEARNING_RUN];
1143
+ // count, stat or notice names it. A purged run is a tombstone: only the readers that sum or count ask for it.
1144
+ const where = [NOT_A_LEARNING_RUN, ...(purged ? [] : ["purged_at IS NULL"])];
1021
1145
  const params = [];
1022
1146
  if (agentId !== undefined)
1023
1147
  (where.push("agent_id = ?"), params.push(agentId));
@@ -1050,7 +1174,7 @@ class SqliteStore {
1050
1174
  (where.push("runs.revision_id = ?"), params.push(revisionId));
1051
1175
  for (const [key, value] of Object.entries(labels ?? {}))
1052
1176
  (where.push(d.jsonObjectHas("runs.labels")), params.push(key, value));
1053
- where.push(`COALESCE(runs.archived_at, agents.archived_at) IS ${archived ? "NOT NULL" : "NULL"}`);
1177
+ where.push(`COALESCE(runs.archived_at, agents.archived_at) IS ${archived ? "NOT NULL" : "NULL"}`, "runs.purged_at IS NULL");
1054
1178
  if (status !== undefined)
1055
1179
  (where.push("runs.list_status = ?"), params.push(status));
1056
1180
  // A run still going (no settled status on its row) whose listing is behind: its list_status may say what it was.
@@ -1073,7 +1197,7 @@ class SqliteStore {
1073
1197
  const [row] = await db.all(`SELECT COUNT(*) AS count, SUM(CASE WHEN runs.state IN ('queued', 'running', 'parked')
1074
1198
  OR (runs.state = 'stopped' AND runs.outcome = 'stopped' AND runs.imported_from IS NULL AND revisions.kind = 'agentic') THEN 1 ELSE 0 END) AS live
1075
1199
  FROM runs JOIN revisions ON revisions.id = runs.revision_id
1076
- WHERE runs.agent_id = ? AND ${NOT_A_SHADOW_RUN} AND runs.${NOT_A_LEARNING_RUN}`, agentId);
1200
+ WHERE runs.agent_id = ? AND ${NOT_A_SHADOW_RUN} AND runs.${NOT_A_LEARNING_RUN} AND runs.purged_at IS NULL`, agentId);
1077
1201
  return { count: Number(row?.count ?? 0), live: Number(row?.live ?? 0) };
1078
1202
  },
1079
1203
  // The rows whose listing is behind, by the three ways one falls behind, each over its own partial index.
@@ -1081,7 +1205,7 @@ class SqliteStore {
1081
1205
  const n = clock();
1082
1206
  const held = heldAt(n.sql);
1083
1207
  const rows = await db.all(`SELECT id, list_mark AS mark, held FROM (
1084
- SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_mark < list_mark
1208
+ SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_mark < list_mark AND purged_at IS NULL
1085
1209
  UNION SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_live = 1 AND NOT ${held}
1086
1210
  UNION SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_until IS NOT NULL AND listing_until <= ${n.sql}
1087
1211
  ) AS behind ORDER BY held, started_at DESC, id DESC LIMIT ? OFFSET ?`, ...n.params, ...n.params, ...n.params, ...n.params, ...n.params, limit, offset);
@@ -1155,7 +1279,55 @@ class SqliteStore {
1155
1279
  // Archiving an archived run keeps its first time: a second archive is a no-op, never a new time.
1156
1280
  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] }]);
1157
1281
  },
1158
- every: async (agentId) => db.all("SELECT id, state FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId),
1282
+ every: async (agentId) => (await db.all("SELECT id, state, runner, purged_at FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId))
1283
+ .map((row) => ({ id: row.id, state: row.state, runner: row.runner, purgedAt: row.purged_at ?? null })),
1284
+ madeFrom: async (runId) => {
1285
+ 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);
1286
+ return [...new Set([...(await launchedFrom(db, runId)), ...learning])].sort();
1287
+ },
1288
+ purge: async (runId, kept) => {
1289
+ const purged = await db.transaction(async (tx) => {
1290
+ // Held as a run's end holds it: a write under a claim of it is either in before this, or finds it final.
1291
+ await d.lockRow(tx, "runs", "id", runId, "update");
1292
+ const run = await tx.get("SELECT state, runner, metrics, purged_at FROM runs WHERE id = ?", runId);
1293
+ if (!run || run.purged_at !== null)
1294
+ return false;
1295
+ if (!FINAL_STATES.includes(run.state) || run.runner !== null)
1296
+ 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`);
1297
+ // A replay or shadow made from it after its purge read them (runs.create, under this row's lock) holds a copy of
1298
+ // its input: each is purged first.
1299
+ const left = [];
1300
+ for (const id of await launchedFrom(tx, runId)) {
1301
+ if ((await tx.get("SELECT purged_at FROM runs WHERE id = ?", id))?.purged_at === null)
1302
+ left.push(id);
1303
+ }
1304
+ if (left.length)
1305
+ throw new RunsMadeFromLeft(runId, left);
1306
+ await dropRunContent(tx, runId);
1307
+ // What names it, let go: a trigger's last run, the firing that started it (its key and status kept, so it never
1308
+ // fires again; the event it was given, its payload and attributes, gone), a firing's wait behind it (the
1309
+ // trigger's room is read again, as for a run that ended), the run a machine's token was minted for.
1310
+ await tx.run("UPDATE triggers SET last_run_id = NULL WHERE last_run_id = ?", runId);
1311
+ await tx.run("UPDATE trigger_firings SET run_id = NULL, payload = NULL, attrs = NULL WHERE run_id = ?", runId);
1312
+ await tx.run("UPDATE trigger_firings SET waits_on = NULL WHERE waits_on = ?", runId);
1313
+ await tx.run("UPDATE minted_tokens SET run = NULL WHERE run = ?", runId);
1314
+ // Its kept learning: what its turn asked and answered and the proposal go; each row stays, with the proposal's
1315
+ // state alone, as the learning meter (learning.spend) and the list's leaving out of learning runs read it.
1316
+ for (const row of await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ?", runId)) {
1317
+ const state = JSON.parse(row.proposal)?.state;
1318
+ await tx.run("UPDATE learning_proposals SET turn = '{}', proposal = ? WHERE run_id = ? AND round = ?", json(typeof state === "string" ? { state } : {}), runId, row.round);
1319
+ }
1320
+ // Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
1321
+ // read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
1322
+ const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
1323
+ await tx.run("UPDATE runs SET summary = NULL, labels = NULL, sign_in_handed = NULL, metrics = ? WHERE id = ?", json(metrics), runId);
1324
+ // Its listing, and its purge time last: no list shows it, and no lister builds it again.
1325
+ 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);
1326
+ return true;
1327
+ });
1328
+ if (purged)
1329
+ await this.#purged();
1330
+ },
1159
1331
  remove: async (runId) => {
1160
1332
  await db.transaction(async (tx) => {
1161
1333
  // Held as a run's end holds it: a write under a claim of it is either in before this, or finds no row.
@@ -1165,23 +1337,14 @@ class SqliteStore {
1165
1337
  return;
1166
1338
  if (!FINAL_STATES.includes(run.state))
1167
1339
  throw new StoreConstraint(`run ${runId} is ${run.state}: only a final run is removed`);
1168
- for (const table of PI_TABLES)
1169
- await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
1170
- await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
1171
- await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
1172
- await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
1173
- await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
1174
- await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
1175
- await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
1176
- await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
1177
- await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
1340
+ await dropRunContent(tx, runId);
1178
1341
  await tx.run("DELETE FROM learning_proposals WHERE run_id = ?", runId);
1179
- await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
1180
- await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
1342
+ // Its computers' usage, which a purge keeps (figures, no words).
1343
+ await tx.run("DELETE FROM computer_intervals WHERE run_id = ?", runId);
1181
1344
  await tx.run("DELETE FROM runs WHERE id = ?", runId);
1182
1345
  });
1183
1346
  },
1184
- reopen: async (runId, { kind, body = null }, { launchSealed } = {}) => {
1347
+ reopen: async (runId, { kind, body = null }, { launchSealed, endedAt } = {}) => {
1185
1348
  const command = await db.transaction(async (tx) => {
1186
1349
  // Never a run of an agent being deleted opened again (its mark, read in this transaction).
1187
1350
  const of = await tx.get("SELECT agent_id FROM runs WHERE id = ?", runId);
@@ -1189,7 +1352,8 @@ class SqliteStore {
1189
1352
  await refuseDeleting(tx, of.agent_id);
1190
1353
  // Back to running, released: the epoch, the journal, cost_usd and metrics stay (its next turn is booked on what it
1191
1354
  // spent); the end's own fields go. Only an agentic run that ended completed, not imported, not a learning run.
1192
- const reopened = await tx.runCounted(`UPDATE runs SET ${REOPEN_SET} WHERE id = ? AND ${reopenableWhere(d)}`, runId);
1355
+ const at = endedAt === undefined ? { sql: "", params: [] } : { sql: " AND ended_at = ?", params: [endedAt] };
1356
+ const reopened = await tx.runCounted(`UPDATE runs SET ${REOPEN_SET} WHERE id = ? AND ${reopenableWhere(d)}${at.sql}`, runId, ...at.params);
1193
1357
  if (reopened === 0)
1194
1358
  throw new RunFinal(runId);
1195
1359
  // The message's launch secrets, with it: the claim that runs its turn reads them.
@@ -1264,7 +1428,7 @@ class SqliteStore {
1264
1428
  }
1265
1429
  }
1266
1430
  // An update that made the run final: its other untaken rows are refused in this transaction, after its own takes.
1267
- await refuseLeftovers(tx, claim.runId, patch.state, at, d);
1431
+ await refuseLeftovers(tx, claim.runId, patch.state, at, d, patch.keepsEnd === true);
1268
1432
  // The bind's save lease, in this same transaction as the sign_in_handed write just made (applyRunPatch, under
1269
1433
  // SIGN_IN_HANDED_LOCK): this run saves unless another run already holds one of the handed pointers (a running run,
1270
1434
  // or — within signInSettleMs of leaving running, a vendor's settle window — one that left running less than that
@@ -1470,18 +1634,20 @@ class SqliteStore {
1470
1634
  ...(row.learning_run_id === null ? {} : { learningRunId: row.learning_run_id }), createdAt: row.created_at,
1471
1635
  });
1472
1636
  const PROPOSAL_COLUMNS = "run_id, round, agent_id, turn, proposal, learning_run_id, created_at";
1637
+ // A purged run's kept learning is its state alone (Runs.purge), for the learning meter: no reader of learning reads it.
1638
+ const NOT_PURGED = "NOT EXISTS (SELECT 1 FROM runs WHERE runs.id = learning_proposals.run_id AND runs.purged_at IS NOT NULL)";
1473
1639
  this.learning = {
1474
1640
  // A round asked for, else the run's newest.
1475
1641
  proposal: async (runId, round) => {
1476
1642
  const row = round === undefined
1477
- ? await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? ORDER BY round DESC LIMIT 1`, runId)
1478
- : await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? AND round = ?`, runId, round);
1643
+ ? await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? AND ${NOT_PURGED} ORDER BY round DESC LIMIT 1`, runId)
1644
+ : await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? AND round = ? AND ${NOT_PURGED}`, runId, round);
1479
1645
  return row ? proposalOf(row) : undefined;
1480
1646
  },
1481
- proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
1647
+ proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? AND ${NOT_PURGED} ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
1482
1648
  kept: async (agentId) => {
1483
- const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY run_id, round`, agentId)).map(proposalOf);
1484
- const learningRuns = (await db.all(`SELECT ${RUN_COLUMNS} FROM runs WHERE id IN (SELECT learning_run_id FROM learning_proposals WHERE agent_id = ? AND learning_run_id IS NOT NULL)`, agentId)).map(runOf);
1649
+ const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? AND ${NOT_PURGED} ORDER BY run_id, round`, agentId)).map(proposalOf);
1650
+ const learningRuns = (await db.all(`SELECT ${RUN_COLUMNS} FROM runs WHERE id IN (SELECT learning_run_id FROM learning_proposals WHERE agent_id = ? AND learning_run_id IS NOT NULL AND ${NOT_PURGED})`, agentId)).map(runOf);
1485
1651
  return { proposals, learningRuns };
1486
1652
  },
1487
1653
  spend: async ({ from, to }) => {
@@ -1645,6 +1811,26 @@ class SqliteStore {
1645
1811
  return (result?.changes ?? 0) === 1;
1646
1812
  },
1647
1813
  };
1814
+ this.computerIntervals = {
1815
+ opened: async (row) => {
1816
+ await db.write([{
1817
+ sql: "INSERT INTO computer_intervals (provider, provider_id, run_id, kind, gpu_type, gpu_count, cpus, memory_mb, disk_gb, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (provider, provider_id) DO NOTHING",
1818
+ params: [row.provider, row.providerId, row.runId, row.kind, row.gpuType, row.gpuCount, row.cpus, row.memoryMb, row.diskGb, row.startedAt],
1819
+ }]);
1820
+ },
1821
+ kept: async (provider, providerId) => {
1822
+ await db.write([{ sql: "UPDATE computer_intervals SET kept = 1 WHERE provider = ? AND provider_id = ?", params: [provider, providerId] }]);
1823
+ },
1824
+ ended: async (provider, providerId, at) => {
1825
+ await db.write([{ sql: "UPDATE computer_intervals SET ended_at = ? WHERE provider = ? AND provider_id = ? AND ended_at IS NULL", params: [at, provider, providerId] }]);
1826
+ },
1827
+ booked: async (provider, providerId, ms) => {
1828
+ if (!Number.isSafeInteger(ms) || ms <= 0)
1829
+ return;
1830
+ await db.write([{ sql: "UPDATE computer_intervals SET booked_ms = booked_ms + ? WHERE provider = ? AND provider_id = ?", params: [ms, provider, providerId] }]);
1831
+ },
1832
+ 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),
1833
+ };
1648
1834
  const PAIRED = "SELECT id, name, hello, driver, labels, pairing_id, created_at, seen_at, revoked_at FROM paired_computers";
1649
1835
  this.pairedComputers = {
1650
1836
  addCode: async (id, codeSha256, expiresAt) => {
@@ -1944,31 +2130,54 @@ class SqliteStore {
1944
2130
  handedAny: async () => (await handedAnyIn(db))?.id,
1945
2131
  };
1946
2132
  }
2133
+ /** After a purge committed (runs.purge, agents.purge), on a SQLite store with a file: a WAL checkpoint (TRUNCATE).
2134
+ * secure_delete (worker.ts open) zeroed the purged bytes in the pages the purge wrote, but those pages are new frames
2135
+ * in the WAL: the file keeps its earlier images of them, and the WAL its earlier frames, until a checkpoint copies the
2136
+ * zeroed pages into the file and truncates the log. A reader in another connection (a runner's read, a backup) may hold
2137
+ * the log back: the checkpoint waits PURGE_CHECKPOINT_BUSY_MS for it, not the connection's own busy wait, since every
2138
+ * request of the store's one connection queues behind it (the purge already committed). One it held back (or that
2139
+ * failed) leaves secureRewrite's marker, so the next start's scrub truncates the log, a crash between included. A marker
2140
+ * that cannot be written (a full disk) throws, the purge committed: its caller answers it as the fault it is (a 500 the
2141
+ * server logs), and drops what it served of the purged run all the same (agent-delete.ts purgeOneOrRefuse). */
2142
+ async #purged() {
2143
+ const marker = this.#scrubMarker;
2144
+ const db = this.#db;
2145
+ if (marker === undefined || !(db instanceof Connection))
2146
+ return;
2147
+ const checkpoint = await db.checkpoint(PURGE_CHECKPOINT_BUSY_MS).catch(() => undefined);
2148
+ if (checkpoint?.busy === 0)
2149
+ return;
2150
+ this.#purgeMarks++;
2151
+ try {
2152
+ markScrub(marker);
2153
+ }
2154
+ catch (error) {
2155
+ 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 });
2156
+ }
2157
+ }
1947
2158
  async secureRewrite(work, options = {}) {
1948
2159
  const marker = this.#scrubMarker;
1949
- if (this.#db.dialect.name !== "sqlite" || marker === undefined)
2160
+ const db = this.#db;
2161
+ if (marker === undefined || !(db instanceof Connection))
1950
2162
  return { rewritten: await work() };
1951
2163
  // Written before any byte changes: a server that dies after the rewrite committed, and before the scrub below is done,
1952
2164
  // leaves it, and its next start scrubs though no row is left in the clear.
1953
2165
  const pending = existsSync(marker);
2166
+ const purgesBefore = this.#purgeMarks;
1954
2167
  markScrub(marker);
1955
- let rewritten;
1956
- await this.#db.all("PRAGMA secure_delete = ON");
1957
- try {
1958
- rewritten = await work();
1959
- }
1960
- finally {
1961
- await this.#db.all("PRAGMA secure_delete = OFF");
1962
- }
1963
- if (rewritten === 0 && !pending) {
2168
+ // secure_delete is on for the connection's whole life (worker.ts open): a rewritten row's old bytes are zeroed in its page.
2169
+ const rewritten = await work();
2170
+ // Nothing rewritten, and the marker is this call's alone: no purge left it while the work ran (#purgeMarks). One that
2171
+ // did needs the checkpoint below, or the next start's scrub.
2172
+ if (rewritten === 0 && !pending && this.#purgeMarks === purgesBefore) {
1964
2173
  rmSync(marker, { force: true });
1965
2174
  return { rewritten };
1966
2175
  }
1967
2176
  // Asked with no VACUUM (a server already serving): the marker stays, and the next start's scrub runs it before it serves.
1968
2177
  if (options.vacuum === false)
1969
2178
  return { rewritten, left: "deferred" };
1970
- // secure_delete zeroes only the bytes `work` freed: a copy an earlier, ordinary update of the row left (a pause, a
1971
- // rename, a firing) is in a free block or page still. VACUUM rebuilds the file with neither, through the log; the
2179
+ // A copy an update of the row left before secure_delete was on (a store an earlier server wrote: a pause, a rename, a
2180
+ // firing) is in a free block or page still. VACUUM rebuilds the file with neither, through the log; the
1972
2181
  // checkpoint copies it into the file and truncates the log. Run outside any transaction.
1973
2182
  try {
1974
2183
  // Another connection's write (a runner's) may hold the lock past the busy wait: one retry after a short pause.
@@ -1978,10 +2187,12 @@ class SqliteStore {
1978
2187
  await new Promise((resolve) => setTimeout(resolve, VACUUM_RETRY_MS));
1979
2188
  await this.#db.all("VACUUM");
1980
2189
  });
1981
- const [checkpoint] = await this.#db.all("PRAGMA wal_checkpoint(TRUNCATE)");
2190
+ const purgesBefore = this.#purgeMarks;
2191
+ const checkpoint = await db.checkpoint();
1982
2192
  // A reader in another connection (a runner, a backup) held the log back: the old frames are there until a
1983
- // checkpoint is done, so the marker stays.
1984
- if (checkpoint?.busy !== 0)
2193
+ // checkpoint is done, so the marker stays. So does one a purge left after this checkpoint was asked: its frames may
2194
+ // be past it.
2195
+ if (checkpoint?.busy !== 0 || this.#purgeMarks !== purgesBefore)
1985
2196
  return { rewritten, left: "busy" };
1986
2197
  }
1987
2198
  catch (error) {