@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
@@ -7,23 +7,15 @@
7
7
  // learning-end.ts gradeCapOf), and each grader call is judged against it before it leaves by the kernel's one rule
8
8
  // (beforeRequestOf, over the learning run's one booking) at its worst case: its input uncached and its whole output bound
9
9
  // (GRADE_MAX_TOKENS), never cut down to fit, so a verdict is never lost to a short answer. A call that doesn't fit is
10
- // never sent, and the grade is skipped, said so (learning-loop.ts GradeOverCap). The generality pre-check's Jev requests
11
- // are the grade's spend too: before they leave, their worst case (decision-cap.ts holdOf: the rule a workflow's
12
- // decision is held at under its run's cap) is judged against the same cap, less what an earlier attempt's cut check may
13
- // have spent; a check that doesn't fit is never sent, and is skipped, said so (learning-loop.ts GeneralOverCap), the
14
- // grader then judged on its own. What the check spent is outside the grade's records, so each grader call's room is the
15
- // cap less it (the ask's `beside`: its kept dollars, else its worst case). An uncapped run's grade is capped by nothing. A
10
+ // never sent, and the grade is skipped, said so (learning-loop.ts GradeOverCap). An uncapped run's grade is capped by nothing. A
16
11
  // grader that never answers is cut at the grade's bound, and what it spent is unknown (null).
17
12
  import { beforeRequestOf } from "@parcha/agentrun-kernel/kernel/cap";
18
- import { money } from "../cap.js";
19
- import { holdOf } from "../decision-cap.js";
20
- import { generalRequest, generalScores } from "../learn/general.js";
21
13
  import { FAUX_ENV } from "../model.js";
22
14
  import { anthropicModelId, openRouterOnly, providerFor } from "../provider.js";
23
15
  import { capModelOf } from "./adapter-run-spec.js";
24
16
  import { bookedAsk } from "./learning-ask.js";
25
17
  import { learningLoopFactory } from "./learning-factory.js";
26
- import { GeneralOverCap, GRADE_TIMEOUT_MS } from "./learning-loop.js";
18
+ import { GRADE_TIMEOUT_MS } from "./learning-loop.js";
27
19
  /** The model a grade runs on, main's order: the grade model the server names, else the agent's own (the model its
28
20
  * revision names), else none (the host's default, which the route picks). */
29
21
  export const gradeModelFor = (grade) => grade.model ?? grade.own;
@@ -81,19 +73,6 @@ export function gradeCap(capUsd, route) {
81
73
  const judge = beforeRequestOf({ capUsd: () => capUsd, modelOf: (id) => (id === route.model ? model : undefined) });
82
74
  return (request) => judge({ ...request, ...(request.outputTokensAsked !== undefined ? { outputTokensLeast: request.outputTokensAsked } : {}) });
83
75
  }
84
- /** The worst case of the generality check's requests to `jev` (learn/general.ts generalRequest, one a note), each held as a
85
- * workflow's decision is under its run's cap (decision-cap.ts holdOf); unpriced when any one's price is not known
86
- * here. */
87
- export async function generalHeld(jev, notes, source) {
88
- let usd = 0;
89
- for (const note of notes) {
90
- const hold = await holdOf(jev, generalRequest(note, source));
91
- if ("unpriced" in hold)
92
- return hold;
93
- usd += hold.usd;
94
- }
95
- return { usd };
96
- }
97
76
  /** The loop for a launch of harness "learning": the runner's dispatch calls it for each such run it claims. */
