@parcha/agentrun-dsl 0.1.0-beta.17 → 0.1.0-beta.19

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.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # @parcha/agentrun-dsl
2
2
 
3
- Composable, typed workflows for agents. The core provides the v2 workflow types, validator, interpreter, events, schema, and an offline CLI. Supply agent, judgment, and effect functions only when a workflow needs them.
3
+ Typed workflows that your agent writes. It drafts a workflow, checks it, dry-runs it for free, then runs it, and every node shows on its graph. The core provides the v2 workflow types, validator, interpreter, events, schema, and an offline CLI. Supply agent, judgment, and effect functions only when a workflow needs them.
4
4
 
5
- Beta: `0.1.0-beta.4`. Requires Node 22.19+; TypeScript consumers require TypeScript 5.4+.
5
+ Beta, on npm under the `beta` dist-tag (`npm view @parcha/agentrun-dsl dist-tags`). Requires Node 22.19+; TypeScript consumers require TypeScript 5.4+.
6
6
 
7
7
  ```sh
8
8
  npm install @parcha/agentrun-dsl@beta
9
- npx agentrun demo
9
+ npx @parcha/agentrun-dsl@beta demo
10
10
  ```
11
11
 
12
12
  For the JavaScript API, save this as `demo.mjs` and run `node demo.mjs`:
@@ -19,9 +19,30 @@ console.log(result.output); // { queue: 'billing', priority: 'normal' }
19
19
 
20
20
  The demo runs real control flow with scripted judgments. `ambiguous` escalates. No model SDK or API key is required by the core. Optional `@parcha/agentrun-jev` and `@parcha/agentrun-pi` adapters add live judgments and agent steps.
21
21
 
22
+ ## From a draft to a run
23
+
24
+ A workflow is a JSON document of typed nodes: each node that asks a model names the JSON Schema its answer must match, and the workflow names the schemas of its input and output. An agent writes the document. This package checks it, tries it without a model, and runs it.
25
+
26
+ 1. **Draft.** In Pi, `/agentrun <task>` has the agent draft the workflow with the packaged author skill (see [the Pi extension](../pi/README.md)). In your own host, `authorWorkflow` gives your agent the same author contract and keeps the candidate and its feedback without running it.
27
+ 2. **Check.** `validateWorkflow(workflow)` checks the structure, the schemas, the state paths between nodes and the predicates, with no model call. A refused workflow lists its `issues`: each names the node or schema at fault with a JSON Pointer `path`, and the rule it breaks with a `code`, so the agent repairs that node and checks again. `inspectWorkflow` shows the tree and the tools and adapters it needs, without running any code.
28
+ 3. **Dry-run, for free.** `dryRunWorkflow(workflow)` runs the whole workflow on synthetic values made from its schemas, with no model, Jev or tool call. Its `status` is `passed` when every check ran, `failed` with the `problems`, or `not_run` when a check could not run, with the reasons in `skipped`. A `not_run` dry run proves nothing.
29
+ 4. **Run.** `runWorkflow(workflow, input, deps)` runs it with your agent, judgment and effect functions, and returns an output that matches the output schema, or an escalation.
30
+ 5. **Watch every node.** `workflowGraph(workflow)` from `@parcha/agentrun-dsl/graph` lists every node and edge from the JSON alone, and `nodeStatus` marks each node `done`, `working`, `failed` or `not-run` from what a durable run kept. Pi's `/agentrun` view draws the same graph, with each node's state as the run goes.
31
+
32
+ The same checks from a shell, in the project where you installed the package, on one of the author skill's examples that ships with it (an agent extracts the change in each release note, then summarizes the migration):
33
+
34
+ ```sh
35
+ cp node_modules/@parcha/agentrun-dsl/skills/author/examples/review-release-notes.json workflow.json
36
+ npx @parcha/agentrun-dsl@beta inspect workflow.json
37
+ npx @parcha/agentrun-dsl@beta validate workflow.json --trusted
38
+ npx @parcha/agentrun-dsl@beta dry-run workflow.json --trusted
39
+ ```
40
+
41
+ Its dry run is `passed`: every node ran on synthetic values, with no model call. The demo's workflow (`npx @parcha/agentrun-dsl@beta example demo.json`) comes back `not_run` instead: its confidence check escalates on a synthetic answer, so the queue choice after it is not exercised, and `skipped` says so. `dry-run --strict` exits 3 on `not_run`, for a script that must stop there; a failure exits 1.
42
+
22
43
  The `agentrun` CLI provides `demo`, `example`, `inspect`, `validate`, `dry-run`, and deterministic `run`. `inspect workflow.json [--json]` displays structure without executing code. Validation/run require `--trusted` because workflow JavaScript can execute, including during validation. This package is not an isolation boundary.
23
44
 
24
- `runWorkflow(workflow, input, deps)` returns a complete schema-validated output or an escalation; its TypeScript output type is `unknown`. `defineWorkflow` binds Standard JSON Schema contracts, including supported Zod schemas, to a frozen v2 document; `runTypedWorkflow` infers those input/output types and delegates to the same interpreter. Intermediate state paths remain runtime-validated. Execution and verification failures throw. Hosts own tools, durable storage, file delivery, idempotency, recovery, and activation.
45
+ `runWorkflow(workflow, input, deps)` returns a complete schema-validated output or an escalation; its TypeScript output type is `unknown`. `defineWorkflow` binds Standard JSON Schema contracts, including supported Zod schemas, to a frozen v2 document; `runTypedWorkflow` infers those input/output types and delegates to the same interpreter. Intermediate state paths remain runtime-validated. Execution and verification failures throw. Hosts own tools, durable storage, file delivery, idempotency, recovery, and activation. A durable run's store keeps each effect's arguments as given, so redact secrets before they reach an effect.
25
46
 
