@parcha/agentrun-serve 0.1.0-beta.59 → 0.1.0-beta.61

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 (250) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +230 -120
  3. package/dist/acp-package.d.ts +4 -0
  4. package/dist/agent-delete.d.ts +6 -9
  5. package/dist/agent-delete.js +5 -3
  6. package/dist/agent-package.js +11 -1
  7. package/dist/api-only.d.ts +21 -3
  8. package/dist/api-only.js +41 -6
  9. package/dist/archil-routes.d.ts +4 -1
  10. package/dist/archil-routes.js +15 -12
  11. package/dist/archil-settings.d.ts +18 -8
  12. package/dist/archil-settings.js +35 -17
  13. package/dist/browser-person.d.ts +1 -1
  14. package/dist/browser-person.js +1 -1
  15. package/dist/calendar/tools.js +1 -1
  16. package/dist/chatgpt-plan.d.ts +4 -2
  17. package/dist/chatgpt-plan.js +13 -3
  18. package/dist/claude-login-token.d.ts +5 -0
  19. package/dist/claude-login-token.js +8 -0
  20. package/dist/claude-login.d.ts +49 -3
  21. package/dist/claude-login.js +140 -10
  22. package/dist/cli-learning/connections.js +1 -1
  23. package/dist/cli.js +42 -10
  24. package/dist/console/assets/{backend-BztxEAvb.js → backend-C9ffXUR5.js} +1 -1
  25. package/dist/console/assets/index-BnZV3lvW.js +639 -0
  26. package/dist/console/assets/{share-L84tlUDW.js → share-B1o5mJ56.js} +2 -2
  27. package/dist/console/assets/{styles-CaRKlHke.js → styles-D_znYrHR.js} +31 -31
  28. package/dist/console/assets/styles-fjQBFfMv.css +1 -0
  29. package/dist/console/index.html +3 -3
  30. package/dist/console/share.html +3 -3
  31. package/dist/decisions.d.ts +1 -1
  32. package/dist/decisions.js +2 -2
  33. package/dist/errors.d.ts +1 -0
  34. package/dist/errors.js +2 -0
  35. package/dist/factory-activity.d.ts +68 -0
  36. package/dist/factory-activity.js +153 -0
  37. package/dist/factory-runs.d.ts +11 -0
  38. package/dist/factory-runs.js +52 -0
  39. package/dist/filed-tool.d.ts +32 -0
  40. package/dist/filed-tool.js +122 -0
  41. package/dist/harness-check.js +2 -1
  42. package/dist/harness-keys.d.ts +1 -2
  43. package/dist/harness-keys.js +1 -2
  44. package/dist/harness-recipe.d.ts +13 -2
  45. package/dist/harness-recipe.js +30 -7
  46. package/dist/harness-sign-in.js +2 -1
  47. package/dist/harness-table.d.ts +9 -3
  48. package/dist/harness-table.js +11 -5
  49. package/dist/harness.js +6 -2
  50. package/dist/import-worker.js +2 -2
  51. package/dist/import.d.ts +9 -0
  52. package/dist/import.js +11 -1
  53. package/dist/key-refusal.d.ts +5 -0
  54. package/dist/key-refusal.js +30 -18
  55. package/dist/learn/audit.d.ts +20 -22
  56. package/dist/learn/audit.js +72 -55
  57. package/dist/learn/check.js +1 -1
  58. package/dist/learn/commit.d.ts +35 -43
  59. package/dist/learn/commit.js +62 -270
  60. package/dist/learn/compile.d.ts +4 -4
  61. package/dist/learn/compile.js +6 -7
  62. package/dist/learn/corrections.js +1 -1
  63. package/dist/learn/delete.d.ts +5 -12
  64. package/dist/learn/delete.js +17 -30
  65. package/dist/learn/forget-run.d.ts +16 -0
  66. package/dist/learn/forget-run.js +53 -0
  67. package/dist/learn/index.js +1 -1
  68. package/dist/learn/learning-of.d.ts +0 -4
  69. package/dist/learn/learning-of.js +0 -5
  70. package/dist/learn/{folder.d.ts → legacy/folder.d.ts} +2 -1
  71. package/dist/learn/{folder.js → legacy/folder.js} +4 -7
  72. package/dist/learn/legacy/place.d.ts +16 -0
  73. package/dist/{workspace/learning-workspace.js → learn/legacy/place.js} +12 -42
  74. package/dist/learn/legacy/scrub.d.ts +28 -0
  75. package/dist/learn/legacy/scrub.js +258 -0
  76. package/dist/learn/promote.d.ts +40 -66
  77. package/dist/learn/promote.js +69 -207
  78. package/dist/learn/reset-ledger.d.ts +18 -0
  79. package/dist/learn/reset-ledger.js +14 -0
  80. package/dist/learn/rows.d.ts +186 -0
  81. package/dist/learn/rows.js +376 -0
  82. package/dist/learn/secrets.d.ts +2 -1
  83. package/dist/learn/secrets.js +2 -2
  84. package/dist/learn/workflow-draft.d.ts +4 -1
  85. package/dist/learn/workflow-draft.js +12 -2
  86. package/dist/learned-nodes.d.ts +36 -0
  87. package/dist/learned-nodes.js +23 -0
  88. package/dist/learning-reset.d.ts +1 -1
  89. package/dist/learning-reset.js +9 -11
  90. package/dist/learning-routes.d.ts +60 -81
  91. package/dist/learning-routes.js +187 -360
  92. package/dist/learning-words.d.ts +2 -0
  93. package/dist/learning-words.js +2 -0
  94. package/dist/learning.d.ts +18 -24
  95. package/dist/learning.js +35 -66
  96. package/dist/local-model.d.ts +144 -0
  97. package/dist/local-model.js +214 -0
  98. package/dist/mcp-gateway.d.ts +6 -0
  99. package/dist/mcp-gateway.js +44 -8
  100. package/dist/mcp-probe.d.ts +7 -0
  101. package/dist/mcp-probe.js +7 -0
  102. package/dist/mcp-resources.d.ts +1 -1
  103. package/dist/native/discovery.d.ts +6 -0
  104. package/dist/native/discovery.js +14 -1
  105. package/dist/native/remote.d.ts +5 -0
  106. package/dist/native/remote.js +16 -0
  107. package/dist/native/runtime.js +3 -2
  108. package/dist/observation/observer.d.ts +6 -6
  109. package/dist/ollama-provider.d.ts +35 -0
  110. package/dist/ollama-provider.js +108 -2
  111. package/dist/openapi.js +147 -35
  112. package/dist/place-offers.d.ts +3 -0
  113. package/dist/place-offers.js +3 -0
  114. package/dist/place.d.ts +35 -12
  115. package/dist/place.js +67 -29
  116. package/dist/print.js +1 -1
  117. package/dist/purged-workflow.d.ts +0 -33
  118. package/dist/purged-workflow.js +3 -71
  119. package/dist/redact/match.d.ts +36 -8
  120. package/dist/redact/match.js +179 -44
  121. package/dist/run-export.js +4 -2
  122. package/dist/run-launch.d.ts +3 -3
  123. package/dist/run-learning-served.d.ts +3 -3
  124. package/dist/run-learning-served.js +1 -1
  125. package/dist/run-listing.d.ts +1 -1
  126. package/dist/run-timeline-served.d.ts +1 -1
  127. package/dist/run-timeline-served.js +6 -5
  128. package/dist/run-usage.js +3 -2
  129. package/dist/runnable.js +25 -8
  130. package/dist/runner/adapter-loop.d.ts +8 -1
  131. package/dist/runner/adapter-loop.js +100 -20
  132. package/dist/runner/adapter-run-spec.d.ts +3 -5
  133. package/dist/runner/adapter-run-spec.js +35 -61
  134. package/dist/runner/adapters/pi.d.ts +3 -2
  135. package/dist/runner/adapters/pi.js +3 -1
  136. package/dist/runner/audit.d.ts +3 -5
  137. package/dist/runner/audit.js +28 -51
  138. package/dist/runner/cli-run-spec.js +19 -22
  139. package/dist/runner/compare-end.d.ts +1 -3
  140. package/dist/runner/compare-end.js +6 -2
  141. package/dist/runner/disk-free.d.ts +15 -4
  142. package/dist/runner/disk-free.js +25 -7
  143. package/dist/runner/dispatch.js +2 -2
  144. package/dist/runner/feedback-round.d.ts +1 -1
  145. package/dist/runner/feedback-round.js +2 -2
  146. package/dist/runner/harness-loops.d.ts +9 -0
  147. package/dist/runner/harness-loops.js +49 -7
  148. package/dist/runner/held.d.ts +4 -11
  149. package/dist/runner/held.js +0 -25
  150. package/dist/runner/journal-kinds.d.ts +4 -1
  151. package/dist/runner/journal-kinds.js +1 -1
  152. package/dist/runner/learned-first.d.ts +0 -2
  153. package/dist/runner/learned-first.js +3 -3
  154. package/dist/runner/learning-end.d.ts +12 -16
  155. package/dist/runner/learning-end.js +41 -75
  156. package/dist/runner/learning-seed.d.ts +13 -16
  157. package/dist/runner/learning-seed.js +13 -23
  158. package/dist/runner/live-ticker.js +3 -4
  159. package/dist/runner/main.js +1 -1
  160. package/dist/runner/mcp-claim.js +3 -2
  161. package/dist/runner/mcp-run.d.ts +23 -4
  162. package/dist/runner/mcp-run.js +31 -2
  163. package/dist/runner/metrics.d.ts +4 -0
  164. package/dist/runner/metrics.js +9 -3
  165. package/dist/runner/monid-run.js +3 -1
  166. package/dist/runner/native-loop.js +3 -4
  167. package/dist/runner/promotion.d.ts +19 -28
  168. package/dist/runner/promotion.js +50 -69
  169. package/dist/runner/redact.d.ts +3 -0
  170. package/dist/runner/redact.js +7 -0
  171. package/dist/runner/reflect-hook.d.ts +2 -2
  172. package/dist/runner/reflect-hook.js +4 -1
  173. package/dist/runner/run-child-host.d.ts +1 -9
  174. package/dist/runner/run-child-host.js +12 -68
  175. package/dist/runner/runner.d.ts +1 -1
  176. package/dist/runner/sdk-loop.js +7 -7
  177. package/dist/runner/workflow-calls.d.ts +4 -1
  178. package/dist/runner/workflow-calls.js +35 -18
  179. package/dist/runner/workflow-loop.d.ts +1 -1
  180. package/dist/runner/workflow-loop.js +3 -1
  181. package/dist/runner/workflow-spec.d.ts +4 -0
  182. package/dist/runner/workflow-spec.js +18 -13
  183. package/dist/runs-over-store.d.ts +2 -2
  184. package/dist/runs-over-store.js +1 -1
  185. package/dist/sdk/check.d.ts +1 -4
  186. package/dist/sdk/check.js +2 -3
  187. package/dist/sdk/runs.d.ts +20 -7
  188. package/dist/sdk/runs.js +105 -68
  189. package/dist/secret-cut.js +7 -4
  190. package/dist/secret-rules.js +97 -83
  191. package/dist/secrets.d.ts +4 -0
  192. package/dist/secrets.js +44 -10
  193. package/dist/server-fs.d.ts +1 -1
  194. package/dist/server-fs.js +1 -1
  195. package/dist/server-keys.d.ts +6 -0
  196. package/dist/server-keys.js +12 -0
  197. package/dist/server.d.ts +22 -15
  198. package/dist/server.js +311 -198
  199. package/dist/slack.js +2 -1
  200. package/dist/source-sync/auxiliary.js +2 -2
  201. package/dist/store/index.d.ts +1 -1
  202. package/dist/store/index.js +1 -1
  203. package/dist/store/postgres/migrate.js +3 -1
  204. package/dist/store/postgres/migrations/0032_learning_rows.sql +65 -0
  205. package/dist/store/schema.d.ts +28 -2
  206. package/dist/store/schema.js +81 -5
  207. package/dist/store/sqlite/learning-rows.d.ts +23 -0
  208. package/dist/store/sqlite/learning-rows.js +559 -0
  209. package/dist/store/sqlite/store.d.ts +7 -1
  210. package/dist/store/sqlite/store.js +84 -18
  211. package/dist/store/store.d.ts +219 -6
  212. package/dist/store/store.js +13 -0
  213. package/dist/store-reads/journal.d.ts +33 -3
  214. package/dist/store-reads/journal.js +99 -4
  215. package/dist/store-reads/learning.d.ts +23 -26
  216. package/dist/store-reads/learning.js +42 -30
  217. package/dist/store-reads/loop.js +1 -1
  218. package/dist/store-view.d.ts +24 -2
  219. package/dist/store-view.js +40 -11
  220. package/dist/templates.d.ts +10 -2
  221. package/dist/templates.js +31 -4
  222. package/dist/tool-plane.d.ts +27 -3
  223. package/dist/tool-plane.js +79 -4
  224. package/dist/tools.d.ts +12 -2
  225. package/dist/tools.js +42 -7
  226. package/dist/trigger-launch-hook.d.ts +2 -2
  227. package/dist/trigger-launch-hook.js +1 -1
  228. package/dist/triggers.d.ts +7 -4
  229. package/dist/triggers.js +4 -4
  230. package/dist/web-holds.d.ts +2 -0
  231. package/dist/web-holds.js +5 -2
  232. package/dist/web-run.js +2 -1
  233. package/dist/workspace/archil-exec.js +1 -1
  234. package/dist/workspace/archil.d.ts +1 -1
  235. package/dist/workspace/archil.js +1 -1
  236. package/dist/workspace/computer-deps.js +5 -3
  237. package/dist/workspace/computer-providers.d.ts +11 -1
  238. package/dist/workspace/computer-providers.js +29 -2
  239. package/dist/workspace/index.d.ts +1 -2
  240. package/dist/workspace/index.js +1 -2
  241. package/dist/workspace/paths.d.ts +0 -4
  242. package/dist/workspace/paths.js +0 -6
  243. package/dist/workspace/workspace.d.ts +1 -1
  244. package/dist/workspace/workspace.js +1 -1
  245. package/package.json +13 -13
  246. package/templates/TOOLS.md +46 -0
  247. package/dist/console/assets/index-LwNL4L9q.js +0 -619
  248. package/dist/console/assets/styles-DQo8rzY-.css +0 -1
  249. package/dist/workspace/learning-workspace.d.ts +0 -24
  250. /package/dist/learn/{learning.sh → legacy/learning.sh} +0 -0
