@nagi-js/core 0.1.1-rc.0 → 0.1.1-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -113,6 +113,20 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
113
113
  readonly needs: NoInfer<NeedsOutputs<N>>;
114
114
  readonly ctx: StepCtx<NoInfer<Input>>;
115
115
  }) => 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
+ readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
125
+ readonly onComplete?: (event: StepCompleteEvent & {
126
+ readonly output: NoInfer<Output>;
127
+ }) => void | Promise<void>;
128
+ readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
129
+ readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
116
130
  }
117
131
  interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
118
132
  readonly schema: Schema;
@@ -202,6 +216,13 @@ interface StepEntryConfig<Input, A extends Record<string, unknown>, Needs extend
202
216
  };
203
217
  readonly ctx: StepCtx<NoInfer<Input>>;
204
218
  }) => Promise<Output>;
219
+ /** See {@link TaskConfig} for hook semantics. */
220
+ readonly onStart?: (event: StepStartEvent) => void | Promise<void>;
221
+ readonly onComplete?: (event: StepCompleteEvent & {
222
+ readonly output: NoInfer<Output>;
223
+ }) => void | Promise<void>;
224
+ readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
225
+ readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
205
226
  }
206
227
  /**
207
228
  * `b` inside `flow({ build: (b) => ... })`.
@@ -279,6 +300,31 @@ type BuilderAccumulator<M extends StepMap> = {
279
300
  type AsStepMap<R> = R extends Builder<unknown, infer A> ? {
280
301
  readonly [K in keyof A]: Step<A[K]>;
281
302
  } : R extends StepMap ? R : never;
303
+ /**
304
+ * Modes for `FlowConcurrency`. v1 implements only `cancel-in-progress`; the
305
+ * union is a single literal so adding `queue` / `reject` later is a
306
+ * non-breaking widening rather than a new discriminator.
307
+ */
308
+ type ConcurrencyMode = "cancel-in-progress";
309
+ /**
310
+ * Per-flow concurrency control. When set, `wf.start()` derives a group key
311
+ * from the validated input and applies the configured `mode` against any
312
+ * prior run sharing the same `(flowId, key)` pair.
313
+ *
314
+ * `cancel-in-progress`: any active prior run with the same key transitions
315
+ * to the `canceled` terminal state before the new run is inserted. In-flight
316
+ * steps on the canceled run run to completion (their facts persist), but the
317
+ * dispatcher stops scheduling further steps for it.
318
+ */
319
+ interface FlowConcurrency<Input = Json> {
320
+ /**
321
+ * Derive the concurrency group key from the validated flow input.
322
+ * Synchronous + pure. Returning a non-string or an empty string throws
323
+ * `NagiValidationError` at `wf.start()` time.
324
+ */
325
+ readonly keyFn: (input: Input) => string;
326
+ readonly mode: ConcurrencyMode;
327
+ }
282
328
  interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R, Output = unknown> {
283
329
  /** Stable persistence handle. TanStack-key shaped (kebab or snake). */
284
330
  readonly id: Id;
@@ -296,12 +342,53 @@ interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R,
296
342
  * the type claims otherwise (consistent with the "skip is transitive" lock).
297
343
  */
298
344
  output?(steps: NeedsOutputs<AsStepMap<R>>): Output;
345
+ /**
346
+ * Concurrency group config. See {@link FlowConcurrency}. `keyFn` is typed
347
+ * against the schema's parsed output — what `b.task`'s `run({ input })`
348
+ * receives — so refactors to the input schema break the key derivation
349
+ * at compile time.
350
+ */
351
+ readonly concurrency?: FlowConcurrency<InferSchemaOutput<InputSchema>>;
352
+ /**
353
+ * Flow-level lifecycle hooks. Like step-local hooks (see {@link TaskConfig}),
354
+ * these fire *before* the cross-cutting `FlowHooks` callbacks, and a thrown
355
+ * hook is swallowed + logged rather than failing the run.
356
+ *
357
+ * `onComplete`'s event is typed against this flow's `Output` (whatever the
358
+ * `output()` resolver returns).
359
+ *
360
+ * `onError` also fires when a run is canceled by a concurrency-group
361
+ * supersede; the event's `error.name` is `"NagiCanceledError"` and
362
+ * `error.cause` carries `{ canceledByRunId, concurrencyKey }`.
363
+ */
364
+ readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
365
+ readonly onComplete?: (event: FlowCompleteEvent & {
366
+ readonly output: NoInfer<Output>;
367
+ }) => void | Promise<void>;
368
+ readonly onError?: (event: FlowErrorEvent) => void | Promise<void>;
299
369
  }
