@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
@@ -0,0 +1,122 @@
1
+ /** The most show paths, and the most segments of one. */
2
+ export const MAX_SHOW_PATHS = 8;
3
+ export const MAX_SHOW_SEGMENTS = 6;
4
+ /** The longest shown string, in characters. */
5
+ export const SHOWN_CHARS = 200;
6
+ /** A folder segment: no dot first (no `..`, no hidden folder), nothing that names another place. */
7
+ const FOLDER_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
8
+ /** A show path's segment: a key's name, an array's index, or -1 (its last item). */
9
+ const SHOW_SEGMENT = /^(?:[A-Za-z_$][A-Za-z0-9_$-]{0,63}|0|[1-9][0-9]{0,8}|-1)$/;
10
+ const FOLDER_WORDS = "1 to 3 segments joined by /, each letters, digits, _, - or . and never starting with a dot (no .., no hidden folder)";
11
+ const PATH_WORDS = `a path of 1 to ${MAX_SHOW_SEGMENTS} segments joined by ., each a key (a letter, _ or $ first), an index (0, 1, ...) or -1 (the last item)`;
12
+ const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13
+ /** The issues of `given` as a file setting, its fields under `at`: none when it is one. */
14
+ export function fileIssues(given, at) {
15
+ if (!isPlain(given) || Object.keys(given).some((key) => key !== "folder" && key !== "show") || given.folder === undefined || given.show === undefined) {
16
+ return [{ field: at, reason: "wrong_type", message: `${at} is {folder, show}: the folder of the run's files each answer of the tool is filed in, whole, and the paths of it the tool's result shows (at most ${MAX_SHOW_PATHS}); the result shows no other value of it` }];
17
+ }
18
+ const issues = [];
19
+ const folder = given.folder;
20
+ const segments = typeof folder === "string" ? folder.split("/") : [];
21
+ if (!(segments.length >= 1 && segments.length <= 3 && segments.every((segment) => FOLDER_SEGMENT.test(segment))))
22
+ issues.push({ field: `${at}.folder`, reason: "not_an_option", message: `${at}.folder is a folder in the run's files: ${FOLDER_WORDS}` });
23
+ const show = given.show;
24
+ if (!Array.isArray(show) || show.length > MAX_SHOW_PATHS) {
25
+ issues.push({ field: `${at}.show`, reason: "not_an_option", message: `${at}.show is a list of at most ${MAX_SHOW_PATHS} paths, each ${PATH_WORDS}` });
26
+ return issues;
27
+ }
28
+ show.forEach((path, i) => {
29
+ const parts = typeof path === "string" ? path.split(".") : [];
30
+ if (!(parts.length >= 1 && parts.length <= MAX_SHOW_SEGMENTS && parts.every((part) => SHOW_SEGMENT.test(part))))
31
+ issues.push({ field: `${at}.show[${i}]`, reason: "not_an_option", message: `${at}.show[${i}] ${JSON.stringify(path)} is ${PATH_WORDS}` });
32
+ });
33
+ const twice = show.find((path, i) => show.indexOf(path) !== i);
34
+ if (twice !== undefined)
35
+ issues.push({ field: `${at}.show`, reason: "not_an_option", message: `${at}.show names ${String(twice)} twice` });
36
+ return issues;
37
+ }
38
+ /** A stored file setting that does not read (a rule tightened since it was written, a runner older than the server that
39
+ * wrote it): every call of its tool is refused, never answered unfiled (mcp-gateway.ts unsendable). */
40
+ export const UNREADABLE = "unreadable";
41
+ /** The file setting of `server`'s `tool` in an agent's tool settings as its revision keeps them (body.toolSettings):
42
+ * undefined when it has none (the tool answers the model as it always has), UNREADABLE when it has one that does not
43
+ * read. */
44
+ export function filedBy(toolSettings) {
45
+ return (server, tool) => {
46
+ const key = `mcp:${server}/${tool}`;
47
+ const setting = isPlain(toolSettings) && Object.hasOwn(toolSettings, key) ? toolSettings[key] : undefined;
48
+ const file = isPlain(setting) ? setting.file : undefined;
49
+ if (file === undefined)
50
+ return undefined;
51
+ if (fileIssues(file, "file").length)
52
+ return UNREADABLE;
53
+ const { folder, show } = file;
54
+ return { folder, show: [...show] };
55
+ };
56
+ }
57
+ /** The value at `path` in `value`, as the model reads it: a scalar (a string cut at SHOWN_CHARS, … marking the cut),
58
+ * else null (absent, or an object or array). */
59
+ export function shownAt(value, path) {
60
+ let at = value;
61
+ for (const part of path.split(".")) {
62
+ if (Array.isArray(at))
63
+ at = part === "-1" ? at[at.length - 1] : /^\d+$/.test(part) ? at[Number(part)] : undefined;
64
+ else if (isPlain(at))
65
+ at = Object.hasOwn(at, part) ? at[part] : undefined;
66
+ else
67
+ at = undefined;
68
+ }
69
+ if (typeof at === "string") {
70
+ const chars = Array.from(at);
71
+ return chars.length > SHOWN_CHARS ? `${chars.slice(0, SHOWN_CHARS).join("")}…` : at;
72
+ }
73
+ return typeof at === "number" || typeof at === "boolean" ? at : null;
74
+ }
75
+ /** The most keys of one object the shape names, and the longest shape. */
76
+ const SHAPE_KEYS = 40;
77
+ const SHAPE_CHARS = 2_000;
78
+ /** A key the shape names: a short name. Any other key (an email, a person's name, an id) can be data, so it is counted,
79
+ * never named. */
80
+ const SHAPE_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,31}$/;
81
+ /** `value`'s shape: types, each array's length and what it holds, an object's keys that are short names while `depth`
82
+ * is under 2 (the rest counted); never a value. */
83
+ export function shapeOf(value, depth = 0) {
84
+ if (value === null)
85
+ return "null";
86
+ if (Array.isArray(value)) {
87
+ const kinds = new Set(value.map((item) => (item === null ? "null" : Array.isArray(item) ? "array" : typeof item)));
88
+ const kind = kinds.size === 1 ? [...kinds][0] : "item";
89
+ return `[${value.length} ${kind}${value.length === 1 ? "" : "s"}]`;
90
+ }
91
+ if (isPlain(value)) {
92
+ if (depth >= 2)
93
+ return "object";
94
+ const keys = Object.keys(value);
95
+ const named = keys.filter((key) => SHAPE_KEY.test(key)).slice(0, SHAPE_KEYS).map((key) => `${JSON.stringify(key)}: ${shapeOf(value[key], depth + 1)}`);
96
+ const rest = keys.length - named.length;
97
+ const counted = rest ? `… ${rest} ${named.length ? "more " : ""}key${rest === 1 ? "" : "s"}` : "";
98
+ return `{${[...named, ...(counted ? [counted] : [])].join(", ")}}`;
99
+ }
100
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? typeof value : "unknown";
101
+ }
102
+ /** The tool's result for an answer filed at `path` (in the run's files): its bytes, where it is, the values `show`
103
+ * names, and its shape. */
104
+ export function filedSummary(tool, text, path, show) {
105
+ let value;
106
+ let json = true;
107
+ try {
108
+ value = JSON.parse(text);
109
+ }
110
+ catch {
111
+ json = false;
112
+ }
113
+ const shown = `{${show.map((one) => `${JSON.stringify(one)}: ${JSON.stringify(json ? shownAt(value, one) : null)}`).join(", ")}}`;
114
+ const shape = json ? shapeOf(value) : "text, not JSON";
115
+ return [
116
+ `${tool} answered ${Buffer.byteLength(text, "utf8").toLocaleString("en-US")} bytes, filed whole at ${path} for the skill's code; its values are not shown here (the agent's setting files this tool's answers); only these are:`,
117
+ shown,
118
+ `Shape: ${shape.length > SHAPE_CHARS ? `${shape.slice(0, SHAPE_CHARS)}…` : shape}`,
119
+ ].join("\n");
120
+ }
121
+ /** The model's text when an answer could not be filed: none of it, the Workspace's words why. */
122
+ export const unfiledSummary = (tool, text, folder, why) => `${tool} answered ${Buffer.byteLength(text, "utf8").toLocaleString("en-US")} bytes, which could not be filed in ${folder}/ (${why}). The agent's setting files this tool's answers, so none of it is shown here.`;
@@ -114,8 +114,7 @@ export declare class HarnessKeysOverStore {
114
114
  private kept;
115
115
  /** GET: `recipe`'s keys, each by name, whether saved for it and when it changed, and those to enter again: never a value. */
116
116
  view(recipe: PlanRecipe): HarnessKeysView;
117
- /** Each id with keys saved whose recipe this server does not name, sorted: capabilities' harness_keys.kept, so the
118
- * console offers the page that removes them. */
117
+ /** Each id with keys saved whose recipe this server does not name, sorted: the page lists them (list), to remove. */
119
118
  unnamed(): string[];
120
119
  /** GET /settings/harness-keys: every plan-billed recipe this server is started with, its keys by name; then each id
121
120
  * with keys saved whose recipe it no longer names (unnamed), its keys kept. */
@@ -253,8 +253,7 @@ export class HarnessKeysOverStore {
253
253
  });
