@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
@@ -75,6 +75,16 @@ export interface ReflectDeps {
75
75
  outcome: "completed" | "failed";
76
76
  refuse: readonly string[];
77
77
  }) => Promise<CompileAsk | undefined>;
78
+ /** Compile once: a compile turn whose drafts all failed their checks (one answered, none passed) is the compile's
79
+ * attempt, kept on a promotion record (learning-end.ts recordDraftFailed) that compileFacts reads. Its `workflow` and
80
+ * `errors` come cut of `refuse`. Absent: none kept. */
81
+ readonly compileFailed?: (input: {
82
+ runId: string;
83
+ agentId: string;
84
+ compile: CompileAsk;
85
+ workflow: string;
86
+ errors: readonly string[];
87
+ }) => Promise<void>;
78
88
  /** The compile turn's deadline, every attempt in it. Default learn/compile.ts COMPILE_TIMEOUT_MS. */
79
89
  readonly compileDeadlineMs?: number;
80
90
  /** What the person said in the run, and a trigger's input, as the checks and the grader read them. */
@@ -237,6 +237,12 @@ export function createReflectHook(deps) {
237
237
  : checked.reason === "checker" ? { ...checked, problems: [...checked.problems, ...problems] }
238
238
  : checked;
239
239
  compiled = { record: result.record, draft_errors: result.draftErrors };
240
+ // Compile once: its failed drafts are the compile's attempt, on record before the learning closes. The draft's
241
+ // name and errors are the model's words: cut of `refuse` as the proposal row is (cutRow) before they are saved
242
+ // on the promotion record or logged, whose reads cut only the server's secrets, never this run's.
243
+ const cut = (text) => redactSecrets(text, refuse, Number.POSITIVE_INFINITY);
244
+ if (result.drafted && deps.compileFailed)
245
+ await deps.compileFailed({ runId: input.runId, agentId: input.agentId, compile, workflow: cut(result.record.workflow), errors: result.draftErrors.map(cut) }).catch(() => undefined);
240
246
  }
241
247
  }
242
248
  const compiledFields = compiled ? { compiled: compiled.record, ...(compiled.draft_errors?.length ? { draft_errors: compiled.draft_errors } : {}) } : {};
@@ -2,7 +2,7 @@ import { type LearnedWorkflow } from "../learning.js";
2
2
  import type { RunLaunch } from "../run-launch.js";
3
3
  import { COST_WINDOW, type RunPath } from "../learning-cost.js";
4
4
  export { COST_WINDOW };
5
- import { type GuardRow, type LoopRow } from "../learned-nodes.js";
5
+ import { type LoopRow } from "../learned-nodes.js";
6
6
  import type { Skipped } from "../learn/replay-calls.js";
7
7
  /** The root entry a run served workflow-first keeps, once the workflow's call ended: which workflow, at which learned
8
8
  * revision, under which call, and how it ended. A later claim that finds it never runs the workflow again. */
