@parcha/agentrun-dsl 0.1.0-beta.3 → 0.1.0-beta.31

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 (103) hide show
  1. package/README.md +165 -21
  2. package/dist/author-references.d.ts +8 -0
  3. package/dist/author-references.js +8 -0
  4. package/dist/author.d.ts +16 -3
  5. package/dist/author.js +40 -16
  6. package/dist/authoring.js +2 -2
  7. package/dist/cli.js +17 -12
  8. package/dist/code-exec.d.ts +6 -0
  9. package/dist/code-exec.js +126 -0
  10. package/dist/decision-provider.d.ts +157 -0
  11. package/dist/decision-provider.js +230 -0
  12. package/dist/decision-receipts.d.ts +143 -0
  13. package/dist/decision-receipts.js +93 -0
  14. package/dist/dry-run.d.ts +14 -1
  15. package/dist/dry-run.js +58 -15
  16. package/dist/graph.d.ts +169 -0
  17. package/dist/graph.js +433 -0
  18. package/dist/index.d.ts +15 -8
  19. package/dist/index.js +8 -4
  20. package/dist/inspection.d.ts +5 -0
  21. package/dist/inspection.js +16 -3
  22. package/dist/job.d.ts +14 -0
  23. package/dist/job.js +5 -0
  24. package/dist/long-timer.d.ts +7 -0
  25. package/dist/long-timer.js +22 -0
  26. package/dist/observer-snapshot.d.ts +3 -0
  27. package/dist/observer-snapshot.js +46 -0
  28. package/dist/predicates.d.ts +10 -0
  29. package/dist/predicates.js +18 -0
  30. package/dist/recovery/binding.d.ts +10 -0
  31. package/dist/recovery/binding.js +43 -0
  32. package/dist/recovery/call-key.d.ts +13 -0
  33. package/dist/recovery/call-key.js +24 -0
  34. package/dist/recovery/canonical-hash.d.ts +7 -0
  35. package/dist/recovery/canonical-hash.js +22 -0
  36. package/dist/recovery/driver.d.ts +238 -0
  37. package/dist/recovery/driver.js +1337 -0
  38. package/dist/recovery/effect-failure.d.ts +34 -0
  39. package/dist/recovery/effect-failure.js +62 -0
  40. package/dist/recovery/errors.d.ts +31 -0
  41. package/dist/recovery/errors.js +51 -0
  42. package/dist/recovery/execution-path.d.ts +53 -0
  43. package/dist/recovery/execution-path.js +167 -0
  44. package/dist/recovery/file-store.d.ts +7 -0
  45. package/dist/recovery/file-store.js +131 -0
  46. package/dist/recovery/frozen-snapshot.d.ts +274 -0
  47. package/dist/recovery/frozen-snapshot.js +187 -0
  48. package/dist/recovery/handoff-block.d.ts +36 -0
  49. package/dist/recovery/handoff-block.js +148 -0
  50. package/dist/recovery/handoff-digest.d.ts +58 -0
  51. package/dist/recovery/handoff-digest.js +195 -0
  52. package/dist/recovery/handoff-files.d.ts +54 -0
  53. package/dist/recovery/handoff-files.js +162 -0
  54. package/dist/recovery/handoff-receipts.d.ts +42 -0
  55. package/dist/recovery/handoff-receipts.js +53 -0
  56. package/dist/recovery/handoff-redact.d.ts +12 -0
  57. package/dist/recovery/handoff-redact.js +44 -0
  58. package/dist/recovery/handoff.d.ts +44 -0
  59. package/dist/recovery/handoff.js +46 -0
  60. package/dist/recovery/index.d.ts +19 -0
  61. package/dist/recovery/index.js +17 -0
  62. package/dist/recovery/item-state.d.ts +48 -0
  63. package/dist/recovery/item-state.js +89 -0
  64. package/dist/recovery/journal.d.ts +28 -0
  65. package/dist/recovery/journal.js +139 -0
  66. package/dist/recovery/memory-store.d.ts +4 -0
  67. package/dist/recovery/memory-store.js +20 -0
  68. package/dist/recovery/store.d.ts +105 -0
  69. package/dist/recovery/store.js +6 -0
  70. package/dist/recovery/testing/conformance.d.ts +4 -0
  71. package/dist/recovery/testing/conformance.js +268 -0
  72. package/dist/recovery/testing/crash-points.d.ts +18 -0
  73. package/dist/recovery/testing/crash-points.js +43 -0
  74. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  75. package/dist/recovery/testing/crash-sweep.js +146 -0
  76. package/dist/recovery/testing/index.d.ts +3 -0
  77. package/dist/recovery/testing/index.js +4 -0
  78. package/dist/recovery/testing/preload.d.ts +1 -0
  79. package/dist/recovery/testing/preload.js +3 -0
  80. package/dist/recovery/transport-facts.d.ts +23 -0
  81. package/dist/recovery/transport-facts.js +46 -0
  82. package/dist/recovery/with-recovery.d.ts +50 -0
  83. package/dist/recovery/with-recovery.js +142 -0
  84. package/dist/submit-envelope.d.ts +9 -0
  85. package/dist/submit-envelope.js +40 -0
  86. package/dist/system-one.d.ts +40 -1
  87. package/dist/system-one.js +141 -5
  88. package/dist/testing/decision-provider.d.ts +32 -0
  89. package/dist/testing/decision-provider.js +183 -0
  90. package/dist/testing/index.d.ts +1 -0
  91. package/dist/testing/index.js +2 -0
  92. package/dist/vocabulary.d.ts +22 -3
  93. package/dist/vocabulary.js +33 -10
  94. package/dist/workflow-shape.d.ts +7 -0
  95. package/dist/workflow-shape.js +115 -67
  96. package/dist/workflow.d.ts +269 -20
  97. package/dist/workflow.js +1251 -341
  98. package/package.json +25 -2
  99. package/schema/workflow.schema.json +506 -12
  100. package/skills/author/SKILL.md +6 -1
  101. package/skills/author/references/jev-decisions.md +58 -6
  102. package/skills/author/references/language.md +28 -19
  103. package/skills/author/references/sdk-authoring.md +2 -0
