@nagi-js/core 0.1.1-rc.7 → 0.1.1-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -71,17 +71,7 @@ interface StepCtx<Input = unknown> {
71
71
  readonly signal: AbortSignal;
72
72
  readonly now: () => Date;
73
73
  readonly logger: Logger;
74
- /**
75
- * Durable per-effect memoization. The first successful call for `(runId, stepId, scope)`
76
- * persists its return value; subsequent calls (including post-crash retries) return the
77
- * cached value without re-invoking `fn`.
78
- */
79
74
  once<T extends Json>(scope: string, fn: () => Promise<T>): Promise<T>;
80
- /**
81
- * Stable idempotency key for external APIs (Stripe, Mux, etc.).
82
- * Returns `hash(runId + stepId + scope)` — identical across retries of the same attempt,
83
- * different across runs.
84
- */
85
75
  idempotencyKey(scope: string): string;
86
76
  }
87
77
  type BackoffStrategy = "exponential" | "linear" | "fixed";
@@ -94,12 +84,6 @@ interface RetryPolicy {
94
84
  }
95
85
  interface StepConfigBase<Input, N extends NeedsMap> {
96
86
  readonly needs?: N;
97
- /**
98
- * Skip this step when the predicate returns false. Locked semantic:
99
- * downstream steps that need a skipped step are also skipped (transitive).
100
- * Therefore at the type level, `needs.x` is the unconditional `Output` —
101
- * not `Output | undefined`.
102
- */
103
87
  readonly when?: (args: {
104
88
  readonly input: NoInfer<Input>;
105
89
  readonly needs: NoInfer<NeedsOutputs<N>>;
@@ -113,14 +97,6 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
113
97
  readonly needs: NoInfer<NeedsOutputs<N>>;
114
98
  readonly ctx: StepCtx<NoInfer<Input>>;
115
99
  }) => Promise<Output>;
116
- /**
117
- * Lifecycle hooks colocated with this step. Fire *before* the cross-cutting
118
- * `FlowHooks` callbacks (deterministic ordering). A throwing hook is logged
119
- * via the runtime's `Logger` and swallowed — hooks cannot fail the run.
120
- *
121
- * `onComplete`'s event is typed against this step's `Output` — no `Json`
122
- * narrowing required at the call site.
123
- */
124
100
  readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
125
101
  readonly onComplete?: (event: StepCompleteEvent & {
126
102
  readonly output: NoInfer<Output>;
@@ -128,289 +104,73 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
128
104
  readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
129
105
  readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
130
106
  }
131
- /**
132
- * One signal step accepts one or more external signal names. Omitting
133
- * `names` defaults to `[stepId]` (back-compat behavior). Passing `names:
134
- * [...]` accepts any listed name; first arrival wins, late losers are a
135
- * no-op + logged. Non-empty tuple type so `names: []` is a compile error.
136
- */
137
107
  interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
138
108
  readonly schema: Schema;
139
109
  readonly names?: readonly [string, ...string[]];
140
110
  }
141
- /**
142
- * Discriminator mode — exhaustive at compile time. `cases` must cover every
143
- * value in the discriminant union; adding a new value to the discriminant
144
- * is a type error until the case is handled.
145
- */
146
- interface MatchDiscriminatorConfig<Input, N extends NeedsMap, D extends string, M extends Record<D, StepMap>> {
147
- readonly needs?: N;
148
- readonly on: (args: {
149
- readonly input: NoInfer<Input>;
150
- readonly needs: NoInfer<NeedsOutputs<N>>;
151
- }) => D;
152
- readonly cases: {
153
- readonly [K in D]: (b: Builder<Input>) => BuildResult<Input, M[K]>;
154
- };
155
- }
156
111
  interface MatchArmGuard<Input, N extends NeedsMap, M extends StepMap> {
157
112
  readonly when: (args: {
158
113
  readonly input: NoInfer<Input>;
159
114
  readonly needs: NoInfer<NeedsOutputs<N>>;
160
115
  }) => boolean;
161
116
  readonly otherwise?: never;
162
- readonly build: (b: Builder<Input>) => BuildResult<Input, M>;
117
+ readonly build: (b: Builder<Input>) => M;
163
118
  }
164
119
  interface MatchArmOtherwise<Input, M extends StepMap> {
165
120
  readonly otherwise: true;
166
121
  readonly when?: never;
167
- readonly build: (b: Builder<Input>) => BuildResult<Input, M>;
122
+ readonly build: (b: Builder<Input>) => M;
168
123
  }
169
124
  type MatchArm<Input, N extends NeedsMap, M extends StepMap> = MatchArmGuard<Input, N, M> | MatchArmOtherwise<Input, M>;
170
- /**
171
- * Inference-friendly arm shape: M is not bound, so each arm in an `arms:` tuple
172
- * keeps its own StepMap (and per-step Output) through inference. The `arms`
173
- * overload of `Builder.match` uses this; user-facing arms still satisfy
174
- * `MatchArm<Input, N, M>` for any concrete M they construct.
175
- */
176
125
  type MatchArmShape<Input, N extends NeedsMap> = {
177
126
  readonly when: (args: {
178
127
  readonly input: NoInfer<Input>;
179
128
  readonly needs: NoInfer<NeedsOutputs<N>>;
180
129
  }) => boolean;
181
130
  readonly otherwise?: never;
182
- readonly build: (b: Builder<Input>) => BuildResult<Input, StepMap>;
131
+ readonly build: (b: Builder<Input>) => StepMap;
183
132
  } | {
184
133
  readonly otherwise: true;
185
134
  readonly when?: never;
186
- readonly build: (b: Builder<Input>) => BuildResult<Input, StepMap>;
135
+ readonly build: (b: Builder<Input>) => StepMap;
187
136
  };
188
- /**
189
- * Guard mode — Rust-style `match { x if guard => ... }`. Top-to-bottom,
190
- * first match wins. The terminal `{ otherwise: true }` arm is required so
191
- * guard mode can never silently fall through.
192
- */
193
137
  interface MatchGuardConfig<Input, N extends NeedsMap, M extends StepMap> {
194
138
  readonly needs?: N;
195
139
  readonly arms: ReadonlyArray<MatchArm<Input, N, M>>;
196
140
  }
197
- /** The output of a match step is a record of each step in the chosen arm. */
198
141
  type MatchArmOutput<M extends StepMap> = {
199
142
  readonly [K in keyof M]: StepOutput<M[K]>;
200
143
  };
201
- /**
202
- * Config for `b.subflow(child, config)`. The `input` callback derives the
203
- * child flow's input from the parent's own input + resolved needs. Typed
204
- * against `FlowInput<Child>` so the child's input schema is honored at
205
- * compile time.
206
- *
207
- * The child flow runs as an independent run on the same store/queue. Its
208
- * `flow.started` fact records `parentRunId` + `parentStepId`, which links
209
- * its eventual `flow.completed` back to this subflow step (see RFC 0006
210
- * for the wake-parent mechanism).
211
- */
212
144
  interface SubflowConfig<Input, N extends NeedsMap, Child extends Flow> extends StepConfigBase<Input, N> {
213
145
  readonly input: (args: {
214
146
  readonly input: NoInfer<Input>;
215
147
  readonly needs: NoInfer<NeedsOutputs<N>>;
216
148
  }) => FlowInput<Child>;
217
149
  }
218
- /**
219
- * The structural output of a subflow step. `childRunId` lets callers
220
- * correlate to the child run for debugging / OTel tracing; `output` carries
221
- * the child flow's own final output (whatever its `flow({ output })` reducer
222
- * produced).
223
- */
224
150
  interface SubflowStepOutput<ChildOutput> {
225
151
  readonly childRunId: RunId;
226
152
  readonly output: ChildOutput;
227
153
  }
228
- /** Across all cases of a discriminator match — the union of arm outputs. */
229
- type MatchDiscriminatorOutput<D extends string, M extends Record<D, StepMap>> = {
230
- [K in D]: MatchArmOutput<M[K]>;
231
- }[D];
232
- /**
233
- * Per-entry config for `b.step(key, config)`. `Needs` is a const tuple of
234
- * sibling keys that resolve against the chain's accumulator `A`.
235
- */
236
- interface StepEntryConfig<Input, A extends Record<string, unknown>, Needs extends ReadonlyArray<keyof A & string>, Output> {
237
- readonly needs?: Needs;
238
- readonly retry?: RetryPolicy;
239
- readonly timeoutMs?: Millis;
240
- readonly when?: (args: {
241
- readonly input: NoInfer<Input>;
242
- readonly needs: {
243
- readonly [P in Needs[number]]: A[P];
244
- };
245
- }) => boolean;
246
- readonly run: (args: {
247
- readonly input: NoInfer<Input>;
248
- readonly needs: {
249
- readonly [P in Needs[number]]: A[P];
250
- };
251
- readonly ctx: StepCtx<NoInfer<Input>>;
252
- }) => Promise<Output>;
253
- /** See {@link TaskConfig} for hook semantics. */
254
- readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
255
- readonly onComplete?: (event: StepCompleteEvent & {
256
- readonly output: NoInfer<Output>;
257
- }) => void | Promise<void>;
258
- readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
259
- readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
260
- }
261
- /**
262
- * `b` inside `flow({ build: (b) => ... })`.
263
- *
264
- * Two complementary authoring styles:
265
- *
266
- * 1. **Standalone constructors** — `b.task`, `b.signal`, `b.match` each
267
- * return a `Step<Output>` value the user can assign and reference. The
268
- * build callback returns a `StepMap` of those values.
269
- *
270
- * 2. **Chain (key-first)** — `b.step(key, config)` is keyed and chainable.
271
- * Each call extends the builder's accumulator `A` with `{ [Key]: Output }`,
272
- * and subsequent `.step()` calls type `needs: ["sibling"]` against `A`.
273
- * `b.include(key, prebuiltStep)` brings a `Step<O>` (from `b.task` /
274
- * `b.signal` / `b.match`) into the chain under a key. The chain itself
275
- * is returned from the build callback; `flow()` extracts the accumulator.
276
- *
277
- * Both styles compose in the same build callback — the chain end is the
278
- * canonical result; pre-built standalone steps enter the chain via
279
- * `.include(key, step)`.
280
- */
281
- interface Builder<Input = unknown, A extends Record<string, unknown> = Record<never, never>> {
154
+ interface Builder<Input = unknown> {
282
155
  task<N extends NeedsMap, Output>(config: TaskConfig<Input, N, Output>): Step<Output>;
283
156
  signal<N extends NeedsMap, S extends StandardSchemaV1>(config: SignalConfig<Input, N, S>): Step<InferSchemaOutput<S>>;
284
- /**
285
- * Embed another flow as a step. The child flow runs as an independent
286
- * run on the same store/queue; this step parks in `running` until the
287
- * child reaches a terminal state, then completes with the child's output.
288
- *
289
- * const transcript = b.subflow(transcriptionFlow, {
290
- * needs: { audio },
291
- * input: ({ needs }) => ({ audioUrl: needs.audio.url }),
292
- * });
293
- * // typed: Step<{ childRunId: RunId; output: FlowOutput<typeof transcriptionFlow> }>
294
- *
295
- * The child must be registered with `nagi({ flows: [parent, child] })` —
296
- * subflow registration is strict, not auto-include. A child failure
297
- * bubbles up as this step's failure with the child's error.
298
- */
299
157
  subflow<N extends NeedsMap, Child extends Flow>(child: Child, config: SubflowConfig<Input, N, Child>): Step<SubflowStepOutput<FlowOutput<Child>>>;
300
- match<N extends NeedsMap, D extends string, Cases extends {
301
- readonly [K in D]: (b: Builder<Input>) => BuildResult<Input, StepMap>;
302
- }>(config: {
303
- readonly needs?: N;
304
- readonly on: (args: {
305
- readonly input: NoInfer<Input>;
306
- readonly needs: NoInfer<NeedsOutputs<N>>;
307
- }) => D;
308
- readonly cases: Cases;
309
- }): Step<{
310
- readonly [K in keyof Cases]: MatchArmOutput<AsStepMap<ReturnType<Cases[K]>>>;
311
- }[keyof Cases]>;
312
158
  match<N extends NeedsMap, Arms extends ReadonlyArray<MatchArmShape<Input, N>>>(config: {
313
159
  readonly needs?: N;
314
160
  readonly arms: Arms;
315
- }): Step<MatchArmOutput<AsStepMap<ReturnType<Arms[number]["build"]>>>>;
316
- /**
317
- * Chainable task definition. The first arg is the persisted step id; the
318
- * config follows the standalone `task` shape plus a `needs: ["sibling"]`
319
- * tuple of accumulator keys. Returns the same builder typed with the new
320
- * entry appended to `A`.
321
- *
322
- * b.step('fetchRecording', { run: async () => ({ url: '…' }) })
323
- * .step('transcribe', {
324
- * needs: ['fetchRecording'],
325
- * run: async ({ needs }) => ({ text: needs.fetchRecording.url + '…' }),
326
- * })
327
- */
328
- step<const Key extends string, const Needs extends ReadonlyArray<keyof A & string>, Output>(key: Exclude<Key, keyof A>, config: StepEntryConfig<Input, A, Needs, Output>): Builder<Input, A & {
329
- readonly [K in Key]: Output;
330
- }>;
331
- /**
332
- * Include a pre-built `Step<O>` (from `b.task` / `b.signal` / `b.match`)
333
- * into the chain under a key. The included step's output joins `A`.
334
- */
335
- include<const Key extends string, S extends Step<unknown>>(key: Exclude<Key, keyof A>, step: S): Builder<Input, A & {
336
- readonly [K in Key]: S extends Step<infer O> ? O : never;
337
- }>;
161
+ }): Step<MatchArmOutput<ReturnType<Arms[number]["build"]>>>;
338
162
  }