@@ -162,9 +162,9 @@ export declare function servedOf(entries: readonly {
162
162
  /** The run-record fields a learning run's metrics carry, from the run-end classifier's `classified` path
163
163
  * (runPathOverStore): the path it took, the learned revision it ran on, the learned workflow it ran (served first, or
164
164
  * called by its agent) and, for one served first, its digest and the promotion it served under (`workflow_promotion`,
165
- * which its grade keeps); and from its root `entries`, each step guard's check of its learned workflows' calls
166
- * (`guards`, learned-nodes.ts guardsOf) and each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second
167
- * pass), when one ran. learning-cost reads path and workflow from here. None for a run that does not learn. */
165
+ * which its grade keeps), and `not_auditable` when a trigger started it (never audited); and from its root `entries`,
166
+ * each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second pass), when one ran. learning-cost reads path
167
+ * and workflow from here. None for a run that does not learn. */
168
168
  export declare function pathMetrics(launch: RunLaunch, classified: {
169
169
  path: RunPath;
170
170
  workflow: string | null;
@@ -179,9 +179,10 @@ export declare function pathMetrics(launch: RunLaunch, classified: {
179
179
  workflow?: string;
180
180
  workflow_digest?: string;
181
181
  workflow_promotion?: number;
182
- guards?: GuardRow[];
182
+ not_auditable?: true;
183
183
  loops?: LoopRow[];
184
184
  replay?: ReplayMetrics;
185
+ audit?: NonNullable<RunLaunch["audit"]>;
185
186
  };
186
187
  /** A replay run's record (metrics.replay): the graded run it replayed and how its workflow ended there. */
187
188
  export type ReplayMetrics = {
@@ -1,12 +1,12 @@
1
1
  // workflow-first: a run of an agent whose learned revision holds one active workflow fitting the run's input starts on
2
2
  // that workflow, with no turn of the agent's model (a JIT's compiled path: the agent is the interpreter, the workflow is
3
- // the code it compiled, its escalate nodes are guards). The workflow answering is the run's answer; the workflow handing
3
+ // the code it compiled, its escalate nodes hand a case back). The workflow answering is the run's answer; the workflow handing
4
4
  // the job back (it escalated, a node failed, its output failed its schema) is a deopt: the same run goes on as an
5
5
  // agentic run, the agent handed the workflow's trace, and the handback feeds the agent's next revision.
6
6
  //
7
7
  // The choice here is structural, never semantic: a workflow fits when its input schema has at least one required field
8
8
  // and the run's input passes it at the top level (validate.ts inputIssues, the check a run's input gets at start). Whether
9
- // the workflow can do the job is its own guards' call, never the engine's. Exactly one fitting active workflow serves;
9
+ // the workflow can do the job is its own escalate nodes' call, never the engine's. Exactly one fitting active workflow serves;
10
10
  // none, or more than one (said in one log line), leaves the run to the agent. A launch's `workflowFirst: false` (RunCreate
11
11
  // `workflow_first`) forces the agent path. A handback is an escalation, never a failure: it asks for no revision (one run
12
12
  // is one sample; a revision is asked only of a workflow its promotion holds), and never keeps the workflow from serving.
@@ -26,11 +26,12 @@
26
26
  // the first input), through the run's own learned_workflow tool, gate, record and ledger.
27
27
  import { createHash } from "node:crypto";
28
28
  import { LEARNING_LABEL } from "../learning.js";
29
- import { COST_WINDOW } from "../learning-cost.js";
29
+ import { COST_WINDOW, SERVED_PATHS } from "../learning-cost.js";
30
+ import { auditableLaunch } from "../learn/audit.js";
30
31
  export { COST_WINDOW };
31
32
  import { KINDS } from "./journal-kinds.js";
32
33
  import { inputIssues, isObject } from "../validate.js";
33
- import { endedIn, guardsOf, loopsOf, replaySkippedIn } from "../learned-nodes.js";
34
+ import { endedIn, loopsOf, replaySkippedIn } from "../learned-nodes.js";
34
35
  import { sameAnswer } from "../learn/promote.js";
35
36
  /** The root entry a run served workflow-first keeps, once the workflow's call ended: which workflow, at which learned
36
37
  * revision, under which call, and how it ended. A later claim that finds it never runs the workflow again. */
@@ -65,7 +66,7 @@ export function costLineOf(past, name, digest) {
65
66
  }
66
67
  const agent = newest.filter((run) => pathFields(run.metrics).path === "agent");
67
68
  const first = Math.min(...newest.filter(ran).map((run) => run.startedAt));
68
- const hand = agent.some(known) ? agent : newest.filter((run) => run.startedAt < first && !SERVED.includes(pathFields(run.metrics).path) && pathFields(run.metrics).path !== "replay");
69
+ const hand = agent.some(known) ? agent : newest.filter((run) => run.startedAt < first && !SERVED.includes(pathFields(run.metrics).path) && pathFields(run.metrics).path !== "replay" && pathFields(run.metrics).path !== "audit");
69
70
  const byHand = hand.filter(known).map((run) => run.allInUsd);
70
71
  return { served: meanOf(served) ?? { runs: 0, mean_usd: null }, by_hand: meanOf(byHand), unknown_runs: servedUnknown + hand.length - byHand.length };
71
72
  }
@@ -222,21 +223,23 @@ export function servedOf(entries) {
222
223
  /** The run-record fields a learning run's metrics carry, from the run-end classifier's `classified` path
223
224
  * (runPathOverStore): the path it took, the learned revision it ran on, the learned workflow it ran (served first, or
224
225
  * called by its agent) and, for one served first, its digest and the promotion it served under (`workflow_promotion`,
225
- * which its grade keeps); and from its root `entries`, each step guard's check of its learned workflows' calls
226
- * (`guards`, learned-nodes.ts guardsOf) and each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second
227
- * pass), when one ran. learning-cost reads path and workflow from here. None for a run that does not learn. */
226
+ * which its grade keeps), and `not_auditable` when a trigger started it (never audited); and from its root `entries`,
227
+ * each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second pass), when one ran. learning-cost reads path
228
+ * and workflow from here. None for a run that does not learn. */
228
229
  export function pathMetrics(launch, classified, entries = []) {
230
+ // A shadow run (runner/audit.ts): path `audit` and the run it audits, whatever it did: no learning, no money rule.
231
+ if (launch.audit)
232
+ return { path: "audit", audit: { of: launch.audit.of, workflow: launch.audit.workflow, digest: launch.audit.digest } };
229
233
  if (!launch.learning)
230
234
  return {};
231
235
  const { path, workflow, digest, promotion } = classified ?? { path: "agent", workflow: null };
232
- const guards = guardsOf(entries);
233
236
  const loops = loopsOf(entries);
234
- const rows = { ...(guards.length ? { guards } : {}), ...(loops.length ? { loops } : {}) };
237
+ const rows = loops.length ? { loops } : {};
235
238
  if (launch.replay) {
236
239
  // A replay run (runner/promotion.ts): path `replay`, whatever its workflow did, so the money rule and the agent's
237
240
  // by-hand cost never read it; how its workflow ended, for the replay's score (learn/promote.ts ReplayRow).
238
241
  const { of, workflow: name, digest: at } = launch.replay;
239
- // Handed back when the workflow ended escalated (an escalate node or a guard: the workflow knowing its limits), however
242
+ // Handed back when the workflow ended escalated (an escalate node: the workflow knowing its limits), however
240
243
  // many of its nodes failed on the way and were recovered (a map's collected item); a workflow that itself ended failed
241
244
  // (a credential or tool the replay ran without, a step's output off its schema), or was refused, is failed: no
242
245
  // evidence. Skipped when a write it needed is not in the graded run's recording (learn/replay-calls.ts): never run.
@@ -244,7 +247,9 @@ export function pathMetrics(launch, classified, entries = []) {
244
247
  const outcome = skipped ? "skipped_write" : path === "workflow" && workflow === name ? "answered" : path === "handed_back" && workflow === name && endedIn(entries, name) === "escalated" ? "handed_back" : "failed";
245
248
  return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...rows, replay: { of, outcome, ...(skipped ? { skipped } : {}) } };
246
249
  }
247
- return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...rows };
250
+ // A served run a trigger started (learn/audit.ts auditableLaunch) is never audited: counted on the promotions read.
251
+ const notAuditable = SERVED_PATHS.includes(path) && !auditableLaunch(launch);
252
+ return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...(notAuditable ? { not_auditable: true } : {}), ...rows };
248
253
  }
