@parcha/agentrun-serve 0.1.0-beta.41 → 0.1.0-beta.43

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 (164) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/NOTICE +2 -0
  3. package/README.md +85 -19
  4. package/dist/agent-rows.d.ts +1 -1
  5. package/dist/agents-store.js +3 -1
  6. package/dist/calendar/address.d.ts +49 -0
  7. package/dist/calendar/address.js +153 -0
  8. package/dist/calendar/fetch.d.ts +24 -0
  9. package/dist/calendar/fetch.js +146 -0
  10. package/dist/calendar/ics-faux.d.ts +39 -0
  11. package/dist/calendar/ics-faux.js +236 -0
  12. package/dist/calendar/labels.d.ts +3 -0
  13. package/dist/calendar/labels.js +61 -0
  14. package/dist/calendar/names.d.ts +52 -0
  15. package/dist/calendar/names.js +54 -0
  16. package/dist/calendar/parse.d.ts +108 -0
  17. package/dist/calendar/parse.js +625 -0
  18. package/dist/calendar/routes.d.ts +17 -0
  19. package/dist/calendar/routes.js +81 -0
  20. package/dist/calendar/tools.d.ts +23 -0
  21. package/dist/calendar/tools.js +124 -0
  22. package/dist/cli.js +3 -1
  23. package/dist/computer-record.d.ts +55 -0
  24. package/dist/computer-record.js +315 -0
  25. package/dist/computer-setting.d.ts +1 -0
  26. package/dist/computer-setting.js +15 -2
  27. package/dist/computers.js +2 -14
  28. package/dist/console/assets/index-BrcDSBD8.css +1 -0
  29. package/dist/console/assets/index-Bz6IWncl.js +711 -0
  30. package/dist/console/index.html +2 -2
  31. package/dist/decisions.js +0 -4
  32. package/dist/eval-feed.d.ts +2 -2
  33. package/dist/eval-feed.js +9 -5
  34. package/dist/feed/parse.d.ts +3 -2
  35. package/dist/feed/parse.js +9 -18
  36. package/dist/feed/pointer.d.ts +2 -0
  37. package/dist/feed/pointer.js +17 -0
  38. package/dist/file-types.js +1 -0
  39. package/dist/host-command.d.ts +3 -0
  40. package/dist/host-command.js +18 -0
  41. package/dist/host.d.ts +3 -0
  42. package/dist/host.js +3 -0
  43. package/dist/import-sources.js +25 -5
  44. package/dist/learn/audit.d.ts +123 -0
  45. package/dist/learn/audit.js +159 -0
  46. package/dist/learn/check.d.ts +14 -0
  47. package/dist/learn/check.js +194 -14
  48. package/dist/learn/compile.d.ts +75 -78
  49. package/dist/learn/compile.js +175 -176
  50. package/dist/learn/folder.d.ts +9 -0
  51. package/dist/learn/folder.js +13 -2
  52. package/dist/learn/promote.d.ts +138 -196
  53. package/dist/learn/promote.js +68 -184
  54. package/dist/learn/replay-calls.d.ts +5 -0
  55. package/dist/learn/replay-calls.js +12 -1
  56. package/dist/learn/secrets.d.ts +8 -0
  57. package/dist/learn/secrets.js +12 -0
  58. package/dist/learn/skills.js +2 -4
  59. package/dist/learn/workflow-nodes.d.ts +1 -2
  60. package/dist/learn/workflow-nodes.js +2 -3
  61. package/dist/learned-nodes.d.ts +9 -34
  62. package/dist/learned-nodes.js +11 -23
  63. package/dist/learned-workflow.d.ts +6 -8
  64. package/dist/learned-workflow.js +18 -57
  65. package/dist/learning-batch.d.ts +13 -5
  66. package/dist/learning-batch.js +34 -8
  67. package/dist/learning-cost.d.ts +11 -4
  68. package/dist/learning-cost.js +4 -2
  69. package/dist/learning-routes.js +1 -1
  70. package/dist/learning-setting.d.ts +38 -0
  71. package/dist/learning-setting.js +83 -0
  72. package/dist/learning-words.d.ts +3 -0
  73. package/dist/learning-words.js +3 -0
  74. package/dist/learning.d.ts +3 -2
  75. package/dist/learning.js +5 -3
  76. package/dist/mcp-oauth.d.ts +8 -0
  77. package/dist/mcp-oauth.js +7 -0
  78. package/dist/mcp-private-hosts.d.ts +13 -0
  79. package/dist/mcp-private-hosts.js +16 -0
  80. package/dist/openapi.d.ts +1 -0
  81. package/dist/openapi.js +195 -59
  82. package/dist/run-files.d.ts +6 -2
  83. package/dist/run-files.js +29 -7
  84. package/dist/run-launch.d.ts +6 -3
  85. package/dist/run-launch.js +2 -0
  86. package/dist/run-learning-served.d.ts +2 -2
  87. package/dist/run-reads-over-store.d.ts +5 -1
  88. package/dist/run-reads-over-store.js +8 -4
  89. package/dist/run-recordings.d.ts +20 -0
  90. package/dist/run-recordings.js +133 -0
  91. package/dist/runner/adapter-loop.d.ts +5 -1
  92. package/dist/runner/adapter-loop.js +20 -8
  93. package/dist/runner/adapter-run-spec.d.ts +16 -1
  94. package/dist/runner/adapter-run-spec.js +36 -11
  95. package/dist/runner/audit.d.ts +64 -0
  96. package/dist/runner/audit.js +338 -0
  97. package/dist/runner/beside.js +2 -2
  98. package/dist/runner/cli-run-spec.js +25 -12
  99. package/dist/runner/feedback-round.d.ts +9 -25
  100. package/dist/runner/feedback-round.js +19 -40
  101. package/dist/runner/harness-loops.js +1 -15
  102. package/dist/runner/journal-kinds.d.ts +0 -7
  103. package/dist/runner/journal-kinds.js +0 -7
  104. package/dist/runner/learning-dispatch.d.ts +0 -16
  105. package/dist/runner/learning-dispatch.js +4 -47
  106. package/dist/runner/learning-end.d.ts +62 -13
  107. package/dist/runner/learning-end.js +180 -74
  108. package/dist/runner/learning-factory.d.ts +1 -1
  109. package/dist/runner/learning-factory.js +1 -4
  110. package/dist/runner/learning-loop.d.ts +2 -38
  111. package/dist/runner/learning-loop.js +8 -116
  112. package/dist/runner/main.d.ts +11 -0
  113. package/dist/runner/main.js +30 -3
  114. package/dist/runner/mcp-run.d.ts +2 -2
  115. package/dist/runner/promotion.d.ts +78 -50
  116. package/dist/runner/promotion.js +371 -503
  117. package/dist/runner/reflect-hook.d.ts +15 -0
  118. package/dist/runner/reflect-hook.js +28 -14
  119. package/dist/runner/store-secrets.js +3 -1
  120. package/dist/runner/workflow-first.d.ts +6 -11
  121. package/dist/runner/workflow-first.js +24 -25
  122. package/dist/runs-over-store.d.ts +1 -1
  123. package/dist/sdk/runs.js +2 -1
  124. package/dist/secrets.js +2 -2
  125. package/dist/server.d.ts +4 -3
  126. package/dist/server.js +132 -26
  127. package/dist/store/agent-body.d.ts +5 -3
  128. package/dist/store/agent-body.js +14 -10
  129. package/dist/store/sqlite/store.js +1 -0
  130. package/dist/store/store.d.ts +3 -0
  131. package/dist/store-reads/learning.d.ts +18 -7
  132. package/dist/store-reads/learning.js +36 -23
  133. package/dist/store-reads/loop.d.ts +5 -39
  134. package/dist/store-reads/loop.js +21 -80
  135. package/dist/store-view.d.ts +5 -0
  136. package/dist/store-view.js +16 -2
  137. package/dist/template-eval.d.ts +7 -0
  138. package/dist/template-eval.js +54 -6
  139. package/dist/templates.d.ts +3 -1
  140. package/dist/templates.js +14 -1
  141. package/dist/timeline/computer.js +2 -1
  142. package/dist/tool-list.js +1 -0
  143. package/dist/tools.d.ts +7 -0
  144. package/dist/tools.js +11 -0
  145. package/dist/trigger-feed.js +67 -18
  146. package/dist/validate.js +7 -2
  147. package/dist/workspace/computer-for-claim.d.ts +7 -0
  148. package/dist/workspace/computer-for-claim.js +12 -2
  149. package/dist/workspace/paths.d.ts +4 -0
  150. package/dist/workspace/paths.js +9 -0
  151. package/dist/workspace/resolve-computer.d.ts +3 -1
  152. package/dist/workspace/run-tools.d.ts +1 -1
  153. package/dist/workspace/run-tools.js +14 -3
  154. package/launcher/agentrun-serve +31 -24
  155. package/package.json +10 -9
  156. package/templates/README.md +11 -2
  157. package/dist/console/assets/index-C3gNPz58.css +0 -1
  158. package/dist/console/assets/index-COGhx_2Z.js +0 -711
  159. package/dist/learn/general.d.ts +0 -69
  160. package/dist/learn/general.js +0 -75
  161. package/dist/learn/refit.d.ts +0 -48
  162. package/dist/learn/refit.js +0 -264
  163. package/dist/runner/step-guard.d.ts +0 -62
  164. package/dist/runner/step-guard.js +0 -93
