@anureo/workflow 0.3.4 → 0.3.8

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.
@@ -1,53 +1,19 @@
1
- import { createHash, randomUUID } from 'node:crypto'
2
- import { z } from 'zod'
3
- import { HarnessSdkError } from '@anureo/sdk'
4
- import { atomicPublish } from './atomic'
5
- import { canonicalJson, jsonCopy, type JsonValue } from './json'
6
- import { journalEventSchema } from './records'
7
-
8
- export type JournalEvent = z.output<typeof journalEventSchema>
9
-
10
- export interface PriorFailure {
11
- code: string
12
- outcomeUnknown: boolean
13
- }
14
-
15
- /** Last result wins per key; started without terminal marks a respawnable call. */
16
- export interface JournalIndex {
17
- results: Map<string, JsonValue>
18
- started: Set<string>
19
- failures: Map<string, PriorFailure>
20
- inputHookRevisions: Map<string, string | undefined>
21
- }
22
-
23
- export function indexJournal(events: readonly JournalEvent[]): JournalIndex {
24
- const index: JournalIndex = { results: new Map(), started: new Set(), failures: new Map(), inputHookRevisions: new Map() }
25
- for (const event of events) {
26
- index.started.delete(event.key)
27
- index.failures.delete(event.key)
28
- index.results.delete(event.key)
29
- if (event.type === 'started') {
30
- index.started.add(event.key)
31
- index.inputHookRevisions.set(event.key, event.inputHookRevision)
32
- }
33
- else if (event.type === 'failed') index.failures.set(event.key, { code: event.code, outcomeUnknown: event.outcomeUnknown })
34
- else index.results.set(event.key, event.result)
35
- }
36
- return index
37
- }
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'
38
5
 
39
6
  /**
40
- * Appended agent-call journal. Cache identity is a chain: each call's key hashes
41
- * the previous key, the prompt, and the canonical semantic options, so any
42
- * upstream change invalidates the whole downstream prefix automatically.
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.
43
14
  */
