@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.
@@ -1,176 +1,316 @@
1
- import type { WorkflowOptions } from '../workflow-types'
2
1
  import { randomUUID } from 'node:crypto'
3
2
  import { hostname } from 'node:os'
4
3
  import { lstat, mkdir, open, readdir, realpath, unlink, type FileHandle } from 'node:fs/promises'
5
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
6
5
  import { HarnessSdkError } from '@anureo/sdk'
7
- import { atomicPublish, syncDirectory } from './atomic'
6
+ import type { WorkflowOptions } from '../workflow-types'
7
+ import { atomicPublish, storageError, syncDirectory } from './checkpoint-files'
8
8
  import { canonicalJson, digest, jsonCopy, type JsonValue } from './json'
9
- import { AgentJournal, type JournalEvent } from './journal'
10
- import { invalidCheckpoint, record, runIdSchema, type Manifest } from './records'
9
+ import { AgentJournal } from './journal'
10
+ import { checkpointFormat, invalidCheckpoint, record, runIdSchema, type Manifest, type StoredFailure } from './records'
11
11
  import { loadSourceJournal } from './replay'
12
12
 
13
+ /** Internal identity saved before workflow enters its body. */
13
14
  export interface RunIdentity {
15
+ /** Validated basename of the run within directory. */
14
16
  runId: string
17
+ /** Canonical parent containing the run's subdirectory. */
15
18
  directory: string
19
+ /** Workflow name used to match a compatible source run. */
16
20
  name: string
21
+ /** Application revision used to match a compatible source run. */
17
22
  revision: string
23
+ /** Isolated persistence snapshot. The body receives its own frozen copy from prepareRun. */
18
24
  input: JsonValue
19
25
  }
20
26
 
21
- export interface StoredFailure {
22
- code: string
23
- retryable: boolean
24
- outcomeUnknown: boolean
25
- cleanupFailed: boolean
26
- }
27
-
27
+ /** Internal storage ownership returned to workflow. Drain agent work before finish or abort,
28
+ * and always await close in finally. The handle serializes finish and abort. AgentJournal
29
+ * serializes its own appends. */
28
30
  export interface RunHandle {
31
+ /** Provides the canonical storage directory for workflow's error details. */
29
32
  readonly identity: RunIdentity
33
+ /** Installed by completeRun as the journal for agent calls in the body. */
30
34
  readonly journal: AgentJournal
35
+ /** Publish result.json before the terminal manifest and resolve after both publications.
36
+ * A rejection may leave a result or manifest already replaced. A queued call that starts
37
+ * after closure rejects with WORKFLOW_CLOSED. */
31
38
  finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void>
39
+ /** Publish a failed manifest and keep any earlier result file and the writer lock.
40
+ * Publication failures reject, as does a queued call that starts after closure. */
32
41
  abort(failure: StoredFailure): Promise<void>
42
+ /** Wait for queued manifests, then release the owned writer lock and close its descriptor.
43
+ * Lock-release failures reject. Sequential repeats are no-ops, including after rejection.
44
+ * Callers must finish scheduling work before closure. */
33
45
  close(): Promise<void>
34
46
  }
35
47
 
36
- function storageError(cause: unknown): HarnessSdkError {
37
- if (cause instanceof HarnessSdkError) return cause
38
- return new HarnessSdkError('WORKFLOW_STORAGE_FAILED')
48
+ /** Create a fresh file-backed run for workflow, publishing its journal and running manifest
49
+ * before returning. An optional inactive source supplies replay events, never the final result.
50
+ * The returned handle owns the writer lock and must be closed after registered agent work drains.
51
+ * SDK errors propagate unless lock rollback fails. Rollback failures and otherwise unclassified
52
+ * I/O failures reject as WORKFLOW_STORAGE_FAILED. If publication left run files behind,
53
+ * a later attempt on the same target rejects with WORKFLOW_RUN_EXISTS. */
54
+ export async function openFileRun(options: FileRunOptions): Promise<RunHandle> {
55
+ validateRunOptions(options)
56
+ try {
57
+ const prepared = await prepareRunStorage(options)
58
+ return await initializeLockedRun({ options, prepared })
59
+ } catch (cause) { throw storageError(cause) }
39
60
  }
40
61
 
41
- function overlaps(a: string, b: string): boolean {
42
- const inside = (parent: string, child: string) => {
43
- const path = relative(parent, child)
44
- return !path || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path))
45
- }
46
- return inside(a, b) || inside(b, a)
47
- }
62
+ type FileRunOptions = WorkflowOptions<JsonValue> & { runId: string }
63
+ type SourceRun = { directory: string; runId: string }
48
64
 