@@ -0,0 +1,34 @@
1
+ import { EffectFailure, type CallRetryClass, type EffectFailureCode } from "../workflow.js";
2
+ /** A failed effect: its closed code, the prose for the reader, and what the host observed
3
+ * (`detail`: the deadline, the elapsed time, the output tail, the filed output) which the
4
+ * interpreter writes onto the attempt's `effect.failed` event. The retry class is the transport's
5
+ * when it gave one, else the code's. */
6
+ export declare class TypedEffectFailure extends EffectFailure {
7
+ readonly code: EffectFailureCode;
8
+ constructor(code: EffectFailureCode, message: string, options?: {
9
+ detail?: Record<string, unknown>;
10
+ cause?: unknown;
11
+ retryClass?: CallRetryClass | null;
12
+ });
13
+ }
14
+ /** A dispatch that succeeded around a failed tool: the transport answered with the tool's own failure
15
+ * envelope as its text. The envelope is the effect's failure, never its result. */
16
+ export declare class EffectEnvelopeFailure extends Error {
17
+ readonly tool: string;
18
+ readonly envelope: string;
19
+ constructor(tool: string, envelope: string);
20
+ }
21
+ /** A thrown error at an effect boundary, as a TypedEffectFailure. A TypedEffectFailure passes through; a
22
+ * tool the host did not grant (`notGranted` names it) is effect_not_granted; an unknown transport
23
+ * (`via` outside the interpreter's list) is effect_unknown_transport; a tool's failure envelope is
24
+ * effect_transport; otherwise the error's typed transport facts decide: a deadline (a TimeoutError, an
25
+ * AbortError, a 408, an idle cut, a timed-out connect) is effect_timeout, any other typed fact (a
26
+ * status, a system code, an error class) is effect_transport with the retry class those facts earn
27
+ * (effectRetryClass), and an error with no typed fact came through no transport that can be named:
28
+ * effect_unknown_transport. The message is carried for the reader and never read. */
29
+ export declare function classifyEffectFailure(error: unknown, at: {
30
+ label: string;
31
+ via: string;
32
+ }, options?: {
33
+ notGranted?: (error: unknown) => string | undefined;
34
+ }): TypedEffectFailure;
@@ -0,0 +1,62 @@
1
+ // An effect's failure, typed at every boundary. Every failure carries one closed code (EFFECT_FAILURE_CODES, the
2
+ // interpreter's list, which `retry.on` names); the prose stays beside it as `message`, for the reader,
3
+ // and is never the discriminator. This module holds the class a host's effect adapters throw, and the one
4
+ // classifier that maps a thrown transport error to a code from its typed facts (the error's class, its
5
+ // HTTP status, its system code), never from its text.
6
+ import { CALL_TRANSPORTS } from "../vocabulary.js";
7
+ import { EffectFailure } from "../workflow.js";
8
+ import { effectRetryClass, transportFactOf } from "./transport-facts.js";
9
+ /** The retry class a code implies when the failure's transport facts name none: a deadline is a
10
+ * timeout and a non-zero exit is an exit, the two the interpreter's default retry list names; every
11
+ * other code is not transient by nature. */
12
+ const IMPLIED_RETRY_CLASS = { effect_timeout: "timeout", effect_exit: "exit" };
13
+ /** A failed effect: its closed code, the prose for the reader, and what the host observed
14
+ * (`detail`: the deadline, the elapsed time, the output tail, the filed output) which the
15
+ * interpreter writes onto the attempt's `effect.failed` event. The retry class is the transport's
16
+ * when it gave one, else the code's. */
17
+ export class TypedEffectFailure extends EffectFailure {
18
+ constructor(code, message, options = {}) {
19
+ super(message, options.retryClass !== undefined ? options.retryClass : IMPLIED_RETRY_CLASS[code] ?? null, {
20
+ code, ...(options.detail ? { detail: options.detail } : {}), ...(options.cause !== undefined ? { cause: options.cause } : {}),
21
+ });
22
+ }
23
+ }
24
+ /** A dispatch that succeeded around a failed tool: the transport answered with the tool's own failure
25
+ * envelope as its text. The envelope is the effect's failure, never its result. */
26
+ export class EffectEnvelopeFailure extends Error {
27
+ tool;
28
+ envelope;
29
+ constructor(tool, envelope) {
30
+ super(`tool "${tool}" returned a failure: ${envelope.slice(0, 500)}`);
31
+ this.tool = tool;
32
+ this.envelope = envelope;
33
+ this.name = "EffectEnvelopeFailure";
34
+ }
35
+ }
36
+ /** A thrown error at an effect boundary, as a TypedEffectFailure. A TypedEffectFailure passes through; a
37
+ * tool the host did not grant (`notGranted` names it) is effect_not_granted; an unknown transport
38
+ * (`via` outside the interpreter's list) is effect_unknown_transport; a tool's failure envelope is
39
+ * effect_transport; otherwise the error's typed transport facts decide: a deadline (a TimeoutError, an
40
+ * AbortError, a 408, an idle cut, a timed-out connect) is effect_timeout, any other typed fact (a
41
+ * status, a system code, an error class) is effect_transport with the retry class those facts earn
42
+ * (effectRetryClass), and an error with no typed fact came through no transport that can be named:
43
+ * effect_unknown_transport. The message is carried for the reader and never read. */
44
+ export function classifyEffectFailure(error, at, options = {}) {
45
+ if (error instanceof TypedEffectFailure)
46
+ return error;
47
+ const text = error instanceof Error ? error.message : String(error);
48
+ const message = `call node "${at.label}": ${text.slice(0, 500)}`;
49
+ const refused = options.notGranted?.(error);
50
+ if (refused !== undefined)
51
+ return new TypedEffectFailure("effect_not_granted", message, { cause: error, detail: { tool: refused } });
52
+ if (!CALL_TRANSPORTS.includes(at.via))
53
+ return new TypedEffectFailure("effect_unknown_transport", message, { cause: error, detail: { transport: at.via } });
54
+ if (error instanceof EffectEnvelopeFailure)
55
+ return new TypedEffectFailure("effect_transport", message, { cause: error, retryClass: null });
56
+ const fact = transportFactOf(error);
57
+ const retryClass = effectRetryClass(fact);
58
+ if (retryClass === "timeout" || fact.errorName === "AbortError")
59
+ return new TypedEffectFailure("effect_timeout", message, { cause: error, retryClass });
60
+ const typed = fact.status !== undefined || fact.causeCode !== undefined || fact.errorName !== undefined || fact.providerType !== undefined || fact.providerCode !== undefined;
61
+ return new TypedEffectFailure(typed ? "effect_transport" : "effect_unknown_transport", message, { cause: error, retryClass });
62
+ }
@@ -0,0 +1,31 @@
1
+ /** The one error family of durable recovery. A failure of the journal itself (a store that will not open, write or
2
+ * bind, a checkpoint or execution path the driver refuses, a host pause or cancel, an effect whose outcome is unknown
3
+ * and must be reconciled) is a RecoveryError. A host stops a run on one and never hands the run to a fallback: the
4
+ * persistence guarantees rest on that. Every other failure of a workflow is the workflow's own. */
5
+ export declare class RecoveryError extends Error {
6
+ readonly code: string;
7
+ readonly transient = false;
8
+ /** The family's failures are typed: a context object marks `code` as the error's kind for a host that reports
9
+ * failures structurally. */
10
+ readonly context: Record<string, never>;
11
+ /** Who issued the host's pause or cancel this failure is, as the host named it. */
12
+ readonly source?: string;
13
+ constructor(message: string, code?: string, options?: {
14
+ cause?: unknown;
15
+ source?: string;
16
+ });
17
+ }
18
+ /** The failure a session under run control raises when its run was paused or cancelled. */
19
+ export declare const runStoppedError: (stop: "pause" | "cancel", source?: string) => RecoveryError;
20
+ /** The pause or cancel that stopped a run and who issued it (the user unless the host named another), read from a
21
+ * RecoveryError anywhere in an error's cause chain; null for every other failure. */
22
+ export declare function runStopOf(error: unknown): {
23
+ stop: "pause" | "cancel";
24
+ code: string;
25
+ source: string;
26
+ } | null;
27
+ /** A failure raised inside a store or the driver, as a RecoveryError: the original message and code are kept, the
28
+ * original error is its cause. */
29
+ export declare function asRecoveryError(error: unknown): RecoveryError;
30
+ /** Whether an error, or any error in its cause chain, is a RecoveryError. */
31
+ export declare function isRecoveryError(error: unknown): boolean;
@@ -0,0 +1,51 @@
1
+ /** The one error family of durable recovery. A failure of the journal itself (a store that will not open, write or
2
+ * bind, a checkpoint or execution path the driver refuses, a host pause or cancel, an effect whose outcome is unknown
3
+ * and must be reconciled) is a RecoveryError. A host stops a run on one and never hands the run to a fallback: the
4
+ * persistence guarantees rest on that. Every other failure of a workflow is the workflow's own. */
5
+ export class RecoveryError extends Error {
6
+ code;
7
+ transient = false;
8
+ /** The family's failures are typed: a context object marks `code` as the error's kind for a host that reports
9
+ * failures structurally. */
10
+ context = {};
11
+ /** Who issued the host's pause or cancel this failure is, as the host named it. */
12
+ source;
13
+ constructor(message, code = "RECEIPTS_FAILURE", options) {
14
+ super(message, options);
15
+ this.name = "RecoveryError";
16
+ this.code = code;
17
+ if (options?.source)
18
+ this.source = options.source;
19
+ }
20
+ }
21
+ /** The stop a typed failure code names: a run ends by pause or cancel at the site that consumed the command (a session
22
+ * under run control, the recovery driver), each with its own code, and a host reads the stop back from the code. */
23
+ const STOP_CODES = { RUN_PAUSED: "pause", RUN_CANCELLED: "cancel", FROZEN_PAUSED: "pause", FROZEN_CANCELLED: "cancel" };
24
+ /** The failure a session under run control raises when its run was paused or cancelled. */
25
+ export const runStoppedError = (stop, source) => new RecoveryError(`Run ${stop} requested`, stop === "pause" ? "RUN_PAUSED" : "RUN_CANCELLED", { source });
26
+ /** The pause or cancel that stopped a run and who issued it (the user unless the host named another), read from a
27
+ * RecoveryError anywhere in an error's cause chain; null for every other failure. */
28
+ export function runStopOf(error) {
29
+ for (let current = error, depth = 0; current && depth < 16; current = current.cause, depth += 1) {
30
+ if (current instanceof RecoveryError && STOP_CODES[current.code])
31
+ return { stop: STOP_CODES[current.code], code: current.code, source: current.source ?? "user" };
32
+ }
33
+ return null;
34
+ }
35
+ /** A failure raised inside a store or the driver, as a RecoveryError: the original message and code are kept, the
36
+ * original error is its cause. */
37
+ export function asRecoveryError(error) {
38
+ if (error instanceof RecoveryError)
39
+ return error;
40
+ const message = error instanceof Error ? error.message : String(error);
41
+ const code = typeof error?.code === "string" ? error.code : "RECEIPTS_FAILURE";
42
+ return new RecoveryError(message, code, { cause: error });
43
+ }
44
+ /** Whether an error, or any error in its cause chain, is a RecoveryError. */
45
+ export function isRecoveryError(error) {
46
+ for (let current = error, depth = 0; current && depth < 16; current = current.cause, depth += 1) {
47
+ if (current instanceof RecoveryError)
48
+ return true;
49
+ }
50
+ return false;
51
+ }
@@ -0,0 +1,53 @@
1
+ import type { Workflow, WorkflowNode } from "../workflow.js";
2
+ /** A path's segments, unescaped, with the offset in the path where each segment's `/` sits, so a
3
+ * prefix of the interpreter's own string can be sliced. Null when the string is not a path. */
4
+ export declare function pathSegments(path: unknown): Array<{
5
+ segment: string;
6
+ at: number;
7
+ }> | null;
8
+ /** The node `path` names in the document the interpreter ran (a desugared view), or undefined when
9
+ * the path does not resolve. A step of a child workflow resolves inside the child's own root. */
10
+ export declare function nodeAt(workflow: Workflow, path: string): WorkflowNode | undefined;
11
+ /** Every chain `path` sits in, outermost first: the chain's own path and the index of the step on
12
+ * the way to `path`. A resume is answered by a chain's committed frontier when the frontier lies past
13
+ * that index. */
14
+ export declare function enclosingChains(path: string): Array<{
15
+ chain: string;
16
+ index: number;
17
+ }>;
18
+ /** The chain step `path` is, when it is one: its chain's path and its index. */
19
+ export declare function chainStep(path: string): {
20
+ chain: string;
21
+ index: number;
22
+ } | undefined;
23
+ /** Every loop iteration `path` runs inside, outermost first: the loop's path and the iteration. */
24
+ export declare function enclosingIterations(path: string): Array<{
25
+ loop: string;
26
+ index: number;
27
+ }>;
28
+ /** The loop iteration a commit at `path` completes, if any: `path` is the iteration's body, or the
29
+ * last committing step of a body that is a chain (a chain never commits itself, so its last step,
30
+ * descending through nested chains, is where the body ends). */
31
+ export declare function completedIteration(workflow: Workflow, path: string): {
32
+ loop: string;
33
+ index: number;
34
+ } | undefined;
35
+ /** The innermost map item `path` lies in, when it lies in one: the item's own path (`<map>/items/<i>`, a prefix of
36
+ * `path` without the item's `/body`), its map's path and its index. A map's own path lies in the item that holds the
37
+ * map, not in its own items. */
38
+ export declare function mapItemOf(path: string): {
39
+ item: string;
40
+ map: string;
41
+ index: number;
42
+ } | undefined;
43
+ /** Whether `inner` is `outer` or lies inside it, compared segment by segment. */
44
+ export declare function isWithin(inner: string, outer: string): boolean;
45
+ /** The top-level step whose completion `path`'s commit is, or undefined. A top-level step commits at
46
+ * its own path; a chain is never committed by the interpreter, so a top-level nested chain completes
47
+ * at a path that runs only through chain steps and is the last step of every nested chain below the
48
+ * document's root chain. A root that is not a chain completes at the root. Read from the path and
49
+ * the document, never built. */
50
+ export declare function topLevelCompletion(workflow: Workflow, path: string): number | undefined;
51
+ /** The nodes directly inside `node`: a chain's steps, a parallel's branches, a map's or a loop's
52
+ * body, a route's branch bodies, a child workflow's root. */
53
+ export declare function childrenOf(node: WorkflowNode): WorkflowNode[];
@@ -0,0 +1,167 @@
1
+ /** A path's segments, unescaped, with the offset in the path where each segment's `/` sits, so a
2
+ * prefix of the interpreter's own string can be sliced. Null when the string is not a path. */
3
+ export function pathSegments(path) {
4
+ if (typeof path !== "string" || !path.startsWith("/root") || (path.length > 5 && path[5] !== "/"))
5
+ return null;
6
+ const out = [];
7
+ let at = 0;
8
+ for (const raw of path.slice(1).split("/")) {
9
+ if (!raw)
10
+ return null;
11
+ out.push({ segment: raw.replace(/~1/g, "/").replace(/~0/g, "~"), at });
12
+ at += raw.length + 1;
13
+ }
14
+ return out;
15
+ }
16
+ /** The prefix of `path` that ends before its segment `index` (the path of an ancestor). */
17
+ const prefix = (path, segments, index) => path.slice(0, segments[index].at);
18
+ const INDEX = /^(0|[1-9][0-9]*)$/;
19
+ /** The node `path` names in the document the interpreter ran (a desugared view), or undefined when
20
+ * the path does not resolve. A step of a child workflow resolves inside the child's own root. */
21
+ export function nodeAt(workflow, path) {
22
+ const segments = pathSegments(path)?.map(s => s.segment);
23
+ if (!segments || segments[0] !== "root")
24
+ return undefined;
25
+ let node = workflow.root;
26
+ for (let i = 1; node && i < segments.length;) {
27
+ const [a, b, c] = segments.slice(i, i + 3);
28
+ if (a === "steps" && node.node === "chain" && INDEX.test(b ?? "")) {
29
+ node = node.steps[Number(b)];
30
+ i += 2;
31
+ }
32
+ else if (a === "items" && node.node === "map" && INDEX.test(b ?? "") && c === "body") {
33
+ node = node.body;
34
+ i += 3;
35
+ }
36
+ else if (a === "iterations" && node.node === "loop" && INDEX.test(b ?? "") && c === "body") {
37
+ node = node.body;
38
+ i += 3;
39
+ }
40
+ else if (a === "branches" && node.node === "parallel" && INDEX.test(b ?? "")) {
41
+ node = node.branches[Number(b)];
42
+ i += 2;
43
+ }
44
+ else if (a === "branches" && node.node === "route" && typeof b === "string" && c === "body" && Object.hasOwn(node.branches, b)) {
45
+ node = node.branches[b]?.body;
46
+ i += 3;
47
+ }
48
+ else if (a === "workflow" && node.node === "workflow" && b === "root") {
49
+ node = node.workflow.root;
50
+ i += 2;
51
+ }
52
+ else
53
+ return undefined;
54
+ }
55
+ return node;
56
+ }
57
+ /** Every chain `path` sits in, outermost first: the chain's own path and the index of the step on
58
+ * the way to `path`. A resume is answered by a chain's committed frontier when the frontier lies past
59
+ * that index. */
60
+ export function enclosingChains(path) {
61
+ const segments = pathSegments(path);
62
+ if (!segments)
63
+ return [];
64
+ const out = [];
65
+ for (let i = 1; i + 1 < segments.length; i += 1) {
66
+ if (segments[i].segment === "steps" && INDEX.test(segments[i + 1].segment))
67
+ out.push({ chain: prefix(path, segments, i), index: Number(segments[i + 1].segment) });
68
+ }
69
+ return out;
70
+ }
71
+ /** The chain step `path` is, when it is one: its chain's path and its index. */
72
+ export function chainStep(path) {
73
+ const segments = pathSegments(path);
74
+ if (!segments || segments.length < 3)
75
+ return undefined;
76
+ const [steps, index] = segments.slice(-2);
77
+ return steps.segment === "steps" && INDEX.test(index.segment) ? { chain: prefix(path, segments, segments.length - 2), index: Number(index.segment) } : undefined;
78
+ }
79
+ /** Every loop iteration `path` runs inside, outermost first: the loop's path and the iteration. */
80
+ export function enclosingIterations(path) {
81
+ const segments = pathSegments(path);
82
+ if (!segments)
83
+ return [];
84
+ const out = [];
85
+ for (let i = 1; i + 2 < segments.length; i += 1) {
86
+ if (segments[i].segment === "iterations" && INDEX.test(segments[i + 1].segment) && segments[i + 2].segment === "body")
87
+ out.push({ loop: prefix(path, segments, i), index: Number(segments[i + 1].segment) });
88
+ }
89
+ return out;
90
+ }
91
+ /** The loop iteration a commit at `path` completes, if any: `path` is the iteration's body, or the
92
+ * last committing step of a body that is a chain (a chain never commits itself, so its last step,
93
+ * descending through nested chains, is where the body ends). */
94
+ export function completedIteration(workflow, path) {
95
+ const segments = pathSegments(path);
96
+ const innermost = enclosingIterations(path).at(-1);
97
+ if (!segments || !innermost)
98
+ return undefined;
99
+ // The body's own path ends three segments past the loop's: iterations/<i>/body.
100
+ const loopDepth = pathSegments(innermost.loop).length;
101
+ let depth = loopDepth + 3;
102
+ let node = nodeAt(workflow, path.slice(0, segments[depth]?.at ?? path.length));
103
+ while (depth < segments.length) {
104
+ if (node?.node !== "chain" || segments[depth].segment !== "steps")
105
+ return undefined;
106
+ const steps = node.steps;
107
+ if (Number(segments[depth + 1]?.segment) !== steps.length - 1)
108
+ return undefined;
109
+ node = steps[steps.length - 1];
110
+ depth += 2;
111
+ }
112
+ return node && node.node !== "chain" ? innermost : undefined;
113
+ }
114
+ /** The innermost map item `path` lies in, when it lies in one: the item's own path (`<map>/items/<i>`, a prefix of
115
+ * `path` without the item's `/body`), its map's path and its index. A map's own path lies in the item that holds the
116
+ * map, not in its own items. */
117
+ export function mapItemOf(path) {
118
+ const segments = pathSegments(path);
119
+ if (!segments)
120
+ return undefined;
121
+ for (let i = segments.length - 3; i >= 1; i -= 1) {
122
+ if (segments[i].segment === "items" && INDEX.test(segments[i + 1].segment) && segments[i + 2].segment === "body") {
123
+ return { item: prefix(path, segments, i + 2), map: prefix(path, segments, i), index: Number(segments[i + 1].segment) };
124
+ }
125
+ }
126
+ return undefined;
127
+ }
128
+ /** Whether `inner` is `outer` or lies inside it, compared segment by segment. */
129
+ export function isWithin(inner, outer) {
130
+ const a = pathSegments(inner);
131
+ const b = pathSegments(outer);
132
+ return Boolean(a && b && b.length <= a.length && b.every((s, i) => s.segment === a[i].segment));
133
+ }
134
+ /** The top-level step whose completion `path`'s commit is, or undefined. A top-level step commits at
135
+ * its own path; a chain is never committed by the interpreter, so a top-level nested chain completes
136
+ * at a path that runs only through chain steps and is the last step of every nested chain below the
137
+ * document's root chain. A root that is not a chain completes at the root. Read from the path and
138
+ * the document, never built. */
139
+ export function topLevelCompletion(workflow, path) {
140
+ const segments = pathSegments(path);
141
+ if (!segments)
142
+ return undefined;
143
+ if (segments.length === 1)
144
+ return workflow.root.node === "chain" ? undefined : 0;
145
+ const chains = enclosingChains(path);
146
+ // Every segment after the root is a chain step's pair: the path runs through chains only.
147
+ if (chains.length * 2 + 1 !== segments.length || workflow.root.node !== "chain")
148
+ return undefined;
149
+ const nested = chains.slice(1).every(({ chain, index }) => {
150
+ const node = nodeAt(workflow, chain);
151
+ return node?.node === "chain" && index === node.steps.length - 1;
152
+ });
153
+ return nested ? chains[0].index : undefined;
154
+ }
155
+ /** The nodes directly inside `node`: a chain's steps, a parallel's branches, a map's or a loop's
156
+ * body, a route's branch bodies, a child workflow's root. */
157
+ export function childrenOf(node) {
158
+ switch (node.node) {
159
+ case "chain": return node.steps ?? [];
160
+ case "parallel": return node.branches ?? [];
161
+ case "map":
162
+ case "loop": return [node.body];
163
+ case "route": return Object.values(node.branches ?? {}).map(branch => branch.body);
164
+ case "workflow": return [node.workflow.root];
165
+ default: return [];
166
+ }
167
+ }
@@ -0,0 +1,7 @@
1
+ import type { RecoveryStore } from "./store.js";
2
+ /** A store that keeps one run's journal as one JSON file in `directory`, for a host on one machine. Each commit
3
+ * replaces the file through a synced temporary file and a rename, so a reader sees the journal before the commit or
4
+ * after it. The owner is an entry in a lock directory, named by its process: an open while that process lives is
5
+ * refused, and a dead owner's journal is taken over. A commit from an owner that lost the journal all the same is
6
+ * refused by its generation. */
7
+ export declare function fileStore(directory: string): RecoveryStore;
@@ -0,0 +1,131 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { RecoveryError } from "./errors.js";
5
+ import { openJournal } from "./journal.js";
6
+ const JOURNAL_FILE = "journal.json";
7
+ const OWNER_LOCK = "owner.lock";
8
+ const alive = (pid) => {
9
+ if (!Number.isInteger(pid) || pid <= 0)
10
+ return false;
11
+ try {
12
+ process.kill(pid, 0);
13
+ return true;
14
+ }
15
+ catch (error) {
16
+ return error.code === "EPERM";
17
+ }
18
+ };
19
+ /** Bytes on disk before the call returns: the file, then the directory entry that names it. */
20
+ function syncDirectory(directory) {
21
+ const fd = fs.openSync(directory, "r");
22
+ try {
23
+ fs.fsyncSync(fd);
24
+ }
25
+ finally {
26
+ fs.closeSync(fd);
27
+ }
28
+ }
29
+ /** A store that keeps one run's journal as one JSON file in `directory`, for a host on one machine. Each commit
30
+ * replaces the file through a synced temporary file and a rename, so a reader sees the journal before the commit or
31
+ * after it. The owner is an entry in a lock directory, named by its process: an open while that process lives is
32
+ * refused, and a dead owner's journal is taken over. A commit from an owner that lost the journal all the same is
33
+ * refused by its generation. */
34
+ export function fileStore(directory) {
35
+ const journal = path.join(directory, JOURNAL_FILE);
36
+ const lock = path.join(directory, OWNER_LOCK);
37
+ const acquire = async () => {
38
+ fs.mkdirSync(directory, { recursive: true });
39
+ const token = randomUUID();
40
+ const mine = `${token}.${process.pid}`;
41
+ const release = async () => {
42
+ fs.rmSync(path.join(lock, mine), { force: true });
43
+ try {
44
+ fs.rmdirSync(lock);
45
+ }
46
+ catch { /* Another owner's lock by now, or already gone. */ }
47
+ };
48
+ // The lock appears whole: a directory that already holds this opener's entry is renamed into place, which fails
49
+ // while a lock holds an entry.
50
+ const staged = `${lock}.${token}`;
51
+ fs.mkdirSync(staged);
52
+ fs.writeFileSync(path.join(staged, mine), "");
53
+ try {
54
+ for (let attempt = 0; attempt < 16; attempt += 1) {
55
+ try {
56
+ fs.renameSync(staged, lock);
57
+ return release;
58
+ }
59
+ catch (error) {
60
+ if (!["ENOTEMPTY", "EEXIST", "EPERM", "EACCES"].includes(error.code ?? ""))
61
+ throw error;
62
+ }
63
+ let entries;
64
+ try {
65
+ entries = fs.readdirSync(lock);
66
+ }
67
+ catch (error) {
68
+ if (error.code === "ENOENT")
69
+ continue;
70
+ throw error;
71
+ }
72
+ // An owner that let go leaves the directory empty for a moment: it is no lock.
73
+ if (entries.length === 0) {
74
+ try {
75
+ fs.rmdirSync(lock);
76
+ }
77
+ catch { /* Filled or removed meanwhile. */ }
78
+ continue;
79
+ }
80
+ if (entries.some((entry) => alive(Number(entry.slice(entry.lastIndexOf(".") + 1)))))
81
+ break;
82
+ // The owner is dead. Its entry is renamed to this opener's, which one opener only can do, and which can never
83
+ // move a live owner's entry: that one has another name.
84
+ try {
85
+ fs.renameSync(path.join(lock, entries[0]), path.join(lock, mine));
86
+ }
87
+ catch (error) {
88
+ if (error.code === "ENOENT")
89
+ continue;
90
+ throw error;
91
+ }
92
+ fs.rmSync(staged, { recursive: true, force: true });
93
+ return release;
94
+ }
95
+ }
96
+ catch (error) {
97
+ fs.rmSync(staged, { recursive: true, force: true });
98
+ throw error;
99
+ }
100
+ fs.rmSync(staged, { recursive: true, force: true });
101
+ throw new RecoveryError("Run already has a live owner");
102
+ };
103
+ return {
104
+ open: (bound) => openJournal({
105
+ acquire,
106
+ async read() {
107
+ try {
108
+ return JSON.parse(fs.readFileSync(journal, "utf8"));
109
+ }
110
+ catch (error) {
111
+ if (error.code === "ENOENT")
112
+ return undefined;
113
+ throw error;
114
+ }
115
+ },
116
+ async write(record) {
117
+ const temporary = `${journal}.${process.pid}.tmp`;
118
+ const fd = fs.openSync(temporary, "w");
119
+ try {
120
+ fs.writeSync(fd, JSON.stringify(record));
121
+ fs.fsyncSync(fd);
122
+ }
123
+ finally {
124
+ fs.closeSync(fd);
125
+ }
126
+ fs.renameSync(temporary, journal);
127
+ syncDirectory(directory);
128
+ },
129
+ }, bound),
130
+ };
131
+ }