26
47
  Raw JSON schemas retain `unknown` boundary types. Zod transforms, refinements, defaults and coercion are rejected rather than silently dropped. The core does not depend on Zod at runtime. Other Standard JSON Schema providers must faithfully represent their contracts. Typed execution accepts the original `defineWorkflow` result; copied or deserialized documents use `runWorkflow`.
27
48
 
@@ -33,7 +54,7 @@ The package root exports a deliberate API. The beta retains agent, structured-ou
33
54
  | --- | --- |
34
55
  | Typed authoring | `defineWorkflow`, `runTypedWorkflow`, `WorkflowSchemaConversionError`; `StandardJSONSchema`, `AuthoringSchema`, `TypedWorkflow`, `WorkflowInput`, `WorkflowOutput`, `TypedWorkflowRunResult`. |
35
56
  | Structural inspection | `inspectWorkflow`, `formatWorkflowTree`; `WorkflowInspection`, `WorkflowInspectionNode`. Reads structure and capability requirements; does not perform semantic validation or run code probes. |
36
- | Run and inspect | `runWorkflow`, `validateWorkflow`, `workflowSha256`, `dryRunWorkflow`; core contracts `Workflow`, `WorkflowNode`, `WorkflowDeps`, `WorkflowRunResult`, plus the named node, predicate, effect, effort and result types. |
57
+ | Run and inspect | `runWorkflow`, `validateWorkflow`, `workflowSha256`, `dryRunWorkflow`; core contracts `Workflow`, `WorkflowNode`, `WorkflowDeps`, `WorkflowRunResult`, `ValidationIssue` and `ValidationCode` (each validation error's JSON Pointer and rule), plus the named node, predicate, effect, effort and result types. |
37
58
  | Recognize outcomes | `WorkflowInvalidError`, `WorkflowInputInvalidError`, `WorkflowOutputInvalidError`, `WorkflowVerificationError`, `EffectFailure`, `EffectDeadlineExceededError`, `EffectOutcomeUnknownError`, `EscalationSignal`. A concurrent failure may contain typed outcomes in `AggregateError.errors`; inspect them before deciding whether an effect is safe to retry. |
38
59
  | Build judgment adapters | `compileQuestions`, `validateAnswers`, `answersToValue`, `answersSidecar`, `answerConfidence`, `SYSTEM_ONE_LIMITS`, `SystemOneError`; `SystemOneQuestion`, `SystemOneAnswer`, `SystemOneResult`, `SystemOneRetryClass`, `CompiledQuestions`, `AnswersSidecar`. |
39
60
  | Integrate a host | `runWorkflowSlice`, `assertWorkflowCapabilities`, `desugarWorkflow`, `resolveSchemaForWorkflow`, `stageSchemaForNode`, `submissionSchemaForNode`, `mergeStageDelta`, `REPORT_SCHEMA`, `SHELL_RESULT_SCHEMA`, `getPath`, `predicateMatches`, `deniedGlobalReferences`. |
@@ -47,7 +68,7 @@ A `code` node runs in the host process through the package's own executor, which
47
68
 
48
69
  The schema helpers resolve the owning workflow's schema catalog; `stageSchemaForNode` and `submissionSchemaForNode` name the same submission contract. `mergeStageDelta` stores declared submission fields under the node's output key; callers must validate the submission first. Internal traversal, compilation, CSV, reference-file and input-normalization helpers are not package-root APIs.
49
70
 
50
- `@parcha/agentrun-dsl/graph` imports nothing, so a static viewer bundles it and a reader with no Node runs it. `workflowGraph(workflow)` returns `{ nodes, edges }` for a workflow document, computed from its JSON alone: a node is `{ path, kind, label, via? }` with `path` a JSON Pointer into the document as written (`/root/steps/1`, `/root/branches/<name>/body`, `/root/body` for a map's or a loop's body, `/root/workflow/root` for a child; the pointers `inspectWorkflow` and a validation issue use), and an edge is `{ from, to, kind }` with `kind` one of `next` (a chain's steps in order, a loop into its body), `branch` (a parallel node's branches), `route` (a route's branches), `item` (a map into its body) and `child` (a workflow node into its child's root). `nodeStatus(graph, source)` says, for each node, `done`, `working`, `failed` or `not-run`, read from what the recovery driver kept: its frame (the `pin` of the frozen snapshot), the map items' records (`agentrun.items`, keyed layout), or both as `{ pin, items }`. A run's map item or loop iteration has no node of its own: its instances count toward the body's node, and a node inside a map's or loop's body is done only once the map or loop is. To read one item's record on its own, pass `{ item: "<map path>/items/<index>" }` as a third argument: that item is then the instance, and its body is done when the item is. The pi session's text view draws the same graph.
71
+ `@parcha/agentrun-dsl/graph` imports nothing, so a static viewer bundles it and a reader with no Node runs it. `workflowGraph(workflow)` returns `{ nodes, edges }` for a workflow document, computed from its JSON alone: a node is `{ path, kind, label, via? }` with `path` a JSON Pointer into the document as written (`/root/steps/1`, `/root/branches/<name>/body`, `/root/body` for a map's or a loop's body, `/root/workflow/root` for a child; the pointers `inspectWorkflow` and a validation issue use), and an edge is `{ from, to, kind }` with `kind` one of `next` (a chain's steps in order, a loop into its body), `branch` (a parallel node's branches), `route` (a route's branches), `item` (a map into its body) and `child` (a workflow node into its child's root). `nodeStatus(graph, source)` says, for each node, `done`, `working`, `failed` or `not-run`, read from what the recovery driver kept: its frame (the `pin` of the frozen snapshot), the map items' records (`agentrun.items`, keyed layout), or both as `{ pin, items }`. A run's map item or loop iteration has no node of its own: its instances count toward the body's node, and a node inside a map's or loop's body is done only once the map or loop is. To read one item's record on its own, pass `{ item: "<map path>/items/<index>" }` as a third argument: that item is then the instance, and its body is done when the item is. `graphNodeOf(graph, executionPath)` names the node an execution path (an event's or a record's) ran at: `{ path, at }`, where `path` is the node's pointer and `at` lists the map items (`{ kind: "item", index }`) and loop iterations (`{ kind: "iteration", index }`) it ran in, outermost first. An execution path is the node's pointer with `items/<i>` before a map's `body` and `iterations/<i>` before a loop's; the path is read by walking the graph by node kind, so a route branch named `items` stays a branch, and a path the graph does not have is `undefined`. The pi session's text view draws the same graph.
51
72
 
52
73
  The separate `@parcha/agentrun-dsl/demo` entrypoint provides the support-triage example. `@parcha/agentrun-dsl/schema` provides the generated workflow JSON Schema.
53
74
 
@@ -55,7 +76,7 @@ Children can contain maps, loops, routes, parallel branches and other children,
55
76
 
56
77
  ## Bounds
57
78
 
58
- These are the current beta's validation rules. The numeric knobs below carry no upper ceiling: the author picks the number, and a host may set its own default, but the validator never caps how high it goes. What remains are lower bounds and structural requirements — a floor a value must sit at or above, a field that must be present — plus the parser's own safety guards, and the System-One question shape (a bounded multiple choice). Hosts may still impose their own budgets as defaults.
79
+ These are the current beta's validation rules. The numeric knobs below carry no upper ceiling: the author picks the number, and a host may set its own default, but the validator never caps how high it goes. What remains are lower bounds and structural requirements (a floor a value must sit at or above, a field that must be present), plus the parser's own safety guards, and the System-One question shape (a bounded multiple choice). Hosts may still impose their own budgets as defaults.
59
80
 
60
81
  | Setting | Bound |
61
82
  | --- | --- |
package/dist/author.js CHANGED
@@ -59,7 +59,7 @@ Their fields:
59
59
  - ${code("out")} names the schema the submission must satisfy; the value lands at ${code("as")}.
60
60
  - ${code("requires")} lists state paths that must hold evidence before the node runs, each produced upstream: missing values, null, blank strings, empty arrays and empty objects stop the run; ${code("false")} and ${code("0")} pass.
61
61
  - ${code("tools")} names tools the host offers. ${code("[]")} means no tools; omitting ${code("tools")} offers every tool the host allows. Never name a tool the host did not offer.
62
- - ${code("effort")} is ${alternatives(EFFORT_LEVELS)}; ${code("thinking")} is ${alternatives(THINKING_LEVELS)} (never off); ${code("tier")} is ${alternatives(MODEL_TIERS)}. They are requests to the host: resource ceilings are the host's.
62
+ - ${code("effort")} is ${alternatives(EFFORT_LEVELS)}; ${code("thinking")} is ${alternatives(THINKING_LEVELS)} (never off); ${code("tier")} is ${alternatives(MODEL_TIERS)}. They are requests to the host: resource ceilings are the host's. A node that names no ${code("thinking")} thinks at medium, unless its host sets another level.
63
63
  - An ${code("agent")} node may carry ${code("budget_usd")}, the most it asks to spend in dollars (above 0), which the host caps by what it has left, and ${code("context")}, ${alternatives(AGENT_CONTEXTS)}: ${code("fresh")} (the default) sees only its instructions and state; ${code("fork")} asks the host to start it from the caller's transcript, which a host refuses where it has none.
64
64
  - ${code("sopSection")} names one heading of the host's SOP, or a list of them, as the exact text after "## ". The node receives those sections verbatim.
65
65
  - ${code("verify")} reviews a submission before it is accepted: {"out": a question schema with at least one boolean question, "state"?, "maxDrives"?: an integer >= 1 (default 2, no maximum), "override"?: {"below": a number in (0, 1), default 0.3}}. A boolean question named after a submission field doubts that field when its yes-probability is below ${code("override.below")}; any other boolean question is a requirement met at 0.5. A rejected submission returns to the same session with the reasons.
@@ -84,7 +84,7 @@ Typed questions answered by the host's judge in one request each: no tools, no s
84
84
  ### Control nodes
85
85
 
86
86
  - ${code("chain")}: non-empty ${code("steps")}, run in order.
87
- - ${code("map")}: ${code("itemsPath")} (an upstream list), ${code("body")} and ${code("as")}. The body sees ${code("item")} and ${code("item_index")}; ${code("maxConcurrency")} is a positive integer (default 4); ${code("resultPath")} selects one path from each completed item's state. Without ${code("resultPath")}, and with no ${code("as")} in the body, each item's result is its whole state, the mapped list included: set ${code("resultPath")} (or an ${code("as")} in the body) for a large map; the validator warns.
87
+ - ${code("map")}: ${code("itemsPath")} (an upstream list), ${code("body")} and ${code("as")}. The body sees ${code("item")} and ${code("item_index")}; ${code("maxConcurrency")} is a positive integer (default 4); ${code("resultPath")} selects one path from each completed item's state. Without ${code("resultPath")}, and with no ${code("as")} in the body, each item's result is its whole state, the mapped list included: set ${code("resultPath")} (or an ${code("as")} in the body) for a large map; the validator warns. ${code("onItemFailure")} is ${code("stop")} (default: the first failing item stops the map and the run) or ${code("collect")}. With ${code("collect")}, an item whose node fails (a call that failed after its retries, an agent that delivered no record, output that does not match its schema, a failed check) ends as {item_index, label, code, message} in the list at ${code("failedAs")}, the other items finish, and ${code("as")} stays aligned with the items: ${code("as[i]")} is item i's result, or ${code("null")} when item i failed. Filter the nulls explicitly if only successes are wanted. Gate on ${code("failedAs")} with ${code("escalate")} or a code node; never let failures pass silently. A crash, a cancel, an ${code("escalate")} inside the item or an effect whose outcome is unknown is never collected.
88
88
  - ${code("parallel")}: at least two ${code("branches")}, each starting from the state before the parallel node. Branches write disjoint keys and never read a sibling's writes.
89
89
  - ${code("loop")}: ${code("body")}, ${code("until")} (a predicate) and an integer ${code("maxIters")} of at least 1 (no maximum), optionally an integer ${code("expect_iters")} of at least 1 (priced passes). At the bound the state passes through with ${code("until")} unmet; follow the loop with an escalate or gate on that condition.
90
90
  - ${code("escalate")}: ${code("when")} (a predicate), and non-empty ${code("kind")}, ${code("stage")} and ${code("summary")}. When the predicate holds the run stops without output and returns the escalation with its interpolated summary.
package/dist/authoring.js CHANGED
@@ -57,7 +57,7 @@ export function defineWorkflow(definition) {
57
57
  });
