@anureo/workflow 0.3.0 → 0.3.2

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 +18 -16
  3. package/src/agent-adapters.test.ts +121 -0
  4. package/src/agent-execution.ts +220 -0
  5. package/src/agent.test.ts +470 -0
  6. package/src/agent.ts +136 -0
  7. package/src/fixtures/workflow-crash.ts +69 -0
  8. package/src/index.ts +9 -0
  9. package/src/output-schema.test.ts +159 -0
  10. package/src/output-schema.ts +237 -0
  11. package/src/parallel.test.ts +96 -0
  12. package/src/parallel.ts +33 -0
  13. package/src/persistence/checkpoint-files.ts +83 -0
  14. package/src/persistence/journal.ts +132 -0
  15. package/src/persistence/json.ts +83 -0
  16. package/src/persistence/records.ts +103 -0
  17. package/src/persistence/replay.ts +93 -0
  18. package/src/persistence/store.ts +315 -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 +131 -0
  23. package/src/workflow-types.ts +38 -0
  24. package/src/workflow.test.ts +503 -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,83 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { constants } from 'node:fs'
3
+ import { lstat, open, rename, unlink } from 'node:fs/promises'
4
+ import { dirname } from 'node:path'
5
+ import { HarnessSdkError } from '@anureo/sdk'
6
+ import { canonicalJson, type JsonValue } from './json'
7
+ import { invalidCheckpoint } from './records'
8
+
9
+ /** Flush directory-entry changes and close the directory handle. I/O failures reject.
10
+ * On Windows this resolves without a flush because Node does not provide directory fsync. */
11
+ export async function syncDirectory(path: string): Promise<void> {
12
+ if (process.platform === 'win32') return
13
+ const directory = await open(path, 'r')
14
+ try { await directory.sync() } finally { await directory.close() }
15
+ }
16
+
17
+ /** Publish one complete checkpoint by renaming a flushed sibling temporary file, then flush
18
+ * its parent directory where supported. FileRunHandle and AgentJournal serialize their own
19
+ * writes because a rename alone cannot prevent an older snapshot from overwriting a newer one.
20
+ * The caller creates the parent. Invalid JSON rejects before any file I/O.
21
+ * The optional callback observes replacement before the directory flush, which can still fail.
22
+ * If temporary-file cleanup fails, the rejection includes both failures. */
23
+ export async function atomicPublish(path: string, value: unknown, onReplace?: () => void): Promise<void> {
24
+ const text = `${canonicalJson(value)}\n`
25
+ const temporary = `${path}.${randomUUID()}.tmp`
26
+ // An exclusive open establishes ownership. Cleanup must leave an existing file alone.
27
+ const file = await open(temporary, 'wx', 0o600)
28
+ try {
29
+ try {
30
+ await file.writeFile(text, 'utf8')
31
+ await file.sync()
32
+ } finally {
33
+ await file.close()
34
+ }
35
+ await rename(temporary, path)
36
+ } catch (cause) {
37
+ try {
38
+ await unlink(temporary)
39
+ } catch (cleanup) {
40
+ throw new AggregateError([cause, cleanup], 'Atomic publish failed')
41
+ }
42
+ throw cause
43
+ }
44
+ onReplace?.()
45
+ await syncDirectory(dirname(path))
46
+ }
47
+
48
+ /** Read strict JSON from a regular file and always close its descriptor. Check the final
49
+ * component with lstat and verify the opened inode to catch replacement during open.
50
+ * Invalid content or file kind rejects as WORKFLOW_CHECKPOINT_INVALID. Replay classifies
51
+ * filesystem failures and validates the returned value against the checkpoint schema. */
52
+ export async function readJson(path: string): Promise<JsonValue> {
53
+ const before = await lstat(path)
54
+ if (!before.isFile()) return invalidCheckpoint()
55
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
56
+ try {
57
+ const current = await file.stat()
58
+ if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino) return invalidCheckpoint()
59
+ return parseCheckpointJson(await file.readFile('utf8'))
60
+ } finally {
61
+ await file.close()
62
+ }
63
+ }
64
+
65
+ /** Normalize failures caught by openFileRun, FileRunHandle and AgentJournal.append.
66
+ * Preserve SDK errors by identity; report other failures as WORKFLOW_STORAGE_FAILED
67
+ * without passing filesystem diagnostics to workflow consumers. */
68
+ export function storageError(cause: unknown): HarnessSdkError {
69
+ if (cause instanceof HarnessSdkError) return cause
70
+ return new HarnessSdkError('WORKFLOW_STORAGE_FAILED')
71
+ }
72
+
73
+ /** Map malformed or nonrepresentable JSON to checkpoint corruption before schema validation.
74
+ * JSON.parse alone accepts number literals that overflow to Infinity. */
75
+ function parseCheckpointJson(text: string): JsonValue {
76
+ try {
77
+ const value = JSON.parse(text) as JsonValue
78
+ canonicalJson(value)
79
+ return value
80
+ } catch {
81
+ return invalidCheckpoint()
82
+ }
83
+ }
@@ -0,0 +1,132 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { atomicPublish, storageError } from './checkpoint-files'
3
+ import { canonicalJson, digest, jsonCopy, type JsonValue } from './json'
4
+ import { journalKeyPrefix, type JournalEvent, type UnknownFailure } 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.sourceIndex = indexJournal(this.events)
23
+ if (this.sourceIndex.results.size || this.sourceIndex.started.size) this.replayPrefix = new Set()
24
+ this.publishedCount = this.events.length
25
+ }
26
+
27
+ /** Advance the chain synchronously before memoizedAgent's first await, including cache hits.
28
+ * Options must be strict JSON. If canonicalJson throws, the chain stays unchanged. */
29
+ nextKey(prompt: string, canonicalOptions: JsonValue): string {
30
+ const key = `${journalKeyPrefix}${createHash('sha256')
31
+ .update(this.previousKey).update('\0')
32
+ .update(JSON.stringify(prompt)).update('\0')
33
+ .update(canonicalJson(canonicalOptions)).digest('hex')}`
34
+ this.previousKey = key
35
+ return key
36
+ }
37
+
38
+ /** Decide how memoizedAgent should handle the reserved key. A replay carries an isolated
39
+ * result for the caller to validate. A miss closes result reuse unless the source left this
40
+ * key at started. Even after reuse closes, an exact-key failure with an unknown outcome
41
+ * requires reconciliation before memoizedAgent can dispatch. */
42
+ resolveCall(key: string): JournalDecision {
43
+ if (this.reuseOpen) {
44
+ const result = this.sourceIndex.results.get(key)
45
+ if (result !== undefined) {
46
+ this.replayPrefix?.add(key)
47
+ return { action: 'replay', result: jsonCopy(result) }
48
+ }
49
+ if (this.sourceIndex.started.has(key)) this.replayPrefix?.add(key)
50
+ else this.reuseOpen = false
51
+ }
52
+ return this.sourceIndex.uncertain.has(key) ? { action: 'reconcile' } : { action: 'execute' }
53
+ }
54
+
55
+ /** Queue a copied event and await serialized atomic publication. Replay decisions use the
56
+ * index built from inherited events. The first start after divergence records the surviving
57
+ * replay prefix in the same publication.
58
+ * On publication failure the event stays in the in-memory snapshot. Non-SDK I/O failures
59
+ * reject as WORKFLOW_STORAGE_FAILED, which RunState records to stop later dispatch. */
60
+ async append(event: JournalEvent): Promise<void> {
61
+ if (event.type === 'started' && !this.reuseOpen && this.replayPrefix) {
62
+ event = { ...event, retainReplayKeys: [...this.replayPrefix] }
63
+ this.replayPrefix = undefined
64
+ }
65
+ this.events.push(jsonCopy(event))
66
+ // Concurrent callers must not race atomic renames: an earlier snapshot
67
+ // landing last would silently drop later events from the published file.
68
+ const publish = this.publishQueue.catch(() => {}).then(async () => {
69
+ try {
70
+ const count = this.events.length
71
+ await atomicPublish(this.path, this.events, () => { this.publishedCount = count })
72
+ } catch (cause) {
73
+ throw storageError(cause)
74
+ }
75
+ })
76
+ this.publishQueue = publish
77
+ await publish
78
+ }
79
+
80
+ /** After agent work drains, bind the manifest to the last installed snapshot and carry
81
+ * uncertain failures that never reached it. */
82
+ checkpoint(): { journalDigest: string; unpublishedUnknownFailures: UnknownFailure[] } {
83
+ return {
84
+ journalDigest: digest(this.events.slice(0, this.publishedCount)),
85
+ unpublishedUnknownFailures: this.events.slice(this.publishedCount).filter(
86
+ (event): event is UnknownFailure => event.type === 'failed' && event.outcomeUnknown,
87
+ ),
88
+ }
89
+ }
90
+
91
+ private readonly events: JournalEvent[] = []
92
+ private readonly sourceIndex: JournalIndex
93
+ private publishedCount: number
94
+ private previousKey = ''
95
+ private reuseOpen = true
96
+ private replayPrefix?: Set<string>
97
+ private publishQueue: Promise<void> = Promise.resolve()
98
+ }
99
+
100
+ /** Result handling stays with memoizedAgent, which owns validation, dispatch and rejection. */
101
+ type JournalDecision = { action: 'replay'; result: JsonValue } | { action: 'execute' | 'reconcile' }
102
+
103
+ /** Replay lookup built from validated events. A key left at started can be respawned. */
104
+ interface JournalIndex {
105
+ results: Map<string, JsonValue>
106
+ started: Set<string>
107
+ uncertain: Set<string>
108
+ }
109
+
110
+ /** Fold validated events in file order. Clear the earlier entry for each key so a newer
111
+ * start or failure supersedes any older result when AgentJournal initializes its replay lookup. */
112
+ function indexJournal(events: readonly JournalEvent[]): JournalIndex {
113
+ const index: JournalIndex = { results: new Map(), started: new Set(), uncertain: new Set() }
114
+ for (const event of events) {
115
+ index.started.delete(event.key)
116
+ index.uncertain.delete(event.key)
117
+ index.results.delete(event.key)
118
+ if (event.type === 'started') {
119
+ if (event.retainReplayKeys) {
120
+ const retained = new Set(event.retainReplayKeys)
121
+ for (const key of index.results.keys()) if (!retained.has(key)) index.results.delete(key)
122
+ for (const key of index.started) if (!retained.has(key)) index.started.delete(key)
123
+ }
124
+ index.started.add(event.key)
125
+ } else if (event.type === 'result') {
126
+ index.results.set(event.key, event.result)
127
+ } else if (event.outcomeUnknown) {
128
+ index.uncertain.add(event.key)
129
+ }
130
+ }
131
+ return index
132
+ }
@@ -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,103 @@
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: 3,
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
+ /** 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
+ const jsonSchema: z.ZodType<JsonValue> = z.lazy(() => z.union([
61
+ z.null(), z.boolean(), z.number().finite(), z.string(), z.array(jsonSchema), z.record(z.string(), jsonSchema),
62
+ ]))
63
+ const identitySchema = z.strictObject({
64
+ runId: runIdSchema, directory: z.string(), name: z.string().min(1), revision: z.string().min(1), input: jsonSchema,
65
+ })
66
+
67
+ /** Versioned chained SHA-256 identity for an agent call, independent of its execution UUID. */
68
+ export const journalKeyPrefix = 'v2:'
69
+ const journalKeySchema = z.string().refine(key =>
70
+ key.startsWith(journalKeyPrefix) && hashSchema.safeParse(key.slice(journalKeyPrefix.length)).success)
71
+ const failedEventSchema = z.strictObject({ type: z.literal('failed'), key: journalKeySchema, agentId: uuidSchema,
72
+ code: z.string().min(1), outcomeUnknown: z.boolean() })
73
+
74
+ /** Strict persisted events. Replay validates the entire array before handing it to AgentJournal.
75
+ * The chained key determines reuse. The execution UUID is recorded as agentId. */
76
+ export const journalEventSchema = z.discriminatedUnion('type', [
77
+ z.strictObject({ type: z.literal('started'), key: journalKeySchema, agentId: uuidSchema,
78
+ retainReplayKeys: journalKeySchema.array().optional() }),
79
+ z.strictObject({ type: z.literal('result'), key: journalKeySchema, agentId: uuidSchema, result: jsonSchema }),
80
+ failedEventSchema,
81
+ ])
82
+
83
+ const unknownFailureSchema = failedEventSchema.extend({ outcomeUnknown: z.literal(true) })
84
+ export type UnknownFailure = z.output<typeof unknownFailureSchema>
85
+
86
+ /** Persist only safe failure metadata; diagnostic messages and details stay out of manifests. */
87
+ const failureSchema = z.strictObject({
88
+ code: z.string(),
89
+ retryable: z.boolean(),
90
+ outcomeUnknown: z.boolean(),
91
+ cleanupFailed: z.boolean(),
92
+ unpublishedUnknownFailures: unknownFailureSchema.array().optional(),
93
+ })
94
+
95
+ /** Replay verifies the manifest digest and the journal of every terminal run. */
96
+ export const manifestSchema = z.strictObject({
97
+ checkpointFormatVersion: z.literal(checkpointFormat.version),
98
+ identity: identitySchema, createdAt: z.string().datetime(),
99
+ resumedFrom: z.strictObject({ directory: z.string(), runId: runIdSchema }).nullable(),
100
+ status: z.enum(['running', 'completed', 'incomplete', 'failed']),
101
+ journalDigest: hashSchema.nullable(), resultDigest: hashSchema.nullable(),
102
+ failure: failureSchema.nullable(), recordDigest: hashSchema,
103
+ })
@@ -0,0 +1,93 @@
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
+ * Terminal sources must have a journal matching the manifest digest. Completed and incomplete
18
+ * sources must also have a matching result.
19
+ * Other filesystem errors propagate for storage error normalization.
20
+ * The caller supplies a separate target directory. This check acquires no source lock. */
21
+ export async function loadSourceJournal(directory: string, identity: SourceIdentity): Promise<JournalEvent[]> {
22
+ await regularDirectory(directory)
23
+ await assertInactive(directory)
24
+ const manifest = verifyRecord(manifestSchema, await requiredJson(join(directory, checkpointFormat.manifest)))
25
+ assertCompatibleIdentity(manifest.identity, identity)
26
+ const raw = await requiredJson(join(directory, checkpointFormat.journal))
27
+ if (manifest.status !== 'running' && digest(raw) !== manifest.journalDigest) invalidCheckpoint()
28
+ const parsed = journalEventSchema.array().safeParse(raw)
29
+ if (!parsed.success) invalidCheckpoint()
30
+ if (manifest.status === 'completed' || manifest.status === 'incomplete') {
31
+ if (digest(await requiredJson(join(directory, checkpointFormat.result))) !== manifest.resultDigest) invalidCheckpoint()
32
+ }
33
+ return parsed.data.concat(manifest.failure?.unpublishedUnknownFailures ?? [])
34
+ }
35
+
36
+ type SourceIdentity = Pick<Manifest['identity'], 'name' | 'revision' | 'runId'>
37
+
38
+ /** Check that the manifest belongs to the selected run before checking workflow compatibility.
39
+ * A misplaced manifest is checkpoint corruption even if its workflow name or revision differs. */
40
+ function assertCompatibleIdentity(actual: SourceIdentity, expected: SourceIdentity): void {
41
+ if (actual.runId !== expected.runId) invalidCheckpoint()
42
+ if (actual.name !== expected.name || actual.revision !== expected.revision) {
43
+ throw new HarnessSdkError('WORKFLOW_INCOMPATIBLE_RUN')
44
+ }
45
+ }
46
+
47
+ /** Map missing required files and symlink races reported as ELOOP to invalid checkpoints.
48
+ * Other failures reach openFileRun for storage error normalization. */
49
+ async function requiredJson(path: string) {
50
+ try { return await readJson(path) }
51
+ catch (cause) {
52
+ if (missing(cause) || (cause as NodeJS.ErrnoException)?.code === 'ELOOP') invalidCheckpoint()
53
+ throw cause
54
+ }
55
+ }
56
+
57
+ /** Permit an absent writer lock or a validated local claim whose PID no longer exists.
58
+ * An invalid lock rejects through verifyRecord. A valid lock that fails the liveness
59
+ * check blocks loadSourceJournal before it reads the manifest. */
60
+ async function assertInactive(directory: string): Promise<void> {
61
+ let lock
62
+ try {
63
+ lock = verifyRecord(lockSchema, await readJson(join(directory, checkpointFormat.lock)))
64
+ } catch (cause) {
65
+ if (missing(cause)) return
66
+ throw cause
67
+ }
68
+ if (!localWriterExited(lock)) throw new HarnessSdkError('WORKFLOW_SOURCE_ACTIVE')
69
+ }
70
+
71
+ /** Only a local PID probe returning ESRCH proves the recorded process is gone.
72
+ * A foreign host, live or reused PID, or refused probe leaves inactivity unproven.
73
+ * This evidence is limited to the writer process and cannot confirm backend termination. */
74
+ function localWriterExited(lock: { hostname: string; pid: number }): boolean {
75
+ if (lock.hostname !== hostname()) return false
76
+ try {
77
+ process.kill(lock.pid, 0)
78
+ return false
79
+ } catch (cause) {
80
+ return (cause as NodeJS.ErrnoException).code === 'ESRCH'
81
+ }
82
+ }
83
+
84
+ /** Reject a symlink or other non-directory source before loadSourceJournal reads its lock.
85
+ * Filesystem errors propagate to openFileRun for normalization. */
86
+ async function regularDirectory(path: string): Promise<void> {
87
+ if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
88
+ }
89
+
90
+ /** Test for ENOENT so replay can allow an absent writer lock and reject absent required files. */
91
+ function missing(cause: unknown): boolean {
92
+ return (cause as NodeJS.ErrnoException)?.code === 'ENOENT'
93
+ }