@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.
@@ -1,47 +1,47 @@
1
- import { createFixture } from './test-helpers'
2
1
  import { afterEach, expect, test } from 'bun:test'
3
2
  import { randomUUID } from 'node:crypto'
4
- import { mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises'
3
+ import { mkdir, mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises'
5
4
  import { tmpdir } from 'node:os'
6
5
  import { join } from 'node:path'
7
6
  import { fileURLToPath } from 'node:url'
8
- import { createClient, HarnessSdkError, type Client } from '@anureo/sdk'
9
- import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
7
+ import { createClient, HarnessSdkError, type Client, type ClientOptions, type SessionEventSink } from '@anureo/sdk'
8
+ import { createScriptedAdapter, type FakeAdapterOptions, type FakeCall } from '@anureo/conformance'
10
9
  import type { HarnessError } from '@anureo/protocol'
11
10
  import { z } from 'zod'
12
- import { workflow, parallel, agent, type WorkflowOptions } from './index'
11
+ import { workflow, pipeline, parallel, agent, type WorkflowOptions } from './index'
13
12
  import { canonicalJson, digest } from './persistence/json'
14
- import { record, type JournalEvent } from './persistence/records'
15
13
 
16
14
  const clients: Client[] = []
17
- const fixture = createFixture(clients)
18
15
  const roots: string[] = []
19
16
  afterEach(async () => {
20
17
  await Promise.all(clients.splice(0).map(client => client.dispose()))
21
18
  await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true })))
22
19
  })
23
- /** Create isolated run storage; afterEach removes it after disposing the test's clients. */
24
20
  async function setup() {
25
21
  const directory = await mkdtemp(join(tmpdir(), 'anureo-workflow-'))
26
22
  roots.push(directory)
27
23
  return { directory, name: 'test', revision: '1', input: {} }
28
24
  }
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. */
25
+ async function fixture(options?: FakeAdapterOptions, clientOptions?: Partial<Pick<ClientOptions, 'identity' | 'hooks'>>) {
26
+ const adapter = createScriptedAdapter(options)
27
+ const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() }, ...clientOptions })
28
+ clients.push(client)
29
+ return { client, adapter }
30
+ }
31
+ /** Emits a failed terminal turn outcome, mirroring native failures. */
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: call.params.submissionId,
38
+ return { submissionId: (call.params as { submissionId: string }).submissionId,
39
39
  accepted: true, disposition: 'started', turnId }
40
40
  }
41
41
  }
42
42
 
43
43
  test('root runtime exports contain the four independently usable primitives', async () => {
44
- expect(Object.keys(await import('./index')).sort()).toEqual(['agent', 'parallel', 'pipeline', 'workflow'])
44
+ expect(Object.keys(await import('./index')).sort()).toEqual(['agent', 'isDroppedOutcome', 'journaledCall', 'parallel', 'pipeline', 'prepareOutputSchema', 'workflow'])
45
45
  })
46
46
 
47
47
  test('run identity is durable before body, inputs are isolated, and results are persisted', async () => {
@@ -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(3)
54
+ expect(manifest.checkpointFormatVersion).toBe(2)
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,28 +63,64 @@ 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))
68
66
  })
69
67
 
70
68
  test('resumed runs replay identical agent calls from the journal without new sessions', async () => {
71
69
  const options = await setup()
72
70
  const { client, adapter } = await fixture()
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)
71
+ const first = await workflow(options, async () =>
72
+ agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) }))
76
73
  expect(adapter.opened).toHaveLength(1)
77
74
  expect(first.result).toEqual({ value: 1 })
78
- const second = await workflow({ ...options, resumeFrom: first.runId }, body)
75
+ const second = await workflow({ ...options, resumeFrom: first.runId }, async () =>
76
+ agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) }))
79
77
  expect(adapter.opened).toHaveLength(1)
80
78
  expect(second.result).toEqual({ value: 1 })
81
79
  // The resumed run carries its own journal copy; the source can be deleted.
82
80
  await rm(join(options.directory, first.runId), { recursive: true })
83
- const third = await workflow({ ...options, resumeFrom: second.runId }, body)
81
+ const third = await workflow({ ...options, resumeFrom: second.runId }, async () =>
82
+ agent('{"value":1}', { client, cwd: options.directory, schema: z.strictObject({ value: z.number() }) }))
84
83
  expect(adapter.opened).toHaveLength(1)
