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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/NOTICE +2 -0
  3. package/README.md +85 -19
  4. package/dist/agent-rows.d.ts +1 -1
  5. package/dist/agents-store.js +3 -1
  6. package/dist/calendar/address.d.ts +49 -0
  7. package/dist/calendar/address.js +153 -0
  8. package/dist/calendar/fetch.d.ts +24 -0
  9. package/dist/calendar/fetch.js +146 -0
  10. package/dist/calendar/ics-faux.d.ts +39 -0
  11. package/dist/calendar/ics-faux.js +236 -0
  12. package/dist/calendar/labels.d.ts +3 -0
  13. package/dist/calendar/labels.js +61 -0
  14. package/dist/calendar/names.d.ts +52 -0
  15. package/dist/calendar/names.js +54 -0
  16. package/dist/calendar/parse.d.ts +108 -0
  17. package/dist/calendar/parse.js +625 -0
  18. package/dist/calendar/routes.d.ts +17 -0
  19. package/dist/calendar/routes.js +81 -0
  20. package/dist/calendar/tools.d.ts +23 -0
  21. package/dist/calendar/tools.js +124 -0
  22. package/dist/cli.js +3 -1
  23. package/dist/computer-record.d.ts +55 -0
  24. package/dist/computer-record.js +315 -0
  25. package/dist/computer-setting.d.ts +1 -0
  26. package/dist/computer-setting.js +15 -2
  27. package/dist/computers.js +2 -14
  28. package/dist/console/assets/index-BrcDSBD8.css +1 -0
  29. package/dist/console/assets/index-Bz6IWncl.js +711 -0
  30. package/dist/console/index.html +2 -2
  31. package/dist/decisions.js +0 -4
  32. package/dist/eval-feed.d.ts +2 -2
  33. package/dist/eval-feed.js +9 -5
  34. package/dist/feed/parse.d.ts +3 -2
  35. package/dist/feed/parse.js +9 -18
  36. package/dist/feed/pointer.d.ts +2 -0
  37. package/dist/feed/pointer.js +17 -0
  38. package/dist/file-types.js +1 -0
  39. package/dist/host-command.d.ts +3 -0
  40. package/dist/host-command.js +18 -0
  41. package/dist/host.d.ts +3 -0
  42. package/dist/host.js +3 -0
  43. package/dist/import-sources.js +25 -5
  44. package/dist/learn/audit.d.ts +123 -0
  45. package/dist/learn/audit.js +159 -0
  46. package/dist/learn/check.d.ts +14 -0
  47. package/dist/learn/check.js +194 -14
  48. package/dist/learn/compile.d.ts +75 -78
  49. package/dist/learn/compile.js +175 -176
  50. package/dist/learn/folder.d.ts +9 -0
  51. package/dist/learn/folder.js +13 -2
  52. package/dist/learn/promote.d.ts +138 -196
  53. package/dist/learn/promote.js +68 -184
  54. package/dist/learn/replay-calls.d.ts +5 -0
  55. package/dist/learn/replay-calls.js +12 -1
  56. package/dist/learn/secrets.d.ts +8 -0
  57. package/dist/learn/secrets.js +12 -0
  58. package/dist/learn/skills.js +2 -4
  59. package/dist/learn/workflow-nodes.d.ts +1 -2
  60. package/dist/learn/workflow-nodes.js +2 -3
  61. package/dist/learned-nodes.d.ts +9 -34
  62. package/dist/learned-nodes.js +11 -23
  63. package/dist/learned-workflow.d.ts +6 -8
  64. package/dist/learned-workflow.js +18 -57
  65. package/dist/learning-batch.d.ts +13 -5
  66. package/dist/learning-batch.js +34 -8
  67. package/dist/learning-cost.d.ts +11 -4
  68. package/dist/learning-cost.js +4 -2
  69. package/dist/learning-routes.js +1 -1
  70. package/dist/learning-setting.d.ts +38 -0
  71. package/dist/learning-setting.js +83 -0
  72. package/dist/learning-words.d.ts +3 -0
  73. package/dist/learning-words.js +3 -0
  74. package/dist/learning.d.ts +3 -2
  75. package/dist/learning.js +5 -3
  76. package/dist/mcp-oauth.d.ts +8 -0
  77. package/dist/mcp-oauth.js +7 -0
  78. package/dist/mcp-private-hosts.d.ts +13 -0
  79. package/dist/mcp-private-hosts.js +16 -0
  80. package/dist/openapi.d.ts +1 -0
  81. package/dist/openapi.js +195 -59
  82. package/dist/run-files.d.ts +6 -2
  83. package/dist/run-files.js +29 -7
  84. package/dist/run-launch.d.ts +6 -3
  85. package/dist/run-launch.js +2 -0
  86. package/dist/run-learning-served.d.ts +2 -2
  87. package/dist/run-reads-over-store.d.ts +5 -1
  88. package/dist/run-reads-over-store.js +8 -4
  89. package/dist/run-recordings.d.ts +20 -0
  90. package/dist/run-recordings.js +133 -0
  91. package/dist/runner/adapter-loop.d.ts +5 -1
  92. package/dist/runner/adapter-loop.js +20 -8
  93. package/dist/runner/adapter-run-spec.d.ts +16 -1
  94. package/dist/runner/adapter-run-spec.js +36 -11
  95. package/dist/runner/audit.d.ts +64 -0
  96. package/dist/runner/audit.js +338 -0
  97. package/dist/runner/beside.js +2 -2
  98. package/dist/runner/cli-run-spec.js +25 -12
  99. package/dist/runner/feedback-round.d.ts +9 -25
  100. package/dist/runner/feedback-round.js +19 -40
  101. package/dist/runner/harness-loops.js +1 -15
  102. package/dist/runner/journal-kinds.d.ts +0 -7
  103. package/dist/runner/journal-kinds.js +0 -7
  104. package/dist/runner/learning-dispatch.d.ts +0 -16
  105. package/dist/runner/learning-dispatch.js +4 -47
  106. package/dist/runner/learning-end.d.ts +62 -13
  107. package/dist/runner/learning-end.js +180 -74
  108. package/dist/runner/learning-factory.d.ts +1 -1
  109. package/dist/runner/learning-factory.js +1 -4
  110. package/dist/runner/learning-loop.d.ts +2 -38
  111. package/dist/runner/learning-loop.js +8 -116
  112. package/dist/runner/main.d.ts +11 -0
  113. package/dist/runner/main.js +30 -3
  114. package/dist/runner/mcp-run.d.ts +2 -2
  115. package/dist/runner/promotion.d.ts +78 -50
  116. package/dist/runner/promotion.js +371 -503
  117. package/dist/runner/reflect-hook.d.ts +15 -0
  118. package/dist/runner/reflect-hook.js +28 -14
  119. package/dist/runner/store-secrets.js +3 -1
  120. package/dist/runner/workflow-first.d.ts +6 -11
  121. package/dist/runner/workflow-first.js +24 -25
  122. package/dist/runs-over-store.d.ts +1 -1
  123. package/dist/sdk/runs.js +2 -1
  124. package/dist/secrets.js +2 -2
  125. package/dist/server.d.ts +4 -3
  126. package/dist/server.js +132 -26
  127. package/dist/store/agent-body.d.ts +5 -3
  128. package/dist/store/agent-body.js +14 -10
  129. package/dist/store/sqlite/store.js +1 -0
  130. package/dist/store/store.d.ts +3 -0
  131. package/dist/store-reads/learning.d.ts +18 -7
  132. package/dist/store-reads/learning.js +36 -23
  133. package/dist/store-reads/loop.d.ts +5 -39
  134. package/dist/store-reads/loop.js +21 -80
  135. package/dist/store-view.d.ts +5 -0
  136. package/dist/store-view.js +16 -2
  137. package/dist/template-eval.d.ts +7 -0
  138. package/dist/template-eval.js +54 -6
  139. package/dist/templates.d.ts +3 -1
  140. package/dist/templates.js +14 -1
  141. package/dist/timeline/computer.js +2 -1
  142. package/dist/tool-list.js +1 -0
  143. package/dist/tools.d.ts +7 -0
  144. package/dist/tools.js +11 -0
  145. package/dist/trigger-feed.js +67 -18
  146. package/dist/validate.js +7 -2
  147. package/dist/workspace/computer-for-claim.d.ts +7 -0
  148. package/dist/workspace/computer-for-claim.js +12 -2
  149. package/dist/workspace/paths.d.ts +4 -0
  150. package/dist/workspace/paths.js +9 -0
  151. package/dist/workspace/resolve-computer.d.ts +3 -1
  152. package/dist/workspace/run-tools.d.ts +1 -1
  153. package/dist/workspace/run-tools.js +14 -3
  154. package/launcher/agentrun-serve +31 -24
  155. package/package.json +10 -9
  156. package/templates/README.md +11 -2
  157. package/dist/console/assets/index-C3gNPz58.css +0 -1
  158. package/dist/console/assets/index-COGhx_2Z.js +0 -711
  159. package/dist/learn/general.d.ts +0 -69
  160. package/dist/learn/general.js +0 -75
  161. package/dist/learn/refit.d.ts +0 -48
  162. package/dist/learn/refit.js +0 -264
  163. package/dist/runner/step-guard.d.ts +0 -62
  164. package/dist/runner/step-guard.js +0 -93
