@parcha/agentrun-dsl 0.1.0-beta.2 → 0.1.0-beta.20

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 (102) hide show
  1. package/README.md +46 -16
  2. package/dist/author.d.ts +96 -0
  3. package/dist/author.js +320 -0
  4. package/dist/authoring.js +1 -1
  5. package/dist/cli.js +8 -3
  6. package/dist/code-exec.d.ts +6 -0
  7. package/dist/code-exec.js +126 -0
  8. package/dist/decision-receipts.d.ts +98 -0
  9. package/dist/decision-receipts.js +51 -0
  10. package/dist/dry-run.d.ts +14 -1
  11. package/dist/dry-run.js +39 -13
  12. package/dist/graph.d.ts +83 -0
  13. package/dist/graph.js +231 -0
  14. package/dist/index.d.ts +12 -4
  15. package/dist/index.js +6 -2
  16. package/dist/inspection.js +2 -2
  17. package/dist/job.d.ts +14 -0
  18. package/dist/job.js +5 -0
  19. package/dist/long-timer.d.ts +7 -0
  20. package/dist/long-timer.js +22 -0
  21. package/dist/observer-snapshot.d.ts +3 -0
  22. package/dist/observer-snapshot.js +46 -0
  23. package/dist/predicates.d.ts +4 -0
  24. package/dist/predicates.js +19 -2
  25. package/dist/recovery/binding.d.ts +10 -0
  26. package/dist/recovery/binding.js +43 -0
  27. package/dist/recovery/call-key.d.ts +13 -0
  28. package/dist/recovery/call-key.js +24 -0
  29. package/dist/recovery/canonical-hash.d.ts +7 -0
  30. package/dist/recovery/canonical-hash.js +22 -0
  31. package/dist/recovery/driver.d.ts +208 -0
  32. package/dist/recovery/driver.js +1222 -0
  33. package/dist/recovery/effect-failure.d.ts +34 -0
  34. package/dist/recovery/effect-failure.js +62 -0
  35. package/dist/recovery/errors.d.ts +31 -0
  36. package/dist/recovery/errors.js +51 -0
  37. package/dist/recovery/execution-path.d.ts +53 -0
  38. package/dist/recovery/execution-path.js +167 -0
  39. package/dist/recovery/file-store.d.ts +7 -0
  40. package/dist/recovery/file-store.js +131 -0
  41. package/dist/recovery/frozen-snapshot.d.ts +244 -0
  42. package/dist/recovery/frozen-snapshot.js +171 -0
  43. package/dist/recovery/handoff-block.d.ts +36 -0
  44. package/dist/recovery/handoff-block.js +148 -0
  45. package/dist/recovery/handoff-digest.d.ts +58 -0
  46. package/dist/recovery/handoff-digest.js +195 -0
  47. package/dist/recovery/handoff-files.d.ts +54 -0
  48. package/dist/recovery/handoff-files.js +162 -0
  49. package/dist/recovery/handoff-receipts.d.ts +42 -0
  50. package/dist/recovery/handoff-receipts.js +53 -0
  51. package/dist/recovery/handoff-redact.d.ts +12 -0
  52. package/dist/recovery/handoff-redact.js +44 -0
  53. package/dist/recovery/handoff.d.ts +44 -0
  54. package/dist/recovery/handoff.js +46 -0
  55. package/dist/recovery/index.d.ts +18 -0
  56. package/dist/recovery/index.js +16 -0
  57. package/dist/recovery/item-state.d.ts +48 -0
  58. package/dist/recovery/item-state.js +89 -0
  59. package/dist/recovery/journal.d.ts +28 -0
  60. package/dist/recovery/journal.js +139 -0
  61. package/dist/recovery/memory-store.d.ts +4 -0
  62. package/dist/recovery/memory-store.js +20 -0
  63. package/dist/recovery/store.d.ts +105 -0
  64. package/dist/recovery/store.js +6 -0
  65. package/dist/recovery/testing/conformance.d.ts +4 -0
  66. package/dist/recovery/testing/conformance.js +268 -0
  67. package/dist/recovery/testing/crash-points.d.ts +18 -0
  68. package/dist/recovery/testing/crash-points.js +43 -0
  69. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  70. package/dist/recovery/testing/crash-sweep.js +146 -0
  71. package/dist/recovery/testing/index.d.ts +3 -0
  72. package/dist/recovery/testing/index.js +4 -0
  73. package/dist/recovery/testing/preload.d.ts +1 -0
  74. package/dist/recovery/testing/preload.js +3 -0
  75. package/dist/recovery/transport-facts.d.ts +23 -0
  76. package/dist/recovery/transport-facts.js +46 -0
  77. package/dist/recovery/with-recovery.d.ts +44 -0
  78. package/dist/recovery/with-recovery.js +87 -0
  79. package/dist/system-one.d.ts +17 -1
  80. package/dist/system-one.js +62 -5
  81. package/dist/vocabulary.d.ts +42 -0
  82. package/dist/vocabulary.js +74 -0
  83. package/dist/workflow-shape.d.ts +7 -0
  84. package/dist/workflow-shape.js +85 -62
  85. package/dist/workflow.d.ts +187 -16
  86. package/dist/workflow.js +967 -324
  87. package/package.json +18 -2
  88. package/schema/workflow.schema.json +251 -15
  89. package/skills/author/SKILL.md +122 -0
  90. package/skills/author/examples/evidence-gate.input.json +6 -0
  91. package/skills/author/examples/evidence-gate.json +125 -0
  92. package/skills/author/examples/read-file.input.json +1 -0
  93. package/skills/author/examples/read-file.json +44 -0
  94. package/skills/author/examples/read-source-decision.input.json +4 -0
  95. package/skills/author/examples/read-source-decision.json +37 -0
  96. package/skills/author/examples/release-note.txt +10 -0
  97. package/skills/author/examples/review-release-notes.input.json +6 -0
  98. package/skills/author/examples/review-release-notes.json +123 -0
  99. package/skills/author/references/jev-decisions.md +125 -0
  100. package/skills/author/references/language.md +118 -0
  101. package/skills/author/references/sdk-authoring.md +11 -0
  102. package/skills/author/references/workflow-format.md +137 -0
