@nagi-js/core 0.1.1-rc.1 → 0.1.1-rc.5

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
@@ -128,8 +128,15 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
128
128
  readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
129
129
  readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
130
130
  }
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
+ */
131
137
  interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
132
138
  readonly schema: Schema;
139
+ readonly names?: readonly [string, ...string[]];
133
140
  }
134
141
  /**
135
142
  * Discriminator mode — exhaustive at compile time. `cases` must cover every
@@ -300,6 +307,31 @@ type BuilderAccumulator<M extends StepMap> = {
300
307
  type AsStepMap<R> = R extends Builder<unknown, infer A> ? {
301
308
  readonly [K in keyof A]: Step<A[K]>;
302
309
  } : R extends StepMap ? R : never;
310
+ /**
311
+ * Modes for `FlowConcurrency`. v1 implements only `cancel-in-progress`; the
312
+ * union is a single literal so adding `queue` / `reject` later is a
313
+ * non-breaking widening rather than a new discriminator.
314
+ */
315
+ type ConcurrencyMode = "cancel-in-progress";
316
+ /**
317
+ * Per-flow concurrency control. When set, `wf.start()` derives a group key
318
+ * from the validated input and applies the configured `mode` against any
319
+ * prior run sharing the same `(flowId, key)` pair.
320
+ *
321
+ * `cancel-in-progress`: any active prior run with the same key transitions
322
+ * to the `canceled` terminal state before the new run is inserted. In-flight
323
+ * steps on the canceled run run to completion (their facts persist), but the
324
+ * dispatcher stops scheduling further steps for it.
325
+ */
326
+ interface FlowConcurrency<Input = Json> {
327
+ /**
328
+ * Derive the concurrency group key from the validated flow input.
329
+ * Synchronous + pure. Returning a non-string or an empty string throws
330
+ * `NagiValidationError` at `wf.start()` time.
331
+ */
332
+ readonly keyFn: (input: Input) => string;
333
+ readonly mode: ConcurrencyMode;
334
+ }
303
335
  interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R, Output = unknown> {
304
336
  /** Stable persistence handle. TanStack-key shaped (kebab or snake). */
305
337
  readonly id: Id;
@@ -317,6 +349,13 @@ interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R,
317
349
  * the type claims otherwise (consistent with the "skip is transitive" lock).
318
350
  */
319
351
  output?(steps: NeedsOutputs<AsStepMap<R>>): Output;
352
+ /**
353
+ * Concurrency group config. See {@link FlowConcurrency}. `keyFn` is typed
354
+ * against the schema's parsed output — what `b.task`'s `run({ input })`
355
+ * receives — so refactors to the input schema break the key derivation
356
+ * at compile time.
357
+ */
358
+ readonly concurrency?: FlowConcurrency<InferSchemaOutput<InputSchema>>;
320
359
  /**
321
360
  * Flow-level lifecycle hooks. Like step-local hooks (see {@link TaskConfig}),
322
361
  * these fire *before* the cross-cutting `FlowHooks` callbacks, and a thrown
@@ -324,6 +363,10 @@ interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R,
324
363
  *
325
364
  * `onComplete`'s event is typed against this flow's `Output` (whatever the
326
365
  * `output()` resolver returns).
366
+ *
367
+ * `onError` also fires when a run is canceled by a concurrency-group
368
+ * supersede; the event's `error.name` is `"NagiCanceledError"` and
369
+ * `error.cause` carries `{ canceledByRunId, concurrencyKey }`.
327
370
  */
328
371
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
329
372
  readonly onComplete?: (event: FlowCompleteEvent & {
@@ -347,6 +390,12 @@ interface Flow<Id extends string = string, InputSchema extends StandardSchemaV1
347
390
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
348
391
  readonly onComplete?: (event: FlowCompleteEvent) => void | Promise<void>;
349
392
  readonly onError?: (event: FlowErrorEvent) => void | Promise<void>;
393
+ /**
394
+ * Forwarded from {@link FlowConfig.concurrency}. The runtime form widens
395
+ * `Input` to `Json` so a concrete `Flow<...{x: number}>` is assignable to
396
+ * `Flow<...unknown>` (the dispatcher's view).
397
+ */
398
+ readonly concurrency?: FlowConcurrency<Json>;
350
399
  }
351
400
  type FlowInput<F> = F extends Flow<string, infer S, StepMap, unknown> ? InferSchemaOutput<S> : never;
352
401
  type FlowOutput<F> = F extends Flow<string, StandardSchemaV1, StepMap, infer O> ? O : never;
@@ -456,19 +505,37 @@ interface Store {
456
505
  /**
457
506
  * Atomically begin a run. Inserts the `flow.started` fact and any
458
507
  * materialized run row keyed by `runId` IFF no run with this `runId` already
459
- * exists. Returns `{ started: true }` if this call created the run,
460
- * `{ started: false }` if the run already exists.
508
+ * exists. Returns `{ started: true, canceled: [...] }` if this call created
509
+ * the run, `{ started: false, canceled: [] }` if the run already exists.
461
510
  *
462
511
  * Two concurrent `tryStartRun(runId, ...)` calls with the same `runId` must
463
512
  * result in exactly one `flow.started` fact. Adapters enforce this at the
464
513
  * durability layer (e.g. Postgres `INSERT ... ON CONFLICT DO NOTHING` keyed
465
514
  * by `run_id`), NOT via app-level check-then-insert.
466
515
  *
516
+ * When `concurrency` is supplied, the adapter ALSO atomically cancels any
517
+ * prior runs whose `(flowId, concurrency.key)` matches and whose status is
518
+ * still `pending` / `running`. Each canceled run gets a `flow.canceled`
519
+ * fact appended to its log and its materialized status updated to
520
+ * `canceled`. The returned `canceled` array carries the fact for each
521
+ * canceled run so the runtime can fire `onFlowError` post-commit.
522
+ *
523
+ * Adapters MUST serialize concurrent starts for the same
524
+ * `(flowId, concurrency.key)` (e.g. Postgres advisory-lock keyed on the
525
+ * pair) so the partial unique index on active runs is never violated.
526
+ *
467
527
  * The runtime calls this exactly once at `wf.start()`. Subsequent facts go
468
528
  * through `appendFact` as usual.
469
529
  */
470
- tryStartRun(runId: RunId, fact: FlowStartedFact): Promise<{
530
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
531
+ readonly key: string;
532
+ readonly mode: ConcurrencyMode;
533
+ }): Promise<{
471
534
  readonly started: boolean;
535
+ readonly canceled: ReadonlyArray<{
536
+ readonly runId: RunId;
537
+ readonly fact: FlowCanceledFact;
538
+ }>;
472
539
  }>;
473
540
  /**
474
541
  * Returns null if the step is already claimed under a live lease. Lease
@@ -594,7 +661,7 @@ interface Clock {
594
661
  interface Trigger {
595
662
  subscribe(handler: (runId: RunId) => void): () => void;
596
663
  }
597
- 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";
664
+ 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";
598
665
  interface FactBase {
599
666
  readonly runId: RunId;
600
667
  readonly at: Date;
@@ -644,6 +711,19 @@ interface FlowFailedFact extends FactBase {
644
711
  readonly kind: "flow.failed";
645
712
  readonly error: SerializedError;
646
713
  }
714
+ /**
715
+ * Recorded on a prior run when a new `wf.start()` with the same concurrency
716
+ * group supersedes it. The fact lives in the canceled run's fact log (not
717
+ * the new run's) — observers reading that run's history see exactly when and
718
+ * why it was canceled.
719
+ */
720
+ interface FlowCanceledFact extends FactBase {
721
+ readonly kind: "flow.canceled";
722
+ /** The new run that took over this run's concurrency slot. */
723
+ readonly canceledByRunId: RunId;
724
+ /** The shared concurrency key between this run and `canceledByRunId`. */
725
+ readonly concurrencyKey: string;
726
+ }
647
727
  interface StepStartedFact extends FactBase {
648
728
  readonly kind: "step.started";
649
729
  readonly stepId: StepId;
@@ -681,6 +761,12 @@ interface SignalReceivedFact extends FactBase {
681
761
  readonly kind: "signal.received";
682
762
  readonly stepId: StepId;
683
763
  readonly payload: Json;
764
+ /**
765
+ * The alias the caller sent, when the resolved signal step accepts
766
+ * multiple names (or a single name != stepId). Absent when the incoming
767
+ * name equals the step id — the back-compat single-name case.
768
+ */
769
+ readonly signalName?: string;
684
770
  }
685
771
  interface OnceRecordedFact extends FactBase {
686
772
  readonly kind: "once.recorded";
@@ -693,8 +779,8 @@ interface MatchArmSelectedFact extends FactBase {
693
779
  readonly stepId: StepId;
694
780
  readonly arm: string;
695
781
  }
696
- type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
697
- type RunStatus = "pending" | "running" | "completed" | "failed";
782
+ type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
783
+ type RunStatus = "pending" | "running" | "completed" | "failed" | "canceled";
698
784
  type StepStatus = "pending" | "running" | "completed" | "failed" | "skipped";
699
785
  interface StepState {
700
786
  readonly stepId: StepId;
@@ -792,6 +878,13 @@ interface CanonicalStep {
792
878
  readonly retry?: CanonicalRetryPolicy;
793
879
  readonly timeoutMs?: Millis;
794
880
  readonly signalSchema?: CanonicalSchema;
881
+ /**
882
+ * External signal names this step accepts, sorted lexicographically. Only
883
+ * present when the caller supplied `name` / `names` on `b.signal`; absent
884
+ * for the default "name == step id" case so pre-RFC-0004 flows hash
885
+ * byte-identically.
886
+ */
887
+ readonly signalNames?: readonly string[];
795
888
  readonly matchMode?: "discriminator" | "guard";
796
889
  readonly matchOnHash?: string;
797
890
  readonly matchArms?: readonly CanonicalMatchArm[];
@@ -826,6 +919,17 @@ declare function canonicalize(flow: Flow): Promise<CanonicalDag>;
826
919
  * deterministic. Two equivalent DAGs produce byte-identical input bytes.
827
920
  */
828
921
  declare function sha256Canonical(dag: CanonicalDag): Promise<string>;
922
+ /**
923
+ * Compute a structural fingerprint over a set of registered flows. Used as
924
+ * the default value of `nagi({ codeVersion })` when the caller omits it.
925
+ *
926
+ * Per-flow projection reuses {@link canonicalize} unchanged — so this hash
927
+ * and each flow's snapshot `flowHash` share one canonical definition and
928
+ * cannot drift apart. Equivalent flow sets produce byte-identical hashes;
929
+ * adding/removing a flow, renaming a flow id, or any structural step change
930
+ * moves the result. `run`-body edits do not.
931
+ */
932
+ declare function fingerprintFlows(flows: ReadonlyArray<Flow>): Promise<string>;
829
933
 
830
934
  /** Fields on a step whose hash-relevant value can change between snapshots. */
831
935
  type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchMode" | "matchOn" | "matchArms";
@@ -874,11 +978,26 @@ declare class InMemoryStore implements Store {
874
978
  private readonly snapshots;
875
979
  private readonly refs;
876
980
  private readonly globalFacts;
981
+ /**
982
+ * The runId currently holding the active slot for `flowId::concurrencyKey`.
983
+ * Updated on `tryStartRun` (set when concurrency is supplied) and on
984
+ * terminal facts (cleared via {@link keyByActiveRun}).
985
+ */
986
+ private readonly activeByKey;
987
+ /** Reverse lookup so terminal facts can free the slot in O(1). */
988
+ private readonly keyByActiveRun;
877
989
  private readonly leaseMs;
878
990
  constructor(opts?: InMemoryStoreOpts);
879
991
  appendFact(runId: RunId, fact: Fact): Promise<void>;
880
- tryStartRun(runId: RunId, fact: FlowStartedFact): Promise<{
992
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
993
+ readonly key: string;
994
+ readonly mode: ConcurrencyMode;
995
+ }): Promise<{
881
996
  readonly started: boolean;
997
+ readonly canceled: ReadonlyArray<{
998
+ readonly runId: RunId;
999
+ readonly fact: FlowCanceledFact;
1000
+ }>;
882
1001
  }>;
883
1002
  loadRunState(runId: RunId): Promise<RunState>;
884
1003
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
@@ -968,11 +1087,18 @@ interface NagiConfig {
968
1087
  readonly logger?: Logger;
969
1088
  readonly defaultRetry?: RetryPolicy;
970
1089
  /**
971
- * Handler-code identifier — typically a git SHA from `process.env.GIT_SHA`
972
- * or your build's bundle hash. Persisted on `workflow_run.code_version` and
973
- * on every `flow.started` fact for runs started by this process. Captures
974
- * handler-body drift orthogonally to the topology hash. See RFC 0001
975
- * "Topology vs handler code."
1090
+ * Process-wide identifier persisted on `workflow_run.code_version` and on
1091
+ * every `flow.started` fact for runs started by this process.
1092
+ *
1093
+ * When omitted (default), nagi computes a structural fingerprint over the
1094
+ * registered flows via {@link fingerprintFlows} and uses that — so the
1095
+ * audit field is meaningful by default and shifts only when flow topology
1096
+ * changes, not on every deploy. Supply an explicit string to override
1097
+ * (e.g. for a forced cutover: `"cutover-2026-05-15"`).
1098
+ *
1099
+ * Drift detection at replay uses each flow's per-flow `flowHash`, not this
1100
+ * value. See RFC 0001 "Topology vs handler code" and RFC 0003 "Auto-compute
1101
+ * codeVersion."
976
1102
  */
977
1103
  readonly codeVersion?: string;
978
1104
  }
@@ -1011,6 +1137,23 @@ declare class NagiValidationError extends Error {
1011
1137
  declare class NagiRuntimeError extends Error {
1012
1138
  constructor(message: string);
1013
1139
  }
1140
+ /**
1141
+ * Carried by `onFlowError` (both flow-local and cross-cutting) when a run is
1142
+ * canceled because a newer `wf.start()` for the same concurrency group
1143
+ * superseded it. The serialized form preserves `name` and a structured
1144
+ * `cause` so observers can discriminate via `error.name === "NagiCanceledError"`
1145
+ * and read `error.cause.canceledByRunId` / `error.cause.concurrencyKey`.
1146
+ */
1147
+ declare class NagiCanceledError extends Error {
1148
+ readonly runId: RunId;
1149
+ readonly canceledByRunId: RunId;
1150
+ readonly concurrencyKey: string;
1151
+ constructor(args: {
1152
+ readonly runId: RunId;
1153
+ readonly canceledByRunId: RunId;
1154
+ readonly concurrencyKey: string;
1155
+ });
1156
+ }
1014
1157
  /**
1015
1158
  * Thrown by `wf.replay(runId)` when the live flow's canonical hash differs
1016
1159
  * from the snapshot the run was pinned to. The default replay behavior is
@@ -1029,4 +1172,4 @@ declare class NagiSnapshotDriftError extends Error {
1029
1172
  }
1030
1173
  declare function nagi(config: NagiConfig): Promise<Wf>;
1031
1174
 
1032
- 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 };
1175
+ 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 };