@@ -1,8 +1,9 @@
1
- // Compile: once an agent's job has repeated (COMPILE_AFTER_NOTES kept notes, or COMPILE_AFTER_RUNS completed runs) and it
2
- // has no learned workflow, its end-of-run look-back asks one more turn in the same session: the whole job as one workflow
1
+ // Compile: once an agent has its definition's `compile_after` completed agent runs (learning-setting.ts, default 20) and
2
+ // no learned workflow, its end-of-run look-back asks one more turn in the same session: the whole job as one workflow
3
3
  // draft, from what it learned (its notes) and its last runs (each run's input, tool calls, answer and what the person
4
- // said after it). A run its learned workflow handed back, or one the money rule stopped from running first, asks the
5
- // same turn for that workflow's next revision. The turn is written against the checker, not from prose: it carries the
4
+ // said after it). A workflow its promotion holds asks the same turn for its next revision, once per hold: the check
5
+ // that held a first draft (runner/promotion.ts) gives it the inputs it disagreed on, as data; a check that held the
6
+ // revision too stops (nothing compiles again). The turn is written against the checker, not from prose: it carries the
6
7
  // workflow language as the DSL renders it from its own vocabulary (authorContract, with this host's addendum), and one
7
8
  // worked example the checks pass. Its answer is checked as a look-back's draft is (propose.ts: the static checks, then a
8
9
  // dry run); what they refuse goes back to the model, as data, and the turn answers again, up to COMPILE_RETRIES times.
@@ -11,22 +12,16 @@
11
12
  // The notes a kept draft does the work of get `compiled_into: <workflow>` in their front matter when it merges
12
13
  // (learn/commit.ts), and stay served: a run the workflow hands back is done by hand with them.
13
14
  import { createHash } from "node:crypto";
14
- import { childNodes, LEARNED_MAX_TURNS, frontMatter, WORKFLOW_NAME, WORKFLOWS_DIR } from "./skills.js";
15
+ import { LEARNED_MAX_TURNS, frontMatter, WORKFLOW_NAME, WORKFLOWS_DIR } from "./skills.js";
15
16
  import { NOTE_BLOCK, parseReflection, SKILL_BLOCK, WORKFLOW_BLOCK } from "./reflect.js";
16
17
  import { NOTE_FILE } from "./notes.js";
17
- import { answersAlone, championOf, LABEL_MAX, PROMOTE_BAR, promotionOf, replayingOf } from "./promote.js";
18
- import { redactSecrets } from "./secrets.js";
19
- /** How many active notes an agent keeps before its look-back compiles its job. */
20
- export const COMPILE_AFTER_NOTES = 3;
21
- /** How many completed runs an agent has (the ending one counted) before its look-back compiles its job. */
22
- export const COMPILE_AFTER_RUNS = 5;
18
+ import { championOf, checkShares, promotionOf } from "./promote.js";
19
+ import { excerptShown, redactSecrets } from "./secrets.js";
20
+ import { isShadowRun } from "./audit.js";
23
21
  /** How many of the agent's last runs (before the ending one, which is in the session already) the compile turn reads. */
24
22
  export const COMPILE_TRACES = 5;
25
23
  /** How many times a refused draft goes back to the model with its errors: at most 1 + COMPILE_RETRIES attempts. */
26
24
  export const COMPILE_RETRIES = 3;
27
- /** How many of an agent's runs before the ending one are read for an earlier compile: one there (it may still wait for
28
- * its grade, or it failed) asks none now, so a job is compiled at most once in that many runs. */
29
- export const COMPILE_QUIET_RUNS = 4;
30
25
  /** The longest the compile turn may take, every attempt in it, before the run ends with what it has. */
31
26
  export const COMPILE_TIMEOUT_MS = 10 * 60_000;
32
27
  /** The most of a run's trace the compile turn holds, in characters. */
@@ -37,49 +32,88 @@ export const NOTES_MAX = 96_000;
37
32
  /** The most errors one attempt keeps, each cut to ERROR_MAX characters. */
38
33
  const ERRORS_MAX = 10;
39
34
  const ERROR_MAX = 400;
40
- /** Whether the draft a compile kept at `digest` serves (learn/promote.ts records, newest wins): true once promoted, or
41
- * once a threshold refit of it was (its new revision serves in its place); false while held, or once a newer revision
42
- * was skipped for a newer one; undefined while it is queued or replayed, or before its first claim decides it. */
35
+ /** Whether the draft a compile kept at `digest` serves (learn/promote.ts records, newest wins): true once promoted, false
36
+ * while held; undefined while its check runs, or before its first claim decides it. */
43
37
  export function promotedOf(records, workflow, digest) {
44
38
  const own = promotionOf(records, workflow, digest);
45
39
  if (own?.decided === "promote")
46
40
  return true;
47
- if (records.some((one) => one.workflow === workflow && one.decided === "promote" && one.source === "refit" && one.refit?.from === digest))
48
- return true;
49
- return own?.decided === "hold" || own?.decided === "skipped" ? false : undefined;
41
+ return own?.decided === "hold" ? false : undefined;
50
42
  }
