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

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 (194) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +188 -106
  3. package/dist/agent-delete.d.ts +6 -9
  4. package/dist/agent-delete.js +5 -3
  5. package/dist/agent-package.js +11 -1
  6. package/dist/api-only.d.ts +2 -2
  7. package/dist/api-only.js +3 -3
  8. package/dist/archil-routes.d.ts +4 -1
  9. package/dist/archil-routes.js +15 -12
  10. package/dist/archil-settings.d.ts +18 -8
  11. package/dist/archil-settings.js +35 -17
  12. package/dist/chatgpt-plan.d.ts +4 -2
  13. package/dist/chatgpt-plan.js +13 -3
  14. package/dist/claude-login-token.d.ts +5 -0
  15. package/dist/claude-login-token.js +8 -0
  16. package/dist/claude-login.d.ts +49 -3
  17. package/dist/claude-login.js +140 -10
  18. package/dist/cli-learning/connections.js +1 -1
  19. package/dist/console/assets/{backend-BztxEAvb.js → backend-QnwGVBeU.js} +1 -1
  20. package/dist/console/assets/index-DZi-muIj.js +629 -0
  21. package/dist/console/assets/{share-L84tlUDW.js → share-pz61zIn9.js} +2 -2
  22. package/dist/console/assets/{styles-CaRKlHke.js → styles-CcceGcu2.js} +31 -31
  23. package/dist/console/assets/styles-fjQBFfMv.css +1 -0
  24. package/dist/console/index.html +3 -3
  25. package/dist/console/share.html +3 -3
  26. package/dist/decisions.d.ts +1 -1
  27. package/dist/decisions.js +2 -2
  28. package/dist/factory-activity.d.ts +68 -0
  29. package/dist/factory-activity.js +153 -0
  30. package/dist/factory-runs.d.ts +11 -0
  31. package/dist/factory-runs.js +52 -0
  32. package/dist/filed-tool.d.ts +32 -0
  33. package/dist/filed-tool.js +122 -0
  34. package/dist/harness-keys.d.ts +1 -2
  35. package/dist/harness-keys.js +1 -2
  36. package/dist/harness-table.d.ts +4 -0
  37. package/dist/harness-table.js +4 -0
  38. package/dist/harness.js +6 -2
  39. package/dist/import-worker.js +2 -2
  40. package/dist/import.d.ts +9 -0
  41. package/dist/import.js +11 -1
  42. package/dist/key-refusal.d.ts +5 -0
  43. package/dist/key-refusal.js +25 -15
  44. package/dist/learn/audit.d.ts +20 -22
  45. package/dist/learn/audit.js +72 -55
  46. package/dist/learn/check.js +1 -1
  47. package/dist/learn/commit.d.ts +35 -43
  48. package/dist/learn/commit.js +62 -270
  49. package/dist/learn/compile.d.ts +4 -4
  50. package/dist/learn/compile.js +6 -7
  51. package/dist/learn/corrections.js +1 -1
  52. package/dist/learn/delete.d.ts +5 -12
  53. package/dist/learn/delete.js +17 -30
  54. package/dist/learn/forget-run.d.ts +16 -0
  55. package/dist/learn/forget-run.js +53 -0
  56. package/dist/learn/index.js +1 -1
  57. package/dist/learn/learning-of.d.ts +0 -4
  58. package/dist/learn/learning-of.js +0 -5
  59. package/dist/learn/{folder.d.ts → legacy/folder.d.ts} +2 -1
  60. package/dist/learn/{folder.js → legacy/folder.js} +4 -7
  61. package/dist/learn/legacy/place.d.ts +16 -0
  62. package/dist/{workspace/learning-workspace.js → learn/legacy/place.js} +12 -42
  63. package/dist/learn/legacy/scrub.d.ts +28 -0
  64. package/dist/learn/legacy/scrub.js +258 -0
  65. package/dist/learn/promote.d.ts +40 -66
  66. package/dist/learn/promote.js +69 -207
  67. package/dist/learn/reset-ledger.d.ts +18 -0
  68. package/dist/learn/reset-ledger.js +14 -0
  69. package/dist/learn/rows.d.ts +186 -0
  70. package/dist/learn/rows.js +376 -0
  71. package/dist/learn/workflow-draft.d.ts +4 -1
  72. package/dist/learn/workflow-draft.js +12 -2
  73. package/dist/learning-reset.d.ts +1 -1
  74. package/dist/learning-reset.js +9 -11
  75. package/dist/learning-routes.d.ts +60 -81
  76. package/dist/learning-routes.js +187 -360
  77. package/dist/learning-words.d.ts +2 -0
  78. package/dist/learning-words.js +2 -0
  79. package/dist/learning.d.ts +18 -24
  80. package/dist/learning.js +35 -66
  81. package/dist/mcp-gateway.d.ts +6 -0
  82. package/dist/mcp-gateway.js +44 -8
  83. package/dist/mcp-resources.d.ts +1 -1
  84. package/dist/native/discovery.d.ts +6 -0
  85. package/dist/native/discovery.js +14 -1
  86. package/dist/native/remote.d.ts +5 -0
  87. package/dist/native/remote.js +16 -0
  88. package/dist/native/runtime.js +3 -2
  89. package/dist/observation/observer.d.ts +6 -6
  90. package/dist/openapi.js +89 -29
  91. package/dist/place-offers.d.ts +3 -0
  92. package/dist/place-offers.js +3 -0
  93. package/dist/place.d.ts +33 -11
  94. package/dist/place.js +61 -26
  95. package/dist/purged-workflow.d.ts +0 -33
  96. package/dist/purged-workflow.js +3 -71
  97. package/dist/redact/match.d.ts +19 -4
  98. package/dist/redact/match.js +123 -30
  99. package/dist/run-launch.d.ts +3 -3
  100. package/dist/run-learning-served.d.ts +3 -3
  101. package/dist/run-learning-served.js +1 -1
  102. package/dist/run-listing.d.ts +1 -1
  103. package/dist/run-timeline-served.d.ts +1 -1
  104. package/dist/run-timeline-served.js +6 -5
  105. package/dist/runnable.js +25 -8
  106. package/dist/runner/adapter-run-spec.js +11 -20
  107. package/dist/runner/audit.d.ts +2 -4
  108. package/dist/runner/audit.js +28 -51
  109. package/dist/runner/cli-run-spec.js +8 -14
  110. package/dist/runner/compare-end.d.ts +0 -2
  111. package/dist/runner/compare-end.js +6 -2
  112. package/dist/runner/disk-free.d.ts +15 -4
  113. package/dist/runner/disk-free.js +25 -7
  114. package/dist/runner/feedback-round.d.ts +1 -1
  115. package/dist/runner/feedback-round.js +2 -2
  116. package/dist/runner/harness-loops.js +2 -3
  117. package/dist/runner/held.d.ts +0 -10
  118. package/dist/runner/held.js +0 -25
  119. package/dist/runner/journal-kinds.d.ts +4 -1
  120. package/dist/runner/journal-kinds.js +1 -1
  121. package/dist/runner/learned-first.d.ts +0 -2
  122. package/dist/runner/learned-first.js +3 -3
  123. package/dist/runner/learning-end.d.ts +12 -16
  124. package/dist/runner/learning-end.js +41 -75
  125. package/dist/runner/learning-seed.d.ts +13 -16
  126. package/dist/runner/learning-seed.js +13 -23
  127. package/dist/runner/main.js +1 -1
  128. package/dist/runner/mcp-run.d.ts +4 -0
  129. package/dist/runner/mcp-run.js +2 -0
  130. package/dist/runner/native-loop.js +2 -3
  131. package/dist/runner/promotion.d.ts +19 -28
  132. package/dist/runner/promotion.js +50 -69
  133. package/dist/runner/reflect-hook.d.ts +2 -2
  134. package/dist/runner/reflect-hook.js +4 -1
  135. package/dist/runner/run-child-host.d.ts +1 -9
  136. package/dist/runner/run-child-host.js +11 -67
  137. package/dist/runner/runner.d.ts +1 -1
  138. package/dist/runner/sdk-loop.js +2 -4
  139. package/dist/sdk/check.d.ts +1 -4
  140. package/dist/sdk/check.js +2 -3
  141. package/dist/sdk/runs.d.ts +20 -7
  142. package/dist/sdk/runs.js +105 -68
  143. package/dist/secrets.d.ts +4 -0
  144. package/dist/secrets.js +44 -10
  145. package/dist/server-fs.d.ts +1 -1
  146. package/dist/server-fs.js +1 -1
  147. package/dist/server-keys.d.ts +6 -0
  148. package/dist/server-keys.js +12 -0
  149. package/dist/server.d.ts +15 -15
  150. package/dist/server.js +214 -164
  151. package/dist/source-sync/auxiliary.js +2 -2
  152. package/dist/store/index.d.ts +1 -1
  153. package/dist/store/index.js +1 -1
  154. package/dist/store/postgres/migrations/0032_learning_rows.sql +65 -0
  155. package/dist/store/schema.d.ts +28 -2
  156. package/dist/store/schema.js +81 -5
  157. package/dist/store/sqlite/learning-rows.d.ts +23 -0
  158. package/dist/store/sqlite/learning-rows.js +559 -0
  159. package/dist/store/sqlite/store.d.ts +7 -1
  160. package/dist/store/sqlite/store.js +84 -18
  161. package/dist/store/store.d.ts +219 -6
  162. package/dist/store/store.js +13 -0
  163. package/dist/store-reads/journal.d.ts +33 -3
  164. package/dist/store-reads/journal.js +99 -4
  165. package/dist/store-reads/learning.d.ts +18 -22
  166. package/dist/store-reads/learning.js +35 -26
  167. package/dist/store-reads/loop.js +1 -1
  168. package/dist/store-view.d.ts +24 -2
  169. package/dist/store-view.js +40 -11
  170. package/dist/templates.d.ts +10 -2
  171. package/dist/templates.js +31 -4
  172. package/dist/tool-plane.d.ts +4 -2
  173. package/dist/tool-plane.js +9 -2
  174. package/dist/web-holds.d.ts +2 -0
  175. package/dist/web-holds.js +5 -2
  176. package/dist/web-run.js +2 -1
  177. package/dist/workspace/archil-exec.js +1 -1
  178. package/dist/workspace/archil.d.ts +1 -1
  179. package/dist/workspace/archil.js +1 -1
  180. package/dist/workspace/computer-deps.js +5 -3
  181. package/dist/workspace/computer-providers.d.ts +11 -1
  182. package/dist/workspace/computer-providers.js +29 -2
  183. package/dist/workspace/index.d.ts +1 -2
  184. package/dist/workspace/index.js +1 -2
  185. package/dist/workspace/paths.d.ts +0 -4
  186. package/dist/workspace/paths.js +0 -6
  187. package/dist/workspace/workspace.d.ts +1 -1
  188. package/dist/workspace/workspace.js +1 -1
  189. package/package.json +13 -13
  190. package/templates/TOOLS.md +46 -0
  191. package/dist/console/assets/index-LwNL4L9q.js +0 -619
  192. package/dist/console/assets/styles-DQo8rzY-.css +0 -1
  193. package/dist/workspace/learning-workspace.d.ts +0 -24
  194. /package/dist/learn/{learning.sh → legacy/learning.sh} +0 -0
