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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +8 -7
  3. package/dist/console/assets/index-BrcDSBD8.css +1 -0
  4. package/dist/console/assets/{index-DYJ_wj27.js → index-Bz6IWncl.js} +186 -186
  5. package/dist/console/index.html +2 -2
  6. package/dist/decisions.js +0 -4
  7. package/dist/import-sources.js +25 -5
  8. package/dist/learn/audit.d.ts +123 -0
  9. package/dist/learn/audit.js +159 -0
  10. package/dist/learn/compile.d.ts +50 -74
  11. package/dist/learn/compile.js +90 -124
  12. package/dist/learn/folder.d.ts +9 -0
  13. package/dist/learn/folder.js +13 -2
  14. package/dist/learn/promote.d.ts +86 -200
  15. package/dist/learn/promote.js +57 -183
  16. package/dist/learn/replay-calls.d.ts +5 -0
  17. package/dist/learn/replay-calls.js +12 -1
  18. package/dist/learn/secrets.d.ts +8 -0
  19. package/dist/learn/secrets.js +12 -0
  20. package/dist/learn/skills.js +2 -4
  21. package/dist/learn/workflow-nodes.d.ts +1 -2
  22. package/dist/learn/workflow-nodes.js +2 -3
  23. package/dist/learned-nodes.d.ts +9 -34
  24. package/dist/learned-nodes.js +11 -23
  25. package/dist/learned-workflow.d.ts +6 -8
  26. package/dist/learned-workflow.js +18 -57
  27. package/dist/learning-batch.d.ts +13 -5
  28. package/dist/learning-batch.js +34 -8
  29. package/dist/learning-cost.d.ts +11 -4
  30. package/dist/learning-cost.js +4 -2
  31. package/dist/learning-routes.js +1 -1
  32. package/dist/learning-setting.d.ts +16 -1
  33. package/dist/learning-setting.js +34 -2
  34. package/dist/openapi.js +95 -55
  35. package/dist/run-launch.d.ts +6 -3
  36. package/dist/run-launch.js +2 -0
  37. package/dist/run-learning-served.d.ts +1 -1
  38. package/dist/runner/adapter-loop.d.ts +4 -0
  39. package/dist/runner/adapter-loop.js +17 -2
  40. package/dist/runner/adapter-run-spec.js +16 -5
  41. package/dist/runner/audit.d.ts +64 -0
  42. package/dist/runner/audit.js +338 -0
  43. package/dist/runner/beside.js +1 -1
  44. package/dist/runner/cli-run-spec.js +15 -5
  45. package/dist/runner/feedback-round.js +1 -4
  46. package/dist/runner/harness-loops.js +1 -15
  47. package/dist/runner/journal-kinds.d.ts +0 -7
  48. package/dist/runner/journal-kinds.js +0 -7
  49. package/dist/runner/learning-dispatch.d.ts +0 -16
  50. package/dist/runner/learning-dispatch.js +4 -47
  51. package/dist/runner/learning-end.d.ts +52 -13
  52. package/dist/runner/learning-end.js +124 -44
  53. package/dist/runner/learning-factory.d.ts +1 -1
  54. package/dist/runner/learning-factory.js +1 -4
  55. package/dist/runner/learning-loop.d.ts +2 -38
  56. package/dist/runner/learning-loop.js +8 -116
  57. package/dist/runner/main.js +1 -1
  58. package/dist/runner/promotion.d.ts +50 -54
  59. package/dist/runner/promotion.js +191 -583
  60. package/dist/runner/reflect-hook.d.ts +10 -0
  61. package/dist/runner/reflect-hook.js +6 -0
  62. package/dist/runner/workflow-first.d.ts +6 -5
  63. package/dist/runner/workflow-first.js +17 -12
  64. package/dist/server.js +61 -16
  65. package/dist/store/sqlite/store.js +1 -0
  66. package/dist/store/store.d.ts +3 -0
  67. package/dist/store-reads/learning.d.ts +17 -6
  68. package/dist/store-reads/learning.js +36 -23
  69. package/dist/store-reads/loop.d.ts +4 -39
  70. package/dist/store-reads/loop.js +10 -79
  71. package/dist/store-view.js +12 -2
  72. package/dist/workspace/run-tools.d.ts +1 -1
  73. package/dist/workspace/run-tools.js +14 -3
  74. package/package.json +9 -9
  75. package/dist/console/assets/index-C3gNPz58.css +0 -1
  76. package/dist/learn/general.d.ts +0 -69
  77. package/dist/learn/general.js +0 -75
  78. package/dist/learn/refit.d.ts +0 -48
  79. package/dist/learn/refit.js +0 -264
  80. package/dist/runner/step-guard.d.ts +0 -62
  81. package/dist/runner/step-guard.js +0 -93
@@ -1,23 +1,12 @@
1
1
  import { answerJson } from "../answer-json.js";
2
- import { workflowNodes } from "./workflow-nodes.js";
3
- /** How many of the agent's newest graded inputs a replay runs on. */
4
- export const REPLAY_INPUTS = 20;
5
- /** The fewest graded inputs a replay runs on: with fewer, a workflow is promoted on its passing dry run, as before. */
6
- export const REPLAY_MIN = 5;
7
- /** How far below the agent path's accuracy on the same inputs a workflow may be and still serve: 2 points. */
8
- export const PROMOTE_BAR = 0.02;
9
- /** A serving revision's thresholds are refit at most once per this many graded runs it served. */
10
- export const REFIT_EVERY = 20;
11
2
  /** How many grades, and how many promotion records, an agent keeps (newest kept). */
12
3
  export const GRADES_KEPT = 500;
13
4
  export const PROMOTIONS_KEPT = 200;
14
5
  /** The most characters a grade's words (`label`) may hold, and the most of them and of an answer a compile ask shows. */
15
6
  export const LABEL_MAX = 4_000;
16
7
  export const GRADE_SOURCES = ["feedback", "eval"];
