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

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 (232) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +236 -30
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +17 -7
  8. package/dist/api-only.d.ts +6 -3
  9. package/dist/api-only.js +8 -5
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/capacity.d.ts +50 -0
  13. package/dist/capacity.js +49 -0
  14. package/dist/cli-learning/claude-wire.d.ts +41 -0
  15. package/dist/cli-learning/claude-wire.js +258 -0
  16. package/dist/cli-learning/cli.d.ts +11 -0
  17. package/dist/cli-learning/cli.js +241 -0
  18. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  19. package/dist/cli-learning/codex-worktree.js +119 -0
  20. package/dist/cli-learning/connections.d.ts +62 -0
  21. package/dist/cli-learning/connections.js +87 -0
  22. package/dist/cli-learning/entry.d.ts +1 -0
  23. package/dist/cli-learning/entry.js +4 -0
  24. package/dist/cli-learning/evidence.d.ts +78 -0
  25. package/dist/cli-learning/evidence.js +492 -0
  26. package/dist/cli-learning/hook.d.ts +33 -0
  27. package/dist/cli-learning/hook.js +544 -0
  28. package/dist/cli-learning/install.d.ts +33 -0
  29. package/dist/cli-learning/install.js +335 -0
  30. package/dist/cli-learning/observation-proof.d.ts +14 -0
  31. package/dist/cli-learning/observation-proof.js +10 -0
  32. package/dist/cli-learning/policy.d.ts +48 -0
  33. package/dist/cli-learning/policy.js +363 -0
  34. package/dist/cli-learning/schema.d.ts +16 -0
  35. package/dist/cli-learning/schema.js +27 -0
  36. package/dist/cli-learning/state.d.ts +23 -0
  37. package/dist/cli-learning/state.js +61 -0
  38. package/dist/cli.js +24 -2
  39. package/dist/computer-setting.d.ts +8 -0
  40. package/dist/computer-setting.js +11 -0
  41. package/dist/computers.d.ts +6 -2
  42. package/dist/computers.js +2 -2
  43. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  44. package/dist/console/assets/{index-D0mr9wfZ.css → index-DlQepP2J.css} +1 -1
  45. package/dist/console/index.html +2 -2
  46. package/dist/email/email-faux.d.ts +3 -1
  47. package/dist/email/email-faux.js +3 -2
  48. package/dist/email/routes.js +22 -12
  49. package/dist/fal-price.d.ts +76 -0
  50. package/dist/fal-price.js +368 -0
  51. package/dist/harness-install.d.ts +6 -2
  52. package/dist/harness-install.js +40 -8
  53. package/dist/harness.d.ts +1 -1
  54. package/dist/harness.js +2 -2
  55. package/dist/learn/commit.d.ts +5 -0
  56. package/dist/learn/commit.js +4 -1
  57. package/dist/learn/compile.d.ts +13 -5
  58. package/dist/learn/compile.js +24 -7
  59. package/dist/learn/delete.d.ts +12 -6
  60. package/dist/learn/delete.js +17 -11
  61. package/dist/learn/folder.d.ts +11 -0
  62. package/dist/learn/folder.js +20 -3
  63. package/dist/learn/learning-of.d.ts +8 -0
  64. package/dist/learn/learning-of.js +8 -0
  65. package/dist/learn/learning.sh +14 -1
  66. package/dist/learn/promote.d.ts +51 -7
  67. package/dist/learn/promote.js +51 -8
  68. package/dist/learn/secrets.js +14 -3
  69. package/dist/learning-reset.d.ts +18 -0
  70. package/dist/learning-reset.js +115 -0
  71. package/dist/learning-routes.d.ts +1 -1
  72. package/dist/learning-words.d.ts +6 -1
  73. package/dist/learning-words.js +6 -1
  74. package/dist/learning.d.ts +8 -6
  75. package/dist/learning.js +5 -4
  76. package/dist/llms.txt +1 -0
  77. package/dist/mcp-gateway.d.ts +39 -2
  78. package/dist/mcp-gateway.js +41 -10
  79. package/dist/mcp-pin-first.js +3 -2
  80. package/dist/mcp-private-hosts.d.ts +24 -3
  81. package/dist/mcp-private-hosts.js +53 -3
  82. package/dist/mcp-servers-store.d.ts +1 -0
  83. package/dist/mcp-servers-store.js +2 -1
  84. package/dist/media-duration.d.ts +2 -0
  85. package/dist/media-duration.js +136 -0
  86. package/dist/model-gateway.d.ts +2 -0
  87. package/dist/model-gateway.js +3 -1
  88. package/dist/native/runtimes.d.ts +2 -0
  89. package/dist/native/runtimes.js +2 -0
  90. package/dist/observation/learning.d.ts +32 -0
  91. package/dist/observation/learning.js +66 -0
  92. package/dist/observation/observer.d.ts +8 -1
  93. package/dist/observation/observer.js +89 -9
  94. package/dist/observation/schema.js +12 -4
  95. package/dist/observation/usage-identity.d.ts +9 -0
  96. package/dist/observation/usage-identity.js +11 -0
  97. package/dist/openapi.js +133 -24
  98. package/dist/provider.d.ts +8 -0
  99. package/dist/provider.js +14 -2
  100. package/dist/refusal-words.d.ts +0 -3
  101. package/dist/refusal-words.js +0 -3
  102. package/dist/request-metadata.d.ts +20 -0
  103. package/dist/request-metadata.js +24 -0
  104. package/dist/run-launch.d.ts +27 -4
  105. package/dist/run-launch.js +18 -3
  106. package/dist/run-learning-served.d.ts +2 -2
  107. package/dist/run-usage.d.ts +48 -4
  108. package/dist/run-usage.js +156 -39
  109. package/dist/run-view.d.ts +2 -0
  110. package/dist/run-view.js +8 -7
  111. package/dist/runner/adapter-loop.d.ts +3 -1
  112. package/dist/runner/adapter-loop.js +41 -35
  113. package/dist/runner/adapter-run-spec.d.ts +1 -1
  114. package/dist/runner/adapter-run-spec.js +15 -15
  115. package/dist/runner/audit.d.ts +8 -3
  116. package/dist/runner/audit.js +21 -6
  117. package/dist/runner/beside.d.ts +13 -0
  118. package/dist/runner/beside.js +27 -8
  119. package/dist/runner/claim-secrets.d.ts +2 -1
  120. package/dist/runner/claim-secrets.js +5 -3
  121. package/dist/runner/cli-run-spec.d.ts +1 -1
  122. package/dist/runner/cli-run-spec.js +14 -13
  123. package/dist/runner/conformance/harness.js +4 -2
  124. package/dist/runner/disk-free.d.ts +44 -0
  125. package/dist/runner/disk-free.js +96 -0
  126. package/dist/runner/dispatch.js +4 -2
  127. package/dist/runner/feedback-round.d.ts +12 -8
  128. package/dist/runner/feedback-round.js +16 -30
  129. package/dist/runner/harness-loops.js +8 -3
  130. package/dist/runner/journal-kinds.d.ts +4 -1
  131. package/dist/runner/learning-end.d.ts +2 -1
  132. package/dist/runner/learning-end.js +51 -22
  133. package/dist/runner/main.d.ts +17 -6
  134. package/dist/runner/main.js +187 -45
  135. package/dist/runner/mcp-claim.js +1 -1
  136. package/dist/runner/mcp-run.d.ts +9 -0
  137. package/dist/runner/mcp-run.js +16 -1
  138. package/dist/runner/model-route.js +7 -4
  139. package/dist/runner/presence.d.ts +11 -2
  140. package/dist/runner/presence.js +31 -3
  141. package/dist/runner/promotion.d.ts +40 -21
  142. package/dist/runner/promotion.js +130 -59
  143. package/dist/runner/run-child-host.d.ts +12 -15
  144. package/dist/runner/run-child-host.js +52 -112
  145. package/dist/runner/run-errors.js +2 -0
  146. package/dist/runner/runner-check.d.ts +51 -0
  147. package/dist/runner/runner-check.js +206 -0
  148. package/dist/runner/runner-metrics.d.ts +19 -0
  149. package/dist/runner/runner-metrics.js +49 -0
  150. package/dist/runner/runner.d.ts +37 -0
  151. package/dist/runner/runner.js +58 -6
  152. package/dist/runner/sdk-loop.d.ts +2 -2
  153. package/dist/runner/sdk-loop.js +37 -25
  154. package/dist/runner/store-port.d.ts +3 -0
  155. package/dist/runner/workflow-spec.js +3 -3
  156. package/dist/runs-over-store.d.ts +13 -3
  157. package/dist/runs-over-store.js +71 -16
  158. package/dist/sdk/check.d.ts +6 -5
  159. package/dist/sdk/check.js +17 -16
  160. package/dist/sdk/runs.d.ts +22 -2
  161. package/dist/sdk/runs.js +167 -82
  162. package/dist/server.d.ts +3 -0
  163. package/dist/server.js +230 -43
  164. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  165. package/dist/start-switches.js +2 -0
  166. package/dist/stats.d.ts +4 -0
  167. package/dist/stats.js +1 -1
  168. package/dist/store/agent-body.d.ts +16 -0
  169. package/dist/store/agent-body.js +20 -3
  170. package/dist/store/dialect.d.ts +2 -0
  171. package/dist/store/dialect.js +1 -0
  172. package/dist/store/index.d.ts +3 -3
  173. package/dist/store/index.js +2 -2
  174. package/dist/store/journal/storage.d.ts +2 -0
  175. package/dist/store/journal/storage.js +2 -1
  176. package/dist/store/postgres/connection.d.ts +5 -2
  177. package/dist/store/postgres/connection.js +19 -7
  178. package/dist/store/postgres/dialect.js +1 -0
  179. package/dist/store/postgres/migrate.d.ts +30 -0
  180. package/dist/store/postgres/migrate.js +72 -5
  181. package/dist/store/postgres/migration-lint.d.ts +8 -0
  182. package/dist/store/postgres/migration-lint.js +119 -0
  183. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  184. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  185. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  186. package/dist/store/postgres/store.d.ts +8 -3
  187. package/dist/store/postgres/store.js +31 -11
  188. package/dist/store/schema.d.ts +32 -2
  189. package/dist/store/schema.js +74 -5
  190. package/dist/store/sqlite/run-launch.d.ts +31 -1
  191. package/dist/store/sqlite/run-launch.js +111 -2
  192. package/dist/store/sqlite/run-patch.d.ts +2 -1
  193. package/dist/store/sqlite/run-patch.js +4 -3
  194. package/dist/store/sqlite/store.d.ts +17 -0
  195. package/dist/store/sqlite/store.js +226 -37
  196. package/dist/store/store-schema.d.ts +34 -0
  197. package/dist/store/store-schema.js +125 -0
  198. package/dist/store/store.d.ts +120 -5
  199. package/dist/store/store.js +13 -0
  200. package/dist/store-reads/analytics.d.ts +3 -2
  201. package/dist/store-reads/analytics.js +20 -8
  202. package/dist/store-reads/learning.d.ts +12 -8
  203. package/dist/store-reads/learning.js +33 -24
  204. package/dist/store-reads/loop.d.ts +4 -3
  205. package/dist/store-reads/loop.js +7 -5
  206. package/dist/store-view.d.ts +4 -3
  207. package/dist/store-view.js +11 -7
  208. package/dist/template-eval.js +4 -4
  209. package/dist/templates.d.ts +6 -2
  210. package/dist/templates.js +7 -5
  211. package/dist/timeline/labels.js +1 -1
  212. package/dist/tool-gate.d.ts +4 -2
  213. package/dist/tools.js +1 -1
  214. package/dist/unified-usage.d.ts +24 -0
  215. package/dist/unified-usage.js +400 -0
  216. package/dist/uploads-archil.d.ts +100 -0
  217. package/dist/uploads-archil.js +431 -0
  218. package/dist/uploads.d.ts +52 -1
  219. package/dist/uploads.js +186 -108
  220. package/dist/validate.js +5 -1
  221. package/dist/web-save.d.ts +3 -0
  222. package/dist/web-save.js +17 -2
  223. package/dist/workspace/archil-disk.d.ts +6 -5
  224. package/dist/workspace/archil-disk.js +27 -12
  225. package/dist/workspace/archil-exec.js +1 -1
  226. package/dist/workspace/archil.js +4 -3
  227. package/dist/workspace/revision-skills.js +24 -11
  228. package/dist/workspace/synced-folder.d.ts +3 -3
  229. package/dist/workspace/synced-folder.js +7 -6
  230. package/package.json +10 -10
  231. package/skills/agentrun-serve/SKILL.md +52 -7
  232. package/dist/console/assets/index-D7G6o-1E.js +0 -720
@@ -30,7 +30,7 @@ Inspect configured models before asking for a key. For an existing setup, follow
30
30
  and history import need no destination model key. Live jobs use the source runtime's existing sign-in.
31
31
 
32
32
  Finish with the first requested run's result and console link, or imported history and counts. Offer optional
33
- self-improvement separately, and verify accepted notes or skills in a fresh later run when requested.
33
+ self-improvement separately, and verify owner corrections in a fresh later run when requested.
34
34
 
35
35
  ## Connect agent
36
36
 
@@ -108,11 +108,56 @@ reported model/harness and activity/usage. CLI `configured` or `delivery_state:
108
108
  delivery. Observed sessions are read-only: idle is not proof of completion, and missing telemetry is not proof of
109
109
  an agent failure. No prompts, transcripts or tool contents are uploaded through this metadata path.
110
110
 
111
- If the user also wants self-improvement for application-owned jobs, follow the supported backend SDK learning
111
+ For independently started **Codex CLI or Claude Code** sessions, use the existing CLI learning path below.
112
+ For SDK application-owned jobs, follow the supported backend SDK learning
112
113
  integration and verify accepted-revision delivery in a fresh run. Observation alone cannot enable it. The current
113
114
  Claude Agent SDK and Codex SDK wrappers are TypeScript integrations; do not claim a Python SDK backend is wrapped
114
115
  by setting OTEL variables. Do not fabricate a runnable native agent or use a copied prompt as proof.
115
116
 
117
+ ### Learning in existing CLI sessions
118
+
119
+ For a connected-session card handoff, read its exact `GET /v2/observations?session_id=...` record.
120
+ On the source machine, resolve `external_session_id` through the collector's private identity map to the
121
+ native session, then inspect that session's actual project through its harness. Never print the identity
122
+ map or credentials, and never select a project from a display name or basename. A verified
123
+ `learning.agent_id` links to the existing shared project/runtime learning profile; reuse it. If the
124
+ source is unavailable, ask the user to open the original session. Run and Edit continue or change that
125
+ original setup, not a managed run or a replacement definition. Delegated children cannot enable independent
126
+ hook learning. Only offer enrollment for the selected root session's project, with its shared scope clear.
127
+
128
+ When requested, use the matching build's `learning connect` on the source machine. This path keeps the
129
+ original CLI in control of task execution and does not require an SDK wrapper. The initial integration
130
+ requires AgentRun on that same machine; identify its loopback port and actual data directory. Do not
131
+ silently replace a remote destination with a new local server. Enrollment uses the local owner credential
132
+ privately and leaves a scoped connection credential for hooks, never an owner key in project files.
133
+
134
+ ```sh
135
+ agentrun-serve learning connect --project /absolute/project --runtime codex \
136
+ --url http://127.0.0.1:7340 --data /absolute/server-data
137
+ ```
138
+
139
+ Use `claude-code` for Claude Code. Scope enrollment to the selected project/runtime. Installation merges
140
+ source hooks without replacing other hooks or changing tools, permissions, instructions or sign-in.
141
+ Codex linked worktrees append exact project-scoped hooks to the corresponding main-checkout
142
+ `.codex/hooks.json`, following native discovery. They keep separate local receipts and a local `.codex`
143
+ directory; disconnect preserves surviving native hook positions. If `learning status` reports `migration-required`,
144
+ rerun the same connect command to migrate unchanged owned hooks without replacing the connection.
145
+ Verify `/hooks`; Codex must trust the current declaration. Project configuration does not hot reload:
146
+ open a new session or close and resume it after the current task finishes. Reloading user settings alone
147
+ does not reload these project hooks. Do not interrupt the user's running task to activate them.
148
+ Do not claim merely writing a configuration file activated a running session. Begin on the next complete
149
+ prompt after activation, without importing earlier conversations or learning from an in-flight turn.
150
+
151
+ The prompt hook supplies pinned owner corrections; completion hooks record bounded role-preserving evidence
152
+ and reported usage. Source dialogue never becomes a standing correction automatically. Source hooks do not
153
+ provide a workflow execution bridge or make extra native reflection calls. Missing policy, truncated evidence
154
+ and cancellation stay explicit. This is not metadata-only observation.
155
+
156
+ Use `learning status` with the same project/runtime/data arguments and open the returned agent's Learning
157
+ tab. Save a correction explicitly, then verify an actual completed source run and its delivery and use
158
+ on a later prompt. Report incomplete evidence accurately. Learning Off controls guidance for future prompts;
159
+ `learning disconnect` revokes enrollment and removes only its installed hooks, retaining prior history.
160
+
116
161
  ### Live connection on this server
117
162
 
118
163
  Verify that the coding agent, source project and AgentRun server are on the same machine. A browser's loopback
@@ -210,11 +255,11 @@ target; duplicates are skipped. The worker does not continuously upload historic
210
255
 
211
256
  ### Optional self-improvement
212
257
 
213
- When requested, verify the imported agent and enable its existing **Self-improving** control. Notes and skills are
214
- additive, pinned to a learning revision for each run. Reflection resumes the exact task session with tools disabled;
215
- the existing checker, grader and merge rules decide what becomes active. Risky proposals await owner review in
216
- Learning Dojo; a connector cannot approve them. Reflection and grading add model usage. Off means later runs
217
- receive and create no AgentRun learning. Do not start a paid run unless authorized, and do not promise enforcement
258
+ When requested, verify the imported agent and enable its existing **Self-improving** control. Owner corrections
259
+ are additive, pinned to a learning revision for each run. Eligible jobs compile into workflow drafts by resuming
260
+ the exact task session with tools disabled; checks and a dry run decide whether to keep a draft. Compilation
261
+ adds model usage. Learned workflows do not serve native runs in this release. Off means later runs receive
262
+ and create no AgentRun learning. Do not start a paid run unless authorized, and do not promise enforcement
218
263
  of native dollar caps, interactive approvals, learned workflows or unsupported desktop tools.
219
264
 
220
265
  ### Historical import into a local store
@@ -2,6 +2,7 @@
2
2
  // caller of the API can widen what the server reaches. GET /v2/capabilities lists them (`switches`), and a refusal one of
3
3
  // them causes names it, the value that allows it and the restart it takes (restartWith).
4
4
  import { BOX_ALLOW_ENV, boxAllowOf, boxAllowSetIn } from "./box-settings.js";
5
+ import { PRIVATE_HOSTS_ENV, privateHostsSwitchValue } from "./mcp-private-hosts.js";
5
6
  /** The env that says this server is a local install (cli.ts), the one kind an MCP server may be on loopback for. */
6
7
  export const MCP_ALLOW_LOOPBACK_ENV = "AGENTRUN_MCP_ALLOW_LOOPBACK";
7
8
  /** The env that lets the outbound webhook send to a private network or this machine. */
@@ -29,6 +30,7 @@ export function startSwitches(env, { mcpLoopback, webhookPrivateTargets }) {
29
30
  return {
30
31
  [MCP_ALLOW_LOOPBACK_ENV]: flag(mcpLoopback, `An MCP server on this machine's loopback (127.0.0.1, localhost), for every caller of this server's API: ${ALONE_WORDS}.`),
31
32
  [WEBHOOK_PRIVATE_TARGETS_ENV]: flag(webhookPrivateTargets, `The outbound webhook (Settings → Webhook) sending to a private network or this machine, which any caller who may set it then reaches: ${ALONE_WORDS}.`),
33
+ [PRIVATE_HOSTS_ENV]: ((value) => ({ on: value !== null, value, allows: "The private-network hosts an owner may allow an MCP server or a calendar on (Settings → MCP servers): unset, the owner's list; none, no private host at all (set it on a server or runner many customers share); or a comma list of address ranges every listed host's address must also fall in. Set it on the server and on each runner: each process holds to its own." }))(privateHostsSwitchValue(env)),
32
34
  [BOX_ALLOW_ENV]: { on: boxAllowSetIn(env), value: boxAllowSetIn(env) ? (allow === "none" ? "none" : allow.join(",")) : null, allows: "The hosts a run's computer may reach: a comma list of host names, or none for no network. Unset, the package registries and GitHub (capabilities' places.allow)." },
33
35
  [BOX_CPUS_ENV]: size(BOX_CPUS_ENV, "A Docker computer's CPUs, such as 2 or 1.5. Unset, the Docker provider's default."),
34
36
  [BOX_MEMORY_ENV]: size(BOX_MEMORY_ENV, "A Docker computer's memory, swap included, such as 512m or 4g. Unset, the Docker provider's default."),
package/dist/stats.d.ts CHANGED
@@ -50,6 +50,7 @@ export declare function analyticsView(a: StoreAnalytics, filter: AnalyticsFilter
50
50
  needs_review: number;
51
51
  failed: number;
52
52
  runs_with_metrics: number;
53
+ runs_with_token_metrics: number;
53
54
  tokens: number | null;
54
55
  cost_usd: number | null;
55
56
  unknown_cost_runs: number;
@@ -66,6 +67,7 @@ export declare function analyticsView(a: StoreAnalytics, filter: AnalyticsFilter
66
67
  needs_review: number;
67
68
  failed: number;
68
69
  runs_with_metrics: number;
70
+ runs_with_token_metrics: number;
69
71
  tokens: number | null;
70
72
  cost_usd: number | null;
71
73
  unknown_cost_runs: number;
@@ -78,6 +80,7 @@ export declare function analyticsView(a: StoreAnalytics, filter: AnalyticsFilter
78
80
  needs_review: number;
79
81
  failed: number;
80
82
  runs_with_metrics: number;
83
+ runs_with_token_metrics: number;
81
84
  tokens: number | null;
82
85
  cost_usd: number | null;
83
86
  unknown_cost_runs: number;
@@ -89,6 +92,7 @@ export declare function analyticsView(a: StoreAnalytics, filter: AnalyticsFilter
89
92
  needs_review: number;
90
93
  failed: number;
91
94
  runs_with_metrics: number;
95
+ runs_with_token_metrics: number;
92
96
  tokens: number | null;
93
97
  cost_usd: number | null;
94
98
  unknown_cost_runs: number;
package/dist/stats.js CHANGED
@@ -70,7 +70,7 @@ export function analyticsFilter(url) {
70
70
  return filter;
71
71
  }
72
72
  /** A group's counts: an escalated run is completed, and needs review; never failed. */
73
- const group = (g) => ({ runs: g.runs, completed: g.completed, needs_review: g.needsReview, failed: g.failed, runs_with_metrics: g.runsWithMetrics, tokens: g.tokens, cost_usd: round(g.costUsd), unknown_cost_runs: g.unknownCostRuns });
73
+ const group = (g) => ({ runs: g.runs, completed: g.completed, needs_review: g.needsReview, failed: g.failed, runs_with_metrics: g.runsWithMetrics, runs_with_token_metrics: g.runsWithTokenMetrics, tokens: g.tokens, cost_usd: round(g.costUsd), unknown_cost_runs: g.unknownCostRuns });
74
74
  export function analyticsView(a, filter) {
75
75
  const t = a.totals;
76
76
  return {
@@ -1,5 +1,6 @@
1
1
  import { type SdkBinding } from "../sdk/runtimes.js";
2
2
  import type { NativeBinding } from "../native/types.js";
3
+ import { type NativeRuntime } from "../native/runtimes.js";
3
4
  import { type LearningSetting } from "../learning-setting.js";
4
5
  /** A revision's body the store refuses: its content is not one the store keeps. The server maps it to an input refusal. */
5
6
  export declare class AgentBodyInvalid extends Error {
@@ -60,8 +61,18 @@ export type MonidPinBody = Readonly<Record<string, {
60
61
  readonly input: Record<string, unknown>;
61
62
  readonly usd: number | null;
62
63
  }>>;
64
+ export type CliLearningBinding = {
65
+ runtime: NativeRuntime;
66
+ connection_id: string;
67
+ project: string;
68
+ };
69
+ export declare const cliLearningOf: (body: unknown) => CliLearningBinding | undefined;
70
+ /** Read old CLI enrollment settings through the current model without rewriting its revision or learned files.
71
+ * New definitions still reject "notes"; existing CLI profiles use owner corrections and no workflow bridge. */
72
+ export declare function learningSettingForBody(body: unknown): LearningSetting | undefined;
63
73
  export type { SdkBinding } from "../sdk/runtimes.js";
64
74
  export type AgenticBody = {
75
+ cli_learning?: CliLearningBinding;
65
76
  sdk?: SdkBinding;
66
77
  native?: NativeBinding;
67
78
  instructions: string;
@@ -77,6 +88,7 @@ export type AgenticBody = {
77
88
  learning?: LearningSetting;
78
89
  toolSettings?: ToolSettings;
79
90
  maxCostUsd?: number;
91
+ maxRequests?: number;
80
92
  approvals?: "ask" | "never";
81
93
  inputSchema?: Record<string, unknown>;
82
94
  outputSchema?: Record<string, unknown>;
@@ -91,12 +103,14 @@ export type WorkflowBody = {
91
103
  computer?: RevisionComputer;
92
104
  toolSettings?: ToolSettings;
93
105
  maxCostUsd?: number;
106
+ maxRequests?: number;
94
107
  approvals?: "ask" | "never";
95
108
  };
96
109
  /** The input a revision's body is built from (the control plane's, in the store's own shape). `toolSettings` is already
97
110
  * checked and canonical (agents-store.ts via tool-plane's one copy); this validator keeps it as given. */
98
111
  export type RevisionBodyInput = {
99
112
  kind: "agentic";
113
+ cli_learning?: CliLearningBinding;
100
114
  sdk?: SdkBinding;
101
115
  native?: NativeBinding;
102
116
  instructions: string;
@@ -112,6 +126,7 @@ export type RevisionBodyInput = {
112
126
  learning?: LearningSetting;
113
127
  toolSettings?: ToolSettings;
114
128
  maxCostUsd?: number;
129
+ maxRequests?: number;
115
130
  approvals?: "ask" | "never";
116
131
  inputSchema?: Record<string, unknown>;
117
132
  outputSchema?: Record<string, unknown>;
@@ -126,6 +141,7 @@ export type RevisionBodyInput = {
126
141
  computer?: unknown;
127
142
  toolSettings?: ToolSettings;
128
143
  maxCostUsd?: number;
144
+ maxRequests?: number;
129
145
  approvals?: "ask" | "never";
130
146
  };
131
147
  /** The body of a new revision and the text of each skill it names (path to text), everything checked here, before any
@@ -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"))
@@ -102,7 +113,10 @@ export function bodyOf(input) {
102
113
  // A default spend cap, for a revision of either kind.
103
114
  if (input.maxCostUsd !== undefined && !(typeof input.maxCostUsd === "number" && Number.isFinite(input.maxCostUsd) && input.maxCostUsd > 0))
104
115
  invalid("the maxCostUsd is not a number above 0");
105
- const capped = input.maxCostUsd !== undefined ? { maxCostUsd: input.maxCostUsd } : {};
116
+ // The agent's own limit on each run's requests on free models (definition.max_requests), under the server's.
117
+ if (input.maxRequests !== undefined && !(typeof input.maxRequests === "number" && Number.isSafeInteger(input.maxRequests) && input.maxRequests >= 1))
118
+ invalid("the maxRequests is not a whole number above 0");
119
+ const capped = { ...(input.maxCostUsd !== undefined ? { maxCostUsd: input.maxCostUsd } : {}), ...(input.maxRequests !== undefined ? { maxRequests: input.maxRequests } : {}) };
106
120
  // Whether the agent runs unattended (its definition.approvals): "never" lets an ask run without a person, for a revision
107
121
  // of either kind. "ask" (the default, as an agent read says it) is taken and kept as no value, so the default stays
108
122
  // implicit and a definition put back as it reads is the same revision; "never" is kept.
@@ -130,10 +144,13 @@ export function bodyOf(input) {
130
144
  invalid("the modelTiers are not fast and strong to a non-empty model");
131
145
  if (input.sdk !== undefined && (!isObject(input.sdk) || Object.keys(input.sdk).some(key => key !== "runtime" && key !== "platform") || !sdkBindingOf(input.sdk)))
132
146
  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");
147
+ if ([input.sdk, input.native, input.cli_learning].filter(Boolean).length > 1)
148
+ invalid("sdk, native and cli_learning connections are mutually exclusive");
149
+ 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))
150
+ invalid("cli_learning requires a registered runtime, connection_id and project");
135
151
  const body = {
136
152
  ...(input.sdk ? { sdk: { ...input.sdk } } : {}),
153
+ ...(input.cli_learning ? { cli_learning: { ...input.cli_learning } } : {}),
137
154
  instructions: input.instructions,
138
155
  ...(input.native !== undefined ? { native: nativeBindingOf(input.native) } : {}),
139
156
  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, AttemptCause, 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, RunAttemptRow, RunAttempts, 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";
@@ -21,6 +21,8 @@ interface SqliteExecutor {
21
21
  get<R extends object>(sql: string, ...params: SqliteValue[]): Promise<R | undefined>;
22
22
  all<R extends object>(sql: string, ...params: SqliteValue[]): Promise<R[]>;
23
23
  }
24
+ /** A run's first id to mint: pi's root conversation is 1. */
25
+ export declare const JOURNAL_FIRST_ID = 2;
24
26
  type StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;
25
27
  /** A document a commit changed, as the live view reads it: its value at that seq, or `retired` with none. */
26
28
  export type JournalDocument = {
@@ -14,7 +14,8 @@ function readsOf(db) {
14
14
  };
15
15
  }
16
16
  /** A run's first id to mint: pi's root conversation is 1. */
17
- const FIRST_ID = 2;
17
+ export const JOURNAL_FIRST_ID = 2;
18
+ const FIRST_ID = JOURNAL_FIRST_ID;
18
19
  const parseJson = (value) => JSON.parse(String(value));
19
20
  const encodeJson = (value) => JSON.stringify(value);
20
21
  // Some SQLite bindings replace lone UTF-16 surrogates. JSON encoding keeps indexed identities lossless.
@@ -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[];