@parcha/agentrun-serve 0.1.0-beta.59 → 0.1.0-beta.61

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 (250) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +230 -120
  3. package/dist/acp-package.d.ts +4 -0
  4. package/dist/agent-delete.d.ts +6 -9
  5. package/dist/agent-delete.js +5 -3
  6. package/dist/agent-package.js +11 -1
  7. package/dist/api-only.d.ts +21 -3
  8. package/dist/api-only.js +41 -6
  9. package/dist/archil-routes.d.ts +4 -1
  10. package/dist/archil-routes.js +15 -12
  11. package/dist/archil-settings.d.ts +18 -8
  12. package/dist/archil-settings.js +35 -17
  13. package/dist/browser-person.d.ts +1 -1
  14. package/dist/browser-person.js +1 -1
  15. package/dist/calendar/tools.js +1 -1
  16. package/dist/chatgpt-plan.d.ts +4 -2
  17. package/dist/chatgpt-plan.js +13 -3
  18. package/dist/claude-login-token.d.ts +5 -0
  19. package/dist/claude-login-token.js +8 -0
  20. package/dist/claude-login.d.ts +49 -3
  21. package/dist/claude-login.js +140 -10
  22. package/dist/cli-learning/connections.js +1 -1
  23. package/dist/cli.js +42 -10
  24. package/dist/console/assets/{backend-BztxEAvb.js → backend-C9ffXUR5.js} +1 -1
  25. package/dist/console/assets/index-BnZV3lvW.js +639 -0
  26. package/dist/console/assets/{share-L84tlUDW.js → share-B1o5mJ56.js} +2 -2
  27. package/dist/console/assets/{styles-CaRKlHke.js → styles-D_znYrHR.js} +31 -31
  28. package/dist/console/assets/styles-fjQBFfMv.css +1 -0
  29. package/dist/console/index.html +3 -3
  30. package/dist/console/share.html +3 -3
  31. package/dist/decisions.d.ts +1 -1
  32. package/dist/decisions.js +2 -2
  33. package/dist/errors.d.ts +1 -0
  34. package/dist/errors.js +2 -0
  35. package/dist/factory-activity.d.ts +68 -0
  36. package/dist/factory-activity.js +153 -0
  37. package/dist/factory-runs.d.ts +11 -0
  38. package/dist/factory-runs.js +52 -0
  39. package/dist/filed-tool.d.ts +32 -0
  40. package/dist/filed-tool.js +122 -0
  41. package/dist/harness-check.js +2 -1
  42. package/dist/harness-keys.d.ts +1 -2
  43. package/dist/harness-keys.js +1 -2
  44. package/dist/harness-recipe.d.ts +13 -2
  45. package/dist/harness-recipe.js +30 -7
  46. package/dist/harness-sign-in.js +2 -1
  47. package/dist/harness-table.d.ts +9 -3
  48. package/dist/harness-table.js +11 -5
  49. package/dist/harness.js +6 -2
  50. package/dist/import-worker.js +2 -2
  51. package/dist/import.d.ts +9 -0
  52. package/dist/import.js +11 -1
  53. package/dist/key-refusal.d.ts +5 -0
  54. package/dist/key-refusal.js +30 -18
  55. package/dist/learn/audit.d.ts +20 -22
  56. package/dist/learn/audit.js +72 -55
  57. package/dist/learn/check.js +1 -1
  58. package/dist/learn/commit.d.ts +35 -43
  59. package/dist/learn/commit.js +62 -270
  60. package/dist/learn/compile.d.ts +4 -4
  61. package/dist/learn/compile.js +6 -7
  62. package/dist/learn/corrections.js +1 -1
  63. package/dist/learn/delete.d.ts +5 -12
  64. package/dist/learn/delete.js +17 -30
  65. package/dist/learn/forget-run.d.ts +16 -0
  66. package/dist/learn/forget-run.js +53 -0
  67. package/dist/learn/index.js +1 -1
  68. package/dist/learn/learning-of.d.ts +0 -4
  69. package/dist/learn/learning-of.js +0 -5
  70. package/dist/learn/{folder.d.ts → legacy/folder.d.ts} +2 -1
  71. package/dist/learn/{folder.js → legacy/folder.js} +4 -7
  72. package/dist/learn/legacy/place.d.ts +16 -0
  73. package/dist/{workspace/learning-workspace.js → learn/legacy/place.js} +12 -42
  74. package/dist/learn/legacy/scrub.d.ts +28 -0
  75. package/dist/learn/legacy/scrub.js +258 -0
  76. package/dist/learn/promote.d.ts +40 -66
  77. package/dist/learn/promote.js +69 -207
  78. package/dist/learn/reset-ledger.d.ts +18 -0
  79. package/dist/learn/reset-ledger.js +14 -0
  80. package/dist/learn/rows.d.ts +186 -0
  81. package/dist/learn/rows.js +376 -0
  82. package/dist/learn/secrets.d.ts +2 -1
  83. package/dist/learn/secrets.js +2 -2
  84. package/dist/learn/workflow-draft.d.ts +4 -1
  85. package/dist/learn/workflow-draft.js +12 -2
  86. package/dist/learned-nodes.d.ts +36 -0
  87. package/dist/learned-nodes.js +23 -0
  88. package/dist/learning-reset.d.ts +1 -1
  89. package/dist/learning-reset.js +9 -11
  90. package/dist/learning-routes.d.ts +60 -81
  91. package/dist/learning-routes.js +187 -360
  92. package/dist/learning-words.d.ts +2 -0
  93. package/dist/learning-words.js +2 -0
  94. package/dist/learning.d.ts +18 -24
  95. package/dist/learning.js +35 -66
  96. package/dist/local-model.d.ts +144 -0
  97. package/dist/local-model.js +214 -0
  98. package/dist/mcp-gateway.d.ts +6 -0
  99. package/dist/mcp-gateway.js +44 -8
  100. package/dist/mcp-probe.d.ts +7 -0
  101. package/dist/mcp-probe.js +7 -0
  102. package/dist/mcp-resources.d.ts +1 -1
  103. package/dist/native/discovery.d.ts +6 -0
  104. package/dist/native/discovery.js +14 -1
  105. package/dist/native/remote.d.ts +5 -0
  106. package/dist/native/remote.js +16 -0
  107. package/dist/native/runtime.js +3 -2
  108. package/dist/observation/observer.d.ts +6 -6
  109. package/dist/ollama-provider.d.ts +35 -0
  110. package/dist/ollama-provider.js +108 -2
  111. package/dist/openapi.js +147 -35
  112. package/dist/place-offers.d.ts +3 -0
  113. package/dist/place-offers.js +3 -0
  114. package/dist/place.d.ts +35 -12
  115. package/dist/place.js +67 -29
  116. package/dist/print.js +1 -1
  117. package/dist/purged-workflow.d.ts +0 -33
  118. package/dist/purged-workflow.js +3 -71
  119. package/dist/redact/match.d.ts +36 -8
  120. package/dist/redact/match.js +179 -44
  121. package/dist/run-export.js +4 -2
  122. package/dist/run-launch.d.ts +3 -3
  123. package/dist/run-learning-served.d.ts +3 -3
  124. package/dist/run-learning-served.js +1 -1
  125. package/dist/run-listing.d.ts +1 -1
  126. package/dist/run-timeline-served.d.ts +1 -1
  127. package/dist/run-timeline-served.js +6 -5
  128. package/dist/run-usage.js +3 -2
  129. package/dist/runnable.js +25 -8
  130. package/dist/runner/adapter-loop.d.ts +8 -1
  131. package/dist/runner/adapter-loop.js +100 -20
  132. package/dist/runner/adapter-run-spec.d.ts +3 -5
  133. package/dist/runner/adapter-run-spec.js +35 -61
  134. package/dist/runner/adapters/pi.d.ts +3 -2
  135. package/dist/runner/adapters/pi.js +3 -1
  136. package/dist/runner/audit.d.ts +3 -5
  137. package/dist/runner/audit.js +28 -51
  138. package/dist/runner/cli-run-spec.js +19 -22
  139. package/dist/runner/compare-end.d.ts +1 -3
  140. package/dist/runner/compare-end.js +6 -2
  141. package/dist/runner/disk-free.d.ts +15 -4
  142. package/dist/runner/disk-free.js +25 -7
  143. package/dist/runner/dispatch.js +2 -2
  144. package/dist/runner/feedback-round.d.ts +1 -1
  145. package/dist/runner/feedback-round.js +2 -2
  146. package/dist/runner/harness-loops.d.ts +9 -0
  147. package/dist/runner/harness-loops.js +49 -7
  148. package/dist/runner/held.d.ts +4 -11
  149. package/dist/runner/held.js +0 -25
  150. package/dist/runner/journal-kinds.d.ts +4 -1
  151. package/dist/runner/journal-kinds.js +1 -1
  152. package/dist/runner/learned-first.d.ts +0 -2
  153. package/dist/runner/learned-first.js +3 -3
  154. package/dist/runner/learning-end.d.ts +12 -16
  155. package/dist/runner/learning-end.js +41 -75
  156. package/dist/runner/learning-seed.d.ts +13 -16
  157. package/dist/runner/learning-seed.js +13 -23
  158. package/dist/runner/live-ticker.js +3 -4
  159. package/dist/runner/main.js +1 -1
  160. package/dist/runner/mcp-claim.js +3 -2
  161. package/dist/runner/mcp-run.d.ts +23 -4
  162. package/dist/runner/mcp-run.js +31 -2
  163. package/dist/runner/metrics.d.ts +4 -0
  164. package/dist/runner/metrics.js +9 -3
  165. package/dist/runner/monid-run.js +3 -1
  166. package/dist/runner/native-loop.js +3 -4
  167. package/dist/runner/promotion.d.ts +19 -28
  168. package/dist/runner/promotion.js +50 -69
  169. package/dist/runner/redact.d.ts +3 -0
  170. package/dist/runner/redact.js +7 -0
  171. package/dist/runner/reflect-hook.d.ts +2 -2
  172. package/dist/runner/reflect-hook.js +4 -1
  173. package/dist/runner/run-child-host.d.ts +1 -9
  174. package/dist/runner/run-child-host.js +12 -68
  175. package/dist/runner/runner.d.ts +1 -1
  176. package/dist/runner/sdk-loop.js +7 -7
  177. package/dist/runner/workflow-calls.d.ts +4 -1
  178. package/dist/runner/workflow-calls.js +35 -18
  179. package/dist/runner/workflow-loop.d.ts +1 -1
  180. package/dist/runner/workflow-loop.js +3 -1
  181. package/dist/runner/workflow-spec.d.ts +4 -0
  182. package/dist/runner/workflow-spec.js +18 -13
  183. package/dist/runs-over-store.d.ts +2 -2
  184. package/dist/runs-over-store.js +1 -1
  185. package/dist/sdk/check.d.ts +1 -4
  186. package/dist/sdk/check.js +2 -3
  187. package/dist/sdk/runs.d.ts +20 -7
  188. package/dist/sdk/runs.js +105 -68
  189. package/dist/secret-cut.js +7 -4
  190. package/dist/secret-rules.js +97 -83
  191. package/dist/secrets.d.ts +4 -0
  192. package/dist/secrets.js +44 -10
  193. package/dist/server-fs.d.ts +1 -1
  194. package/dist/server-fs.js +1 -1
  195. package/dist/server-keys.d.ts +6 -0
  196. package/dist/server-keys.js +12 -0
  197. package/dist/server.d.ts +22 -15
  198. package/dist/server.js +311 -198
  199. package/dist/slack.js +2 -1
  200. package/dist/source-sync/auxiliary.js +2 -2
  201. package/dist/store/index.d.ts +1 -1
  202. package/dist/store/index.js +1 -1
  203. package/dist/store/postgres/migrate.js +3 -1
  204. package/dist/store/postgres/migrations/0032_learning_rows.sql +65 -0
  205. package/dist/store/schema.d.ts +28 -2
  206. package/dist/store/schema.js +81 -5
  207. package/dist/store/sqlite/learning-rows.d.ts +23 -0
  208. package/dist/store/sqlite/learning-rows.js +559 -0
  209. package/dist/store/sqlite/store.d.ts +7 -1
  210. package/dist/store/sqlite/store.js +84 -18
  211. package/dist/store/store.d.ts +219 -6
  212. package/dist/store/store.js +13 -0
  213. package/dist/store-reads/journal.d.ts +33 -3
  214. package/dist/store-reads/journal.js +99 -4
  215. package/dist/store-reads/learning.d.ts +23 -26
  216. package/dist/store-reads/learning.js +42 -30
  217. package/dist/store-reads/loop.js +1 -1
  218. package/dist/store-view.d.ts +24 -2
  219. package/dist/store-view.js +40 -11
  220. package/dist/templates.d.ts +10 -2
  221. package/dist/templates.js +31 -4
  222. package/dist/tool-plane.d.ts +27 -3
  223. package/dist/tool-plane.js +79 -4
  224. package/dist/tools.d.ts +12 -2
  225. package/dist/tools.js +42 -7
  226. package/dist/trigger-launch-hook.d.ts +2 -2
  227. package/dist/trigger-launch-hook.js +1 -1
  228. package/dist/triggers.d.ts +7 -4
  229. package/dist/triggers.js +4 -4
  230. package/dist/web-holds.d.ts +2 -0
  231. package/dist/web-holds.js +5 -2
  232. package/dist/web-run.js +2 -1
  233. package/dist/workspace/archil-exec.js +1 -1
  234. package/dist/workspace/archil.d.ts +1 -1
  235. package/dist/workspace/archil.js +1 -1
  236. package/dist/workspace/computer-deps.js +5 -3
  237. package/dist/workspace/computer-providers.d.ts +11 -1
  238. package/dist/workspace/computer-providers.js +29 -2
  239. package/dist/workspace/index.d.ts +1 -2
  240. package/dist/workspace/index.js +1 -2
  241. package/dist/workspace/paths.d.ts +0 -4
  242. package/dist/workspace/paths.js +0 -6
  243. package/dist/workspace/workspace.d.ts +1 -1
  244. package/dist/workspace/workspace.js +1 -1
  245. package/package.json +13 -13
  246. package/templates/TOOLS.md +46 -0
  247. package/dist/console/assets/index-LwNL4L9q.js +0 -619
  248. package/dist/console/assets/styles-DQo8rzY-.css +0 -1
  249. package/dist/workspace/learning-workspace.d.ts +0 -24
  250. /package/dist/learn/{learning.sh → legacy/learning.sh} +0 -0