339
- /**
340
- * Acceptable shape for a build callback's return. Either a plain `StepMap`
341
- * (record-literal style) or a `Builder<Input, A>` whose accumulator is
342
- * extracted by `flow()`.
343
- */
344
- type BuildResult<Input, M extends StepMap> = M | Builder<Input, BuilderAccumulator<M>>;
345
- /** Convert a `StepMap` back to its accumulator shape `{ [K]: Output }`. */
346
- type BuilderAccumulator<M extends StepMap> = {
347
- readonly [K in keyof M]: M[K] extends Step<infer O> ? O : never;
348
- };
349
- /** Extract a `StepMap` from either a plain map or a `Builder` chain result. */
350
- type AsStepMap<R> = R extends Builder<unknown, infer A> ? {
351
- readonly [K in keyof A]: Step<A[K]>;
352
- } : R extends StepMap ? R : never;
353
- /**
354
- * Modes for `FlowConcurrency`. v1 implements only `cancel-in-progress`; the
355
- * union is a single literal so adding `queue` / `reject` later is a
356
- * non-breaking widening rather than a new discriminator.
357
- */
358
163
  type ConcurrencyMode = "cancel-in-progress";
359
- /**
360
- * Per-flow concurrency control. When set, `wf.start()` derives a group key
361
- * from the validated input and applies the configured `mode` against any
362
- * prior run sharing the same `(flowId, key)` pair.
363
- *
364
- * `cancel-in-progress`: any active prior run with the same key transitions
365
- * to the `canceled` terminal state before the new run is inserted. In-flight
366
- * steps on the canceled run run to completion (their facts persist), but the
367
- * dispatcher stops scheduling further steps for it.
368
- */
369
164
  interface FlowConcurrency<Input = Json> {
370
- /**
371
- * Derive the concurrency group key from the validated flow input.
372
- * Synchronous + pure. Returning a non-string or an empty string throws
373
- * `NagiValidationError` at `wf.start()` time.
374
- */
375
165
  readonly keyFn: (input: Input) => string;
376
166
  readonly mode: ConcurrencyMode;
377
167
  }