@@ -0,0 +1,1222 @@
1
+ // The recovery driver: the durable state of one workflow run, addressed by the interpreter's execution paths. Execution
2
+ // stays in the interpreter. The driver implements its `recovery` hooks over a RecoveryStore, admits each effect before
3
+ // it is dispatched, and holds each LLM step's record, each route's decision and the escalation that ends a run.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import { desugarWorkflow, isItemFailure } from "../workflow.js";
8
+ import { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, topLevelCompletion } from "./execution-path.js";
9
+ import { bindingDigests, LEDGER_FORMAT } from "./binding.js";
10
+ import { canonicalHash as hash } from "./canonical-hash.js";
11
+ import { RecoveryError } from "./errors.js";
12
+ import { gatewayIntentOf } from "./handoff-receipts.js";
13
+ import { validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, stateDelta, applyStateDelta, isItemOutcome } from "./frozen-snapshot.js";
14
+ const failure = (code, message) => new RecoveryError(message, code);
15
+ /** The branch a route runs for its answer, as the interpreter takes it: the node's `unsure` branch when
16
+ * the answer's confidence is below `unsure.gte`, else the choice the answer names. */
17
+ export function routeTaken(node, answers) {
18
+ const answer = answers?.branch;
19
+ const choice = String(answer?.choice ?? "");
20
+ const unsure = Boolean(node.unsure && typeof answer?.confidence === "number" && answer.confidence < node.unsure.gte);
21
+ return { branch: unsure ? node.unsure.branch : choice, choice, unsure };
22
+ }
23
+ /** A path the driver cannot place: the path is in the message, so the fault names where it happened. */
24
+ const pathFault = (at, message) => failure("FROZEN_PATH_INVALID", `${message}: ${typeof at === "string" ? at : JSON.stringify(at)}`);
25
+ /** Completes the route decisions of a checkpoint that holds a decision without `choice` and `unsure`:
26
+ * each takes the branch, the choice and the flag `routeTaken` derives from its stored answer, so a
27
+ * decision whose answer was unsure names the unsure branch it ran, never the answer's choice. */
28
+ function completeRouteDecisions(frame, doc) {
29
+ for (const [at, decision] of Object.entries(frame.routes)) {
30
+ if (typeof decision.choice === "string" && typeof decision.unsure === "boolean")
31
+ continue;
32
+ const node = nodeAt(doc, at);
33
+ if (node?.node !== "route")
34
+ throw pathFault(at, "Only a route's answer is a decision");
35
+ Object.assign(decision, routeTaken(node, decision.result.answers));
36
+ }
37
+ }
38
+ const LLM_KINDS = new Set(["agent", "decide", "extract", "report"]);
39
+ /** What a run's binding covers: the workflow as authored and what the host binds beside it, never the build. A run
40
+ * resumes across a deploy, and is refused when one of these changed: changing any of them is a new run. */
41
+ const bindingParts = (workflow, bind) => ({ engine: "frozen.v2", ledger: LEDGER_FORMAT, workflow, ...bind });
42
+ /** The binding of a run of `workflow` under what the host binds beside it. */
43
+ export function recoveryBinding(workflow, bind) {
44
+ return hash(bindingParts(workflow, bind));
45
+ }
46
+ /** What a store is opened under for a run of `workflow`: its binding, and the digest of each input the binding
47
+ * covers. The driver opens its store under it, and so does an operator who reconciles an effect by hand. */
48
+ export function recoveryBound(workflow, bind) {
49
+ return { binding: recoveryBinding(workflow, bind), inputs: bindingDigests(bindingParts(workflow, bind)) };
50
+ }
51
+ /** The files of a workspace directory: a name is relative to it, and a file that resolves outside it is refused. */
52
+ export function workspaceFiles(cwd) {
53
+ /** The file a name reaches, followed link by link as the system follows it, whether or not anything is at the end
54
+ * yet: a link to a reserved file that does not exist still reaches that file. What does not exist is kept as
55
+ * written. */
56
+ const reached = (name) => {
57
+ const parts = (full) => path.relative(path.parse(full).root, full).split(path.sep).filter(Boolean);
58
+ const start = path.resolve(cwd, name);
59
+ let at = path.parse(start).root;
60
+ let pending = parts(start);
61
+ for (let links = 0; pending.length > 0;) {
62
+ const next = path.join(at, pending[0]);
63
+ let link;
64
+ try {
65
+ if (fs.lstatSync(next).isSymbolicLink())
66
+ link = fs.readlinkSync(next);
67
+ }
68
+ catch {
69
+ return path.join(at, ...pending);
70
+ }
71
+ pending = pending.slice(1);
72
+ if (link === undefined) {
73
+ at = next;
74
+ continue;
75
+ }
76
+ // A chain of links that never ends reaches no file: it is its own name.
77
+ if ((links += 1) > 40)
78
+ return path.join(next, ...pending);
79
+ const target = path.resolve(at, link);
80
+ at = path.parse(target).root;
81
+ pending = [...parts(target), ...pending];
82
+ }
83
+ return at;
84
+ };
85
+ /** The file itself, whatever names it has: two hard links are one file. */
86
+ const identity = (file) => {
87
+ try {
88
+ const stat = fs.statSync(file, { bigint: true });
89
+ return `${stat.dev}:${stat.ino}`;
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ };
95
+ return {
96
+ same: (a, b) => {
97
+ const [first, second] = [reached(a), reached(b)];
98
+ if (first === second)
99
+ return true;
100
+ const file = identity(first);
101
+ return file !== undefined && file === identity(second);
102
+ },
103
+ hashes: (names) => Object.fromEntries(names.map(name => {
104
+ let filename;
105
+ try {
106
+ filename = fs.realpathSync(path.resolve(cwd, name));
107
+ }
108
+ catch (error) {
109
+ // A promised file the workspace no longer holds (a store that travelled without it) is an invalid artifact, never a raw errno.
110
+ if (["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
111
+ throw failure("FROZEN_ARTIFACT_INVALID", `Recovery artifact is missing from the workspace: ${name}`);
112
+ throw error;
113
+ }
114
+ const relative = path.relative(fs.realpathSync(cwd), filename);
115
+ if (!relative || relative === ".." || relative.startsWith(".." + path.sep) || path.isAbsolute(relative)) {
116
+ throw failure("FROZEN_ARTIFACT_INVALID", "Recovery artifact escaped workspace");
117
+ }
118
+ return [name, createHash("sha256").update(fs.readFileSync(filename)).digest("hex")];
119
+ })),
120
+ };
121
+ }
122
+ /** Every file a node, or anything inside it, declares it writes: an artifact's path, a call's outputs. */
123
+ function declaredFiles(node, out = []) {
124
+ if (node.node === "artifact" && node.path)
125
+ out.push(node.path);
126
+ if (node.node === "call")
127
+ out.push(...(node.produces ?? []));
128
+ for (const child of childrenOf(node))
129
+ declaredFiles(child, out);
130
+ return out;
131
+ }
132
+ const labelOf = (node) => "label" in node && typeof node.label === "string" ? node.label : undefined;
133
+ /** Every label in the document, a child workflow's steps named `<invocation>/<step>` as the interpreter
134
+ * names them, so a label that appears twice is found. */
135
+ function labelsOf(node, prefix = "", out = []) {
136
+ const label = labelOf(node);
137
+ if (label !== undefined)
138
+ out.push(`${prefix}${label}`);
139
+ for (const child of childrenOf(node))
140
+ labelsOf(child, node.node === "workflow" ? `${prefix}${label}/` : prefix, out);
141
+ return out;
142
+ }
143
+ /** Opens the durable state of one run of `workflow` in `store` and takes ownership of it. Execution remains in the
144
+ * interpreter: the workflow runs with the returned driver's hooks, and `close` lets go of the run. */
145
+ export async function openRecovery(store, workflow, options) {
146
+ const reader = options.files ?? workspaceFiles(process.cwd());
147
+ const reservedOutputs = options.reservedOutputs ?? [];
148
+ const reserved = (name) => reservedOutputs.some(file => reader.same(name, file));
149
+ /** A refusal found before any step runs: a workflow with a label on two nodes, or one that writes a file the host
150
+ * owns. The driver still opens (a run is durable whatever its shape), and the host ends the run through an
151
+ * escalation commit naming the refusal. */
152
+ const hostOwned = declaredFiles(workflow.root).find(reserved);
153
+ // Execution paths address every node; labels still name the node an escalation, a step record and a
154
+ // decision are about, so two nodes may not share one.
155
+ const labels = labelsOf(workflow.root);
156
+ const duplicate = labels.find((label, index) => labels.indexOf(label) !== index);
157
+ const preStepRefusal = duplicate !== undefined ? {
158
+ code: "RUN_CONTROL_UNSUPPORTED", kind: "duplicate_label", label: duplicate,
159
+ message: `Frozen workflow recovery requires unique labels; "${duplicate}" names two nodes`,
160
+ } : hostOwned !== undefined ? {
161
+ code: "RUN_CONTROL_UNSUPPORTED", kind: "host_owned_output", label: "workflow",
162
+ message: `Recovered artifacts must not overwrite ${reservedOutputs.length > 1 ? `${reservedOutputs.slice(0, -1).join(", ")} or ${reservedOutputs.at(-1)}` : reservedOutputs[0]}; the host owns those files, and the pin writes ${hostOwned}`,
163
+ } : null;
164
+ // The document the interpreter runs, and so the one its paths resolve in.
165
+ const view = options.view ?? desugarWorkflow(workflow);
166
+ const bound = recoveryBound(workflow, options.bind);
167
+ const binding = bound.binding;
168
+ const driver = options.key;
169
+ const controller = new AbortController();
170
+ let fatal;
171
+ /** A pause or cancel was applied: its commit still lands, and nothing after it. */
172
+ let stopping = false;
173
+ const journal = await store.open(bound);
174
+ /** Whether the store keeps parts beside the state: the keyed layout needs both reads. */
175
+ const keyed = typeof journal.items === "function" && typeof journal.stateOf === "function";
176
+ /** The keyed layout is in effect for this open, and why not when the host asked for it. `moving` is a run stored whole
177
+ * that takes the keyed layout at its first write that knows the base of every map still running in it: a map's base
178
+ * is the state it starts from, which the run's whole record does not hold, and the map names it when it resumes. */
179
+ let layoutV4 = false;
180
+ let moving = false;
181
+ let layoutReason;
182
+ // The keyed layout's bookkeeping: the maps the run started (with the base each item is kept against), the states
183
+ // already stored by digest, each item's record as last written (its revision aside), and the path that produced each
184
+ // file a map item owns.
185
+ const maps = new Map();
186
+ const writtenStates = new Set();
187
+ const lastItems = new Map();
188
+ const fileOwners = new Map();
189
+ /** At a restore: the files the driver's own record keeps (the latest write of each, whoever made it), and, for a file
190
+ * only item records keep, the revision of the record it was taken from (a later record's write is the latest). */
191
+ const driverFiles = new Set();
192
+ const fileRevisions = new Map();
193
+ /** The effects this process admitted, landed or still queued on the commit chain: an item's record lists each one it
194
+ * owns, even one whose admission has not landed when the record is built. */
195
+ const queued = new Set();
196
+ const deltas = new WeakMap();
197
+ const digests = new WeakMap();
198
+ const digestOf = (state) => { let digest = digests.get(state); if (digest === undefined) {
199
+ digest = hash(state);
200
+ digests.set(state, digest);
201
+ } return digest; };
202
+ const invalid = (message) => failure("FROZEN_CHECKPOINT_INVALID", message);
203
+ /** A state the run references by digest, read back and checked against it. */
204
+ const stateBy = async (sha256) => {
205
+ const state = await journal.stateOf(sha256);
206
+ if (!state || typeof state !== "object" || Array.isArray(state) || hash(state) !== sha256)
207
+ throw invalid(`The state ${sha256} the run references is missing or changed`);
208
+ writtenStates.add(sha256);
209
+ digests.set(state, sha256);
210
+ return state;
211
+ };
212
+ /** A value the run references by digest (a failed map's result, which may be any JSON value), read back and checked. */
213
+ const valueBy = async (sha256) => {
214
+ const value = await journal.stateOf(sha256);
215
+ if (value === undefined || hash(value) !== sha256)
216
+ throw invalid(`The value ${sha256} the run references is missing or changed`);
217
+ writtenStates.add(sha256);
218
+ return value;
219
+ };
220
+ const SHA = /^[a-f0-9]{64}$/;
221
+ const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
222
+ const validEntry = (entry) => isRecord(entry) && Number.isSafeInteger(entry.length) && entry.length >= 0
223
+ && Number.isSafeInteger(entry.items) && entry.items >= 0 && typeof entry.base === "string" && SHA.test(entry.base);
224
+ /** The path of map item `index` of the map at `mapPath`: the prefix the interpreter gives every path inside it. */
225
+ const itemPathOf = (mapPath, index) => `${mapPath}/items/${index}`;
226
+ /** Reads back the records of every item the maps in `table` wrote, merging into `snapshot` what lies in them: all of
227
+ * it for a map still running, and what a committed map's items keep in the whole state (their committed paths, step
228
+ * records, clocks, files and effects) for one that committed. Nested maps are read through their item. */
229
+ const restoreMaps = async (table, snapshot) => {
230
+ if (!isRecord(table))
231
+ throw invalid("The run's maps are not a record");
232
+ const frame = snapshot.pin;
233
+ for (const [mapPath, entry] of Object.entries(table)) {
234
+ if (!validEntry(entry) || nodeAt(view, mapPath)?.node !== "map")
235
+ throw invalid(`The map at ${mapPath} is not one this run can hold`);
236
+ const committed = frame.done.includes(mapPath);
237
+ const baseState = committed ? undefined : await stateBy(entry.base);
238
+ maps.set(mapPath, { length: entry.length, items: entry.items, base: entry.base, ...(baseState ? { baseState } : {}) });
239
+ const paths = Array.from({ length: entry.items }, (_, index) => itemPathOf(mapPath, index));
240
+ const records = await journal.items(paths);
241
+ for (const [index, item] of records.entries()) {
242
+ if (item === undefined)
243
+ continue;
244
+ const path = paths[index];
245
+ const record = item;
246
+ const valid = record.driver === driver && record.map === mapPath && record.index === index && record.base === entry.base && Number.isSafeInteger(record.revision)
247
+ && ["running", "committed", "failed"].includes(record.status) && isRecord(record.frame) && Array.isArray(record.frame.done)
248
+ && [record.frame.states, record.frame.chains, record.frame.loops, record.frame.routes, record.frame.inputs, record.frame.steps, record.clocks, record.files, record.unknownResponses, record.maps].every(isRecord)
249
+ && Array.isArray(record.effects) && record.effects.every((id) => typeof id === "string")
250
+ // An item that ended on its failure, and only one, holds how it ended; its map collects its items' failures.
251
+ && (record.status === "failed"
252
+ ? isItemOutcome(record.outcome) && nodeAt(view, mapPath)?.onItemFailure === "collect"
253
+ : record.outcome === undefined);
254
+ if (!valid)
255
+ throw invalid(`The record of map item ${path} is not one this run wrote`);
256
+ if (record.outcome)
257
+ (frame.failures ??= {})[path] = { ...record.outcome };
258
+ lastItems.set(path, JSON.stringify({ ...record, revision: 0 }));
259
+ frame.done.push(...record.frame.done);
260
+ Object.assign(frame.steps, record.frame.steps);
261
+ Object.assign(snapshot.clocks, record.clocks);
262
+ for (const [name, sha256] of Object.entries(record.files)) {
263
+ // A committed item keeps the record it last wrote, so a file a later step wrote again holds an older hash there.
264
+ if (driverFiles.has(name) || (fileRevisions.get(name) ?? -1) > record.revision)
265
+ continue;
266
+ snapshot.files[name] = sha256;
267
+ fileOwners.set(name, `${path}/body`);
268
+ fileRevisions.set(name, record.revision);
269
+ }
270
+ if (Object.keys(record.unknownResponses).length)
271
+ Object.assign(snapshot.unknownResponses ??= {}, record.unknownResponses);
272
+ if (!committed) {
273
+ for (const [at, delta] of Object.entries(record.frame.states)) {
274
+ if (!isRecord(delta) || !isRecord(delta.set) || !Array.isArray(delta.unset) || typeof delta.sha256 !== "string")
275
+ throw invalid(`The state at ${at} is not a delta`);
276
+ const state = applyStateDelta(baseState, delta);
277
+ if (hash(state) !== delta.sha256)
278
+ throw invalid(`The state at ${at} does not rebuild to the state that was committed`);
279
+ frame.states[at] = state;
280
+ deltas.set(state, delta);
281
+ digests.set(state, delta.sha256);
282
+ }
283
+ Object.assign(frame.chains, record.frame.chains);
284
+ Object.assign(frame.loops, record.frame.loops);
285
+ Object.assign(frame.routes, record.frame.routes);
286
+ Object.assign(frame.inputs, record.frame.inputs);
287
+ }
288
+ await restoreMaps(record.maps, snapshot);
289
+ }
290
+ }
291
+ };
292
+ /** The whole state of a run stored in the keyed layout: its own record with every state read back by digest, and what
293
+ * its map items keep. */
294
+ const restoreV4 = async (stored) => {
295
+ // A copy: what the items hold is merged into the restored frame, and the store's own state (which it writes back for
296
+ // a completion that names none) must stay the driver's record alone.
297
+ const { maps: table, pin, ...rest } = structuredClone(stored);
298
+ if (!isRecord(pin) || !isRecord(pin.states) || !Object.values(pin.states).every((sha256) => typeof sha256 === "string" && SHA.test(sha256)) || !Array.isArray(pin.done))
299
+ throw invalid("Invalid frozen recovery checkpoint");
300
+ const states = {};
301
+ for (const [at, sha256] of Object.entries(pin.states))
302
+ states[at] = await stateBy(sha256);
303
+ const restored = { ...rest, schema: FROZEN_SNAPSHOT_SCHEMA, pin: { ...pin, done: [...pin.done], states }, clocks: { ...rest.clocks }, files: { ...rest.files } };
304
+ for (const name of Object.keys(restored.files))
305
+ driverFiles.add(name);
306
+ // A failed map's finished results: the list of their slots is one value kept by its digest, each slot the digest of
307
+ // its result or null for an item that never finished.
308
+ if (pin.partial !== undefined) {
309
+ const partial = pin.partial;
310
+ if (!isRecord(partial) || typeof partial.path !== "string" || typeof partial.as !== "string" || typeof partial.results !== "string" || !SHA.test(partial.results)) {
311
+ throw invalid("A failed map's results are not kept by digest");
312
+ }
313
+ const slots = await valueBy(partial.results);
314
+ if (!Array.isArray(slots) || !slots.every((slot) => slot === null || (typeof slot === "string" && SHA.test(slot))))
315
+ throw invalid("A failed map's results are not a list of digests");
316
+ restored.pin.partial = { path: partial.path, as: partial.as, results: await Promise.all(slots.map((slot) => (slot === null ? null : valueBy(slot)))) };
317
+ }
318
+ await restoreMaps(table, restored);
319
+ return restored;
320
+ };
321
+ /** The host's stop as it was handed over (a cancel outranks a pause), and who issued it. */
322
+ let requested;
323
+ /** The one error the driver's stop is: its signal's reason and every refusal after it, naming the committed stop. */
324
+ let stopError;
325
+ let snapshot;
326
+ /** This process's ownership generation of the run: one per process that holds it. */
327
+ const generation = journal.generation;
328
+ const serial = () => serializeFrozenSnapshot(snapshot);
329
+ /** Files the run holds, with the path that produced them: a map item's file is kept in the item's record. */
330
+ const keepFiles = (files, at) => {
331
+ Object.assign(snapshot.files, files);
332
+ for (const name of Object.keys(files)) {
333
+ if (at === undefined)
334
+ fileOwners.delete(name);
335
+ else
336
+ fileOwners.set(name, at);
337
+ }
338
+ };
339
+ /** The path an effect clock belongs to: an attempt's effect, a poll's or a wait's node. */
340
+ const clockPath = (key) => {
341
+ if (key.startsWith("attempt:"))
342
+ return frozenEffectPath(key.slice("attempt:".length))?.path;
343
+ // poll:<tag>:<path>, and wait:<tag>:<path>:<ordinal>.
344
+ const poll = /^poll:[^:]+:(\/root.*)$/s.exec(key);
345
+ if (poll)
346
+ return poll[1];
347
+ const wait = /^wait:[^:]+:(\/root.*):\d+$/s.exec(key);
348
+ return wait ? wait[1] : undefined;
349
+ };
350
+ /** One write in the keyed layout: the driver's record without what lies in map items, the records of the items that
351
+ * changed, and the states first referenced now. `admitting` is an effect admitted in this write; `owner` the item that
352
+ * lists it. */
353
+ const keyedWrite = (admitting) => {
354
+ const frame = snapshot.pin;
355
+ const done = new Set(frame.done);
356
+ const builds = new Map();
357
+ /** The record a path lies in: undefined for the driver's own, null for an item of a map that committed (it keeps
358
+ * the record it last wrote). */
359
+ const own = (path) => {
360
+ const at = path === undefined ? undefined : mapItemOf(path);
361
+ if (!at)
362
+ return undefined;
363
+ // A committed map's items keep the records they last wrote; one that committed before the run took the keyed
364
+ // layout has none, and what lies in its items stays in the driver's record, as it was.
365
+ // A map that commits in the very write that moves the run has items with no record yet: they are written once, here.
366
+ if (done.has(at.map) && (!maps.has(at.map) || lastItems.has(at.item)))
367
+ return maps.has(at.map) ? null : undefined;
368
+ let build = builds.get(at.item);
369
+ if (!build) {
370
+ const map = maps.get(at.map);
371
+ if (!map)
372
+ throw invalid(`The map item ${at.item} belongs to no map this run started`);
373
+ build = { path: at.item, map: at.map, index: at.index, record: {
374
+ driver, map: at.map, index: at.index, base: map.base, revision: 0, status: "running",
375
+ frame: { done: [], states: {}, chains: {}, loops: {}, routes: {}, inputs: {}, steps: {} },
376
+ effects: [], clocks: {}, files: {}, unknownResponses: {}, maps: {},
377
+ } };
378
+ builds.set(at.item, build);
379
+ }
380
+ return build;
381
+ };
382
+ const states = {};
383
+ const kept = (state) => {
384
+ const digest = digestOf(state);
385
+ if (!writtenStates.has(digest)) {
386
+ writtenStates.add(digest);
387
+ states[digest] = state;
388
+ }
389
+ return digest;
390
+ };
391
+ /** A failed map's result, which may be any JSON value, kept once by its digest. */
392
+ const keptValue = (value) => {
393
+ if (isRecord(value))
394
+ return kept(value);
395
+ const digest = hash(value);
396
+ if (!writtenStates.has(digest)) {
397
+ writtenStates.add(digest);
398
+ states[digest] = value;
399
+ }
400
+ return digest;
401
+ };
402
+ const deltaOf = (map, state) => {
403
+ const known = deltas.get(state);
404
+ if (known)
405
+ return known;
406
+ const base = maps.get(map)?.baseState;
407
+ if (!base)
408
+ throw invalid(`The base of the map at ${map} is not known`);
409
+ const delta = stateDelta(base, state, digestOf(state));
410
+ deltas.set(state, delta);
411
+ return delta;
412
+ };
413
+ const pin = { input: frame.input, done: [], states: {}, chains: {}, loops: {}, routes: {}, inputs: {}, steps: {},
414
+ // A failed map's results: one digest, of the list of each result's digest (null for an item that never finished).
415
+ ...(frame.partial ? { partial: { path: frame.partial.path, as: frame.partial.as, results: keptValue(frame.partial.results.map((result) => (result === null || result === undefined ? null : keptValue(result)))) } } : {}) };
416
+ for (const at of frame.done) {
417
+ const build = own(at);
418
+ if (build === undefined)
419
+ pin.done.push(at);
420
+ else if (build)
421
+ build.record.frame.done.push(at);
422
+ }
423
+ for (const [at, state] of Object.entries(frame.states)) {
424
+ const build = own(at);
425
+ if (build === undefined)
426
+ pin.states[at] = kept(state);
427
+ else if (build)
428
+ build.record.frame.states[at] = deltaOf(build.map, state);
429
+ }
430
+ for (const table of ["chains", "loops", "routes", "inputs", "steps"]) {
431
+ for (const [at, value] of Object.entries(frame[table])) {
432
+ const build = own(at);
433
+ if (build === undefined)
434
+ pin[table][at] = value;
435
+ else if (build)
436
+ build.record.frame[table][at] = value;
437
+ }
438
+ }
439
+ const clocks = {};
440
+ for (const [key, value] of Object.entries(snapshot.clocks)) {
441
+ const build = own(clockPath(key));
442
+ if (build === undefined)
443
+ clocks[key] = value;
444
+ else if (build)
445
+ build.record.clocks[key] = value;
446
+ }
447
+ const files = {};
448
+ for (const [name, sha256] of Object.entries(snapshot.files)) {
449
+ const build = own(fileOwners.get(name));
450
+ if (build === undefined)
451
+ files[name] = sha256;
452
+ else if (build)
453
+ build.record.files[name] = sha256;
454
+ }
455
+ const unknownResponses = {};
456
+ for (const [id, value] of Object.entries(snapshot.unknownResponses ?? {})) {
457
+ const build = own(frozenEffectPath(id)?.path);
458
+ if (build === undefined)
459
+ unknownResponses[id] = value;
460
+ else if (build)
461
+ build.record.unknownResponses[id] = value;
462
+ }
463
+ // An item that ended on its failure keeps it in its own record.
464
+ for (const [item, outcome] of Object.entries(frame.failures ?? {})) {
465
+ const build = own(`${item}/body`);
466
+ if (build === undefined)
467
+ (pin.failures ??= {})[item] = outcome;
468
+ else if (build)
469
+ build.record.outcome = outcome;
470
+ }
471
+ for (const id of new Set([...journal.effects().map((effect) => effect.id), ...queued, ...(admitting === undefined ? [] : [admitting])])) {
472
+ const build = own(frozenEffectPath(id)?.path);
473
+ if (build)
474
+ build.record.effects.push(id);
475
+ }
476
+ // A map's item records are the first ones: count them before the maps are written.
477
+ for (const build of builds.values()) {
478
+ const map = maps.get(build.map);
479
+ map.items = Math.max(map.items, build.index + 1);
480
+ }
481
+ const table = {};
482
+ for (const [at, map] of maps) {
483
+ const build = own(at);
484
+ const entry = { length: map.length, items: map.items, base: map.base };
485
+ if (build === undefined)
486
+ table[at] = entry;
487
+ else if (build)
488
+ build.record.maps[at] = entry;
489
+ if (!done.has(at) && map.baseState)
490
+ kept(map.baseState);
491
+ }
492
+ /** An item is done when its body committed: a chain never commits itself, so the last step a chain body runs
493
+ * through, descending through nested chains, is where the body ends. */
494
+ const finished = (item) => {
495
+ let at = `${item}/body`;
496
+ let node = nodeAt(view, at);
497
+ while (node?.node === "chain" && node.steps.length > 0) {
498
+ at = `${at}/steps/${node.steps.length - 1}`;
499
+ node = node.steps[node.steps.length - 1];
500
+ }
501
+ return done.has(at);
502
+ };
503
+ const items = {};
504
+ for (const build of builds.values()) {
505
+ build.record.status = build.record.outcome ? "failed" : finished(build.path) ? "committed" : "running";
506
+ const text = JSON.stringify(build.record);
507
+ if (lastItems.get(build.path) !== text) {
508
+ lastItems.set(build.path, text);
509
+ items[build.path] = build.record;
510
+ }
511
+ }
512
+ const { pin: _pin, schema: _schema, clocks: _clocks, files: _files, unknownResponses: _unknown, ...rest } = snapshot;
513
+ const state = serializeFrozenSnapshot({ ...rest, schema: FROZEN_SNAPSHOT_SCHEMA_V4, pin, clocks, files,
514
+ ...(Object.keys(unknownResponses).length ? { unknownResponses } : {}), maps: table });
515
+ const owner = admitting === undefined ? undefined : (own(frozenEffectPath(admitting)?.path) ?? undefined)?.path;
516
+ return { state, parts: (revision) => ({ items: Object.fromEntries(Object.entries(items).map(([path, item]) => [path, { ...item, revision }])), states }), ...(owner ? { owner } : {}) };
517
+ };
518
+ /** Whether every map still running with something in its items has its base: then a run stored whole can move. */
519
+ const basesKnown = () => {
520
+ const frame = snapshot.pin;
521
+ const done = new Set(frame.done);
522
+ const paths = [...frame.done, ...Object.keys(frame.states), ...Object.keys(frame.chains), ...Object.keys(frame.inputs), ...Object.keys(frame.steps),
523
+ ...Object.keys(frame.loops), ...Object.keys(frame.routes), ...Object.keys(frame.failures ?? {}).map((item) => `${item}/body`)];
524
+ return paths.every((path) => { const at = mapItemOf(path); return !at || done.has(at.map) || Boolean(maps.get(at.map)?.baseState); });
525
+ };
526
+ /** One write of the driver's state, in the layout this open keeps. */
527
+ const writeOf = (admitting) => {
528
+ if (admitting !== undefined)
529
+ queued.add(admitting);
530
+ if (moving && basesKnown()) {
531
+ moving = false;
532
+ layoutV4 = true;
533
+ }
534
+ return layoutV4 ? keyedWrite(admitting) : { state: serial() };
535
+ };
536
+ /** The journal's commits, in the order the driver made them: a commit a synchronous method starts lands before any
537
+ * later one, and an effect's admission waits for every earlier commit. A failed commit stops the run. */
538
+ let chain = Promise.resolve();
539
+ const persist = (write) => {
540
+ const next = chain.then(() => { if (fatal && !stopping)
541
+ throw fatal; return write(); });
542
+ chain = next.catch((error) => { if (!fatal) {
543
+ fatal = error;
544
+ controller.abort(error);
545
+ } });
546
+ return next;
547
+ };
548
+ /** Every commit the driver started has landed; a failed one is thrown. */
549
+ const flush = async () => { await chain; if (fatal && !stopping)
550
+ throw fatal; };
551
+ try {
552
+ // A driver an earlier process bound, with no checkpoint, is a run killed between its binding and its first
553
+ // checkpoint when the journal holds nothing else of it: it never started, and it starts now. One with effects and
554
+ // no checkpoint needs reconciliation.
555
+ const stored = journal.state;
556
+ // A run a later build stored in a schema this build does not know: refused with its own code, so a host leaves the
557
+ // run for a build that knows it rather than ending it.
558
+ const known = [FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4];
559
+ const found = stored?.schema;
560
+ const version = typeof found === "string" ? /^agentrun\.frozen_run\.v(\d+)$/.exec(found)?.[1] : undefined;
561
+ if (version !== undefined && !known.includes(found) && Number(version) > 4) {
562
+ throw Object.assign(new RecoveryError(`This run is stored as ${found}, newer than this build knows (${known.join(", ")}); open it with a build that knows it`, "RECOVERY_SCHEMA_NEWER"), { found, known });
563
+ }
564
+ // The keyed layout is sticky: a run stored in it stays in it. A run stored whole, or a new one, takes it when the
565
+ // host asks for it and the store keeps parts.
566
+ if (stored?.schema === FROZEN_SNAPSHOT_SCHEMA_V4) {
567
+ if (!keyed)
568
+ throw invalid("This run is stored in the keyed layout (agentrun.frozen_run.v4), and this store keeps no parts");
569
+ layoutV4 = true;
570
+ }
571
+ else {
572
+ moving = options.layout === "v4" && keyed;
573
+ if (options.layout === "v4" && !keyed)
574
+ layoutReason = "the store keeps no parts (its journal has no items and stateOf)";
575
+ }
576
+ const saved = stored?.schema === FROZEN_SNAPSHOT_SCHEMA_V4 ? await restoreV4(stored) : stored;
577
+ if (journal.existing && !saved && journal.effects().length > 0)
578
+ throw failure("FROZEN_CHECKPOINT_INVALID", "Existing frozen run has no checkpoint; retained workspace requires reconciliation");
579
+ // Only the paths of the run's own document are resolved.
580
+ if (saved)
581
+ validateFrozenSnapshot(saved, { resolves: (at) => Boolean(nodeAt(view, at)) });
582
+ snapshot = openedFrozenSnapshot(saved);
583
+ // A route decision a checkpoint holds without the choice and the unsure flag holds the
584
+ // answer whole: the branch taken, the choice and the flag are derived from it by the
585
+ // interpreter's rule, and the commit below stores them.
586
+ completeRouteDecisions(snapshot.pin, view);
587
+ const left = journal.effects().filter((effect) => effect.status === "unknown");
588
+ if (options.reconcile && left.length > 0) {
589
+ let reconciling = true;
590
+ try {
591
+ await options.reconcile(structuredClone(left), async (id, value, receipt) => {
592
+ if (!reconciling)
593
+ throw failure("RECOVERY_RECONCILE_FAILED", `Reconcile ${id} after reconcile returned`);
594
+ if (!left.some((effect) => effect.id === id))
595
+ throw failure("RECOVERY_RECONCILE_FAILED", `Reconcile ${id}: not an unknown effect of this run`);
596
+ // The files the effect declares are hashed now, as a normal completion records them: a missing output refuses the
597
+ // settlement, and a later resume refuses an output that changed.
598
+ const at = frozenEffectPath(id)?.path;
599
+ const declared = at === undefined ? undefined : nodeAt(view, at);
600
+ const files = reader.hashes(declared?.node === "call" ? declared.produces ?? [] : []);
601
+ keepFiles(files, at);
602
+ // The calls an earlier process kept stay: the host's re-send is added after them, so a call that applied before the kill is still on record.
603
+ if (receipt?.calls?.length)
604
+ await journal.called(id, [...(journal.effect(id)?.calls ?? []), ...receipt.calls]);
605
+ await journal.complete(id, { value, files, ...(receipt?.intent ? { intent: receipt.intent } : {}) });
606
+ });
607
+ }
608
+ catch (error) {
609
+ throw error instanceof RecoveryError && error.code === "RECOVERY_RECONCILE_FAILED" ? error
610
+ : new RecoveryError(`Reconcile failed: ${error instanceof Error ? error.message : String(error)}`, "RECOVERY_RECONCILE_FAILED", { cause: error });
611
+ }
612
+ finally {
613
+ reconciling = false;
614
+ }
615
+ }
616
+ // The open's commit: a run stored whole that takes the keyed layout moves to it here, whole or not at all.
617
+ const opening = writeOf();
618
+ const layoutNote = layoutReason ? { kind: "layout", detail: { schema: FROZEN_SNAPSHOT_SCHEMA, reason: layoutReason } } : undefined;
619
+ await journal.save(opening.state, layoutNote, opening.parts);
620
+ }
621
+ catch (error) {
622
+ await journal.close();
623
+ throw error;
624
+ }
625
+ const ordinals = new Map();
626
+ /** One commit of the driver's state. */
627
+ const save = () => {
628
+ const write = writeOf();
629
+ // A synchronous method does not wait for it; the failure is the run's, and the next awaited commit throws it.
630
+ return persist(() => journal.save(write.state, undefined, write.parts)).catch(() => undefined);
631
+ };
632
+ /** Effects dispatched and not yet completed or failed. A pause is not taken while one is in flight. */
633
+ let inFlight = 0;
634
+ /** New work waiting at a seam for a pause to be taken, woken when the last effect in flight ends or a stop is taken. */
635
+ let drained;
636
+ const wake = () => { const waiting = drained; drained = undefined; waiting?.wake(); };
637
+ const pausePending = () => !fatal && requested?.action === "pause" && snapshot.status !== "paused" && inFlight > 0;
638
+ const guard = () => {
639
+ if (fatal)
640
+ throw fatal;
641
+ try {
642
+ // The driver owns the run-wide pause and cancel; its steps stop through its signal. A pause waits for every
643
+ // effect in flight to complete and commit; a cancel does not.
644
+ const stop = frozenStop(snapshot.status, requested?.action);
645
+ if (stop === "paused" && inFlight > 0)
646
+ return;
647
+ if (stop) {
648
+ snapshot.status = stop;
649
+ // The stopped state is still committed, after which nothing else is.
650
+ stopping = true;
651
+ const error = stopError = new RecoveryError(`Frozen run ${snapshot.status}`, stop === "cancelled" ? "FROZEN_CANCELLED" : "FROZEN_PAUSED", { source: requested?.source });
652
+ fatal = error;
653
+ controller.abort(error);
654
+ void save();
655
+ throw error;
656
+ }
657
+ }
658
+ catch (error) {
659
+ if (!fatal) {
660
+ fatal = error;
661
+ controller.abort(error);
662
+ }
663
+ throw error;
664
+ }
665
+ };
666
+ /** A seam: where new work starts. While a pause waits for an effect in flight, new work waits here; then the pause
667
+ * is taken and the work is refused with it. */
668
+ const seam = async () => {
669
+ while (pausePending()) {
670
+ if (!drained) {
671
+ let wake;
672
+ drained = { promise: new Promise((resolve) => { wake = resolve; }), wake };
673
+ }
674
+ await drained.promise;
675
+ }
676
+ guard();
677
+ };
678
+ /** An effect in flight has ended. The last one lets a waiting pause be taken. */
679
+ const settled = () => {
680
+ inFlight -= 1;
681
+ if (inFlight > 0)
682
+ return;
683
+ if (requested?.action === "pause") {
684
+ try {
685
+ guard();
686
+ }
687
+ catch { /* The pause is taken: its commit is queued. */ }
688
+ }
689
+ wake();
690
+ };
691
+ const fileHashes = (names) => reader.hashes(names);
692
+ const verifyFiles = (files) => {
693
+ if (hash(fileHashes(Object.keys(files))) !== hash(files))
694
+ throw failure("FROZEN_ARTIFACT_INVALID", "Committed artifact bytes changed; effect will not be repeated");
695
+ };
696
+ /** An effect-level clock is set once and kept across resume: a poll window or an attempt deadline
697
+ * belongs to the outside world, so downtime counts against it, never against the run. */
698
+ const clock = (key, duration) => {
699
+ if (snapshot.clocks[key] === undefined) {
700
+ snapshot.clocks[key] = Date.now() + duration;
701
+ save();
702
+ }
703
+ if (!Number.isFinite(snapshot.clocks[key]))
704
+ throw failure("FROZEN_CHECKPOINT_INVALID", "Invalid durable clock");
705
+ return snapshot.clocks[key];
706
+ };
707
+ // A row that names a commit is checked against the journal: the escalation row's revision is an
708
+ // escalation commit, or the checkpoint is refused. A placeholder revision never survives a resume.
709
+ const escalated = snapshot.escalation;
710
+ if (escalated && !(escalated.revision >= 1 && journal.notes().some((note) => note.revision === escalated.revision && note.kind === "escalation"))) {
711
+ await journal.close();
712
+ throw failure("FROZEN_CHECKPOINT_INVALID", `The escalation row names revision ${escalated.revision}, which is not an escalation commit`);
713
+ }
714
+ /** The frame the interpreter is running: the run's document. Its tag names its sessions and effects. */
715
+ const active = () => ({ frame: snapshot.pin, tag: "step", doc: view });
716
+ const doneSets = new WeakMap();
717
+ const doneOf = (frame) => doneSets.get(frame) ?? doneSets.set(frame, new Set(frame.done)).get(frame);
718
+ /** Frames whose document input this process has checked: the first resume of a process starts the
719
+ * document, so it is where a changed input shows. */
720
+ const inputChecked = new WeakSet();
721
+ /** The path the interpreter named, when it resolves in the running document. */
722
+ const placed = (at, doc) => {
723
+ if (typeof at !== "string" || !nodeAt(doc, at))
724
+ throw pathFault(at, "The interpreter named a path this run's document does not hold");
725
+ return at;
726
+ };
727
+ /** The committed state a resume at `at` is answered from: its own, or the frontier of a chain it sits
728
+ * in when the frontier lies past it. A chain threads one state, so every step before its frontier,
729
+ * and everything inside those steps, is answered with the frontier's. */
730
+ const answer = (frame, at) => {
731
+ if (frame.states[at])
732
+ return frame.states[at];
733
+ for (const { chain, index } of enclosingChains(at)) {
734
+ const head = frame.chains[chain];
735
+ if (head && head.index > index)
736
+ return frame.states[head.path];
737
+ }
738
+ return undefined;
739
+ };
740
+ /** Drops what no resume can ask for again: the states, chain frontiers, loop counts, route decisions
741
+ * and start bindings of the paths `gone` names. Step records stay: a host reads its sessions from them; and so do
742
+ * failed items, as committed paths do: a map that commits in the write that moves its run writes its items' records
743
+ * then, a failed one's with its outcome. */
744
+ const prune = (frame, gone) => {
745
+ for (const table of [frame.states, frame.chains, frame.loops, frame.routes, frame.inputs]) {
746
+ for (const key of Object.keys(table))
747
+ if (gone(key))
748
+ delete table[key];
749
+ }
750
+ };
751
+ /** Whether `at` lies in an item of a map that collects its items' failures, at any depth. */
752
+ const collectedAt = (at, doc) => {
753
+ for (let item = mapItemOf(at); item; item = mapItemOf(item.map)) {
754
+ const map = nodeAt(doc, item.map);
755
+ if (map?.node === "map" && map.onItemFailure === "collect")
756
+ return true;
757
+ }
758
+ return false;
759
+ };
760
+ /** The item of a map that collects its items' failures whose body is at `at`, or a fault. */
761
+ const collectingItem = (at, doc) => {
762
+ const item = mapItemOf(at);
763
+ const map = item && nodeAt(doc, item.map);
764
+ if (!item || `${item.item}/body` !== at || map?.node !== "map" || map.onItemFailure !== "collect") {
765
+ throw pathFault(at, "Only the body of an item of a map that collects its items' failures ends on a failure");
766
+ }
767
+ return item;
768
+ };
769
+ const recovery = {
770
+ // Every store key below is the interpreter's execution path, so a composed graph (a loop, a route, a
771
+ // map whose body is structure, a nested child) resumes where it stopped.
772
+ supportsExecutionPaths: true,
773
+ async resume(node, state, _item, executionPath) {
774
+ await seam();
775
+ const { frame, doc } = active();
776
+ const at = placed(executionPath, doc);
777
+ if (frame.input === null) {
778
+ frame.input = hash(state);
779
+ inputChecked.add(frame);
780
+ await save();
781
+ await flush();
782
+ }
783
+ else if (!inputChecked.has(frame)) {
784
+ if (frame.input !== hash(state))
785
+ throw failure("FROZEN_INPUT_CHANGED", `Materialized workflow input changed: ${at}`);
786
+ inputChecked.add(frame);
787
+ }
788
+ verifyFiles(snapshot.files);
789
+ const committed = answer(frame, at);
790
+ if (committed)
791
+ return committed;
792
+ if (doneOf(frame).has(at))
793
+ throw pathFault(at, "A committed path was asked for again after its state was released");
794
+ // A map that starts, or starts again, names the base its items are kept against: the state it starts from.
795
+ if ((layoutV4 || moving) && node.node === "map") {
796
+ const list = String(node.itemsPath).split(".").reduce((value, key) => value?.[key], state);
797
+ maps.set(at, { length: Array.isArray(list) ? list.length : 0, items: maps.get(at)?.items ?? 0, base: digestOf(state), baseState: state });
798
+ }
799
+ // A node started in an earlier process starts again from the same state, or not at all. The
800
+ // binding is durable with the next commit, which is the first durable thing done under it.
801
+ const digest = hash(state);
802
+ if (frame.inputs[at] === undefined)
803
+ frame.inputs[at] = digest;
804
+ else if (frame.inputs[at] !== digest)
805
+ throw failure("FROZEN_INPUT_CHANGED", `The input of ${at} changed since it started`);
806
+ return undefined;
807
+ },
808
+ async commit(node, state, _item, executionPath) {
809
+ // Finished work commits while a pause waits for an effect in flight; it starts nothing.
810
+ guard();
811
+ const { frame, doc } = active();
812
+ const at = placed(executionPath, doc);
813
+ const done = doneOf(frame);
814
+ if (done.has(at))
815
+ throw pathFault(at, "A path commits once");
816
+ // Every loop the path runs in is on the iteration the path belongs to: iteration k+1 commits
817
+ // nothing before iteration k is complete.
818
+ for (const { loop, index } of enclosingIterations(at)) {
819
+ if (index !== (frame.loops[loop] ?? 0))
820
+ throw pathFault(at, `Iteration ${index} committed while its loop is on iteration ${frame.loops[loop] ?? 0}`);
821
+ }
822
+ const step = chainStep(at);
823
+ if (step && (frame.chains[step.chain]?.index ?? -1) >= step.index)
824
+ throw pathFault(at, "A chain step committed behind its chain's frontier");
825
+ if (node.node === "artifact" && node.path)
826
+ keepFiles(fileHashes([node.path]), at);
827
+ frame.done.push(at);
828
+ done.add(at);
829
+ // A map that committed, alone or inside what committed, has its results in the state: what it had finished
830
+ // when it failed earlier is no longer the run's.
831
+ if (frame.partial && isWithin(frame.partial.path, at))
832
+ delete frame.partial;
833
+ // Everything inside the committed node is answered by it now, and so is everything before it
834
+ // in its chain.
835
+ prune(frame, key => isWithin(key, at));
836
+ if (step) {
837
+ prune(frame, key => enclosingChains(key).some(c => c.chain === step.chain && c.index < step.index));
838
+ frame.chains[step.chain] = { index: step.index, path: at };
839
+ }
840
+ frame.states[at] = state;
841
+ const completed = completedIteration(doc, at);
842
+ if (completed)
843
+ frame.loops[completed.loop] = completed.index + 1;
844
+ await save();
845
+ await flush();
846
+ },
847
+ async fail(node, results, _error, executionPath) {
848
+ // Finished work commits while a pause waits for an effect in flight; it starts nothing.
849
+ guard();
850
+ const { frame, doc } = active();
851
+ // A map that ended on an item's failure keeps its finished items committed: the handoff's state
852
+ // carries them under the map's key, and a later open answers them from their paths.
853
+ frame.partial = { path: placed(executionPath, doc), as: String(node.as ?? node.node), results: results.map(result => result === undefined ? null : result) };
854
+ await save();
855
+ await flush();
856
+ },
857
+ async failItem(_node, row, executionPath) {
858
+ // Finished work commits while a pause waits for an effect in flight; it starts nothing.
859
+ guard();
860
+ const { frame, doc } = active();
861
+ const at = placed(executionPath, doc);
862
+ const { item } = collectingItem(at, doc);
863
+ if (frame.failures?.[item])
864
+ throw pathFault(at, "An item ends on its failure once");
865
+ // An effect the item admitted and never completed may have happened: that is uncertainty, reconciled before the
866
+ // run goes on, and never an item failure. A call that threw is one: the driver never certifies a thrown dispatch.
867
+ const uncertain = journal.effects().find((effect) => effect.status === "unknown" && isWithin(frozenEffectPath(effect.id)?.path ?? "", item));
868
+ if (uncertain)
869
+ throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${uncertain.id}: an item whose effect's outcome is unknown does not end on its failure`);
870
+ // What the item had in progress is no one's now: nothing in it is asked for again. Its committed paths, step
871
+ // records and effects stay, as a finished item's do.
872
+ prune(frame, key => isWithin(key, item));
873
+ (frame.failures ??= {})[item] = { code: row.code, label: row.label, message: row.message };
874
+ await save();
875
+ await flush();
876
+ },
877
+ async itemFailure(_node, executionPath) {
878
+ guard();
879
+ const { frame, doc } = active();
880
+ const at = placed(executionPath, doc);
881
+ const { item, index } = collectingItem(at, doc);
882
+ const held = frame.failures?.[item];
883
+ // The row as the item's own process wrote it, key for key.
884
+ return held ? { item_index: index, label: held.label, code: held.code, message: held.message } : undefined;
885
+ },
886
+ pollStartedAt(node, _item, executionPath) {
887
+ guard();
888
+ const { tag, doc } = active();
889
+ const at = placed(executionPath, doc);
890
+ return clock(`poll:${tag}:${at}`, node.poll.deadline_s * 1000) - node.poll.deadline_s * 1000;
891
+ },
892
+ async wait(_node, ms, _item, executionPath) {
893
+ await seam();
894
+ const { tag, doc } = active();
895
+ const key = `${tag}:${placed(executionPath, doc)}`;
896
+ const until = Math.min(snapshot.clocks[`poll:${key}`] ?? Infinity, clock(`wait:${key}:${ordinals.get(key) ?? 0}`, ms));
897
+ // The wait's clock is durable before the wait starts, so a process that dies inside it resumes the same wait.
898
+ await flush();
899
+ await new Promise((resolve, reject) => {
900
+ const onAbort = () => { clearTimeout(wait); reject(controller.signal.reason); };
901
+ const wait = setTimeout(() => { controller.signal.removeEventListener("abort", onAbort); resolve(); }, Math.max(0, until - Date.now()));
902
+ controller.signal.addEventListener("abort", onAbort, { once: true });
903
+ });
904
+ guard();
905
+ },
906
+ };
907
+ /** An LLM step's record in the running frame, by its execution path. */
908
+ const llmStep = (executionPath) => {
909
+ const { frame, tag, doc } = active();
910
+ const at = placed(executionPath, doc);
911
+ if (!LLM_KINDS.has(nodeAt(doc, at).node))
912
+ throw pathFault(at, "Only an LLM step has a session");
913
+ return { frame, tag, at };
914
+ };
915
+ const sessionOf = (tag, at, step, attempt = step.attempt) => frozenStepSessionId(driver, step.label, tag, at, attempt);
916
+ /** The highest top-level step of `doc` the frame completed, and the committed path its state is
917
+ * read at (`topLevelCompletion`). */
918
+ const completedHead = (frame, doc) => {
919
+ let head;
920
+ for (const at of frame.done) {
921
+ const index = topLevelCompletion(doc, at);
922
+ if (index !== undefined && (!head || index > head.index))
923
+ head = { index, at };
924
+ }
925
+ return head;
926
+ };
927
+ return {
928
+ recovery, signal: controller.signal, resumed: journal.existing,
929
+ /** This process's generation of the run: a request this process makes is named with it, so a
930
+ * process that asks again never reuses an earlier process's invocation. */
931
+ get generation() { return generation; },
932
+ /** A refusal found before any step, or null: the host escalates it before any step runs. */
933
+ preStepRefusal,
934
+ /** How this open keeps the run: the layout's schema, and why it is not the keyed one the host asked for. */
935
+ get layout() {
936
+ return { schema: layoutV4 ? FROZEN_SNAPSHOT_SCHEMA_V4 : FROZEN_SNAPSHOT_SCHEMA, ...(layoutReason ? { reason: layoutReason } : {}) };
937
+ },
938
+ binding,
939
+ /** The run's key: what its step sessions and effects are named under. */
940
+ driverId: driver,
941
+ /** The host hands the driver its stop here. A cancel stops the driver at once, and its steps and effects through
942
+ * its signal. A pause refuses new work at once and is taken when no effect is in flight: an effect already
943
+ * dispatched completes and commits its receipt first, so a paused run resumes without a reconciliation. */
944
+ stop: (stop) => {
945
+ if (requested?.action !== "cancel")
946
+ requested = stop;
947
+ // A cancel after the driver paused replaces the pause it committed and the stop it reports: a cancelled run never resumes.
948
+ if (stopError && snapshot.status === "paused" && stop.action === "cancel") {
949
+ snapshot.status = "cancelled";
950
+ Object.assign(stopError, { code: "FROZEN_CANCELLED", message: "Frozen run cancelled", source: stop.source });
951
+ void save();
952
+ }
953
+ try {
954
+ guard();
955
+ }
956
+ catch { /* Sticky: the stop blocks every admission. */ }
957
+ if (fatal)
958
+ wake();
959
+ },
960
+ /** The driver's stop check, for a branch that hands off without entering the interpreter: a pause or cancel the
961
+ * driver took stops the run here, before anything resumes. */
962
+ checkStop() { guard(); },
963
+ /** A seam for new work: it waits while a pause waits for an effect in flight, then applies any stop taken. */
964
+ seam,
965
+ /** An LLM step's execution record, admitted before it dispatches. The first call fixes the label
966
+ * the interpreter names it by (a child's step under its invocation) and the retry limit; a resume
967
+ * at this path gets the same record, so its session is found again. A closed attempt advances to a new
968
+ * session identity here, and only here; a failed step never gets another. */
969
+ stepSession(executionPath, label, admission) {
970
+ guard();
971
+ const { frame, tag, at } = llmStep(executionPath);
972
+ const { step, changed } = admitFrozenStep(frame.steps, at, label, admission);
973
+ if (changed)
974
+ save();
975
+ return { ...step, stepId: frozenStepId(tag, at), sessionId: sessionOf(tag, at, step), earlierSessionIds: Array.from({ length: step.attempt }, (_, earlier) => sessionOf(tag, at, step, earlier)) };
976
+ },
977
+ /** Whether the step already has an execution record: a resumed step was admitted in an earlier
978
+ * process and is continued, never refused again. */
979
+ stepAdmitted(executionPath) { const { frame, at } = llmStep(executionPath); return frame.steps[at] !== undefined; },
980
+ /** The current attempt did not submit: its session closes with its spend kept.
981
+ * The step is `closed` until a retry is admitted, or `failed` when no attempt remains. */
982
+ stepAttemptFailed(executionPath, final = false, error) {
983
+ guard();
984
+ const { frame, tag, at } = llmStep(executionPath);
985
+ const step = frame.steps[at];
986
+ if (!step)
987
+ throw pathFault(at, "Step attempt failed before admission");
988
+ const id = sessionOf(tag, at, step);
989
+ if (options.closeStepSession)
990
+ void persist(() => options.closeStepSession(id)).catch(() => undefined);
991
+ // An item failure that fails a step in an item of a map that collects them is kept with the step: the item's own
992
+ // commit comes after this one, and a process that resumes between the two ends the item on the same failure.
993
+ const kept = error instanceof Error && isItemFailure(error) && collectedAt(at, view)
994
+ ? { code: String(error.code), message: String(error.message || error).slice(0, 300) } : undefined;
995
+ closeFrozenStepAttempt(step, final, kept);
996
+ save();
997
+ },
998
+ /** The step delivered its record; the row and the step record agree before the step commit. */
999
+ stepSubmitted(executionPath) {
1000
+ guard();
1001
+ const { frame, at } = llmStep(executionPath);
1002
+ const step = frame.steps[at];
1003
+ if (step) {
1004
+ step.status = "submitted";
1005
+ save();
1006
+ }
1007
+ },
1008
+ /** The short identity of an admitted LLM step (a digest of its frame and path), for the escalation
1009
+ * row when it fails; null for a path that ran no LLM step. */
1010
+ stepId(executionPath) {
1011
+ const { frame, tag, doc } = active();
1012
+ return typeof executionPath === "string" && nodeAt(doc, executionPath) && frame.steps[executionPath] ? frozenStepId(tag, executionPath) : null;
1013
+ },
1014
+ /** Spend outside any question or session, committed with the driver's state the moment it is priced, so the run's
1015
+ * recorded spend holds it. It may be called inside a tool, so it never applies a stop; a failed commit is the run's
1016
+ * persistence failure. */
1017
+ async charge(usd) {
1018
+ if (fatal)
1019
+ throw fatal;
1020
+ if (!Number.isFinite(usd) || usd <= 0)
1021
+ return;
1022
+ snapshot.questionSpendUsd = +((snapshot.questionSpendUsd ?? 0) + usd).toFixed(8);
1023
+ await save();
1024
+ await flush();
1025
+ },
1026
+ /** A question's metered spend, committed with the driver's state so a resume that skips the
1027
+ * finished question still reports it; an unpriced answer (`null`) adds nothing. A route's answer is its decision: it commits in the same save, once per route path, and a resume
1028
+ * inside the branch follows it instead of asking again. */
1029
+ recordQuestionSpend(usd, route) {
1030
+ guard();
1031
+ let changed = false;
1032
+ if (usd !== null && Number.isFinite(usd) && usd >= 0) {
1033
+ snapshot.questionSpendUsd = +((snapshot.questionSpendUsd ?? 0) + usd).toFixed(8);
1034
+ changed = true;
1035
+ }
1036
+ if (route) {
1037
+ const { frame, doc } = active();
1038
+ const at = placed(route.executionPath, doc);
1039
+ const node = nodeAt(doc, at);
1040
+ if (node?.node !== "route")
1041
+ throw pathFault(at, "Only a route's answer is a decision");
1042
+ if (frame.routes[at])
1043
+ throw pathFault(at, "A route is decided once");
1044
+ frame.routes[at] = { label: route.label, ...routeTaken(node, route.result.answers), request_sha256: typeof route.result.request_sha256 === "string" ? route.result.request_sha256 : null, result: route.result, receipts: route.receipts };
1045
+ changed = true;
1046
+ }
1047
+ if (changed)
1048
+ save();
1049
+ },
1050
+ /** The host has written what it keeps of the route at `executionPath`: its decision no longer carries the
1051
+ * receipts a resume would write. */
1052
+ routeReceipted(executionPath) {
1053
+ guard();
1054
+ const { frame, doc } = active();
1055
+ const decision = frame.routes[placed(executionPath, doc)];
1056
+ if (!decision?.receipts)
1057
+ return;
1058
+ decision.receipts = null;
1059
+ save();
1060
+ },
1061
+ /** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
1062
+ routeDecision(executionPath) {
1063
+ const { frame, doc } = active();
1064
+ return frame.routes[placed(executionPath, doc)];
1065
+ },
1066
+ /** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
1067
+ * as an escalation commit before anything acts on it. A later open gets the same row and the same
1068
+ * continuation identity, whatever fires again. */
1069
+ async escalate(row) {
1070
+ guard();
1071
+ if (snapshot.escalation)
1072
+ return snapshot.escalation;
1073
+ const stepId = row.step_exec_id ?? null;
1074
+ const tailId = stepId ?? Math.random().toString(36).slice(2, 10);
1075
+ // The row is placed before the commit so the commit's state carries it, and the state is
1076
+ // serialized inside the commit's transaction with that commit's revision: no boundary
1077
+ // exists where the row is durable and its revision is not.
1078
+ snapshot.escalation = { ...row, step_exec_id: stepId, tail: `${driver}:escalated:${tailId}`, revision: 0 };
1079
+ // The note names the handoff, not the state: the state rides the snapshot.
1080
+ const detail = { kind: row.kind, stage: row.stage, summary: String(row.summary ?? "").slice(0, 512), step_label: row.step_label, step_exec_id: stepId, workflow_sha_used: row.workflow_sha_used,
1081
+ cost_usd: row.cost_usd, tail: snapshot.escalation.tail, state_keys: Object.keys(row.state ?? {}) };
1082
+ // The parts are computed with the state, after the row has its revision.
1083
+ let parts;
1084
+ await persist(() => journal.save((revision) => { snapshot.escalation.revision = revision; const write = writeOf(); parts = write.parts; return write.state; }, { kind: "escalation", detail }, (revision) => parts?.(revision) ?? {}));
1085
+ return snapshot.escalation;
1086
+ },
1087
+ escalation() { return snapshot.escalation; },
1088
+ /** How many effects the driver admitted. */
1089
+ effectCalls() { return journal.effects().length; },
1090
+ /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
1091
+ * read and its identity. */
1092
+ async annotateHandoff(detail) {
1093
+ await persist(() => journal.note("inherited", detail));
1094
+ },
1095
+ /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
1096
+ * the escalation commit, so the row the continuation reads the spend from is brought current here,
1097
+ * by one `handoff` commit that names the escalation. The escalation's revision, what the
1098
+ * continuation binds on, does not change. */
1099
+ async handoff(spend) {
1100
+ guard();
1101
+ const row = snapshot.escalation;
1102
+ if (!row)
1103
+ throw failure("FROZEN_CHECKPOINT_INVALID", "A handoff follows an escalation; none is recorded");
1104
+ if (row.cost_usd === spend.cost_usd && row.turns === spend.turns && row.effect_calls === spend.effect_calls)
1105
+ return row;
1106
+ const detail = { escalation_revision: row.revision, previous_cost_usd: row.cost_usd,
1107
+ cost_usd: spend.cost_usd, turns: spend.turns, effect_calls: spend.effect_calls };
1108
+ Object.assign(row, spend);
1109
+ const write = writeOf();
1110
+ await persist(() => journal.save(write.state, { kind: "handoff", detail }, write.parts));
1111
+ return row;
1112
+ },
1113
+ /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
1114
+ * items produced under the map's key: what an escalation on a failure carries. */
1115
+ lastState() {
1116
+ const { frame, doc } = active();
1117
+ const head = completedHead(frame, doc);
1118
+ const state = head ? frame.states[head.at] ?? {} : {};
1119
+ const partial = frame.partial;
1120
+ return partial ? { ...state, [partial.as]: partial.results } : state;
1121
+ },
1122
+ get started() {
1123
+ if (snapshot.pin.input === null && journal.effects().length > 0) {
1124
+ throw failure("FROZEN_CHECKPOINT_INVALID", "Effects exist before the frozen input checkpoint");
1125
+ }
1126
+ return snapshot.pin.input !== null;
1127
+ },
1128
+ wrapEffect(run) {
1129
+ return async (params) => {
1130
+ await seam();
1131
+ const { tag, doc } = active();
1132
+ const at = placed(params.executionPath, doc);
1133
+ const key = `${tag}:${at}`;
1134
+ const ordinal = ordinals.get(key) ?? 0;
1135
+ ordinals.set(key, ordinal + 1);
1136
+ const id = frozenEffectId(tag, at, ordinal);
1137
+ const argsHash = hash({ input: params.input, node: params.node, idempotencyKey: params.idempotencyKey });
1138
+ const existing = journal.effect(id);
1139
+ if (existing) {
1140
+ if (existing.argsHash !== argsHash)
1141
+ throw failure("FROZEN_INPUT_CHANGED", "Recovered effect arguments changed");
1142
+ if (existing.status !== "completed")
1143
+ throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id} before resuming; it will not be repeated`);
1144
+ const receipt = existing.result;
1145
+ verifyFiles(receipt.files);
1146
+ keepFiles(receipt.files, at);
1147
+ await save();
1148
+ await flush();
1149
+ return receipt.value;
1150
+ }
1151
+ if (params.produces.some(reserved))
1152
+ throw failure("RUN_CONTROL_UNSUPPORTED", "Effect declares a host-owned output path");
1153
+ // The effect's own clock: the node's deadline, and the poll window when it is a poll.
1154
+ const deadline = Math.min(snapshot.clocks[`poll:${key}`] ?? Infinity, clock(`attempt:${id}`, params.node.deadline_s * 1000));
1155
+ if (Date.now() >= deadline)
1156
+ throw failure("FROZEN_EFFECT_DEADLINE", "Effect exceeded its own deadline");
1157
+ // A tool effect is admitted with the external call it makes, keyed as a continuation keys its own calls
1158
+ // (`gatewayIntentOf`: a fetch wrapper's call is the gateway tool it names and its arguments), so a continuation
1159
+ // that inherits it unknown refuses the same call.
1160
+ const external = params.node.via === "tool" ? gatewayIntentOf(String(params.node.tool), params.input ?? {}) : undefined;
1161
+ // From its admission the effect is in flight: a pause waits for it to complete and commit, so the admission is
1162
+ // never left without its dispatch.
1163
+ inFlight += 1;
1164
+ try {
1165
+ // The driver's state and the admission are one transaction.
1166
+ const admission = writeOf(id);
1167
+ const admitted = await persist(() => journal.admit(id, String(params.node.label), argsHash, admission.state, driver, external, params.input ?? null, admission.parts, admission.owner));
1168
+ if (admitted !== "new")
1169
+ throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id} before dispatch`);
1170
+ // What landed while the admission was being committed still counts: after a cancel, the caller's own
1171
+ // cancellation or the effect's deadline, the effect stays admitted and unknown and the adapter is never called.
1172
+ // A pause lets it dispatch and complete.
1173
+ guard();
1174
+ if (params.signal.aborted)
1175
+ throw params.signal.reason;
1176
+ if (Date.now() >= deadline)
1177
+ throw failure("FROZEN_EFFECT_DEADLINE", "Effect exceeded its own deadline");
1178
+ const signal = AbortSignal.any([params.signal, controller.signal, AbortSignal.timeout(Math.max(1, deadline - Date.now()))]);
1179
+ // A thrown/aborted call remains UNKNOWN, including transient failures: no blind retry. Each outside call the effect
1180
+ // makes is kept on its record as it ends, on the driver's commit chain, so a process killed mid-effect keeps the
1181
+ // calls it made and a commit that fails is the run's failure, which aborts the effect at once.
1182
+ const calls = [];
1183
+ const keep = (record) => { calls.push(record); const held = [...calls]; persist(() => journal.called(id, held)).catch(() => undefined); };
1184
+ let value;
1185
+ try {
1186
+ value = await run({ ...params, signal, call: keep, effect: { id, argsHash } });
1187
+ }
1188
+ finally {
1189
+ if (calls.length)
1190
+ await flush();
1191
+ }
1192
+ if (signal.aborted)
1193
+ throw signal.reason;
1194
+ const returned = value;
1195
+ if (returned?.outcome === "unknown" || returned?.effect_status === "unknown"
1196
+ || returned?.details?.outcome === "unknown" || returned?.details?.effect_status === "unknown") {
1197
+ (snapshot.unknownResponses ??= {})[id] = value;
1198
+ await save(); // Preserve the observation without certifying completion.
1199
+ await flush();
1200
+ throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id}: tool returned an unknown outcome`);
1201
+ }
1202
+ const files = fileHashes(params.produces);
1203
+ // A tool effect's receipt names the external call it paid for (the tool and its arguments),
1204
+ // so a continuation that inherits the receipt can answer the same call from it. Any other
1205
+ // effect keeps its arguments beside its result.
1206
+ const intent = params.node.via === "tool" ? { tool: String(params.node.tool), args: params.input } : undefined;
1207
+ keepFiles(files, at);
1208
+ const completion = writeOf();
1209
+ await persist(() => journal.complete(id, { value, files, ...(intent ? { intent } : { args: params.input ?? null }) }, completion.state, completion.parts));
1210
+ return value;
1211
+ }
1212
+ finally {
1213
+ settled();
1214
+ }
1215
+ };
1216
+ },
1217
+ /** Every commit the driver started has landed; a failed one is thrown. */
1218
+ flush,
1219
+ /** Let go of the run once every commit the driver started has landed. */
1220
+ async close() { await chain; await journal.close(); },
1221
+ };
1222
+ }