@@ -1,16 +1,12 @@
1
1
  import type { RunPath } from "../learning-cost.js";
2
2
  import type { FeedbackRound, OpenedRound } from "../runner/feedback-round.js";
3
- import type { Settings } from "../store/store.js";
3
+ import type { Settings, Store } from "../store/store.js";
4
4
  import type { Skipped } from "./replay-calls.js";
5
5
  import { type CheckTally, type FieldVerdict } from "./field-check.js";
6
+ import { type ResetRevision } from "./reset-ledger.js";
6
7
  import type { ReplayOutcome } from "../runner/workflow-first.js";
7
- /** How many grades, and how many promotion records, an agent keeps (newest kept). */
8
+ /** How many grades an agent keeps (newest kept). */
8
9
  export declare const GRADES_KEPT = 500;
9
- export declare const PROMOTIONS_KEPT = 200;
10
- /** How many champions of a workflow the promotions trim keeps back from the one the purge gate's answer leaves, that
11
- * one included (trimPromotions): a purge that lands inside one write's ask-to-write window and refuses fewer than this
12
- * many champions in a row still leaves one before them that serves. */
13
- export declare const CHAMPIONS_KEPT = 5;
14
10
  /** The most characters a grade's words (`label`) may hold, and the most of them and of an answer a compile ask shows. */
