@anureo/workflow 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -96
- package/package.json +4 -5
- package/src/agent-mcp.test.ts +19 -0
- package/src/agent-outcome.ts +21 -0
- package/src/agent-pi.test.ts +21 -0
- package/src/agent.test.ts +51 -237
- package/src/agent.ts +90 -115
- package/src/fixtures/workflow-crash.ts +17 -54
- package/src/index.ts +5 -6
- package/src/journal-call.test.ts +68 -0
- package/src/journal-call.ts +93 -0
- package/src/native.test.ts +71 -0
- package/src/output-schema.test.ts +12 -45
- package/src/output-schema.ts +96 -208
- package/src/parallel.test.ts +0 -1
- package/src/parallel.ts +8 -26
- package/src/persistence/atomic.ts +32 -0
- package/src/persistence/journal.ts +92 -104
- package/src/persistence/json.ts +32 -58
- package/src/persistence/records.ts +56 -82
- package/src/persistence/replay.ts +30 -74
- package/src/persistence/store.ts +120 -259
- package/src/pipeline.test.ts +0 -19
- package/src/pipeline.ts +23 -69
- package/src/run-context.ts +19 -0
- package/src/workflow-state.ts +18 -72
- package/src/workflow-types.ts +2 -20
- package/src/workflow.test.ts +104 -199
- package/src/workflow.ts +30 -88
- package/src/agent-adapters.test.ts +0 -121
- package/src/agent-execution.ts +0 -220
- package/src/persistence/checkpoint-files.ts +0 -83
- package/src/test-helpers.ts +0 -23
|
@@ -1,132 +1,120 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto'
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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
|
+
}
|
|
5
38
|
|
|
6
39
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
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.
|
|
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.
|
|
14
43
|
*/
|
|
15
44
|
export class AgentJournal {
|
|
16
|
-
|
|
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
|
+
|
|
17
51
|
constructor(
|
|
18
52
|
private readonly path: string,
|
|
19
53
|
source: readonly JournalEvent[],
|
|
54
|
+
/** Memory-only journals keep their event/index state but never touch the filesystem. */
|
|
55
|
+
private readonly persist = true,
|
|
20
56
|
) {
|
|
21
57
|
this.events.push(...jsonCopy(source))
|
|
22
|
-
this.
|
|
23
|
-
if (this.sourceIndex.results.size || this.sourceIndex.started.size) this.replayPrefix = new Set()
|
|
24
|
-
this.publishedCount = this.events.length
|
|
58
|
+
this.index = indexJournal(this.events)
|
|
25
59
|
}
|
|
26
60
|
|
|
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
61
|
nextKey(prompt: string, canonicalOptions: JsonValue): string {
|
|
30
|
-
const key =
|
|
62
|
+
const key = `v1:${createHash('sha256')
|
|
31
63
|
.update(this.previousKey).update('\0')
|
|
32
|
-
.update(
|
|
64
|
+
.update(prompt).update('\0')
|
|
33
65
|
.update(canonicalJson(canonicalOptions)).digest('hex')}`
|
|
34
66
|
this.previousKey = key
|
|
35
67
|
return key
|
|
36
68
|
}
|
|
37
69
|
|
|
38
|
-
/**
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
|
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)
|
|
51
75
|
}
|
|
52
|
-
|
|
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
|
|
76
|
+
if (this.index.inputHookRevisions.has(key) && this.index.inputHookRevisions.get(key) !== inputHookRevision) {
|
|
77
|
+
return new HarnessSdkError('WORKFLOW_INPUT_POLICY_CHANGED')
|
|
64
78
|
}
|
|
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
|
}
|
|
79
80
|
|
|
80
|
-
/**
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
unpublishedUnknownFailures: this.events.slice(this.publishedCount).filter(
|
|
86
|
-
(event): event is UnknownFailure => event.type === 'failed' && event.outcomeUnknown,
|
|
87
|
-
),
|
|
88
|
-
}
|
|
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)
|
|
89
86
|
}
|
|
90
87
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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
|
-
}
|
|
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
|
|
95
|
+
}
|
|
109
96
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
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)
|
|
97
|
+
async append(event: JournalEvent): Promise<void> {
|
|
98
|
+
this.events.push(jsonCopy(event))
|
|
99
|
+
if (this.persist) {
|
|
100
|
+
// Concurrent callers must not race atomic renames: an earlier snapshot
|
|
101
|
+
// landing last would silently drop later events from the published file.
|
|
102
|
+
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')
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
this.publishQueue = publish
|
|
110
|
+
await publish
|
|
129
111
|
}
|
|
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 })
|
|
130
115
|
}
|
|
131
|
-
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function newAgentId(): string {
|
|
119
|
+
return randomUUID()
|
|
132
120
|
}
|
package/src/persistence/json.ts
CHANGED
|
@@ -1,27 +1,49 @@
|
|
|
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. */
|
|
5
4
|
export type JsonValue = null | boolean | number | string | JsonValue[] | {
|
|
6
5
|
[key: string]: JsonValue
|
|
7
6
|
}
|
|
8
7
|
|
|
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
8
|
export function canonicalJson(value: unknown): string {
|
|
14
|
-
|
|
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)
|
|
15
41
|
}
|
|
16
42
|
|
|
17
|
-
/** Return a detached copy of JSON-compatible data. Unsupported values throw as in canonicalJson.
|
|
18
|
-
* Shared references are copied by value. */
|
|
19
43
|
export function jsonCopy<T>(value: T): T {
|
|
20
44
|
return JSON.parse(canonicalJson(value)) as T
|
|
21
45
|
}
|
|
22
46
|
|
|
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
47
|
export function freezeJson<T>(value: T): T {
|
|
26
48
|
if (value && typeof value === 'object') {
|
|
27
49
|
for (const child of Object.values(value)) freezeJson(child)
|
|
@@ -30,54 +52,6 @@ export function freezeJson<T>(value: T): T {
|
|
|
30
52
|
return value
|
|
31
53
|
}
|
|
32
54
|
|
|
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
55
|
export function digest(value: unknown): string {
|
|
37
56
|
return createHash('sha256').update(canonicalJson(value)).digest('hex')
|
|
38
57
|
}
|
|
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,28 +1,50 @@
|
|
|
1
|
+
import { constants } from 'node:fs'
|
|
2
|
+
import { open, lstat } from 'node:fs/promises'
|
|
1
3
|
import { z } from 'zod'
|
|
2
4
|
import { HarnessSdkError } from '@anureo/sdk'
|
|
3
|
-
import { digest, type JsonValue } from './json'
|
|
5
|
+
import { canonicalJson, digest, type JsonValue } from './json'
|
|
4
6
|
|
|
5
|
-
|
|
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
|
+
})
|
|
6
40
|
export type Manifest = z.output<typeof manifestSchema>
|
|
7
41
|
|
|
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
42
|
export function invalidCheckpoint(): never { throw new HarnessSdkError('WORKFLOW_CHECKPOINT_INVALID') }
|
|
16
43
|
|
|
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
44
|
export function record<T extends object>(value: T): T & { recordDigest: string } {
|
|
20
45
|
return { ...value, recordDigest: digest(value) }
|
|
21
46
|
}
|
|
22
47
|
|
|
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
48
|
export function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.output<S> {
|
|
27
49
|
const parsed = schema.safeParse(value)
|
|
28
50
|
if (!parsed.success) return invalidCheckpoint()
|
|
@@ -31,73 +53,25 @@ export function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.
|
|
|
31
53
|
return parsed.data
|
|
32
54
|
}
|
|
33
55
|
|
|
34
|
-
/**
|
|
35
|
-
export
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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>
|
|
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
|
+
}
|
|
85
70
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
retryable: z.boolean(),
|
|
90
|
-
outcomeUnknown: z.boolean(),
|
|
91
|
-
cleanupFailed: z.boolean(),
|
|
92
|
-
unpublishedUnknownFailures: unknownFailureSchema.array().optional(),
|
|
93
|
-
})
|
|
71
|
+
export async function regularDirectory(path: string): Promise<void> {
|
|
72
|
+
if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
|
|
73
|
+
}
|
|
94
74
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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
|
-
})
|
|
75
|
+
export function missing(cause: unknown): boolean {
|
|
76
|
+
return (cause as NodeJS.ErrnoException)?.code === 'ENOENT'
|
|
77
|
+
}
|
|
@@ -1,51 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { HarnessSdkError } from '@anureo/sdk'
|
|
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'
|
|
6
4
|
import { digest } from './json'
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
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'>
|
|
5
|
+
import { journalEventSchema, lockSchema, manifestSchema, invalidCheckpoint, missing,
|
|
6
|
+
readJson, regularDirectory, verifyRecord, type Manifest } from './records'
|
|
7
|
+
import type { JournalEvent } from './journal'
|
|
37
8
|
|
|
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
9
|
async function requiredJson(path: string) {
|
|
50
10
|
try { return await readJson(path) }
|
|
51
11
|
catch (cause) {
|
|
@@ -54,40 +14,36 @@ async function requiredJson(path: string) {
|
|
|
54
14
|
}
|
|
55
15
|
}
|
|
56
16
|
|
|
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
17
|
async function assertInactive(directory: string): Promise<void> {
|
|
61
18
|
let lock
|
|
62
|
-
try {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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 }
|
|
67
24
|
}
|
|
68
|
-
|
|
25
|
+
// A reused PID is conservatively considered active. Never infer backend termination.
|
|
26
|
+
throw new HarnessSdkError('WORKFLOW_SOURCE_ACTIVE')
|
|
69
27
|
}
|
|
70
28
|
|
|
71
|
-
/**
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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')
|
|
81
41
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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'
|
|
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
|
|
93
49
|
}
|