@@ -0,0 +1,64 @@
1
+ import { type Context } from "@earendil-works/chord/context";
2
+ import { type AuditLoop } from "../learning-setting.js";
3
+ import { type RunLaunch } from "../run-launch.js";
4
+ import { type RunRow, type Store } from "../store/store.js";
5
+ import { type LearningFolder } from "../learn/folder.js";
6
+ import type { Shown } from "../learning.js";
7
+ import type { EndOfRunTurn } from "./loop-contract.js";
8
+ import { type WorkflowFirst } from "./workflow-first.js";
9
+ /** What the audit reads and writes at a claim (or the server's grade): the agent, the run claimed (none for a grade),
10
+ * its revision (whose definition holds the numbers) and launch, the agent's learning folder, the host's secrets as a
11
+ * hold's texts are cut of them (`shown`, as a check's are), the seal key (a shadow is handed the per_run MCP
12
+ * credentials its served run was). */
13
+ export type AuditDeps = {
14
+ readonly store: Store;
15
+ readonly agentId: string;
16
+ readonly revisionId: string;
17
+ readonly context: Context;
18
+ readonly folder: () => LearningFolder;
19
+ readonly shown: () => Promise<Pick<Shown, "text">>;
20
+ readonly log: (line: string) => void;
21
+ readonly sealKey?: Buffer;
22
+ readonly now?: () => number;
23
+ };
24
+ /** The words a second hold within stop_window leaves on its record: what the owner reads. */
25
+ export declare const STOPPED_TWICE = "stopped: the workflow disagreed with the agent twice";
26
+ /** The audit numbers of revision `revisionId`'s definition (each one it leaves out at its default). */
27
+ export declare function auditLoopOfRevision(store: Pick<Store, "agents">, revisionId: string): Promise<AuditLoop>;
28
+ /** How many of the newest stop_window runs `workflow` at `digest` served were not auditable (auditableLaunch: a trigger
29
+ * started them): what the promotions read counts beside the audit line. */
30
+ export declare function notAuditableOf(store: Pick<Store, "runs">, agentId: string, workflow: string, digest: string, loop: Pick<AuditLoop, "stop_window">): Promise<number>;
31
+ /** The words a shadow run ends failed with where it would wait on a person (AdapterRunSpec.neverWaits: an approval, a
32
+ * raise of its cap, which is what its served run's cap left, a question), what it would wait on after them: its row is
33
+ * `parked`, with no verdict. */
34
+ export declare const AUDIT_PARKED = "the audit ended where it would wait on a person";
35
+ /** The served run's end-of-run step `step` (none for a run that only uses what its agent learned), its audit started
36
+ * after it (startAudit) on an end the run reached on its own (a cut run starts none): the learned workflow that served
37
+ * it, read from its journal whatever claim it served on (servedOf), and, for a capped run, what its cap leaves once this
38
+ * end is counted (auditRoomOf: its job, its look-back, the grades beside it and the one this end queues). A run that
39
+ * could never be audited (no learning start, or not auditableLaunch) keeps `step` as it is. */
40
+ export declare function withAudit(step: EndOfRunTurn | undefined, deps: AuditDeps & {
41
+ readonly launch: RunLaunch;
42
+ }): EndOfRunTurn | undefined;
43
+ /** Starts the shadow of run `runId`, at its end, when the learned workflow `serve` served it first and its id is drawn:
44
+ * never for a replay or a shadow, a run that does not learn, one not auditable (auditableLaunch: a trigger started it,
45
+ * or it was handed files), nor a run of an agent that can call a tool that writes (auditWriterOf). A capped run's shadow
46
+ * is capped at what its cap leaves (`room`, read now: the served run spent all it will under it), so the two never
47
+ * spend past the served run's cap; with less than a run's smallest cap left (or a spend not known), no shadow is started
48
+ * and its row says `skipped: "no allowance"`. Its started line is appended first: a shadow is created only once the
49
+ * ledger names it (settlement finds it there, never in a window of runs), and one whose line could not be written is
50
+ * never created. Idempotent: one line and one shadow per run. */
51
+ export declare function startAudit(deps: AuditDeps & {
52
+ readonly runId: string;
53
+ readonly launch: RunLaunch;
54
+ readonly room?: () => Promise<number | null>;
55
+ }, serve: Pick<WorkflowFirst, "name" | "digest" | "replay"> | undefined): Promise<void>;
56
+ /** Writes the row of each open audit (a started line with no row yet) whose two runs, read by id, ended, the batch
57
+ * oldest served run first (the ledger's tail is its newest); a run that is gone (its shadow never created, say) ends it
58
+ * with no verdict. Then applies the hold rule over the ledger as it is now, rows added or not: the hold is a function of
59
+ * the ledger, so one a crash or a failed write lost after the rows were committed is made at the next claim. */
60
+ export declare function settleAudits(deps: AuditDeps): Promise<void>;
61
+ /** The row an owner's grade of served run `run` writes (source grade, agreed = the grade, counted for the digest's
62
+ * promotion now), then the hold rule: only for a run the workflow answered alone (its answer is the workflow's).
63
+ * Nothing else: no round, no compile by itself. */
64
+ export declare function gradeRow(deps: AuditDeps, run: RunRow, correct: boolean): Promise<void>;
@@ -0,0 +1,338 @@
1
+ // The shadow audit of a serving learned workflow, at a run's claim and its end (learn/audit.ts keeps the ledger).
2
+ // startAudit (withAudit: at the served run's end, before the end commits): a run the promoted workflow served first is
3
+ // drawn at 1 in k (auditDrawn, from its id), and a drawn one appends a `started` line to audits.jsonl (with the
4
+ // promotion serving it and the answer it audits, `turn`: the id of the run's newest answer row now), then starts its
5
+ // shadow run: the same agent and revision on the same input with learning off (no seed, no look-back), marked as the
6
+ // audit of the served run (launch.audit), no row of the run list, billed to the agent as learning cost. Its cap is
7
+ // what the served run's cap left (the two together never pass it; the served run's later gates count it beside them,
8
+ // learning-end.ts besideOf); none left, no shadow (`skipped: "no allowance"`). A shadow never waits on a person: where
9
+ // it would park (an approval its owner's setting asks, a raise of that cap, a question) it ends at once in
10
+ // AUDIT_PARKED's words (AdapterRunSpec.neverWaits, the gate untouched: nothing is let through, no one is asked to
11
+ // answer), and its row is `parked`. Only a run started over the API (no trigger: its context is never rebuilt for a
12
+ // shadow) of an agent every tool of which only reads (learn/audit.ts auditWriterOf, the replay's readOnlyHint rule): a
13
+ // shadow never writes again.
14
+ // settleAudits: each open started line (no result row yet) whose two runs, read by id, ended writes its row (agreed:
15
+ // the audited answer, its `turn`'s, and the shadow's say the same, learn/promote.ts sameAnswer; a follow-up's answer
16
+ // since is never read), oldest served run first; then, rows added or not, the hold rule reads the serving revisions'
17
+ // rows: a hold is a function of the ledger alone.
18
+ // applyHold: at least hold_disagree disagreements in the newest hold_window rows of the digest's current promotion
19
+ // hold the workflow (a promotion hold carrying `audit`, with those rows, each text cut of the host's secrets before
20
+ // it is shortened, learn/secrets.ts excerptShown): the agent's next run asks one recompile with them as data
21
+ // (runner/learning-end.ts compileAskOf), which S3a's check decides on its inputs plus the disagreeing ones. A second
22
+ // hold within stop_window served runs of the first stops it: no compile, the stop said on the record.
23
+ // gradeRow: an owner's grade on a run the workflow answered alone is a row too (source grade, agreed = the grade).
24
+ // Every number is the agent definition's (learning-setting.ts auditLoopOf). Nothing here fails a claim: a failure is logged.
25
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
26
+ import { overCapMessage } from "@parcha/agentrun-kernel/kernel/cap";
27
+ import { auditLoopOf } from "../learning-setting.js";
28
+ import { RUN_CAP_MIN_USD } from "../learning-batch.js";
29
+ import { SERVED_PATHS } from "../learning-cost.js";
30
+ import { launchBody, readLaunchBody } from "../run-launch.js";
31
+ import { runEntries } from "../store-reads/journal.js";
32
+ import { FINAL_STATES, StoreConstraint } from "../store/store.js";
33
+ import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
34
+ import { isObject } from "../validate.js";
35
+ import { auditableLaunch, auditChange, auditEveryOf, auditDrawn, auditsOffWords, auditWriterOf, holdOf, ledgerOf, lineKey, openAudits, rowsOf, shadowRunId } from "../learn/audit.js";
36
+ import { lastRunsOf } from "../learn/compile.js";
37
+ import { readLearning, writeLearning } from "../learn/folder.js";
38
+ import { CHECK_TEXT_MAX, promotionOf, promotionsOf, promotionStartOf, recordPromotion, sameAnswer, servingOf } from "../learn/promote.js";
39
+ import { excerptShown } from "../learn/secrets.js";
40
+ import { auditRoomOf } from "./learning-end.js";
41
+ import { answerOf, answerRowOf } from "./promotion.js";
42
+ import { servedOf } from "./workflow-first.js";
43
+ /** The words a second hold within stop_window leaves on its record: what the owner reads. */
44
+ export const STOPPED_TWICE = "stopped: the workflow disagreed with the agent twice";
45
+ const iso = (ms) => new Date(ms).toISOString();
46
+ const ended = (row) => row !== undefined && FINAL_STATES.includes(row.state) && row.runner === null;
47
+ const inputText = (input) => (typeof input === "string" ? input : JSON.stringify(input) ?? "");
48
+ const metricsOf = (row) => (isObject(row?.metrics) ? row.metrics : {});
49
+ const served = (row) => SERVED_PATHS.includes(metricsOf(row).path);
50
+ /** A line's `turn` (AuditRow.turn): the answer row's id, none when the run had no answer. */
51
+ const turnOf = (id) => (id === undefined ? {} : { turn: id });
52
+ /** The answer an audit row is of: its `turn`'s, read from the run by that row's id; none when it names none. */
53
+ const auditedAnswer = (deps, row) => (row.turn === undefined ? Promise.resolve(null) : answerOf(deps.store, row.run, deps.context, row.turn));
54
+ /** The audit numbers of revision `revisionId`'s definition (each one it leaves out at its default). */
55
+ export async function auditLoopOfRevision(store, revisionId) {
56
+ try {
57
+ return auditLoopOf((await store.agents.revision(revisionId))?.body?.learning);
58
+ }
59
+ catch {
60
+ return auditLoopOf(undefined);
61
+ }
62
+ }
63
+ /** The served runs of `workflow` (at `digest` when given) that `keep` keeps too, the newest `n` of them (lastRunsOf: the
64
+ * shadows and the agent's own runs among them never push one out of the read). */
65
+ const servedRuns = (store, agentId, n, workflow, digest, keep = () => true) => lastRunsOf(store, agentId, n, (row) => served(row) && metricsOf(row).workflow === workflow && (digest === undefined || metricsOf(row).workflow_digest === digest) && keep(row));
66
+ /** How many of the newest stop_window runs `workflow` at `digest` served were not auditable (auditableLaunch: a trigger
67
+ * started them): what the promotions read counts beside the audit line. */
68
+ export async function notAuditableOf(store, agentId, workflow, digest, loop) {
69
+ return (await servedRuns(store, agentId, loop.stop_window, workflow, digest)).filter((row) => metricsOf(row).not_auditable === true).length;
70
+ }
71
+ /** The words a shadow run ends failed with where it would wait on a person (AdapterRunSpec.neverWaits: an approval, a
72
+ * raise of its cap, which is what its served run's cap left, a question), what it would wait on after them: its row is
73
+ * `parked`, with no verdict. */
74
+ export const AUDIT_PARKED = "the audit ended where it would wait on a person";
75
+ /** The served run's end-of-run step `step` (none for a run that only uses what its agent learned), its audit started
76
+ * after it (startAudit) on an end the run reached on its own (a cut run starts none): the learned workflow that served
77
+ * it, read from its journal whatever claim it served on (servedOf), and, for a capped run, what its cap leaves once this
78
+ * end is counted (auditRoomOf: its job, its look-back, the grades beside it and the one this end queues). A run that
79
+ * could never be audited (no learning start, or not auditableLaunch) keeps `step` as it is. */
80
+ export function withAudit(step, deps) {
81
+ if (!deps.launch.learning || !auditableLaunch(deps.launch))
82
+ return step;
83
+ return async (input) => {
84
+ const rows = step ? await step(input) : undefined;
85
+ if (input.cut === undefined)
86
+ await auditAtEnd(deps, input.runId, rows?.also ?? []);
87
+ return rows;
88
+ };
89
+ }
90
+ async function auditAtEnd(deps, runId, queued) {
91
+ try {
92
+ const entries = await runEntries(deps.store, runId, BACKGROUND_CONTEXT);
93
+ const served = servedOf(entries);
94
+ if (!served?.digest)
95
+ return;
96
+ const capUsd = deps.launch.maxCostUsd;
97
+ await startAudit({ ...deps, runId, ...(capUsd !== undefined ? { room: () => auditRoomOf(deps.store, runId, capUsd, entries, queued) } : {}) }, { name: served.workflow, digest: served.digest });
98
+ }
99
+ catch (error) {
100
+ deps.log(`workflow-first: the audit of this run did not start (${error?.message ?? error})`);
101
+ }
102
+ }
103
+ /** Starts the shadow of run `runId`, at its end, when the learned workflow `serve` served it first and its id is drawn:
104
+ * never for a replay or a shadow, a run that does not learn, one not auditable (auditableLaunch: a trigger started it,
105
+ * or it was handed files), nor a run of an agent that can call a tool that writes (auditWriterOf). A capped run's shadow
106
+ * is capped at what its cap leaves (`room`, read now: the served run spent all it will under it), so the two never
107
+ * spend past the served run's cap; with less than a run's smallest cap left (or a spend not known), no shadow is started
108
+ * and its row says `skipped: "no allowance"`. Its started line is appended first: a shadow is created only once the
109
+ * ledger names it (settlement finds it there, never in a window of runs), and one whose line could not be written is
110
+ * never created. Idempotent: one line and one shadow per run. */
111
+ export async function startAudit(deps, serve) {
112
+ const { store, agentId, runId, launch, log } = deps;
113
+ if (!serve || serve.replay || launch.replay || launch.audit || !launch.learning || !auditableLaunch(launch))
114
+ return;
115
+ try {
116
+ // Read after the claim pinned the revision's MCP tools (mcp-claim.ts pinFirst): the pin a revision saved without one
117
+ // takes at its first run is what its tools are classed by.
118
+ const revision = await store.agents.revision(deps.revisionId);
119
+ const writer = auditWriterOf(revision);
120
+ if (writer !== undefined) {
121
+ log(`workflow-first: ${serve.name} at ${serve.digest} serves this run, never audited: ${auditsOffWords(writer)}`);
122
+ return;
123
+ }
124
+ const loop = auditLoopOf(revision?.body?.learning);
125
+ const before = (await servedRuns(store, agentId, loop.audit_later_after, serve.name, serve.digest, (row) => row.id !== runId)).length;
126
+ const k = auditEveryOf(loop, before);
127
+ if (!auditDrawn(runId, k))
128
+ return;
129
+ const id = shadowRunId(runId);
130
+ // Once per run: an end after a follow-up finds its shadow made, or its row written (skipped, or settled). A started
131
+ // line with no shadow (a crash between the two) is made now.
132
+ if (await store.runs.get(id))
133
+ return;
134
+ if ((await readLedger(deps)).some((line) => line.run === runId && line.source === "shadow"))
135
+ return;
136
+ const promoted = promotionStartOf(await promotionsOf(store.settings, agentId), serve.name, serve.digest);
137
+ // The answer audited: the run's newest answer now, at the end that drew it, kept by its row's id so a follow-up's
138
+ // answer since is never the one compared.
139
+ const turn = turnOf((await answerRowOf(store, runId, deps.context))?.id);
140
+ // What the served run's cap leaves its shadow (none for an uncapped run), to a millionth, never above it.
141
+ const room = deps.room ? await deps.room() : undefined;
142
+ const allowance = room === undefined || room === null ? room : Math.floor(room * 1e6 + 1e-6) / 1e6;
143
+ if (allowance === null || (allowance !== undefined && allowance < RUN_CAP_MIN_USD)) {
144
+ const skipped = { run: runId, shadow_run: null, workflow: serve.name, digest: serve.digest, promoted_at: promoted?.at ?? null, source: "shadow", agreed: null, served_cost: null, shadow_cost: null, ...turn, skipped: "no allowance", at: iso((deps.now ?? Date.now)()) };
145
+ await addLines(deps, [skipped]);
146
+ log(`workflow-first: ${serve.name} at ${serve.digest} served this run, drawn for its audit (1 in ${k}); no shadow: ${allowance === null ? "what it spent under its cap is not known" : `its cap leaves $${allowance}, under a run's smallest cap`} (no allowance)`);
147
+ return;
148
+ }
149
+ const shadow = {
150
+ input: launch.input,
151
+ title: `Audit of ${launch.title}`.slice(0, 200),
152
+ place: launch.place,
153
+ ...(launch.repo !== undefined ? { repo: launch.repo } : {}),
154
+ ...(launch.harness !== undefined ? { harness: launch.harness } : {}),
155
+ ...(launch.model ? { model: launch.model } : {}),
156
+ ...(launch.effort !== undefined ? { effort: launch.effort } : {}),
157
+ ...(allowance !== undefined ? { maxCostUsd: allowance } : {}),
158
+ ...(launch.plane ? { plane: launch.plane } : {}),
159
+ ...(launch.approvers !== undefined ? { approvers: launch.approvers } : {}),
160
+ ...(launch.documents !== undefined ? { documents: launch.documents } : {}),
161
+ ...(launch.boxAllow !== undefined ? { boxAllow: launch.boxAllow } : {}),
162
+ ...(launch.boxAllowSet ? { boxAllowSet: true } : {}),
163
+ ...(launch.archilDisk ? { archilDisk: launch.archilDisk } : {}),
164
+ audit: { of: runId, workflow: serve.name, digest: serve.digest },
165
+ };
166
+ const started = { source: "started", run: runId, shadow_run: id, workflow: serve.name, digest: serve.digest, promoted_at: promoted?.at ?? null, ...turn, at: iso((deps.now ?? Date.now)()) };
167
+ await addLines(deps, [started]);
168
+ const sealed = await handedTo(deps, runId, id);
169
+ try {
170
+ await store.runs.create({ id, agentId, revisionId: deps.revisionId }, { body: launchBody(shadow), ...(sealed ? { sealed } : {}) });
171
+ }
172
+ catch (error) {
173
+ if (error instanceof StoreConstraint && (await store.runs.get(id)))
174
+ return;
175
+ throw error;
176
+ }
177
+ log(`workflow-first: ${serve.name} at ${serve.digest} serves this run; drawn for its audit (1 in ${k}): its shadow run ${id} runs the agent on the same input`);
178
+ }
179
+ catch (error) {
180
+ log(`workflow-first: the audit of this run did not start (${error?.message ?? error})`);
181
+ }
182
+ }
183
+ /** The per_run MCP credentials run `from` was handed, sealed for shadow run `id` alone (as a replay run's are). */
184
+ async function handedTo(deps, from, id) {
185
+ if (!deps.sealKey)
186
+ return undefined;
187
+ const sealed = await deps.store.runs.launch(from).then((one) => one.sealed ?? null, () => null);
188
+ const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, from, sealed);
189
+ return handed && Object.keys(handed).length ? sealRunMcpAuth(deps.sealKey, id, handed) : undefined;
190
+ }
191
+ /** Writes the row of each open audit (a started line with no row yet) whose two runs, read by id, ended, the batch
192
+ * oldest served run first (the ledger's tail is its newest); a run that is gone (its shadow never created, say) ends it
193
+ * with no verdict. Then applies the hold rule over the ledger as it is now, rows added or not: the hold is a function of
194
+ * the ledger, so one a crash or a failed write lost after the rows were committed is made at the next claim. */
195
+ export async function settleAudits(deps) {
196
+ const { store, log } = deps;
197
+ try {
198
+ // An agent with no promotion record never served a learned workflow: it has no ledger to read.
199
+ if (!(await promotionsOf(store.settings, deps.agentId)).length)
200
+ return;
201
+ const lines = await readLedger(deps);
202
+ const now = (deps.now ?? Date.now)();
203
+ const rows = [];
204
+ for (const open of openAudits(lines)) {
205
+ const [servedRow, shadow] = [await store.runs.get(open.run), await store.runs.get(open.shadow_run)];
206
+ // Its shadow is created after its line, at the served run's claim: one missing once the served run ended never ran.
207
+ if ((servedRow && !ended(servedRow)) || (shadow && !ended(shadow)))
208
+ continue;
209
+ // One that ended where it would wait on a person (AUDIT_PARKED: an approval, a raise of its cap, a question), or
210
+ // once its cost passed its cap (the kernel's overCapEnd: it would wait on a raise), has no answer: `parked`.
211
+ const parked = shadow?.state === "failed" && ((shadow.summary ?? "").startsWith(AUDIT_PARKED) || overCapMessage(shadow.summary) !== undefined);
212
+ rows.push({ at: servedRow?.startedAt ?? 0, row: { run: open.run, shadow_run: open.shadow_run, workflow: open.workflow, digest: open.digest, promoted_at: open.promoted_at, source: "shadow", agreed: null, served_cost: servedRow?.costUsd ?? null, shadow_cost: shadow?.costUsd ?? null, ...turnOf(open.turn), ...(parked ? { parked: true } : {}), at: iso(now) } });
213
+ }
214
+ rows.sort((a, b) => a.at - b.at || (a.row.run < b.row.run ? -1 : a.row.run > b.row.run ? 1 : 0));
215
+ const { all, added } = rows.length ? await addLines(deps, rows.map(({ row }) => row), async (row) => {
216
+ const shadow = await store.runs.get(row.shadow_run);
217
+ if (shadow?.state !== "ended" || !(await store.runs.get(row.run)))
218
+ return null;
219
+ // The audited answer (the row's turn), never the run's newest: a follow-up since may have answered again.
220
+ const [a, b] = [await auditedAnswer(deps, row), await answerOf(store, row.shadow_run, deps.context)];
221
+ return a === null || b === null ? null : sameAnswer(a, b);
222
+ }) : { all: lines, added: [] };
223
+ const written = rowsOf(added);
224
+ if (written.length)
225
+ log(`workflow-first: ${written.length} audit row${written.length === 1 ? "" : "s"} written (${written.filter((row) => row.agreed === false).length} disagreeing)`);
226
+ await holdByLedger(deps, rowsOf(all));
227
+ }
228
+ catch (error) {
229
+ log(`workflow-first: the audits were not settled (${error?.message ?? error}); a later claim settles them`);
230
+ }
231
+ }
232
+ /** The row an owner's grade of served run `run` writes (source grade, agreed = the grade, counted for the digest's
233
+ * promotion now), then the hold rule: only for a run the workflow answered alone (its answer is the workflow's).
234
+ * Nothing else: no round, no compile by itself. */
235
+ export async function gradeRow(deps, run, correct) {
236
+ const m = metricsOf(run);
237
+ if (m.path !== "workflow" || typeof m.workflow !== "string" || typeof m.workflow_digest !== "string")
238
+ return;
239
+ const promoted = promotionStartOf(await promotionsOf(deps.store.settings, deps.agentId), m.workflow, m.workflow_digest);
240
+ // The answer graded: the run's newest now, kept by its row's id (as a shadow's audit keeps its turn).
241
+ const turn = turnOf((await answerRowOf(deps.store, run.id, deps.context))?.id);
242
+ const row = { run: run.id, shadow_run: null, workflow: m.workflow, digest: m.workflow_digest, promoted_at: promoted?.at ?? null, source: "grade", agreed: correct, served_cost: run.costUsd, shadow_cost: null, ...turn, at: iso((deps.now ?? Date.now)()) };
243
+ const { all } = await addLines(deps, [row], async () => correct, true);
244
+ await holdByLedger(deps, rowsOf(all));
245
+ }
246
+ /** The ledger's lines on the agent's learning folder's main. */
247
+ async function readLedger(deps) {
248
+ const folder = deps.folder();
249
+ try {
250
+ return await readLearning(folder.workspace, ledgerOf);
251
+ }
252
+ finally {
253
+ await folder.end().catch(() => undefined);
254
+ }
255
+ }
256
+ /** Appends `lines` (each not in the ledger yet, lineKey; a row's verdict read by `agreed` once it is known to be new) in
257
+ * their order, and answers the ledger after (`all`) with the lines it appended. A grade's row (`again`) replaces an
258
+ * earlier grade of the same run. */
259
+ async function addLines(deps, lines, agreed, again = false) {
260
+ const folder = deps.folder();
261
+ try {
262
+ const verdicts = new Map();
263
+ const done = await writeLearning(folder.workspace, async (read) => {
264
+ const before = (await ledgerOf(read)).filter((one) => !again || !lines.some((line) => lineKey(line) === lineKey(one)));
265
+ const known = new Set(before.map(lineKey));
266
+ const fresh = [];
267
+ for (const line of lines) {
268
+ const key = lineKey(line);
269
+ if (known.has(key))
270
+ continue;
271
+ if (line.source === "started" || !agreed) {
272
+ fresh.push(line);
273
+ continue;
274
+ }
275
+ if (!verdicts.has(key))
276
+ verdicts.set(key, await agreed(line));
277
+ fresh.push({ ...line, agreed: verdicts.get(key) });
278
+ }
279
+ const change = auditChange(before, fresh);
280
+ return { result: { all: [...before, ...change.added], added: change.added }, ...(change.change ? { change: change.change } : {}) };
281
+ });
282
+ return done.result;
283
+ }
284
+ finally {
285
+ await folder.end().catch(() => undefined);
286
+ }
287
+ }
288
+ /** The hold rule over the ledger's rows `all` for each workflow that serves now (its champion's digest), whether or not
289
+ * a row was just added: idempotent (applyHold holds only a digest whose newest record still promotes it). */
290
+ async function holdByLedger(deps, all) {
291
+ if (!all.length)
292
+ return;
293
+ const loop = await auditLoopOfRevision(deps.store, deps.revisionId);
294
+ for (const { workflow, digest } of servingOf(await promotionsOf(deps.store.settings, deps.agentId))) {
295
+ if (digest !== null)
296
+ await applyHold(deps, all, loop, workflow, digest);
297
+ }
298
+ }
299
+ /** The hold rule on `workflow` at `digest` over the ledger `rows`, when it serves now (its newest record promotes it),
300
+ * on the rows of its current promotion alone (promotionStartOf: a digest its owner's replay promoted again after a hold
301
+ * starts on none): a hold carrying `audit` with the disagreeing rows, or a stop when an earlier audit hold of the
302
+ * workflow is within stop_window served runs. Kept only while the record it read is still the digest's (of two claims,
303
+ * one holds). */
304
+ async function applyHold(deps, rows, loop, workflow, digest) {
305
+ const { store, agentId, log } = deps;
306
+ const records = await promotionsOf(store.settings, agentId);
307
+ const current = promotionOf(records, workflow, digest);
308
+ if (current?.decided !== "promote")
309
+ return;
310
+ const hold = holdOf(rows, workflow, digest, promotionStartOf(records, workflow, digest)?.at ?? null, loop);
311
+ if (!hold)
312
+ return;
313
+ const first = records.findLast((one) => one.workflow === workflow && one.decided === "hold" && one.audit !== undefined);
314
+ const since = first ? Date.parse(first.at) : undefined;
315
+ const servedSince = since === undefined ? 0 : (await servedRuns(store, agentId, loop.stop_window, workflow, undefined, (row) => row.startedAt >= since)).length;
316
+ const stopped = first !== undefined && servedSince < loop.stop_window;
317
+ // Each text cut of the host's secrets whole, then shortened (learn/secrets.ts excerptShown), as a check's are.
318
+ const shown = await deps.shown();
319
+ const cut = (text) => excerptShown(text, shown, CHECK_TEXT_MAX);
320
+ const disagreements = [];
321
+ for (const row of hold.disagreed) {
322
+ const input = await store.runs.launch(row.run).then((one) => inputText(readLaunchBody(one.body)?.input ?? null), () => "");
323
+ // The answer the row compared (its turn's), as the verdict read it: never a follow-up's since.
324
+ const draft = await auditedAnswer(deps, row);
325
+ const agent = row.shadow_run ? await answerOf(store, row.shadow_run, deps.context) : null;
326
+ disagreements.push({ run: row.shadow_run ?? row.run, served: row.run, input: cut(input), agent: agent === null ? null : cut(agent), draft: draft === null ? null : cut(draft), ...(row.source === "grade" ? { graded: true } : {}) });
327
+ }
328
+ const said = `it disagreed with the agent's own answer on ${hold.disagreed.length} of its last ${hold.rows.length} audited runs (the bar: ${loop.hold_disagree} of ${loop.hold_window})`;
329
+ const reason = stopped ? STOPPED_TWICE : `held: ${said}; the agent's next run recompiles it once with them`;
330
+ const record = {
331
+ workflow, digest, at: iso((deps.now ?? Date.now)()), decided: "hold", reason,
332
+ audit: { window: loop.hold_window, disagree: loop.hold_disagree, rows: hold.rows.length, disagreements, ...(stopped ? { stopped: true } : {}) },
333
+ ...(current.commit ? { commit: current.commit } : {}),
334
+ };
335
+ const kept = await recordPromotion(store.settings, agentId, record, (was) => was?.decided === "promote" && was.at === current.at);
336
+ if (kept.won)
337
+ log(`workflow-first: ${workflow} at ${digest} ${stopped ? `stopped (${said}, a second hold within ${loop.stop_window} served runs)` : reason}`);
338
+ }
@@ -63,8 +63,8 @@ export async function runnerBeside(dataDir, { loops, drainMs, env, janitor, hub,
63
63
  const { hostCommandRefusals } = await import("../computers.js");
64
64
  const computers = runnerComputers(store, runs, seal.key, { dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs), hostWhy: hostCommandRefusals(PROVIDERS, process.env.PATH), ...(hub ? { hub } : {}), ...(dial ? { dial } : {}) });
65
65
  // `mcpLoopback`: the server beside it is a local install (Serve.localInstall), so its runs may reach an MCP server on
66
- // loopback; any other runner's runs never do. `mcpOwn`: that server's own addresses (Serve.own), whose ports a run's
67
- // loopback read never goes to. A run's log lines (a learning run's skipped generality check) go to
66
+ // loopback; a runner in its own process does only as its own environment says (main.ts runnerLoopback). `mcpOwn`: that server's own addresses (Serve.own), whose ports a run's
67
+ // loopback read never goes to. A run's log lines (a sweep that failed) go to
68
68
  // stderr with the runner's other lines. `evalFakes`: the template eval's fakes (EvalFakes: a case's web, now, monid and
69
69
  // email), by the agent each of its runs is of; only the eval, in its own process, hands them. `harnessInstall`: what a
70
70
  // claim's first-use install installs with (the eval's sharedInstaller, which the server beside it takes too).
@@ -37,7 +37,7 @@ import { learningStartOf, seedFailed } from "../run-launch.js";
37
37
  import { readsFiles, systemOf } from "../skills.js";
38
38
  import { DATA_ENV } from "../server-fs.js";
39
39
  import { placeRunInputs } from "../uploads.js";
40
- import { runFolder, scratchFolder } from "../workspace/paths.js";
40
+ import { recordingsFolder, runFolder, scratchFolder } from "../workspace/paths.js";
41
41
  import { openRunWorkspace } from "../workspace/run-workspace.js";
42
42
  import { layOwnSkills } from "../workspace/revision-skills.js";
43
43
  import { runTools, withKindTools } from "../workspace/run-tools.js";
@@ -47,7 +47,7 @@ import { settingOfDefinition } from "../computer-setting.js";
47
47
  import { computerKeptWords, computerReadyWords, computerReplacedNote, computerStartingWords, imageWaitWords } from "../workspace/computer-deps.js";
48
48
  import { hadComputer } from "./computer-journal.js";
49
49
  import { hostLifecycle } from "./adapter-loop.js";
50
- import { adapterRunGate, answersCut, buildToolHost, capModelOf as capModelOfRoute, hostToolCtxOf, learnedTierRoutes, learnedTiers, learnedWorkflowHostTool, learnsWorkflows, modelAskOf, PI_WIRES, webHostTools } from "./adapter-run-spec.js";
50
+ import { adapterRunGate, answersCut, buildToolHost, capModelOf as capModelOfRoute, hostToolCtxOf, learnedTierRoutes, learnedTiers, learnedWorkflowHostTool, learnsWorkflows, mcpReachOf, modelAskOf, PI_WIRES, webHostTools } from "./adapter-run-spec.js";
51
51
  import { openTierProxies } from "./adapters/pi.js";
52
52
  import { signInReads } from "../sign-ins-store.js";
53
53
  import { isWebHostTool } from "../tool-list.js";
@@ -65,6 +65,7 @@ import { journalEntries } from "./journal-reader.js";
65
65
  import { hashedMcpOf, piShaped } from "../store-reads/journal.js";
66
66
  import { claimPromotion, promotionGate, replayCallsFor, replayClaimed, replayLaid, toolFlowsFor } from "./promotion.js";
67
67
  import { pathMetrics, workflowFirstOf } from "./workflow-first.js";
68
+ import { AUDIT_PARKED, settleAudits, withAudit } from "./audit.js";
68
69
  import { pastRunsOverStore, runPathOverStore } from "../store-reads/learning.js";
69
70
  import { specBuilt } from "./spec-holds.js";
70
71
  import { heldRedactor, holdClaimed, runnerSecrets, secretRedactor } from "./redact.js";
@@ -226,6 +227,8 @@ export function cliRunSpecFromLaunch(launch, run, deps, claim) {
226
227
  }
227
228
  async function cliSpec(launch, run, deps, claim, holds) {
228
229
  const context = BACKGROUND_CONTEXT;
230
+ // What this claim may reach on loopback, read once for its MCP servers and its calendar_events alike (mcpReachOf).
231
+ const reach = await mcpReachOf(deps);
229
232
  // The spec's log lines carry error text (a release, a computer, a workspace's end): cut of every secret the runner's env
230
233
  // holds.
231
234
  const cut = heldRedactor(secretRedactor(runnerSecrets(deps.env)));
@@ -314,7 +317,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
314
317
  // A credential the claim opens mid-run (a GitHub App token, a saved or per_run server's) joins the run's redactors.
315
318
  const hold = (values) => { for (const redact of [...(run.redact ? [heldRedactor(run.redact)] : []), cut])
316
319
  redact.hold(values); };
317
- const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => runFolder(deps.data, runRow.agentId, claim.runId), launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...(deps.mcpLoopback ? { loopback: true } : {}), ...(deps.mcpOwn ? { own: deps.mcpOwn } : {}) });
320
+ const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => runFolder(deps.data, runRow.agentId, claim.runId), launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...reach });
318
321
  // The claim's MCP goes to the loop, which lets it go; a build that throws lets it go itself.