249
254
  /** What run `entries` (its root's) say its learned workflow answered alone: the workflow and its answer (the model's
250
255
  * message written just before the WORKFLOW_FIRST entry, in its commit); undefined for a run it did not answer. A follow-up that opens such a
package/dist/server.js CHANGED
@@ -84,8 +84,11 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
84
84
  import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
85
85
  import { answerOf, logged } from "./agents.js";
86
86
  import { keepGrade } from "./runner/feedback-round.js";
87
+ import { gradeRow, notAuditableOf } from "./runner/audit.js";
88
+ import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf } from "./learn/audit.js";
89
+ import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
87
90
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
88
- import { GRADE_SOURCES, GRADES_KEPT, gradeView, LABEL_MAX, promotionsOf, promotionsShown } from "./learn/promote.js";
91
+ import { GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf } from "./learn/promote.js";
89
92
  import { runModelRef } from "./model.js";
90
93
  import { REDACTED } from "./secret-cut.js";
91
94
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
@@ -106,7 +109,7 @@ import { DRAIN_TIMEOUT } from "./runner/beside.js";
106
109
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
107
110
  import { agentLoopOverStore } from "./store-reads/loop.js";
108
111
  import { printable } from "./learn/index.js";
109
- import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd } from "./store-reads/learning.js";
112
+ import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd, shadowSpendOf } from "./store-reads/learning.js";
110
113
  import { figuresOf, LearningBatches } from "./learning-batch.js";
111
114
  import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
112
115
  import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
@@ -401,6 +404,7 @@ export const ROUTES = [
401
404
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
402
405
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
403
406
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/promotions$/, name: "listLearningPromotions" },
407
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/audits$/, name: "listLearningAudits" },
404
408
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "createLearningBatch" },
405
409
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "listLearningBatches" },
406
410
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)$/, name: "getLearningBatch" },
@@ -1351,8 +1355,9 @@ async function startHolding(options, data, checked, stops) {
1351
1355
  // Every round the run kept (a review follow-up opens a round of its own), in order: what each one learned and merged.
1352
1356
  const newest = await store.learning.proposal(runId);
1353
1357
  const ends = await Promise.all(Array.from({ length: newest?.round ?? 1 }, (_, i) => runLearningEnd(store, runId, i + 1)));
1354
- // A run still going names no path yet (its end writes it): the batch reads it as the agent's until then.
1355
- return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends);
1358
+ // A run still going names no path yet (its end writes it): the batch reads it as the agent's until then. Its all-in
1359
+ // is not known while its audit's shadow run is queued or running (shadowSpendOf): the batch closes no row on it.
1360
+ return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends, (await shadowSpendOf(store, runId)).open);
1356
1361
  },
1357
1362
  // A batch's reads are the learning routes' reads: the same cut, the same 403 when a sign-in can't be read here.
1358
1363
  shown: (agentId) => learningShown(agentId),
@@ -1371,6 +1376,16 @@ async function startHolding(options, data, checked, stops) {
1371
1376
  return [...serverSecrets(), ...pointers];
1372
1377
  };
1373
1378
  const learningShown = async (agentId) => secretsShown(await learningValues(agentId));
1379
+ // The agent's audit ledger on its learning folder's main (learn/audit.ts), oldest first.
1380
+ const auditsOfAgent = async (agentId) => {
1381
+ const { workspace, end } = learningFolderOf(data, agentId);
1382
+ try {
1383
+ return await readAudits(workspace);
1384
+ }
1385
+ finally {
1386
+ await end().catch(() => undefined);
1387
+ }
1388
+ };
1374
1389
  // What a run held for its owner's OK reads as it stands on its agent's learning folder's main (statusesOf).
1375
1390
  const statuses = (agentId) => statusesOf(data, agentId);
1376
1391
  const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses });
@@ -1781,7 +1796,7 @@ async function startHolding(options, data, checked, stops) {
1781
1796
  const learning = await learningOfAgent(entry);
1782
1797
  const native = nativeOf(entry.revision?.body);
1783
1798
  const nativeStatus = native?.remote ? await new RemoteConnectors(store).status(native) : undefined;
1784
- const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
1799
+ const runs = (await listRunsOverStore(store, { agent: entry.agent.id }, ctx)).filter((run) => !isShadowRun(run.id));
1785
1800
  return {
1786
1801
  ...(nativeStatus ? { nativeStatus } : {}),
1787
1802
  signIns: await signIns.view(entry.agent.id),
@@ -2561,7 +2576,8 @@ async function startHolding(options, data, checked, stops) {
2561
2576
  // `label=<key>:<value>`, once: only the runs holding it (run-labels.ts), filtered in the store.
2562
2577
  const labels = labelFilter(url.searchParams.getAll("label"));
2563
2578
  const vd = viewDepsFor(origin);
2564
- let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
2579
+ // An audit's shadow run is no row of the list (learn/audit.ts): it is read by id, and its cost is its served run's.
2580
+ let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived && !isShadowRun(row.id));
2565
2581
  if (status !== null) {
2566
2582
  // The v2 status is the run view's (store-view over the journal), per row.
2567
2583
  const statuses = await Promise.all(rows.map((row) => viewOverStore(store, row.id, vd).then((v) => v?.status)));
@@ -3523,6 +3539,8 @@ async function startHolding(options, data, checked, stops) {
3523
3539
  const m = (isObject(row.metrics) ? row.metrics : {});
3524
3540
  if (m.path === "replay")
3525
3541
  throw invalid([{ field: "run_id", reason: "not_allowed", message: "A replay run is never graded: its answer is scored against the run it replays." }]);
3542
+ if (m.path === "audit" || isShadowRun(row.id))
3543
+ throw invalid([{ field: "run_id", reason: "not_allowed", message: "An audit's shadow run is never graded: grade the run it audits." }]);
3526
3544
  const path = RUN_PATHS.includes(m.path) ? m.path : "agent";
3527
3545
  const grade = {
3528
3546
  run: row.id, correct: body.correct, ...(body.expected !== undefined ? { expected: body.expected } : {}), source: body.source ?? "feedback", at: new Date().toISOString(), path,
@@ -3531,6 +3549,10 @@ async function startHolding(options, data, checked, stops) {
3531
3549
  };
3532
3550
  // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
3533
3551
  const kept = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined));
3552
+ // A grade of a run its learned workflow answered alone is an audit row too (runner/audit.ts gradeRow): the hold rule
3553
+ // reads it with the shadows'. A row not written now is logged, never the grade refused.
3554
+ const said = (line) => log?.(logLine("audit", { run: row.id, said: line }));
3555
+ await gradeRow({ store, agentId: row.agentId, revisionId: row.revisionId, context: ctx, folder: () => learningFolderOf(data, row.agentId), shown: () => learningShown(row.agentId), log: said }, row, body.correct).catch((error) => said(`the grade wrote no audit row (${error?.message ?? error})`));
3534
3556
  // Its workflow's name cut as GET /runs/{id}/learning cuts it (learningShown); withheld whole when that cut can't be
3535
3557
  // read (the grade is kept by then: never a shorter cut, never a refusal of a grade it kept).
3536
3558
  const shown = await learningShown(row.agentId).catch(() => undefined);
@@ -4037,11 +4059,34 @@ async function startHolding(options, data, checked, stops) {
4037
4059
  return send(res, 200, { agent: id, ...cost });
4038
4060
  }
4039
4061
  case "listLearningPromotions": {
4062
+ const entry = await needAgent(id);
4063
+ // Each learned workflow's promotion records, oldest first (learn/promote.ts): its check's numbers and decisions,
4064
+ // its holds (a check's, an audit's). Every text in them cut as the other learning reads cut theirs
4065
+ // (promotionsShown: a reason as well as each workflow's name). Beside what serves, each one's state, its check's
4066
+ // numbers and its audit line (learn/audit.ts servingLinesOf), at the agent's numbers.
4067
+ const records = await promotionsOf(store.settings, id);
4068
+ const shown = await learningShown(id);
4069
+ const shownRead = promotionsShown(records, shown);
4070
+ // A ledger that can't be read now leaves each audit line at no rows, never the read refused.
4071
+ const loop = auditLoopOf(entry.revision?.body?.learning);
4072
+ const lines = servingLinesOf(records, await auditsOfAgent(id).catch(() => []), loop);
4073
+ // Why its runs are never audited, when the agent can call a tool that writes (learn/audit.ts auditWriterOf, the
4074
+ // rule startAudit reads); and how many of the serving revision's runs a trigger started (never audited).
4075
+ const writer = auditWriterOf(entry.revision ?? undefined);
4076
+ const auditsOff = writer === undefined ? null : shown.text(auditsOffWords(writer));
4077
+ const serving = await Promise.all(servingOf(records).map(async (one, i) => ({
4078
+ ...shownRead.serving[i], ...lines[i], audits_off: auditsOff,
4079
+ not_auditable: one.digest === null ? 0 : await notAuditableOf(store, id, one.workflow, one.digest, loop).catch(() => 0),
4080
+ })));
4081
+ return send(res, 200, { agent: id, promotions: shownRead.promotions, serving });
4082
+ }
4083
+ case "listLearningAudits": {
4040
4084
  await needAgent(id);
4041
- // Each learned workflow's promotion records, oldest first (learn/promote.ts): its replays' numbers and decisions,
4042
- // its refits, its holds. Aggregates only; every text in them cut as the other learning reads cut theirs
4043
- // (promotionsShown: a reason and a refit guard's label as well as each workflow's name).
4044
- return send(res, 200, { agent: id, ...promotionsShown(await promotionsOf(store.settings, id), await learningShown(id)) });
4085
+ // The audit ledger (learn/audit.ts audits.jsonl), oldest first: each workflow's name and every other text cut as the
4086
+ // promotions read cuts its own.
4087
+ const shown = await learningShown(id);
4088
+ const rows = await auditsOfAgent(id);
4089
+ return send(res, 200, { agent: id, audits: rows.map((row) => ({ ...row, workflow: shown.name(row.workflow), run: shown.text(row.run), shadow_run: row.shadow_run === null ? null : shown.text(row.shadow_run), digest: shown.text(row.digest) })) });
4045
4090
  }
4046
4091
  case "createLearningBatch": {
4047
4092
  await needAgent(id);
@@ -4075,7 +4120,7 @@ async function startHolding(options, data, checked, stops) {
4075
4120
  }
4076
4121
  case "getLearningLoop": {
4077
4122
  await needAgent(id);
4078
- // The loop's own record over the one store (store-reads/loop.ts): compile turns and guarded steps, aggregates only.
4123
+ // The loop's own record over the one store (store-reads/loop.ts): compile turns, aggregates only.
4079
4124
  // Names cut as the other learning reads cut them; a compile's error texts cut by its run's own cut as its run's
4080
4125
  // learning read cuts them (run-learning-served.ts), and left out when that run's handed values can't be read.
4081
4126
  const shown = await learningShown(id);
@@ -4090,8 +4135,7 @@ async function startHolding(options, data, checked, stops) {
4090
4135
  const said = (error) => shown.text(printable({ rule: "workflow", detail: error }, all).detail);
4091
4136
  return { ...one, workflow, from_notes: one.from_notes.map(shown.name), attempts: one.attempts.map(({ ok, errors }) => ({ ok, errors: errors.map(said) })), draft_errors: one.draft_errors.map(said), withheld: false };
4092
4137
  }));
4093
- const guards = read.guards.map((one) => ({ ...one, workflow: shown.name(one.workflow), node: shown.text(one.node) }));
4094
- return send(res, 200, { agent: id, completed_runs: read.completed_runs, compiles, guards });
4138
+ return send(res, 200, { agent: id, completed_runs: read.completed_runs, compiles });
4095
4139
  }
4096
4140
  case "listLearningNotes":
4097
4141
  case "listLearningLog":
@@ -4141,8 +4185,8 @@ async function startHolding(options, data, checked, stops) {
4141
4185
  if (extra.length)
4142
4186
  throw invalid(extra);
4143
4187
  const inputs = body.inputs === undefined ? "held" : body.inputs;
4144
- if (inputs !== "held" && !(typeof inputs === "number" && Number.isInteger(inputs) && inputs >= 1 && inputs <= GRADES_KEPT)) {
4145
- throw new ApiError("bad_request", `inputs is "held" (the graded inputs the revision was last decided on, the default) or a whole number from 1 to ${GRADES_KEPT}: that many of the agent's newest graded inputs.`);
4188
+ if (inputs !== "held" && !(typeof inputs === "number" && Number.isInteger(inputs) && inputs >= 1 && inputs <= COMPILE_AFTER_MAX)) {
4189
+ throw new ApiError("bad_request", `inputs is "held" (the runs the revision was last checked on, the default) or a whole number from 1 to ${COMPILE_AFTER_MAX}: that many of the agent's newest completed runs.`);
4146
4190
  }
4147
4191
  const [, , name, digest] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
4148
4192
  const started = await replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs));
@@ -4540,7 +4584,8 @@ async function startHolding(options, data, checked, stops) {
4540
4584
  * is not done (a read that failed, or its notice not saved): it is read again. */
