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

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 (146) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +142 -17
  3. package/dist/agents-store.js +7 -3
  4. package/dist/api-only.d.ts +2 -1
  5. package/dist/api-only.js +3 -2
  6. package/dist/capacity.d.ts +50 -0
  7. package/dist/capacity.js +49 -0
  8. package/dist/cli-learning/claude-wire.d.ts +41 -0
  9. package/dist/cli-learning/claude-wire.js +258 -0
  10. package/dist/cli-learning/cli.d.ts +11 -0
  11. package/dist/cli-learning/cli.js +241 -0
  12. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  13. package/dist/cli-learning/codex-worktree.js +119 -0
  14. package/dist/cli-learning/connections.d.ts +62 -0
  15. package/dist/cli-learning/connections.js +87 -0
  16. package/dist/cli-learning/entry.d.ts +1 -0
  17. package/dist/cli-learning/entry.js +4 -0
  18. package/dist/cli-learning/evidence.d.ts +78 -0
  19. package/dist/cli-learning/evidence.js +492 -0
  20. package/dist/cli-learning/hook.d.ts +33 -0
  21. package/dist/cli-learning/hook.js +544 -0
  22. package/dist/cli-learning/install.d.ts +33 -0
  23. package/dist/cli-learning/install.js +335 -0
  24. package/dist/cli-learning/observation-proof.d.ts +14 -0
  25. package/dist/cli-learning/observation-proof.js +10 -0
  26. package/dist/cli-learning/policy.d.ts +48 -0
  27. package/dist/cli-learning/policy.js +363 -0
  28. package/dist/cli-learning/schema.d.ts +16 -0
  29. package/dist/cli-learning/schema.js +27 -0
  30. package/dist/cli-learning/state.d.ts +23 -0
  31. package/dist/cli-learning/state.js +61 -0
  32. package/dist/cli.js +24 -2
  33. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  34. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  35. package/dist/console/index.html +2 -2
  36. package/dist/email/email-faux.d.ts +3 -1
  37. package/dist/email/email-faux.js +3 -2
  38. package/dist/email/routes.js +22 -12
  39. package/dist/harness-install.d.ts +6 -2
  40. package/dist/harness-install.js +40 -8
  41. package/dist/harness.d.ts +1 -1
  42. package/dist/harness.js +2 -2
  43. package/dist/learn/secrets.js +14 -3
  44. package/dist/learning-words.d.ts +1 -1
  45. package/dist/learning-words.js +1 -1
  46. package/dist/mcp-pin-first.js +2 -1
  47. package/dist/mcp-private-hosts.d.ts +24 -3
  48. package/dist/mcp-private-hosts.js +53 -3
  49. package/dist/model-gateway.d.ts +2 -0
  50. package/dist/model-gateway.js +3 -1
  51. package/dist/native/runtimes.d.ts +2 -0
  52. package/dist/native/runtimes.js +2 -0
  53. package/dist/observation/learning.d.ts +32 -0
  54. package/dist/observation/learning.js +66 -0
  55. package/dist/observation/observer.d.ts +8 -1
  56. package/dist/observation/observer.js +89 -9
  57. package/dist/observation/schema.js +12 -4
  58. package/dist/observation/usage-identity.d.ts +9 -0
  59. package/dist/observation/usage-identity.js +11 -0
  60. package/dist/openapi.js +89 -13
  61. package/dist/run-launch.d.ts +14 -0
  62. package/dist/run-launch.js +4 -0
  63. package/dist/run-view.d.ts +2 -0
  64. package/dist/run-view.js +12 -7
  65. package/dist/runner/adapter-loop.js +29 -26
  66. package/dist/runner/adapter-run-spec.js +2 -2
  67. package/dist/runner/beside.d.ts +13 -0
  68. package/dist/runner/beside.js +27 -8
  69. package/dist/runner/cli-run-spec.js +2 -2
  70. package/dist/runner/disk-free.d.ts +44 -0
  71. package/dist/runner/disk-free.js +96 -0
  72. package/dist/runner/feedback-round.d.ts +12 -8
  73. package/dist/runner/feedback-round.js +16 -30
  74. package/dist/runner/harness-loops.js +3 -1
  75. package/dist/runner/journal-kinds.d.ts +1 -1
  76. package/dist/runner/learning-end.js +4 -0
  77. package/dist/runner/main.d.ts +17 -6
  78. package/dist/runner/main.js +187 -45
  79. package/dist/runner/presence.d.ts +11 -2
  80. package/dist/runner/presence.js +31 -3
  81. package/dist/runner/run-child-host.d.ts +12 -15
  82. package/dist/runner/run-child-host.js +46 -108
  83. package/dist/runner/run-errors.js +2 -0
  84. package/dist/runner/runner-check.d.ts +51 -0
  85. package/dist/runner/runner-check.js +206 -0
  86. package/dist/runner/runner-metrics.d.ts +19 -0
  87. package/dist/runner/runner-metrics.js +49 -0
  88. package/dist/runner/runner.d.ts +37 -0
  89. package/dist/runner/runner.js +43 -3
  90. package/dist/runner/sdk-loop.js +34 -22
  91. package/dist/runs-over-store.d.ts +8 -1
  92. package/dist/runs-over-store.js +57 -9
  93. package/dist/sdk/runs.d.ts +22 -2
  94. package/dist/sdk/runs.js +103 -34
  95. package/dist/server.d.ts +3 -0
  96. package/dist/server.js +149 -26
  97. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  98. package/dist/start-switches.js +2 -0
  99. package/dist/stats.d.ts +4 -0
  100. package/dist/stats.js +1 -1
  101. package/dist/store/agent-body.d.ts +12 -0
  102. package/dist/store/agent-body.js +16 -2
  103. package/dist/store/dialect.d.ts +2 -0
  104. package/dist/store/dialect.js +1 -0
  105. package/dist/store/index.d.ts +3 -3
  106. package/dist/store/index.js +2 -2
  107. package/dist/store/postgres/connection.d.ts +5 -2
  108. package/dist/store/postgres/connection.js +19 -7
  109. package/dist/store/postgres/dialect.js +1 -0
  110. package/dist/store/postgres/migrate.d.ts +30 -0
  111. package/dist/store/postgres/migrate.js +72 -5
  112. package/dist/store/postgres/migration-lint.d.ts +8 -0
  113. package/dist/store/postgres/migration-lint.js +119 -0
  114. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  115. package/dist/store/postgres/store.d.ts +8 -3
  116. package/dist/store/postgres/store.js +31 -11
  117. package/dist/store/schema.d.ts +18 -1
  118. package/dist/store/schema.js +33 -2
  119. package/dist/store/sqlite/run-launch.d.ts +9 -1
  120. package/dist/store/sqlite/run-launch.js +44 -0
  121. package/dist/store/sqlite/store.d.ts +17 -0
  122. package/dist/store/sqlite/store.js +87 -10
  123. package/dist/store/store-schema.d.ts +34 -0
  124. package/dist/store/store-schema.js +125 -0
  125. package/dist/store/store.d.ts +53 -1
  126. package/dist/store/store.js +13 -0
  127. package/dist/store-reads/analytics.d.ts +3 -2
  128. package/dist/store-reads/analytics.js +20 -8
  129. package/dist/store-view.d.ts +4 -3
  130. package/dist/store-view.js +11 -7
  131. package/dist/templates.d.ts +3 -2
  132. package/dist/tool-gate.d.ts +4 -2
  133. package/dist/unified-usage.d.ts +24 -0
  134. package/dist/unified-usage.js +400 -0
  135. package/dist/uploads-archil.d.ts +100 -0
  136. package/dist/uploads-archil.js +430 -0
  137. package/dist/uploads.d.ts +55 -1
  138. package/dist/uploads.js +185 -98
  139. package/dist/validate.js +1 -1
  140. package/dist/workspace/archil-disk.d.ts +6 -5
  141. package/dist/workspace/archil-disk.js +27 -12
  142. package/dist/workspace/archil.js +3 -2
  143. package/package.json +10 -10
  144. package/skills/agentrun-serve/SKILL.md +52 -7
  145. package/dist/console/assets/index-D0mr9wfZ.css +0 -1
  146. package/dist/console/assets/index-D7G6o-1E.js +0 -720