319
322
  holds.hold({ passed: mcp });
320
323
  // The run's mode is the server's: Mode 2 where its Archil settings are saved (archil-settings.ts), the run's folder then
@@ -378,8 +381,9 @@ async function cliSpec(launch, run, deps, claim, holds) {
378
381
  // whose computer is a browser is refused in words at its claim, before anything is made.
379
382
  // A person's stop ends the claim's waits at once: a first image pull or registration (Agent37's runs minutes) among them.
380
383
  // Whether an earlier claim made the run a computer of its own is the run's journal's to say (hadComputer), as the pi
381
- // spec asks it. The computer a park kept, attached again, brings its mount credential with it (inheritMount).
382
- { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, refuseKind: cliRefusesKind, hadComputer: () => hadComputer(deps.journal(claim), context), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
384
+ // spec asks it. The computer a park kept, attached again, brings its mount credential with it (inheritMount). Its
385
+ // screen's recording (computer.record) goes in the run's recordings folder, as the pi spec's does.
386
+ { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, refuseKind: cliRefusesKind, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
383
387
  holds.hold({ computer });
384
388
  const loopComputer = loopComputerOf(computer.computer, computer.held, computer.made);
385
389
  const heldComputer = heldSpecOf(launch, loopComputer);
@@ -500,7 +504,8 @@ async function cliSpec(launch, run, deps, claim, holds) {
500
504
  const tierRoute = tierRoutes.get(by);
501
505
  return tierRoute && tierRoute.model === id ? capModelOfRoute(tierRoute) : undefined;
502
506
  },
503
- // What its learning runs' grades took beside it, read by every gate with its own sessions (none: it queues none).
507
+ // What its learning runs' grades and its audit's shadow took beside it, read by every gate with its own sessions
508
+ // (none: it queues none).
504
509
  ...(besideOf ? { beside: besideOf } : {}),
505
510
  // The most requests on free models it makes, capped or not (AGENTRUN_FREE_MODEL_REQUESTS).
506
511
  freeRequests: freeModelRequestsOf(deps.env),
@@ -544,13 +549,17 @@ async function cliSpec(launch, run, deps, claim, holds) {
544
549
  // The keys the claim hands the run (its web tools and its learned workflow's call nodes run on them): never learned
545
550
  // (learningEndOfRun).
546
551
  let handedKeys = [];
547
- // A replay run lays the workflow it replays record-only (runner/promotion.ts replayLaid).
552
+ // A replay run lays only the workflow it replays (runner/promotion.ts replayLaid).
548
553
  const laidFlows = replayLaid(launch, seedLaid?.workflows ?? []);
549
554
  // The learned workflow the run starts on, before its agent's first turn, when one fits its input (workflow-first.ts),
550
555
  // chosen before the learned_workflow tool is bound, so the tool runs the text that serves. Only a promoted digest
551
556
  // serves (runner/promotion.ts: replayed on the agent's graded inputs first, or promoted on its dry run with fewer than
552
557
  // five); while the folder's revision replays or is held, the champion (the digest promoted last) serves in its place
553
- // (laidFor). Or the one the money rule stopped, over the agent's past runs (costLineOf): the run asks for its revision.
558
+ // (laidFor). Or the one the money rule stopped, over the agent's past runs (costLineOf): the agent takes the run.
559
+ // The audits that finished since are written first (runner/audit.ts settleAudits): a hold they make decides this claim.
560
+ const audits = { store: deps.store, agentId: runRow.agentId, revisionId: runRow.revisionId, context, log, folder: learningFolder, shown, sealKey: deps.sealKey };
561
+ if (launch.learning && !launch.replay && !launch.audit)
562
+ await settleAudits(audits);
554
563
  const promotion = claimPromotion({
555
564
  store: deps.store, agentId: runRow.agentId, runId: claim.runId, revisionId: runRow.revisionId, launch, context, log, folder: learningFolder, shown, sealKey: deps.sealKey,
556
565
  });
@@ -583,7 +592,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
583
592
  toolEnv[TOOL_PLANE_ENV] = JSON.stringify(launch.plane);
584
593
  if (webNames.length) {
585
594
  life = hostLifecycle();
586
- const host = buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: held, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}) });
595
+ const host = buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: held, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}), ...reach });
587
596
  gate.askedOn(host);