@@ -1,11 +1,9 @@
1
- import { createHash } from "node:crypto";
2
1
  import { CORRECTIONS_CAP, draftProblems, frontKeys, isHeld, LEARNED_KEYS, learnedPlace, learnedStatus, printable, released, restorable, restoredLearned, retiredLearned, UNCLEAR_FRONT, unclearFront, unstorable, WORKFLOW_NAME, WORKFLOWS_DIR } from "./learn/index.js";
3
2
  import { readmeProblems } from "./learn/workflow-draft.js";
4
- import { forgetRunText, putCorrections, readCorrections } from "./learn/commit.js";
5
- import { blobOid, FolderBusy, folderOf, FolderRefused, FolderTooLarge, FolderUnreadable, readLearning, PATCH_CAP, readRunDiff, readSnapshot, runDiffKey, snapshotAt, textsAt, writeLearning } from "./learn/folder.js";
6
- import { purgedRun, purgeGate, purgedRows } from "./purged-workflow.js";
3
+ import { putCorrections, readCorrections } from "./learn/commit.js";
4
+ import { blobOid, LearningBusy, learningOf, logChange, logOf, PATCH_CAP, readLearning, readView, runDiff, runDiffKey, writeLearning } from "./learn/rows.js";
7
5
  import { ApiError, invalid } from "./errors.js";
8
- import { detailShown, filesView, learningFolderOf, reasonShown, withAgentRepo } from "./learning.js";
6
+ import { detailShown, filesView, reasonShown } from "./learning.js";
9
7
  import { isObject } from "./validate.js";
10
8
  import { launchOf } from "./handed-values.js";
11
9
  import { learningStartOf } from "./run-launch.js";
@@ -14,78 +12,14 @@ import { runLearningEnd } from "./store-reads/learning.js";
14
12
  const LOG_PAGE = 20;
15
13
  const PAGE_MAX = 200;
16
14
  export { secretsShown } from "./learning.js";
17
- /** The few values last kept, by key, oldest dropped first: at most `entries` of them. */
18
- class Recent {
19
- entries;
20
- held = new Map();
21
- constructor(entries) {
22
- this.entries = entries;
23
- }
24
- get(key) {
25
- const hit = this.held.get(key);
26
- if (hit === undefined)
27
- return undefined;
28
- this.held.delete(key);
29
- this.held.set(key, hit);
30
- return hit;
31
- }
32
- set(key, value) {
33
- this.held.delete(key);
34
- this.held.set(key, value);
35
- while (this.held.size > this.entries)
36
- this.held.delete(this.held.keys().next().value);
37
- }
38
- }
39
- /** The snapshots this server read last, by the folder's agent and main: a later page's cursor names one of them. */
40
- const seen = new Recent(16);
41
- const seenKey = (agentId, main) => `${agentId}\0${main}`;
42
15
  export const etagOf = (oid) => `"${oid}"`;