85
84
  expect(third.result).toEqual({ value: 1 })
86
85
  })
87
86
 
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
+
88
124
  test('chained keys invalidate the downstream prefix when any call changes', async () => {
89
125
  const options = await setup()
90
126
  const { client, adapter } = await fixture()
@@ -120,17 +156,6 @@ test('prompt, options, and client identity changes miss the cache', async () =>
120
156
  expect(other.adapter.opened).toHaveLength(1)
121
157
  })
122
158
 
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
-
134
159
  test('name or revision changes reject resume before the body runs', async () => {
135
160
  const options = await setup()
136
161
  const { client } = await fixture()
@@ -176,65 +201,22 @@ test('unknown previous outcomes require reconciliation instead of silent re-exec
176
201
  const { client, adapter } = await fixture({
177
202
  execute: failingExecute({ code: 'NATIVE_FAILED', message: 'unknown', retryable: false, outcomeUnknown: true }),
178
203
  })
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
- )
204
+ const failure = await workflow(options, () => agent('unknown', { client, cwd: options.directory }))
205
+ .then(value => { throw new Error(`expected rejection, completed with ${JSON.stringify(value)}`) })
206
+ .catch(cause => cause as HarnessSdkError & { details: { runId: string } })
184
207
  expect(failure).toBeInstanceOf(HarnessSdkError)
185
- if (!(failure instanceof HarnessSdkError)) throw failure
186
208
  expect(failure.outcomeUnknown).toBe(true)
187
209
  expect(adapter.opened).toHaveLength(1)
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 }, () =>
210
+ await expect(workflow({ ...options, resumeFrom: failure.details.runId }, () =>
191
211
  agent('unknown', { client, cwd: options.directory })))
192
212
  .rejects.toMatchObject({ code: 'WORKFLOW_RECONCILIATION_REQUIRED' })
193
- expect(adapter.opened).toHaveLength(1)
194
- })
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 })))
213
+ const revised = await fixture(undefined, { identity: client.identity,
214
+ hooks: { inputRevision: 'new', beforeInput: [() => undefined] } })
215
+ await expect(workflow({ ...options, resumeFrom: failure.details.runId }, () =>
216
+ agent('unknown', { client: revised.client, cwd: options.directory })))
215
217
  .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
218
  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)
219
+ expect(revised.adapter.opened).toHaveLength(0)
238
220
  })
239
221
 