588
597
  webTools = await webHostTools(host, granted, ctx);
589
598
  }
@@ -630,8 +639,10 @@ async function cliSpec(launch, run, deps, claim, holds) {
630
639
  // The run's end-of-run step, when it learns, the same as the pi spec's: the reflect-and-propose turn over the run's
631
640
  // store, its learning folder where the run's place keeps it — Mode 1 under the data directory, Mode 2 on this claim's
632
641
  // Archil disk — so the proposal is checked against the seed in the run's own Workspace, never this machine's local path.
633
- // A replay run asks nothing at its end: it is the promotion's, never the agent's to learn from.
634
- const endOfRun = launch.replay ? undefined : learningEndOfRun(launch, {
642
+ // A replay run or an audit's shadow run asks nothing at its end: it is the promotion's, never the agent's to learn from.
643
+ // A run the promoted workflow served first starts its shadow audit after the step, drawn at 1 in k (runner/audit.ts
644
+ // withAudit): at its end, so the shadow's cap is what the run's own left.
645
+ const endOfRun = launch.replay || launch.audit ? undefined : withAudit(learningEndOfRun(launch, {
635
646
  store: deps.store,
636
647
  data: deps.data,
637
648
  ...(deps.env ? { env: deps.env } : {}),
@@ -647,7 +658,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
647
658
  learningFolder: archil === undefined
648
659
  ? (agentId) => learningFolderOf(deps.data, agentId)
649
660
  : (agentId) => learningWorkspace({ mode: "archil", agentId, archil }),
650
- });
661
+ }), { ...audits, launch });
651
662
  return {
652
663
  adapter,
653
664
  session,
@@ -671,6 +682,8 @@ async function cliSpec(launch, run, deps, claim, holds) {
671
682
  // The web tools' install lifecycle, run by the adapter loop, as the pi spec's (they register none today).
672
683
  ...(life ? { lifecycle: life } : {}),
673
684
  agentId: runRow.agentId,
685
+ // An audit's shadow run waits on no one, as the pi spec's (runner/audit.ts AUDIT_PARKED).
686
+ ...(launch.audit ? { neverWaits: AUDIT_PARKED } : {}),
674
687
  // The run's computer and the person's hold on a desktop or phone, as the claim made them (as the pi spec gives them).
675
688
  ...(loopComputer ? { computer: loopComputer } : {}),
676
689
  // A desktop or a phone as a codemode script gets it: the script's `computer`, over the run's computer tools.
@@ -1,27 +1,21 @@
1
1
  import { type Grade } from "../learn/promote.js";
2
2
  import type { RunPath } from "../learning-cost.js";
3
3
  import { type Command, type Store } from "../store/store.js";
4
- export declare const FEEDBACK_ROUNDS: readonly ["revise", "look_back"];
4
+ export declare const FEEDBACK_ROUNDS: readonly ["look_back"];
5
5
  export type FeedbackRound = (typeof FEEDBACK_ROUNDS)[number];
6
6
  /** A feedback round, as its steer's body carries it (`feedback`) and its FEEDBACK entry keeps it: the round, whether the
7
- * grade said right, the workflow a revision is asked of, and the grade's words (`text`). */
7
+ * grade said right, and the grade's words (`text`). */
8
8
  export interface FeedbackData {
9
9
  readonly round: FeedbackRound;
10
10
  readonly correct: boolean;
11
- readonly workflow?: string;
12
11
  readonly text: string;
13
12
  }
14
- /** What a grade asks for: `revise` for a wrong grade of a run its learned workflow answered alone, `look_back` for a
15
- * graded run the agent finished when the grade has words, else none (undefined). A replay run is never graded. */
13
+ /** What a grade asks for: `look_back` for a graded run the agent finished when the grade has words, else none
14
+ * (undefined): a run its learned workflow answered alone opens none, right or wrong (its grade is kept). A replay run
15
+ * is never graded. */
16
16
  export declare function feedbackRoundOf(grade: {
17
- readonly correct: boolean;
18
17
  readonly path: RunPath;
19
- readonly workflow?: string;
20
18
  }, label: string | undefined): FeedbackRound | undefined;
21
- /** The grade's words as the round says them: its `label`, else the fields a right answer holds (`expected`), else
22
- * "(no words)". Never the verdict: feedbackAsk and the compile ask each say it once. (A right grade opens a round only
23
- * with a label (feedbackRoundOf), so none reaches here without one.) */
24
- export declare function feedbackWords(label: string | undefined, expected: Readonly<Record<string, unknown>> | undefined): string;
25
19
  /** The feedback round a steer's body asks for (`body.feedback`, the server's own: server.ts gradeRun writes it, and the
26
20
  * message API never does), else undefined. */
27
21
  export declare function feedbackOf(body: unknown): FeedbackData | undefined;
@@ -31,17 +25,8 @@ export declare function pendingFeedbackOf(entries: readonly {
31
25
  readonly kind: string;
32
26
  readonly data?: unknown;
33
27
  }[]): FeedbackData | undefined;
34
- /** What the end-of-run turn of a feedback round is told before its prompt: for a run whose agent never took the job (its
35
- * learned workflow answered alone, so its session saw nothing), the job and what the workflow answered first
36
- * (`job`, `served`); then the grade and its words. The look-back keeps notes only: a revision's ask to give the workflow
37
- * again changed is the compile turn's, after it (learning-end.ts compileAskOf reads the round, learn/compile.ts asks). */
38
- export declare function feedbackAsk(feedback: FeedbackData, seen?: {
39
- readonly job: string;
40
- readonly served: {
41
- readonly workflow: string;
42
- readonly answer: string;
43
- };
44
- }): string;
28
+ /** What the end-of-run turn of a feedback round is told before its prompt: the grade and its words. */
29
+ export declare function feedbackAsk(feedback: FeedbackData): string;
45
30
  /** How a feedback round stands (GET /runs/{id}/learning `graded.feedback_status`): `running` until it settles; `ended`,
46
31
  * its run took the grade's words and ended after them; `not_run`, its run ended before it took them. */
47
32
  export declare const FEEDBACK_STATUSES: readonly ["running", "ended", "not_run"];
@@ -65,9 +50,8 @@ export interface OpenedRound {
65
50
  readonly command: number;
66
51
  }
67
52
  /** Opens run `grade.run` again on the feedback round its grade asks for (feedbackRoundOf), with the grade's words
68
- * (`label`, else feedbackWords'), and says which, with its steer: only a run that learns (its launch's learning start,
69
- * never one that only uses what was learned, nor a notes-only run's revision ask), whose runner supports managed
70
- * feedback, neither archived nor of an archived
53
+ * (`label`), and says which, with its steer: only a run that learns (its launch's learning start,
54
+ * never one that only uses what was learned), whose runner supports managed feedback, neither archived nor of an archived
71
55
  * agent (closed history: a grade of it starts no paid work), and one the store opens again (an agentic run that answered
72
56
  * or that a person stopped). Null when the grade asks for nothing more, or the run can't be opened again (the grade is
73
57
  * kept either way). */