300
370
  interface Flow<Id extends string = string, InputSchema extends StandardSchemaV1 = StandardSchemaV1, M extends StepMap = StepMap, Output = unknown> {
301
371
  readonly id: Id;
302
372
  readonly input: InputSchema;
303
373
  readonly steps: M;
304
374
  output?(steps: NeedsOutputs<M>): Output;
375
+ /**
376
+ * Forwarded from {@link FlowConfig}; surfaced for the dispatcher.
377
+ *
378
+ * Note these use the plain (non-Output-augmented) event types — the typed
379
+ * narrowing lives on {@link FlowConfig}'s callbacks at build time, while
380
+ * the runtime form is variance-friendly so a concrete `Flow<...{x: number}>`
381
+ * stays assignable to `Flow<...unknown>` (the dispatcher's view).
382
+ */
383
+ readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
384
+ readonly onComplete?: (event: FlowCompleteEvent) => void | Promise<void>;
385
+ readonly onError?: (event: FlowErrorEvent) => void | Promise<void>;
386
+ /**
387
+ * Forwarded from {@link FlowConfig.concurrency}. The runtime form widens
388
+ * `Input` to `Json` so a concrete `Flow<...{x: number}>` is assignable to
389
+ * `Flow<...unknown>` (the dispatcher's view).
390
+ */
391
+ readonly concurrency?: FlowConcurrency<Json>;
305
392
  }
306
393
  type FlowInput<F> = F extends Flow<string, infer S, StepMap, unknown> ? InferSchemaOutput<S> : never;
307
394
  type FlowOutput<F> = F extends Flow<string, StandardSchemaV1, StepMap, infer O> ? O : never;
@@ -411,19 +498,37 @@ interface Store {
411
498
  /**
412
499
  * Atomically begin a run. Inserts the `flow.started` fact and any
413
500
  * materialized run row keyed by `runId` IFF no run with this `runId` already
414
- * exists. Returns `{ started: true }` if this call created the run,
415
- * `{ started: false }` if the run already exists.
501
+ * exists. Returns `{ started: true, canceled: [...] }` if this call created
502
+ * the run, `{ started: false, canceled: [] }` if the run already exists.
416
503
  *
417
504
  * Two concurrent `tryStartRun(runId, ...)` calls with the same `runId` must
418
505
  * result in exactly one `flow.started` fact. Adapters enforce this at the
419
506
  * durability layer (e.g. Postgres `INSERT ... ON CONFLICT DO NOTHING` keyed
420
507
  * by `run_id`), NOT via app-level check-then-insert.
421
508
  *
509
+ * When `concurrency` is supplied, the adapter ALSO atomically cancels any
510
+ * prior runs whose `(flowId, concurrency.key)` matches and whose status is
511
+ * still `pending` / `running`. Each canceled run gets a `flow.canceled`
512
+ * fact appended to its log and its materialized status updated to
513
+ * `canceled`. The returned `canceled` array carries the fact for each
514
+ * canceled run so the runtime can fire `onFlowError` post-commit.
515
+ *
516
+ * Adapters MUST serialize concurrent starts for the same
517
+ * `(flowId, concurrency.key)` (e.g. Postgres advisory-lock keyed on the
518
+ * pair) so the partial unique index on active runs is never violated.
519
+ *
422
520
  * The runtime calls this exactly once at `wf.start()`. Subsequent facts go
423
521
  * through `appendFact` as usual.
424
522
  */
425
- tryStartRun(runId: RunId, fact: FlowStartedFact): Promise<{
523
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
524
+ readonly key: string;
525
+ readonly mode: ConcurrencyMode;
526
+ }): Promise<{
426
527
  readonly started: boolean;
528
+ readonly canceled: ReadonlyArray<{
529
+ readonly runId: RunId;
530
+ readonly fact: FlowCanceledFact;
531
+ }>;
427
532
  }>;
