@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
@@ -0,0 +1,186 @@
1
+ import type { LearningAt, LearningSave, Store } from "../store/store.js";
2
+ /** A diff's file whose patch is larger than this is withheld as too large. */
3
+ export declare const PATCH_CAP: number;
4
+ /** The store's learning rows, as this module reads and writes them. */
5
+ export type LearningRows = Pick<Store["learning"], "seed" | "newest" | "itemsAt" | "saves" | "saveOf" | "versions" | "diff" | "save">;
6
+ /** One agent's learning: the rows and the agent. */
7
+ export type AgentLearning = {
8
+ readonly rows: LearningRows;
9
+ readonly agentId: string;
10
+ };
11
+ export declare const learningOf: (store: {
12
+ readonly learning: LearningRows;
13
+ }, agentId: string) => AgentLearning;
14
+ /** A file's ETag: git's blob id of its bytes (the sha1 of "blob <length>\0" and the bytes), kept from when the folder was
15
+ * git, so an ETag a client holds keeps its meaning. */
16
+ export declare const blobOid: (bytes: Uint8Array | string) => string;
17
+ /** The workflow a path is in, by name: `workflows/<name>/...`; else undefined. */
18
+ export declare function folderOf(path: string): string | undefined;
19
+ /** The merge key of a run's round: the run's id for its first, `<run>.r<round>` for each later one (a follow-up's
20
+ * look-back), so each round merges once. */
21
+ export declare const runDiffKey: (runId: string, round?: number) => string;
22
+ export type PersonKind = "approved" | "edited" | "created" | "retired" | "restored";
23
+ export type LastChange = {
24
+ kind: PersonKind | "learned";
25
+ by: "person" | "run";
26
+ at: string;
27
+ };
28
+ /** A workflow's history: when it last changed and how, its newest retire and its newest change by a person. */
29
+ export type ItemHistory = {
30
+ at: string;
31
+ last?: LastChange;
32
+ retire?: LastChange;
33
+ person?: LastChange;
34
+ };
35
+ export type ViewFile = {
36
+ path: string;
37
+ oid: string;
38
+ bytes: number;
39
+ };
40
+ /** A learned workflow as the view lists it: its README.md (`file`, `oid`, `bytes`), what it says (description, status,
41
+ * the status a retire recorded), the run whose text it is (`run`), its files and its history. */
42
+ export type LearnedItem = {
43
+ name: string;
44
+ file: string;
45
+ description: string;
46
+ status: "active" | "pending" | "retired";
47
+ retired_from?: "active" | "pending";
48
+ run: string | null;
49
+ files: ViewFile[];
50
+ oid: string;
51
+ bytes: number;
52
+ history: ItemHistory;
53
+ };
54
+ /** A save as the log shows it: its version id, when, who (a run, or a person and how), why and the paths it changed. */
55
+ export type LogChange = {
56
+ commit: string;
57
+ at: string;
58
+ by: {
59
+ run: string;
60
+ } | {
61
+ user: true;
62
+ via?: string;
63
+ };
64
+ reason: string;
65
+ files: string[];
66
+ };
67
+ /** The agent's learning at one save: its version id (`main`), corrections.md (absent: no line), its workflows. */
68
+ export type LearningView = {
69
+ main: string;
70
+ version: number;
71
+ at: string;
72
+ corrections?: ViewFile;
73
+ workflows: LearnedItem[];
74
+ };
75
+ /** What a reader is given: the view (undefined: the agent has no save yet) and each file's text by path. */
76
+ export type LearningRead = {
77
+ view: LearningView | undefined;
78
+ text: (path: string) => string | undefined;
79
+ };
80
+ /** What `at` holds, as a reader reads it. */
81
+ export declare function readOf(at: LearningAt | undefined): LearningRead;
82
+ /** `read` over the agent's learning at its newest save. */
83
+ export declare function readLearning<T>(learning: AgentLearning, read: (folder: LearningRead) => T | Promise<T>): Promise<T>;
84
+ /** The agent's learning at its newest save; undefined before its first. */
85
+ export declare const readView: (learning: AgentLearning) => Promise<LearningView | undefined>;
86
+ /** The agent's learning as save `id` left it, read now (a purged run's text gone from it); undefined when the agent's
87
+ * learning holds no such save. */
88
+ export declare function readAt(learning: AgentLearning, id: string): Promise<LearningRead | undefined>;
89
+ /** Whether the agent's learning holds save `id`. */
90
+ export declare const holdsSave: (learning: AgentLearning, id: string) => Promise<boolean>;
91
+ /** A save as the log shows it; undefined for the host's (an init, a purged run's). */
92
+ export declare function logChange(save: LearningSave): LogChange | undefined;
93
+ /** A page of the agent's log, newest first: at most `limit`, below version `before` when given. */
94
+ export declare function logOf(learning: AgentLearning, page: {
95
+ limit: number;
96
+ before?: number;
97
+ }): Promise<{
98
+ changes: {
99
+ change: LogChange;
100
+ version: number;
101
+ }[];
102
+ more: boolean;
103
+ total: number;
104
+ }>;
105
+ /** A run's merge: its version id, its parent's (null: none before it), and each file it changed with its patch. */
106
+ export type RunDiff = {
107
+ run: string;
108
+ merge: string;
109
+ parent: string | null;
110
+ files: {
111
+ path: string;
112
+ status: "added" | "modified" | "deleted";
113
+ patch: string;
114
+ }[];
115
+ };
116
+ /** The merge of the run's round `key` (runDiffKey), or undefined when it never merged, or its run was purged. */
117
+ export declare function runDiff(learning: AgentLearning, key: string): Promise<RunDiff | undefined>;
118
+ /** Run `runId`'s merge of `round` (runDiff), or undefined when it never merged. */
119
+ export declare const runMergeOf: (learning: AgentLearning, runId: string, round?: number) => Promise<RunDiff | undefined>;
120
+ /** `before` to `after` as git's unified diff writes a file's hunks (three lines of context, a hunk's count left out when
121
+ * it is one, the start the line before when it is none). Empty when they are the same. */
122
+ export declare function unifiedPatch(before: string, after: string): string;
123
+ /** A change to the agent's learning: what a person or a run's merge writes, as files (corrections.md, a workflow's
124
+ * `workflows/<name>/<file>`). `same`: paths that must be at the newest version as they are at another save (a run's
125
+ * seed, or the save a revision's text was read at). `seed`: a save the agent's learning must still hold (a run's seed:
126
+ * a reset removed it, and the whole merge is refused). */
127
+ export type LearningWrite = {
128
+ by: {
129
+ person: PersonKind;
130
+ file: string;
131
+ approved?: boolean;
132
+ } | {
133
+ run: string;
134
+ reason: string;
135
+ round?: number;
136
+ };
137
+ writes: readonly {
138
+ path: string;
139
+ text: string;
140
+ }[];
141
+ deletes?: readonly string[];
142
+ same?: readonly {
143
+ at: string;
144
+ path: string;
145
+ }[];
146
+ seed?: string;
147
+ /** The saves the write's text was read at (a run's seed, a revised workflow's base): refused whole when a run's purge
148
+ * came after one (Store.learning save's `readAt`). */
149
+ readAt?: readonly string[];
150
+ };
151
+ /** A write that kept moving under its compute, WRITE_TRIES times: routes answer 503. */
152
+ export declare class LearningBusy extends Error {
153
+ constructor();
154
+ }
155
+ /** A write's preconditions that failed at the newest version: nothing was written. */
156
+ export declare class LearningRefused extends Error {
157
+ readonly same: string[];
158
+ /** A run's merge whose seed the agent's learning no longer holds: its learning was reset. */
159
+ readonly seed: string | undefined;
160
+ /** A run's merge read at a save (`purged`, its id) that a run's purge came after: purged since its seed. */
161
+ readonly purged: string | undefined;
162
+ constructor(refused: {
163
+ same: string[];
164
+ seed?: string;
165
+ purged?: string;
166
+ });
167
+ }
168
+ /** A run's round that merged already (another call: a reclaimed run racing its first claim): its save. */
169
+ export declare class LearningMerged extends Error {
170
+ readonly save: LearningSave;
171
+ constructor(save: LearningSave);
172
+ }
173
+ /**
174
+ * A write to the agent's learning: `compute` reads it at its newest save and says what to write, or nothing (its result
175
+ * stands alone). Saved by compare and swap on that version; another write landing first computes it again on the newest
176
+ * (WRITE_TRIES in all, then LearningBusy). Throws LearningRefused when a precondition fails (a file changed since it was
177
+ * read, a seed a reset removed, a run's purge since a save it was read at), LearningMerged when a run's round merged
178
+ * already.
179
+ */
180
+ export declare function writeLearning<T>(learning: AgentLearning, compute: (folder: LearningRead) => Promise<{
181
+ result: T;
182
+ change?: LearningWrite;
183
+ }>, maxTries?: number): Promise<{
184
+ result: T;
185
+ saved?: LearningSave;
186
+ }>;
@@ -0,0 +1,376 @@
1
+ // An agent's learning as the routes, a run's seed and a run's merge read and write it, over the store's learning rows
2
+ // (store/sqlite/learning-rows.ts). The rows keep items: each line of the owner's corrections.md a note, each learned
3
+ // workflow's folder a workflow (its files whole, by path). This module turns them into what a person and a run see:
4
+ // corrections.md's text, each workflow's files and what its README.md says (LearningView), the log of saves, a run's
5
+ // merge as a patch (runDiff); and a write of files into item versions (writeLearning), computed on the agent's newest
6
+ // version and saved by compare and swap on it, computed again when another write landed first.
7
+ import { createHash } from "node:crypto";
8
+ import { CORRECTIONS_FILE } from "./corrections.js";
9
+ import { learnedFront, learnedStatus, retiredFrom, WORKFLOW_NAME, WORKFLOWS_DIR, workflowRunOf } from "./workflow-draft.js";
10
+ /** A diff's file whose patch is larger than this is withheld as too large. */
11
+ export const PATCH_CAP = 64 * 1024;
12
+ /** How many times a write is computed again on a newest version that moved under it. */
13
+ const WRITE_TRIES = 3;
14
+ export const learningOf = (store, agentId) => ({ rows: store.learning, agentId });
15
+ /** A file's ETag: git's blob id of its bytes (the sha1 of "blob <length>\0" and the bytes), kept from when the folder was
16
+ * git, so an ETag a client holds keeps its meaning. */
17
+ export const blobOid = (bytes) => {
18
+ const data = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : bytes;
19
+ return createHash("sha1").update(`blob ${data.length}\0`).update(data).digest("hex");
20
+ };
21
+ /** A workflow's digest: its workflow.json's (runner/workflow-first.ts workflowDigest), which its promotions name. */
22
+ const digestOf = (text) => createHash("sha256").update(text).digest("hex").slice(0, 16);
23
+ /** The workflow a path is in, by name: `workflows/<name>/...`; else undefined. */
24
+ export function folderOf(path) {
25
+ const [top, name, ...rest] = path.split("/");
26
+ return top === WORKFLOWS_DIR && name && rest.length ? name : undefined;
27
+ }
28
+ const keyFile = (name) => `${WORKFLOWS_DIR}/${name}/README.md`;
29
+ const viewFile = (name) => `${WORKFLOWS_DIR}/${name}/workflow.json`;
30
+ const byBytes = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
31
+ const iso = (ms) => new Date(ms).toISOString();
32
+ /** The merge key of a run's round: the run's id for its first, `<run>.r<round>` for each later one (a follow-up's
33
+ * look-back), so each round merges once. */
34
+ export const runDiffKey = (runId, round = 1) => (round > 1 ? `${runId}.r${round}` : runId);
35
+ const fileOf = (path, text) => ({ path, oid: blobOid(text), bytes: Buffer.byteLength(text, "utf8") });
36
+ const filesOf = (item) => (item.body === null ? {} : JSON.parse(item.body));
37
+ const notesOf = (at) => (at?.items ?? []).filter((item) => item.kind === "note").sort((a, b) => a.pos - b.pos || byBytes(a.name, b.name));
38
+ const correctionsText = (at) => {
39
+ const notes = notesOf(at);
40
+ return notes.length ? `${notes.map((note) => note.body ?? "").join("\n")}\n` : undefined;
41
+ };
42
+ /** corrections.md as its notes hold it: every line ends in a newline, the last one too, so no note is an empty line
43
+ * past the end (whose run's purge would change how the file ends). */
44
+ const asNotes = (text) => (text === "" || text.endsWith("\n") ? text : `${text}\n`);
45
+ /** A version's change as the history says it. */
46
+ const lastOf = (item) => ({ kind: item.change, by: item.person ? "person" : "run", at: iso(item.at) });
47
+ /** What `at` holds, as a reader reads it. */
48
+ export function readOf(at) {
49
+ if (!at)
50
+ return { view: undefined, text: () => undefined };
51
+ const texts = new Map();
52
+ const corrections = correctionsText(at);
53
+ if (corrections !== undefined)
54
+ texts.set(CORRECTIONS_FILE, corrections);
55
+ const workflows = [];
56
+ for (const item of at.items) {
57
+ if (item.kind !== "workflow" || !WORKFLOW_NAME.test(item.name))
58
+ continue;
59
+ const files = filesOf(item);
60
+ for (const [path, text] of Object.entries(files))
61
+ texts.set(path, text);
62
+ const readme = files[keyFile(item.name)];
63
+ if (readme === undefined || files[viewFile(item.name)] === undefined)
64
+ continue;
65
+ const versions = at.history.filter((one) => one.kind === "workflow" && one.name === item.name).sort((a, b) => a.version - b.version);
66
+ const newest = versions.at(-1) ?? item;
67
+ const retire = versions.findLast((one) => one.change === "retired" && one.person);
68
+ const person = versions.findLast((one) => one.person);
69
+ const status = learnedStatus(readme);
70
+ workflows.push({
71
+ name: item.name, file: keyFile(item.name), description: learnedFront(readme)?.description ?? "", status,
72
+ ...(status === "retired" ? { retired_from: retiredFrom(readme) } : {}),
73
+ run: item.byRun,
74
+ files: Object.entries(files).map(([path, text]) => fileOf(path, text)).sort((a, b) => byBytes(a.path, b.path)),
75
+ ...(({ oid, bytes }) => ({ oid, bytes }))(fileOf(keyFile(item.name), readme)),
76
+ history: { at: iso(newest.at), last: lastOf(newest), ...(retire ? { retire: lastOf(retire) } : {}), ...(person ? { person: lastOf(person) } : {}) },
77
+ });
78
+ }
79
+ const view = {
80
+ main: at.save.id, version: at.save.version, at: iso(at.save.at),
81
+ ...(corrections !== undefined ? { corrections: fileOf(CORRECTIONS_FILE, corrections) } : {}),
82
+ workflows: workflows.sort((a, b) => byBytes(a.name, b.name)),
83
+ };
84
+ return { view, text: (path) => texts.get(path) };
85
+ }
86
+ /** `read` over the agent's learning at its newest save. */
87
+ export async function readLearning(learning, read) {
88
+ return read(readOf(await learning.rows.newest(learning.agentId)));
89
+ }
90
+ /** The agent's learning at its newest save; undefined before its first. */
91
+ export const readView = async (learning) => readOf(await learning.rows.newest(learning.agentId)).view;
92
+ /** The agent's learning as save `id` left it, read now (a purged run's text gone from it); undefined when the agent's
93
+ * learning holds no such save. */
94
+ export async function readAt(learning, id) {
95
+ const at = await learning.rows.itemsAt(learning.agentId, id);
96
+ return at ? readOf(at) : undefined;
97
+ }
98
+ /** Whether the agent's learning holds save `id`. */
99
+ export const holdsSave = async (learning, id) => (await learning.rows.saveOf(learning.agentId, { id })) !== undefined;
100
+ /** A save as the log shows it; undefined for the host's (an init, a purged run's). */
101
+ export function logChange(save) {
102
+ if ("host" in save.by)
103
+ return undefined;
104
+ const by = "run" in save.by ? { run: save.by.run } : { user: true, ...(save.by.approved ? { via: "console" } : {}) };
105
+ return { commit: save.id, at: iso(save.at), by, reason: save.reason, files: [...save.files] };
106
+ }
107
+ /** A page of the agent's log, newest first: at most `limit`, below version `before` when given. */
108
+ export async function logOf(learning, page) {
109
+ const { saves, more, total } = await learning.rows.saves(learning.agentId, page);
110
+ return { changes: saves.flatMap((save) => { const change = logChange(save); return change ? [{ change, version: save.version }] : []; }), more, total };
111
+ }
112
+ /** The merge of the run's round `key` (runDiffKey), or undefined when it never merged, or its run was purged. */
113
+ export async function runDiff(learning, key) {
114
+ const save = await learning.rows.saveOf(learning.agentId, { mergeKey: key });
115
+ if (!save || "host" in save.by)
116
+ return undefined;
117
+ const diff = await learning.rows.diff(learning.agentId, save.id);
118
+ if (!diff)
119
+ return undefined;
120
+ const files = [];
121
+ const add = (path, before, after) => {
122
+ if (before === after)
123
+ return;
124
+ files.push({ path, status: before === undefined ? "added" : after === undefined ? "deleted" : "modified", patch: unifiedPatch(before ?? "", after ?? "") });
125
+ };
126
+ for (const item of diff.items) {
127
+ if (item.kind !== "workflow")
128
+ continue;
129
+ const [before, after] = [filesOf({ body: item.before }), filesOf({ body: item.after })];
130
+ for (const path of [...new Set([...Object.keys(before), ...Object.keys(after)])].sort(byBytes))
131
+ add(path, before[path], after[path]);
132
+ }
133
+ if (diff.items.some((item) => item.kind === "note")) {
134
+ const [before, after] = await Promise.all([diff.parent ? learning.rows.itemsAt(learning.agentId, diff.parent.id) : undefined, learning.rows.itemsAt(learning.agentId, save.id)]);
135
+ add(CORRECTIONS_FILE, correctionsText(before), correctionsText(after));
136
+ }
137
+ return { run: key, merge: save.id, parent: diff.parent?.id ?? null, files: files.sort((a, b) => byBytes(a.path, b.path)) };
138
+ }
139
+ /** Run `runId`'s merge of `round` (runDiff), or undefined when it never merged. */
140
+ export const runMergeOf = (learning, runId, round = 1) => runDiff(learning, runDiffKey(runId, round));
141
+ /** Lines of `text`, the last one marked when the text does not end in a newline (git's ""). */
142
+ function linesOf(text) {
143
+ if (text === "")
144
+ return [];
145
+ const lines = text.split("\n");
146
+ if (text.endsWith("\n"))
147
+ lines.pop();
148
+ else
149
+ lines[lines.length - 1] = `${lines.at(-1)}\0`;
150
+ return lines;
151
+ }
152
+ const NO_NEWLINE = "\\n";
153
+ const lineOut = (mark, line) => (line.endsWith("\0") ? `${mark}${line.slice(0, -1)}\n${NO_NEWLINE}` : `${mark}${line}\n`);
154
+ /** `before` to `after` as git's unified diff writes a file's hunks (three lines of context, a hunk's count left out when
155
+ * it is one, the start the line before when it is none). Empty when they are the same. */
156
+ export function unifiedPatch(before, after) {
157
+ const a = linesOf(before);
158
+ const b = linesOf(after);
159
+ const ops = [];
160
+ if (a.length * b.length <= 4_000_000) {
161
+ const width = b.length + 1;
162
+ const lcs = new Uint32Array((a.length + 1) * width);
163
+ for (let i = a.length - 1; i >= 0; i--)
164
+ for (let j = b.length - 1; j >= 0; j--)
165
+ lcs[i * width + j] = a[i] === b[j] ? lcs[(i + 1) * width + j + 1] + 1 : Math.max(lcs[(i + 1) * width + j], lcs[i * width + j + 1]);
166
+ let [i, j] = [0, 0];
167
+ while (i < a.length || j < b.length) {
168
+ if (i < a.length && j < b.length && a[i] === b[j])
169
+ ops.push({ op: " ", line: a[i], ai: i++, bi: j++ });
170
+ else if (j < b.length && (i >= a.length || lcs[i * width + j + 1] >= lcs[(i + 1) * width + j]))
171
+ ops.push({ op: "+", line: b[j], ai: i, bi: j++ });
172
+ else
173
+ ops.push({ op: "-", line: a[i], ai: i++, bi: j });
174
+ }
175
+ }
176
+ else {
177
+ a.forEach((line, i) => ops.push({ op: "-", line, ai: i, bi: 0 }));
178
+ b.forEach((line, j) => ops.push({ op: "+", line, ai: a.length, bi: j }));
179
+ }
180
+ const CONTEXT = 3;
181
+ const changed = ops.flatMap((one, k) => (one.op === " " ? [] : [k]));
182
+ let out = "";
183
+ for (let c = 0; c < changed.length;) {
184
+ // A hunk: CONTEXT lines around each change, changes closer than 2 * CONTEXT lines of context in one.
185
+ let last = c;
186
+ while (last + 1 < changed.length && changed[last + 1] - changed[last] <= 2 * CONTEXT + 1)
187
+ last++;
188
+ const hunk = ops.slice(Math.max(0, changed[c] - CONTEXT), Math.min(ops.length, changed[last] + CONTEXT + 1));
189
+ const olds = hunk.filter((one) => one.op !== "+").length;
190
+ const news = hunk.filter((one) => one.op !== "-").length;
191
+ const range = (from, count) => (count === 1 ? `${from + 1}` : `${count ? from + 1 : from},${count}`);
192
+ out += `@@ -${range(hunk[0].ai, olds)} +${range(hunk[0].bi, news)} @@\n`;
193
+ for (const one of hunk)
194
+ out += lineOut(one.op, one.line);
195
+ c = last + 1;
196
+ }
197
+ return out;
198
+ }
199
+ /** A write that kept moving under its compute, WRITE_TRIES times: routes answer 503. */
200
+ export class LearningBusy extends Error {
201
+ constructor() {
202
+ super("the agent's learning kept changing under this write: try again");
203
+ this.name = "LearningBusy";
204
+ }
205
+ }
206
+ /** A write's preconditions that failed at the newest version: nothing was written. */
207
+ export class LearningRefused extends Error {
208
+ same;
209
+ /** A run's merge whose seed the agent's learning no longer holds: its learning was reset. */
210
+ seed;
211
+ /** A run's merge read at a save (`purged`, its id) that a run's purge came after: purged since its seed. */
212
+ purged;
213
+ constructor(refused) {
214
+ super(`the agent's learning refused the write: ${[...(refused.seed !== undefined ? [`the run's seed ${refused.seed} is not held`] : []), ...(refused.purged !== undefined ? [`a run's purge came after save ${refused.purged}, which it was read at`] : []), ...refused.same.map((path) => `${path} changed`)].join(", ")}`);
215
+ this.name = "LearningRefused";
216
+ this.same = refused.same;
217
+ this.seed = refused.seed;
218
+ this.purged = refused.purged;
219
+ }
220
+ }
221
+ /** A run's round that merged already (another call: a reclaimed run racing its first claim): its save. */
222
+ export class LearningMerged extends Error {
223
+ save;
224
+ constructor(save) {
225
+ super(`the run merged already, at ${save.id}`);
226
+ this.name = "LearningMerged";
227
+ this.save = save;
228
+ }
229
+ }
230
+ /** The item versions `change` writes on `at` (version `version` once saved), and the paths whose text it changes. */
231
+ function itemsFor(at, read, change, version) {
232
+ const run = "run" in change.by ? change.by.run : undefined;
233
+ const kind = "run" in change.by ? "learned" : change.by.person;
234
+ const person = run === undefined;
235
+ const writes = new Map(change.writes.map(({ path, text }) => [path, text]));
236
+ const deletes = new Set(change.deletes ?? []);
237
+ const items = [];
238
+ const files = [];
239
+ for (const path of [...writes.keys(), ...deletes]) {
240
+ if (path !== CORRECTIONS_FILE && folderOf(path) === undefined)
241
+ throw new Error(`${path} is no learning file: corrections.md or a workflow's workflows/<name>/<file>`);
242
+ }
243
+ // corrections.md: one note a line, matched to the lines there by their longest common run; a line kept keeps its
244
+ // item (moved when its place changed). A line the run left out whose words an old note left out also holds is that
245
+ // note moved, matched one to one in order (a reorder moves a line outside the longest run): it keeps its writer, so
246
+ // its run's purge still takes it. Only words no such note holds are a new item; a note left unmatched is ended.
247
+ if (writes.has(CORRECTIONS_FILE) || deletes.has(CORRECTIONS_FILE)) {
248
+ const text = asNotes(writes.get(CORRECTIONS_FILE) ?? "");
249
+ if (text !== (read.text(CORRECTIONS_FILE) ?? ""))
250
+ files.push(CORRECTIONS_FILE);
251
+ const old = notesOf(at);
252
+ const lines = text === "" ? [] : text.slice(0, -1).split("\n");
253
+ const width = lines.length + 1;
254
+ const lcs = new Uint32Array((old.length + 1) * width);
255
+ for (let i = old.length - 1; i >= 0; i--)
256
+ for (let j = lines.length - 1; j >= 0; j--)
257
+ lcs[i * width + j] = old[i].body === lines[j] ? lcs[(i + 1) * width + j + 1] + 1 : Math.max(lcs[(i + 1) * width + j], lcs[i * width + j + 1]);
258
+ // Each line's old note (undefined: none in the longest run), and the old notes the longest run left out.
259
+ const kept = lines.map(() => undefined);
260
+ const left = [];
261
+ let [i, j] = [0, 0];
262
+ while (i < old.length || j < lines.length) {
263
+ if (i < old.length && j < lines.length && old[i].body === lines[j])
264
+ kept[j++] = old[i++];
265
+ else if (j < lines.length && (i >= old.length || lcs[i * width + j + 1] >= lcs[(i + 1) * width + j]))
266
+ j++;
267
+ else
268
+ left.push(old[i++]);
269
+ }
270
+ // A line outside the longest run takes the first old note left out with its words, in order.
271
+ const leftBy = new Map();
272
+ for (const note of left)
273
+ leftBy.set(note.body ?? "", [...(leftBy.get(note.body ?? "") ?? []), note]);
274
+ lines.forEach((line, pos) => { kept[pos] ??= leftBy.get(line)?.shift(); });
275
+ const moved = new Set(kept);
276
+ lines.forEach((line, pos) => {
277
+ const note = kept[pos];
278
+ if (!note)
279
+ items.push({ kind: "note", name: `${version}.${pos}`, body: line, byRun: run ?? null, change: kind, person, pos, digest: null, writers: null });
280
+ else if (note.pos !== pos)
281
+ items.push({ kind: "note", name: note.name, body: note.body, byRun: note.byRun, change: note.change, person: note.person, pos, digest: null, writers: null });
282
+ });
283
+ for (const note of left)
284
+ if (!moved.has(note))
285
+ items.push({ kind: "note", name: note.name, body: null, byRun: note.byRun, change: kind, person, pos: note.pos, digest: null, writers: null });
286
+ }
287
+ // Each workflow touched: a run's merge writes it whole (its folder is the files the run gives); a person's change keeps
288
+ // its files as they are, with the writes and deletes in its folder. Gone when none is left. Each file keeps its writer
289
+ // (LearningItem.writers): the run whose merge changed it to its text. A file given as it is (a run's merge that copies
290
+ // it unchanged), and a person's edit of a file, keep the writer before; a run's change of it is the run's; a person's
291
+ // new file is no run's. So a purge takes back only the files the run wrote, each to its text before.
292
+ const names = new Set([...writes.keys(), ...deletes].map(folderOf).filter((name) => name !== undefined));
293
+ for (const name of [...names].sort(byBytes)) {
294
+ const now = at?.items.find((item) => item.kind === "workflow" && item.name === name);
295
+ const files0 = now ? filesOf(now) : {};
296
+ const next = run === undefined ? { ...files0 } : {};
297
+ for (const path of Object.keys(next))
298
+ if (folderOf(path) === name && deletes.has(path))
299
+ delete next[path];
300
+ for (const [path, text] of writes)
301
+ if (folderOf(path) === name)
302
+ next[path] = text;
303
+ const paths = [...new Set([...Object.keys(files0), ...Object.keys(next)])].sort(byBytes);
304
+ const changed = paths.filter((path) => files0[path] !== next[path]);
305
+ if (!changed.length)
306
+ continue;
307
+ files.push(...changed);
308
+ const kept = Object.keys(next).sort(byBytes);
309
+ const json = next[viewFile(name)];
310
+ const before = now?.writers ?? {};
311
+ const writerOf = (path) => {
312
+ const was = Object.hasOwn(files0, path) ? (before[path] ?? null) : null;
313
+ if (Object.hasOwn(files0, path) && files0[path] === next[path])
314
+ return was;
315
+ return run ?? was;
316
+ };
317
+ const writers = Object.fromEntries(kept.map((path) => [path, writerOf(path)]));
318
+ items.push({
319
+ kind: "workflow", name, body: kept.length ? JSON.stringify(Object.fromEntries(kept.map((path) => [path, next[path]]))) : null,
320
+ // The workflow's run is its workflow.json's writer (what its promotions are of); its README.md's when it has none.
321
+ byRun: workflowRunOf(name, writers), change: kind, person, pos: 0, digest: json === undefined ? null : digestOf(json),
322
+ writers: kept.length ? writers : null,
323
+ });
324
+ }
325
+ return { items, files: files.sort(byBytes) };
326
+ }
327
+ /**
328
+ * A write to the agent's learning: `compute` reads it at its newest save and says what to write, or nothing (its result
329
+ * stands alone). Saved by compare and swap on that version; another write landing first computes it again on the newest
330
+ * (WRITE_TRIES in all, then LearningBusy). Throws LearningRefused when a precondition fails (a file changed since it was
331
+ * read, a seed a reset removed, a run's purge since a save it was read at), LearningMerged when a run's round merged
332
+ * already.
333
+ */
334
+ export async function writeLearning(learning, compute, maxTries = WRITE_TRIES) {
335
+ const { rows, agentId } = learning;
336
+ for (let tries = 0; tries < maxTries; tries++) {
337
+ const at = await rows.newest(agentId);
338
+ const read = readOf(at);
339
+ const out = await compute(read);
340
+ if (!out.change)
341
+ return { result: out.result };
342
+ const change = out.change;
343
+ // A seed the agent's learning no longer holds (a reset since) refuses the whole write as that, before any file is
344
+ // compared with what it held.
345
+ if (change.seed !== undefined && change.seed !== at?.save.id && !(await rows.saveOf(agentId, { id: change.seed })))
346
+ throw new LearningRefused({ same: [], seed: change.seed });
347
+ const same = [];
348
+ for (const { at: then, path } of change.same ?? []) {
349
+ const was = then === at?.save.id ? read : await readAt(learning, then);
350
+ if (!was || was.text(path) !== read.text(path))
351
+ same.push(path);
352
+ }
353
+ if (same.length)
354
+ throw new LearningRefused({ same });
355
+ const base = at?.save.version ?? 0;
356
+ const { items, files } = itemsFor(at, read, change, base + 1);
357
+ const by = change.by;
358
+ const done = await rows.save(agentId, {
359
+ base, files, items,
360
+ by: "run" in by ? { run: by.run, ...(by.round !== undefined && by.round > 1 ? { round: by.round } : {}) } : { person: by.person, file: by.file, ...(by.approved ? { approved: true } : {}) },
361
+ reason: "run" in by ? by.reason : `${by.person} by a person: ${by.file}`,
362
+ ...("run" in by ? { mergeKey: runDiffKey(by.run, by.round) } : {}),
363
+ ...(change.seed !== undefined ? { seed: change.seed } : {}),
364
+ ...(change.readAt?.length ? { readAt: change.readAt } : {}),
365
+ });
366
+ if ("saved" in done)
367
+ return { result: out.result, saved: done.saved };
368
+ if ("already" in done)
369
+ throw new LearningMerged(done.already);
370
+ if ("refused" in done)
371
+ throw new LearningRefused({ same: [], seed: done.refused.seed });
372
+ if ("purged" in done)
373
+ throw new LearningRefused({ same: [], purged: done.purged.readAt });
374
+ }
375
+ throw new LearningBusy();
376
+ }
@@ -64,6 +64,7 @@ export declare function excerptShown(text: string, shown: {
64
64
  /** A matcher for `values` in a text: plain, split by whitespace, as JSON writes it, percent or form encoded, base64 or
65
65
  * hex, and each hex identifier in a value folded: in any case, its separators dropped or moved (foldedOf). Values
66
66
  * shorter than MIN_SECRET are left out. `fold: false`, the matcher without the folded needles. */
67
- export declare function valueMatcher(values: readonly string[], { fold }?: {
67
+ export declare function valueMatcher(values: readonly string[], { fold, separated }?: {
68
68
  fold?: boolean;
69
+ separated?: boolean;
69
70
  }): (text: string) => boolean;
@@ -305,7 +305,7 @@ function heldFields(value) {
305
305
  /** A matcher for `values` in a text: plain, split by whitespace, as JSON writes it, percent or form encoded, base64 or
306
306
  * hex, and each hex identifier in a value folded: in any case, its separators dropped or moved (foldedOf). Values
307
307
  * shorter than MIN_SECRET are left out. `fold: false`, the matcher without the folded needles. */
308
- export function valueMatcher(values, { fold = true } = {}) {
308
+ export function valueMatcher(values, { fold = true, separated = false } = {}) {
309
309
  const needles = derivedOf(values);
310
- return (text) => holds(text, needles, { fold });
310
+ return (text) => holds(text, needles, { fold, separated });
311
311
  }
@@ -3,6 +3,9 @@ import type { assertWorkflowCapabilities, desugarWorkflow, dryRunWorkflow, inspe
3
3
  export declare const WORKFLOWS_DIR = "workflows";
4
4
  /** A workflow's name: lowercase letters, digits, dashes and underscores, at most 64, starting with a letter or digit. */
5
5
  export declare const WORKFLOW_NAME: RegExp;
6
+ /** A learned workflow's run (Store LearningItem.byRun) from its files' writers (LearningItem.writers): its
7
+ * workflow.json's (what its promotions are of), else its README.md's, else none. */
8
+ export declare function workflowRunOf(name: string, writers: Readonly<Record<string, string | null>>): string | null;
6
9
  /** A workflow's `workflow.json` or its `README.md`, by the folder it names. */
7
10
  export type LearnedPlace = {
8
11
  readonly kind: "workflow" | "readme";
@@ -109,7 +112,7 @@ export declare const readmeOf: (name: string, description: string) => string;
109
112
  * README with no description, which the checker refuses; what the JSON holds is the checker's to judge. `example`, its
110
113
  * `example:` front matter line as written (the run's own input to the workflow, one JSON object): what its dry run runs
111
114
  * on (draftDryRun), and never a file's: the README holds its name and description alone, so the run's input, which can
112
- * be a customer's data, is never kept in the learning folder. */
115
+ * be a customer's data, is never kept in the learning. */
113
116
  export declare function draftFiles(name: string, block: string): {
114
117
  json: string;
115
118
  readme: string;
@@ -1,4 +1,4 @@
1
- // A learned workflow draft: `workflows/<name>/workflow.json` with its `README.md`, their place in the learning folder, the
1
+ // A learned workflow draft: `workflows/<name>/workflow.json` with its `README.md`, their place in the learning, the
2
2
  // shape each file must have, and what its dry run reads. check.ts checks a draft; nothing here reads a file, runs a draft
3
3
  // or calls a model.
4
4
  import { mcpNameOf } from "../tool-names.js";
@@ -7,6 +7,16 @@ import { repeatedLabels, workflowNodes } from "./workflow-nodes.js";
7
7
  export const WORKFLOWS_DIR = "workflows";
8
8
  /** A workflow's name: lowercase letters, digits, dashes and underscores, at most 64, starting with a letter or digit. */
9
9
  export const WORKFLOW_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
10
+ /** A learned workflow's run (Store LearningItem.byRun) from its files' writers (LearningItem.writers): its
11
+ * workflow.json's (what its promotions are of), else its README.md's, else none. */
12
+ export function workflowRunOf(name, writers) {
13
+ for (const file of ["workflow.json", "README.md"]) {
14
+ const path = `${WORKFLOWS_DIR}/${name}/${file}`;
15
+ if (Object.hasOwn(writers, path))
16
+ return writers[path] ?? null;
17
+ }
18
+ return null;
19
+ }
10
20
  const PLACES = [
11
21
  [/^workflows\/([^/]+)\/workflow\.json$/, "workflow"],
12
22
  [/^workflows\/([^/]+)\/README\.md$/, "readme"],
@@ -388,7 +398,7 @@ function frontLine(key, value) {
388
398
  * README with no description, which the checker refuses; what the JSON holds is the checker's to judge. `example`, its
389
399
  * `example:` front matter line as written (the run's own input to the workflow, one JSON object): what its dry run runs
390
400
  * on (draftDryRun), and never a file's: the README holds its name and description alone, so the run's input, which can
391
- * be a customer's data, is never kept in the learning folder. */
401
+ * be a customer's data, is never kept in the learning. */
392
402
  export function draftFiles(name, block) {
393
403
  const front = frontOf(block);
394
404
  if (typeof front === "string")