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

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 (194) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +188 -106
  3. package/dist/agent-delete.d.ts +6 -9
  4. package/dist/agent-delete.js +5 -3
  5. package/dist/agent-package.js +11 -1
  6. package/dist/api-only.d.ts +2 -2
  7. package/dist/api-only.js +3 -3
  8. package/dist/archil-routes.d.ts +4 -1
  9. package/dist/archil-routes.js +15 -12
  10. package/dist/archil-settings.d.ts +18 -8
  11. package/dist/archil-settings.js +35 -17
  12. package/dist/chatgpt-plan.d.ts +4 -2
  13. package/dist/chatgpt-plan.js +13 -3
  14. package/dist/claude-login-token.d.ts +5 -0
  15. package/dist/claude-login-token.js +8 -0
  16. package/dist/claude-login.d.ts +49 -3
  17. package/dist/claude-login.js +140 -10
  18. package/dist/cli-learning/connections.js +1 -1
  19. package/dist/console/assets/{backend-BztxEAvb.js → backend-QnwGVBeU.js} +1 -1
  20. package/dist/console/assets/index-DZi-muIj.js +629 -0
  21. package/dist/console/assets/{share-L84tlUDW.js → share-pz61zIn9.js} +2 -2
  22. package/dist/console/assets/{styles-CaRKlHke.js → styles-CcceGcu2.js} +31 -31
  23. package/dist/console/assets/styles-fjQBFfMv.css +1 -0
  24. package/dist/console/index.html +3 -3
  25. package/dist/console/share.html +3 -3
  26. package/dist/decisions.d.ts +1 -1
  27. package/dist/decisions.js +2 -2
  28. package/dist/factory-activity.d.ts +68 -0
  29. package/dist/factory-activity.js +153 -0
  30. package/dist/factory-runs.d.ts +11 -0
  31. package/dist/factory-runs.js +52 -0
  32. package/dist/filed-tool.d.ts +32 -0
  33. package/dist/filed-tool.js +122 -0
  34. package/dist/harness-keys.d.ts +1 -2
  35. package/dist/harness-keys.js +1 -2
  36. package/dist/harness-table.d.ts +4 -0
  37. package/dist/harness-table.js +4 -0
  38. package/dist/harness.js +6 -2
  39. package/dist/import-worker.js +2 -2
  40. package/dist/import.d.ts +9 -0
  41. package/dist/import.js +11 -1
  42. package/dist/key-refusal.d.ts +5 -0
  43. package/dist/key-refusal.js +25 -15
  44. package/dist/learn/audit.d.ts +20 -22
  45. package/dist/learn/audit.js +72 -55
  46. package/dist/learn/check.js +1 -1
  47. package/dist/learn/commit.d.ts +35 -43
  48. package/dist/learn/commit.js +62 -270
  49. package/dist/learn/compile.d.ts +4 -4
  50. package/dist/learn/compile.js +6 -7
  51. package/dist/learn/corrections.js +1 -1
  52. package/dist/learn/delete.d.ts +5 -12
  53. package/dist/learn/delete.js +17 -30
  54. package/dist/learn/forget-run.d.ts +16 -0
  55. package/dist/learn/forget-run.js +53 -0
  56. package/dist/learn/index.js +1 -1
  57. package/dist/learn/learning-of.d.ts +0 -4
  58. package/dist/learn/learning-of.js +0 -5
  59. package/dist/learn/{folder.d.ts → legacy/folder.d.ts} +2 -1
  60. package/dist/learn/{folder.js → legacy/folder.js} +4 -7
  61. package/dist/learn/legacy/place.d.ts +16 -0
  62. package/dist/{workspace/learning-workspace.js → learn/legacy/place.js} +12 -42
  63. package/dist/learn/legacy/scrub.d.ts +28 -0
  64. package/dist/learn/legacy/scrub.js +258 -0
  65. package/dist/learn/promote.d.ts +40 -66
  66. package/dist/learn/promote.js +69 -207
  67. package/dist/learn/reset-ledger.d.ts +18 -0
  68. package/dist/learn/reset-ledger.js +14 -0
  69. package/dist/learn/rows.d.ts +186 -0
  70. package/dist/learn/rows.js +376 -0
  71. package/dist/learn/workflow-draft.d.ts +4 -1
  72. package/dist/learn/workflow-draft.js +12 -2
  73. package/dist/learning-reset.d.ts +1 -1
  74. package/dist/learning-reset.js +9 -11
  75. package/dist/learning-routes.d.ts +60 -81
  76. package/dist/learning-routes.js +187 -360
  77. package/dist/learning-words.d.ts +2 -0
  78. package/dist/learning-words.js +2 -0
  79. package/dist/learning.d.ts +18 -24
  80. package/dist/learning.js +35 -66
  81. package/dist/mcp-gateway.d.ts +6 -0
  82. package/dist/mcp-gateway.js +44 -8
  83. package/dist/mcp-resources.d.ts +1 -1
  84. package/dist/native/discovery.d.ts +6 -0
  85. package/dist/native/discovery.js +14 -1
  86. package/dist/native/remote.d.ts +5 -0
  87. package/dist/native/remote.js +16 -0
  88. package/dist/native/runtime.js +3 -2
  89. package/dist/observation/observer.d.ts +6 -6
  90. package/dist/openapi.js +89 -29
  91. package/dist/place-offers.d.ts +3 -0
  92. package/dist/place-offers.js +3 -0
  93. package/dist/place.d.ts +33 -11
  94. package/dist/place.js +61 -26
  95. package/dist/purged-workflow.d.ts +0 -33
  96. package/dist/purged-workflow.js +3 -71
  97. package/dist/redact/match.d.ts +19 -4
  98. package/dist/redact/match.js +123 -30
  99. package/dist/run-launch.d.ts +3 -3
  100. package/dist/run-learning-served.d.ts +3 -3
  101. package/dist/run-learning-served.js +1 -1
  102. package/dist/run-listing.d.ts +1 -1
  103. package/dist/run-timeline-served.d.ts +1 -1
  104. package/dist/run-timeline-served.js +6 -5
  105. package/dist/runnable.js +25 -8
  106. package/dist/runner/adapter-run-spec.js +11 -20
  107. package/dist/runner/audit.d.ts +2 -4
  108. package/dist/runner/audit.js +28 -51
  109. package/dist/runner/cli-run-spec.js +8 -14
  110. package/dist/runner/compare-end.d.ts +0 -2
  111. package/dist/runner/compare-end.js +6 -2
  112. package/dist/runner/disk-free.d.ts +15 -4
  113. package/dist/runner/disk-free.js +25 -7
  114. package/dist/runner/feedback-round.d.ts +1 -1
  115. package/dist/runner/feedback-round.js +2 -2
  116. package/dist/runner/harness-loops.js +2 -3
  117. package/dist/runner/held.d.ts +0 -10
  118. package/dist/runner/held.js +0 -25
  119. package/dist/runner/journal-kinds.d.ts +4 -1
  120. package/dist/runner/journal-kinds.js +1 -1
  121. package/dist/runner/learned-first.d.ts +0 -2
  122. package/dist/runner/learned-first.js +3 -3
  123. package/dist/runner/learning-end.d.ts +12 -16
  124. package/dist/runner/learning-end.js +41 -75
  125. package/dist/runner/learning-seed.d.ts +13 -16
  126. package/dist/runner/learning-seed.js +13 -23
  127. package/dist/runner/main.js +1 -1
  128. package/dist/runner/mcp-run.d.ts +4 -0
  129. package/dist/runner/mcp-run.js +2 -0
  130. package/dist/runner/native-loop.js +2 -3
  131. package/dist/runner/promotion.d.ts +19 -28
  132. package/dist/runner/promotion.js +50 -69
  133. package/dist/runner/reflect-hook.d.ts +2 -2
  134. package/dist/runner/reflect-hook.js +4 -1
  135. package/dist/runner/run-child-host.d.ts +1 -9
  136. package/dist/runner/run-child-host.js +11 -67
  137. package/dist/runner/runner.d.ts +1 -1
  138. package/dist/runner/sdk-loop.js +2 -4
  139. package/dist/sdk/check.d.ts +1 -4
  140. package/dist/sdk/check.js +2 -3
  141. package/dist/sdk/runs.d.ts +20 -7
  142. package/dist/sdk/runs.js +105 -68
  143. package/dist/secrets.d.ts +4 -0
  144. package/dist/secrets.js +44 -10
  145. package/dist/server-fs.d.ts +1 -1
  146. package/dist/server-fs.js +1 -1
  147. package/dist/server-keys.d.ts +6 -0
  148. package/dist/server-keys.js +12 -0
  149. package/dist/server.d.ts +15 -15
  150. package/dist/server.js +214 -164
  151. package/dist/source-sync/auxiliary.js +2 -2
  152. package/dist/store/index.d.ts +1 -1
  153. package/dist/store/index.js +1 -1
  154. package/dist/store/postgres/migrations/0032_learning_rows.sql +65 -0
  155. package/dist/store/schema.d.ts +28 -2
  156. package/dist/store/schema.js +81 -5
  157. package/dist/store/sqlite/learning-rows.d.ts +23 -0
  158. package/dist/store/sqlite/learning-rows.js +559 -0
  159. package/dist/store/sqlite/store.d.ts +7 -1
  160. package/dist/store/sqlite/store.js +84 -18
  161. package/dist/store/store.d.ts +219 -6
  162. package/dist/store/store.js +13 -0
  163. package/dist/store-reads/journal.d.ts +33 -3
  164. package/dist/store-reads/journal.js +99 -4
  165. package/dist/store-reads/learning.d.ts +18 -22
  166. package/dist/store-reads/learning.js +35 -26
  167. package/dist/store-reads/loop.js +1 -1
  168. package/dist/store-view.d.ts +24 -2
  169. package/dist/store-view.js +40 -11
  170. package/dist/templates.d.ts +10 -2
  171. package/dist/templates.js +31 -4
  172. package/dist/tool-plane.d.ts +4 -2
  173. package/dist/tool-plane.js +9 -2
  174. package/dist/web-holds.d.ts +2 -0
  175. package/dist/web-holds.js +5 -2
  176. package/dist/web-run.js +2 -1
  177. package/dist/workspace/archil-exec.js +1 -1
  178. package/dist/workspace/archil.d.ts +1 -1
  179. package/dist/workspace/archil.js +1 -1
  180. package/dist/workspace/computer-deps.js +5 -3
  181. package/dist/workspace/computer-providers.d.ts +11 -1
  182. package/dist/workspace/computer-providers.js +29 -2
  183. package/dist/workspace/index.d.ts +1 -2
  184. package/dist/workspace/index.js +1 -2
  185. package/dist/workspace/paths.d.ts +0 -4
  186. package/dist/workspace/paths.js +0 -6
  187. package/dist/workspace/workspace.d.ts +1 -1
  188. package/dist/workspace/workspace.js +1 -1
  189. package/package.json +13 -13
  190. package/templates/TOOLS.md +46 -0
  191. package/dist/console/assets/index-LwNL4L9q.js +0 -619
  192. package/dist/console/assets/styles-DQo8rzY-.css +0 -1
  193. package/dist/workspace/learning-workspace.d.ts +0 -24
  194. /package/dist/learn/{learning.sh → legacy/learning.sh} +0 -0