4541
4585
  const tellWait = async (row) => {
4542
4586
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
4543
- if (readWaits.get(row.id) === seen)
4587
+ // An audit's shadow run waits on no one (runner/audit.ts AUDIT_PARKED): the park it ends at once is no one's to answer.
4588
+ if (readWaits.get(row.id) === seen || isShadowRun(row.id))
4544
4589
  return true;
4545
4590
  const view = await viewOverStore(store, row.id, viewDepsFor(ownOriginOf()));
4546
4591
  if (view?.status !== "input_required")
@@ -1167,6 +1167,7 @@ class SqliteStore {
1167
1167
  return row ? proposalOf(row) : undefined;
1168
1168
  },
1169
1169
  proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
1170
+ grading: async (agentId) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? AND learning_run_id IN (SELECT id FROM runs WHERE state NOT IN (${FINAL})) ORDER BY created_at DESC, run_id DESC, round DESC`, agentId)).map(proposalOf),
1170
1171
  kept: async (agentId) => {
1171
1172
  const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY run_id, round`, agentId)).map(proposalOf);
1172
1173
  const learningRuns = (await db.all(`SELECT ${RUN_COLUMNS} FROM runs WHERE id IN (SELECT learning_run_id FROM learning_proposals WHERE agent_id = ? AND learning_run_id IS NOT NULL)`, agentId)).map(runOf);
