@parcha/agentrun-serve 0.1.0-beta.42 → 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 (81) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +8 -7
  3. package/dist/console/assets/index-BrcDSBD8.css +1 -0
  4. package/dist/console/assets/{index-DYJ_wj27.js → index-Bz6IWncl.js} +186 -186
  5. package/dist/console/index.html +2 -2
  6. package/dist/decisions.js +0 -4
  7. package/dist/import-sources.js +25 -5
  8. package/dist/learn/audit.d.ts +123 -0
  9. package/dist/learn/audit.js +159 -0
  10. package/dist/learn/compile.d.ts +50 -74
  11. package/dist/learn/compile.js +90 -124
  12. package/dist/learn/folder.d.ts +9 -0
  13. package/dist/learn/folder.js +13 -2
  14. package/dist/learn/promote.d.ts +86 -200
  15. package/dist/learn/promote.js +57 -183
  16. package/dist/learn/replay-calls.d.ts +5 -0
  17. package/dist/learn/replay-calls.js +12 -1
  18. package/dist/learn/secrets.d.ts +8 -0
  19. package/dist/learn/secrets.js +12 -0
  20. package/dist/learn/skills.js +2 -4
  21. package/dist/learn/workflow-nodes.d.ts +1 -2
  22. package/dist/learn/workflow-nodes.js +2 -3
  23. package/dist/learned-nodes.d.ts +9 -34
  24. package/dist/learned-nodes.js +11 -23
  25. package/dist/learned-workflow.d.ts +6 -8
  26. package/dist/learned-workflow.js +18 -57
  27. package/dist/learning-batch.d.ts +13 -5
  28. package/dist/learning-batch.js +34 -8
  29. package/dist/learning-cost.d.ts +11 -4
  30. package/dist/learning-cost.js +4 -2
  31. package/dist/learning-routes.js +1 -1
  32. package/dist/learning-setting.d.ts +16 -1
  33. package/dist/learning-setting.js +34 -2
  34. package/dist/openapi.js +95 -55
  35. package/dist/run-launch.d.ts +6 -3
  36. package/dist/run-launch.js +2 -0
  37. package/dist/run-learning-served.d.ts +1 -1
  38. package/dist/runner/adapter-loop.d.ts +4 -0
  39. package/dist/runner/adapter-loop.js +17 -2
  40. package/dist/runner/adapter-run-spec.js +16 -5
  41. package/dist/runner/audit.d.ts +64 -0
  42. package/dist/runner/audit.js +338 -0
  43. package/dist/runner/beside.js +1 -1
  44. package/dist/runner/cli-run-spec.js +15 -5
  45. package/dist/runner/feedback-round.js +1 -4
  46. package/dist/runner/harness-loops.js +1 -15
  47. package/dist/runner/journal-kinds.d.ts +0 -7
  48. package/dist/runner/journal-kinds.js +0 -7
  49. package/dist/runner/learning-dispatch.d.ts +0 -16
  50. package/dist/runner/learning-dispatch.js +4 -47
  51. package/dist/runner/learning-end.d.ts +52 -13
  52. package/dist/runner/learning-end.js +124 -44
  53. package/dist/runner/learning-factory.d.ts +1 -1
  54. package/dist/runner/learning-factory.js +1 -4
  55. package/dist/runner/learning-loop.d.ts +2 -38
  56. package/dist/runner/learning-loop.js +8 -116
  57. package/dist/runner/main.js +1 -1
  58. package/dist/runner/promotion.d.ts +50 -54
  59. package/dist/runner/promotion.js +191 -583
  60. package/dist/runner/reflect-hook.d.ts +10 -0
  61. package/dist/runner/reflect-hook.js +6 -0
  62. package/dist/runner/workflow-first.d.ts +6 -5
  63. package/dist/runner/workflow-first.js +17 -12
  64. package/dist/server.js +61 -16
  65. package/dist/store/sqlite/store.js +1 -0
  66. package/dist/store/store.d.ts +3 -0
  67. package/dist/store-reads/learning.d.ts +17 -6
  68. package/dist/store-reads/learning.js +36 -23
  69. package/dist/store-reads/loop.d.ts +4 -39
  70. package/dist/store-reads/loop.js +10 -79
  71. package/dist/store-view.js +12 -2
  72. package/dist/workspace/run-tools.d.ts +1 -1
  73. package/dist/workspace/run-tools.js +14 -3
  74. package/package.json +9 -9
  75. package/dist/console/assets/index-C3gNPz58.css +0 -1
  76. package/dist/learn/general.d.ts +0 -69
  77. package/dist/learn/general.js +0 -75
  78. package/dist/learn/refit.d.ts +0 -48
  79. package/dist/learn/refit.js +0 -264
  80. package/dist/runner/step-guard.d.ts +0 -62
  81. package/dist/runner/step-guard.js +0 -93
@@ -1,5 +1,5 @@
1
1
  import { type ToolRegistration } from "@earendil-works/pi-durable";
2
- import { type GuardRow, type LearnedEnded, type LearnedNode, type LoopRow } from "./learned-nodes.js";
2
+ import { type LearnedEnded, type LearnedNode, type LoopRow } from "./learned-nodes.js";
3
3
  import { type LearnedWorkflow } from "./learning.js";
4
4
  import type { ModelRef } from "./model.js";
5
5
  import { type Ledger } from "./paid-calls.js";
@@ -138,25 +138,23 @@ export declare const learnedWorkflowDescription: (workflows: readonly LearnedWor
138
138
  export declare function learnedOutput(output: unknown): string;
139
139
  /** What a learned workflow that escalated says to whoever takes the job on: the step that handed it back and its own
140
140
  * words for why, the steps it ran, and what it had found (its state's top-level fields, each whole or named by its
141
- * size). A guard that fails is a handback, never a failure of the run: the agent finishes the job from here. */
141
+ * size). An escalate is a handback, never a failure of the run: the agent finishes the job from here. */
142
142
  export declare function handedBackText(name: string, escalation: {
143
143
  kind: string;
144
144
  stage: string;
145
145
  summary: string;
146
146
  label?: string;
147
- }, state: Record<string, unknown>, nodes: readonly LearnedNode[], guards?: readonly GuardRow[]): string;
147
+ }, state: Record<string, unknown>, nodes: readonly LearnedNode[]): string;
148
148
  /** The run's `learned_workflow` tool over `run.workflows`. */