240
222
  test('storage failure is sticky and blocks subsequent agent dispatch', async () => {
@@ -243,8 +225,10 @@ test('storage failure is sticky and blocks subsequent agent dispatch', async ()
243
225
  let id = ''
244
226
  await expect(workflow(options, async run => {
245
227
  id = run.runId
246
- // Moving the run directory breaks every subsequent journal publication.
247
- await rename(join(options.directory, id), join(options.directory, `${id}-moved`))
228
+ // Block atomic replacement of the journal while leaving the open writer lock alone.
229
+ const journal = join(options.directory, id, 'journal.json')
230
+ await rm(journal)
231
+ await mkdir(journal)
248
232
  try { await agent('first', { client, cwd: options.directory }) } catch {}
249
233
  try { await agent('second', { client, cwd: options.directory }) } catch {}
250
234
  return 'caught'
@@ -256,14 +240,16 @@ test('storage failure is sticky and blocks subsequent agent dispatch', async ()
256
240
  test('body completion waits for already registered unawaited agent work', async () => {
257
241
  const options = await setup()
258
242
  const { client } = await fixture()
259
- const entered = Promise.withResolvers<void>()
243
+ let resolve!: () => void
244
+ const wait = new Promise<void>(done => { resolve = done })
260
245
  let ended = false
261
246
  const result = workflow(options, () => {
262
247
  void agent('slow', { client, cwd: options.directory }).then(() => { ended = true })
263
- entered.resolve()
248
+ void wait.then(() => {})
249
+ resolve()
264
250
  return 'body'
265
251
  })
266
- await entered.promise
252
+ await wait
267
253
  expect((await result).status).toBe('completed')
268
254
  expect(ended).toBe(true)
269
255
  })
@@ -284,33 +270,29 @@ test('agent calls detached from the run context execute as ordinary unjournaled
284
270
  test('source activity, target competition, and reused explicit ids reject before body', async () => {
285
271
  const options = await setup()
286
272
  const { client } = await fixture()
287
- const entered = Promise.withResolvers<void>()
288
- const release = Promise.withResolvers<void>()
273
+ let release!: () => void
274
+ let entered!: () => void
275
+ const ready = new Promise<void>(done => { entered = done })
276
+ const waiting = new Promise<void>(done => { release = done })
289
277
  const first = workflow({ ...options, runId: 'owned' }, async () => {
290
- entered.resolve()
278
+ entered()
291
279
  await agent('held', { client, cwd: options.directory })
292
- await release.promise
280
+ await waiting
293
281
  return 'done'
294
282
  })
295
- await entered.promise
283
+ await ready
296
284
  try {
297
285
  await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
298
286
  await expect(workflow({ ...options, resumeFrom: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_SOURCE_ACTIVE' })
299
- } finally {
300
- release.resolve()
301
- await first
302
- }
287
+ } finally { release(); await first }
303
288
  await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
304
289
  })
305
290
 
306
291
  test('initialization rejects invalid identities and releases a failed target claim before entering body', async () => {
307
292
  const options = await setup()
308
293
  let entered = false
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
- })
294
+ await expect(workflow({ ...options, runId: '../escape' }, () => { entered = true; return {} }))
295
+ .rejects.toMatchObject({ code: 'INVALID_PARAMS' })
314
296
  const { client } = await fixture()
315
297
  const original = await workflow({ ...options, runId: 'source' }, () => agent('a', { client, cwd: options.directory }))
316
298
  await expect(workflow({ ...options, name: 'incompatible', runId: 'target', resumeFrom: original.runId }, () => {
@@ -320,22 +302,6 @@ test('initialization rejects invalid identities and releases a failed target cla
320
302
  expect(await readdir(join(options.directory, 'target'))).not.toContain('writer.lock')
321
303
  })
322
304
 
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
-
339
305
  test('preallocated Unicode and spaced output names resume without changing directory meaning', async () => {
340
306
  const options = await setup()
341
307
  const { client, adapter } = await fixture()
@@ -347,13 +313,12 @@ test('preallocated Unicode and spaced output names resume without changing direc
347
313
  })
348
314
 
349
315
  test('corrupt or missing recovery materials fail rather than execute', async () => {
350
- for (const variant of ['bad-json', 'stale', 'missing', 'symlink'] as const) {
316
+ for (const variant of ['bad-json', 'missing', 'symlink'] as const) {
351
317
  const options = await setup()
352
318
  const { client, adapter } = await fixture()
353
319
  const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
354
320
  const path = join(options.directory, first.runId, 'journal.json')
355
321
  if (variant === 'bad-json') await writeFile(path, '{broken')
356
- else if (variant === 'stale') await writeFile(path, '[]')
357
322
  else {
358
323
  await rm(path)
359
324
  if (variant === 'symlink') await symlink(join(options.directory, first.runId, 'run.json'), path)
@@ -364,17 +329,15 @@ test('corrupt or missing recovery materials fail rather than execute', async ()
364
329
  }
365
330
  })
366
331
 
367
- test('rejects correctly digested manifests with older format versions', async () => {
332
+ test('format-v1 run directories are rejected on resume', async () => {
368
333
  const options = await setup()
369
334
  const { client } = await fixture()
370
335
  const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
371
336
  const manifestPath = join(options.directory, first.runId, 'run.json')
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
- }
337
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
338
+ await writeFile(manifestPath, JSON.stringify({ ...manifest, checkpointFormatVersion: 1 }))
339
+ await expect(workflow({ ...options, resumeFrom: first.runId }, () => 'bad'))
340
+ .rejects.toMatchObject({ code: 'WORKFLOW_CHECKPOINT_INVALID' })
378
341
  })
379
342
 
380
343
  test('strict JSON rejects lossy inputs and canonical hashes ignore object insertion order', () => {
@@ -388,82 +351,25 @@ test('strict JSON rejects lossy inputs and canonical hashes ignore object insert
388
351
  })
389
352
 
390
353
  test('real process death at durable boundaries replays committed agent work only', async () => {
391
- for (const phase of ['before-started', 'after-execute', 'before-final', 'after-later-result']) {
354
+ for (const phase of ['before-started', 'after-execute', 'before-final']) {
392
355
  const options = await setup()
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()
399
- const result = await workflow({ ...options, name: 'crash-test', resumeFrom: 'crashed' }, async () => {
400
- const first = agent('work', { client, cwd: options.directory })
401
- // An unfinished first key permits a rerun without invalidating the second key's saved result.
402
- return phase === 'after-later-result'
403
- ? Promise.all([first, agent('later', { client, cwd: options.directory })])
404
- : first
405
- })
406
- expect(result.result).toEqual(phase === 'after-later-result' ? ['work', 'later'] : 'work')
356
+ const child = Bun.spawn([process.execPath, fileURLToPath(new URL('./fixtures/workflow-crash.ts', import.meta.url)),
357
+ options.directory, phase], { stdout: 'ignore', stderr: 'pipe' })
358
+ const code = await child.exited
359
+ expect(code).not.toBe(0)
360
+ const error = await new Response(child.stderr).text()
361
+ expect(error).toBe('')
362
+ const adapter = createScriptedAdapter()
363
+ const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: 'crash-fixture' } })
364
+ clients.push(client)
365
+ const result = await workflow({ ...options, name: 'crash-test', resumeFrom: 'crashed' }, () =>
366
+ agent('work', { client, cwd: options.directory }))
367
+ expect(result.result).toBe('work')
407
368
  expect(adapter.opened).toHaveLength(phase === 'before-final' ? 0 : 1)
408
- if (phase === 'after-later-result') {
409
- const submissions = adapter.calls.filter(call => call.method === 'input/submit')
410
- expect(submissions).toHaveLength(1)
411
- expect(submissions[0]?.params).toMatchObject({ input: [{ type: 'text', text: 'work' }] })
412
- }
413
369
  await client.dispose()
414
370
  }
415
371
  }, 15000)
416
372
 
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
-
467
373
  test('an interrupted run reuses the unchanged call prefix in original order', async () => {
468
374
  const options = await setup()
469
375
  const { client, adapter } = await fixture()
@@ -483,7 +389,6 @@ test('an interrupted run reuses the unchanged call prefix in original order', as
483
389
  expect(result.status).toBe('completed')
484
390
  })
485
391
 
486
- /** Compile-only consumer checks for context and awaited body-result inference; never invoked. */
487
392
  function typeChecks(options: WorkflowOptions<{ files: string[] }>) {
488
393
  const run = workflow(options, async context => {
489
394
  const file: string = context.input.files[0]!
package/src/workflow.ts CHANGED
@@ -1,25 +1,11 @@
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, runWith, storedFailure } from './workflow-state'
4
+ import { RunState, storedFailure } from './workflow-state'
5
+ import { runWith } from './run-context'
5
6
  import { freezeJson, jsonCopy, type JsonValue } from './persistence/json'
6
7
  import { openFileRun, type RunHandle } from './persistence/store'
7
8
 
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
- */
23
9
  export async function workflow<Input, Result>(
24
10
  options: WorkflowOptions<Input>,
25
11
  body: (run: WorkflowContext<Input>) => Result | Promise<Result>,
@@ -27,86 +13,42 @@ export async function workflow<Input, Result>(
27
13
  const runId = options?.runId ?? randomUUID()
28
14
  const state = new RunState()
29
15
  let handle: RunHandle | undefined
30
- let publishedResult: Awaited<Result> | undefined
16
+ let value: Awaited<Result> | undefined
31
17
  try {
32
- const { storageOptions, context } = prepareRun(options, body, runId)
33
- handle = await openFileRun(storageOptions)
34
- publishedResult = await completeRun({ handle, state, body, context })
18
+ if (!options || typeof options !== 'object' || typeof body !== 'function') {
19
+ throw new HarnessSdkError('INVALID_PARAMS')
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)
35
35
  } catch (cause) {
36
- await abortRun({ cause, state, handle })
36
+ state.stop(sdkError(cause, 'WORKFLOW_FAILED'))
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
+ }
37
42
  } finally {
38
43
  if (handle) {
39
44
  try { await handle.close() }
40
- catch { state.noteStorageFailure() }
45
+ catch { state.stop(new HarnessSdkError('WORKFLOW_STORAGE_FAILED')) }
41
46
  }
42
47
  }
43
48
  const failure = state.failure
44
49
  if (failure) {
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() }
50
+ throw new HarnessSdkError(failure.code, failure.message, false, failure.outcomeUnknown,
51
+ { ...failure.details, runId, directory: handle?.identity.directory ?? options?.directory })
111
52
  }
53
+ return { runId, status: state.status, result: value as Awaited<Result> }
112
54
  }