@anureo/workflow 0.3.1 → 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.
- package/package.json +9 -8
- package/src/agent-execution.ts +58 -39
- package/src/agent.test.ts +139 -2
- package/src/agent.ts +40 -39
- package/src/fixtures/workflow-crash.ts +23 -7
- package/src/output-schema.test.ts +13 -1
- package/src/output-schema.ts +11 -5
- package/src/persistence/checkpoint-files.ts +3 -2
- package/src/persistence/journal.ts +50 -29
- package/src/persistence/records.ts +32 -26
- package/src/persistence/replay.ts +4 -2
- package/src/persistence/store.ts +37 -8
- package/src/workflow-state.ts +1 -0
- package/src/workflow.test.ts +145 -18
package/src/output-schema.ts
CHANGED
|
@@ -28,9 +28,7 @@ export interface AgentOutputSchema<S extends z.ZodObject = z.ZodObject> {
|
|
|
28
28
|
* Require closed objects and required JSON fields, including fields with JSON-compatible defaults.
|
|
29
29
|
* Conversion schemas and other unsupported shapes synchronously throw INVALID_PARAMS with a
|
|
30
30
|
* rule code in details.rule.
|
|
31
|
-
*
|
|
32
|
-
* executeAgent prepares its own pair before opening a session. On a journal miss this happens
|
|
33
|
-
* after the started record is published and dispatch is rechecked.
|
|
31
|
+
* prepareAgentCall prepares the pair at invocation for fresh execution and typed replay.
|
|
34
32
|
*/
|
|
35
33
|
export function prepareOutputSchema<S extends z.ZodObject>(source: S): AgentOutputSchema<S> {
|
|
36
34
|
const { schema, validate } = compilePortableSchema(source)
|
|
@@ -65,8 +63,16 @@ function parseRawOutput(text: string, validate: ValidateFunction): unknown {
|
|
|
65
63
|
} catch {
|
|
66
64
|
throw new HarnessSdkError('AGENT_STRUCTURED_OUTPUT_NOT_JSON')
|
|
67
65
|
}
|
|
68
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
69
|
-
|
|
66
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw outputMismatch([])
|
|
67
|
+
if (!validate(value)) {
|
|
68
|
+
const issues = validate.errors?.map(({ instancePath, keyword, params }) => {
|
|
69
|
+
const property = keyword === 'required' ? params.missingProperty
|
|
70
|
+
: keyword === 'additionalProperties' ? params.additionalProperty : undefined
|
|
71
|
+
const path = typeof property === 'string'
|
|
72
|
+
? `${instancePath}/${property.replace(/~/g, '~0').replace(/\//g, '~1')}`
|
|
73
|
+
: instancePath
|
|
74
|
+
return { path, code: keyword }
|
|
75
|
+
}) ?? []
|
|
70
76
|
throw outputMismatch(issues)
|
|
71
77
|
}
|
|
72
78
|
return value
|
|
@@ -18,9 +18,9 @@ export async function syncDirectory(path: string): Promise<void> {
|
|
|
18
18
|
* its parent directory where supported. FileRunHandle and AgentJournal serialize their own
|
|
19
19
|
* writes because a rename alone cannot prevent an older snapshot from overwriting a newer one.
|
|
20
20
|
* The caller creates the parent. Invalid JSON rejects before any file I/O.
|
|
21
|
-
*
|
|
21
|
+
* The optional callback observes replacement before the directory flush, which can still fail.
|
|
22
22
|
* If temporary-file cleanup fails, the rejection includes both failures. */
|
|
23
|
-
export async function atomicPublish(path: string, value: unknown): Promise<void> {
|
|
23
|
+
export async function atomicPublish(path: string, value: unknown, onReplace?: () => void): Promise<void> {
|
|
24
24
|
const text = `${canonicalJson(value)}\n`
|
|
25
25
|
const temporary = `${path}.${randomUUID()}.tmp`
|
|
26
26
|
// An exclusive open establishes ownership. Cleanup must leave an existing file alone.
|
|
@@ -41,6 +41,7 @@ export async function atomicPublish(path: string, value: unknown): Promise<void>
|
|
|
41
41
|
}
|
|
42
42
|
throw cause
|
|
43
43
|
}
|
|
44
|
+
onReplace?.()
|
|
44
45
|
await syncDirectory(dirname(path))
|
|
45
46
|
}
|
|
46
47
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
2
|
import { atomicPublish, storageError } from './checkpoint-files'
|
|
3
|
-
import { canonicalJson, jsonCopy, type JsonValue } from './json'
|
|
4
|
-
import type
|
|
3
|
+
import { canonicalJson, digest, jsonCopy, type JsonValue } from './json'
|
|
4
|
+
import { journalKeyPrefix, type JournalEvent, type UnknownFailure } from './records'
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Internal agent-call journal created by publishInitialRun for a new run and exposed
|
|
@@ -19,15 +19,17 @@ export class AgentJournal {
|
|
|
19
19
|
source: readonly JournalEvent[],
|
|
20
20
|
) {
|
|
21
21
|
this.events.push(...jsonCopy(source))
|
|
22
|
-
this.
|
|
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
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
/** Advance the chain synchronously before memoizedAgent's first await, including cache hits.
|
|
26
28
|
* Options must be strict JSON. If canonicalJson throws, the chain stays unchanged. */
|
|
27
29
|
nextKey(prompt: string, canonicalOptions: JsonValue): string {
|
|
28
|
-
const key =
|
|
30
|
+
const key = `${journalKeyPrefix}${createHash('sha256')
|
|
29
31
|
.update(this.previousKey).update('\0')
|
|
30
|
-
.update(prompt).update('\0')
|
|
32
|
+
.update(JSON.stringify(prompt)).update('\0')
|
|
31
33
|
.update(canonicalJson(canonicalOptions)).digest('hex')}`
|
|
32
34
|
this.previousKey = key
|
|
33
35
|
return key
|
|
@@ -39,38 +41,59 @@ export class AgentJournal {
|
|
|
39
41
|
* requires reconciliation before memoizedAgent can dispatch. */
|
|
40
42
|
resolveCall(key: string): JournalDecision {
|
|
41
43
|
if (this.reuseOpen) {
|
|
42
|
-
const result = this.
|
|
43
|
-
if (result !== undefined)
|
|
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
|
|
44
51
|
}
|
|
45
|
-
|
|
46
|
-
return this.index.uncertain.has(key) ? { action: 'reconcile' } : { action: 'execute' }
|
|
52
|
+
return this.sourceIndex.uncertain.has(key) ? { action: 'reconcile' } : { action: 'execute' }
|
|
47
53
|
}
|
|
48
54
|
|
|
49
|
-
/** Queue a copied event and await serialized atomic publication
|
|
50
|
-
*
|
|
51
|
-
*
|
|
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.
|
|
52
58
|
* On publication failure the event stays in the in-memory snapshot. Non-SDK I/O failures
|
|
53
59
|
* reject as WORKFLOW_STORAGE_FAILED, which RunState records to stop later dispatch. */
|
|
54
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
|
+
}
|
|
55
65
|
this.events.push(jsonCopy(event))
|
|
56
66
|
// Concurrent callers must not race atomic renames: an earlier snapshot
|
|
57
67
|
// landing last would silently drop later events from the published file.
|
|
58
68
|
const publish = this.publishQueue.catch(() => {}).then(async () => {
|
|
59
69
|
try {
|
|
60
|
-
|
|
70
|
+
const count = this.events.length
|
|
71
|
+
await atomicPublish(this.path, this.events, () => { this.publishedCount = count })
|
|
61
72
|
} catch (cause) {
|
|
62
73
|
throw storageError(cause)
|
|
63
74
|
}
|
|
64
75
|
})
|
|
65
76
|
this.publishQueue = publish
|
|
66
77
|
await publish
|
|
67
|
-
|
|
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
|
+
}
|
|
68
89
|
}
|
|
69
90
|
|
|
70
91
|
private readonly events: JournalEvent[] = []
|
|
71
|
-
private readonly
|
|
92
|
+
private readonly sourceIndex: JournalIndex
|
|
93
|
+
private publishedCount: number
|
|
72
94
|
private previousKey = ''
|
|
73
95
|
private reuseOpen = true
|
|
96
|
+
private replayPrefix?: Set<string>
|
|
74
97
|
private publishQueue: Promise<void> = Promise.resolve()
|
|
75
98
|
}
|
|
76
99
|
|
|
@@ -92,20 +115,18 @@ function indexJournal(events: readonly JournalEvent[]): JournalIndex {
|
|
|
92
115
|
index.started.delete(event.key)
|
|
93
116
|
index.uncertain.delete(event.key)
|
|
94
117
|
index.results.delete(event.key)
|
|
95
|
-
if (event.type === 'started')
|
|
96
|
-
|
|
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
|
+
}
|
|
97
130
|
}
|
|
98
131
|
return index
|
|
99
132
|
}
|
|
100
|
-
|
|
101
|
-
/** Populate the terminal lookup. The replay fold clears superseded entries before calling
|
|
102
|
-
* this helper. Live append retains the source prefix markers for miss handling. */
|
|
103
|
-
function indexTerminalEvent(index: JournalIndex, event: Exclude<JournalEvent, { type: 'started' }>): void {
|
|
104
|
-
if (event.type === 'result') {
|
|
105
|
-
index.results.set(event.key, event.result)
|
|
106
|
-
} else if (event.outcomeUnknown) {
|
|
107
|
-
index.uncertain.add(event.key)
|
|
108
|
-
} else {
|
|
109
|
-
index.uncertain.delete(event.key)
|
|
110
|
-
}
|
|
111
|
-
}
|
|
@@ -33,7 +33,7 @@ export function verifyRecord<S extends z.ZodType>(schema: S, value: unknown): z.
|
|
|
33
33
|
|
|
34
34
|
/** File names and version used by the target writer and the compatible-source reader. */
|
|
35
35
|
export const checkpointFormat = {
|
|
36
|
-
version:
|
|
36
|
+
version: 3,
|
|
37
37
|
lock: 'writer.lock',
|
|
38
38
|
manifest: 'run.json',
|
|
39
39
|
journal: 'journal.json',
|
|
@@ -51,22 +51,12 @@ export const runIdSchema = z.string().min(1).refine(value => value !== '.' && va
|
|
|
51
51
|
const uuidSchema = z.string().uuid()
|
|
52
52
|
const hashSchema = z.string().regex(/^[a-f0-9]{64}$/)
|
|
53
53
|
|
|
54
|
-
/**
|
|
54
|
+
/** Writer claim. Replay checks host/PID liveness. Release checks the held inode. */
|
|
55
55
|
export const lockSchema = z.strictObject({
|
|
56
56
|
checkpointFormatVersion: z.literal(checkpointFormat.version), token: uuidSchema, hostname: z.string(),
|
|
57
57
|
pid: z.number().int().positive(), createdAt: z.string().datetime(), recordDigest: hashSchema,
|
|
58
58
|
})
|
|
59
59
|
|
|
60
|
-
/** Persist only safe failure metadata; diagnostic messages and details stay out of manifests. */
|
|
61
|
-
const failureSchema = z.strictObject({
|
|
62
|
-
code: z.string(),
|
|
63
|
-
retryable: z.boolean(),
|
|
64
|
-
/** The failure left execution's outcome uncertain. */
|
|
65
|
-
outcomeUnknown: z.boolean(),
|
|
66
|
-
/** Resource release failed even if execution itself had a known outcome. */
|
|
67
|
-
cleanupFailed: z.boolean(),
|
|
68
|
-
})
|
|
69
|
-
|
|
70
60
|
const jsonSchema: z.ZodType<JsonValue> = z.lazy(() => z.union([
|
|
71
61
|
z.null(), z.boolean(), z.number().finite(), z.string(), z.array(jsonSchema), z.record(z.string(), jsonSchema),
|
|
72
62
|
]))
|
|
@@ -74,24 +64,40 @@ const identitySchema = z.strictObject({
|
|
|
74
64
|
runId: runIdSchema, directory: z.string(), name: z.string().min(1), revision: z.string().min(1), input: jsonSchema,
|
|
75
65
|
})
|
|
76
66
|
|
|
77
|
-
/** Format-v2 run metadata. Replay rejects earlier formats, checks recordDigest with verifyRecord,
|
|
78
|
-
* and checks resultDigest against result.json for completed and incomplete runs. */
|
|
79
|
-
export const manifestSchema = z.strictObject({
|
|
80
|
-
checkpointFormatVersion: z.literal(checkpointFormat.version),
|
|
81
|
-
identity: identitySchema, createdAt: z.string().datetime(),
|
|
82
|
-
resumedFrom: z.strictObject({ directory: z.string(), runId: runIdSchema }).nullable(),
|
|
83
|
-
status: z.enum(['running', 'completed', 'incomplete', 'failed']),
|
|
84
|
-
resultDigest: hashSchema.nullable(), failure: failureSchema.nullable(), recordDigest: hashSchema,
|
|
85
|
-
})
|
|
86
|
-
|
|
87
67
|
/** Versioned chained SHA-256 identity for an agent call, independent of its execution UUID. */
|
|
88
|
-
const
|
|
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() })
|
|
89
73
|
|
|
90
74
|
/** Strict persisted events. Replay validates the entire array before handing it to AgentJournal.
|
|
91
75
|
* The chained key determines reuse. The execution UUID is recorded as agentId. */
|
|
92
76
|
export const journalEventSchema = z.discriminatedUnion('type', [
|
|
93
|
-
z.strictObject({ type: z.literal('started'), key: journalKeySchema, agentId: uuidSchema
|
|
77
|
+
z.strictObject({ type: z.literal('started'), key: journalKeySchema, agentId: uuidSchema,
|
|
78
|
+
retainReplayKeys: journalKeySchema.array().optional() }),
|
|
94
79
|
z.strictObject({ type: z.literal('result'), key: journalKeySchema, agentId: uuidSchema, result: jsonSchema }),
|
|
95
|
-
|
|
96
|
-
code: z.string().min(1), outcomeUnknown: z.boolean() }),
|
|
80
|
+
failedEventSchema,
|
|
97
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
|
+
})
|
|
@@ -14,7 +14,8 @@ import {
|
|
|
14
14
|
* into the new journal. A mismatched run ID or invalid required record rejects as
|
|
15
15
|
* WORKFLOW_CHECKPOINT_INVALID. Mismatched name or revision rejects as WORKFLOW_INCOMPATIBLE_RUN.
|
|
16
16
|
* A valid lock without evidence of a dead local writer rejects as WORKFLOW_SOURCE_ACTIVE.
|
|
17
|
-
*
|
|
17
|
+
* Terminal sources must have a journal matching the manifest digest. Completed and incomplete
|
|
18
|
+
* sources must also have a matching result.
|
|
18
19
|
* Other filesystem errors propagate for storage error normalization.
|
|
19
20
|
* The caller supplies a separate target directory. This check acquires no source lock. */
|
|
20
21
|
export async function loadSourceJournal(directory: string, identity: SourceIdentity): Promise<JournalEvent[]> {
|
|
@@ -23,12 +24,13 @@ export async function loadSourceJournal(directory: string, identity: SourceIdent
|
|
|
23
24
|
const manifest = verifyRecord(manifestSchema, await requiredJson(join(directory, checkpointFormat.manifest)))
|
|
24
25
|
assertCompatibleIdentity(manifest.identity, identity)
|
|
25
26
|
const raw = await requiredJson(join(directory, checkpointFormat.journal))
|
|
27
|
+
if (manifest.status !== 'running' && digest(raw) !== manifest.journalDigest) invalidCheckpoint()
|
|
26
28
|
const parsed = journalEventSchema.array().safeParse(raw)
|
|
27
29
|
if (!parsed.success) invalidCheckpoint()
|
|
28
30
|
if (manifest.status === 'completed' || manifest.status === 'incomplete') {
|
|
29
31
|
if (digest(await requiredJson(join(directory, checkpointFormat.result))) !== manifest.resultDigest) invalidCheckpoint()
|
|
30
32
|
}
|
|
31
|
-
return parsed.data
|
|
33
|
+
return parsed.data.concat(manifest.failure?.unpublishedUnknownFailures ?? [])
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
type SourceIdentity = Pick<Manifest['identity'], 'name' | 'revision' | 'runId'>
|
package/src/persistence/store.ts
CHANGED
|
@@ -91,8 +91,9 @@ class FileRunHandle implements RunHandle {
|
|
|
91
91
|
* The manifest comes last so it refers to an already published result. */
|
|
92
92
|
async finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void> {
|
|
93
93
|
await this.updateManifest(async () => {
|
|
94
|
+
const { journalDigest } = this.journal.checkpoint()
|
|
94
95
|
await atomicPublish(join(this.path, checkpointFormat.result), result)
|
|
95
|
-
await this.publishManifest({ status, resultDigest: digest(result), failure: null })
|
|
96
|
+
await this.publishManifest({ status, journalDigest, resultDigest: digest(result), failure: null })
|
|
96
97
|
})
|
|
97
98
|
}
|
|
98
99
|
|
|
@@ -100,7 +101,11 @@ class FileRunHandle implements RunHandle {
|
|
|
100
101
|
* even if finish left an earlier result file. */
|
|
101
102
|
async abort(failure: StoredFailure): Promise<void> {
|
|
102
103
|
await this.updateManifest(async () => {
|
|
103
|
-
|
|
104
|
+
const { journalDigest, unpublishedUnknownFailures } = this.journal.checkpoint()
|
|
105
|
+
await this.publishManifest({ status: 'failed', journalDigest, resultDigest: null, failure: {
|
|
106
|
+
...failure,
|
|
107
|
+
...(unpublishedUnknownFailures.length ? { unpublishedUnknownFailures } : {}),
|
|
108
|
+
} })
|
|
104
109
|
})
|
|
105
110
|
}
|
|
106
111
|
|
|
@@ -140,7 +145,7 @@ class FileRunHandle implements RunHandle {
|
|
|
140
145
|
|
|
141
146
|
/** Recompute the digest from payload only for every terminal transition, then publish it.
|
|
142
147
|
* Keep the in-memory transition even if publication rejects, as abort may follow a failed finish. */
|
|
143
|
-
private async publishManifest(update: Pick<Manifest, 'status' | 'resultDigest' | 'failure'>): Promise<void> {
|
|
148
|
+
private async publishManifest(update: Pick<Manifest, 'status' | 'journalDigest' | 'resultDigest' | 'failure'>): Promise<void> {
|
|
144
149
|
const { recordDigest: _, ...payload } = this.manifest
|
|
145
150
|
this.manifest = record({ ...payload, ...update })
|
|
146
151
|
await atomicPublish(join(this.path, checkpointFormat.manifest), this.manifest)
|
|
@@ -149,18 +154,27 @@ class FileRunHandle implements RunHandle {
|
|
|
149
154
|
|
|
150
155
|
/** Throw INVALID_PARAMS for malformed target identity before copying input or touching storage. */
|
|
151
156
|
function validateRunOptions(options: FileRunOptions): void {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
157
|
+
const issues: string[] = []
|
|
158
|
+
if (!runIdSchema.safeParse(options.runId).success) {
|
|
159
|
+
issues.push('runId must be a valid directory basename (at most 255 UTF-8 bytes)')
|
|
155
160
|
}
|
|
161
|
+
if (typeof options.name !== 'string' || !options.name) issues.push('name must be a nonempty string')
|
|
162
|
+
if (typeof options.revision !== 'string' || !options.revision) issues.push('revision must be a nonempty string')
|
|
163
|
+
if (typeof options.directory !== 'string' || !options.directory) issues.push('directory must be a nonempty string')
|
|
164
|
+
if (issues.length) throw new HarnessSdkError('INVALID_PARAMS', `Invalid workflow options: ${issues.join(', ')}`)
|
|
156
165
|
}
|
|
157
166
|
|
|
158
167
|
/** Snapshot input, resolve parent/source paths, and create a real target directory before locking.
|
|
159
168
|
* Flush the parent when creating the target. Initialization checks existing contents under the lock. */
|
|
160
169
|
async function prepareRunStorage(options: FileRunOptions): Promise<PreparedRun> {
|
|
161
170
|
const input = jsonCopy(options.input)
|
|
162
|
-
|
|
163
|
-
|
|
171
|
+
const root = resolve(options.directory)
|
|
172
|
+
if (options.resumeFrom !== undefined && typeof options.resumeFrom !== 'string') {
|
|
173
|
+
const directory = await prospectiveDirectory(root)
|
|
174
|
+
await resolveSourceRun({ resumeFrom: options.resumeFrom, directory, path: join(directory, options.runId) })
|
|
175
|
+
}
|
|
176
|
+
await mkdir(root, { recursive: true, mode: 0o700 })
|
|
177
|
+
const directory = await realpath(root)
|
|
164
178
|
const path = join(directory, options.runId)
|
|
165
179
|
const source = await resolveSourceRun({ resumeFrom: options.resumeFrom, directory, path })
|
|
166
180
|
try {
|
|
@@ -170,9 +184,23 @@ async function prepareRunStorage(options: FileRunOptions): Promise<PreparedRun>
|
|
|
170
184
|
if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause
|
|
171
185
|
}
|
|
172
186
|
if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
|
|
187
|
+
if (source && overlaps(await realpath(path), join(source.directory, source.runId))) {
|
|
188
|
+
throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS')
|
|
189
|
+
}
|
|
173
190
|
return { directory, path, input, source }
|
|
174
191
|
}
|
|
175
192
|
|
|
193
|
+
/** Resolve existing ancestors so the overlap check can run before creating a missing root. */
|
|
194
|
+
async function prospectiveDirectory(path: string): Promise<string> {
|
|
195
|
+
try {
|
|
196
|
+
return await realpath(path)
|
|
197
|
+
} catch (cause) {
|
|
198
|
+
const parent = dirname(path)
|
|
199
|
+
if ((cause as NodeJS.ErrnoException).code !== 'ENOENT' || parent === path) throw cause
|
|
200
|
+
return join(await prospectiveDirectory(parent), relative(parent, path))
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
176
204
|
/** Resolve optional replay coordinates before target creation so overlapping source/target trees
|
|
177
205
|
* reject before a writer claim. Omission selects fresh execution. A string uses the target's
|
|
178
206
|
* canonical parent, while an object supplies its own parent to resolve. */
|
|
@@ -253,6 +281,7 @@ async function publishInitialRun({ options, prepared, lock }: {
|
|
|
253
281
|
createdAt: new Date().toISOString(),
|
|
254
282
|
resumedFrom: source,
|
|
255
283
|
status: 'running',
|
|
284
|
+
journalDigest: null,
|
|
256
285
|
resultDigest: null,
|
|
257
286
|
failure: null,
|
|
258
287
|
})
|
package/src/workflow-state.ts
CHANGED
|
@@ -59,6 +59,7 @@ export class RunState {
|
|
|
59
59
|
if (!first) return undefined
|
|
60
60
|
return new HarnessSdkError(first.code, first.message, false,
|
|
61
61
|
failures.some(error => error.outcomeUnknown), {
|
|
62
|
+
...first.details,
|
|
62
63
|
failureCodes: [...new Set(failures.map(error => error.code))],
|
|
63
64
|
cleanupFailed: failures.some(cleanupFailed),
|
|
64
65
|
})
|
package/src/workflow.test.ts
CHANGED
|
@@ -11,6 +11,7 @@ import type { HarnessError } from '@anureo/protocol'
|
|
|
11
11
|
import { z } from 'zod'
|
|
12
12
|
import { workflow, parallel, agent, type WorkflowOptions } from './index'
|
|
13
13
|
import { canonicalJson, digest } from './persistence/json'
|
|
14
|
+
import { record, type JournalEvent } from './persistence/records'
|
|
14
15
|
|
|
15
16
|
const clients: Client[] = []
|
|
16
17
|
const fixture = createFixture(clients)
|
|
@@ -50,7 +51,7 @@ test('run identity is durable before body, inputs are isolated, and results are
|
|
|
50
51
|
const manifest = JSON.parse(await readFile(join(options.directory, run.runId, 'run.json'), 'utf8'))
|
|
51
52
|
expect(manifest.identity.runId).toBe(run.runId)
|
|
52
53
|
expect(manifest.status).toBe('running')
|
|
53
|
-
expect(manifest.checkpointFormatVersion).toBe(
|
|
54
|
+
expect(manifest.checkpointFormatVersion).toBe(3)
|
|
54
55
|
expect(Object.isFrozen(run.input.values)).toBe(true)
|
|
55
56
|
expect(Object.isFrozen(options.input.values)).toBe(false)
|
|
56
57
|
return agent('hello', { client, cwd: options.directory })
|
|
@@ -62,6 +63,8 @@ test('run identity is durable before body, inputs are isolated, and results are
|
|
|
62
63
|
const journal = JSON.parse(await readFile(join(options.directory, result.runId, 'journal.json'), 'utf8'))
|
|
63
64
|
expect(journal).toHaveLength(2)
|
|
64
65
|
expect(journal[1]).toMatchObject({ type: 'result', result: 'hello' })
|
|
66
|
+
const manifest = JSON.parse(await readFile(join(options.directory, result.runId, 'run.json'), 'utf8'))
|
|
67
|
+
expect(manifest.journalDigest).toBe(digest(journal))
|
|
65
68
|
})
|
|
66
69
|
|
|
67
70
|
test('resumed runs replay identical agent calls from the journal without new sessions', async () => {
|
|
@@ -117,6 +120,17 @@ test('prompt, options, and client identity changes miss the cache', async () =>
|
|
|
117
120
|
expect(other.adapter.opened).toHaveLength(1)
|
|
118
121
|
})
|
|
119
122
|
|
|
123
|
+
test('lone surrogates and replacement characters have distinct replay keys', async () => {
|
|
124
|
+
const options = await setup()
|
|
125
|
+
const { client, adapter } = await fixture()
|
|
126
|
+
const first = await workflow(options, () => agent('\ud800', { client, cwd: options.directory }))
|
|
127
|
+
const second = await workflow({ ...options, resumeFrom: first.runId }, () =>
|
|
128
|
+
agent('\ufffd', { client, cwd: options.directory }))
|
|
129
|
+
expect(first.result).toBe('\ud800')
|
|
130
|
+
expect(second.result).toBe('\ufffd')
|
|
131
|
+
expect(adapter.opened).toHaveLength(2)
|
|
132
|
+
})
|
|
133
|
+
|
|
120
134
|
test('name or revision changes reject resume before the body runs', async () => {
|
|
121
135
|
const options = await setup()
|
|
122
136
|
const { client } = await fixture()
|
|
@@ -179,6 +193,50 @@ test('unknown previous outcomes require reconciliation instead of silent re-exec
|
|
|
179
193
|
expect(adapter.opened).toHaveLength(1)
|
|
180
194
|
})
|
|
181
195
|
|
|
196
|
+
test('a failed journal replacement preserves exact-key uncertainty in the manifest', async () => {
|
|
197
|
+
const options = { ...await setup(), name: 'crash-test' }
|
|
198
|
+
await runCrashFixture(options.directory, 'unpublished-unknown', 0)
|
|
199
|
+
const source = join(options.directory, 'crashed')
|
|
200
|
+
const journal = JSON.parse(await readFile(join(source, 'journal.json'), 'utf8')) as JournalEvent[]
|
|
201
|
+
expect(journal.map(event => event.type)).toEqual(['started'])
|
|
202
|
+
const manifest = JSON.parse(await readFile(join(source, 'run.json'), 'utf8'))
|
|
203
|
+
expect(manifest).toMatchObject({ status: 'failed', journalDigest: digest(journal), failure: {
|
|
204
|
+
outcomeUnknown: true,
|
|
205
|
+
unpublishedUnknownFailures: [{
|
|
206
|
+
...journal[0], type: 'failed', code: 'NATIVE_FAILED', outcomeUnknown: true,
|
|
207
|
+
}],
|
|
208
|
+
} })
|
|
209
|
+
|
|
210
|
+
const { client, adapter } = await crashClient()
|
|
211
|
+
const resumed = { ...options, resumeFrom: 'crashed' }
|
|
212
|
+
await expect(workflow({ ...resumed, runId: 'blocked' }, () => agent('work', { client, cwd: options.directory })))
|
|
213
|
+
.rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
|
|
214
|
+
await expect(workflow({ ...resumed, resumeFrom: 'blocked' }, () => agent('work', { client, cwd: options.directory })))
|
|
215
|
+
.rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
|
|
216
|
+
expect(adapter.opened).toHaveLength(0)
|
|
217
|
+
const other = await workflow(resumed, () => agent('other', { client, cwd: options.directory }))
|
|
218
|
+
expect(other.result).toBe('other')
|
|
219
|
+
await writeFile(join(source, 'journal.json'), '[]')
|
|
220
|
+
await expect(workflow(resumed, () => agent('work', { client, cwd: options.directory })))
|
|
221
|
+
.rejects.toMatchObject({ code: 'WORKFLOW_CHECKPOINT_INVALID' })
|
|
222
|
+
expect(adapter.opened).toHaveLength(1)
|
|
223
|
+
})
|
|
224
|
+
|
|
225
|
+
test('workflow rejections preserve schema diagnostics outside the stored failure summary', async () => {
|
|
226
|
+
const options = { ...await setup(), runId: 'schema-error' }
|
|
227
|
+
const { client, adapter } = await fixture()
|
|
228
|
+
await expect(workflow(options, () => agent('work', {
|
|
229
|
+
client, cwd: options.directory, schema: z.strictObject({ value: z.string().optional() }),
|
|
230
|
+
}))).rejects.toMatchObject({
|
|
231
|
+
code: 'INVALID_PARAMS', details: { rule: 'valueConversionOrNonportableType', runId: options.runId },
|
|
232
|
+
})
|
|
233
|
+
const manifest = JSON.parse(await readFile(join(options.directory, options.runId, 'run.json'), 'utf8'))
|
|
234
|
+
expect(manifest.failure).toEqual({
|
|
235
|
+
code: 'INVALID_PARAMS', retryable: false, outcomeUnknown: false, cleanupFailed: false,
|
|
236
|
+
})
|
|
237
|
+
expect(adapter.opened).toHaveLength(0)
|
|
238
|
+
})
|
|
239
|
+
|
|
182
240
|
test('storage failure is sticky and blocks subsequent agent dispatch', async () => {
|
|
183
241
|
const options = await setup()
|
|
184
242
|
const { client, adapter } = await fixture()
|
|
@@ -248,8 +306,11 @@ test('source activity, target competition, and reused explicit ids reject before
|
|
|
248
306
|
test('initialization rejects invalid identities and releases a failed target claim before entering body', async () => {
|
|
249
307
|
const options = await setup()
|
|
250
308
|
let entered = false
|
|
251
|
-
await expect(workflow({ ...options, runId: '../escape' }, () => { entered = true; return {} }))
|
|
252
|
-
.rejects.toMatchObject({
|
|
309
|
+
await expect(workflow({ ...options, runId: '../escape', revision: '' }, () => { entered = true; return {} }))
|
|
310
|
+
.rejects.toMatchObject({
|
|
311
|
+
code: 'INVALID_PARAMS',
|
|
312
|
+
message: 'Invalid workflow options: runId must be a valid directory basename (at most 255 UTF-8 bytes), revision must be a nonempty string',
|
|
313
|
+
})
|
|
253
314
|
const { client } = await fixture()
|
|
254
315
|
const original = await workflow({ ...options, runId: 'source' }, () => agent('a', { client, cwd: options.directory }))
|
|
255
316
|
await expect(workflow({ ...options, name: 'incompatible', runId: 'target', resumeFrom: original.runId }, () => {
|
|
@@ -259,6 +320,22 @@ test('initialization rejects invalid identities and releases a failed target cla
|
|
|
259
320
|
expect(await readdir(join(options.directory, 'target'))).not.toContain('writer.lock')
|
|
260
321
|
})
|
|
261
322
|
|
|
323
|
+
test('overlapping target roots are rejected without creating directories in the source', async () => {
|
|
324
|
+
const options = await setup()
|
|
325
|
+
const first = await workflow(options, () => 'source')
|
|
326
|
+
const source = join(options.directory, first.runId)
|
|
327
|
+
const alias = join(options.directory, 'alias')
|
|
328
|
+
await symlink(source, alias, 'dir')
|
|
329
|
+
const original = await readdir(source)
|
|
330
|
+
for (const root of [source, alias]) {
|
|
331
|
+
await expect(workflow({
|
|
332
|
+
...options, directory: join(root, 'missing', 'nested'),
|
|
333
|
+
resumeFrom: { directory: options.directory, runId: first.runId },
|
|
334
|
+
}, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_OVERLAPPING_RUNS' })
|
|
335
|
+
expect(await readdir(source)).toEqual(original)
|
|
336
|
+
}
|
|
337
|
+
})
|
|
338
|
+
|
|
262
339
|
test('preallocated Unicode and spaced output names resume without changing directory meaning', async () => {
|
|
263
340
|
const options = await setup()
|
|
264
341
|
const { client, adapter } = await fixture()
|
|
@@ -270,12 +347,13 @@ test('preallocated Unicode and spaced output names resume without changing direc
|
|
|
270
347
|
})
|
|
271
348
|
|
|
272
349
|
test('corrupt or missing recovery materials fail rather than execute', async () => {
|
|
273
|
-
for (const variant of ['bad-json', 'missing', 'symlink'] as const) {
|
|
350
|
+
for (const variant of ['bad-json', 'stale', 'missing', 'symlink'] as const) {
|
|
274
351
|
const options = await setup()
|
|
275
352
|
const { client, adapter } = await fixture()
|
|
276
353
|
const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
|
|
277
354
|
const path = join(options.directory, first.runId, 'journal.json')
|
|
278
355
|
if (variant === 'bad-json') await writeFile(path, '{broken')
|
|
356
|
+
else if (variant === 'stale') await writeFile(path, '[]')
|
|
279
357
|
else {
|
|
280
358
|
await rm(path)
|
|
281
359
|
if (variant === 'symlink') await symlink(join(options.directory, first.runId, 'run.json'), path)
|
|
@@ -286,15 +364,17 @@ test('corrupt or missing recovery materials fail rather than execute', async ()
|
|
|
286
364
|
}
|
|
287
365
|
})
|
|
288
366
|
|
|
289
|
-
test('
|
|
367
|
+
test('rejects correctly digested manifests with older format versions', async () => {
|
|
290
368
|
const options = await setup()
|
|
291
369
|
const { client } = await fixture()
|
|
292
370
|
const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
|
|
293
371
|
const manifestPath = join(options.directory, first.runId, 'run.json')
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
372
|
+
const { recordDigest: _, ...payload } = JSON.parse(await readFile(manifestPath, 'utf8'))
|
|
373
|
+
for (const checkpointFormatVersion of [1, 2]) {
|
|
374
|
+
await writeFile(manifestPath, canonicalJson(record({ ...payload, checkpointFormatVersion })))
|
|
375
|
+
await expect(workflow({ ...options, resumeFrom: first.runId }, () => 'bad'))
|
|
376
|
+
.rejects.toMatchObject({ code: 'WORKFLOW_CHECKPOINT_INVALID' })
|
|
377
|
+
}
|
|
298
378
|
})
|
|
299
379
|
|
|
300
380
|
test('strict JSON rejects lossy inputs and canonical hashes ignore object insertion order', () => {
|
|
@@ -310,15 +390,12 @@ test('strict JSON rejects lossy inputs and canonical hashes ignore object insert
|
|
|
310
390
|
test('real process death at durable boundaries replays committed agent work only', async () => {
|
|
311
391
|
for (const phase of ['before-started', 'after-execute', 'before-final', 'after-later-result']) {
|
|
312
392
|
const options = await setup()
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
const adapter = createScriptedAdapter()
|
|
320
|
-
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
|
|
321
|
-
clients.push(client)
|
|
393
|
+
await runCrashFixture(options.directory, phase, 137)
|
|
394
|
+
if (phase === 'before-started' || phase === 'after-execute') {
|
|
395
|
+
const journal = JSON.parse(await readFile(join(options.directory, 'crashed', 'journal.json'), 'utf8')) as JournalEvent[]
|
|
396
|
+
expect(journal.map(event => event.type)).toEqual(phase === 'before-started' ? [] : ['started'])
|
|
397
|
+
}
|
|
398
|
+
const { client, adapter } = await crashClient()
|
|
322
399
|
const result = await workflow({ ...options, name: 'crash-test', resumeFrom: 'crashed' }, async () => {
|
|
323
400
|
const first = agent('work', { client, cwd: options.directory })
|
|
324
401
|
// An unfinished first key permits a rerun without invalidating the second key's saved result.
|
|
@@ -337,6 +414,56 @@ test('real process death at durable boundaries replays committed agent work only
|
|
|
337
414
|
}
|
|
338
415
|
}, 15000)
|
|
339
416
|
|
|
417
|
+
test('a retry invalidates inherited suffix results even when the process dies before the next call', async () => {
|
|
418
|
+
const options = { ...await setup(), name: 'crash-test' }
|
|
419
|
+
const fail = failingExecute({ code: 'NATIVE_FAILED', message: 'failed', retryable: false, outcomeUnknown: false })
|
|
420
|
+
const { client: sourceClient } = await crashClient({
|
|
421
|
+
async execute(call, sink) {
|
|
422
|
+
if (call.method === 'input/submit' && 'input' in call.params
|
|
423
|
+
&& call.params.input.some(part => part.type === 'text' && part.text === 'work')) return fail(call, sink)
|
|
424
|
+
return undefined
|
|
425
|
+
},
|
|
426
|
+
})
|
|
427
|
+
const cwd = options.directory
|
|
428
|
+
const source = await workflow({ ...options, runId: 'source' }, async () => {
|
|
429
|
+
await agent('prefix', { client: sourceClient, cwd })
|
|
430
|
+
await expect(agent('work', { client: sourceClient, cwd })).rejects.toMatchObject({ code: 'NATIVE_FAILED' })
|
|
431
|
+
return agent('later', { client: sourceClient, cwd })
|
|
432
|
+
})
|
|
433
|
+
expect(source.status).toBe('incomplete')
|
|
434
|
+
expect(source.result).toBe('later')
|
|
435
|
+
await runCrashFixture(cwd, 'after-retry', 137)
|
|
436
|
+
const journal = JSON.parse(await readFile(join(cwd, 'crashed', 'journal.json'), 'utf8')) as JournalEvent[]
|
|
437
|
+
expect(journal.slice(-2)).toMatchObject([{ type: 'started' }, { type: 'result', result: 'work' }])
|
|
438
|
+
|
|
439
|
+
const { client, adapter } = await crashClient()
|
|
440
|
+
const result = await workflow({ ...options, resumeFrom: 'crashed' }, async () => {
|
|
441
|
+
const prefix = await agent('prefix', { client, cwd })
|
|
442
|
+
const work = await agent('work', { client, cwd })
|
|
443
|
+
const later = await agent('later', { client, cwd })
|
|
444
|
+
return [prefix, work, later]
|
|
445
|
+
})
|
|
446
|
+
expect(result.result).toEqual(['prefix', 'work', 'later'])
|
|
447
|
+
const submissions = adapter.calls.filter(call => call.method === 'input/submit')
|
|
448
|
+
expect(submissions).toHaveLength(1)
|
|
449
|
+
expect(submissions[0]?.params).toMatchObject({ input: [{ type: 'text', text: 'later' }] })
|
|
450
|
+
})
|
|
451
|
+
|
|
452
|
+
async function runCrashFixture(directory: string, phase: string, exitCode: number): Promise<void> {
|
|
453
|
+
const child = Bun.spawn([process.execPath, fileURLToPath(new URL('./fixtures/workflow-crash.ts', import.meta.url)),
|
|
454
|
+
directory, phase], { stdout: 'ignore', stderr: 'pipe' })
|
|
455
|
+
const error = await new Response(child.stderr).text()
|
|
456
|
+
expect(error).toBe('')
|
|
457
|
+
expect(await child.exited).toBe(exitCode)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
async function crashClient(options?: FakeAdapterOptions) {
|
|
461
|
+
const adapter = createScriptedAdapter(options)
|
|
462
|
+
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
|
|
463
|
+
clients.push(client)
|
|
464
|
+
return { client, adapter }
|
|
465
|
+
}
|
|
466
|
+
|
|
340
467
|
test('an interrupted run reuses the unchanged call prefix in original order', async () => {
|
|
341
468
|
const options = await setup()
|
|
342
469
|
const { client, adapter } = await fixture()
|