@parcha/agentrun-dsl 0.1.0-beta.13 → 0.1.0-beta.130

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 (88) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +155 -16
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +4 -3
  6. package/dist/author.js +20 -11
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +166 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +64 -3
  14. package/dist/decision-receipts.js +50 -8
  15. package/dist/dry-run.d.ts +41 -1
  16. package/dist/dry-run.js +158 -27
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +63 -0
  19. package/dist/graph.d.ts +169 -0
  20. package/dist/graph.js +433 -0
  21. package/dist/index.d.ts +19 -12
  22. package/dist/index.js +17 -10
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +14 -1
  25. package/dist/job.d.ts +14 -0
  26. package/dist/job.js +5 -0
  27. package/dist/pattern-screen.d.ts +14 -0
  28. package/dist/pattern-screen.js +451 -0
  29. package/dist/predicates.d.ts +29 -0
  30. package/dist/predicates.js +62 -3
  31. package/dist/record.d.ts +4 -0
  32. package/dist/record.js +6 -0
  33. package/dist/recovery/binding.js +2 -1
  34. package/dist/recovery/call-key.d.ts +0 -4
  35. package/dist/recovery/call-key.js +0 -7
  36. package/dist/recovery/canonical-hash.d.ts +1 -1
  37. package/dist/recovery/canonical-hash.js +3 -3
  38. package/dist/recovery/driver.d.ts +79 -24
  39. package/dist/recovery/driver.js +634 -78
  40. package/dist/recovery/execution-path.d.ts +8 -0
  41. package/dist/recovery/execution-path.js +14 -0
  42. package/dist/recovery/frozen-snapshot.d.ts +128 -3
  43. package/dist/recovery/frozen-snapshot.js +63 -12
  44. package/dist/recovery/handoff-receipts.d.ts +0 -35
  45. package/dist/recovery/handoff-receipts.js +2 -44
  46. package/dist/recovery/index.d.ts +6 -10
  47. package/dist/recovery/index.js +5 -8
  48. package/dist/recovery/item-state.d.ts +48 -0
  49. package/dist/recovery/item-state.js +89 -0
  50. package/dist/recovery/journal.d.ts +6 -3
  51. package/dist/recovery/journal.js +20 -8
  52. package/dist/recovery/store.d.ts +33 -9
  53. package/dist/recovery/testing/conformance.js +55 -0
  54. package/dist/recovery/with-recovery.d.ts +9 -3
  55. package/dist/recovery/with-recovery.js +78 -18
  56. package/dist/submit-envelope.d.ts +9 -0
  57. package/dist/submit-envelope.js +44 -0
  58. package/dist/system-one.d.ts +37 -2
  59. package/dist/system-one.js +112 -18
  60. package/dist/testing/decision-provider.d.ts +32 -0
  61. package/dist/testing/decision-provider.js +183 -0
  62. package/dist/testing/index.d.ts +1 -0
  63. package/dist/testing/index.js +2 -0
  64. package/dist/vocabulary.d.ts +11 -3
  65. package/dist/vocabulary.js +19 -9
  66. package/dist/workflow-shape.d.ts +7 -0
  67. package/dist/workflow-shape.js +116 -70
  68. package/dist/workflow.d.ts +173 -18
  69. package/dist/workflow.js +1103 -398
  70. package/dist/zod-json-contract.js +6 -8
  71. package/package.json +19 -4
  72. package/schema/workflow.schema.json +366 -1
  73. package/skills/author/SKILL.md +6 -1
  74. package/skills/author/references/jev-decisions.md +50 -5
  75. package/skills/author/references/language.md +19 -14
  76. package/skills/author/references/sdk-authoring.md +2 -0
  77. package/dist/recovery/effect-failure.d.ts +0 -34
  78. package/dist/recovery/effect-failure.js +0 -62
  79. package/dist/recovery/handoff-block.d.ts +0 -36
  80. package/dist/recovery/handoff-block.js +0 -148
  81. package/dist/recovery/handoff-digest.d.ts +0 -58
  82. package/dist/recovery/handoff-digest.js +0 -195
  83. package/dist/recovery/handoff-files.d.ts +0 -54
  84. package/dist/recovery/handoff-files.js +0 -162
  85. package/dist/recovery/handoff-redact.d.ts +0 -12
  86. package/dist/recovery/handoff-redact.js +0 -44
  87. package/dist/recovery/handoff.d.ts +0 -44
  88. package/dist/recovery/handoff.js +0 -46
@@ -4,18 +4,23 @@
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
6
  import { createHash } from "node:crypto";
7
- import { desugarWorkflow } from "../workflow.js";
8
- import { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, nodeAt, topLevelCompletion } from "./execution-path.js";
7
+ import { desugarWorkflow, isItemFailure } from "../workflow.js";
8
+ import { setLongTimeout } from "../long-timer.js";
9
+ import { isRecord } from "../record.js";
10
+ import { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, topLevelCompletion } from "./execution-path.js";
9
11
  import { bindingDigests, LEDGER_FORMAT } from "./binding.js";
10
12
  import { canonicalHash as hash } from "./canonical-hash.js";
11
13
  import { RecoveryError } from "./errors.js";
12
14
  import { gatewayIntentOf } from "./handoff-receipts.js";