254
254
  return { id: recipe.id, label: recipe.label, named: true, keys, kept: this.kept(recipe.id, recipe.keys), ready: this.saved(recipe), reenter };
255
255
  }
256
- /** Each id with keys saved whose recipe this server does not name, sorted: capabilities' harness_keys.kept, so the
257
- * console offers the page that removes them. */
256
+ /** Each id with keys saved whose recipe this server does not name, sorted: the page lists them (list), to remove. */
258
257
  unnamed() {
259
258
  const named = new Set(this.recipes.map((recipe) => recipe.id));
260
259
  return [...new Set([...this.current.keys()].flatMap((row) => rowParts(row)?.harness ?? []))].filter((id) => !named.has(id)).sort();
@@ -268,6 +268,10 @@ export declare const harnessModulesEnv: (names: readonly string[], data: string)
268
268
  /** The ids of the harnesses `env`'s table lists, in its order: the built-in ones (pi first), then those its modules add;
269
269
  * not one its entry hides on `env` (HarnessEntry.hidden: Goose until it is installed). */
270
270
  export declare const harnessIds: (env: NodeJS.ProcessEnv) => readonly string[];
271
+ /** The ids capabilities offer (harness.ts harnessOffers), in the table's order: harnessIds', and each recipe the server is
272
+ * started with though its entry hides it (not installed, not checked, keys not saved): its owner named it, so it is
273
+ * offered as not available, with why and the command that fixes it, never left out. */
274
+ export declare const offeredIds: (env: NodeJS.ProcessEnv) => readonly string[];
271
275
  /** The ids of every harness `env`'s table has, hidden ones too: those a definition may name (a save warns of a hidden one,
272
276
  * a run is refused with why). */
273
277
  export declare const tableIds: (env: NodeJS.ProcessEnv) => readonly string[];
@@ -580,6 +580,10 @@ export const harnessModulesEnv = (names, data) => (names.length ? { [HARNESS_MOD
580
580
  /** The ids of the harnesses `env`'s table lists, in its order: the built-in ones (pi first), then those its modules add;
581
581
  * not one its entry hides on `env` (HarnessEntry.hidden: Goose until it is installed). */
582
582
  export const harnessIds = (env) => Object.entries(harnessTable(env)).filter(([, entry]) => entry.hidden?.(env) === undefined).map(([id]) => id);
583
+ /** The ids capabilities offer (harness.ts harnessOffers), in the table's order: harnessIds', and each recipe the server is
584
+ * started with though its entry hides it (not installed, not checked, keys not saved): its owner named it, so it is
585
+ * offered as not available, with why and the command that fixes it, never left out. */
586
+ export const offeredIds = (env) => Object.entries(harnessTable(env)).filter(([, entry]) => entry.hidden?.(env) === undefined || madeByRecipe.has(entry)).map(([id]) => id);
583
587
  /** The ids of every harness `env`'s table has, hidden ones too: those a definition may name (a save warns of a hidden one,
584
588
  * a run is refused with why). */
585
589
  export const tableIds = (env) => Object.keys(harnessTable(env));
package/dist/harness.js CHANGED
@@ -41,11 +41,15 @@ export function harnessOffers(env) {
41
41
  const { hostMemory, neverFits } = await import("./host.js");
42
42
  const memory = hostMemory();
43
43
  const { harnessInstalled } = await import("./adapters.js");
44
- const { harnessIds, harnessOf, NATIVE_PROMISES } = await import("./harness-table.js");
45
- const probed = await Promise.all(harnessIds(env).map(async (id) => {
44
+ const { harnessOf, NATIVE_PROMISES, offeredIds } = await import("./harness-table.js");
45
+ const probed = await Promise.all(offeredIds(env).map(async (id) => {
46
46
  const entry = harnessOf(env, id);
47
47
  const card = entry.card?.(env);
48
48
  const named = { label: entry.label, promises: entry.promises ?? NATIVE_PROMISES, ...(card ? { card } : {}) };
49
+ // A recipe the server is started with that its entry hides (offeredIds): not available, with why.
50
+ const hidden = entry.hidden?.(env);
51
+ if (hidden !== undefined)
52
+ return { id, ...named, available: false, steer: entry.steer, reason: hidden };
49
53
  // The start's probe: these offers hold until a restart (server.ts), so the reason says so where installing fixes it.
50
54
  // Claude Code not installed yet says so (its install probes the offers again).
51
55
  const firstUse = entry.installs && !(await harnessInstalled(entry, env)) ? { installs: "on_first_use" } : {};
@@ -7,7 +7,7 @@
7
7
  // Before anything loads node:sqlite, as in the server's own thread: its ExperimentalWarning is not the server's to print.
8
8
  import "./quiet-sqlite-warning.js";
9
9
  import { parentPort, workerData } from "node:worker_threads";
10
- import { candidatesOf, ownSecrets, planImport, runImport, sessionsOf } from "./import.js";
10
+ import { candidatesOf, ownSecrets, planImport, runImport, sessionsOf, wrappedReading } from "./import.js";
11
11
  import { importStoreProxy } from "./import-proxy.js";
12
12
  import { catalogPrices } from "./model.js";
13
13
  import { toolKeysOverStore } from "./tool-keys-store.js";
@@ -27,7 +27,7 @@ const answer = async () => {
27
27
  if (task === "wrapped") {
28
28
  const failures = [];
29
29
  const { wrappedHome } = await import("@parcha/agentrun-import");
30
- return { wrapped: await wrappedHome(home, year, { failures, catalog: await catalogPrices() }), unread: failures.length };
30
+ return { wrapped: await wrappedHome(home, year, { failures, catalog: await catalogPrices(), ...wrappedReading() }), unread: failures.length };
31
31
  }
32
32
  if (task === "plan") {
33
33
  // A count keeps no transcript: no key scan (a whole history read through secretlint at every start).
package/dist/import.d.ts CHANGED
@@ -44,6 +44,15 @@ export declare const MAX_SESSION_BYTES: number;
44
44
  export declare const MAX_RUN_BYTES: number;
45
45
  /** The most projects a count names for the owner to choose from: the latest active. */
46
46
  export declare const MAX_CANDIDATES = 500;
47
+ /** The heap of the worker that counts or imports this machine's sessions, or reads a year of them for Wrapped. A run is
48
+ * read whole, at most MAX_RUN_BYTES of files, which this holds several times over. */
49
+ export declare const IMPORT_HEAP_MB = 2048;
50
+ /** How the import worker reads a year of the home for Wrapped (wrappedHome): on the cores less one, at most
51
+ * WRAPPED_THREADS, and with a quarter of the worker's heap for the reads waiting, which it holds. */
52
+ export declare function wrappedReading(cores?: number): {
53
+ threads: number;
54
+ readAhead: number;
55
+ };
47
56
  /** The most of one instructions or skill file read, and of one agent's skill files together. */
48
57
  export declare const MAX_FILE_BYTES: number;
49
58
  export declare const MAX_SKILL_BYTES: number;
package/dist/import.js CHANGED
@@ -7,7 +7,7 @@
7
7
  import { createHash, randomUUID } from "node:crypto";
8
8
  import { existsSync } from "node:fs";
9
9
  import { lstat, open, realpath, stat } from "node:fs/promises";
10
- import { homedir, tmpdir } from "node:os";
10
+ import { availableParallelism, homedir, tmpdir } from "node:os";
11
11
  import { basename, join, sep } from "node:path";
12
12
  import { parseArgs } from "node:util";
13
13
  import { BACKGROUND_CONTEXT as ctx } from "@earendil-works/chord/context";
@@ -246,6 +246,16 @@ export const MAX_SESSION_BYTES = 256 * 1024 * 1024;
246
246
  export const MAX_RUN_BYTES = MAX_SESSION_BYTES;
247
247
  /** The most projects a count names for the owner to choose from: the latest active. */
248
248
  export const MAX_CANDIDATES = 500;
249
+ /** The heap of the worker that counts or imports this machine's sessions, or reads a year of them for Wrapped. A run is
250
+ * read whole, at most MAX_RUN_BYTES of files, which this holds several times over. */
251
+ export const IMPORT_HEAP_MB = 2048;
252
+ /** The most threads Wrapped's read of the home starts. */
253
+ const WRAPPED_THREADS = 8;
254
+ /** How the import worker reads a year of the home for Wrapped (wrappedHome): on the cores less one, at most
255
+ * WRAPPED_THREADS, and with a quarter of the worker's heap for the reads waiting, which it holds. */
256
+ export function wrappedReading(cores = availableParallelism()) {
257
+ return { threads: Math.max(1, Math.min(cores - 1, WRAPPED_THREADS)), readAhead: (IMPORT_HEAP_MB / 4) * 2 ** 20 };
258
+ }
249
259
  /** The most of one instructions or skill file read, and of one agent's skill files together. */
250
260
  export const MAX_FILE_BYTES = 256 * 1024;
251
261
  export const MAX_SKILL_BYTES = 1024 * 1024;
@@ -9,6 +9,11 @@ export type RunKey = {
9
9
  /** The key `harness`'s run of model `ref` (the revision's; none, this host's default for the harness) sends, by the route
10
10
  * its wire takes (provider.ts; pi's, model.ts); undefined where it is not a model key this server names. */
11
11
  export declare function runKeyOf(env: NodeJS.ProcessEnv, harness?: string, ref?: string): RunKey | undefined;
12
+ /** How many texts redacted and withheldWhole have read in this process: a test reads it to see a read of a run's rows
13
+ * cut only the texts an earlier read had not (store-reads/journal.ts rowCutsOnce). */
14
+ export declare const cutPasses: {
15
+ count: number;
16
+ };
12
17
  /** `text`, a run's error as serve shows it, with no held secret in it: the one rule learning's checker uses
13
18
  * (learn/secrets.ts redactSecrets: each value as written, JSON-escaped, base64 at each offset, hex and percent-encoded,
14
19
  * and secret-shaped text), over `secrets`, the values the server holds and handed its run.
@@ -7,7 +7,7 @@ import { harnessOf } from "./harness-table.js";
7
7
  import { cutSecrets, endsInScheme, foldsHeld, redactSecrets, secretShapes, valueLeft, valueMatcher } from "./learn/secrets.js";
8
8
  import { hostModel, MODEL_KEYS } from "./model.js";
9
9
  import { modelWire, openRouterOnly, WIRES } from "./provider.js";
10
- import { entityAt, jsonEscapeAt, privateKeyEnd, scanned, squeeze } from "./redact/match.js";
10
+ import { entityAt, jsonEscapeAt, privateKeyEnd, pythonEscapeAt, scanned, squeeze } from "./redact/match.js";
11
11
  import { savedGatewayIn } from "./model-gateway.js";
12
12
  const row = (id) => {
13
13
  const found = MODEL_KEYS.find((r) => r.id === id);
@@ -49,6 +49,9 @@ function detailOf(rest) {
49
49
  const text = rest.replace(/^[\s:.-]*(unauthorized\b)?[\s:.-]*/i, "").replace(/,?\s*url:.*$/is, "").trim();
50
50
  return (text.split(/(?<=[.!?])\s/)[0] ?? "").slice(0, 200).replace(/[.\s]+$/, "");
51
51
  }
52
+ /** How many texts redacted and withheldWhole have read in this process: a test reads it to see a read of a run's rows
53
+ * cut only the texts an earlier read had not (store-reads/journal.ts rowCutsOnce). */
54
+ export const cutPasses = { count: 0 };
52
55
  /** The most of a run's error or a tool's output serve ever shows: a Timeline row's text, cut at 2000 characters
53
56
  * (`CAPS.text` in timeline/; a summary and a tool result's preview at 500), which the error box reads too. */
54
57
  const SHOWN = 2000;
@@ -62,6 +65,7 @@ const SHOWN = 2000;
62
65
  * error costs no more to redact than a short one, whatever it holds. `shown`: a head of another length, for a reader
63
66
  * that is shown more. */
64
67
  export function redacted(text, secrets, shown = SHOWN) {
68
+ cutPasses.count++;
65
69
  const longest = secrets.reduce((most, value) => Math.max(most, value.length), 0);
66
70
  const window = shown + 6 * longest + 16;
67
71
  if (text.length <= window)
@@ -126,6 +130,7 @@ export function redactedCall(text, secrets, shown, show = (piece) => piece) {
126
130
  * own finds, so a value read wholly inside one of them is taken there (sdk/runs.ts withheldParts: a part withheld by
127
131
  * itself). */
128
132
  export function withheldWhole(text, secrets, held = []) {
133
+ cutPasses.count++;
129
134
  return redactSecrets(text, secrets, Number.POSITIVE_INFINITY, held) === "[redacted]";
130
135
  }
131
136
  /** Whether the text a reader is about to be shown (`shown`, what the caller returns) holds a held value, or the joined
@@ -240,15 +245,16 @@ function inPieces(text, secrets, enough = Number.POSITIVE_INFINITY, show = (piec
240
245
  }
241
246
  /** text from `from` on, as far as `count` characters the matcher sees (all of it, if it holds fewer), each run of
242
247
  * whitespace in it one space. The matcher reads "+" as a space and decodes percent-encoded bytes, JSON's escapes (one
243
- * level and two, as the JSON view reads them) and HTML's numeric character references, so a "+", an encoded byte, an
244
- * escape and a reference that decode to whitespace
245
- * count no more than whitespace does, and any other escape counts as what the view keeps of the character it decodes
246
- * to. A character that renders as nothing (a zero-width space, a soft hyphen) or a combining mark counts as nothing
247
- * too: the views drop it. So does a quote or JSON's punctuation ("{", "}", "[", "]", ",", ":"), which the join view
248
- * drops between a text's strings, and, with `fold` (a held value folds: learn/secrets.ts foldsHeld), a separator ("-",
249
- * "_", ":", "."), which the fold view drops. Padding of any of them never hides the rest of a value split before it.
250
- * Undefined, so the caller withholds the text, when that takes more than a piece of text (a run of whitespace counted
251
- * as one): no redaction pass reads more than a piece. */
248
+ * level and two, as the JSON view reads them), Python's ("\'", "\x" and two hex digits, as the view that reads a
249
+ * single-quoted dict through them does) and HTML's character references (named and numeric), so a "+", an encoded
250
+ * byte, an escape and a reference that decode to whitespace count no more than whitespace does, and any other escape
251
+ * counts as what the view keeps of the character it decodes to. A character that renders as nothing (a zero-width
252
+ * space, a soft hyphen) or a combining mark counts as nothing too: the views drop it. So does a quote, an apostrophe
253
+ * or JSON's punctuation ("{", "}", "[", "]", ",", ":"), which the join views drop between a text's strings, and, with
254
+ * `fold` (a held value folds: learn/secrets.ts foldsHeld), a separator ("-", "_", ":", "."), which the fold view
255
+ * drops. Padding of any of them never hides the rest of a value split before it. Undefined, so the caller withholds
256
+ * the text, when that takes more than a piece of text (a run of whitespace counted as one): no redaction pass reads
257
+ * more than a piece. */
252
258
  function peek(text, from, count, fold) {
253
259
  const read = visible(text, from, count, text.length, fold);
254
260
  return read.span > ANSWER_PIECE ? undefined : read.parts.join("");
@@ -313,11 +319,14 @@ function visible(text, from, count, to, fold) {
313
319
  }
314
320
  return { parts, found, span };
315
321
  }
316
- /** The character text[at] starts, as the views read it: a JSON escape's (jsonEscapeAt) or a character reference's
317
- * (entityAt), else the UTF-16 unit itself (`raw`), and where it ends. */
322
+ /** The character text[at] starts, as the views read it: one of Python's escapes (pythonEscapeAt, at either level:
323
+ * "\x20" and "\\x20" are a space), else a JSON escape's (jsonEscapeAt), or a character reference's (entityAt), else
324
+ * the UTF-16 unit itself (`raw`), and where it ends. Python's first: where JSON's escapes read "\\x20" as a backslash
325
+ * and three characters, the view that reads Python's twice reads a space; counting less only reads further. */
318
326
  function charAt(text, at) {
319
327
  let escape;
320
- if ((text[at] === "\\" && (escape = jsonEscapeAt(text, at)) !== undefined) || (text[at] === "&" && (escape = entityAt(text, at)) !== undefined))
328
+ if ((text[at] === "\\" && ((escape = pythonEscapeAt(text, at)) !== undefined || (escape = jsonEscapeAt(text, at)) !== undefined)) ||
329
+ (text[at] === "&" && (escape = entityAt(text, at)) !== undefined))
321
330
  return { ...escape, raw: false };
322
331
  return { char: text[at], end: at + 1, raw: true };
323
332
  }
@@ -325,8 +334,9 @@ const HIGH = (char) => char.length === 1 && char.charCodeAt(0) >= 0xd800 && char
325
334
  const LOW = (char) => char.length === 1 && char.charCodeAt(0) >= 0xdc00 && char.charCodeAt(0) <= 0xdfff;
326
335
  const SPACES = /\s+/y;
327
336
  const HEX_PAIR = /^[0-9A-Fa-f]{2}$/;
328
- /** What every view drops between a text's strings: a quote and JSON's punctuation (the join view). */
329
- const JOIN_DROPS = new Set(['"', "{", "}", "[", "]", ",", ":"]);
337
+ /** What every view drops between a text's strings: a quote, an apostrophe (the join of single-quoted strings) and JSON's
338
+ * punctuation (the join view). */
339
+ const JOIN_DROPS = new Set(['"', "'", "{", "}", "[", "]", ",", ":"]);
330
340
  /** What the fold view drops: the separators of a hex identifier. */
331
341
  const FOLD_DROPS = new Set(["-", "_", ":", "."]);
332
342
  /** How many characters the views keep of `chars` at the least (peek): squeezed, less each the join view drops, and,
@@ -1,14 +1,12 @@
1
- import type { Workspace } from "../workspace/index.js";
1
+ import { type Store } from "../store/store.js";
2
2
  import type { AuditLoop } from "../learning-setting.js";
3
3
  import type { RunLaunch } from "../run-launch.js";
4
- import { AUDITS_FILE, type FolderChange, type FolderRead } from "./folder.js";
5
- import { type CostStop, type PromotionRecord, type Refused, type ServingState } from "./promote.js";
6
- export { AUDITS_FILE };
7
- /** The newest rows the ledger keeps: twice the widest window a definition may set (AUDIT_MAX), and a file well under the
8
- * folder's file cap (a line is a few hundred bytes); with them, the started lines of theirs, and every open one. */
9
- export declare const AUDITS_KEPT = 2000;
4
+ import { type CostStop, type PromotionRecord, type ServingState } from "./promote.js";
10
5
  /** What every shadow run's id starts with: its served run's id follows (shadowRunId). No server-minted id starts so. */
11
6
  export declare const SHADOW_PREFIX = "audit.";
7
+ /** The newest rows the ledger keeps: twice the widest window a definition may set (AUDIT_MAX); with them, the started
8
+ * lines of theirs, and every open one (addAuditLines trims it in the write that adds). */
9
+ export declare const AUDITS_KEPT = 2000;
12
10
  /** One finished audit. `run`: the served run; `shadow_run`: its shadow (null for a grade's row, or one never started);
13
11
  * `workflow` at `digest` served it, under the promotion begun at `promoted_at` (learn/promote.ts promotionStartOf: the
14
12
  * one serving when its shadow started, or at the grade; null: none); `agreed`: whether the served answer is right
@@ -75,22 +73,22 @@ export declare const auditsOffWords: (tool: string) => string;
75
73
  * uploaded files. A triggered run's context (a GitHub event's checkout, the thread it answers on) is never rebuilt for a
76
74
  * shadow, which could answer there too: its served run is not auditable (its record's metrics.not_auditable). */
77
75
  export declare const auditableLaunch: (launch: Pick<RunLaunch, "trigger" | "inputOrigin" | "files">) => boolean;
78
- /** The lines of a ledger's text, in the order written; one out of shape is skipped. */
79
- export declare function parseLedger(text: string): LedgerLine[];
80
- /** The ledger's text for `lines`: from the AUDITS_KEPT-th newest row on, and every open started line before it. */
81
- export declare function auditsText(lines: readonly LedgerLine[]): string;
82
- /** The ledger's lines on the folder's main as `folder` reads it (none before the first). */
83
- export declare function ledgerOf(folder: FolderRead): Promise<LedgerLine[]>;
84
- /** The ledger's rows on the folder's main: its finished audits, oldest first. */
85
- export declare const readAudits: (ws: Workspace) => Promise<AuditRow[]>;
76
+ /** The store's learning records, as the ledger is read and written. */
77
+ export type AuditRecords = Pick<Store["learning"], "records" | "changeRecords">;
78
+ /** The agent's ledger, in the order written (none before the first line). */
79
+ export declare const ledgerOf: (rows: Pick<AuditRecords, "records">, agentId: string) => Promise<LedgerLine[]>;
80
+ /** The ledger's rows: its finished audits, oldest first. */
81
+ export declare const readAudits: (rows: Pick<AuditRecords, "records">, agentId: string) => Promise<AuditRow[]>;
86
82
  /** A line's place in the ledger: one per served run and source (a started line's, its shadow's row, a grade's row). */
87
83
  export declare const lineKey: (line: LedgerLine) => string;
88
- /** The change that appends `lines` to the ledger `before` (none when each is there already: lineKey), with the lines it
89
- * appends. */
90
- export declare function auditChange(before: readonly LedgerLine[], lines: readonly LedgerLine[]): {
84
+ /** Appends `lines` to the ledger, each not there yet (lineKey), in one transaction: `replace`, a line whose key is there
85
+ * takes the place of the one there (a grade's row of a run graded again). The ledger after (`all`) with the lines it
86
+ * appended. A line of a digest no version of its workflow holds (a run's purge took it since the line was read), or of a
87
+ * run that was purged, is never appended (Store.learning changeRecords refuses it): the others are. */
88
+ export declare function addAuditLines(rows: AuditRecords, agentId: string, lines: readonly LedgerLine[], replace?: boolean): Promise<{
89
+ all: LedgerLine[];
91
90
  added: LedgerLine[];
92
- change?: FolderChange;
93
- };
91
+ }>;
94
92
  /** The rows the hold rule counts for `workflow` at `digest` under the promotion begun at `promotedAt` (learn/promote.ts
95
93
  * promotionStartOf; none counted for null): those with a verdict, the newest `hold_window` of them. A served run an
96
94
  * owner graded is counted by its grade's row alone: the grade is its known answer, as it is the check's, so its
@@ -112,7 +110,7 @@ export declare function auditLineOf(rows: readonly AuditRow[], workflow: string,
112
110
  /** What the promotions read says of each learned workflow beside what serves (learn/promote.ts servingOf, in its order):
113
111
  * `state` (learn/promote.ts servingStateOf with the money rule's decision, `costStop`: the word the learning view's
114
112
  * `status` says too), its newest decided check's numbers, and its audit line over the rows of the serving (else the
115
- * newest) revision's newest promotion (the ones the hold rule counts). Its champions skip `refused` (championOf). */
113
+ * newest) revision's newest promotion (the ones the hold rule counts). */
116
114
  export type ServingLine = {
117
115
  readonly state: ServingState;
118
116
  readonly check: {
@@ -123,4 +121,4 @@ export type ServingLine = {
123
121
  } | null;
124
122
  readonly audit: AuditLine | null;
125
123
  };
126
- export declare function servingLinesOf(records: readonly PromotionRecord[], rows: readonly AuditRow[], loop: Pick<AuditLoop, "hold_window" | "hold_disagree">, costStop: CostStop, refused?: Refused): ServingLine[];
124
+ export declare function servingLinesOf(records: readonly PromotionRecord[], rows: readonly AuditRow[], loop: Pick<AuditLoop, "hold_window" | "hold_disagree">, costStop: CostStop): ServingLine[];
@@ -1,5 +1,5 @@
1
- // The audit ledger: audits.jsonl at the top of an agent's git learning folder, one JSON line each, appended by the host
2
- // alone (runner/audit.ts, and the server for an owner's grade). A `started` line is a shadow audit begun (written before
1
+ // The audit ledger: the agent's audit records (Store.learning records of kind audit), one line each, appended by the
2
+ // host alone (runner/audit.ts, and the server for an owner's grade). A `started` line is a shadow audit begun (written before
3
3
  // its shadow run is created); a row is one finished audit of a run a promoted learned workflow served first: its shadow
4
4
  // run's answer (the same agent on the same input, learning off) against the served one (source `shadow`, the started
5
5
  // line's result), or an owner's grade of the served run (source `grade`: the served answer against the grade's known
@@ -10,15 +10,14 @@
10
10
  // run cost.
11
11
  import { createHash } from "node:crypto";
12
12
  import { COMPUTER_TOOLS } from "@parcha/agentrun-kernel/kernel";
13
+ import { LearningRecordRefused } from "../store/store.js";
13
14
  import { pinAnnotations, toolClassOf, toolWord } from "./replay-calls.js";
14
- import { AUDITS_FILE, readLearning } from "./folder.js";
15
15
  import { promotionStartOf, servingOf, servingStateOf } from "./promote.js";
16
- export { AUDITS_FILE };
17
- /** The newest rows the ledger keeps: twice the widest window a definition may set (AUDIT_MAX), and a file well under the
18
- * folder's file cap (a line is a few hundred bytes); with them, the started lines of theirs, and every open one. */
19
- export const AUDITS_KEPT = 2_000;
20
16
  /** What every shadow run's id starts with: its served run's id follows (shadowRunId). No server-minted id starts so. */
21
17
  export const SHADOW_PREFIX = "audit.";
18
+ /** The newest rows the ledger keeps: twice the widest window a definition may set (AUDIT_MAX); with them, the started
19
+ * lines of theirs, and every open one (addAuditLines trims it in the write that adds). */
20
+ export const AUDITS_KEPT = 2_000;
22
21
  /** The rows of `lines` (the finished audits), oldest first. */
23
22
  export const rowsOf = (lines) => lines.filter((line) => line.source !== "started");
24
23
  /** The started lines of `lines` with no result row yet: the audits settlement still owes, oldest first. */
@@ -76,57 +75,75 @@ const isLine = (value) => {
76
75
  const noVerdictOf = (line) => line.agreed !== null ? {} : line.skipped === "no allowance" ? { skipped: "no allowance" } : line.parked === true ? { parked: true } : {};
77
76
  /** A line's turn (AuditRow.turn), as written: none when it has none. */
78
77
  const turnOf = (line) => (line.turn === undefined ? {} : { turn: line.turn });
79
- /** The lines of a ledger's text, in the order written; one out of shape is skipped. */
80
- export function parseLedger(text) {
81
- const out = [];
82
- for (const raw of text.split("\n")) {
83
- if (!raw.trim())
84
- continue;
78
+ /** A ledger line as read back, or undefined for one out of shape. */
79
+ function lineOf(value) {
80
+ if (!isLine(value))
81
+ return undefined;
82
+ const { run, workflow, digest, promoted_at, at } = value;
83
+ return value.source === "started"
84
+ ? { source: "started", run, shadow_run: value.shadow_run, workflow, digest, promoted_at, ...turnOf(value), at }
85
+ : { run, shadow_run: value.shadow_run, workflow, digest, promoted_at, source: value.source, agreed: value.agreed, served_cost: value.served_cost, shadow_cost: value.shadow_cost, ...turnOf(value), ...noVerdictOf(value), at };
86
+ }
87
+ const linesOf = (records) => records.flatMap((one) => { const line = lineOf(one.data); return line ? [line] : []; });
88
+ /** A line's record: its served run, so the run's purge deletes it. */
89
+ const lineWrite = (line) => ({ runId: line.run, workflow: line.workflow, digest: line.digest, data: line });
90
+ /** The agent's ledger, in the order written (none before the first line). */
91
+ export const ledgerOf = async (rows, agentId) => linesOf(await rows.records(agentId, "audit"));
92
+ /** The ledger's rows: its finished audits, oldest first. */
93
+ export const readAudits = async (rows, agentId) => rowsOf(await ledgerOf(rows, agentId));
94
+ /** A line's place in the ledger: one per served run and source (a started line's, its shadow's row, a grade's row). */
95
+ export const lineKey = (line) => `${line.source}:${line.run}`;
96
+ /** Appends `lines` to the ledger, each not there yet (lineKey), in one transaction: `replace`, a line whose key is there
97
+ * takes the place of the one there (a grade's row of a run graded again). The ledger after (`all`) with the lines it
98
+ * appended. A line of a digest no version of its workflow holds (a run's purge took it since the line was read), or of a
99
+ * run that was purged, is never appended (Store.learning changeRecords refuses it): the others are. */
100
+ export async function addAuditLines(rows, agentId, lines, replace = false) {
101
+ let left = lines;
102
+ for (let tries = 0;; tries++) {
85
103
  try {
86
- const value = JSON.parse(raw);
87
- if (!isLine(value))
88
- continue;
89
- const { run, workflow, digest, promoted_at, at } = value;
90
- out.push(value.source === "started"
91
- ? { source: "started", run, shadow_run: value.shadow_run, workflow, digest, promoted_at, ...turnOf(value), at }
92
- : { run, shadow_run: value.shadow_run, workflow, digest, promoted_at, source: value.source, agreed: value.agreed, served_cost: value.served_cost, shadow_cost: value.shadow_cost, ...turnOf(value), ...noVerdictOf(value), at });
104
+ return await appendLines(rows, agentId, left, replace);
93
105
  }
94
- catch {
95
- // A torn line is no line.
106
+ catch (error) {
107
+ // A purged run's line, refused in the write's own transaction: the write again without it.
108
+ if (!(error instanceof LearningRecordRefused) || tries >= 2)
109
+ throw error;
110
+ const refused = new Set(error.records.map((one) => one.runId));
111
+ const kept = left.filter((line) => !refused.has(line.run));
112
+ if (kept.length === left.length)
113
+ throw error;
114
+ left = kept;
96
115
  }
97
116
  }
98
- return out;
99
- }
100
- /** The ledger's text for `lines`: from the AUDITS_KEPT-th newest row on, and every open started line before it. */
101
- export function auditsText(lines) {
102
- const rows = lines.flatMap((line, i) => (line.source === "started" ? [] : [i]));
103
- const from = rows.length > AUDITS_KEPT ? rows[rows.length - AUDITS_KEPT] : 0;
104
- const open = new Set(openAudits(lines));
105
- return lines.filter((line, i) => i >= from || open.has(line)).map((line) => JSON.stringify(line)).join("\n") + "\n";
106
117
  }
107
- /** The ledger's lines on the folder's main as `folder` reads it (none before the first). */
108
- export async function ledgerOf(folder) {
109
- const at = folder.snapshot?.audits;
110
- return at ? parseLedger(await folder.body(AUDITS_FILE, at.oid)) : [];
118
+ function appendLines(rows, agentId, lines, replace) {
119
+ return rows.changeRecords(agentId, "audit", (records, held) => {
120
+ const keys = new Set(lines.map(lineKey));
121
+ const kept = records.filter((one) => { const line = lineOf(one.data); return !replace || !line || !keys.has(lineKey(line)); });
122
+ const before = linesOf(kept);
123
+ const known = new Set(before.map(lineKey));
124
+ const added = [];
125
+ for (const line of lines) {
126
+ if (known.has(lineKey(line)))
127
+ continue;
128
+ if (held !== undefined && !held(line.workflow, line.digest))
129
+ continue;
130
+ known.add(lineKey(line));
131
+ added.push(line);
132
+ }
133
+ if (!added.length && kept.length === records.length)
134
+ return { result: { all: before, added } };
135
+ const writes = trimmed([...kept.map((one) => ({ seq: one.seq, runId: one.runId, workflow: one.workflow, digest: one.digest, data: one.data })), ...added.map(lineWrite)]);
136
+ return { records: writes, result: { all: linesOf(writes), added } };
137
+ });
111
138
  }
112
- /** The ledger's rows on the folder's main: its finished audits, oldest first. */
113
- export const readAudits = async (ws) => rowsOf(await readLearning(ws, ledgerOf));
114
- /** A line's place in the ledger: one per served run and source (a started line's, its shadow's row, a grade's row). */
115
- export const lineKey = (line) => `${line.source}:${line.run}`;
116
- /** The change that appends `lines` to the ledger `before` (none when each is there already: lineKey), with the lines it
117
- * appends. */
118
- export function auditChange(before, lines) {
119
- const known = new Set(before.map(lineKey));
120
- const added = [];
121
- for (const line of lines) {
122
- if (known.has(lineKey(line)))
123
- continue;
124
- known.add(lineKey(line));
125
- added.push(line);
126
- }
127
- const rows = rowsOf(added).length;
128
- const said = rows ? `${rows} audit row${rows === 1 ? "" : "s"}` : `${added.length} audit${added.length === 1 ? "" : "s"} started`;
129
- return added.length ? { added, change: { by: { host: said }, writes: [{ path: AUDITS_FILE, text: auditsText([...before, ...added]) }] } } : { added };
139
+ /** The ledger's records from the AUDITS_KEPT-th newest row on, and every open started line before it (main's folder
140
+ * ledger kept the same): so it never grows past its cap. */
141
+ function trimmed(writes) {
142
+ const lines = writes.map((one) => lineOf(one.data));
143
+ const rows = lines.flatMap((line, i) => (line && line.source !== "started" ? [i] : []));
144
+ const from = rows.length > AUDITS_KEPT ? rows[rows.length - AUDITS_KEPT] : 0;
145
+ const open = new Set(openAudits(lines.filter((line) => line !== undefined)));
146
+ return writes.filter((_, i) => i >= from || (lines[i] !== undefined && open.has(lines[i])));
130
147
  }
131
148
  /** The rows the hold rule counts for `workflow` at `digest` under the promotion begun at `promotedAt` (learn/promote.ts
132
149
  * promotionStartOf; none counted for null): those with a verdict, the newest `hold_window` of them. A served run an
@@ -148,14 +165,14 @@ export function auditLineOf(rows, workflow, digest, promotedAt, loop) {
148
165
  const counted = windowOf(rows, workflow, digest, promotedAt, loop);
149
166
  return { window: loop.hold_window, disagree: loop.hold_disagree, rows: counted.length, disagreed: counted.filter((row) => row.agreed === false).length };
150
167
  }
151
- export function servingLinesOf(records, rows, loop, costStop, refused) {
152
- return servingOf(records, refused).map(({ workflow, digest }) => {
168
+ export function servingLinesOf(records, rows, loop, costStop) {
169
+ return servingOf(records).map(({ workflow, digest }) => {
153
170
  const own = records.filter((one) => one.workflow === workflow);
154
171
  const newest = own.at(-1);
155
172
  const checked = own.findLast((one) => one.check?.n !== undefined)?.check;
156
173
  const at = digest ?? newest?.digest;
157
174
  return {
158
- state: servingStateOf(records, workflow, costStop, refused),
175
+ state: servingStateOf(records, workflow, costStop),
159
176
  check: checked ? { n: checked.n, agreed: checked.agreed ?? 0, alone: checked.alone ?? 0, attempt: checked.attempt } : null,
160
177
  audit: at === undefined ? null : auditLineOf(rows, workflow, at, promotionStartOf(records, workflow, at)?.at ?? null, loop),
161
178
  };
@@ -1,4 +1,4 @@
1
- // The checker of a workflow draft a run's compile turn gives its agent's learning folder (SPEC.md): its workflow.json and
1
+ // The checker of a workflow draft a run's compile turn gives its agent's learning (SPEC.md): its workflow.json and
2
2
  // README.md, each a change against what the folder holds. Structure only, and what must never be stored; nothing the
3
3
  // checker refuses is ever written to git. Every problem it reports is printable: its path and detail are cut of the
4
4
  // host's secrets and of text shaped like one, and a field over PRINT_MAX is redacted whole.