43
16
  const EMPTY = { items: [], total: 0, next_cursor: null };
44
- /** A folder failure as a route answers it, failing closed: a link in the folder is an error whose words name it, a
45
- * backend that cannot answer (or a body that changed twice as it was read) is 503. */
17
+ /** A write's failure as a route answers it: a write that kept moving under it is 503. */
46
18
  function routeFailure(error) {
47
- if (error instanceof FolderBusy)
19
+ if (error instanceof LearningBusy)
48
20
  return new ApiError("unavailable", error.message);
49
- if (error instanceof FolderUnreadable)
50
- return error.link ? new Error(error.message) : new ApiError("unavailable", error.message);
51
21
  return error;
52
22
  }
53
- /** Run `runId`'s text taken off agent `agentId`'s learning folder's current files at its purge (learn/commit.ts
54
- * forgetRunText: a workflow it changed last goes back to the version before it that no purged run of `store` wrote),
55
- * in the agent's queue, as every write of the folder is. */
56
- export async function forgetRunLearning(data, agentId, runId, store) {
57
- await withAgentRepo(data, agentId, async () => {
58
- const { workspace: ws, end } = learningFolderOf(data, agentId);
59
- try {
60
- await forgetRunText(ws, runId, async (run) => (await purgedRows(store, [run])).has(run));
61
- }
62
- catch (error) {
63
- throw routeFailure(error);
64
- }
65
- finally {
66
- await end();
67
- }
68
- });
69
- }
70
- /** A read of agent `agentId`'s folder: `read` over its snapshot and the bodies it names (learn/folder.ts readLearning),
71
- * `none` for a folder with no main yet; the folder ended after. */
72
- async function reading(data, agentId, read, none) {
73
- const { workspace: ws, end } = learningFolderOf(data, agentId);
74
- try {
75
- return await readLearning(ws, async ({ snapshot, body }) => {
76
- if (!snapshot)
77
- return none();
78
- seen.set(seenKey(agentId, snapshot.main), snapshot);
79
- return read({ ws, snapshot, body });
80
- });
81
- }
82
- catch (error) {
83
- throw routeFailure(error);
84
- }
85
- finally {
86
- await end();
87
- }
88
- }
89
23
  /** A retired draft's `retired`: its newest retire by a person; else, one a person made retired another way, their
90
24
  * newest change; else its newest change's time. `from`: the status its restore gives back (its retire recorded it,
91
25
  * retired_from; none recorded reads pending). `unread`: the host could not read its README.md. */
@@ -100,10 +34,10 @@ function workflowView(item, shown, stateOf, unread = false) {
100
34
  ...(item.status === "retired" ? { retired: retiredOf(item.history, item.retired_from, unread) } : {}),
101
35
  };
102
36
  }
103
- /** A change on main as the log shows it, cut of the host's secrets. */
37
+ /** A save as the log shows it, cut of the host's secrets. */
104
38
  const changeView = (change, shown) => ({ by: change.by, commit: change.commit, at: change.at, reason: shown.text(change.reason), files: change.files.map(shown.name) });