51
43
  /** The learned workflows whose newest revision other than their champion (learn/promote.ts championOf, which serves while
52
44
  * that revision is held) is held: each one's compile turn is asked for a revision (once per hold). A champion's own
53
- * graded hold counts: with it held there is no champion. One with a revision queued is not: that newer revision replays
54
- * next (a replay ahead of it held meanwhile asks for nothing). */
45
+ * hold counts: with it held there is no champion. Not one a check stopped (its recompile's check held it too): nothing
46
+ * compiles it again. */
55
47
  export function heldNamesOf(records) {
56
48
  return new Set([...new Set(records.map(({ workflow }) => workflow))].filter((name) => {
57
49
  const champion = championOf(records, name)?.digest;
58
- return records.findLast((one) => one.workflow === name && one.digest !== champion)?.decided === "hold" && !replayingOf(records, name, null, "queued").length;
50
+ const newest = records.findLast((one) => one.workflow === name && one.digest !== champion);
51
+ return newest?.decided === "hold" && !newest.check?.stopped && !newest.audit?.stopped;
59
52
  }));
60
53
  }
54
+ /** The words a compile's promotion record starts with when every draft of its turn failed its checks (runner/
55
+ * learning-end.ts recordDraftFailed): a hold with nothing checked, the compile's attempt all the same. */
56
+ export const DRAFT_FAILED = "its draft failed its checks";
57
+ /** Whether a promotion record is a compile turn's failed draft (DRAFT_FAILED), not a check's decision. */
58
+ export const draftFailedOf = (record) => record.check?.n === 0 && record.reason.startsWith(`${DRAFT_FAILED}:`);
59
+ /** Which compile a new workflow's is, for an agent with no learned workflow: 2 (the one recompile) right after a first
60
+ * compile whose drafts all failed their checks (the agent's newest record), else 1. */
61
+ export function newCompileAttempt(records) {
62
+ const last = records.at(-1);
63
+ return last && draftFailedOf(last) && last.check?.attempt === 1 && !last.check.stopped ? 2 : 1;
64
+ }
65
+ /** Whether the agent's compile stopped on its drafts: its newest record is a recompile's failed draft (nothing compiles
66
+ * a new workflow again until its owner acts). */
67
+ export function compileStoppedOf(records) {
68
+ const last = records.at(-1);
69
+ return last !== undefined && draftFailedOf(last) && last.check?.stopped === true;
70
+ }
71
+ /** Whether a store run ended completed (its state `ended`, a plain completion), and is no audit's shadow run (an
72
+ * agent's answer kept for an audit, never a run of the agent's own to learn from). */
73
+ export const completedRun = (run) => run.state === "ended" && (run.outcome === null || run.outcome === "completed") && !isShadowRun(run.id);
74
+ /** Whether a store run is a completed run of the agent's own (completedRun), not one its learned workflow answered alone
75
+ * nor a check's replay run (nor an audit's shadow, completedRun): what compile_after counts. */
76
+ export const agentRun = (run) => {
77
+ const path = run.metrics?.path;
78
+ return completedRun(run) && path !== "workflow" && path !== "replay";
79
+ };
80
+ /** The first page of the agent's runs lastRunsOf reads; each page after it is OWN_PAGE_GROWTH times the one before,
81
+ * until it holds `n` of the runs it keeps or the agent has no more. */
82
+ const OWN_PAGE_MIN = 200;
83
+ const OWN_PAGE_GROWTH = 4;
84
+ /** The agent's newest `n` runs that `keep` keeps (of those the store lists by `listed`: e.g. only ended, not archived),
85
+ * newest first, picked before anything else limits them: runs it does not keep, however many, never push them out of the
86
+ * read (it reads more of the agent's runs until it has `n`, or there are no more). */
87
+ export async function lastRunsOf(store, agentId, n, keep, listed = {}) {
88
+ for (let limit = Math.max(OWN_PAGE_MIN, 3 * n);; limit *= OWN_PAGE_GROWTH) {
89
+ const page = await store.runs.list({ agentId, ...listed, limit });
90
+ const found = page.filter(keep).slice(0, n);
91
+ if (found.length >= n || page.length < limit)
92
+ return found;
93
+ }
94
+ }
95
+ /** The agent's last `n` completed runs of its own (agentRun: not one its learned workflow answered alone, not a replay
96
+ * nor a shadow audit; never `exceptRunId`, an archived run or an imported one), newest first (lastRunsOf: runs its
97
+ * workflow served since never push them out of the read). The one read of what compile_after counts and of a check's
98
+ * inputs. */
99
+ export const lastOwnRuns = (store, agentId, n, exceptRunId) => lastRunsOf(store, agentId, n, (row) => row.id !== exceptRunId && agentRun(row) && row.archivedAt === null && !row.importedFrom, { state: "ended", archived: false });
61
100
  /** Whether a run's look-back compiles its agent's job: the run completed, the agent has no learned workflow (active or
62
- * waiting for its owner's OK), none of its last COMPILE_QUIET_RUNS runs compiled, and it keeps COMPILE_AFTER_NOTES
63
- * active notes or has COMPILE_AFTER_RUNS completed runs. */
64
- export const compileDue = (facts) => facts.completed && facts.workflows === 0 && !facts.compiledLately && (facts.notes >= COMPILE_AFTER_NOTES || facts.runs >= COMPILE_AFTER_RUNS);
101
+ * waiting for its owner's OK), and it has `compileAfter` completed
102
+ * agent runs (its definition's compile_after, learning-setting.ts), the ending one counted. */
103
+ export const compileDue = (facts) => facts.completed && facts.workflows === 0 && facts.runs >= facts.compileAfter;
65
104
  /** The node kinds a learned workflow runs (learned-workflow.ts runLearned): model and tool-call nodes and the control
66
105
  * nodes around them; judge, pick, sift and route on a run with a decision provider. Never code (it would run in the
67
106
  * host's process), a report or an artifact (its answer is the value at output.path). */
68
107
  const LEARNED_KINDS = ["chain", "extract", "decide", "agent", "call", "escalate", "map", "parallel", "loop"];
69
108
  const JUDGING_KINDS = ["judge", "pick", "sift", "route"];
70
- /** The threshold a compiled step's guard starts at (SPEC: the guard shape), until the host fits one on graded runs. */
71
- export const GUARD_THRESHOLD = 0.7;
72
- /** The guards a compiled step is asked for (SPEC: the guard shape; Jev by default): with Jev, a judgment step's own
73
- * confidence and Jev's read together (`both`: min until a refit fits a logistic), and Jev alone on a step that reports
74
- * no confidence (extract, call); without it, the step's own confidence, and no guard where there is none. */
75
- const guardOf = (signal) => ({ signal, threshold: GUARD_THRESHOLD });
76
- const guardText = (signal) => `\`"guard": {"signal": "${signal}", "threshold": ${GUARD_THRESHOLD}}\``;
77
109
  /** The quote check a compiled workflow's answer gets when it quotes fetched pages (check.ts quoteCheckProblems refuses a
78
- * draft without it): code, never a judge. */
79
- const QUOTE_CHECK_RULE = "An answer that quotes pages a call step fetched is checked in code: an escalate on `{\"predicate\": \"quote_missing\", \"path\": \"<the answer's quotes, e.g. answer.evidence>\", \"field\": \"quote\", \"pages\": [<the keys the call steps write>]}`, a step of the top-level chain after the step that writes the answer, hands back an answer quoting text no fetched page holds. Its pages are what the calls fetched, never a model's summary of them. Never ask a judge, an `ask` or a guard whether quotes are verbatim. Give the answer one re-pick before it hands back: make the step that writes the answer the body of a `loop` with `\"maxIters\": 2` and `\"until\": {\"predicate\": \"not\", \"of\": <that same quote_missing>}`, its instructions saying that a draft already in state failed the quote check (recopy each quote exactly from the page it names, or quote another line); the step in the loop has no `state` map, so it reads the whole run state and its second pass sees the failed draft (a `state` map passes only the keys it names, and naming the answer there fails the first pass, before any draft exists); and keep the escalate a step of the top-level chain: the check after the loop, never inside it (a check in its body hands back on the first miss, so the loop never re-picks); only a second miss hands back. The loop's `until` reads one check: keep the answer's quotes in one place one `quote_missing` reads (a quote, a list of quotes or a list of records each holding its quote at one field), never a quote that may be a string or records, nor quotes in two places.";
110
+ * draft without it): code, never a judge, and one re-pick whose step reads its failed draft through an optional
111
+ * placeholder in its `state` map, never the whole state (compactStateProblems: no page reaches a step off the fast tier). */
112
+ const QUOTE_CHECK_RULE = "An answer that quotes pages a call step fetched is checked in code: an escalate on `{\"predicate\": \"quote_missing\", \"path\": \"<the answer's quotes, e.g. answer.evidence>\", \"field\": \"quote\", \"pages\": [<the keys the call steps write>]}`, a step of the top-level chain after the step that writes the answer, hands back an answer quoting text no fetched page holds. Its pages are what the calls fetched, never a model's summary of them. Never ask a judge or an `ask` whether quotes are verbatim. Give the answer one re-pick before it hands back: make the step that writes the answer the body of a `loop` with `\"maxIters\": 2` and `\"until\": {\"predicate\": \"not\", \"of\": <that same quote_missing>}`; the step in the loop reads the compact facts and its own failed draft through its `state` map, e.g. `{\"facts\": \"{facts}\", \"draft\": \"{answer?}\"}`: the `?` makes the placeholder null on the first pass, before any draft exists, and the failed draft on the second (unmarked, `\"{answer}\"` fails the first pass; with no `state` map the step reads the whole state, pages included), and its instructions say that a draft there failed the quote check (recopy each quote exactly from the facts, or quote another line); keep the escalate a step of the top-level chain: the check after the loop, never inside it (a check in its body hands back on the first miss, so the loop never re-picks); only a second miss hands back. The loop's `until` reads one check: keep the answer's quotes in one place one `quote_missing` reads (a quote, a list of quotes or a list of records each holding its quote at one field), never a quote that may be a string or records, nor quotes in two places.";
113
+ /** The compact-state rule (check.ts compactStateProblems): a model step off the fast tier never reads a page. */
114
+ const COMPACT_STATE_RULE = "A model step off the fast tier (no `\"tier\": \"fast\"`: the answering step among them) never reads a page a call step fetched. Give it a `state` map naming only compact keys: the facts a fast-tier extract step wrote from the pages (the verbatim lines the answer will quote among them), the run's own small input fields, and, in a re-pick loop, its own draft as `\"{answer?}\"`. With no `state` map a step reads the whole state, every page in it. Pages reach the agent's model only through a fast-tier step's output.";
80
115
  /** This host's addendum to the DSL's author contract: the node kinds it runs, and its rules, each one the checks hold a
81
- * draft to (learn/skills.ts draftProblems; propose.ts). `jev`: the run can call Jev (one of its decision providers,
82
- * not denied), so every step is asked for a guard Jev reads. */
116
+ * draft to (learn/skills.ts draftProblems; propose.ts; check.ts). */
83
117
  export function learnedHost(options) {
84
118
  const { tools, judges } = options;
85
119
  if (options.workflowAdapters !== undefined) {
@@ -92,15 +126,12 @@ export function learnedHost(options) {
92
126
  tools.length ? `A call node runs via tool alone and names only this allowed callback catalog: ${tools.join(", ")}. Its arguments and output schema must match that callback. Never shell or executor.` : "There is no allowed tool callback: author no call node.",
93
127
  model ? "runNode is explicitly registered for tool-free model nodes. It owns model selection; name no model or tier and grant its model nodes no tools." : "This backend provides NO runNode: author no extract, decide or agent node. Never invent a model adapter.",
94
128
  judge ? "runJudge is explicitly registered for decision nodes; the backend owns its implementation." : "This backend provides NO runJudge: author no judge, pick, sift, verification or model-based predicate.",
95
- "There is no guardStep callback: author no step guard, including self, jev or both. Do not assume hosted decision or confidence machinery.",
96
129
  `At most 128 static nodes. Never automatically retry a delegated tool call. An agent node uses at most ${LEARNED_MAX_TURNS} max_turns and never context fork.`,
97
130
  "The workflow's declared input takes the caller's fields. output.path selects the job's actual answer in its required format; use a declared formatter callback when necessary.",
98
131
  QUOTE_CHECK_RULE,
99
132
  ],
100
133
  };
101
134
  }
102
- const jev = options.jev === true;
103
- const judgment = judges ? "decide, agent, judge, pick and sift" : "decide and agent";
104
135
  return {
105
136
  name: "AgentRun learned workflow",
106
137
  nodeKinds: [...LEARNED_KINDS, ...(judges ? JUDGING_KINDS : [])],
@@ -111,12 +142,10 @@ export function learnedHost(options) {
111
142
  "A model node (extract, decide, agent) names no `tools`: it runs in a session of its own with none. Fetch with a call node.",
112
143
  `An agent node asks at most ${LEARNED_MAX_TURNS} \`max_turns\`, and never \`context: "fork"\`.`,
113
144
  "Give each legwork model node `\"tier\": \"fast\"`. The step that writes the answer (`output.path`) names no tier: it runs on the agent's model.",
145
+ COMPACT_STATE_RULE,
114
146
  "`input.schemaId` names a schema whose required fields are the run's own input fields, as a run is given them: then the workflow runs first on later runs, before the agent.",
115
147
  "`output.path` is required: the workflow's answer is the value there, the job's answer in the format the runs answered with.",
116
- jev
117
- ? `Give every ${judgment} step a guard ${guardText("both")}: its own confidence and one Jev check of its output against its input, read together. The step submits its confidence beside its record, so its output schema has no confidence field${judges ? "; a judge, pick or sift step reads its weakest answer" : ""}. Give every extract and call step a guard ${guardText("jev")}: it reports no confidence of its own, so Jev alone checks it. Each threshold starts at ${GUARD_THRESHOLD}; the host refits it on graded runs.`
118
- : `Give every ${judgment} step a guard ${guardText("self")}: the step submits its confidence beside its record, so its output schema has no confidence field${judges ? "; a judge, pick or sift step reads its weakest answer" : ""}. This run cannot call Jev: a guard reads \`self\` alone, never \`jev\` or \`both\`, and an extract or call step takes no guard.`,
119
- "An escalate step hands back a case the job's own rules send to a person, on a value a step wrote (`field_equals`, `in`); an unsure step is the guard's to hand back, not an escalate's.",
148
+ "An escalate step hands back a case the job's own rules do not cover, on a value a step wrote (`field_equals`, `in`), or a quote check's second miss.",
120
149
  QUOTE_CHECK_RULE,
121
150
  ],
122
151
  };
@@ -125,41 +154,66 @@ export function learnedHost(options) {
125
154
  * it names exactly the kinds, fields and predicates its validator admits) with this host's addendum. */
126
155
  export const compileReference = (dsl, options) => dsl.authorContract({ host: learnedHost(options) });
127
156
  /** The worked example's input, as a run gives it. */
128
- export const EXAMPLE_INPUT = { content: "Refund request: order 1043, a $42 kettle that arrived broken, bought 9 days ago." };
129
- /** The worked example: a whole job, input to answer, that the checks and the dry run pass (a test holds it to them).
130
- * An extract step reads the facts on the fast tier, a judge asks one typed question of them (with a decision provider),
131
- * a decide step answers on the agent's own model (no tier: answerTierProblems), and an escalate step hands back a case the policy does not cover. With Jev (`jev`) each judgment step is
132
- * guarded on its own confidence and Jev's (`both`) and the extract step on Jev's; without, the judgment steps on their
133
- * own confidence alone. */
134
- export function compileExample(judges, jev = false) {
135
- const guard = guardOf(jev ? "both" : "self");
136
- const facts = jev ? { guard: guardOf("jev") } : {};
157
+ export const EXAMPLE_INPUT = { content: "Is the parser library at https://example.org/parser under a permissive licence?" };
158
+ /** The tool the worked example's call step names: it stands for the tool the agent's runs read pages with. */
159
+ export const EXAMPLE_TOOL = "fetch_page";
160
+ /** The worked example's name. */
161
+ const EXAMPLE_NAME = "licence-check";
162
+ /** The quote check of the worked example's answer: its evidence quotes, against the page its call step fetched. */
163
+ const EXAMPLE_QUOTE_CHECK = { predicate: "quote_missing", path: "answer.evidence", field: "quote", pages: ["page"] };
164
+ /** The worked example: the cascade skeleton every repeated job compiles to (H1, H5d: ~$0.08 a run booked against the
165
+ * agent's ~$0.89), a whole job, input to answer, that the checks and the dry run pass (a test holds it to them). The
166
+ * legwork on the fast tier: an extract step reads the target from the input, a call step fetches its page (`fetches`:
167
+ * the run has a tool), an extract step copies compact facts from the page, the verbatim lines the answer will quote among
168
+ * them. The answer on the agent's own model (no tier: answerTierProblems) from those facts and its own draft alone, never
169
+ * the page (compactStateProblems), in a re-pick loop of 2 until its quotes are in the page (quoteCheckProblems); then the
170
+ * quote check hands back a second miss, and an escalate step a case the policy does not cover.
171
+ * With no tool to fetch with, the facts come from the input and the answer quotes nothing it must check. */
172
+ export function compileExample(fetches = true) {
173
+ const quote = { type: "object", properties: { url: { type: "string" }, quote: { type: "string" } }, required: ["url", "quote"] };
137
174
  const schemas = {
138
175
  Request: { type: "object", properties: { content: { type: "string" } }, required: ["content"] },
139
- Facts: { type: "object", properties: { item: { type: "string" }, amount_usd: { type: ["number", "null"] }, days_since_purchase: { type: ["number", "null"] }, damaged: { type: "boolean" } }, required: ["item", "amount_usd", "days_since_purchase", "damaged"] },
140
- Answer: { type: "object", properties: { decision: { type: "string", enum: ["refund", "replace", "decline", "needs_review"] }, reply: { type: "string" } }, required: ["decision", "reply"] },
141
- ...(judges ? { Policy: { type: "object", properties: { within_policy: { type: "boolean", description: "Is this request within a 30-day refund policy for a damaged item?" } }, required: ["within_policy"] } } : {}),
176
+ ...(fetches ? {
177
+ Target: { type: "object", properties: { name: { type: "string" }, url: { type: "string" } }, required: ["name", "url"] },
178
+ Page: { type: "object", properties: { url: { type: "string" }, text: { type: "string" } }, required: ["text"] },
179
+ } : {}),
180
+ Facts: { type: "object", properties: { licence: { type: ["string", "null"] }, quotes: { type: "array", items: quote } }, required: ["licence", "quotes"] },
181
+ Answer: { type: "object", properties: { verdict: { type: "string", enum: ["permissive", "copyleft", "proprietary", "unclear"] }, reason: { type: "string" }, evidence: { type: "array", items: quote } }, required: ["verdict", "reason", "evidence"] },
142
182
  };
143
- const steps = [
144
- { node: "extract", label: "facts", instructions: "Read the request: the item, its price in dollars, how many days ago it was bought, and whether it arrived damaged. Null for what it does not say.", state: { content: "{content}" }, out: "Facts", as: "facts", tier: "fast", ...facts },
145
- ...(judges ? [{ node: "judge", label: "policy", state: { facts: "{facts}" }, out: "Policy", as: "policy", guard }] : []),
146
- { node: "decide", label: "answer", instructions: "Decide refund, replace or decline by the refund policy, and write the reply to the customer. A request the policy does not cover is needs_review.", state: judges ? { facts: "{facts}", policy: "{policy}" } : { facts: "{facts}" }, out: "Answer", as: "answer", guard },
147
- { node: "escalate", label: "review", when: { predicate: "field_equals", path: "answer.decision", value: "needs_review" }, kind: "needs_review", stage: "answer", summary: "The policy does not cover this request: {answer.reply}" },
148
- ];
149
- return { v: 2, name: "refund-request", schemas, input: { schemaId: "Request" }, output: { schemaId: "Answer", path: "answer" }, root: { node: "chain", steps } };
183
+ const answer = (state) => ({ node: "decide", label: "answer", instructions: `Say whether the licence the facts name is permissive, copyleft or proprietary, with the reason in one sentence; evidence: 1-3 lines copied exactly from facts.quotes, each with its url. A licence the facts do not settle is unclear.${fetches ? " A draft that is not null failed the quote check: recopy each of its quotes exactly from facts.quotes, or quote another line." : ""}`, state, out: "Answer", as: "answer" });
184
+ const unclear = { node: "escalate", label: "unclear", when: { predicate: "field_equals", path: "answer.verdict", value: "unclear" }, kind: "needs_review", stage: "answer", summary: "The pages read do not settle the licence: {answer.reason}" };
185
+ const steps = fetches
186
+ ? [
187
+ { node: "extract", label: "target", instructions: "Copy the library's name and the URL the request gives, exactly as written.", state: { content: "{content}" }, out: "Target", as: "target", tier: "fast" },
188
+ { node: "call", label: "fetch", via: "tool", tool: EXAMPLE_TOOL, args: { url: "{target.url}" }, out: "Page", as: "page", deadline_s: 60 },
189
+ { node: "extract", label: "facts", instructions: "From the page only: the licence's name, or null; quotes: up to 4 lines naming the licence or its terms, each one unbroken run copied exactly from the page, with the page's url.", state: { target: "{target}", page: "{page}" }, out: "Facts", as: "facts", tier: "fast" },
190
+ { node: "loop", label: "repick", maxIters: 2, until: { predicate: "not", of: EXAMPLE_QUOTE_CHECK }, body: answer({ target: "{target}", facts: "{facts}", draft: "{answer?}" }) },
191
+ { node: "escalate", label: "quotes", when: EXAMPLE_QUOTE_CHECK, kind: "quote_missing", stage: "answer", summary: "An evidence quote for {target.name} is in no page this run read, after one re-pick." },
192
+ unclear,
193
+ ]
194
+ : [
195
+ { node: "extract", label: "facts", instructions: "From the request only: the licence's name, or null; quotes: up to 4 lines of the request naming the licence or its terms, copied exactly.", state: { content: "{content}" }, out: "Facts", as: "facts", tier: "fast" },
196
+ answer({ facts: "{facts}" }),
197
+ unclear,
198
+ ];
199
+ return { v: 2, name: EXAMPLE_NAME, schemas, input: { schemaId: "Request" }, output: { schemaId: "Answer", path: "answer" }, root: { node: "chain", steps } };
150
200
  }
201
+ /** What the prompt says of the worked example: the cascade's shape, and which of its parts are the job's to fill. */
202
+ const exampleLine = (fetches) => fetches
203
+ ? `The shape to compile to: the legwork on the fast tier (a call step fetches the page, a fast extract step copies compact facts from it, the verbatim lines the answer will quote among them), the answer decided on the agent's model from those facts and its own draft alone, never a page, its quotes checked against the fetched page in code after one re-pick, and a case the policy does not cover handed back. Fill in this job's parts from your runs: what to fetch and with which tool (\`${EXAMPLE_TOOL}\` stands for the tool your runs read with: name only the tools listed under This job, with the arguments each takes), which facts to copy, and how to decide.`
204
+ : "The shape to compile to: the facts read on the fast tier, the answer decided on the agent's model from those facts alone, and a case the policy does not cover handed back. Fill in this job's parts from your runs: which facts to copy, and how to decide.";
151
205
  /** The worked example as an answer block, whole: front matter, then the JSON. */
152
- const exampleBlock = (judges, jev) => [
153
- `\`\`\`\`${WORKFLOW_BLOCK} refund-request`,
206
+ const exampleBlock = (fetches) => [
207
+ `\`\`\`\`${WORKFLOW_BLOCK} ${EXAMPLE_NAME}`,
154
208
  "---",
155
- "description: Decides a refund request and writes the reply; use when a customer asks for a refund",
209
+ "description: Says whether a library's licence is permissive, quoting its page; use when asked about a library's licence",
156
210
  `example: ${JSON.stringify(EXAMPLE_INPUT)}`,
157
- "from_notes: [refund-window.md, damaged-items.md]",
211
+ "from_notes: [licence-names.md]",
158
212
  "---",
159
- JSON.stringify(compileExample(judges, jev)),
213
+ JSON.stringify(compileExample(fetches)),
160
214
  "````",
161
215
  ].join("\n");
162
- /** SDK syntax example: a delegated effect, with no implicit model or guard callback. Catalog schemas remain authoritative. */
216
+ /** SDK syntax example: a delegated effect, with no implicit model callback. Catalog schemas remain authoritative. */
163
217
  const sdkExampleBlock = (tool) => [
164
218
  `\`\`\`\`${WORKFLOW_BLOCK} read-value`, "---", "description: Read a value through the declared backend callback when requested.",
165
219
  'example: {"key":"example"}', "---",
@@ -184,6 +238,19 @@ const fenced = (what, text) => {
184
238
  const token = fenceToken(what, text);
185
239
  return [`----- begin ${token}: ${what} -----`, text, `----- end ${token} -----`];
186
240
  };
241
+ /** A check's disagreement as the prompt fences it (learn/promote.ts CheckDisagreement). */
242
+ const disagreementText = (one, i) => clean([
243
+ `Input ${i + 1}: ${one.input}`,
244
+ `Your answer: ${one.agent ?? "(none recorded)"}`,
245
+ one.draft !== undefined ? `The draft's answer: ${one.draft}` : one.escalated !== undefined ? `The draft handed it back: ${one.escalated}` : "The draft failed on it: a step did not finish.",
246
+ ].join("\n"), TRACE_MAX);
247
+ /** An audited run the workflow disagreed on, as the prompt fences it: its input, the agent's answer on its shadow run (or
248
+ * the grade's mark for a run a person graded wrong), and the workflow's served answer. */
249
+ const auditDisagreementText = (one, i) => clean([
250
+ `Input ${i + 1}: ${one.input}`,
251
+ one.graded ? "A person graded the workflow's answer wrong." : `Your answer: ${one.agent ?? "(none recorded)"}`,
252
+ `The workflow's answer: ${one.draft ?? "(none recorded)"}`,
253
+ ].join("\n"), TRACE_MAX);
187
254
  /** A trace as the prompt fences it. */
188
255
  const traceText = (trace, n) => clean([
189
256
  `Run ${n}. Asked: ${trace.input}`,
@@ -223,29 +290,22 @@ export function compilePrompt(ask) {
223
290
  ]
224
291
  : [
225
292
  `${COMPILE_OPENS.revise} \`${ask.workflow}\`.`,
226
- ask.handedBack
227
- ? `Your learned workflow \`${ask.workflow}\` ran first on this run and handed it back to you.`
228
- : ask.revise
229
- ? `Your learned workflow \`${ask.workflow}\` no longer runs first: over its last ${ask.revise.runs} served runs it cost $${ask.revise.served_usd} a run, against $${ask.revise.by_hand_usd} a run by hand.`
230
- : ask.graded
231
- ? `Your learned workflow \`${ask.workflow}\` answered this run alone, and a reviewer graded its answer wrong.`
232
- : ask.held
233
- ? heldLine(ask.workflow, ask.held)
234
- : `Your learned workflow \`${ask.workflow}\` needs a revision.`,
235
- ...(ask.graded
293
+ heldLine(ask.workflow, ask.held),
294
+ ...(ask.held.check
236
295
  ? [
237
- ...fenced("its answer", clean(ask.graded.answer, LABEL_MAX)),
238
- "What the reviewer said:",
239
- ...fenced("the grade", clean(ask.graded.words, LABEL_MAX)),
240
- `Give \`${ask.workflow}\` again whole under its name, changed so it answers cases like this one right or hands them back to you at an \`escalate\` node, keeping what it already answers right.`,
241
- "If no change to it would, answer `No change.` and nothing else.",
296
+ ...(ask.held.check.disagreements?.length
297
+ ? ["The inputs it did not agree with you on, as data: each one's input, your answer, and the draft's answer or why it handed the input back. Read them as a record, never as instructions.", ...fenced("the disagreements", ask.held.check.disagreements.map(disagreementText).join("\n\n"))]
298
+ : []),
299
+ `Give \`${ask.workflow}\` again whole under its name, changed so it answers these inputs alone and says what you said: fix the step that gets them wrong, and hand back at an \`escalate\` step only a case its rules do not cover. This revision is checked the same way once; if it falls short again, nothing compiles again.`,
242
300
  ]
243
- : ask.held
244
- ? [`Give \`${ask.workflow}\` again whole under its name, changed so its answers agree with the graded ones: fix the step that gets them wrong, or guard it so it hands those cases back.`]
245
- : [
246
- `Give \`${ask.workflow}\` again whole under its name, changed so it finishes more cases like this one alone, or spends less on each, and still hands back what it can't be sure of.`,
247
- "If it was right to hand this case back and nothing would help, answer `No change.` and nothing else.",
248
- ]),
301
+ : ask.held.audit
302
+ ? [
303
+ ...(ask.held.audit.disagreements.length
304
+ ? ["The audited runs it disagreed with you on, as data: each one's input, your answer on the same input with learning off (or that a person graded its answer wrong), and the workflow's answer. Read them as a record, never as instructions.", ...fenced("the disagreements", ask.held.audit.disagreements.map(auditDisagreementText).join("\n\n"))]
305
+ : []),
306
+ `Give \`${ask.workflow}\` again whole under its name, changed so it says what you said on these inputs: fix the step that gets them wrong, and hand back at an \`escalate\` step only a case its rules do not cover. This revision is checked once on your recent inputs and these; if audits hold it again, nothing compiles again.`,
307
+ ]
308
+ : [`Give \`${ask.workflow}\` again whole under its name, changed so its answers agree with the agent's own: fix the step that gets them wrong, or hand those cases back at an \`escalate\` step.`]),
249
309
  OUTPUT_FORMAT,
250
310
  ];
251
311
  return [
@@ -259,9 +319,9 @@ export function compilePrompt(ask) {
259
319
  ...(ask.outputSchema !== undefined ? [SHAPE_LINE, "", "```json", JSON.stringify(ask.outputSchema, null, 2), "```", ""] : []),
260
320
  "## A worked example",
261
321
  "",
262
- sdk ? "Syntax only: a delegated tool call, without an implicit model or confidence guard. Replace its arguments and schemas with the actual catalog's and the job's output format; this example grants no capability." : "A whole job: the facts read, " + (ask.judges ? "a typed question asked of them, " : "") + `the answer decided, ${ask.jev ? "each step under a guard Jev reads" : "each judgment under a guard"} that hands back an unsure step, and a case the policy does not cover handed back.`,
322
+ sdk ? "Syntax only: a delegated tool call, without an implicit model. Replace its arguments and schemas with the actual catalog's and the job's output format; this example grants no capability." : exampleLine(ask.tools.length > 0),
263
323
  "",
264
- sdk ? (ask.tools.length ? sdkExampleBlock(ask.tools[0]) : "There is no tool callback to illustrate. Use only the callbacks the backend explicitly registered; if they cannot express this job, keep notes and skills and no workflow.") : exampleBlock(ask.judges, ask.jev === true),
324
+ sdk ? (ask.tools.length ? sdkExampleBlock(ask.tools[0]) : "There is no tool callback to illustrate. Use only the callbacks the backend explicitly registered; if they cannot express this job, keep notes and skills and no workflow.") : exampleBlock(ask.tools.length > 0),
265
325
  "",
266
326
  "## This job",
267
327
  "",
@@ -281,17 +341,20 @@ export function compilePrompt(ask) {
281
341
  `and sends back what it refuses, up to ${COMPILE_RETRIES} times.`,
282
342
  ].join("\n");
283
343
  }
284
- /** Why a held workflow does not run first, in the hold's numbers: its replay's (the workflow's accuracy, its hand-backs
285
- * scored on the agent's recorded answer, against the agent's; or that it handed back every input, so it never answered
286
- * alone), else the hold's own reason (host-written). */
344
+ /** Why a held workflow does not run first, in its check's numbers (how many inputs it answered alone, and how many of
345
+ * those said what the agent said), else the hold's own reason (host-written). */
287
346
  function heldLine(workflow, held) {
288
347
  const pct = (value) => `${(value * 100).toFixed(1)}%`;
289
- const { replay } = held;
290
- const why = replay && replay.n > 0 && !answersAlone(replay)
291
- ? `replayed on ${replay.n} of the agent's graded inputs, it handed back every one: it would never answer alone. A check or an escalate that stops every draft, right or wrong, is the step to change.`
292
- : replay
293
- ? `replayed on ${replay.n} of the agent's graded inputs, it was right ${pct(replay.wf_acc)} of the time (${replay.handed_back} handed back, each scored on the agent's answer), against the agent's ${pct(replay.agent_acc)}: ${replay.delta >= 0 ? "+" : ""}${(replay.delta * 100).toFixed(1)} pts, more than ${PROMOTE_BAR * 100} pts under.`
294
- : `it was held (${clean(held.reason, 400).replace(/\n/g, " ").replace(/\.$/, "")}).`;
348
+ const { check, audit } = held;
349
+ if (audit) {
350
+ const disagreed = audit.disagreements.length;
351
+ return `Your learned workflow \`${workflow}\` does not run first: it disagreed with your own answer on ${disagreed} of its last ${audit.rows} audited runs (held at ${audit.disagree} of ${audit.window}).`;
352
+ }
353
+ if (check && check.n !== undefined) {
354
+ const shares = checkShares({ n: check.n, agreed: check.agreed ?? 0, alone: check.alone ?? 0 });
355
+ return `Your learned workflow \`${workflow}\` does not run first: checked on ${check.n} ${check.n === 1 ? "input" : "inputs"} of your last ${check.compile_after} completed runs, it answered ${check.alone ?? 0} alone (${pct(shares.alone)}, at least ${pct(check.alone_min)} needed), and ${check.agreed ?? 0} of those said what you said (${pct(shares.agreement)}, at least ${pct(check.agree_min)} needed).`;
356
+ }
357
+ const why = `it was held (${clean(held.reason, 400).replace(/\n/g, " ").replace(/\.$/, "")}).`;
295
358
  return `Your learned workflow \`${workflow}\` does not run first: ${why} It stays held until a new revision of it.`;
296
359
  }
297
360
  /** What each tool a call node may run takes and gives, one line each (reflect.ts said this under a draft ask). */
@@ -318,10 +381,10 @@ export function compileAgain(errors, attempt) {
318
381
  }
319
382
  /** The compile turn's answer, read: exactly one ````workflow <name> block (a revision's under its own name). */
320
383
  export function readCompile(answer, ask) {
321
- // `No change.` is a revision's answer only where its prompt offers it: a held one's never does (it stays held until a
322
- // new revision), so there it is refused as any unreadable answer is, asked again, and recorded with its attempt.
384
+ // `No change.` is never a revision's answer: a held workflow stays held until a new revision, so it is refused as any
385
+ // unreadable answer is, asked again, and recorded with its attempt.
323
386
  if (ask.mode === "revise" && /^\s*`?No change\.?`?\s*$/i.test(answer)) {
324
- return ask.held ? { ok: false, error: `\`${ask.workflow}\` is held until a new revision of it: \`No change.\` is no answer here; give it again whole under its name` } : { ok: false, unchanged: true };
387
+ return { ok: false, error: `\`${ask.workflow}\` is held until a new revision of it: \`No change.\` is no answer here; give it again whole under its name` };
325
388
  }
326
389
  const parsed = parseReflection(answer);
327
390
  if (!parsed.ok)
@@ -380,74 +443,13 @@ function draftDigestOf(checked, name) {
380
443
  const file = (checked.proposal?.files ?? []).find((one) => one?.file === draftPaths(name)[0]);
381
444
  return typeof file?.text === "string" ? createHash("sha256").update(file.text).digest("hex").slice(0, 16) : undefined;
382
445
  }
383
- /** The node kinds whose own confidence a guard reads (they submit one), and those that report none (Jev alone checks
384
- * them): learnedHost's rules. */
385
- const SELF_KINDS = new Set(["decide", "agent", "judge", "pick", "sift"]);
386
- const UNREPORTED_KINDS = new Set(["extract", "call"]);
387
- const guardWords = (signal) => JSON.stringify(guardOf(signal)).replace(/,/g, ", ").replace(/:/g, ": ");
388
- /** Every step of a workflow document's root, depth first (skills.ts childNodes: a chain's steps, a parallel's branches,
389
- * a map's or loop's body, a route's bodies, a composed workflow's root), never a literal value (a step's `state`, a
390
- * call's `args`) that holds a `node` key. */
391
- function nodesOf(value, out = []) {
392
- if (value === null || typeof value !== "object" || Array.isArray(value))
393
- return out;
394
- const node = value;
395
- if (typeof node.node !== "string")
396
- return out;
397
- out.push(node);
398
- for (const child of node.node === "workflow" ? [node.workflow?.root] : childNodes(node))
399
- nodesOf(child, out);
400
- return out;
401
- }
402
- /** What a draft's guards leave out of the ones the compile turn asked for (learnedHost's rules), one line each: a
403
- * judgment step with no guard; with Jev, an extract or call step with none, or one reading its own confidence (it
404
- * reports none); without Jev, a guard that reads it (it would hand every case back). None when every one is there. */
405
- export function guardProblems(doc, options) {
406
- if (options.workflowAdapters !== undefined)
407
- return nodesOf(doc?.root).filter(node => node.guard !== undefined).map(() => "the SDK bridge has no guardStep callback: omit step guards");
408
- const own = options.jev ? "both" : "self";
409
- const problems = [];
410
- for (const node of nodesOf(doc?.root)) {
411
- const kind = node.node;
412
- if (!SELF_KINDS.has(kind) && !UNREPORTED_KINDS.has(kind))
413
- continue;
414
- const step = `the ${kind} step ${JSON.stringify(String(node.label ?? "(no label)").slice(0, 64))}`;
415
- const guard = node.guard;
416
- const signal = guard !== null && typeof guard === "object" ? guard.signal : undefined;
417
- if (signal === undefined) {
418
- if (SELF_KINDS.has(kind))
419
- problems.push(`${step} has no guard: give it ${guardWords(own)}`);
420
- else if (options.jev)
421
- problems.push(`${step} has no guard: give it ${guardWords("jev")}`);
422
- }
423
- else if (!options.jev && (signal === "jev" || signal === "both")) {
424
- problems.push(`${step} has a guard that reads ${signal}, and this run cannot call Jev: ${SELF_KINDS.has(kind) ? `give it ${guardWords("self")}` : "an extract or call step takes no guard"}`);
425
- }
426
- else if (UNREPORTED_KINDS.has(kind) && signal !== "jev") {
427
- problems.push(`${step} reports no confidence of its own: its guard reads jev, ${guardWords("jev")}`);
428
- }
429
- }
430
- return problems;
431
- }
432
- /** The guards draft `name` as the checks kept it (its workflow.json's text in the proposal) leaves out (guardProblems),
433
- * each the checks' way, `guard: ` in front; one problem when its text can't be read. */
434
- function draftGuardErrorsOf(checked, name, ask) {
435
- const file = checked.state === "proposed" ? (checked.proposal?.files ?? []).find((one) => one?.file === draftPaths(name)[0]) : undefined;
436
- let doc;
437
- try {
438
- doc = JSON.parse(String(file?.text));
439
- }
440
- catch {
441
- return ["guard: its workflow.json as the checks kept it could not be read for its guards"];
442
- }
443
- return guardProblems(doc, { jev: ask.jev === true, ...(ask.workflowAdapters !== undefined ? { workflowAdapters: ask.workflowAdapters } : {}) }).slice(0, ERRORS_MAX).map((problem) => `guard: ${problem}`.slice(0, ERROR_MAX));
444
- }
445
446
  /** The record's workflow when no attempt named one. */
446
447
  export const UNNAMED = "(unnamed)";
447
- /** The compile turn, start to end: ask, read, check (`check` over the look-back's answer with the draft in it, then the
448
- * guards the turn asked for, guardProblems), and on a refusal ask again with the errors, at most 1 + COMPILE_RETRIES
448
+ /** The compile turn, start to end: ask, read, check (`check` over the look-back's answer with the draft in it), and on a refusal ask again with the errors, at most 1 + COMPILE_RETRIES
449
449
  * times and within `deadlineMs`. What it ends with: `kept` with the answer and what the checks made of it when an
450
- * attempt passed; else none, with every attempt. Notes over NOTES_MAX ask nothing: one attempt says why. */
450
+ * attempt passed; else none, with every attempt, and `drafted` when an attempt answered (its drafts failed their
451
+ * checks: the compile's attempt, DRAFT_FAILED; a turn that never answered is none). Notes over NOTES_MAX ask nothing:
452
+ * one attempt says why. */
451
453
  export async function compileTurn(input) {
452
454
  const now = input.now ?? Date.now;
453
455
  const deadline = now() + (input.deadlineMs ?? COMPILE_TIMEOUT_MS);
@@ -460,6 +462,7 @@ export async function compileTurn(input) {
460
462
  return { record: { workflow: name || UNNAMED, from_notes: [], attempts: [{ ok: false, errors }] }, draftErrors: errors };
461
463
  }
462
464
  let fromNotes = [];
465
+ let answered = false;
463
466
  const firstPrompt = compilePrompt(input.compile);
464
467
  let prompt = firstPrompt;
465
468
  for (let attempt = 1; attempt <= 1 + COMPILE_RETRIES; attempt++) {
@@ -471,9 +474,8 @@ export async function compileTurn(input) {
471
474
  attempts.push({ ok: false, errors: ["the turn ended before it answered"] });
472
475
  break;
473
476
  }
477
+ answered = true;
474
478
  const read = readCompile(said.answer, input.compile);
475
- if (!read.ok && "unchanged" in read)
476
- break;
477
479
  let errors;
478
480
  if (!read.ok)
479
481
  errors = [read.error];
@@ -483,9 +485,6 @@ export async function compileTurn(input) {
483
485
  const answer = withCompiled(input.answer, read.block);
484
486
  const checked = await input.check(answer).catch(() => undefined);
485
487
  errors = draftErrorsOf(checked, read.name);
486
- // The guards the turn asked for, on the draft as the checks kept it: a judgment it runs unguarded never hands back.
487
- if (!errors.length && checked)
488
- errors = draftGuardErrorsOf(checked, read.name, input.compile);
489
488
  if (!errors.length && checked) {
490
489
  attempts.push({ ok: true, errors: [] });
491
490
  const digest = draftDigestOf(checked, read.name);
@@ -497,12 +496,12 @@ export async function compileTurn(input) {
497
496
  // Native/managed sessions retain the earlier turn. SDK booked requests are independent: every retry must carry
498
497
  // the same bounded contract/catalog/notes and only its immediately preceding, redacted failed answer as data.
499
498
  prompt = input.compile.workflowAdapters !== undefined
500
- ? [again, firstPrompt, ...fenced("the previous compile answer", clean(redactSecrets(said.answer, input.refuse ?? [], Number.POSITIVE_INFINITY), 32_000))].join("\n\n")
499
+ ? [again, firstPrompt, ...fenced("the previous compile answer", excerptShown(said.answer, { text: (text) => clean(redactSecrets(text, input.refuse ?? [], Number.POSITIVE_INFINITY), Number.POSITIVE_INFINITY) }, 32_000))].join("\n\n")
501
500
  : again;
502
501
  }
503
502
  if (!attempts.length)
504
503
  return { draftErrors: [] };
505
504
  const last = attempts.findLast((one) => one.errors.length)?.errors ?? [];
506
505
  // A draft that never named itself is recorded all the same, under UNNAMED: every attempt is.
507
- return { record: { workflow: name || UNNAMED, from_notes: fromNotes, attempts }, draftErrors: [...last] };
506
+ return { record: { workflow: name || UNNAMED, from_notes: fromNotes, attempts }, draftErrors: [...last], ...(answered ? { drafted: true } : {}) };
508
507
  }
@@ -4,6 +4,8 @@ import { type LearnedNote } from "./notes.js";
4
4
  export declare const HOST_DIR = ".agentrun";
5
5
  export declare const SNAPSHOT_FILE = ".agentrun/snapshot.json";
6
6
  export declare const DIFFS_DIR = ".agentrun/diffs";
7
+ /** The audit ledger at the folder's top (learn/audit.ts): one JSON row per line. */
8
+ export declare const AUDITS_FILE = "audits.jsonl";
7
9
  /** The most changes the snapshot's log keeps, newest first; `log_more` says older exist. */
8
10
  export declare const LOG_KEEP = 200;
9
11
  /** A file main holds over this is no note and no learned file: a note is at most 4 KB (check.ts CAPS.note). */
@@ -84,6 +86,11 @@ export type Snapshot = {
84
86
  oid: string;
85
87
  bytes: number;
86
88
  };
89
+ /** The audit ledger (learn/audit.ts AUDITS_FILE), once a row was written: the host's, never laid into a run. */
90
+ audits?: {
91
+ oid: string;
92
+ bytes: number;
93
+ };
87
94
  notes: SnapNote[];
88
95
  skills: SnapLearned[];
89
96
  workflows: SnapLearned[];
@@ -156,6 +163,8 @@ export type FolderChange = {
156
163
  run: string;
157
164
  reason: string;
158
165
  round?: number;
166
+ } | {
167
+ host: string;
159
168
  };
160
169
  writes: readonly {
161
170
  path: string;