13
- import { validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop } from "./frozen-snapshot.js";
14
- const failure = (code, message) => new RecoveryError(message, code);
15
+ import { validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, failure, SHA256 as SHA, FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, stateDelta, applyStateDelta, isItemOutcome, DECISION_REQUEST } from "./frozen-snapshot.js";
15
16
  /** 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
+ * the answer's confidence is below `unsure.gte`, else the choice the answer names. A refused answer chose no branch:
18
+ * with an `unsure` branch the route took it (choice null, refused); without one the run escalated, and there is no
19
+ * decision (null). */
17
20
  export function routeTaken(node, answers) {
18
21
  const answer = answers?.branch;
22
+ if (answer?.type === "refusal")
23
+ return node.unsure ? { branch: node.unsure.branch, choice: null, unsure: true, refused: true } : null;
19
24
  const choice = String(answer?.choice ?? "");
20
25
  const unsure = Boolean(node.unsure && typeof answer?.confidence === "number" && answer.confidence < node.unsure.gte);
21
26
  return { branch: unsure ? node.unsure.branch : choice, choice, unsure };
@@ -168,9 +173,162 @@ export async function openRecovery(store, workflow, options) {
168
173
  const driver = options.key;
169
174
  const controller = new AbortController();
170
175
  let fatal;
171
- /** A pause or cancel was applied: its commit still lands, and nothing after it. */
176
+ /** A pause or cancel was applied: its commit is still made, and no admission after it. */
172
177
  let stopping = false;
178
+ /** A commit the store refused after a pause or cancel was applied (the stop's own, say): the stop is not durable, the
179
+ * journal still reads as it did, and the host hears it from `flush` and `close`. */
180
+ let refusedAfterStop;
173
181
  const journal = await store.open(bound);
182
+ /** Whether the store keeps parts beside the state: the keyed layout needs both reads. */
183
+ const keyed = typeof journal.items === "function" && typeof journal.stateOf === "function";
184
+ /** The keyed layout is in effect for this open, and why not when the host asked for it. `moving` is a run stored whole
185
+ * that takes the keyed layout at its first write that knows the base of every map still running in it: a map's base
186
+ * is the state it starts from, which the run's whole record does not hold, and the map names it when it resumes. */
187
+ let layoutV4 = false;
188
+ let moving = false;
189
+ let layoutReason;
190
+ // The keyed layout's bookkeeping: the maps the run started (with the base each item is kept against), the states
191
+ // already stored by digest, each item's record as last written (its revision aside), and the path that produced each
192
+ // file a map item owns.
193
+ const maps = new Map();
194
+ const writtenStates = new Set();
195
+ const lastItems = new Map();
196
+ const fileOwners = new Map();
197
+ /** At a restore: the files the driver's own record keeps (the latest write of each, whoever made it), and, for a file
198
+ * only item records keep, the revision of the record it was taken from (a later record's write is the latest). */
199
+ const driverFiles = new Set();
200
+ const fileRevisions = new Map();
201
+ /** The effects this process admitted, landed or still queued on the commit chain: an item's record lists each one it
202
+ * owns, even one whose admission has not landed when the record is built. */
203
+ const queued = new Set();
204
+ const deltas = new WeakMap();
205
+ const digests = new WeakMap();
206
+ const digestOf = (state) => { let digest = digests.get(state); if (digest === undefined) {
207
+ digest = hash(state);
208
+ digests.set(state, digest);
209
+ } return digest; };
210
+ const invalid = (message) => failure("FROZEN_CHECKPOINT_INVALID", message);
211
+ /** A state the run references by digest, read back and checked against it. */
212
+ const stateBy = async (sha256) => {
213
+ const state = await journal.stateOf(sha256);
214
+ if (!isRecord(state) || hash(state) !== sha256)
215
+ throw invalid(`The state ${sha256} the run references is missing or changed`);
216
+ writtenStates.add(sha256);
217
+ digests.set(state, sha256);
218
+ return state;
219
+ };
220
+ /** A value the run references by digest (a failed map's result, which may be any JSON value), read back and checked. */
221
+ const valueBy = async (sha256) => {
222
+ const value = await journal.stateOf(sha256);
223
+ if (value === undefined || hash(value) !== sha256)
224
+ throw invalid(`The value ${sha256} the run references is missing or changed`);
225
+ writtenStates.add(sha256);
226
+ return value;
227
+ };
228
+ const validEntry = (entry) => isRecord(entry) && Number.isSafeInteger(entry.length) && entry.length >= 0
229
+ && Number.isSafeInteger(entry.items) && entry.items >= 0 && typeof entry.base === "string" && SHA.test(entry.base);
230
+ /** The path of map item `index` of the map at `mapPath`: the prefix the interpreter gives every path inside it. */
231
+ const itemPathOf = (mapPath, index) => `${mapPath}/items/${index}`;
232
+ /** Reads back the records of every item the maps in `table` wrote, merging into `snapshot` what lies in them: all of
233
+ * it for a map still running, and what a committed map's items keep in the whole state (their committed paths, step
234
+ * records, clocks, files and effects) for one that committed. Nested maps are read through their item. */
235
+ const restoreMaps = async (table, snapshot) => {
236
+ if (!isRecord(table))
237
+ throw invalid("The run's maps are not a record");
238
+ const frame = snapshot.pin;
239
+ for (const [mapPath, entry] of Object.entries(table)) {
240
+ if (!validEntry(entry) || nodeAt(view, mapPath)?.node !== "map")
241
+ throw invalid(`The map at ${mapPath} is not one this run can hold`);
242
+ const committed = frame.done.includes(mapPath);
243
+ const baseState = committed ? undefined : await stateBy(entry.base);
244
+ maps.set(mapPath, { length: entry.length, items: entry.items, base: entry.base, ...(baseState ? { baseState } : {}) });
245
+ const paths = Array.from({ length: entry.items }, (_, index) => itemPathOf(mapPath, index));
246
+ const records = await journal.items(paths);
247
+ for (const [index, item] of records.entries()) {
248
+ if (item === undefined)
249
+ continue;
250
+ const path = paths[index];
251
+ const record = item;
252
+ const valid = record.driver === driver && record.map === mapPath && record.index === index && record.base === entry.base && Number.isSafeInteger(record.revision)
253
+ && ["running", "committed", "failed"].includes(record.status) && isRecord(record.frame) && Array.isArray(record.frame.done)
254
+ && (record.frame.decisions === undefined || isRecord(record.frame.decisions))
255
+ && [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)
256
+ && Array.isArray(record.effects) && record.effects.every((id) => typeof id === "string")
257
+ // An item that ended on its failure, and only one, holds how it ended; its map collects its items' failures.
258
+ && (record.status === "failed"
259
+ ? isItemOutcome(record.outcome) && nodeAt(view, mapPath)?.onItemFailure === "collect"
260
+ : record.outcome === undefined);
261
+ if (!valid)
262
+ throw invalid(`The record of map item ${path} is not one this run wrote`);
263
+ if (record.outcome)
264
+ (frame.failures ??= {})[path] = { ...record.outcome };
265
+ lastItems.set(path, JSON.stringify({ ...record, revision: 0 }));
266
+ frame.done.push(...record.frame.done);
267
+ Object.assign(frame.steps, record.frame.steps);
268
+ if (record.frame.decisions) {
269
+ frame.decisions ??= {};
270
+ Object.assign(frame.decisions, record.frame.decisions);
271
+ }
272
+ Object.assign(snapshot.clocks, record.clocks);
273
+ for (const [name, sha256] of Object.entries(record.files)) {
274
+ // A committed item keeps the record it last wrote, so a file a later step wrote again holds an older hash there.
275
+ if (driverFiles.has(name) || (fileRevisions.get(name) ?? -1) > record.revision)
276
+ continue;
277
+ snapshot.files[name] = sha256;
278
+ fileOwners.set(name, `${path}/body`);
279
+ fileRevisions.set(name, record.revision);
280
+ }
281
+ if (Object.keys(record.unknownResponses).length)
282
+ Object.assign(snapshot.unknownResponses ??= {}, record.unknownResponses);
283
+ if (!committed) {
284
+ for (const [at, delta] of Object.entries(record.frame.states)) {
285
+ if (!isRecord(delta) || !isRecord(delta.set) || !Array.isArray(delta.unset) || typeof delta.sha256 !== "string")
286
+ throw invalid(`The state at ${at} is not a delta`);
287
+ const state = applyStateDelta(baseState, delta);
288
+ if (hash(state) !== delta.sha256)
289
+ throw invalid(`The state at ${at} does not rebuild to the state that was committed`);
290
+ frame.states[at] = state;
291
+ deltas.set(state, delta);
292
+ digests.set(state, delta.sha256);
293
+ }
294
+ Object.assign(frame.chains, record.frame.chains);
295
+ Object.assign(frame.loops, record.frame.loops);
296
+ Object.assign(frame.routes, record.frame.routes);
297
+ Object.assign(frame.inputs, record.frame.inputs);
298
+ }
299
+ await restoreMaps(record.maps, snapshot);
300
+ }
301
+ }
302
+ };
303
+ /** The whole state of a run stored in the keyed layout: its own record with every state read back by digest, and what
304
+ * its map items keep. */
305
+ const restoreV4 = async (stored) => {
306
+ // A copy: what the items hold is merged into the restored frame, and the store's own state (which it writes back for
307
+ // a completion that names none) must stay the driver's record alone.
308
+ const { maps: table, pin, ...rest } = structuredClone(stored);
309
+ if (!isRecord(pin) || !isRecord(pin.states) || !Object.values(pin.states).every((sha256) => typeof sha256 === "string" && SHA.test(sha256)) || !Array.isArray(pin.done))
310
+ throw invalid("Invalid frozen recovery checkpoint");
311
+ const states = {};
312
+ for (const [at, sha256] of Object.entries(pin.states))
313
+ states[at] = await stateBy(sha256);
314
+ const restored = { ...rest, schema: FROZEN_SNAPSHOT_SCHEMA, pin: { ...pin, done: [...pin.done], states }, clocks: { ...rest.clocks }, files: { ...rest.files } };
315
+ for (const name of Object.keys(restored.files))
316
+ driverFiles.add(name);
317
+ // A failed map's finished results: the list of their slots is one value kept by its digest, each slot the digest of
318
+ // its result or null for an item that never finished.
319
+ if (pin.partial !== undefined) {
320
+ const partial = pin.partial;
321
+ if (!isRecord(partial) || typeof partial.path !== "string" || typeof partial.as !== "string" || typeof partial.results !== "string" || !SHA.test(partial.results)) {
322
+ throw invalid("A failed map's results are not kept by digest");
323
+ }
324
+ const slots = await valueBy(partial.results);
325
+ if (!Array.isArray(slots) || !slots.every((slot) => slot === null || (typeof slot === "string" && SHA.test(slot))))
326
+ throw invalid("A failed map's results are not a list of digests");
327
+ restored.pin.partial = { path: partial.path, as: partial.as, results: await Promise.all(slots.map((slot) => (slot === null ? null : valueBy(slot)))) };
328
+ }
329
+ await restoreMaps(table, restored);
330
+ return restored;
331
+ };
174
332
  /** The host's stop as it was handed over (a cancel outranks a pause), and who issued it. */
175
333
  let requested;
176
334
  /** The one error the driver's stop is: its signal's reason and every refusal after it, naming the committed stop. */
@@ -179,26 +337,271 @@ export async function openRecovery(store, workflow, options) {
179
337
  /** This process's ownership generation of the run: one per process that holds it. */
180
338
  const generation = journal.generation;
181
339
  const serial = () => serializeFrozenSnapshot(snapshot);
340
+ /** Files the run holds, with the path that produced them: a map item's file is kept in the item's record. */
341
+ const keepFiles = (files, at) => {
342
+ Object.assign(snapshot.files, files);
343
+ for (const name of Object.keys(files)) {
344
+ if (at === undefined)
345
+ fileOwners.delete(name);
346
+ else
347
+ fileOwners.set(name, at);
348
+ }
349
+ };
350
+ /** The path an effect clock belongs to: an attempt's effect, a poll's or a wait's node. */
351
+ const clockPath = (key) => {
352
+ if (key.startsWith("attempt:"))
353
+ return frozenEffectPath(key.slice("attempt:".length))?.path;
354
+ // poll:<tag>:<path>, and wait:<tag>:<path>:<ordinal>.
355
+ const poll = /^poll:[^:]+:(\/root.*)$/s.exec(key);
356
+ if (poll)
357
+ return poll[1];
358
+ const wait = /^wait:[^:]+:(\/root.*):\d+$/s.exec(key);
359
+ return wait ? wait[1] : undefined;
360
+ };
361
+ /** One write in the keyed layout: the driver's record without what lies in map items, the records of the items that
362
+ * changed, and the states first referenced now. `admitting` is an effect admitted in this write; `owner` the item that
363
+ * lists it. */
364
+ const keyedWrite = (admitting) => {
365
+ const frame = snapshot.pin;
366
+ const done = new Set(frame.done);
367
+ const builds = new Map();
368
+ /** The record a path lies in: undefined for the driver's own, null for an item of a map that committed (it keeps
369
+ * the record it last wrote). */
370
+ const own = (path) => {
371
+ const at = path === undefined ? undefined : mapItemOf(path);
372
+ if (!at)
373
+ return undefined;
374
+ // A committed map's items keep the records they last wrote; one that committed before the run took the keyed
375
+ // layout has none, and what lies in its items stays in the driver's record, as it was.
376
+ // A map that commits in the very write that moves the run has items with no record yet: they are written once, here.
377
+ if (done.has(at.map) && (!maps.has(at.map) || lastItems.has(at.item)))
378
+ return maps.has(at.map) ? null : undefined;
379
+ let build = builds.get(at.item);
380
+ if (!build) {
381
+ const map = maps.get(at.map);
382
+ if (!map)
383
+ throw invalid(`The map item ${at.item} belongs to no map this run started`);
384
+ build = { path: at.item, map: at.map, index: at.index, record: {
385
+ driver, map: at.map, index: at.index, base: map.base, revision: 0, status: "running",
386
+ frame: { done: [], states: {}, chains: {}, loops: {}, routes: {}, inputs: {}, steps: {} },
387
+ effects: [], clocks: {}, files: {}, unknownResponses: {}, maps: {},
388
+ } };
389
+ builds.set(at.item, build);
390
+ }
391
+ return build;
392
+ };
393
+ const states = {};
394
+ const kept = (state) => {
395
+ const digest = digestOf(state);
396
+ if (!writtenStates.has(digest)) {
397
+ writtenStates.add(digest);
398
+ states[digest] = state;
399
+ }
400
+ return digest;
401
+ };
402
+ /** A failed map's result, which may be any JSON value, kept once by its digest. */
403
+ const keptValue = (value) => {
404
+ if (isRecord(value))
405
+ return kept(value);
406
+ const digest = hash(value);
407
+ if (!writtenStates.has(digest)) {
408
+ writtenStates.add(digest);
409
+ states[digest] = value;
410
+ }
411
+ return digest;
412
+ };
413
+ const deltaOf = (map, state) => {
414
+ const known = deltas.get(state);
415
+ if (known)
416
+ return known;
417
+ const base = maps.get(map)?.baseState;
418
+ if (!base)
419
+ throw invalid(`The base of the map at ${map} is not known`);
420
+ const delta = stateDelta(base, state, digestOf(state));
421
+ deltas.set(state, delta);
422
+ return delta;
423
+ };
424
+ const pin = { input: frame.input, done: [], states: {}, chains: {}, loops: {}, routes: {}, inputs: {}, steps: {},
425
+ // A failed map's results: one digest, of the list of each result's digest (null for an item that never finished).
426
+ ...(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)))) } } : {}) };
427
+ for (const at of frame.done) {
428
+ const build = own(at);
429
+ if (build === undefined)
430
+ pin.done.push(at);
431
+ else if (build)
432
+ build.record.frame.done.push(at);
433
+ }
434
+ for (const [at, state] of Object.entries(frame.states)) {
435
+ const build = own(at);
436
+ if (build === undefined)
437
+ pin.states[at] = kept(state);
438
+ else if (build)
439
+ build.record.frame.states[at] = deltaOf(build.map, state);
440
+ }
441
+ for (const table of ["chains", "loops", "routes", "inputs", "steps"]) {
442
+ for (const [at, value] of Object.entries(frame[table])) {
443
+ const build = own(at);
444
+ if (build === undefined)
445
+ pin[table][at] = value;
446
+ else if (build)
447
+ build.record.frame[table][at] = value;
448
+ }
449
+ }
450
+ // A map item's decision requests are kept in its record, as its steps are; a frame with none writes no table.
451
+ for (const [at, requests] of Object.entries(frame.decisions ?? {})) {
452
+ const build = own(at);
453
+ if (build === undefined) {
454
+ pin.decisions ??= {};
455
+ pin.decisions[at] = requests;
456
+ }
457
+ else if (build) {
458
+ build.record.frame.decisions ??= {};
459
+ build.record.frame.decisions[at] = requests;
460
+ }
461
+ }
462
+ const clocks = {};
463
+ for (const [key, value] of Object.entries(snapshot.clocks)) {
464
+ const build = own(clockPath(key));
465
+ if (build === undefined)
466
+ clocks[key] = value;
467
+ else if (build)
468
+ build.record.clocks[key] = value;
469
+ }
470
+ const files = {};
471
+ for (const [name, sha256] of Object.entries(snapshot.files)) {
472
+ const build = own(fileOwners.get(name));
473
+ if (build === undefined)
474
+ files[name] = sha256;
475
+ else if (build)
476
+ build.record.files[name] = sha256;
477
+ }
478
+ const unknownResponses = {};
479
+ for (const [id, value] of Object.entries(snapshot.unknownResponses ?? {})) {
480
+ const build = own(frozenEffectPath(id)?.path);
481
+ if (build === undefined)
482
+ unknownResponses[id] = value;
483
+ else if (build)
484
+ build.record.unknownResponses[id] = value;
485
+ }
486
+ // An item that ended on its failure keeps it in its own record.
487
+ for (const [item, outcome] of Object.entries(frame.failures ?? {})) {
488
+ const build = own(`${item}/body`);
489
+ if (build === undefined)
490
+ (pin.failures ??= {})[item] = outcome;
491
+ else if (build)
492
+ build.record.outcome = outcome;
493
+ }
494
+ for (const id of new Set([...journal.effects().map((effect) => effect.id), ...queued, ...(admitting === undefined ? [] : [admitting])])) {
495
+ const build = own(frozenEffectPath(id)?.path);
496
+ if (build)
497
+ build.record.effects.push(id);
498
+ }
499
+ // A map's item records are the first ones: count them before the maps are written.
500
+ for (const build of builds.values()) {
501
+ const map = maps.get(build.map);
502
+ map.items = Math.max(map.items, build.index + 1);
503
+ }
504
+ const table = {};
505
+ for (const [at, map] of maps) {
506
+ const build = own(at);
507
+ const entry = { length: map.length, items: map.items, base: map.base };
508
+ if (build === undefined)
509
+ table[at] = entry;
510
+ else if (build)
511
+ build.record.maps[at] = entry;
512
+ if (!done.has(at) && map.baseState)
513
+ kept(map.baseState);
514
+ }
515
+ /** An item is done when its body committed: a chain never commits itself, so the last step a chain body runs
516
+ * through, descending through nested chains, is where the body ends. */
517
+ const finished = (item) => {
518
+ let at = `${item}/body`;
519
+ let node = nodeAt(view, at);
520
+ while (node?.node === "chain" && node.steps.length > 0) {
521
+ at = `${at}/steps/${node.steps.length - 1}`;
522
+ node = node.steps[node.steps.length - 1];
523
+ }
524
+ return done.has(at);
525
+ };
526
+ const items = {};
527
+ for (const build of builds.values()) {
528
+ build.record.status = build.record.outcome ? "failed" : finished(build.path) ? "committed" : "running";
529
+ const text = JSON.stringify(build.record);
530
+ if (lastItems.get(build.path) !== text) {
531
+ lastItems.set(build.path, text);
532
+ items[build.path] = build.record;
533
+ }
534
+ }
535
+ const { pin: _pin, schema: _schema, clocks: _clocks, files: _files, unknownResponses: _unknown, ...rest } = snapshot;
536
+ const state = serializeFrozenSnapshot({ ...rest, schema: FROZEN_SNAPSHOT_SCHEMA_V4, pin, clocks, files,
537
+ ...(Object.keys(unknownResponses).length ? { unknownResponses } : {}), maps: table });
538
+ const owner = admitting === undefined ? undefined : (own(frozenEffectPath(admitting)?.path) ?? undefined)?.path;
539
+ return { state, parts: (revision) => ({ items: Object.fromEntries(Object.entries(items).map(([path, item]) => [path, { ...item, revision }])), states }), ...(owner ? { owner } : {}) };
540
+ };
541
+ /** Whether every map still running with something in its items has its base: then a run stored whole can move. */
542
+ const basesKnown = () => {
543
+ const frame = snapshot.pin;
544
+ const done = new Set(frame.done);
545
+ const paths = [...frame.done, ...Object.keys(frame.states), ...Object.keys(frame.chains), ...Object.keys(frame.inputs), ...Object.keys(frame.steps),
546
+ ...Object.keys(frame.loops), ...Object.keys(frame.routes), ...Object.keys(frame.decisions ?? {}), ...Object.keys(frame.failures ?? {}).map((item) => `${item}/body`)];
547
+ return paths.every((path) => { const at = mapItemOf(path); return !at || done.has(at.map) || Boolean(maps.get(at.map)?.baseState); });
548
+ };
549
+ /** One write of the driver's state, in the layout this open keeps. */
550
+ const writeOf = (admitting) => {
551
+ if (admitting !== undefined)
552
+ queued.add(admitting);
553
+ if (moving && basesKnown()) {
554
+ moving = false;
555
+ layoutV4 = true;
556
+ }
557
+ return layoutV4 ? keyedWrite(admitting) : { state: serial() };
558
+ };
182
559
  /** The journal's commits, in the order the driver made them: a commit a synchronous method starts lands before any
183
560
  * later one, and an effect's admission waits for every earlier commit. A failed commit stops the run. */