49
- /** Ownership is tied to the inode held by this instance, including partial initialization. */
50
- async function releaseLock(path: string, handle: FileHandle) {
51
- try {
52
- const held = await handle.stat()
53
- const actual = await lstat(path)
54
- if (actual.dev !== held.dev || actual.ino !== held.ino || !actual.isFile()) {
55
- throw new HarnessSdkError('WORKFLOW_LOCK_OWNERSHIP_LOST')
56
- }
57
- await unlink(path)
58
- await syncDirectory(dirname(path))
59
- } finally { await handle.close() }
65
+ /** Storage coordinates prepared before claiming writer ownership. */
66
+ interface PreparedRun {
67
+ directory: string
68
+ path: string
69
+ input: JsonValue
70
+ source: SourceRun | null
60
71
  }
61
72
 
73
+ /** Own the open lock descriptor and serialize manifest transitions until workflow releases it. */
62
74
  class FileRunHandle implements RunHandle {
63
- private closed = false
64
- private manifestQueue: Promise<void> = Promise.resolve()
65
-
66
- constructor(readonly identity: RunIdentity, private readonly path: string,
67
- private readonly lock: FileHandle, private manifest: Manifest,
68
- readonly journal: AgentJournal) {}
69
-
70
- private async io<T>(operation: () => Promise<T>): Promise<T> {
71
- if (this.closed) throw new HarnessSdkError('WORKFLOW_CLOSED')
72
- try { return await operation() } catch (cause) { throw storageError(cause) }
73
- }
74
-
75
- private updateManifest(update: () => Promise<void>): Promise<void> {
76
- const next = this.manifestQueue.catch(() => {}).then(() => this.io(update))
77
- this.manifestQueue = next
78
- return next
75
+ /** Take ownership only after initial publication; initialization retains rollback responsibility. */
76
+ constructor({ identity, path, lock, manifest, journal }: {
77
+ identity: RunIdentity
78
+ path: string
79
+ lock: FileHandle
80
+ manifest: Manifest
81
+ journal: AgentJournal
82
+ }) {
83
+ this.identity = identity
84
+ this.path = path
85
+ this.lock = lock
86
+ this.manifest = manifest
87
+ this.journal = journal
79
88
  }
80
89
 
90
+ /** completeRun awaits both publications before returning the body result to workflow.
91
+ * The manifest comes last so it refers to an already published result. */
81
92
  async finish(status: 'completed' | 'incomplete', result: JsonValue): Promise<void> {
82
93
  await this.updateManifest(async () => {
83
- await atomicPublish(join(this.path, 'result.json'), result)
84
- const { recordDigest: _, ...payload } = this.manifest
85
- this.manifest = record({ ...payload, status, resultDigest: digest(result), failure: null })
86
- await atomicPublish(join(this.path, 'run.json'), this.manifest)
94
+ const { journalDigest } = this.journal.checkpoint()
95
+ await atomicPublish(join(this.path, checkpointFormat.result), result)
96
+ await this.publishManifest({ status, journalDigest, resultDigest: digest(result), failure: null })
87
97
  })
88
98
  }
89
99
 
100
+ /** abortRun awaits this after draining. Replay treats the failed manifest as authoritative
101
+ * even if finish left an earlier result file. */
90
102
  async abort(failure: StoredFailure): Promise<void> {
91
103
  await this.updateManifest(async () => {
92
- const { recordDigest: _, ...payload } = this.manifest
93
- this.manifest = record({ ...payload, status: 'failed', resultDigest: null, failure })
94
- await atomicPublish(join(this.path, 'run.json'), this.manifest)
104
+ const { journalDigest, unpublishedUnknownFailures } = this.journal.checkpoint()
105
+ await this.publishManifest({ status: 'failed', journalDigest, resultDigest: null, failure: {
106
+ ...failure,
107
+ ...(unpublishedUnknownFailures.length ? { unpublishedUnknownFailures } : {}),
108
+ } })
95
109
  })
96
110
  }
97
111
 
112
+ /** workflow awaits this in finally and records any rejection as a storage failure.
113
+ * A failed publication already reached finish or abort, so proceed with lock release. */
98
114
  async close(): Promise<void> {
99
115
  if (this.closed) return
100
- try { await this.manifestQueue.catch(() => {}); await releaseLock(join(this.path, 'writer.lock'), this.lock) }
101
- catch (cause) { throw storageError(cause) }
102
- finally { this.closed = true }
116
+ try {
117
+ await this.manifestQueue.catch(() => {})
118
+ await releaseLock(join(this.path, checkpointFormat.lock), this.lock)
119
+ } catch (cause) {
120
+ throw storageError(cause)
121
+ } finally {
122
+ this.closed = true
123
+ }
124
+ }
125
+
126
+ readonly identity: RunIdentity
127
+ readonly journal: AgentJournal
128
+
129
+ private closed = false
130
+ private manifestQueue: Promise<void> = Promise.resolve()
131
+ private readonly path: string
132
+ private readonly lock: FileHandle
133
+ private manifest: Manifest
134
+
135
+ /** Run finish/abort's publication callback in order, checking closure when it actually starts.
136
+ * A rejected predecessor still permits abort publication. Non-SDK failures are normalized. */
137
+ private updateManifest(update: () => Promise<void>): Promise<void> {
138
+ const next = this.manifestQueue.catch(() => {}).then(async () => {
139
+ if (this.closed) throw new HarnessSdkError('WORKFLOW_CLOSED')
140
+ try { await update() } catch (cause) { throw storageError(cause) }
141
+ })
142
+ this.manifestQueue = next
143
+ return next
144
+ }
145
+
146
+ /** Recompute the digest from payload only for every terminal transition, then publish it.
147
+ * Keep the in-memory transition even if publication rejects, as abort may follow a failed finish. */
148
+ private async publishManifest(update: Pick<Manifest, 'status' | 'journalDigest' | 'resultDigest' | 'failure'>): Promise<void> {
149
+ const { recordDigest: _, ...payload } = this.manifest
150
+ this.manifest = record({ ...payload, ...update })
151
+ await atomicPublish(join(this.path, checkpointFormat.manifest), this.manifest)
103
152
  }
104
153
  }
105
154
 
106
- class MemoryRunHandle implements RunHandle {
107
- constructor(readonly identity: RunIdentity, readonly journal: AgentJournal) {}
108
- async finish(): Promise<void> { /* No checkpoint: the run lives only for this process. */ }
109
- async abort(): Promise<void> { /* No checkpoint: the run lives only for this process. */ }
110
- async close(): Promise<void> { /* No lock was acquired. */ }
155
+ /** Throw INVALID_PARAMS for malformed target identity before copying input or touching storage. */
156
+ function validateRunOptions(options: FileRunOptions): void {
157
+ const issues: string[] = []
158
+ if (!runIdSchema.safeParse(options.runId).success) {
159
+ issues.push('runId must be a valid directory basename (at most 255 UTF-8 bytes)')
160
+ }
161
+ if (typeof options.name !== 'string' || !options.name) issues.push('name must be a nonempty string')
162
+ if (typeof options.revision !== 'string' || !options.revision) issues.push('revision must be a nonempty string')
163
+ if (typeof options.directory !== 'string' || !options.directory) issues.push('directory must be a nonempty string')
164
+ if (issues.length) throw new HarnessSdkError('INVALID_PARAMS', `Invalid workflow options: ${issues.join(', ')}`)
111
165
  }
112
166
 
113
- export async function openFileRun(
114
- options: WorkflowOptions<JsonValue> & { runId: string },
115
- ): Promise<RunHandle> {
116
- if (!runIdSchema.safeParse(options.runId).success || typeof options.name !== 'string' || !options.name
117
- || typeof options.revision !== 'string' || !options.revision) {
118
- throw new HarnessSdkError('INVALID_PARAMS')
167
+ /** Snapshot input, resolve parent/source paths, and create a real target directory before locking.
168
+ * Flush the parent when creating the target. Initialization checks existing contents under the lock. */
169
+ async function prepareRunStorage(options: FileRunOptions): Promise<PreparedRun> {
170
+ const input = jsonCopy(options.input)
171
+ const root = resolve(options.directory)
172
+ if (options.resumeFrom !== undefined && typeof options.resumeFrom !== 'string') {
173
+ const directory = await prospectiveDirectory(root)
174
+ await resolveSourceRun({ resumeFrom: options.resumeFrom, directory, path: join(directory, options.runId) })
175
+ }
176
+ await mkdir(root, { recursive: true, mode: 0o700 })
177
+ const directory = await realpath(root)
178
+ const path = join(directory, options.runId)
179
+ const source = await resolveSourceRun({ resumeFrom: options.resumeFrom, directory, path })
180
+ try {
181
+ await mkdir(path, { mode: 0o700 })
182
+ await syncDirectory(directory)
183
+ } catch (cause) {
184
+ if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause
119
185
  }
120
- if (options.directory === undefined) {
121
- if (options.resumeFrom !== undefined) throw new HarnessSdkError('WORKFLOW_RESUME_NOT_FOUND')
122
- const identity = { runId: options.runId, directory: '', name: options.name, revision: options.revision, input: jsonCopy(options.input) }
123
- return new MemoryRunHandle(identity, new AgentJournal(`memory:${options.runId}`, [], false))
186
+ if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
187
+ if (source && overlaps(await realpath(path), join(source.directory, source.runId))) {
188
+ throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS')
124
189
  }
125
- if (typeof options.directory !== 'string' || !options.directory) throw new HarnessSdkError('INVALID_PARAMS')
126
- let lock: FileHandle | undefined
127
- let lockPath: string | undefined
190
+ return { directory, path, input, source }
191
+ }
192
+
193
+ /** Resolve existing ancestors so the overlap check can run before creating a missing root. */
194
+ async function prospectiveDirectory(path: string): Promise<string> {
128
195
  try {
129
- const input = jsonCopy(options.input)
130
- await mkdir(resolve(options.directory), { recursive: true, mode: 0o700 })
131
- const directory = await realpath(resolve(options.directory))
132
- const path = join(directory, options.runId)
133
- let source: { directory: string; runId: string } | null = null
134
- if (options.resumeFrom !== undefined) {
135
- const reference = typeof options.resumeFrom === 'string'
136
- ? { directory, runId: options.resumeFrom } : options.resumeFrom
137
- if (!reference || !runIdSchema.safeParse(reference.runId).success || typeof reference.directory !== 'string') {
138
- throw new HarnessSdkError('INVALID_PARAMS')
139
- }
140
- source = { directory: await realpath(resolve(reference.directory)), runId: reference.runId }
141
- if (overlaps(path, join(source.directory, source.runId))) throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS')
142
- }
143
- try { await mkdir(path, { mode: 0o700 }); await syncDirectory(directory) }
144
- catch (cause) { if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause }
145
- if (!(await lstat(path)).isDirectory()) invalidCheckpoint()
146
- lockPath = join(path, 'writer.lock')
147
- try { lock = await open(lockPath, 'wx', 0o600) }
148
- catch (cause) {
149
- if ((cause as NodeJS.ErrnoException).code === 'EEXIST') throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
150
- throw cause
151
- }
152
- await lock.writeFile(`${canonicalJson(record({ checkpointFormatVersion: 2, token: randomUUID(),
153
- hostname: hostname(), pid: process.pid, createdAt: new Date().toISOString() }))}\n`)
154
- await lock.sync()
155
- if ((await readdir(path)).some(name => name !== 'writer.lock')) throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
156
- const inherited: JournalEvent[] = source
157
- ? await loadSourceJournal(join(source.directory, source.runId), {
158
- name: options.name, revision: options.revision, runId: source.runId,
159
- })
160
- : []
161
- const journal = new AgentJournal(join(path, 'journal.json'), inherited)
162
- await atomicPublish(join(path, 'journal.json'), [...inherited])
163
- const identity = { runId: options.runId, directory, name: options.name, revision: options.revision, input }
164
- const manifest: Manifest = record({ checkpointFormatVersion: 2,
165
- identity, createdAt: new Date().toISOString(), resumedFrom: source,
166
- status: 'running', resultDigest: null, failure: null })
167
- await atomicPublish(join(path, 'run.json'), manifest)
168
- return new FileRunHandle(identity, path, lock, manifest, journal)
196
+ return await realpath(path)
169
197
  } catch (cause) {
170
- if (lock && lockPath) {
171
- try { await releaseLock(lockPath, lock) }
172
- catch { throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED') }
198
+ const parent = dirname(path)
199
+ if ((cause as NodeJS.ErrnoException).code !== 'ENOENT' || parent === path) throw cause
200
+ return join(await prospectiveDirectory(parent), relative(parent, path))
201
+ }
202
+ }
203
+
204
+ /** Resolve optional replay coordinates before target creation so overlapping source/target trees
205
+ * reject before a writer claim. Omission selects fresh execution. A string uses the target's
206
+ * canonical parent, while an object supplies its own parent to resolve. */
207
+ async function resolveSourceRun({ resumeFrom, directory, path }: {
208
+ resumeFrom: FileRunOptions['resumeFrom']
209
+ directory: string
210
+ path: string
211
+ }): Promise<SourceRun | null> {
212
+ if (resumeFrom === undefined) return null
213
+ const reference = typeof resumeFrom === 'string' ? { directory, runId: resumeFrom } : resumeFrom
214
+ if (!reference || !runIdSchema.safeParse(reference.runId).success || typeof reference.directory !== 'string') {
215
+ throw new HarnessSdkError('INVALID_PARAMS')
216
+ }
217
+ const source = { directory: await realpath(resolve(reference.directory)), runId: reference.runId }
218
+ if (overlaps(path, join(source.directory, source.runId))) throw new HarnessSdkError('WORKFLOW_OVERLAPPING_RUNS')
219
+ return source
220
+ }
221
+
222
+ /** Exclusively claim and initialize the lock before inspecting target contents or source records.
223
+ * Transfer ownership only on successful publication; rollback also covers partial lock writes.
224
+ * Cleanup failure takes precedence as WORKFLOW_STORAGE_FAILED; other failures reach openFileRun. */
225
+ async function initializeLockedRun({ options, prepared }: {
226
+ options: FileRunOptions
227
+ prepared: PreparedRun
228
+ }): Promise<RunHandle> {
229
+ const lockPath = join(prepared.path, checkpointFormat.lock)
230
+ const lock = await open(lockPath, 'wx', 0o600).catch(cause => {
231
+ if ((cause as NodeJS.ErrnoException).code === 'EEXIST') throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
232
+ throw cause
233
+ })
234
+ try {
235
+ await writeWriterClaim(lock)
236
+ if ((await readdir(prepared.path)).some(name => name !== checkpointFormat.lock)) {
237
+ throw new HarnessSdkError('WORKFLOW_RUN_EXISTS')
173
238
  }
174
- throw storageError(cause)
239
+ return await publishInitialRun({ options, prepared, lock })
240
+ } catch (cause) {
241
+ try { await releaseLock(lockPath, lock) }
242
+ catch { throw new HarnessSdkError('WORKFLOW_STORAGE_FAILED') }
243
+ throw cause
175
244
  }
176
245
  }
246
+
247
+ /** Write and flush the claim on the exclusively opened descriptor. Replay validates this
248
+ * record before probing its writer, and initializeLockedRun owns rollback on rejection. */
249
+ async function writeWriterClaim(lock: FileHandle): Promise<void> {
250
+ const claim = record({
251
+ checkpointFormatVersion: checkpointFormat.version,
252
+ token: randomUUID(),
253
+ hostname: hostname(),
254
+ pid: process.pid,
255
+ createdAt: new Date().toISOString(),
256
+ })
257
+ await lock.writeFile(`${canonicalJson(claim)}\n`)
258
+ await lock.sync()
259
+ }
260
+
261
+ /** Validate replay under the target lock, publish a self-contained journal before its manifest,
262
+ * then hand the descriptor to FileRunHandle. Failures leave lock cleanup to initializeLockedRun. */
263
+ async function publishInitialRun({ options, prepared, lock }: {
264
+ options: FileRunOptions
265
+ prepared: PreparedRun
266
+ lock: FileHandle
267
+ }): Promise<RunHandle> {
268
+ const { directory, path, input, source } = prepared
269
+ const inherited = source
270
+ ? await loadSourceJournal(join(source.directory, source.runId), {
271
+ name: options.name, revision: options.revision, runId: source.runId,
272
+ })
273
+ : []
274
+ const journalPath = join(path, checkpointFormat.journal)
275
+ const journal = new AgentJournal(journalPath, inherited)
276
+ await atomicPublish(journalPath, [...inherited])
277
+ const identity = { runId: options.runId, directory, name: options.name, revision: options.revision, input }
278
+ const manifest: Manifest = record({
279
+ checkpointFormatVersion: checkpointFormat.version,
280
+ identity,
281
+ createdAt: new Date().toISOString(),
282
+ resumedFrom: source,
283
+ status: 'running',
284
+ journalDigest: null,
285
+ resultDigest: null,
286
+ failure: null,
287
+ })
288
+ await atomicPublish(join(path, checkpointFormat.manifest), manifest)
289
+ return new FileRunHandle({ identity, path, lock, manifest, journal })
290
+ }
291
+
292
+ /** Detect equal or nested run trees in either direction. resolveSourceRun uses canonical
293
+ * parent directories so writes cannot overlap the selected source tree. */
294
+ function overlaps(a: string, b: string): boolean {
295
+ const inside = (parent: string, child: string) => {
296
+ const path = relative(parent, child)
297
+ return !path || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path))
298
+ }
299
+ return inside(a, b) || inside(b, a)
300
+ }
301
+
302
+ /** Compare the on-disk entry with the held descriptor before unlinking, so rollback also works
303
+ * for a partially written lock. Flush the parent after unlinking and always close the descriptor.
304
+ * An observed inode or file kind mismatch rejects as WORKFLOW_LOCK_OWNERSHIP_LOST. */
305
+ async function releaseLock(path: string, handle: FileHandle): Promise<void> {
306
+ try {
307
+ const held = await handle.stat()
308
+ const actual = await lstat(path)
309
+ if (actual.dev !== held.dev || actual.ino !== held.ino || !actual.isFile()) {
310
+ throw new HarnessSdkError('WORKFLOW_LOCK_OWNERSHIP_LOST')
311
+ }
312
+ await unlink(path)
313
+ await syncDirectory(dirname(path))
314
+ } finally { await handle.close() }
315
+ }
316
+
@@ -85,6 +85,24 @@ test('passes the previous result, original item and index to every stage', async
85
85
  expect(result).toEqual([{ length: 5, item: 'first', index: 0 }, { length: 6, item: 'second', index: 1 }])
86
86
  })
87
87
 
88
+ test('snapshots input entries and indices before starting any item chain', async () => {
89
+ const resolved = Promise.resolve('first')
90
+ const first: PromiseLike<string> = {
91
+ get then() {
92
+ // Awaiting this entry reads `then` while the other item chains are still being started.
93
+ items.splice(1, 1, Promise.resolve('replacement'))
94
+ return resolved.then.bind(resolved)
95
+ },
96
+ }
97
+ const second = Promise.resolve('second')
98
+ const items = [first, second]
99
+ const results = await pipeline(items, (value, original, index) => ({ value, original, index }))
100
+
101
+ expect(results.map(result => result && [result.value, result.index])).toEqual([['first', 0], ['second', 1]])
102
+ expect(results[0]?.original).toBe(first)
103
+ expect(results[1]?.original).toBe(second)
104
+ })
105
+
88
106
  test('null input or stage results skip later stages while other falsy values continue', async () => {
89
107
  const entered: unknown[] = []
90
108
  const next: unknown[] = []
@@ -125,6 +143,7 @@ test('validates arrays and all stages before processing nonempty input', async (
125
143
  expect(await pipeline([], undefined)).toEqual([])
126
144
  })
127
145
 
146
+ /** Compile-only assertions for stage compatibility, context and nullable results; never invoked at runtime. */
128
147
  function checkTypes() {
129
148
  const firstStage = (value: string) => value.length
130
149
  const secondStage = (value: number) => value > 0
package/src/pipeline.ts CHANGED
@@ -1,14 +1,23 @@
1
- // Prepending Input aligns each stage's index with the previous stage's output.
2
- type PreviousStageOutput<Input, Outputs extends readonly unknown[], K> =
3
- K extends '0' ? Input : [Input, ...Outputs][K & keyof [Input, ...Outputs]]
4
-
5
- type Stages<Input, Outputs extends readonly unknown[]> = {
6
- [K in keyof Outputs]: Stage<PreviousStageOutput<Input, Outputs, K>, Input, Outputs[K]>
7
- }
8
- type Last<Outputs extends readonly unknown[]> = Outputs extends readonly [...unknown[], infer Output] ? Awaited<Output> : never
9
- type Stage<Previous, Input, Output> = (value: Exclude<Awaited<Previous>, null>, originalItem: Input, index: number) => Output
10
-
11
- /** Items advance independently; null or failure stops an item and retains its position. */
1
+ /**
2
+ * Run each input through sequential stages at its own pace. Each stage receives the awaited input
3
+ * or prior result, the original array entry as supplied and its zero-based index in the snapshot.
4
+ * Inline stages infer their input types through six stages. Longer chains can use typed functions
5
+ * that accept the preceding stage's awaited result with `null` excluded.
6
+ *
7
+ * The promise resolves after all item chains settle and returns their final values in input order.
8
+ * An input or stage that resolves to `null` or rejects ends that item's chain with `null`.
9
+ * A synchronous stage throw has the same effect. Sibling chains continue after a failure,
10
+ * and other falsy values advance normally. With zero stages, return awaited inputs with
11
+ * rejections as `null`.
12
+ *
13
+ * Handle input and stage failures before they reach the pipeline to retain the original cause.
14
+ * The caller owns concurrency limits, cancellation, retries and resource cleanup for input
15
+ * work and stages. Return the work each stage needs the pipeline to await.
16
+ *
17
+ * A non-array input rejects with `TypeError`. The function snapshots the array and resolves to `[]`
18
+ * for an empty snapshot. For nonempty input, a non-function stage rejects with `TypeError` before
19
+ * item processing starts.
20
+ */
12
21
  export function pipeline<Input>(items: readonly Input[]): Promise<(Awaited<Input> | null)[]>
13
22
  export function pipeline<A, B>(items: readonly A[], first: Stage<A, A, B>): Promise<(Awaited<B> | null)[]>
14
23
  export function pipeline<A, B, C>(
@@ -31,23 +40,60 @@ export function pipeline<A, B, C, D, E, F, G>(
31
40
  third: Stage<C, A, D>, fourth: Stage<D, A, E>,
32
41
  fifth: Stage<E, A, F>, sixth: Stage<F, A, G>,
33
42
  ): Promise<(Awaited<G> | null)[]>
34
- // Homomorphic tuple inference also supports arbitrary-length chains of typed functions.
43
+ /**
44
+ * Run a nonempty chain of typed stages, checking each stage against its predecessor. Resolve
45
+ * with the last stage's awaited results in input order, using `null` for failed or skipped items.
46
+ */
35
47
  export function pipeline<Input, Outputs extends readonly unknown[]>(
36
48
  items: readonly Input[],
37
49
  ...stages: Stages<Input, Outputs> & { 0: Stage<Input, Input, unknown> }
38
- ): Promise<(Last<Outputs> | null)[]>
39
- export async function pipeline(items: readonly unknown[], ...stages: Array<(value: never, originalItem: never, index: number) => unknown>): Promise<unknown[]> {
50
+ ): Promise<(LastAwaitedOutput<Outputs> | null)[]>
51
+ export async function pipeline(
52
+ items: readonly unknown[],
53
+ ...stages: Stage<never, never, unknown>[]
54
+ ): Promise<unknown[]> {
40
55
  if (!Array.isArray(items)) throw new TypeError('pipeline expects an array as the first argument')
41
56
  const inputs = [...items]
42
57
  if (!inputs.length) return []
43
58
  if (stages.some(stage => typeof stage !== 'function')) throw new TypeError('pipeline stages must be functions')
44
- const results = await Promise.allSettled(inputs.map(async (originalItem, index) => {
45
- let value = await originalItem
46
- for (const stage of stages) {
47
- if (value === null) break
48
- value = await (stage as (value: unknown, originalItem: unknown, index: number) => unknown)(value, originalItem, index)
49
- }
50
- return value
51
- }))
52
- return results.map(result => result.status === 'fulfilled' ? result.value : null)
59
+ // The overloads check compatibility between adjacent stages. The runner only needs their order.
60
+ const orderedStages = stages as unknown as readonly Stage<unknown, unknown, unknown>[]
61
+ const settledItems = await Promise.allSettled(
62
+ inputs.map((originalItem, index) => runItem(originalItem, index, orderedStages)),
63
+ )
64
+ return settledItems.map(result => result.status === 'fulfilled' ? result.value : null)
65
+ }
66
+
67
+ /**
68
+ * Advance one pipeline item by awaiting its input and each stage in turn. Pass the original
69
+ * entry and snapshot index to every stage, and return early on `null`. Input rejections and
70
+ * stage errors reject this chain so `pipeline` can collect `null` at the item's original position.
71
+ */
72
+ async function runItem(
73
+ originalItem: unknown,
74
+ index: number,
75
+ stages: readonly Stage<unknown, unknown, unknown>[],
76
+ ): Promise<unknown> {
77
+ let value = await originalItem
78
+ for (const stage of stages) {
79
+ if (value === null) return null
80
+ value = await stage(value, originalItem, index)
81
+ }
82
+ return value
53
83
  }
84
+
85
+ /** Align each stage with its predecessor's output by prepending the original input type. */
86
+ type PreviousStageOutput<Input, Outputs extends readonly unknown[], K> =
87
+ K extends '0' ? Input : [Input, ...Outputs][K & keyof [Input, ...Outputs]]
88
+
89
+ /** Check each variadic stage against the preceding output while retaining the original input context. */
90
+ type Stages<Input, Outputs extends readonly unknown[]> = {
91
+ [K in keyof Outputs]: Stage<PreviousStageOutput<Input, Outputs, K>, Input, Outputs[K]>
92
+ }
93
+
94
+ /** Infer the pipeline's resolved value type from the final stage of a typed chain. */
95
+ type LastAwaitedOutput<Outputs extends readonly unknown[]> =
96
+ Outputs extends readonly [...unknown[], infer Output] ? Awaited<Output> : never
97
+
98
+ /** Exclude only null from a stage's awaited input because null short-circuits the item at runtime. */
99
+ type Stage<Previous, Input, Output> = (value: Exclude<Awaited<Previous>, null>, originalItem: Input, index: number) => Output
@@ -0,0 +1,24 @@
1
+ // Scripted client setup shared by workflow tests; each suite retains its own disposal registry.
2
+ import { randomUUID } from 'node:crypto'
3
+ import { createClient, type Client } from '@anureo/sdk'
4
+ import { createScriptedAdapter, type FakeAdapterOptions } from '@anureo/conformance'
5
+
6
+ /**
7
+ * Give the agent and workflow suites a factory for initialized scripted clients. Register each
8
+ * initialized client in the caller's registry. Both suites dispose those clients in afterEach.
9
+ * Initialization failures reject before registration.
10
+ */
11
+ export function createFixture(clients: Client[]) {
12
+ /**
13
+ * Forward optional hook and capability overrides to the scripted adapter. Return the initialized
14
+ * client and adapter for dispatch assertions. Give each fixture a distinct runtime identity so
15
+ * journal replay can distinguish clients, unless the caller pins the identity for revised-policy
16
+ * probes that must hash to the same journal key.
17
+ */
18
+ return async function fixture(options?: FakeAdapterOptions, identity?: { adapterId: string; runtimeConfigId: string }) {
19
+ const adapter = createScriptedAdapter(options)
20
+ const client = await createClient({ adapter, identity: identity ?? { adapterId: 'scripted', runtimeConfigId: randomUUID() } })
21
+ clients.push(client)
22
+ return { client, adapter }
23
+ }
24
+ }