149
149
  export declare function learnedWorkflowTool(run: LearnedWorkflowRun): ToolRegistration;
150
150
  /** `flow` run on `input` for `run`: its output as its tool hands it back (learnedOutput), or why it did not run, and each of its nodes that ran (at most
151
151
  * LEARNED_NODES_MAX), none for one refused before any node ran. Never throws, but on an abort. `ledger`: the tool call's,
152
152
  * which each call node's paid requests are booked under, as a call of its own within it. `nodes`: where each node is
153
- * added as it ends, the caller's to keep when the call is aborted (and so throws) part way. `guards`: where every guard
154
- * check is added as it is made, never capped (a map's checks past the trace's cap too), the caller's to keep likewise.
155
- * `nested`: the session's tools as calls nested in this one, which its MCP nodes run as; and the values its first run
153
+ * added as it ends, the caller's to keep when the call is aborted (and so throws) part way. `nested`: the session's tools as calls nested in this one, which its MCP nodes run as; and the values its first run
156
154
  * fixed (`memo`), so a rerun of the call (after a park, a crash) goes on from what its model, decision and call nodes
157
155
  * answered then, its MCP calls with the arguments they were asked and approved with, each recorded one answered from its
158
- * record, never sent twice. `loops`: where each loop's exit is added (LoopRow), as `guards` are. */
159
- export declare function runLearned(run: LearnedWorkflowRun, flow: LearnedWorkflow, input: unknown, signal?: AbortSignal, ledger?: Ledger, nodes?: LearnedNode[], guards?: GuardRow[], nested?: NestedCalls, loops?: LoopRow[]): Promise<{
156
+ * record, never sent twice. `loops`: where each loop's exit is added (LoopRow), never capped. */
157
+ export declare function runLearned(run: LearnedWorkflowRun, flow: LearnedWorkflow, input: unknown, signal?: AbortSignal, ledger?: Ledger, nodes?: LearnedNode[], nested?: NestedCalls, loops?: LoopRow[]): Promise<{
160
158
  text: string;
161
159
  isError: boolean;
162
160
  nodes: LearnedNode[];
@@ -32,7 +32,6 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
32
32
  import { defineTool, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
33
33
  import { registerLabel, registerOutcome } from "./timeline/index.js";
34
34
  import { LEARNED_NODES, LEARNED_NODES_MAX } from "./learned-nodes.js";
35
- import { guardJevOn, guardLine, rowOf, stepGuard } from "./runner/step-guard.js";
36
35
  import { draftProblems, LEARNED_MAX_TURNS } from "./learn/index.js";
37
36
  import { decisionsAsked, deniedDecisionWords } from "./learn/skills.js";
38
37
  import { DEFAULT_DECISION_PROVIDER } from "./decisions.js";
@@ -45,7 +44,6 @@ import { allows, CALL_TOOLS, learnedDraftTools, toolOf } from "./tools.js";
45
44
  import { isMcpName } from "./tool-names.js";
46
45
  import { workflowNodes } from "./model.js";
47
46
  import { SKIPPED_WRITE, toolWord, unmarkedWords } from "./learn/replay-calls.js";
48
- import { SOFT_ESCALATE_THRESHOLD } from "./learn/promote.js";
49
47
  /** What a learned_workflow call's approval card says of its MCP actions' arguments: a `{name}` in one is filled in as
50
48
  * the workflow runs. */
51
49
  export const LEARNED_MCP_ARGUMENTS = "each {name} is filled in while the workflow runs, from its input or an earlier step";
@@ -223,24 +221,19 @@ async function sideStream(models, model, context, options) {
223
221
  * size, never cut mid-value, so the run's redactor still finds a held value in what it shows. */
224
222
  const HANDBACK_FIELDS = 20;
225
223
  const HANDBACK_VALUE = 2_000;
226
- /** The steps a learned workflow ran, as one line after its words: each node's label, kind and status; then the guards of
227
- * those steps, and any check that handed back on a step past the trace's cap (`guards`: every check of the call). */
228
- const stepsLine = (nodes, guards = []) => {
229
- const shown = nodes.flatMap(({ guard }) => (guard ? [guard] : []));
230
- const lines = [...shown, ...guards.filter((row) => row.escalated && !shown.includes(row))].map(guardLine);
231
- return (nodes.length ? `\nIts steps: ${nodes.map(({ label, kind, status }) => `${label} (${kind}) ${status}`).join("; ")}.` : "") + (lines.length ? `\nIts guards: ${lines.join("; ")}.` : "");
232
- };
224
+ /** The steps a learned workflow ran, as one line after its words: each node's label, kind and status. */
225
+ const stepsLine = (nodes) => nodes.length ? `\nIts steps: ${nodes.map(({ label, kind, status }) => `${label} (${kind}) ${status}`).join("; ")}.` : "";
233
226
  /** What a learned workflow that escalated says to whoever takes the job on: the step that handed it back and its own
234
227
  * words for why, the steps it ran, and what it had found (its state's top-level fields, each whole or named by its
235
- * size). A guard that fails is a handback, never a failure of the run: the agent finishes the job from here. */
236
- export function handedBackText(name, escalation, state, nodes, guards = []) {
228
+ * size). An escalate is a handback, never a failure of the run: the agent finishes the job from here. */
229
+ export function handedBackText(name, escalation, state, nodes) {
237
230
  const at = escalation.label ? ` at its step "${escalation.label}"` : "";
238
231
  const why = escalation.summary?.trim() || escalation.kind;
239
232
  const fields = Object.entries(state ?? {}).filter(([key]) => !key.startsWith("$")).slice(0, HANDBACK_FIELDS).map(([key, value]) => {
240
233
  const text = typeof value === "string" ? value : JSON.stringify(value) ?? "null";
241
234
  return `- ${key}: ${text.length > HANDBACK_VALUE ? `(${text.length} characters)` : text}`;
242
235
  });
243
- return [`The learned workflow ${name} handed the job back${at}: ${why}${stepsLine(nodes, guards)}`, ...(fields.length ? ["What it had:", ...fields] : [])].join("\n");
236
+ return [`The learned workflow ${name} handed the job back${at}: ${why}${stepsLine(nodes)}`, ...(fields.length ? ["What it had:", ...fields] : [])].join("\n");
244
237
  }
245
238
  /** The run's `learned_workflow` tool over `run.workflows`. */
246
239
  export function learnedWorkflowTool(run) {
@@ -267,12 +260,10 @@ export function learnedWorkflowTool(run) {
267
260
  if (!flow)
268
261
  return forModel(`No learned workflow of this agent is named ${JSON.stringify(name)}. Its workflows: ${names.join(", ")}.`, { isError: true });
269
262
  const ledger = ledgerOf(api.callId);
270
- // Which of its nodes ran, kept beside the call in the run's journal (LEARNED_NODES), for its timeline row, and every
271
- // guard check it made (`guards`, uncapped: the run's metrics, B4's replay and refit read each); a trace that can't
272
- // be kept never fails the call. A call stopped part way keeps the nodes and checks that ended before it stopped,
263
+ // Which of its nodes ran, kept beside the call in the run's journal (LEARNED_NODES), for its timeline row; a trace
264
+ // that can't be kept never fails the call. A call stopped part way keeps the nodes that ended before it stopped,
273
265
  // written outside the stopped call's context, and still ends as a stop.
274
266
  const trace = [];
275
- const guards = [];
276
267
  // Every loop's exit (`loops`, uncapped too: a quote re-pick is a loop's second pass, which the run's metrics count).
277
268
  const loops = [];
278
269
  // A replay's write the recording did not have (learn/replay-calls.ts) rides on the same entry, ran a node or not; so
@@ -281,13 +272,13 @@ export function learnedWorkflowTool(run) {
281
272
  const keep = (signal, ended) => {
282
273
  const skipped = run.replay?.skipped;
283
274
  // A loop's exit counts too: a loop over an empty map ends no node, yet its row is the run's (metrics `loops`).
284
- if (!trace.length && !guards.length && !loops.length && !skipped && !(run.replay && ended))
275
+ if (!trace.length && !loops.length && !skipped && !(run.replay && ended))
285
276
  return undefined;
286
- return api.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: LEARNED_NODES, data: { call: ledger.call, workflow: flow.name, nodes: trace, ...(guards.length ? { guards } : {}), ...(loops.length ? { loops } : {}), ...(skipped ? { replay_skipped: skipped } : {}), ...(ended ? { ended } : {}) } })), signal).catch(() => undefined);
277
+ return api.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: LEARNED_NODES, data: { call: ledger.call, workflow: flow.name, nodes: trace, ...(loops.length ? { loops } : {}), ...(skipped ? { replay_skipped: skipped } : {}), ...(ended ? { ended } : {}) } })), signal).catch(() => undefined);
287
278
  };