184
561
  let chain = Promise.resolve();
185
562
  const persist = (write) => {
186
563
  const next = chain.then(() => { if (fatal && !stopping)
187
564
  throw fatal; return write(); });
188
- chain = next.catch((error) => { if (!fatal) {
189
- fatal = error;
190
- controller.abort(error);
191
- } });
565
+ chain = next.catch((error) => {
566
+ if (!fatal) {
567
+ fatal = error;
568
+ controller.abort(error);
569
+ }
570
+ else if (stopping && refusedAfterStop === undefined)
571
+ refusedAfterStop = error;
572
+ });
192
573
  return next;
193
574
  };
194
- /** Every commit the driver started has landed; a failed one is thrown. */
195
- const flush = async () => { await chain; if (fatal && !stopping)
575
+ /** Every commit the driver started has landed; a failed one is thrown, a pause's or a cancel's own commit included. */
576
+ const flush = async () => { await chain; if (refusedAfterStop !== undefined)
577
+ throw refusedAfterStop; if (fatal && !stopping)
196
578
  throw fatal; };
197
579
  try {
198
580
  // A driver an earlier process bound, with no checkpoint, is a run killed between its binding and its first
199
581
  // checkpoint when the journal holds nothing else of it: it never started, and it starts now. One with effects and
200
582
  // no checkpoint needs reconciliation.
201
- const saved = journal.state;
583
+ const stored = journal.state;
584
+ // A run a later build stored in a schema this build does not know: refused with its own code, so a host leaves the
585
+ // run for a build that knows it rather than ending it.
586
+ const known = [FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4];
587
+ const found = stored?.schema;
588
+ const version = typeof found === "string" ? /^agentrun\.frozen_run\.v(\d+)$/.exec(found)?.[1] : undefined;
589
+ if (version !== undefined && Number(version) > 4) {
590
+ 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 });
591
+ }
592
+ // 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
593
+ // host asks for it and the store keeps parts.
594
+ if (stored?.schema === FROZEN_SNAPSHOT_SCHEMA_V4) {
595
+ if (!keyed)
596
+ throw invalid("This run is stored in the keyed layout (agentrun.frozen_run.v4), and this store keeps no parts");
597
+ layoutV4 = true;
598
+ }
599
+ else {
600
+ moving = options.layout === "v4" && keyed;
601
+ if (options.layout === "v4" && !keyed)
602
+ layoutReason = "the store keeps no parts (its journal has no items and stateOf)";
603
+ }
604
+ const saved = stored?.schema === FROZEN_SNAPSHOT_SCHEMA_V4 ? await restoreV4(stored) : stored;
202
605
  if (journal.existing && !saved && journal.effects().length > 0)