17
- /** The ReplayScore fields of `x` alone (a scoreRows or refitGuards result, or a record's `replay`): the one pick of them. */
18
- export const scoreOf = (x) => ({ n: x.n, agree: x.agree, agent_acc: x.agent_acc, wf_acc: x.wf_acc, delta: x.delta, handed_back: x.handed_back });
19
- /** Whether a replay or refit answered alone on at least one of its inputs: one that hands back every input would never
20
- * serve. The one spelling of it (clears, settle's hold, the compile's held line); the count is n - handed_back. */
8
+ /** Whether a replay answered alone on at least one of its inputs: one that hands back every input would never serve. The
9
+ * one spelling of it (the compile's held line); the count is n - handed_back. */
21
10
  export const answersAlone = (score) => score.handed_back < score.n;
22
11
  /** The most characters of an input or an answer a check's disagreement keeps. */
23
12
  export const CHECK_TEXT_MAX = 1_200;
@@ -73,78 +62,68 @@ export const putGrade = async (settings, agentId, grade) => {
73
62
  return kept;
74
63
  };
75
64
  /** Marks the kept grade `grade` (its run, given at its `at`, kept at its `seq`) with the feedback round it opened and
76
- * that round's steer, in place: its `seq` stays, so a serving digest's check never counts it twice. A newer grade of the
77
- * run is left as it is, one given in the same millisecond too (its `seq` is another). The grade, marked. */
65
+ * that round's steer, in place: its `seq` stays. A newer grade of the run is left as it is, one given in the same
66
+ * millisecond too (its `seq` is another). The grade, marked. */
78
67
  export const markGradeRound = async (settings, agentId, grade, opened) => {
79
68
  const mark = { feedback: opened.round, feedbackCommand: opened.command };
80
69
  await updateKept(settings, gradesKey(agentId), (items) => items.map((one) => (one.run === grade.run && one.at === grade.at && one.seq === grade.seq ? { ...one, ...mark } : one)));
81
70
  return { ...grade, ...mark };
82
71
  };
83
- /** The agent's promotion records, oldest first. A beta.39 store may hold `decided: "superseded"` (a replay a newer draft
84
- * cancelled; beta.40 writes `skipped` for an older draft instead): read as `skipped`, `skipped_by` the draft that
85
- * superseded it, with a reason that says when. Only the read maps (readAs, also what a guarded write compares): the stored
86
- * record is never rewritten. */
87
- export const readAs = (one) => {
88
- if (one.decided !== "superseded")
89
- return one;
90
- const { superseded_by: by, ...rest } = one;
91
- return { ...rest, decided: "skipped", reason: "a newer draft arrived while it replayed (before beta.40)", ...(by ? { skipped_by: by } : {}) };
92
- };
93
- export const promotionsOf = async (settings, agentId) => itemsOf(await settings.get(promotionsKey(agentId))).map(readAs);
72
+ /** The states a promotion record is written in (PromotionRecord.decided). */
73
+ const DECIDED = ["promote", "hold", "replaying"];
74
+ /** The records of `items` in a state this code writes: one saved in any other is dropped, as if absent (its revision is
75
+ * checked again). */
76
+ const writtenOf = (items) => items.filter((one) => DECIDED.includes(one?.decided));
77
+ /** The agent's promotion records, oldest first: only those in a state this code writes (writtenOf). */
78
+ export const promotionsOf = async (settings, agentId) => writtenOf(itemsOf(await settings.get(promotionsKey(agentId))));
94
79
  /** The newest record of `workflow` at `digest`, or undefined. */
95
80
  export const promotionOf = (records, workflow, digest) => records.findLast((one) => one.workflow === workflow && one.digest === digest);
96
- /** The champion of `workflow`: the newest record of the digest promoted last (a digest's place is its latest win's,
97
- * winsOf), while that digest's newest record still says promote. A newer revision replaying or held never stops it; a
98
- * wrong served grade asks for nothing and never stops it alone; it stops when a newer revision's replay promotes that one
99
- * (then the champion), or its own graded runs hold it (source graded: no champion until a revision is promoted). A held
100
- * revision its owner replays (runner/promotion.ts askReplay) and the replay promotes wins again: the champion from then.
101
- * The money rule stops it on its own (runner/workflow-first.ts). Undefined: none. */
81
+ /** The champion of `workflow`: the newest record of the digest promoted last, while that digest's newest record still
82
+ * says promote. A newer revision replaying or held never stops it; it stops when a newer revision's check promotes that
83
+ * one (then the champion), or when its own newest record is a hold (a held revision its owner replays, askReplay, that
84
+ * promotes wins again). The money rule stops it on its own (runner/workflow-first.ts). Undefined: none. */
102
85
  export function championOf(records, workflow) {
103
86
  const last = lastPromotedOf(records, workflow);
104
87
  const now = last === undefined ? undefined : promotionOf(records, workflow, last);
105
88
  return now?.decided === "promote" ? now : undefined;
106
89
  }
