@anureo/workflow 0.3.0 → 0.3.1

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 (63) hide show
  1. package/README.md +96 -70
  2. package/package.json +17 -16
  3. package/src/agent-adapters.test.ts +121 -0
  4. package/src/agent-execution.ts +201 -0
  5. package/src/agent.test.ts +333 -0
  6. package/src/agent.ts +135 -0
  7. package/src/fixtures/workflow-crash.ts +53 -0
  8. package/src/index.ts +9 -0
  9. package/src/output-schema.test.ts +147 -0
  10. package/src/output-schema.ts +231 -0
  11. package/src/parallel.test.ts +96 -0
  12. package/src/parallel.ts +33 -0
  13. package/src/persistence/checkpoint-files.ts +82 -0
  14. package/src/persistence/journal.ts +111 -0
  15. package/src/persistence/json.ts +83 -0
  16. package/src/persistence/records.ts +97 -0
  17. package/src/persistence/replay.ts +91 -0
  18. package/src/persistence/store.ts +286 -0
  19. package/src/pipeline.test.ts +201 -0
  20. package/src/pipeline.ts +99 -0
  21. package/src/test-helpers.ts +23 -0
  22. package/src/workflow-state.ts +130 -0
  23. package/src/workflow-types.ts +38 -0
  24. package/src/workflow.test.ts +376 -0
  25. package/src/workflow.ts +112 -0
  26. package/tsconfig.json +13 -0
  27. package/LICENSE +0 -201
  28. package/src/agent-outcome.d.ts +0 -15
  29. package/src/agent-outcome.js +0 -28
  30. package/src/agent.d.ts +0 -49
  31. package/src/agent.js +0 -206
  32. package/src/index.d.ts +0 -6
  33. package/src/index.js +0 -5
  34. package/src/output-schema.d.ts +0 -27
  35. package/src/output-schema.js +0 -192
  36. package/src/parallel.d.ts +0 -18
  37. package/src/parallel.js +0 -25
  38. package/src/persistence/atomic.d.ts +0 -9
  39. package/src/persistence/atomic.js +0 -48
  40. package/src/persistence/journal.d.ts +0 -54
  41. package/src/persistence/journal.js +0 -106
  42. package/src/persistence/json.d.ts +0 -17
  43. package/src/persistence/json.js +0 -75
  44. package/src/persistence/read-json.d.ts +0 -11
  45. package/src/persistence/read-json.js +0 -46
  46. package/src/persistence/records.d.ts +0 -92
  47. package/src/persistence/records.js +0 -70
  48. package/src/persistence/replay.d.ts +0 -11
  49. package/src/persistence/replay.js +0 -79
  50. package/src/persistence/store.d.ts +0 -45
  51. package/src/persistence/store.js +0 -238
  52. package/src/pipeline.d.ts +0 -41
  53. package/src/pipeline.js +0 -24
  54. package/src/run-context.d.ts +0 -16
  55. package/src/run-context.js +0 -13
  56. package/src/test-helpers.d.ts +0 -11
  57. package/src/test-helpers.js +0 -21
  58. package/src/workflow-state.d.ts +0 -44
  59. package/src/workflow-state.js +0 -96
  60. package/src/workflow-types.d.ts +0 -39
  61. package/src/workflow-types.js +0 -0
  62. package/src/workflow.d.ts +0 -17
  63. package/src/workflow.js +0 -104
@@ -0,0 +1,111 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { atomicPublish, storageError } from './checkpoint-files'
3
+ import { canonicalJson, jsonCopy, type JsonValue } from './json'
4
+ import type { JournalEvent } from './records'
5
+
6
+ /**
7
+ * Internal agent-call journal created by publishInitialRun for a new run and exposed
8
+ * by workflow through the ambient run context.
9
+ * memoizedAgent reserves keys in invocation order and checks replay. On a miss,
10
+ * executeJournaledAgent awaits markers before dispatch and settlement. Each key hashes its
11
+ * predecessor, prompt and semantic options, so upstream changes invalidate later call identities.
12
+ * workflow drains registered agent work before final publication and releases the writer
13
+ * lock through the run handle.
14
+ */
15
+ export class AgentJournal {
16
+ /** Copy validated source events into a new run's journal; construction performs no file I/O. */
17
+ constructor(
18
+ private readonly path: string,
19
+ source: readonly JournalEvent[],
20
+ ) {
21
+ this.events.push(...jsonCopy(source))
22
+ this.index = indexJournal(this.events)
23
+ }
24
+
25
+ /** Advance the chain synchronously before memoizedAgent's first await, including cache hits.
26
+ * Options must be strict JSON. If canonicalJson throws, the chain stays unchanged. */
27
+ nextKey(prompt: string, canonicalOptions: JsonValue): string {
28
+ const key = `v1:${createHash('sha256')
29
+ .update(this.previousKey).update('\0')
30
+ .update(prompt).update('\0')
31
+ .update(canonicalJson(canonicalOptions)).digest('hex')}`
32
+ this.previousKey = key
33
+ return key
34
+ }
35
+
36
+ /** Decide how memoizedAgent should handle the reserved key. A replay carries an isolated
37
+ * result for the caller to validate. A miss closes result reuse unless the source left this
38
+ * key at started. Even after reuse closes, an exact-key failure with an unknown outcome
39
+ * requires reconciliation before memoizedAgent can dispatch. */
40
+ resolveCall(key: string): JournalDecision {
41
+ if (this.reuseOpen) {
42
+ const result = this.index.results.get(key)
43
+ if (result !== undefined) return { action: 'replay', result: jsonCopy(result) }
44
+ }
45
+ if (!this.index.started.has(key)) this.reuseOpen = false
46
+ return this.index.uncertain.has(key) ? { action: 'reconcile' } : { action: 'execute' }
47
+ }
48
+
49
+ /** Queue a copied event and await serialized atomic publication before indexing terminal data.
50
+ * executeJournaledAgent awaits started before dispatch and terminals before settlement. Keep the
51
+ * event unchanged until settlement and its result payload immutable while the lookup retains it.
52
+ * On publication failure the event stays in the in-memory snapshot. Non-SDK I/O failures
53
+ * reject as WORKFLOW_STORAGE_FAILED, which RunState records to stop later dispatch. */
54
+ async append(event: JournalEvent): Promise<void> {
55
+ this.events.push(jsonCopy(event))
56
+ // Concurrent callers must not race atomic renames: an earlier snapshot
57
+ // landing last would silently drop later events from the published file.
58
+ const publish = this.publishQueue.catch(() => {}).then(async () => {
59
+ try {
60
+ await atomicPublish(this.path, this.events)
61
+ } catch (cause) {
62
+ throw storageError(cause)
63
+ }
64
+ })
65
+ this.publishQueue = publish
66
+ await publish
67
+ if (event.type !== 'started') indexTerminalEvent(this.index, event)
68
+ }
69
+
70
+ private readonly events: JournalEvent[] = []
71
+ private readonly index: JournalIndex
72
+ private previousKey = ''
73
+ private reuseOpen = true
74
+ private publishQueue: Promise<void> = Promise.resolve()
75
+ }
76
+
77
+ /** Result handling stays with memoizedAgent, which owns validation, dispatch and rejection. */
78
+ type JournalDecision = { action: 'replay'; result: JsonValue } | { action: 'execute' | 'reconcile' }
79
+
80
+ /** Replay lookup built from validated events. A key left at started can be respawned. */
81
+ interface JournalIndex {
82
+ results: Map<string, JsonValue>
83
+ started: Set<string>
84
+ uncertain: Set<string>
85
+ }
86
+
87
+ /** Fold validated events in file order. Clear the earlier entry for each key so a newer
88
+ * start or failure supersedes any older result when AgentJournal initializes its replay lookup. */
89
+ function indexJournal(events: readonly JournalEvent[]): JournalIndex {
90
+ const index: JournalIndex = { results: new Map(), started: new Set(), uncertain: new Set() }
91
+ for (const event of events) {
92
+ index.started.delete(event.key)
93
+ index.uncertain.delete(event.key)
94
+ index.results.delete(event.key)
95
+ if (event.type === 'started') index.started.add(event.key)
96
+ else indexTerminalEvent(index, event)
97
+ }
98
+ return index
99
+ }
100
+
101
+ /** Populate the terminal lookup. The replay fold clears superseded entries before calling
102
+ * this helper. Live append retains the source prefix markers for miss handling. */
103
+ function indexTerminalEvent(index: JournalIndex, event: Exclude<JournalEvent, { type: 'started' }>): void {
104
+ if (event.type === 'result') {
105
+ index.results.set(event.key, event.result)
106
+ } else if (event.outcomeUnknown) {
107
+ index.uncertain.add(event.key)
108
+ } else {
109
+ index.uncertain.delete(event.key)
110
+ }
111
+ }
@@ -0,0 +1,83 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { HarnessSdkError } from '@anureo/sdk'
3
+
4
+ /** Workflow JSON data shape. The encoder also checks runtime properties and rejects cycles. */
5
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
6
+ [key: string]: JsonValue
7
+ }
8
+
9
+ /** Encode strict JSON with sorted object keys for persistence and cache identity.
10
+ * Throws WORKFLOW_NON_JSON_VALUE for unsupported values such as non-finite numbers, sparse
11
+ * arrays, cycles, non-plain objects, symbol keys, accessors and hidden data fields.
12
+ * Shared acyclic references encode by value. Encoding never calls toJSON. */
13
+ export function canonicalJson(value: unknown): string {
14
+ return encodeJson(value, new Set())
15
+ }
16
+
17
+ /** Return a detached copy of JSON-compatible data. Unsupported values throw as in canonicalJson.
18
+ * Shared references are copied by value. */
19
+ export function jsonCopy<T>(value: T): T {
20
+ return JSON.parse(canonicalJson(value)) as T
21
+ }
22
+
23
+ /** Deeply freeze an already validated, acyclic JSON value in place and return it.
24
+ * prepareRun passes an owned copy for workflow to expose to the body. */
25
+ export function freezeJson<T>(value: T): T {
26
+ if (value && typeof value === 'object') {
27
+ for (const child of Object.values(value)) freezeJson(child)
28
+ Object.freeze(value)
29
+ }
30
+ return value
31
+ }
32
+
33
+ /** Hash canonical JSON as lowercase SHA-256 hex. record and verifyRecord agree on this encoding
34
+ * for record payloads, and FileRunHandle.finish and loadSourceJournal use it for result.json.
35
+ * Unsupported values throw as in canonicalJson. */
36
+ export function digest(value: unknown): string {
37
+ return createHash('sha256').update(canonicalJson(value)).digest('hex')
38
+ }
39
+
40
+ /** Track only the current ancestry so repeated references encode normally while cycles reject. */
41
+ function encodeJson(item: unknown, ancestors: Set<object>): string {
42
+ if (item === null) return 'null'
43
+ if (typeof item === 'string' || typeof item === 'boolean') return JSON.stringify(item)
44
+ if (typeof item === 'number') return Number.isFinite(item) ? JSON.stringify(item) : invalidJson()
45
+ if (typeof item !== 'object' || ancestors.has(item)) return invalidJson()
46
+ if (Reflect.ownKeys(item).some(key => typeof key !== 'string')) return invalidJson()
47
+ const descriptors = Object.getOwnPropertyDescriptors(item)
48
+ ancestors.add(item)
49
+ try {
50
+ return Array.isArray(item)
51
+ ? encodeArray(item, descriptors, ancestors)
52
+ : encodeObject(item, descriptors, ancestors)
53
+ } finally {
54
+ ancestors.delete(item)
55
+ }
56
+ }
57
+
58
+ /** Dense array slots must be the only own properties besides length to avoid silent data loss. */
59
+ function encodeArray(item: unknown[], descriptors: Record<string, PropertyDescriptor>, ancestors: Set<object>): string {
60
+ if (Object.keys(descriptors).length !== item.length + 1) return invalidJson()
61
+ const values: string[] = []
62
+ for (let i = 0; i < item.length; i++) {
63
+ values.push(encodeDataProperty(descriptors[String(i)], ancestors))
64
+ }
65
+ return `[${values.join(',')}]`
66
+ }
67
+
68
+ /** Restrict objects to plain data and sort their keys so insertion order cannot change identity. */
69
+ function encodeObject(item: object, descriptors: Record<string, PropertyDescriptor>, ancestors: Set<object>): string {
70
+ const prototype = Object.getPrototypeOf(item)
71
+ if (prototype !== Object.prototype && prototype !== null) return invalidJson()
72
+ return `{${Object.keys(descriptors).sort().map(key =>
73
+ `${JSON.stringify(key)}:${encodeDataProperty(descriptors[key], ancestors)}`
74
+ ).join(',')}}`
75
+ }
76
+
77
+ /** Inspect descriptors instead of reading properties so getters never supply persisted data. */
78
+ function encodeDataProperty(field: PropertyDescriptor | undefined, ancestors: Set<object>): string {
79
+ if (!field || !field.enumerable || !('value' in field)) return invalidJson()
80
+ return encodeJson(field.value, ancestors)
81
+ }
82
+
83
+ function invalidJson(): never { throw new HarnessSdkError('WORKFLOW_NON_JSON_VALUE') }
@@ -0,0 +1,97 @@
1
+ import { z } from 'zod'
2
+ import { HarnessSdkError } from '@anureo/sdk'
3
+ import { digest, type JsonValue } from './json'
4
+
5
+ /** Validated manifest shape; its digest and referenced result still require separate verification. */
6
+ export type Manifest = z.output<typeof manifestSchema>
7
+
8
+ /** Persist only failure classification from workflow aborts, without diagnostic text. */
9
+ export type StoredFailure = z.output<typeof failureSchema>
10
+
11
+ /** Internal validated event persisted before dispatch or before exposing an agent outcome. */
12
+ export type JournalEvent = z.output<typeof journalEventSchema>
13
+
14
+ /** Reject unusable recovery material without treating corruption as an empty cache. */
15
+ export function invalidCheckpoint(): never { throw new HarnessSdkError('WORKFLOW_CHECKPOINT_INVALID') }
16
+
17
+ /** Add a digest of the supplied JSON payload for a lock or manifest. Callers must omit
18
+ * recordDigest so the payload matches what verifyRecord later hashes. Strict JSON errors throw. */
19
+ export function record<T extends object>(value: T): T & { recordDigest: string } {
20
+ return { ...value, recordDigest: digest(value) }
21
+ }
22
+
23
+ /** Return parsed lock or manifest data after verifying the payload digest. A schema
24
+ * mismatch or different digest throws WORKFLOW_CHECKPOINT_INVALID. The schema must
25
+ * yield strict JSON with a recordDigest field. */
26
+ export function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.output<S> {
27
+ const parsed = schema.safeParse(value)
28
+ if (!parsed.success) return invalidCheckpoint()
29
+ const { recordDigest, ...payload } = parsed.data as Record<string, unknown>
30
+ if (digest(payload) !== recordDigest) return invalidCheckpoint()
31
+ return parsed.data
32
+ }
33
+
34
+ /** File names and version used by the target writer and the compatible-source reader. */
35
+ export const checkpointFormat = {
36
+ version: 2,
37
+ lock: 'writer.lock',
38
+ manifest: 'run.json',
39
+ journal: 'journal.json',
40
+ result: 'result.json',
41
+ } as const
42
+
43
+ /** Check target and source basenames before joining paths. Reject blanks, separators,
44
+ * control characters, dot traversal and names over 255 UTF-8 bytes. Unicode and spaces
45
+ * support caller-assigned CLI basenames. */
46
+ export const runIdSchema = z.string().min(1).refine(value => value !== '.' && value !== '..'
47
+ && value.trim().length > 0 && !/[\\/\x00-\x1f\x7f]/.test(value) && Buffer.byteLength(value) <= 255)
48
+
49
+ // The exported record schemas evaluate their component schemas during initialization.
50
+ /** UUID rule shared by journal agent identities and writer-lock ownership tokens. */
51
+ const uuidSchema = z.string().uuid()
52
+ const hashSchema = z.string().regex(/^[a-f0-9]{64}$/)
53
+
54
+ /** Format-v2 writer claim. Replay checks host/PID liveness. Release checks the held inode. */
55
+ export const lockSchema = z.strictObject({
56
+ checkpointFormatVersion: z.literal(checkpointFormat.version), token: uuidSchema, hostname: z.string(),
57
+ pid: z.number().int().positive(), createdAt: z.string().datetime(), recordDigest: hashSchema,
58
+ })
59
+
60
+ /** Persist only safe failure metadata; diagnostic messages and details stay out of manifests. */
61
+ const failureSchema = z.strictObject({
62
+ code: z.string(),
63
+ retryable: z.boolean(),
64
+ /** The failure left execution's outcome uncertain. */
65
+ outcomeUnknown: z.boolean(),
66
+ /** Resource release failed even if execution itself had a known outcome. */
67
+ cleanupFailed: z.boolean(),
68
+ })
69
+
70
+ const jsonSchema: z.ZodType<JsonValue> = z.lazy(() => z.union([
71
+ z.null(), z.boolean(), z.number().finite(), z.string(), z.array(jsonSchema), z.record(z.string(), jsonSchema),
72
+ ]))
73
+ const identitySchema = z.strictObject({
74
+ runId: runIdSchema, directory: z.string(), name: z.string().min(1), revision: z.string().min(1), input: jsonSchema,
75
+ })
76
+
77
+ /** Format-v2 run metadata. Replay rejects earlier formats, checks recordDigest with verifyRecord,
78
+ * and checks resultDigest against result.json for completed and incomplete runs. */
79
+ export const manifestSchema = z.strictObject({
80
+ checkpointFormatVersion: z.literal(checkpointFormat.version),
81
+ identity: identitySchema, createdAt: z.string().datetime(),
82
+ resumedFrom: z.strictObject({ directory: z.string(), runId: runIdSchema }).nullable(),
83
+ status: z.enum(['running', 'completed', 'incomplete', 'failed']),
84
+ resultDigest: hashSchema.nullable(), failure: failureSchema.nullable(), recordDigest: hashSchema,
85
+ })
86
+
87
+ /** Versioned chained SHA-256 identity for an agent call, independent of its execution UUID. */
88
+ const journalKeySchema = z.string().regex(/^v1:[a-f0-9]{64}$/)
89
+
90
+ /** Strict persisted events. Replay validates the entire array before handing it to AgentJournal.
91
+ * The chained key determines reuse. The execution UUID is recorded as agentId. */
92
+ export const journalEventSchema = z.discriminatedUnion('type', [
93
+ z.strictObject({ type: z.literal('started'), key: journalKeySchema, agentId: uuidSchema }),
94
+ z.strictObject({ type: z.literal('result'), key: journalKeySchema, agentId: uuidSchema, result: jsonSchema }),
95
+ z.strictObject({ type: z.literal('failed'), key: journalKeySchema, agentId: uuidSchema,
96
+ code: z.string().min(1), outcomeUnknown: z.boolean() }),
97
+ ])
@@ -0,0 +1,91 @@
1
+ import { lstat } from 'node:fs/promises'
2
+ import { hostname } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { HarnessSdkError } from '@anureo/sdk'
5
+ import { readJson } from './checkpoint-files'
6
+ import { digest } from './json'
7
+ import {
8
+ checkpointFormat, invalidCheckpoint, journalEventSchema, lockSchema, manifestSchema, verifyRecord,
9
+ type JournalEvent, type Manifest,
10
+ } from './records'
11
+
12
+ /** Load an inactive source run's validated events without modifying its files.
13
+ * publishInitialRun calls this while holding the target lock, then copies the events
14
+ * into the new journal. A mismatched run ID or invalid required record rejects as
15
+ * WORKFLOW_CHECKPOINT_INVALID. Mismatched name or revision rejects as WORKFLOW_INCOMPATIBLE_RUN.
16
+ * A valid lock without evidence of a dead local writer rejects as WORKFLOW_SOURCE_ACTIVE.
17
+ * Completed and incomplete sources must have a result matching the manifest digest.
18
+ * Other filesystem errors propagate for storage error normalization.
19
+ * The caller supplies a separate target directory. This check acquires no source lock. */
20
+ export async function loadSourceJournal(directory: string, identity: SourceIdentity): Promise<JournalEvent[]> {
21
+ await regularDirectory(directory)
22
+ await assertInactive(directory)
23
+ const manifest = verifyRecord(manifestSchema, await requiredJson(join(directory, checkpointFormat.manifest)))
24
+ assertCompatibleIdentity(manifest.identity, identity)
25
+ const raw = await requiredJson(join(directory, checkpointFormat.journal))
26
+ const parsed = journalEventSchema.array().safeParse(raw)
27
+ if (!parsed.success) invalidCheckpoint()
28
+ if (manifest.status === 'completed' || manifest.status === 'incomplete') {
29
+ if (digest(await requiredJson(join(directory, checkpointFormat.result))) !== manifest.resultDigest) invalidCheckpoint()
30
+ }
31
+ return parsed.data
32
+ }
33
+
34
+ type SourceIdentity = Pick<Manifest['identity'], 'name' | 'revision' | 'runId'>
35
+
36
+ /** Check that the manifest belongs to the selected run before checking workflow compatibility.
37
+ * A misplaced manifest is checkpoint corruption even if its workflow name or revision differs. */
38
+ function assertCompatibleIdentity(actual: SourceIdentity, expected: SourceIdentity): void {
39
+ if (actual.runId !== expected.runId) invalidCheckpoint()
40
+ if (actual.name !== expected.name || actual.revision !== expected.revision) {
41
+ throw new HarnessSdkError('WORKFLOW_INCOMPATIBLE_RUN')
42
+ }
43
+ }
44
+
45
+ /** Map missing required files and symlink races reported as ELOOP to invalid checkpoints.
46
+ * Other failures reach openFileRun for storage error normalization. */
47
+ async function requiredJson(path: string) {
48
+ try { return await readJson(path) }
49
+ catch (cause) {
50
+ if (missing(cause) || (cause as NodeJS.ErrnoException)?.code === 'ELOOP') invalidCheckpoint()
51
+ throw cause
52
+ }
53
+ }
54
+
55
+ /** Permit an absent writer lock or a validated local claim whose PID no longer exists.
56
+ * An invalid lock rejects through verifyRecord. A valid lock that fails the liveness
57
+ * check blocks loadSourceJournal before it reads the manifest. */
58
+ async function assertInactive(directory: string): Promise<void> {
59
+ let lock
60
+ try {
61
+ lock = verifyRecord(lockSchema, await readJson(join(directory, checkpointFormat.lock)))
62
+ } catch (cause) {
63
+ if (missing(cause)) return
64
+ throw cause
65
+ }
66
+ if (!localWriterExited(lock)) throw new HarnessSdkError('WORKFLOW_SOURCE_ACTIVE')
67
+ }
68
+
69
+ /** Only a local PID probe returning ESRCH proves the recorded process is gone.
70
+ * A foreign host, live or reused PID, or refused probe leaves inactivity unproven.
71
+ * This evidence is limited to the writer process and cannot confirm backend termination. */
72
+ function localWriterExited(lock: { hostname: string; pid: number }): boolean {
73
+ if (lock.hostname !== hostname()) return false
74
+ try {
75
+ process.kill(lock.pid, 0)
76
+ return false
77
+ } catch (cause) {
78
+ return (cause as NodeJS.ErrnoException).code === 'ESRCH'
79
+ }
80
+ }
81
+
82
+ /** Reject a symlink or other non-directory source before loadSourceJournal reads its lock.
83
+ * Filesystem errors propagate to openFileRun for normalization. */
84
+ async function regularDirectory(path: string): Promise<void> {
85
+ if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
86
+ }
87
+
88
+ /** Test for ENOENT so replay can allow an absent writer lock and reject absent required files. */
89
+ function missing(cause: unknown): boolean {
90
+ return (cause as NodeJS.ErrnoException)?.code === 'ENOENT'
91
+ }
@@ -0,0 +1,286 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { hostname } from 'node:os'
3
+ import { lstat, mkdir, open, readdir, realpath, unlink, type FileHandle } from 'node:fs/promises'
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
5
+ import { HarnessSdkError } from '@anureo/sdk'
6
+ import type { WorkflowOptions } from '../workflow-types'
7
+ import { atomicPublish, storageError, syncDirectory } from './checkpoint-files'
8
+ import { canonicalJson, digest, jsonCopy, type JsonValue } from './json'
9
+ import { AgentJournal } from './journal'
10
+ import { checkpointFormat, invalidCheckpoint, record, runIdSchema, type Manifest, type StoredFailure } from './records'
11
+ import { loadSourceJournal } from './replay'
12
+
13
+ /** Internal identity saved before workflow enters its body. */
14
+ export interface RunIdentity {
15
+ /** Validated basename of the run within directory. */
16
+ runId: string
17
+ /** Canonical parent containing the run's subdirectory. */
18
+ directory: string
19
+ /** Workflow name used to match a compatible source run. */
20
+ name: string
21
+ /** Application revision used to match a compatible source run. */
22
+ revision: string
23
+ /** Isolated persistence snapshot. The body receives its own frozen copy from prepareRun. */
24
+ input: JsonValue
25
+ }
26
+
27
+ /** Internal storage ownership returned to workflow. Drain agent work before finish or abort,
28
+ * and always await close in finally. The handle serializes finish and abort. AgentJournal
29
+ * serializes its own appends. */
30
+ export interface RunHandle {
31
+ /** Provides the canonical storage directory for workflow's error details. */
32
+ readonly identity: RunIdentity
33
+ /** Installed by completeRun as the journal for agent calls in the body. */
34
+ readonly journal: AgentJournal
35
+ /** Publish result.json before the terminal manifest and resolve after both publications.
36
+ * A rejection may leave a result or manifest already replaced. A queued call that starts
37
+ * after closure rejects with WORKFLOW_CLOSED. */
38
+ finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void>
39
+ /** Publish a failed manifest and keep any earlier result file and the writer lock.
40
+ * Publication failures reject, as does a queued call that starts after closure. */
41
+ abort(failure: StoredFailure): Promise<void>
42
+ /** Wait for queued manifests, then release the owned writer lock and close its descriptor.
43
+ * Lock-release failures reject. Sequential repeats are no-ops, including after rejection.
44
+ * Callers must finish scheduling work before closure. */
45
+ close(): Promise<void>
46
+ }
47
+
48
+ /** Create a fresh file-backed run for workflow, publishing its journal and running manifest
49
+ * before returning. An optional inactive source supplies replay events, never the final result.
50
+ * The returned handle owns the writer lock and must be closed after registered agent work drains.
51
+ * SDK errors propagate unless lock rollback fails. Rollback failures and otherwise unclassified
52
+ * I/O failures reject as WORKFLOW_STORAGE_FAILED. If publication left run files behind,
53
+ * a later attempt on the same target rejects with WORKFLOW_RUN_EXISTS. */
54
+ export async function openFileRun(options: FileRunOptions): Promise<RunHandle> {
55
+ validateRunOptions(options)
56
+ try {
57
+ const prepared = await prepareRunStorage(options)
58
+ return await initializeLockedRun({ options, prepared })
59
+ } catch (cause) { throw storageError(cause) }
60
+ }
61
+
62
+ type FileRunOptions = WorkflowOptions<JsonValue> & { runId: string }
63
+ type SourceRun = { directory: string; runId: string }
64
+
65
+ /** Storage coordinates prepared before claiming writer ownership. */
66
+ interface PreparedRun {
67
+ directory: string
68
+ path: string
69
+ input: JsonValue
70
+ source: SourceRun | null
71
+ }
72
+
73
+ /** Own the open lock descriptor and serialize manifest transitions until workflow releases it. */
74
+ class FileRunHandle implements RunHandle {
75
+ /** Take ownership only after initial publication; initialization retains rollback responsibility. */
76
+ constructor({ identity, path, lock, manifest, journal }: {
77
+ identity: RunIdentity
78
+ path: string
79
+ lock: FileHandle
80
+ manifest: Manifest
81
+ journal: AgentJournal
82
+ }) {
83
+ this.identity = identity
84
+ this.path = path
85
+ this.lock = lock
86
+ this.manifest = manifest
87
+ this.journal = journal
88
+ }
89
+
90
+ /** completeRun awaits both publications before returning the body result to workflow.
91
+ * The manifest comes last so it refers to an already published result. */
92
+ async finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void> {
93
+ await this.updateManifest(async () => {
94
+ await atomicPublish(join(this.path, checkpointFormat.result), result)
95
+ await this.publishManifest({ status, resultDigest: digest(result), failure: null })
96
+ })
97
+ }
98
+
99
+ /** abortRun awaits this after draining. Replay treats the failed manifest as authoritative
100
+ * even if finish left an earlier result file. */
101
+ async abort(failure: StoredFailure): Promise<void> {
102
+ await this.updateManifest(async () => {
103
+ await this.publishManifest({ status: 'failed', resultDigest: null, failure })
104
+ })
105
+ }
106
+
107
+ /** workflow awaits this in finally and records any rejection as a storage failure.
108
+ * A failed publication already reached finish or abort, so proceed with lock release. */
109
+ async close(): Promise<void> {
110
+ if (this.closed) return
111
+ try {
112
+ await this.manifestQueue.catch(() => {})
113
+ await releaseLock(join(this.path, checkpointFormat.lock), this.lock)
114
+ } catch (cause) {
115
+ throw storageError(cause)
116
+ } finally {
117
+ this.closed = true
118
+ }
119
+ }
120
+
121
+ readonly identity: RunIdentity
122
+ readonly journal: AgentJournal
123
+
124
+ private closed = false
125
+ private manifestQueue: Promise<void> = Promise.resolve()
126
+ private readonly path: string
127
+ private readonly lock: FileHandle
128
+ private manifest: Manifest
129
+
130
+ /** Run finish/abort's publication callback in order, checking closure when it actually starts.
131
+ * A rejected predecessor still permits abort publication. Non-SDK failures are normalized. */
132
+ private updateManifest(update: () => Promise<void>): Promise<void> {
133
+ const next = this.manifestQueue.catch(() => {}).then(async () => {
134
+ if (this.closed) throw new HarnessSdkError('WORKFLOW_CLOSED')
135
+ try { await update() } catch (cause) { throw storageError(cause) }
136
+ })
137
+ this.manifestQueue = next
138
+ return next
139
+ }
140
+
141
+ /** Recompute the digest from payload only for every terminal transition, then publish it.
142
+ * Keep the in-memory transition even if publication rejects, as abort may follow a failed finish. */
143
+ private async publishManifest(update: Pick<Manifest, 'status' | 'resultDigest' | 'failure'>): Promise<void> {
144
+ const { recordDigest: _, ...payload } = this.manifest
145
+ this.manifest = record({ ...payload, ...update })
146
+ await atomicPublish(join(this.path, checkpointFormat.manifest), this.manifest)
147
+ }
148
+ }
149
+
150
+ /** Throw INVALID_PARAMS for malformed target identity before copying input or touching storage. */
151
+ function validateRunOptions(options: FileRunOptions): void {
152
+ if (!runIdSchema.safeParse(options.runId).success || typeof options.name !== 'string' || !options.name
153
+ || typeof options.revision !== 'string' || !options.revision || typeof options.directory !== 'string' || !options.directory) {
154
+ throw new HarnessSdkError('INVALID_PARAMS')
155
+ }
156
+ }
157
+
158
+ /** Snapshot input, resolve parent/source paths, and create a real target directory before locking.
159
+ * Flush the parent when creating the target. Initialization checks existing contents under the lock. */
160
+ async function prepareRunStorage(options: FileRunOptions): Promise<PreparedRun> {
161
+ const input = jsonCopy(options.input)
162
+ await mkdir(resolve(options.directory), { recursive: true, mode: 0o700 })
163
+ const directory = await realpath(resolve(options.directory))
164
+ const path = join(directory, options.runId)
165
+ const source = await resolveSourceRun({ resumeFrom: options.resumeFrom, directory, path })
166
+ try {
167
+ await mkdir(path, { mode: 0o700 })
168
+ await syncDirectory(directory)
169
+ } catch (cause) {
170
+ if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause
171
+ }
172
+ if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
173
+ return { directory, path, input, source }
174
+ }
175
+
176
+ /** Resolve optional replay coordinates before target creation so overlapping source/target trees
177
+ * reject before a writer claim. Omission selects fresh execution. A string uses the target's
178
+ * canonical parent, while an object supplies its own parent to resolve. */
179
+ async function resolveSourceRun({ resumeFrom, directory, path }: {
180
+ resumeFrom: FileRunOptions['resumeFrom']
181
+ directory: string
182
+ path: string
183
+ }): Promise<SourceRun | null> {
184
+ if (resumeFrom === undefined) return null
185
+ const reference = typeof resumeFrom === 'string' ? { directory, runId: resumeFrom } : resumeFrom
186
+ if (!reference || !runIdSchema.safeParse(reference.runId).success || typeof reference.directory !== 'string') {
187
+ throw new HarnessSdkError('INVALID_PARAMS')
188
+ }
189
+ const source = { directory: await realpath(resolve(reference.directory)), runId: reference.runId }
190
+ if (overlaps(path, join(source.directory, source.runId))) throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS')
191
+ return source
192
+ }
193
+
194
+ /** Exclusively claim and initialize the lock before inspecting target contents or source records.
195
+ * Transfer ownership only on successful publication; rollback also covers partial lock writes.
196
+ * Cleanup failure takes precedence as WORKFLOW_STORAGE_FAILED; other failures reach openFileRun. */
197
+ async function initializeLockedRun({ options, prepared }: {
198
+ options: FileRunOptions
199
+ prepared: PreparedRun
200
+ }): Promise<RunHandle> {
201
+ const lockPath = join(prepared.path, checkpointFormat.lock)
202
+ const lock = await open(lockPath, 'wx', 0o600).catch(cause => {
203
+ if ((cause as NodeJS.ErrnoException).code === 'EEXIST') throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
204
+ throw cause
205
+ })
206
+ try {
207
+ await writeWriterClaim(lock)
208
+ if ((await readdir(prepared.path)).some(name => name !== checkpointFormat.lock)) {
209
+ throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
210
+ }
211
+ return await publishInitialRun({ options, prepared, lock })
212
+ } catch (cause) {
213
+ try { await releaseLock(lockPath, lock) }
214
+ catch { throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED') }
215
+ throw cause
216
+ }
217
+ }
218
+
219
+ /** Write and flush the claim on the exclusively opened descriptor. Replay validates this
220
+ * record before probing its writer, and initializeLockedRun owns rollback on rejection. */
221
+ async function writeWriterClaim(lock: FileHandle): Promise<void> {
222
+ const claim = record({
223
+ checkpointFormatVersion: checkpointFormat.version,
224
+ token: randomUUID(),
225
+ hostname: hostname(),
226
+ pid: process.pid,
227
+ createdAt: new Date().toISOString(),
228
+ })
229
+ await lock.writeFile(`${canonicalJson(claim)}\n`)
230
+ await lock.sync()
231
+ }
232
+
233
+ /** Validate replay under the target lock, publish a self-contained journal before its manifest,
234
+ * then hand the descriptor to FileRunHandle. Failures leave lock cleanup to initializeLockedRun. */
235
+ async function publishInitialRun({ options, prepared, lock }: {
236
+ options: FileRunOptions
237
+ prepared: PreparedRun
238
+ lock: FileHandle
239
+ }): Promise<RunHandle> {
240
+ const { directory, path, input, source } = prepared
241
+ const inherited = source
242
+ ? await loadSourceJournal(join(source.directory, source.runId), {
243
+ name: options.name, revision: options.revision, runId: source.runId,
244
+ })
245
+ : []
246
+ const journalPath = join(path, checkpointFormat.journal)
247
+ const journal = new AgentJournal(journalPath, inherited)
248
+ await atomicPublish(journalPath, [...inherited])
249
+ const identity = { runId: options.runId, directory, name: options.name, revision: options.revision, input }
250
+ const manifest: Manifest = record({
251
+ checkpointFormatVersion: checkpointFormat.version,
252
+ identity,
253
+ createdAt: new Date().toISOString(),
254
+ resumedFrom: source,
255
+ status: 'running',
256
+ resultDigest: null,
257
+ failure: null,
258
+ })
259
+ await atomicPublish(join(path, checkpointFormat.manifest), manifest)
260
+ return new FileRunHandle({ identity, path, lock, manifest, journal })
261
+ }
262
+
263
+ /** Detect equal or nested run trees in either direction. resolveSourceRun uses canonical
264
+ * parent directories so writes cannot overlap the selected source tree. */
265
+ function overlaps(a: string, b: string): boolean {
266
+ const inside = (parent: string, child: string) => {
267
+ const path = relative(parent, child)
268
+ return !path || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path))
269
+ }
270
+ return inside(a, b) || inside(b, a)
271
+ }
272
+
273
+ /** Compare the on-disk entry with the held descriptor before unlinking, so rollback also works
274
+ * for a partially written lock. Flush the parent after unlinking and always close the descriptor.
275
+ * An observed inode or file kind mismatch rejects as WORKFLOW_LOCK_OWNERSHIP_LOST. */
276
+ async function releaseLock(path: string, handle: FileHandle): Promise<void> {
277
+ try {
278
+ const held = await handle.stat()
279
+ const actual = await lstat(path)
280
+ if (actual.dev !== held.dev || actual.ino !== held.ino || !actual.isFile()) {
281
+ throw new HarnessSdkError('WORKFLOW_LOCK_OWNERSHIP_LOST')
282
+ }
283
+ await unlink(path)
284
+ await syncDirectory(dirname(path))
285
+ } finally { await handle.close() }
286
+ }