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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +46 -16
  2. package/dist/author.d.ts +96 -0
  3. package/dist/author.js +320 -0
  4. package/dist/authoring.js +1 -1
  5. package/dist/cli.js +8 -3
  6. package/dist/code-exec.d.ts +6 -0
  7. package/dist/code-exec.js +126 -0
  8. package/dist/decision-receipts.d.ts +98 -0
  9. package/dist/decision-receipts.js +51 -0
  10. package/dist/dry-run.d.ts +14 -1
  11. package/dist/dry-run.js +39 -13
  12. package/dist/graph.d.ts +83 -0
  13. package/dist/graph.js +231 -0
  14. package/dist/index.d.ts +12 -4
  15. package/dist/index.js +6 -2
  16. package/dist/inspection.js +2 -2
  17. package/dist/job.d.ts +14 -0
  18. package/dist/job.js +5 -0
  19. package/dist/long-timer.d.ts +7 -0
  20. package/dist/long-timer.js +22 -0
  21. package/dist/observer-snapshot.d.ts +3 -0
  22. package/dist/observer-snapshot.js +46 -0
  23. package/dist/predicates.d.ts +4 -0
  24. package/dist/predicates.js +19 -2
  25. package/dist/recovery/binding.d.ts +10 -0
  26. package/dist/recovery/binding.js +43 -0
  27. package/dist/recovery/call-key.d.ts +13 -0
  28. package/dist/recovery/call-key.js +24 -0
  29. package/dist/recovery/canonical-hash.d.ts +7 -0
  30. package/dist/recovery/canonical-hash.js +22 -0
  31. package/dist/recovery/driver.d.ts +208 -0
  32. package/dist/recovery/driver.js +1222 -0
  33. package/dist/recovery/effect-failure.d.ts +34 -0
  34. package/dist/recovery/effect-failure.js +62 -0
  35. package/dist/recovery/errors.d.ts +31 -0
  36. package/dist/recovery/errors.js +51 -0
  37. package/dist/recovery/execution-path.d.ts +53 -0
  38. package/dist/recovery/execution-path.js +167 -0
  39. package/dist/recovery/file-store.d.ts +7 -0
  40. package/dist/recovery/file-store.js +131 -0
  41. package/dist/recovery/frozen-snapshot.d.ts +244 -0
  42. package/dist/recovery/frozen-snapshot.js +171 -0
  43. package/dist/recovery/handoff-block.d.ts +36 -0
  44. package/dist/recovery/handoff-block.js +148 -0
  45. package/dist/recovery/handoff-digest.d.ts +58 -0
  46. package/dist/recovery/handoff-digest.js +195 -0
  47. package/dist/recovery/handoff-files.d.ts +54 -0
  48. package/dist/recovery/handoff-files.js +162 -0
  49. package/dist/recovery/handoff-receipts.d.ts +42 -0
  50. package/dist/recovery/handoff-receipts.js +53 -0
  51. package/dist/recovery/handoff-redact.d.ts +12 -0
  52. package/dist/recovery/handoff-redact.js +44 -0
  53. package/dist/recovery/handoff.d.ts +44 -0
  54. package/dist/recovery/handoff.js +46 -0
  55. package/dist/recovery/index.d.ts +18 -0
  56. package/dist/recovery/index.js +16 -0
  57. package/dist/recovery/item-state.d.ts +48 -0
  58. package/dist/recovery/item-state.js +89 -0
  59. package/dist/recovery/journal.d.ts +28 -0
  60. package/dist/recovery/journal.js +139 -0
  61. package/dist/recovery/memory-store.d.ts +4 -0
  62. package/dist/recovery/memory-store.js +20 -0
  63. package/dist/recovery/store.d.ts +105 -0
  64. package/dist/recovery/store.js +6 -0
  65. package/dist/recovery/testing/conformance.d.ts +4 -0
  66. package/dist/recovery/testing/conformance.js +268 -0
  67. package/dist/recovery/testing/crash-points.d.ts +18 -0
  68. package/dist/recovery/testing/crash-points.js +43 -0
  69. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  70. package/dist/recovery/testing/crash-sweep.js +146 -0
  71. package/dist/recovery/testing/index.d.ts +3 -0
  72. package/dist/recovery/testing/index.js +4 -0
  73. package/dist/recovery/testing/preload.d.ts +1 -0
  74. package/dist/recovery/testing/preload.js +3 -0
  75. package/dist/recovery/transport-facts.d.ts +23 -0
  76. package/dist/recovery/transport-facts.js +46 -0
  77. package/dist/recovery/with-recovery.d.ts +44 -0
  78. package/dist/recovery/with-recovery.js +87 -0
  79. package/dist/system-one.d.ts +17 -1
  80. package/dist/system-one.js +62 -5
  81. package/dist/vocabulary.d.ts +42 -0
  82. package/dist/vocabulary.js +74 -0
  83. package/dist/workflow-shape.d.ts +7 -0
  84. package/dist/workflow-shape.js +85 -62
  85. package/dist/workflow.d.ts +187 -16
  86. package/dist/workflow.js +967 -324
  87. package/package.json +18 -2
  88. package/schema/workflow.schema.json +251 -15
  89. package/skills/author/SKILL.md +122 -0
  90. package/skills/author/examples/evidence-gate.input.json +6 -0
  91. package/skills/author/examples/evidence-gate.json +125 -0
  92. package/skills/author/examples/read-file.input.json +1 -0
  93. package/skills/author/examples/read-file.json +44 -0
  94. package/skills/author/examples/read-source-decision.input.json +4 -0
  95. package/skills/author/examples/read-source-decision.json +37 -0
  96. package/skills/author/examples/release-note.txt +10 -0
  97. package/skills/author/examples/review-release-notes.input.json +6 -0
  98. package/skills/author/examples/review-release-notes.json +123 -0
  99. package/skills/author/references/jev-decisions.md +125 -0
  100. package/skills/author/references/language.md +118 -0
  101. package/skills/author/references/sdk-authoring.md +11 -0
  102. package/skills/author/references/workflow-format.md +137 -0
@@ -0,0 +1,44 @@
1
+ import { type InheritedSession, type TranscriptMessage } from "./handoff-digest.js";
2
+ import { type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
3
+ import type { RecoveryJournal } from "./store.js";
4
+ /** What a continuation inherits from a run that escalated. The package returns it; the host decides who continues. */
5
+ export type Handoff = {
6
+ /** What happened, the typed state, inputs and spend: bounded and redacted. */
7
+ block: string;
8
+ /** Each LLM step's transcript, each paid effect and result, files and evidence; null when it could not be built. */
9
+ digest: string | null;
10
+ /** The attempt written as files under the workspace, relative paths, sorted. */
11
+ files: string[];
12
+ /** Completed tool effects, keyed by tool and argument hash. */
13
+ receipts: InheritedReceipt[];
14
+ /** Effects the continuation must not send again. */
15
+ unknown: InheritedUnknown[];
16
+ /** Why the attempt files could not be written, when they could not: the block then points at files that are not there. */
17
+ filesError?: string;
18
+ /** Why the digest is null, when it is. */
19
+ digestError?: string;
20
+ };
21
+ export type HandoffOptions = {
22
+ /** The run's workspace: the attempt's files are written under it. */
23
+ cwd: string;
24
+ /** The run's identity as its step sessions are named (`<run>:<label>:step:...`). */
25
+ runId: string;
26
+ /** The input the run started from, as the dispatch carried it. */
27
+ input?: unknown;
28
+ /** Where the attempt's report was moved to, when the host set one aside. */
29
+ reportPath?: string | null;
30
+ /** The host's sizes for the continuation. */
31
+ budget?: {
32
+ max_tool_calls?: number;
33
+ max_seconds?: number;
34
+ } | null;
35
+ /** The run's step sessions with their spend, from the host's own record of them. */
36
+ sessions?: readonly InheritedSession[];
37
+ /** A step's transcript by its session id, or null when there is none. */
38
+ transcriptOf?: (sessionId: string) => readonly TranscriptMessage[] | null;
39
+ };
40
+ /** The one place a handoff is built: the escalation row and effects of an open journal, rendered as the continuation's
41
+ * first turn. The row must be one the driver committed. Deterministic for a journal and a workspace. */
42
+ export declare function buildHandoff(journal: Pick<RecoveryJournal, "state" | "effects">, options: HandoffOptions): Promise<Handoff>;
43
+ /** The continuation's first turn: the escalation block, then the digest. Deterministic from its inputs. */
44
+ export declare const handoffFirstTurn: (handoff: Pick<Handoff, "block" | "digest">) => string;
@@ -0,0 +1,46 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { escalationContextBlock } from "./handoff-block.js";
4
+ import { inheritedJobDigest } from "./handoff-digest.js";
5
+ import { HANDOFF_FILES_DIR, inputProvenance, writeHandoffFiles } from "./handoff-files.js";
6
+ import { inheritableReceipts, inheritableUnknowns } from "./handoff-receipts.js";
7
+ /** The one place a handoff is built: the escalation row and effects of an open journal, rendered as the continuation's
8
+ * first turn. The row must be one the driver committed. Deterministic for a journal and a workspace. */
9
+ export async function buildHandoff(journal, options) {
10
+ const snapshot = journal.state;
11
+ const row = snapshot?.escalation;
12
+ if (!row)
13
+ throw new Error("A handoff is built from an escalation the driver committed");
14
+ const effects = journal.effects();
15
+ const routes = snapshot?.pin?.routes && typeof snapshot.pin.routes === "object" && !Array.isArray(snapshot.pin.routes) ? { ...snapshot.pin.routes } : {};
16
+ let files = [];
17
+ let effectFiles = {};
18
+ let filesError;
19
+ try {
20
+ ({ files, effectFiles } = await writeHandoffFiles(options.cwd, row, { effects, routes }, options.input));
21
+ }
22
+ catch (error) {
23
+ filesError = String(error?.message ?? error);
24
+ }
25
+ const evidenceDir = path.join(options.cwd, "evidence");
26
+ const gathered = await fs.readdir(evidenceDir).then((names) => names.some((name) => name !== path.basename(HANDOFF_FILES_DIR)), () => false);
27
+ const evidence = gathered ? (row.evidence_dir ?? evidenceDir) : null;
28
+ const block = escalationContextBlock({ ...row, evidence_dir: evidence, report_path: options.reportPath ?? null, files,
29
+ inputs: options.input === undefined ? [] : inputProvenance(options.input), budget: options.budget ?? null });
30
+ let digest = null;
31
+ let digestError;
32
+ try {
33
+ digest = inheritedJobDigest({
34
+ runId: options.runId, transcriptOf: options.transcriptOf ?? (() => null), cwd: options.cwd, evidenceDir: evidence,
35
+ sessions: [...(options.sessions ?? [])],
36
+ effects: effects.map((e) => ({ id: e.id, name: e.name, status: e.status, ...(e.status === "completed" ? { result: e.result } : {}) })),
37
+ files: snapshot?.files && typeof snapshot.files === "object" ? snapshot.files : {}, effectFiles,
38
+ });
39
+ }
40
+ catch (error) {
41
+ digestError = `digest unavailable: ${String(error?.message ?? error)}`;
42
+ }
43
+ return { block, digest, files, receipts: inheritableReceipts(effects), unknown: inheritableUnknowns(effects), ...(filesError ? { filesError } : {}), ...(digestError && digest === null ? { digestError } : {}) };
44
+ }
45
+ /** The continuation's first turn: the escalation block, then the digest. Deterministic from its inputs. */
46
+ export const handoffFirstTurn = (handoff) => [handoff.block, handoff.digest].filter(Boolean).join("\n\n");
@@ -0,0 +1,18 @@
1
+ export type { RecoveryBinding, RecoveryEffect, RecoveryIntent, RecoveryItem, RecoveryJournal, RecoveryNote, RecoveryParts, RecoveryStore } from "./store.js";
2
+ export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles, type RecoveryEffectParams, type RecoveryFiles, type RecoveryOptions, type RecoveryStop } from "./driver.js";
3
+ export { withRecovery, type RecoveryAdapters, type RecoveryDriver, type RecoveryNodeParams, type RecoveryStep, type WithRecoveryOptions } from "./with-recovery.js";
4
+ export { memoryStore } from "./memory-store.js";
5
+ export { fileStore } from "./file-store.js";
6
+ export { openJournal, type JournalBackend, type JournalRecord } from "./journal.js";
7
+ export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
8
+ export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
9
+ export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
10
+ export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
11
+ export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type FrozenSnapshotV4, type ItemRecord, type MapEntry, type StateDelta, type Sha256, type PartialSlot, type PathFrame, type RouteDecision, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
12
+ export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
13
+ export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
14
+ export { effectRetryClass, transportFactOf, type TransportFact } from "./transport-facts.js";
15
+ export { buildHandoff, handoffFirstTurn, type Handoff, type HandoffOptions } from "./handoff.js";
16
+ export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
17
+ export { inputProvenance, judgedRecords, type InputProvenance } from "./handoff-files.js";
18
+ export { type InheritedSession, type InheritedEffect, type TranscriptMessage } from "./handoff-digest.js";
@@ -0,0 +1,16 @@
1
+ export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles } from "./driver.js";
2
+ export { withRecovery } from "./with-recovery.js";
3
+ export { memoryStore } from "./memory-store.js";
4
+ export { fileStore } from "./file-store.js";
5
+ export { openJournal } from "./journal.js";
6
+ export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
7
+ export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
8
+ export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
9
+ export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
10
+ export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
11
+ export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
12
+ export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
13
+ export { effectRetryClass, transportFactOf } from "./transport-facts.js";
14
+ export { buildHandoff, handoffFirstTurn } from "./handoff.js";
15
+ export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure } from "./handoff-receipts.js";
16
+ export { inputProvenance, judgedRecords } from "./handoff-files.js";
@@ -0,0 +1,48 @@
1
+ type State = Record<string, unknown>;
2
+ /** A committed state inside a map item, against its map's base (the state the map started from): the keys it sets
3
+ * (new, or holding another value than the base's), the base's keys it lacks, and the digest of the whole state, which
4
+ * a rebuild must reach. */
5
+ export type StateDelta = {
6
+ set: State;
7
+ unset: string[];
8
+ sha256: string;
9
+ };
10
+ /** The hex SHA-256 of a text's UTF-8 bytes, synchronous. */
11
+ export type Sha256 = (text: string) => string;
12
+ /** The JSON a state's digest is taken over: every object's keys sorted. */
13
+ export declare function canonicalJson(value: unknown): string;
14
+ /** `state` against `base`, as a map item keeps it. */
15
+ export declare function stateDelta(base: State, state: State, sha256: string): StateDelta;
16
+ /** The state a delta was taken from, in its own key order: the base's keys first (a map item starts from a copy of its
17
+ * base), then the keys it added. */
18
+ export declare function applyStateDelta(base: State, delta: StateDelta): State;
19
+ /** A map item's state at `path`, rebuilt as the driver rebuilds it: the `agentrun.states` value its `base` names, with
20
+ * the item's `set` and `unset` for that path applied, checked against that path's `sha256`. `item` is an
21
+ * `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256; `sha256` hashes a text's UTF-8 bytes.
22
+ * When the base is missing, or a digest differs, it says why and never guesses. */
23
+ export declare function itemState(item: unknown, states: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>, path: string, { sha256 }: {
24
+ sha256: Sha256;
25
+ }): {
26
+ state: State;
27
+ } | {
28
+ unreadable: string;
29
+ };
30
+ /** A slot of a failed map: `null` for an item that never finished, its result, or why it cannot be read. */
31
+ export type PartialSlot = null | {
32
+ result: unknown;
33
+ } | {
34
+ unreadable: string;
35
+ };
36
+ /** A failed map's finished results, read as the driver reads them: `partial` is the driver state's `pin.partial`. In the
37
+ * keyed layout its `results` is one SHA-256 naming the `agentrun.states` value that lists each slot (null, or the
38
+ * SHA-256 of that item's result); `states` holds `agentrun.states` values by SHA-256, and every digest is checked. A
39
+ * whole-state run's `results` is the list itself. A document that is missing or does not match its digest is
40
+ * unreadable, never guessed: the list as a whole, or one slot. */
41
+ export declare function partialResults(partial: unknown, states: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>, { sha256 }: {
42
+ sha256: Sha256;
43
+ }): {
44
+ slots: PartialSlot[];
45
+ } | {
46
+ unreadable: string;
47
+ };
48
+ export {};
@@ -0,0 +1,89 @@
1
+ // A map item's state in the keyed layout, rebuilt from its record and its base. This module imports nothing, so a
2
+ // reader with no Node (the static viewer inlines it) runs the same rebuild the driver runs; the SHA-256 is the caller's.
3
+ /** The JSON a state's digest is taken over: every object's keys sorted. */
4
+ export function canonicalJson(value) {
5
+ return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item)
6
+ ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
7
+ }
8
+ const sameValue = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
9
+ /** `state` against `base`, as a map item keeps it. */
10
+ export function stateDelta(base, state, sha256) {
11
+ const set = {};
12
+ for (const [key, value] of Object.entries(state))
13
+ if (!Object.hasOwn(base, key) || !sameValue(base[key], value))
14
+ set[key] = value;
15
+ return { set, unset: Object.keys(base).filter((key) => !Object.hasOwn(state, key)), sha256 };
16
+ }
17
+ /** The state a delta was taken from, in its own key order: the base's keys first (a map item starts from a copy of its
18
+ * base), then the keys it added. */
19
+ export function applyStateDelta(base, delta) {
20
+ const unset = new Set(delta.unset);
21
+ const state = {};
22
+ for (const key of Object.keys(base))
23
+ if (!unset.has(key))
24
+ state[key] = Object.hasOwn(delta.set, key) ? delta.set[key] : base[key];
25
+ for (const [key, value] of Object.entries(delta.set))
26
+ if (!Object.hasOwn(base, key))
27
+ state[key] = value;
28
+ return state;
29
+ }
30
+ const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
31
+ /** A map item's state at `path`, rebuilt as the driver rebuilds it: the `agentrun.states` value its `base` names, with
32
+ * the item's `set` and `unset` for that path applied, checked against that path's `sha256`. `item` is an
33
+ * `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256; `sha256` hashes a text's UTF-8 bytes.
34
+ * When the base is missing, or a digest differs, it says why and never guesses. */
35
+ export function itemState(item, states, path, { sha256 }) {
36
+ if (typeof sha256 !== "function")
37
+ throw new TypeError("itemState needs a sha256 function");
38
+ if (!isObject(item) || typeof item.base !== "string" || !isObject(item.frame) || !isObject(item.frame.states))
39
+ return { unreadable: "not a map item's record" };
40
+ const delta = item.frame.states[path];
41
+ if (delta === undefined)
42
+ return { unreadable: `the item keeps no state at ${path}` };
43
+ if (!isObject(delta) || !isObject(delta.set) || !Array.isArray(delta.unset) || !delta.unset.every((key) => typeof key === "string") || typeof delta.sha256 !== "string") {
44
+ return { unreadable: `the state at ${path} is not a delta` };
45
+ }
46
+ const held = states instanceof Map ? states.get(item.base) : Object.hasOwn(states, item.base) ? states[item.base] : undefined;
47
+ if (!isObject(held) || !isObject(held.state))
48
+ return { unreadable: `its base ${item.base} is missing` };
49
+ if (sha256(canonicalJson(held.state)) !== item.base)
50
+ return { unreadable: `its base does not match its SHA-256 ${item.base}` };
51
+ const state = applyStateDelta(held.state, delta);
52
+ if (sha256(canonicalJson(state)) !== delta.sha256)
53
+ return { unreadable: `the state at ${path} does not rebuild to its SHA-256 ${delta.sha256}` };
54
+ return { state };
55
+ }
56
+ /** A failed map's finished results, read as the driver reads them: `partial` is the driver state's `pin.partial`. In the
57
+ * keyed layout its `results` is one SHA-256 naming the `agentrun.states` value that lists each slot (null, or the
58
+ * SHA-256 of that item's result); `states` holds `agentrun.states` values by SHA-256, and every digest is checked. A
59
+ * whole-state run's `results` is the list itself. A document that is missing or does not match its digest is
60
+ * unreadable, never guessed: the list as a whole, or one slot. */
61
+ export function partialResults(partial, states, { sha256 }) {
62
+ if (typeof sha256 !== "function")
63
+ throw new TypeError("partialResults needs a sha256 function");
64
+ if (!isObject(partial) || typeof partial.path !== "string" || typeof partial.as !== "string")
65
+ return { unreadable: "not a failed map's results" };
66
+ if (Array.isArray(partial.results))
67
+ return { slots: partial.results.map((result) => (result === null ? null : { result })) };
68
+ if (typeof partial.results !== "string")
69
+ return { unreadable: "not a failed map's results" };
70
+ const read = (digest) => {
71
+ const held = states instanceof Map ? states.get(digest) : Object.hasOwn(states, digest) ? states[digest] : undefined;
72
+ if (!isObject(held) || !Object.hasOwn(held, "state"))
73
+ return { unreadable: `${digest} is missing` };
74
+ if (sha256(canonicalJson(held.state)) !== digest)
75
+ return { unreadable: `${digest} does not match its SHA-256` };
76
+ return { value: held.state };
77
+ };
78
+ const list = read(partial.results);
79
+ if ("unreadable" in list)
80
+ return { unreadable: `the list of results ${list.unreadable}` };
81
+ if (!Array.isArray(list.value) || !list.value.every((slot) => slot === null || (typeof slot === "string" && /^[a-f0-9]{64}$/.test(slot))))
82
+ return { unreadable: "the list of results is not a list of digests" };
83
+ return { slots: list.value.map((slot) => {
84
+ if (slot === null)
85
+ return null;
86
+ const result = read(slot);
87
+ return "unreadable" in result ? { unreadable: `the result ${result.unreadable}` } : { result: result.value };
88
+ }) };
89
+ }
@@ -0,0 +1,28 @@
1
+ import type { RecoveryBinding, RecoveryEffect, RecoveryItem, RecoveryJournal, RecoveryNote } from "./store.js";
2
+ /** A journal as a backend keeps it: what it is bound to, who owns it, its state, its notes, its effects in admission
3
+ * order, each with the outside calls it made, and the parts written beside the state (map items' records by path,
4
+ * states by digest). */
5
+ export type JournalRecord = {
6
+ binding: string | null;
7
+ inputs: Record<string, string> | null;
8
+ generation: number;
9
+ revision: number;
10
+ state: unknown;
11
+ notes: RecoveryNote[];
12
+ effects: Array<RecoveryEffect & {
13
+ calls?: unknown;
14
+ }>;
15
+ items?: Record<string, RecoveryItem>;
16
+ states?: Record<string, unknown>;
17
+ };
18
+ export type JournalBackend = {
19
+ /** Take the journal for one owner, or throw when it has a live one. Resolves to what lets go of it. */
20
+ acquire(): Promise<() => Promise<void>>;
21
+ /** The record as the last `write` left it, or undefined before the first. The caller may change what it gets. */
22
+ read(): Promise<JournalRecord | undefined>;
23
+ /** Replace the record: whole or not at all, and durable before the promise resolves. */
24
+ write(record: JournalRecord): Promise<void>;
25
+ };
26
+ /** Open the journal a backend keeps and take ownership of it: a journal with a live owner refuses, a binding that
27
+ * differs refuses naming the inputs that moved, and the generation advances. */
28
+ export declare function openJournal(backend: JournalBackend, bound: RecoveryBinding): Promise<RecoveryJournal>;
@@ -0,0 +1,139 @@
1
+ // A journal over a record that a backend keeps whole: ownership, the generation check, the revision counter and the
2
+ // six writes. A backend only takes the journal for one owner, reads the record and replaces it, whole and durably.
3
+ // The memory store and the file store are this journal over two backends.
4
+ import { bindingMismatch } from "./binding.js";
5
+ import { RecoveryError, asRecoveryError } from "./errors.js";
6
+ /** A value as a journal stores it: plain JSON, every number finite. */
7
+ function json(value) {
8
+ return value === undefined ? null : JSON.parse(JSON.stringify(value, (_key, item) => {
9
+ if (typeof item === "bigint" || typeof item === "function" || typeof item === "symbol" || (typeof item === "number" && !Number.isFinite(item))) {
10
+ throw new RecoveryError("A journal holds finite JSON values only");
11
+ }
12
+ return item;
13
+ }));
14
+ }
15
+ const publicEffect = ({ id, name, argsHash, status, session, result, intent, args, calls }) => ({ id, name, argsHash, status, session, result, ...(intent ? { intent: { tool: intent.tool, argsHash: intent.argsHash } } : {}), ...(args !== undefined ? { args } : {}), ...(Array.isArray(calls) ? { calls } : {}) });
16
+ /** Open the journal a backend keeps and take ownership of it: a journal with a live owner refuses, a binding that
17
+ * differs refuses naming the inputs that moved, and the generation advances. */
18
+ export async function openJournal(backend, bound) {
19
+ const release = await backend.acquire();
20
+ let opened;
21
+ let existing;
22
+ try {
23
+ opened = (await backend.read()) ?? { binding: null, inputs: null, generation: 0, revision: 0, state: null, notes: [], effects: [] };
24
+ existing = opened.binding !== null;
25
+ if (existing && opened.binding !== bound.binding)
26
+ throw bindingMismatch(opened.inputs ? JSON.stringify(opened.inputs) : null, bound.inputs);
27
+ if (!existing) {
28
+ opened.binding = bound.binding;
29
+ opened.inputs = bound.inputs ? { ...bound.inputs } : null;
30
+ }
31
+ opened.generation += 1;
32
+ await backend.write(opened);
33
+ }
34
+ catch (error) {
35
+ await release();
36
+ throw asRecoveryError(error);
37
+ }
38
+ const generation = opened.generation;
39
+ const effects = new Map(opened.effects.map((effect) => [effect.id, publicEffect(effect)]));
40
+ const notes = [...opened.notes];
41
+ let revision = opened.revision;
42
+ let closed = false;
43
+ /** Writes run one at a time, in the order they were asked for, each with its checks: two asked for together never
44
+ * both pass a check the first one's commit would fail. A failed write does not stop the next, and one asked for
45
+ * before `close` still lands. */
46
+ let queue = Promise.resolve();
47
+ const inOrder = (write) => {
48
+ if (closed)
49
+ return Promise.reject(new RecoveryError("The journal is closed"));
50
+ const done = queue.then(write).catch((error) => { throw asRecoveryError(error); });
51
+ queue = done.catch(() => undefined);
52
+ return done;
53
+ };
54
+ /** One commit, inside a write: it checks this open still owns the journal, advances the revision, and lets `change`
55
+ * alter the record with that revision, then lays the parts beside it. The record is replaced only when both return. */
56
+ const commit = async (change, parts) => {
57
+ const record = await backend.read();
58
+ if (!record || record.generation !== generation)
59
+ throw new RecoveryError("Run owner generation is not acquired");
60
+ const next = record.revision + 1;
61
+ change(record, next);
62
+ const laid = parts?.(next);
63
+ if (laid?.items)
64
+ record.items = { ...record.items, ...json(laid.items) };
65
+ if (laid?.states) {
66
+ const states = record.states ??= {};
67
+ for (const [sha256, state] of Object.entries(laid.states))
68
+ if (!Object.hasOwn(states, sha256))
69
+ states[sha256] = json(state);
70
+ }
71
+ record.revision = next;
72
+ await backend.write(record);
73
+ revision = next;
74
+ return next;
75
+ };
76
+ const stored = (record, id) => record.effects.find((effect) => effect.id === id);
77
+ return {
78
+ existing, generation, state: json(opened.state),
79
+ get revision() { return revision; },
80
+ effects: () => [...effects.values()],
81
+ effect: (id) => effects.get(id),
82
+ notes: () => [...notes],
83
+ save: (state, note, parts) => inOrder(async () => {
84
+ let entry;
85
+ const committed = await commit((record, next) => {
86
+ record.state = json(typeof state === "function" ? state(next) : state);
87
+ if (note) {
88
+ entry = { revision: next, kind: note.kind, detail: json(note.detail), at: new Date().toISOString() };
89
+ record.notes.push(entry);
90
+ }
91
+ }, parts);
92
+ if (entry)
93
+ notes.push(entry);
94
+ return committed;
95
+ }),
96
+ note: (kind, detail) => inOrder(async () => {
97
+ const entry = { kind, detail: json(detail), at: new Date().toISOString() };
98
+ const committed = await commit((record, next) => { record.notes.push({ revision: next, ...entry }); });
99
+ notes.push({ revision: committed, ...entry });
100
+ return committed;
101
+ }),
102
+ // A record kept whole lists every effect itself, an owned one too.
103
+ admit: (id, name, argsHash, state, session = null, intent, args, parts) => inOrder(async () => {
104
+ const known = effects.get(id);
105
+ if (known)
106
+ return known;
107
+ const effect = { id, name, argsHash, status: "unknown", session, result: null, ...(intent ? { intent: json(intent) } : {}), ...(args !== undefined ? { args: json(args) } : {}) };
108
+ await commit((record) => { record.effects.push({ ...effect }); record.state = json(state); }, parts);
109
+ effects.set(id, effect);
110
+ return "new";
111
+ }),
112
+ complete: (id, result, state = opened.state, parts) => inOrder(async () => {
113
+ const known = effects.get(id);
114
+ if (!known)
115
+ throw new RecoveryError(`Effect ${id} completes without an admission`);
116
+ if (known.status === "completed")
117
+ throw new RecoveryError(`Effect ${id} completes once`);
118
+ const value = json(result);
119
+ await commit((record) => { Object.assign(stored(record, id), { status: "completed", result: value }); record.state = json(state); }, parts);
120
+ effects.set(id, { ...known, status: "completed", result: value });
121
+ }),
122
+ called: (id, calls) => inOrder(async () => {
123
+ if (!effects.has(id))
124
+ throw new RecoveryError(`Effect ${id} records calls without an admission`);
125
+ const value = json(calls);
126
+ await commit((record) => { stored(record, id).calls = value; });
127
+ effects.set(id, { ...effects.get(id), ...(Array.isArray(value) ? { calls: value } : {}) });
128
+ }),
129
+ async close() {
130
+ if (closed)
131
+ return;
132
+ closed = true;
133
+ await queue;
134
+ await release();
135
+ },
136
+ items: async (paths) => { const record = await backend.read(); return paths.map((path) => (record?.items && Object.hasOwn(record.items, path) ? json(record.items[path]) : undefined)); },
137
+ stateOf: async (sha256) => { const record = await backend.read(); return record?.states && Object.hasOwn(record.states, sha256) ? json(record.states[sha256]) : undefined; },
138
+ };
139
+ }
@@ -0,0 +1,4 @@
1
+ import type { RecoveryStore } from "./store.js";
2
+ /** A store that keeps one run's journal in this process: for tests, and for a host that wants the driver's rules
3
+ * within one process and no resume after it. */
4
+ export declare function memoryStore(): RecoveryStore;
@@ -0,0 +1,20 @@
1
+ import { RecoveryError } from "./errors.js";
2
+ import { openJournal } from "./journal.js";
3
+ /** A store that keeps one run's journal in this process: for tests, and for a host that wants the driver's rules
4
+ * within one process and no resume after it. */
5
+ export function memoryStore() {
6
+ let record;
7
+ let owned = false;
8
+ return {
9
+ open: (bound) => openJournal({
10
+ async acquire() {
11
+ if (owned)
12
+ throw new RecoveryError("Run already has a live owner");
13
+ owned = true;
14
+ return async () => { owned = false; };
15
+ },
16
+ read: async () => record && structuredClone(record),
17
+ write: async (next) => { record = structuredClone(next); },
18
+ }, bound),
19
+ };
20
+ }
@@ -0,0 +1,105 @@
1
+ /** What a journal is bound to: one digest over everything that must not change between two opens of the same run, and
2
+ * the digest of each input it covers, by name, so that a refused open names the inputs that moved. */
3
+ export type RecoveryBinding = {
4
+ binding: string;
5
+ inputs?: Record<string, string>;
6
+ };
7
+ /** A decision recorded beside the state, with the revision of the commit that wrote it. `layout` says once per open
8
+ * that the driver keeps the whole state in one record although the host asked for the keyed layout, and why. */
9
+ export type RecoveryNote = {
10
+ revision: number;
11
+ kind: "escalation" | "handoff" | "inherited" | "layout";
12
+ detail: unknown;
13
+ at: string;
14
+ };
15
+ /** A map item's record, as a store keeps it beside the state: plain JSON the driver writes and reads back. The store
16
+ * reads one field of it, `effects`: the ids of the effects admitted with this item as their owner. */
17
+ export type RecoveryItem = {
18
+ effects: string[];
19
+ [field: string]: unknown;
20
+ };
21
+ /** What a write keeps beside the state, in the same commit: map items' records by item path, each replacing the one
22
+ * before it whole, and states by their digest (`canonicalHash`), each written once and never changed. Computed with
23
+ * the commit's revision, after the state. */
24
+ export type RecoveryParts = {
25
+ items?: Record<string, RecoveryItem>;
26
+ states?: Record<string, unknown>;
27
+ };
28
+ /** The external call an effect stands for: the tool it calls and the hash of the arguments it calls it with
29
+ * (`canonicalHash` of the arguments). A continuation's own call is keyed the same way, so a call that repeats an
30
+ * effect is known for one whatever the effect's status. */
31
+ export type RecoveryIntent = {
32
+ tool: string;
33
+ argsHash: string;
34
+ };
35
+ /** An effect as the journal holds it. `unknown` is admitted and never completed: nobody knows whether it happened, and
36
+ * it is never dispatched again. `session` names the identity it was admitted under, or is null. `intent` names the
37
+ * external call it was admitted for, when it makes one; an effect admitted without one has no `intent` key. */
38
+ export type RecoveryEffect = {
39
+ id: string;
40
+ name: string;
41
+ argsHash: string;
42
+ status: "unknown" | "completed";
43
+ session: string | null;
44
+ result: unknown;
45
+ intent?: RecoveryIntent;
46
+ args?: unknown;
47
+ calls?: unknown[];
48
+ };
49
+ /** One run's journal, held by the driver that opened it. Every write is one commit: it lands whole or not at all, it is
50
+ * durable before its promise resolves, it is refused once a later open has taken the journal, and it advances the
51
+ * revision by one. Values are stored as plain JSON with finite numbers. */
52
+ export type RecoveryJournal = {
53
+ /** Whether an earlier open bound this journal. */
54
+ readonly existing: boolean;
55
+ /** This open's ownership generation: one more than the open before it. */
56
+ readonly generation: number;
57
+ /** The state the last commit before this open left, or null before the first. */
58
+ readonly state: unknown;
59
+ /** The revision of the last commit: the journal's own counter, one per commit, never reused. */
60
+ readonly revision: number;
61
+ /** Every effect admitted so far, in any status. */
62
+ effects(): RecoveryEffect[];
63
+ effect(id: string): RecoveryEffect | undefined;
64
+ notes(): RecoveryNote[];
65
+ /** Commit a state computed with the commit's own revision, so a row that names its revision is never durable without
66
+ * it, and a note when the state records a decision, and the parts that go with it. Resolves to that revision. */
67
+ save(state: (revision: number) => unknown, note?: Pick<RecoveryNote, "kind" | "detail">, parts?: (revision: number) => RecoveryParts): Promise<number>;
68
+ /** Commit the state, and a note when the state records a decision, and the parts that go with it. Resolves to the
69
+ * commit's revision. */
70
+ save(state: unknown, note?: Pick<RecoveryNote, "kind" | "detail">, parts?: (revision: number) => RecoveryParts): Promise<number>;
71
+ /** Commit a note with no state change. Resolves to the commit's revision. */
72
+ note(kind: RecoveryNote["kind"], detail: unknown): Promise<number>;
73
+ /** Admit an effect before it is dispatched, with the state that admits it, in one commit, and the external call it
74
+ * makes when it makes one: the intent is kept with the effect from its admission, through its completion, at every
75
+ * later open. `args` are the call's arguments as the driver admitted it, kept with the effect as the host's door is sent them
76
+ * (an optional field: a record without them reads as it always did). A store that does not keep them leaves a call that was
77
+ * admitted and never sent unsettleable: a host's `reconcile` cannot re-send it, and the resume refuses it
78
+ * (`FROZEN_EFFECT_UNKNOWN`). An id already admitted is returned as it stands and nothing is written. `owner` names the
79
+ * map item whose record lists the effect, written in `parts` in the same commit: a store that keeps parts lists the
80
+ * effect there, and needs not list it again. */
81
+ admit(id: string, name: string, argsHash: string, state: unknown, session?: string | null, intent?: RecoveryIntent, args?: unknown, parts?: (revision: number) => RecoveryParts, owner?: string): Promise<"new" | RecoveryEffect>;
82
+ /** Complete an admitted effect with its result, and the state that follows, in one commit. An effect completes once,
83
+ * and never without an admission. With no state given, the state stays as this open found it: that is how an
84
+ * operator reconciles an unknown effect. */
85
+ complete(id: string, result: unknown, state?: unknown, parts?: (revision: number) => RecoveryParts): Promise<void>;
86
+ /** Keep the outside calls an admitted effect made, whether or not the effect completes: the list given replaces the one the
87
+ * effect held, and the effect's `calls` carries it from then on, at every later open. They are evidence for the host; no
88
+ * resume depends on them. A caller that adds to the calls an earlier process kept passes the earlier ones first. */
89
+ called(id: string, calls: unknown): Promise<void>;
90
+ /** Let go of the journal. No later commit is made through this open, and the next open is the next generation. */
91
+ close(): Promise<void>;
92
+ /** The records of the map items at `paths`, as the last commit that wrote each left it (undefined for one never
93
+ * written), so a driver reads back what it wrote in `parts`. The effects they list are then in `effects()` too.
94
+ * A store that keeps parts has both `items` and `stateOf`; a store without them cannot keep the keyed layout, and the
95
+ * driver keeps the whole state in one record there. */
96
+ items?(paths: string[]): Promise<Array<RecoveryItem | undefined>>;
97
+ /** The state written in `parts` under `sha256`, or undefined. */
98
+ stateOf?(sha256: string): Promise<unknown>;
99
+ };
100
+ /** Where one run's journal lives. `open` takes ownership of it: a journal that is already open is refused, a binding
101
+ * that differs from the one the journal was first opened under is refused naming the inputs that moved, and the
102
+ * generation advances. */
103
+ export type RecoveryStore = {
104
+ open(bound: RecoveryBinding): Promise<RecoveryJournal>;
105
+ };
@@ -0,0 +1,6 @@
1
+ // The store contract of durable recovery: where one run's journal lives, and the only way a recovery driver reads and
2
+ // writes it. A driver decides what is stored; a store keeps it, one atomic commit per write. The at-most-once rule for
3
+ // effects rests on three things every store must hold: an admission is durable, together with the state it carries,
4
+ // before `admit` resolves; an effect admitted and never completed stays `unknown` across every later open; and a
5
+ // journal has one owner at a time.
6
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { RecoveryStore } from "../store.js";
2
+ /** Registers the suite as `node:test` tests named under `name`. `create` returns a new, empty store on every call;
3
+ * the suite opens one store several times, as the successive processes of one run would. */
4
+ export declare function registerStoreConformance(name: string, create: () => RecoveryStore | Promise<RecoveryStore>): void;