378
- interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R, Output = unknown> {
379
- /** Stable persistence handle. TanStack-key shaped (kebab or snake). */
168
+ interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R extends StepMap, Output = unknown> {
380
169
  readonly id: Id;
381
170
  readonly input: InputSchema;
382
- /**
383
- * Returns either a `StepMap` (record-literal style with `b.task` / `b.signal`
384
- * / `b.match`) or a chained `Builder<Input, A>` (Express-style with `b.step`
385
- * / `b.include`). `flow()` extracts the assembled `StepMap` either way.
386
- */
387
171
  readonly build: (b: Builder<InferSchemaOutput<InputSchema>>) => R;
388
- /**
389
- * Compute the flow's terminal output from its step outputs. Fired once at
390
- * `flow.completed` and persisted on the fact + `onFlowComplete` event.
391
- * Skipped steps land as `null` in the input record at runtime even though
392
- * the type claims otherwise (consistent with the "skip is transitive" lock).
393
- */
394
- output?(steps: NeedsOutputs<AsStepMap<R>>): Output;
395
- /**
396
- * Concurrency group config. See {@link FlowConcurrency}. `keyFn` is typed
397
- * against the schema's parsed output — what `b.task`'s `run({ input })`
398
- * receives — so refactors to the input schema break the key derivation
399
- * at compile time.
400
- */
172
+ output?(steps: NeedsOutputs<R>): Output;
401
173
  readonly concurrency?: FlowConcurrency<InferSchemaOutput<InputSchema>>;
402
- /**
403
- * Flow-level lifecycle hooks. Like step-local hooks (see {@link TaskConfig}),
404
- * these fire *before* the cross-cutting `FlowHooks` callbacks, and a thrown
405
- * hook is swallowed + logged rather than failing the run.
406
- *
407
- * `onComplete`'s event is typed against this flow's `Output` (whatever the
408
- * `output()` resolver returns).
409
- *
410
- * `onError` also fires when a run is canceled by a concurrency-group
411
- * supersede; the event's `error.name` is `"NagiCanceledError"` and
412
- * `error.cause` carries `{ canceledByRunId, concurrencyKey }`.
413
- */
414
174
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
415
175
  readonly onComplete?: (event: FlowCompleteEvent & {
416
176
  readonly output: NoInfer<Output>;
@@ -422,22 +182,9 @@ interface Flow<Id extends string = string, InputSchema extends StandardSchemaV1
422
182
  readonly input: InputSchema;
423
183
  readonly steps: M;
424
184
  output?(steps: NeedsOutputs<M>): Output;
425
- /**
426
- * Forwarded from {@link FlowConfig}; surfaced for the dispatcher.
427
- *
428
- * Note these use the plain (non-Output-augmented) event types — the typed
429
- * narrowing lives on {@link FlowConfig}'s callbacks at build time, while
430
- * the runtime form is variance-friendly so a concrete `Flow<...{x: number}>`
431
- * stays assignable to `Flow<...unknown>` (the dispatcher's view).
432
- */
433
185
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
434
186
  readonly onComplete?: (event: FlowCompleteEvent) => void | Promise<void>;
435
187
  readonly onError?: (event: FlowErrorEvent) => void | Promise<void>;
436
- /**
437
- * Forwarded from {@link FlowConfig.concurrency}. The runtime form widens
438
- * `Input` to `Json` so a concrete `Flow<...{x: number}>` is assignable to
439
- * `Flow<...unknown>` (the dispatcher's view).
440
- */
441
188
  readonly concurrency?: FlowConcurrency<Json>;
442
189
  }
443
190
  type FlowInput<F> = F extends Flow<string, infer S, StepMap, unknown> ? InferSchemaOutput<S> : never;
@@ -449,6 +196,16 @@ interface FlowEvent {
449
196
  }
450
197
  interface FlowStartEvent extends FlowEvent {
451
198
  readonly input: Json;
199
+ /**
200
+ * Set when this run was started as a subflow child. Undefined for
201
+ * top-level runs (start / startById). Carried in-process only — for
202
+ * durable linkage see FlowStartedFact.parentRunId / parentStepId.
203
+ */
204
+ readonly parent?: {
205
+ readonly runId: RunId;
206
+ readonly stepId: StepId;
207
+ readonly attempt: AttemptNumber;
208
+ };
452
209
  }
453
210
  interface FlowCompleteEvent extends FlowEvent {
454
211
  readonly output: Json;
@@ -462,13 +219,6 @@ interface StepEvent extends FlowEvent {
462
219
  readonly kind: StepKind;
463
220
  }
464
221
  interface StepStartEvent extends StepEvent {
465
- /**
466
- * The resolved input for this step at the moment it starts.
467
- * - Task: the value passed to `run({ input, needs, ctx })`.
468
- * - Signal: `null` (signals await an external payload — no pre-execution input).
469
- * - Match: `null` (the discriminator value is computed inside the match
470
- * handler; the start event fires before that resolves).
471
- */
472
222
  readonly input: Json;
473
223
  }
474
224
  interface StepCompleteEvent extends StepEvent {
@@ -502,25 +252,20 @@ interface FlowHooks {
502
252
  interface WorkerConfig {
503
253
  readonly concurrency?: number;
504
254
  readonly pollIntervalMs?: Millis;
505
- /** AbortSignal drives graceful drain on SIGTERM/SIGINT. */
506
255
  readonly signal?: AbortSignal;
507
256
  }
508
257
  interface WorkerRunOnceOpts {
509
258
  readonly maxSteps?: number;
510
259
  }
511
260
  interface WorkerRunUntilEmptyOpts {
512
- /** Wall-clock deadline in `Date.now()` units. Edge runtimes have CPU/wall-time budgets. */
513
261
  readonly deadline?: number;
514
262
  }
515
263
  interface WorkerRunResult {
516
264
  readonly processed: number;
517
265
  }
518
266
  interface Worker {
519
- /** Long-running fleet (Cloud Run service, ECS, dedicated VM). Blocks until `signal` aborts. */
520
267
  run(): Promise<void>;
521
- /** HTTP server alongside requests. Returns after up to `maxSteps` are processed. */
522
268
  runOnce(opts?: WorkerRunOnceOpts): Promise<WorkerRunResult>;
523
- /** Serverless / edge. Drains everything available within the deadline and exits. */
524
269
  runUntilEmpty(opts?: WorkerRunUntilEmptyOpts): Promise<WorkerRunResult>;
525
270
  }
526
271
  type ClaimToken = string & {
@@ -532,44 +277,9 @@ interface SerializedError {
532
277
  readonly stack?: string;
533
278
  readonly cause?: Json;
534
279
  }
535
- /**
536
- * Fact-ordering invariant (must hold for every Store implementation):
537
- * facts persisted via `appendFact` / `completeStep` / `failStep` MUST be
538
- * visible to the next `loadRunState` call. The scheduler decides what to run
539
- * by projecting `RunState.steps` from the fact log, then calls `nextRunnable`
540
- * — if a `step.completed` write isn't reflected in a subsequent read, the
541
- * scheduler will re-enqueue or skip steps incorrectly. Adapters with read
542
- * replicas must route `loadRunState` to the primary or wait for replication
543
- * within a single `advance` cycle.
544
- */
545
280
  interface Store {
546
281
  appendFact(runId: RunId, fact: Fact): Promise<void>;
547
282
  loadRunState(runId: RunId): Promise<RunState>;
548
- /**
549
- * Atomically begin a run. Inserts the `flow.started` fact and any
550
- * materialized run row keyed by `runId` IFF no run with this `runId` already
551
- * exists. Returns `{ started: true, canceled: [...] }` if this call created
552
- * the run, `{ started: false, canceled: [] }` if the run already exists.
553
- *
554
- * Two concurrent `tryStartRun(runId, ...)` calls with the same `runId` must
555
- * result in exactly one `flow.started` fact. Adapters enforce this at the
556
- * durability layer (e.g. Postgres `INSERT ... ON CONFLICT DO NOTHING` keyed
557
- * by `run_id`), NOT via app-level check-then-insert.
558
- *
559
- * When `concurrency` is supplied, the adapter ALSO atomically cancels any
560
- * prior runs whose `(flowId, concurrency.key)` matches and whose status is
561
- * still `pending` / `running`. Each canceled run gets a `flow.canceled`
562
- * fact appended to its log and its materialized status updated to
563
- * `canceled`. The returned `canceled` array carries the fact for each
564
- * canceled run so the runtime can fire `onFlowError` post-commit.
565
- *
566
- * Adapters MUST serialize concurrent starts for the same
567
- * `(flowId, concurrency.key)` (e.g. Postgres advisory-lock keyed on the
568
- * pair) so the partial unique index on active runs is never violated.
569
- *
570
- * The runtime calls this exactly once at `wf.start()`. Subsequent facts go
571
- * through `appendFact` as usual.
572
- */
573
283
  tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
574
284
  readonly key: string;
575
285
  readonly mode: ConcurrencyMode;
@@ -577,161 +287,49 @@ interface Store {
577
287
  readonly started: boolean;
578
288
  readonly canceled: ReadonlyArray<{
579
289
  readonly runId: RunId;
580
- readonly fact: FlowCanceledFact;
290
+ readonly fact: FlowCanceledByConcurrencyFact;
581
291
  }>;
582
292
  }>;
583
- /**
584
- * Returns null if the step is already claimed under a live lease. Lease
585
- * duration is owned by the Store implementation; configure it on the adapter.
586
- */
587
293
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
588
294
  completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
589
295
  failStep(runId: RunId, stepId: StepId, error: SerializedError, fact: Fact): Promise<void>;
590
- /** Memoization read — returns the persisted output of a previously completed step. */
591
296
  getStepOutput(runId: RunId, stepId: StepId): Promise<Json | null>;
592
- /** `ctx.once` durable record. */
593
297
  recordOnce(runId: RunId, stepId: StepId, scope: string, value: Json): Promise<void>;
594
298
  getOnce(runId: RunId, stepId: StepId, scope: string): Promise<Json | null>;
595
- /**
596
- * Run a task step's handler inside an adapter-owned transaction.
597
- *
598
- * Implementations open a transaction (or equivalent atomic scope), invoke
599
- * `body(tx)`, and on a successful return persist the returned fact
600
- * atomically with any writes the handler made via `ctx.tx`. The output is
601
- * returned to the caller; for `step.failed` facts the output is ignored
602
- * (callers should still return the placeholder shape the type requires).
603
- *
604
- * Contract:
605
- * - If `body` throws, the transaction is rolled back and the error
606
- * propagates. The caller (dispatcher) is responsible for recording the
607
- * failure via `failStep` in a separate scope so the failure survives
608
- * even when domain writes do not.
609
- * - On a returned `step.completed` fact, the same atomic scope must also
610
- * record the step output (such that `getStepOutput` reflects it) and
611
- * release any worker lease held for `(runId, stepId, attempt)`.
612
- *
613
- * For adapters with no real transaction (in-memory, sqlite without WAL),
614
- * `tx` is passed as `undefined as Tx` and the write is non-atomic — those
615
- * adapters are not used with `ctx.tx` writes.
616
- */
617
299
  runStep<T extends Json>(runId: RunId, stepId: StepId, attempt: AttemptNumber, body: (tx: Tx) => Promise<{
618
300
  readonly output: T;
619
301
  readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
620
302
  }>): Promise<T>;
621
- /**
622
- * Deduped store of canonical flow DAGs, keyed by content hash. Inserts are
623
- * idempotent — the same `(flowHash, dag)` may be written by many concurrent
624
- * boots; only the first physical row survives. Subsequent writes are
625
- * no-ops.
626
- *
627
- * Adapters MUST enforce this at the durability layer (e.g. Postgres
628
- * `INSERT ... ON CONFLICT (flow_hash) DO NOTHING`).
629
- */
630
303
  upsertSnapshot(args: {
631
304
  readonly flowHash: string;
632
305
  readonly flowId: string;
633
306
  readonly dag: Json;
634
307
  }): Promise<void>;
635
- /**
636
- * Read the currently-published hash for a flow id. Returns `null` if no
637
- * `flow_ref` row exists yet — first boot of a never-published flow.
638
- */
639
308
  getRef(flowId: string): Promise<string | null>;
640
- /**
641
- * Atomically set the published hash for a flow id. Last writer wins; the
642
- * audit trail of ref changes lives in {@link appendGlobalFact} as
643
- * `flow_ref.updated`.
644
- *
645
- * Adapters MUST enforce atomicity at the durability layer (e.g. Postgres
646
- * `INSERT ... ON CONFLICT (flow_id) DO UPDATE`).
647
- */
648
309
  setRef(flowId: string, flowHash: string): Promise<void>;
649
- /**
650
- * Load a snapshot by its content hash. Returns `null` if no snapshot with
651
- * this hash has been recorded — e.g., the deployment is replaying a run
652
- * whose pinned topology was never seen by this store.
653
- */
654
310
  loadSnapshot(flowHash: string): Promise<{
655
311
  readonly flowId: string;
656
312
  readonly dag: Json;
657
313
  } | null>;
658
- /**
659
- * Append a non-run-scoped fact. See {@link GlobalFact} for the union.
660
- * Currently only `flow_ref.updated` events flow through this method.
661
- */
662
314
  appendGlobalFact(fact: GlobalFact): Promise<void>;
663
- /**
664
- * Discover runs by their input + flow + status. See {@link QueryRunsOpts}
665
- * and {@link Wf.queryRuns} (in `runtime.ts`) for the public contract.
666
- *
667
- * Adapters MUST order results by `(startedAt DESC, runId DESC)` so cursor
668
- * pagination is stable across calls. Adapters MUST treat
669
- * `opts.where.input` as JSONB containment (Postgres `@>` semantics —
670
- * the row's input is a superset of the filter object, recursively).
671
- */
672
315
  queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
673
- /**
674
- * Return the run ids of every direct child run spawned by `parentRunId`
675
- * via `b.subflow()`. Identified by `flow.started.parentRunId === parentRunId`.
676
- * Order is unspecified.
677
- *
678
- * Used by `wf.cancel(runId)` to cascade cancellation transitively. Indexed
679
- * lookup: Postgres adapter persists `parent_run_id` as a column on
680
- * `workflow_run` with a btree index; in-memory adapter maintains a
681
- * `parent → set<children>` map updated on `tryStartRun`.
682
- */
683
316
  listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
684
- /**
685
- * Retention prune. Deletes facts (and run-scoped per-step rows) for terminal
686
- * runs whose `completed_at < opts.olderThan` and whose status is in
687
- * `opts.statuses`. See {@link PruneOpts} and {@link Wf.pruneFacts} (in
688
- * `runtime.ts`) for the public contract.
689
- *
690
- * Adapters MUST:
691
- * - Never prune runs in non-terminal status (`pending` / `running`). The
692
- * public type forbids it; this is defense-in-depth.
693
- * - Delete in batches of `opts.batchSize` until no more victims remain.
694
- * Postgres uses `FOR UPDATE SKIP LOCKED` so concurrent pruners share work
695
- * safely; in-memory is single-process and atomic between awaits.
696
- * - When `opts.keepSummary` is true, retain a summary row visible to
697
- * `queryRuns` (postgres keeps the `workflow_run` row; in-memory keeps a
698
- * `RunSummary` shadow). When false, the run is fully removed.
699
- */
700
317
  pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
701
318
  }
702
319
  interface QueryRunsWhere {
703
320
  readonly flowId?: string;
704
321
  readonly status?: RunStatus | ReadonlyArray<RunStatus>;
705
- /**
706
- * JSONB containment against `flow.started.input`. The stored input is a
707
- * superset of this object — recursive on nested objects, exact on
708
- * arrays/scalars. Example: `{ videoId: 'abc' }` matches
709
- * `{ videoId: 'abc', userId: 7 }`.
710
- *
711
- * Containment only — no JSONPath, no operators. Combine keys for AND.
712
- */
713
322
  readonly input?: Record<string, Json>;
714
323
  }
715
- /**
716
- * Options for {@link Wf.queryRuns}.
717
- *
718
- * Encoded as a discriminated union on `latest` so the type system rejects
719
- * `{ latest: true, limit, cursor }` at compile time — those fields are
720
- * meaningless when only one row is requested. Adapters still validate at
721
- * runtime as defense-in-depth.
722
- */
723
324
  type QueryRunsOpts = {
724
325
  readonly where?: QueryRunsWhere;
725
- /** Return at most one run — the most recently started match. */
726
326
  readonly latest: true;
727
327
  readonly limit?: never;
728
328
  readonly cursor?: never;
729
329
  } | {
730
330
  readonly where?: QueryRunsWhere;
731
331
  readonly latest?: false;
732
- /** Page size. Default 50, max 500. */
733
332
  readonly limit?: number;
734
- /** Opaque cursor from a previous `queryRuns` call. */
735
333
  readonly cursor?: string;
736
334
  };
737
335
  interface RunSummary {
@@ -744,44 +342,13 @@ interface RunSummary {
744
342
  }
745
343
  interface QueryRunsResult {
746
344
  readonly runs: ReadonlyArray<RunSummary>;
747
- /** Pass to the next `queryRuns` to resume. `null` when no more rows. */
748
345
  readonly cursor: string | null;
749
346
  }
750
- /**
751
- * Statuses {@link Wf.pruneFacts} accepts. Restricted to terminal statuses —
752
- * `pending` and `running` are excluded at the type level so the compiler
753
- * rejects `statuses: ["running"]`. The runtime re-validates as defense in
754
- * depth for JS callers / `as any` escape hatches.
755
- */
756
347
  type PrunableStatus = Extract<RunStatus, "completed" | "failed" | "canceled">;
757
- /**
758
- * Options for {@link Wf.pruneFacts}. Retention sweep over terminal runs.
759
- *
760
- * The prune is keyed on `workflow_run.completed_at`. Runs whose
761
- * `completed_at` is null (still active) are skipped regardless of `statuses`.
762
- */
763
348
  interface PruneOpts {
764
- /** Prune runs whose `completed_at < olderThan`. */
765
349
  readonly olderThan: Date;
766
- /**
767
- * Terminal statuses to prune. Default: `["completed"]`. `pending` /
768
- * `running` are never prunable (compile-time and runtime).
769
- */
770
350
  readonly statuses?: ReadonlyArray<PrunableStatus>;
771
- /**
772
- * Per-batch deletion size. Default: 1000. Postgres uses one transaction
773
- * per batch so a large prune doesn't hold locks across the whole table.
774
- */
775
351
  readonly batchSize?: number;
776
- /**
777
- * When true (default), retain a summary row so the run is still visible to
778
- * `queryRuns` — facts/steps/leases/timers/dedupes are still deleted. When
779
- * false, the run is fully removed (and `queryRuns` no longer finds it).
780
- *
781
- * Trade-off: kept summaries cost ~80 bytes per run (postgres) / one
782
- * `RunSummary` (in-memory). Use `false` only if `queryRuns` history is
783
- * not needed past the retention window.
784
- */
785
352
  readonly keepSummary?: boolean;
786
353
  }
787
354
  interface PruneResult {
@@ -799,11 +366,8 @@ interface QueueDequeueOpts {
799
366
  readonly count: number;
800
367
  }
801
368
  interface QueueEnqueueOpts {
802
- /** Attempt number to publish. Defaults to 1. The dispatcher controls increments. */
803
369
  readonly attempt?: AttemptNumber;
804
- /** Visibility delay — the message becomes dequeueable after `delayMs`. */
805
370
  readonly delayMs?: Millis;
806
- /** Adapter-specific extra data. Core never reads this. */
807
371
  readonly payload?: Json;
808
372
  }
809
373
  interface Queue {
@@ -817,17 +381,9 @@ interface Queue {
817
381
  }
818
382
  interface Clock {
819
383
  now(): Date;
820
- /** Resolves when `ms` has elapsed or `signal` aborts. */
821
384
  sleep(ms: Millis, signal?: AbortSignal): Promise<void>;
822
- /** Persistent timer — wakes the scheduler at `at` for `(runId, stepId)`. */
823
385
  schedule(at: Date, runId: RunId, stepId: StepId): Promise<void>;
824
386
  }
825
- /**
826
- * Wakes the scheduler when there's work to do. Default impl polls via the
827
- * Queue plugin; Postgres adapter offers a NOTIFY/LISTEN variant.
828
- * Per the sharding-safety lock: the handler receives a `runId` — there is no
829
- * global tick.
830
- */
831
387
  interface Trigger {
832
388
  subscribe(handler: (runId: RunId) => void): () => void;
833
389
  }
@@ -840,44 +396,14 @@ interface FlowStartedFact extends FactBase {
840
396
  readonly kind: "flow.started";
841
397
  readonly flowId: string;
842
398
  readonly input: Json;
843
- /**
844
- * Content hash of the canonical flow DAG at the moment this run started.
845
- * Pins the run to a specific topology; `wf.replay()` reads this to detect
846
- * snapshot drift. Optional in v0 — legacy runs from before the snapshot
847
- * store landed have `undefined`. After a soak period it becomes required.
848
- */
849
399
  readonly flowHash?: string;
850
- /**
851
- * Free-form handler-code identifier, typically a git SHA. Sourced from
852
- * `nagi({ codeVersion })`. Captures handler-source drift orthogonally to
853
- * `flowHash` (which only captures topology). See RFC 0001
854
- * "Topology vs handler code."
855
- */
856
400
  readonly codeVersion?: string;
857
- /**
858
- * For runs spawned by `b.subflow()`: the parent run that started this
859
- * child, and the parent step id awaiting its completion. The pair forms a
860
- * back-pointer the runtime uses to wake the parent step when this run
861
- * reaches `flow.completed` / `flow.failed`. See RFC 0006 (issue #10).
862
- *
863
- * Both undefined for runs started directly via `wf.start()`.
864
- */
865
401
  readonly parentRunId?: RunId;
866
402
  readonly parentStepId?: StepId;
867
403
  }
868
- /**
869
- * A non-run-scoped event, recorded as a side effect of nagi runtime activity
870
- * that has no specific `runId`. Lives in the `nagi.global_fact` table.
871
- *
872
- * Per RFC 0001: when nagi boots and a flow's canonical hash differs from the
873
- * currently-published one, the runtime updates `flow_ref` and appends a
874
- * `flow_ref.updated` global fact. The audit trail of ref changes is queryable
875
- * independently of any single run.
876
- */
877
404
  interface FlowRefUpdatedFact {
878
405
  readonly kind: "flow_ref.updated";
879
406
  readonly flowId: string;
880
- /** Previous hash, or null when this is the first publish of `flowId`. */
881
407
  readonly from: string | null;
882
408
  readonly to: string;
883
409
  readonly at: Date;
@@ -891,38 +417,26 @@ interface FlowFailedFact extends FactBase {
891
417
  readonly kind: "flow.failed";
892
418
  readonly error: SerializedError;
893
419
  }
894
- /**
895
- * Recorded when a run reaches the canceled terminal status. Three cause
896
- * paths share the same fact kind:
897
- *
898
- * - `"concurrency"` — a new `wf.start()` with the same concurrency group
899
- * superseded this run. `canceledByRunId` is the new run; `concurrencyKey`
900
- * is the shared key.
901
- * - `"explicit"` — `wf.cancel(runId)` was called. `canceledByRunId === runId`,
902
- * `concurrencyKey` carries the caller's `reason` string (back-compat).
903
- * - `"operator"` — `wf.operator().abort(runId, { actor, note? })` was called.
904
- * `actor` is required; `note` is optional human context. `canceledByRunId
905
- * === runId`, `concurrencyKey === ""`.
906
- *
907
- * The `cause` field is the canonical discriminator. It is optional in the
908
- * type for back-compat with pre-cause facts: projectors treat a missing
909
- * `cause` as `"concurrency"` (the original semantic).
910
- */
911
- interface FlowCanceledFact extends FactBase {
420
+ interface FlowCanceledByConcurrencyFact extends FactBase {
912
421
  readonly kind: "flow.canceled";
913
- readonly cause?: "concurrency" | "explicit" | "operator";
914
- /** The new run that took over this run's concurrency slot, or self for explicit/operator cancels. */
422
+ readonly cause: "concurrency";
915
423
  readonly canceledByRunId: RunId;
916
- /**
917
- * For `"concurrency"`: the shared concurrency key. For `"explicit"`: the
918
- * caller's `reason` string (legacy carrier). For `"operator"`: empty.
919
- */
920
424
  readonly concurrencyKey: string;
921
- /** Operator who triggered the cancel. Present when `cause === "operator"`. */
922
- readonly actor?: string;
923
- /** Free-form audit note from the operator. */
425
+ }
426
+ interface FlowCanceledExplicitlyFact extends FactBase {
427
+ readonly kind: "flow.canceled";
428
+ readonly cause: "explicit";
429
+ readonly reason: string;
430
+ readonly note?: string;
431
+ }
432
+ interface FlowCanceledByOperatorFact extends FactBase {
433
+ readonly kind: "flow.canceled";
434
+ readonly cause: "operator";
435
+ readonly actor: string;
436
+ readonly reason: string;
924
437
  readonly note?: string;
925
438
  }
439
+ type FlowCanceledFact = FlowCanceledByConcurrencyFact | FlowCanceledExplicitlyFact | FlowCanceledByOperatorFact;
926
440
  interface StepStartedFact extends FactBase {
927
441
  readonly kind: "step.started";
928
442
  readonly stepId: StepId;
@@ -940,19 +454,6 @@ interface StepFailedFact extends FactBase {
940
454
  readonly attempt: AttemptNumber;
941
455
  readonly error: SerializedError;
942
456
  }
943
- /**
944
- * Terminal classification for a step whose attempt did not produce a
945
- * `step.completed` output because the run was canceled while it was in
946
- * flight — either because a newer `wf.start()` superseded this run via a
947
- * concurrency group, or because the handler honored `ctx.signal` (composed
948
- * with a user-supplied timeout, etc.) and threw an `AbortError`.
949
- *
950
- * Recorded in place of `step.completed` / `step.failed` so observers can
951
- * discriminate "canceled mid-execution" from "handler errored". Not retried.
952
- * `error` is preserved when the cancellation surfaced as a thrown
953
- * `AbortError`; absent when classification happened at the boundary (handler
954
- * returned normally on an already-canceled run).
955
- */
956
457
  interface StepCanceledFact extends FactBase {
957
458
  readonly kind: "step.canceled";
958
459
  readonly stepId: StepId;
@@ -968,27 +469,9 @@ interface StepRetriedFact extends FactBase {
968
469
  interface StepSkippedFact extends FactBase {
969
470
  readonly kind: "step.skipped";
970
471
  readonly stepId: StepId;
971
- /**
972
- * - `"when-false"` — the step's `when` predicate returned false.
973
- * - `"transitive"` — an upstream dependency was skipped or failed.
974
- * - `"manual"` — an operator explicitly skipped this step via
975
- * `wf.operator().skip()`. `actor` + optional `note` + `cascade` are
976
- * populated; the other reasons leave them undefined.
977
- */
978
472
  readonly reason: "when-false" | "transitive" | "manual";
979
- /** Operator who triggered a manual skip. */
980
473
  readonly actor?: string;
981
- /** Free-form audit note for a manual skip. */
982
474
  readonly note?: string;
983
- /**
984
- * For manual skips only. `"skip"` (default) keeps the existing locked
985
- * semantic: downstream steps with `needs: { x }` are transitively skipped.
986
- * `"continue"` lets downstream run with `needs.x === null` — same shape
987
- * `resolveNeeds` produces for any skipped step, but the scheduler stops
988
- * propagating the skip past this step. The handler is responsible for
989
- * tolerating the null value; the type contract on `needs.x` (locked as
990
- * unconditional `Output`) does not change.
991
- */
992
475
  readonly cascade?: "skip" | "continue";
993
476
  }
994
477
  interface SignalSentFact extends FactBase {
@@ -1000,11 +483,6 @@ interface SignalReceivedFact extends FactBase {
1000
483
  readonly kind: "signal.received";
1001
484
  readonly stepId: StepId;
1002
485
  readonly payload: Json;
1003
- /**
1004
- * The alias the caller sent, when the resolved signal step accepts
1005
- * multiple names (or a single name != stepId). Absent when the incoming
1006
- * name equals the step id — the back-compat single-name case.
1007
- */
1008
486
  readonly signalName?: string;
1009
487
  }
1010
488
  interface OnceRecordedFact extends FactBase {
@@ -1018,55 +496,18 @@ interface MatchArmSelectedFact extends FactBase {
1018
496
  readonly stepId: StepId;
1019
497
  readonly arm: string;
1020
498
  }
1021
- /**
1022
- * Marks a step as cleared from the projected `RunState.steps` so the next
1023
- * `nextRunnable()` pass treats it (and any cascaded descendants) as runnable
1024
- * again. Emitted by `wf.replay(runId, { from })` and `wf.operator().retry()` —
1025
- * one fact per step that the runtime resolved as part of the cascade. The
1026
- * user-named step has `cascadedFrom === undefined`; transitively reset
1027
- * descendants record the originating step so read-side UIs can group them.
1028
- *
1029
- * `actor` and `note` are populated only when the reset came from
1030
- * `wf.operator().retry()`. Both are absent on user-driven `wf.replay({from})`
1031
- * calls so the existing fact log shape is preserved.
1032
- */
1033
499
  interface StepResetFact extends FactBase {
1034
500
  readonly kind: "step.reset";
1035
501
  readonly stepId: StepId;
1036
- /** The user-named `from` step that caused this reset, when this fact is a cascaded descendant. */
1037
502
  readonly cascadedFrom?: StepId;
1038
- /** Operator who triggered the retry. */
1039
503
  readonly actor?: string;
1040
- /** Free-form audit note from the operator. */
1041
504
  readonly note?: string;
1042
505
  }
1043
- /**
1044
- * Operator-initiated signal that a step's in-flight attempt should abort.
1045
- * The cancel watcher in `executeTask` polls for this fact and calls
1046
- * `ctx.signal.abort()` when it lands for the current `(stepId, attempt)`.
1047
- *
1048
- * This fact does not mutate projected state on its own — the resulting
1049
- * `step.canceled` fact (recorded once the handler returns / throws) is what
1050
- * marks the attempt terminal. Audit fields (`actor`, `note`) carry through
1051
- * to the read-side.
1052
- *
1053
- * Emitted by `wf.operator().retry()` when called on a `running` step; the
1054
- * subsequent `step.reset` + advance happens after the in-flight attempt
1055
- * settles, so a single retry call writes:
1056
- *
1057
- * step.abort-requested (audit)
1058
- * ... (handler aborts; step.canceled lands via boundary check)
1059
- * step.reset (cascade)
1060
- * ... (advance re-enqueues)
1061
- */
1062
506
  interface StepAbortRequestedFact extends FactBase {
1063
507
  readonly kind: "step.abort-requested";
1064
508
  readonly stepId: StepId;
1065
- /** Attempt number being aborted — matches the in-flight attempt. */
1066
509
  readonly attempt: AttemptNumber;
1067
- /** Operator who requested the abort. */
1068
510
  readonly actor: string;
1069
- /** Free-form audit note. */
1070
511
  readonly note?: string;
1071
512
  }
1072
513
  type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepCanceledFact | StepRetriedFact | StepSkippedFact | StepResetFact | StepAbortRequestedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
@@ -1085,157 +526,37 @@ interface RunState {
1085
526
  readonly status: RunStatus;
1086
527
  readonly steps: Readonly<Record<StepId, StepState>>;
1087
528
  readonly facts: ReadonlyArray<Fact>;
1088
- /** Content hash of the canonical flow DAG this run is pinned to. */
1089
529
  readonly flowHash?: string;
1090
- /** Handler-code identifier (typically a git SHA) recorded at run start. */
1091
530
  readonly codeVersion?: string;
1092
531
  }
1093
532
  type ReplayMode = "inspect" | "continue";
1094
533
  interface ReplayOpts {
1095
534
  readonly mode: ReplayMode;
1096
- /**
1097
- * When true, allow replays to proceed even if the live flow's canonical
1098
- * hash differs from the snapshot pinned to the run. Scheduling decisions
1099
- * come from the pinned snapshot; handler bodies are resolved from the
1100
- * currently-registered flow by step id (best-effort).
1101
- *
1102
- * When false (default), drift throws `NagiSnapshotDriftError`.
1103
- */
1104
535
  readonly allowDrift?: boolean;
1105
- /**
1106
- * Whether step / flow lifecycle hooks (both the step-local ones on
1107
- * `TaskConfig` / `FlowConfig` and the cross-cutting `FlowHooks`) fire during
1108
- * replay. Defaults to `true` — replay re-executes steps via the idempotent
1109
- * dispatcher and emits the same observable lifecycle. Set to `false` for
1110
- * backfills or inspection-style replays where re-emitting webhooks would
1111
- * dual-publish.
1112
- */
1113
536
  readonly fireHooks?: boolean;
1114
- /**
1115
- * Replay starting from a specific step instead of the default "first
1116
- * incomplete" behavior. The runtime appends `step.reset` facts for `from`
1117
- * and every transitive descendant, then re-dispatches — completed steps
1118
- * downstream of `from` re-run, completed steps upstream are preserved.
1119
- *
1120
- * - Throws `NagiValidationError` if `from` is not a registered step in the
1121
- * effective flow (the snapshot topology under drift + `allowDrift`, else
1122
- * the live flow).
1123
- * - Throws `NagiRuntimeError` if the run is still `running` — resetting
1124
- * mid-flight races in-flight workers.
1125
- * - Ignored under `mode: "inspect"` (inspect remains side-effect-free).
1126
- */
1127
537
  readonly from?: StepId;
1128
538
  }
1129
- /**
1130
- * Audit fields common to every operator action. `actor` is free-form — the
1131
- * adapter logs whatever the caller supplies. Authorization lives upstream
1132
- * (HTTP / CLI / etc.), not in core; the operator surface trusts its caller.
1133
- */
1134
539
  interface OperatorAuditOpts {
1135
- /** Identifier for the human or system that triggered this operation. */
1136
540
  readonly actor: string;
1137
- /** Optional free-form audit note recorded on the resulting fact(s). */
1138
541
  readonly note?: string;
1139
542
  }
1140
543
  interface OperatorSkipOpts extends OperatorAuditOpts {
1141
- /**
1142
- * - `"skip"` (default) — downstream `needs.x` steps are transitively
1143
- * skipped, matching the locked semantic for `when:false` and failure
1144
- * propagation. Type contract on `needs.x` is preserved.
1145
- * - `"continue"` — downstream `needs.x` steps run. The handler sees
1146
- * `needs.x === null` (same shape `resolveNeeds` produces for any
1147
- * skipped step). The handler is responsible for tolerating the null
1148
- * value; the type contract on `needs.x` (locked as unconditional
1149
- * `Output`) is not changed at the type level.
1150
- */
1151
544
  readonly cascade?: "skip" | "continue";
1152
545
  }
1153
- /**
1154
- * Operator-facing API for unsticking runs. Returned by `wf.operator()`.
1155
- * Every action appends an audit-bearing fact to the run's fact log so the
1156
- * intervention is observable to downstream tooling without read-modify-write
1157
- * against the materialized tables.
1158
- *
1159
- * Authorization is the caller's responsibility — typically a thin HTTP /
1160
- * CLI wrapper checks who is allowed to call these before delegating.
1161
- */
1162
546
  interface Operator {
1163
- /**
1164
- * Mark `stepId` as skipped, regardless of its current state. Appends
1165
- * `step.skipped` with `reason: "manual"`. Behavior on downstream cascade
1166
- * is controlled by `opts.cascade`.
1167
- *
1168
- * Idempotent on already-terminal steps: a skip of a `completed` step is
1169
- * a logged no-op, not a re-classification — the fact log preserves the
1170
- * earlier `step.completed` and observers see both. To force a re-run,
1171
- * use {@link retry} instead.
1172
- *
1173
- * Throws {@link NagiValidationError} if `stepId` is not a step in the
1174
- * run's flow. Throws {@link NagiRuntimeError} if the run is already
1175
- * terminal.
1176
- */
1177
547
  skip(runId: RunId, stepId: StepId, opts: OperatorSkipOpts): Promise<void>;
1178
- /**
1179
- * Re-run `stepId` and its descendants. Equivalent to
1180
- * `wf.replay(runId, { from: stepId })` for terminal-state steps, with
1181
- * audit fields stamped onto the resulting `step.reset` facts.
1182
- *
1183
- * For a step in `running` state, first appends
1184
- * `step.abort-requested` so the in-flight handler's `ctx.signal`
1185
- * aborts, waits for the attempt to land its `step.canceled` fact, then
1186
- * proceeds with the reset cascade. The whole call resolves once the
1187
- * step is ready to re-dispatch.
1188
- *
1189
- * Throws {@link NagiValidationError} if `stepId` is not a step in the
1190
- * run's flow. Throws {@link NagiRuntimeError} if the run is `canceled`
1191
- * (use a new run instead).
1192
- */
1193
548
  retry(runId: RunId, stepId: StepId, opts: OperatorAuditOpts): Promise<void>;
1194
- /**
1195
- * Cancel an entire run and all subflow descendants. Appends `flow.canceled`
1196
- * with `cause: "operator"` and the operator's audit fields. In-flight step
1197
- * handlers see their `ctx.signal` abort (via the dispatch-side cancel
1198
- * watcher) and reclassify as `step.canceled` per the boundary check.
1199
- *
1200
- * Idempotent on already-terminal runs (logged no-op).
1201
- */
1202
549
  abort(runId: RunId, opts: OperatorAuditOpts): Promise<void>;
1203
550
  }
1204
551
 
1205
- /**
1206
- * Construct a flow.
1207
- *
1208
- * 1. Run `build(b)` to collect the user's StepMap. Each call to `b.task` /
1209
- * `b.signal` / `b.match` produced a Step with `id: ""` and a captured def
1210
- * (which may reference upstream Step values from earlier in the closure).
1211
- * Match defs additionally hold their arms' nested StepMaps on `_nested`.
1212
- * 2. Walk the returned map *recursively*, descending into match arms. Each
1213
- * step gets an id derived from its position: top-level keys verbatim,
1214
- * nested arm steps namespaced as `<matchKey>.<armId>.<stepKey>`.
1215
- * 3. Rewrite every def's `needs` so each upstream Step value carries its
1216
- * assigned id. Nested-arm step defs additionally get a `parentMatch`
1217
- * annotation so the scheduler can gate them on arm selection.
1218
- * 4. Promote `MatchArmDef._nested` → `MatchArmDef.stepIds` (the namespaced
1219
- * IDs of the arm's nested steps), then drop `_nested`.
1220
- */
1221
- declare function flow<const Id extends string, InputSchema extends StandardSchemaV1, R, Output = unknown>(config: FlowConfig<Id, InputSchema, R, Output>): Flow<Id, InputSchema, AsStepMap<R>, Output>;
552
+ declare function flow<const Id extends string, InputSchema extends StandardSchemaV1, R extends StepMap, Output = unknown>(config: FlowConfig<Id, InputSchema, R, Output>): Flow<Id, InputSchema, R, Output>;
1222
553
 
1223
- /**
1224
- * Canonical retry shape. Defaults are materialized explicitly so equivalent
1225
- * retry configs hash identically regardless of source-side omission style.
1226
- * `retryOn` is dropped — it's a function, not serializable.
1227
- */
1228
554
  interface CanonicalRetryPolicy {
1229
555
  readonly maxAttempts: number;
1230
556
  readonly backoff: BackoffStrategy;
1231
557
  readonly initialDelayMs: Millis;
1232
558
  readonly maxDelayMs: Millis;
1233
559
  }
1234
- /**
1235
- * Canonical schema fingerprint. v0 hashes `validate.toString()` alongside
1236
- * runtime-stable `vendor` + `version` — best-effort, breaks under minification.
1237
- * Documented as a known limit in RFC 0001.
1238
- */
1239
560
  interface CanonicalSchema {
1240
561
  readonly vendor: string;
1241
562
  readonly version: number;
@@ -1245,83 +566,31 @@ interface CanonicalMatchArm {
1245
566
  readonly id: string;
1246
567
  readonly otherwise?: true;
1247
568
  readonly whenHash?: string;
1248
- /** Namespaced IDs of nested steps for this arm, sorted lexicographically. */
1249
569
  readonly stepIds: readonly StepId[];
1250
570
  }
1251
571
  interface CanonicalStep {
1252
572
  readonly id: StepId;
1253
573
  readonly kind: StepKind;
1254
- /** Upstream step ids the step depends on, sorted lexicographically. */
1255
574
  readonly needs: readonly StepId[];
1256
575
  readonly whenHash?: string;
1257
576
  readonly retry?: CanonicalRetryPolicy;
1258
577
  readonly timeoutMs?: Millis;
1259
578
  readonly signalSchema?: CanonicalSchema;
1260
- /**
1261
- * External signal names this step accepts, sorted lexicographically. Only
1262
- * present when the caller supplied `name` / `names` on `b.signal`; absent
1263
- * for the default "name == step id" case so pre-RFC-0004 flows hash
1264
- * byte-identically.
1265
- */
1266
579
  readonly signalNames?: readonly string[];
1267
- readonly matchMode?: "discriminator" | "guard";
1268
- readonly matchOnHash?: string;
1269
580
  readonly matchArms?: readonly CanonicalMatchArm[];
1270
- /**
1271
- * The referenced child flow's id. Topology changes in the child do NOT
1272
- * propagate into the parent's hash — child carries its own `flowHash` on
1273
- * its own `flow.started` fact. The parent's hash captures only the
1274
- * structural fact "this step starts a child of this flow id with this
1275
- * input mapping."
1276
- */
1277
581
  readonly childFlowId?: string;
1278
- /** Hash of the `input: ({ input, needs }) => ChildInput` callback source. */
1279
582
  readonly subflowInputHash?: string;
1280
583
  }
1281
584
  interface CanonicalDag {
1282
585
  readonly flowId: string;
1283
586
  readonly inputSchema: CanonicalSchema;
1284
- /** Steps sorted by `id` lexicographically — insertion order is ignored. */
1285
587
  readonly steps: readonly CanonicalStep[];
1286
588
  }
1287
- /**
1288
- * Build the canonical DAG for a flow.
1289
- *
1290
- * Stable across cosmetic source changes (step-key reorder, needs-key reorder)
1291
- * and different across topology changes (added/removed steps, edge changes,
1292
- * `when` flips, retry edits, timeout edits).
1293
- *
1294
- * Handler `run` bodies are intentionally NOT part of the hash — see RFC 0001
1295
- * "Topology vs handler code." Use `nagi({ codeVersion })` (typically a git
1296
- * SHA) to capture handler-code drift orthogonally.
1297
- *
1298
- * Async because predicate/schema source bodies are sha256'd via
1299
- * `crypto.subtle` so the stored `dag` JSON stays compact.
1300
- */
1301
589
  declare function canonicalize(flow: Flow): Promise<CanonicalDag>;
1302
- /**
1303
- * Compute the sha256 hex digest of a canonical DAG. Uses Web Crypto
1304
- * (`crypto.subtle.digest`) which is available in Node ≥ 19, modern browsers,
1305
- * Cloudflare Workers, Deno, and Bun.
1306
- *
1307
- * The DAG is serialized via {@link stableStringify} so object-key order is
1308
- * deterministic. Two equivalent DAGs produce byte-identical input bytes.
1309
- */
1310
590
  declare function sha256Canonical(dag: CanonicalDag): Promise<string>;
1311
- /**
1312
- * Compute a structural fingerprint over a set of registered flows. Used as
1313
- * the default value of `nagi({ codeVersion })` when the caller omits it.
1314
- *
1315
- * Per-flow projection reuses {@link canonicalize} unchanged — so this hash
1316
- * and each flow's snapshot `flowHash` share one canonical definition and
1317
- * cannot drift apart. Equivalent flow sets produce byte-identical hashes;
1318
- * adding/removing a flow, renaming a flow id, or any structural step change
1319
- * moves the result. `run`-body edits do not.
1320
- */
1321
591
  declare function fingerprintFlows(flows: ReadonlyArray<Flow>): Promise<string>;
1322
592
 
1323
- /** Fields on a step whose hash-relevant value can change between snapshots. */
1324
- type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchMode" | "matchOn" | "matchArms";
593
+ type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchArms";
1325
594
  interface SnapshotChangedEdge {
1326
595
  readonly from: StepId;
1327
596
  readonly to: StepId;
@@ -1332,22 +601,6 @@ interface SnapshotChangedField_ {
1332
601
  readonly stepId: StepId;
1333
602
  readonly field: SnapshotChangedField;
1334
603
  }
1335
- /**
1336
- * Structural delta between two snapshots — added/removed steps, added/removed
1337
- * edges, per-field topology changes on shared steps.
1338
- *
1339
- * Pure function over canonical DAGs. The output mirrors the RFC 0001 shape:
1340
- *
1341
- * {
1342
- * addedSteps,
1343
- * removedSteps,
1344
- * changedEdges, // append-or-remove edges between shared steps
1345
- * changedPredicates // when / retry / timeoutMs / schema / match changes
1346
- * }
1347
- *
1348
- * "Changed" means the canonical hash-relevant value differs. For predicates
1349
- * this is best-effort under the same source-hash limit as canonicalize.
1350
- */
1351
604
  interface SnapshotDiff {
1352
605
  readonly addedSteps: readonly StepId[];
1353
606
  readonly removedSteps: readonly StepId[];
@@ -1367,27 +620,9 @@ declare class InMemoryStore implements Store {
1367
620
  private readonly snapshots;
1368
621
  private readonly refs;
1369
622
  private readonly globalFacts;
1370
- /**
1371
- * The runId currently holding the active slot for `flowId::concurrencyKey`.
1372
- * Updated on `tryStartRun` (set when concurrency is supplied) and on
1373
- * terminal facts (cleared via {@link keyByActiveRun}).
1374
- */
1375
623
  private readonly activeByKey;
1376
- /** Reverse lookup so terminal facts can free the slot in O(1). */
1377
624
  private readonly keyByActiveRun;
1378
- /**
1379
- * Index: parentRunId → set of child run ids spawned by `b.subflow()`.
1380
- * Populated in `tryStartRun` when `fact.parentRunId` is set. Used by
1381
- * `listChildren()` to power transitive cancel cascade in O(children).
1382
- */
1383
625
  private readonly childrenByParent;
1384
- /**
1385
- * Pruned-but-kept summaries. Populated by `pruneFacts` when `keepSummary`
1386
- * is true so that `queryRuns` still surfaces runs whose facts were dropped.
1387
- * Mirrors the postgres adapter's retained `workflow_run` row after a prune.
1388
- * Also blocks `tryStartRun` from reusing a pruned runId — matching the
1389
- * postgres `INSERT ... ON CONFLICT DO NOTHING` semantic on `run_id`.
1390
- */
1391
626
  private readonly summaries;
1392
627
  private readonly leaseMs;
1393
628
  constructor(opts?: InMemoryStoreOpts);
@@ -1399,7 +634,7 @@ declare class InMemoryStore implements Store {
1399
634
  readonly started: boolean;
1400
635
  readonly canceled: ReadonlyArray<{
1401
636
  readonly runId: RunId;
1402
- readonly fact: FlowCanceledFact;
637
+ readonly fact: FlowCanceledByConcurrencyFact;
1403
638
  }>;
1404
639
  }>;
1405
640
  listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
@@ -1426,16 +661,10 @@ declare class InMemoryStore implements Store {
1426
661
  readonly dag: Json;
1427
662
  } | null>;
1428
663
  appendGlobalFact(fact: GlobalFact): Promise<void>;
1429
- /** Test-only: peek at the in-memory global fact log. */
1430
664
  readGlobalFacts(): ReadonlyArray<GlobalFact>;
1431
665
  queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
1432
666
  pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
1433
667
  }
1434
- /**
1435
- * Project an append-only fact stream into a `RunState`. Public so adapters
1436
- * (e.g. `@nagi-js/postgres`) can re-use the same projection rules — keeping
1437
- * one canonical definition of "what does the fact log mean".
1438
- */
1439
668
  declare function projectRunState(runId: RunId, facts: readonly Fact[]): RunState;
1440
669
  interface InMemoryQueueOpts {
1441
670
  readonly leaseMs?: Millis;
@@ -1454,13 +683,6 @@ declare class InMemoryQueue implements Queue {
1454
683
  extend(receipt: string, leaseMs: Millis): Promise<void>;
1455
684
  }
1456
685
  interface InMemoryClockOpts {
1457
- /**
1458
- * Wires `schedule()` wake-ups to a trigger. When the persistent timer fires,
1459
- * the clock calls `trigger.fire(runId)` so scheduler subscribers can resume
1460
- * the run. Without this, `schedule()` is a no-op on the worker loop and any
1461
- * step that depends on it (time-based gates, long-delayed retries) will
1462
- * stall in tests.
1463
- */
1464
686
  readonly trigger?: InMemoryTrigger;
1465
687
  }
1466
688
  declare class InMemoryClock implements Clock {
@@ -1470,16 +692,11 @@ declare class InMemoryClock implements Clock {
1470
692
  now(): Date;
1471
693
  sleep(ms: Millis, signal?: AbortSignal): Promise<void>;
1472
694
  schedule(at: Date, runId: RunId, stepId: StepId): Promise<void>;
1473
- /** Clear any pending scheduled timers. Call from test teardown. */
1474
695
  dispose(): void;
1475
696
  }
1476
697
  declare class InMemoryTrigger implements Trigger {
1477
698
  private handlers;
1478
699
  subscribe(handler: (runId: RunId) => void): () => void;
1479
- /**
1480
- * Test-only: synchronously dispatch a wake-up to all subscribers.
1481
- * Real triggers fire from a Store change (NOTIFY/LISTEN, polling, etc.).
1482
- */
1483
700
  fire(runId: RunId): void;
1484
701
  }
1485
702
 
@@ -1492,107 +709,35 @@ interface NagiConfig {
1492
709
  readonly hooks?: FlowHooks;
1493
710
  readonly logger?: Logger;
1494
711
  readonly defaultRetry?: RetryPolicy;
1495
- /**
1496
- * Process-wide identifier persisted on `workflow_run.code_version` and on
1497
- * every `flow.started` fact for runs started by this process.
1498
- *
1499
- * When omitted (default), nagi computes a structural fingerprint over the
1500
- * registered flows via {@link fingerprintFlows} and uses that — so the
1501
- * audit field is meaningful by default and shifts only when flow topology
1502
- * changes, not on every deploy. Supply an explicit string to override
1503
- * (e.g. for a forced cutover: `"cutover-2026-05-15"`).
1504
- *
1505
- * Drift detection at replay uses each flow's per-flow `flowHash`, not this
1506
- * value. See RFC 0001 "Topology vs handler code" and RFC 0003 "Auto-compute
1507
- * codeVersion."
1508
- */
1509
712
  readonly codeVersion?: string;
1510
713
  }
1511
714
  interface StartOpts {
1512
- /**
1513
- * Caller-supplied runId for idempotent kickoff. If provided and a run with
1514
- * this ID already exists, `start()` is a no-op and returns the same ID
1515
- * without re-appending `flow.started`, re-dispatching, or re-validating the
1516
- * input. Two concurrent `start()` calls with the same `runId` produce
1517
- * exactly one run (enforced at the Store layer).
1518
- *
1519
- * If omitted, the runtime mints a fresh ID via `crypto.randomUUID()`.
1520
- *
1521
- * Typical usage: a content hash of the input, so callers de-duplicate
1522
- * kickoffs without coordinating.
1523
- */
1524
715
  readonly runId?: RunId;
1525
716
  }
1526
717
  interface CancelOpts {
1527
- /**
1528
- * Caller-supplied reason recorded on the `flow.canceled` fact. Surfaces in
1529
- * the cascaded `step.failed` error message for any parent waiting on this
1530
- * run via `b.subflow()`. Default: "explicit wf.cancel()".
1531
- */
1532
718
  readonly reason?: string;
1533
719
  }
1534
720
  interface Wf {
1535
- /** Begin a new run. Returns the runId. */
1536
721
  start<F extends Flow>(flow: F, input: FlowInput<F>, opts?: StartOpts): Promise<RunId>;
1537
- /** Resolve a `b.signal()` step waiting on external input. */
1538
- signal(runId: RunId, stepName: string, payload: unknown): Promise<void>;
1539
722
  /**
1540
- * Cancel a pending or running run. Writes `flow.canceled` to the run's
1541
- * fact log and cascades transitively to every child run spawned by
1542
- * `b.subflow()`. Idempotent: cancelling a run that's already terminal
1543
- * (`completed` / `failed` / `canceled`) is a logged no-op.
723
+ * Start a flow by id with a runtime-typed input. Intended for callers
724
+ * holding a serialized payload (transactional-outbox reconcilers, queue
725
+ * consumers replaying DLQs, admin CLIs replaying a runId): the input
726
+ * is validated against the registered flow's schema before the run is
727
+ * created, mirroring `start`'s runtime contract without requiring a
728
+ * compile-time-typed input.
1544
729
  *
1545
- * For canceled child runs, the parent's subflow step (if still running)
1546
- * transitions to `failed` with a structured cancel error — the parent
1547
- * doesn't hang waiting for a child that will never finish.
730
+ * Throws `NagiRuntimeError` when `flowId` is not registered with
731
+ * `nagi()`, and `NagiValidationError` when the input fails the flow's
732
+ * schema or when `opts.runId` is invalid.
1548
733
  */
734
+ startById(flowId: string, input: unknown, opts?: StartOpts): Promise<RunId>;
735
+ signal(runId: RunId, stepName: string, payload: unknown): Promise<void>;
1549
736
  cancel(runId: RunId, opts?: CancelOpts): Promise<void>;
1550
- /** Construct a worker; call `run` / `runOnce` / `runUntilEmpty` on it. */
1551
737
  worker(config?: WorkerConfig): Worker;
1552
- /**
1553
- * Re-dispatch from the first incomplete step. `mode: "continue"` runs side
1554
- * effects (idempotency protects); `mode: "inspect"` is a no-op probe.
1555
- */
1556
738
  replay(runId: RunId, opts?: ReplayOpts): Promise<void>;
1557
- /**
1558
- * Discover runs by flow / status / input. Read-only — does not create or
1559
- * mutate runs. Use this to power read-side surfaces like "current run for
1560
- * video X" without coupling consumers to nagi's storage schema.
1561
- *
1562
- * Filtering on `input` is JSONB containment: the stored input is a
1563
- * superset of the filter object (recursive on nested objects).
1564
- *
1565
- * Pagination is keyset on `(startedAt, runId)` DESC. Pass the returned
1566
- * `cursor` to the next call. `latest: true` returns at most one run and
1567
- * forbids `limit` / `cursor` at the type level.
1568
- */
1569
739
  queryRuns(opts?: QueryRunsOpts): Promise<QueryRunsResult>;
1570
- /**
1571
- * Operator-facing API for unsticking runs: `skip`, `retry`, `abort`. Each
1572
- * action appends an audit-bearing fact to the run's fact log so the
1573
- * intervention shows up in the read-side without read-modify-write
1574
- * against materialized tables. See {@link Operator}.
1575
- *
1576
- * Authorization is the caller's responsibility — typically a thin
1577
- * HTTP/CLI wrapper gates who is allowed to call these.
1578
- */
1579
740
  operator(): Operator;
1580
- /**
1581
- * Retention sweep over terminal runs. Deletes facts (and per-step rows,
1582
- * leases, timers, dedupes) for runs whose `completedAt < olderThan` and
1583
- * whose status is in `statuses` (default `["completed"]`). `pending` /
1584
- * `running` runs are excluded at compile time via {@link PrunableStatus}
1585
- * and re-validated at runtime.
1586
- *
1587
- * `keepSummary: true` (default) retains a summary row so `queryRuns` still
1588
- * lists the pruned run; the postgres adapter keeps the `workflow_run` row
1589
- * and the in-memory adapter keeps a shadow {@link RunSummary}. After a
1590
- * prune, `loadRunState` and `replay` for that run return an empty state —
1591
- * documented trade-off: you traded fact-fidelity for storage.
1592
- *
1593
- * Idempotent and safe under concurrent callers (postgres uses
1594
- * `FOR UPDATE SKIP LOCKED` on the victim set).
1595
- */
1596
741
  pruneFacts(opts: PruneOpts): Promise<PruneResult>;
1597
742
  }
1598
743
  declare class NagiValidationError extends Error {
@@ -1602,13 +747,6 @@ declare class NagiValidationError extends Error {
1602
747
  declare class NagiRuntimeError extends Error {
1603
748
  constructor(message: string);
1604
749
  }
1605
- /**
1606
- * Carried by `onFlowError` (both flow-local and cross-cutting) when a run is
1607
- * canceled because a newer `wf.start()` for the same concurrency group
1608
- * superseded it. The serialized form preserves `name` and a structured
1609
- * `cause` so observers can discriminate via `error.name === "NagiCanceledError"`
1610
- * and read `error.cause.canceledByRunId` / `error.cause.concurrencyKey`.
1611
- */
1612
750
  declare class NagiCanceledError extends Error {
1613
751
  readonly runId: RunId;
1614
752
  readonly canceledByRunId: RunId;
@@ -1619,12 +757,6 @@ declare class NagiCanceledError extends Error {
1619
757
  readonly concurrencyKey: string;
1620
758
  });
1621
759
  }
1622
- /**
1623
- * Thrown by `wf.replay(runId)` when the live flow's canonical hash differs
1624
- * from the snapshot the run was pinned to. The default replay behavior is
1625
- * fail-loud — pass `replayOpts.allowDrift = true` to proceed using a
1626
- * synthesized flow (topology from snapshot, handlers/predicates from live).
1627
- */
1628
760
  declare class NagiSnapshotDriftError extends Error {
1629
761
  readonly runId: RunId;
1630
762
  readonly expected: string;
@@ -1637,4 +769,4 @@ declare class NagiSnapshotDriftError extends Error {
1637
769
  }
1638
770
  declare function nagi(config: NagiConfig): Promise<Wf>;
1639
771
 
1640
- export { type AsStepMap, type AttemptNumber, type BackoffStrategy, type BuildResult, type Builder, type BuilderAccumulator, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type ConcurrencyMode, type Fact, type FactKind, type Flow, type FlowCanceledFact, type FlowCompleteEvent, type FlowCompletedFact, type FlowConcurrency, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, type FlowInput, type FlowOutput, type FlowRefUpdatedFact, type FlowStartEvent, type FlowStartedFact, type GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, type InferSchemaInput, type InferSchemaOutput, type Json, type Logger, type MatchArm, type MatchArmGuard, type MatchArmOtherwise, type MatchArmOutput, type MatchArmSelectedFact, type MatchArmShape, type MatchDiscriminatorConfig, type MatchDiscriminatorOutput, type MatchGuardConfig, type Millis, NagiCanceledError, type NagiConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Operator, type OperatorAuditOpts, type OperatorSkipOpts, type PrunableStatus, type PruneOpts, type PruneResult, type QueryRunsOpts, type QueryRunsResult, type QueryRunsWhere, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type RetryPolicy, type RunId, type RunState, type RunStatus, type RunSummary, type SerializedError, type SignalConfig, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepAbortRequestedFact, type StepCanceledFact, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepEntryConfig, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepResetFact, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, type SubflowConfig, type SubflowStepOutput, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };
772
+ export { type AttemptNumber, type BackoffStrategy, type Builder, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type ConcurrencyMode, type Fact, type FactKind, type Flow, type FlowCanceledByConcurrencyFact, type FlowCanceledByOperatorFact, type FlowCanceledExplicitlyFact, type FlowCanceledFact, type FlowCompleteEvent, type FlowCompletedFact, type FlowConcurrency, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, type FlowInput, type FlowOutput, type FlowRefUpdatedFact, type FlowStartEvent, type FlowStartedFact, type GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, type InferSchemaInput, type InferSchemaOutput, type Json, type Logger, type MatchArm, type MatchArmGuard, type MatchArmOtherwise, type MatchArmOutput, type MatchArmSelectedFact, type MatchArmShape, type MatchGuardConfig, type Millis, NagiCanceledError, type NagiConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Operator, type OperatorAuditOpts, type OperatorSkipOpts, type PrunableStatus, type PruneOpts, type PruneResult, type QueryRunsOpts, type QueryRunsResult, type QueryRunsWhere, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type RetryPolicy, type RunId, type RunState, type RunStatus, type RunSummary, type SerializedError, type SignalConfig, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepAbortRequestedFact, type StepCanceledFact, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepResetFact, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, type SubflowConfig, type SubflowStepOutput, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };