@anureo/workflow 0.3.0 → 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.
Files changed (63) hide show
  1. package/README.md +96 -70
  2. package/package.json +18 -16
  3. package/src/agent-adapters.test.ts +121 -0
  4. package/src/agent-execution.ts +220 -0
  5. package/src/agent.test.ts +470 -0
  6. package/src/agent.ts +136 -0
  7. package/src/fixtures/workflow-crash.ts +69 -0
  8. package/src/index.ts +9 -0
  9. package/src/output-schema.test.ts +159 -0
  10. package/src/output-schema.ts +237 -0
  11. package/src/parallel.test.ts +96 -0
  12. package/src/parallel.ts +33 -0
  13. package/src/persistence/checkpoint-files.ts +83 -0
  14. package/src/persistence/journal.ts +132 -0
  15. package/src/persistence/json.ts +83 -0
  16. package/src/persistence/records.ts +103 -0
  17. package/src/persistence/replay.ts +93 -0
  18. package/src/persistence/store.ts +315 -0
  19. package/src/pipeline.test.ts +201 -0
  20. package/src/pipeline.ts +99 -0
  21. package/src/test-helpers.ts +23 -0
  22. package/src/workflow-state.ts +131 -0
  23. package/src/workflow-types.ts +38 -0
  24. package/src/workflow.test.ts +503 -0
  25. package/src/workflow.ts +112 -0
  26. package/tsconfig.json +13 -0
  27. package/LICENSE +0 -201
  28. package/src/agent-outcome.d.ts +0 -15
  29. package/src/agent-outcome.js +0 -28
  30. package/src/agent.d.ts +0 -49
  31. package/src/agent.js +0 -206
  32. package/src/index.d.ts +0 -6
  33. package/src/index.js +0 -5
  34. package/src/output-schema.d.ts +0 -27
  35. package/src/output-schema.js +0 -192
  36. package/src/parallel.d.ts +0 -18
  37. package/src/parallel.js +0 -25
  38. package/src/persistence/atomic.d.ts +0 -9
  39. package/src/persistence/atomic.js +0 -48
  40. package/src/persistence/journal.d.ts +0 -54
  41. package/src/persistence/journal.js +0 -106
  42. package/src/persistence/json.d.ts +0 -17
  43. package/src/persistence/json.js +0 -75
  44. package/src/persistence/read-json.d.ts +0 -11
  45. package/src/persistence/read-json.js +0 -46
  46. package/src/persistence/records.d.ts +0 -92
  47. package/src/persistence/records.js +0 -70
  48. package/src/persistence/replay.d.ts +0 -11
  49. package/src/persistence/replay.js +0 -79
  50. package/src/persistence/store.d.ts +0 -45
  51. package/src/persistence/store.js +0 -238
  52. package/src/pipeline.d.ts +0 -41
  53. package/src/pipeline.js +0 -24
  54. package/src/run-context.d.ts +0 -16
  55. package/src/run-context.js +0 -13
  56. package/src/test-helpers.d.ts +0 -11
  57. package/src/test-helpers.js +0 -21
  58. package/src/workflow-state.d.ts +0 -44
  59. package/src/workflow-state.js +0 -96
  60. package/src/workflow-types.d.ts +0 -39
  61. package/src/workflow-types.js +0 -0
  62. package/src/workflow.d.ts +0 -17
  63. package/src/workflow.js +0 -104