58
58
  const result = validateWorkflow(document);
59
59
  if (!result.ok)
60
- throw new WorkflowInvalidError(document.name, result.errors);
60
+ throw new WorkflowInvalidError(document.name, result.errors, result.issues);
61
61
  const inputSchema = resolveSchemaForWorkflow(document, document.schemas[definition.input]);
62
62
  if (!objectContract(inputSchema)) {
63
63
  throw new WorkflowSchemaConversionError(definition.input, new Error("workflow input must be constrained to JSON objects; declare type: object or object-only schema alternatives"));
package/dist/cli.js CHANGED
@@ -12,7 +12,7 @@ const help = `AgentRun DSL — build, test, and run agent workflows
12
12
  agentrun example [file.json] Write the demo workflow (never overwrite)
13
13
  agentrun inspect workflow.json [--json] Show structure without executing code
14
14
  agentrun validate workflow.json [input.json] --trusted
15
- agentrun dry-run workflow.json [input.json] --trusted
15
+ agentrun dry-run workflow.json [input.json] --trusted [--strict]
16
16
  agentrun run workflow.json input.json --trusted
17
17
 
18
18
  demo runs the real interpreter with scripted judgments, without a key or network.
@@ -22,6 +22,8 @@ during validation and running. Only use workflows you trust; this is not a sandb
22
22
  validate checks a supplied input against the workflow's input contract.
23
23
  dry-run uses supplied input, or synthesizes it from the declared input schema.
24
24
  Without an input schema, dry-run starts with an empty input object.
25
+ dry-run exits 1 when a check fails. A check that could not run (status not_run, the
26
+ reasons under skipped) exits 0 unless --strict is given, which makes it exit 3.
25
27
  `;
26
28
  async function main(args) {
27
29
  const [command] = args;
@@ -86,14 +88,15 @@ async function main(args) {
86
88
  throw new Error(`Unknown command "${command}". Use agentrun --help.`);
87
89
  if (!args.includes("--trusted"))
88
90
  throw new Error("Pass --trusted only after reviewing the workflow. Authored JavaScript may execute, including during validation.");
89
- const positional = args.slice(1).filter(arg => arg !== "--trusted");
91
+ const strict = command === "dry-run" && args.includes("--strict");
92
+ const positional = args.slice(1).filter(arg => arg !== "--trusted" && !(strict && arg === "--strict"));
90
93
  const unknown = positional.find(arg => arg.startsWith("--"));
91
94
  if (unknown)
92
95
  throw new Error(`Unknown option "${unknown}". Use agentrun --help.`);
93
96
  if (!positional[0])
94
97
  throw new Error("Provide a workflow JSON file.");
95
98
  if (positional.length > 2)
96
- throw new Error(`Usage: agentrun ${command} workflow.json ${command === "run" ? "input.json" : "[input.json]"} --trusted`);
99
+ throw new Error(`Usage: agentrun ${command} workflow.json ${command === "run" ? "input.json" : "[input.json]"} --trusted${command === "dry-run" ? " [--strict]" : ""}`);
97
100
  if (command === "run" && !positional[1])
98
101
  throw new Error("Provide an input JSON file.");
99
102
  const workflow = JSON.parse(await readFile(resolve(positional[0]), "utf8"));
@@ -121,6 +124,8 @@ async function main(args) {
121
124
  console.log(JSON.stringify(result, null, 2));
122
125
  if (!result.ok)
123
126
  process.exitCode = 1;
127
+ else if (strict && result.status === "not_run")
128
+ process.exitCode = 3;
124
129
  }
125
130
  else {
126
131
  const result = await runWorkflow(workflow, input, {});
package/dist/dry-run.d.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  import { type Workflow, type WorkflowDeps } from "./workflow.js";
2
+ /** `ok` keeps its meaning: false only when a check failed. `status` says whether every check ran: `passed`, `not_run`
3
+ * (a check stood down; `skipped` says which and why, so this is not proof the graph was exercised) or `failed`. */
2
4
  export type DryRunResult = {
3
5
  ok: true;
6
+ status: "passed" | "not_run";
4
7
  skipped?: string[];
5
8
  } | {
6
9
  ok: false;
10
+ status: "failed";
7
11
  problems: string[];
8
12
  stage?: string;
9
13
  };
package/dist/dry-run.js CHANGED
@@ -118,7 +118,7 @@ function unsupportedConstructs(schema, path, found, depth = 0) {
118
118
  export async function dryRunWorkflow(workflow, opts = {}) {
119
119
  const valid = validateWorkflow(workflow, { ...(opts.input === undefined ? {} : { input: opts.input }), ...(opts.runCode ? { executeCode: false } : {}) });
120
120
  if (!valid.ok)
121
- return { ok: false, problems: [new WorkflowInvalidError(String(workflow?.name), valid.errors).message] };
121
+ return { ok: false, status: "failed", problems: [new WorkflowInvalidError(String(workflow?.name), valid.errors, valid.issues).message] };
122
122
  const skipped = [];
123
123
  const scanSchemas = (plan) => {
124
124
  for (const [id, schema] of Object.entries(plan.schemas || {}))
@@ -139,13 +139,13 @@ export async function dryRunWorkflow(workflow, opts = {}) {
139
139
  };
140
140
  scanSchemas(workflow);
141
141
  if (skipped.length)
142
- return { ok: true, skipped };
142
+ return { ok: true, status: "not_run", skipped };
143
143
  let input = opts.input ?? {};
144
144
  if (opts.input === undefined && workflow.input) {
145
145
  const schema = resolveSchemaForWorkflow(workflow, workflow.schemas[workflow.input.schemaId]);
146
146
  const generated = synthesizeInstance(schema, schema.definitions ?? workflow.schemas);
147
147
  if (!generated || typeof generated !== "object" || Array.isArray(generated) || !Compile(schema).Check(generated)) {
148
- return { ok: true, skipped: ["Could not synthesize a valid input object. Supply input explicitly to dryRunWorkflow or the dry-run CLI."] };
148
+ return { ok: true, status: "not_run", skipped: ["Could not synthesize a valid input object. Supply input explicitly to dryRunWorkflow or the dry-run CLI."] };
149
149
  }
150
150
  input = generated;
151
151
  }
@@ -199,19 +199,19 @@ export async function dryRunWorkflow(workflow, opts = {}) {
199
199
  });
200
200
  if (result.status === "escalated") {
201
201
  // Synthetic values tripping an escalate predicate proves nothing about real cases.
202
- return { ok: true, skipped: [`escalated:${result.escalation.kind}@${result.escalation.stage} on synthetic values`] };
202
+ return { ok: true, status: "not_run", skipped: [`escalated:${result.escalation.kind}@${result.escalation.stage} on synthetic values`] };
203
203
  }
204
- return { ok: true };
204
+ return { ok: true, status: "passed" };
205
205
  }
206
206
  catch (error) {
207
207
  if (stopped)
208
- return { ok: true, skipped: [stopped] };
208
+ return { ok: true, status: "not_run", skipped: [stopped] };
209
209
  if (error instanceof WorkflowOutputInvalidError) {
210
- return { ok: false, problems: error.problems, stage: error.stage };
210
+ return { ok: false, status: "failed", problems: error.problems, stage: error.stage };
211
211
  }
212
212
  if (error instanceof WorkflowInputInvalidError)
213
- return { ok: false, problems: [error.message] };
213
+ return { ok: false, status: "failed", problems: [error.message] };
214
214
  const message = error instanceof Error ? error.message : String(error);
215
- return { ok: false, problems: [`deterministic path threw over schema-conforming inputs${currentLabel ? ` (at "${currentLabel}")` : ""}: ${message.slice(0, 1200)}`], stage: currentLabel || undefined };
215
+ return { ok: false, status: "failed", problems: [`deterministic path threw over schema-conforming inputs${currentLabel ? ` (at "${currentLabel}")` : ""}: ${message.slice(0, 1200)}`], stage: currentLabel || undefined };
216
216
  }
217
217
  }
package/dist/graph.d.ts CHANGED
@@ -64,4 +64,20 @@ export type StatusOptions = {
64
64
  * layout, the records of the map items (a run's whole story is the frame and the items together). A source that is not
65
65
  * one of those shows no node run. */
66
66
  export declare function nodeStatus(graph: WorkflowGraph, source: StatusSource, options?: StatusOptions): Record<string, NodeState>;
67
+ /** Where an execution path is in the graph: the node it ran at (`path`, a node of the graph) and the map items and loop
68
+ * iterations it ran in, outermost first. */
69
+ export type GraphNodeAt = {
70
+ path: string;
71
+ at: {
72
+ kind: "item" | "iteration";
73
+ index: number;
74
+ }[];
75
+ };
76
+ /** The graph node an execution path ran at. An execution path is the node's JSON Pointer with two runtime segments added:
77
+ * a map's item (`items/<i>` before the map's `body`) and a loop's iteration (`iterations/<i>` before the loop's `body`); the
78
+ * graph has `/body` for both, and the indexes are returned in `at`. The path is read by walking the graph from `/root`, by
79
+ * each node's kind, never by matching its text, so a route branch named `items` or `iterations` is a branch. Undefined for
80
+ * a path the graph does not have, or one that is not an execution path (a map's `body` without an item, an item without
81
+ * its `body`). */
82
+ export declare function graphNodeOf(graph: WorkflowGraph, executionPath: string): GraphNodeAt | undefined;
67
83
  export {};
package/dist/graph.js CHANGED
@@ -2,7 +2,8 @@
2
2
  // (the static viewer inlines it) and the pi session's text view draw the same graph; nothing here validates, runs or
3
3
  // reads a store. `workflowGraph` reads the workflow JSON as written; `nodeStatus` reads the driver's record of a run
4
4
  // (the `agentrun.driver` frame of the frozen snapshot, and the `agentrun.items` of a keyed-layout run) and says, for
5
- // each node of that graph, whether it is done, working, failed or not run.
5
+ // each node of that graph, whether it is done, working, failed or not run; `graphNodeOf` names the node an execution path ran
6
+ // at, and the map items and loop iterations around it.
6
7
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7
8
  const pointer = (part) => part.replace(/~/g, "~0").replace(/\//g, "~1");
8
9
  /** The nesting depth `validateWorkflow` and `inspectWorkflow` accept (128 JSON levels): a node nests at least one level deeper than its parent, so every node of such a document is within it. */
@@ -156,3 +157,75 @@ export function nodeStatus(graph, source, options = {}) {
156
157
  }
157
158
  return out;
158
159
  }
160
+ /** An item or iteration index as an execution path writes it: a whole number with no sign and no leading zero. */
161
+ const indexOf = (segment) => segment !== undefined && /^(0|[1-9][0-9]*)$/.test(segment) && Number.isSafeInteger(Number(segment)) ? Number(segment) : undefined;
162
+ /** The graph node an execution path ran at. An execution path is the node's JSON Pointer with two runtime segments added:
163
+ * a map's item (`items/<i>` before the map's `body`) and a loop's iteration (`iterations/<i>` before the loop's `body`); the
164
+ * graph has `/body` for both, and the indexes are returned in `at`. The path is read by walking the graph from `/root`, by
165
+ * each node's kind, never by matching its text, so a route branch named `items` or `iterations` is a branch. Undefined for
166
+ * a path the graph does not have, or one that is not an execution path (a map's `body` without an item, an item without
167
+ * its `body`). */
168
+ export function graphNodeOf(graph, executionPath) {
169
+ if (typeof executionPath !== "string")
170
+ return undefined;
171
+ const kinds = new Map(graph.nodes.map((node) => [node.path, node.kind]));
172
+ const parts = executionPath.split("/");
173
+ if (parts[0] !== "" || parts[1] !== "root" || !kinds.has("/root"))
174
+ return undefined;
175
+ let path = "/root";
176
+ const at = [];
177
+ for (let i = 2; i < parts.length;) {
178
+ const [first, second, third] = [parts[i], parts[i + 1], parts[i + 2]];
179
+ let next;
180
+ switch (kinds.get(path)) {
181
+ case "chain":
182
+ if (first === "steps" && indexOf(second) !== undefined) {
183
+ next = `${path}/steps/${second}`;
184
+ i += 2;
185
+ }
186
+ break;
187
+ case "parallel":
188
+ if (first === "branches" && indexOf(second) !== undefined) {
189
+ next = `${path}/branches/${second}`;
190
+ i += 2;
191
+ }
192
+ break;
193
+ case "route":
194
+ // The branch's name, pointer-escaped as in the graph, whatever it is: `items`, `iterations`, `0`, and the empty name a
195
+ // route Jev chooses may give a branch, included.
196
+ if (first === "branches" && second !== undefined && third === "body") {
197
+ next = `${path}/branches/${second}/body`;
198
+ i += 3;
199
+ }
200
+ break;
201
+ case "workflow":
202
+ if (first === "workflow" && second === "root") {
203
+ next = `${path}/workflow/root`;
204
+ i += 2;
205
+ }
206
+ break;
207
+ case "map": {
208
+ const index = indexOf(second);
209
+ if (first === "items" && index !== undefined && third === "body") {
210
+ at.push({ kind: "item", index });
211
+ next = `${path}/body`;
212
+ i += 3;
213
+ }
214
+ break;
215
+ }
216
+ case "loop": {
217
+ const index = indexOf(second);
218
+ if (first === "iterations" && index !== undefined && third === "body") {
219
+ at.push({ kind: "iteration", index });
220
+ next = `${path}/body`;
221
+ i += 3;
222
+ }
223
+ break;
224
+ }
225
+ }
226
+ if (next === undefined || !kinds.has(next))
227
+ return undefined;
228
+ path = next;
229
+ }
230
+ return { path, at };
231
+ }
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
2
2
  export type { StandardJSONSchema, AuthoringSchema, TypedWorkflow, TypedWorkflowRunResult, WorkflowInput, WorkflowOutput, } from "./authoring.js";
3
- export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, } from "./workflow.js";
3
+ export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, isItemFailure, } from "./workflow.js";
4
4
  export { defineJob } from "./job.js";
5
5
  export type { Job } from "./job.js";
6
6
  export { DECISION_RECEIPT_VERSION, rederiveDecision } from "./decision-receipts.js";
7
7
  export type { DecisionKind, DecisionReceipt, DecisionRule } from "./decision-receipts.js";
8
- export type { Workflow, WorkflowNode, NodeMetadata, WorkflowDeps, WorkflowEvent, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, DecisionExchange, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, RouteByJudgmentNode, RouteByValueNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CodeNode, CallRetryClass, EffectFailureCode, CallPredicate, PollClause, ModelTier, AgentContext, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, MechanicalPredicate, Predicate, } from "./workflow.js";
8
+ export type { Workflow, WorkflowNode, NodeMetadata, WorkflowDeps, WorkflowEvent, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, MapItemFailure, DecisionExchange, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, RouteByJudgmentNode, RouteByValueNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CodeNode, CallRetryClass, EffectFailureCode, CallPredicate, PollClause, ModelTier, AgentContext, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, MechanicalPredicate, Predicate, ValidationCode, ValidationIssue, } from "./workflow.js";
9
9
  export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
10
10
  export type { DryRunOptions, DryRunResult } from "./dry-run.js";
11
11
  export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, } from "./system-one.js";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
2
- export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, } from "./workflow.js";
2
+ export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, isItemFailure, } from "./workflow.js";
3
3
  export { defineJob } from "./job.js";
4
4
  export { DECISION_RECEIPT_VERSION, rederiveDecision } from "./decision-receipts.js";
5
5
  export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
@@ -102,6 +102,8 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
102
102
  pollStartedAt: (node: import("../workflow.js").CallNode, item?: import("../workflow.js").MapItem, executionPath?: string) => number;
103
103
  wait: (node: import("../workflow.js").CallNode, ms: number, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<void>;
104
104
  fail?: (node: WorkflowNode, results: unknown[], error: unknown, executionPath?: string) => Promise<void>;
105
+ failItem?: (node: WorkflowNode, failure: import("../workflow.js").MapItemFailure, executionPath?: string) => Promise<void>;
106
+ itemFailure?: (node: WorkflowNode, executionPath?: string) => Promise<import("../workflow.js").MapItemFailure | undefined>;
105
107
  decision?: (id: string) => Promise<import("../decision-receipts.js").DecisionReceipt | undefined>;
106
108
  };
107
109
  signal: AbortSignal;
@@ -149,7 +151,7 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
149
151
  stepAdmitted(executionPath: unknown): boolean;
150
152
  /** The current attempt did not submit: its session closes with its spend kept.
151
153
  * The step is `closed` until a retry is admitted, or `failed` when no attempt remains. */
152
- stepAttemptFailed(executionPath: unknown, final?: boolean): void;
154
+ stepAttemptFailed(executionPath: unknown, final?: boolean, error?: unknown): void;
153
155
  /** The step delivered its record; the row and the step record agree before the step commit. */
154
156
  stepSubmitted(executionPath: unknown): void;
155
157
  /** The short identity of an admitted LLM step (a digest of its frame and path), for the escalation
@@ -4,13 +4,13 @@
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";
7
+ import { desugarWorkflow, isItemFailure } from "../workflow.js";
8
8
  import { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, topLevelCompletion } from "./execution-path.js";
9
9
  import { bindingDigests, LEDGER_FORMAT } from "./binding.js";
10
10
  import { canonicalHash as hash } from "./canonical-hash.js";
11
11
  import { RecoveryError } from "./errors.js";
12
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 } from "./frozen-snapshot.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
14
  const failure = (code, message) => new RecoveryError(message, code);
15
15
  /** The branch a route runs for its answer, as the interpreter takes it: the node's `unsure` branch when
16
16
  * the answer's confidence is below `unsure.gte`, else the choice the answer names. */
@@ -246,9 +246,15 @@ export async function openRecovery(store, workflow, options) {
246
246
  const valid = record.driver === driver && record.map === mapPath && record.index === index && record.base === entry.base && Number.isSafeInteger(record.revision)
247
247
  && ["running", "committed", "failed"].includes(record.status) && isRecord(record.frame) && Array.isArray(record.frame.done)
248
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");
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);
250
254
  if (!valid)
251
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 };
252
258
  lastItems.set(path, JSON.stringify({ ...record, revision: 0 }));