203
606
  throw failure("FROZEN_CHECKPOINT_INVALID", "Existing frozen run has no checkpoint; retained workspace requires reconciliation");
204
607
  // Only the paths of the run's own document are resolved.
@@ -223,7 +626,7 @@ export async function openRecovery(store, workflow, options) {
223
626
  const at = frozenEffectPath(id)?.path;
224
627
  const declared = at === undefined ? undefined : nodeAt(view, at);
225
628
  const files = reader.hashes(declared?.node === "call" ? declared.produces ?? [] : []);
226
- Object.assign(snapshot.files, files);
629
+ keepFiles(files, at);
227
630
  // 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.
228
631
  if (receipt?.calls?.length)
229
632
  await journal.called(id, [...(journal.effect(id)?.calls ?? []), ...receipt.calls]);
@@ -238,18 +641,21 @@ export async function openRecovery(store, workflow, options) {
238
641
  reconciling = false;
239
642
  }
240
643
  }
241
- await journal.save(serial());
644
+ // The open's commit: a run stored whole that takes the keyed layout moves to it here, whole or not at all.
645
+ const opening = writeOf();
646
+ const layoutNote = layoutReason ? { kind: "layout", detail: { schema: FROZEN_SNAPSHOT_SCHEMA, reason: layoutReason } } : undefined;
647
+ await journal.save(opening.state, layoutNote, opening.parts);
242
648
  }