@@ -176,6 +176,14 @@ export function bookedDecisionsOf(entries, ids) {
176
176
  * call (runner/workflow-calls.ts). $0 for none; null once one has no known cost, or one a crash cut is counted at its
177
177
  * hold (`atMost`: the most it can cost, never what it cost). */
178
178
  export function callCostOf(entries, callId, from, to) {
179
+ const kept = callTurnsOf(entries, callId, from, to);
180
+ const cost = runCostOf(entries.filter((e) => !(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || kept.has(turnOf(e))));
181
+ return cost.atMost > 0 ? null : cost.usd;
182
+ }
183
+ /** The turns of the requests call `callId` booked, by callCostOf's rule: each request whose record names it or one nested
184
+ * in it, and each of host work admitted in its window (`from` < at <= `to`; -1 for both: no window, those named alone).
185
+ * None: nothing was booked under the call. */
186
+ export function callTurnsOf(entries, callId, from, to) {
179
187
  const keyed = sessionConversations(entries);
180
188
  const hosted = new Set([keyed.get(TOOL_SESSION), keyed.get(DECISION_SESSION)].filter((one) => one !== undefined));
181
189
  const ours = (e, at) => {
@@ -184,9 +192,7 @@ export function callCostOf(entries, callId, from, to) {
184
192
  return true;
185
193
  return at > from && at <= to && (typeof d.host === "string" || d.side === true || hosted.has(Number(e.conversationId)));
186
194
  };
187
- const kept = new Set(entries.flatMap((e, at) => (e.kind === RUNNER_RECORDS.request && ours(e, at) ? [turnOf(e)] : [])));
188
- const cost = runCostOf(entries.filter((e) => !(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || kept.has(turnOf(e))));
189
- return cost.atMost > 0 ? null : cost.usd;
195
+ return new Set(entries.flatMap((e, at) => (e.kind === RUNNER_RECORDS.request && ours(e, at) ? [turnOf(e)] : [])));
190
196
  }
191
197
  /** A sum of charges with its float noise rounded off, nothing more (as the decisions row rounds, decision-rows.ts): a
192
198
  * decision costs millionths of a dollar, so a sum rounded to the millionth would lose it. */
@@ -158,11 +158,13 @@ export function withMonid(mcp, monid) {
158
158
  return mcp;
159
159
  return {
160
160
  tools: [...(mcp?.tools ?? []), ...monid.tools],
161
+ unconnected: mcp?.unconnected ?? [],
162
+ ...(mcp?.leftOut ? { leftOut: mcp.leftOut } : {}),
161
163
  catalogOf: (tool) => mcp?.catalogOf(tool) ?? monid.catalogOf(tool),
162
164
  argumentsOf: (name) => mcp?.argumentsOf(name),
163
165
  effectOf: (name) => mcp?.effectOf(name),
164
166
  priceOf: (name) => mcp?.priceOf(name) ?? monid.priceOf(name),
165
- fresh: async () => mcp?.fresh(),
167
+ fresh: async () => (await mcp?.fresh()) ?? [],
166
168
  release: () => mcp?.release(),
167
169
  };
168
170
  }
@@ -7,7 +7,6 @@ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
7
7
  import { join } from 'node:path';
8
8
  import { BACKGROUND_CONTEXT, withAbortSignal } from '@earendil-works/chord/context';
9
9
  import { ROOT_CONVERSATION_ID } from '@earendil-works/pi-durable';
10
- import { learningFolderOf } from '../learning.js';
11
10
  import { nativeOf, nativeModelOverrides, nativeExecutionOverrides, NATIVE_MODEL_SETTINGS_UNSUPPORTED, NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, NATIVE_TOOL_BUDGET_UNSUPPORTED } from '../native/binding.js';
12
11
  import { launchNative } from '../native/connection.js';
13
12
  import { openNativeSession } from '../native/runtime.js';
@@ -197,7 +196,7 @@ export function createNativeLoop(launch, host) {
197
196
  const entries = await journalEntries(journal, ctx);
198
197
  const spend = bookedSpend(entries, 'model');
199
198
  // Its path by the one writer every harness's end calls: a native task never calls a learned workflow, so `agent`.
200
- const path = await runPathMetricsOverStore(host.store, claim.runId, launch);
199
+ const path = await runPathMetricsOverStore(host.store, claim.runId, launch, { redact });
201
200
  return { costUsd: spend.usd, metrics: { ...nativeMetrics(entries, spend, model, turn, path, runtime), native_session_id: nativeSessionId, ...(usage ? { native_usage: usage } : {}) } };
202
201
  };
203
202
  endPatch = await Promise.race([read(), late]);
@@ -275,7 +274,7 @@ export function createNativeLoop(launch, host) {
275
274
  await append(KINDS.message, { role: 'person', text: retry, at: Date.now(), origin: { kind: 'server', reason: 'output_retry' } });
276
275
  result = await task(retry);
277
276
  }
278
- const end = automaticLearningUnavailable ? undefined : learningEndOfRun(launch, { store: host.store, data: host.data, learningFolder: id => learningFolderOf(host.data, id), env: process.env, stored: () => storeSecrets(host.store, host.sealKey, host.data) });
277
+ const end = automaticLearningUnavailable ? undefined : learningEndOfRun(launch, { store: host.store, data: host.data, env: process.env, stored: () => storeSecrets(host.store, host.sealKey, host.data) });
279
278
  if (end) {
280
279
  reflect = true;
281
280
  also = (await end({ runId: claim.runId, agentId, claim, outcome: 'completed', signal, ask: async (prompt, opts) => {
@@ -315,7 +314,7 @@ export function createNativeLoop(launch, host) {
315
314
  await append(`${MARK}.waiting`, { project: launch.native?.project }, { state: 'parked', summary: 'Waiting for the other native job in this source project.' });
316
315
  return { state: 'parked', wakeAt: Date.now() + 1000 };
317
316
  }
318
- const hook = automaticLearningUnavailable ? undefined : learningEndOfRun(launch, { store: host.store, data: host.data, learningFolder: id => learningFolderOf(host.data, id) });
317
+ const hook = automaticLearningUnavailable ? undefined : learningEndOfRun(launch, { store: host.store, data: host.data });
319
318
  if (hook && !also)
320
319
  also = (await hook({ runId: claim.runId, agentId, claim, outcome: 'failed', cut: reflect ? 'stopped-looking' : 'faulted', signal, ask: async () => ({ failed: { code: 'native_failed', message } }) }))?.also;
321
320
  await append(KINDS.end, { state: 'failed', error: message }, { state: 'failed', outcome: null, summary: message, ...partial }, also);
@@ -5,9 +5,8 @@ import { type RunLaunch } from "../run-launch.js";
5
5
  import { type Store } from "../store/store.js";
6
6
  import { type Recorded, type ReplayCalls, type Skipped } from "../learn/replay-calls.js";
7
7
  import { type Json } from "../validate.js";
8
- import { type CheckBar, type CheckRecord, type CheckTurns, type Compared, type PromotionRecord, recordPromotion, type Refused, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
8
+ import { type CheckBar, type CheckRecord, type CheckTurns, type Compared, type PromotionRecord, recordPromotion, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
9
9
  import { type FirstChoice, type Promoted, type ReplayOutcome } from "./workflow-first.js";
10
- import type { LearningFolder } from "../learn/folder.js";
11
10
  import type { Shown } from "../learning.js";
12
11
  /** A replay run still not ended this long after its replay started counts as failed (no evidence), and is cancelled once
13
12
  * the replay is decided without it. */
@@ -31,15 +30,11 @@ export interface PromotionDeps {
31
30
  readonly launch: RunLaunch;
32
31
  readonly context: Context;
33
32
  readonly log: (line: string) => void;
34
- /** The learned workflow `name` as the learning folder held it active at `commit` (a champion's text), or undefined when
35
- * it held none by that name, or a purged run wrote it (learning.ts seedAt): a purged run's text is never served (the
36
- * champion skips it first, `refused`). Absent: no champion serves. */
33
+ /** The learned workflow `name` as the agent's learning held it active at save `commit` (a champion's text), read now,
34
+ * or undefined when it holds none by that name: a purged run's text went with its rows (learning.ts seedAt), so it is
35
+ * never served. Absent: no champion serves. */
37
36
  readonly champion?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>;
38
- /** The records of `workflows` (all, when absent) championOf skips (purged-workflow.ts refusedIn over the learning
39
- * folder): a champion the purge gate refuses at its commit, so the newest promotion it lets through serves, and the
40
- * promotions trim keeps that one (recordPromotion). Absent: none skipped. */
41
- readonly refused?: (records: readonly PromotionRecord[], workflows?: Iterable<string>) => Promise<Refused>;
42
- /** The digest of the learned workflow `name` the learning folder's main holds now (the newest revision), or undefined
37
+ /** The digest of the learned workflow `name` the agent's newest save holds (the newest revision), or undefined
43
38
  * when it holds none by that name. Absent: every revision is the newest. */
44
39
  readonly newest?: (name: string) => Promise<string | undefined>;
45
40
  /** The learned workflow an earlier claim of this run served first (its WORKFLOW_FIRST entry, answered or handed back:
@@ -59,20 +54,18 @@ export interface PromotionDeps {
59
54
  }
60
55
  /** What deciding a check needs (decideCheck, stopUnchecked): a claim's ports, or those of a connected agent's start or
61
56
  * run end, whose record names its commit (no claimed launch to read a seed from). */
62
- type DecideDeps = Pick<PromotionDeps, "store" | "agentId" | "log" | "shown"> & Partial<Pick<PromotionDeps, "launch" | "now" | "refused">>;
63
- /** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a champion read
64
- * from it at its record's commit, cut of the server's secrets (`shown`) as the claim's lay is; and the workflow an earlier
65
- * claim of this run served (`kept`, from its journal: none on a first claim). */
66
- export declare function claimPromotion(deps: Omit<PromotionDeps, "champion" | "kept"> & {
67
- readonly folder: () => LearningFolder;
68
- }): PromotionDeps;
57
+ type DecideDeps = Pick<PromotionDeps, "store" | "agentId" | "log" | "shown"> & Partial<Pick<PromotionDeps, "launch" | "now">>;
58
+ /** The claim's promotion ports: a champion read from the agent's learning at its record's save, cut of the server's
59
+ * secrets (`shown`) as the claim's lay is; and the workflow an earlier claim of this run served (`kept`, from its
60
+ * journal: none on a first claim). */
61
+ export declare function claimPromotion(deps: Omit<PromotionDeps, "champion" | "kept">): PromotionDeps;
69
62
  /** A replay run's claim (launch.replay) of run `runId`, once its first choice is made: refused (ClaimRefused: the run ends
70
63
  * failed, no agent turn, nothing sent) unless its revision's record still says replaying and names it among its runs (it
71
64
  * is reserved before its runs are created), or has none (trimmed), and the claim laid that revision to serve it. A
72
65
  * promoted or held revision's replay run never runs (a cancel that never reached it included), nor an older
73
66
  * replay's leftover once its revision replays again; one whose workflow is not laid at its digest (the seed could not be
74
67
  * read, the folder moved on) never falls to the agent's path. Any other run: nothing to check. */
75
- export declare function replayClaimed(store: Pick<Store, "settings">, agentId: string, runId: string, launch: RunLaunch, choice: FirstChoice): Promise<void>;
68
+ export declare function replayClaimed(store: Pick<Store, "learning">, agentId: string, runId: string, launch: RunLaunch, choice: FirstChoice): Promise<void>;
76
69
  /** The workflows a replay run's claim lays (`laid`, the seed lay's): the one it replays, or none by that name when the
77
70
  * laid one is not the digest it replays (the replay then fails, never scoring another revision). Any other run's, as laid. */
78
71
  export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWorkflow[]): LearnedWorkflow[];
@@ -84,13 +77,12 @@ export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWork
84
77
  * never named is an unchecked draft and is not offered. A replay run's as laid (replayLaid). The records unread: only
85
78
  * the one served first, as the gate leaves a run to its agent. The money rule over what this hands the tool, the one
86
79
  * its first choice stopped included, is runner/learned-first.ts's (workflow-first.ts toolStopsOf). */
87
- export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "refused" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
80
+ export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
88
81
  /** `flow`'s champion (championOf) and the text it serves from: `flow` itself when it is the champion, else the
89
82
  * champion's text read at its record's commit (`read`), kept only when its digest is the champion's. No text: none is
90
- * promoted, or its text cannot be read. The champion skips what `refused` says the purge gate refuses (PromotionDeps
91
- * refused), so after a purge of its run the newest promotion the gate lets through serves. The one champion lookup a
83
+ * promoted, or its text cannot be read (a purged run's text went with its rows). The one champion lookup a
92
84
  * claim's gate (servingNow), the learned_workflow tool (toolFlowsFor) and a connected agent's start (sdk/runs.ts) share. */
93
- export declare function championTextOf(records: readonly PromotionRecord[], flow: LearnedWorkflow, read?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>, refused?: PromotionDeps["refused"]): Promise<{
85
+ export declare function championTextOf(records: readonly PromotionRecord[], flow: LearnedWorkflow, read?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>): Promise<{
94
86
  champion?: PromotionRecord;
95
87
  text?: LearnedWorkflow;
96
88
  }>;
@@ -144,11 +136,11 @@ export declare const WHOLE_ANSWER = "answer";
144
136
  * answer and none was wrong (a grade that contradicts itself). The audit's one verdict (runner/audit.ts). */
145
137
  export declare function answerJudged(row: Pick<CheckRow, "agent" | "answer" | "compared" | "expected" | "correct">, on: readonly string[] | undefined): boolean | null;
146
138
  /** Decides a check on its rows, with a connected agent's turns checked before them (`before`), judged field by field on
147
- * its bar (judgeRows). Promoted when it serves (learn/field-check.ts: enough answered alone, every field passes) and the
148
- * purge gate lets its revision through at its commit (`refused`: else held, a purged run's text); else held on its
149
- * failing fields with the inputs it did not agree on, which the agent's next run's compile turn reads as data (its one
150
- * recompile); a recompile's check that holds it too stops: nothing compiles again. No refit, queue or second replay.
151
- * Kept only while `still` holds of the digest's record (the one write: of two claims at once, one decides). */
139
+ * its bar (judgeRows). Promoted when it serves (learn/field-check.ts: enough answered alone, every field passes); else
140
+ * held on its failing fields with the inputs it did not agree on, which the agent's next run's compile turn reads as
141
+ * data (its one recompile); a recompile's check that holds it too stops: nothing compiles again. No refit, queue or
142
+ * second replay. Kept only while `still` holds of the digest's record (the one write: of two claims at once, one
143
+ * decides). */
152
144
  export declare function decideCheck(deps: DecideDeps, name: string, digest: string, bar: CheckBar, read: {
153
145
  rows: readonly CheckRow[];
154
146
  cost: number | null;
@@ -244,7 +236,6 @@ export interface ReplayAsk {
244
236
  readonly agentId: string;
245
237
  readonly context: Context;
246
238
  readonly log: (line: string) => void;
247
- readonly folder: () => LearningFolder;
248
239
  readonly shown: () => Promise<Shown>;
249
240
  readonly launchOf: (input: Json) => Promise<{
250
241
  readonly launch: RunLaunch;
@@ -58,10 +58,9 @@ import { isObject } from "../validate.js";
58
58
  import { agentRun, lastOwnRuns, newCompileAttempt, sinceReset } from "../learn/compile.js";
59
59
  import { answerAt, answerValue, checkShares, CHECK_TEXT_MAX, championOf, compareAnswers, comparedGrade, comparedOf, gradesOf, knownAnswerText, promotionOf, promotionsOf, recordPromotion, replayingOf, sameAnswer, skippedToolsOf, valueAtPath } from "../learn/promote.js";
60
60
  import { check as checkFields, jointSaid, KNOWN, tallyOf } from "../learn/field-check.js";
61
- import { refusedIn } from "../purged-workflow.js";
62
61
  import { sendCommand } from "./commands.js";
63
62
  import { ClaimRefused } from "./loop-contract.js";
64
- import { readSnapshot } from "../learn/folder.js";
63
+ import { readView, learningOf } from "../learn/rows.js";
65
64
  import { fits, laidFor, servedOf, workflowDigest } from "./workflow-first.js";
66
65
  import { excerptShown } from "../learn/secrets.js";
67
66
  import { dslRefusalOf } from "../learn/workflow-draft.js";
@@ -73,25 +72,17 @@ export const REPLAY_DEADLINE_MS = 60 * 60 * 1000;
73
72
  /** A reserved replay run still not created this long after its record was reserved is a launch that was interrupted (the
74
73
  * reserving claim crashed, or its create failed): the next claim creates it (relaunch). Before then it is pending. */
75
74
  export const REPLAY_LAUNCH_GRACE_MS = 5 * 60 * 1000;
76
- /** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a champion read
77
- * from it at its record's commit, cut of the server's secrets (`shown`) as the claim's lay is; and the workflow an earlier
78
- * claim of this run served (`kept`, from its journal: none on a first claim). */
75
+ /** The claim's promotion ports: a champion read from the agent's learning at its record's save, cut of the server's
76
+ * secrets (`shown`) as the claim's lay is; and the workflow an earlier claim of this run served (`kept`, from its
77
+ * journal: none on a first claim). */
79
78
  export function claimPromotion(deps) {
80
79
  return {
81
80
  ...deps,
82
81
  kept: async () => (deps.runId ? servedOf(await runEntries(deps.store, deps.runId, deps.context).catch(() => [])) : undefined),
83
- champion: async (name, commit) => (await workflowsAt({ folder: deps.folder, store: deps.store, shown: deps.shown }, commit)).find((one) => one.name === name),
84
- refused: refusedIn(deps.folder, deps.store, deps.log),
82
+ champion: async (name, commit) => (await workflowsAt(deps, commit)).find((one) => one.name === name),
85
83
  newest: async (name) => {
86
- const folder = deps.folder();
87
- let main;
88
- try {
89
- main = (await readSnapshot(folder.workspace))?.main;
90
- }
91
- finally {
92
- await folder.end().catch(() => undefined);
93
- }
94
- const text = main ? (await workflowsAt({ folder: deps.folder, store: deps.store, shown: deps.shown }, main)).find((one) => one.name === name) : undefined;
84
+ const main = (await readView(learningOf(deps.store, deps.agentId)))?.main;
85
+ const text = main ? (await workflowsAt(deps, main)).find((one) => one.name === name) : undefined;
95
86
  return text ? workflowDigest(text) : undefined;
96
87
  },
97
88
  };
@@ -106,7 +97,7 @@ export async function replayClaimed(store, agentId, runId, launch, choice) {
106
97
  if (!launch.replay)
107
98
  return;
108
99
  const { workflow, digest } = launch.replay;
109
- const record = promotionOf(await promotionsOf(store.settings, agentId), workflow, digest);
100
+ const record = promotionOf(await promotionsOf(store.learning, agentId), workflow, digest);
110
101
  if (record && record.decided !== "replaying")
111
102
  throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision is ${record.decided === "promote" ? "promoted already" : "held already"}.`);
112
103
  if (record && !record.runs?.includes(runId))
@@ -137,7 +128,7 @@ export async function toolFlowsFor(deps, launch, laid, choice) {
137
128
  const name = choice.serve?.name;
138
129
  let records;
139
130
  try {
140
- records = await promotionsOf(deps.store.settings, deps.agentId);
131
+ records = await promotionsOf(deps.store.learning, deps.agentId);
141
132
  }
142
133
  catch (error) {
143
134
  deps.log(`workflow-first: the promotions could not be read (${error?.message ?? error}); the learned_workflow tool runs only the workflow chosen first`);
@@ -150,7 +141,7 @@ export async function toolFlowsFor(deps, launch, laid, choice) {
150
141
  continue;
151
142
  }
152
143
  const digest = workflowDigest(one);
153
- const { champion, text } = await championTextOf(records, one, deps.champion, deps.refused);
144
+ const { champion, text } = await championTextOf(records, one, deps.champion);
154
145
  if (text === one)
155
146
  out.push(one);
156
147
  else if (text) {
@@ -164,11 +155,10 @@ export async function toolFlowsFor(deps, launch, laid, choice) {
164
155
  }
165
156
  /** `flow`'s champion (championOf) and the text it serves from: `flow` itself when it is the champion, else the
166
157
  * champion's text read at its record's commit (`read`), kept only when its digest is the champion's. No text: none is
167
- * promoted, or its text cannot be read. The champion skips what `refused` says the purge gate refuses (PromotionDeps
168
- * refused), so after a purge of its run the newest promotion the gate lets through serves. The one champion lookup a
158
+ * promoted, or its text cannot be read (a purged run's text went with its rows). The one champion lookup a
169
159
  * claim's gate (servingNow), the learned_workflow tool (toolFlowsFor) and a connected agent's start (sdk/runs.ts) share. */
170
- export async function championTextOf(records, flow, read, refused) {
171
- const champion = championOf(records, flow.name, refused ? await refused(records, [flow.name]) : undefined);
160
+ export async function championTextOf(records, flow, read) {
161
+ const champion = championOf(records, flow.name);
172
162
  if (!champion)
173
163
  return {};
174
164
  if (champion.digest === workflowDigest(flow))
@@ -222,8 +212,8 @@ export const promotionGate = (deps) => {
222
212
  * does not take the input). Another champion: its text at its record's commit (its digest checked). Undefined when none
223
213
  * serves: none promoted, the champion held, or its text cannot be read (the agent takes the run). */
224
214
  async function servingNow(deps, workflow, digest, laid) {
225
- const records = await promotionsOf(deps.store.settings, deps.agentId);
226
- const { champion, text } = await championTextOf(records, workflow, deps.champion, deps.refused);
215
+ const records = await promotionsOf(deps.store.learning, deps.agentId);
216
+ const { champion, text } = await championTextOf(records, workflow, deps.champion);
227
217
  const own = promotionOf(records, workflow.name, digest);
228
218
  if (!champion) {
229
219
  if (own?.decided === "promote")
@@ -260,12 +250,12 @@ async function holdRefused(deps, serving) {
260
250
  return serving;
261
251
  const { name } = serving.workflow;
262
252
  const digest = workflowDigest(serving.workflow);
263
- const current = promotionOf(await promotionsOf(deps.store.settings, deps.agentId), name, digest);
253
+ const current = promotionOf(await promotionsOf(deps.store.learning, deps.agentId), name, digest);
264
254
  if (current?.decided !== "promote")
265
255
  return serving;
266
256
  const reason = excerptShown(`${DSL_REFUSES}: ${refused}`, await deps.shown(), CHECK_TEXT_MAX);
267
257
  const record = { workflow: name, digest, at: iso((deps.now ?? Date.now)()), decided: "hold", reason, ...(current.commit ? { commit: current.commit } : {}) };
268
- const kept = await recordPromotion(deps.store.settings, deps.agentId, record, (was) => was?.decided === "promote" && was.at === current.at, deps.refused);
258
+ const kept = await recordPromotion(deps.store.learning, deps.agentId, record, (was) => was?.decided === "promote" && was.at === current.at);
269
259
  if (kept.won)
270
260
  deps.log(`workflow-first: ${name} at ${digest} is held: ${reason}; the agent's next run recompiles it once`);
271
261
  return serving;
@@ -281,7 +271,7 @@ async function keptFor(deps, workflow, digest) {
281
271
  return undefined;
282
272
  if (kept.digest !== digest) {
283
273
  // Its newest record naming a commit.
284
- const record = (await promotionsOf(deps.store.settings, deps.agentId)).findLast((one) => one.workflow === workflow.name && one.digest === kept.digest && one.commit);
274
+ const record = (await promotionsOf(deps.store.learning, deps.agentId)).findLast((one) => one.workflow === workflow.name && one.digest === kept.digest && one.commit);
285
275
  const text = record?.commit && deps.champion ? await deps.champion(workflow.name, record.commit).catch(() => undefined) : undefined;
286
276
  if (text && workflowDigest(text) === kept.digest) {
287
277
  deps.log(`workflow-first: ${workflow.name} at ${kept.digest} served this run on an earlier claim; it keeps that revision`);
@@ -295,7 +285,7 @@ async function keptFor(deps, workflow, digest) {
295
285
  * (after finishing a launch that was interrupted). It decides nothing about who serves (servingNow does). */
296
286
  async function decide(deps, workflow, digest) {
297
287
  const { store, agentId, log } = deps;
298
- const record = promotionOf(await promotionsOf(store.settings, agentId), workflow.name, digest);
288
+ const record = promotionOf(await promotionsOf(store.learning, agentId), workflow.name, digest);
299
289
  if (record?.decided === "promote")
300
290
  return;
301
291
  if (record?.decided === "hold") {
@@ -397,17 +387,17 @@ async function startCheck(deps, workflow, digest) {
397
387
  const off = deps.spendOff?.("A learned workflow's replay check");
398
388
  if (off)
399
389
  return void log(`workflow-first: ${off} ${workflow.name} at ${digest} is not checked and does not serve this run`);
400
- // Only the learning folder's newest revision is checked: a run pinned to an older commit lays an older text.
390
+ // Only the agent's newest revision is checked: a run pinned to an older save lays an older text.
401
391
  const newest = deps.newest ? await deps.newest(workflow.name) : undefined;
402
392
  if (newest !== undefined && newest !== digest) {
403
- log(`workflow-first: ${workflow.name} at ${digest} is not the learning folder's newest revision of it (${newest}); it is not checked and does not serve this run`);
393
+ log(`workflow-first: ${workflow.name} at ${digest} is not the agent's newest revision of it (${newest}); it is not checked and does not serve this run`);
404
394
  return;
405
395
  }
406
396
  // One check at a time, and one at work finishes: decided here once its runs ended (its verdict stands), never
407
397
  // cancelled. While it runs, this revision waits, recording nothing: the claim after it is decided starts this one.
408
- for (const ahead of replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest))
398
+ for (const ahead of replayingOf(await promotionsOf(store.learning, agentId), workflow.name, digest))
409
399
  await settleAhead(deps, workflow.name, ahead);
410
- const records = await promotionsOf(store.settings, agentId);
400
+ const records = await promotionsOf(store.learning, agentId);
411
401
  const rival = replayingOf(records, workflow.name, digest)[0];
412
402
  if (rival) {
413
403
  log(`workflow-first: ${workflow.name} at ${digest} waits: ${rival.digest} is being checked (one check at a time); it does not serve this run`);
@@ -446,7 +436,7 @@ export const differentDecisionWords = (k, n, example) => `its answers reached a
446
436
  * or its owner acts, and `extra` on the record (a connected agent's check: what its reservation carries). Kept only while
447
437
  * `still` holds of the digest's record (the one write), and logged. */
448
438
  async function holdUnchecked(deps, name, digest, bar, reason, still, { stopped = false, check = {}, extra = {} } = {}) {
449
- const decided = await recordPromotion(deps.store.settings, deps.agentId, { workflow: name, digest, at: iso((deps.now ?? Date.now)()), decided: "hold", reason, check: { ...bar, n: 0, agreed: 0, alone: 0, agent_agreed: 0, of: [], ...check, ...(stopped ? { stopped: true } : {}) }, ...seedOf(deps), ...extra }, still, deps.refused);
439
+ const decided = await recordPromotion(deps.store.learning, deps.agentId, { workflow: name, digest, at: iso((deps.now ?? Date.now)()), decided: "hold", reason, check: { ...bar, n: 0, agreed: 0, alone: 0, agent_agreed: 0, of: [], ...check, ...(stopped ? { stopped: true } : {}) }, ...seedOf(deps), ...extra }, still);
450
440
  if (decided.won)
451
441
  deps.log(`workflow-first: ${name} at ${digest} ${stopped ? "stopped" : "held"}: ${reason}`);
452
442
  return decided;
@@ -523,7 +513,7 @@ async function checkRows(deps, record) {
523
513
  if (!late && runs.some((row) => !row || !FINAL_STATES.includes(row.state)))
524
514
  return undefined;
525
515
  // The newest grade of each run (gradesOf keeps them oldest first): a re-grade replaces what an earlier one said.
526
- const grades = new Map((await gradesOf(store.settings, deps.agentId)).map((grade) => [grade.run, grade]));
516
+ const grades = new Map((await gradesOf(store.learning, deps.agentId)).map((grade) => [grade.run, grade]));
527
517
  // An input whose grader was asked is judged on the grade it was asked against (Compared.graded): a grade given after
528
518
  // that is not the pair's, so it counts from the next check, never makes this verdict stale.
529
519
  const graded = (of, compared) => (compared?.graded !== undefined ? compared.graded : comparedGrade(grades.get(of))) ?? {};
@@ -631,11 +621,11 @@ async function judgeRows(deps, bar, rows, before) {
631
621
  /** Two outcome counts added. */
632
622
  const outcomesAdded = (a, b) => b ? { answered: a.answered + b.answered, handed_back: a.handed_back + b.handed_back, failed: a.failed + b.failed, skipped_write: a.skipped_write + b.skipped_write } : a;
633
623
  /** Decides a check on its rows, with a connected agent's turns checked before them (`before`), judged field by field on
634
- * its bar (judgeRows). Promoted when it serves (learn/field-check.ts: enough answered alone, every field passes) and the
635
- * purge gate lets its revision through at its commit (`refused`: else held, a purged run's text); else held on its
636
- * failing fields with the inputs it did not agree on, which the agent's next run's compile turn reads as data (its one
637
- * recompile); a recompile's check that holds it too stops: nothing compiles again. No refit, queue or second replay.
638
- * Kept only while `still` holds of the digest's record (the one write: of two claims at once, one decides). */
624
+ * its bar (judgeRows). Promoted when it serves (learn/field-check.ts: enough answered alone, every field passes); else
625
+ * held on its failing fields with the inputs it did not agree on, which the agent's next run's compile turn reads as
626
+ * data (its one recompile); a recompile's check that holds it too stops: nothing compiles again. No refit, queue or
627
+ * second replay. Kept only while `still` holds of the digest's record (the one write: of two claims at once, one
628
+ * decides). */
639
629
  export async function decideCheck(deps, name, digest, bar, read, still, extra) {
640
630
  const now = deps.now ?? Date.now;
641
631
  const { before } = read;
@@ -682,13 +672,12 @@ export async function decideCheck(deps, name, digest, bar, read, still, extra) {
682
672
  const check = { ...bar, ...score, agent_agreed: tally.agent_agreed, joint: joint.pass, ...(fieldCount ? { fields } : {}), ...numbers, ...(disagreements.length ? { disagreements } : {}), ...(stopped ? { stopped: true } : {}), ...(grader ? { grader } : {}) };
683
673
  const record = { workflow: name, digest, at: iso(now()), decided: ok ? "promote" : "hold", reason, check, ...seedOf(deps), ...extra };
684
674
  // A check that outlives its revision's run: the run's purge never stops it (it replays other runs' inputs), and the
685
- // purge gate refuses the revision at the commit it was checked at (purged-workflow.ts refusedOf). It is held, never
686
- // promoted, so no promotion of the purged run's text lands.
687
- const gone = ok && deps.refused !== undefined && (await deps.refused([record], [name]))(record);
688
- const kept = gone ? { ...record, decided: "hold", reason: `${said}: held, never promoted: a purged run wrote this revision, and its text is gone` } : record;
689
- const decided = await recordPromotion(deps.store.settings, deps.agentId, kept, still, deps.refused);
675
+ // purge deletes the revision's rows and records. No version of the workflow holds the digest then: nothing is written
676
+ // (recordPromotion), no hold and no promote of the purged run's text. Read in the record's own write, so no purge goes
677
+ // between.
678
+ const decided = await recordPromotion(deps.store.learning, deps.agentId, record, still);
690
679
  if (decided.won)
691
- deps.log(`workflow-first: ${name} at ${digest} ${kept.decided === "promote" ? "promoted" : "held"}: ${kept.reason}`);
680
+ deps.log(`workflow-first: ${name} at ${digest} ${decided.record?.decided === "promote" ? "promoted" : "held"}: ${decided.record?.reason}`);
692
681
  return decided;
693
682
  }
694
683
  /** Reserves a check of `workflow` at `digest` on `inputs`, then starts its runs: its replaying record names the replay
@@ -700,7 +689,7 @@ async function reserve(deps, workflow, digest, inputs, reason, still, check) {
700
689
  const now = deps.now ?? Date.now;
701
690
  const ids = inputs.map(() => uuidv7());
702
691
  const launch = replayLaunchOf(deps);
703
- const reserved = await recordPromotion(deps.store.settings, deps.agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "replaying", reason, runs: ids, inputs: inputs.map((one) => one.run), replay_id: uuidv7(), launch, ...seedOf(deps), check }, (was, items) => still(was) && replayingOf(items, workflow.name, digest).length === 0, deps.refused);
692
+ const reserved = await recordPromotion(deps.store.learning, deps.agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "replaying", reason, runs: ids, inputs: inputs.map((one) => one.run), replay_id: uuidv7(), launch, ...seedOf(deps), check }, (was, items) => still(was) && replayingOf(items, workflow.name, digest).length === 0);
704
693
  if (reserved.won)
705
694
  for (const [i, one] of inputs.entries())
706
695
  await startReplay(deps, workflow, digest, one.run, one.launch, ids[i], launch);
@@ -758,7 +747,7 @@ export async function reserveSdkCheck(deps, turn) {
758
747
  const now = deps.now ?? Date.now;
759
748
  for (const flow of turn.flows) {
760
749
  const digest = workflowDigest(flow);
761
- const before = await promotionsOf(deps.store.settings, deps.agentId);
750
+ const before = await promotionsOf(deps.store.learning, deps.agentId);
762
751
  for (const pending of replayingOf(before, flow.name, null)) {
763
752
  if (pending.via !== "sdk" || overtaken(before, pending))
764
753
  continue;
@@ -771,17 +760,17 @@ export async function reserveSdkCheck(deps, turn) {
771
760
  }
772
761
  if (!turn.takes(flow))
773
762
  continue;
774
- const records = await promotionsOf(deps.store.settings, deps.agentId);
763
+ const records = await promotionsOf(deps.store.learning, deps.agentId);
775
764
  const own = promotionOf(records, flow.name, digest);
776
765
  if ((own && !waitingSdk(own)) || blocking(records, flow.name, digest).length)
777
766
  continue;
778
767
  const id = uuidv7();
779
768
  const check = own?.check ?? { ...loopOf(turn.learning), attempt: attemptOf(records, flow.name, digest) };
780
- const reserved = await recordPromotion(deps.store.settings, deps.agentId, {
769
+ const reserved = await recordPromotion(deps.store.learning, deps.agentId, {
781
770
  workflow: flow.name, digest, at: iso(now()), decided: "replaying", via: "sdk",
782
771
  reason: `Checking it in the connected agent against an independent native turn before it can be reused: ${sdkTurnsWords(check)}.`,
783
772
  replay_id: id, runs: [turn.runId], inputs: [turn.runId], commit: revision, check,
784
- }, (was, current) => (own ? waitingSdk(was) && was.replay_id === own.replay_id : was === undefined) && blocking(current, flow.name, digest).length === 0, deps.refused);
773
+ }, (was, current) => (own ? waitingSdk(was) && was.replay_id === own.replay_id : was === undefined) && blocking(current, flow.name, digest).length === 0);
785
774
  if (reserved.won)
786
775
  return { id, revision, digest, workflow: flow };
787
776
  }
@@ -805,7 +794,7 @@ export async function sdkCheckTurn(deps, record, row, still, read = {}) {
805
794
  const turnStill = (was, current) => still(was, current) && heldTurn(was, record);
806
795
  if ((before?.n ?? 0) + 1 >= bar.compile_after)
807
796
  return decideCheck(deps, record.workflow, record.digest, bar, { rows: [row], cost: null, outcomes, unstarted: 0, ...read, ...(before ? { before } : {}) }, turnStill, sdkExtra(record));
808
- if (overtaken(await promotionsOf(deps.store.settings, deps.agentId), record)) {
797
+ if (overtaken(await promotionsOf(deps.store.learning, deps.agentId), record)) {
809
798
  deps.log(`workflow-first: ${record.workflow} at ${record.digest} checked a native turn; a newer revision has a record since, so it is left as it is`);
810
799
  return;
811
800
  }
@@ -825,7 +814,7 @@ export async function sdkCheckTurn(deps, record, row, still, read = {}) {
825
814
  * as waiting: a turn's row (sdkCheckTurn) and a give-back (releaseSdkCheck). */
826
815
  function waitAgain(deps, record, check, reason, still = () => true) {
827
816
  const { runs: _runs, inputs: _inputs, ...rest } = record;
828
- return recordPromotion(deps.store.settings, deps.agentId, { ...rest, at: iso((deps.now ?? Date.now)()), check, reason }, (was, current) => still(was, current) && sameReplay(was, record) && heldTurn(was, record) && !overtaken(current, was), deps.refused);
817
+ return recordPromotion(deps.store.learning, deps.agentId, { ...rest, at: iso((deps.now ?? Date.now)()), check, reason }, (was, current) => still(was, current) && sameReplay(was, record) && heldTurn(was, record) && !overtaken(current, was));
829
818
  }
830
819
  /** A connected agent's check whose native turn did not settle it by REPLAY_DEADLINE_MS (the backend never completed the
831
820
  * turn, or the server stopped before the run's end): one failed row of its turns (sdkCheckTurn), as a managed check's
@@ -834,7 +823,7 @@ function waitAgain(deps, record, check, reason, still = () => true) {
834
823
  export async function sdkCheckDeadline(deps, pending) {
835
824
  const runId = pending.runs?.[0];
836
825
  const { check } = pending;
837
- if (!runId || !check || overtaken(await promotionsOf(deps.store.settings, deps.agentId), pending))
826
+ if (!runId || !check || overtaken(await promotionsOf(deps.store.learning, deps.agentId), pending))
838
827
  return;
839
828
  const launch = await deps.store.runs.launch(runId).then((one) => readLaunchBody(one.body), () => undefined);
840
829
  return sdkCheckTurn(deps, { ...pending, check }, { of: runId, input: sdkInputText(launch), agent: null, outcome: "failed", answer: null }, (was, current) => sameReplay(was, pending) && !overtaken(current, was));
@@ -847,7 +836,7 @@ export async function sdkCheckDeadline(deps, pending) {
847
836
  export async function releaseSdkCheck(deps, record, cause, counted = true) {
848
837
  if (!record.check)
849
838
  return;
850
- if (overtaken(await promotionsOf(deps.store.settings, deps.agentId), record)) {
839
+ if (overtaken(await promotionsOf(deps.store.learning, deps.agentId), record)) {
851
840
  deps.log(`workflow-first: ${record.workflow} at ${record.digest} gave back its native turn (${cause}); a newer revision has a record since, so it is left as it is`);
852
841
  return;
853
842
  }
@@ -1074,14 +1063,7 @@ export class ReplayRefused extends Error {
1074
1063
  * first), else the folder's main. When neither holds it, whether the agent has a workflow by that name at all (`named`:
1075
1064
  * a record names it, or main holds it). */
1076
1065
  async function revisionOf(ask, records, name, digest) {
1077
- const folder = ask.folder();
1078
- let main;
1079
- try {
1080
- main = (await readSnapshot(folder.workspace))?.main;
1081
- }
1082
- finally {
1083
- await folder.end().catch(() => undefined);
1084
- }
1066
+ const main = (await readView(learningOf(ask.store, ask.agentId)))?.main;
1085
1067
  const named = records.filter((one) => one.workflow === name && one.digest === digest && one.commit).map((one) => one.commit).reverse();
1086
1068
  let onMain = false;
1087
1069
  for (const commit of new Set([...named, ...(main ? [main] : [])])) {
@@ -1094,8 +1076,7 @@ async function revisionOf(ask, records, name, digest) {
1094
1076
  return { named: onMain || records.some((one) => one.workflow === name) };
1095
1077
  }
1096
1078
  /** The agent runs `name` at `digest` was last checked on: its newest record that names them, a decided
1097
- * check's `check.of` or a reservation's `inputs`. A check's reservation leaves the kept history (trimPromotions) while
1098
- * its decision stays, so the decision's own list is read first. Undefined when no record names any. */
1079
+ * check's `check.of` or a reservation's `inputs`, the decision's own list read first. Undefined when no record names any. */
1099
1080
  function heldInputsOf(records, name, digest) {
1100
1081
  const checked = (one) => (one.decided !== "replaying" && one.check?.of?.length ? one.check.of : undefined);
1101
1082
  const last = records.findLast((one) => one.workflow === name && one.digest === digest && (checked(one) ?? one.inputs)?.length);
@@ -1109,10 +1090,10 @@ function heldInputsOf(records, name, digest) {
1109
1090
  * (it serves already); no input it fits (nothing is reserved); an agent that does not learn here. The replay's id and
1110
1091
  * its inputs. */
1111
1092
  export async function askReplay(ask, name, digest, inputs) {
1112
- const records = await promotionsOf(ask.store.settings, ask.agentId);
1093
+ const records = await promotionsOf(ask.store.learning, ask.agentId);
1113
1094
  const found = await revisionOf(ask, records, name, digest);
1114
1095
  if ("named" in found)
1115
- throw new ReplayRefused("missing", found.named ? `The learned workflow ${name} has no revision ${digest}: no promotion record names it, and the learning folder's main holds another.` : `The agent has no learned workflow ${name}.`);
1096
+ throw new ReplayRefused("missing", found.named ? `The learned workflow ${name} has no revision ${digest}: no promotion record names it, and the newest learning save holds another.` : `The agent has no learned workflow ${name}.`);
1116
1097
  const own = promotionOf(records, name, digest);
1117
1098
  if (own?.decided === "replaying")
1118
1099
  throw new ReplayRefused("conflict", `${name} at ${digest} is replaying already: read that replay, or wait for it to end.`);
@@ -1134,7 +1115,7 @@ export async function askReplay(ask, name, digest, inputs) {
1134
1115
  throw new ReplayRefused("conflict", PROJECT_REPLAY_REFUSED);
1135
1116
  if (!launch.learning || launch.learning.noWorkflows)
1136
1117
  throw new ReplayRefused("conflict", `A replay runs ${name} as a run of the agent that learns does, and the agent's runs do not take learned workflows here (its learning is off, it takes no workflows, or this server's is off).`);
1137
- const deps = { store: ask.store, agentId: ask.agentId, revisionId, launch: { ...launch, learning: { ...launch.learning, seed: found.commit } }, context: ask.context, log: ask.log, shown: ask.shown, refused: refusedIn(ask.folder, ask.store, ask.log), ...(ask.admitAuxiliary ? { admitAuxiliary: ask.admitAuxiliary } : {}), ...(ask.now ? { now: ask.now } : {}) };
1118
+ const deps = { store: ask.store, agentId: ask.agentId, revisionId, launch: { ...launch, learning: { ...launch.learning, seed: found.commit } }, context: ask.context, log: ask.log, shown: ask.shown, ...(ask.admitAuxiliary ? { admitAuxiliary: ask.admitAuxiliary } : {}), ...(ask.now ? { now: ask.now } : {}) };
1138
1119
  const bar = { ...loop, attempt: attemptOf(records, name, digest) };
1139
1120
  const said = `checking it on ${plural(picked.length, "input")} of the agent's own runs, as its owner asked`;
1140
1121
  // Kept only while the revision's newest record is still the one read here: each record write stamps a new `at`.
@@ -1178,7 +1159,7 @@ function readPorts(ask, launch) {
1178
1159
  * older, held one) is decided too, and never running forever. Once decided, it reads only its record. Refused
1179
1160
  * (missing) when the agent has no such replay. */
1180
1161
  export async function replayView(ask, name, digest, id) {
1181
- const find = async () => (await promotionsOf(ask.store.settings, ask.agentId)).findLast((one) => one.workflow === name && one.digest === digest && one.replay_id === id);
1162
+ const find = async () => (await promotionsOf(ask.store.learning, ask.agentId)).findLast((one) => one.workflow === name && one.digest === digest && one.replay_id === id);
1182
1163
  let record = await find();
1183
1164
  if (!record)
1184
1165
  throw new ReplayRefused("missing", `${name} at ${digest} has no replay ${id}.`);
@@ -35,6 +35,9 @@ export interface HeldRedact extends Redact {
35
35
  * values stay held (`hold`). */
36
36
  dropCarried(runId: string): void;
37
37
  }
38
+ /** `redact` when it is a held redactor (heldRedactor), else a throw naming `where` (a loop or a run's spec): one given
39
+ * none fails before it opens a key, and never runs with the keys it opens unheld. For a caller the types don't reach. */
40
+ export declare function mustHold(redact: HeldRedact | undefined, where: string): HeldRedact;
38
41
  /** `base`, then every value held since (`hold`). One that holds already is itself: wrapped once, the one instance. */
39
42
  export declare function heldRedactor(base: Redact): HeldRedact;
40
43
  /** Every string inside `value` cut by `cut`: what the run's process writes, as the runner's redactor would cut it in a
@@ -36,6 +36,13 @@ export function secretRedactor(values) {
36
36
  * redactor reads the environment; runner.ts reads no environment or argv itself. */
37
37
  export const processSecretRedactor = () => secretRedactor(runnerSecrets(process.env));
38
38
  const isHeld = (redact) => typeof redact.hold === "function";
39
+ /** `redact` when it is a held redactor (heldRedactor), else a throw naming `where` (a loop or a run's spec): one given
40
+ * none fails before it opens a key, and never runs with the keys it opens unheld. For a caller the types don't reach. */
41
+ export function mustHold(redact, where) {
42
+ if (typeof redact !== "function" || !isHeld(redact))
43
+ throw new TypeError(`${where} was given no redactor that holds keys (heldRedactor), so it does not run: a key it opened would reach the run's record uncut`);
44
+ return redact;
45
+ }
39
46
  /** `base`, then every value held since (`hold`). One that holds already is itself: wrapped once, the one instance. */
40
47
  export function heldRedactor(base) {
41
48
  if (isHeld(base))
@@ -22,7 +22,7 @@ export type Committed = {
22
22
  readonly refusedCorrection?: readonly Problem[];
23
23
  } | {
24
24
  readonly ok: false;
25
- readonly reason: "conflict" | "refused" | "unavailable";
25
+ readonly reason: "conflict" | "refused" | "purged" | "unavailable";
26
26
  readonly problems: readonly Problem[];
27
27
  };
28
28
  /** What the step reads of the run and the host. */
@@ -91,7 +91,7 @@ export interface ReflectDeps {
91
91
  readonly base: string;
92
92
  };
93
93
  }) => Promise<DraftChecked<DraftCommit>>;
94
- /** The round's merge on the agent's learning folder (learning-end.ts commitDirect): its draft and its owner's
94
+ /** The round's merge on the agent's learning (learning-end.ts commitDirect): its draft and its owner's
95
95
  * correction, one commit by the run. */
96
96
  readonly commit: (input: {
97
97
  runId: string;
@@ -1,5 +1,5 @@
1
1
  // The learning lane's end-of-run step on the runner (loop-contract.ts EndOfRunTurn): what a run that learns keeps
2
- // beside its end, with no look-back turn and no grade. Two things, one merge a round on its agent's learning folder:
2
+ // beside its end, with no look-back turn and no grade. Two things, one merge a round on its agent's learning:
3
3
  // - its owner's feedback (a grade's words, a message after its first), appended to corrections.md as one line, with
4
4
  // no model turn;
5
5
  // - its compile turn (learn/compile.ts), when one is due: the job written as a workflow, or a revision of a held one,
@@ -149,6 +149,9 @@ export function createReflectHook(deps) {
149
149
  }
150
150
  if (done.reason === "unavailable")
151
151
  return close(dropped("reflect_failed", said.stopped(STOPPED.failed), compiledFields));
152
+ // A run's purge came after this run's seed: nothing of its merge was written (learn/commit.ts `purged`).
153
+ if (done.reason === "purged")
154
+ return close(dropped("purged_since_seed", said.purgedSinceSeed, compiledFields));
152
155
  return close(dropped("checker", correctionWords(done.problems), { problems: [...done.problems], ...compiledFields }));
153
156
  }
154
157
  if (refusedCorrection.length)