105
- const cursorOf = (sha, offset) => Buffer.from(`${sha}.${offset}`).toString("base64url");
106
- /** A page's request: its limit (1 to PAGE_MAX), and the main and offset its cursor names. */
39
+ const cursorOf = (main, before) => Buffer.from(`${main}.${before}`).toString("base64url");
40
+ /** A page's request: its limit (1 to PAGE_MAX), and the version its cursor says the page starts below. */
107
41
  function pageRequest(query, fallback) {
108
42
  const given = query.get("limit");
109
43
  const limit = given === null ? fallback : Number(given);
@@ -112,135 +46,120 @@ function pageRequest(query, fallback) {
112
46
  const cursor = query.get("cursor");
113
47
  if (cursor === null)
114
48
  return { limit };
115
- const named = /^([0-9a-f]{40}|[0-9a-f]{64})\.(\d{1,9})$/.exec(Buffer.from(cursor, "base64url").toString("utf8"));
49
+ const named = /^[0-9a-f]{40}\.(\d{1,15})$/.exec(Buffer.from(cursor, "base64url").toString("utf8"));
116
50
  if (!named)
117
51
  throw new ApiError("bad_request", "cursor is not one this server gave");
118
- return { limit, at: { sha: named[1], offset: Number(named[2]) } };
52
+ return { limit, before: Number(named[1]) };
119
53
  }
120
- /** The snapshot a page reads: main now's, or the one its cursor names while this server holds it, else main now's from
121
- * its first item. */
122
- function pageAt(agentId, snapshot, at) {
123
- if (!at)
124
- return { snapshot, offset: 0 };
125
- if (at.sha === snapshot.main)
126
- return { snapshot, offset: at.offset };
127
- const kept = seen.get(seenKey(agentId, at.sha));
128
- return kept ? { snapshot: kept, offset: at.offset } : { snapshot, offset: 0 };
54
+ /** A page of the agent's log, newest first, cut of the host's secrets: below version `before` when given. */
55
+ async function logPage(rows, agentId, main, page, shown) {
56
+ const { changes, more, total } = await logOf(learningOf(rows, agentId), page);
57
+ const last = changes.at(-1);
58
+ return { items: changes.map(({ change }) => changeView(change, shown)), total, next_cursor: more && last ? cursorOf(main, last.version) : null };
129
59
  }
130
- /** A page of the changes on main, newest first, cut of the host's secrets. */
131
- /** `served` changes only: the offset and the cursor count the log as the snapshot keeps it, so a run purged between two
132
- * pages moves no change the next page starts at. */
133
- function logPage(snapshot, offset, limit, shown, served) {
134
- const { log } = snapshot;
135
- const items = [];
136
- let at = offset;
137
- for (; at < log.length && items.length < limit; at++)
138
- if (served(log[at]))
139
- items.push(changeView(log[at], shown));
140
- const more = log.slice(at).some(served);
141
- return { items, total: log.filter(served).length, next_cursor: more ? cursorOf(snapshot.main, at) : null };
142
- }
143
- /** For tests: how many times a folder's statuses were read (once per commit of its main). */
60
+ /** For tests: how many times an agent's statuses were read (once per save of its learning). */
144
61
  export const pendingTestHooks = { reads: 0 };
145
- /** By agent: its folder's main commit and each draft's status there. */
62
+ /** By agent: its newest save and each draft's status there. */
146
63
  const statusBy = new Map();
147
- /** Each workflow draft's status on agent `agentId`'s folder's main, by its workflow.json (as its README.md says it):
148
- * `active`, `pending` or `retired`. Built once per main (a list asks for many runs). A folder never made, or with no
149
- * main, holds none; one whose snapshot cannot be read is undefined. */
150
- export async function statusesOf(data, agentId) {
151
- const folder = learningFolderOf(data, agentId);
64
+ /** Each workflow draft's status at agent `agentId`'s newest save, by its workflow.json (as its README.md says it):
65
+ * `active`, `pending` or `retired`. Built once per save (a list asks for many runs): the newest save's id (of any kind,
66
+ * a purge's too) is read first, and the view, its items and their history, only when it moved. An agent with no save
67
+ * holds none; one whose learning cannot be read is undefined. */
68
+ export async function statusesOf(rows, agentId) {
152
69
  try {
153
- const snapshot = await readSnapshot(folder.workspace);
154
- if (!snapshot)
155
- return new Map();
156
70
  const known = statusBy.get(agentId);
157
- if (known?.sha === snapshot.main)
71
+ const newest = await rows.learning.newestSave(agentId);
72
+ if (newest !== undefined && known?.main === newest)
158
73
  return known.status;
159
- // Built at once, with no wait between the miss and the keep: requests that miss together build it once.
74
+ const view = await readView(learningOf(rows, agentId));
75
+ if (!view)
76
+ return new Map();
160
77
  pendingTestHooks.reads += 1;
161
- const status = new Map(snapshot.workflows.map((item) => [`${WORKFLOWS_DIR}/${item.name}/workflow.json`, { status: item.status }]));
162
- statusBy.set(agentId, { sha: snapshot.main, status });
78
+ const status = new Map(view.workflows.map((item) => [`${WORKFLOWS_DIR}/${item.name}/workflow.json`, { status: item.status }]));
79
+ statusBy.set(agentId, { main: view.main, status });
163
80
  return status;
164
81
  }
165
82
  catch {
166
83
  return undefined;
167
84
  }
168
- finally {
169
- await folder.end();
170
- }
171
85
  }
172
- /** How many of agent `agentId`'s workflow drafts wait for its owner's OK on its folder's main (statusesOf). A folder
173
- * never made has none waiting; one that cannot be read is undefined (the caller shows no count). */
174
- export async function pendingCount(data, agentId) {
175
- const status = await statusesOf(data, agentId);
86
+ /** How many of agent `agentId`'s workflow drafts wait for its owner's OK at its newest save (statusesOf). An agent with
87
+ * no save has none waiting; one that cannot be read is undefined (the caller shows no count). */
88
+ export async function pendingCount(rows, agentId) {
89
+ const status = await statusesOf(rows, agentId);
176
90
  return status === undefined ? undefined : [...status.values()].filter((value) => value.status === "pending").length;
177
91
  }
178
- export async function agentLearning(data, agentId, shown, counts, impact, stateOf, store) {
179
- return reading(data, agentId, async ({ snapshot, body }) => {
180
- const gate = await purgeGate(snapshot, store, true);
181
- const corrections = (await readCorrections(snapshot, body)).text;
182
- // A retired draft whose README.md can't be read is said so (unclearFront), read from its file now, as the snapshot's
183
- // status was: a few retired items, one read each.
184
- const unread = async (item) => item.status === "retired" && unclearFront(await body(item.file, item.oid));
185
- const items = snapshot.workflows.filter(({ name }) => !gate.workflows.has(name));
186
- return { agent: agentId, main: snapshot.main, corrections: shown.text(corrections), workflows: await Promise.all(items.map(async (item) => workflowView(item, shown, stateOf, await unread(item)))), log: logPage(snapshot, 0, LOG_PAGE, shown, gate.served), counts, impact };
187
- }, () => ({ agent: agentId, main: null, corrections: "", workflows: [], log: EMPTY, counts, impact }));
92
+ export async function agentLearning(rows, agentId, shown, counts, impact, stateOf) {
93
+ return readLearning(learningOf(rows, agentId), async (read) => {
94
+ const { view } = read;
95
+ if (!view)
96
+ return { agent: agentId, main: null, corrections: "", workflows: [], log: EMPTY, counts, impact };
97
+ const corrections = readCorrections(read).text;
98
+ // A retired draft whose README.md can't be read is said so (unclearFront), read from its file as its status was.
99
+ const unread = (item) => item.status === "retired" && unclearFront(read.text(item.file) ?? "");
100
+ return { agent: agentId, main: view.main, corrections: shown.text(corrections), workflows: view.workflows.map((item) => workflowView(item, shown, stateOf, unread(item))), log: await logPage(rows, agentId, view.main, { limit: LOG_PAGE }, shown), counts, impact };
101
+ });
188
102
  }
189
- /** GET /agents/{id}/learning/log?cursor=&limit=: a page of the changes on main, newest first, a purged run's left out
190
- * (purgeGate). */
191
- export async function learningLog(data, agentId, query, shown, store) {
192
- const { limit, at } = pageRequest(query, LOG_PAGE);
193
- return reading(data, agentId, async ({ snapshot }) => {
194
- const page = pageAt(agentId, snapshot, at);
195
- return logPage(page.snapshot, page.offset, limit, shown, (await purgeGate(page.snapshot, store, true)).served);
196
- }, () => EMPTY);
103
+ /** GET /agents/{id}/learning/log?cursor=&limit=: a page of the agent's log, newest first. */
104
+ export async function learningLog(rows, agentId, query, shown) {
105
+ const page = pageRequest(query, LOG_PAGE);
106
+ const view = await readView(learningOf(rows, agentId));
107
+ return view ? logPage(rows, agentId, view.main, page, shown) : EMPTY;
197
108
  }
198
- /** GET /agents/{id}/learning/corrections: corrections.md on main as text (empty when main holds none), its ETag (its blob
199
- * id; an empty file's when there is none) and the cap a PUT keeps to, cut of the host's secrets as every read is. */
200
- export async function correctionsView(data, agentId, shown) {
201
- const read = await reading(data, agentId, ({ snapshot, body }) => readCorrections(snapshot, body), () => ({ text: "", oid: blobOid("") }));
109
+ /** GET /agents/{id}/learning/corrections: corrections.md at the newest save as text (empty when it holds none), its ETag
110
+ * (its blob id; an empty file's when there is none) and the cap a PUT keeps to, cut of the host's secrets as every read
111
+ * is. */
112
+ export async function correctionsView(rows, agentId, shown) {
113
+ const read = await readLearning(learningOf(rows, agentId), readCorrections);
202
114
  return { text: shown.text(read.text), etag: etagOf(read.oid), cap_bytes: CORRECTIONS_CAP };
203
115
  }
204
116
  /** PUT /agents/{id}/learning/corrections: corrections.md replaced whole by a person (`text`), only over the version they
205
117
  * read (`ifMatch`: its ETag; none, or `*`, is 428; another version is 412). Refused whole, nothing written, when it holds
206
118
  * what must never be stored (a host secret, text shaped like one, a hidden character) or passes the cap (422 with the
207
119
  * problems, printable). A text read cut of a secret and sent back replaces the secret with the cut: a person's write never
208
- * puts a secret back. In the agent's queue, one commit on main. */
209
- export async function correctionsWrite(data, agentId, input) {
120
+ * puts a secret back. One save. */
121
+ export async function correctionsWrite(rows, agentId, input) {
210
122
  const match = input.ifMatch?.trim();
211
123
  if (!match || match === "*")
212
124
  throw new ApiError("precondition_required", "A write names the version it read: If-Match with corrections.md's ETag, as GET answered it.");
213
- return withAgentRepo(data, agentId, async () => {
214
- const { workspace: ws, end } = learningFolderOf(data, agentId);
215
- try {
216
- const done = await putCorrections(ws, { text: input.text, ifMatch: match, refuseValues: input.refuse });
217
- if (done.ok)
218
- return { text: done.text, etag: etagOf(done.oid), cap_bytes: CORRECTIONS_CAP };
219
- if (done.reason === "conflict")
220
- throw new ApiError("precondition_failed", "corrections.md changed since it was read (a run's correction, or another edit): read it again.");
221
- const problems = done.problems.map((problem) => printable(problem, input.refuse));
222
- throw invalid(problems.map((problem) => ({ field: "text", reason: problem.rule, message: problem.detail })));
223
- }
224
- catch (error) {
225
- if (error instanceof FolderTooLarge)
226
- throw invalid([{ field: "text", reason: "too_large", message: error.message }]);
227
- throw routeFailure(error);
228
- }
229
- finally {
230
- await end();
231
- }
232
- });
125
+ try {
126
+ const done = await putCorrections(learningOf(rows, agentId), { text: input.text, ifMatch: match, refuseValues: input.refuse });
127
+ if (done.ok)
128
+ return { text: done.text, etag: etagOf(done.oid), cap_bytes: CORRECTIONS_CAP };
129
+ if (done.reason === "conflict")
130
+ throw new ApiError("precondition_failed", "corrections.md changed since it was read (a run's correction, or another edit): read it again.");
131
+ const problems = done.problems.map((problem) => printable(problem, input.refuse));
132
+ throw invalid(problems.map((problem) => ({ field: "text", reason: problem.rule, message: problem.detail })));
133
+ }
134
+ catch (error) {
135
+ throw routeFailure(error);
136
+ }
233
137
  }
234
138
  /** The most revisions a workflow's history answers, and its default. */
235
139
  const REVISIONS_MAX = 50;
236
140
  const REVISIONS_DEFAULT = 20;
141
+ /** Learned workflow `name`'s workflow.json at each of its versions, oldest first, with the save that wrote it: one per
142
+ * version that changed its text. */
143
+ async function revisionsOf(rows, agentId, name) {
144
+ const path = `${WORKFLOWS_DIR}/${name}/workflow.json`;
145
+ const out = [];
146
+ let before = null;
147
+ // Store.learning.versions answers newest first; a revision is read against the one before it.
148
+ for (const version of (await rows.learning.versions(agentId, "workflow", name)).reverse()) {
149
+ const text = version.body === null ? null : JSON.parse(version.body)[path] ?? null;
150
+ const change = logChange(version.save);
151
+ if (text !== before && change)
152
+ out.push({ change, text, digest: text === null ? null : version.digest });
153
+ before = text;
154
+ }
155
+ return out;
156
+ }
237
157
  /** GET /agents/{id}/learning/workflows/{name}/revisions?limit=: the latest revisions of learned workflow `name` (the
238
- * commits on main's log that changed `workflows/<name>/workflow.json`), oldest first, each with the workflow's text at
239
- * that commit, so a person can step through how it changed. One read-only exec per revision (textsAt), at most `limit`
240
- * of them. `total` counts every such commit the log holds, `truncated` says the log itself is cut (it keeps the latest
241
- * LOG_KEEP changes). A purged run's merge is no revision (purgeGate). A workflow no commit of the log changed is
158
+ * saves that changed `workflows/<name>/workflow.json`), oldest first, each with the workflow's text there, so a person
159
+ * can step through how it changed: at most `limit` of them. `total` counts every such save; `truncated` is false, the
160
+ * rows keep every one. A purged run's save is no revision: its rows went with it. A workflow no save changed is
242
161
  * not_found. */
243
- export async function workflowRevisions(data, agentId, name, query, shown, store) {
162
+ export async function workflowRevisions(rows, agentId, name, query, shown) {
244
163
  if (!WORKFLOW_NAME.test(name))
245
164
  throw new ApiError("bad_request", "A workflow's folder is named with lowercase letters, digits, dashes and underscores.");
246
165
  const given = query.get("limit");
@@ -249,54 +168,30 @@ export async function workflowRevisions(data, agentId, name, query, shown, store
249
168
  throw new ApiError("bad_request", `limit is an integer from 1 to ${REVISIONS_MAX}`);
250
169
  const path = `${WORKFLOWS_DIR}/${name}/workflow.json`;
251
170
  if (shown.name(path) !== path)
252
- throw new ApiError("not_found", "the agent's learning folder has no such workflow");
253
- const found = await reading(data, agentId, async ({ ws, snapshot }) => {
254
- const { served } = await purgeGate(snapshot, store, true);
255
- const touched = snapshot.log.filter((change) => served(change) && change.files.includes(path));
256
- const latest = touched.slice(0, limit).reverse();
257
- const revisions = [];
258
- for (const change of latest) {
259
- const texts = await textsAt(ws, change.commit, [path]).catch((error) => { throw routeFailure(error); });
260
- const raw = texts?.[path];
261
- // Its digest, read from the text as it is (workflow-first.ts workflowDigest's): the one a run's metrics and the
262
- // promotion records name, so a revision's runs and promotion are found by it.
263
- revisions.push({ commit: change.commit, at: change.at, by: change.by, reason: shown.text(change.reason), text: raw === undefined ? null : shown.text(raw), digest: raw === undefined ? null : createHash("sha256").update(raw).digest("hex").slice(0, 16) });
264
- }
265
- return { revisions, total: touched.length, truncated: snapshot.log_more };
266
- }, () => undefined);
267
- if (!found || !found.total)
268
- throw new ApiError("not_found", "the agent's learning folder has no such workflow");
269
- return { name, ...found };
171
+ throw new ApiError("not_found", "the agent's learning has no such workflow");
172
+ const all = await revisionsOf(rows, agentId, name);
173
+ if (!all.length)
174
+ throw new ApiError("not_found", "the agent's learning has no such workflow");
175
+ // Its digest, read from the text as it is (workflow-first.ts workflowDigest's): the one a run's metrics and the
176
+ // promotion records name, so a revision's runs and promotion are found by it.
177
+ const revisions = all.slice(-limit).map(({ change, text, digest }) => ({ commit: change.commit, at: change.at, by: change.by, reason: shown.text(change.reason), text: text === null ? null : shown.text(text), digest }));
178
+ return { name, revisions, total: all.length, truncated: false };
270
179
  }
271
180
  /** Learned workflow `name`'s text at `digest` (a champion's, as its promotion records name it), read by that digest and
272
- * never by paging the workflow's history: at `commits` (the records' learning commits, newest first), then at main, the
273
- * first commit whose workflow.json is that digest's text, with the commit it was read at. Undefined when none is (no
274
- * main yet, or no commit read holds it). A commit whose text a purged run wrote is never read (purgeGate), however
275
- * old. One read-only exec per commit tried (textsAt), and one more for the commit that holds the digest, unless
276
- * it is main (snapshotAt). */
277
- export async function workflowAtDigest(data, agentId, name, digest, commits, store) {
181
+ * never by paging the workflow's history: its newest version whose workflow.json is that digest's, with the save it was
182
+ * written at. Undefined when none is. */
183
+ export async function workflowAtDigest(rows, agentId, name, digest) {
278
184
  if (!WORKFLOW_NAME.test(name))
279
185
  return undefined;
280
- const path = `${WORKFLOWS_DIR}/${name}/workflow.json`;
281
- return reading(data, agentId, async ({ ws, snapshot }) => {
282
- for (const commit of new Set([...commits, snapshot.main])) {
283
- const raw = (await textsAt(ws, commit, [path]).catch(() => undefined))?.[path];
284
- if (raw === undefined || createHash("sha256").update(raw).digest("hex").slice(0, 16) !== digest)
285
- continue;
286
- const at = commit === snapshot.main ? snapshot : await snapshotAt(ws, commit).catch(() => undefined);
287
- if (!at || (await purgeGate(at, store)).workflows.has(name))
288
- continue;
289
- return { text: raw, commit };
290
- }
291
- return undefined;
292
- }, () => undefined);
186
+ const found = (await revisionsOf(rows, agentId, name)).findLast((one) => one.digest === digest && one.text !== null);
187
+ return found ? { text: found.text, commit: found.change.commit } : undefined;
293
188
  }
294
- /** The blob of a draft's `file` on the snapshot's main; undefined when main holds no such file the snapshot names. */
295
- function blobIn(snapshot, file) {
189
+ /** The text of a draft's `file` at the read's save; undefined when it holds no such file. */
190
+ function fileIn(read, file) {
296
191
  const place = learnedPlace(file);
297
- if (!snapshot || !place)
192
+ if (!read.view || !place)
298
193
  return undefined;
299
- return snapshot.workflows.find((item) => item.name === place.name)?.files.find(({ path }) => path === file)?.oid;
194
+ return read.view.workflows.some((item) => item.name === place.name && item.files.some(({ path }) => path === file)) ? read.text(file) : undefined;
300
195
  }
301
196
  /** The file a route names, decoded: a draft's workflow.json or README.md (`workflows/<name>/README.md`,
302
197
  * percent-encoded); for an approve, a retire or a restore, its README.md, the file that says whether it waits. Anything
@@ -318,27 +213,14 @@ function fileOf(raw, use) {
318
213
  throw new ApiError("bad_request", "A workflow is approved, retired and restored by its README.md, the file that says whether it is in use.");
319
214
  return file;
320
215
  }
321
- /** GET /agents/{id}/learning/files/{file}: a draft's file on main as text, its ETag, and its type (workflow.json is
322
- * JSON). A purged run's workflow left main with its purge (learn/commit.ts forgetRunText), so its files are the 404 any
323
- * missing file is. A file of a workflow still on main whose workflow.json a purged run wrote (its run purged before its
324
- * purge took the folder's text, until its DELETE is sent again) is 410 purged, as every route of that run is
325
- * (purgeGate). */
326
- export async function readLearnedFile(data, agentId, raw, shown, store) {
216
+ /** GET /agents/{id}/learning/files/{file}: a draft's file at the newest save as text, its ETag, and its type
217
+ * (workflow.json is JSON). A purged run's workflow went with its rows, so its files are the 404 any missing file is. */
218
+ export async function readLearnedFile(rows, agentId, raw, shown) {
327
219
  const file = fileOf(raw, "read");
328
- const place = learnedPlace(file);
329
- const found = await reading(data, agentId, async ({ snapshot, body }) => {
330
- const oid = blobIn(snapshot, file);
331
- if (oid === undefined)
332
- return undefined;
333
- // Either file of the workflow: the gate refuses its folder whole, as the view and a merge's diff do.
334
- const purged = (await purgeGate(snapshot, store)).workflows.get(place.name);
335
- if (purged)
336
- throw purgedRun(purged);
337
- return { oid, text: await body(file, oid) };
338
- }, () => undefined);
339
- if (!found)
340
- throw new ApiError("not_found", "the agent's learning folder has no such file on main");
341
- return { text: shown.text(found.text), etag: etagOf(found.oid), ...(file.endsWith(".json") ? { type: "application/json; charset=utf-8" } : {}) };
220
+ const text = await readLearning(learningOf(rows, agentId), (read) => fileIn(read, file));
221
+ if (text === undefined)
222
+ throw new ApiError("not_found", "the agent's learning has no such file");
223
+ return { text: shown.text(text), etag: etagOf(blobOid(text)), ...(file.endsWith(".json") ? { type: "application/json; charset=utf-8" } : {}) };
342
224
  }
343
225
  /** A learning file as a text answer: its ETag, an explicit type (markdown unless it names one), nosniff, and a sandbox on
344
226
  * whatever opens it. */
@@ -390,17 +272,14 @@ export async function textBody(req, max) {
390
272
  }
391
273
  const refused = (problems) => new ApiError("bad_request", `The workflow does not pass the checks: ${[...new Set(problems.map((problem) => problem.rule))].join(", ")}.`, { problems });
392
274
  /** POST /agents/{id}/learning/files/{file}/approve, .../retire or .../restore, as a person, on a draft's README.md
393
- * (`file`): If-Match on the version read (none, or `*`, is 428; another is 412), then one commit on main by the learning
394
- * script (learn/folder.ts writeLearning), in the agent's queue, its message `learning: <approved|retired|restored> by a
395
- * person: <file>` with a `Changed-By: user` trailer (and `Approved-Via: console` on an approval). An approval releases a
396
- * held draft (status: pending) to every later run; a retire takes it out of every later run unchecked, so a leaking one
397
- * can always be revoked; a restore brings it back to the status its retire recorded, checked again as a new draft is
398
- * (secrets' shapes, the host's values, hidden characters, its README's format, its workflow.json against the agent's
399
- * tools and gate). A retire of a retired draft commits nothing. An approval or a restore of a workflow whose
400
- * workflow.json a purged run wrote (still on main until its DELETE is sent again) is 410 purged (purgeGate over
401
- * `store`'s runs): no person's change gives it to a run; a retire takes it out as any other. `refuse`: the host's
402
- * secrets. */
403
- export async function changeWorkflow(data, agentId, raw, input) {
275
+ * (`file`): If-Match on the version read (none, or `*`, is 428; another is 412), then one save of the agent's learning
276
+ * (learn/rows.ts writeLearning), its reason `<approved|retired|restored> by a person: <file>`, and an approval's said to
277
+ * come through the console. An approval releases a held draft (status: pending) to every later run; a retire takes it
278
+ * out of every later run unchecked, so a leaking one can always be revoked; a restore brings it back to the status its
279
+ * retire recorded, checked again as a new draft is (secrets' shapes, the host's values, hidden characters, its README's
280
+ * format, its workflow.json against the agent's tools and gate). A retire of a retired draft saves nothing. `refuse`:
281
+ * the host's secrets. */
282
+ export async function changeWorkflow(rows, agentId, raw, input) {
404
283
  const file = fileOf(raw, input.action);
405
284
  const place = learnedPlace(file);
406
285
  const match = input.ifMatch?.split(",").map((tag) => tag.trim()).filter(Boolean);
@@ -408,83 +287,65 @@ export async function changeWorkflow(data, agentId, raw, input) {
408
287
  throw new ApiError("precondition_required", "If-Match: * names no version: send the README's ETag, as GET answered it.");
409
288
  if (!match?.length)
410
289
  throw new ApiError("precondition_required", "A change names the version it read: If-Match with the README's ETag.");
411
- return withAgentRepo(data, agentId, async () => {
412
- // The folder as a run's merge reaches it: a link in it is refused (an error naming it, nothing written), never
413
- // followed.
414
- const { workspace: ws, end } = learningFolderOf(data, agentId);
415
- try {
416
- const { result } = await writeLearning(ws, async ({ snapshot, body, bytes }) => {
417
- const oid = blobIn(snapshot, file);
418
- const current = oid === undefined ? undefined : { oid, text: await body(file, oid) };
419
- if (!current)
420
- throw new ApiError("not_found", "the agent's learning folder has no such workflow on main");
421
- if (!match.includes(etagOf(current.oid)))
422
- throw new ApiError("precondition_failed", "The workflow changed since it was read (a run's merge, or another change): read it again.");
423
- if (input.action !== "retire") {
424
- const purged = (await purgeGate(snapshot, input.store)).workflows.get(place.name);
425
- if (purged)
426
- throw purgedRun(purged);
427
- }
428
- let text;
429
- if (input.action === "restore") {
430
- const status = learnedStatus(current.text);
431
- if (status !== "retired")
432
- throw new ApiError("bad_request", `The workflow is not retired: it is ${status}.`);
433
- // Read as retired since its front matter reads no way, or its status (or the retired_from its retire recorded) is
434
- // set on more than one line, which no writer edits: refused until it is written so.
435
- if (!restorable(current.text))
436
- throw refused([printable({ rule: "workflow", path: file, detail: UNCLEAR_FRONT }, input.refuse)]);
437
- // Back to the status its retire recorded, never active unless it was active: a held draft waits for its owner's OK again.
438
- text = restoredLearned(current.text);
439
- const problems = readmeProblems(text, place.name).map((detail) => printable({ rule: "workflow", path: file, detail }, input.refuse));
440
- const extra = (frontKeys(text) ?? []).filter((key) => !LEARNED_KEYS.includes(key) && key !== "status");
441
- if (extra.length)
442
- problems.push(printable({ rule: "workflow", path: file, detail: `its front matter sets ${extra.join(", ")}: a learned workflow's README sets name and description alone` }, input.refuse));
443
- const others = snapshot.workflows.find((item) => item.name === place.name)?.files.filter(({ path }) => path !== file) ?? [];
444
- const changes = [{ path: file, status: "modified", bytes: Buffer.from(text, "utf8") }, ...(await Promise.all(others.map(async ({ path, oid: blob }) => ({ path, status: "modified", bytes: await bytes(path, blob) }))))];
445
- problems.push(...unstorable(changes, input.refuse));
446
- // Its workflow.json passes the checks a run's draft passes (its tools and the gate's settings), so a restore never
447
- // brings back a draft no run could run.
448
- const draft = changes.find(({ path }) => path === `${WORKFLOWS_DIR}/${place.name}/workflow.json`);
449
- if (draft && input.draftTools) {
450
- const { tools, gated, deniedBy, decisions } = await input.draftTools();
451
- const dsl = await import("@parcha/agentrun-dsl");
452
- for (const { rule, detail } of draftProblems(dsl, draft.bytes.toString("utf8"), tools, gated, deniedBy ?? {}, decisions))
453
- problems.push(printable({ rule, path: draft.path, detail }, input.refuse));
454
- }
455
- if (problems.length)
456
- throw refused(problems);
457
- }
458
- else if (input.action === "retire") {
459
- // One already retired is answered as it is; nothing else in the folder changes.
460
- if (learnedStatus(current.text) === "retired")
461
- return { result: { status: 200, file, text: current.text, etag: etagOf(current.oid) } };
462
- text = retiredLearned(current.text);
463
- }
464
- else {
465
- // Approved, it is no longer held: given to every later run. Nothing else in the folder changes.
466
- if (!isHeld(current.text))
467
- throw new ApiError("bad_request", `The workflow is not waiting for an OK: it is ${learnedStatus(current.text)}.`);
468
- text = released(current.text);
290
+ try {
291
+ const { result } = await writeLearning(learningOf(rows, agentId), async (read) => {
292
+ const now = fileIn(read, file);
293
+ if (now === undefined)
294
+ throw new ApiError("not_found", "the agent's learning has no such workflow");
295
+ const current = { oid: blobOid(now), text: now };
296
+ if (!match.includes(etagOf(current.oid)))
297
+ throw new ApiError("precondition_failed", "The workflow changed since it was read (a run's merge, or another change): read it again.");
298
+ let text;
299
+ if (input.action === "restore") {
300
+ const status = learnedStatus(current.text);
301
+ if (status !== "retired")
302
+ throw new ApiError("bad_request", `The workflow is not retired: it is ${status}.`);
303
+ // Read as retired since its front matter reads no way, or its status (or the retired_from its retire recorded) is
304
+ // set on more than one line, which no writer edits: refused until it is written so.
305
+ if (!restorable(current.text))
306
+ throw refused([printable({ rule: "workflow", path: file, detail: UNCLEAR_FRONT }, input.refuse)]);
307
+ // Back to the status its retire recorded, never active unless it was active: a held draft waits for its owner's OK again.
308
+ text = restoredLearned(current.text);
309
+ const problems = readmeProblems(text, place.name).map((detail) => printable({ rule: "workflow", path: file, detail }, input.refuse));
310
+ const extra = (frontKeys(text) ?? []).filter((key) => !LEARNED_KEYS.includes(key) && key !== "status");
311
+ if (extra.length)
312
+ problems.push(printable({ rule: "workflow", path: file, detail: `its front matter sets ${extra.join(", ")}: a learned workflow's README sets name and description alone` }, input.refuse));
313
+ const others = read.view.workflows.find((item) => item.name === place.name)?.files.filter(({ path }) => path !== file) ?? [];
314
+ const changes = [{ path: file, status: "modified", bytes: Buffer.from(text, "utf8") }, ...others.map(({ path }) => ({ path, status: "modified", bytes: Buffer.from(read.text(path) ?? "", "utf8") }))];
315
+ problems.push(...unstorable(changes, input.refuse));
316
+ // Its workflow.json passes the checks a run's draft passes (its tools and the gate's settings), so a restore never
317
+ // brings back a draft no run could run.
318
+ const draft = changes.find(({ path }) => path === `${WORKFLOWS_DIR}/${place.name}/workflow.json`);
319
+ if (draft && input.draftTools) {
320
+ const { tools, gated, deniedBy, decisions } = await input.draftTools();
321
+ const dsl = await import("@parcha/agentrun-dsl");
322
+ for (const { rule, detail } of draftProblems(dsl, draft.bytes.toString("utf8"), tools, gated, deniedBy ?? {}, decisions))
323
+ problems.push(printable({ rule, path: draft.path, detail }, input.refuse));
469
324
  }
470
- const kind = input.action === "approve" ? "approved" : input.action === "restore" ? "restored" : "retired";
471
- // Who approved, and how, in the trailers; the commit's own date is when. Never the file's text.
472
- const change = { by: { person: kind, file, approved: input.action === "approve" }, writes: [{ path: file, text }] };
473
- return { result: { status: 200, file, text, etag: etagOf(blobOid(text)) }, change };
474
- });
475
- return result;
476
- }
477
- catch (error) {
478
- if (error instanceof FolderRefused)
479
- throw new ApiError("precondition_failed", "The folder's file by this name on main is no regular UTF-8 file, and a person's change never replaces it.");
480
- if (error instanceof FolderTooLarge)
481
- throw refused([{ rule: "too_large", path: file, detail: error.message }]);
482
- throw routeFailure(error);
483
- }
484
- finally {
485
- await end();
486
- }
487
- });
325
+ if (problems.length)
326
+ throw refused(problems);
327
+ }
328
+ else if (input.action === "retire") {
329
+ // One already retired is answered as it is; nothing else changes.
330
+ if (learnedStatus(current.text) === "retired")
331
+ return { result: { status: 200, file, text: current.text, etag: etagOf(current.oid) } };
332
+ text = retiredLearned(current.text);
333
+ }
334
+ else {
335
+ // Approved, it is no longer held: given to every later run. Nothing else changes.
336
+ if (!isHeld(current.text))
337
+ throw new ApiError("bad_request", `The workflow is not waiting for an OK: it is ${learnedStatus(current.text)}.`);
338
+ text = released(current.text);
339
+ }
340
+ const kind = input.action === "approve" ? "approved" : input.action === "restore" ? "restored" : "retired";
341
+ const change = { by: { person: kind, file, approved: input.action === "approve" }, writes: [{ path: file, text }] };
342
+ return { result: { status: 200, file, text, etag: etagOf(blobOid(text)) }, change };
343
+ });
344
+ return result;
345
+ }
346
+ catch (error) {
347
+ throw routeFailure(error);
348
+ }
488
349
  }
489
350
  /** GET /runs/{id}/learning's body, from the run's learning as it reads now, the seed it started from and whether it
490
351
  * settled: the one shape, read from the one store (store-reads/learning.ts runLearningOverStore). */
@@ -513,12 +374,12 @@ export function runLearningBody(input, shown, secrets) {
513
374
  };
514
375
  }
515
376
  /** GET /runs/{id}/learning/diff over the one store: once merged (its learning end, store-reads/learning.ts
516
- * runLearningEnd), its merge commit against its parent, as its merge's script wrote it (`.agentrun/diffs/<run>.json` in
517
- * its agent's learning folder); a run that merged nothing, no file, against the seed its launch's learning start names. A
518
- * run that does not learn (no learning start and no learning end) is not_found. A file's patch is withheld when too large
519
- * (as the script wrote it), or when it holds one of the host's secrets now (`shown`); any other is served as every
520
- * learning text is (`shown.text`: a loopback address reads "a local address"). */
521
- export async function runDiffOverStore(data, store, runId, shown) {
377
+ * runLearningEnd), its merge's save against the one before it (learn/rows.ts runDiff); a run that merged nothing
378
+ * against the seed its launch's learning start names. A run that does not learn (no learning start and no learning
379
+ * end) is not_found, as a merge its agent's learning no longer holds is. A file's patch is withheld when too large, or
380
+ * when it holds one of the host's secrets now (`shown`); any other is served as every learning text is (`shown.text`:
381
+ * a loopback address reads "a local address"). */
382
+ export async function runDiffOverStore(store, runId, shown) {
522
383
  const [end, kept, launch, row] = await Promise.all([runLearningEnd(store, runId), store.learning.proposal(runId), launchOf(store, runId), store.runs.get(runId)]);
523
384
  const start = launch ? learningStartOf(launch) : undefined;
524
385
  if (!row || (!end && !start))
@@ -533,44 +394,10 @@ export async function runDiffOverStore(data, store, runId, shown) {
533
394
  return Buffer.byteLength(served) > PATCH_CAP ? { path, status, withheld: "too_large" } : { path, status, patch: served };
534
395
  };
535
396
  if (end?.merged) {
536
- const folder = learningFolderOf(data, row.agentId);
537
- const diff = await readRunDiff(folder.workspace, runDiffKey(runId, kept?.round)).then((read) => (read && read.merge === end.merged ? againstPurged(folder.workspace, read, store) : undefined)).catch((error) => Promise.reject(routeFailure(error))).finally(() => folder.end());
538
- if (!diff)
539
- throw new ApiError("not_found", "the run's merge is not in its agent's learning folder");
540
- return { base: diff.parent, head: diff.merge, files: diff.files.map((entry) => ("patch" in entry ? file(entry.path, entry.status, entry.patch) : { path: shown.name(entry.path), status: entry.status, withheld: entry.withheld })) };
397
+ const diff = await runDiff(learningOf(store, row.agentId), runDiffKey(runId, kept?.round));
398
+ if (!diff || diff.merge !== end.merged)
399
+ throw new ApiError("not_found", "the run's merge is not in its agent's learning");
400
+ return { base: diff.parent, head: diff.merge, files: diff.files.map((entry) => file(entry.path, entry.status, entry.patch)) };
541
401
  }
542
402
  return { base: start?.seed ?? null, head: null, files: [] };
543
403
  }
544
- /** `diff` with each file of a learned workflow whose text at its parent a purged run wrote (purgeGate), its whole
545
- * `workflows/<name>/` folder (README.md too), diffed against nothing, so its patch never shows that text: its text at
546
- * the merge as an added file, or, deleted there, no file. One more read-only exec when the merge changed such a file
547
- * (snapshotAt), and one per file served so. */
548
- async function againstPurged(ws, diff, store) {
549
- const replaced = (path, status) => (status === "added" ? undefined : folderOf(path));
550
- if (!diff.files.some(({ path, status }) => replaced(path, status)))
551
- return diff;
552
- const purged = (await purgeGate(await snapshotAt(ws, diff.parent), store)).workflows;
553
- const files = [];
554
- for (const entry of diff.files) {
555
- const name = replaced(entry.path, entry.status);
556
- if (name === undefined || !purged.has(name))
557
- files.push(entry);
558
- else if (entry.status === "modified") {
559
- const text = (await textsAt(ws, diff.merge, [entry.path]))?.[entry.path];
560
- if (text !== undefined)
561
- files.push({ path: entry.path, status: "added", patch: addedPatch(text) });
562
- }
563
- }
564
- return { ...diff, files };
565
- }
566
- /** `text` as git's unified diff writes an added file, its hunk alone (as the learning script keeps a patch): no hunk for
567
- * an empty file, a one-line hunk's count left out, and a last line with no newline marked so. */
568
- function addedPatch(text) {
569
- if (text === "")
570
- return "";
571
- const lines = text.split("\n");
572
- const ended = text.endsWith("\n");
573
- if (ended)
574
- lines.pop();
575
- return `@@ -0,0 +1${lines.length === 1 ? "" : `,${lines.length}`} @@\n${lines.map((line) => `+${line}\n`).join("")}${ended ? "" : "\\n"}`;
576
- }