243
649
  catch (error) {
244
650
  await journal.close();
245
651
  throw error;
246
652
  }
247
653
  const ordinals = new Map();
248
- /** One commit of the driver's whole state. */
654
+ /** One commit of the driver's state. */
249
655
  const save = () => {
250
- const state = serial();
656
+ const write = writeOf();
251
657
  // A synchronous method does not wait for it; the failure is the run's, and the next awaited commit throws it.
252
- return persist(() => journal.save(state)).catch(() => undefined);
658
+ return persist(() => journal.save(write.state, undefined, write.parts)).catch(() => undefined);
253
659
  };
254
660
  /** Effects dispatched and not yet completed or failed. A pause is not taken while one is in flight. */
255
661
  let inFlight = 0;
@@ -310,9 +716,8 @@ export async function openRecovery(store, workflow, options) {
310
716
  }
311
717
  wake();
312
718
  };
313
- const fileHashes = (names) => reader.hashes(names);
314
719
  const verifyFiles = (files) => {
315
- if (hash(fileHashes(Object.keys(files))) !== hash(files))
720
+ if (hash(reader.hashes(Object.keys(files))) !== hash(files))
316
721
  throw failure("FROZEN_ARTIFACT_INVALID", "Committed artifact bytes changed; effect will not be repeated");
317
722
  };
318
723
  /** An effect-level clock is set once and kept across resume: a poll window or an attempt deadline
@@ -346,6 +751,14 @@ export async function openRecovery(store, workflow, options) {
346
751
  throw pathFault(at, "The interpreter named a path this run's document does not hold");
347
752
  return at;
348
753
  };
754
+ /** Where a decision's requests are kept: its own node, or the loop whose `until` the interpreter asks at
755
+ * `<loop>/iterations/<n>`, the one path a question is asked at that no node holds. Any other path is refused. */
756
+ const decisionPlace = (at, doc) => {
757
+ const loop = typeof at === "string" ? /^(.+)\/iterations\/(?:0|[1-9][0-9]*)$/.exec(at)?.[1] : undefined;
758
+ if (loop !== undefined && nodeAt(doc, loop)?.node === "loop")
759
+ return loop;
760
+ return placed(at, doc);
761
+ };
349
762
  /** The committed state a resume at `at` is answered from: its own, or the frontier of a chain it sits
350
763
  * in when the frontier lies past it. A chain threads one state, so every step before its frontier,
351
764
  * and everything inside those steps, is answered with the frontier's. */
@@ -360,7 +773,10 @@ export async function openRecovery(store, workflow, options) {
360
773
  return undefined;
361
774
  };
362
775
  /** Drops what no resume can ask for again: the states, chain frontiers, loop counts, route decisions
363
- * and start bindings of the paths `gone` names. Step records stay: a host reads its sessions from them. */
776
+ * and start bindings of the paths `gone` names. Step records stay: a host reads its sessions from them; decision
777
+ * requests stay, as what the run asked and paid for; and so do
778
+ * failed items, as committed paths do: a map that commits in the write that moves its run writes its items' records
779
+ * then, a failed one's with its outcome. */
364
780
  const prune = (frame, gone) => {
365
781
  for (const table of [frame.states, frame.chains, frame.loops, frame.routes, frame.inputs]) {
366
782
  for (const key of Object.keys(table))
@@ -368,11 +784,29 @@ export async function openRecovery(store, workflow, options) {
368
784
  delete table[key];
369
785
  }
370
786
  };
787
+ /** Whether `at` lies in an item of a map that collects its items' failures, at any depth. */
788
+ const collectedAt = (at, doc) => {
789
+ for (let item = mapItemOf(at); item; item = mapItemOf(item.map)) {
790
+ const map = nodeAt(doc, item.map);
791
+ if (map?.node === "map" && map.onItemFailure === "collect")
792
+ return true;
793
+ }
794
+ return false;
795
+ };
796
+ /** The item of a map that collects its items' failures whose body is at `at`, or a fault. */
797
+ const collectingItem = (at, doc) => {
798
+ const item = mapItemOf(at);
799
+ const map = item && nodeAt(doc, item.map);
800
+ if (!item || `${item.item}/body` !== at || map?.node !== "map" || map.onItemFailure !== "collect") {
801
+ throw pathFault(at, "Only the body of an item of a map that collects its items' failures ends on a failure");
802
+ }
803
+ return item;
804
+ };
371
805
  const recovery = {
372
806
  // Every store key below is the interpreter's execution path, so a composed graph (a loop, a route, a
373
807
  // map whose body is structure, a nested child) resumes where it stopped.
374
808
  supportsExecutionPaths: true,
375
- async resume(_node, state, _item, executionPath) {
809
+ async resume(node, state, _item, executionPath) {
376
810
  await seam();
377
811
  const { frame, doc } = active();
378
812
  const at = placed(executionPath, doc);
@@ -393,6 +827,11 @@ export async function openRecovery(store, workflow, options) {
393
827
  return committed;
394
828
  if (doneOf(frame).has(at))
395
829
  throw pathFault(at, "A committed path was asked for again after its state was released");
830
+ // A map that starts, or starts again, names the base its items are kept against: the state it starts from.
831
+ if ((layoutV4 || moving) && node.node === "map") {
832
+ const list = String(node.itemsPath).split(".").reduce((value, key) => value?.[key], state);
833
+ maps.set(at, { length: Array.isArray(list) ? list.length : 0, items: maps.get(at)?.items ?? 0, base: digestOf(state), baseState: state });
834
+ }
396
835
  // A node started in an earlier process starts again from the same state, or not at all. The
397
836
  // binding is durable with the next commit, which is the first durable thing done under it.
398
837
  const digest = hash(state);
@@ -420,7 +859,7 @@ export async function openRecovery(store, workflow, options) {
420
859
  if (step && (frame.chains[step.chain]?.index ?? -1) >= step.index)
421
860
  throw pathFault(at, "A chain step committed behind its chain's frontier");
422
861
  if (node.node === "artifact" && node.path)
423
- Object.assign(snapshot.files, fileHashes([node.path]));
862
+ keepFiles(reader.hashes([node.path]), at);
424
863
  frame.done.push(at);
425
864
  done.add(at);
426
865
  // A map that committed, alone or inside what committed, has its results in the state: what it had finished
@@ -451,6 +890,35 @@ export async function openRecovery(store, workflow, options) {
451
890
  await save();
452
891
  await flush();
453
892
  },
893
+ async failItem(_node, row, executionPath) {
894
+ // Finished work commits while a pause waits for an effect in flight; it starts nothing.
895
+ guard();
896
+ const { frame, doc } = active();
897
+ const at = placed(executionPath, doc);
898
+ const { item } = collectingItem(at, doc);
899
+ if (frame.failures?.[item])
900
+ throw pathFault(at, "An item ends on its failure once");
901
+ // An effect the item admitted and never completed may have happened: that is uncertainty, reconciled before the
902
+ // run goes on, and never an item failure. A call that threw is one: the driver never certifies a thrown dispatch.
903
+ const uncertain = journal.effects().find((effect) => effect.status === "unknown" && isWithin(frozenEffectPath(effect.id)?.path ?? "", item));
904
+ if (uncertain)
905
+ throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${uncertain.id}: an item whose effect's outcome is unknown does not end on its failure`);
906
+ // What the item had in progress is no one's now: nothing in it is asked for again. Its committed paths, step
907
+ // records and effects stay, as a finished item's do.
908
+ prune(frame, key => isWithin(key, item));
909
+ (frame.failures ??= {})[item] = { code: row.code, label: row.label, message: row.message };
910
+ await save();
911
+ await flush();
912
+ },
913
+ async itemFailure(_node, executionPath) {
914
+ guard();
915
+ const { frame, doc } = active();
916
+ const at = placed(executionPath, doc);
917
+ const { item, index } = collectingItem(at, doc);
918
+ const held = frame.failures?.[item];
919
+ // The row as the item's own process wrote it, key for key.
920
+ return held ? { item_index: index, label: held.label, code: held.code, message: held.message } : undefined;
921
+ },
454
922
  pollStartedAt(node, _item, executionPath) {
455
923
  guard();
456
924
  const { tag, doc } = active();
@@ -465,8 +933,9 @@ export async function openRecovery(store, workflow, options) {
465
933
  // The wait's clock is durable before the wait starts, so a process that dies inside it resumes the same wait.
466
934
  await flush();
467
935
  await new Promise((resolve, reject) => {
468
- const onAbort = () => { clearTimeout(wait); reject(controller.signal.reason); };
469
- const wait = setTimeout(() => { controller.signal.removeEventListener("abort", onAbort); resolve(); }, Math.max(0, until - Date.now()));
936
+ const onAbort = () => { wait.clear(); reject(controller.signal.reason); };
937
+ // setLongTimeout: a wait past Node's 2^31-1 ms timer limit waits instead of firing at once.
938
+ const wait = setLongTimeout(() => { controller.signal.removeEventListener("abort", onAbort); resolve(); }, until - Date.now());
470
939
  controller.signal.addEventListener("abort", onAbort, { once: true });
471
940
  });
472
941
  guard();
@@ -499,6 +968,10 @@ export async function openRecovery(store, workflow, options) {
499
968
  get generation() { return generation; },
500
969
  /** A refusal found before any step, or null: the host escalates it before any step runs. */
501
970
  preStepRefusal,
971
+ /** How this open keeps the run: the layout's schema, and why it is not the keyed one the host asked for. */
972
+ get layout() {
973
+ return { schema: layoutV4 ? FROZEN_SNAPSHOT_SCHEMA_V4 : FROZEN_SNAPSHOT_SCHEMA, ...(layoutReason ? { reason: layoutReason } : {}) };
974
+ },
502
975
  binding,
503
976
  /** The run's key: what its step sessions and effects are named under. */
504
977
  driverId: driver,
@@ -543,7 +1016,7 @@ export async function openRecovery(store, workflow, options) {
543
1016
  stepAdmitted(executionPath) { const { frame, at } = llmStep(executionPath); return frame.steps[at] !== undefined; },
544
1017
  /** The current attempt did not submit: its session closes with its spend kept.
545
1018
  * The step is `closed` until a retry is admitted, or `failed` when no attempt remains. */
546
- stepAttemptFailed(executionPath, final = false) {
1019
+ stepAttemptFailed(executionPath, final = false, error) {
547
1020
  guard();
548
1021
  const { frame, tag, at } = llmStep(executionPath);
549
1022
  const step = frame.steps[at];
@@ -552,7 +1025,11 @@ export async function openRecovery(store, workflow, options) {
552
1025
  const id = sessionOf(tag, at, step);
553
1026
  if (options.closeStepSession)
554
1027
  void persist(() => options.closeStepSession(id)).catch(() => undefined);
555
- closeFrozenStepAttempt(step, final);
1028
+ // 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
1029
+ // commit comes after this one, and a process that resumes between the two ends the item on the same failure.
1030
+ const kept = error instanceof Error && isItemFailure(error) && collectedAt(at, view)
1031
+ ? { code: String(error.code), message: String(error.message || error).slice(0, 300) } : undefined;
1032
+ closeFrozenStepAttempt(step, final, kept);
556
1033
  save();
557
1034
  },
558
1035
  /** The step delivered its record; the row and the step record agree before the step commit. */
@@ -584,15 +1061,17 @@ export async function openRecovery(store, workflow, options) {
584
1061
  await flush();
585
1062
  },
586
1063
  /** A question's metered spend, committed with the driver's state so a resume that skips the
587
- * 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
588
- * inside the branch follows it instead of asking again. */
1064
+ * finished question still reports it. A priced answer adds to `questionSpendUsd`; an answer with no
1065
+ * price (`null`, or a cost that is not a non-negative finite number) is counted in
1066
+ * `unpricedQuestionCount` instead, so the run's spend is read as incomplete and never as a bare total
1067
+ * that silently omits it: an unknown cost is never zero. A route's answer is its decision: it commits
1068
+ * in the same save, once per route path, and a resume inside the branch follows it instead of asking
1069
+ * again; its price, priced or not, is recorded the same way. */
589
1070
  recordQuestionSpend(usd, route) {
590
1071
  guard();
591
- let changed = false;
592
- if (usd !== null && Number.isFinite(usd) && usd >= 0) {
593
- snapshot.questionSpendUsd = +((snapshot.questionSpendUsd ?? 0) + usd).toFixed(8);
594
- changed = true;
595
- }
1072
+ // A route's checks run before any state is touched, so a refused call (not a route, or a route already
1073
+ // decided) leaves the snapshot clean: the next save never carries a half-recorded answer forward.
1074
+ let decision;
596
1075
  if (route) {
597
1076
  const { frame, doc } = active();
598
1077
  const at = placed(route.executionPath, doc);
@@ -601,11 +1080,18 @@ export async function openRecovery(store, workflow, options) {
601
1080
  throw pathFault(at, "Only a route's answer is a decision");
602
1081
  if (frame.routes[at])
603
1082
  throw pathFault(at, "A route is decided once");
604
- 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 };
605
- changed = true;
1083
+ // A refused route with no unsure branch took no branch: its answer is spent, and there is no decision.
1084
+ const taken = routeTaken(node, route.result.answers);
1085
+ if (taken)
1086
+ decision = { at, row: { label: route.label, ...taken, request_sha256: typeof route.result.request_sha256 === "string" ? route.result.request_sha256 : null, result: route.result, receipts: route.receipts } };
606
1087
  }
607
- if (changed)
608
- save();
1088
+ if (usd !== null && Number.isFinite(usd) && usd >= 0)
1089
+ snapshot.questionSpendUsd = +((snapshot.questionSpendUsd ?? 0) + usd).toFixed(8);
1090
+ else
1091
+ snapshot.unpricedQuestionCount = (snapshot.unpricedQuestionCount ?? 0) + 1;
1092
+ if (decision)
1093
+ active().frame.routes[decision.at] = decision.row;
1094
+ save();
609
1095
  },
610
1096
  /** The host has written what it keeps of the route at `executionPath`: its decision no longer carries the
611
1097
  * receipts a resume would write. */
@@ -619,10 +1105,72 @@ export async function openRecovery(store, workflow, options) {
619
1105
  save();
620
1106
  },
621
1107
  /** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
1108
+ /** Moves the poll window of the call node at `executionPath` back by `ms`, the time its host held the call (a pause
1109
+ * for a raise of the run's spend cap, which no deadline is for), durably: a later open reads the moved window, and
1110
+ * the next effect's check (wrapEffect) and the interpreter's poll start (pollStartedAt) take it. A node with no poll
1111
+ * window started, or no time held, moves nothing. `hold` names the hold (the host's id for it): one hold moves the
1112
+ * window once, however often a resume reports it again. */
1113
+ holdPoll(executionPath, ms, hold) {
1114
+ const { tag, doc } = active();
1115
+ const at = placed(executionPath, doc);
1116
+ const key = `poll:${tag}:${at}`;
1117
+ const once = `hold:${tag}:${at}:${hold}`;
1118
+ if (snapshot.clocks[key] === undefined || snapshot.clocks[once] !== undefined || !(Number.isFinite(ms) && ms > 0))
1119
+ return;
1120
+ snapshot.clocks[key] += ms;
1121
+ snapshot.clocks[once] = ms;
1122
+ void save();
1123
+ },
622
1124
  routeDecision(executionPath) {
623
1125
  const { frame, doc } = active();
624
1126
  return frame.routes[placed(executionPath, doc)];
625
1127
  },
1128
+ /** Every decision request this run committed, by decision id. */
1129
+ decisionRequests() {
1130
+ const { frame } = active();
1131
+ return structuredClone(Object.assign({}, ...Object.values(frame.decisions ?? {})));
1132
+ },
1133
+ /** Admits a decision's request before the host's judge is asked, in the driver's next commit, which the caller
1134
+ * awaits: a new request, or the next attempt of one that failed in its own process (undefined). A request found
1135
+ * in any other status was asked by an earlier process and is returned as it stands; the caller does not ask again.
1136
+ * An admitted request is in flight until `decisionSettled`: a pause waits for it, as for an effect. */
1137
+ admitDecision(executionPath, request) {
1138
+ guard();
1139
+ const { frame, doc } = active();
1140
+ const at = decisionPlace(executionPath, doc);
1141
+ frame.decisions ??= {};
1142
+ frame.decisions[at] ??= {};
1143
+ const requests = frame.decisions[at];
1144
+ const known = requests[request.decision_id];
1145
+ if (known && known.status !== "failed")
1146
+ return structuredClone(known);
1147
+ requests[request.decision_id] = { record: DECISION_REQUEST, ...request, attempt: (known?.attempt ?? 0) + 1, status: "requested" };
1148
+ inFlight += 1;
1149
+ save();
1150
+ return undefined;
1151
+ },
1152
+ /** A request `admitDecision` admitted is no longer in flight. */
1153
+ decisionSettled() { settled(); },
1154
+ /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
1155
+ * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
1156
+ * It never applies a stop: a request the run asked ends whatever stops the run. */
1157
+ decisionEnded(executionPath, decisionId, status, cost_usd, alongside) {
1158
+ if (fatal)
1159
+ throw fatal;
1160
+ const { frame, doc } = active();
1161
+ const request = frame.decisions?.[decisionPlace(executionPath, doc)]?.[decisionId];
1162
+ if (!request)
1163
+ throw failure("FROZEN_CHECKPOINT_INVALID", `The decision ${decisionId} ends without its request`);
1164
+ if (request.status !== "requested")
1165
+ throw failure("FROZEN_CHECKPOINT_INVALID", `The decision ${decisionId} ends once`);
1166
+ Object.assign(request, { status, cost_usd });
1167
+ try {
1168
+ alongside?.();
1169
+ }
1170
+ finally {
1171
+ save();
1172
+ }
1173
+ },
626
1174
  /** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
627
1175
  * as an escalation commit before anything acts on it. A later open gets the same row and the same
628
1176
  * continuation identity, whatever fires again. */
@@ -639,34 +1187,16 @@ export async function openRecovery(store, workflow, options) {
639
1187
  // The note names the handoff, not the state: the state rides the snapshot.
640
1188
  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,
641
1189
  cost_usd: row.cost_usd, tail: snapshot.escalation.tail, state_keys: Object.keys(row.state ?? {}) };
642
- await persist(() => journal.save((revision) => { snapshot.escalation.revision = revision; return serial(); }, { kind: "escalation", detail }));
1190
+ // The parts are computed with the state, after the row has its revision.
1191
+ let parts;
1192
+ await persist(() => journal.save((revision) => { snapshot.escalation.revision = revision; const write = writeOf(); parts = write.parts; return write.state; }, { kind: "escalation", detail }, (revision) => parts?.(revision) ?? {}));
643
1193
  return snapshot.escalation;
644
1194
  },
645
1195
  escalation() { return snapshot.escalation; },
1196
+ /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
1197
+ pinJson() { return JSON.stringify(snapshot.pin); },
646
1198
  /** How many effects the driver admitted. */
647
1199
  effectCalls() { return journal.effects().length; },
648
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
649
- * read and its identity. */
650
- async annotateHandoff(detail) {
651
- await persist(() => journal.note("inherited", detail));
652
- },
653
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
654
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
655
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
656
- * continuation binds on, does not change. */
657
- async handoff(spend) {
658
- guard();
659
- const row = snapshot.escalation;
660
- if (!row)
661
- throw failure("FROZEN_CHECKPOINT_INVALID", "A handoff follows an escalation; none is recorded");
662
- if (row.cost_usd === spend.cost_usd && row.turns === spend.turns && row.effect_calls === spend.effect_calls)
663
- return row;
664
- const detail = { escalation_revision: row.revision, previous_cost_usd: row.cost_usd,
665
- cost_usd: spend.cost_usd, turns: spend.turns, effect_calls: spend.effect_calls };
666
- Object.assign(row, spend);
667
- await persist(() => journal.save(serial(), { kind: "handoff", detail }));
668
- return row;
669
- },
670
1200
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
671
1201
  * items produced under the map's key: what an escalation on a failure carries. */
672
1202
  lastState() {
@@ -700,7 +1230,7 @@ export async function openRecovery(store, workflow, options) {
700
1230
  throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id} before resuming; it will not be repeated`);
701
1231
  const receipt = existing.result;
702
1232
  verifyFiles(receipt.files);
703
- Object.assign(snapshot.files, receipt.files);
1233
+ keepFiles(receipt.files, at);
704
1234
  await save();
705
1235
  await flush();
706
1236
  return receipt.value;
@@ -718,11 +1248,16 @@ export async function openRecovery(store, workflow, options) {
718
1248
  // From its admission the effect is in flight: a pause waits for it to complete and commit, so the admission is
719
1249
  // never left without its dispatch.
720
1250
  inFlight += 1;
1251
+ let deadlineTimer;
721
1252
  try {
722
1253
  // The driver's state and the admission are one transaction.
723
- const admitted = await persist(() => journal.admit(id, String(params.node.label), argsHash, serial(), driver, external, params.input ?? null));
1254
+ const admission = writeOf(id);
1255
+ const admitted = await persist(() => journal.admit(id, String(params.node.label), argsHash, admission.state, driver, external, params.input ?? null, admission.parts, admission.owner));
724
1256
  if (admitted !== "new")
725
1257
  throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id} before dispatch`);
1258
+ // The admission durable before the dispatch, where the host's store needs a barrier for it (afterAdmit).
1259
+ if (options.afterAdmit)
1260
+ await persist(options.afterAdmit);
726
1261
  // What landed while the admission was being committed still counts: after a cancel, the caller's own
727
1262
  // cancellation or the effect's deadline, the effect stays admitted and unknown and the adapter is never called.
728
1263
  // A pause lets it dispatch and complete.
@@ -731,7 +1266,15 @@ export async function openRecovery(store, workflow, options) {
731
1266
  throw params.signal.reason;
732
1267
  if (Date.now() >= deadline)
733
1268
  throw failure("FROZEN_EFFECT_DEADLINE", "Effect exceeded its own deadline");
734
- const signal = AbortSignal.any([params.signal, controller.signal, AbortSignal.timeout(Math.max(1, deadline - Date.now()))]);
1269
+ // The deadline is the clock the driver kept, so a fraction of a millisecond, or a delay past Node's 2^31-1 ms timer
1270
+ // limit, waits out its time; it aborts with the TimeoutError AbortSignal.timeout gives, which a host reads as a deadline.
1271
+ const timeout = new AbortController();
1272
+ deadlineTimer = setLongTimeout(() => timeout.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError")), deadline - Date.now());
1273
+ const signal = AbortSignal.any([params.signal, controller.signal, timeout.signal]);
1274
+ // Clear the deadline timer the moment the effect is aborted (a cancel, a pause, or the deadline itself): a
1275
+ // `runEffect` that ignores its signal and stays pending would otherwise leave this process alive until the
1276
+ // deadline — hours or days out — because the `finally` runs only when the dispatch settles.
1277
+ signal.addEventListener("abort", () => deadlineTimer?.clear(), { once: true });
735
1278
  // A thrown/aborted call remains UNKNOWN, including transient failures: no blind retry. Each outside call the effect
736
1279
  // makes is kept on its record as it ends, on the driver's commit chain, so a process killed mid-effect keeps the
737
1280
  // calls it made and a commit that fails is the run's failure, which aborts the effect at once.
@@ -741,37 +1284,50 @@ export async function openRecovery(store, workflow, options) {
741
1284
  try {
742
1285
  value = await run({ ...params, signal, call: keep, effect: { id, argsHash } });
743
1286
  }
1287
+ catch (error) {
1288
+ // The host's one signal that it cannot know the outcome: what it observed is kept for the operator, without
1289
+ // certifying completion. Any other throw leaves the effect unknown too, with nothing observed.
1290
+ if (error instanceof RecoveryError && error.code === "FROZEN_EFFECT_UNKNOWN") {
1291
+ if (calls.length)
1292
+ await flush();
1293
+ if (error.cause !== undefined) {
1294
+ (snapshot.unknownResponses ??= {})[id] = error.cause;
1295
+ await save();
1296
+ await flush();
1297
+ }
1298
+ throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id}: the host reported an unknown outcome`);
1299
+ }
1300
+ throw error;
1301
+ }
744
1302
  finally {
745
1303
  if (calls.length)
746
1304
  await flush();
747
1305
  }
748
1306
  if (signal.aborted)
749
1307
  throw signal.reason;
750
- const returned = value;
751
- if (returned?.outcome === "unknown" || returned?.effect_status === "unknown"
752
- || returned?.details?.outcome === "unknown" || returned?.details?.effect_status === "unknown") {
753
- (snapshot.unknownResponses ??= {})[id] = value;
754
- await save(); // Preserve the observation without certifying completion.
755
- await flush();
756
- throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id}: tool returned an unknown outcome`);
757
- }
758
- const files = fileHashes(params.produces);
1308
+ const files = reader.hashes(params.produces);
759
1309
  // A tool effect's receipt names the external call it paid for (the tool and its arguments),
760
1310
  // so a continuation that inherits the receipt can answer the same call from it. Any other
761
1311
  // effect keeps its arguments beside its result.
762
1312
  const intent = params.node.via === "tool" ? { tool: String(params.node.tool), args: params.input } : undefined;
763
- Object.assign(snapshot.files, files);
764
- await persist(() => journal.complete(id, { value, files, ...(intent ? { intent } : { args: params.input ?? null }) }, serial()));
1313
+ keepFiles(files, at);
1314
+ const completion = writeOf();
1315
+ await persist(() => journal.complete(id, { value, files, ...(intent ? { intent } : { args: params.input ?? null }) }, completion.state, completion.parts));
765
1316
  return value;
766
1317
  }
767
1318
  finally {
1319
+ deadlineTimer?.clear();
768
1320
  settled();
769
1321
  }
770
1322
  };
771
1323
  },
772
- /** Every commit the driver started has landed; a failed one is thrown. */
1324
+ /** Every commit the driver started has landed; a failed one is thrown, a pause's or a cancel's own commit included. */
773
1325
  flush,
774
- /** Let go of the run once every commit the driver started has landed. */
775
- async close() { await chain; await journal.close(); },
1326
+ /** Let go of the run once every commit the driver started has landed. A commit the store refused after a pause or
1327
+ * cancel is thrown once the journal is released: the stop is not durable, and the host must not take the run as
1328
+ * stopped. It is thrown even when a later stop's commit lands, since a later commit does not carry every record the
1329
+ * refused one held. A run's own failed commit is the run's failure and is not thrown again here. */
1330
+ async close() { await chain; await journal.close(); if (refusedAfterStop !== undefined)
1331
+ throw refusedAfterStop; },
776
1332
  };
777
1333
  }