@@ -8,6 +8,7 @@
8
8
  import { sdkBindingOf } from "../sdk/runtimes.js";
9
9
  import { createHash } from "node:crypto";
10
10
  import { nativeBindingOf } from "../native/binding.js";
11
+ import { isNativeRuntime } from "../native/runtimes.js";
11
12
  import { learningSettingIssue, learningSettingOf } from "../learning-setting.js";
12
13
  /** A revision's body the store refuses: its content is not one the store keeps. The server maps it to an input refusal. */
13
14
  export class AgentBodyInvalid extends Error {
@@ -38,6 +39,16 @@ export const isSkillPath = (value) => typeof value === "string" && value !== ""
38
39
  /** An id a host knows: a harness, a place's mode, a box (lowercase letters, digits and dashes). */
39
40
  const HOST_ID = /^[a-z][a-z0-9-]{0,63}$/;
40
41
  const hostId = (value) => typeof value === "string" && HOST_ID.test(value);
42
+ export const cliLearningOf = (body) => isObject(body) && isObject(body.cli_learning) && isNativeRuntime(body.cli_learning.runtime) && typeof body.cli_learning.connection_id === "string" && typeof body.cli_learning.project === "string" ? body.cli_learning : undefined;
43
+ /** Read old CLI enrollment settings through the current model without rewriting its revision or learned files.
44
+ * New definitions still reject "notes"; existing CLI profiles use owner corrections and no workflow bridge. */
45
+ export function learningSettingForBody(body) {
46
+ if (!isObject(body) || body.learning === undefined)
47
+ return undefined;
48
+ if (cliLearningOf(body) && body.learning === "notes")
49
+ return true;
50
+ return learningSettingIssue(body.learning) === undefined ? body.learning : undefined;
51
+ }
41
52
  /** A place as a body keeps it: `{mode, box?}`, nothing else. */
42
53
  function placeOf(place) {
43
54
  if (!isObject(place) || !hostId(place.mode) || (place.box !== undefined && !hostId(place.box)) || Object.keys(place).some((key) => key !== "mode" && key !== "box"))
@@ -130,10 +141,13 @@ export function bodyOf(input) {
130
141
  invalid("the modelTiers are not fast and strong to a non-empty model");
131
142
  if (input.sdk !== undefined && (!isObject(input.sdk) || Object.keys(input.sdk).some(key => key !== "runtime" && key !== "platform") || !sdkBindingOf(input.sdk)))
132
143
  invalid("sdk is {runtime: claude-agent-sdk, codex-sdk or eve}, or {runtime: external, platform: a label of 1–80 characters without surrounding whitespace, controls or lone surrogates}");
133
- if (input.sdk && input.native)
134
- invalid("sdk and native connections are mutually exclusive");
144
+ if ([input.sdk, input.native, input.cli_learning].filter(Boolean).length > 1)
145
+ invalid("sdk, native and cli_learning connections are mutually exclusive");
146
+ if (input.cli_learning !== undefined && (!cliLearningOf(input) || Object.keys(input.cli_learning).some(key => !["runtime", "connection_id", "project"].includes(key)) || !input.cli_learning.connection_id || !input.cli_learning.project))
147
+ invalid("cli_learning requires a registered runtime, connection_id and project");
135
148
  const body = {
136
149
  ...(input.sdk ? { sdk: { ...input.sdk } } : {}),
150
+ ...(input.cli_learning ? { cli_learning: { ...input.cli_learning } } : {}),
137
151
  instructions: input.instructions,
138
152
  ...(input.native !== undefined ? { native: nativeBindingOf(input.native) } : {}),
139
153
  skills: skillShas,
@@ -6,6 +6,8 @@ export interface Dialect {
6
6
  readonly name: "sqlite" | "postgres";
7
7
  /** A JSON TEXT column's value at `path` (object keys), as SQL text to compare with a string parameter. */
8
8
  jsonText(column: string, path: readonly string[]): string;
9
+ /** The value at `path` as JSON text, preserving scalar types; SQL NULL when absent. */
10
+ jsonValue(column: string, path: readonly string[]): string;
9
11
  /** True unless the JSON TEXT column's value at `path` is false or 0 (absent or null count as true). */
10
12
  jsonNotFalse(column: string, path: readonly string[]): string;
11
13
  /** True when the JSON array in TEXT column `column` holds the string parameter that follows (one `?`). */
@@ -13,6 +13,7 @@ const jsonPath = (path) => `'$.${path.join(".")}'`;
13
13
  export const SQLITE = {
14
14
  name: "sqlite",
15
15
  jsonText: (column, path) => `json_extract(${column}, ${jsonPath(path)})`,
16
+ jsonValue: (column, path) => `${column} -> ${jsonPath(path)}`,
16
17
  jsonNotFalse: (column, path) => `json_extract(${column}, ${jsonPath(path)}) IS NOT 0`,
17
18
  jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ?)`,
18
19
  jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) AS entry WHERE entry.key = ? AND entry.value = ?)`,
@@ -1,5 +1,5 @@
1
- export { AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
- export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerIntervalRow, ComputerIntervals, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, PurgeKept, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
1
+ export { AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
+ export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerIntervalRow, ComputerIntervals, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, StoreSchemaState, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, PurgeKept, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
3
3
  export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunLaunch, openRunMcpAuth, type RunLaunchSecrets, type ComposioBinding, type RunMcpAuth, type RunMcpEntry, type RunModelKey, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, type AgenticBody, bodyOf, canonical, isObject, isSkillPath, type PromptVariant, type ModelTiers, type MonidPinBody, type RevisionBodyInput, type RevisionComputer, type RevisionPlace, sha256, type ToolSettings, type WorkflowBody, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -12,6 +12,6 @@ export { cleanText, type Dialect, SQLITE } from "./dialect.js";
12
12
  export { DEFAULT_STORE_POOL_SIZE, MAX_STORE_POOL_SIZE, openStore, type OpenStoreOptions, storePlace, storePoolSize, storeTarget, type StoreTarget } from "./open.js";
13
13
  export { CLOCK_WARN_MS, DEFAULT_SCHEMA, openPostgresStore, type PostgresStoreOptions, postgresWhere } from "./postgres/store.js";
14
14
  export { LEASE_DEADLINE_MS, OWNER_WAIT_MS, PgConnection, SCHEMA_NAME, STORE_CONNECT_TIMEOUT_MS, Unanswered } from "./postgres/connection.js";
15
- export { dropPostgresSchema, migrate, migrationsIn, versionOf as postgresVersionOf } from "./postgres/migrate.js";
15
+ export { dropPostgresSchema, LAST_UNMARKED, marksBreaking, migrate, type Migration, migrationsIn, runnerFloorOf, runnerOn, RUNNERS_BREAKING, type SchemaState, versionOf as postgresVersionOf } from "./postgres/migrate.js";
16
16
  export { applyRunPatch, RUN_COLUMNS, runOf, type RunRecord } from "./sqlite/run-patch.js";
17
17
  export { readLaunch, writeLaunch } from "./sqlite/run-launch.js";
@@ -1,5 +1,5 @@
1
1
  // The one store (design 2.1), for the cutover: nothing on main imports it until then.
2
- export { AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
+ export { AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
3
3
  export { aadOf, openMcpCredential, openRunLaunch, openRunMcpAuth, sealColumn, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, bodyOf, canonical, isObject, isSkillPath, sha256, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -12,6 +12,6 @@ export { cleanText, SQLITE } from "./dialect.js";
12
12
  export { DEFAULT_STORE_POOL_SIZE, MAX_STORE_POOL_SIZE, openStore, storePlace, storePoolSize, storeTarget } from "./open.js";
13
13
  export { CLOCK_WARN_MS, DEFAULT_SCHEMA, openPostgresStore, postgresWhere } from "./postgres/store.js";
14
14
  export { LEASE_DEADLINE_MS, OWNER_WAIT_MS, PgConnection, SCHEMA_NAME, STORE_CONNECT_TIMEOUT_MS, Unanswered } from "./postgres/connection.js";
15
- export { dropPostgresSchema, migrate, migrationsIn, versionOf as postgresVersionOf } from "./postgres/migrate.js";
15
+ export { dropPostgresSchema, LAST_UNMARKED, marksBreaking, migrate, migrationsIn, runnerFloorOf, runnerOn, RUNNERS_BREAKING, versionOf as postgresVersionOf } from "./postgres/migrate.js";
16
16
  export { applyRunPatch, RUN_COLUMNS, runOf } from "./sqlite/run-patch.js";
17
17
  export { readLaunch, writeLaunch } from "./sqlite/run-launch.js";
@@ -91,8 +91,11 @@ export declare class PgConnection implements StoreConnection {
91
91
  transaction<T>(callback: (transaction: Tx) => Promise<T>, options?: TransactionOptions): Promise<T>;
92
92
  /** The database's clock (ms): the runner compares its own with it at its start. */
93
93
  clock(): Promise<number>;
94
- /** One client of the pool for setup (migrations), released after `work`. */
95
- withClient<T>(work: (client: pg.PoolClient) => Promise<T>): Promise<T>;
94
+ /** One client of the pool for setup (migrations), released after `work`. With `deadlineMs`, `work` unanswered past it is
95
+ * Unanswered and its client destroyed, never waited on (a read that runs on a timer: Store.schemaState). The deadline
96
+ * starts once a client is in hand: taking one waits as every call's does (a new connection's connect timeout, or a full
97
+ * pool's wait), so a read can take that long beside it. */
98
+ withClient<T>(work: (client: pg.PoolClient) => Promise<T>, deadlineMs?: number): Promise<T>;
96
99
  /** How long a statement waits for a lock (lock_timeout). */
97
100
  get busyTimeoutMs(): number;
98
101
  /** Waits for every call in flight, then ends the pool and lets the owner lock go. */
@@ -249,8 +249,14 @@ function typed(error, deadlineMs) {
249
249
  const message = String(e?.message ?? error);
250
250
  const code = typeof e?.code === "string" ? e.code : "";
251
251
  // 23: integrity, its rule by SQLSTATE; 22P02 a CHECK's json cast of text that is not JSON.
252
- if (code.startsWith("23") || code === "22P02")
253
- return new StoreConstraint(message, RULES[code] ? { rule: RULES[code] } : code === "22P02" ? { rule: "check" } : {});
252
+ if (code.startsWith("23") || code === "22P02") {
253
+ const refused = new StoreConstraint(message, RULES[code] ? { rule: RULES[code] } : code === "22P02" ? { rule: "check" } : {});
254
+ // JSON TEXT can hold lone surrogates that extraction refuses. Keep only a fixed, private diagnostic so a
255
+ // read-only projection can use its legacy JS parser; never retain JSON context, query text or parameters.
256
+ if (code === "22P02" && (e.detail === "Unicode low surrogate must follow a high surrogate." || e.detail === "Unicode high surrogate must not follow a high surrogate."))
257
+ Object.defineProperty(refused, "cause", { value: { code, reason: "json_surrogate" } });
258
+ return refused;
259
+ }
254
260
  // 55P03 a lock not granted within lock_timeout; 40P01 a deadlock; 40001 a serialization failure.
255
261
  if (code === "55P03" || code === "40P01" || code === "40001")
256
262
  return new StoreBusy(`the store stayed locked past its busy wait: ${message}`);
@@ -707,15 +713,21 @@ export class PgConnection {
707
713
  async clock() {
708
714
  return Number((await this.get("SELECT (extract(epoch FROM clock_timestamp()) * 1000)::bigint AS now")).now);
709
715
  }
710
- /** One client of the pool for setup (migrations), released after `work`. */
711
- async withClient(work) {
716
+ /** One client of the pool for setup (migrations), released after `work`. With `deadlineMs`, `work` unanswered past it is
717
+ * Unanswered and its client destroyed, never waited on (a read that runs on a timer: Store.schemaState). The deadline
718
+ * starts once a client is in hand: taking one waits as every call's does (a new connection's connect timeout, or a full
719
+ * pool's wait), so a read can take that long beside it. */
720
+ async withClient(work, deadlineMs) {
712
721
  return this.#call(async () => {
713
722
  const client = await this.#pool.connect();
714
723
  try {
715
- return await work(client);
716
- }
717
- finally {
724
+ const result = await (deadlineMs === undefined ? work(client) : answered(work(client), deadlineMs, "a read of the schema's version"));
718
725
  client.release();
726
+ return result;
727
+ }
728
+ catch (error) {
729
+ client.release(error instanceof Unanswered ? error : undefined);
730
+ throw error;
719
731
  }
720
732
  });
721
733
  }
@@ -9,6 +9,7 @@ export function postgresDialect(schema, { testClock = false } = {}) {
9
9
  name: "postgres",
10
10
  ...(testClock ? {} : { nowSql: DATABASE_NOW_MS }),
11
11
  jsonText: (column, keys) => `(${column}::json #>> ${path(keys)})`,
12
+ jsonValue: (column, keys) => `(${column}::json #> ${path(keys)})::text`,
12
13
  // SQLite's json_extract(...) IS NOT 0: true unless the value is false or the number 0 (absent and null are true).
13
14
  jsonNotFalse: (column, keys) => `COALESCE((${column}::json #> ${path(keys)})::text NOT IN ('false', '0'), TRUE)`,
14
15
  jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_array_elements_text(${column}::json) AS element(value) WHERE element.value = ?)`,
@@ -8,7 +8,20 @@ export interface Migration {
8
8
  * schema cannot take the migration yet, each in a `refusal` column, in words that name what holds it back and what to do.
9
9
  * Not part of the file's hash: it runs only before the migration applies. */
10
10
  readonly check?: string;
11
+ /** The file says RUNNERS_BREAKING in its leading comment: a runner of a build that does not know this version cannot run
12
+ * on the schema it leaves, so applying it raises the runner floor to its version. Absent: read from its header
13
+ * (marksBreaking). */
14
+ readonly breaking?: boolean;
11
15
  }
16
+ /** The line of a migration's leading comment that marks it breaking for runners of earlier builds (Migration.breaking). */
17
+ export declare const RUNNERS_BREAKING = "-- runners: breaking";
18
+ /** The newest migration the lint never checked: 0001-0022 were written before migrations said whether they break runners,
19
+ * and a runner of a build before the floor opened only the exact version it knew. Each one up to it counts as breaking,
20
+ * so the floor is never below it on a schema that has it. 0023 (computer_intervals' disk_gb and booked_ms, released
21
+ * without the header) is the first the lint reads: additive, a nullable column and a NOT NULL one with a default. */
22
+ export declare const LAST_UNMARKED = 22;
23
+ /** Whether `sql`'s leading comment (its first lines, each a `--` comment or blank) holds RUNNERS_BREAKING. */
24
+ export declare function marksBreaking(sql: string): boolean;
12
25
  /** The migrations shipped beside this module (dist/store/postgres/migrations), in version order, numbered 1, 2, 3 … with
13
26
  * no gap. */
14
27
  export declare function migrationsIn(dir?: URL): Migration[];
@@ -16,6 +29,23 @@ export declare function migrationsIn(dir?: URL): Migration[];
16
29
  export declare const placeOf: (schema: string) => string;
17
30
  /** The schema's version: the highest migration applied, or null when none is (no schema, or not set up yet). */
18
31
  export declare function versionOf(client: Pick<pg.ClientBase, "query">, schema: string): Promise<number | null>;
32
+ /** A schema's version and its runner floor, as a runner and `agentrun-serve store-schema` read them. */
33
+ export interface SchemaState {
34
+ /** The highest migration applied; null when none is (no schema, or not set up yet). */
35
+ readonly version: number | null;
36
+ /** The oldest schema version a runner's build must know to run on this schema: the highest migration applied that is
37
+ * breaking for runners (Migration.breaking), or LAST_UNMARKED and before; null when none is applied. */
38
+ readonly runnerFloor: number | null;
39
+ }
40
+ /** `schema`'s version and runner floor (SchemaState), read without a lock or a write. A ledger an earlier server kept,
41
+ * with no runners_breaking column, has every version up to it unmarked: its floor is its version. */
42
+ export declare function runnerFloorOf(client: Pick<pg.ClientBase, "query">, schema: string): Promise<SchemaState>;
43
+ /** What a runner of a build that knows version `known` does on a schema at `state`: opens it, waits for its server to
44
+ * migrate it (behind), or is refused (none set up yet, or past the floor). */
45
+ export declare function runnerOn(state: SchemaState, known: number): "opens" | "waits" | "refused";
46
+ /** Refuses a runner of a build that knows `known` on `schema` at `state`, the way its open does: SchemaVersionUnknown when
47
+ * none is set up, StoreAwaitsServer's words left to the caller (behind), RunnerBelowFloor past the floor. */
48
+ export declare function refuseBelowFloor(schema: string, state: SchemaState, known: number): void;
19
49
  /** Removes the store in `schema` and everything in it, on its own connection: for a scratch store's cleanup (the conformance
20
50
  * harness's world, the tests'), never a server's path. */
21
51
  export declare function dropPostgresSchema(url: string, schema: string): Promise<void>;
@@ -1,11 +1,18 @@
1
1
  // The store's Postgres schema, owned by AgentRun: versioned SQL files (migrations/NNNN_name.sql), applied in order by the
2
2
  // server only, all pending ones in one transaction under an advisory lock (two servers starting at once apply each file
3
3
  // once), each recorded in <schema>.schema_migrations with its file's SHA-256. An applied file is never edited: a server
4
- // that finds one changed refuses to start, naming it. A runner applies nothing; it reads the version and refuses one it does
5
- // not know (SchemaVersionUnknown), as on SQLite.
4
+ // that finds one changed refuses to start, naming it. A runner applies nothing: it reads the version and the runner floor
5
+ // (runnerFloorOf), waits for a server on a schema behind its build (StoreAwaitsServer), and runs on one ahead of it while
6
+ // the floor is at most the version its build knows; past the floor it is refused (RunnerBelowFloor).
7
+ //
8
+ // Migrations are additive by default: a runner of an earlier build keeps running on the schema one leaves. A migration
9
+ // that an earlier build's runner cannot run beside (it drops or renames something, changes a column's type, makes a
10
+ // column NOT NULL, adds one NOT NULL without a default) says so on a line of its leading comment, RUNNERS_BREAKING, and
11
+ // the server records it (schema_migrations.runners_breaking): the floor rises to its version. migration-lint.ts finds such
12
+ // statements, and a test fails a migration past LAST_UNMARKED that has one and no header.
6
13
  import { createHash } from "node:crypto";
7
14
  import { existsSync, readdirSync, readFileSync } from "node:fs";
8
- import { SchemaVersionUnknown } from "../store.js";
15
+ import { RunnerBelowFloor, SchemaVersionUnknown } from "../store.js";
9
16
  import { SCHEMA_NAME } from "./connection.js";
10
17
  /** `schema` as SQL takes it here, unquoted: refused (TypeError) unless it is a store schema name (SCHEMA_NAME), before any
11
18
  * statement is sent. Every entry point checks it too; this is the last line, for a caller that comes here directly. */
@@ -14,6 +21,26 @@ function schemaName(schema) {
14
21
  throw new TypeError(`not a store schema name: ${JSON.stringify(schema)}`);
15
22
  return schema;
16
23
  }
24
+ /** The line of a migration's leading comment that marks it breaking for runners of earlier builds (Migration.breaking). */
25
+ export const RUNNERS_BREAKING = "-- runners: breaking";
26
+ /** The newest migration the lint never checked: 0001-0022 were written before migrations said whether they break runners,
27
+ * and a runner of a build before the floor opened only the exact version it knew. Each one up to it counts as breaking,
28
+ * so the floor is never below it on a schema that has it. 0023 (computer_intervals' disk_gb and booked_ms, released
29
+ * without the header) is the first the lint reads: additive, a nullable column and a NOT NULL one with a default. */
30
+ export const LAST_UNMARKED = 22;
31
+ /** Whether `sql`'s leading comment (its first lines, each a `--` comment or blank) holds RUNNERS_BREAKING. */
32
+ export function marksBreaking(sql) {
33
+ for (const line of sql.split("\n")) {
34
+ const text = line.trim();
35
+ if (text === "")
36
+ continue;
37
+ if (!text.startsWith("--"))
38
+ return false;
39
+ if (text === RUNNERS_BREAKING)
40
+ return true;
41
+ }
42
+ return false;
43
+ }
17
44
  const FILE = /^(\d{4})_([a-z0-9_]+)\.sql$/;
18
45
  /** The migrations shipped beside this module (dist/store/postgres/migrations), in version order, numbered 1, 2, 3 … with
19
46
  * no gap. */
@@ -25,7 +52,7 @@ export function migrationsIn(dir = new URL("./migrations/", import.meta.url)) {
25
52
  const sql = readFileSync(new URL(match[0], dir), "utf8");
26
53
  const checkFile = new URL(`${match[1]}_${match[2]}.check.sql`, dir);
27
54
  const check = existsSync(checkFile) ? readFileSync(checkFile, "utf8") : undefined;
28
- return { version: Number(match[1]), name: match[2], sql, sha256: createHash("sha256").update(sql).digest("hex"), ...(check === undefined ? {} : { check }) };
55
+ return { version: Number(match[1]), name: match[2], sql, sha256: createHash("sha256").update(sql).digest("hex"), breaking: marksBreaking(sql), ...(check === undefined ? {} : { check }) };
29
56
  })
30
57
  .sort((a, b) => a.version - b.version);
31
58
  found.forEach((migration, index) => {
@@ -57,6 +84,41 @@ export async function versionOf(client, schema) {
57
84
  throw error;
58
85
  }
59
86
  }
87
+ /** `schema`'s version and runner floor (SchemaState), read without a lock or a write. A ledger an earlier server kept,
88
+ * with no runners_breaking column, has every version up to it unmarked: its floor is its version. */
89
+ export async function runnerFloorOf(client, schema) {
90
+ schemaName(schema);
91
+ const number = (value) => (value === null || value === undefined ? null : Number(value));
92
+ try {
93
+ const result = await client.query(`SELECT max(version) AS version, max(version) FILTER (WHERE runners_breaking OR version <= ${LAST_UNMARKED}) AS floor FROM ${schema}.schema_migrations`);
94
+ return { version: number(result.rows[0]?.version), runnerFloor: number(result.rows[0]?.floor) };
95
+ }
96
+ catch (error) {
97
+ if (isMissing(error))
98
+ return { version: null, runnerFloor: null };
99
+ // 42703: undefined_column, a ledger from before the floor.
100
+ if (error?.code !== "42703")
101
+ throw error;
102
+ const version = await versionOf(client, schema);
103
+ return { version, runnerFloor: version };
104
+ }
105
+ }
106
+ /** What a runner of a build that knows version `known` does on a schema at `state`: opens it, waits for its server to
107
+ * migrate it (behind), or is refused (none set up yet, or past the floor). */
108
+ export function runnerOn(state, known) {
109
+ if (state.version === null)
110
+ return "refused";
111
+ if (state.version < known)
112
+ return "waits";
113
+ return (state.runnerFloor ?? state.version) <= known ? "opens" : "refused";
114
+ }
115
+ /** Refuses a runner of a build that knows `known` on `schema` at `state`, the way its open does: SchemaVersionUnknown when
116
+ * none is set up, StoreAwaitsServer's words left to the caller (behind), RunnerBelowFloor past the floor. */
117
+ export function refuseBelowFloor(schema, state, known) {
118
+ if (state.version !== null && state.version > known && (state.runnerFloor ?? state.version) > known) {
119
+ throw new RunnerBelowFloor(placeOf(schema), state.version, known, state.runnerFloor ?? state.version);
120
+ }
121
+ }
60
122
  /** Removes the store in `schema` and everything in it, on its own connection: for a scratch store's cleanup (the conformance
61
123
  * harness's world, the tests'), never a server's path. */
62
124
  export async function dropPostgresSchema(url, schema) {
@@ -101,6 +163,11 @@ export async function migrate(client, schema, at, migrations = migrationsIn()) {
101
163
  await createSchema(client, schema);
102
164
  await client.query(`SET LOCAL search_path TO ${schema}`);
103
165
  await client.query("CREATE TABLE IF NOT EXISTS schema_migrations (version BIGINT PRIMARY KEY, name TEXT NOT NULL, sha256 TEXT NOT NULL, applied_at BIGINT NOT NULL)");
166
+ // Whether each applied migration raised the runner floor (runnerFloorOf). Added only where missing: an ALTER that finds
167
+ // the column would still lock the ledger every runner reads its floor from, until this transaction ends.
168
+ const marked = (await client.query("SELECT 1 FROM information_schema.columns WHERE table_schema = $1 AND table_name = 'schema_migrations' AND column_name = 'runners_breaking'", [schema])).rowCount !== 0;
169
+ if (!marked)
170
+ await client.query("ALTER TABLE schema_migrations ADD COLUMN runners_breaking BOOLEAN NOT NULL DEFAULT false");
104
171
  const applied = (await client.query("SELECT version, name, sha256 FROM schema_migrations ORDER BY version")).rows;
105
172
  const top = applied.length === 0 ? null : Number(applied.at(-1).version);
106
173
  if (top !== null && top > known)
@@ -118,7 +185,7 @@ export async function migrate(client, schema, at, migrations = migrationsIn()) {
118
185
  throw new Error(`${placeOf(schema)} cannot take migration ${String(migration.version).padStart(4, "0")}_${migration.name}.sql, so nothing was applied: ${refusals.join("; ")}`);
119
186
  }
120
187
  await client.query(migration.sql);
121
- await client.query("INSERT INTO schema_migrations (version, name, sha256, applied_at) VALUES ($1, $2, $3, $4)", [migration.version, migration.name, migration.sha256, at]);
188
+ await client.query("INSERT INTO schema_migrations (version, name, sha256, applied_at, runners_breaking) VALUES ($1, $2, $3, $4, $5)", [migration.version, migration.name, migration.sha256, at, migration.breaking ?? marksBreaking(migration.sql)]);
122
189
  }
123
190
  await client.query("COMMIT");
124
191
  return known;
@@ -0,0 +1,8 @@
1
+ /** One statement of a migration an earlier build's runner cannot run beside, and why. */
2
+ export interface BreakingStatement {
3
+ readonly why: string;
4
+ /** The statement, its comments and string literals cut, on one line. */
5
+ readonly statement: string;
6
+ }
7
+ /** The statements of `sql` an earlier build's runner cannot run beside (BREAKING), in their order. */
8
+ export declare function breakingStatements(sql: string): BreakingStatement[];
@@ -0,0 +1,119 @@
1
+ // Which statements of a Postgres migration a runner of an earlier build cannot run beside (migrate.ts RUNNERS_BREAKING):
2
+ // a migration past LAST_UNMARKED with any of them carries the header, or the migration lint (its test) fails. The rule
3
+ // is the deploy order's: the server migrates first, under runners of the earlier release that keep running; a schema
4
+ // change those runners' statements no longer fit (a table or column they read gone or renamed, a type they write changed,
5
+ // a column they never write made NOT NULL) fails their runs. Such a change lands in two releases: the additive half first,
6
+ // and the destructive cleanup one release later, marked, which raises the runner floor.
7
+ //
8
+ // It reads statements, never meaning: a tightened constraint an earlier runner's writes break (a new UNIQUE, CHECK or
9
+ // FOREIGN KEY on what it writes) is not found here, and its author marks it as well. A new PRIMARY KEY is found: it makes
10
+ // its columns NOT NULL. A function's or DO block's body is not read: a destructive statement in one (an EXECUTE of a DROP)
11
+ // is its author's to mark.
12
+ /** `sql` with its comments gone and every string literal's text and dollar-quoted body emptied: what is left is the
13
+ * statements' own words, so a refusal's text or a function's body is never read as a statement. */
14
+ function bare(sql) {
15
+ let out = "";
16
+ for (let i = 0; i < sql.length;) {
17
+ const rest = sql.slice(i);
18
+ if (rest.startsWith("--")) {
19
+ const end = sql.indexOf("\n", i);
20
+ i = end === -1 ? sql.length : end;
21
+ continue;
22
+ }
23
+ if (rest.startsWith("/*")) {
24
+ const end = sql.indexOf("*/", i + 2);
25
+ i = end === -1 ? sql.length : end + 2;
26
+ out += " ";
27
+ continue;
28
+ }
29
+ const dollar = /^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.exec(rest);
30
+ if (dollar) {
31
+ const end = sql.indexOf(dollar[0], i + dollar[0].length);
32
+ i = end === -1 ? sql.length : end + dollar[0].length;
33
+ out += "''";
34
+ continue;
35
+ }
36
+ if (sql[i] === "'") {
37
+ let j = i + 1;
38
+ while (j < sql.length) {
39
+ if (sql[j] === "'" && sql[j + 1] === "'")
40
+ j += 2;
41
+ else if (sql[j] === "'")
42
+ break;
43
+ else
44
+ j += 1;
45
+ }
46
+ i = j + 1;
47
+ out += "''";
48
+ continue;
49
+ }
50
+ out += sql[i];
51
+ i += 1;
52
+ }
53
+ return out;
54
+ }
55
+ /** Each kind of statement an earlier build's runner cannot run beside: tested on one statement, upper-cased, with its
56
+ * whitespace on one line. */
57
+ const BREAKING = [
58
+ // DROP TABLE, DROP COLUMN, DROP INDEX (an ON CONFLICT of an earlier runner may name it), DROP CONSTRAINT (a unique one
59
+ // too), DROP DEFAULT (an earlier runner's insert may leave the column out). DROP NOT NULL only loosens, and a trigger
60
+ // is the database's own work, which no runner's statement names.
61
+ { why: "drops what an earlier runner may read or write", test: (s) => /\bDROP\b/.test(s.replace(/\bDROP\s+NOT\s+NULL\b|^DROP\s+TRIGGER\b/g, "")) },
62
+ { why: "renames what an earlier runner names", test: (s) => /\bRENAME\b/.test(s) },
63
+ { why: "changes a column's type", test: (s) => /\bALTER\s+(?:COLUMN\s+)?(?:"[^"]+"|\w+)\s+(?:SET\s+DATA\s+)?TYPE\b/.test(s) },
64
+ { why: "makes a column NOT NULL that an earlier runner may leave empty", test: (s) => /\bSET\s+NOT\s+NULL\b/.test(s) },
65
+ // A primary key makes each of its columns NOT NULL, and is unique besides.
66
+ { why: "adds a primary key, which makes its columns NOT NULL", test: (s) => /^ALTER\s+TABLE\b/.test(s) && /\bADD\s+(?:CONSTRAINT\s+(?:"[^"]+"|\w+)\s+)?PRIMARY\s+KEY\b/.test(s) },
67
+ {
68
+ why: "adds a NOT NULL column with no default, which an earlier runner's inserts leave out",
69
+ // A column's own PRIMARY KEY makes it NOT NULL as well.
70
+ test: (s) => /^ALTER\s+TABLE\b/.test(s) && addedColumns(s).map(outerWords).map((column) => column.replace(/\bSET\s+DEFAULT\b/g, "")).some((column) => (/\bNOT\s+NULL\b/.test(column) || /\bPRIMARY\s+KEY\b/.test(column)) && !/\bDEFAULT\b/.test(column) && !/\bGENERATED\b/.test(column)),
71
+ },
72
+ ];
73
+ /** `clause` with everything inside its parentheses removed, at any depth: a CHECK's `x IS NOT NULL`, however nested, is
74
+ * no NOT NULL of the column's own. */
75
+ function outerWords(clause) {
76
+ let out = "";
77
+ let depth = 0;
78
+ for (const c of clause) {
79
+ if (c === "(")
80
+ depth += 1;
81
+ else if (c === ")")
82
+ depth = Math.max(0, depth - 1);
83
+ else if (depth === 0)
84
+ out += c;
85
+ }
86
+ return out;
87
+ }
88
+ /** Each ADD COLUMN clause of an ALTER TABLE statement, up to the next top-level comma. */
89
+ function addedColumns(statement) {
90
+ const clauses = [];
91
+ let depth = 0;
92
+ let start = 0;
93
+ for (let i = 0; i <= statement.length; i++) {
94
+ const c = statement[i];
95
+ if (c === "(")
96
+ depth += 1;
97
+ else if (c === ")")
98
+ depth -= 1;
99
+ else if ((c === "," && depth === 0) || i === statement.length) {
100
+ clauses.push(statement.slice(start, i));
101
+ start = i + 1;
102
+ }
103
+ }
104
+ return clauses.filter((clause) => /\bADD\s+COLUMN\b/.test(clause) || /^\s*ADD\s+(?!CONSTRAINT\b|PRIMARY\b|UNIQUE\b|CHECK\b|FOREIGN\b|EXCLUDE\b)/.test(clause.replace(/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?\S+\s*/, "")));
105
+ }
106
+ /** The statements of `sql` an earlier build's runner cannot run beside (BREAKING), in their order. */
107
+ export function breakingStatements(sql) {
108
+ const found = [];
109
+ for (const raw of bare(sql).split(";")) {
110
+ const statement = raw.replace(/\s+/g, " ").trim();
111
+ if (statement === "")
112
+ continue;
113
+ const upper = statement.toUpperCase();
114
+ for (const kind of BREAKING)
115
+ if (kind.test(upper))
116
+ found.push({ why: kind.why, statement });
117
+ }
118
+ return found;
119
+ }
@@ -0,0 +1,28 @@
1
+ -- The store's schema on Postgres, version 24: what each runner says of itself and each hand-back, for the server's
2
+ -- capacity read (GET /v2/capacity, capacity.ts), as store/schema.ts keeps them on SQLite (RUNNERS_ADDED, HAND_BACKS).
3
+ -- Applied once, after 0023, inside the transaction migrate.ts opens. Never edit this file once applied: a change is a new
4
+ -- file. Additive: a runner of an earlier build that is already running writes its row as before, its version and slots
5
+ -- read as unknown (null). A runner of an earlier build that starts after this file is applied refuses the store
6
+ -- (openPostgresStore: the schema is newer than it knows), so Postgres runners are upgraded with the server.
7
+ --
8
+ -- runners.version: the runner's build (the serve package's version); null on a row an earlier build wrote.
9
+ -- runners.slots: the most runs the runner holds at once (its loops); null on a row an earlier build wrote.
10
+ -- hand_backs: one row per release that left its run running (a runner's drain, a loop that closed itself, a claim given
11
+ -- back): the run, the runner that let it go, the epoch it let go of and when, on the database's clock. Counts and ids only,
12
+ -- kept 24 hours (the release that writes one removes the older rows), indexed by time (the window, the prune) and by
13
+ -- run (a run's purge and delete). Each piece is made only where missing, so a store
14
+ -- whose record of this file was lost applies it again unharmed.
15
+
16
+ ALTER TABLE runners ADD COLUMN IF NOT EXISTS version TEXT COLLATE "C";
17
+ ALTER TABLE runners ADD COLUMN IF NOT EXISTS slots INTEGER;
18
+
19
+ CREATE TABLE IF NOT EXISTS hand_backs (
20
+ run_id TEXT COLLATE "C" NOT NULL,
21
+ runner TEXT COLLATE "C" NOT NULL,
22
+ epoch BIGINT NOT NULL,
23
+ at BIGINT NOT NULL
24
+ );
25
+ CREATE INDEX IF NOT EXISTS hand_backs_at ON hand_backs (at);
26
+ CREATE INDEX IF NOT EXISTS hand_backs_run ON hand_backs (run_id);
27
+
28
+ UPDATE store_meta SET schema_version = 24 WHERE singleton = 1;
@@ -1,4 +1,7 @@
1
1
  import { type Store, type StoreOwned, type StoreRole } from "../store.js";
2
+ /** How long Store.schemaState waits for the database before it is Unanswered and its connection is dropped (ms): under
3
+ * the runner's 10 s floor read, so a read that hangs never outlasts the next one. */
4
+ export declare const SCHEMA_STATE_MS = 5000;
2
5
  /** The schema a store is in when none is named. */
3
6
  export declare const DEFAULT_SCHEMA = "agentrun";
4
7
  /** How far a runner's clock may be from the database's before it says so at its start (ms). Leases are 30 s, so a gap this
@@ -42,7 +45,9 @@ export interface PostgresStoreOptions {
42
45
  readonly onOwnerLost?: (error: StoreOwned) => void;
43
46
  }
44
47
  /** Opens the store in `schema` on the Postgres at `url`. As the server (the default): takes the owner lock (StoreOwned when
45
- * another server holds the schema) and applies the pending migrations. As a runner: sets nothing up, and warns when its
46
- * clock is far from the database's. Either refuses a schema version this build does not know (SchemaVersionUnknown), a
47
- * runner also a schema not set up yet, and one this build's server has yet to migrate (StoreAwaitsServer). */
48
+ * another server holds the schema) and applies the pending migrations; it refuses a schema a later build migrated
49
+ * (SchemaVersionUnknown). As a runner: sets nothing up, and warns when its clock is far from the database's. It refuses a
50
+ * schema not set up yet (SchemaVersionUnknown) and one this build's server has yet to migrate (StoreAwaitsServer), and
51
+ * opens one a later build migrated while that schema's runner floor is at most this build's version (RunnerBelowFloor
52
+ * past it). The store it answers reads the version and the floor again (Store.schemaState). */
48
53
  export declare function openPostgresStore(options: PostgresStoreOptions): Promise<Store>;
@@ -1,11 +1,15 @@
1
1
  // The Store on Postgres: the same domain code as SQLite's (sqlite/store.ts storeOver) over a Postgres connection
2
2
  // (connection.ts) in the store's own schema (default "agentrun"). The server sets the schema up (migrate.ts) and holds the
3
- // owner lock, one server per schema; runners are many, set nothing up, and refuse a schema version they do not know.
3
+ // owner lock, one server per schema; runners are many, set nothing up, wait for the server on a schema behind them, and
4
+ // run on one ahead of them while its runner floor is at most what they know (migrate.ts runnerFloorOf).
4
5
  import { SchemaVersionUnknown, StoreAwaitsServer } from "../store.js";
5
6
  import { backfillNativeCommandOwners } from '../native-command-owner.js';
6
7
  import { storeOver } from "../sqlite/store.js";
7
8
  import { PgConnection, SCHEMA_NAME } from "./connection.js";
8
- import { migrate, migrationsIn, placeOf, versionOf } from "./migrate.js";
9
+ import { migrate, migrationsIn, placeOf, refuseBelowFloor, runnerFloorOf, versionOf } from "./migrate.js";
10
+ /** How long Store.schemaState waits for the database before it is Unanswered and its connection is dropped (ms): under
11
+ * the runner's 10 s floor read, so a read that hangs never outlasts the next one. */
12
+ export const SCHEMA_STATE_MS = 5_000;
9
13
  /** The schema a store is in when none is named. */
10
14
  export const DEFAULT_SCHEMA = "agentrun";
11
15
  /** How far a runner's clock may be from the database's before it says so at its start (ms). Leases are 30 s, so a gap this
@@ -13,9 +17,11 @@ export const DEFAULT_SCHEMA = "agentrun";
13
17
  export const CLOCK_WARN_MS = 2_000;
14
18
  export { postgresWhere } from "./connection.js";
15
19
  /** Opens the store in `schema` on the Postgres at `url`. As the server (the default): takes the owner lock (StoreOwned when
16
- * another server holds the schema) and applies the pending migrations. As a runner: sets nothing up, and warns when its
17
- * clock is far from the database's. Either refuses a schema version this build does not know (SchemaVersionUnknown), a
18
- * runner also a schema not set up yet, and one this build's server has yet to migrate (StoreAwaitsServer). */
20
+ * another server holds the schema) and applies the pending migrations; it refuses a schema a later build migrated
21
+ * (SchemaVersionUnknown). As a runner: sets nothing up, and warns when its clock is far from the database's. It refuses a
22
+ * schema not set up yet (SchemaVersionUnknown) and one this build's server has yet to migrate (StoreAwaitsServer), and
23
+ * opens one a later build migrated while that schema's runner floor is at most this build's version (RunnerBelowFloor
24
+ * past it). The store it answers reads the version and the floor again (Store.schemaState). */
19
25
  export async function openPostgresStore(options) {
20
26
  const schema = options.schema ?? DEFAULT_SCHEMA;
21
27
  if (!SCHEMA_NAME.test(schema))
@@ -41,11 +47,21 @@ export async function openPostgresStore(options) {
41
47
  },
42
48
  });
43
49
  try {
44
- const found = await connection.withClient((client) => (role === "server" ? migrate(client, schema, now(), migrations) : versionOf(client, schema)));
45
- if (role === "runner" && found !== null && found < known)
46
- throw new StoreAwaitsServer(`bring this store from version ${found} to ${known}`);
47
- if (found !== known)
48
- throw new SchemaVersionUnknown(placeOf(schema), found, known);
50
+ if (role === "server") {
51
+ const found = await connection.withClient((client) => migrate(client, schema, now(), migrations));
52
+ if (found !== known)
53
+ throw new SchemaVersionUnknown(placeOf(schema), found, known);
54
+ }
55
+ else {
56
+ const state = await connection.withClient((client) => runnerFloorOf(client, schema));
57
+ const found = state.version;
58
+ if (found !== null && found < known)
59
+ throw new StoreAwaitsServer(`bring this store from version ${found} to ${known}`);
60
+ if (found === null)
61
+ throw new SchemaVersionUnknown(placeOf(schema), found, known);
62
+ // Ahead of this build: additive migrations leave the floor where it was, and this runner runs on them.
63
+ refuseBelowFloor(schema, state, known);
64
+ }
49
65
  if (role === "server")
50
66
  await backfillNativeCommandOwners(connection);
51
67
  if (role === "runner" && options.warn) {
@@ -59,5 +75,9 @@ export async function openPostgresStore(options) {
59
75
  await connection.close().catch(() => undefined);
60
76
  throw error;
61
77
  }
62
- return storeOver(connection, now);
78
+ const store = storeOver(connection, now);
79
+ // Bounded: a runner reads it on a timer, and a database that stops answering must neither hold that timer's read for good
80
+ // nor the store's close, which waits for every call in flight.
81
+ const schemaState = async () => ({ ...(await connection.withClient((client) => runnerFloorOf(client, schema), SCHEMA_STATE_MS)), known });
82
+ return Object.assign(store, { schemaState });
63
83
  }