@nagi-js/core 0.1.1-rc.1 → 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
@@ -300,6 +300,31 @@ type BuilderAccumulator<M extends StepMap> = {
300
300
  type AsStepMap<R> = R extends Builder<unknown, infer A> ? {
301
301
  readonly [K in keyof A]: Step<A[K]>;
302
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
+ }
303
328
  interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R, Output = unknown> {
304
329
  /** Stable persistence handle. TanStack-key shaped (kebab or snake). */
305
330
  readonly id: Id;
@@ -317,6 +342,13 @@ interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R,
317
342
  * the type claims otherwise (consistent with the "skip is transitive" lock).
318
343
  */
319
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>>;
320
352
  /**
321
353
  * Flow-level lifecycle hooks. Like step-local hooks (see {@link TaskConfig}),
322
354
  * these fire *before* the cross-cutting `FlowHooks` callbacks, and a thrown
@@ -324,6 +356,10 @@ interface FlowConfig<Id extends string, InputSchema extends StandardSchemaV1, R,
324
356
  *
325
357
  * `onComplete`'s event is typed against this flow's `Output` (whatever the
326
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 }`.
327
363
  */
328
364
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
329
365
  readonly onComplete?: (event: FlowCompleteEvent & {
@@ -347,6 +383,12 @@ interface Flow<Id extends string = string, InputSchema extends StandardSchemaV1
347
383
  readonly onStart?: (event: FlowStartEvent) => void | Promise<void>;
348
384
  readonly onComplete?: (event: FlowCompleteEvent) => void | Promise<void>;
349
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>;
350
392
  }
351
393
  type FlowInput<F> = F extends Flow<string, infer S, StepMap, unknown> ? InferSchemaOutput<S> : never;
352
394
  type FlowOutput<F> = F extends Flow<string, StandardSchemaV1, StepMap, infer O> ? O : never;
@@ -456,19 +498,37 @@ interface Store {
456
498
  /**
457
499
  * Atomically begin a run. Inserts the `flow.started` fact and any
458
500
  * 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.
501
+ * exists. Returns `{ started: true, canceled: [...] }` if this call created
502
+ * the run, `{ started: false, canceled: [] }` if the run already exists.
461
503
  *
462
504
  * Two concurrent `tryStartRun(runId, ...)` calls with the same `runId` must
463
505
  * result in exactly one `flow.started` fact. Adapters enforce this at the
464
506
  * durability layer (e.g. Postgres `INSERT ... ON CONFLICT DO NOTHING` keyed
465
507
  * by `run_id`), NOT via app-level check-then-insert.
466
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
+ *
467
520
  * The runtime calls this exactly once at `wf.start()`. Subsequent facts go
468
521
  * through `appendFact` as usual.
469
522
  */
470
- tryStartRun(runId: RunId, fact: FlowStartedFact): Promise<{
523
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
524
+ readonly key: string;
525
+ readonly mode: ConcurrencyMode;
526
+ }): Promise<{
471
527
  readonly started: boolean;
528
+ readonly canceled: ReadonlyArray<{
529
+ readonly runId: RunId;
530
+ readonly fact: FlowCanceledFact;
531
+ }>;
472
532
  }>;
473
533
  /**
474
534
  * Returns null if the step is already claimed under a live lease. Lease
@@ -594,7 +654,7 @@ interface Clock {
594
654
  interface Trigger {
595
655
  subscribe(handler: (runId: RunId) => void): () => void;
596
656
  }
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";
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";
598
658
  interface FactBase {
599
659
  readonly runId: RunId;
600
660
  readonly at: Date;
@@ -644,6 +704,19 @@ interface FlowFailedFact extends FactBase {
644
704
  readonly kind: "flow.failed";
645
705
  readonly error: SerializedError;
646
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
+ }
647
720
  interface StepStartedFact extends FactBase {
648
721
  readonly kind: "step.started";
649
722
  readonly stepId: StepId;
@@ -693,8 +766,8 @@ interface MatchArmSelectedFact extends FactBase {
693
766
  readonly stepId: StepId;
694
767
  readonly arm: string;
695
768
  }
696
- type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
697
- 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";
698
771
  type StepStatus = "pending" | "running" | "completed" | "failed" | "skipped";
699
772
  interface StepState {
700
773
  readonly stepId: StepId;
@@ -826,6 +899,17 @@ declare function canonicalize(flow: Flow): Promise<CanonicalDag>;
826
899
  * deterministic. Two equivalent DAGs produce byte-identical input bytes.
827
900
  */
828
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>;
829
913
 
830
914
  /** Fields on a step whose hash-relevant value can change between snapshots. */
831
915
  type SnapshotChangedField = "kind" | "when" | "retry" | "timeoutMs" | "signalSchema" | "matchMode" | "matchOn" | "matchArms";
@@ -874,11 +958,26 @@ declare class InMemoryStore implements Store {
874
958
  private readonly snapshots;
875
959
  private readonly refs;
876
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;
877
969
  private readonly leaseMs;
878
970
  constructor(opts?: InMemoryStoreOpts);
879
971
  appendFact(runId: RunId, fact: Fact): Promise<void>;
880
- tryStartRun(runId: RunId, fact: FlowStartedFact): Promise<{
972
+ tryStartRun(runId: RunId, fact: FlowStartedFact, concurrency?: {
973
+ readonly key: string;
974
+ readonly mode: ConcurrencyMode;
975
+ }): Promise<{
881
976
  readonly started: boolean;
977
+ readonly canceled: ReadonlyArray<{
978
+ readonly runId: RunId;
979
+ readonly fact: FlowCanceledFact;
980
+ }>;
882
981
  }>;
883
982
  loadRunState(runId: RunId): Promise<RunState>;
884
983
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
@@ -968,11 +1067,18 @@ interface NagiConfig {
968
1067
  readonly logger?: Logger;
969
1068
  readonly defaultRetry?: RetryPolicy;
970
1069
  /**
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."
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."
976
1082
  */
977
1083
  readonly codeVersion?: string;
978
1084
  }
@@ -1011,6 +1117,23 @@ declare class NagiValidationError extends Error {
1011
1117
  declare class NagiRuntimeError extends Error {
1012
1118
  constructor(message: string);
1013
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
+ }
1014
1137
  /**
1015
1138
  * Thrown by `wf.replay(runId)` when the live flow's canonical hash differs
1016
1139
  * from the snapshot the run was pinned to. The default replay behavior is
@@ -1029,4 +1152,4 @@ declare class NagiSnapshotDriftError extends Error {
1029
1152
  }
1030
1153
  declare function nagi(config: NagiConfig): Promise<Wf>;
1031
1154
 
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 };
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 };
package/dist/index.js CHANGED
@@ -236,7 +236,8 @@ function flow(config) {
236
236
  ...config.onComplete !== void 0 ? {
237
237
  onComplete: config.onComplete
238
238
  } : {},
239
- ...config.onError !== void 0 ? { onError: config.onError } : {}
239
+ ...config.onError !== void 0 ? { onError: config.onError } : {},
240
+ ...config.concurrency !== void 0 ? { concurrency: config.concurrency } : {}
240
241
  };
241
242
  }
242
243
  function collectIds(map, prefix, idByIdentity) {
@@ -421,6 +422,15 @@ async function hashFnSource(fn) {
421
422
  async function sha256Canonical(dag) {
422
423
  return sha256Hex(stableStringify(dag));
423
424
  }
425
+ async function fingerprintFlows(flows) {
426
+ const entries = [];
427
+ for (const f of flows) {
428
+ const dag = await canonicalize(f);
429
+ entries.push([f.id, await sha256Canonical(dag)]);
430
+ }
431
+ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
432
+ return sha256Hex(stableStringify(entries));
433
+ }
424
434
  function stableStringify(value) {
425
435
  if (value === void 0) return "null";
426
436
  if (value === null || typeof value !== "object") return JSON.stringify(value);
@@ -567,6 +577,14 @@ var InMemoryStore = class {
567
577
  snapshots = /* @__PURE__ */ new Map();
568
578
  refs = /* @__PURE__ */ new Map();
569
579
  globalFacts = [];
580
+ /**
581
+ * The runId currently holding the active slot for `flowId::concurrencyKey`.
582
+ * Updated on `tryStartRun` (set when concurrency is supplied) and on
583
+ * terminal facts (cleared via {@link keyByActiveRun}).
584
+ */
585
+ activeByKey = /* @__PURE__ */ new Map();
586
+ /** Reverse lookup so terminal facts can free the slot in O(1). */
587
+ keyByActiveRun = /* @__PURE__ */ new Map();
570
588
  leaseMs;
571
589
  constructor(opts = {}) {
572
590
  this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
@@ -575,13 +593,40 @@ var InMemoryStore = class {
575
593
  const list = this.facts.get(runId) ?? [];
576
594
  list.push(fact);
577
595
  this.facts.set(runId, list);
596
+ if (fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled") {
597
+ const slot = this.keyByActiveRun.get(runId);
598
+ if (slot !== void 0) {
599
+ this.keyByActiveRun.delete(runId);
600
+ if (this.activeByKey.get(slot) === runId) {
601
+ this.activeByKey.delete(slot);
602
+ }
603
+ }
604
+ }
578
605
  }
579
- async tryStartRun(runId, fact) {
606
+ async tryStartRun(runId, fact, concurrency) {
580
607
  if (this.facts.has(runId)) {
581
- return { started: false };
608
+ return { started: false, canceled: [] };
609
+ }
610
+ const canceled = [];
611
+ if (concurrency !== void 0) {
612
+ const slot = `${fact.flowId}::${concurrency.key}`;
613
+ const priorRunId = this.activeByKey.get(slot);
614
+ if (priorRunId !== void 0) {
615
+ const cancelFact = {
616
+ kind: "flow.canceled",
617
+ runId: priorRunId,
618
+ at: fact.at,
619
+ canceledByRunId: runId,
620
+ concurrencyKey: concurrency.key
621
+ };
622
+ await this.appendFact(priorRunId, cancelFact);
623
+ canceled.push({ runId: priorRunId, fact: cancelFact });
624
+ }
625
+ this.activeByKey.set(slot, runId);
626
+ this.keyByActiveRun.set(runId, slot);
582
627
  }
583
628
  this.facts.set(runId, [fact]);
584
- return { started: true };
629
+ return { started: true, canceled };
585
630
  }
586
631
  async loadRunState(runId) {
587
632
  return projectRunState(runId, this.facts.get(runId) ?? []);
@@ -663,6 +708,9 @@ function projectRunState(runId, facts) {
663
708
  case "flow.failed":
664
709
  status = "failed";
665
710
  break;
711
+ case "flow.canceled":
712
+ status = "canceled";
713
+ break;
666
714
  case "step.started":
667
715
  steps[fact.stepId] = {
668
716
  stepId: fact.stepId,
@@ -980,6 +1028,10 @@ async function dispatchMessage(deps, message) {
980
1028
  }
981
1029
  const def = getDef(step);
982
1030
  const preState = await store.loadRunState(runId);
1031
+ if (preState.status === "canceled") {
1032
+ await queue.ack(message.receipt);
1033
+ return;
1034
+ }
983
1035
  const preStep = preState.steps[stepId];
984
1036
  if (preStep && (preStep.status === "completed" || preStep.status === "failed" || preStep.status === "skipped")) {
985
1037
  await queue.ack(message.receipt);
@@ -1342,8 +1394,13 @@ function retryAllows(policy, err) {
1342
1394
  return policy.retryOn(err);
1343
1395
  }
1344
1396
  function isFlowTerminal(facts) {
1345
- const last = facts[facts.length - 1];
1346
- return last !== void 0 && (last.kind === "flow.completed" || last.kind === "flow.failed");
1397
+ for (let i = facts.length - 1; i >= 0; i--) {
1398
+ const f = facts[i];
1399
+ if (f !== void 0 && (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled")) {
1400
+ return true;
1401
+ }
1402
+ }
1403
+ return false;
1347
1404
  }
1348
1405
  async function finalizeFlowFailure(args) {
1349
1406
  const { deps, flow: flow2, runId, error } = args;
@@ -1504,6 +1561,24 @@ var NagiRuntimeError = class extends Error {
1504
1561
  this.name = "NagiRuntimeError";
1505
1562
  }
1506
1563
  };
1564
+ var NagiCanceledError = class extends Error {
1565
+ runId;
1566
+ canceledByRunId;
1567
+ concurrencyKey;
1568
+ constructor(args) {
1569
+ super(
1570
+ `Run ${args.runId} was canceled (superseded by run ${args.canceledByRunId} for concurrency key "${args.concurrencyKey}").`
1571
+ );
1572
+ this.name = "NagiCanceledError";
1573
+ this.runId = args.runId;
1574
+ this.canceledByRunId = args.canceledByRunId;
1575
+ this.concurrencyKey = args.concurrencyKey;
1576
+ this.cause = {
1577
+ canceledByRunId: args.canceledByRunId,
1578
+ concurrencyKey: args.concurrencyKey
1579
+ };
1580
+ }
1581
+ };
1507
1582
  var NagiSnapshotDriftError = class extends Error {
1508
1583
  runId;
1509
1584
  expected;
@@ -1549,6 +1624,7 @@ async function nagi(config) {
1549
1624
  });
1550
1625
  }
1551
1626
  }
1627
+ const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
1552
1628
  async function flowFor(runId) {
1553
1629
  const runState = await config.store.loadRunState(runId);
1554
1630
  const flow2 = flowsById.get(runState.flowId);
@@ -1599,12 +1675,63 @@ async function nagi(config) {
1599
1675
  input: validated,
1600
1676
  at: startedAt,
1601
1677
  ...flowHash !== void 0 ? { flowHash } : {},
1602
- ...config.codeVersion !== void 0 ? { codeVersion: config.codeVersion } : {}
1678
+ codeVersion
1603
1679
  };
1604
- const { started } = await config.store.tryStartRun(runId, fact);
1680
+ let concurrencyArg;
1681
+ if (flow2.concurrency !== void 0) {
1682
+ const derived = flow2.concurrency.keyFn(validated);
1683
+ if (typeof derived !== "string" || derived.length === 0) {
1684
+ throw new NagiValidationError([
1685
+ {
1686
+ message: `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
1687
+ path: ["concurrency", "keyFn"]
1688
+ }
1689
+ ]);
1690
+ }
1691
+ concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
1692
+ }
1693
+ const { started, canceled } = await config.store.tryStartRun(
1694
+ runId,
1695
+ fact,
1696
+ concurrencyArg
1697
+ );
1605
1698
  if (!started) {
1606
1699
  return runId;
1607
1700
  }
1701
+ for (const c of canceled) {
1702
+ const cancelError = new NagiCanceledError({
1703
+ runId: c.runId,
1704
+ canceledByRunId: runId,
1705
+ concurrencyKey: c.fact.concurrencyKey
1706
+ });
1707
+ const serialized = {
1708
+ name: cancelError.name,
1709
+ message: cancelError.message,
1710
+ ...cancelError.stack !== void 0 ? { stack: cancelError.stack } : {},
1711
+ cause: {
1712
+ canceledByRunId: runId,
1713
+ concurrencyKey: c.fact.concurrencyKey
1714
+ }
1715
+ };
1716
+ const errorEvent = {
1717
+ runId: c.runId,
1718
+ flowId: flow2.id,
1719
+ error: serialized,
1720
+ at: c.fact.at
1721
+ };
1722
+ await fireHook(
1723
+ flow2.onError,
1724
+ errorEvent,
1725
+ "flow.onError",
1726
+ dispatchDeps
1727
+ );
1728
+ await fireHook(
1729
+ config.hooks?.onFlowError,
1730
+ errorEvent,
1731
+ "onFlowError",
1732
+ dispatchDeps
1733
+ );
1734
+ }
1608
1735
  const startEvent = {
1609
1736
  runId,
1610
1737
  flowId: flow2.id,
@@ -1707,6 +1834,11 @@ async function nagi(config) {
1707
1834
  `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
1708
1835
  );
1709
1836
  }
1837
+ if (runState.status === "canceled") {
1838
+ throw new NagiRuntimeError(
1839
+ `Run ${runId} was canceled (superseded by a newer run with the same concurrency key). Replay is not supported for canceled runs \u2014 start a new run instead.`
1840
+ );
1841
+ }
1710
1842
  if (opts.mode === "inspect") return;
1711
1843
  const fireHooks = opts.fireHooks !== false;
1712
1844
  const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
@@ -1800,6 +1932,6 @@ function synthesizeReplayFlow(dag, liveFlow) {
1800
1932
  };
1801
1933
  }
1802
1934
 
1803
- export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, flow, nagi, projectRunState, sha256Canonical };
1935
+ export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiCanceledError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };
1804
1936
  //# sourceMappingURL=index.js.map
1805
1937
  //# sourceMappingURL=index.js.map