253
259
  frame.done.push(...record.frame.done);
254
260
  Object.assign(frame.steps, record.frame.steps);
@@ -454,6 +460,14 @@ export async function openRecovery(store, workflow, options) {
454
460
  else if (build)
455
461
  build.record.unknownResponses[id] = value;
456
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
+ }
457
471
  for (const id of new Set([...journal.effects().map((effect) => effect.id), ...queued, ...(admitting === undefined ? [] : [admitting])])) {
458
472
  const build = own(frozenEffectPath(id)?.path);
459
473
  if (build)
@@ -488,7 +502,7 @@ export async function openRecovery(store, workflow, options) {
488
502
  };
489
503
  const items = {};
490
504
  for (const build of builds.values()) {
491
- build.record.status = finished(build.path) ? "committed" : "running";
505
+ build.record.status = build.record.outcome ? "failed" : finished(build.path) ? "committed" : "running";
492
506
  const text = JSON.stringify(build.record);
493
507
  if (lastItems.get(build.path) !== text) {
494
508
  lastItems.set(build.path, text);
@@ -506,7 +520,7 @@ export async function openRecovery(store, workflow, options) {
506
520
  const frame = snapshot.pin;
507
521
  const done = new Set(frame.done);
508
522
  const paths = [...frame.done, ...Object.keys(frame.states), ...Object.keys(frame.chains), ...Object.keys(frame.inputs), ...Object.keys(frame.steps),
509
- ...Object.keys(frame.loops), ...Object.keys(frame.routes)];
523
+ ...Object.keys(frame.loops), ...Object.keys(frame.routes), ...Object.keys(frame.failures ?? {}).map((item) => `${item}/body`)];
510
524
  return paths.every((path) => { const at = mapItemOf(path); return !at || done.has(at.map) || Boolean(maps.get(at.map)?.baseState); });
511
525
  };
512
526
  /** One write of the driver's state, in the layout this open keeps. */
@@ -724,7 +738,9 @@ export async function openRecovery(store, workflow, options) {
724
738
  return undefined;
725
739
  };
726
740
  /** Drops what no resume can ask for again: the states, chain frontiers, loop counts, route decisions
727
- * and start bindings of the paths `gone` names. Step records stay: a host reads its sessions from them. */
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. */
728
744
  const prune = (frame, gone) => {
729
745
  for (const table of [frame.states, frame.chains, frame.loops, frame.routes, frame.inputs]) {
730
746
  for (const key of Object.keys(table))
@@ -732,6 +748,24 @@ export async function openRecovery(store, workflow, options) {
732
748
  delete table[key];
733
749
  }
734
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
+ };
735
769
  const recovery = {
736
770
  // Every store key below is the interpreter's execution path, so a composed graph (a loop, a route, a
737
771
  // map whose body is structure, a nested child) resumes where it stopped.
@@ -820,6 +854,35 @@ export async function openRecovery(store, workflow, options) {
820
854
  await save();
821
855
  await flush();
822
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
+ },
823
886
  pollStartedAt(node, _item, executionPath) {
824
887
  guard();
825
888
  const { tag, doc } = active();
@@ -916,7 +979,7 @@ export async function openRecovery(store, workflow, options) {
916
979
  stepAdmitted(executionPath) { const { frame, at } = llmStep(executionPath); return frame.steps[at] !== undefined; },
917
980
  /** The current attempt did not submit: its session closes with its spend kept.
918
981
  * The step is `closed` until a retry is admitted, or `failed` when no attempt remains. */
919
- stepAttemptFailed(executionPath, final = false) {
982
+ stepAttemptFailed(executionPath, final = false, error) {
920
983
  guard();
921
984
  const { frame, tag, at } = llmStep(executionPath);
922
985
  const step = frame.steps[at];
@@ -925,7 +988,11 @@ export async function openRecovery(store, workflow, options) {
925
988
  const id = sessionOf(tag, at, step);
926
989
  if (options.closeStepSession)
927
990
  void persist(() => options.closeStepSession(id)).catch(() => undefined);
928
- closeFrozenStepAttempt(step, final);
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);
929
996
  save();
930
997
  },
931
998
  /** The step delivered its record; the row and the step record agree before the step commit. */
@@ -21,7 +21,10 @@ export type ItemRecord = {
21
21
  base: string;
22
22
  /** The journal revision of the commit that wrote this value. */
23
23
  revision: number;
24
+ /** `failed`: the item ended on its failure, which `outcome` holds; its map collects its items' failures. */
24
25
  status: "running" | "committed" | "failed";
26
+ /** Present exactly when `status` is `failed`. */
27
+ outcome?: ItemOutcome;
25
28
  frame: {
26
29
  done: string[];
27
30
  states: Record<string, StateDelta>;
@@ -126,6 +129,15 @@ export type PathFrame = {
126
129
  as: string;
127
130
  results: unknown[];
128
131
  };
132
+ /** The map items that ended on their failure (`onItemFailure: "collect"`), by the item's path (`<map>/items/<i>`): an
133
+ * item here is answered from its row and its body never runs again. Kept with the run, as committed paths are. */
134
+ failures?: Record<string, ItemOutcome>;
135
+ };
136
+ /** How a map item that ended on its failure ended: the failing node's label, the failure's code and its message. */
137
+ export type ItemOutcome = {
138
+ code: string;
139
+ label: string;
140
+ message: string;
129
141
  };
130
142
  /** The recovery driver's durable state. It lives whole in the journal; each commit replaces it. No run
131
143
  * clock: clocks exist only per effect. */
@@ -149,6 +161,12 @@ export type StepRecord = {
149
161
  attempt: number;
150
162
  attemptsAllowed: number;
151
163
  status: "running" | "closed" | "failed" | "submitted";
164
+ /** The failure that failed the step, when it was an item failure (`isItemFailure`) in an item of a map that collects
165
+ * its items' failures: a later open refuses the step with it, so the item ends on the same failure in every process. */
166
+ failure?: {
167
+ code: string;
168
+ message: string;
169
+ };
152
170
  };
153
171
  export type EscalationRow = {
154
172
  kind: string;
@@ -180,6 +198,8 @@ export type FrozenShape = {
180
198
  resolves: (path: string) => boolean;
181
199
  };
182
200
  export declare const emptyPathFrame: () => PathFrame;
201
+ /** Whether a value is an item's committed failure: three strings, and nothing else. */
202
+ export declare const isItemOutcome: (value: unknown) => value is ItemOutcome;
183
203
  /** Refuses a saved snapshot the driver could not have produced for this run. */
184
204
  export declare function validateFrozenSnapshot(saved: any, shape: FrozenShape): void;
185
205
  /** The snapshot a driver runs under: the saved one (a paused run resumes running, retired keys
@@ -218,7 +238,7 @@ export declare function admitFrozenStep(steps: Record<string, StepRecord>, path:
218
238
  };
219
239
  /** The current attempt ended without a submission: `closed` until a retry is admitted, or
220
240
  * `failed` when the failure is final or no attempt remains. */
221
- export declare function closeFrozenStepAttempt(step: StepRecord, final: boolean): void;
241
+ export declare function closeFrozenStepAttempt(step: StepRecord, final: boolean, failure?: StepRecord["failure"]): void;
222
242
  /** The run-wide stop the driver applies: the host's pause or cancel it was handed, or null when it keeps
223
243
  * running. A cancelled snapshot stays cancelled. */
224
244
  export declare function frozenStop(status: FrozenSnapshot["status"], requested: "pause" | "cancel" | undefined): "paused" | "cancelled" | null;