@anureo/workflow 0.0.0-stage → 0.3.0
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/LICENSE +201 -0
- package/README.md +172 -2
- package/package.json +36 -4
- package/src/agent-outcome.d.ts +15 -0
- package/src/agent-outcome.js +28 -0
- package/src/agent.d.ts +49 -0
- package/src/agent.js +206 -0
- package/src/index.d.ts +6 -0
- package/src/index.js +5 -0
- package/src/output-schema.d.ts +27 -0
- package/src/output-schema.js +192 -0
- package/src/parallel.d.ts +18 -0
- package/src/parallel.js +25 -0
- package/src/persistence/atomic.d.ts +9 -0
- package/src/persistence/atomic.js +48 -0
- package/src/persistence/journal.d.ts +54 -0
- package/src/persistence/journal.js +106 -0
- package/src/persistence/json.d.ts +17 -0
- package/src/persistence/json.js +75 -0
- package/src/persistence/read-json.d.ts +11 -0
- package/src/persistence/read-json.js +46 -0
- package/src/persistence/records.d.ts +92 -0
- package/src/persistence/records.js +70 -0
- package/src/persistence/replay.d.ts +11 -0
- package/src/persistence/replay.js +79 -0
- package/src/persistence/store.d.ts +45 -0
- package/src/persistence/store.js +238 -0
- package/src/pipeline.d.ts +41 -0
- package/src/pipeline.js +24 -0
- package/src/run-context.d.ts +16 -0
- package/src/run-context.js +13 -0
- package/src/test-helpers.d.ts +11 -0
- package/src/test-helpers.js +21 -0
- package/src/workflow-state.d.ts +44 -0
- package/src/workflow-state.js +96 -0
- package/src/workflow-types.d.ts +39 -0
- package/src/workflow-types.js +0 -0
- package/src/workflow.d.ts +17 -0
- package/src/workflow.js +104 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { HarnessSdkError } from '@anureo/sdk';
|
|
3
|
+
import { atomicPublish } from "./atomic.js";
|
|
4
|
+
import { canonicalJson, jsonCopy } from "./json.js";
|
|
5
|
+
/** Fold validated events in file order. Clear the earlier entry for each key so a newer
|
|
6
|
+
* start or failure supersedes any older result when AgentJournal initializes its replay lookup. */
|
|
7
|
+
export function indexJournal(events) {
|
|
8
|
+
const index = { results: new Map(), started: new Set(), failures: new Map() };
|
|
9
|
+
for (const event of events) {
|
|
10
|
+
index.started.delete(event.key);
|
|
11
|
+
index.failures.delete(event.key);
|
|
12
|
+
index.results.delete(event.key);
|
|
13
|
+
if (event.type === 'started')
|
|
14
|
+
index.started.add(event.key);
|
|
15
|
+
else
|
|
16
|
+
indexTerminalEvent(index, event);
|
|
17
|
+
}
|
|
18
|
+
return index;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Internal agent-call journal created by publishInitialRun for a new run and exposed
|
|
22
|
+
* by workflow through the ambient run context.
|
|
23
|
+
* memoizedAgent reserves keys in invocation order, checks replay, and awaits markers before
|
|
24
|
+
* dispatch or settlement. Each key hashes its predecessor, prompt and semantic options,
|
|
25
|
+
* so upstream changes invalidate later call identities. The run handle owns the writer lock.
|
|
26
|
+
* workflow drains registered agent work before final publication and closure.
|
|
27
|
+
*/
|
|
28
|
+
export class AgentJournal {
|
|
29
|
+
path;
|
|
30
|
+
/** Copy validated source events into a new run's journal; construction performs no file I/O. */
|
|
31
|
+
constructor(path, source) {
|
|
32
|
+
this.path = path;
|
|
33
|
+
this.events.push(...jsonCopy(source));
|
|
34
|
+
this.index = indexJournal(this.events);
|
|
35
|
+
}
|
|
36
|
+
/** Advance the chain synchronously before memoizedAgent's first await, including cache hits.
|
|
37
|
+
* Options must be strict JSON. If canonicalJson throws, the chain stays unchanged. */
|
|
38
|
+
nextKey(prompt, canonicalOptions) {
|
|
39
|
+
const key = `v1:${createHash('sha256')
|
|
40
|
+
.update(this.previousKey).update('\0')
|
|
41
|
+
.update(prompt).update('\0')
|
|
42
|
+
.update(canonicalJson(canonicalOptions)).digest('hex')}`;
|
|
43
|
+
this.previousKey = key;
|
|
44
|
+
return key;
|
|
45
|
+
}
|
|
46
|
+
/** Return an isolated cached result while reuse remains open, or undefined for execution.
|
|
47
|
+
* memoizedAgent revalidates typed hits against the current output schema before returning them. */
|
|
48
|
+
resultFor(key) {
|
|
49
|
+
if (!this.reuseOpen)
|
|
50
|
+
return undefined;
|
|
51
|
+
const result = this.index.results.get(key);
|
|
52
|
+
return result === undefined ? undefined : jsonCopy(result);
|
|
53
|
+
}
|
|
54
|
+
/** Record a miss after resultFor returns undefined. A source key left at started can be
|
|
55
|
+
* respawned while preserving eligibility for later keys. Any other miss closes result reuse
|
|
56
|
+
* for the rest of the run. Return the exact key's prior terminal failure, if any, so
|
|
57
|
+
* memoizedAgent can reject an unknown outcome before dispatch. */
|
|
58
|
+
beginExecution(key) {
|
|
59
|
+
if (!this.index.started.has(key))
|
|
60
|
+
this.reuseOpen = false;
|
|
61
|
+
return this.index.failures.get(key);
|
|
62
|
+
}
|
|
63
|
+
/** Queue a copied event and await serialized atomic publication before indexing terminal data.
|
|
64
|
+
* memoizedAgent awaits started before dispatch and terminals before settlement. Keep the
|
|
65
|
+
* event unchanged until settlement and its result payload immutable while the lookup retains it.
|
|
66
|
+
* On publication failure the event remains queued. Non-SDK I/O failures reject as
|
|
67
|
+
* WORKFLOW_STORAGE_FAILED and stop subsequent workflow dispatch. */
|
|
68
|
+
async append(event) {
|
|
69
|
+
this.events.push(jsonCopy(event));
|
|
70
|
+
// Concurrent callers must not race atomic renames: an earlier snapshot
|
|
71
|
+
// landing last would silently drop later events from the published file.
|
|
72
|
+
const publish = this.publishQueue.catch(() => { }).then(async () => {
|
|
73
|
+
try {
|
|
74
|
+
await atomicPublish(this.path, this.events);
|
|
75
|
+
}
|
|
76
|
+
catch (cause) {
|
|
77
|
+
if (cause instanceof HarnessSdkError)
|
|
78
|
+
throw cause;
|
|
79
|
+
throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED');
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
this.publishQueue = publish;
|
|
83
|
+
await publish;
|
|
84
|
+
if (event.type !== 'started')
|
|
85
|
+
indexTerminalEvent(this.index, event);
|
|
86
|
+
}
|
|
87
|
+
events = [];
|
|
88
|
+
index;
|
|
89
|
+
previousKey = '';
|
|
90
|
+
reuseOpen = true;
|
|
91
|
+
publishQueue = Promise.resolve();
|
|
92
|
+
}
|
|
93
|
+
/** Generate a UUID suitable for a journal event's agentId; this does not reserve a cache key. */
|
|
94
|
+
export function newAgentId() {
|
|
95
|
+
return randomUUID();
|
|
96
|
+
}
|
|
97
|
+
/** Populate the terminal lookup. The replay fold clears superseded entries before calling
|
|
98
|
+
* this helper. Live append retains the source prefix markers for miss handling. */
|
|
99
|
+
function indexTerminalEvent(index, event) {
|
|
100
|
+
if (event.type === 'result') {
|
|
101
|
+
index.results.set(event.key, event.result);
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
index.failures.set(event.key, { code: event.code, outcomeUnknown: event.outcomeUnknown });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Workflow JSON data shape. The encoder also checks runtime properties and rejects cycles. */
|
|
2
|
+
export type JsonValue = null | boolean | number | string | JsonValue[] | {
|
|
3
|
+
[key: string]: JsonValue;
|
|
4
|
+
};
|
|
5
|
+
/** Encode strict JSON with sorted object keys for persistence and cache identity.
|
|
6
|
+
* Throws WORKFLOW_NON_JSON_VALUE for unsupported values such as non-finite numbers, sparse
|
|
7
|
+
* arrays, cycles, non-plain objects, symbol keys, accessors and hidden data fields.
|
|
8
|
+
* Shared acyclic references encode by value. Encoding never calls toJSON. */
|
|
9
|
+
export declare function canonicalJson(value: unknown): string;
|
|
10
|
+
/** Return a detached copy of JSON-compatible data. Unsupported values throw as in canonicalJson.
|
|
11
|
+
* Shared references are copied by value. */
|
|
12
|
+
export declare function jsonCopy<T>(value: T): T;
|
|
13
|
+
/** Deeply freeze an already validated, acyclic JSON value in place and return it.
|
|
14
|
+
* prepareRun passes an owned copy for workflow to expose to the body. */
|
|
15
|
+
export declare function freezeJson<T>(value: T): T;
|
|
16
|
+
/** Hash canonical JSON as lowercase SHA-256 hex; unsupported values throw as in canonicalJson. */
|
|
17
|
+
export declare function digest(value: unknown): string;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { HarnessSdkError } from '@anureo/sdk';
|
|
3
|
+
/** Encode strict JSON with sorted object keys for persistence and cache identity.
|
|
4
|
+
* Throws WORKFLOW_NON_JSON_VALUE for unsupported values such as non-finite numbers, sparse
|
|
5
|
+
* arrays, cycles, non-plain objects, symbol keys, accessors and hidden data fields.
|
|
6
|
+
* Shared acyclic references encode by value. Encoding never calls toJSON. */
|
|
7
|
+
export function canonicalJson(value) {
|
|
8
|
+
return encodeJson(value, new Set());
|
|
9
|
+
}
|
|
10
|
+
/** Return a detached copy of JSON-compatible data. Unsupported values throw as in canonicalJson.
|
|
11
|
+
* Shared references are copied by value. */
|
|
12
|
+
export function jsonCopy(value) {
|
|
13
|
+
return JSON.parse(canonicalJson(value));
|
|
14
|
+
}
|
|
15
|
+
/** Deeply freeze an already validated, acyclic JSON value in place and return it.
|
|
16
|
+
* prepareRun passes an owned copy for workflow to expose to the body. */
|
|
17
|
+
export function freezeJson(value) {
|
|
18
|
+
if (value && typeof value === 'object') {
|
|
19
|
+
for (const child of Object.values(value))
|
|
20
|
+
freezeJson(child);
|
|
21
|
+
Object.freeze(value);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
/** Hash canonical JSON as lowercase SHA-256 hex; unsupported values throw as in canonicalJson. */
|
|
26
|
+
export function digest(value) {
|
|
27
|
+
return createHash('sha256').update(canonicalJson(value)).digest('hex');
|
|
28
|
+
}
|
|
29
|
+
/** Track only the current ancestry so repeated references encode normally while cycles reject. */
|
|
30
|
+
function encodeJson(item, ancestors) {
|
|
31
|
+
if (item === null)
|
|
32
|
+
return 'null';
|
|
33
|
+
if (typeof item === 'string' || typeof item === 'boolean')
|
|
34
|
+
return JSON.stringify(item);
|
|
35
|
+
if (typeof item === 'number')
|
|
36
|
+
return Number.isFinite(item) ? JSON.stringify(item) : invalidJson();
|
|
37
|
+
if (typeof item !== 'object' || ancestors.has(item))
|
|
38
|
+
return invalidJson();
|
|
39
|
+
if (Reflect.ownKeys(item).some(key => typeof key !== 'string'))
|
|
40
|
+
return invalidJson();
|
|
41
|
+
const descriptors = Object.getOwnPropertyDescriptors(item);
|
|
42
|
+
ancestors.add(item);
|
|
43
|
+
try {
|
|
44
|
+
return Array.isArray(item)
|
|
45
|
+
? encodeArray(item, descriptors, ancestors)
|
|
46
|
+
: encodeObject(item, descriptors, ancestors);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
ancestors.delete(item);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Dense array slots must be the only own properties besides length to avoid silent data loss. */
|
|
53
|
+
function encodeArray(item, descriptors, ancestors) {
|
|
54
|
+
if (Object.keys(descriptors).length !== item.length + 1)
|
|
55
|
+
return invalidJson();
|
|
56
|
+
const values = [];
|
|
57
|
+
for (let i = 0; i < item.length; i++) {
|
|
58
|
+
values.push(encodeDataProperty(descriptors[String(i)], ancestors));
|
|
59
|
+
}
|
|
60
|
+
return `[${values.join(',')}]`;
|
|
61
|
+
}
|
|
62
|
+
/** Restrict objects to plain data and sort their keys so insertion order cannot change identity. */
|
|
63
|
+
function encodeObject(item, descriptors, ancestors) {
|
|
64
|
+
const prototype = Object.getPrototypeOf(item);
|
|
65
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
66
|
+
return invalidJson();
|
|
67
|
+
return `{${Object.keys(descriptors).sort().map(key => `${JSON.stringify(key)}:${encodeDataProperty(descriptors[key], ancestors)}`).join(',')}}`;
|
|
68
|
+
}
|
|
69
|
+
/** Inspect descriptors instead of reading properties so getters never supply persisted data. */
|
|
70
|
+
function encodeDataProperty(field, ancestors) {
|
|
71
|
+
if (!field || !field.enumerable || !('value' in field))
|
|
72
|
+
return invalidJson();
|
|
73
|
+
return encodeJson(field.value, ancestors);
|
|
74
|
+
}
|
|
75
|
+
function invalidJson() { throw new HarnessSdkError('WORKFLOW_NON_JSON_VALUE'); }
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type JsonValue } from "./json.js";
|
|
2
|
+
/** Read strict JSON from a regular file and always close its descriptor. Check the final
|
|
3
|
+
* component with lstat and verify the opened inode to catch replacement during open.
|
|
4
|
+
* Invalid content or file kind rejects as WORKFLOW_CHECKPOINT_INVALID. Replay classifies
|
|
5
|
+
* filesystem failures and validates the returned value against the checkpoint schema. */
|
|
6
|
+
export declare function readJson(path: string): Promise<JsonValue>;
|
|
7
|
+
/** Require the source's final path component to be a real directory. Other file kinds
|
|
8
|
+
* reject as WORKFLOW_CHECKPOINT_INVALID before replay reads it. Filesystem errors propagate. */
|
|
9
|
+
export declare function regularDirectory(path: string): Promise<void>;
|
|
10
|
+
/** Test for ENOENT so replay can allow an absent writer lock and reject absent required files. */
|
|
11
|
+
export declare function missing(cause: unknown): boolean;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Checks the filesystem entries that replay reads before validating checkpoint schemas.
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, open } from 'node:fs/promises';
|
|
4
|
+
import { canonicalJson } from "./json.js";
|
|
5
|
+
import { invalidCheckpoint } from "./records.js";
|
|
6
|
+
/** Read strict JSON from a regular file and always close its descriptor. Check the final
|
|
7
|
+
* component with lstat and verify the opened inode to catch replacement during open.
|
|
8
|
+
* Invalid content or file kind rejects as WORKFLOW_CHECKPOINT_INVALID. Replay classifies
|
|
9
|
+
* filesystem failures and validates the returned value against the checkpoint schema. */
|
|
10
|
+
export async function readJson(path) {
|
|
11
|
+
const before = await lstat(path);
|
|
12
|
+
if (!before.isFile())
|
|
13
|
+
return invalidCheckpoint();
|
|
14
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
15
|
+
try {
|
|
16
|
+
const current = await file.stat();
|
|
17
|
+
if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino)
|
|
18
|
+
return invalidCheckpoint();
|
|
19
|
+
return parseCheckpointJson(await file.readFile('utf8'));
|
|
20
|
+
}
|
|
21
|
+
finally {
|
|
22
|
+
await file.close();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Require the source's final path component to be a real directory. Other file kinds
|
|
26
|
+
* reject as WORKFLOW_CHECKPOINT_INVALID before replay reads it. Filesystem errors propagate. */
|
|
27
|
+
export async function regularDirectory(path) {
|
|
28
|
+
if (!(await lstat(path)).isDirectory())
|
|
29
|
+
invalidCheckpoint();
|
|
30
|
+
}
|
|
31
|
+
/** Test for ENOENT so replay can allow an absent writer lock and reject absent required files. */
|
|
32
|
+
export function missing(cause) {
|
|
33
|
+
return cause?.code === 'ENOENT';
|
|
34
|
+
}
|
|
35
|
+
/** Map malformed or nonrepresentable JSON to checkpoint corruption before schema validation.
|
|
36
|
+
* JSON.parse alone accepts number literals that overflow to Infinity. */
|
|
37
|
+
function parseCheckpointJson(text) {
|
|
38
|
+
try {
|
|
39
|
+
const value = JSON.parse(text);
|
|
40
|
+
canonicalJson(value);
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return invalidCheckpoint();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { type JsonValue } from "./json.js";
|
|
3
|
+
/** Check target and source basenames before joining paths. Reject blanks, separators,
|
|
4
|
+
* control characters, dot traversal and names over 255 UTF-8 bytes. Unicode and spaces
|
|
5
|
+
* support caller-assigned CLI basenames. */
|
|
6
|
+
export declare const runIdSchema: z.ZodString;
|
|
7
|
+
/** UUID rule shared by journal agent identities and writer-lock ownership tokens. */
|
|
8
|
+
export declare const uuidSchema: z.ZodString;
|
|
9
|
+
/** Persist only safe failure metadata; diagnostic messages and details stay out of manifests. */
|
|
10
|
+
export declare const failureSchema: z.ZodObject<{
|
|
11
|
+
code: z.ZodString;
|
|
12
|
+
retryable: z.ZodBoolean;
|
|
13
|
+
outcomeUnknown: z.ZodBoolean;
|
|
14
|
+
cleanupFailed: z.ZodBoolean;
|
|
15
|
+
}, z.core.$strict>;
|
|
16
|
+
/** Versioned chained SHA-256 identity for an agent call, independent of its execution UUID. */
|
|
17
|
+
export declare const journalKeySchema: z.ZodString;
|
|
18
|
+
/** Validated manifest shape; its digest and referenced result still require separate verification. */
|
|
19
|
+
export type Manifest = z.output<typeof manifestSchema>;
|
|
20
|
+
/** Persist only failure classification from workflow aborts, without diagnostic text. */
|
|
21
|
+
export type StoredFailure = z.output<typeof failureSchema>;
|
|
22
|
+
/** Internal validated event persisted before dispatch or before exposing an agent outcome. */
|
|
23
|
+
export type JournalEvent = z.output<typeof journalEventSchema>;
|
|
24
|
+
/** Reject unusable recovery material without treating corruption as an empty cache. */
|
|
25
|
+
export declare function invalidCheckpoint(): never;
|
|
26
|
+
/** Add a digest of the supplied JSON payload for a lock or manifest. Callers must omit
|
|
27
|
+
* recordDigest so the payload matches what verifyRecord later hashes. Strict JSON errors throw. */
|
|
28
|
+
export declare function record<T extends object>(value: T): T & {
|
|
29
|
+
recordDigest: string;
|
|
30
|
+
};
|
|
31
|
+
/** Return parsed lock or manifest data after verifying the payload digest. A schema
|
|
32
|
+
* mismatch or different digest throws WORKFLOW_CHECKPOINT_INVALID. The schema must
|
|
33
|
+
* yield strict JSON with a recordDigest field. */
|
|
34
|
+
export declare function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.output<S>;
|
|
35
|
+
/** Format-v2 writer claim. Replay checks host/PID liveness; release checks the held inode. */
|
|
36
|
+
export declare const lockSchema: z.ZodObject<{
|
|
37
|
+
checkpointFormatVersion: z.ZodLiteral<2>;
|
|
38
|
+
token: z.ZodString;
|
|
39
|
+
hostname: z.ZodString;
|
|
40
|
+
pid: z.ZodNumber;
|
|
41
|
+
createdAt: z.ZodString;
|
|
42
|
+
recordDigest: z.ZodString;
|
|
43
|
+
}, z.core.$strict>;
|
|
44
|
+
/** Format-v2 run metadata. Replay rejects earlier formats, checks recordDigest with verifyRecord,
|
|
45
|
+
* and checks resultDigest against result.json for completed and incomplete runs. */
|
|
46
|
+
export declare const manifestSchema: z.ZodObject<{
|
|
47
|
+
checkpointFormatVersion: z.ZodLiteral<2>;
|
|
48
|
+
identity: z.ZodObject<{
|
|
49
|
+
runId: z.ZodString;
|
|
50
|
+
directory: z.ZodString;
|
|
51
|
+
name: z.ZodString;
|
|
52
|
+
revision: z.ZodString;
|
|
53
|
+
input: z.ZodType<JsonValue, unknown, z.core.$ZodTypeInternals<JsonValue, unknown>>;
|
|
54
|
+
}, z.core.$strict>;
|
|
55
|
+
createdAt: z.ZodString;
|
|
56
|
+
resumedFrom: z.ZodNullable<z.ZodObject<{
|
|
57
|
+
directory: z.ZodString;
|
|
58
|
+
runId: z.ZodString;
|
|
59
|
+
}, z.core.$strict>>;
|
|
60
|
+
status: z.ZodEnum<{
|
|
61
|
+
running: "running";
|
|
62
|
+
completed: "completed";
|
|
63
|
+
failed: "failed";
|
|
64
|
+
incomplete: "incomplete";
|
|
65
|
+
}>;
|
|
66
|
+
resultDigest: z.ZodNullable<z.ZodString>;
|
|
67
|
+
failure: z.ZodNullable<z.ZodObject<{
|
|
68
|
+
code: z.ZodString;
|
|
69
|
+
retryable: z.ZodBoolean;
|
|
70
|
+
outcomeUnknown: z.ZodBoolean;
|
|
71
|
+
cleanupFailed: z.ZodBoolean;
|
|
72
|
+
}, z.core.$strict>>;
|
|
73
|
+
recordDigest: z.ZodString;
|
|
74
|
+
}, z.core.$strict>;
|
|
75
|
+
/** Strict persisted events. Replay validates the entire array before handing it to AgentJournal.
|
|
76
|
+
* The chained key determines reuse. The execution UUID is recorded as agentId. */
|
|
77
|
+
export declare const journalEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
78
|
+
type: z.ZodLiteral<"started">;
|
|
79
|
+
key: z.ZodString;
|
|
80
|
+
agentId: z.ZodString;
|
|
81
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
82
|
+
type: z.ZodLiteral<"result">;
|
|
83
|
+
key: z.ZodString;
|
|
84
|
+
agentId: z.ZodString;
|
|
85
|
+
result: z.ZodType<JsonValue, unknown, z.core.$ZodTypeInternals<JsonValue, unknown>>;
|
|
86
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
87
|
+
type: z.ZodLiteral<"failed">;
|
|
88
|
+
key: z.ZodString;
|
|
89
|
+
agentId: z.ZodString;
|
|
90
|
+
code: z.ZodString;
|
|
91
|
+
outcomeUnknown: z.ZodBoolean;
|
|
92
|
+
}, z.core.$strict>], "type">;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { HarnessSdkError } from '@anureo/sdk';
|
|
3
|
+
import { digest } from "./json.js";
|
|
4
|
+
/** Check target and source basenames before joining paths. Reject blanks, separators,
|
|
5
|
+
* control characters, dot traversal and names over 255 UTF-8 bytes. Unicode and spaces
|
|
6
|
+
* support caller-assigned CLI basenames. */
|
|
7
|
+
export const runIdSchema = z.string().min(1).refine(value => value !== '.' && value !== '..'
|
|
8
|
+
&& value.trim().length > 0 && !/[\\/\x00-\x1f\x7f]/.test(value) && Buffer.byteLength(value) <= 255);
|
|
9
|
+
/** UUID rule shared by journal agent identities and writer-lock ownership tokens. */
|
|
10
|
+
export const uuidSchema = z.string().uuid();
|
|
11
|
+
/** Persist only safe failure metadata; diagnostic messages and details stay out of manifests. */
|
|
12
|
+
export const failureSchema = z.strictObject({
|
|
13
|
+
code: z.string(),
|
|
14
|
+
retryable: z.boolean(),
|
|
15
|
+
/** The failure left execution's outcome uncertain. */
|
|
16
|
+
outcomeUnknown: z.boolean(),
|
|
17
|
+
/** Resource release failed even if execution itself had a known outcome. */
|
|
18
|
+
cleanupFailed: z.boolean(),
|
|
19
|
+
});
|
|
20
|
+
/** Versioned chained SHA-256 identity for an agent call, independent of its execution UUID. */
|
|
21
|
+
export const journalKeySchema = z.string().regex(/^v1:[a-f0-9]{64}$/);
|
|
22
|
+
/** Reject unusable recovery material without treating corruption as an empty cache. */
|
|
23
|
+
export function invalidCheckpoint() { throw new HarnessSdkError('WORKFLOW_CHECKPOINT_INVALID'); }
|
|
24
|
+
/** Add a digest of the supplied JSON payload for a lock or manifest. Callers must omit
|
|
25
|
+
* recordDigest so the payload matches what verifyRecord later hashes. Strict JSON errors throw. */
|
|
26
|
+
export function record(value) {
|
|
27
|
+
return { ...value, recordDigest: digest(value) };
|
|
28
|
+
}
|
|
29
|
+
/** Return parsed lock or manifest data after verifying the payload digest. A schema
|
|
30
|
+
* mismatch or different digest throws WORKFLOW_CHECKPOINT_INVALID. The schema must
|
|
31
|
+
* yield strict JSON with a recordDigest field. */
|
|
32
|
+
export function verifyRecord(schema, value) {
|
|
33
|
+
const parsed = schema.safeParse(value);
|
|
34
|
+
if (!parsed.success)
|
|
35
|
+
return invalidCheckpoint();
|
|
36
|
+
const { recordDigest, ...payload } = parsed.data;
|
|
37
|
+
if (digest(payload) !== recordDigest)
|
|
38
|
+
return invalidCheckpoint();
|
|
39
|
+
return parsed.data;
|
|
40
|
+
}
|
|
41
|
+
// These schemas must be initialized before the exported record schemas that compose them.
|
|
42
|
+
const hashSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
|
43
|
+
const jsonSchema = z.lazy(() => z.union([
|
|
44
|
+
z.null(), z.boolean(), z.number().finite(), z.string(), z.array(jsonSchema), z.record(z.string(), jsonSchema),
|
|
45
|
+
]));
|
|
46
|
+
const identitySchema = z.strictObject({
|
|
47
|
+
runId: runIdSchema, directory: z.string(), name: z.string().min(1), revision: z.string().min(1), input: jsonSchema,
|
|
48
|
+
});
|
|
49
|
+
/** Format-v2 writer claim. Replay checks host/PID liveness; release checks the held inode. */
|
|
50
|
+
export const lockSchema = z.strictObject({
|
|
51
|
+
checkpointFormatVersion: z.literal(2), token: uuidSchema, hostname: z.string(),
|
|
52
|
+
pid: z.number().int().positive(), createdAt: z.string().datetime(), recordDigest: hashSchema,
|
|
53
|
+
});
|
|
54
|
+
/** Format-v2 run metadata. Replay rejects earlier formats, checks recordDigest with verifyRecord,
|
|
55
|
+
* and checks resultDigest against result.json for completed and incomplete runs. */
|
|
56
|
+
export const manifestSchema = z.strictObject({
|
|
57
|
+
checkpointFormatVersion: z.literal(2),
|
|
58
|
+
identity: identitySchema, createdAt: z.string().datetime(),
|
|
59
|
+
resumedFrom: z.strictObject({ directory: z.string(), runId: runIdSchema }).nullable(),
|
|
60
|
+
status: z.enum(['running', 'completed', 'incomplete', 'failed']),
|
|
61
|
+
resultDigest: hashSchema.nullable(), failure: failureSchema.nullable(), recordDigest: hashSchema,
|
|
62
|
+
});
|
|
63
|
+
/** Strict persisted events. Replay validates the entire array before handing it to AgentJournal.
|
|
64
|
+
* The chained key determines reuse. The execution UUID is recorded as agentId. */
|
|
65
|
+
export const journalEventSchema = z.discriminatedUnion('type', [
|
|
66
|
+
z.strictObject({ type: z.literal('started'), key: journalKeySchema, agentId: uuidSchema }),
|
|
67
|
+
z.strictObject({ type: z.literal('result'), key: journalKeySchema, agentId: uuidSchema, result: jsonSchema }),
|
|
68
|
+
z.strictObject({ type: z.literal('failed'), key: journalKeySchema, agentId: uuidSchema,
|
|
69
|
+
code: z.string().min(1), outcomeUnknown: z.boolean() }),
|
|
70
|
+
]);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Manifest, type JournalEvent } from "./records.js";
|
|
2
|
+
/** Load an inactive source run's validated events without modifying its files.
|
|
3
|
+
* publishInitialRun calls this while holding the target lock, then copies the events
|
|
4
|
+
* into the new journal. A mismatched run ID or invalid required record rejects as
|
|
5
|
+
* WORKFLOW_CHECKPOINT_INVALID. Mismatched name or revision rejects as WORKFLOW_INCOMPATIBLE_RUN.
|
|
6
|
+
* A valid lock without evidence of a dead local writer rejects as WORKFLOW_SOURCE_ACTIVE.
|
|
7
|
+
* Other filesystem errors propagate. Failed and running sources need no result file.
|
|
8
|
+
* The caller supplies a separate target directory. This check acquires no source lock. */
|
|
9
|
+
export declare function loadSourceJournal(directory: string, identity: SourceIdentity): Promise<JournalEvent[]>;
|
|
10
|
+
type SourceIdentity = Pick<Manifest['identity'], 'name' | 'revision' | 'runId'>;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { HarnessSdkError } from '@anureo/sdk';
|
|
2
|
+
import { hostname } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { digest } from "./json.js";
|
|
5
|
+
import { readJson, regularDirectory, missing } from "./read-json.js";
|
|
6
|
+
import { journalEventSchema, lockSchema, manifestSchema, invalidCheckpoint, verifyRecord, } from "./records.js";
|
|
7
|
+
/** Load an inactive source run's validated events without modifying its files.
|
|
8
|
+
* publishInitialRun calls this while holding the target lock, then copies the events
|
|
9
|
+
* into the new journal. A mismatched run ID or invalid required record rejects as
|
|
10
|
+
* WORKFLOW_CHECKPOINT_INVALID. Mismatched name or revision rejects as WORKFLOW_INCOMPATIBLE_RUN.
|
|
11
|
+
* A valid lock without evidence of a dead local writer rejects as WORKFLOW_SOURCE_ACTIVE.
|
|
12
|
+
* Other filesystem errors propagate. Failed and running sources need no result file.
|
|
13
|
+
* The caller supplies a separate target directory. This check acquires no source lock. */
|
|
14
|
+
export async function loadSourceJournal(directory, identity) {
|
|
15
|
+
await regularDirectory(directory);
|
|
16
|
+
await assertInactive(directory);
|
|
17
|
+
const manifest = verifyRecord(manifestSchema, await requiredJson(join(directory, 'run.json')));
|
|
18
|
+
assertCompatibleIdentity(manifest.identity, identity);
|
|
19
|
+
const raw = await requiredJson(join(directory, 'journal.json'));
|
|
20
|
+
const parsed = journalEventSchema.array().safeParse(raw);
|
|
21
|
+
if (!parsed.success)
|
|
22
|
+
invalidCheckpoint();
|
|
23
|
+
if (manifest.status === 'completed' || manifest.status === 'incomplete') {
|
|
24
|
+
if (digest(await requiredJson(join(directory, 'result.json'))) !== manifest.resultDigest)
|
|
25
|
+
invalidCheckpoint();
|
|
26
|
+
}
|
|
27
|
+
return parsed.data;
|
|
28
|
+
}
|
|
29
|
+
/** Check that the manifest belongs to the selected run before checking workflow compatibility.
|
|
30
|
+
* A misplaced manifest is checkpoint corruption even if its workflow name or revision differs. */
|
|
31
|
+
function assertCompatibleIdentity(actual, expected) {
|
|
32
|
+
if (actual.runId !== expected.runId)
|
|
33
|
+
invalidCheckpoint();
|
|
34
|
+
if (actual.name !== expected.name || actual.revision !== expected.revision) {
|
|
35
|
+
throw new HarnessSdkError('WORKFLOW_INCOMPATIBLE_RUN');
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Classify missing recovery files and final symlinks as invalid checkpoints.
|
|
39
|
+
* Other failures reach openFileRun for storage error normalization. */
|
|
40
|
+
async function requiredJson(path) {
|
|
41
|
+
try {
|
|
42
|
+
return await readJson(path);
|
|
43
|
+
}
|
|
44
|
+
catch (cause) {
|
|
45
|
+
if (missing(cause) || cause?.code === 'ELOOP')
|
|
46
|
+
invalidCheckpoint();
|
|
47
|
+
throw cause;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** Permit an absent writer lock or a validated local claim whose PID no longer exists.
|
|
51
|
+
* An invalid lock rejects through verifyRecord. A valid lock that fails the liveness
|
|
52
|
+
* check blocks loadSourceJournal before it reads the manifest. */
|
|
53
|
+
async function assertInactive(directory) {
|
|
54
|
+
let lock;
|
|
55
|
+
try {
|
|
56
|
+
lock = verifyRecord(lockSchema, await readJson(join(directory, 'writer.lock')));
|
|
57
|
+
}
|
|
58
|
+
catch (cause) {
|
|
59
|
+
if (missing(cause))
|
|
60
|
+
return;
|
|
61
|
+
throw cause;
|
|
62
|
+
}
|
|
63
|
+
if (!localWriterExited(lock))
|
|
64
|
+
throw new HarnessSdkError('WORKFLOW_SOURCE_ACTIVE');
|
|
65
|
+
}
|
|
66
|
+
/** Only a local PID probe returning ESRCH proves the recorded process is gone.
|
|
67
|
+
* A foreign host, live or reused PID, or refused probe leaves inactivity unproven.
|
|
68
|
+
* This evidence is limited to the writer process and cannot confirm backend termination. */
|
|
69
|
+
function localWriterExited(lock) {
|
|
70
|
+
if (lock.hostname !== hostname())
|
|
71
|
+
return false;
|
|
72
|
+
try {
|
|
73
|
+
process.kill(lock.pid, 0);
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
catch (cause) {
|
|
77
|
+
return cause.code === 'ESRCH';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { WorkflowOptions } from "../workflow-types.js";
|
|
2
|
+
import { type JsonValue } from "./json.js";
|
|
3
|
+
import { AgentJournal } from "./journal.js";
|
|
4
|
+
import { type StoredFailure } from "./records.js";
|
|
5
|
+
/** Internal identity saved before workflow enters its body. */
|
|
6
|
+
export interface RunIdentity {
|
|
7
|
+
/** Validated basename of the run within directory. */
|
|
8
|
+
runId: string;
|
|
9
|
+
/** Canonical parent containing the run's subdirectory. */
|
|
10
|
+
directory: string;
|
|
11
|
+
name: string;
|
|
12
|
+
revision: string;
|
|
13
|
+
/** Isolated persistence snapshot. The body receives its own frozen copy from prepareRun. */
|
|
14
|
+
input: JsonValue;
|
|
15
|
+
}
|
|
16
|
+
/** Internal storage ownership returned to workflow. Drain agent work before finish or abort,
|
|
17
|
+
* and always await close in finally. Only manifest operations are serialized by this handle. */
|
|
18
|
+
export interface RunHandle {
|
|
19
|
+
/** Provides the canonical storage directory for workflow's error details. */
|
|
20
|
+
readonly identity: RunIdentity;
|
|
21
|
+
/** Installed by completeRun as the journal for agent calls in the body. */
|
|
22
|
+
readonly journal: AgentJournal;
|
|
23
|
+
/** Publish result.json before the terminal manifest and resolve after both publications.
|
|
24
|
+
* A rejection may leave a result or manifest already replaced. A queued call that starts
|
|
25
|
+
* after closure rejects with WORKFLOW_CLOSED. */
|
|
26
|
+
finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void>;
|
|
27
|
+
/** Publish a failed manifest and keep any earlier result file and the writer lock.
|
|
28
|
+
* Publication failures reject, as does a queued call that starts after closure. */
|
|
29
|
+
abort(failure: StoredFailure): Promise<void>;
|
|
30
|
+
/** Wait for queued manifests, then release the owned writer lock and close its descriptor.
|
|
31
|
+
* Lock-release failures reject. Sequential repeats are no-ops, including after rejection.
|
|
32
|
+
* Callers must finish scheduling work before closure. */
|
|
33
|
+
close(): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
/** Create a fresh file-backed run for workflow, publishing its journal and running manifest
|
|
36
|
+
* before returning. An optional inactive source supplies replay events, never the final result.
|
|
37
|
+
* The returned handle owns the writer lock and must be closed after registered agent work drains.
|
|
38
|
+
* SDK errors propagate unless lock rollback fails. Rollback failures and otherwise unclassified
|
|
39
|
+
* I/O failures reject as WORKFLOW_STORAGE_FAILED. If publication left run files behind,
|
|
40
|
+
* a later attempt on the same target rejects with WORKFLOW_RUN_EXISTS. */
|
|
41
|
+
export declare function openFileRun(options: FileRunOptions): Promise<RunHandle>;
|
|
42
|
+
type FileRunOptions = WorkflowOptions<JsonValue> & {
|
|
43
|
+
runId: string;
|
|
44
|
+
};
|
|
45
|
+
export {};
|