@@ -297,6 +297,9 @@ export interface Learning {
297
297
  proposals(agentId: string, options?: {
298
298
  limit?: number;
299
299
  }): Promise<LearningProposal[]>;
300
+ /** The agent's kept proposals whose learning run (its grade) has not ended: queued, running or parked. Every one of
301
+ * them, however many proposals were kept since, newest first. */
302
+ grading(agentId: string): Promise<LearningProposal[]>;
300
303
  /** Everything agent `agentId`'s runs' learning kept, in two reads whatever the number of its runs: every round of every
301
304
  * run's kept proposal (oldest round first within a run), and the rows of the learning runs they name (as runs.get
302
305
  * reads one; a learning run named and never written has none). An agent-wide read's, never a read a run. */
@@ -39,7 +39,8 @@ export type RunRecords = {
39
39
  /** Agent `agentId`'s runs' records read at once, whatever their number: its runs' launches (Store.runs.launches) and every
40
40
  * round its runs' learning kept with the learning runs they name (Store.learning.kept), two reads beside `listed` (its
41
41
  * runs, as runs.list read them). Each answers as the store's per-run read does: a run of `listed` with no launch row is
42
- * StoreLaunchMissing, one that kept no learning has no round. A run not of `listed` is read from the store. */
42
+ * StoreLaunchMissing, one that kept no learning has no round. A run not of `listed` is read from the store, but for an
43
+ * audit's shadow run: `listed` is every run of the agent, its shadows among them. */
43
44
  export declare function agentRecordsOf(store: Store, agentId: string, listed: readonly RunRecord[]): Promise<RunRecords>;
44
45
  /** Run `runId`'s learning end (its newest round's, or round `round`'s); null when the run kept no learning. Proposed while its learning run has not ended. `records`: where its rows are read (the store's per-run reads by default). */
45
46
  export declare function runLearningEnd(store: Store, runId: string, round?: number, records?: RunRecords): Promise<RunLearningEnd | null>;
@@ -104,10 +105,11 @@ export declare function agentCostOverStore(store: Store, agentId: string, limit?
104
105
  unknown_path_runs: number;
105
106
  workflows: ReturnType<typeof workflowCostsOf>;
106
107
  }>;
107
- /** The replay the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
108
- * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's `replay` numbers
109
- * and whether they cleared the bar (withinBar, promotion's own). Null when no run was served, nothing serves now (held,
110
- * or never promoted), or it was promoted with no replay (a dry run). */
108
+ /** The check the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
109
+ * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's check numbers
110
+ * (the share of the inputs it ran on that said what the agent said, against the agent's own 100%). `cleared`: it passed
111
+ * (a champion is promoted), with the agreement check it passed (`agreed` of `alone`, its bar `agree_min`). Null when no run was served, nothing serves now (held, or never promoted), or it was promoted
112
+ * on no input (a dry run). */
111
113
  export declare function servingReplayOf(records: readonly PromotionRecord[], runs: readonly CostRun[]): CostReplay | null;
112
114
  /** What run `runId`'s learning spent, as its cost per run counts it, over every round a follow-up opened (roundsOf): what
113
115
  * it kept as it answered (`looked`: answeredOf), and its grades' spend (`grade`): each round's learning run's cost once
@@ -130,6 +132,15 @@ type RunRecord = NonNullable<Awaited<ReturnType<Store["runs"]["get"]>>>;
130
132
  * never the newest round's alone), else its one round's (learningSpendOf). `total_usd` is the run's all-in cost, the one
131
133
  * the cost page shows and the money rule reads (pastRunsOverStore); null when any part is unknown. */
132
134
  export declare function allInOf(store: RunRecords, run: RunRecord): Promise<ReturnType<typeof runCostOf>>;
135
+ /** What run `runId`'s audit shadow run (runner/audit.ts) adds to its all-in cost: `open` while it is queued or running
136
+ * (its cost not known yet: `usd` null, never $0), else its cost once it ended, stopped or failed (null: unknown); 0 when
137
+ * none was started, and for a shadow itself. */
138
+ export declare function shadowSpendOf(store: {
139
+ readonly runs: Pick<RunRecords["runs"], "get">;
140
+ }, runId: string): Promise<{
141
+ open: boolean;
142
+ usd: number | null;
143
+ }>;
133
144
  /** One run of the cost series, as number `n` of it: its figures (allInOf) and its path (agentCostOverStore's loop body,
134
145
  * and a learning batch's row once the run's learning has settled). */
135
146
  export declare function costRunOf(store: RunRecords, run: RunRecord, n: number): Promise<CostRun>;
@@ -309,7 +320,7 @@ export declare function runLearningOverStore(store: Store, runId: string, shown:
309
320
  feedback_status: "running" | "ended" | "not_run" | null;
310
321
  source: "feedback" | "eval";
311
322
  graded_at: string;
312
- path: "agent" | "workflow" | "handed_back" | "replay";
323
+ path: "agent" | "workflow" | "handed_back" | "replay" | "audit";
313
324
  workflow_digest: string | null;
314
325
  feedback: "look_back" | null;
315
326
  run_id: string;
@@ -24,8 +24,8 @@ import { journalEntries } from "../runner/journal-reader.js";
24
24
  import { KINDS } from "../runner/journal-kinds.js";
25
25
  import { keptOf, learnedOf, lostOf } from "../runner/learning-loop.js";
26
26
  import { promotedOf } from "../learn/compile.js";
27
- import { championOf, gradesOf, gradeView, promotionsOf, withinBar } from "../learn/promote.js";
28
- import { GENERAL_NO_BUDGET, GENERAL_NO_ROOM, GENERAL_UNCHECKED } from "../learn/general.js";
27
+ import { isShadowRun, shadowRunId } from "../learn/audit.js";
28
+ import { championOf, checkShares, gradesOf, gradeView, promotionsOf } from "../learn/promote.js";
29
29
  const timeOf = (ms) => new Date(ms).toISOString();
30
30
  const usdOrNull = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
31
31
  /** What a kept row says of a run that looked back (learning-run.ts closeLearning's fields): none for one that did not. */
@@ -37,7 +37,8 @@ function answeredOf(row) {
37
37
  /** Agent `agentId`'s runs' records read at once, whatever their number: its runs' launches (Store.runs.launches) and every
38
38
  * round its runs' learning kept with the learning runs they name (Store.learning.kept), two reads beside `listed` (its
39
39
  * runs, as runs.list read them). Each answers as the store's per-run read does: a run of `listed` with no launch row is
40
- * StoreLaunchMissing, one that kept no learning has no round. A run not of `listed` is read from the store. */
40
+ * StoreLaunchMissing, one that kept no learning has no round. A run not of `listed` is read from the store, but for an
41
+ * audit's shadow run: `listed` is every run of the agent, its shadows among them. */
41
42
  export async function agentRecordsOf(store, agentId, listed) {
42
43
  const [starts, kept] = await Promise.all([store.runs.learningStarts(agentId), store.learning.kept(agentId)]);
43
44
  const ours = new Set(listed.map((run) => run.id));
@@ -57,7 +58,9 @@ export async function agentRecordsOf(store, agentId, listed) {
57
58
  throw new StoreLaunchMissing(runId);
58
59
  return learningStartOfStored(startOf.get(runId));
59
60
  },
60
- get: async (id) => rows.get(id) ?? store.runs.get(id),
61
+ // An audit's shadow run is the agent's: one not among `listed` (every run of the agent) was never started, so a
62
+ // run's shadow (allInOf) is no read a run.
63
+ get: async (id) => rows.get(id) ?? (isShadowRun(id) ? undefined : store.runs.get(id)),
61
64
  },
62
65
  learning: {
63
66
  proposal: async (runId, round) => {
@@ -118,26 +121,20 @@ async function endOfKept(store, kept, row, records = store) {
118
121
  // What the grade spent: the graded entry's, or what a grade that failed spent before it did.
119
122
  const spent = graded ?? (dropped && "usd" in dropped ? { usd: dropped.usd ?? null, tokens: dropped.tokens ?? null } : undefined);
120
123
  const cost = spent ? { cost_usd: { grade: spent.usd }, tokens: { grade: spent.tokens ?? null } } : {};
121
- // A generality check that could not run (learning-loop.ts `unchecked`) is said after the end's words: the grader read
122
- // every note. Its provider's error stays in the journal.
123
- // One skipped for no room under the cap (GENERAL_NO_BUDGET) says so.
124
- const unchecked = graded?.unchecked ?? dropped?.unchecked;
125
- const skip = unchecked === undefined ? undefined : unchecked === GENERAL_NO_BUDGET ? GENERAL_NO_ROOM : GENERAL_UNCHECKED;
126
- const withSkip = (detail) => (skip ? [detail, skip].filter(Boolean).join(" ") : detail);
127
124
  if (merged && graded) {
128
125
  // Each item as the merge settled it: its record's verdict (a note it left out is no longer kept, and says why). A merge
129
126
  // recorded with none (before the record kept it) reads no item decisions.
130
127
  const verdict = merged.verdict;
131
128
  const what = verdict ? learnedOf(keptOf(row.proposal, verdict), verdict) : { learned: [], pending: [], skills: [], workflows: [] };
132
129
  return {
133
- state: "merged", reason: null, detail: withSkip(merged.detail), at: endedAt, ...left, ...(verdict ? { verdict } : {}), graded: { ...graded.graded }, ...cost, merged: merged.commit,
130
+ state: "merged", reason: null, detail: merged.detail, at: endedAt, ...left, ...(verdict ? { verdict } : {}), graded: { ...graded.graded }, ...cost, merged: merged.commit,
134
131
  learned: what.learned, ...(what.pending.length ? { pending: what.pending } : {}), ...(what.skills.length ? { skills: what.skills } : {}), ...(what.workflows.length ? { workflows: what.workflows } : {}),
135
132
  };
136
133
  }
137
134
  const reason = (dropped?.reason ?? null);
138
135
  const lost = reason === "grader" ? lostOf(row.proposal) : [];
139
136
  return {
140
- state: "dropped", reason, detail: withSkip(dropped?.detail ?? null), at: endedAt,
137
+ state: "dropped", reason, detail: dropped?.detail ?? null, at: endedAt,
141
138
  ...(dropped?.problems?.length ? { problems: [...dropped.problems] } : left),
142
139
  // The verdict, when one was given; the blobs it read only go with a merge (the server kept them for its merge alone).
143
140
  ...(graded ? { verdict: graded.verdict } : {}), ...cost, ...(lost.length ? { lost } : {}),
@@ -265,7 +262,8 @@ export async function agentCostOverStore(store, agentId, limit = Infinity) {
265
262
  const listed = (await store.runs.list({ agentId })).filter((run) => run.agentId === agentId);
266
263
  // Every run's launch and learning in a few reads (agentRecordsOf), never a read a run.
267
264
  const records = await agentRecordsOf(store, agentId, listed);
268
- const ended = listed.filter((run) => FINAL_STATES.includes(run.state) && !run.importedFrom && run.archivedAt === null).sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : 1));
265
+ // An audit's shadow run is no run of the series: its cost is its served run's learning (allInOf).
266
+ const ended = listed.filter((run) => FINAL_STATES.includes(run.state) && !run.importedFrom && run.archivedAt === null && !isShadowRun(run.id)).sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : 1));
269
267
  const runs = [];
270
268
  let unknownPath = 0;
271
269
  for (const run of ended) {
@@ -287,17 +285,18 @@ export async function agentCostOverStore(store, agentId, limit = Infinity) {
287
285
  const replay = servingReplayOf(await promotionsOf(store.settings, agentId), runs);
288
286
  return { runs: runs.slice(Math.max(0, runs.length - limit)), summary: costSummary(runs, replay), total_runs: runs.length, unknown_cost_runs: runs.filter((run) => run.total_usd === null).length, unknown_path_runs: unknownPath, workflows };
289
287
  }
290
- /** The replay the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
291
- * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's `replay` numbers
292
- * and whether they cleared the bar (withinBar, promotion's own). Null when no run was served, nothing serves now (held,
293
- * or never promoted), or it was promoted with no replay (a dry run). */
288
+ /** The check the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
289
+ * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's check numbers
290
+ * (the share of the inputs it ran on that said what the agent said, against the agent's own 100%). `cleared`: it passed
291
+ * (a champion is promoted), with the agreement check it passed (`agreed` of `alone`, its bar `agree_min`). Null when no run was served, nothing serves now (held, or never promoted), or it was promoted
292
+ * on no input (a dry run). */
294
293
  export function servingReplayOf(records, runs) {
295
294
  const name = runs.findLast((run) => (run.path === "workflow" || run.path === "handed_back") && run.workflow !== null)?.workflow;
296
- const score = name ? championOf(records, name)?.replay : undefined;
297
- if (!score)
295
+ const check = name ? championOf(records, name)?.check : undefined;
296
+ if (!check?.n)
298
297
  return null;
299
- const pct = (acc) => Math.round(acc * 1000) / 10;
300
- return { n: score.n, workflow_pct: pct(score.wf_acc), agent_pct: pct(score.agent_acc), cleared: withinBar(score) };
298
+ const agreed = check.agreed ?? 0, alone = check.alone ?? 0;
299
+ return { n: check.n, workflow_pct: Math.round(checkShares({ n: check.n, agreed, alone }).agreement * 1000) / 10, agent_pct: 100, cleared: true, agreed, alone, agree_min: check.agree_min };
301
300
  }
302
301
  /** What run `runId`'s learning spent, as its cost per run counts it, over every round a follow-up opened (roundsOf): what
303
302
  * it kept as it answered (`looked`: answeredOf), and its grades' spend (`grade`): each round's learning run's cost once
@@ -355,7 +354,21 @@ async function roundsSpentOf(store, rounds) {
355
354
  export async function allInOf(store, run) {
356
355
  // Every round's (learningSpendOf over the rounds: what its row spent after its job answered is learning, roundsLooked).
357
356
  const { looked, grade } = await learningSpendOf(store, run.id, run.costUsd);
358
- return runCostOf(run.costUsd, looked, grade);
357
+ // An audit's shadow run of it (runner/audit.ts) is its learning too (shadowSpendOf): unknown while it is queued or
358
+ // running, never $0.
359
+ const audited = (await shadowSpendOf(store, run.id)).usd;
360
+ return runCostOf(run.costUsd, looked, grade === null || audited === null ? null : grade + audited);
361
+ }
362
+ /** What run `runId`'s audit shadow run (runner/audit.ts) adds to its all-in cost: `open` while it is queued or running
363
+ * (its cost not known yet: `usd` null, never $0), else its cost once it ended, stopped or failed (null: unknown); 0 when
364
+ * none was started, and for a shadow itself. */
365
+ export async function shadowSpendOf(store, runId) {
366
+ if (isShadowRun(runId))
367
+ return { open: false, usd: 0 };
368
+ const shadow = await store.runs.get(shadowRunId(runId));
369
+ if (!shadow)
370
+ return { open: false, usd: 0 };
371
+ return FINAL_STATES.includes(shadow.state) ? { open: false, usd: shadow.costUsd ?? null } : { open: true, usd: null };
359
372
  }
360
373
  /** One run of the cost series, as number `n` of it: its figures (allInOf) and its path (agentCostOverStore's loop body,
361
374
  * and a learning batch's row once the run's learning has settled). */
@@ -376,7 +389,7 @@ export async function pastRunsOverStore(store, agentId, known, records = store)
376
389
  const kinds = new Map();
377
390
  const kept = [];
378
391
  for (const run of await store.runs.list({ agentId, limit: PAST_RUNS })) {
379
- if (run.agentId !== agentId || !FINAL_STATES.includes(run.state) || run.importedFrom || run.archivedAt !== null)
392
+ if (run.agentId !== agentId || !FINAL_STATES.includes(run.state) || run.importedFrom || run.archivedAt !== null || isShadowRun(run.id))
380
393
  continue;
381
394
  if (!kinds.has(run.revisionId))
382
395
  kinds.set(run.revisionId, (await store.agents.revision(run.revisionId))?.kind);
@@ -1,9 +1,6 @@
1
1
  import { type Store } from "../store/store.js";
2
- import type { GuardRow } from "../learned-nodes.js";
3
2
  /** How many compile turns the read gives, the newest. */
4
3
  export declare const LOOP_COMPILES_MAX = 50;
5
- /** How many runs' p a guarded step gives, its newest. */
6
- export declare const LOOP_POINTS_MAX = 200;
7
4
  /** One compile turn of a run, in the round of it that compiled (a follow-up opens a round past the first, and each
8
5
  * round's end may compile): `errors` its draft's when none passed (never silent). */
9
6
  export type LoopCompile = {
@@ -20,43 +17,11 @@ export type LoopCompile = {
20
17
  promoted: boolean | null;
21
18
  draft_errors: string[];
22
19
  };
23
- /** One run's guard outcome on a step: its p (the least its checks read, a step in a map checking once per item; null
24
- * when a signal was missing on one: it handed back), whether one of its checks handed back, and, when the run's answer
25
- * was the workflow's own and it was graded, whether that was right. */
26
- export type LoopPoint = {
27
- run_id: string;
28
- p: number | null;
29
- escalated: boolean;
30
- correct: boolean | null;
31
- };
32
- /** One guarded step of one revision of a learned workflow, over the runs it served first on (each run once, however many
33
- * checks a map made of it): its threshold as those runs read it (null when only replays ran it), how many it guarded and
34
- * handed back, how many of those the workflow answered
35
- * alone were graded right and wrong, each over every such run, and the newest runs' p. A replay run reads its guards at
36
- * RECORD_ONLY_THRESHOLD (learn/promote.ts: it hands back on nothing it reads), so its row says nothing of a hand-back
37
- * at the serving threshold: it is counted apart (`replays`) and in none of the others. */
38
- export type LoopGuard = {
39
- workflow: string;
40
- digest: string;
41
- node: string;
42
- signal: GuardRow["signal"];
43
- threshold: number | null;
44
- runs: number;
45
- escalated: number;
46
- right: number;
47
- wrong: number;
48
- /** Runs it answered alone whose grade, if one was given, is no longer kept (the agent keeps its newest GRADES_KEPT
49
- * grades): in neither `right` nor `wrong`, never read as "not graded". */
50
- grades_past: number;
51
- replays: number;
52
- points: LoopPoint[];
53
- };
54
- /** The agent's compile turns (every round of each run, roundsOf: newest first, LOOP_COMPILES_MAX) and its learned
55
- * workflows' guarded steps, over its ended runs (not imported, not archived). A compile's `promoted` is its revision's
56
- * promotion as the records say now (null while undecided): whether it serves now is the promotions read's `serving`. A step's `correct` is the run's grade only on a run its workflow answered alone (path `workflow`): a
57
- * hand-back's answer was the agent's, and a replay run is never graded. */
20
+ /** The agent's compile turns (every round of each run, roundsOf: newest first, LOOP_COMPILES_MAX), over its ended runs
21
+ * (not imported, not archived), and how many completed runs of its own count toward its compile. A compile's `promoted`
22
+ * is its revision's promotion as the records say now (null while undecided): whether it serves now is the promotions
23
+ * read's `serving`. */
58
24
  export declare function agentLoopOverStore(store: Store, agentId: string): Promise<{
59
25
  compiles: LoopCompile[];
60
- guards: LoopGuard[];
61
26
  completed_runs: number;
62
27
  }>;