@anureo/workflow 0.3.4 → 0.3.7
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 +102 -82
- package/package.json +9 -8
- package/src/agent-adapters.test.ts +121 -0
- package/src/agent-execution.ts +228 -0
- package/src/agent.test.ts +237 -51
- package/src/agent.ts +61 -92
- package/src/fixtures/workflow-crash.ts +54 -17
- package/src/index.ts +6 -2
- package/src/journal-call.test.ts +2 -10
- package/src/journal-call.ts +44 -32
- package/src/output-schema.test.ts +45 -12
- package/src/output-schema.ts +208 -96
- package/src/parallel.test.ts +1 -0
- package/src/parallel.ts +26 -8
- package/src/persistence/checkpoint-files.ts +83 -0
- package/src/persistence/journal.ts +98 -82
- package/src/persistence/json.ts +58 -32
- package/src/persistence/records.ts +82 -56
- package/src/persistence/replay.ts +74 -30
- package/src/persistence/store.ts +260 -120
- package/src/pipeline.test.ts +19 -0
- package/src/pipeline.ts +69 -23
- package/src/test-helpers.ts +24 -0
- package/src/workflow-state.ts +72 -18
- package/src/workflow-types.ts +20 -2
- package/src/workflow.test.ts +204 -97
- package/src/workflow.ts +88 -30
- package/src/agent-outcome.ts +0 -21
- package/src/agent-pi.test.ts +0 -21
- package/src/native.test.ts +0 -71
- package/src/persistence/atomic.ts +0 -32
- package/src/run-context.ts +0 -19
package/src/workflow.test.ts
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
+
import { createFixture } from './test-helpers'
|
|
1
2
|
import { afterEach, expect, test } from 'bun:test'
|
|
2
3
|
import { randomUUID } from 'node:crypto'
|
|
3
4
|
import { mkdir, mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises'
|
|
4
5
|
import { tmpdir } from 'node:os'
|
|
5
6
|
import { join } from 'node:path'
|
|
6
7
|
import { fileURLToPath } from 'node:url'
|
|
7
|
-
import { createClient, HarnessSdkError, type Client
|
|
8
|
-
import { createScriptedAdapter, type FakeAdapterOptions
|
|
8
|
+
import { createClient, HarnessSdkError, type Client } from '@anureo/sdk'
|
|
9
|
+
import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
|
|
9
10
|
import type { HarnessError } from '@anureo/protocol'
|
|
10
11
|
import { z } from 'zod'
|
|
11
|
-
import { workflow,
|
|
12
|
+
import { workflow, parallel, agent, type WorkflowOptions } from './index'
|
|
12
13
|
import { canonicalJson, digest } from './persistence/json'
|
|
14
|
+
import { record, type JournalEvent } from './persistence/records'
|
|
13
15
|
|
|
14
16
|
const clients: Client[] = []
|
|
17
|
+
const fixture = createFixture(clients)
|
|
15
18
|
const roots: string[] = []
|
|
16
19
|
afterEach(async () => {
|
|
17
20
|
await Promise.all(clients.splice(0).map(client => client.dispose()))
|
|
18
21
|
await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true })))
|
|
19
22
|
})
|
|
23
|
+
/** Create isolated run storage; afterEach removes it after disposing the test's clients. */
|
|
20
24
|
async function setup() {
|
|
21
25
|
const directory = await mkdtemp(join(tmpdir(), 'anureo-workflow-'))
|
|
22
26
|
roots.push(directory)
|
|
23
27
|
return { directory, name: 'test', revision: '1', input: {} }
|
|
24
28
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
clients.push(client)
|
|
29
|
-
return { client, adapter }
|
|
30
|
-
}
|
|
31
|
-
/** Emits a failed terminal turn outcome, mirroring native failures. */
|
|
29
|
+
|
|
30
|
+
/** Supply a scripted input/submit handler that emits terminal failure before returning acceptance.
|
|
31
|
+
* Returning undefined for other calls lets the scripted adapter apply its default behavior. */
|
|
32
32
|
function failingExecute(error: HarnessError): NonNullable<FakeAdapterOptions['execute']> {
|
|
33
33
|
return async (call, sink) => {
|
|
34
34
|
if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
|
|
35
35
|
const turnId = randomUUID()
|
|
36
36
|
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
37
37
|
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error } }, { turnId })
|
|
38
|
-
return { submissionId:
|
|
38
|
+
return { submissionId: call.params.submissionId,
|
|
39
39
|
accepted: true, disposition: 'started', turnId }
|
|
40
40
|
}
|
|
41
41
|
}
|
|
@@ -51,7 +51,7 @@ test('run identity is durable before body, inputs are isolated, and results are
|
|
|
51
51
|
const manifest = JSON.parse(await readFile(join(options.directory, run.runId, 'run.json'), 'utf8'))
|
|
52
52
|
expect(manifest.identity.runId).toBe(run.runId)
|
|
53
53
|
expect(manifest.status).toBe('running')
|
|
54
|
-
expect(manifest.checkpointFormatVersion).toBe(
|
|
54
|
+
expect(manifest.checkpointFormatVersion).toBe(3)
|
|
55
55
|
expect(Object.isFrozen(run.input.values)).toBe(true)
|
|
56
56
|
expect(Object.isFrozen(options.input.values)).toBe(false)
|
|
57
57
|
return agent('hello', { client, cwd: options.directory })
|
|
@@ -63,64 +63,28 @@ test('run identity is durable before body, inputs are isolated, and results are
|
|
|
63
63
|
const journal = JSON.parse(await readFile(join(options.directory, result.runId, 'journal.json'), 'utf8'))
|
|
64
64
|
expect(journal).toHaveLength(2)
|
|
65
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))
|
|
66
68
|
})
|
|
67
69
|
|
|
68
70
|
test('resumed runs replay identical agent calls from the journal without new sessions', async () => {
|
|
69
71
|
const options = await setup()
|
|
70
72
|
const { client, adapter } = await fixture()
|
|
71
|
-
const
|
|
72
|
-
agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) })
|
|
73
|
+
const body = async () =>
|
|
74
|
+
agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) })
|
|
75
|
+
const first = await workflow(options, body)
|
|
73
76
|
expect(adapter.opened).toHaveLength(1)
|
|
74
77
|
expect(first.result).toEqual({ value: 1 })
|
|
75
|
-
const second = await workflow({ ...options, resumeFrom: first.runId },
|
|
76
|
-
agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) }))
|
|
78
|
+
const second = await workflow({ ...options, resumeFrom: first.runId }, body)
|
|
77
79
|
expect(adapter.opened).toHaveLength(1)
|
|
78
80
|
expect(second.result).toEqual({ value: 1 })
|
|
79
81
|
// The resumed run carries its own journal copy; the source can be deleted.
|
|
80
82
|
await rm(join(options.directory, first.runId), { recursive: true })
|
|
81
|
-
const third = await workflow({ ...options, resumeFrom: second.runId },
|
|
82
|
-
agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) }))
|
|
83
|
+
const third = await workflow({ ...options, resumeFrom: second.runId }, body)
|
|
83
84
|
expect(adapter.opened).toHaveLength(1)
|
|
84
85
|
expect(third.result).toEqual({ value: 1 })
|
|
85
86
|
})
|
|
86
87
|
|
|
87
|
-
test('workflow reuses results only under the same input hook revision', async () => {
|
|
88
|
-
const options = await setup()
|
|
89
|
-
const identity = { adapterId: 'scripted', runtimeConfigId: 'input-policy' }
|
|
90
|
-
const without = await fixture(undefined, { identity })
|
|
91
|
-
const calls: string[] = []
|
|
92
|
-
const withPolicy = (inputRevision: string) => fixture(undefined, { identity, hooks: {
|
|
93
|
-
inputRevision,
|
|
94
|
-
transformInput: [() => {
|
|
95
|
-
calls.push(inputRevision)
|
|
96
|
-
return [{ type: 'text', text: 'transformed' }]
|
|
97
|
-
}],
|
|
98
|
-
} })
|
|
99
|
-
const v1 = await withPolicy('1')
|
|
100
|
-
const same = await withPolicy('1')
|
|
101
|
-
const v2 = await withPolicy('2')
|
|
102
|
-
const execute = (client: Client) => agent('original', { client, cwd: options.directory })
|
|
103
|
-
const original = await workflow(options, () => execute(without.client))
|
|
104
|
-
const policy = await workflow(options, () => execute(v1.client))
|
|
105
|
-
expect(policy.result).toBe('transformed')
|
|
106
|
-
await expect(workflow({ ...options, resumeFrom: policy.runId }, () => execute(same.client)))
|
|
107
|
-
.resolves.toMatchObject({ result: 'transformed' })
|
|
108
|
-
expect(same.adapter.opened).toHaveLength(0)
|
|
109
|
-
const scenarios = [
|
|
110
|
-
[original.runId, v1.client], [policy.runId, without.client], [policy.runId, v2.client],
|
|
111
|
-
] as const
|
|
112
|
-
for (const [runId, client] of scenarios) {
|
|
113
|
-
await expect(workflow({ ...options, resumeFrom: runId }, async () => {
|
|
114
|
-
try { await execute(client) } catch {}
|
|
115
|
-
try { await agent('later', { client, cwd: options.directory }) } catch {}
|
|
116
|
-
})).rejects.toMatchObject({ code: 'WORKFLOW_INPUT_POLICY_CHANGED', outcomeUnknown: false })
|
|
117
|
-
}
|
|
118
|
-
expect(v1.adapter.opened).toHaveLength(1)
|
|
119
|
-
expect(without.adapter.opened).toHaveLength(1)
|
|
120
|
-
expect(v2.adapter.opened).toHaveLength(0)
|
|
121
|
-
expect(calls).toEqual(['1'])
|
|
122
|
-
})
|
|
123
|
-
|
|
124
88
|
test('chained keys invalidate the downstream prefix when any call changes', async () => {
|
|
125
89
|
const options = await setup()
|
|
126
90
|
const { client, adapter } = await fixture()
|
|
@@ -156,6 +120,17 @@ test('prompt, options, and client identity changes miss the cache', async () =>
|
|
|
156
120
|
expect(other.adapter.opened).toHaveLength(1)
|
|
157
121
|
})
|
|
158
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
|
+
|
|
159
134
|
test('name or revision changes reject resume before the body runs', async () => {
|
|
160
135
|
const options = await setup()
|
|
161
136
|
const { client } = await fixture()
|
|
@@ -201,24 +176,77 @@ test('unknown previous outcomes require reconciliation instead of silent re-exec
|
|
|
201
176
|
const { client, adapter } = await fixture({
|
|
202
177
|
execute: failingExecute({ code: 'NATIVE_FAILED', message: 'unknown', retryable: false, outcomeUnknown: true }),
|
|
203
178
|
})
|
|
204
|
-
const failure = await workflow(options, () => agent('unknown', { client, cwd: options.directory }))
|
|
205
|
-
.then(
|
|
206
|
-
|
|
179
|
+
const failure: unknown = await workflow(options, () => agent('unknown', { client, cwd: options.directory }))
|
|
180
|
+
.then(
|
|
181
|
+
value => { throw new Error(`expected rejection, completed with ${JSON.stringify(value)}`) },
|
|
182
|
+
cause => cause,
|
|
183
|
+
)
|
|
207
184
|
expect(failure).toBeInstanceOf(HarnessSdkError)
|
|
185
|
+
if (!(failure instanceof HarnessSdkError)) throw failure
|
|
208
186
|
expect(failure.outcomeUnknown).toBe(true)
|
|
209
187
|
expect(adapter.opened).toHaveLength(1)
|
|
210
|
-
|
|
188
|
+
const runId = failure.details?.runId
|
|
189
|
+
if (typeof runId !== 'string') throw new Error('expected the failed run ID')
|
|
190
|
+
await expect(workflow({ ...options, resumeFrom: runId }, () =>
|
|
211
191
|
agent('unknown', { client, cwd: options.directory })))
|
|
212
192
|
.rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
193
|
+
const revisedAdapter = createScriptedAdapter()
|
|
194
|
+
const revised = {
|
|
195
|
+
client: await createClient({ adapter: revisedAdapter, identity: client.identity, hooks: { inputRevision: 'new', beforeInput: [() => undefined] } }),
|
|
196
|
+
adapter: revisedAdapter,
|
|
197
|
+
}
|
|
198
|
+
clients.push(revised.client)
|
|
199
|
+
await expect(workflow({ ...options, resumeFrom: runId }, () =>
|
|
216
200
|
agent('unknown', { client: revised.client, cwd: options.directory })))
|
|
217
201
|
.rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
|
|
218
202
|
expect(adapter.opened).toHaveLength(1)
|
|
219
203
|
expect(revised.adapter.opened).toHaveLength(0)
|
|
220
204
|
})
|
|
221
205
|
|
|
206
|
+
test('a failed journal replacement preserves exact-key uncertainty in the manifest', async () => {
|
|
207
|
+
const options = { ...await setup(), name: 'crash-test' }
|
|
208
|
+
await runCrashFixture(options.directory, 'unpublished-unknown', 0)
|
|
209
|
+
const source = join(options.directory, 'crashed')
|
|
210
|
+
const journal = JSON.parse(await readFile(join(source, 'journal.json'), 'utf8')) as JournalEvent[]
|
|
211
|
+
expect(journal.map(event => event.type)).toEqual(['started'])
|
|
212
|
+
const manifest = JSON.parse(await readFile(join(source, 'run.json'), 'utf8'))
|
|
213
|
+
expect(manifest).toMatchObject({ status: 'failed', journalDigest: digest(journal), failure: {
|
|
214
|
+
outcomeUnknown: true,
|
|
215
|
+
unpublishedUnknownFailures: [{
|
|
216
|
+
...journal[0], type: 'failed', code: 'NATIVE_FAILED', outcomeUnknown: true,
|
|
217
|
+
}],
|
|
218
|
+
} })
|
|
219
|
+
|
|
220
|
+
const { client, adapter } = await crashClient()
|
|
221
|
+
const resumed = { ...options, resumeFrom: 'crashed' }
|
|
222
|
+
await expect(workflow({ ...resumed, runId: 'blocked' }, () => agent('work', { client, cwd: options.directory })))
|
|
223
|
+
.rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
|
|
224
|
+
await expect(workflow({ ...resumed, resumeFrom: 'blocked' }, () => agent('work', { client, cwd: options.directory })))
|
|
225
|
+
.rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
|
|
226
|
+
expect(adapter.opened).toHaveLength(0)
|
|
227
|
+
const other = await workflow(resumed, () => agent('other', { client, cwd: options.directory }))
|
|
228
|
+
expect(other.result).toBe('other')
|
|
229
|
+
await writeFile(join(source, 'journal.json'), '[]')
|
|
230
|
+
await expect(workflow(resumed, () => agent('work', { client, cwd: options.directory })))
|
|
231
|
+
.rejects.toMatchObject({ code: 'WORKFLOW_CHECKPOINT_INVALID' })
|
|
232
|
+
expect(adapter.opened).toHaveLength(1)
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
test('workflow rejections preserve schema diagnostics outside the stored failure summary', async () => {
|
|
236
|
+
const options = { ...await setup(), runId: 'schema-error' }
|
|
237
|
+
const { client, adapter } = await fixture()
|
|
238
|
+
await expect(workflow(options, () => agent('work', {
|
|
239
|
+
client, cwd: options.directory, schema: z.strictObject({ value: z.string().optional() }),
|
|
240
|
+
}))).rejects.toMatchObject({
|
|
241
|
+
code: 'INVALID_PARAMS', details: { rule: 'valueConversionOrNonportableType', runId: options.runId },
|
|
242
|
+
})
|
|
243
|
+
const manifest = JSON.parse(await readFile(join(options.directory, options.runId, 'run.json'), 'utf8'))
|
|
244
|
+
expect(manifest.failure).toEqual({
|
|
245
|
+
code: 'INVALID_PARAMS', retryable: false, outcomeUnknown: false, cleanupFailed: false,
|
|
246
|
+
})
|
|
247
|
+
expect(adapter.opened).toHaveLength(0)
|
|
248
|
+
})
|
|
249
|
+
|
|
222
250
|
test('storage failure is sticky and blocks subsequent agent dispatch', async () => {
|
|
223
251
|
const options = await setup()
|
|
224
252
|
const { client, adapter } = await fixture()
|
|
@@ -240,16 +268,14 @@ test('storage failure is sticky and blocks subsequent agent dispatch', async ()
|
|
|
240
268
|
test('body completion waits for already registered unawaited agent work', async () => {
|
|
241
269
|
const options = await setup()
|
|
242
270
|
const { client } = await fixture()
|
|
243
|
-
|
|
244
|
-
const wait = new Promise<void>(done => { resolve = done })
|
|
271
|
+
const entered = Promise.withResolvers<void>()
|
|
245
272
|
let ended = false
|
|
246
273
|
const result = workflow(options, () => {
|
|
247
274
|
void agent('slow', { client, cwd: options.directory }).then(() => { ended = true })
|
|
248
|
-
|
|
249
|
-
resolve()
|
|
275
|
+
entered.resolve()
|
|
250
276
|
return 'body'
|
|
251
277
|
})
|
|
252
|
-
await
|
|
278
|
+
await entered.promise
|
|
253
279
|
expect((await result).status).toBe('completed')
|
|
254
280
|
expect(ended).toBe(true)
|
|
255
281
|
})
|
|
@@ -270,29 +296,33 @@ test('agent calls detached from the run context execute as ordinary unjournaled
|
|
|
270
296
|
test('source activity, target competition, and reused explicit ids reject before body', async () => {
|
|
271
297
|
const options = await setup()
|
|
272
298
|
const { client } = await fixture()
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
const ready = new Promise<void>(done => { entered = done })
|
|
276
|
-
const waiting = new Promise<void>(done => { release = done })
|
|
299
|
+
const entered = Promise.withResolvers<void>()
|
|
300
|
+
const release = Promise.withResolvers<void>()
|
|
277
301
|
const first = workflow({ ...options, runId: 'owned' }, async () => {
|
|
278
|
-
entered()
|
|
302
|
+
entered.resolve()
|
|
279
303
|
await agent('held', { client, cwd: options.directory })
|
|
280
|
-
await
|
|
304
|
+
await release.promise
|
|
281
305
|
return 'done'
|
|
282
306
|
})
|
|
283
|
-
await
|
|
307
|
+
await entered.promise
|
|
284
308
|
try {
|
|
285
309
|
await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
|
|
286
310
|
await expect(workflow({ ...options, resumeFrom: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_SOURCE_ACTIVE' })
|
|
287
|
-
} finally {
|
|
311
|
+
} finally {
|
|
312
|
+
release.resolve()
|
|
313
|
+
await first
|
|
314
|
+
}
|
|
288
315
|
await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
|
|
289
316
|
})
|
|
290
317
|
|
|
291
318
|
test('initialization rejects invalid identities and releases a failed target claim before entering body', async () => {
|
|
292
319
|
const options = await setup()
|
|
293
320
|
let entered = false
|
|
294
|
-
await expect(workflow({ ...options, runId: '../escape' }, () => { entered = true; return {} }))
|
|
295
|
-
.rejects.toMatchObject({
|
|
321
|
+
await expect(workflow({ ...options, runId: '../escape', revision: '' }, () => { entered = true; return {} }))
|
|
322
|
+
.rejects.toMatchObject({
|
|
323
|
+
code: 'INVALID_PARAMS',
|
|
324
|
+
message: 'Invalid workflow options: runId must be a valid directory basename (at most 255 UTF-8 bytes), revision must be a nonempty string',
|
|
325
|
+
})
|
|
296
326
|
const { client } = await fixture()
|
|
297
327
|
const original = await workflow({ ...options, runId: 'source' }, () => agent('a', { client, cwd: options.directory }))
|
|
298
328
|
await expect(workflow({ ...options, name: 'incompatible', runId: 'target', resumeFrom: original.runId }, () => {
|
|
@@ -302,6 +332,22 @@ test('initialization rejects invalid identities and releases a failed target cla
|
|
|
302
332
|
expect(await readdir(join(options.directory, 'target'))).not.toContain('writer.lock')
|
|
303
333
|
})
|
|
304
334
|
|
|
335
|
+
test('overlapping target roots are rejected without creating directories in the source', async () => {
|
|
336
|
+
const options = await setup()
|
|
337
|
+
const first = await workflow(options, () => 'source')
|
|
338
|
+
const source = join(options.directory, first.runId)
|
|
339
|
+
const alias = join(options.directory, 'alias')
|
|
340
|
+
await symlink(source, alias, 'dir')
|
|
341
|
+
const original = await readdir(source)
|
|
342
|
+
for (const root of [source, alias]) {
|
|
343
|
+
await expect(workflow({
|
|
344
|
+
...options, directory: join(root, 'missing', 'nested'),
|
|
345
|
+
resumeFrom: { directory: options.directory, runId: first.runId },
|
|
346
|
+
}, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_OVERLAPPING_RUNS' })
|
|
347
|
+
expect(await readdir(source)).toEqual(original)
|
|
348
|
+
}
|
|
349
|
+
})
|
|
350
|
+
|
|
305
351
|
test('preallocated Unicode and spaced output names resume without changing directory meaning', async () => {
|
|
306
352
|
const options = await setup()
|
|
307
353
|
const { client, adapter } = await fixture()
|
|
@@ -313,12 +359,13 @@ test('preallocated Unicode and spaced output names resume without changing direc
|
|
|
313
359
|
})
|
|
314
360
|
|
|
315
361
|
test('corrupt or missing recovery materials fail rather than execute', async () => {
|
|
316
|
-
for (const variant of ['bad-json', 'missing', 'symlink'] as const) {
|
|
362
|
+
for (const variant of ['bad-json', 'stale', 'missing', 'symlink'] as const) {
|
|
317
363
|
const options = await setup()
|
|
318
364
|
const { client, adapter } = await fixture()
|
|
319
365
|
const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
|
|
320
366
|
const path = join(options.directory, first.runId, 'journal.json')
|
|
321
367
|
if (variant === 'bad-json') await writeFile(path, '{broken')
|
|
368
|
+
else if (variant === 'stale') await writeFile(path, '[]')
|
|
322
369
|
else {
|
|
323
370
|
await rm(path)
|
|
324
371
|
if (variant === 'symlink') await symlink(join(options.directory, first.runId, 'run.json'), path)
|
|
@@ -329,15 +376,17 @@ test('corrupt or missing recovery materials fail rather than execute', async ()
|
|
|
329
376
|
}
|
|
330
377
|
})
|
|
331
378
|
|
|
332
|
-
test('
|
|
379
|
+
test('rejects correctly digested manifests with older format versions', async () => {
|
|
333
380
|
const options = await setup()
|
|
334
381
|
const { client } = await fixture()
|
|
335
382
|
const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
|
|
336
383
|
const manifestPath = join(options.directory, first.runId, 'run.json')
|
|
337
|
-
const
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
384
|
+
const { recordDigest: _, ...payload } = JSON.parse(await readFile(manifestPath, 'utf8'))
|
|
385
|
+
for (const checkpointFormatVersion of [1, 2]) {
|
|
386
|
+
await writeFile(manifestPath, canonicalJson(record({ ...payload, checkpointFormatVersion })))
|
|
387
|
+
await expect(workflow({ ...options, resumeFrom: first.runId }, () => 'bad'))
|
|
388
|
+
.rejects.toMatchObject({ code: 'WORKFLOW_CHECKPOINT_INVALID' })
|
|
389
|
+
}
|
|
341
390
|
})
|
|
342
391
|
|
|
343
392
|
test('strict JSON rejects lossy inputs and canonical hashes ignore object insertion order', () => {
|
|
@@ -351,25 +400,82 @@ test('strict JSON rejects lossy inputs and canonical hashes ignore object insert
|
|
|
351
400
|
})
|
|
352
401
|
|
|
353
402
|
test('real process death at durable boundaries replays committed agent work only', async () => {
|
|
354
|
-
for (const phase of ['before-started', 'after-execute', 'before-final']) {
|
|
403
|
+
for (const phase of ['before-started', 'after-execute', 'before-final', 'after-later-result']) {
|
|
355
404
|
const options = await setup()
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
const
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
405
|
+
await runCrashFixture(options.directory, phase, 137)
|
|
406
|
+
if (phase === 'before-started' || phase === 'after-execute') {
|
|
407
|
+
const journal = JSON.parse(await readFile(join(options.directory, 'crashed', 'journal.json'), 'utf8')) as JournalEvent[]
|
|
408
|
+
expect(journal.map(event => event.type)).toEqual(phase === 'before-started' ? [] : ['started'])
|
|
409
|
+
}
|
|
410
|
+
const { client, adapter } = await crashClient()
|
|
411
|
+
const result = await workflow({ ...options, name: 'crash-test', resumeFrom: 'crashed' }, async () => {
|
|
412
|
+
const first = agent('work', { client, cwd: options.directory })
|
|
413
|
+
// An unfinished first key permits a rerun without invalidating the second key's saved result.
|
|
414
|
+
return phase === 'after-later-result'
|
|
415
|
+
? Promise.all([first, agent('later', { client, cwd: options.directory })])
|
|
416
|
+
: first
|
|
417
|
+
})
|
|
418
|
+
expect(result.result).toEqual(phase === 'after-later-result' ? ['work', 'later'] : 'work')
|
|
368
419
|
expect(adapter.opened).toHaveLength(phase === 'before-final' ? 0 : 1)
|
|
420
|
+
if (phase === 'after-later-result') {
|
|
421
|
+
const submissions = adapter.calls.filter(call => call.method === 'input/submit')
|
|
422
|
+
expect(submissions).toHaveLength(1)
|
|
423
|
+
expect(submissions[0]?.params).toMatchObject({ input: [{ type: 'text', text: 'work' }] })
|
|
424
|
+
}
|
|
369
425
|
await client.dispose()
|
|
370
426
|
}
|
|
371
427
|
}, 15000)
|
|
372
428
|
|
|
429
|
+
test('a retry invalidates inherited suffix results even when the process dies before the next call', async () => {
|
|
430
|
+
const options = { ...await setup(), name: 'crash-test' }
|
|
431
|
+
const fail = failingExecute({ code: 'NATIVE_FAILED', message: 'failed', retryable: false, outcomeUnknown: false })
|
|
432
|
+
const { client: sourceClient } = await crashClient({
|
|
433
|
+
async execute(call, sink) {
|
|
434
|
+
if (call.method === 'input/submit' && 'input' in call.params
|
|
435
|
+
&& call.params.input.some(part => part.type === 'text' && part.text === 'work')) return fail(call, sink)
|
|
436
|
+
return undefined
|
|
437
|
+
},
|
|
438
|
+
})
|
|
439
|
+
const cwd = options.directory
|
|
440
|
+
const source = await workflow({ ...options, runId: 'source' }, async () => {
|
|
441
|
+
await agent('prefix', { client: sourceClient, cwd })
|
|
442
|
+
await expect(agent('work', { client: sourceClient, cwd })).rejects.toMatchObject({ code: 'NATIVE_FAILED' })
|
|
443
|
+
return agent('later', { client: sourceClient, cwd })
|
|
444
|
+
})
|
|
445
|
+
expect(source.status).toBe('incomplete')
|
|
446
|
+
expect(source.result).toBe('later')
|
|
447
|
+
await runCrashFixture(cwd, 'after-retry', 137)
|
|
448
|
+
const journal = JSON.parse(await readFile(join(cwd, 'crashed', 'journal.json'), 'utf8')) as JournalEvent[]
|
|
449
|
+
expect(journal.slice(-2)).toMatchObject([{ type: 'started' }, { type: 'result', result: 'work' }])
|
|
450
|
+
|
|
451
|
+
const { client, adapter } = await crashClient()
|
|
452
|
+
const result = await workflow({ ...options, resumeFrom: 'crashed' }, async () => {
|
|
453
|
+
const prefix = await agent('prefix', { client, cwd })
|
|
454
|
+
const work = await agent('work', { client, cwd })
|
|
455
|
+
const later = await agent('later', { client, cwd })
|
|
456
|
+
return [prefix, work, later]
|
|
457
|
+
})
|
|
458
|
+
expect(result.result).toEqual(['prefix', 'work', 'later'])
|
|
459
|
+
const submissions = adapter.calls.filter(call => call.method === 'input/submit')
|
|
460
|
+
expect(submissions).toHaveLength(1)
|
|
461
|
+
expect(submissions[0]?.params).toMatchObject({ input: [{ type: 'text', text: 'later' }] })
|
|
462
|
+
})
|
|
463
|
+
|
|
464
|
+
async function runCrashFixture(directory: string, phase: string, exitCode: number): Promise<void> {
|
|
465
|
+
const child = Bun.spawn([process.execPath, fileURLToPath(new URL('./fixtures/workflow-crash.ts', import.meta.url)),
|
|
466
|
+
directory, phase], { stdout: 'ignore', stderr: 'pipe' })
|
|
467
|
+
const error = await new Response(child.stderr).text()
|
|
468
|
+
expect(error).toBe('')
|
|
469
|
+
expect(await child.exited).toBe(exitCode)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
async function crashClient(options?: FakeAdapterOptions) {
|
|
473
|
+
const adapter = createScriptedAdapter(options)
|
|
474
|
+
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
|
|
475
|
+
clients.push(client)
|
|
476
|
+
return { client, adapter }
|
|
477
|
+
}
|
|
478
|
+
|
|
373
479
|
test('an interrupted run reuses the unchanged call prefix in original order', async () => {
|
|
374
480
|
const options = await setup()
|
|
375
481
|
const { client, adapter } = await fixture()
|
|
@@ -389,6 +495,7 @@ test('an interrupted run reuses the unchanged call prefix in original order', as
|
|
|
389
495
|
expect(result.status).toBe('completed')
|
|
390
496
|
})
|
|
391
497
|
|
|
498
|
+
/** Compile-only consumer checks for context and awaited body-result inference; never invoked. */
|
|
392
499
|
function typeChecks(options: WorkflowOptions<{ files: string[] }>) {
|
|
393
500
|
const run = workflow(options, async context => {
|
|
394
501
|
const file: string = context.input.files[0]!
|
|
@@ -405,4 +512,4 @@ function typeChecks(options: WorkflowOptions<{ files: string[] }>) {
|
|
|
405
512
|
void negative
|
|
406
513
|
return positive
|
|
407
514
|
}
|
|
408
|
-
void typeChecks
|
|
515
|
+
void typeChecks
|
package/src/workflow.ts
CHANGED
|
@@ -1,11 +1,25 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
2
|
import { HarnessSdkError, sdkError } from '@anureo/sdk'
|
|
3
3
|
import type { WorkflowContext, WorkflowOptions, WorkflowResult } from './workflow-types'
|
|
4
|
-
import { RunState, storedFailure } from './workflow-state'
|
|
5
|
-
import { runWith } from './run-context'
|
|
4
|
+
import { RunState, runWith, storedFailure } from './workflow-state'
|
|
6
5
|
import { freezeJson, jsonCopy, type JsonValue } from './persistence/json'
|
|
7
6
|
import { openFileRun, type RunHandle } from './persistence/store'
|
|
8
7
|
|
|
8
|
+
/**
|
|
9
|
+
* Run a body with a durable identity, frozen JSON input and journaled agent calls. The body
|
|
10
|
+
* receives the new run's ID and input after initial publication. On resume the body starts from
|
|
11
|
+
* the beginning and eligible agent calls reuse saved results. Account for repeated side effects
|
|
12
|
+
* from body code and agent calls that execute again.
|
|
13
|
+
* Supply strict JSON for the input and awaited body result. Await your own background work inside
|
|
14
|
+
* the body. Keep borrowed clients alive until the workflow promise settles, then dispose them separately.
|
|
15
|
+
*
|
|
16
|
+
* Resolve with a JSON copy of the body result after registered agent work settles, publication
|
|
17
|
+
* succeeds and the writer lock is released. A drop or an ordinary failure in registered work can
|
|
18
|
+
* yield an incomplete result if the body still returns. Invalid inputs, uncaught body errors,
|
|
19
|
+
* fatal agent failures, and storage failures reject. Run failures report the run ID and storage
|
|
20
|
+
* root in SDK error details, using the supplied directory if initialization fails. A
|
|
21
|
+
* lock-release failure can reject after the result and terminal manifest have been published.
|
|
22
|
+
*/
|
|
9
23
|
export async function workflow<Input, Result>(
|
|
10
24
|
options: WorkflowOptions<Input>,
|
|
11
25
|
body: (run: WorkflowContext<Input>) => Result | Promise<Result>,
|
|
@@ -13,42 +27,86 @@ export async function workflow<Input, Result>(
|
|
|
13
27
|
const runId = options?.runId ?? randomUUID()
|
|
14
28
|
const state = new RunState()
|
|
15
29
|
let handle: RunHandle | undefined
|
|
16
|
-
let
|
|
30
|
+
let publishedResult: Awaited<Result> | undefined
|
|
17
31
|
try {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
const input = freezeJson(jsonCopy(options.input))
|
|
22
|
-
const resumeFrom = options.resumeFrom && typeof options.resumeFrom === 'object'
|
|
23
|
-
? { ...options.resumeFrom } : options.resumeFrom
|
|
24
|
-
handle = await openFileRun({ ...options, runId, input: input as JsonValue, resumeFrom })
|
|
25
|
-
const context: WorkflowContext<Input> = { runId, input }
|
|
26
|
-
try {
|
|
27
|
-
value = await runWith({ journal: handle.journal, state }, async () => body(context))
|
|
28
|
-
}
|
|
29
|
-
catch (cause) { state.stop(sdkError(cause, 'WORKFLOW_BODY_FAILED')) }
|
|
30
|
-
await state.closeAndDrain()
|
|
31
|
-
const failure = state.failure
|
|
32
|
-
if (failure) throw failure
|
|
33
|
-
value = jsonCopy(value)
|
|
34
|
-
await handle.finish(state.status, value as JsonValue)
|
|
32
|
+
const { storageOptions, context } = prepareRun(options, body, runId)
|
|
33
|
+
handle = await openFileRun(storageOptions)
|
|
34
|
+
publishedResult = await completeRun({ handle, state, body, context })
|
|
35
35
|
} catch (cause) {
|
|
36
|
-
|
|
37
|
-
await state.closeAndDrain()
|
|
38
|
-
if (handle) {
|
|
39
|
-
try { await handle.abort(storedFailure(state.failure!)) }
|
|
40
|
-
catch { state.stop(new HarnessSdkError('WORKFLOW_STORAGE_FAILED')) }
|
|
41
|
-
}
|
|
36
|
+
await abortRun({ cause, state, handle })
|
|
42
37
|
} finally {
|
|
43
38
|
if (handle) {
|
|
44
39
|
try { await handle.close() }
|
|
45
|
-
catch { state.
|
|
40
|
+
catch { state.noteStorageFailure() }
|
|
46
41
|
}
|
|
47
42
|
}
|
|
48
43
|
const failure = state.failure
|
|
49
44
|
if (failure) {
|
|
50
|
-
throw new HarnessSdkError(failure.code, failure.message, false, failure.outcomeUnknown,
|
|
51
|
-
|
|
45
|
+
throw new HarnessSdkError(failure.code, failure.message, false, failure.outcomeUnknown, {
|
|
46
|
+
...failure.details,
|
|
47
|
+
runId,
|
|
48
|
+
directory: handle?.identity.directory ?? options?.directory,
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
// A failed publication also stops the run, so only published results reach this return.
|
|
52
|
+
return { runId, status: state.status, result: publishedResult as Awaited<Result> }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Snapshot input and an object source reference before workflow awaits storage. The body gets a
|
|
56
|
+
* frozen input and the writer snapshots it separately. Malformed options, a non-function body or
|
|
57
|
+
* non-JSON input throw before storage opens. */
|
|
58
|
+
function prepareRun<Input, Result>(
|
|
59
|
+
options: WorkflowOptions<Input>,
|
|
60
|
+
body: (run: WorkflowContext<Input>) => Result | Promise<Result>,
|
|
61
|
+
runId: string,
|
|
62
|
+
): { storageOptions: WorkflowOptions<JsonValue> & { runId: string }; context: WorkflowContext<Input> } {
|
|
63
|
+
if (!options || typeof options !== 'object' || typeof body !== 'function') {
|
|
64
|
+
throw new HarnessSdkError('INVALID_PARAMS')
|
|
65
|
+
}
|
|
66
|
+
const input = freezeJson(jsonCopy(options.input))
|
|
67
|
+
const resumeFrom = options.resumeFrom && typeof options.resumeFrom === 'object'
|
|
68
|
+
? { ...options.resumeFrom } : options.resumeFrom
|
|
69
|
+
return {
|
|
70
|
+
storageOptions: { ...options, runId, input: input as JsonValue, resumeFrom },
|
|
71
|
+
context: { runId, input },
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Give the body access to the journal through the async context. Stop dispatch on an uncaught
|
|
76
|
+
* body failure and drain before choosing the terminal outcome, since settling agents can still
|
|
77
|
+
* change it. Return the JSON result after publication. workflow routes rejections through abortRun. */
|
|
78
|
+
async function completeRun<Input, Result>({ handle, state, body, context }: {
|
|
79
|
+
handle: RunHandle
|
|
80
|
+
state: RunState
|
|
81
|
+
body: (run: WorkflowContext<Input>) => Result | Promise<Result>
|
|
82
|
+
context: WorkflowContext<Input>
|
|
83
|
+
}): Promise<Awaited<Result>> {
|
|
84
|
+
let value: Awaited<Result> | undefined
|
|
85
|
+
try {
|
|
86
|
+
value = await runWith({ journal: handle.journal, state }, async () => body(context))
|
|
87
|
+
}
|
|
88
|
+
catch (cause) { state.stop(sdkError(cause, 'WORKFLOW_BODY_FAILED')) }
|
|
89
|
+
await state.closeAndDrain()
|
|
90
|
+
const failure = state.failure
|
|
91
|
+
if (failure) throw failure
|
|
92
|
+
const result = jsonCopy(value)
|
|
93
|
+
await handle.finish(state.status, result as JsonValue)
|
|
94
|
+
return result as Awaited<Result>
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Record workflow's failure and drain before publishing the aggregate to an acquired handle.
|
|
98
|
+
* Initialization failures can arrive before a handle exists. An abort publication error is
|
|
99
|
+
* recorded as a storage failure. workflow still releases the handle and reports the final aggregate. */
|
|
100
|
+
async function abortRun({ cause, state, handle }: {
|
|
101
|
+
cause: unknown
|
|
102
|
+
state: RunState
|
|
103
|
+
handle: RunHandle | undefined
|
|
104
|
+
}): Promise<void> {
|
|
105
|
+
const error = sdkError(cause, 'WORKFLOW_FAILED')
|
|
106
|
+
state.stop(error)
|
|
107
|
+
await state.closeAndDrain()
|
|
108
|
+
if (handle) {
|
|
109
|
+
try { await handle.abort(storedFailure(state.failure ?? error)) }
|
|
110
|
+
catch { state.noteStorageFailure() }
|
|
52
111
|
}
|
|
53
|
-
return { runId, status: state.status, result: value as Awaited<Result> }
|
|
54
112
|
}
|
package/src/agent-outcome.ts
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import type { HarnessError } from '@anureo/protocol'
|
|
2
|
-
import { HarnessSdkError } from '@anureo/sdk'
|
|
3
|
-
|
|
4
|
-
// Only apply to native failed terminal results, never open/submit/observation failures.
|
|
5
|
-
const terminalApiErrors = new Set([
|
|
6
|
-
'AUTH_REQUIRED', 'AUTH_FORBIDDEN', 'USAGE_LIMIT_EXCEEDED', 'RATE_LIMITED', 'NATIVE_SERVICE_UNAVAILABLE',
|
|
7
|
-
])
|
|
8
|
-
|
|
9
|
-
export function isDroppedOutcome(error: HarnessError, status: 'failed' | 'interrupted'): boolean {
|
|
10
|
-
if (error.outcomeUnknown) return false
|
|
11
|
-
if (status === 'interrupted') return error.details?.workflowDisposition === 'skipped'
|
|
12
|
-
return isStartupBlocked(error) || terminalApiErrors.has(error.code)
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function isStartupBlocked(error: Pick<HarnessSdkError, 'code' | 'outcomeUnknown' | 'details'>): boolean {
|
|
16
|
-
return !error.outcomeUnknown && error.code === 'AGENT_STARTUP_BLOCKED' && error.details?.workflowDisposition === 'startup_blocked'
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export function isStartupBlockException(cause: unknown): cause is HarnessSdkError {
|
|
20
|
-
return cause instanceof HarnessSdkError && isStartupBlocked(cause)
|
|
21
|
-
}
|