15
11
  export declare const LABEL_MAX = 4000;
16
12
  export declare const GRADE_SOURCES: readonly ["feedback", "eval"];
@@ -79,8 +75,9 @@ export interface PromotionRecord {
79
75
  * credentials run `handed_from` was handed (a claim's claimed run), else none (an owner's replay). One replay runs on
80
76
  * one set of settings. Never in the promotions read (promotionsShown). */
81
77
  readonly launch?: ReplayLaunch;
82
- /** The learning commit whose workflows/<workflow>/workflow.json is this digest's text: the seed of the claim that
83
- * recorded it. What the digest serves from as the champion (championOf) once a newer revision is on the folder's main. */
78
+ /** The learning save (its version id) whose workflows/<workflow>/workflow.json is this digest's text: the seed of the
79
+ * claim that recorded it. What the digest serves from as the champion (championOf) once a newer revision is the
80
+ * agent's newest. */
84
81
  readonly commit?: string;
85
82
  /** `sdk`: a connected (SDK) agent's check (runner/promotion.ts reserveSdkCheck), on each reservation and the record that
86
83
  * decides it. Its one run (`runs`) is the agent's native turn reserved now, not a replay run; a replaying one with no
@@ -235,23 +232,17 @@ export declare function skippedToolsOf(rows: readonly {
235
232
  readonly outcome: ReplayOutcome;
236
233
  readonly skipped?: Skipped;
237
234
  }[]): SkippedTool[];
238
- export declare const gradesKey: (agentId: string) => string;
239
- export declare const promotionsKey: (agentId: string) => string;
240
- /** A learned workflow revision an agent's learning reset deleted (DELETE /agents/{id}/learning, learning-reset.ts): its
241
- * workflow, its digest and its K (its check's compile_after; null when its records named none), nothing else of its
242
- * records. What the runs it served carry of its compile and check (learn/ledger.ts summarize, store-reads/learning.ts revisionsOf) is read
243
- * from it after the reset, so a kept run's cost reads as before. The runs keep the same names and digests. */
244
- export interface ResetRevision {
245
- readonly workflow: string;
246
- readonly digest: string;
247
- readonly k: number | null;
248
- }
249
- export declare const resetLedgerKey: (agentId: string) => string;
250
- /** The revisions the agent's resets deleted, first reset first. */
235
+ /** The store's learning records, as the promotion records and grades are read and written. */
236
+ export type LearningRecords = Pick<Store["learning"], "records" | "changeRecords">;
237
+ export { type ResetRevision, resetLedgerKey } from "./reset-ledger.js";
238
+ /** The revisions the agent's resets deleted, first reset first, and the ones a run's purge deleted while other runs
239
+ * still carry their spend (store/sqlite/learning-rows.ts dropRunLearning keeps them, in the purge's transaction). */
251
240
  export declare const resetLedgerOf: (settings: Pick<Settings, "get">, agentId: string) => Promise<ResetRevision[]>;
252
241
  /** Each revision `records` name (one per workflow and digest, its newest record's K) added to the agent's reset ledger,
253
- * before a reset deletes the records. A revision it holds already keeps its place and takes the records' K: while they
254
- * stood, the ledger read their K (store-reads/learning.ts revisionsOf), so the runs' shares read the same after this reset too. */
242
+ * before a reset deletes the records. A revision it holds already keeps its place and takes the records' K (withKept):
243
+ * while they stood, the ledger read their K (store-reads/learning.ts revisionsOf), so the runs' shares read the same
244
+ * after this reset too. A run's purge keeps the revisions it deletes by the same rule (learning-rows.ts
245
+ * dropRunLearning). */
255
246
  export declare function keepResetLedger(settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, agentId: string, records: readonly PromotionRecord[]): Promise<void>;
256
247
  /** The agent's reset watermark: when its newest reset began (epoch ms). Learning reads only the runs after it
257
248
  * (learn/compile.ts sinceReset): a run that started, or read its learning seed, at or before it learns nothing and is
@@ -262,37 +253,29 @@ export declare const resetAtOf: (settings: Pick<Settings, "get">, agentId: strin
262
253
  /** Agent `agentId`'s reset watermark set to `at`, in place of an earlier reset's. */
263
254
  export declare const keepResetAt: (settings: Pick<Settings, "put">, agentId: string, at: number) => Promise<void>;
264
255
  /** The agent's grades, oldest first. */
265
- export declare const gradesOf: (settings: Pick<Settings, "get">, agentId: string) => Promise<Grade[]>;
256
+ export declare const gradesOf: (rows: LearningRecords, agentId: string) => Promise<Grade[]>;
266
257
  /** Keeps `grade`, in place of any earlier grade of the same run, the newest GRADES_KEPT kept, at the next `seq`. */
267
- export declare const putGrade: (settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, agentId: string, grade: Grade) => Promise<Grade>;
268
- /** Every kept grade of run `runId` dropped (the run's delete, agent-delete.ts); no write when the agent keeps no grades. */
269
- export declare const dropGrades: (settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, agentId: string, runId: string) => Promise<void>;
258
+ export declare const putGrade: (rows: LearningRecords, agentId: string, grade: Grade) => Promise<Grade>;
259
+ /** Every kept grade of run `runId` dropped (the run's delete, agent-delete.ts); no write when the agent keeps none. */
260
+ export declare const dropGrades: (rows: LearningRecords, agentId: string, runId: string) => Promise<void>;
270
261
  /** What agent `agentId`'s learning copied from run `runId`, gone (the run's purge, agent-delete.ts): its kept grades
271
262
  * dropped (dropGrades), and its promotion records' disagreements naming it blanked (forgetRunIn), each record's decision,
272
263
  * numbers and run ids kept. No write when nothing names it. */
273
- export declare const forgetRunCopies: (settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, agentId: string, runId: string) => Promise<void>;
264
+ export declare const forgetRunCopies: (rows: LearningRecords, agentId: string, runId: string) => Promise<void>;
274
265
  /** Marks the kept grade `grade` (its run, given at its `at`, kept at its `seq`) with the feedback round it opened and
275
266
  * 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
276
267
  * millisecond too (its `seq` is another). The grade, marked. */
277
- export declare const markGradeRound: (settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, agentId: string, grade: Grade, opened: OpenedRound) => Promise<Grade>;
268
+ export declare const markGradeRound: (rows: LearningRecords, agentId: string, grade: Grade, opened: OpenedRound) => Promise<Grade>;
278
269
  /** The agent's promotion records, oldest first: only those in a state this code writes (writtenOf). */
279
- export declare const promotionsOf: (settings: Pick<Settings, "get">, agentId: string) => Promise<PromotionRecord[]>;
270
+ export declare const promotionsOf: (rows: Pick<LearningRecords, "records">, agentId: string) => Promise<PromotionRecord[]>;
280
271
  /** The newest record of `workflow` at `digest`, or undefined. */
281
272
  export declare const promotionOf: (records: readonly PromotionRecord[], workflow: string, digest: string) => PromotionRecord | undefined;