@@ -1,7 +1,6 @@
1
1
  import type { Duplex } from "node:stream";
2
2
  import { type GenAiTracing } from "../otel/tracer.js";
3
3
  import { type HeldRedact, type Redact } from "./redact.js";
4
- import type { Workspace } from "../workspace/workspace.js";
5
4
  import { type AdapterSpecDeps } from "./adapter-run-spec.js";
6
5
  import type { ClaudeAgentLogin } from "@parcha/agentrun-harness-claude";
7
6
  import type { Held } from "./held.js";
@@ -141,13 +140,6 @@ export declare function heldFor(deps: AdapterSpecDeps & {
141
140
  release(): Promise<void>;
142
141
  projectEnd?(): Promise<void>;
143
142
  };
144
- /** A call of the learning folder a run's process asks (Held.learning), on the runner's own Workspace of the claim's
145
- * agent's folder: reads pass, and the learning script runs its reads, with the script's own environment (the script
146
- * laid by the runner as the folder's own); nothing the process asks writes there. */
147
- export declare function learningCall(folder: {
148
- readonly workspace: Workspace;
149
- end(): Promise<void>;
150
- }, method: string, args: readonly unknown[]): Promise<unknown>;
151
143
  /** What the runner's child loops share: its deps (its seal key), its isolation, its slots, its log. */
152
144
  export interface ChildLoopsOptions {
153
145
  readonly deps: AdapterSpecDeps & {
@@ -165,7 +157,7 @@ export interface ChildLoopsOptions {
165
157
  export declare const childArgv: () => string[];
166
158
  /** Whether a run stays in its runner's process rather than one of its own: one that runs no agent's code or tool here.
167
159
  * A built-in learning run (its launch names harness "learning"): its grade is one ask through the runner's model route,
168
- * and its one write is the merge into the agent's learning folder, which no run's process may write. An SDK backend
160
+ * and its one write is the merge into the agent's learning, which no run's process may write. An SDK backend
169
161
  * run (launch.sdk): its agent runs in the caller's application, and its loop here reads the evidence it posts and closes
170
162
  * its inbox. A CLI capture (launch.cli_learning) likewise only receives source evidence and serves owner corrections.
171
163
  * A native run (launch.native): its agent is the source machine's own sign-in, reached through the server's
@@ -43,7 +43,6 @@ import { withinCarried } from "../paid-calls.js";
43
43
  import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
44
44
  import { runZone } from "../environment.js";
45
45
  import { shadowRunId } from "../learn/audit.js";
46
- import { LEARNING_SCRIPT, learningWorkspace } from "../learn/folder.js";
47
46
  import { agreeOnOf } from "../learning-setting.js";
48
47
  import { openedAtUse, openRunWorkspace } from "../workspace/run-workspace.js";
49
48
  import { archilClaim, MOUNT_TTL_MS } from "../workspace/archil-claim.js";
@@ -56,7 +55,7 @@ import { githubAppAccess } from "./github-app.js";
56
55
  import { githubPullOf, githubTargetOf } from "../github.js";
57
56
  import { isObject } from "../validate.js";
58
57
  import { liveForRun, runnerLiveOf } from "../live-reach.js";
59
- import { learningFolderOf, secretsShown } from "../learning.js";
58
+ import { secretsShown } from "../learning.js";
60
59
  import { learningStartOf, seedFailed } from "../run-launch.js";
61
60
  import { messageText } from "../run-manifest.js";
62
61
  import { filesToCopy, placeRunInputs } from "../uploads.js";
@@ -409,15 +408,14 @@ const ownWrittenSettings = (bound) => new Map([
409
408
  * over, and the server parses the row on every read of the run and every Screen poll. */
410
409
  const OWN_ROW_MAX_BYTES = 4096;
411
410
  /** The settings of the claim's own run and agent a run's process may read: its run's Archil disk, SDK record, kept
412
- * computer, browser wait and browser take, and its agent's Archil disk and promotions. Every other row (another run's
413
- * or agent's) is not its to read. */
411
+ * computer, browser wait and browser take, and its agent's Archil disk. Every other row (another run's or agent's)
412
+ * is not its to read. */
414
413
  const ownSettings = (bound) => new Set([
415
414
  `archil.run.${bound.claim.runId}`,
416
415
  `sdk-run:${bound.claim.runId}`,
417
416
  keptKeyOf(bound.claim.runId),
418
417
  ...ownWrittenSettings(bound).keys(),
419
418
  `archil.agent.${bound.agentId}`,
420
- `learning.promotions.${bound.agentId}`,
421
419
  ]);
422
420
  /** Whether a run's process may read setting `key`. */
423
421
  export const settingReadable = (key, bound) => typeof key === "string" && (SHARED_SETTINGS.has(key) || ownSettings(bound).has(key));
@@ -484,6 +482,8 @@ const STORE_CALLS = new Map([
484
482
  ["learning.proposals", ownAgent],
485
483
  ["learning.list", ownAgent],
486
484
  ["learning.get", always],
485
+ // Its agent's learning at a save (learning-seed.ts layLearningSeed): read only, its agent's alone.
486
+ ["learning.itemsAt", ownAgent],
487
487
  ["computerLedger.book", ownClaim],
488
488
  ["computerLedger.list", ownRun],
489
489
  ["live.put", ownClaim],
@@ -686,15 +686,6 @@ export function heldFor(deps, reads, cut, log, bigs = runBigWrites()) {
686
686
  * A faux run still runs its learned steps on the faux model: only modelRefused refuses them. */
687
687
  const keyless = sendsNoModelKey(launch, deps.env ?? {});
688
688
  const refusedSpend = () => new ClaimRefused("a held run its model kept from running asks its runner for no model spend: it routes no model and takes no learning step");
689
- const learningFolder = async () => {
690
- const made = await archilOf();
691
- return made === undefined ? learningFolderOf(deps.data, run.agentId) : learningWorkspace({ mode: "archil", agentId: run.agentId, archil: made });
692
- };
693
- /** The learning folder's reader, made once the claim's Archil claim is known (learnedFirst's folder is synchronous). */
694
- const folderNow = async () => {
695
- const made = await archilOf();
696
- return () => (made === undefined ? learningFolderOf(deps.data, run.agentId) : learningWorkspace({ mode: "archil", agentId: run.agentId, archil: made }));
697
- };
698
689
  /** What a learned workflow must never hold, as this runner sees it: every secret it holds (learning-seed.ts). */
699
690
  const shown = async () => secretsShown(runnerSecrets(deps.env, await storeSecrets(store, sealKey, deps.data)), { local: true });
700
691
  /** The workflows the claim's learned_workflow tool runs, as this runner chose them (held.learnedFirst): what scopes the
@@ -834,7 +825,7 @@ export function heldFor(deps, reads, cut, log, bigs = runBigWrites()) {
834
825
  const overTheDisk = disk === undefined ? undefined : openedAtUse(() => openRunWorkspace({ mode: 2, agentId: run.agentId, runId: claim.runId, archil: disk, sweep: false, log }));
835
826
  if (overTheDisk)
836
827
  releases.push(() => overTheDisk.end());
837
- const made = await mcpForClaim({ claim, store, sealKey, grants: granted, harness: harness, work: () => (overTheDisk === undefined ? runFolder(deps.data, run.agentId, claim.runId) : mountedFolder ?? overTheDisk.workspace()), launchInput: launch.input, githubAppAccess: () => github(), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...(deps.composioMcpOrigin ? { composioMcpOrigin: deps.composioMcpOrigin } : {}), ...reach, ...claimMetering(deps, undefined, launch) });
828
+ const made = await mcpForClaim({ claim, store, sealKey, grants: granted, harness: harness, toolSettings: revision.body.toolSettings, work: () => (overTheDisk === undefined ? runFolder(deps.data, run.agentId, claim.runId) : mountedFolder ?? overTheDisk.workspace()), launchInput: launch.input, githubAppAccess: () => github(), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...(deps.composioMcpOrigin ? { composioMcpOrigin: deps.composioMcpOrigin } : {}), ...reach, ...claimMetering(deps, undefined, launch) });
838
829
  if (!made)
839
830
  return undefined;
840
831
  releases.push(() => made.release());
@@ -934,7 +925,6 @@ export function heldFor(deps, reads, cut, log, bigs = runBigWrites()) {
934
925
  signInForgotten: (resolution) => forgottenSignIns(store, sealKey, run.agentId, String(resolution)),
935
926
  emailAccount: async () => (grantsEmail(granted) ? openAccount(store, sealKey) : undefined),
936
927
  calendar: async () => (granted.includes(CALENDAR_EVENTS) ? openCalendar(store, sealKey) : undefined),
937
- learning: async (method, args) => learningCall(await learningFolder(), method, args),
938
928
  install: async (name, signal) => {
939
929
  const harness = launch.harness ?? revision.body.harness;
940
930
  const entry = harness === undefined ? undefined : harnessOf(deps.env, harness);
@@ -1015,14 +1005,13 @@ export function heldFor(deps, reads, cut, log, bigs = runBigWrites()) {
1015
1005
  // compares its answer with the other one through its grader, handed in by the run's process (runner/compare-end.ts).
1016
1006
  // This runner reads both answers and the learning ledger, which no run's process may.
1017
1007
  if (launch.replay || launch.audit) {
1018
- const compare = compareEndOfRun(launch, { store, folder: await folderNow(), log, redact: cut });
1008
+ const compare = compareEndOfRun(launch, { store, log, redact: cut });
1019
1009
  const grade = input.grade;
1020
1010
  const rows = compare && grade && typeof input.grader === "string"
1021
1011
  ? await compare({ runId: claim.runId, agentId: run.agentId, claim, outcome: input.outcome === "failed" ? "failed" : "completed", ...(input.cut === undefined ? {} : { cut: "faulted" }), grader: input.grader, grade: (request) => grade(request), ask: input.ask, signal: input.signal })
1022
1012
  : undefined;
1023
1013
  return rows?.compared ? { also: [], compared: dataOnly(rows.compared) } : undefined;
1024
1014
  }
1025
- const made = await archilOf();
1026
1015
  // The audit's spend, skipped as the run's spec skips it (claim-secrets.ts claimSpendOff): over the claim's own key.
1027
1016
  const spendOff = await claimSpendOff(keys, await claimModelKey(keys, claim.runId));
1028
1017
  // The audit's start after the step (audit.ts withAudit) is this runner's too: it reads the run's journal and writes
@@ -1036,8 +1025,7 @@ export function heldFor(deps, reads, cut, log, bigs = runBigWrites()) {
1036
1025
  stored: () => storeSecrets(store, sealKey, deps.data),
1037
1026
  log,
1038
1027
  decisionProviders: async () => decisionProvidersIn({ ...(deps.env ?? {}), ...(await hostDecisionKeys(keys, DECISION_PROVIDER_KEYS)) }),
1039
- learningFolder: made === undefined ? (agentId) => learningFolderOf(deps.data, agentId) : (agentId) => learningWorkspace({ mode: "archil", agentId, archil: made }),
1040
- }), { store, agentId: run.agentId, revisionId: run.revisionId, context: BACKGROUND_CONTEXT, folder: await folderNow(), shown, log, sealKey, spendOff, launch, redact: cut, admitAuxiliary });
1028
+ }), { store, agentId: run.agentId, revisionId: run.revisionId, context: BACKGROUND_CONTEXT, shown, log, sealKey, spendOff, launch, redact: cut, admitAuxiliary });
1041
1029
  if (!step)
1042
1030
  return undefined;
1043
1031
  // keptOf is the run's process's, asked over the channel: read once, for the round learningEndOfRun reads (the
@@ -1065,11 +1053,10 @@ export function heldFor(deps, reads, cut, log, bigs = runBigWrites()) {
1065
1053
  // the process's lay chose them: none where its lay laid none (`laid` false: a read that failed, a seed with no
1066
1054
  // workflows).
1067
1055
  const start = learningStartOf(launch);
1068
- const folder = await folderNow();
1069
- const laid = ask?.laid === true && start && !seedFailed(start) && !start.noWorkflows ? await workflowsAt({ folder, store, shown }, start.seed).catch(() => []) : [];
1056
+ const laid = ask?.laid === true && start && !seedFailed(start) && !start.noWorkflows ? await workflowsAt({ store, agentId: run.agentId, shown }, start.seed).catch(() => []) : [];
1070
1057
  const spendOff = await claimSpendOff(keys, await claimModelKey(keys, claim.runId));
1071
1058
  const outputSchema = revision.body.outputSchema;
1072
- const got = await learnedFirst({ store, sealKey, agentId: run.agentId, runId: claim.runId, revisionId: run.revisionId, kind: revision.kind, ...(outputSchema !== undefined ? { outputSchema } : {}), launch, context: BACKGROUND_CONTEXT, log, folder, shown, spendOff, admitAuxiliary }, laid);
1059
+ const got = await learnedFirst({ store, sealKey, agentId: run.agentId, runId: claim.runId, revisionId: run.revisionId, kind: revision.kind, ...(outputSchema !== undefined ? { outputSchema } : {}), launch, context: BACKGROUND_CONTEXT, log, shown, spendOff, admitAuxiliary }, laid);
1073
1060
  learnedFlows = got.workflows;
1074
1061
  return cutDeep(dataOnly(got), cut);
1075
1062
  })()),
@@ -1118,54 +1105,11 @@ export function heldFor(deps, reads, cut, log, bigs = runBigWrites()) {
1118
1105
  }
1119
1106
  /** `env`'s string values. */
1120
1107
  const stringsOf = (env) => Object.fromEntries(Object.getOwnPropertyNames(env).flatMap((name) => (typeof env[name] === "string" ? [[name, env[name]]] : [])));
1121
- /** The learning-script ops a run's process may run (learn/folder.ts): its reads alone. The folder's writers (the
1122
- * end-of-run step's check, the learning run's merge, a repair) are the runner's. */
1123
- const LEARNING_OPS = new Set(["read", "show", "has", "log", "diff", "status"]);
1124
- /** A call of the learning folder a run's process asks (Held.learning), on the runner's own Workspace of the claim's
1125
- * agent's folder: reads pass, and the learning script runs its reads, with the script's own environment (the script
1126
- * laid by the runner as the folder's own); nothing the process asks writes there. */
1127
- export async function learningCall(folder, method, args) {
1128
- const ws = folder.workspace;
1129
- try {
1130
- switch (method) {
1131
- case "read":
1132
- return await ws.read(String(args[0]), args[1]);
1133
- case "stat":
1134
- return dataOnly(await ws.stat(String(args[0])));
1135
- case "list":
1136
- return dataOnly(await ws.list(String(args[0])));
1137
- case "grep":
1138
- return dataOnly(await ws.grep(String(args[0]), args[1]));
1139
- case "write":
1140
- // The learning script laid as learn/folder.ts lays it (ensureScript, before a script run): the runner's own text.
1141
- if (args[0] === LEARNING_SCRIPT.file())
1142
- return await LEARNING_SCRIPT.ensure(ws);
1143
- throw new ClaimRefused(`a run's process may not write ${JSON.stringify(args[0])} in its learning folder`);
1144
- case "append":
1145
- case "remove":
1146
- case "mkdir":
1147
- throw new ClaimRefused(`a run's process may not ${method} ${JSON.stringify(args[0])} in its learning folder`);
1148
- case "exec": {
1149
- const argv = args[0];
1150
- const options = (args[1] ?? {});
1151
- if (!Array.isArray(argv) || argv[0] !== "sh" || argv[1] !== LEARNING_SCRIPT.file() || !LEARNING_OPS.has(String(argv[2])) || !argv.every((part) => typeof part === "string"))
1152
- throw new ClaimRefused("a run's process runs no program in its learning folder but its learning script");
1153
- await LEARNING_SCRIPT.ensure(ws);
1154
- return dataOnly(await ws.exec(argv, { env: LEARNING_SCRIPT.env(), timeoutMs: LEARNING_SCRIPT.timeoutMs(), ...(options.stdin instanceof Uint8Array ? { stdin: options.stdin } : {}) }));
1155
- }
1156
- default:
1157
- throw new ClaimRefused(`a run's learning folder has no ${method} in its process`);
1158
- }
1159
- }
1160
- finally {
1161
- await folder.end().catch(() => undefined);
1162
- }
1163
- }
1164
1108
  /** The node and module a run's process starts with. */
1165
1109
  export const childArgv = () => [process.execPath, "--import", new URL("../secrets.js", import.meta.url).pathname, new URL("./run-child.js", import.meta.url).pathname];
1166
1110
  /** Whether a run stays in its runner's process rather than one of its own: one that runs no agent's code or tool here.
1167
1111
  * A built-in learning run (its launch names harness "learning"): its grade is one ask through the runner's model route,
1168
- * and its one write is the merge into the agent's learning folder, which no run's process may write. An SDK backend
1112
+ * and its one write is the merge into the agent's learning, which no run's process may write. An SDK backend
1169
1113
  * run (launch.sdk): its agent runs in the caller's application, and its loop here reads the evidence it posts and closes
1170
1114
  * its inbox. A CLI capture (launch.cli_learning) likewise only receives source evidence and serves owner corrections.
1171
1115
  * A native run (launch.native): its agent is the source machine's own sign-in, reached through the server's
@@ -120,7 +120,7 @@ export interface RunnerOptions {
120
120
  onBeat?: () => void;
121
121
  /** Whether this runner may claim now: undefined while it may, else why not, in words a person can act on (runner/main.ts
122
122
  * diskFreeGate: a runner whose data directory is not the server's, while the server keeps runs' folders on its own
123
- * disk). Asked before each poll's claims (`fresh` false: an answer a few seconds old will do) and again, fresh, once a
123
+ * disk; a runner given an Archil region whose S3 URL may not be the server's). Asked before each poll's claims (`fresh` false: an answer a few seconds old will do) and again, fresh, once a
124
124
  * poll claimed any, before a loop starts on them: a run claimed as the answer changed is released at once, untouched,
125
125
  * for a runner that can serve it. While it refuses, the runner claims nothing and says why on its presence row, where
126
126
  * the server reads it (presence.ts runnersRefused); a throw is said as an error and that poll claims nothing. Absent:
@@ -5,8 +5,7 @@ import { setTimeout as delay } from "node:timers/promises";
5
5
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
6
6
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
7
7
  import { freeRequestLimitOf } from "@parcha/agentrun-kernel/kernel/cap";
8
- import { learningFolderOf, secretsShown } from "../learning.js";
9
- import { refusedIn } from "../purged-workflow.js";
8
+ import { secretsShown } from "../learning.js";
10
9
  import { said, STOPPED } from "../learning-words.js";
11
10
  import { cliPolicyOf, closeSdkInbox, sdkInbox } from "../sdk/runs.js";
12
11
  import { settleSdkCheck } from "../sdk/check.js";
@@ -103,7 +102,6 @@ export function createSdkLoop(launch, host, route) {
103
102
  store: host.store, agentId: agent, launch, inbox,
104
103
  shown: async () => secretsShown(Object.values(await storeSecrets(host.store, host.sealKey, host.data)), { local: true }),
105
104
  log: (line) => host.log?.(line),
106
- refused: refusedIn(() => learningFolderOf(host.data, agent), host.store, (line) => host.log?.(line)),
107
105
  });
108
106
  }
109
107
  catch (error) {
@@ -194,6 +192,7 @@ export function createSdkLoop(launch, host, route) {
194
192
  kind: KINDS.callStart,
195
193
  data: { callId: event.id, tool: event.name, input: event.input ?? {}, replaySafe: false,
196
194
  ...(event.parent_tool_use_id ? { parentCallId: event.parent_tool_use_id } : {}),
195
+ ...(event.name === "learned_workflow" && inbox.workflow_calls && Object.hasOwn(inbox.workflow_calls, event.id) ? { workflow: inbox.workflow_calls[event.id] } : {}),
197
196
  },
198
197
  });
199
198
  }
@@ -285,7 +284,6 @@ export function createSdkLoop(launch, host, route) {
285
284
  const end = learningEndOfRun(launch, {
286
285
  store: host.store,
287
286
  data: host.data,
288
- learningFolder: (id) => learningFolderOf(host.data, id),
289
287
  env: host.env ?? process.env,
290
288
  stored: () => storeSecrets(host.store, host.sealKey, host.data),
291
289
  });
@@ -1,5 +1,4 @@
1
1
  import type { Shown } from "../learning.js";
2
- import { type PromotionDeps } from "../runner/promotion.js";
3
2
  import type { RunLaunch } from "../run-launch.js";
4
3
  import type { Store } from "../store/store.js";
5
4
  import type { SdkInbox } from "./runs.js";
@@ -22,8 +21,7 @@ export type SdkWorkflowCheckEvent = {
22
21
  * the check (sdkCheckTurn: kept until the check holds compile_after rows, the one that makes compile_after deciding on
23
22
  * them all); any other turn is given back (releaseSdkCheck) and the check waits for the next turn; a turn the backend
24
23
  * never completed before its inbox expired is one failed row (sdkCheckDeadline). Exact retries and reclaims compete on
25
- * the reservation. `refused`: what the purge gate refuses of the records, so the promotions trim keeps the champion its
26
- * readers serve (purged-workflow.ts refusedIn). */
24
+ * the reservation. */
27
25
  export declare function settleSdkCheck(deps: {
28
26
  store: Store;
29
27
  agentId: string;
@@ -31,5 +29,4 @@ export declare function settleSdkCheck(deps: {
31
29
  inbox: SdkInbox;
32
30
  shown: () => Promise<Shown>;
33
31
  log: (line: string) => void;
34
- refused?: PromotionDeps["refused"];
35
32
  }): Promise<import("../learn/promote.js").Recorded | undefined>;
package/dist/sdk/check.js CHANGED
@@ -25,14 +25,13 @@ function notBaseline(inbox, reported) {
25
25
  * the check (sdkCheckTurn: kept until the check holds compile_after rows, the one that makes compile_after deciding on
26
26
  * them all); any other turn is given back (releaseSdkCheck) and the check waits for the next turn; a turn the backend
27
27
  * never completed before its inbox expired is one failed row (sdkCheckDeadline). Exact retries and reclaims compete on
28
- * the reservation. `refused`: what the purge gate refuses of the records, so the promotions trim keeps the champion its
29
- * readers serve (purged-workflow.ts refusedIn). */
28
+ * the reservation. */
30
29
  export async function settleSdkCheck(deps) {
31
30
  const { inbox } = deps;
32
31
  const check = inbox.learning_check;
33
32
  if (!check)
34
33
  return;
35
- const record = promotionOf(await promotionsOf(deps.store.settings, deps.agentId), check.workflow.name, check.digest);
34
+ const record = promotionOf(await promotionsOf(deps.store.learning, deps.agentId), check.workflow.name, check.digest);
36
35
  if (record?.decided !== "replaying" || record.via !== "sdk" || record.replay_id !== check.id || !record.check || record.commit !== check.revision || record.runs?.[0] !== inbox.run_id)
37
36
  return;
38
37
  const completion = inbox.completion;
@@ -64,8 +64,10 @@ export type SdkInbox = {
64
64
  }[];
65
65
  /** Exact promoted executable workflows delivered by the start receipt. */
66
66
  learning_workflows?: LearnedWorkflow[];
67
- /** The learning commit each of learning_workflows was read at, by name (its seed's, or its champion record's): where
68
- * the receipt asks whether a purged run wrote it (receipt). */
67
+ /** The runs whose text learning_workflows and learning_check's draft are, every file's writer (a README.md's as well
68
+ * as a workflow.json's): a receipt sent again after one of them is purged answers 410 purged (receipt). */
69
+ learning_writers?: string[];
70
+ /** Legacy: a server before learning rows wrote this (the save each workflow was read at) and no learning_writers. */
69
71
  learning_commits?: Record<string, string>;
70
72
  /** The learned workflow a learned_workflow start names, by its call's id as stored, where its input is stored withheld (a held
71
73
  * value split across its arguments, withheldParts): the parent check of a callback nested in it reads its name here
@@ -86,6 +88,14 @@ export declare const sdkRunKey: (id: string) => string;
86
88
  export declare const SDK_MAX_OPEN_MS = 86400000;
87
89
  export declare const sdkOf: (body: unknown) => SdkBinding | undefined;
88
90
  export declare function sdkInbox(store: Pick<Store, "settings">, runId: string): Promise<SdkInbox>;
91
+ /** What every SDK run's inbox holds of run `runId`'s text, gone (its purge; `agentId` the run's agent): an inbox whose
92
+ * workflows or check draft it wrote (`learning_writers` names it) keeps none of them, its writers kept, so its receipt
93
+ * answers 410 purged. An inbox that names no writers (unwritten) is emptied by the purge of any run of its own agent,
94
+ * since the run may be one of them, its learning_commits kept, so its receipt is refused still. A run of another agent
95
+ * never wrote that agent's learning, so its purge writes no row of such an inbox. Run after the run's purge committed,
96
+ * and a start checks its writers after its inbox is written (start), so one of the two always sees the other: no
97
+ * inbox keeps a purged run's workflow text. */
98
+ export declare function forgetSdkCopies(store: Pick<Store, "settings" | "runs">, agentId: string, runId: string): Promise<void>;
89
99
  /** Completion and closure compete on the same inbox. A stale runner cannot close it, and a completion that won
90
100
  * remains available to the next claim even if this one cannot read or journal it. No external SDK call is replayed.
91
101
  * An expiry is checked against the row it replaces: an events batch that moved the deadline keeps the inbox open. */
@@ -137,12 +147,15 @@ export declare class SdkRuns {
137
147
  workflows: LearnedWorkflow[];
138
148
  };
139
149
  }>;
140
- /** The purged run (purgeGate) that wrote a workflow of `pinned`, each read at the learning commit a start took its
141
- * text from. One read-only exec per commit. */
142
- private purgedPinned;
143
- /** The workflows a start delivers and the learning commit each was read at (`commits`: the seed's, or its champion
144
- * record's), and the drafts a check may take. */
150
+ /** The workflows a start delivers, each the seed's or its champion's text read at its record's save, and the runs whose
151
+ * text each is (`writers`: every run that wrote one of its files there, its README.md's description as well as its
152
+ * workflow.json's text); the drafts a check may take, and the runs whose text each is (`drafts`, by name). A text and
153
+ * its writer are two reads, and a purge rewrites the saves they read in place: it adds a save of its own after the
154
+ * newest (Store.learning purgeRun), so a selection a purge save moved under is read again (a normal save rewrites
155
+ * nothing it read), and one that keeps moving refuses the start, to start again. Never the purged run's text named as
156
+ * no run's. */
145
157
  private selectedWorkflows;
158
+ private selectedOnce;
146
159
  private modify;
147
160
  private writable;
148
161
  events(runId: string, body: Record<string, unknown>): Promise<{
package/dist/sdk/runs.js CHANGED
@@ -10,15 +10,15 @@ import { uuidv7 } from "../ids.js";
10
10
  import { launchBody } from "../run-launch.js";
11
11
  import { learningStartFor } from "../runs-over-store.js";
12
12
  import { labelsIssues, labelsOf } from "../run-labels.js";
13
- import { chooseWorkflows, learningFolderOf, seedAt, secretsShown, withAgentRepo } from "../learning.js";
13
+ import { chooseWorkflows, inLearningQueue, seedAt, secretsShown } from "../learning.js";
14
14
  import { INSTRUCTION_EVIDENCE_BYTES } from "../native/instructions.js";
15
15
  import { CLI_POLICY_BYTES } from "../cli-learning/policy.js";
16
16
  import { refuseWhileNoRunner } from "../runner/presence.js";
17
17
  import { secretRedactor } from "../runner/redact.js";
18
18
  import { redactedOutput, withheldWhole } from "../key-refusal.js";
19
19
  import { decodedStrings, draftProblems } from "../learn/workflow-draft.js";
20
- import { snapshotAt } from "../learn/folder.js";
21
- import { purgedRun, purgeGate, refusedIn, refusedOf } from "../purged-workflow.js";
20
+ import { learningOf } from "../learn/rows.js";
21
+ import { purgedRun, purgedRows } from "../purged-workflow.js";
22
22
  import { sdkWorkflowManifest, sdkDraftTools } from "./workflows.js";
23
23
  import { promotionOf, promotionsOf, resetAtOf } from "../learn/promote.js";
24
24
  import { championTextOf, releaseSdkCheck, reserveSdkCheck } from "../runner/promotion.js";
@@ -105,6 +105,36 @@ export async function sdkInbox(store, runId) {
105
105
  throw new ApiError("not_found", "No backend SDK run with that id.");
106
106
  return row;
107
107
  }
108
+ /** An inbox a server before learning rows wrote: it holds learning and names no writers (a start now always names them,
109
+ * none too), so whether a purged run wrote its text can't be known. Its receipt is refused (receipt). */
110
+ const unwritten = (inbox) => inbox.learning_writers === undefined && (inbox.learning_commits !== undefined || !!inbox.learning_workflows?.length || !!inbox.learning_check);
111
+ /** What every SDK run's inbox holds of run `runId`'s text, gone (its purge; `agentId` the run's agent): an inbox whose
112
+ * workflows or check draft it wrote (`learning_writers` names it) keeps none of them, its writers kept, so its receipt
113
+ * answers 410 purged. An inbox that names no writers (unwritten) is emptied by the purge of any run of its own agent,
114
+ * since the run may be one of them, its learning_commits kept, so its receipt is refused still. A run of another agent
115
+ * never wrote that agent's learning, so its purge writes no row of such an inbox. Run after the run's purge committed,
116
+ * and a start checks its writers after its inbox is written (start), so one of the two always sees the other: no
117
+ * inbox keeps a purged run's workflow text. */
118
+ export async function forgetSdkCopies(store, agentId, runId) {
119
+ for (const row of await store.settings.all({ prefix: keyOf("") })) {
120
+ for (let value = row.value, retry = 0; retry < 20; retry++) {
121
+ if (!isObject(value))
122
+ break;
123
+ const inbox = value;
124
+ if (!inbox.learning_workflows?.length && !inbox.learning_check)
125
+ break;
126
+ const legacy = unwritten(inbox);
127
+ if (!legacy && !inbox.learning_writers?.includes(runId))
128
+ break;
129
+ if (legacy && (await store.runs.get(inbox.run_id))?.agentId !== agentId)
130
+ break;
131
+ const { learning_check: _check, ...rest } = inbox;
132
+ if (await store.settings.replaceIf(row.key, value, { ...rest, learning_workflows: [], ...(legacy ? { learning_commits: inbox.learning_commits ?? {} } : {}) }))
133
+ break;
134
+ value = await store.settings.get(row.key);
135
+ }
136
+ }
137
+ }
108
138
  /** Completion and closure compete on the same inbox. A stale runner cannot close it, and a completion that won
109
139
  * remains available to the next claim even if this one cannot read or journal it. No external SDK call is replayed.
110
140
  * An expiry is checked against the row it replaces: an events batch that moved the deadline keeps the inbox open. */
@@ -340,7 +370,7 @@ export class SdkRuns {
340
370
  if (!cli)
341
371
  await compile.check(learning.model);
342
372
  if (learning.seedFailed)
343
- throw new ApiError("unavailable", "The learning seed could not be read. Retry after restoring the agent learning folder.");
373
+ throw new ApiError("unavailable", "The learning seed could not be read. Retry the start.");
344
374
  }
345
375
  const revision = entry.revision;
346
376
  const admit = async () => {
@@ -349,17 +379,18 @@ export class SdkRuns {
349
379
  const reset = learning ? await resetAtOf(this.store.settings, entry.agent.id) : undefined;
350
380
  if (learning && reset !== undefined && !(learning.seededAt !== undefined && learning.seededAt > reset))
351
381
  throw new ApiError("unavailable", "The agent's learning was reset while this run started: start it again.", { retry_after_ms: 1_000 });
352
- const selected = learning && !learning.noWorkflows && workflow ? await this.selectedWorkflows(entry.agent.id, learning.seed, workflow) : { workflows: [], commits: {}, candidates: [] };
382
+ const selected = learning && !learning.noWorkflows && workflow ? await this.selectedWorkflows(entry.agent.id, learning.seed, workflow) : { workflows: [], writers: new Map(), candidates: [], drafts: {} };
353
383
  const cleaned = this.clean({ instructions, ...(model ? { model } : {}) });
354
384
  const runId = uuidv7();
355
385
  const redacted = cleanedInput !== input || cleaned.instructions !== instructions;
356
386
  // A turn is a check only when it can be one's baseline: no protected value in its task or policy, and an input the
357
387
  // draft takes (sdkTakes). A prose turn whose input the client cannot resolve is given back (releaseSdkCheck).
358
388
  const takes = (flow) => !redacted && sdkTakes(flow, input, resolveSchemaForWorkflow);
359
- const checkDeps = { store: this.store, agentId: entry.agent.id, log: () => { }, shown: async () => secretsShown(this.secrets(), { local: true }), refused: refusedIn(() => learningFolderOf(this.data, entry.agent.id), this.store) };
389
+ const checkDeps = { store: this.store, agentId: entry.agent.id, log: () => { }, shown: async () => secretsShown(this.secrets(), { local: true }) };
360
390
  const check = learning ? await reserveSdkCheck(checkDeps, { runId, revision: learning.seed, learning: revisionBody.learning, flows: selected.candidates, takes }) : undefined;
361
391
  // A shadow check needs the original agent's own answer, not an answer produced by its existing champion.
362
392
  const workflows = check ? [] : selected.workflows;
393
+ const writers = [...new Set([...workflows.flatMap((flow) => selected.writers.get(flow) ?? []), ...(check ? (selected.drafts[check.workflow.name] ?? []) : [])])];
363
394
  const launch = {
364
395
  input: { content: cleanedInput },
365
396
  title: title === undefined ? cleanedInput.trim().replace(/\s+/g, " ").slice(0, 80) : this.clean({ title }).title,
@@ -381,11 +412,16 @@ export class SdkRuns {
381
412
  expires_at: now + (cli ? SDK_MAX_OPEN_MS : SDK_OPEN_MS),
382
413
  batches: [],
383
414
  learning_workflows: workflows,
384
- ...(workflows.length ? { learning_commits: selected.commits } : {}),
415
+ // Named whenever it holds learning, none too: an inbox without the key is an earlier server's (unwritten).
416
+ ...(workflows.length || check ? { learning_writers: writers } : {}),
385
417
  ...(check ? { learning_check: check } : {}),
386
418
  ...(redacted ? { check_redacted: true } : {}),
387
419
  ...(cli && cleanedInput !== input ? { evidence_incomplete: true } : {}),
388
420
  });
421
+ // A writer purged since the selection read it (the purge's own scrub of inboxes, forgetSdkCopies, runs after it
422
+ // commits, so it sees this inbox unless this read sees the purge): the start is refused, its inbox removed.
423
+ if (writers.length && (await purgedRows(this.store, writers)).size)
424
+ throw new ApiError("unavailable", "The agent's learning changed while this run started: start it again.", { retry_after_ms: 1_000 });
389
425
  await this.store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: revision.id, ...(cli ? { expectedCurrent, settingsGuards: sourceGuards } : {}), ...(origin ? { origin } : {}), ...(labels ? { labels } : {}), ...(startedAt !== undefined ? { startedAt } : {}) }, { body: launchBody(launch) });
390
426
  }
391
427
  catch (error) {
@@ -393,7 +429,7 @@ export class SdkRuns {
393
429
  // The reservation comes first because the launch it is created with withholds the champion from a check's turn.
394
430
  // No turn ran, so the check waits for the next one, the release uncounted: never a hold of a draft never compared.
395
431
  if (check) {
396
- const record = promotionOf(await promotionsOf(this.store.settings, entry.agent.id).catch(() => []), check.workflow.name, check.digest);
432
+ const record = promotionOf(await promotionsOf(this.store.learning, entry.agent.id).catch(() => []), check.workflow.name, check.digest);
397
433
  if (record?.decided === "replaying" && record.replay_id === check.id)
398
434
  await releaseSdkCheck(checkDeps, record, "its start could not be admitted", false).catch(() => undefined);
399
435
  }
@@ -411,11 +447,11 @@ export class SdkRuns {
411
447
  }
412
448
  return runId;
413
449
  };
414
- // A learning start is admitted in its agent's learning queue (learning.ts withAgentRepo), the one a reset of the
450
+ // A learning start is admitted in its agent's learning queue (learning.ts inLearningQueue), the one a reset of the
415
451
  // agent's learning deletes it in: either the reset comes first, and the seed read before it is refused above, or this
416
452
  // run's row is made first, and the reset refuses while it goes (409 learning_busy). No check of a draft the reset
417
453
  // deleted is reserved, and no run starts on it.
418
- const runId = learning ? await withAgentRepo(this.data, entry.agent.id, admit) : await admit();
454
+ const runId = learning ? await inLearningQueue(this.data, entry.agent.id, admit) : await admit();
419
455
  return this.receipt(runId, consoleOrigin);
420
456
  }
421
457
  async receipt(runId, consoleOrigin) {
@@ -425,13 +461,10 @@ export class SdkRuns {
425
461
  const launch = (await this.store.runs.launch(runId)).body;
426
462
  const inbox = await sdkInbox(this.store, runId);
427
463
  const workflows = inbox.learning_workflows ?? [];
464
+ if (unwritten(inbox))
465
+ throw new ApiError("not_continuable", "This SDK start was pinned before a server upgrade, so the runs that wrote its learning can't be checked. Start a new run with a new Idempotency-Key.");
428
466
  // A start sent again answers the receipt it pinned, never a workflow a purged run wrote: 410 purged, as its file read.
429
- // Each is read at the commit it was taken from (learning_commits; the check's draft at the seed).
430
- const seed = launch.learning?.seed ?? null;
431
- const purged = seed === null ? undefined : await this.purgedPinned(run.agentId, [
432
- ...workflows.map((flow) => [flow, inbox.learning_commits?.[flow.name] ?? seed]),
433
- ...(inbox.learning_check ? [[inbox.learning_check.workflow, seed]] : []),
434
- ]);
467
+ const purged = [...(await purgedRows(this.store, inbox.learning_writers ?? [])).values()][0];
435
468
  if (purged)
436
469
  throw purgedRun(purged);
437
470
  const shown = secretsShown(this.secrets(), { local: true });
@@ -455,62 +488,66 @@ export class SdkRuns {
455
488
  },
456
489
  };
457
490
  }
458
- /** The purged run (purgeGate) that wrote a workflow of `pinned`, each read at the learning commit a start took its
459
- * text from. One read-only exec per commit. */
460
- async purgedPinned(agentId, pinned) {
461
- if (pinned.length === 0)
462
- return undefined;
463
- const folder = learningFolderOf(this.data, agentId);
464
- try {
465
- const reads = new Map();
466
- const at = (commit) => reads.get(commit) ?? reads.set(commit, snapshotAt(folder.workspace, commit).then(async (snapshot) => (await purgeGate(snapshot, this.store)).workflows)).get(commit);
467
- for (const [flow, commit] of pinned) {
468
- const row = (await at(commit)).get(flow.name);
469
- if (row)
470
- return row;
471
- }
472
- return undefined;
473
- }
474
- finally {
475
- await folder.end();
491
+ /** The workflows a start delivers, each the seed's or its champion's text read at its record's save, and the runs whose
492
+ * text each is (`writers`: every run that wrote one of its files there, its README.md's description as well as its
493
+ * workflow.json's text); the drafts a check may take, and the runs whose text each is (`drafts`, by name). A text and
494
+ * its writer are two reads, and a purge rewrites the saves they read in place: it adds a save of its own after the
495
+ * newest (Store.learning purgeRun), so a selection a purge save moved under is read again (a normal save rewrites
496
+ * nothing it read), and one that keeps moving refuses the start, to start again. Never the purged run's text named as
497
+ * no run's. */
498
+ async selectedWorkflows(agentId, revision, binding) {
499
+ const newest = () => this.store.learning.newestPurge(agentId);
500
+ for (let attempt = 0; attempt < 3; attempt++) {
501
+ const before = await newest();
502
+ const selected = await this.selectedOnce(agentId, revision, binding);
503
+ if ((await newest()) === before)
504
+ return selected;
476
505
  }
506
+ throw new ApiError("unavailable", "The agent's learning changed while this run started: start it again.", { retry_after_ms: 1_000 });
477
507
  }
478
- /** The workflows a start delivers and the learning commit each was read at (`commits`: the seed's, or its champion
479
- * record's), and the drafts a check may take. */
480
- async selectedWorkflows(agentId, revision, binding) {
481
- const folder = learningFolderOf(this.data, agentId);
482
- try {
483
- const seed = await seedAt(folder.workspace, revision, this.store);
484
- const { flows } = chooseWorkflows(seed, secretsShown(this.secrets(), { local: true }));
485
- const dsl = await import("@parcha/agentrun-dsl");
486
- const { tools, gated, deniedBy } = sdkDraftTools(binding.workflow_tools);
487
- const records = await promotionsOf(this.store.settings, agentId);
488
- let room = 256 * 1024;
489
- const compatible = (flow) => {
490
- const bytes = Buffer.byteLength(JSON.stringify(flow));
491
- if (bytes > room || draftProblems(dsl, flow.workflow, tools, gated, deniedBy, undefined, binding.workflow_adapters).length)
492
- return false;
493
- room -= bytes;
494
- return true;
495
- };
496
- const workflows = [], candidates = [], commits = {};
497
- const atCommit = async (name, commit) => chooseWorkflows(await seedAt(folder.workspace, commit, this.store), secretsShown(this.secrets(), { local: true })).flows.find((one) => one.name === name);
498
- // The champion skips a record the purge gate refuses at its commit (purged-workflow.ts refusedOf), as a claim's does.
499
- const refused = async (all, names) => refusedOf(all, names ?? all.map((one) => one.workflow), folder.workspace, this.store);
500
- for (const flow of flows) {
501
- const { text: serving, champion } = await championTextOf(records, flow, atCommit, refused);
502
- if (serving && compatible(serving)) {
503
- workflows.push(serving);
504
- commits[serving.name] = serving === flow ? seed.sha : champion.commit;
505
- }
506
- if ((!serving || workflowDigest(serving) !== workflowDigest(flow)) && compatible(flow))
507
- candidates.push(flow);
508
+ async selectedOnce(agentId, revision, binding) {
509
+ const learning = learningOf(this.store, agentId);
510
+ const reads = new Map();
511
+ const readSave = (save) => reads.get(save) ?? reads.set(save, this.store.learning.itemsAt(agentId, save)).get(save);
512
+ // Every run whose file of workflow `name` save `save` holds: its README.md's (the description delivered) as well as
513
+ // its workflow.json's (the item's run), and any other file's, so a purge of any of them refuses the receipt.
514
+ const writersAt = async (name, save) => {
515
+ const item = save === null ? undefined : (await readSave(save))?.items.find((one) => one.kind === "workflow" && one.name === name);
516
+ if (!item)
517
+ return [];
518
+ return [...new Set([item.byRun, ...Object.values(item.writers ?? {})].filter((run) => typeof run === "string"))];
519
+ };
520
+ const seed = await seedAt(learning, revision);
521
+ const { flows } = chooseWorkflows(seed, secretsShown(this.secrets(), { local: true }));
522
+ const dsl = await import("@parcha/agentrun-dsl");
523
+ const { tools, gated, deniedBy } = sdkDraftTools(binding.workflow_tools);
524
+ const records = await promotionsOf(this.store.learning, agentId);
525
+ let room = 256 * 1024;
526
+ const compatible = (flow) => {
527
+ const bytes = Buffer.byteLength(JSON.stringify(flow));
528
+ if (bytes > room || draftProblems(dsl, flow.workflow, tools, gated, deniedBy, undefined, binding.workflow_adapters).length)
529
+ return false;
530
+ room -= bytes;
531
+ return true;
532
+ };
533
+ const workflows = [], candidates = [], writers = new Map(), drafts = {};
534
+ const atSave = async (name, save) => chooseWorkflows(await seedAt(learning, save), secretsShown(this.secrets(), { local: true })).flows.find((one) => one.name === name);
535
+ for (const flow of flows) {
536
+ const { text: serving, champion } = await championTextOf(records, flow, atSave);
537
+ if (serving && compatible(serving)) {
538
+ workflows.push(serving);
539
+ const runs = await writersAt(serving.name, serving === flow ? seed.sha : champion.commit ?? null);
540
+ if (runs.length)
541
+ writers.set(serving, runs);
542
+ }
543
+ if ((!serving || workflowDigest(serving) !== workflowDigest(flow)) && compatible(flow)) {
544
+ candidates.push(flow);
545
+ const runs = await writersAt(flow.name, seed.sha);
546
+ if (runs.length)
547
+ drafts[flow.name] = runs;
508
548
  }
509
- return { workflows, commits, candidates };
510
- }
511
- finally {
512
- await folder.end();
513
549
  }
550
+ return { workflows, writers, candidates, drafts };
514
551
  }
515
552
  async modify(runId, change, limit = TOTAL_LIMIT) {
516
553
  for (let retry = 0; retry < 20; retry++) {