428
533
  /**
429
534
  * Returns null if the step is already claimed under a live lease. Lease
@@ -549,7 +654,7 @@ interface Clock {
549
654
  interface Trigger {
550
655
  subscribe(handler: (runId: RunId) => void): () => void;
551
656
  }
552
- type FactKind = "flow.started" | "flow.completed" | "flow.failed" | "step.started" | "step.completed" | "step.failed" | "step.retried" | "step.skipped" | "signal.sent" | "signal.received" | "once.recorded" | "match.arm-selected";
657
+ type FactKind = "flow.started" | "flow.completed" | "flow.failed" | "flow.canceled" | "step.started" | "step.completed" | "step.failed" | "step.retried" | "step.skipped" | "signal.sent" | "signal.received" | "once.recorded" | "match.arm-selected";
553
658
  interface FactBase {
554
659
  readonly runId: RunId;
555
660
  readonly at: Date;
@@ -599,6 +704,19 @@ interface FlowFailedFact extends FactBase {
599
704
  readonly kind: "flow.failed";
600
705
  readonly error: SerializedError;
601
706
  }
707
+ /**
708
+ * Recorded on a prior run when a new `wf.start()` with the same concurrency
709
+ * group supersedes it. The fact lives in the canceled run's fact log (not
710
+ * the new run's) — observers reading that run's history see exactly when and
711
+ * why it was canceled.
712
+ */
713
+ interface FlowCanceledFact extends FactBase {
714
+ readonly kind: "flow.canceled";
715
+ /** The new run that took over this run's concurrency slot. */
716
+ readonly canceledByRunId: RunId;
717
+ /** The shared concurrency key between this run and `canceledByRunId`. */
718
+ readonly concurrencyKey: string;
719
+ }
602
720
  interface StepStartedFact extends FactBase {
603
721
  readonly kind: "step.started";
604
722
  readonly stepId: StepId;
@@ -648,8 +766,8 @@ interface MatchArmSelectedFact extends FactBase {
648
766
  readonly stepId: StepId;
649
767
  readonly arm: string;
650
768
  }
651
- type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
652
- type RunStatus = "pending" | "running" | "completed" | "failed";
769
+ type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
770
+ type RunStatus = "pending" | "running" | "completed" | "failed" | "canceled";
653
771
  type StepStatus = "pending" | "running" | "completed" | "failed" | "skipped";
654
772
  interface StepState {
655
773
  readonly stepId: StepId;
@@ -681,6 +799,15 @@ interface ReplayOpts {
681
799
  * When false (default), drift throws `NagiSnapshotDriftError`.
682
800
  */
683
801
  readonly allowDrift?: boolean;
802
+ /**
803
+ * Whether step / flow lifecycle hooks (both the step-local ones on
804
+ * `TaskConfig` / `FlowConfig` and the cross-cutting `FlowHooks`) fire during
805
+ * replay. Defaults to `true` — replay re-executes steps via the idempotent
806
+ * dispatcher and emits the same observable lifecycle. Set to `false` for
807
+ * backfills or inspection-style replays where re-emitting webhooks would
808
+ * dual-publish.
809
+ */
810
+ readonly fireHooks?: boolean;
684
811
  }
685
812
 
686
813
  /**
@@ -772,6 +899,17 @@ declare function canonicalize(flow: Flow): Promise<CanonicalDag>;
772
899
  * deterministic. Two equivalent DAGs produce byte-identical input bytes.
773
900
  */
774
901
  declare function sha256Canonical(dag: CanonicalDag): Promise<string>;
902
+ /**
903
+ * Compute a structural fingerprint over a set of registered flows. Used as
904
+ * the default value of `nagi({ codeVersion })` when the caller omits it.
905
+ *
906
+ * Per-flow projection reuses {@link canonicalize} unchanged — so this hash
907
+ * and each flow's snapshot `flowHash` share one canonical definition and
908
+ * cannot drift apart. Equivalent flow sets produce byte-identical hashes;
909
+ * adding/removing a flow, renaming a flow id, or any structural step change
910
+ * moves the result. `run`-body edits do not.
911
+ */
912
+ declare function fingerprintFlows(flows: ReadonlyArray<Flow>): Promise<string>;
775
913
 
776
914
  /** Fields on a step whose hash-relevant value can change between snapshots. */
777
915
  type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchMode" | "matchOn" | "matchArms";
@@ -820,11 +958,26 @@ declare class InMemoryStore implements Store {
820
958
  private readonly snapshots;
821
959
  private readonly refs;
822
960
  private readonly globalFacts;
961
+ /**
962
+ * The runId currently holding the active slot for `flowId::concurrencyKey`.
963
+ * Updated on `tryStartRun` (set when concurrency is supplied) and on
964
+ * terminal facts (cleared via {@link keyByActiveRun}).
965
+ */
966
+ private readonly activeByKey;
967
+ /** Reverse lookup so terminal facts can free the slot in O(1). */
968
+ private readonly keyByActiveRun;
823
969
  private readonly leaseMs;
824
970
  constructor(opts?: InMemoryStoreOpts);
825
971
  appendFact(runId: RunId, fact: Fact): Promise<void>;
826
- tryStartRun(runId: RunId, fact: FlowStartedFact): Promise<{
972
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
973
+ readonly key: string;
974
+ readonly mode: ConcurrencyMode;
975
+ }): Promise<{
827
976
  readonly started: boolean;
977
+ readonly canceled: ReadonlyArray<{
978
+ readonly runId: RunId;
979
+ readonly fact: FlowCanceledFact;
980
+ }>;
828
981
  }>;
829
982
  loadRunState(runId: RunId): Promise<RunState>;
830
983
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
@@ -914,11 +1067,18 @@ interface NagiConfig {
914
1067
  readonly logger?: Logger;
915
1068
  readonly defaultRetry?: RetryPolicy;
916
1069
  /**
917
- * Handler-code identifier — typically a git SHA from `process.env.GIT_SHA`
918
- * or your build's bundle hash. Persisted on `workflow_run.code_version` and
919
- * on every `flow.started` fact for runs started by this process. Captures
920
- * handler-body drift orthogonally to the topology hash. See RFC 0001
921
- * "Topology vs handler code."
1070
+ * Process-wide identifier persisted on `workflow_run.code_version` and on
1071
+ * every `flow.started` fact for runs started by this process.
1072
+ *
1073
+ * When omitted (default), nagi computes a structural fingerprint over the
1074
+ * registered flows via {@link fingerprintFlows} and uses that — so the
1075
+ * audit field is meaningful by default and shifts only when flow topology
1076
+ * changes, not on every deploy. Supply an explicit string to override
1077
+ * (e.g. for a forced cutover: `"cutover-2026-05-15"`).
1078
+ *
1079
+ * Drift detection at replay uses each flow's per-flow `flowHash`, not this
1080
+ * value. See RFC 0001 "Topology vs handler code" and RFC 0003 "Auto-compute
1081
+ * codeVersion."
922
1082
  */
923
1083
  readonly codeVersion?: string;
924
1084
  }
@@ -957,6 +1117,23 @@ declare class NagiValidationError extends Error {
957
1117
  declare class NagiRuntimeError extends Error {
958
1118
  constructor(message: string);
959
1119
  }
1120
+ /**
1121
+ * Carried by `onFlowError` (both flow-local and cross-cutting) when a run is
1122
+ * canceled because a newer `wf.start()` for the same concurrency group
1123
+ * superseded it. The serialized form preserves `name` and a structured
1124
+ * `cause` so observers can discriminate via `error.name === "NagiCanceledError"`
1125
+ * and read `error.cause.canceledByRunId` / `error.cause.concurrencyKey`.
1126
+ */
1127
+ declare class NagiCanceledError extends Error {
1128
+ readonly runId: RunId;
1129
+ readonly canceledByRunId: RunId;
1130
+ readonly concurrencyKey: string;
1131
+ constructor(args: {
1132
+ readonly runId: RunId;
1133
+ readonly canceledByRunId: RunId;
1134
+ readonly concurrencyKey: string;
1135
+ });
1136
+ }
960
1137
  /**
961
1138
  * Thrown by `wf.replay(runId)` when the live flow's canonical hash differs
962
1139
  * from the snapshot the run was pinned to. The default replay behavior is
@@ -975,4 +1152,4 @@ declare class NagiSnapshotDriftError extends Error {
975
1152
  }
976
1153
  declare function nagi(config: NagiConfig): Promise<Wf>;
977
1154
 
978
- 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 Fact, type FactKind, type Flow, type FlowCompleteEvent, type FlowCompletedFact, 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, type NagiConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type RetryPolicy, type RunId, type RunState, type RunStatus, type SerializedError, type SignalConfig, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepEntryConfig, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, canonicalize, diffSnapshots, flow, nagi, projectRunState, sha256Canonical };
1155
+ 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 Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type RetryPolicy, type RunId, type RunState, type RunStatus, type SerializedError, type SignalConfig, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepEntryConfig, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, 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 };