44
15
  export class AgentJournal {
45
- private readonly events: JournalEvent[] = []
46
- private readonly index: JournalIndex
47
- private previousKey = ''
48
- private reuseOpen = true
49
- private publishQueue: Promise<void> = Promise.resolve()
50
-
16
+ /** Copy validated source events into a new run's journal; construction performs no file I/O. */
51
17
  constructor(
52
18
  private readonly path: string,
53
19
  source: readonly JournalEvent[],
@@ -55,66 +21,116 @@ export class AgentJournal {
55
21
  private readonly persist = true,
56
22
  ) {
57
23
  this.events.push(...jsonCopy(source))
58
- this.index = indexJournal(this.events)
24
+ this.sourceIndex = indexJournal(this.events)
25
+ if (this.sourceIndex.results.size || this.sourceIndex.started.size) this.replayPrefix = new Set()
26
+ this.publishedCount = this.events.length
59
27
  }
60
28
 
29
+ /** Advance the chain synchronously before memoizedAgent's first await, including cache hits.
30
+ * Options must be strict JSON. If canonicalJson throws, the chain stays unchanged. */
61
31
  nextKey(prompt: string, canonicalOptions: JsonValue): string {
62
- const key = `v1:${createHash('sha256')
32
+ const key = `${journalKeyPrefix}${createHash('sha256')
63
33
  .update(this.previousKey).update('\0')
64
- .update(prompt).update('\0')
34
+ .update(JSON.stringify(prompt)).update('\0')
65
35
  .update(canonicalJson(canonicalOptions)).digest('hex')}`
66
36
  this.previousKey = key
67
37
  return key
68
38
  }
69
39
 
70
- /** Check the source of a matching logical call before cache lookup or execution. */
71
- resumeConflict(key: string, inputHookRevision: string | undefined): HarnessSdkError | undefined {
72
- if (this.index.failures.get(key)?.outcomeUnknown) {
73
- return new HarnessSdkError('WORKFLOW_RECONCILIATION_REQUIRED',
74
- 'A previous run left this agent call with an unknown outcome; reconcile it before resuming', false, true)
40
+ /** Decide how a journaled call should handle the reserved key. A replay carries an isolated
41
+ * result for the caller to validate. A miss closes result reuse unless the source left this
42
+ * key at started. Even after reuse closes, an exact-key failure with an unknown outcome
43
+ * requires reconciliation before the call can dispatch. */
44
+ resolveCall(key: string): JournalDecision {
45
+ if (this.reuseOpen) {
46
+ const result = this.sourceIndex.results.get(key)
47
+ if (result !== undefined) {
48
+ this.replayPrefix?.add(key)
49
+ return { action: 'replay', result: jsonCopy(result) }
50
+ }
51
+ if (this.sourceIndex.started.has(key)) this.replayPrefix?.add(key)
52
+ else this.reuseOpen = false
75
53
  }
76
- if (this.index.inputHookRevisions.has(key) && this.index.inputHookRevisions.get(key) !== inputHookRevision) {
77
- return new HarnessSdkError('WORKFLOW_INPUT_POLICY_CHANGED')
78
- }
79
- }
80
-
81
- /** Returns a copy of the cached result, or undefined when this call must execute. */
82
- resultFor(key: string): JsonValue | undefined {
83
- if (!this.reuseOpen) return undefined
84
- const result = this.index.results.get(key)
85
- return result === undefined ? undefined : jsonCopy(result)
86
- }
87
-
88
- /**
89
- * Marks a cache miss. A source entry with only `started` (crash during a call)
90
- * is a respawnable prefix: it stays reuse-eligible for later calls, matching
91
- * the "longest unchanged prefix" semantics.
92
- */
93
- beginExecution(key: string): void {
94
- if (!this.index.started.has(key)) this.reuseOpen = false
54
+ return this.sourceIndex.uncertain.has(key) ? { action: 'reconcile' } : { action: 'execute' }
95
55
  }
96
56
 
57
+ /** Queue a copied event and await serialized atomic publication. Replay decisions use the
58
+ * index built from inherited events. The first start after divergence records the surviving
59
+ * replay prefix in the same publication.
60
+ * On publication failure the event stays in the in-memory snapshot. Non-SDK I/O failures
61
+ * reject as WORKFLOW_STORAGE_FAILED, which RunState records to stop later dispatch. */
97
62
  async append(event: JournalEvent): Promise<void> {
63
+ if (event.type === 'started' && !this.reuseOpen && this.replayPrefix) {
64
+ event = { ...event, retainReplayKeys: [...this.replayPrefix] }
65
+ this.replayPrefix = undefined
66
+ }
98
67
  this.events.push(jsonCopy(event))
99
68
  if (this.persist) {
100
69
  // Concurrent callers must not race atomic renames: an earlier snapshot
101
70
  // landing last would silently drop later events from the published file.
102
71
  const publish = this.publishQueue.catch(() => {}).then(async () => {
103
- try { await atomicPublish(this.path, this.events) }
104
- catch (cause) {
105
- if (cause instanceof HarnessSdkError) throw cause
106
- throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED')
72
+ try {
73
+ const count = this.events.length
74
+ await atomicPublish(this.path, this.events, () => { this.publishedCount = count })
75
+ } catch (cause) {
76
+ throw storageError(cause)
107
77
  }
108
78
  })
109
79
  this.publishQueue = publish
110
80
  await publish
111
81
  }
112
- if (event.type === 'started') this.index.inputHookRevisions.set(event.key, event.inputHookRevision)
113
- else if (event.type === 'result') this.index.results.set(event.key, event.result)
114
- else if (event.type === 'failed') this.index.failures.set(event.key, { code: event.code, outcomeUnknown: event.outcomeUnknown })
115
82
  }
83
+
84
+ /** After agent work drains, bind the manifest to the last installed snapshot and carry
85
+ * uncertain failures that never reached it. */
86
+ checkpoint(): { journalDigest: string; unpublishedUnknownFailures: UnknownFailure[] } {
87
+ return {
88
+ journalDigest: digest(this.events.slice(0, this.publishedCount)),
89
+ unpublishedUnknownFailures: this.events.slice(this.publishedCount).filter(
90
+ (event): event is UnknownFailure => event.type === 'failed' && event.outcomeUnknown,
91
+ ),
92
+ }
93
+ }
94
+
95
+ private readonly events: JournalEvent[] = []
96
+ private readonly sourceIndex: JournalIndex
97
+ private publishedCount: number
98
+ private previousKey = ''
99
+ private reuseOpen = true
100
+ private replayPrefix?: Set<string>
101
+ private publishQueue: Promise<void> = Promise.resolve()
102
+ }
103
+
104
+ /** Result handling stays with the journaled caller, which owns validation, dispatch and rejection. */
105
+ type JournalDecision = { action: 'replay'; result: JsonValue } | { action: 'execute' | 'reconcile' }
106
+
107
+ /** Replay lookup built from validated events. A key left at started can be respawned. */
108
+ interface JournalIndex {
109
+ results: Map<string, JsonValue>
110
+ started: Set<string>
111
+ uncertain: Set<string>
116
112
  }
117
113
 
118
- export function newAgentId(): string {
119
- return randomUUID()
114
+ /** Fold validated events in file order. Clear the earlier entry for each key so a newer
115
+ * start or failure supersedes any older result when AgentJournal initializes its replay lookup. */
116
+ function indexJournal(events: readonly JournalEvent[]): JournalIndex {
117
+ const index: JournalIndex = { results: new Map(), started: new Set(), uncertain: new Set() }
118
+ for (const event of events) {
119
+ index.started.delete(event.key)
120
+ index.uncertain.delete(event.key)
121
+ index.results.delete(event.key)
122
+ if (event.type === 'started') {
123
+ if (event.retainReplayKeys) {
124
+ const retained = new Set(event.retainReplayKeys)
125
+ for (const key of index.results.keys()) if (!retained.has(key)) index.results.delete(key)
126
+ for (const key of index.started) if (!retained.has(key)) index.started.delete(key)
127
+ }
128
+ index.started.add(event.key)
129
+ } else if (event.type === 'result') {
130
+ index.results.set(event.key, event.result)
131
+ } else if (event.outcomeUnknown) {
132
+ index.uncertain.add(event.key)
133
+ }
134
+ }
135
+ return index
120
136
  }
@@ -1,49 +1,27 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { HarnessSdkError } from '@anureo/sdk'
3
3
 
4
+ /** Workflow JSON data shape. The encoder also checks runtime properties and rejects cycles. */
4
5
  export type JsonValue = null | boolean | number | string | JsonValue[] | {
5
6
  [key: string]: JsonValue
6
7
  }
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. */
8
13
  export function canonicalJson(value: unknown): string {
9
- const ancestors = new Set<object>()
10
- const invalid = (): never => { throw new HarnessSdkError('WORKFLOW_NON_JSON_VALUE') }
11
- function encode(item: unknown): string {
12
- if (item === null) return 'null'
13
- if (typeof item === 'string' || typeof item === 'boolean') return JSON.stringify(item)
14
- if (typeof item === 'number') return Number.isFinite(item) ? JSON.stringify(item) : invalid()
15
- if (typeof item !== 'object' || ancestors.has(item)) return invalid()
16
- if (Reflect.ownKeys(item).some(key => typeof key !== 'string')) return invalid()
17
- const descriptors = Object.getOwnPropertyDescriptors(item)
18
- const keys = Object.keys(descriptors)
19
- ancestors.add(item)
20
- try {
21
- if (Array.isArray(item)) {
22
- if (keys.length !== item.length + 1) return invalid()
23
- const values: string[] = []
24
- for (let i = 0; i < item.length; i++) {
25
- const field = descriptors[String(i)]
26
- if (!field || !field.enumerable || !('value' in field)) return invalid()
27
- values.push(encode(field.value))
28
- }
29
- return `[${values.join(',')}]`
30
- }
31
- const prototype = Object.getPrototypeOf(item)
32
- if (prototype !== Object.prototype && prototype !== null) return invalid()
33
- return `{${keys.sort().map(key => {
34
- const field = descriptors[key]!
35
- if (!field.enumerable || !('value' in field)) return invalid()
36
- return `${JSON.stringify(key)}:${encode(field.value)}`
37
- }).join(',')}}`
38
- } finally { ancestors.delete(item) }
39
- }
40
- return encode(value)
14
+ return encodeJson(value, new Set())
41
15
  }
42
16
 
17
+ /** Return a detached copy of JSON-compatible data. Unsupported values throw as in canonicalJson.
18
+ * Shared references are copied by value. */
43
19
  export function jsonCopy<T>(value: T): T {
44
20
  return JSON.parse(canonicalJson(value)) as T
45
21
  }
46
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. */
47
25
  export function freezeJson<T>(value: T): T {
48
26
  if (value && typeof value === 'object') {
49
27
  for (const child of Object.values(value)) freezeJson(child)
@@ -52,6 +30,54 @@ export function freezeJson<T>(value: T): T {
52
30
  return value
53
31
  }
54
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. */
55
36
  export function digest(value: unknown): string {
56
37
  return createHash('sha256').update(canonicalJson(value)).digest('hex')
57
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') }
@@ -1,50 +1,28 @@
1
- import { constants } from 'node:fs'
2
- import { open, lstat } from 'node:fs/promises'
3
1
  import { z } from 'zod'
4
2
  import { HarnessSdkError } from '@anureo/sdk'
5
- import { canonicalJson, digest, type JsonValue } from './json'
3
+ import { digest, type JsonValue } from './json'
6
4
 
7
- // Caller-assigned IDs also support existing CLI output basenames (including Unicode/spaces).
8
- export const runIdSchema = z.string().min(1).refine(value => value !== '.' && value !== '..'
9
- && value.trim().length > 0 && !/[\\/\x00-\x1f\x7f]/.test(value) && Buffer.byteLength(value) <= 255)
10
- export const uuidSchema = z.string().uuid()
11
- const hashSchema = z.string().regex(/^[a-f0-9]{64}$/)
12
- const jsonSchema: z.ZodType<JsonValue> = z.lazy(() => z.union([
13
- z.null(), z.boolean(), z.number().finite(), z.string(), z.array(jsonSchema), z.record(z.string(), jsonSchema),
14
- ]))
15
- export const failureSchema = z.strictObject({
16
- code: z.string(), retryable: z.boolean(), outcomeUnknown: z.boolean(), cleanupFailed: z.boolean(),
17
- })
18
- const identitySchema = z.strictObject({
19
- runId: runIdSchema, directory: z.string(), name: z.string().min(1), revision: z.string().min(1), input: jsonSchema,
20
- })
21
- export const manifestSchema = z.strictObject({
22
- checkpointFormatVersion: z.literal(2),
23
- identity: identitySchema, createdAt: z.string().datetime(),
24
- resumedFrom: z.strictObject({ directory: z.string(), runId: runIdSchema }).nullable(),
25
- status: z.enum(['running', 'completed', 'incomplete', 'failed']),
26
- resultDigest: hashSchema.nullable(), failure: failureSchema.nullable(), recordDigest: hashSchema,
27
- })
28
- export const journalKeySchema = z.string().regex(/^v1:[a-f0-9]{64}$/)
29
- export const journalEventSchema = z.discriminatedUnion('type', [
30
- z.strictObject({ type: z.literal('started'), key: journalKeySchema, agentId: uuidSchema,
31
- inputHookRevision: z.string().refine(value => value.trim().length > 0).optional() }),
32
- z.strictObject({ type: z.literal('result'), key: journalKeySchema, agentId: uuidSchema, result: jsonSchema }),
33
- z.strictObject({ type: z.literal('failed'), key: journalKeySchema, agentId: uuidSchema,
34
- code: z.string().min(1), outcomeUnknown: z.boolean() }),
35
- ])
36
- export const lockSchema = z.strictObject({
37
- checkpointFormatVersion: z.literal(2), token: uuidSchema, hostname: z.string(),
38
- pid: z.number().int().positive(), createdAt: z.string().datetime(), recordDigest: hashSchema,
39
- })
5
+ /** Validated manifest shape; its digest and referenced result still require separate verification. */
40
6
  export type Manifest = z.output<typeof manifestSchema>
41
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. */
42
15
  export function invalidCheckpoint(): never { throw new HarnessSdkError('WORKFLOW_CHECKPOINT_INVALID') }
43
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. */
44
19
  export function record<T extends object>(value: T): T & { recordDigest: string } {
45
20
  return { ...value, recordDigest: digest(value) }
46
21
  }
47
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. */
48
26
  export function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.output<S> {
49
27
  const parsed = schema.safeParse(value)
50
28
  if (!parsed.success) return invalidCheckpoint()
@@ -53,25 +31,73 @@ export function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.
53
31
  return parsed.data
54
32
  }
55
33
 
56
- /** Only ENOENT represents missing data; links, bad JSON and bad schemas are never cache misses. */
57
- export async function readJson(path: string): Promise<JsonValue> {
58
- const before = await lstat(path)
59
- if (!before.isFile()) return invalidCheckpoint()
60
- const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
61
- try {
62
- const current = await file.stat()
63
- if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino) return invalidCheckpoint()
64
- const text = await file.readFile('utf8')
65
- let value: unknown
66
- try { value = JSON.parse(text); canonicalJson(value) } catch { return invalidCheckpoint() }
67
- return value as JsonValue
68
- } finally { await file.close() }
69
- }
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
70
42
 
71
- export async function regularDirectory(path: string): Promise<void> {
72
- if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
73
- }
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)
74
48
 
75
- export function missing(cause: unknown): boolean {
76
- return (cause as NodeJS.ErrnoException)?.code === 'ENOENT'
77
- }
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
+ })
@@ -1,11 +1,51 @@
1
- import { HarnessSdkError } from '@anureo/sdk'
1
+ import { lstat } from 'node:fs/promises'
2
2
  import { hostname } from 'node:os'
3
3
  import { join } from 'node:path'
4
+ import { HarnessSdkError } from '@anureo/sdk'
5
+ import { readJson } from './checkpoint-files'
4
6
  import { digest } from './json'
5
- import { journalEventSchema, lockSchema, manifestSchema, invalidCheckpoint, missing,
6
- readJson, regularDirectory, verifyRecord, type Manifest } from './records'
7
- import type { JournalEvent } from './journal'
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'>
8
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. */
9
49
  async function requiredJson(path: string) {
10
50
  try { return await readJson(path) }
11
51
  catch (cause) {
@@ -14,36 +54,40 @@ async function requiredJson(path: string) {
14
54
  }
15
55
  }
16
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. */
17
60
  async function assertInactive(directory: string): Promise<void> {
18
61
  let lock
19
- try { lock = verifyRecord(lockSchema, await readJson(join(directory, 'writer.lock'))) }
20
- catch (cause) { if (missing(cause)) return; throw cause }
21
- if (lock.hostname === hostname()) {
22
- try { process.kill(lock.pid, 0) }
23
- catch (cause) { if ((cause as NodeJS.ErrnoException).code === 'ESRCH') return }
62
+ try {
63
+ lock = verifyRecord(lockSchema, await readJson(join(directory, checkpointFormat.lock)))
64
+ } catch (cause) {
65
+ if (missing(cause)) return
66
+ throw cause
24
67
  }
25
- // A reused PID is conservatively considered active. Never infer backend termination.
26
- throw new HarnessSdkError('WORKFLOW_SOURCE_ACTIVE')
68
+ if (!localWriterExited(lock)) throw new HarnessSdkError('WORKFLOW_SOURCE_ACTIVE')
27
69
  }
28
70
 
29
- /** Loads a finished or crashed source run's journal for cache replay. */
30
- export async function loadSourceJournal(
31
- directory: string,
32
- identity: { name: string; revision: string; runId: string },
33
- ): Promise<JournalEvent[]> {
34
- await regularDirectory(directory)
35
- await assertInactive(directory)
36
- // A format-v1 (explicit step) run directory fails manifest validation here.
37
- const manifest: Manifest = verifyRecord(manifestSchema, await requiredJson(join(directory, 'run.json')))
38
- if (manifest.identity.runId !== identity.runId) invalidCheckpoint()
39
- if (manifest.identity.name !== identity.name || manifest.identity.revision !== identity.revision) {
40
- throw new HarnessSdkError('WORKFLOW_INCOMPATIBLE_RUN')
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'
41
81
  }
42
- const raw = await requiredJson(join(directory, 'journal.json'))
43
- const parsed = journalEventSchema.array().safeParse(raw)
44
- if (!parsed.success) invalidCheckpoint()
45
- if (manifest.status === 'completed' || manifest.status === 'incomplete') {
46
- if (digest(await requiredJson(join(directory, 'result.json'))) !== manifest.resultDigest) invalidCheckpoint()
47
- }
48
- return parsed.data
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'
49
93
  }