107
- /** Each promote record's win, by index: the index of the promote record that began its digest's run of promote records
108
- * (its first, or the first after a record of that digest that was not promote: a replay that promoted a held revision).
109
- * A graded check's mark (a promote after a promote, runner/promotion.ts stillServing) is never a win of its own. */
110
- function winsOf(records) {
111
- const wins = new Map();
112
- const streak = new Map();
113
- records.forEach((one, i) => {
114
- const at = JSON.stringify([one.workflow, one.digest]);
90
+ /** The newest promotion of `workflow` at `digest`: the promote record that began its newest run of promote records (its
91
+ * first, or the first after a record of that digest that was not promote: an owner's replay that promoted a held
92
+ * revision), or undefined when none was ever promoted. Its `at` names that promotion: an audit row keeps the one serving
93
+ * when its evidence began (learn/audit.ts promoted_at), and the hold rule counts only the rows of the one serving now,
94
+ * so a digest its owner's replay promotes again after a hold starts on no rows. */
95
+ export function promotionStartOf(records, workflow, digest) {
96
+ let start;
97
+ let streak = false;
98
+ for (const one of records) {
99
+ if (one.workflow !== workflow || one.digest !== digest)
100
+ continue;
115
101
  if (one.decided !== "promote")
116
- return void streak.delete(at);
117
- if (!streak.has(at))
118
- streak.set(at, i);
119
- wins.set(i, streak.get(at));
120
- });
121
- return wins;
102
+ streak = false;
103
+ else if (!streak)
104
+ [start, streak] = [one, true];
105
+ }
106
+ return start;
122
107
  }
123
- /** The digest of `workflow` promoted last: the one whose latest win (winsOf) is the newest of every digest's. */
108
+ /** The digest of `workflow` promoted last: the one of its newest promote record. */
124
109
  function lastPromotedOf(records, workflow) {
125
- let last;
126
- for (const [i, win] of winsOf(records))
127
- if (i === win && records[i].workflow === workflow)
128
- last = records[i].digest;
129
- return last;
110
+ return records.findLast((one) => one.workflow === workflow && one.decided === "promote")?.digest;
130
111
  }
131
- /** The revisions of `workflow` other than `digest` whose newest record still says `decided` (replaying, else queued),
132
- * newest first: at most one replaying (one replay at a time, the reservation's guarded write), and at most one queued
133
- * once each newer one skips the one queued before it (runner/promotion.ts). */
134
- export function replayingOf(records, workflow, digest, decided = "replaying") {
112
+ /** The revision of `workflow` other than `digest` whose newest record still says replaying, newest first: at most one (one
113
+ * check at a time, the reservation's guarded write). */
114
+ export function replayingOf(records, workflow, digest) {
135
115
  const out = [];
136
116
  for (const one of [...records].reverse()) {
137
117
  if (one.workflow !== workflow || one.digest === digest || out.some((seen) => seen.digest === one.digest))
138
118
  continue;
139
- if (promotionOf(records, workflow, one.digest) === one && one.decided === decided)
119
+ if (promotionOf(records, workflow, one.digest) === one && one.decided === "replaying")
140
120
  out.push(one);
141
121
  }
142
122
  return out;
143
123
  }
144
124
  /** What each learned workflow with a record serves, by name: `digest`, its champion's (championOf; null: none serves,
145
- * the agent takes its runs), and `replaying`, the revision other than it whose replay is at work (null: none; a queued
146
- * one is not at work yet). What the promotions list says beside the records
147
- * (GET /agents/{id}/learning/promotions). */
125
+ * the agent takes its runs), and `replaying`, the revision other than it whose check is at work (null: none). What the
126
+ * promotions list says beside the records (GET /agents/{id}/learning/promotions). */
148
127
  export function servingOf(records) {
149
128
  const names = [...new Set(records.map((one) => one.workflow))].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
150
129
  return names.map((workflow) => {
@@ -155,8 +134,8 @@ export function servingOf(records) {
155
134
  /** The promotions list as it leaves (GET /agents/{id}/learning/promotions): the records and what serves (servingOf), every
156
135
  * text in them cut by `shown` (learning.ts secretsShown, as the other learning reads cut theirs), at any depth and under
157
136
  * any field, so a field added later is cut too: a workflow's name whole (`shown.name`), any other text of its part
158
- * (`shown.text`: a reason, a refit guard's label, a digest, a run id). Numbers and the rest as they are. A replaying
159
- * record's `launch` (a run launch: its notes, model and plane) never leaves: aggregates only. */
137
+ * (`shown.text`: a reason, a digest, a run id). Numbers and the rest as they are. A replaying record's `launch` (a run
138
+ * launch: its notes, model and plane) never leaves: aggregates only. */
160
139
  export function promotionsShown(records, shown) {
161
140
  const cut = (value, key) => typeof value === "string" ? (key === "workflow" ? shown.name(value) : shown.text(value))
162
141
  : Array.isArray(value) ? value.map((one) => cut(one))
@@ -165,62 +144,45 @@ export function promotionsShown(records, shown) {
165
144
  return { promotions: records.map(({ launch: _, ...one }) => cut(one)), serving: servingOf(records).map((one) => cut(one)) };
166
145
  }
167
146
  /** Keeps `record` as the newest of its workflow at its digest, when `still` holds of the one there now (none: undefined)
168
- * and of every record kept (`items`: a check across revisions, one challenger at a time, in the same guarded write): so
169
- * of two claims deciding at once only the first decision is kept, and only its claim acts on it (Recorded.won). `also`:
170
- * records kept after it in the same write, all or none (a queue change and the skips it makes, runner/promotion.ts). */
171
- export async function recordPromotion(settings, agentId, record, still, also = []) {
147
+ * and of every record kept (`items`: a check across revisions, one at a time, in the same guarded write): so of two
148
+ * claims deciding at once only the first decision is kept, and only its claim acts on it (Recorded.won). */
149
+ export async function recordPromotion(settings, agentId, record, still) {
172
150
  let out = { record, won: true };
173
- await updateKept(settings, promotionsKey(agentId), (items) => {
174
- // `still` compares what a read shows (readAs); the write keeps the stored items as they are.
175
- const read = items.map(readAs);
176
- const now = promotionOf(read, record.workflow, record.digest);
177
- if (!still(now, read)) {
151
+ await updateKept(settings, promotionsKey(agentId), (saved) => {
152
+ const items = writtenOf(saved);
153
+ const now = promotionOf(items, record.workflow, record.digest);
154
+ if (!still(now, items)) {
178
155
  out = { record: now, won: false };
179
156
  return items;
180
157
  }
181
158
  out = { record, won: true };
182
- return trimPromotions([...items, record, ...also]);
159
+ return trimPromotions([...items, record]);
183
160
  });
184
161
  return out;
185
162
  }
186
163
  /** The newest records, at most PROMOTIONS_KEPT, in order, with each workflow's champion (championOf) the same after as
187
- * before, whatever was dropped. championOf reads two things, and the trim keeps both: the place of every digest it can
188
- * still see promoted (a promote record kept keeps its win, winsOf, beside it, so an older revision's late graded check
189
- * never reads as a newer promotion), and the digest promoted last, its latest win and its newest record (so a held last
190
- * revision is never trimmed into handing the champion back). The kept records are a run of the newest plus those wins,
191
- * and a win's own run reaches no further back than it: a record that ended an older run of the same digest is newer
192
- * than every record of that run, so a run is never joined to an older one by the trim. The queue's state is kept too,
193
- * whatever its age: a replaying revision's newest record (what its settle, its runs' claims and the one-replay-at-a-time
194
- * check read: dropped, a newer revision would start a second replay while its runs run, and its verdict would never
195
- * land) and a queued one's (what replays next). Neither is a promote record, so championOf reads the same. */
164
+ * before, whatever was dropped: championOf reads the digest promoted last and its newest record, so the trim keeps both
165
+ * (a held last revision is never trimmed into handing the champion back), and a replaying revision's newest record (what
166
+ * its settle, its runs' claims and the one-check-at-a-time rule read: dropped, a newer revision would start a second
167
+ * check while its runs run, and its verdict would never land). The rest is the newest records. */
196
168
  export function trimPromotions(items) {
197
169
  if (items.length <= PROMOTIONS_KEPT)
198
170
  return [...items];
199
- const wins = winsOf(items);
200
- const placeOf = (i) => wins.get(i);
201
171
  const keep = new Set();
202
172
  for (const workflow of new Set(items.map((one) => one.workflow))) {
203
- for (const one of [...replayingOf(items, workflow, null), ...replayingOf(items, workflow, null, "queued")])
173
+ for (const one of replayingOf(items, workflow, null))
204
174
  keep.add(items.lastIndexOf(one));
205
175
  const last = lastPromotedOf(items, workflow);
206
176
  if (last === undefined)
207
177
  continue;
208
- const newest = items.findLastIndex((one) => one.workflow === workflow && one.digest === last);
209
- // Its latest win: the newest win of that digest.
210
- keep.add(Math.max(...[...wins].filter(([i, win]) => i === win && items[i].workflow === workflow && items[i].digest === last).map(([i]) => i)));
211
- keep.add(newest);
178
+ keep.add(items.findLastIndex((one) => one.workflow === workflow && one.digest === last && one.decided === "promote"));
179
+ keep.add(items.findLastIndex((one) => one.workflow === workflow && one.digest === last));
212
180
  }
213
181
  for (let i = items.length - 1, room = PROMOTIONS_KEPT - keep.size; i >= 0 && room > 0; i--) {
214
182
  if (keep.has(i))
215
183
  continue;
216
- const place = placeOf(i);
217
- const adds = place === undefined || keep.has(place) || place === i ? 1 : 2;
218
- if (adds > room)
219
- break;
220
184
  keep.add(i);
221
- if (place !== undefined)
222
- keep.add(place);
223
- room -= adds;
185
+ room -= 1;
224
186
  }
225
187
  return items.filter((_, i) => keep.has(i));
226
188
  }
@@ -254,94 +216,6 @@ function same(a, b) {
254
216
  }
255
217
  /** Whether two answers say the same: equal as JSON values, else as trimmed text. */
256
218
  export const sameAnswer = (a, b) => a !== null && b !== null && same(valueOf(a), valueOf(b));
257
- /** Whether the workflow's `answer` to a graded input is right by its grade: with the grade's expected fields, when its JSON
258
- * holds each of them (or, one field expected, when the answer is that field's value: a workflow whose output is one
259
- * field answers with its text, or its JSON text when it is no text, learned-workflow.ts learnedOutput). Else, graded
260
- * right, when it says what the graded run said. Graded wrong: on a run a learned workflow answered alone (`workflow`),
261
- * when it says anything else (the bar on a wrong grade is the grade: saying what was graded wrong again is never a tie),
262
- * and wrong when what it said could not be read (nothing says it differs); on a run the agent answered, wrong whatever it
263
- * says (another answer proves nothing: a neutral tie with the agent's, agentRight). */
264
- export function answerCorrect(answer, recorded) {
265
- if (answer === null)
266
- return false;
267
- if (recorded.expected) {
268
- const value = valueOf(answer);
269
- const fields = Object.values(recorded.expected);
270
- if (fields.length === 1 && (typeof fields[0] === "string" ? answer.trim() === fields[0].trim() : same(value, fields[0])))
271
- return true;
272
- if (!value || typeof value !== "object" || Array.isArray(value))
273
- return false;
274
- return Object.entries(recorded.expected).every(([key, want]) => same(value[key], want));
275
- }
276
- if (recorded.correct)
277
- return sameAnswer(answer, recorded.answer);
278
- return recorded.path === "workflow" && recorded.answer !== null && !sameAnswer(answer, recorded.answer);
279
- }
280
- /** Whether the agent's answer to a replayed input is right, the agent's side of a replay's score: the graded run's grade
281
- * when the answer graded is the agent's (path `agent`, or `handed_back`: the agent finished it). On a run a learned
282
- * workflow answered alone (`workflow`) the store holds no answer of the agent's on that input, so a right grade is the
283
- * agent's too and a wrong one counts the agent right: the grade's expected answer is the agent's when it gave one, and
284
- * with none the agent is the default. So a revision held on runs it served wrong never ties its own wrong answers; it
285
- * serves again only by answering them right (answerCorrect) or handing them back. */
286
- export const agentRight = (recorded) => recorded.correct || recorded.path === "workflow";
287
- /** The thresholds a workflow's guards serve at, by step label (the guard rows' `node`): every step of the workflow
288
- * with a `guard` and a `label` (walkGuards). A label names one step: a learned draft that repeats one never runs
289
- * (skills.ts draftProblems, repeatedLabels), so no two steps' rows share a threshold here or in a refit. */
290
- export function thresholdsOf(workflowText) {
291
- const out = new Map();
292
- try {
293
- walkGuards(JSON.parse(workflowText), (label, guard) => {
294
- if (typeof guard.threshold === "number")
295
- out.set(label, guard.threshold);
296
- });
297
- }
298
- catch {
299
- // Not JSON: no guards to read.
300
- }
301
- return out;
302
- }
303
- /** Each node of a workflow document with a guard, by its label as the DSL names its step when it runs, in document order:
304
- * a step of a child workflow (a `workflow` node's `workflow`) as `parent/child`, as the DSL prefixes its events and its
305
- * guard rows (scopeDepsToChild), so a nested guard's serving threshold and its refit read the rows it made. Only the
306
- * workflow's node positions (workflow-nodes.ts): a call's args or a schema shaped like `{label, guard}` is data, never
307
- * a guard, so a replay or a refit never changes it. */
308
- export function walkGuards(doc, visit) {
309
- for (const { node, prefix } of workflowNodes(doc)) {
310
- const guard = node.guard;
311
- if (typeof node.label === "string" && guard && typeof guard === "object" && !Array.isArray(guard))
312
- visit(`${prefix}${node.label}`, guard, node);
313
- }
314
- }
315
- /** The threshold a soft escalate's row (GuardRow signal `escalate`) is read at: its p is 0 when it fired, else 1, so it
316
- * hands back at its serving setting exactly when it fired. */
317
- export const SOFT_ESCALATE_THRESHOLD = 0.5;
318
- /** The threshold a replay's guards read at: the least the DSL takes (a threshold is in (0, 1), exclusive), so a guard
319
- * hands back only when p is null (a signal it reads is missing) or 0. */
320
- export const RECORD_ONLY_THRESHOLD = 1e-9;
321
- /** A workflow's text with every guard's threshold at RECORD_ONLY_THRESHOLD: each guard still reads its signals and
322
- * records its row. What a replay runs, so every step's p is known for the refit and the serving thresholds are applied
323
- * after (learn/refit.ts scoreRows). The text unchanged when it has no guard. */
324
- export function recordOnly(workflowText) {
325
- let doc;
326
- try {
327
- doc = JSON.parse(workflowText);
328
- }
329
- catch {
330
- return workflowText;
331
- }
332
- let any = false;
333
- walkGuards(doc, (_label, guard) => {
334
- guard.threshold = RECORD_ONLY_THRESHOLD;
335
- any = true;
336
- });
337
- return any ? JSON.stringify(doc) : workflowText;
338
- }
339
- /** Whether a score clears the bar: the workflow's accuracy at most PROMOTE_BAR under the agent path's, and it answered
340
- * alone on at least one input (one that hands back every input scores the agent's own accuracy, and would never serve). */
341
- export const clears = (score) => withinBar(score) && answersAlone(score);
342
- /** Whether a score's workflow is at most PROMOTE_BAR under the agent: clears' bar, and what a replay of a held revision
343
- * meets on the runs it was held on alone (runner/promotion.ts settle), where a hand-back on each is fine. */
344
- export const withinBar = (score) => score.delta >= -PROMOTE_BAR - 1e-9;
345
219
  /** A grade as the API answers it (PUT /runs/{id}/grade; GET /runs/{id}/learning's `graded`, without `expected`). */
346
220
  export const gradeView = (grade) => ({
347
221
  run_id: grade.run, correct: grade.correct, ...(grade.expected ? { expected: grade.expected } : {}), source: grade.source, graded_at: grade.at,
@@ -1,3 +1,4 @@
1
+ import type { McpPin } from "../mcp-gateway.js";
1
2
  /** The built-in tools a call node may run that read only: they change nothing outside the run (a web page or search read,
2
3
  * a document's pages drawn into the run's own work/, one model completion). Every other built-in is a write. */
3
4
  export declare const READ_TOOLS: readonly string[];
@@ -11,6 +12,10 @@ export type ToolClass = "read" | "write" | "unmarked";
11
12
  * destructiveHint is not, unmarked when it is listed with no readOnlyHint and not destructive; a built-in by READ_TOOLS;
12
13
  * else write. */
13
14
  export declare function toolClassOf(tool: string, annotations?: (tool: string) => Readonly<Record<string, unknown>> | undefined): ToolClass;
15
+ /** The annotations toolClassOf reads, from an MCP pin (a run's, or its revision's as its save made it): a pinned tool's
16
+ * listing (`{}` when its server listed none, so it reads unmarked, never as a tool it does not list); undefined for a tool
17
+ * the pin does not hold. */
18
+ export declare function pinAnnotations(pin: McpPin | null | undefined): (tool: string) => Readonly<Record<string, unknown>> | undefined;
14
19
  /** Why replay can't run MCP tools with no readOnlyHint (bare tool names, most-skipped first): "browse, fetch_page and 2
15
20
  * more have no readOnlyHint, so replay can't run them: if they only read, mark them read-only in the MCP server". */
16
21
  export declare function unmarkedWords(names: readonly string[]): string;
@@ -7,7 +7,7 @@
7
7
  // hit, recorded or already run in this replay, costs nothing and is never sent again.
8
8
  // - A write is NEVER run in a replay: it is answered from the graded run's recording when a call there has the same
9
9
  // tool and canonical args (its answer, an error included), else the replay of that input stops there and is skipped
10
- // (SKIPPED_WRITE): no evidence either way, never scored wrong or failed (learn/refit.ts refitRowsOf).
10
+ // (SKIPPED_WRITE): no evidence either way, never scored wrong or failed (runner/promotion.ts decideCheck).
11
11
  // The recording is the graded run's own journal (a CLI's record shaped as pi's), each tool call by the wire name the
12
12
  // harness called it by (catalog.ts wireName): a call node names its tool by catalog name, matched through the same map.
13
13
  // Prior art: MCP's tool annotations (readOnlyHint, destructiveHint, 2025-03-26 spec) for the read/write line; VCR-style
@@ -39,6 +39,17 @@ export function toolClassOf(tool, annotations) {
39
39
  }
40
40
  return READ_TOOLS.includes(tool) ? "read" : "write";
41
41
  }
42
+ /** The annotations toolClassOf reads, from an MCP pin (a run's, or its revision's as its save made it): a pinned tool's
43
+ * listing (`{}` when its server listed none, so it reads unmarked, never as a tool it does not list); undefined for a tool
44
+ * the pin does not hold. */
45
+ export function pinAnnotations(pin) {
46
+ return (tool) => {
47
+ const named = MCP_TOOL.exec(tool);
48
+ const server = named && pin && Object.hasOwn(pin, named[1]) ? pin[named[1]] : undefined;
49
+ const listed = server?.tools.find((one) => one.name === named[2]);
50
+ return listed ? (listed.annotations ?? {}) : undefined;
51
+ };
52
+ }
42
53
  /** Why replay can't run MCP tools with no readOnlyHint (bare tool names, most-skipped first): "browse, fetch_page and 2
43
54
  * more have no readOnlyHint, so replay can't run them: if they only read, mark them read-only in the MCP server". */
44
55
  export function unmarkedWords(names) {
@@ -24,6 +24,14 @@ export declare function redactSecrets(text: string, values: readonly string[], m
24
24
  export declare function redactLearned(text: string, values: readonly string[], max?: number): string;
25
25
  /** A value shorter than this matches too much text by chance to be refused. */
26
26
  export declare const MIN_SECRET = 8;
27
+ /** An excerpt of a run's input or answer as learning keeps it: `text` cut of the secrets `shown` knows, whole, then
28
+ * shortened to `max` characters ("…" after a cut, never half a surrogate pair). Shortened first, a secret straddling the
29
+ * cut would leave its prefix, which no redactor matches after. Every stored or prompted excerpt is made here: a check's
30
+ * and an audit hold's disagreements (runner/promotion.ts decideCheck, runner/audit.ts applyHold), a compile turn's traces
31
+ * (runner/learning-end.ts traceFrom) and the compile answer a retry quotes (learn/compile.ts). */
32
+ export declare function excerptShown(text: string, shown: {
33
+ readonly text: (text: string) => string;
34
+ }, max: number): string;
27
35
  /** A matcher for `values` in a text: plain, split by whitespace, as JSON writes it, percent or form encoded, base64 or
28
36
  * hex, and each hex identifier in a value folded: in any case, its separators dropped or moved (foldedOf). Values
29
37
  * shorter than MIN_SECRET are left out. `fold: false`, the matcher without the folded needles (redactSecrets' first
@@ -144,6 +144,18 @@ function cutAt(text, found) {
144
144
  }
145
145
  /** A value shorter than this matches too much text by chance to be refused. */
146
146
  export const MIN_SECRET = 8;
147
+ /** An excerpt of a run's input or answer as learning keeps it: `text` cut of the secrets `shown` knows, whole, then
148
+ * shortened to `max` characters ("…" after a cut, never half a surrogate pair). Shortened first, a secret straddling the
149
+ * cut would leave its prefix, which no redactor matches after. Every stored or prompted excerpt is made here: a check's
150
+ * and an audit hold's disagreements (runner/promotion.ts decideCheck, runner/audit.ts applyHold), a compile turn's traces
151
+ * (runner/learning-end.ts traceFrom) and the compile answer a retry quotes (learn/compile.ts). */
152
+ export function excerptShown(text, shown, max) {
153
+ const clean = shown.text(text);
154
+ if (clean.length <= max)
155
+ return clean;
156
+ const end = /[\uD800-\uDBFF]/.test(clean.charAt(max - 1)) ? max - 1 : max;
157
+ return `${clean.slice(0, end)}…`;
158
+ }
147
159
  const squeeze = (text) => text.normalize("NFKC").replace(/\s+/gu, "");
148
160
  /** The base64 of `secret` as it can sit inside a longer blob: the characters that depend on the secret's bytes alone,
149
161
  * at each of the three alignments, in both alphabets. */
@@ -959,9 +959,7 @@ const unrunnableNodes = (dsl, doc, decisions, adapters) => {
959
959
  // Managed runs name the providers their host can ask; SDK runs supply their own explicit adapter capabilities.
960
960
  const judging = decisions ? { ...(adapters === undefined || adapters.includes("runJudge") ? { runJudge: async () => ({}) } : {}), decisionProviders: { providers: decisions.providers, default: decisions.default } } : {};
961
961
  const callbacks = Object.fromEntries((adapters ?? ["runNode"]).map((name) => [name, async () => ({})]));
962
- // Managed learned runs supply step guards; the SDK bridge advertises only the callbacks its backend implements.
963
- const guards = adapters === undefined ? { guardStep: async () => ({ p: 1 }) } : {};
964
- const runner = { runEffect: async () => ({}), ...callbacks, ...judging, ...guards };
962
+ const runner = { runEffect: async () => ({}), ...callbacks, ...judging };
965
963
  try {
966
964
  dsl.assertWorkflowCapabilities(workflow.root, runner, workflow);
967
965
  return [];
@@ -998,7 +996,7 @@ export function draftProblems(dsl, text, tools, gated = {}, deniedBy = {}, decis
998
996
  return issues.slice(0, 5).map((issue) => ({ rule: "workflow", detail: `the workflow DSL refuses it: ${issue.code} at ${issue.path || "/"}: ${issue.message.slice(0, 200)}` }));
999
997
  let out;
1000
998
  try {
1001
- // A label names one step (workflow-nodes.ts repeatedLabels): its guard's threshold, replay score and refit included.
999
+ // A label names one step (workflow-nodes.ts repeatedLabels): its events and escalation read by it.
1002
1000
  out = [...repeatedLabels(doc).map((label) => ({ rule: "workflow", detail: `the label "${label}" names two steps: give each step its own label` })), ...toolingNodes(dsl, doc), ...executableNodes(dsl, doc), ...unrunnableNodes(dsl, doc, decisions, adapters), ...longNodes(dsl, doc), ...sdkNodeLimit(dsl, doc, adapters), ...sdkRetries(doc, adapters), ...gatedNodes(dsl, doc, gated, deniedBy), ...gatedDecisions(dsl, doc, decisions), ...[...synthesisProblems(doc, dsl), ...loopProblems(doc)].map((detail) => ({ rule: "workflow", detail }))];
1003
1001
  // A learned workflow answers the value at its output's path: one that names none would answer its whole state, which
1004
1002
  // fails its output schema when the call ends, after every node spent.
@@ -9,7 +9,6 @@ export type WorkflowNodeAt = {
9
9
  * Walked with a stack of its own, never the call stack, so no draft's nesting can throw here. */
10
10
  export declare function workflowNodes(doc: unknown): WorkflowNodeAt[];
11
11
  /** The labels of `doc` that name more than one node, each once, in document order, as the DSL names a step when it runs
12
- * (`parent/child` in a child workflow). A label names one step: its events, its escalation and its guard rows (whose
13
- * `node` keys the serving thresholds, a replay's score and a refit) read by it, and the durable runner refuses a workflow
12
+ * (`parent/child` in a child workflow). A label names one step: its events and its escalation read by it, and the durable runner refuses a workflow
14
13
  * that repeats one (DUPLICATE_LABEL). */
15
14
  export declare function repeatedLabels(doc: unknown): string[];
@@ -1,4 +1,4 @@
1
- // The one walk over a learned workflow's nodes (learn/skills.ts callNodes, learn/promote.ts walkGuards): only the
1
+ // The one walk over a learned workflow's nodes (learn/skills.ts callNodes): only the
2
2
  // workflow's node positions, never an object in a call's args, a schema or any other data, however it is shaped.
3
3
  const asNode = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : undefined);
4
4
  /** Every node of `doc` (a parsed workflow.json), in document order: its root, a chain's steps, a parallel's branches, a
@@ -26,8 +26,7 @@ export function workflowNodes(doc) {
26
26
  return out;
27
27
  }
28
28
  /** The labels of `doc` that name more than one node, each once, in document order, as the DSL names a step when it runs
29
- * (`parent/child` in a child workflow). A label names one step: its events, its escalation and its guard rows (whose
30
- * `node` keys the serving thresholds, a replay's score and a refit) read by it, and the durable runner refuses a workflow
29
+ * (`parent/child` in a child workflow). A label names one step: its events and its escalation read by it, and the durable runner refuses a workflow
31
30
  * that repeats one (DUPLICATE_LABEL). */
32
31
  export function repeatedLabels(doc) {
33
32
  const seen = new Set();
@@ -1,12 +1,11 @@
1
1
  import type { Skipped } from "./learn/replay-calls.js";
2
- /** The journal entry a learned_workflow call keeps beside itself: `{ call, workflow, nodes, guards?, loops? }`, its call's
3
- * id, the workflow's name, each of its nodes that ran (LearnedNode, at most LEARNED_NODES_MAX), every guard check it made
4
- * (GuardRow) and every loop exit (LoopRow), these two never capped (a map over more items than the trace holds keeps
5
- * each); on a replay run's call that a write
6
- * stopped (learn/replay-calls.ts: one the graded run's recording does not have), `replay_skipped: { tool, step }` too; and
2
+ /** The journal entry a learned_workflow call keeps beside itself: `{ call, workflow, nodes, loops? }`, its call's
3
+ * id, the workflow's name, each of its nodes that ran (LearnedNode, at most LEARNED_NODES_MAX) and every loop exit
4
+ * (LoopRow), never capped (a map over more items than the trace holds keeps each); on a replay run's call that a write
5
+ * stopped (learn/replay-calls.ts: one the agent's recording does not have), `replay_skipped: { tool, step }` too; and
7
6
  * `ended`, how the workflow ended (LearnedEnded), on a call that ended (a replay run's call always keeps its entry). */
8
7
  export declare const LEARNED_NODES = "agentrun.learned_nodes";
9
- /** How a learned workflow's call ended: `complete` (it answered), `escalated` (it handed back: an escalate node or a guard,
8
+ /** How a learned workflow's call ended: `complete` (it answered), `escalated` (it handed back: an escalate node,
10
9
  * however many nodes failed on the way and were recovered, a map's collected item say), or `failed` (it threw, or was
11
10
  * refused before any node ran). */
12
11
  export type LearnedEnded = "complete" | "escalated" | "failed";
@@ -24,29 +23,11 @@ export type LearnedNode = {
24
23
  readonly duration_ms: number;
25
24
  readonly model?: string;
26
25
  readonly tier?: string;
27
- readonly guard?: GuardRow;
28
- };
29
- /** One step guard's check (runner/step-guard.ts), on the node it guards: the step (its label, a child's prefixed), the
30
- * guard's signal and threshold, the signals it read (raw probabilities: its own confidence `self`, Jev's yes `jev`),
31
- * `p` (through the guard's fit when it has one; null when a signal it reads was missing, so it handed back) and whether
32
- * it handed the job back. A run's rows are its metrics' `guards` (runner/workflow-first.ts pathMetrics), each naming
33
- * the workflow whose call made it (`workflow`: a run can call more than one, the next after the first hands back).
34
- * `escalate`: no guard but an escalate node a replay recorded instead of obeying (the DSL's softEscalates), on
35
- * its label: p 0 when it fired, else 1, at SOFT_ESCALATE_THRESHOLD, never `escalated` (the run went on past it). */
36
- export type GuardRow = {
37
- readonly node: string;
38
- readonly signal: "self" | "jev" | "both" | "escalate";
39
- readonly self?: number;
40
- readonly jev?: number;
41
- readonly p: number | null;
42
- readonly threshold: number;
43
- readonly escalated: boolean;
44
- readonly workflow?: string;
45
26
  };
46
27
  /** One loop's exit (the DSL's `loop.exited`): its label, how many passes its body ran and whether its `until` held (false:
47
28
  * it reached maxIters). A compiled answer's quote re-pick (learn/check.ts) is a loop of 2 until its quote check passes:
48
29
  * `iterations` 2 is a re-pick, `met` whether it found its quotes. Rows, uncapped, are a run's metrics' `loops`, each
49
- * naming the workflow whose call ran it (`workflow`), as `guards` are. */
30
+ * naming the workflow whose call ran it (`workflow`). */
50
31
  export type LoopRow = {
51
32
  readonly node: string;
52
33
  readonly iterations: number;
@@ -63,15 +44,9 @@ export declare function learnedCallEntries(entries: readonly {
63
44
  readonly kind: string;
64
45
  readonly data?: unknown;
65
46
  }[]): Map<string, number>;
66
- /** A run's guard rows, from its root entries: every guard check of every learned_workflow call (LEARNED_NODES `guards`,
67
- * never the capped trace's), in order, each with its call's workflow, from the entry that counts for each call
68
- * (learnedCallEntries). What its metrics keep as `guards`. */
69
- export declare function guardsOf(entries: readonly {
70
- readonly kind: string;
71
- readonly data?: unknown;
72
- }[]): GuardRow[];
73
- /** A run's loop rows, from its root entries: every loop exit of every learned_workflow call (LEARNED_NODES `loops`), read
74
- * as guardsOf reads `guards`. What its metrics keep as `loops`. */
47
+ /** A run's loop rows, from its root entries: every loop exit of every learned_workflow call (LEARNED_NODES `loops`), in
48
+ * order, each with its call's workflow, from the entry that counts for each call (learnedCallEntries). What its metrics
49
+ * keep as `loops`. */
75
50
  export declare function loopsOf(entries: readonly {
76
51
  readonly kind: string;
77
52
  readonly data?: unknown;
@@ -1,8 +1,7 @@
1
- /** The journal entry a learned_workflow call keeps beside itself: `{ call, workflow, nodes, guards?, loops? }`, its call's
2
- * id, the workflow's name, each of its nodes that ran (LearnedNode, at most LEARNED_NODES_MAX), every guard check it made
3
- * (GuardRow) and every loop exit (LoopRow), these two never capped (a map over more items than the trace holds keeps
4
- * each); on a replay run's call that a write
5
- * stopped (learn/replay-calls.ts: one the graded run's recording does not have), `replay_skipped: { tool, step }` too; and
1
+ /** The journal entry a learned_workflow call keeps beside itself: `{ call, workflow, nodes, loops? }`, its call's
2
+ * id, the workflow's name, each of its nodes that ran (LearnedNode, at most LEARNED_NODES_MAX) and every loop exit
3
+ * (LoopRow), never capped (a map over more items than the trace holds keeps each); on a replay run's call that a write
4
+ * stopped (learn/replay-calls.ts: one the agent's recording does not have), `replay_skipped: { tool, step }` too; and
6
5
  * `ended`, how the workflow ended (LearnedEnded), on a call that ended (a replay run's call always keeps its entry). */
7
6
  export const LEARNED_NODES = "agentrun.learned_nodes";
8
7
  /** The most nodes a call keeps: a map over a long list runs its body once per item. */
@@ -22,8 +21,8 @@ export function learnedCallEntries(entries) {
22
21
  const data = entry.data;
23
22
  if (typeof data?.call !== "string")
24
23
  return;
25
- // A loop's exit is a run's row as a check is (a loop over an empty map exits with no node ended).
26
- const made = [data.nodes, data.guards, data.loops].some((rows) => Array.isArray(rows) && rows.length > 0);
24
+ // A loop's exit is a run's row (a loop over an empty map exits with no node ended).
25
+ const made = [data.nodes, data.loops].some((rows) => Array.isArray(rows) && rows.length > 0);
27
26
  if (made)
28
27
  ran.add(data.call);
29
28
  if (made || !ran.has(data.call))
@@ -31,20 +30,10 @@ export function learnedCallEntries(entries) {
31
30
  });
32
31
  return last;
33
32
  }
34
- /** A run's guard rows, from its root entries: every guard check of every learned_workflow call (LEARNED_NODES `guards`,
35
- * never the capped trace's), in order, each with its call's workflow, from the entry that counts for each call
36
- * (learnedCallEntries). What its metrics keep as `guards`. */
37
- export function guardsOf(entries) {
38
- return rowsOf(entries, "guards");
39
- }
40
- /** A run's loop rows, from its root entries: every loop exit of every learned_workflow call (LEARNED_NODES `loops`), read
41
- * as guardsOf reads `guards`. What its metrics keep as `loops`. */
33
+ /** A run's loop rows, from its root entries: every loop exit of every learned_workflow call (LEARNED_NODES `loops`), in
34
+ * order, each with its call's workflow, from the entry that counts for each call (learnedCallEntries). What its metrics
35
+ * keep as `loops`. */
42
36
  export function loopsOf(entries) {
43
- return rowsOf(entries, "loops");
44
- }
45
- /** The rows at `key` of each LEARNED_NODES entry that counts for its call (learnedCallEntries), in order, each with its
46
- * call's workflow. */
47
- function rowsOf(entries, key) {
48
37
  const rows = [];
49
38
  const last = learnedCallEntries(entries);
50
39
  for (const [index, entry] of entries.entries()) {
@@ -53,11 +42,10 @@ function rowsOf(entries, key) {
53
42
  const data = entry.data;
54
43
  if (typeof data?.call === "string" && last.get(data.call) !== index)
55
44
  continue;
56
- const kept = data?.[key];
57
- if (!Array.isArray(kept))
45
+ if (!Array.isArray(data?.loops))
58
46
  continue;
59
47
  const workflow = typeof data?.workflow === "string" ? data.workflow : undefined;
60
- for (const row of kept)
48
+ for (const row of data.loops)
61
49
  if (row && typeof row === "object")
62
50
  rows.push(workflow ? { ...row, workflow } : row);
63
51
  }