@@ -0,0 +1,131 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { HarnessSdkError, sdkError } from '@anureo/sdk'
3
+ import type { AgentJournal } from './persistence/journal'
4
+ import type { StoredFailure } from './persistence/records'
5
+
6
+ /** Internal run context installed for the workflow body and inherited by agent calls. */
7
+ export interface RunContext {
8
+ /** Source replay and target journal used by memoizedAgent. */
9
+ readonly journal: AgentJournal
10
+ /** Admission, pending work and failure state shared with workflow. */
11
+ readonly state: RunState
12
+ }
13
+
14
+ /** Invoke completeRun's callback with context inherited by asynchronous descendants. The caller
15
+ * receives the callback promise or a synchronous throw and owns closing admission and draining work. */
16
+ export function runWith<T>(context: RunContext, body: () => Promise<T>): Promise<T> {
17
+ return storage.run(context, body)
18
+ }
19
+
20
+ /** Read the current async context so agent can choose journaled or ordinary execution.
21
+ * Async descendants can retain a closed context. RunState.track then rejects admission. */
22
+ export function currentRun(): RunContext | undefined {
23
+ return storage.getStore()
24
+ }
25
+
26
+ /** Project abortRun's failure into manifest metadata, excluding diagnostic messages and details. */
27
+ export function storedFailure(error: HarnessSdkError): StoredFailure {
28
+ return {
29
+ code: error.code,
30
+ retryable: error.retryable,
31
+ outcomeUnknown: error.outcomeUnknown,
32
+ cleanupFailed: cleanupFailed(error),
33
+ }
34
+ }
35
+
36
+ /** Tell memoizedAgent and RunState.track when a failure must stop later dispatch even if caught.
37
+ * Uncertain execution, failed cleanup and broken persistence cannot safely continue the run. */
38
+ export function isFatal(error: HarnessSdkError): boolean {
39
+ return error.outcomeUnknown || cleanupFailed(error)
40
+ || error.code === 'WORKFLOW_STORAGE_FAILED'
41
+ || error.code === 'WORKFLOW_CHECKPOINT_INVALID'
42
+ }
43
+
44
+ /** Internal admission and settlement state shared by workflow and its journaled agent calls.
45
+ * Ordinary step failures mark completion incomplete; sticky failures reject the run and block dispatch.
46
+ * workflow's completion and abort phases close admission and drain registered work. */
47
+ export class RunState {
48
+ /** Preserve a failure for workflow's rejection and prevent later dispatch. Active work keeps settling. */
49
+ stop(error: HarnessSdkError): void { this.stops.add(error) }
50
+
51
+ /** Record a normalized storage failure when abortRun cannot publish or workflow cannot release the handle. */
52
+ noteStorageFailure(): void { this.stop(new HarnessSdkError('WORKFLOW_STORAGE_FAILED')) }
53
+
54
+ /** Return the first sticky code and message with all recorded codes, uncertainty and cleanup evidence.
55
+ * abortRun snapshots this for failure publication. workflow reads it again after lock release. */
56
+ get failure(): HarnessSdkError | undefined {
57
+ const failures = [...this.stops]
58
+ const first = failures[0]
59
+ if (!first) return undefined
60
+ return new HarnessSdkError(first.code, first.message, false,
61
+ failures.some(error => error.outcomeUnknown), {
62
+ ...first.details,
63
+ failureCodes: [...new Set(failures.map(error => error.code))],
64
+ cleanupFailed: failures.some(cleanupFailed),
65
+ })
66
+ }
67
+
68
+ /** Publication status for workflow when no sticky failure remains to reject the run. */
69
+ get status(): 'completed' | 'incomplete' {
70
+ return this.incomplete ? 'incomplete' : 'completed'
71
+ }
72
+
73
+ /** Mark a drop from executeJournaledAgent or a rejection observed by track incomplete.
74
+ * Fatality is checked separately. */
75
+ noteIncomplete(): void { this.incomplete = true }
76
+
77
+ /** Throw the sticky aggregate. track checks this before starting registered work, and
78
+ * executeJournaledAgent checks again after publishing started because another call may have
79
+ * stopped dispatch during that await. */
80
+ assertDispatch(): void {
81
+ const failure = this.failure
82
+ if (failure) throw failure
83
+ }
84
+
85
+ /** Invoke memoizedAgent's operation immediately and register it for workflow's drain.
86
+ * Closed admission returns a WORKFLOW_CLOSED rejection without invoking the operation.
87
+ * Sticky failures and synchronous operation throws become rejected promises. Return the work
88
+ * promise and register a separate observer so catching its rejection cannot hide incomplete
89
+ * work or fatal failures from workflow. */
90
+ track<T>(operation: () => Promise<T>): Promise<T> {
91
+ if (!this.accepting) return Promise.reject(new HarnessSdkError('WORKFLOW_CLOSED'))
92
+ let work: Promise<T>
93
+ try {
94
+ this.assertDispatch()
95
+ work = operation()
96
+ } catch (cause) {
97
+ work = Promise.reject(cause)
98
+ }
99
+ const observed = work.then(() => {}, cause => {
100
+ this.noteIncomplete()
101
+ const error = sdkError(cause, 'WORKFLOW_STEP_FAILED')
102
+ if (isFatal(error)) this.stop(error)
103
+ })
104
+ this.pending.add(observed)
105
+ void observed.then(() => { this.pending.delete(observed) })
106
+ return work
107
+ }
108
+
109
+ /** Stop admitting agent work synchronously, then await all work already registered by track.
110
+ * completeRun calls this before publication, and abortRun uses it on failure. Work continues
111
+ * settling without cancellation. The observers record operation rejections in run state. */
112
+ async closeAndDrain(): Promise<void> {
113
+ this.accepting = false
114
+ await Promise.all([...this.pending])
115
+ }
116
+
117
+ private accepting = true
118
+ private pending = new Set<Promise<void>>()
119
+ private stops = new Set<HarnessSdkError>()
120
+ private incomplete = false
121
+ }
122
+
123
+ const storage = new AsyncLocalStorage<RunContext>()
124
+
125
+ /** Recognize SDK resource-release errors and explicit cleanup evidence on another failure.
126
+ * isFatal, storedFailure and RunState.failure share this rule for dispatch and reporting. */
127
+ function cleanupFailed(error: HarnessSdkError): boolean {
128
+ return error.code === 'RESOURCE_RELEASE_FAILED'
129
+ || error.details?.cleanupFailed === true
130
+ || (Array.isArray(error.details?.cleanupErrors) && error.details.cleanupErrors.length > 0)
131
+ }
@@ -0,0 +1,38 @@
1
+ /** Identify a new durable run and optionally supply a compatible source journal for replay. */
2
+ export interface WorkflowOptions<Input> {
3
+ /** Nonempty workflow name. Resume requires the same name in the source manifest. */
4
+ name: string
5
+ /** Nonempty application-managed revision. A changed revision prevents resuming older runs. */
6
+ revision: string
7
+ /** Nonempty storage root. Relative paths are resolved against the process working directory. */
8
+ directory: string
9
+ /** New target directory name, defaulting to a random UUID. Use a nonblank single path
10
+ * component of at most 255 UTF-8 bytes. Control characters, separators, `.` and `..` are
11
+ * invalid. A locked or nonempty target directory rejects. */
12
+ runId?: string
13
+ /** Strict JSON input. The body receives a deeply frozen copy. */
14
+ input: Input
15
+ /** Omit for a fresh journal. A string selects a run under `directory`. An object supplies the
16
+ * source's storage root and ID explicitly. The source must be inactive, compatible by name and
17
+ * revision, and separate from the target tree. The new run copies its journal before invoking the body. */
18
+ resumeFrom?: string | { directory: string; runId: string }
19
+ }
20
+
21
+ /** Body inputs available after the initial manifest has been published. */
22
+ export interface WorkflowContext<Input> {
23
+ /** Identity of the new run, including when replaying a source journal. */
24
+ readonly runId: string
25
+ /** Isolated, deeply frozen JSON copy of the input supplied for this invocation. */
26
+ readonly input: Input
27
+ }
28
+
29
+ /** Published body result returned after registered agent work settles and the writer lock is released. */
30
+ export interface WorkflowResult<Result> {
31
+ /** Identity of the run that published this result. */
32
+ runId: string
33
+ /** Incomplete if registered agent work rejected or was dropped and the workflow could still
34
+ * publish a result. Fatal agent failures reject the workflow promise. */
35
+ status: 'completed' | 'incomplete'
36
+ /** JSON copy of the awaited body return value. */
37
+ result: Result
38
+ }
@@ -0,0 +1,503 @@
1
+ import { createFixture } from './test-helpers'
2
+ import { afterEach, expect, test } from 'bun:test'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises'
5
+ import { tmpdir } from 'node:os'
6
+ import { join } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { createClient, HarnessSdkError, type Client } from '@anureo/sdk'
9
+ import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
10
+ import type { HarnessError } from '@anureo/protocol'
11
+ import { z } from 'zod'
12
+ import { workflow, parallel, agent, type WorkflowOptions } from './index'
13
+ import { canonicalJson, digest } from './persistence/json'
14
+ import { record, type JournalEvent } from './persistence/records'
15
+
16
+ const clients: Client[] = []
17
+ const fixture = createFixture(clients)
18
+ const roots: string[] = []
19
+ afterEach(async () => {
20
+ await Promise.all(clients.splice(0).map(client => client.dispose()))
21
+ await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true })))
22
+ })
23
+ /** Create isolated run storage; afterEach removes it after disposing the test's clients. */
24
+ async function setup() {
25
+ const directory = await mkdtemp(join(tmpdir(), 'anureo-workflow-'))
26
+ roots.push(directory)
27
+ return { directory, name: 'test', revision: '1', input: {} }
28
+ }
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
+ function failingExecute(error: HarnessError): NonNullable<FakeAdapterOptions['execute']> {
33
+ return async (call, sink) => {
34
+ if (call.method !== 'input/submit' || !('submissionId' in call.params)) return undefined
35
+ const turnId = randomUUID()
36
+ await sink.emit({ type: 'turn/started', payload: { turnId } })
37
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error } }, { turnId })
38
+ return { submissionId: call.params.submissionId,
39
+ accepted: true, disposition: 'started', turnId }
40
+ }
41
+ }
42
+
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'])
45
+ })
46
+
47
+ test('run identity is durable before body, inputs are isolated, and results are persisted', async () => {
48
+ const options = { ...await setup(), input: { values: [1] } }
49
+ const { client } = await fixture()
50
+ const result = await workflow(options, async run => {
51
+ const manifest = JSON.parse(await readFile(join(options.directory, run.runId, 'run.json'), 'utf8'))
52
+ expect(manifest.identity.runId).toBe(run.runId)
53
+ expect(manifest.status).toBe('running')
54
+ expect(manifest.checkpointFormatVersion).toBe(3)
55
+ expect(Object.isFrozen(run.input.values)).toBe(true)
56
+ expect(Object.isFrozen(options.input.values)).toBe(false)
57
+ return agent('hello', { client, cwd: options.directory })
58
+ })
59
+ expect(result.result).toBe('hello')
60
+ expect(result.status).toBe('completed')
61
+ const stored = await readdir(join(options.directory, result.runId))
62
+ expect(stored.sort()).toEqual(['journal.json', 'result.json', 'run.json'])
63
+ const journal = JSON.parse(await readFile(join(options.directory, result.runId, 'journal.json'), 'utf8'))
64
+ expect(journal).toHaveLength(2)
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
+ })
69
+
70
+ test('resumed runs replay identical agent calls from the journal without new sessions', async () => {
71
+ const options = await setup()
72
+ 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)
76
+ expect(adapter.opened).toHaveLength(1)
77
+ expect(first.result).toEqual({ value: 1 })
78
+ const second = await workflow({ ...options, resumeFrom: first.runId }, body)
79
+ expect(adapter.opened).toHaveLength(1)
80
+ expect(second.result).toEqual({ value: 1 })
81
+ // The resumed run carries its own journal copy; the source can be deleted.
82
+ await rm(join(options.directory, first.runId), { recursive: true })
83
+ const third = await workflow({ ...options, resumeFrom: second.runId }, body)
84
+ expect(adapter.opened).toHaveLength(1)
85
+ expect(third.result).toEqual({ value: 1 })
86
+ })
87
+
88
+ test('chained keys invalidate the downstream prefix when any call changes', async () => {
89
+ const options = await setup()
90
+ const { client, adapter } = await fixture()
91
+ const first = await workflow(options, async () => {
92
+ const a = await agent('a', { client, cwd: options.directory })
93
+ const b = await agent('b', { client, cwd: options.directory })
94
+ return `${a}${b}`
95
+ })
96
+ expect(first.result).toBe('ab')
97
+ expect(adapter.opened).toHaveLength(2)
98
+ const second = await workflow({ ...options, resumeFrom: first.runId }, async () => {
99
+ const a = await agent('a', { client, cwd: options.directory })
100
+ const changed = await agent('CHANGED', { client, cwd: options.directory })
101
+ const b = await agent('b', { client, cwd: options.directory })
102
+ return `${a}${changed}${b}`
103
+ })
104
+ expect(adapter.opened).toHaveLength(4)
105
+ expect(second.result).toBe('aCHANGEDb')
106
+ })
107
+
108
+ test('prompt, options, and client identity changes miss the cache', async () => {
109
+ const options = await setup()
110
+ const { client, adapter } = await fixture()
111
+ const other = await fixture()
112
+ const first = await workflow(options, () => agent('same', { client, cwd: options.directory, model: 'm1' }))
113
+ expect(adapter.opened).toHaveLength(1)
114
+ await workflow({ ...options, resumeFrom: first.runId }, () => agent('same', { client, cwd: options.directory, model: 'm2' }))
115
+ expect(adapter.opened).toHaveLength(2)
116
+ await workflow({ ...options, resumeFrom: first.runId }, () => agent('other', { client, cwd: options.directory, model: 'm1' }))
117
+ expect(adapter.opened).toHaveLength(3)
118
+ await workflow({ ...options, resumeFrom: first.runId }, () => agent('same', { client: other.client, cwd: options.directory, model: 'm1' }))
119
+ expect(adapter.opened).toHaveLength(3)
120
+ expect(other.adapter.opened).toHaveLength(1)
121
+ })
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
+
134
+ test('name or revision changes reject resume before the body runs', async () => {
135
+ const options = await setup()
136
+ const { client } = await fixture()
137
+ const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
138
+ for (const update of [{ revision: '2' }, { name: 'other' }]) {
139
+ let entered = false
140
+ await expect(workflow({ ...options, ...update, resumeFrom: first.runId }, () => {
141
+ entered = true; return 'bad'
142
+ })).rejects.toMatchObject({ code: 'WORKFLOW_INCOMPATIBLE_RUN' })
143
+ expect(entered).toBe(false)
144
+ }
145
+ })
146
+
147
+ test('dropped agents never cache and resume repeats them', async () => {
148
+ const options = await setup()
149
+ const { client, adapter } = await fixture({
150
+ execute: failingExecute({ code: 'RATE_LIMITED', message: 'limited', retryable: true, outcomeUnknown: false }),
151
+ })
152
+ const first = await workflow(options, async () =>
153
+ await agent('dropped', { client, cwd: options.directory }))
154
+ expect(first.result).toBeNull()
155
+ expect(first.status).toBe('incomplete')
156
+ await workflow({ ...options, resumeFrom: first.runId }, () => agent('dropped', { client, cwd: options.directory }))
157
+ expect(adapter.opened).toHaveLength(2)
158
+ })
159
+
160
+ test('failed agent outcomes stay incomplete through composition and re-execute on resume', async () => {
161
+ const options = await setup()
162
+ const { client, adapter } = await fixture({
163
+ execute: failingExecute({ code: 'NATIVE_FAILED', message: 'failed', retryable: true, outcomeUnknown: false }),
164
+ })
165
+ const result = await workflow(options, async () =>
166
+ await parallel([() => agent('failing', { client, cwd: options.directory })]))
167
+ expect(result.status).toBe('incomplete')
168
+ expect(result.result).toEqual([null])
169
+ await workflow({ ...options, resumeFrom: result.runId }, () =>
170
+ parallel([() => agent('failing', { client, cwd: options.directory })]))
171
+ expect(adapter.opened).toHaveLength(2)
172
+ })
173
+
174
+ test('unknown previous outcomes require reconciliation instead of silent re-execution', async () => {
175
+ const options = await setup()
176
+ const { client, adapter } = await fixture({
177
+ execute: failingExecute({ code: 'NATIVE_FAILED', message: 'unknown', retryable: false, outcomeUnknown: true }),
178
+ })
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
+ )
184
+ expect(failure).toBeInstanceOf(HarnessSdkError)
185
+ if (!(failure instanceof HarnessSdkError)) throw failure
186
+ expect(failure.outcomeUnknown).toBe(true)
187
+ 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 }, () =>
191
+ agent('unknown', { client, cwd: options.directory })))
192
+ .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 })))
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
+
240
+ test('storage failure is sticky and blocks subsequent agent dispatch', async () => {
241
+ const options = await setup()
242
+ const { client, adapter } = await fixture()
243
+ let id = ''
244
+ await expect(workflow(options, async run => {
245
+ 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`))
248
+ try { await agent('first', { client, cwd: options.directory }) } catch {}
249
+ try { await agent('second', { client, cwd: options.directory }) } catch {}
250
+ return 'caught'
251
+ })).rejects.toMatchObject({ code: 'WORKFLOW_STORAGE_FAILED' })
252
+ // The started marker could not be published, so no session was ever opened.
253
+ expect(adapter.opened).toHaveLength(0)
254
+ })
255
+
256
+ test('body completion waits for already registered unawaited agent work', async () => {
257
+ const options = await setup()
258
+ const { client } = await fixture()
259
+ const entered = Promise.withResolvers<void>()
260
+ let ended = false
261
+ const result = workflow(options, () => {
262
+ void agent('slow', { client, cwd: options.directory }).then(() => { ended = true })
263
+ entered.resolve()
264
+ return 'body'
265
+ })
266
+ await entered.promise
267
+ expect((await result).status).toBe('completed')
268
+ expect(ended).toBe(true)
269
+ })
270
+
271
+ test('agent calls detached from the run context execute as ordinary unjournaled agents', async () => {
272
+ const options = await setup()
273
+ const { client, adapter } = await fixture()
274
+ let saved!: () => Promise<unknown>
275
+ await workflow(options, () => {
276
+ saved = () => agent('late', { client, cwd: options.directory })
277
+ return 'body'
278
+ })
279
+ // The closure escapes the run's async context, so no journal applies.
280
+ expect(await saved()).toBe('late')
281
+ expect(adapter.opened).toHaveLength(1)
282
+ })
283
+
284
+ test('source activity, target competition, and reused explicit ids reject before body', async () => {
285
+ const options = await setup()
286
+ const { client } = await fixture()
287
+ const entered = Promise.withResolvers<void>()
288
+ const release = Promise.withResolvers<void>()
289
+ const first = workflow({ ...options, runId: 'owned' }, async () => {
290
+ entered.resolve()
291
+ await agent('held', { client, cwd: options.directory })
292
+ await release.promise
293
+ return 'done'
294
+ })
295
+ await entered.promise
296
+ try {
297
+ await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
298
+ await expect(workflow({ ...options, resumeFrom: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_SOURCE_ACTIVE' })
299
+ } finally {
300
+ release.resolve()
301
+ await first
302
+ }
303
+ await expect(workflow({ ...options, runId: 'owned' }, () => 'bad')).rejects.toMatchObject({ code: 'WORKFLOW_RUN_EXISTS' })
304
+ })
305
+
306
+ test('initialization rejects invalid identities and releases a failed target claim before entering body', async () => {
307
+ const options = await setup()
308
+ 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
+ })
314
+ const { client } = await fixture()
315
+ const original = await workflow({ ...options, runId: 'source' }, () => agent('a', { client, cwd: options.directory }))
316
+ await expect(workflow({ ...options, name: 'incompatible', runId: 'target', resumeFrom: original.runId }, () => {
317
+ entered = true; return {}
318
+ })).rejects.toMatchObject({ code: 'WORKFLOW_INCOMPATIBLE_RUN' })
319
+ expect(entered).toBe(false)
320
+ expect(await readdir(join(options.directory, 'target'))).not.toContain('writer.lock')
321
+ })
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
+
339
+ test('preallocated Unicode and spaced output names resume without changing directory meaning', async () => {
340
+ const options = await setup()
341
+ const { client, adapter } = await fixture()
342
+ const first = await workflow({ ...options, runId: '审查 output' }, () => agent('同', { client, cwd: options.directory }))
343
+ const result = await workflow({ ...options, resumeFrom: first.runId }, () => agent('同', { client, cwd: options.directory }))
344
+ expect(first.runId).toBe('审查 output')
345
+ expect(result.result).toBe('同')
346
+ expect(adapter.opened).toHaveLength(1)
347
+ })
348
+
349
+ test('corrupt or missing recovery materials fail rather than execute', async () => {
350
+ for (const variant of ['bad-json', 'stale', 'missing', 'symlink'] as const) {
351
+ const options = await setup()
352
+ const { client, adapter } = await fixture()
353
+ const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
354
+ const path = join(options.directory, first.runId, 'journal.json')
355
+ if (variant === 'bad-json') await writeFile(path, '{broken')
356
+ else if (variant === 'stale') await writeFile(path, '[]')
357
+ else {
358
+ await rm(path)
359
+ if (variant === 'symlink') await symlink(join(options.directory, first.runId, 'run.json'), path)
360
+ }
361
+ await expect(workflow({ ...options, resumeFrom: first.runId }, () => agent('a', { client, cwd: options.directory })))
362
+ .rejects.toMatchObject({ code: 'WORKFLOW_CHECKPOINT_INVALID' })
363
+ expect(adapter.opened).toHaveLength(1)
364
+ }
365
+ })
366
+
367
+ test('rejects correctly digested manifests with older format versions', async () => {
368
+ const options = await setup()
369
+ const { client } = await fixture()
370
+ const first = await workflow(options, () => agent('a', { client, cwd: options.directory }))
371
+ 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
+ }
378
+ })
379
+
380
+ test('strict JSON rejects lossy inputs and canonical hashes ignore object insertion order', () => {
381
+ for (const value of [undefined, NaN, Infinity, new Date(), [undefined], Array(1), { a: undefined },
382
+ Object.defineProperty({}, 'hidden', { value: 1 }), { get a() { return 1 } }]) {
383
+ expect(() => canonicalJson(value)).toThrow()
384
+ }
385
+ const cyclic: Record<string, unknown> = {}; cyclic.self = cyclic
386
+ expect(() => canonicalJson(cyclic)).toThrow()
387
+ expect(digest({ a: 1, b: 2 })).toBe(digest({ b: 2, a: 1 }))
388
+ })
389
+
390
+ 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']) {
392
+ 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')
407
+ 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
+ await client.dispose()
414
+ }
415
+ }, 15000)
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
+
467
+ test('an interrupted run reuses the unchanged call prefix in original order', async () => {
468
+ const options = await setup()
469
+ const { client, adapter } = await fixture()
470
+ await expect(workflow({ ...options, runId: 'partial' }, async () => {
471
+ for (let n = 0; n < 3; n++) await agent(`item-${n}`, { client, cwd: options.directory })
472
+ throw new HarnessSdkError('HOST_STOPPED')
473
+ })).rejects.toMatchObject({ code: 'HOST_STOPPED' })
474
+ expect(adapter.opened).toHaveLength(3)
475
+ const executed: number[] = []
476
+ const result = await workflow({ ...options, resumeFrom: 'partial' }, async () => {
477
+ for (let n = 0; n < 3; n++) await agent(`item-${n}`, { client, cwd: options.directory })
478
+ for (let n = 3; n < 5; n++) { await agent(`item-${n}`, { client, cwd: options.directory }); executed.push(n) }
479
+ return 'done'
480
+ })
481
+ expect(executed).toEqual([3, 4])
482
+ expect(adapter.opened).toHaveLength(5)
483
+ expect(result.status).toBe('completed')
484
+ })
485
+
486
+ /** Compile-only consumer checks for context and awaited body-result inference; never invoked. */
487
+ function typeChecks(options: WorkflowOptions<{ files: string[] }>) {
488
+ const run = workflow(options, async context => {
489
+ const file: string = context.input.files[0]!
490
+ const result = await agent('review', {
491
+ client: {} as never, cwd: file, schema: z.strictObject({ value: z.number() }),
492
+ })
493
+ // @ts-expect-error result is inferred from the schema.
494
+ const invalid: string = result.value
495
+ return result === null ? null : result.value
496
+ })
497
+ const positive: Promise<{ runId: string; status: 'completed' | 'incomplete'; result: number | null }> = run
498
+ // @ts-expect-error body result inference is retained.
499
+ const negative: Promise<{ result: string }> = run
500
+ void negative
501
+ return positive
502
+ }
503
+ void typeChecks