@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,23 +1,16 @@
1
1
  import { type Store } from "../store/store.js";
2
- import type { LearningFolder } from "./folder.js";
3
2
  /** A delete refused: work of the agent's learning is still in flight (`runs`: a run of the agent not ended, its
4
3
  * compile turn, a check's replay or an audit's shadow among them). Nothing was removed. */
5
4
  export declare class LearningInFlight extends Error {
6
5
  readonly runs: readonly string[];
7
6
  constructor(agentId: string, runs: readonly string[]);
8
7
  }
9
- /** Agent `agentId`'s learning deleted: its learning folder on each other disk it is on (`elsewhere`: a Mode 2 run's end
10
- * writes it on the Archil disk its claim mounted; server.ts names those disks), then every file of its learning folder
11
- * here (`folder`, learning.ts learningFolderOf: its corrections.md and workflows, its git history and snapshot,
12
- * audits.jsonl), then the learning records the store keeps for it (its promotions and grades, and the reset ledger and
13
- * watermark its earlier resets kept, unless `keepResetLedger`: a reset keeps them, the runs they cover staying).
14
- * Refused (LearningInFlight), with nothing removed, while a run of the agent has not ended; `elsewhere` failing leaves
15
- * this folder and the records for the next call. Idempotent: what is gone already is skipped, so a second call removes
16
- * nothing. `files`: this folder's entries it removed; `records`: the store's records. `folder` is ended here. */
17
- export declare function deleteLearning(store: Store, agentId: string, folder: LearningFolder, { keepResetLedger, elsewhere }?: {
8
+ /** Agent `agentId`'s learning deleted: every learning row the store keeps for it (Store.learning: its items, saves,
9
+ * promotions, grades and audits), and the reset ledger and watermark its earlier resets kept, unless `keepResetLedger`
10
+ * (a reset keeps them, the runs they cover staying). Refused (LearningInFlight), with nothing removed, while a run of
11
+ * the agent has not ended. Idempotent: a second call removes nothing. `records`: the settings rows it removed. */
12
+ export declare function deleteLearning(store: Store, agentId: string, { keepResetLedger }?: {
18
13
  keepResetLedger?: boolean;
19
- elsewhere?: () => Promise<void>;
20
14
  }): Promise<{
21
- files: number;
22
15
  records: number;
23
16
  }>;
@@ -3,9 +3,8 @@
3
3
  // deletes the agent's store rows, in that order, so a call again after a crash finishes what a first one began and no
4
4
  // learning is left with no agent to own it; DELETE /v2/agents/{id}/learning (learning-reset.ts) keeps the agent and its
5
5
  // runs.
6
- import { isWorkspaceError } from "../workspace/workspace.js";
7
6
  import { FINAL_STATES } from "../store/store.js";
8
- import { gradesKey, promotionsKey, resetAtKey, resetLedgerKey } from "./promote.js";
7
+ import { resetAtKey, resetLedgerKey } from "./promote.js";
9
8
  /** A delete refused: work of the agent's learning is still in flight (`runs`: a run of the agent not ended, its
10
9
  * compile turn, a check's replay or an audit's shadow among them). Nothing was removed. */
11
10
  export class LearningInFlight extends Error {
@@ -16,33 +15,21 @@ export class LearningInFlight extends Error {
16
15
  this.runs = runs;
17
16
  }
18
17
  }
19
- /** Agent `agentId`'s learning deleted: its learning folder on each other disk it is on (`elsewhere`: a Mode 2 run's end
20
- * writes it on the Archil disk its claim mounted; server.ts names those disks), then every file of its learning folder
21
- * here (`folder`, learning.ts learningFolderOf: its corrections.md and workflows, its git history and snapshot,
22
- * audits.jsonl), then the learning records the store keeps for it (its promotions and grades, and the reset ledger and
23
- * watermark its earlier resets kept, unless `keepResetLedger`: a reset keeps them, the runs they cover staying).
24
- * Refused (LearningInFlight), with nothing removed, while a run of the agent has not ended; `elsewhere` failing leaves
25
- * this folder and the records for the next call. Idempotent: what is gone already is skipped, so a second call removes
26
- * nothing. `files`: this folder's entries it removed; `records`: the store's records. `folder` is ended here. */
27
- export async function deleteLearning(store, agentId, folder, { keepResetLedger = false, elsewhere } = {}) {
28
- try {
29
- const open = (await store.runs.list({ agentId })).filter((run) => run.agentId === agentId && !FINAL_STATES.includes(run.state)).map((run) => run.id);
30
- if (open.length)
31
- throw new LearningInFlight(agentId, open);
32
- await elsewhere?.();
33
- const entries = await folder.workspace.list("").catch((error) => (isWorkspaceError(error, "NOT_FOUND") ? [] : Promise.reject(error)));
34
- for (const entry of entries)
35
- await folder.workspace.remove(entry.name, { recursive: true, force: true });
36
- let records = 0;
37
- for (const key of [promotionsKey(agentId), gradesKey(agentId), ...(keepResetLedger ? [] : [resetLedgerKey(agentId), resetAtKey(agentId)])]) {
38
- if ((await store.settings.get(key)) === undefined)
39
- continue;
40
- await store.settings.remove(key);
41
- records += 1;
42
- }
43
- return { files: entries.length, records };
44
- }
45
- finally {
46
- await folder.end();
18
+ /** Agent `agentId`'s learning deleted: every learning row the store keeps for it (Store.learning: its items, saves,
19
+ * promotions, grades and audits), and the reset ledger and watermark its earlier resets kept, unless `keepResetLedger`
20
+ * (a reset keeps them, the runs they cover staying). Refused (LearningInFlight), with nothing removed, while a run of
21
+ * the agent has not ended. Idempotent: a second call removes nothing. `records`: the settings rows it removed. */
22
+ export async function deleteLearning(store, agentId, { keepResetLedger = false } = {}) {
23
+ const open = (await store.runs.list({ agentId })).filter((run) => run.agentId === agentId && !FINAL_STATES.includes(run.state)).map((run) => run.id);
24
+ if (open.length)
25
+ throw new LearningInFlight(agentId, open);
26
+ await (keepResetLedger ? store.learning.reset(agentId) : store.learning.erase(agentId));
27
+ let records = 0;
28
+ for (const key of keepResetLedger ? [] : [resetLedgerKey(agentId), resetAtKey(agentId)]) {
29
+ if ((await store.settings.get(key)) === undefined)
30
+ continue;
31
+ await store.settings.remove(key);
32
+ records += 1;
47
33
  }
34
+ return { records };
48
35
  }
@@ -0,0 +1,16 @@
1
+ import type { AuditDisagreement, CheckDisagreement, PromotionRecord } from "./promote.js";
2
+ /** A check's disagreement with what it copied from its run blanked: its run id and which way the draft went (an answer,
3
+ * a hand-back, a failed step) and the fields it had wrong (the definition's names, no run text) and where each known
4
+ * answer came from kept, its input, the agent's answer, the draft's, the known answers' values and the grader's words
5
+ * gone. */
6
+ export declare const blankCheck: (one: CheckDisagreement) => CheckDisagreement;
7
+ /** An audit's disagreement blanked the same way: its run ids and whether a grade wrote it kept, its known answer empty. */
8
+ export declare const blankAudit: (one: AuditDisagreement) => AuditDisagreement;
9
+ /** `record` with what it copied from run `runId` blanked: each disagreement naming it (a check's agent run, a connected
10
+ * agent's collected turn too; an audit's served run or shadow run), and the grader's words its reason quotes from one
11
+ * (differentDecisionWords' example). Its decision, numbers and run ids stay. The record itself when it names no such
12
+ * disagreement. */
13
+ export declare function forgetRunIn(record: PromotionRecord, runId: string): PromotionRecord;
14
+ /** The runs whose copies `record` holds (forgetRunIn blanks them): each disagreement's run, a connected agent's collected
15
+ * turn's, an audit's served run and shadow run. */
16
+ export declare function runsNamedIn(record: PromotionRecord): string[];
@@ -0,0 +1,53 @@
1
+ /** A check's disagreement with what it copied from its run blanked: its run id and which way the draft went (an answer,
2
+ * a hand-back, a failed step) and the fields it had wrong (the definition's names, no run text) and where each known
3
+ * answer came from kept, its input, the agent's answer, the draft's, the known answers' values and the grader's words
4
+ * gone. */
5
+ export const blankCheck = (one) => ({
6
+ run: one.run, input: "", agent: null,
7
+ ...(one.draft !== undefined ? { draft: "" } : {}),
8
+ ...(one.escalated !== undefined ? { escalated: "" } : {}),
9
+ ...(one.failed ? { failed: true } : {}),
10
+ ...(one.fields ? { fields: one.fields } : {}),
11
+ ...(one.expected ? { expected: one.expected.map(({ field, known, value }) => ({ field, known, ...(value !== undefined ? { value: "" } : {}) })) } : {}),
12
+ });
13
+ /** An audit's disagreement blanked the same way: its run ids and whether a grade wrote it kept, its known answer empty. */
14
+ export const blankAudit = (one) => ({ run: one.run, served: one.served, input: "", agent: null, draft: null, ...(one.graded ? { graded: true } : {}), ...(one.expected !== undefined ? { expected: "" } : {}) });
15
+ /** `record` with what it copied from run `runId` blanked: each disagreement naming it (a check's agent run, a connected
16
+ * agent's collected turn too; an audit's served run or shadow run), and the grader's words its reason quotes from one
17
+ * (differentDecisionWords' example). Its decision, numbers and run ids stay. The record itself when it names no such
18
+ * disagreement. */
19
+ export function forgetRunIn(record, runId) {
20
+ if (!record || typeof record !== "object")
21
+ return record;
22
+ const check = record.check?.disagreements?.some((one) => one.run === runId);
23
+ const turns = record.check?.turns?.disagreements?.some((one) => one.run === runId);
24
+ const audit = record.audit?.disagreements.some((one) => one.run === runId || one.served === runId);
25
+ if (!check && !turns && !audit)
26
+ return record;
27
+ let reason = record.reason;
28
+ for (const one of record.check?.disagreements ?? [])
29
+ if (one.run === runId && one.differs_on !== undefined)
30
+ reason = reason.replace(` (for example: ${one.differs_on})`, "");
31
+ const blanked = (list) => list.map((one) => (one.run === runId ? blankCheck(one) : one));
32
+ return {
33
+ ...record,
34
+ reason,
35
+ ...((check || turns) && record.check ? { check: {
36
+ ...record.check,
37
+ ...(check ? { disagreements: blanked(record.check.disagreements) } : {}),
38
+ ...(turns ? { turns: { ...record.check.turns, disagreements: blanked(record.check.turns.disagreements) } } : {}),
39
+ } } : {}),
40
+ ...(audit && record.audit ? { audit: { ...record.audit, disagreements: record.audit.disagreements.map((one) => (one.run === runId || one.served === runId ? blankAudit(one) : one)) } } : {}),
41
+ };
42
+ }
43
+ /** The runs whose copies `record` holds (forgetRunIn blanks them): each disagreement's run, a connected agent's collected
44
+ * turn's, an audit's served run and shadow run. */
45
+ export function runsNamedIn(record) {
46
+ if (!record || typeof record !== "object")
47
+ return [];
48
+ return [...new Set([
49
+ ...(record.check?.disagreements ?? []).map((one) => one.run),
50
+ ...(record.check?.turns?.disagreements ?? []).map((one) => one.run),
51
+ ...(record.audit?.disagreements ?? []).flatMap((one) => [one.run, one.served]),
52
+ ].filter((run) => typeof run === "string"))];
53
+ }
@@ -1,6 +1,6 @@
1
1
  // The server's learning code, as one surface: a workflow draft's format and checks (workflow-draft.ts, check.ts), the
2
2
  // owner's corrections (corrections.ts), and the hidden-character and secret matchers they use (invisible.ts,
3
- // secrets.ts). SPEC.md, beside it, is the learning folder's contract. The rest of the server imports it from here.
3
+ // secrets.ts). SPEC.md, beside it, is the learning's contract. The rest of the server imports it from here.
4
4
  export { CAPS, checkDraft, printable, unstorable } from "./check.js";
5
5
  export { CORRECTIONS_CAP, CORRECTIONS_FILE, correctionLine, correctionsProblems, problemWords } from "./corrections.js";
6
6
  export { hiddenCharacter } from "./invisible.js";
@@ -1,8 +1,4 @@
1
1
  import type { RunLaunch } from "../run-launch.js";
2
- import type { Store } from "../store/store.js";
3
2
  /** The disk a run's launch names as its own: the launch's `archilDisk` of kind "launch", by its id; null for none or its
4
3
  * agent's own (the default disk). The store keeps the same on the run's row (RunRow.disk). */
5
4
  export declare const learningDiskOf: (launch: Pick<RunLaunch, "archilDisk">) => string | null;
6
- /** Each named disk a run of agent `agentId` used (Store.runs.every: its built-in learning runs and purged runs included,
7
- * a purged run's tombstone keeping its disk): where a learning folder of the agent may be, past the server's own. */
8
- export declare function namedDisksOf(store: Pick<Store, "runs">, agentId: string): Promise<string[]>;
@@ -1,8 +1,3 @@
1
1
  /** The disk a run's launch names as its own: the launch's `archilDisk` of kind "launch", by its id; null for none or its
2
2
  * agent's own (the default disk). The store keeps the same on the run's row (RunRow.disk). */
3
3
  export const learningDiskOf = (launch) => launch.archilDisk?.kind === "launch" ? launch.archilDisk.diskId : null;
4
- /** Each named disk a run of agent `agentId` used (Store.runs.every: its built-in learning runs and purged runs included,
5
- * a purged run's tombstone keeping its disk): where a learning folder of the agent may be, past the server's own. */
6
- export async function namedDisksOf(store, agentId) {
7
- return [...new Set((await store.runs.every(agentId)).map((run) => run.disk).filter((disk) => disk !== null))];
8
- }
@@ -1,4 +1,5 @@
1
- import { type LearningPlace as OneLearningPlace, type LearningWorkspace as OneLearningWorkspace, type Workspace } from "../workspace/index.js";
1
+ import { type Workspace } from "../../workspace/index.js";
2
+ import { type LearningPlace as OneLearningPlace, type LearningWorkspace as OneLearningWorkspace } from "./place.js";
2
3
  /** The host's folder inside the learning folder: the snapshot, the diffs and the script. Never learned, never seeded. */
3
4
  export declare const HOST_DIR = ".agentrun";
4
5
  export declare const SNAPSHOT_FILE = ".agentrun/snapshot.json";
@@ -21,10 +21,10 @@
21
21
  // (audits.jsonl, never served to a run), nothing else.
22
22
  import { createHash, randomBytes } from "node:crypto";
23
23
  import { readFileSync } from "node:fs";
24
- import { isWorkspaceError, learningWorkspace as oneLearningWorkspace, } from "../workspace/index.js";
25
- import { CORRECTIONS_FILE } from "./corrections.js";
26
- import { learnedFront, learnedStatus, retiredFrom, WORKFLOW_NAME, WORKFLOWS_DIR } from "./workflow-draft.js";
27
- import { held, heldLearningFolder } from "../runner/held.js";
24
+ import { isWorkspaceError } from "../../workspace/index.js";
25
+ import { CORRECTIONS_FILE } from "../corrections.js";
26
+ import { learnedFront, learnedStatus, retiredFrom, WORKFLOW_NAME, WORKFLOWS_DIR } from "../workflow-draft.js";
27
+ import { learningWorkspace as oneLearningWorkspace } from "./place.js";
28
28
  /** The host's folder inside the learning folder: the snapshot, the diffs and the script. Never learned, never seeded. */
29
29
  export const HOST_DIR = ".agentrun";
30
30
  export const SNAPSHOT_FILE = `${HOST_DIR}/snapshot.json`;
@@ -376,9 +376,6 @@ const withMain = (snapshot, main) => JSON.parse(JSON.stringify(snapshot).replace
376
376
  export function learningWorkspace(place) {
377
377
  if (folderTestHooks.workspace)
378
378
  return folderTestHooks.workspace(place);
379
- // A run's own process never opens a learning folder itself: its runner does, the claim's agent's (held.ts).
380
- if (held())
381
- return heldLearningFolder();
382
379
  return oneLearningWorkspace(place);
383
380
  }
384
381
  /** What a learning folder's script run is, as a runner checks one a run's process asks of it (run-child-host.ts): its
@@ -0,0 +1,16 @@
1
+ import { type Workspace } from "../../workspace/workspace.js";
2
+ /** Agent `agentId`'s legacy learning folder: `<data>/disk/agents/<agent>/learning`. */
3
+ export declare const legacyLearningFolder: (data: string, agentId: string) => string;
4
+ /** Where an agent's legacy learning folder is: the local folder under the data directory. */
5
+ export type LearningPlace = {
6
+ readonly agentId: string;
7
+ readonly mode: "local"; /** The data directory. */
8
+ readonly data: string;
9
+ };
10
+ /** The folder's Workspace, and its end. */
11
+ export interface LearningWorkspace {
12
+ readonly workspace: Workspace;
13
+ end(): Promise<void>;
14
+ }
15
+ /** Agent `agentId`'s legacy learning Workspace. */
16
+ export declare function learningWorkspace(place: LearningPlace): LearningWorkspace;
@@ -1,24 +1,14 @@
1
- // An agent's learning Workspace, the one learningWorkspace: its learning folder in paths.ts's one agent layout
2
- // (agentFolder, then "learning"), on the local disk ({ mode: "local", data }: agentLearningFolder) or on the Archil disk
3
- // at learningKey ({ mode: "archil", archil }: the claim's disk, region and image). Learning's grade and merge run as one
4
- // script through it (learning's own code: written into .agentrun, then run with exec at the folder's root), and the
5
- // server reads learning's snapshot back with read, stat and list. Given synchronously; its end() is called in a finally
6
- // after every use.
7
- //
8
- // The local folder is made by the first call that writes (anything but read, stat, list, grep and mountSpec), one level
9
- // at a time from the data directory, and its .git is checked too. A read makes nothing: while a level is missing, a
10
- // read is NOT_FOUND "the learning folder is not made yet" (no main yet). A level that is a symbolic link is refused as
11
- // ESCAPE naming it, so nothing is read, made or run where a link points; one that is not a folder is UNAVAILABLE. The
12
- // local end() does nothing.
13
- // The Archil folder makes nothing by reading either (the file API answers a missing key as NOT_FOUND). Its end() sweeps
14
- // the learning folder's exec spill folder once; what an exec's cleanup leaves, or a sweep that fails, goes to the log,
15
- // never failing the caller.
1
+ // The learning folder kept from before learning moved to the store's rows (changes/learning-store-rows.md): an agent's
2
+ // git folder under the data directory, <data>/disk/agents/<agent>/learning. Nothing reads it any more; a run's purge
3
+ // alone opens it, to take that run's text off it (legacy/scrub.ts). Local only: on an Archil disk the purge deletes the
4
+ // agent's folder there whole (archil-routes.ts removeLearningFolder), as it did before.
16
5
  import { lstat, mkdir } from "node:fs/promises";
17
6
  import { dirname, join } from "node:path";
18
- import { archilWorkspace } from "./archil.js";
19
- import { localWorkspace } from "./local.js";
20
- import { agentLearningFolder, DISK_DIR, learningKey } from "./paths.js";
21
- import { WorkspaceError } from "./workspace.js";
7
+ import { localWorkspace } from "../../workspace/local.js";
8
+ import { agentDirName, DISK_DIR } from "../../workspace/paths.js";
9
+ import { WorkspaceError } from "../../workspace/workspace.js";
10
+ /** Agent `agentId`'s legacy learning folder: `<data>/disk/agents/<agent>/learning`. */
11
+ export const legacyLearningFolder = (data, agentId) => join(data, DISK_DIR, "agents", agentDirName(agentId), "learning");
22
12
  /** The Workspace calls that only read: they never make the folder. */
23
13
  const READS = new Set(["read", "stat", "list", "grep", "mountSpec"]);
24
14
  /** `dir` checked: a folder, never a symbolic link; made first where absent when `make`. Missing and not made: false. */
@@ -47,7 +37,7 @@ async function level(data, dir, make) {
47
37
  }
48
38
  /** The local learning folder's Workspace: made by the first write, never by a read. */
49
39
  function localLearning(data, agentId) {
50
- const root = agentLearningFolder(data, agentId);
40
+ const root = legacyLearningFolder(data, agentId);
51
41
  const levels = [];
52
42
  // Every level from <data>/disk down to the folder (the walk stops at the data directory, or the top of the tree).
53
43
  for (let dir = root; dir !== join(data, DISK_DIR, "..") && dir !== dirname(dir); dir = dirname(dir))
@@ -81,27 +71,7 @@ function localLearning(data, agentId) {
81
71
  get process() { return localWorkspace(root).process; },
82
72
  };
83
73
  }
84
- /** Agent `agentId`'s learning Workspace. */
74
+ /** Agent `agentId`'s legacy learning Workspace. */
85
75
  export function learningWorkspace(place) {
86
- const { agentId } = place;
87
- if (place.mode === "local")
88
- return { workspace: localLearning(place.data, agentId), end: async () => { } };
89
- const claim = place.archil;
90
- if (claim === undefined)
91
- throw new TypeError("an Archil learning Workspace is opened with its claim's Archil claim (archilClaim)");
92
- const say = (line) => {
93
- try {
94
- place.log?.(line);
95
- }
96
- catch { /* the caller's log */ }
97
- };
98
- const workspace = archilWorkspace(claim.disk, learningKey(agentId), {
99
- ...(claim.image === undefined ? {} : { image: claim.image }),
100
- onCleanupFailed: say,
101
- });
102
- let ended;
103
- const end = () => (ended ??= workspace.sweep().catch((error) => {
104
- say(`the learning folder's exec spill folder could not be swept (the next sweep takes what is left): ${error?.message ?? error}`);
105
- }));
106
- return { workspace, end };
76
+ return { workspace: localLearning(place.data, place.agentId), end: async () => { } };
107
77
  }
@@ -0,0 +1,28 @@
1
+ import type { Settings, Store } from "../../store/index.js";
2
+ import { type Workspace } from "../../workspace/index.js";
3
+ /** The legacy settings keys a purge scrubs: the agent's kept grades and its promotion records. */
4
+ export declare const legacyGradesKey: (agentId: string) => string;
5
+ export declare const legacyPromotionsKey: (agentId: string) => string;
6
+ /** Run `runId`'s text off agent `agentId`'s legacy learning: its folder under `data` (forgetRunText: a workflow it
7
+ * changed last goes back to the version before it that no purged run of `store` wrote), in the agent's queue, then its
8
+ * copies in the legacy settings keys. A folder that can't be read or written now is 503 unavailable (the next DELETE
9
+ * does it again); a folder never made is no work. */
10
+ export declare function forgetLegacyRunLearning(data: string, agentId: string, runId: string, store: Pick<Store, "runs" | "settings">): Promise<void>;
11
+ /** What the legacy settings keys copied from run `runId`, gone: its kept grades dropped, its promotion records'
12
+ * disagreements naming it blanked (forget-run.ts forgetRunIn), each record's decision, numbers and run ids kept. No write
13
+ * when nothing names it. */
14
+ export declare function forgetLegacyRunCopies(settings: Pick<Settings, "get" | "replaceIf">, agentId: string, runId: string): Promise<void>;
15
+ /**
16
+ * Run `runId`'s text taken off the folder's current files, at its purge (agent-delete.ts purgeRun): first its learned
17
+ * workflows (forgetRunWorkflows; `purged`: whether another run is purged), whether or not it left a diff file; then the
18
+ * lines each of its merges added to corrections.md, as its diff file keeps them, dropped from main in one host commit
19
+ * per merge (a line a person edited since is theirs and stays); each other merge's diff that shows such a line as
20
+ * context written without it; then the run's diff files deleted, last, so a call stopped part way finds what it has
21
+ * left to do. Its merges stay in the folder's git history until its agent's purge deletes the
22
+ * folder. Idempotent: each merge's scrub lands once, nothing left to drop makes no commit, and a run with no diff file
23
+ * and no workflow here is no work.
24
+ * `commit`: the host's last commit, when one was made.
25
+ */
26
+ export declare function forgetRunText(ws: Workspace, runId: string, purged: (run: string) => Promise<boolean>): Promise<{
27
+ commit?: string;
28
+ }>;
@@ -0,0 +1,258 @@
1
+ // A run's purge on the learning kept from before learning moved to the store's rows (changes/learning-store-rows.md):
2
+ // nothing reads that learning any more, and the purge alone touches it, so DELETE /runs still takes the run's text off
3
+ // it as it did before. Two places, each as the purge did then:
4
+ // - the agent's learning folder under the data directory (legacy/folder.ts, the git folder and its script): the run's
5
+ // learned workflows put back as they stood before it, its corrections.md lines dropped, its diff files deleted
6
+ // (forgetRunText). Its merges stay in the folder's git history until the agent's purge deletes the
7
+ // folder whole.
8
+ // - the settings keys learning.grades.<agent> (its grades dropped) and learning.promotions.<agent> (its copies in the
9
+ // promotion records blanked).
10
+ // On an Archil disk the run's launch named, the purge deletes the agent's folder there whole (archil-routes.ts
11
+ // removeLearningFolder), and an agent's purge removes its folder here and both keys (server.ts forgetAgent), each as
12
+ // before. Nothing else of it is removed, and no reader opens it.
13
+ import { join } from "node:path";
14
+ import { ApiError } from "../../errors.js";
15
+ import { purgedRows } from "../../purged-workflow.js";
16
+ import { agentFolderOf, serialBy } from "../../server-fs.js";
17
+ import { isWorkspaceError } from "../../workspace/index.js";
18
+ import { CORRECTIONS_FILE } from "../corrections.js";
19
+ import { forgetRunIn } from "../forget-run.js";
20
+ import { DIFFS_DIR, folderAt, folderFailure, FolderBusy, FolderMerged, FolderUnreadable, forgetBody, learningRepair, learningWorkspace, readRunDiff, readSnapshot, writeLearning } from "./folder.js";
21
+ /** The legacy settings keys a purge scrubs: the agent's kept grades and its promotion records. */
22
+ export const legacyGradesKey = (agentId) => `learning.grades.${agentId}`;
23
+ export const legacyPromotionsKey = (agentId) => `learning.promotions.${agentId}`;
24
+ const queues = new Map();
25
+ /** Run `runId`'s text off agent `agentId`'s legacy learning: its folder under `data` (forgetRunText: a workflow it
26
+ * changed last goes back to the version before it that no purged run of `store` wrote), in the agent's queue, then its
27
+ * copies in the legacy settings keys. A folder that can't be read or written now is 503 unavailable (the next DELETE
28
+ * does it again); a folder never made is no work. */
29
+ export async function forgetLegacyRunLearning(data, agentId, runId, store) {
30
+ const repo = join(agentFolderOf(data, agentId), "learning");
31
+ await serialBy(queues, repo, async () => {
32
+ const { workspace: ws, end } = learningWorkspace({ mode: "local", agentId, data });
33
+ try {
34
+ await forgetRunText(ws, runId, async (run) => (await purgedRows(store, [run])).has(run));
35
+ }
36
+ catch (error) {
37
+ if (isWorkspaceError(error, "NOT_FOUND"))
38
+ return;
39
+ if (error instanceof FolderBusy)
40
+ throw new ApiError("unavailable", error.message);
41
+ if (error instanceof FolderUnreadable)
42
+ throw error.link ? new Error(error.message) : new ApiError("unavailable", error.message);
43
+ throw error;
44
+ }
45
+ finally {
46
+ await end();
47
+ }
48
+ });
49
+ await forgetLegacyRunCopies(store.settings, agentId, runId);
50
+ }
51
+ const itemsOf = (value) => (value && typeof value === "object" && Array.isArray(value.items) ? [...(value.items)] : []);
52
+ /** `key`'s kept list replaced by `update` of it under compare-and-swap, tried again while another write won. */
53
+ async function updateKept(settings, key, update) {
54
+ for (let i = 0; i < 8; i++) {
55
+ const before = await settings.get(key);
56
+ if (before === undefined || before === null)
57
+ return;
58
+ const after = { ...before, items: update(itemsOf(before)) };
59
+ if (await settings.replaceIf(key, before, after))
60
+ return;
61
+ }
62
+ throw new ApiError("unavailable", `the legacy learning setting ${key} kept changing under the purge: send the DELETE again`);
63
+ }
64
+ /** What the legacy settings keys copied from run `runId`, gone: its kept grades dropped, its promotion records'
65
+ * disagreements naming it blanked (forget-run.ts forgetRunIn), each record's decision, numbers and run ids kept. No write
66
+ * when nothing names it. */
67
+ export async function forgetLegacyRunCopies(settings, agentId, runId) {
68
+ if (itemsOf(await settings.get(legacyGradesKey(agentId))).some((one) => one?.run === runId)) {
69
+ await updateKept(settings, legacyGradesKey(agentId), (items) => items.filter((one) => one?.run !== runId));
70
+ }
71
+ if (itemsOf(await settings.get(legacyPromotionsKey(agentId))).some((one) => forgetRunIn(one, runId) !== one)) {
72
+ await updateKept(settings, legacyPromotionsKey(agentId), (items) => items.map((one) => forgetRunIn(one, runId)));
73
+ }
74
+ }
75
+ /**
76
+ * Run `runId`'s text taken off the folder's current files, at its purge (agent-delete.ts purgeRun): first its learned
77
+ * workflows (forgetRunWorkflows; `purged`: whether another run is purged), whether or not it left a diff file; then the
78
+ * lines each of its merges added to corrections.md, as its diff file keeps them, dropped from main in one host commit
79
+ * per merge (a line a person edited since is theirs and stays); each other merge's diff that shows such a line as
80
+ * context written without it; then the run's diff files deleted, last, so a call stopped part way finds what it has
81
+ * left to do. Its merges stay in the folder's git history until its agent's purge deletes the
82
+ * folder. Idempotent: each merge's scrub lands once, nothing left to drop makes no commit, and a run with no diff file
83
+ * and no workflow here is no work.
84
+ * `commit`: the host's last commit, when one was made.
85
+ */
86
+ export async function forgetRunText(ws, runId, purged) {
87
+ let commit = await forgetRunWorkflows(ws, runId, async (run) => run === runId || (await purged(run)));
88
+ const names = await diffNames(ws);
89
+ const own = new RegExp(`^${runId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\.r\\d+)?\\.json(\\..+)?$`);
90
+ const mine = names.filter((name) => own.test(name));
91
+ if (!mine.length)
92
+ return commit ? { commit } : {};
93
+ const lines = [];
94
+ for (const name of mine.filter(isDiffFile)) {
95
+ const added = ((await diffOrNone(ws, name))?.files ?? []).flatMap((file) => (file.path === CORRECTIONS_FILE && "patch" in file ? addedLines(file.patch) : []));
96
+ if (!added.length)
97
+ continue;
98
+ lines.push(...added);
99
+ // Lands once, by the merge's diff key (the folder's ref for its scrub): a call that stopped after it finds it landed
100
+ // and takes no line again, so another run's same line stays; a merge of the run made since (a purge that stopped
101
+ // before the run's tombstone left it open to a grade) is a key of its own, scrubbed in its turn.
102
+ const done = await writeLearning(ws, async ({ snapshot, body }) => {
103
+ if (!snapshot?.corrections)
104
+ return { result: undefined };
105
+ const before = await body(CORRECTIONS_FILE, snapshot.corrections.oid);
106
+ const after = withoutLines(before, added);
107
+ if (after === before)
108
+ return { result: undefined };
109
+ const write = after ? { writes: [{ path: CORRECTIONS_FILE, text: after }] } : { writes: [], deletes: [CORRECTIONS_FILE] };
110
+ return { result: snapshot.corrections.oid, change: { by: { host: "a purged run's corrections removed" }, purged: name.slice(0, -".json".length), ...write } };
111
+ }).catch((error) => (error instanceof FolderMerged ? { result: undefined, main: undefined } : Promise.reject(error)));
112
+ if (done.result !== undefined) {
113
+ forgetBody(done.result);
114
+ commit = done.main;
115
+ }
116
+ }
117
+ if (lines.length) {
118
+ const gone = new Set(lines);
119
+ for (const name of names.filter((one) => isDiffFile(one) && !own.test(one))) {
120
+ const diff = await diffOrNone(ws, name);
121
+ if (!diff)
122
+ continue;
123
+ let changed = false;
124
+ const files = diff.files.map((file) => {
125
+ if (file.path !== CORRECTIONS_FILE || !("patch" in file))
126
+ return file;
127
+ const patch = withoutContext(file.patch, gone);
128
+ if (patch === file.patch)
129
+ return file;
130
+ changed = true;
131
+ return { ...file, patch };
132
+ });
133
+ if (!changed)
134
+ continue;
135
+ await ws.write(`${DIFFS_DIR}/${name}`, `${JSON.stringify({ ...diff, files })}\n`).catch((error) => { throw folderFailure(error); });
136
+ }
137
+ }
138
+ for (const name of mine)
139
+ await ws.remove(`${DIFFS_DIR}/${name}`, { force: true }).catch((error) => { throw folderFailure(error); });
140
+ return commit ? { commit } : {};
141
+ }
142
+ /** Each learned workflow on main whose workflow.json run `runId` wrote last (SnapLearned.run, the rule purged-workflow.ts
143
+ * reads) put back in one host commit as it stood at the newest commit where its writer was no purged run (`purged`,
144
+ * `runId` among them), every file of its `workflows/<name>/` folder, its writer that run again (the commit's
145
+ * `Written-By` line: folder.ts writerOf); taken off main whole when the purged runs wrote every version of it. So a
146
+ * purge takes off main only what purged runs put there, and a version another run wrote, a champion included, stays
147
+ * served. The commit, or undefined when main holds none of the run's (a repeat finds its own put back, and one another
148
+ * run wrote since names that run). The snapshot is rebuilt from main first (two execs and a checkout): a merge that
149
+ * moved main and stopped before its snapshot leaves one that names none of that merge's workflows, and finding no work
150
+ * commits nothing that would show it stale. One more read-only exec of main's history when the run wrote one, and one
151
+ * per version put back; either read finding nothing refuses (FolderUnreadable), so no guess takes a folder off. */
152
+ async function forgetRunWorkflows(ws, runId, purged) {
153
+ if (await readSnapshot(ws))
154
+ await learningRepair(ws);
155
+ const done = await writeLearning(ws, async ({ snapshot }) => {
156
+ const mine = (snapshot?.workflows ?? []).filter((item) => item.run === runId);
157
+ if (!mine.length)
158
+ return { result: false };
159
+ // No history read, no guess: a purge that can't tell what came before the run's version refuses (503, sent again
160
+ // later), and never takes the whole folder off main.
161
+ const unread = () => new FolderUnreadable(false, "the learning folder's history at main can't be read, so a purge puts nothing back and takes nothing off: send the DELETE again");
162
+ const history = await folderAt(ws, snapshot.main);
163
+ if (!history)
164
+ throw unread();
165
+ const writes = [];
166
+ const deletes = [];
167
+ const written = {};
168
+ for (const item of mine) {
169
+ // Newest first: the first writer no purged run is the version to put back, as it stood just before the next
170
+ // writer took the file over.
171
+ const writers = history.writers(item.name);
172
+ let back = [];
173
+ for (let i = 1; i < writers.length; i++) {
174
+ const { run } = writers[i];
175
+ if (run !== null && (await purged(run)))
176
+ continue;
177
+ const before = writers[i - 1].before;
178
+ const at = before ? await folderAt(ws, before) : undefined;
179
+ if (!at)
180
+ throw unread();
181
+ const files = at.snapshot.workflows.find((one) => one.name === item.name)?.files ?? [];
182
+ back = files.map(({ path, oid }) => ({ path, text: at.blobs.get(oid).toString("utf8") }));
183
+ // Named even when `back` is main's bytes already, so the writer still moves (folder.ts writtenIn).
184
+ if (back.length)
185
+ written[item.name] = run;
186
+ break;
187
+ }
188
+ writes.push(...back);
189
+ deletes.push(...[...item.files.map(({ path }) => path), ...(item.links ?? [])].filter((path) => !back.some((file) => file.path === path)));
190
+ }
191
+ const host = writes.length ? "a purged run's workflows put back as they were before it" : "a purged run's workflows removed";
192
+ return { result: true, change: { by: { host, written }, writes, deletes } };
193
+ });
194
+ return done.result ? done.main : undefined;
195
+ }
196
+ /** The names in the folder's diffs directory; none when it is not there. */
197
+ const diffNames = (ws) => ws.list(DIFFS_DIR).then((entries) => entries.filter((entry) => entry.kind === "file").map((entry) => entry.name), (error) => (isWorkspaceError(error, "NOT_FOUND") ? [] : Promise.reject(folderFailure(error))));
198
+ /** A merge's diff file, `<key>.json`; not one a stopped write left half written (`.json.<suffix>`). */
199
+ const isDiffFile = (name) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.json$/.test(name);
200
+ /** Diff file `name` as readRunDiff reads it, or undefined when it does not read as one: a folder that can't be read
201
+ * throws. */
202
+ const diffOrNone = (ws, name) => readRunDiff(ws, name.slice(0, -".json".length)).catch((error) => (error instanceof FolderUnreadable ? Promise.reject(error) : undefined));
203
+ /** The lines a patch (git's hunks) adds and does not take away: what a merge appended. */
204
+ function addedLines(patch) {
205
+ const lines = patch.split("\n");
206
+ const taken = new Map();
207
+ for (const line of lines)
208
+ if (line.startsWith("-"))
209
+ taken.set(line.slice(1), (taken.get(line.slice(1)) ?? 0) + 1);
210
+ return lines.filter((line) => line.startsWith("+")).map((line) => line.slice(1)).filter((line) => {
211
+ const left = taken.get(line) ?? 0;
212
+ if (left)
213
+ taken.set(line, left - 1);
214
+ return !left && line.trim() !== "";
215
+ });
216
+ }
217
+ /** `text` with the last line equal to each of `lines` left out. */
218
+ function withoutLines(text, lines) {
219
+ const kept = text.split("\n");
220
+ for (const line of lines) {
221
+ const at = kept.lastIndexOf(line);
222
+ if (at >= 0)
223
+ kept.splice(at, 1);
224
+ }
225
+ return kept.join("\n");
226
+ }
227
+ /** `patch` (git's hunks) with each context line that is one of `gone` left out, a hunk that lost one given the header
228
+ * of what it keeps: the start moved past the lines it lost at its top (git names the line before when it keeps none
229
+ * on a side), each count less what it lost. */
230
+ function withoutContext(patch, gone) {
231
+ const lines = patch.split("\n");
232
+ const out = [];
233
+ const dropped = (line) => line.startsWith(" ") && gone.has(line.slice(1));
234
+ for (let i = 0; i < lines.length;) {
235
+ const head = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/.exec(lines[i]);
236
+ if (!head) {
237
+ out.push(lines[i++]);
238
+ continue;
239
+ }
240
+ let end = i + 1;
241
+ while (end < lines.length && !lines[end].startsWith("@@"))
242
+ end++;
243
+ const body = lines.slice(i + 1, end);
244
+ const kept = body.filter((line) => !dropped(line));
245
+ const lost = body.length - kept.length;
246
+ if (!lost)
247
+ out.push(lines[i], ...body);
248
+ else {
249
+ const top = body.findIndex((line) => !dropped(line));
250
+ const lead = top < 0 ? lost : top;
251
+ const [olds, news] = [Number(head[2] ?? 1) - lost, Number(head[4] ?? 1) - lost];
252
+ const at = (start, count) => Number(start) + lead - (count ? 0 : 1);
253
+ out.push(`@@ -${at(head[1], olds)},${olds} +${at(head[3], news)},${news} @@${head[5]}`, ...kept);
254
+ }
255
+ i = end;
256
+ }
257
+ return out.join("\n");
258
+ }