98
77
  export function learningLoopOf(deps) {
99
78
  return (loopDeps) => {
@@ -105,31 +84,9 @@ export function learningLoopOf(deps) {
105
84
  const route = await deps.routeOf(grade.route);
106
85
  // The loop's own signal (a stop, a lost claim, its bound) and the grade's bound, both: whichever ends first cuts it.
107
86
  const bound = deps.gradeBound ? deps.gradeBound() : AbortSignal.timeout(GRADE_TIMEOUT_MS);
108
- // Under a cap, the room for the call is what the cap leaves once the generality check's spend beside the grade's
109
- // records is counted.
110
- const capUsd = grade.capUsd === undefined ? undefined : Math.max(0, grade.capUsd - (request.beside ?? 0));
111
- return bookedAsk({ ...route, ...(capUsd !== undefined ? { beforeRequest: gradeCap(capUsd, route) } : {}) })(request, AbortSignal.any([signal, bound]), run);
112
- };
113
- // The generality pre-check on this host's Jev; none set up here, none asked. Under a cap, its requests' worst case
114
- // is judged against what the cap leaves (less `before`, an earlier attempt's cut check's) before any leaves.
115
- const general = async (notes, source, signal, run, sending, before) => {
116
- const jev = await deps.jev?.();
117
- if (!jev)
118
- return undefined;
119
- if (claimed === undefined)
120
- throw new Error("the learning run's generality check was asked before its claim");
121
- const { capUsd } = await gradeOf(deps.store, claimed);
122
- if (capUsd === undefined)
123
- return generalScores(jev, notes, source, signal, run, sending && (() => sending()));
124
- const held = await generalHeld(jev, notes, source);
125
- const room = Math.max(0, capUsd - (before ?? 0));
126
- if ("unpriced" in held)
127
- throw new GeneralOverCap(held.unpriced, true);
128
- if (held.usd > room)
129
- throw new GeneralOverCap(`its worst case of ${money(held.usd)} is over the ${money(room)} the cap leaves`, false);
130
- return generalScores(jev, notes, source, signal, run, sending && (() => sending(held.usd)));
87
+ return bookedAsk({ ...route, ...(grade.capUsd !== undefined ? { beforeRequest: gradeCap(grade.capUsd, route) } : {}) })(request, AbortSignal.any([signal, bound]), run);
131
88
  };
132
- const loop = learningLoopFactory({ store: deps.store, data: deps.data, ask, ...(deps.sourceInstructions ? { sourceInstructions: deps.sourceInstructions } : {}), ...(deps.jev ? { general } : {}), ...(deps.generalThreshold !== undefined ? { generalThreshold: deps.generalThreshold } : {}), ...(deps.log ? { log: deps.log } : {}), ...(deps.now ? { now: deps.now } : {}) })(loopDeps);
89
+ const loop = learningLoopFactory({ store: deps.store, data: deps.data, ask, ...(deps.sourceInstructions ? { sourceInstructions: deps.sourceInstructions } : {}), ...(deps.log ? { log: deps.log } : {}), ...(deps.now ? { now: deps.now } : {}) })(loopDeps);
133
90
  return {
134
91
  start: (claim) => {
135
92
  claimed = claim.runId;
@@ -4,7 +4,7 @@ import { type CompileAsk, type CompileTrace } from "../learn/compile.js";
4
4
  import type { RunPath } from "../learning-cost.js";
5
5
  import { type RunLaunch } from "../run-launch.js";
6
6
  import { type SignInReader } from "../run-view.js";
7
- import type { Store } from "../store/store.js";
7
+ import { type AlsoRow, type Store } from "../store/store.js";
8
8
  import type { EndOfRunTurn } from "./loop-contract.js";
9
9
  /** What the step reads: the run's store, the data directory (the server's tool settings a draft's tools are read with),
10
10
  * the agent's learning folder (where the run's place keeps it), the runner's environment (the host's secrets a
@@ -40,12 +40,25 @@ export interface LearningEndDeps {
40
40
  * does not learn is asked nothing and keeps nothing), else the reflect hook over the run's store. */
41
41
  export declare function learningEndOfRun(launch: RunLaunch, deps: LearningEndDeps): EndOfRunTurn | undefined;
42
42
  /** What every cap gate of run `runId` reads as spent beside it on its behalf (adapter-loop.ts RunCapConfig.beside): its
43
- * learning runs' grades (Store.learning.spentBeside, the one figure), for a capped run that learns, the only run whose
44
- * ends queue them; none for any other, whose gates read only its own sessions. */
45
- export declare function spentBesideOf(launch: RunLaunch, store: Pick<Store, "learning">, runId: string): (() => Promise<number | null>) | undefined;
43
+ * learning runs' grades and its audit's shadow run (besideOf), for a capped run with a learning start, the only run
44
+ * whose ends queue them (one that only uses what its agent learned queues no grade, but may start a shadow); none for any
45
+ * other, whose gates read only its own sessions. */
46
+ export declare function spentBesideOf(launch: RunLaunch, store: Pick<Store, "learning" | "runs">, runId: string): (() => Promise<number | null>) | undefined;
47
+ /** What was spent beside run `runId` on its behalf, the one figure its cap gates and its grades' caps read: its learning
48
+ * runs' grades (Store.learning.spentBeside; `beforeRound`: its earlier rounds' alone) and its audit's shadow run
49
+ * (runner/audit.ts, started at its end with what its cap left): the shadow at its cost once it ended, at its own cap while
50
+ * it has not (the most it may take) or when it ended at a cost not known, 0 when none was started. Null: unknown. */
51
+ export declare function besideOf(store: Pick<Store, "learning" | "runs">, runId: string, options?: {
52
+ beforeRound?: number;
53
+ }): Promise<number | null>;
54
+ /** What run `runId`'s cap leaves its audit's shadow run at its end (runner/audit.ts startAudit): the cap it is held to now
55
+ * (capNowOf: its newest raise's, else `launchCapUsd`), less what it spent under it (capSpendOf over `entries`, its
56
+ * journal: its job, its look-back, every grade an earlier round queued) and the cap of the grade this end queues
57
+ * (`queued`, the end's rows: it is not in the store until the end commits). Null when that spend is unknown. */
58
+ export declare function auditRoomOf(store: Pick<Store, "learning" | "runs">, runId: string, launchCapUsd: number, entries: readonly EntryLike[], queued: readonly AlsoRow[]): Promise<number | null>;
46
59
  /** What capped run `runId` has spent under its cap, as every gate of the run reads it: its sessions' booking as the kernel
47
60
  * cap counts it (metrics.ts bookedCapSpend over `entries`, its journal) and what was spent beside it on its behalf
48
- * (Learning.spentBeside; `beforeRound`: its earlier rounds' grades alone). Null when either is unknown.
61
+ * (besideOf: its grades, `beforeRound` its earlier rounds' alone, and its audit's shadow). Null when either is unknown.
49
62
  *
50
63
  * The rule for a cost no one knows (a request answered with no price of its own, one cut short or lost): under a cap it
51
64
  * counts at the figure the cap held it at when it was admitted (its worst case at the model's price, and a lost one's
@@ -54,7 +67,7 @@ export declare function spentBesideOf(launch: RunLaunch, store: Pick<Store, "lea
54
67
  * unknown (a held figure is the cap's, never a charge). Only a request held at no figure (none is, under a cap) leaves
55
68
  * the spend itself unknown: then nothing more is sent under the cap, and the words say the spend is unknown, as the
56
69
  * kernel's unknownSpend refusal does, never "no room". */
57
- export declare function capSpendOf(store: Pick<Store, "learning">, runId: string, entries: readonly EntryLike[], beforeRound?: number): Promise<number | null>;
70
+ export declare function capSpendOf(store: Pick<Store, "learning" | "runs">, runId: string, entries: readonly EntryLike[], beforeRound?: number): Promise<number | null>;
58
71
  /** The cap the grade of round `round` of run `runId` runs under (its learning run's max_cost_usd), so the run's grades
59
72
  * never take it past its cap: the cap the run is held to now (capNowOf: its newest raise's, else `launchCapUsd`), less
60
73
  * what the run spent under it (its job, its follow-ups and every look-back) and what was spent beside it on its behalf by
@@ -62,6 +75,17 @@ export declare function capSpendOf(store: Pick<Store, "learning">, runId: string
62
75
  * when that spend is unknown, or a read fails: the grade is then not run, said so (said.gradeUnknownSpend), never run
63
76
  * with a room nobody knows and never told it has none. */
64
77
  export declare function gradeCapOf(store: Store, runId: string, round: number, launchCapUsd: number): Promise<number | null>;
78
+ /** A workflow text written straight onto the agent's learning folder as a merge by `runId`, from the claim's `seed`: the
79
+ * one direct commit a runner makes outside a learning run (a compile turn's revision). A file changed on main since the
80
+ * seed is a conflict, never written over. The learning commit it landed as, or null when it did not (the reason is
81
+ * logged). The folder is always released. */
82
+ export declare function commitDirect(deps: {
83
+ readonly folder: () => LearningFolder;
84
+ readonly log: (line: string) => void;
85
+ }, files: {
86
+ path: string;
87
+ text: string;
88
+ }[], reason: string, runId: string, seed?: string): Promise<string | null>;
65
89
  /** The learning run of round `round` of run `runId`'s learning: `<runId>-learning` for its first, `<runId>-learning-<n>`
66
90
  * for each later one. */
67
91
  export declare const learningRunIdOf: (runId: string, round?: number) => string;
@@ -98,6 +122,20 @@ export declare function workflowNameOf(calls: readonly {
98
122
  tool: string;
99
123
  args: Record<string, unknown>;
100
124
  }[]): string | null;
125
+ /** Compile once: run `runId`'s compile turn whose drafts all failed their checks is the compile's attempt, kept as a
126
+ * promotion record of the shape a check's stop has (runner/promotion.ts stopUnchecked): a hold with nothing checked,
127
+ * its reason (DRAFT_FAILED) naming the failed checks. A first compile's earns the one recompile, as a check's hold
128
+ * does (the agent's next due run compiles once more: learn/compile.ts newCompileAttempt); a recompile's (a revision of
129
+ * a held workflow, or a new one after a first compile's failed drafts) stops (compileStoppedOf, heldNamesOf): nothing
130
+ * compiles it again. One record per run (its digest is the run's), written once: a claim that ends the run again
131
+ * writes none. */
132
+ export declare function recordDraftFailed(deps: Pick<LearningEndDeps, "store" | "log">, input: {
133
+ runId: string;
134
+ agentId: string;
135
+ compile: CompileAsk;
136
+ workflow: string;
137
+ errors: readonly string[];
138
+ }): Promise<void>;
101
139
  /** One earlier run as the compile turn reads it (learn/compile.ts CompileTrace), from its timeline (traceFrom). */
102
140
  export declare function traceOf(store: Store, runId: string, refuse: readonly string[]): Promise<CompileTrace>;
103
141
  /** A run's trace from its timeline rows, the end-of-run turn's (LEARNING_LABEL) left out: its first message (the
@@ -108,13 +146,14 @@ export declare function traceOf(store: Store, runId: string, refuse: readonly st
108
146
  * shape. */
109
147
  export declare function traceFrom(timeline: readonly TimelineEvent[], refuse: readonly string[]): CompileTrace;
110
148
  /** The compile turn's facts for run `runId` of agent `agentId` (learn/compile.ts): a revision of the learned workflow
111
- * that fits the run's input and whose promotion holds it at main's digest (runner/promotion.ts: its replay on the
112
- * agent's graded inputs, or its graded served runs, fell under the bar; its champion served the run, or the agent did by
113
- * hand), its text as main holds it, with the hold's numbers, once per hold (none when any run since the hold compiled
114
- * it, read from the agent's kept learning; a check's hold with the inputs it disagreed on, a stopped check's none);
115
- * else, when the job is due (compileDue: the run completed, the agent has no learned workflow active or waiting, none
116
- * of its last COMPILE_QUIET_RUNS runs compiled, and it has its definition's compile_after completed agent runs), a new
117
- * one. Nothing else asks one: a hand-back, a wrong grade of a served answer and the money rule's
149
+ * that fits the run's input and whose promotion holds it at main's digest (runner/promotion.ts: its one check on the
150
+ * agent's own runs fell under the bar; its champion served the run, or the agent did by hand), its text as main holds
151
+ * it, with the check's numbers and the inputs it disagreed on, once per hold (none when any run since the hold compiled
152
+ * it, read from the agent's kept learning; a stopped check's none); else, when the job is due (compileDue: the run
153
+ * completed, the agent has no learned workflow active or waiting, and it has its definition's compile_after completed
154
+ * agent runs), a new one, compiled once: none while the last compile's passing draft waits on its grade
155
+ * (draftAwaitingGrade), one more after a first compile whose drafts all failed their checks, and none after a
156
+ * recompile's (recordDraftFailed). Nothing else asks one: a hand-back, a wrong grade of a served answer and the money rule's
118
157
  * stop are single runs, which the hold reads among many. Either way the
119
158
  * agent's active notes whole, the traces of its last COMPILE_TRACES completed runs before this one, the tools a call node
120
159
  * may run (draftTools) with what each takes and gives, its decision providers, the run's input (`input`, its fields for
@@ -24,20 +24,22 @@
24
24
  // runner's run has no door token: its loop runs in the runner's process.
25
25
  // A proposal queues the learning run (learning_run), which the runner's dispatch runs on the learning loop
26
26
  // (harness-loops.ts: harness "learning"), to grade and merge it. A run whose seed could not be read keeps that drop.
27
+ import { createHash } from "node:crypto";
27
28
  import { mkdtemp, readFile, rm } from "node:fs/promises";
28
29
  import { tmpdir } from "node:os";
29
30
  import { join } from "node:path";
30
31
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
31
32
  import { isMessageRow } from "../timeline/index.js";
32
33
  import { Hearing } from "../heard.js";
34
+ import { learningCommit } from "../learn/commit.js";
33
35
  import { readLearning, readSnapshot } from "../learn/folder.js";
34
- import { completedRun, lastOwnRuns, compileDue, compilePrompt, compileReference, COMPILE_QUIET_RUNS, COMPILE_TRACES, heldNamesOf } from "../learn/compile.js";
36
+ import { completedRun, compileStoppedOf, lastOwnRuns, compileDue, compilePrompt, compileReference, COMPILE_TRACES, DRAFT_FAILED, heldNamesOf, newCompileAttempt } from "../learn/compile.js";
35
37
  import { loopOf } from "../learning-setting.js";
36
- import { promotionOf, promotionsOf, scoreOf } from "../learn/promote.js";
38
+ import { CHECK_TEXT_MAX, promotionOf, promotionsOf, recordPromotion } from "../learn/promote.js";
37
39
  import { draftDecisionProviders } from "../learn/skills.js";
38
40
  import { DECISION_PROVIDER_KEYS } from "../tool-plane.js";
39
41
  import { handedValuesOf } from "../handed-values.js";
40
- import { MIN_SECRET, redactSecrets } from "../learn/secrets.js";
42
+ import { excerptShown, MIN_SECRET, redactSecrets } from "../learn/secrets.js";
41
43
  import { LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
42
44
  import { META_TOOLS } from "../meta-tool-names.js";
43
45
  import { holdsSecret, LEARNING_LABEL, PROPOSAL, secretsShown } from "../learning.js";
@@ -46,6 +48,8 @@ import { said, STOPPED } from "../learning-words.js";
46
48
  import { proposeRun } from "../propose.js";
47
49
  import { learningStartOf, readLaunchBody, seedFailed } from "../run-launch.js";
48
50
  import { costOf } from "../run-view.js";
51
+ import { FINAL_STATES } from "../store/store.js";
52
+ import { shadowRunId } from "../learn/audit.js";
49
53
  import { getMcpServer } from "../mcp-store.js";
50
54
  import { readApprovers } from "../server-approvers.js";
51
55
  import { runEntries, runReflect, runTimeline, withFeedback, withoutFeedbackRounds } from "../store-reads/journal.js";
@@ -75,8 +79,8 @@ export function learningEndOfRun(launch, deps) {
75
79
  // were admitted under, never the launch's alone. A person's stop comes to the hook as its `cut`.
76
80
  // Its spend under that cap is what the run's own gates read (capSpendOf: a request with no price of its own at the
77
81
  // figure it was held at), never the cost a person is shown, which is unknown once one request's is. What its earlier
78
- // rounds' grades took beside it counts toward that cap as its own spend does (Learning.spentBeside, the figure its
79
- // gates read). Either unknown: the spend is unknown, said so, never read as the whole cap.
82
+ // rounds' grades and its audit's shadow took beside it counts toward that cap as its own spend does (besideOf, the
83
+ // figure its gates read). Either unknown: the spend is unknown, said so, never read as the whole cap.
80
84
  facts: async (runId) => {
81
85
  const [rows, entries] = await Promise.all([
82
86
  runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false }),
@@ -106,6 +110,7 @@ export function learningEndOfRun(launch, deps) {
106
110
  // workflows looks back only on its owner's feedback (ownerSaid).
107
111
  ...(start.notesOnly ? {} : {
108
112
  compileFacts: (input) => compileAskOf(deps, { ...input, input: launch.input, seedWorkflows: start.workflows?.length ?? 0 }),
113
+ compileFailed: (input) => recordDraftFailed(deps, input),
109
114
  ownerSaid: async (runId) => {
110
115
  const [entries, rows] = await Promise.all([runEntries(deps.store, runId, BACKGROUND_CONTEXT), runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })]);
111
116
  return ownerSaid(entries, rows);
@@ -177,17 +182,46 @@ export function learningEndOfRun(launch, deps) {
177
182
  };
178
183
  }
179
184
  /** What every cap gate of run `runId` reads as spent beside it on its behalf (adapter-loop.ts RunCapConfig.beside): its
180
- * learning runs' grades (Store.learning.spentBeside, the one figure), for a capped run that learns, the only run whose
181
- * ends queue them; none for any other, whose gates read only its own sessions. */
185
+ * learning runs' grades and its audit's shadow run (besideOf), for a capped run with a learning start, the only run
186
+ * whose ends queue them (one that only uses what its agent learned queues no grade, but may start a shadow); none for any
187
+ * other, whose gates read only its own sessions. */
182
188
  export function spentBesideOf(launch, store, runId) {
183
- const start = learningStartOf(launch);
184
- if (launch.maxCostUsd === undefined || !start || start.use)
189
+ if (launch.maxCostUsd === undefined || !learningStartOf(launch))
185
190
  return undefined;
186
- return () => store.learning.spentBeside(runId);
191
+ return () => besideOf(store, runId);
192
+ }
193
+ /** What was spent beside run `runId` on its behalf, the one figure its cap gates and its grades' caps read: its learning
194
+ * runs' grades (Store.learning.spentBeside; `beforeRound`: its earlier rounds' alone) and its audit's shadow run
195
+ * (runner/audit.ts, started at its end with what its cap left): the shadow at its cost once it ended, at its own cap while
196
+ * it has not (the most it may take) or when it ended at a cost not known, 0 when none was started. Null: unknown. */
197
+ export async function besideOf(store, runId, options = {}) {
198
+ const [grades, shadow] = await Promise.all([store.learning.spentBeside(runId, options), shadowBesideOf(store, runId)]);
199
+ return grades === null || shadow === null ? null : grades + shadow;
200
+ }
201
+ async function shadowBesideOf(store, runId) {
202
+ const id = shadowRunId(runId);
203
+ const shadow = await store.runs.get(id);
204
+ if (!shadow)
205
+ return 0;
206
+ const figure = (usd) => typeof usd === "number" && Number.isFinite(usd) && usd >= 0;
207
+ if (FINAL_STATES.includes(shadow.state) && figure(shadow.costUsd))
208
+ return shadow.costUsd;
209
+ const cap = readLaunchBody((await store.runs.launch(id)).body)?.maxCostUsd;
210
+ return figure(cap) ? cap : null;
211
+ }
212
+ /** What run `runId`'s cap leaves its audit's shadow run at its end (runner/audit.ts startAudit): the cap it is held to now
213
+ * (capNowOf: its newest raise's, else `launchCapUsd`), less what it spent under it (capSpendOf over `entries`, its
214
+ * journal: its job, its look-back, every grade an earlier round queued) and the cap of the grade this end queues
215
+ * (`queued`, the end's rows: it is not in the store until the end commits). Null when that spend is unknown. */
216
+ export async function auditRoomOf(store, runId, launchCapUsd, entries, queued) {
217
+ const capUsd = capNowOf(launchCapUsd, entries);
218
+ const spent = await capSpendOf(store, runId, entries);
219
+ const grade = queued.find((row) => row.table === "learning_run")?.row.capUsd ?? 0;
220
+ return spent === null ? null : capUsd - spent - grade;
187
221
  }
188
222
  /** What capped run `runId` has spent under its cap, as every gate of the run reads it: its sessions' booking as the kernel
189
223
  * cap counts it (metrics.ts bookedCapSpend over `entries`, its journal) and what was spent beside it on its behalf
190
- * (Learning.spentBeside; `beforeRound`: its earlier rounds' grades alone). Null when either is unknown.
224
+ * (besideOf: its grades, `beforeRound` its earlier rounds' alone, and its audit's shadow). Null when either is unknown.
191
225
  *
192
226
  * The rule for a cost no one knows (a request answered with no price of its own, one cut short or lost): under a cap it
193
227
  * counts at the figure the cap held it at when it was admitted (its worst case at the model's price, and a lost one's
@@ -200,7 +234,7 @@ export async function capSpendOf(store, runId, entries, beforeRound) {
200
234
  const spent = bookedCapSpend(entries);
201
235
  if (spent === null)
202
236
  return null;
203
- const beside = await store.learning.spentBeside(runId, beforeRound === undefined ? {} : { beforeRound });
237
+ const beside = await besideOf(store, runId, beforeRound === undefined ? {} : { beforeRound });
204
238
  return beside === null ? null : spent + beside;
205
239
  }
206
240
  /** The cap the grade of round `round` of run `runId` runs under (its learning run's max_cost_usd), so the run's grades
@@ -220,6 +254,22 @@ export async function gradeCapOf(store, runId, round, launchCapUsd) {
220
254
  return null;
221
255
  }
222
256
  }
257
+ /** A workflow text written straight onto the agent's learning folder as a merge by `runId`, from the claim's `seed`: the
258
+ * one direct commit a runner makes outside a learning run (a compile turn's revision). A file changed on main since the
259
+ * seed is a conflict, never written over. The learning commit it landed as, or null when it did not (the reason is
260
+ * logged). The folder is always released. */
261
+ export async function commitDirect(deps, files, reason, runId, seed) {
262
+ const folder = deps.folder();
263
+ try {
264
+ const done = await learningCommit(folder.workspace, { kind: "merge", runId, reason, files, graded: {}, ...(seed ? { seed } : {}) });
265
+ if (!done.ok)
266
+ deps.log(`learning: a direct commit could not be written (${done.reason})`);
267
+ return done.ok ? done.commit : null;
268
+ }
269
+ finally {
270
+ await folder.end();
271
+ }
272
+ }
223
273
  /** The learning run of round `round` of run `runId`'s learning: `<runId>-learning` for its first, `<runId>-learning-<n>`
224
274
  * for each later one. */
225
275
  export const learningRunIdOf = (runId, round = 1) => (round > 1 ? `${runId}-learning-${round}` : `${runId}-learning`);
@@ -368,6 +418,42 @@ async function loopOfRun(store, runId) {
368
418
  return loopOf(undefined);
369
419
  }
370
420
  }
421
+ /** Compile once: run `runId`'s compile turn whose drafts all failed their checks is the compile's attempt, kept as a
422
+ * promotion record of the shape a check's stop has (runner/promotion.ts stopUnchecked): a hold with nothing checked,
423
+ * its reason (DRAFT_FAILED) naming the failed checks. A first compile's earns the one recompile, as a check's hold
424
+ * does (the agent's next due run compiles once more: learn/compile.ts newCompileAttempt); a recompile's (a revision of
425
+ * a held workflow, or a new one after a first compile's failed drafts) stops (compileStoppedOf, heldNamesOf): nothing
426
+ * compiles it again. One record per run (its digest is the run's), written once: a claim that ends the run again
427
+ * writes none. */
428
+ export async function recordDraftFailed(deps, input) {
429
+ try {
430
+ const records = await promotionsOf(deps.store.settings, input.agentId);
431
+ const attempt = input.compile.mode === "revise" ? 2 : newCompileAttempt(records);
432
+ const { compile_after, agree_min, alone_min } = await loopOfRun(deps.store, input.runId);
433
+ const workflow = input.compile.mode === "revise" ? input.compile.workflow : input.workflow;
434
+ const digest = createHash("sha256").update(`draft-failed\n${input.runId}`).digest("hex").slice(0, 16);
435
+ const failed = input.errors.join("; ").slice(0, CHECK_TEXT_MAX) || "no draft passed";
436
+ const reason = `${DRAFT_FAILED}: ${failed}. ${attempt === 2 ? "It was the recompile, so it stops: nothing compiles again until its owner acts" : "It is not promoted; the next due run compiles it once more"}`;
437
+ const check = { compile_after, agree_min, alone_min, attempt, n: 0, agreed: 0, alone: 0, of: [], ...(attempt === 2 ? { stopped: true } : {}) };
438
+ const kept = await recordPromotion(deps.store.settings, input.agentId, { workflow, digest, at: new Date().toISOString(), decided: "hold", reason, check }, (was) => was === undefined);
439
+ if (kept.won)
440
+ deps.log?.(`learning: run ${input.runId}: the compile of ${workflow} failed its checks (attempt ${attempt}${attempt === 2 ? ", stopped" : ""})`);
441
+ }
442
+ catch (error) {
443
+ deps.log?.(`learning: run ${input.runId}: the compile's failed drafts were not recorded: ${error instanceof Error ? error.message : String(error)}`);
444
+ }
445
+ }
446
+ /** Whether a new workflow's compile is waiting on its grade: a run's kept learning carries a draft that passed its
447
+ * checks (a compiled digest) whose learning run, which grades and merges it, has not ended. It is the compile: none
448
+ * is asked until it lands (a learned workflow then) or is dropped. Read from the agent's kept learning whose grade has
449
+ * not ended (Learning.grading: every one, however many runs kept learning since, never a window of the newest); one
450
+ * that can't be read waits. */
451
+ async function draftAwaitingGrade(store, agentId) {
452
+ const grading = await store.learning.grading(agentId).catch(() => undefined);
453
+ if (!grading)
454
+ return true;
455
+ return grading.some((one) => typeof one.proposal?.compiled?.digest === "string");
456
+ }
371
457
  /** The most tool calls of one run a trace keeps, and the most of a call's input or a message it holds, in characters. */
372
458
  const TRACE_CALLS = 20;
373
459
  const TRACE_TEXT = 600;
@@ -383,7 +469,8 @@ export async function traceOf(store, runId, refuse) {
383
469
  * shape. */
384
470
  export function traceFrom(timeline, refuse) {
385
471
  const rows = withoutFeedbackRounds(timeline).filter((row) => row.agent_label !== LEARNING_LABEL);
386
- const cut = (text) => redactSecrets(String(text ?? ""), refuse, Number.POSITIVE_INFINITY).replace(/\s+/g, " ").trim().slice(0, TRACE_TEXT);
472
+ const shown = { text: (text) => redactSecrets(text, refuse, Number.POSITIVE_INFINITY).replace(/\s+/g, " ").trim() };
473
+ const cut = (text) => excerptShown(String(text ?? ""), shown, TRACE_TEXT);
387
474
  const messages = rows.filter(isMessageRow);
388
475
  const failed = new Set(rows.filter((row) => row.kind === "tool_result" && row.tool_status === "failed").map((row) => row.tool_use_id));
389
476
  const models = modelsOwn(rows);
@@ -393,13 +480,14 @@ export function traceFrom(timeline, refuse) {
393
480
  return { input: first ? cut(first.text ?? first.summary) : "", calls, answer: cut(answer), feedback: messages.slice(1).filter((row) => row.kind === "user_message").map((row) => cut(row.text ?? row.summary)) };
394
481
  }
395
482
  /** The compile turn's facts for run `runId` of agent `agentId` (learn/compile.ts): a revision of the learned workflow
396
- * that fits the run's input and whose promotion holds it at main's digest (runner/promotion.ts: its replay on the
397
- * agent's graded inputs, or its graded served runs, fell under the bar; its champion served the run, or the agent did by
398
- * hand), its text as main holds it, with the hold's numbers, once per hold (none when any run since the hold compiled
399
- * it, read from the agent's kept learning; a check's hold with the inputs it disagreed on, a stopped check's none);
400
- * else, when the job is due (compileDue: the run completed, the agent has no learned workflow active or waiting, none
401
- * of its last COMPILE_QUIET_RUNS runs compiled, and it has its definition's compile_after completed agent runs), a new
402
- * one. Nothing else asks one: a hand-back, a wrong grade of a served answer and the money rule's
483
+ * that fits the run's input and whose promotion holds it at main's digest (runner/promotion.ts: its one check on the
484
+ * agent's own runs fell under the bar; its champion served the run, or the agent did by hand), its text as main holds
485
+ * it, with the check's numbers and the inputs it disagreed on, once per hold (none when any run since the hold compiled
486
+ * it, read from the agent's kept learning; a stopped check's none); else, when the job is due (compileDue: the run
487
+ * completed, the agent has no learned workflow active or waiting, and it has its definition's compile_after completed
488
+ * agent runs), a new one, compiled once: none while the last compile's passing draft waits on its grade
489
+ * (draftAwaitingGrade), one more after a first compile whose drafts all failed their checks, and none after a
490
+ * recompile's (recordDraftFailed). Nothing else asks one: a hand-back, a wrong grade of a served answer and the money rule's
403
491
  * stop are single runs, which the hold reads among many. Either way the
404
492
  * agent's active notes whole, the traces of its last COMPILE_TRACES completed runs before this one, the tools a call node
405
493
  * may run (draftTools) with what each takes and gives, its decision providers, the run's input (`input`, its fields for
@@ -408,8 +496,7 @@ export function traceFrom(timeline, refuse) {
408
496
  * when the folder can't be read. */
409
497
  export async function compileAskOf(deps, input) {
410
498
  // A revision is asked only of a workflow its promotion holds, once per hold. One run is one sample: a hand-back, a wrong
411
- // grade of a served answer or the money rule's stop asks for none (with a 10-15% base error rate on both sides, one
412
- // wrong answer says nothing about the workflow); the hold, read over many runs, does.
499
+ // grade of a served answer or the money rule's stop asks for none; the hold, read over many runs, does.
413
500
  // The workflows whose newest revision other than their champion (learn/promote.ts championOf: it serves while that one
414
501
  // is held) is held: the run's own may be one (its champion served it, or it went by hand).
415
502
  const records = await promotionsOf(deps.store.settings, input.agentId).catch(() => []);
@@ -418,28 +505,18 @@ export async function compileAskOf(deps, input) {
418
505
  // completed agent runs, the ending one counted.
419
506
  const { compile_after: compileAfter } = await loopOfRun(deps.store, input.runId);
420
507
  // The agent's latest runs, newest first: those after the ending one in the list started before it.
421
- const listed = await deps.store.runs.list({ agentId: input.agentId, limit: Math.max(200, 2 * compileAfter + COMPILE_QUIET_RUNS) });
508
+ const listed = await deps.store.runs.list({ agentId: input.agentId, limit: Math.max(200, 2 * compileAfter) });
422
509
  const at = listed.findIndex((run) => run.id === input.runId);
423
510
  const earlier = (at < 0 ? listed : listed.slice(at + 1)).filter((run) => run.agentId === input.agentId);
424
511
  const done = earlier.filter(completedRun);
425
512
  const byHand = (await lastOwnRuns(deps.store, input.agentId, compileAfter, input.runId)).length;
426
- let compiledLately = false;
427
- const dueWith = (workflows) => compileDue({ completed: input.outcome === "completed", runs: byHand + (input.outcome === "completed" ? 1 : 0), workflows, compiledLately, compileAfter });
513
+ const dueWith = (workflows) => compileDue({ completed: input.outcome === "completed", runs: byHand + (input.outcome === "completed" ? 1 : 0), workflows, compileAfter });
428
514
  const compiledOf = (kept) => kept?.proposal?.compiled;
429
- // Every learning round a run kept: its newest, and each before it (a follow-up opened the run again after it).
430
- const roundsOf = async (runId) => {
431
- const newest = await deps.store.learning.proposal(runId).catch(() => undefined);
432
- if (!newest)
433
- return [];
434
- return [newest, ...(await Promise.all(Array.from({ length: Math.max(0, newest.round - 1) }, (_, i) => deps.store.learning.proposal(runId, i + 1).catch(() => undefined))))];
435
- };
436
- // A compile in any learning round of the agent's last runs (a draft still waiting for its grade, or one that failed)
437
- // asks no new one now: a follow-up's round keeps no compile of its own, so a run's earlier rounds are read too.
438
- const lately = (await Promise.all(earlier.slice(0, COMPILE_QUIET_RUNS).map((run) => roundsOf(run.id)))).flat();
439
- compiledLately = lately.some((kept) => compiledOf(kept) !== undefined);
515
+ // Compile once: a recompile whose drafts failed their checks stopped the agent's new compiles (recordDraftFailed).
516
+ const stopped = compileStoppedOf(records);
440
517
  // First by what the run started from (its seed's notes and the workflows it was offered): a run not due by them
441
518
  // opens no folder, unless one of its workflows is held. Main is read below for the turn itself, and decides again.
442
- if (!heldNames.size && !dueWith(input.seedWorkflows ?? 0))
519
+ if (!heldNames.size && (stopped || !dueWith(input.seedWorkflows ?? 0)))
443
520
  return undefined;
444
521
  const dsl = await import("@parcha/agentrun-dsl");
445
522
  // Every text the turn is told passes the check a run's start makes (learning.ts holdsSecret, as chooseWorkflows reads a
@@ -475,7 +552,7 @@ export async function compileAskOf(deps, input) {
475
552
  }
476
553
  const fitting = active.filter((one) => fits(one, input.input, dsl.resolveSchemaForWorkflow));
477
554
  const record = fitting.length === 1 ? promotionOf(records, fitting[0].name, workflowDigest(fitting[0])) : undefined;
478
- if (record?.decided === "hold")
555
+ if (record?.decided === "hold" && !record.check?.stopped && !record.audit?.stopped)
479
556
  [held, current] = [record, fitting[0].workflow];
480
557
  }
481
558
  // An agent with a learned workflow compiles nothing new: its notes' text is not read.
@@ -515,13 +592,18 @@ export async function compileAskOf(deps, input) {
515
592
  const kept = await deps.store.learning.proposals(input.agentId, { limit: HELD_ASKED_READ }).catch(() => undefined);
516
593
  if (!kept || kept.some((one) => !(one.createdAt < since) && compiledOf(one)?.workflow === read.held.workflow))
517
594
  return sayLeftOut(), undefined;
518
- const { workflow, digest, source, reason, replay, check } = read.held;
519
- // A check's disagreements are the agent's own inputs and answers: cut of the run's secrets as a trace is (traceFrom).
595
+ const { workflow, digest, reason, check, audit } = read.held;
596
+ // A check's or an audit's disagreements are the agent's own inputs and answers: cut of the run's secrets as a trace is
597
+ // (traceFrom).
520
598
  const cut = (text) => redactSecrets(text, input.refuse, Number.POSITIVE_INFINITY);
521
599
  const checked = check ? { ...check, ...(check.disagreements ? { disagreements: check.disagreements.map((one) => ({ ...one, input: cut(one.input), agent: one.agent === null ? null : cut(one.agent), ...(one.draft !== undefined ? { draft: cut(one.draft) } : {}), ...(one.escalated !== undefined ? { escalated: cut(one.escalated) } : {}) })) } : {}) } : undefined;
522
- held = { workflow, digest, source, reason, ...(replay ? { replay: scoreOf(replay) } : {}), ...(checked ? { check: checked } : {}) };
600
+ const audited = audit ? { ...audit, disagreements: audit.disagreements.map((one) => ({ ...one, input: cut(one.input), agent: one.agent === null ? null : cut(one.agent), draft: one.draft === null ? null : cut(one.draft) })) } : undefined;
601
+ held = { workflow, digest, reason, ...(checked ? { check: checked } : {}), ...(audited ? { audit: audited } : {}) };
523
602
  }
524
- if (!held && !dueWith(read.workflows))
603
+ if (!held && (stopped || !dueWith(read.workflows)))
604
+ return sayLeftOut(), undefined;
605
+ // A new workflow is compiled once: not while the last compile's passing draft waits on its grade.
606
+ if (!held && (await draftAwaitingGrade(deps.store, input.agentId)))
525
607
  return sayLeftOut(), undefined;
526
608
  // An earlier run's trace is cut of each value it held (traceFrom); one that still holds a secret (a value in a call's
527
609
  // input spelled in JSON escapes, a shape the cut does not take) is left out whole.
@@ -536,8 +618,6 @@ export async function compileAskOf(deps, input) {
536
618
  const { tools, decisions, outputSchema, workflowAdapters, described: sdkCatalog } = await draftTools(deps, input.runId);
537
619
  const allowed = draftDecisionProviders(decisions);
538
620
  const judges = workflowAdapters !== undefined ? workflowAdapters.includes("runJudge") : allowed.length > 0;
539
- // No Jev by default: a draft's steps are asked for no Jev guard, whether or not the run can call Jev (per-step Jev guards
540
- // gave no judgment that moved a served answer; a check in code does that job).
541
621
  const described = sdkCatalog ?? await describedOf(tools, deps.store);
542
622
  const object = input.input !== null && typeof input.input === "object" && !Array.isArray(input.input);
543
623
  leftOut.input = object && holds(input.input);
@@ -3,7 +3,7 @@ import { type LearningLoopDeps } from "./learning-loop.js";
3
3
  import type { LoopFactory } from "./loop-contract.js";
4
4
  /** The harness a learning run's launch names (store/sqlite/run-patch.ts learningLaunchOf). */
5
5
  export declare const LEARNING_HARNESS = "learning";
6
- export interface LearningFactoryDeps extends Pick<LearningLoopDeps, "ask" | "now" | "general" | "generalThreshold"> {
6
+ export interface LearningFactoryDeps extends Pick<LearningLoopDeps, "ask" | "now"> {
7
7
  readonly store: Pick<Store, "runs" | "agents" | "learning">;
8
8
  /** The server's data directory: where each agent's learning folder is. */
9
9
  readonly data: string;
@@ -8,8 +8,7 @@
8
8
  // readMain main as the grader reads it, from the folder's snapshot (learn/commit.ts readMain);
9
9
  // commit the folder's one write (learn/commit.ts learningCommit);
10
10
  // merged the run's merge when it is on main already, with the texts its own commit holds (learn/commit.ts mergedAt),
11
- // for a resume after its commit;
12
- // general the generality pre-check (learn/general.ts), on this host's Jev, when it has one (passed in by the wiring).
11
+ // for a resume after its commit.
13
12
  import { learningCommit, mainTexts, mergedAt, readMain } from "../learn/commit.js";
14
13
  import { learningWorkspace } from "../learn/folder.js";
15
14
  import { createLearningLoop } from "./learning-loop.js";
@@ -46,8 +45,6 @@ export function learningLoopFactory(deps) {
46
45
  mainTexts: (ws, paths) => mainTexts(ws, paths),
47
46
  merged: (ws, runId, paths, round) => mergedAt(ws, runId, paths, round),
48
47
  ...(deps.now ? { now: deps.now } : {}),
49
- ...(deps.general ? { general: deps.general } : {}),
50
- ...(deps.generalThreshold !== undefined ? { generalThreshold: deps.generalThreshold } : {}),
51
48
  ...(deps.log ? { log: deps.log } : {}),
52
49
  });
53
50
  }