288
279
  let said;
289
280
  try {
290
- said = await runLearned(run, flow, input, context?.abortSignal, ledger, trace, guards, run.nestedOf?.(api.callId), loops);
281
+ said = await runLearned(run, flow, input, context?.abortSignal, ledger, trace, run.nestedOf?.(api.callId), loops);
291
282
  }
292
283
  catch (error) {
293
284
  await keep(BACKGROUND_CONTEXT);
@@ -301,13 +292,11 @@ export function learnedWorkflowTool(run) {
301
292
  /** `flow` run on `input` for `run`: its output as its tool hands it back (learnedOutput), or why it did not run, and each of its nodes that ran (at most
302
293
  * LEARNED_NODES_MAX), none for one refused before any node ran. Never throws, but on an abort. `ledger`: the tool call's,
303
294
  * which each call node's paid requests are booked under, as a call of its own within it. `nodes`: where each node is
304
- * added as it ends, the caller's to keep when the call is aborted (and so throws) part way. `guards`: where every guard
305
- * check is added as it is made, never capped (a map's checks past the trace's cap too), the caller's to keep likewise.
306
- * `nested`: the session's tools as calls nested in this one, which its MCP nodes run as; and the values its first run
295
+ * added as it ends, the caller's to keep when the call is aborted (and so throws) part way. `nested`: the session's tools as calls nested in this one, which its MCP nodes run as; and the values its first run
307
296
  * fixed (`memo`), so a rerun of the call (after a park, a crash) goes on from what its model, decision and call nodes
308
297
  * answered then, its MCP calls with the arguments they were asked and approved with, each recorded one answered from its
309
- * record, never sent twice. `loops`: where each loop's exit is added (LoopRow), as `guards` are. */
310
- export async function runLearned(run, flow, input, signal, ledger, nodes = [], guards = [], nested, loops = []) {
298
+ * record, never sent twice. `loops`: where each loop's exit is added (LoopRow), never capped. */
299
+ export async function runLearned(run, flow, input, signal, ledger, nodes = [], nested, loops = []) {
311
300
  const refuse = (why) => ({ text: `The learned workflow ${flow.name} was not run: ${why}`, isError: true, nodes, ended: "failed" });
312
301
  if (!input || typeof input !== "object" || Array.isArray(input))
313
302
  return refuse("its input must be a JSON object");
@@ -447,21 +436,8 @@ export async function runLearned(run, flow, input, signal, ledger, nodes = [], g
447
436
  const skippedWords = () => {
448
437
  const skipped = replay?.skipped;
449
438
  const why = skipped?.unmarked ? `${unmarkedWords([toolWord(skipped.tool)])}; the graded run's recording has no call of it with these arguments` : `a write, and the graded run's recording has no call of it with these arguments, so it ${SKIPPED_WRITE}`;
450
- return skipped ? { text: `The learned workflow ${flow.name} was not replayed on this input: its step "${skipped.step}" calls ${skipped.tool}, ${why}. Nothing was sent.${stepsLine(nodes, guards)}`, isError: true, nodes, ended: "failed" } : undefined;
439
+ return skipped ? { text: `The learned workflow ${flow.name} was not replayed on this input: its step "${skipped.step}" calls ${skipped.tool}, ${why}. Nothing was sent.${stepsLine(nodes)}`, isError: true, nodes, ended: "failed" } : undefined;
451
440
  };
452
- // Its step guards (runner/step-guard.ts): a guard's Jev is a decision of the call, on the run's decisions (its judge,
453
- // its gate, its one cap); a run with no Jev provider has no Jev signal, so a guard that reads one hands back.
454
- const jevProvider = run.decisions?.providers.providers.jev;
455
- const guardStep = stepGuard(runJudge && jevProvider ? guardJevOn(runJudge, jevProvider) : undefined);
456
- // Each guard's check by its step's execution path, as the DSL decided it: kept in `guards` at once (what the run's
457
- // metrics read), and its node.end (the same path) puts it on the step's trace, where the timeline and a hand-back say it.
458
- const guarded = new Map();
459
- // A replay records each escalate that reads a judge's field instead of obeying it (the DSL's softEscalates): a judge's
460
- // field is one model's opinion of a draft the workflow already wrote, so the workflow goes on to its answer, and the
461
- // escalate's row says whether it fired, for the replay's score at the serving setting (it hands back when it fired) and
462
- // the refit (it may be switched off). Every other escalate (on a call's result, a route's, the input) stops a replay as
463
- // it stops serving. Serving obeys every escalate.
464
- const soft = replay ? dsl.softEscalates(doc) : undefined;
465
441
  // Each node as it ends, by the DSL's own event: what the call's timeline row shows of it.
466
442
  const onEvent = (event) => {
467
443
  if (event.type === "loop.exited") {
@@ -470,35 +446,20 @@ export async function runLearned(run, flow, input, signal, ledger, nodes = [], g
470
446
  loops.push({ node: String(event.label), iterations: detail.iterations, met: detail.reason === "condition_met" });
471
447
  return;
472
448
  }
473
- if (event.type === "escalate.evaluated") {
474
- const detail = (event.detail ?? {});
475
- if (detail.soft === true)
476
- guards.push({ node: String(event.label), signal: "escalate", p: detail.fired === true ? 0 : 1, threshold: SOFT_ESCALATE_THRESHOLD, escalated: false });
477
- return;
478
- }
479
- if (event.type === "guard.evaluated") {
480
- const row = rowOf(String(event.label), event.detail);
481
- if (row) {
482
- guards.push(row);
483
- guarded.set(event.executionPath ?? String(event.label), row);
484
- }
485
- return;
486
- }
487
449
  if (event.type !== "node.end" || nodes.length >= LEARNED_NODES_MAX)
488
450
  return;
489
451
  const detail = (event.detail ?? {});
490
452
  const ran = typeof event.executionPath === "string" ? ranOn.get(event.executionPath) : undefined;
491
- const guard = guarded.get(event.executionPath ?? String(event.label));
492
- nodes.push({ label: String(event.label), kind: String(detail.kind ?? ""), status: String(detail.status ?? ""), duration_ms: typeof detail.duration_ms === "number" ? detail.duration_ms : 0, ...ran, ...(guard ? { guard } : {}) });
453
+ nodes.push({ label: String(event.label), kind: String(detail.kind ?? ""), status: String(detail.status ?? ""), duration_ms: typeof detail.duration_ms === "number" ? detail.duration_ms : 0, ...ran });
493
454
  };
494
455
  try {
495
456
  const judging = runJudge && run.decisions ? { runJudge, decisionProviders: run.decisions.providers } : {};
496
- const result = await dsl.runWorkflow(doc, input, { runNode: runNode, runEffect: runEffect, guardStep, onEvent, ...judging, ...(soft?.size ? { softEscalate: (label) => soft.has(label) } : {}), ...(stopped ? { signal: stopped } : {}) });
457
+ const result = await dsl.runWorkflow(doc, input, { runNode: runNode, runEffect: runEffect, onEvent, ...judging, ...(stopped ? { signal: stopped } : {}) });
497
458
  const skipped = skippedWords();
498
459
  if (skipped)
499
460
  return skipped;
500
461
  if (result.status === "escalated")
501
- return { text: learnedText(handedBackText(flow.name, result.escalation, result.state, nodes, guards)), isError: true, nodes, ended: "escalated" };
462
+ return { text: learnedText(handedBackText(flow.name, result.escalation, result.state, nodes)), isError: true, nodes, ended: "escalated" };
502
463
  if (result.status !== "complete")
503
464
  return refuse(`it ended ${result.status}`);
504
465
  return { text: learnedText(learnedOutput(result.output)), isError: false, nodes, ended: "complete" };
@@ -509,7 +470,7 @@ export async function runLearned(run, flow, input, signal, ledger, nodes = [], g
509
470
  const skipped = skippedWords();
510
471
  if (skipped)
511
472
  return skipped;
512
- return { text: `The learned workflow ${flow.name} failed: ${String(error?.message ?? error).slice(0, 1000)}${stepsLine(nodes, guards)}`, isError: true, nodes, ended: "failed" };
473
+ return { text: `The learned workflow ${flow.name} failed: ${String(error?.message ?? error).slice(0, 1000)}${stepsLine(nodes)}`, isError: true, nodes, ended: "failed" };
513
474
  }
514
475
  }
515
476
  /** A node's key among the calls and values of its learned_workflow call (NestedCalls: `<callId>/<key>`), the same in
@@ -15,7 +15,7 @@ export type Stage = "pending" | "started" | "answered" | "reviewed" | "done" | "
15
15
  /** The row machine. pending -> started: its run started under the row's key (a start the server stopped before this write
16
16
  * is found again by the key); started -> answered: the run's first end, its answer, right or wrong and the review's words
17
17
  * written once; answered -> reviewed: the review sent (a resume finds it in the run's commands and sends none); reviewed ->
18
- * done: the review's turn completed and its learning settled. Every other ending is failed, and a live row (started,
18
+ * done: the review's turn completed, its learning settled and its all-in known (its audit's shadow run ended). Every other ending is failed, and a live row (started,
19
19
  * answered, reviewed) moves to failed only once its run has stopped (cancelled, waited for with its grade, then booked). */
20
20
  export declare const ROW_MOVES: Readonly<Record<Stage, readonly Stage[]>>;
21
21
  export declare const stageOf: (row: Row) => Stage;
@@ -95,8 +95,9 @@ export type Header = {
95
95
  /** The rows' total $ (job and learning) of the rows finished, and how many of them cost nothing known. */
96
96
  spent_usd: number;
97
97
  unknown_cost_rows: number;
98
- /** Rows finished by the path their run took (a batch's run is never a replay run: runner/promotion.ts starts those). */
99
- paths: Record<Exclude<RunPath, "replay">, number>;
98
+ /** Rows finished by the path their run took (a batch's run is never a replay run nor an audit's shadow run:
99
+ * runner/promotion.ts and runner/audit.ts start those). */
100
+ paths: Record<Exclude<RunPath, "replay" | "audit">, number>;
100
101
  /** What the batch's learning kept, each name once, and the merges that touched workflows: [{row, commit, workflows}]. */
101
102
  lessons: Lessons;
102
103
  revisions: {
@@ -118,7 +119,9 @@ export type RunSnap = {
118
119
  learning_state: string | null;
119
120
  error: string | null;
120
121
  };
121
- /** What a finished run's learning and cost say (store-reads/learning.ts costRunOf, runLearningEnd): figuresOf. */
122
+ /** What a finished run's learning and cost say (store-reads/learning.ts costRunOf, runLearningEnd): figuresOf.
123
+ * `unsettled`: its all-in is not known yet, its audit's shadow run still queued or running (store-reads/learning.ts
124
+ * shadowSpendOf): a row is never closed on it, and its cost never saved, until it is. */
122
125
  export type Figures = {
123
126
  path: RunPath;
124
127
  cost_usd: number | null;
@@ -127,6 +130,7 @@ export type Figures = {
127
130
  learned: Lessons;
128
131
  merged: string | null;
129
132
  revisions: Revision[];
133
+ unsettled?: true;
130
134
  };
131
135
  /** A round's learning end as figuresOf reads it (store-reads/learning.ts RunLearningEnd): null for a round that kept none. */
132
136
  type RoundEnd = {
@@ -144,7 +148,7 @@ type RoundEnd = {
144
148
  /** A run's figures from its cost (costRunOf) and the end of each round its learning kept, in order (the job's, then each
145
149
  * follow-up's, a review's): what every round learned, each name once; the last merge's commit; and each round that merged
146
150
  * workflows as a revision of its own, with its own commit (a round dropped is none, and moves no other round's commit). */
147
- export declare function figuresOf(cost: Pick<Figures, "path" | "cost_usd" | "learning_usd" | "total_usd">, ends: readonly RoundEnd[]): Figures;
151
+ export declare function figuresOf(cost: Pick<Figures, "path" | "cost_usd" | "learning_usd" | "total_usd">, ends: readonly RoundEnd[], unsettled?: boolean): Figures;
148
152
  /** Everything the loop needs of the server, injected: the run-create path that POST /agents/{id}/runs checks and starts by,
149
153
  * the message path, the run's view, its figures. */
150
154
  export interface BatchHost {
@@ -272,6 +276,10 @@ export declare class LearningBatches {
272
276
  * review (sent once), the review's turn and look-back, the booking. Returns the header folded once the row ended; a cancel
273
277
  * or a halt leaves it live (the batch's ending stops it, or the next start takes it up). */
274
278
  private runRow;
279
+ /** The run's figures once its all-in is known (Figures.unsettled: its audit's shadow run still queued or running, whose
280
+ * cost is never read as $0), read again until then: "stop" on a halt (and a cancel, when `cancels`), "timeout" past
281
+ * `ms`. */
282
+ private allIn;
275
283
  /** A row ends failed: a live row's run is asked to stop (nothing to one that ended; a stop that fails is the loop's
276
284
  * failure, so the row stays live and owned) and waited for, with its grade, before its figures are read; one that does not
277
285
  * stop within settleMs leaves the row's cost unknown. A halt meanwhile leaves the row as it is, for the next start. */
@@ -19,7 +19,7 @@ const COLUMNS_MAX = 40;
19
19
  /** The row machine. pending -> started: its run started under the row's key (a start the server stopped before this write
20
20
  * is found again by the key); started -> answered: the run's first end, its answer, right or wrong and the review's words
21
21
  * written once; answered -> reviewed: the review sent (a resume finds it in the run's commands and sends none); reviewed ->
22
- * done: the review's turn completed and its learning settled. Every other ending is failed, and a live row (started,
22
+ * done: the review's turn completed, its learning settled and its all-in known (its audit's shadow run ended). Every other ending is failed, and a live row (started,
23
23
  * answered, reviewed) moves to failed only once its run has stopped (cancelled, waited for with its grade, then booked). */
24
24
  export const ROW_MOVES = { pending: ["started", "failed"], started: ["answered", "failed"], answered: ["reviewed", "failed"], reviewed: ["done", "failed"], done: [], failed: [] };
25
25
  const LIVE = new Set(["started", "answered", "reviewed"]);
@@ -32,11 +32,11 @@ export const BATCH_MOVES = { running: ["ending"], ending: ["completed", "cancell
32
32
  /** A run's figures from its cost (costRunOf) and the end of each round its learning kept, in order (the job's, then each
33
33
  * follow-up's, a review's): what every round learned, each name once; the last merge's commit; and each round that merged
34
34
  * workflows as a revision of its own, with its own commit (a round dropped is none, and moves no other round's commit). */
35
- export function figuresOf(cost, ends) {
35
+ export function figuresOf(cost, ends, unsettled = false) {
36
36
  const names = (pick) => [...new Set(ends.flatMap((e) => (e ? (pick(e) ?? []).map((x) => x.name) : [])))];
37
37
  const revisions = ends.flatMap((e) => (e?.workflows?.length ? [{ commit: e.merged ?? null, workflows: [...new Set(e.workflows.map((w) => w.name))] }] : []));
38
38
  const merged = [...ends].reverse().find((e) => e?.merged)?.merged ?? null;
39
- return { path: cost.path, cost_usd: cost.cost_usd, learning_usd: cost.learning_usd, total_usd: cost.total_usd, merged, revisions, learned: { notes: names((e) => e.learned), skills: names((e) => e.skills), workflows: names((e) => e.workflows) } };
39
+ return { path: cost.path, cost_usd: cost.cost_usd, learning_usd: cost.learning_usd, total_usd: cost.total_usd, merged, revisions, learned: { notes: names((e) => e.learned), skills: names((e) => e.skills), workflows: names((e) => e.workflows) }, ...(unsettled ? { unsettled: true } : {}) };
40
40
  }
41
41
  const ANSWER_SHOWN = 2_000;
42
42
  /** The least cap a run can take a step under (cap.ts: the next step needs at least a cent). */
@@ -508,25 +508,47 @@ export class LearningBatches {
508
508
  return this.fail(h, row, "the run waits on a person after its review: a batch's runs ask no one", loop);
509
509
  if (back.status !== "completed")
510
510
  return this.fail(h, row, `the review's turn ${back.status === "cancelled" ? "was cancelled" : "failed"}${back.error ? `: ${back.error}` : ""}`, loop);
511
- const f = await this.host.figures(runId);
511
+ // Closed, and its cost saved, only once its all-in is known (its audit's shadow run ended): the next row's room reads it.
512
+ const f = await this.allIn(runId, loop, true, this.host.rowTimeoutMs ?? 30 * 60_000);
513
+ if (f === "stop")
514
+ return h;
515
+ if (f === "timeout")
516
+ return this.fail(h, row, "its audit's shadow run did not end in time", loop);
512
517
  await this.move(h.id, row, "done", f ? { cost_usd: f.cost_usd, learning_usd: f.learning_usd, total_usd: f.total_usd, learned: f.learned, merged: f.merged, revisions: f.revisions } : {});
513
518
  return this.tally(h);
514
519
  }
520
+ /** The run's figures once its all-in is known (Figures.unsettled: its audit's shadow run still queued or running, whose
521
+ * cost is never read as $0), read again until then: "stop" on a halt (and a cancel, when `cancels`), "timeout" past
522
+ * `ms`. */
523
+ async allIn(runId, loop, cancels, ms) {
524
+ const started = this.clock();
525
+ for (;;) {
526
+ if (loop.halted || (cancels && loop.cancelled))
527
+ return "stop";
528
+ const f = await this.host.figures(runId);
529
+ if (!f?.unsettled)
530
+ return f;
531
+ if (this.clock() - started > ms)
532
+ return "timeout";
533
+ await sleep(this.pollMs);
534
+ }
535
+ }
515
536
  /** A row ends failed: a live row's run is asked to stop (nothing to one that ended; a stop that fails is the loop's
516
537
  * failure, so the row stays live and owned) and waited for, with its grade, before its figures are read; one that does not
517
538
  * stop within settleMs leaves the row's cost unknown. A halt meanwhile leaves the row as it is, for the next start. */
518
539
  async fail(h, row, error, loop) {
519
540
  const runId = row.run_id;
520
541
  let known = true;
542
+ const started = this.clock();
543
+ const settleMs = this.host.settleMs ?? 10 * 60_000;
521
544
  if (runId) {
522
545
  const now = await this.host.view(runId).catch(() => undefined);
523
546
  if (!now || !settled(now))
524
547
  await this.host.cancel(runId);
525
- const started = this.clock();
526
548
  for (let s = now; !(s && settled(s));) {
527
549
  if (loop.halted)
528
550
  return h;
529
- if (this.clock() - started > (this.host.settleMs ?? 10 * 60_000)) {
551
+ if (this.clock() - started > settleMs) {
530
552
  known = false;
531
553
  break;
532
554
  }
@@ -534,7 +556,11 @@ export class LearningBatches {
534
556
  s = await this.host.view(runId).catch(() => undefined);
535
557
  }
536
558
  }
537
- const f = runId && known ? await this.host.figures(runId).catch(() => undefined) : undefined;
559
+ // And its audit's shadow run, within the same time: an all-in not known by then is booked unknown, never short.
560
+ const all = runId && known ? await this.allIn(runId, loop, false, Math.max(0, settleMs - (this.clock() - started))).catch(() => undefined) : undefined;
561
+ if (all === "stop")
562
+ return h;
563
+ const f = all === "timeout" ? undefined : all;
538
564
  await this.move(h.id, row, "failed", { error: error.slice(0, 400), total_usd: runId ? (f?.total_usd ?? null) : 0, ...(f ? { path: row.path ?? f.path, cost_usd: f.cost_usd, learning_usd: f.learning_usd, learned: f.learned, merged: f.merged, revisions: f.revisions } : {}) });
539
565
  return this.tally(h);
540
566
  }
@@ -557,7 +583,7 @@ export class LearningBatches {
557
583
  if (row.run_id && (row.total_usd === null || row.total_usd === undefined))
558
584
  next.unknown_cost_rows++;
559
585
  spent += row.total_usd ?? 0;
560
- if (row.path && row.path !== "replay")
586
+ if (row.path && row.path !== "replay" && row.path !== "audit")
561
587
  next.paths[row.path]++;
562
588
  for (const kind of ["notes", "skills", "workflows"])
563
589
  for (const name of row.learned?.[kind] ?? [])
@@ -3,9 +3,11 @@
3
3
  * rule for a run with nothing new to look back on, runner/learning-end.ts onlyLearnedWorkflows); `handed_back`, a
4
4
  * learned workflow ran and the agent went on (it handed back, failed, escalated, or the agent did more work after it);
5
5
  * `agent`, no learned workflow ran; `replay`, a replay run deciding whether a learned workflow's new revision serves
6
- * (runner/promotion.ts: the workflow alone on a graded run's input, at workflow cost). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
6
+ * (runner/promotion.ts: the workflow alone on a graded run's input, at workflow cost); `audit`, a shadow run auditing a
7
+ * run a learned workflow served (runner/audit.ts: the agent on its input with learning off; its cost is that run's
8
+ * learning). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
7
9
  * record at its end (metrics.path). */
8
- export declare const RUN_PATHS: readonly ["agent", "handed_back", "workflow", "replay"];
10
+ export declare const RUN_PATHS: readonly ["agent", "handed_back", "workflow", "replay", "audit"];
9
11
  export type RunPath = (typeof RUN_PATHS)[number];
10
12
  /** What a run that looked back kept of its costs as it answered (runner/reflect-hook.ts: store-reads/learning.ts
11
13
  * answeredOf): when the job answered, what it had cost by then and what looking back cost after it. */
@@ -53,13 +55,18 @@ export declare const COST_WINDOW = 10;
53
55
  /** The latest runs the route answers by default, and at most. */
54
56
  export declare const COST_RUNS_DEFAULT = 1000;
55
57
  export declare const COST_RUNS_MAX = 10000;
56
- /** The serving promotion's replay (store-reads/learning.ts servingReplayOf): on `n` inputs, the workflow's accuracy and the
57
- * agent's in percent to a tenth, and whether it `cleared` the bar promotion reads (learn/promote.ts withinBar). */
58
+ /** The serving promotion's check (store-reads/learning.ts servingReplayOf): on `n` inputs, the workflow's agreement and the
59
+ * agent's own in percent to a tenth, whether it `cleared` the bar (learn/promote.ts checkPasses), and the agreement check
60
+ * itself: `agreed` of the `alone` inputs it answered alone said what the agent said, against the bar `agree_min` (0-1).
61
+ * Passing that bar is all it says: never that the workflow is as accurate as the agent. */
58
62
  export type CostReplay = {
59
63
  n: number;
60
64
  workflow_pct: number;
61
65
  agent_pct: number;
62
66
  cleared: boolean;
67
+ agreed: number;
68
+ alone: number;
69
+ agree_min: number;
63
70
  };
64
71
  /** The paths a learned workflow served a run on: it ran first and answered alone (`workflow`) or handed back
65
72
  * (`handed_back`). A `replay` checks a new revision on a graded input and serves no one; an `agent` run is by hand. */
@@ -10,9 +10,11 @@ import { ApiError } from "./errors.js";
10
10
  * rule for a run with nothing new to look back on, runner/learning-end.ts onlyLearnedWorkflows); `handed_back`, a
11
11
  * learned workflow ran and the agent went on (it handed back, failed, escalated, or the agent did more work after it);
12
12
  * `agent`, no learned workflow ran; `replay`, a replay run deciding whether a learned workflow's new revision serves
13
- * (runner/promotion.ts: the workflow alone on a graded run's input, at workflow cost). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
13
+ * (runner/promotion.ts: the workflow alone on a graded run's input, at workflow cost); `audit`, a shadow run auditing a
14
+ * run a learned workflow served (runner/audit.ts: the agent on its input with learning off; its cost is that run's
15
+ * learning). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
14
16
  * record at its end (metrics.path). */
15
- export const RUN_PATHS = ["agent", "handed_back", "workflow", "replay"];
17
+ export const RUN_PATHS = ["agent", "handed_back", "workflow", "replay", "audit"];
16
18
  const usd = (value) => Math.round(value * 1e6) / 1e6;
17
19
  /** A run's own cost and what learning added for it, from its row's cost (`rowUsd`: the job, its look-back and any turn a
18
20
  * person asked of it after), what it kept as it answered (`looked`, none for a run that did not look back) and what its
@@ -254,7 +254,7 @@ export async function workflowRevisions(data, agentId, name, query, shown) {
254
254
  const texts = await textsAt(ws, change.commit, [path]).catch((error) => { throw routeFailure(error); });
255
255
  const raw = texts?.[path];
256
256
  // Its digest, read from the text as it is (workflow-first.ts workflowDigest's): the one a run's metrics and the
257
- // promotion records name, so a revision's runs, guards and promotion are found by it.
257
+ // promotion records name, so a revision's runs and promotion are found by it.
258
258
  revisions.push({ commit: change.commit, at: change.at, by: change.by, reason: shown.text(change.reason), text: raw === undefined ? null : shown.text(raw), digest: raw === undefined ? null : createHash("sha256").update(raw).digest("hex").slice(0, 16) });
259
259
  }
260
260
  return { revisions, total: touched.length, truncated: snapshot.log_more };
@@ -3,7 +3,17 @@ export interface LearningLoop {
3
3
  readonly compile_after?: number;
4
4
  readonly agree_min?: number;
5
5
  readonly alone_min?: number;
6
+ readonly audit_every?: number;
7
+ readonly audit_every_later?: number;
8
+ readonly audit_later_after?: number;
9
+ readonly hold_window?: number;
10
+ readonly hold_disagree?: number;
11
+ readonly stop_window?: number;
6
12
  }
13
+ /** The check's numbers (runner/promotion.ts): what a check record keeps of the loop. */
14
+ export type CheckLoop = Required<Pick<LearningLoop, "compile_after" | "agree_min" | "alone_min">>;
15
+ /** The audit's numbers (runner/audit.ts). */
16
+ export type AuditLoop = Required<Pick<LearningLoop, "audit_every" | "audit_every_later" | "audit_later_after" | "hold_window" | "hold_disagree" | "stop_window">>;
7
17
  /** A definition's `learning`, as kept on an agentic revision. */
8
18
  export type LearningSetting = boolean | "notes" | LearningLoop;
9
19
  export declare const COMPILE_AFTER_DEFAULT = 20;
@@ -11,10 +21,15 @@ export declare const AGREE_MIN_DEFAULT = 0.8;
11
21
  export declare const ALONE_MIN_DEFAULT = 0.7;
12
22
  /** The most completed runs a compile may wait for: the newest this many of an agent's runs are what it counts and checks. */
13
23
  export declare const COMPILE_AFTER_MAX = 200;
24
+ export declare const AUDIT_DEFAULTS: AuditLoop;
25
+ /** The most any audit number may be: 1 in 1,000 runs, a window of 1,000 (the ledger keeps more rows than that). */
26
+ export declare const AUDIT_MAX = 1000;
14
27
  /** Whether `learning` has the agent's runs learn workflows too (true, or an object): never "notes", false or absent. */
15
28
  export declare const learnsWorkflowsOf: (learning: unknown) => boolean;
16
29
  /** The loop's numbers for a revision's `learning`: its object's, each one it leaves out at its default. */
17
- export declare function loopOf(learning: unknown): Required<LearningLoop>;
30
+ export declare function loopOf(learning: unknown): CheckLoop;
31
+ /** The audit's numbers for a revision's `learning`: its object's, each one it leaves out at its default (AUDIT_DEFAULTS). */
32
+ export declare function auditLoopOf(learning: unknown): AuditLoop;
18
33
  /** What is wrong with a definition's `learning`, in words naming the field (`at` its path), or undefined when it is one
19
34
  * of true, false, "notes" or an object of the loop's numbers. */
20
35
  export declare function learningSettingIssue(value: unknown, at?: string): string | undefined;
@@ -5,12 +5,31 @@
5
5
  // it answered alone, at least this share say what the agent's own recorded answer said;
6
6
  // alone_min (S): ...and when it answered at least this share of them alone (no escalate, no failed step).
7
7
  // learn/compile.ts compileDue reads compile_after; runner/promotion.ts's check reads all three.
8
+ // Once a workflow serves, its shadow audit (runner/audit.ts) reads the other six:
9
+ // audit_every (k): a run it serves is audited at 1 in k, drawn from the run's id (learn/audit.ts auditDrawn);
10
+ // audit_every_later, audit_later_after: 1 in this many once the digest served audit_later_after runs;
11
+ // hold_window, hold_disagree: it stops serving (a hold) when its last hold_window audit rows hold at least
12
+ // hold_disagree disagreements;
13
+ // stop_window: a second hold within this many served runs of the first stops it for good.
8
14
  export const COMPILE_AFTER_DEFAULT = 20;
9
15
  export const AGREE_MIN_DEFAULT = 0.8;
10
16
  export const ALONE_MIN_DEFAULT = 0.7;
11
17
  /** The most completed runs a compile may wait for: the newest this many of an agent's runs are what it counts and checks. */
12
18
  export const COMPILE_AFTER_MAX = 200;
13
- const LOOP_KEYS = ["compile_after", "agree_min", "alone_min"];
19
+ export const AUDIT_DEFAULTS = { audit_every: 10, audit_every_later: 20, audit_later_after: 50, hold_window: 10, hold_disagree: 3, stop_window: 100 };
20
+ /** The most any audit number may be: 1 in 1,000 runs, a window of 1,000 (the ledger keeps more rows than that). */
21
+ export const AUDIT_MAX = 1_000;
22
+ const AUDIT_KEYS = ["audit_every", "audit_every_later", "audit_later_after", "hold_window", "hold_disagree", "stop_window"];
23
+ const LOOP_KEYS = ["compile_after", "agree_min", "alone_min", ...AUDIT_KEYS];
24
+ /** Each audit number's words, for its 422. */
25
+ const AUDIT_WORDS = {
26
+ audit_every: "audits 1 in this many served runs",
27
+ audit_every_later: "audits 1 in this many served runs once audit_later_after served",
28
+ audit_later_after: "is the served runs after which audit_every_later applies",
29
+ hold_window: "is the audit rows the hold rule reads",
30
+ hold_disagree: "is the disagreements in hold_window rows that hold the workflow",
31
+ stop_window: "is the served runs within which a second hold stops the workflow",
32
+ };
14
33
  const isLoop = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
15
34
  /** Whether `learning` has the agent's runs learn workflows too (true, or an object): never "notes", false or absent. */
16
35
  export const learnsWorkflowsOf = (learning) => learning === true || isLoop(learning);
@@ -23,13 +42,18 @@ export function loopOf(learning) {
23
42
  alone_min: set.alone_min ?? ALONE_MIN_DEFAULT,
24
43
  };
25
44
  }
45
+ /** The audit's numbers for a revision's `learning`: its object's, each one it leaves out at its default (AUDIT_DEFAULTS). */
46
+ export function auditLoopOf(learning) {
47
+ const set = isLoop(learning) ? learning : {};
48
+ return Object.fromEntries(AUDIT_KEYS.map((key) => [key, set[key] ?? AUDIT_DEFAULTS[key]]));
49
+ }
26
50
  /** What is wrong with a definition's `learning`, in words naming the field (`at` its path), or undefined when it is one
27
51
  * of true, false, "notes" or an object of the loop's numbers. */
28
52
  export function learningSettingIssue(value, at = "learning") {
29
53
  if (typeof value === "boolean" || value === "notes")
30
54
  return undefined;
31
55
  if (!isLoop(value))
32
- return `${at} is true, false, "notes" or an object of the loop's numbers ({compile_after?, agree_min?, alone_min?}, on with those set)`;
56
+ return `${at} is true, false, "notes" or an object of the loop's numbers ({${LOOP_KEYS.map((key) => `${key}?`).join(", ")}}, on with those set)`;
33
57
  const other = Object.keys(value).find((key) => !LOOP_KEYS.includes(key));
34
58
  if (other !== undefined)
35
59
  return `${at}.${other} is not one of the loop's numbers: ${LOOP_KEYS.join(", ")}`;
@@ -40,6 +64,14 @@ export function learningSettingIssue(value, at = "learning") {
40
64
  if (share !== undefined && !(typeof share === "number" && Number.isFinite(share) && share >= 0 && share <= 1))
41
65
  return `${at}.${key} is a share from 0 to 1`;
42
66
  }
67
+ for (const key of AUDIT_KEYS) {
68
+ const n = value[key];
69
+ if (n !== undefined && !(Number.isInteger(n) && n >= 1 && n <= AUDIT_MAX))
70
+ return `${at}.${key} ${AUDIT_WORDS[key]}: a whole number from 1 to ${AUDIT_MAX}`;
71
+ }
72
+ const audit = auditLoopOf(value);
73
+ if (audit.hold_disagree > audit.hold_window)
74
+ return `${at}.hold_disagree is at most hold_window (${audit.hold_window}): the disagreements are counted in that many rows`;
43
75
  return undefined;
44
76
  }
45
77
  /** A valid `learning` as a revision keeps it: an object's numbers in one order, so two definitions that say the same are