282
273
  /** The champion of `workflow`: the newest record of the digest promoted last, while that digest's newest record still
283
274
  * says promote. A newer revision replaying or held never stops it; it stops when a newer revision's check promotes that
284
275
  * one (then the champion), or when its own newest record is a hold (a held revision its owner replays, askReplay, that
285
- * promotes wins again). The money rule stops it on its own (runner/workflow-first.ts). A record `refused` names is
286
- * skipped, as if absent: one whose commit holds its workflow as a purged run wrote it (purged-workflow.ts refusedOf), so
287
- * after a purge of the champion's run the newest promotion the purge gate lets through serves again. Undefined: none. */
288
- export declare function championOf(records: readonly PromotionRecord[], workflow: string, refused?: Refused): PromotionRecord | undefined;
289
- /** The promotion records championOf skips (purged-workflow.ts refusedOf: the purge gate refuses each at its commit, so
290
- * it names a record by its workflow and commit, a copy read later included). Every reader that serves or names the
291
- * champion passes it, and the trim keeps the champion past it (trimPromotions). `unread`: a commit it asked could not be
292
- * read, so it may refuse too few, and the trim trims nothing on it (recordPromotion fails closed). */
293
- export type Refused = ((record: PromotionRecord) => boolean) & {
294
- readonly unread?: boolean;
295
- };
276
+ * promotes wins again). The money rule stops it on its own (runner/workflow-first.ts). A purged run's records are gone
277
+ * with it (Store.learning purgeRun), so the champion before it serves again. Undefined: none. */
278
+ export declare function championOf(records: readonly PromotionRecord[], workflow: string): PromotionRecord | undefined;
296
279
  /** The newest promotion of `workflow` at `digest`: the promote record that began its newest run of promote records (its
297
280
  * first, or the first after a record of that digest that was not promote: an owner's replay that promoted a held
298
281
  * revision), or undefined when none was ever promoted. Its `at` names that promotion: an audit row keeps the one serving
@@ -304,8 +287,8 @@ export declare function promotionStartOf(records: readonly PromotionRecord[], wo
304
287
  export declare function replayingOf(records: readonly PromotionRecord[], workflow: string, digest: string | null): PromotionRecord[];
305
288
  /** What each learned workflow with a record serves, by name: `digest`, its champion's (championOf; null: none serves,
306
289
  * the agent takes its runs), and `replaying`, the revision other than it whose check is at work (null: none). What the
307
- * promotions list says beside the records (GET /agents/{id}/learning/promotions), its champion skipping `refused`. */
308
- export declare function servingOf(records: readonly PromotionRecord[], refused?: Refused): {
290
+ * promotions list says beside the records (GET /agents/{id}/learning/promotions). */
291
+ export declare function servingOf(records: readonly PromotionRecord[]): {
309
292
  workflow: string;
310
293
  digest: string | null;
311
294
  replaying: string | null;
@@ -321,16 +304,16 @@ export type ServingState = "serving" | "checking" | "held" | "stopped";
321
304
  /** Whether the money rule stops `workflow` at `digest` from running first: runner/workflow-first.ts costStopOf over the
322
305
  * agent's runs, the decision a run's claim reads (workflowFirstOf). */
323
306
  export type CostStop = (workflow: string, digest: string) => boolean;
324
- export declare function servingStateOf(records: readonly PromotionRecord[], workflow: string, costStop: CostStop, refused?: Refused): ServingState;
307
+ export declare function servingStateOf(records: readonly PromotionRecord[], workflow: string, costStop: CostStop): ServingState;
325
308
  /** The promotions list as it leaves (GET /agents/{id}/learning/promotions): the records and what serves (servingOf), every
326
309
  * text in them cut by `shown` (learning.ts secretsShown, as the other learning reads cut theirs), at any depth and under
327
310
  * any field, so a field added later is cut too: a workflow's name whole (`shown.name`), any other text of its part
328
311
  * (`shown.text`: a reason, a digest, a run id). Numbers and the rest as they are. A replaying record's `launch` (a run
329
- * launch: its notes, model and plane) never leaves: aggregates only. Its champions skip `refused` (championOf). */
312
+ * launch: its notes, model and plane) never leaves: aggregates only. */
330
313
  export declare function promotionsShown(records: readonly PromotionRecord[], shown: {
331
314
  readonly text: (text: string) => string;
332
315
  readonly name: (name: string) => string;
333
- }, refused?: Refused): {
316
+ }): {
334
317
  promotions: PromotionRecord[];
335
318
  serving: ReturnType<typeof servingOf>;
336
319
  };
@@ -352,25 +335,16 @@ export type Recorded = {
352
335
  * and of every record kept (`items`: a check across revisions, one at a time, in the same guarded write): so of two
353
336
  * claims deciding at once only the first decision is kept, and only its claim acts on it (Recorded.won). What the one
354
337
  * there now has blanked is blanked in `record` too (forgetRunIn): a record built on a copy read before a run's purge
355
- * (a connected agent's next turn, release or decision carries its turns on) never writes that run's text back. The trim
356
- * keeps the champion past what the purge gate refuses too (`refused`, purged-workflow.ts refusedIn: asked before the
357
- * guarded write when it would trim, over the records that write reads and `record` after them, so a promotion it lands
358
- * for a revision the gate refuses is skipped as its readers skip it; a write that would trim records other than those
359
- * it asked over, another writer's landing in between, reads and asks again). Fails closed: a gate that could not read
360
- * a commit (Refused.unread) or could not be asked leaves every record, the write trims nothing. */
361
- export declare function recordPromotion(settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, agentId: string, record: PromotionRecord, still: (now: PromotionRecord | undefined, items: readonly PromotionRecord[]) => boolean, refused?: (records: readonly PromotionRecord[]) => Promise<Refused>): Promise<Recorded>;
362
- /** The newest records, at most PROMOTIONS_KEPT, in order, with each workflow's champion (championOf) the same after as
363
- * before, whatever was dropped: championOf reads the digest promoted last and its newest record, so the trim keeps both
364
- * (a held last revision is never trimmed into handing the champion back), read over every record and again past those
365
- * `refused` names (the purge gate's: a champion its readers skip, so the earlier one they serve is kept), and a
366
- * replaying revision's newest record (what its settle, its runs' claims and the one-check-at-a-time rule read: dropped,
367
- * a newer revision would start a second check while its runs run, and its verdict would never land). Then the newest
368
- * RECENT_KEPT records (the newest one, the record a write just landed, always: its write said it won, so its decision
369
- * is there for the next claim). Then, in the room those leave, the champions before the one `refused` leaves, nearest
370
- * first, CHAMPIONS_KEPT in all from that one (a purge landing after the gate answered refuses every champion its run
371
- * wrote, two or more in a row: the newest one before them still serves), each one's promote and newest record whole
372
- * or neither. The rest is the newest records. */
373
- export declare function trimPromotions(items: readonly PromotionRecord[], refused?: Refused): PromotionRecord[];
338
+ * (a connected agent's next turn, release or decision carries its turns on) never writes that run's text back. A record
339
+ * of a digest no version of its workflow holds (a run's purge took it since the record's check or reservation read it)
340
+ * writes nothing, not won, read in the same write (Store.learning changeRecords `held`), so no replay, hold or promote
341
+ * of a purged run's text lands; `anyDigest`, a failed draft's record (its digest is its run's, which no version holds),
342
+ * is the one exception, written as its run's (`runId`): its run's purge takes it. One transaction (Store.learning
343
+ * changeRecords), which also blanks a purged run's copies the record holds (forgetRunIn). */
344
+ export declare function recordPromotion(rows: LearningRecords, agentId: string, record: PromotionRecord, still: (now: PromotionRecord | undefined, items: readonly PromotionRecord[]) => boolean, options?: {
345
+ readonly anyDigest?: true;
346
+ readonly runId?: string;
347
+ }): Promise<Recorded>;
374
348
  /** How many of a replay's own runs ended each way (a run not ended past its deadline is failed): what each run did. A
375
349
  * check record keeps them as it was decided on. */
376
350
  export type ReplayOutcomes = Readonly<Record<ReplayOutcome, number>>;
@@ -3,25 +3,19 @@
3
3
  // each input's best known answer (a grade's expected answer, else the agent's own recorded answer: learn/field-check.ts;
4
4
  // the bar is the agent definition's, learning-setting.ts). A replay runs the workflow alone on a run's recorded input (a
5
5
  // run of its own, at workflow cost, runner/promotion.ts); a step it hands back on is not an answer alone. This module is
6
- // the answer comparison and the two records the store keeps (the agent's grades, its workflows' promotion records), over
7
- // the settings table; the orchestration is runner/promotion.ts. Grades are what a person or an eval said of a run (PUT
8
- // /runs/{id}/grade).
6
+ // the answer comparison and the two records the store keeps (the agent's grades, its workflows' promotion records), as
7
+ // learning records (Store.learning records); the orchestration is runner/promotion.ts. Grades are what a person or an
8
+ // eval said of a run (PUT /runs/{id}/grade).
9
9
  import { createHash } from "node:crypto";
10
10
  import { isDeepStrictEqual } from "node:util";
11
11
  import { answerJson } from "../answer-json.js";
12
12
  import { pathSegments } from "../learning-setting.js";
13
13
  import { isObject } from "../validate.js";
14
14
  import { sameValue } from "./field-check.js";
15
- /** How many grades, and how many promotion records, an agent keeps (newest kept). */
15
+ import { blankCheck, forgetRunIn } from "./forget-run.js";
16
+ import { resetLedgerKey, resetRevisionKey, withKept } from "./reset-ledger.js";
17
+ /** How many grades an agent keeps (newest kept). */
16
18
  export const GRADES_KEPT = 500;
17
- export const PROMOTIONS_KEPT = 200;
18
- /** How many champions of a workflow the promotions trim keeps back from the one the purge gate's answer leaves, that
19
- * one included (trimPromotions): a purge that lands inside one write's ask-to-write window and refuses fewer than this
20
- * many champions in a row still leaves one before them that serves. */
21
- export const CHAMPIONS_KEPT = 5;
22
- /** How many of the newest records the promotions trim keeps ahead of the champions before (CHAMPIONS_KEPT): those only
23
- * take the room the newest leave, so they never crowd out a decision a check just landed. */
24
- const RECENT_KEPT = PROMOTIONS_KEPT / 2;
25
19
  /** The most characters a grade's words (`label`) may hold, and the most of them and of an answer a compile ask shows. */
26
20
  export const LABEL_MAX = 4_000;
27
21
  export const GRADE_SOURCES = ["feedback", "eval"];
@@ -42,10 +36,8 @@ export function skippedToolsOf(rows) {
42
36
  return [...by].map(([tool, one]) => ({ tool, inputs: one.inputs, no_read_only_hint: one.unmarked }))
43
37
  .sort((a, b) => b.inputs - a.inputs || (a.tool < b.tool ? -1 : a.tool > b.tool ? 1 : 0));
44
38
  }
45
- export const gradesKey = (agentId) => `learning.grades.${agentId}`;
46
- export const promotionsKey = (agentId) => `learning.promotions.${agentId}`;
47
39
  const itemsOf = (value) => (value && typeof value === "object" && Array.isArray(value.items) ? [...(value.items)] : []);
48
- /** `update` over the list kept under `key`, compare-and-set so two writers never lose one's change; the list after. */
40
+ /** `update` over the list kept under settings `key`, compare-and-set so two writers never lose one's change. */
49
41
  async function updateKept(settings, key, update) {
50
42
  for (let tries = 0; tries < 20; tries++) {
51
43
  const was = await settings.get(key);
@@ -62,22 +54,28 @@ async function updateKept(settings, key, update) {
62
54
  }
63
55
  throw new Error(`${key} kept changing under this write; try again`);
64
56
  }
65
- export const resetLedgerKey = (agentId) => `learning.reset-ledger.${agentId}`;
66
- /** The revisions the agent's resets deleted, first reset first. */
57
+ /** A record's write as it was read: its seq kept, so changeRecords keeps it in place. */
58
+ const keptWrite = (one, data = one.data) => ({ seq: one.seq, runId: one.runId, workflow: one.workflow, digest: one.digest, data });
59
+ const gradeWrite = (grade) => ({ runId: grade.run, workflow: grade.workflow ?? null, digest: grade.digest ?? null, data: grade });
60
+ /** A promotion record's write: no run's (a check's decision outlives each run it read), unless `runId`, the run whose
61
+ * record it is alone (a failed draft's hold: its run's purge takes it, and a write after that purge writes nothing). */
62
+ const promotionWrite = (record, runId = null) => ({ runId, workflow: record.workflow, digest: record.digest, data: record });
63
+ export { resetLedgerKey } from "./reset-ledger.js";
64
+ /** The revisions the agent's resets deleted, first reset first, and the ones a run's purge deleted while other runs
65
+ * still carry their spend (store/sqlite/learning-rows.ts dropRunLearning keeps them, in the purge's transaction). */
67
66
  export const resetLedgerOf = async (settings, agentId) => itemsOf(await settings.get(resetLedgerKey(agentId)));
68
67
  /** Each revision `records` name (one per workflow and digest, its newest record's K) added to the agent's reset ledger,
69
- * before a reset deletes the records. A revision it holds already keeps its place and takes the records' K: while they
70
- * stood, the ledger read their K (store-reads/learning.ts revisionsOf), so the runs' shares read the same after this reset too. */
68
+ * before a reset deletes the records. A revision it holds already keeps its place and takes the records' K (withKept):
69
+ * while they stood, the ledger read their K (store-reads/learning.ts revisionsOf), so the runs' shares read the same
70
+ * after this reset too. A run's purge keeps the revisions it deletes by the same rule (learning-rows.ts
71
+ * dropRunLearning). */
71
72
  export async function keepResetLedger(settings, agentId, records) {
72
73
  const newest = new Map();
73
74
  for (const record of records)
74
- newest.set(`${record.workflow}\0${record.digest}`, { workflow: record.workflow, digest: record.digest, k: record.check?.compile_after ?? null });
75
+ newest.set(resetRevisionKey(record), { workflow: record.workflow, digest: record.digest, k: record.check?.compile_after ?? null });
75
76
  if (!newest.size)
76
77
  return;
77
- await updateKept(settings, resetLedgerKey(agentId), (items) => {
78
- const held = new Set(items.map((one) => `${one.workflow}\0${one.digest}`));
79
- return [...items.map((one) => newest.get(`${one.workflow}\0${one.digest}`) ?? one), ...[...newest].filter(([key]) => !held.has(key)).map(([, one]) => one)];
80
- });
78
+ await updateKept(settings, resetLedgerKey(agentId), (items) => withKept(items, newest));
81
79
  }
82
80
  /** The agent's reset watermark: when its newest reset began (epoch ms). Learning reads only the runs after it
83
81
  * (learn/compile.ts sinceReset): a run that started, or read its learning seed, at or before it learns nothing and is
@@ -92,80 +90,31 @@ export const resetAtOf = async (settings, agentId) => {
92
90
  /** Agent `agentId`'s reset watermark set to `at`, in place of an earlier reset's. */
93
91
  export const keepResetAt = (settings, agentId, at) => settings.put(resetAtKey(agentId), { at });
94
92
  /** The agent's grades, oldest first. */
95
- export const gradesOf = async (settings, agentId) => itemsOf(await settings.get(gradesKey(agentId)));
93
+ export const gradesOf = async (rows, agentId) => (await rows.records(agentId, "grade")).map((one) => one.data);
96
94
  /** Keeps `grade`, in place of any earlier grade of the same run, the newest GRADES_KEPT kept, at the next `seq`. */
97
- export const putGrade = async (settings, agentId, grade) => {
98
- let kept = grade;
99
- await updateKept(settings, gradesKey(agentId), (items) => {
100
- kept = { ...grade, seq: Math.max(0, ...items.map((one) => one.seq ?? 0)) + 1 };
101
- return [...items.filter((one) => one.run !== grade.run), kept].slice(-GRADES_KEPT);
102
- });
103
- return kept;
104
- };
105
- /** Every kept grade of run `runId` dropped (the run's delete, agent-delete.ts); no write when the agent keeps no grades. */
106
- export const dropGrades = async (settings, agentId, runId) => {
107
- if (!(await gradesOf(settings, agentId)).some((one) => one.run === runId))
108
- return;
109
- await updateKept(settings, gradesKey(agentId), (items) => items.filter((one) => one.run !== runId));
110
- };
111
- /** A check's disagreement with what it copied from its run blanked: its run id and which way the draft went (an answer,
112
- * a hand-back, a failed step) and the fields it had wrong (the definition's names, no run text) and where each known
113
- * answer came from kept, its input, the agent's answer, the draft's, the known answers' values and the grader's words
114
- * gone. */
115
- const blankCheck = (one) => ({
116
- run: one.run, input: "", agent: null,
117
- ...(one.draft !== undefined ? { draft: "" } : {}),
118
- ...(one.escalated !== undefined ? { escalated: "" } : {}),
119
- ...(one.failed ? { failed: true } : {}),
120
- ...(one.fields ? { fields: one.fields } : {}),
121
- ...(one.expected ? { expected: one.expected.map(({ field, known, value }) => ({ field, known, ...(value !== undefined ? { value: "" } : {}) })) } : {}),
95
+ export const putGrade = (rows, agentId, grade) => rows.changeRecords(agentId, "grade", (records) => {
96
+ const kept = { ...grade, seq: Math.max(0, ...records.map((one) => one.data.seq ?? 0)) + 1 };
97
+ const others = records.filter((one) => one.data.run !== grade.run).slice(-(GRADES_KEPT - 1));
98
+ return { records: [...others.map((one) => keptWrite(one)), gradeWrite(kept)], result: kept };
122
99
  });
123
- /** An audit's disagreement blanked the same way: its run ids and whether a grade wrote it kept, its known answer empty. */
124
- const blankAudit = (one) => ({ run: one.run, served: one.served, input: "", agent: null, draft: null, ...(one.graded ? { graded: true } : {}), ...(one.expected !== undefined ? { expected: "" } : {}) });
125
- /** `record` with what it copied from run `runId` blanked: each disagreement naming it (a check's agent run, a connected
126
- * agent's collected turn too; an audit's served run or shadow run), and the grader's words its reason quotes from one
127
- * (differentDecisionWords' example). Its decision, numbers and run ids stay. The record itself when it names no such
128
- * disagreement. */
129
- function forgetRunIn(record, runId) {
130
- if (!record || typeof record !== "object")
131
- return record;
132
- const check = record.check?.disagreements?.some((one) => one.run === runId);
133
- const turns = record.check?.turns?.disagreements?.some((one) => one.run === runId);
134
- const audit = record.audit?.disagreements.some((one) => one.run === runId || one.served === runId);
135
- if (!check && !turns && !audit)
136
- return record;
137
- let reason = record.reason;
138
- for (const one of record.check?.disagreements ?? [])
139
- if (one.run === runId && one.differs_on !== undefined)
140
- reason = reason.replace(` (for example: ${one.differs_on})`, "");
141
- const blanked = (list) => list.map((one) => (one.run === runId ? blankCheck(one) : one));
142
- return {
143
- ...record,
144
- reason,
145
- ...((check || turns) && record.check ? { check: {
146
- ...record.check,
147
- ...(check ? { disagreements: blanked(record.check.disagreements) } : {}),
148
- ...(turns ? { turns: { ...record.check.turns, disagreements: blanked(record.check.turns.disagreements) } } : {}),
149
- } } : {}),
150
- ...(audit && record.audit ? { audit: { ...record.audit, disagreements: record.audit.disagreements.map((one) => (one.run === runId || one.served === runId ? blankAudit(one) : one)) } } : {}),
151
- };
152
- }
100
+ /** Every kept grade of run `runId` dropped (the run's delete, agent-delete.ts); no write when the agent keeps none. */
101
+ export const dropGrades = (rows, agentId, runId) => rows.changeRecords(agentId, "grade", (records) => (records.some((one) => one.data.run === runId) ? { records: records.filter((one) => one.data.run !== runId).map((one) => keptWrite(one)), result: undefined } : { result: undefined }));
153
102
  /** What agent `agentId`'s learning copied from run `runId`, gone (the run's purge, agent-delete.ts): its kept grades
154
103
  * dropped (dropGrades), and its promotion records' disagreements naming it blanked (forgetRunIn), each record's decision,
155
104
  * numbers and run ids kept. No write when nothing names it. */
156
- export const forgetRunCopies = async (settings, agentId, runId) => {
157
- await dropGrades(settings, agentId, runId);
158
- const records = itemsOf(await settings.get(promotionsKey(agentId)));
159
- if (records.every((one) => forgetRunIn(one, runId) === one))
160
- return;
161
- await updateKept(settings, promotionsKey(agentId), (items) => items.map((one) => forgetRunIn(one, runId)));
105
+ export const forgetRunCopies = async (rows, agentId, runId) => {
106
+ await dropGrades(rows, agentId, runId);
107
+ await rows.changeRecords(agentId, "promotion", (records) => {
108
+ const after = records.map((one) => ({ one, data: forgetRunIn(one.data, runId) }));
109
+ return after.every(({ one, data }) => data === one.data) ? { result: undefined } : { records: after.map(({ one, data }) => keptWrite(one, data)), result: undefined };
110
+ });
162
111
  };
163
112
  /** Marks the kept grade `grade` (its run, given at its `at`, kept at its `seq`) with the feedback round it opened and
164
113
  * 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
165
114
  * millisecond too (its `seq` is another). The grade, marked. */
166
- export const markGradeRound = async (settings, agentId, grade, opened) => {
115
+ export const markGradeRound = async (rows, agentId, grade, opened) => {
167
116
  const mark = { feedback: opened.round, feedbackCommand: opened.command };
168
- await updateKept(settings, gradesKey(agentId), (items) => items.map((one) => (one.run === grade.run && one.at === grade.at && one.seq === grade.seq ? { ...one, ...mark } : one)));
117
+ await rows.changeRecords(agentId, "grade", (records) => ({ records: records.map((one) => { const kept = one.data; return keptWrite(one, kept.run === grade.run && kept.at === grade.at && kept.seq === grade.seq ? { ...kept, ...mark } : kept); }), result: undefined }));
169
118
  return { ...grade, ...mark };
170
119
  };
171
120
  /** The states a promotion record is written in (PromotionRecord.decided). */
@@ -174,24 +123,19 @@ const DECIDED = ["promote", "hold", "replaying"];
174
123
  * checked again). */
175
124
  const writtenOf = (items) => items.filter((one) => DECIDED.includes(one?.decided));
176
125
  /** The agent's promotion records, oldest first: only those in a state this code writes (writtenOf). */
177
- export const promotionsOf = async (settings, agentId) => writtenOf(itemsOf(await settings.get(promotionsKey(agentId))));
126
+ export const promotionsOf = async (rows, agentId) => writtenOf((await rows.records(agentId, "promotion")).map((one) => one.data));
178
127
  /** The newest record of `workflow` at `digest`, or undefined. */
179
128
  export const promotionOf = (records, workflow, digest) => records.findLast((one) => one.workflow === workflow && one.digest === digest);
180
129
  /** The champion of `workflow`: the newest record of the digest promoted last, while that digest's newest record still
181
130
  * says promote. A newer revision replaying or held never stops it; it stops when a newer revision's check promotes that
182
131
  * one (then the champion), or when its own newest record is a hold (a held revision its owner replays, askReplay, that
183
- * promotes wins again). The money rule stops it on its own (runner/workflow-first.ts). A record `refused` names is
184
- * skipped, as if absent: one whose commit holds its workflow as a purged run wrote it (purged-workflow.ts refusedOf), so
185
- * after a purge of the champion's run the newest promotion the purge gate lets through serves again. Undefined: none. */
186
- export function championOf(records, workflow, refused = NONE_REFUSED) {
187
- const kept = records.filter((one) => one.workflow === workflow && !refused(one));
188
- const last = lastPromotedOf(kept, workflow);
189
- const now = last === undefined ? undefined : promotionOf(kept, workflow, last);
132
+ * promotes wins again). The money rule stops it on its own (runner/workflow-first.ts). A purged run's records are gone
133
+ * with it (Store.learning purgeRun), so the champion before it serves again. Undefined: none. */
134
+ export function championOf(records, workflow) {
135
+ const last = lastPromotedOf(records, workflow);
136
+ const now = last === undefined ? undefined : promotionOf(records, workflow, last);
190
137
  return now?.decided === "promote" ? now : undefined;
191
138
  }
192
- const NONE_REFUSED = () => false;
193
- /** The gate's answer when it could not be asked at all: refuses none, said unread. */
194
- const UNREAD = Object.assign(() => false, { unread: true });
195
139
  /** The newest promotion of `workflow` at `digest`: the promote record that began its newest run of promote records (its
196
140
  * first, or the first after a record of that digest that was not promote: an owner's replay that promoted a held
197
141
  * revision), or undefined when none was ever promoted. Its `at` names that promotion: an audit row keeps the one serving
@@ -228,19 +172,19 @@ export function replayingOf(records, workflow, digest) {
228
172
  }
229
173
  /** What each learned workflow with a record serves, by name: `digest`, its champion's (championOf; null: none serves,
230
174
  * the agent takes its runs), and `replaying`, the revision other than it whose check is at work (null: none). What the
231
- * promotions list says beside the records (GET /agents/{id}/learning/promotions), its champion skipping `refused`. */
232
- export function servingOf(records, refused) {
175
+ * promotions list says beside the records (GET /agents/{id}/learning/promotions). */
176
+ export function servingOf(records) {
233
177
  const names = [...new Set(records.map((one) => one.workflow))].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
234
178
  return names.map((workflow) => {
235
- const digest = championOf(records, workflow, refused)?.digest ?? null;
179
+ const digest = championOf(records, workflow)?.digest ?? null;
236
180
  return { workflow, digest, replaying: replayingOf(records, workflow, digest)[0]?.digest ?? null };
237
181
  });
238
182
  }
239
- export function servingStateOf(records, workflow, costStop, refused) {
183
+ export function servingStateOf(records, workflow, costStop) {
240
184
  const newest = records.findLast((one) => one.workflow === workflow);
241
185
  if (newest === undefined || newest.decided === "replaying")
242
186
  return "checking";
243
- const champion = championOf(records, workflow, refused);
187
+ const champion = championOf(records, workflow);
244
188
  if (champion)
245
189
  return costStop(workflow, champion.digest) ? "stopped" : "serving";
246
190
  return newest.decided === "hold" && (newest.check?.stopped || newest.audit?.stopped) ? "stopped" : "held";
@@ -249,9 +193,9 @@ export function servingStateOf(records, workflow, costStop, refused) {
249
193
  * text in them cut by `shown` (learning.ts secretsShown, as the other learning reads cut theirs), at any depth and under
250
194
  * any field, so a field added later is cut too: a workflow's name whole (`shown.name`), any other text of its part
251
195
  * (`shown.text`: a reason, a digest, a run id). Numbers and the rest as they are. A replaying record's `launch` (a run
252
- * launch: its notes, model and plane) never leaves: aggregates only. Its champions skip `refused` (championOf). */
253
- export function promotionsShown(records, shown, refused) {
254
- return { promotions: records.map(({ launch: _, ...one }) => shownDeep(one, shown)), serving: servingOf(records, refused).map((one) => shownDeep(one, shown)) };
196
+ * launch: its notes, model and plane) never leaves: aggregates only. */
197
+ export function promotionsShown(records, shown) {
198
+ return { promotions: records.map(({ launch: _, ...one }) => shownDeep(one, shown)), serving: servingOf(records).map((one) => shownDeep(one, shown)) };
255
199
  }
256
200
  /** `value` cut as the promotions read cuts its records (promotionsShown), at any depth and under any field: a workflow's
257
201
  * name whole (`shown.name`), any other text of its part (`shown.text`). Numbers and the rest as they are. */
@@ -268,106 +212,24 @@ const blankedRuns = (record) => [...(record?.check?.disagreements ?? []), ...(re
268
212
  * and of every record kept (`items`: a check across revisions, one at a time, in the same guarded write): so of two
269
213
  * claims deciding at once only the first decision is kept, and only its claim acts on it (Recorded.won). What the one
270
214
  * there now has blanked is blanked in `record` too (forgetRunIn): a record built on a copy read before a run's purge
271
- * (a connected agent's next turn, release or decision carries its turns on) never writes that run's text back. The trim
272
- * keeps the champion past what the purge gate refuses too (`refused`, purged-workflow.ts refusedIn: asked before the
273
- * guarded write when it would trim, over the records that write reads and `record` after them, so a promotion it lands
274
- * for a revision the gate refuses is skipped as its readers skip it; a write that would trim records other than those
275
- * it asked over, another writer's landing in between, reads and asks again). Fails closed: a gate that could not read
276
- * a commit (Refused.unread) or could not be asked leaves every record, the write trims nothing. */
277
- export async function recordPromotion(settings, agentId, record, still, refused) {
278
- for (let tries = 0; tries < 20; tries++) {
279
- let out;
280
- const before = refused ? writtenOf(itemsOf(await settings.get(promotionsKey(agentId)))) : [];
281
- const skip = refused && before.length >= PROMOTIONS_KEPT ? await refused([...before, record]).catch(() => UNREAD) : undefined;
282
- const asked = JSON.stringify(before);
283
- await updateKept(settings, promotionsKey(agentId), (saved) => {
284
- const items = writtenOf(saved);
285
- const now = promotionOf(items, record.workflow, record.digest);
286
- if (!still(now, items)) {
287
- out = { record: now, won: false };
288
- return items;
289
- }
290
- const kept = blankedRuns(now).reduce(forgetRunIn, record);
291
- if (refused && items.length >= PROMOTIONS_KEPT && JSON.stringify(items) !== asked) {
292
- out = undefined;
293
- return items;
294
- }
295
- out = { record: kept, won: true };
296
- return skip?.unread ? [...items, kept] : trimPromotions([...items, kept], skip);
297
- });
298
- if (out)
299
- return out;
300
- }
301
- throw new Error(`${promotionsKey(agentId)} kept changing under this write; try again`);
302
- }
303
- /** The newest records, at most PROMOTIONS_KEPT, in order, with each workflow's champion (championOf) the same after as
304
- * before, whatever was dropped: championOf reads the digest promoted last and its newest record, so the trim keeps both
305
- * (a held last revision is never trimmed into handing the champion back), read over every record and again past those
306
- * `refused` names (the purge gate's: a champion its readers skip, so the earlier one they serve is kept), and a
307
- * replaying revision's newest record (what its settle, its runs' claims and the one-check-at-a-time rule read: dropped,
308
- * a newer revision would start a second check while its runs run, and its verdict would never land). Then the newest
309
- * RECENT_KEPT records (the newest one, the record a write just landed, always: its write said it won, so its decision
310
- * is there for the next claim). Then, in the room those leave, the champions before the one `refused` leaves, nearest
311
- * first, CHAMPIONS_KEPT in all from that one (a purge landing after the gate answered refuses every champion its run
312
- * wrote, two or more in a row: the newest one before them still serves), each one's promote and newest record whole
313
- * or neither. The rest is the newest records. */
314
- export function trimPromotions(items, refused = NONE_REFUSED) {
315
- if (items.length <= PROMOTIONS_KEPT)
316
- return [...items];
317
- const keep = new Set();
318
- // The champions before, by how far back: [0] is each workflow's nearest one, so the room goes to those first. Each is
319
- // its promote and its newest record together.
320
- const before = [];
321
- for (const workflow of new Set(items.map((one) => one.workflow))) {
322
- for (const one of replayingOf(items, workflow, null))
323
- keep.add(items.lastIndexOf(one));
324
- const passes = [NONE_REFUSED, refused];
325
- for (let pass = 0; pass < passes.length; pass++) {
326
- const skip = passes[pass];
327
- const own = (one) => one.workflow === workflow && !skip(one);
328
- const last = items.findLast((one) => own(one) && one.decided === "promote")?.digest;
329
- if (last === undefined)
330
- continue;
331
- const found = [items.findLastIndex((one) => own(one) && one.digest === last && one.decided === "promote"), items.findLastIndex((one) => own(one) && one.digest === last)];
332
- if (pass < 2)
333
- for (const i of found)
334
- keep.add(i);
335
- else
336
- (before[pass - 2] ??= []).push({ workflow, found });
337
- // The champions before the one `refused` leaves: a purge that lands between the write's ask of the gate and its
338
- // write refuses each one its run wrote, and the guard (the records read) never sees it, so its readers serve the
339
- // newest one before them. Past CHAMPIONS_KEPT, or past the room, it fails closed: none serves, never a purged
340
- // run's text.
341
- if (pass >= 1 && pass < CHAMPIONS_KEPT)
342
- passes.push((one) => skip(one) || (one.workflow === workflow && one.digest === last));
343
- }
344
- }
345
- const newest = (count) => {
346
- for (let i = items.length - 1; i >= 0 && count > 0; i--) {
347
- if (keep.has(i))
348
- continue;
349
- keep.add(i);
350
- count -= 1;
351
- }
352
- };
353
- newest(Math.max(keep.has(items.length - 1) ? 0 : 1, Math.min(RECENT_KEPT, PROMOTIONS_KEPT - keep.size)));
354
- // A champion before goes in whole or not at all: its promote kept without the hold after it would read as promoted, and
355
- // a revision held for its answers would serve again. One that does not fit cuts its workflow's chain there, so none
356
- // further back is kept past it (that one would serve in place of the nearer one). The newest records that fill the
357
- // rest never split one either: a promote they keep, they kept every record after it first.
358
- const cut = new Set();
359
- for (const { workflow, found } of before.flat()) {
360
- if (cut.has(workflow))
361
- continue;
362
- const missing = new Set(found.filter((i) => !keep.has(i)));
363
- if (keep.size + missing.size > PROMOTIONS_KEPT)
364
- cut.add(workflow);
365
- else
366
- for (const i of missing)
367
- keep.add(i);
368
- }
369
- newest(PROMOTIONS_KEPT - keep.size);
370
- return items.filter((_, i) => keep.has(i));
215
+ * (a connected agent's next turn, release or decision carries its turns on) never writes that run's text back. A record
216
+ * of a digest no version of its workflow holds (a run's purge took it since the record's check or reservation read it)
217
+ * writes nothing, not won, read in the same write (Store.learning changeRecords `held`), so no replay, hold or promote
218
+ * of a purged run's text lands; `anyDigest`, a failed draft's record (its digest is its run's, which no version holds),
219
+ * is the one exception, written as its run's (`runId`): its run's purge takes it. One transaction (Store.learning
220
+ * changeRecords), which also blanks a purged run's copies the record holds (forgetRunIn). */
221
+ export function recordPromotion(rows, agentId, record, still, options = {}) {
222
+ return rows.changeRecords(agentId, "promotion", (saved, held) => {
223
+ const kept0 = saved.filter((one) => DECIDED.includes(one.data?.decided));
224
+ const items = kept0.map((one) => one.data);
225
+ const now = promotionOf(items, record.workflow, record.digest);
226
+ if (!options.anyDigest && held !== undefined && !held(record.workflow, record.digest))
227
+ return { result: { record: now, won: false } };
228
+ if (!still(now, items))
229
+ return { result: { record: now, won: false } };
230
+ const kept = blankedRuns(now).reduce(forgetRunIn, record);
231
+ return { records: [...saved.map((one) => keptWrite(one)), promotionWrite(kept, options.runId ?? null)], result: { record: kept, won: true } };
232
+ }, options.anyDigest ? { anyDigest: record.digest } : undefined);
371
233
  }
372
234
  /** The text inside an answer that is one unlabelled fence and nothing else, or undefined. */
373
235
  const WHOLE_FENCE = /^ {0,3}(`{3,}|~{3,})[ \t]*\r?\n([\s\S]*?)\r?\n {0,3}\1[`~]*[ \t]*$/;
@@ -0,0 +1,18 @@
1
+ /** A learned workflow revision whose records were deleted, by an agent's learning reset (DELETE /agents/{id}/learning,
2
+ * learning-reset.ts) or by the purge of the run that wrote it while another run still carries its spend
3
+ * (learning-rows.ts dropRunLearning): its workflow, its digest and its K (its check's compile_after; null when its
4
+ * records named none), nothing else of its records. What the runs it served carry of its compile and check
5
+ * (learn/ledger.ts summarize, store-reads/learning.ts revisionsOf) is read from it after, so a kept run's cost reads as
6
+ * before. The runs keep the same names and digests. */
7
+ export interface ResetRevision {
8
+ readonly workflow: string;
9
+ readonly digest: string;
10
+ readonly k: number | null;
11
+ }
12
+ export declare const resetLedgerKey: (agentId: string) => string;
13
+ /** A revision's place in the ledger: its workflow and its digest (two workflows of the same text share a digest). */
14
+ export declare const resetRevisionKey: (one: Pick<ResetRevision, "workflow" | "digest">) => string;
15
+ /** The ledger `items` with the revisions `kept` (by resetRevisionKey) in: one it holds already keeps its place and takes
16
+ * the new K (while its records stood the ledger read theirs, so the runs' shares read the same after); a new one is
17
+ * added after, in `kept`'s order. */
18
+ export declare function withKept(items: readonly ResetRevision[], kept: ReadonlyMap<string, ResetRevision>): ResetRevision[];
@@ -0,0 +1,14 @@
1
+ // The agent's reset ledger (settings key `learning.reset-ledger.<agent>`): the learned workflow revisions whose promotion
2
+ // records were deleted while runs still carry their spend, each with the K those runs' shares are read at. A leaf
3
+ // module, so the store's learning rows (store/sqlite/learning-rows.ts) keep a purge's revisions in it, in the purge's own
4
+ // transaction, without importing promote.ts.
5
+ export const resetLedgerKey = (agentId) => `learning.reset-ledger.${agentId}`;
6
+ /** A revision's place in the ledger: its workflow and its digest (two workflows of the same text share a digest). */
7
+ export const resetRevisionKey = (one) => `${one.workflow}\0${one.digest}`;
8
+ /** The ledger `items` with the revisions `kept` (by resetRevisionKey) in: one it holds already keeps its place and takes
9
+ * the new K (while its records stood the ledger read theirs, so the runs' shares read the same after); a new one is
10
+ * added after, in `kept`'s order. */
11
+ export function withKept(items, kept) {
12
+ const held = new Set(items.map(resetRevisionKey));
13
+ return [...items.map((one) => kept.get(resetRevisionKey(one)) ?? one), ...[...kept].filter(([key]) => !held.has(key)).map(([, one]) => one)];
14
+ }