@nagi-js/core 0.1.1-rc.21 → 0.1.1-rc.23

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.
@@ -72,42 +72,6 @@ function isStepTerminal(s) {
72
72
  return s.tag === "completed" || s.tag === "failed" || s.tag === "skipped" || s.tag === "canceled";
73
73
  }
74
74
 
75
- // src/retry.ts
76
- var DEFAULT_RETRY = {
77
- maxAttempts: 3,
78
- backoff: "exponential",
79
- initialDelayMs: 1e3,
80
- maxDelayMs: 6e4
81
- };
82
- function resolveRetry(handlerPolicy, runtimeDefault) {
83
- return handlerPolicy ?? runtimeDefault ?? DEFAULT_RETRY;
84
- }
85
- function stepBackoff(policy) {
86
- const initial = policy.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs;
87
- const max = policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs;
88
- return (attempt) => {
89
- switch (policy.backoff) {
90
- case "exponential":
91
- return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
92
- case "linear":
93
- return Math.min(initial * Math.max(1, attempt), max);
94
- case "fixed":
95
- return Math.min(initial, max);
96
- }
97
- };
98
- }
99
- var MAX_DEQUEUE_BACKOFF_MS = 3e4;
100
- var MIN_DEQUEUE_BACKOFF_MS = 50;
101
- function dequeueBackoff(pollIntervalMs) {
102
- const base = Math.max(pollIntervalMs, MIN_DEQUEUE_BACKOFF_MS);
103
- return (consecutiveFailures) => Math.min(base * 2 ** (consecutiveFailures - 1), MAX_DEQUEUE_BACKOFF_MS);
104
- }
105
- var SNAPSHOT_GONE_DELIVERY_BUDGET = 60;
106
- var MAX_SNAPSHOT_GONE_BACKOFF_MS = 3e5;
107
- var snapshotGoneBackoff = (readCount) => Math.min(readCount * readCount * 1e3, MAX_SNAPSHOT_GONE_BACKOFF_MS);
108
- var defaultSnapshotGonePolicy = (readCount) => readCount > SNAPSHOT_GONE_DELIVERY_BUDGET ? { action: "fail" } : { action: "retry", delayMs: snapshotGoneBackoff(readCount) };
109
- var reapBackoff = () => 0;
110
-
111
75
  // src/internal.ts
112
76
  function isOptional(ref) {
113
77
  return "__optional" in ref;
@@ -151,15 +115,23 @@ function peekDef(step) {
151
115
  return step[DEF];
152
116
  }
153
117
  function handlerDef(def) {
154
- return def.kind === "task" || def.kind === "activity" || def.kind === "streaming" ? def : void 0;
118
+ switch (def.kind) {
119
+ case "task":
120
+ case "activity":
121
+ case "streaming":
122
+ return def;
123
+ case "signal":
124
+ case "subflow":
125
+ return void 0;
126
+ }
155
127
  }
156
128
  function needsStepIds(def) {
157
129
  return Object.values(def.needs).map((ref) => ref.step.id);
158
130
  }
159
- function resolveNeeds(def, loadResolved) {
131
+ function resolveNeeds(def, state) {
160
132
  const result = {};
161
133
  for (const [localKey, ref] of Object.entries(def.needs)) {
162
- const resolved = loadResolved(ref.step.id);
134
+ const resolved = resolvedOf(stepStateOf(state, ref.step.id));
163
135
  result[localKey] = ref.optional ? resolved : unwrap(resolved);
164
136
  }
165
137
  return result;
@@ -167,15 +139,6 @@ function resolveNeeds(def, loadResolved) {
167
139
  function asStepMapWithDefs(steps) {
168
140
  return steps;
169
141
  }
170
- function selectArm(def, args) {
171
- for (const arm of def.arms) {
172
- if (arm.guard.kind === "otherwise") return arm.id;
173
- if (arm.guard.when(args)) return arm.id;
174
- }
175
- throw new Error(
176
- `match: no arm matched and no { otherwise: true } fallback was provided`
177
- );
178
- }
179
142
 
180
143
  // src/errors.ts
181
144
  var NagiValidationError = class extends Error {
@@ -331,6 +294,9 @@ function serializeError(err) {
331
294
  }
332
295
 
333
296
  // src/facts/flow.ts
297
+ function isRunEnd(fact) {
298
+ return fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled";
299
+ }
334
300
  var flowFacts = {
335
301
  flowStarted(a) {
336
302
  return {
@@ -389,15 +355,10 @@ function runCancelCause(fact) {
389
355
  reason: fact.reason,
390
356
  ...compact({ note: fact.note })
391
357
  };
392
- case "operator":
393
- return {
394
- kind: "operator",
395
- actor: fact.actor,
396
- reason: fact.reason,
397
- ...compact({ note: fact.note })
398
- };
399
358
  }
400
359
  }
360
+ var RELEASE_RUN = { tag: "release-run" };
361
+ var CLOSE_RUN = { tag: "close-run" };
401
362
  var flowKinds = {
402
363
  "flow.started": {
403
364
  fold: (draft, fact) => {
@@ -417,7 +378,10 @@ var flowKinds = {
417
378
  flowHash: fact.flowHash ?? null,
418
379
  codeVersion: fact.codeVersion ?? null,
419
380
  parent: fact.parent ?? null
420
- })
381
+ }),
382
+ release: null,
383
+ stream: null,
384
+ event: (fact) => ({ type: "flow.started", flowId: fact.flowId })
421
385
  },
422
386
  "flow.completed": {
423
387
  fold: (draft, fact) => {
@@ -428,7 +392,12 @@ var flowKinds = {
428
392
  status: "completed",
429
393
  output: fact.output,
430
394
  completedAt: fact.at
431
- })
395
+ }),
396
+ release: () => RELEASE_RUN,
397
+ // Closes every still-open channel of the run, so a subscriber to a skipped
398
+ // or never-emitting step never hangs.
399
+ stream: () => CLOSE_RUN,
400
+ event: (fact) => ({ type: "flow.completed", output: fact.output })
432
401
  },
433
402
  "flow.failed": {
434
403
  fold: (draft, fact) => {
@@ -439,7 +408,10 @@ var flowKinds = {
439
408
  status: "failed",
440
409
  error: fact.error,
441
410
  completedAt: fact.at
442
- })
411
+ }),
412
+ release: () => RELEASE_RUN,
413
+ stream: () => CLOSE_RUN,
414
+ event: (fact) => ({ type: "flow.failed", error: fact.error })
443
415
  },
444
416
  "flow.canceled": {
445
417
  fold: (draft, fact) => {
@@ -450,7 +422,14 @@ var flowKinds = {
450
422
  status: "canceled",
451
423
  canceledByRunId: fact.cause === "concurrency" ? fact.canceledByRunId : null,
452
424
  completedAt: fact.at
453
- })
425
+ }),
426
+ release: () => RELEASE_RUN,
427
+ stream: () => CLOSE_RUN,
428
+ event: (fact) => fact.cause === "concurrency" ? {
429
+ type: "flow.canceled",
430
+ cause: "concurrency",
431
+ canceledByRunId: fact.canceledByRunId
432
+ } : { type: "flow.canceled", cause: fact.cause }
454
433
  }
455
434
  };
456
435
 
@@ -469,10 +448,21 @@ var leaseFacts = {
469
448
  }
470
449
  };
471
450
  var leaseKinds = {
472
- // Audit-only: the reaper re-enqueues at attempt+1; the projection updates
473
- // when the next attempt writes its step.started/step.failed.
474
- "lease.reaped": { fold: () => {
475
- }, rows: null }
451
+ // The reaper re-enqueues at attempt+1; the projection updates when the next
452
+ // attempt writes its step.started/step.failed. Only the reaped attempt's
453
+ // lease goes: a newer attempt may already hold its own.
454
+ "lease.reaped": {
455
+ fold: () => {
456
+ },
457
+ rows: null,
458
+ release: (fact) => ({
459
+ tag: "release-lease",
460
+ stepId: fact.stepId,
461
+ attempt: fact.attempt
462
+ }),
463
+ stream: null,
464
+ event: null
465
+ }
476
466
  };
477
467
 
478
468
  // src/facts/signal.ts
@@ -506,7 +496,10 @@ var signalKinds = {
506
496
  fold: (draft, fact) => {
507
497
  delete draft.bufferedSignals[fact.stepId];
508
498
  },
509
- rows: null
499
+ rows: null,
500
+ release: null,
501
+ stream: null,
502
+ event: null
510
503
  },
511
504
  "signal.buffered": {
512
505
  // First buffered signal per step wins, mirroring the happy path where the
@@ -519,7 +512,10 @@ var signalKinds = {
519
512
  };
520
513
  }
521
514
  },
522
- rows: null
515
+ rows: null,
516
+ release: null,
517
+ stream: null,
518
+ event: null
523
519
  }
524
520
  };
525
521
 
@@ -566,8 +562,7 @@ var stepFacts = {
566
562
  runId: a.runId,
567
563
  stepId: a.stepId,
568
564
  reason: a.reason,
569
- at: a.at,
570
- ...compact({ actor: a.actor, note: a.note })
565
+ at: a.at
571
566
  };
572
567
  },
573
568
  stepReset(a) {
@@ -578,9 +573,7 @@ var stepFacts = {
578
573
  at: a.at,
579
574
  ...compact({
580
575
  cascadedFrom: a.cascadedFrom,
581
- scope: a.scope === "cascade" ? void 0 : a.scope,
582
- actor: a.actor,
583
- note: a.note
576
+ scope: a.scope === "cascade" ? void 0 : a.scope
584
577
  })
585
578
  };
586
579
  },
@@ -590,13 +583,8 @@ var stepFacts = {
590
583
  runId: a.runId,
591
584
  stepId: a.stepId,
592
585
  attempt: a.attempt,
593
- actor: a.actor,
594
- at: a.at,
595
- ...compact({ note: a.note })
586
+ at: a.at
596
587
  };
597
- },
598
- matchArmSelected(runId, stepId, arm, at) {
599
- return { kind: "match.arm-selected", runId, stepId, arm, at };
600
588
  }
601
589
  };
602
590
  function startTarget(stepKind, attempt) {
@@ -608,16 +596,24 @@ function startTarget(stepKind, attempt) {
608
596
  case "task":
609
597
  case "activity":
610
598
  case "streaming":
611
- case "match":
612
599
  return { tag: "running", attempt };
613
600
  }
614
601
  }
602
+ function releaseStep(stepId, timer) {
603
+ return { tag: "release-step", stepId, timer };
604
+ }
605
+ function inFlight(prev, attempt) {
606
+ return (prev.tag === "running" || prev.tag === "awaitingSignal" || prev.tag === "awaitingChild" || prev.tag === "aborting") && prev.attempt === attempt;
607
+ }
608
+ function settles(prev, attempt) {
609
+ return !isStepTerminal(prev) && attempt <= attemptOf(prev);
610
+ }
615
611
  var stepKinds = {
616
612
  "step.started": {
617
613
  fold: (draft, fact) => foldStep(
618
614
  draft,
619
615
  fact.stepId,
620
- (prev) => prev.tag === "pending" || prev.tag === "backoff" ? startTarget(fact.stepKind, fact.attempt) : prev
616
+ (prev) => !isStepTerminal(prev) && fact.attempt > attemptOf(prev) ? startTarget(fact.stepKind, fact.attempt) : prev
621
617
  ),
622
618
  rows: (fact) => ({
623
619
  row: "step",
@@ -625,19 +621,35 @@ var stepKinds = {
625
621
  stepId: fact.stepId,
626
622
  attempt: fact.attempt,
627
623
  startedAt: fact.at
624
+ }),
625
+ release: null,
626
+ stream: null,
627
+ event: (fact) => ({
628
+ type: "step.started",
629
+ stepId: fact.stepId,
630
+ attempt: fact.attempt
628
631
  })
629
632
  },
630
633
  "step.completed": {
631
634
  fold: (draft, fact) => foldStep(
632
635
  draft,
633
636
  fact.stepId,
634
- (prev) => isStepTerminal(prev) ? prev : { tag: "completed", attempt: fact.attempt, output: fact.output }
637
+ (prev) => settles(prev, fact.attempt) ? { tag: "completed", attempt: fact.attempt, output: fact.output } : prev
635
638
  ),
636
639
  rows: (fact) => ({
637
640
  row: "step",
638
641
  status: "completed",
639
642
  stepId: fact.stepId,
640
643
  attempt: fact.attempt,
644
+ output: fact.output,
645
+ completedAt: fact.at
646
+ }),
647
+ release: (fact) => releaseStep(fact.stepId, true),
648
+ stream: (fact) => ({ tag: "close-ok", stepId: fact.stepId }),
649
+ event: (fact) => ({
650
+ type: "step.completed",
651
+ stepId: fact.stepId,
652
+ attempt: fact.attempt,
641
653
  output: fact.output
642
654
  })
643
655
  },
@@ -645,19 +657,33 @@ var stepKinds = {
645
657
  fold: (draft, fact) => foldStep(
646
658
  draft,
647
659
  fact.stepId,
648
- (prev) => isStepTerminal(prev) ? prev : { tag: "failed", attempt: fact.attempt, error: fact.error }
660
+ (prev) => settles(prev, fact.attempt) ? { tag: "failed", attempt: fact.attempt, error: fact.error } : prev
649
661
  ),
650
662
  rows: (fact) => ({
651
663
  row: "step",
652
664
  status: "failed",
653
665
  stepId: fact.stepId,
654
666
  attempt: fact.attempt,
667
+ error: fact.error,
668
+ completedAt: fact.at
669
+ }),
670
+ release: (fact) => releaseStep(fact.stepId, false),
671
+ // Only written on terminal failure (retries use step.retried).
672
+ stream: (fact) => ({
673
+ tag: "close-error",
674
+ stepId: fact.stepId,
675
+ error: fact.error
676
+ }),
677
+ event: (fact) => ({
678
+ type: "step.failed",
679
+ stepId: fact.stepId,
680
+ attempt: fact.attempt,
655
681
  error: fact.error
656
682
  })
657
683
  },
658
684
  "step.canceled": {
659
685
  fold: (draft, fact) => foldStep(draft, fact.stepId, (prev) => {
660
- if (isStepTerminal(prev)) return prev;
686
+ if (!settles(prev, fact.attempt)) return prev;
661
687
  const cause = prev.tag === "aborting" ? { kind: "aborted", ...compact({ error: fact.error }) } : { kind: "run-canceled" };
662
688
  return { tag: "canceled", cause };
663
689
  }),
@@ -666,65 +692,88 @@ var stepKinds = {
666
692
  status: "canceled",
667
693
  stepId: fact.stepId,
668
694
  attempt: fact.attempt,
669
- error: fact.error ?? null
670
- })
695
+ error: fact.error ?? null,
696
+ completedAt: fact.at
697
+ }),
698
+ release: (fact) => releaseStep(fact.stepId, false),
699
+ stream: null,
700
+ event: null
671
701
  },
672
702
  "step.retried": {
673
703
  fold: (draft, fact) => foldStep(
674
704
  draft,
675
705
  fact.stepId,
676
- (prev) => prev.tag === "running" ? {
706
+ (prev) => inFlight(prev, fact.attempt) ? {
677
707
  tag: "backoff",
678
708
  failedAttempt: fact.attempt,
679
709
  retryAt: fact.nextAttemptAt,
680
710
  error: fact.error
681
711
  } : prev
682
712
  ),
683
- rows: null
713
+ rows: (fact) => ({
714
+ row: "step",
715
+ status: "backoff",
716
+ stepId: fact.stepId,
717
+ attempt: fact.attempt,
718
+ error: fact.error
719
+ }),
720
+ release: null,
721
+ stream: (fact) => ({
722
+ tag: "retry",
723
+ stepId: fact.stepId,
724
+ nextAttempt: fact.attempt + 1
725
+ }),
726
+ // Carries the attempt that FAILED; the next one is attempt + 1.
727
+ event: (fact) => ({
728
+ type: "step.retried",
729
+ stepId: fact.stepId,
730
+ attempt: fact.attempt
731
+ })
684
732
  },
685
733
  "step.skipped": {
686
- // An operator may skip an in-flight step, not just a pending one.
687
734
  fold: (draft, fact) => foldStep(
688
735
  draft,
689
736
  fact.stepId,
690
737
  (prev) => isStepTerminal(prev) ? prev : { tag: "skipped", reason: fact.reason }
691
738
  ),
692
- rows: (fact) => ({ row: "step", status: "skipped", stepId: fact.stepId })
739
+ rows: (fact) => ({
740
+ row: "step",
741
+ status: "skipped",
742
+ stepId: fact.stepId,
743
+ completedAt: fact.at
744
+ }),
745
+ release: null,
746
+ stream: null,
747
+ event: (fact) => ({
748
+ type: "step.skipped",
749
+ stepId: fact.stepId,
750
+ reason: fact.reason
751
+ })
693
752
  },
694
753
  "step.reset": {
695
754
  fold: (draft, fact) => {
696
755
  draft.steps[fact.stepId] = PENDING;
697
- delete draft.selectedArms[fact.stepId];
756
+ draft.resetCounts[fact.stepId] = (draft.resetCounts[fact.stepId] ?? 0) + 1;
698
757
  delete draft.bufferedSignals[fact.stepId];
699
758
  if (draft.phase.tag === "completed" || draft.phase.tag === "failed") {
700
759
  draft.phase = { tag: "running" };
701
760
  }
702
761
  },
703
- rows: (fact) => ({ row: "step", status: "reset", stepId: fact.stepId })
762
+ rows: (fact) => ({ row: "step", status: "reset", stepId: fact.stepId }),
763
+ release: (fact) => releaseStep(fact.stepId, true),
764
+ stream: null,
765
+ event: null
704
766
  },
705
767
  "step.abort-requested": {
706
768
  fold: (draft, fact) => foldStep(
707
769
  draft,
708
770
  fact.stepId,
709
- (prev) => prev.tag === "running" || prev.tag === "awaitingSignal" || prev.tag === "awaitingChild" ? { tag: "aborting", attempt: fact.attempt } : prev
771
+ (prev) => inFlight(prev, fact.attempt) && prev.tag !== "aborting" ? { tag: "aborting", attempt: fact.attempt } : prev
710
772
  ),
711
- rows: null
712
- },
713
- "match.arm-selected": {
714
- fold: (draft, fact) => {
715
- draft.selectedArms[fact.stepId] = fact.arm;
716
- },
717
- rows: null
718
- },
719
- "once.recorded": {
720
- fold: () => {
721
- },
722
- rows: (fact) => ({
723
- row: "once",
724
- stepId: fact.stepId,
725
- scope: fact.scope,
726
- value: fact.value
727
- })
773
+ rows: null,
774
+ release: null,
775
+ stream: null,
776
+ event: null
728
777
  }
729
778
  };
730
779
 
@@ -753,8 +802,8 @@ function foldRun(runId, facts) {
753
802
  flowHash: void 0,
754
803
  codeVersion: void 0,
755
804
  steps: {},
756
- selectedArms: {},
757
- bufferedSignals: {}
805
+ bufferedSignals: {},
806
+ resetCounts: {}
758
807
  };
759
808
  for (const fact of facts) armOf(fact.kind)?.fold(draft, fact);
760
809
  const { parent, flowHash, codeVersion, ...projected } = draft;
@@ -765,10 +814,52 @@ function foldRun(runId, facts) {
765
814
  ...compact({ parent, flowHash, codeVersion })
766
815
  };
767
816
  }
768
- function rowDeltaOf(fact) {
769
- return armOf(fact.kind)?.rows?.(fact) ?? null;
817
+ function factConsequences(fact) {
818
+ const arm = armOf(fact.kind);
819
+ return {
820
+ rows: arm?.rows?.(fact) ?? null,
821
+ release: arm?.release?.(fact) ?? null,
822
+ stream: arm?.stream?.(fact) ?? null,
823
+ event: arm?.event?.(fact) ?? null
824
+ };
770
825
  }
771
826
 
827
+ // src/retry.ts
828
+ var DEFAULT_RETRY = {
829
+ maxAttempts: 3,
830
+ backoff: "exponential",
831
+ initialDelayMs: 1e3,
832
+ maxDelayMs: 6e4
833
+ };
834
+ function resolveRetry(handlerPolicy, runtimeDefault) {
835
+ return handlerPolicy ?? runtimeDefault ?? DEFAULT_RETRY;
836
+ }
837
+ function stepBackoff(policy) {
838
+ const initial = policy.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs;
839
+ const max = policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs;
840
+ return (attempt) => {
841
+ switch (policy.backoff) {
842
+ case "exponential":
843
+ return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
844
+ case "linear":
845
+ return Math.min(initial * Math.max(1, attempt), max);
846
+ case "fixed":
847
+ return Math.min(initial, max);
848
+ }
849
+ };
850
+ }
851
+ var MAX_DEQUEUE_BACKOFF_MS = 3e4;
852
+ var MIN_DEQUEUE_BACKOFF_MS = 50;
853
+ function dequeueBackoff(pollIntervalMs) {
854
+ const base = Math.max(pollIntervalMs, MIN_DEQUEUE_BACKOFF_MS);
855
+ return (consecutiveFailures) => Math.min(base * 2 ** (consecutiveFailures - 1), MAX_DEQUEUE_BACKOFF_MS);
856
+ }
857
+ var SNAPSHOT_GONE_DELIVERY_BUDGET = 60;
858
+ var MAX_SNAPSHOT_GONE_BACKOFF_MS = 3e5;
859
+ var snapshotGoneBackoff = (readCount) => Math.min(readCount * readCount * 1e3, MAX_SNAPSHOT_GONE_BACKOFF_MS);
860
+ var defaultSnapshotGonePolicy = (readCount) => readCount > SNAPSHOT_GONE_DELIVERY_BUDGET ? { action: "fail" } : { action: "retry", delayMs: snapshotGoneBackoff(readCount) };
861
+ var reapBackoff = () => 0;
862
+
772
863
  // src/lease-reaper.ts
773
864
  function decideExpiredLeaseAction(args) {
774
865
  const { lease, stepStatus, childActive, now } = args;
@@ -782,58 +873,17 @@ function decideExpiredLeaseAction(args) {
782
873
  return { tag: "skip", reason: "still-live" };
783
874
  }
784
875
  const nextAttempt = lease.attempt + 1;
785
- return { tag: "reap", nextAttempt, backoffMs: reapBackoff() };
876
+ const { runId, stepId, attempt } = lease;
877
+ return {
878
+ tag: "reap",
879
+ fact: Facts.leaseReaped({ runId, stepId, attempt, at: now, reapedAt: now }),
880
+ nextAttempt,
881
+ backoffMs: reapBackoff()
882
+ };
786
883
  }
787
884
  var DEFAULT_REAPER_INTERVAL_MS = 3e4;
788
885
 
789
886
  // src/run-events.ts
790
- function runEventOf(fact) {
791
- switch (fact.kind) {
792
- case "flow.started":
793
- return { type: "flow.started", flowId: fact.flowId };
794
- case "flow.completed":
795
- return { type: "flow.completed", output: fact.output };
796
- case "flow.failed":
797
- return { type: "flow.failed", error: fact.error };
798
- case "flow.canceled":
799
- return fact.cause === "concurrency" ? {
800
- type: "flow.canceled",
801
- cause: "concurrency",
802
- canceledByRunId: fact.canceledByRunId
803
- } : { type: "flow.canceled", cause: fact.cause };
804
- case "step.started":
805
- return {
806
- type: "step.started",
807
- stepId: fact.stepId,
808
- attempt: fact.attempt
809
- };
810
- case "step.completed":
811
- return {
812
- type: "step.completed",
813
- stepId: fact.stepId,
814
- attempt: fact.attempt,
815
- output: fact.output
816
- };
817
- case "step.failed":
818
- return {
819
- type: "step.failed",
820
- stepId: fact.stepId,
821
- attempt: fact.attempt,
822
- error: fact.error
823
- };
824
- case "step.retried":
825
- return {
826
- type: "step.retried",
827
- stepId: fact.stepId,
828
- // Carries the attempt that FAILED; the next one is attempt + 1.
829
- attempt: fact.attempt
830
- };
831
- case "step.skipped":
832
- return { type: "step.skipped", stepId: fact.stepId, reason: fact.reason };
833
- default:
834
- return null;
835
- }
836
- }
837
887
  function isTerminalRunEvent(event) {
838
888
  return event.type === "flow.completed" || event.type === "flow.failed" || event.type === "flow.canceled";
839
889
  }
@@ -878,6 +928,327 @@ function safely(handler, envelope) {
878
928
  }
879
929
  }
880
930
 
931
+ // src/canonicalize.ts
932
+ var warnedAboutSourceHash = false;
933
+ function warnSourceHashOnce() {
934
+ if (warnedAboutSourceHash) return;
935
+ warnedAboutSourceHash = true;
936
+ console.warn(
937
+ "[nagi] canonicalize: hashing `when`/schema source via Function.prototype.toString(). Cosmetic source changes (minification, whitespace, identifier renames) will flip the flow hash even when behavior is unchanged."
938
+ );
939
+ }
940
+ async function canonicalize(flow) {
941
+ const withDefs = asStepMapWithDefs(flow.steps);
942
+ const ids = Object.keys(withDefs).sort();
943
+ const steps = [];
944
+ for (const id of ids) {
945
+ const step = withDefs[id];
946
+ if (step === void 0) continue;
947
+ steps.push(await canonicalizeStep(id, getDef(step)));
948
+ }
949
+ return {
950
+ flowId: flow.id,
951
+ inputSchema: await canonicalizeSchema(flow.input),
952
+ steps
953
+ };
954
+ }
955
+ async function canonicalizeStep(id, def) {
956
+ const needs = [...needsStepIds(def)].sort();
957
+ const base = { id, kind: def.kind, needs };
958
+ switch (def.kind) {
959
+ // Streaming and activity hash like a task: chunks are ephemeral and the
960
+ // tx boundary is execution, not DAG shape. `kind` alone tells them apart.
961
+ case "task":
962
+ case "activity":
963
+ case "streaming":
964
+ return canonicalizeHandler(base, def);
965
+ case "signal":
966
+ return canonicalizeSignal(base, def);
967
+ case "subflow":
968
+ return canonicalizeSubflow(base, def);
969
+ }
970
+ }
971
+ async function applyGuardAndTimeout(out, def) {
972
+ if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
973
+ if (def.timeoutMs !== void 0 && def.timeoutMs !== "unbounded")
974
+ out.timeoutMs = def.timeoutMs;
975
+ }
976
+ async function canonicalizeHandler(base, def) {
977
+ const out = { ...base };
978
+ await applyGuardAndTimeout(out, def);
979
+ if (def.retry !== void 0) out.retry = normalizeRetry(def.retry);
980
+ return out;
981
+ }
982
+ async function canonicalizeSignal(base, def) {
983
+ const out = { ...base };
984
+ await applyGuardAndTimeout(out, def);
985
+ out.signalSchema = await canonicalizeSchema(def.schema);
986
+ if (def.names !== void 0) {
987
+ out.signalNames = [...def.names].sort();
988
+ }
989
+ return out;
990
+ }
991
+ async function canonicalizeSubflow(base, def) {
992
+ const out = { ...base };
993
+ await applyGuardAndTimeout(out, def);
994
+ out.childFlowId = def.childFlowId;
995
+ out.subflowInputHash = await hashFnSource(def.buildInput);
996
+ return out;
997
+ }
998
+ function normalizeRetry(retry) {
999
+ return {
1000
+ maxAttempts: retry.maxAttempts,
1001
+ backoff: retry.backoff,
1002
+ initialDelayMs: retry.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs,
1003
+ maxDelayMs: retry.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs
1004
+ };
1005
+ }
1006
+ async function canonicalizeSchema(schema) {
1007
+ const props = schema["~standard"];
1008
+ return {
1009
+ vendor: props.vendor,
1010
+ version: props.version,
1011
+ validateHash: await hashFnSource(props.validate)
1012
+ };
1013
+ }
1014
+ async function hashFnSource(fn) {
1015
+ warnSourceHashOnce();
1016
+ return sha256Hex(fn.toString());
1017
+ }
1018
+ async function sha256Canonical(dag) {
1019
+ return sha256Hex(stableStringify(dag));
1020
+ }
1021
+ async function fingerprintFlows(flows) {
1022
+ const entries = [];
1023
+ for (const f of flows) {
1024
+ const dag = await canonicalize(f);
1025
+ entries.push([f.id, await sha256Canonical(dag)]);
1026
+ }
1027
+ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1028
+ return sha256Hex(stableStringify(entries));
1029
+ }
1030
+ function stableStringify(value) {
1031
+ if (value === void 0) return "null";
1032
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1033
+ if (Array.isArray(value)) {
1034
+ return `[${value.map(stableStringify).join(",")}]`;
1035
+ }
1036
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1037
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
1038
+ }
1039
+ async function sha256Hex(input) {
1040
+ const bytes = new TextEncoder().encode(input);
1041
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
1042
+ return hex(new Uint8Array(digest));
1043
+ }
1044
+ function hex(bytes) {
1045
+ let s = "";
1046
+ for (let i = 0; i < bytes.length; i++) {
1047
+ s += bytes[i].toString(16).padStart(2, "0");
1048
+ }
1049
+ return s;
1050
+ }
1051
+
1052
+ // src/flows.ts
1053
+ function requireCurrent(resolution) {
1054
+ if (resolution.kind === "current") return resolution.flow;
1055
+ throw resolution.error;
1056
+ }
1057
+ function makeFlowOf(deps) {
1058
+ const { registry, store, emitLog } = deps;
1059
+ return async (runId, drift) => {
1060
+ const resolution = registry.resolve(await store.loadRunState(runId));
1061
+ if (resolution.kind === "current" || drift === "freeze") return resolution;
1062
+ try {
1063
+ return { kind: "current", flow: await registry.synthesize(resolution) };
1064
+ } catch (err) {
1065
+ if (!(err instanceof NagiRuntimeError)) throw err;
1066
+ emitLog({
1067
+ level: "warn",
1068
+ msg: "flowOf: drift synthesis failed \u2014 treating run as snapshot-gone",
1069
+ attrs: {
1070
+ runId: resolution.error.runId,
1071
+ flowId: resolution.error.flowId,
1072
+ pinnedHash: resolution.error.pinnedHash,
1073
+ error: err.message
1074
+ }
1075
+ });
1076
+ return resolution;
1077
+ }
1078
+ };
1079
+ }
1080
+ function pinRun(runId, flow, flowOf) {
1081
+ const pinned = { kind: "current", flow };
1082
+ return async (id) => id === runId ? pinned : flowOf(id);
1083
+ }
1084
+ async function registerFlows(deps) {
1085
+ const { flows, store, clock } = deps;
1086
+ const byId = /* @__PURE__ */ new Map();
1087
+ const hashById = /* @__PURE__ */ new Map();
1088
+ const streamingStepIds = /* @__PURE__ */ new Set();
1089
+ for (const flow of flows) {
1090
+ if (byId.has(flow.id)) {
1091
+ throw new NagiRuntimeError(
1092
+ `Duplicate flow id "${flow.id}" passed to nagi()`
1093
+ );
1094
+ }
1095
+ byId.set(flow.id, flow);
1096
+ for (const [stepId, step] of Object.entries(
1097
+ asStepMapWithDefs(flow.steps)
1098
+ )) {
1099
+ if (getDef(step).kind !== "streaming") continue;
1100
+ if (store.stream === void 0) {
1101
+ throw new NagiRuntimeError(
1102
+ `Flow "${flow.id}" has a streaming step "${stepId}" (b.streamingTask), but the store has no \`stream\` transport \u2014 it cannot carry ephemeral chunks. The in-memory store always exposes one; postgresStore() needs a \`listener\`. Otherwise remove the streaming step.`
1103
+ );
1104
+ }
1105
+ streamingStepIds.add(stepId);
1106
+ }
1107
+ }
1108
+ for (const flow of flows) {
1109
+ const dag = await canonicalize(flow);
1110
+ const flowHash = await sha256Canonical(dag);
1111
+ hashById.set(flow.id, flowHash);
1112
+ await store.upsertSnapshot({
1113
+ flowHash,
1114
+ flowId: flow.id,
1115
+ dag
1116
+ });
1117
+ const previousHash = await store.getRef(flow.id);
1118
+ if (previousHash !== flowHash) {
1119
+ await store.setRef(flow.id, flowHash);
1120
+ await store.appendGlobalFact(
1121
+ Facts.flowRefUpdated({
1122
+ flowId: flow.id,
1123
+ from: previousHash,
1124
+ to: flowHash,
1125
+ at: clock.now()
1126
+ })
1127
+ );
1128
+ }
1129
+ }
1130
+ function require2(flowId) {
1131
+ const flow = byId.get(flowId);
1132
+ if (!flow) {
1133
+ throw new NagiRuntimeError(
1134
+ `Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
1135
+ );
1136
+ }
1137
+ return flow;
1138
+ }
1139
+ function hashOf(flowId) {
1140
+ const hash = hashById.get(flowId);
1141
+ if (hash === void 0) {
1142
+ throw new NagiRuntimeError(
1143
+ `Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
1144
+ );
1145
+ }
1146
+ return hash;
1147
+ }
1148
+ function resolve(state) {
1149
+ const { runId, flowId, flowHash: pinnedHash } = state;
1150
+ const live = byId.get(flowId);
1151
+ if (pinnedHash === void 0) {
1152
+ if (live === void 0) {
1153
+ throw new NagiRuntimeError(
1154
+ `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
1155
+ );
1156
+ }
1157
+ return { kind: "current", flow: live };
1158
+ }
1159
+ const currentHash = live === void 0 ? null : hashOf(flowId);
1160
+ if (live !== void 0 && currentHash === pinnedHash) {
1161
+ return { kind: "current", flow: live };
1162
+ }
1163
+ const error = new NagiFlowSnapshotGoneError({
1164
+ runId,
1165
+ flowId,
1166
+ pinnedHash,
1167
+ currentHash
1168
+ });
1169
+ return isTerminalRun(state) ? { kind: "gone-terminal", error, live } : { kind: "gone-live", error, live };
1170
+ }
1171
+ const synthesizedByHash = /* @__PURE__ */ new Map();
1172
+ function synthesize(gone) {
1173
+ const { pinnedHash } = gone.error;
1174
+ const cached = synthesizedByHash.get(pinnedHash);
1175
+ if (cached !== void 0) return cached;
1176
+ const pending = synthesizeUncached(gone);
1177
+ synthesizedByHash.set(pinnedHash, pending);
1178
+ pending.catch(() => synthesizedByHash.delete(pinnedHash));
1179
+ return pending;
1180
+ }
1181
+ async function synthesizeUncached(gone) {
1182
+ const { runId, flowId, pinnedHash } = gone.error;
1183
+ if (gone.live === void 0) {
1184
+ throw new NagiRuntimeError(
1185
+ `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
1186
+ );
1187
+ }
1188
+ const snapshot = await store.loadSnapshot(pinnedHash);
1189
+ if (snapshot === null) {
1190
+ throw new NagiRuntimeError(
1191
+ `Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Nothing can resume it.`
1192
+ );
1193
+ }
1194
+ return synthesizeReplayFlow(
1195
+ snapshot.dag,
1196
+ gone.live
1197
+ );
1198
+ }
1199
+ return {
1200
+ get: (flowId) => byId.get(flowId),
1201
+ has: (flowId) => byId.has(flowId),
1202
+ require: require2,
1203
+ hashOf,
1204
+ isStreaming: (stepId) => streamingStepIds.has(stepId),
1205
+ resolve,
1206
+ synthesize
1207
+ };
1208
+ }
1209
+ function synthesizeReplayFlow(dag, liveFlow) {
1210
+ const liveSteps = asStepMapWithDefs(liveFlow.steps);
1211
+ const synthesized = {};
1212
+ for (const canonStep of dag.steps) {
1213
+ const liveStep = liveSteps[canonStep.id];
1214
+ if (liveStep === void 0) {
1215
+ throw new NagiRuntimeError(
1216
+ `Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
1217
+ );
1218
+ }
1219
+ synthesized[canonStep.id] = attachDef(
1220
+ { kind: canonStep.kind, id: canonStep.id },
1221
+ getDef(liveStep)
1222
+ );
1223
+ }
1224
+ for (const canonStep of dag.steps) {
1225
+ const shell = synthesized[canonStep.id];
1226
+ if (shell === void 0) continue;
1227
+ const synthesizedNeeds = {};
1228
+ for (const upstreamId of canonStep.needs) {
1229
+ const upstreamShell = synthesized[upstreamId];
1230
+ if (upstreamShell === void 0) {
1231
+ throw new NagiRuntimeError(
1232
+ `Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
1233
+ );
1234
+ }
1235
+ synthesizedNeeds[upstreamId] = upstreamShell;
1236
+ }
1237
+ setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
1238
+ }
1239
+ return {
1240
+ id: liveFlow.id,
1241
+ input: liveFlow.input,
1242
+ steps: synthesized,
1243
+ ...compact({
1244
+ output: liveFlow.output,
1245
+ onStart: liveFlow.onStart,
1246
+ onComplete: liveFlow.onComplete,
1247
+ onError: liveFlow.onError
1248
+ })
1249
+ };
1250
+ }
1251
+
881
1252
  // src/validate.ts
882
1253
  async function validate(schema, value) {
883
1254
  const result = await schema["~standard"].validate(value);
@@ -953,10 +1324,9 @@ function decideTimeout(args) {
953
1324
  };
954
1325
  }
955
1326
  function makeSignals(deps) {
956
- const { dispatcher, store, clock, registry, hooks, flowHooks, emitLog } = deps;
1327
+ const { dispatcher, store, clock, flowOf, hooks, flowHooks, emitLog } = deps;
957
1328
  async function signal(runId, signalName, payload) {
958
- const runState = await store.loadRunState(runId);
959
- const flow = registry.require(runState.flowId);
1329
+ const flow = requireCurrent(await flowOf(runId));
960
1330
  const resolved = resolveSignalStep(flow, signalName);
961
1331
  if (resolved === null) {
962
1332
  throw new NagiRuntimeError(
@@ -1029,59 +1399,6 @@ function resolveSignalStep(flow, signalName) {
1029
1399
  }
1030
1400
 
1031
1401
  // src/store-policy.ts
1032
- var QUERY_RUNS_DEFAULT_LIMIT = 50;
1033
- var QUERY_RUNS_MAX_LIMIT = 500;
1034
- function clampQueryLimit(limit) {
1035
- if (limit === void 0) return QUERY_RUNS_DEFAULT_LIMIT;
1036
- if (!Number.isInteger(limit) || limit < 1) return QUERY_RUNS_DEFAULT_LIMIT;
1037
- return Math.min(limit, QUERY_RUNS_MAX_LIMIT);
1038
- }
1039
- function compareRunOrder(a, b) {
1040
- const t = b.startedAt.getTime() - a.startedAt.getTime();
1041
- if (t !== 0) return t;
1042
- return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
1043
- }
1044
- function isPastCursor(row, cursor) {
1045
- return compareRunOrder(row, cursor) > 0;
1046
- }
1047
- function encodeRunCursor(c) {
1048
- const bytes = new TextEncoder().encode(
1049
- JSON.stringify({ t: c.startedAt.getTime(), r: c.runId })
1050
- );
1051
- let binary = "";
1052
- for (const b of bytes) binary += String.fromCharCode(b);
1053
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1054
- }
1055
- function decodeRunCursor(s) {
1056
- try {
1057
- const binary = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
1058
- const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
1059
- const parsed = JSON.parse(new TextDecoder().decode(bytes));
1060
- if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
1061
- const { t, r } = parsed;
1062
- return { startedAt: new Date(t), runId: r };
1063
- }
1064
- throw new Error("malformed cursor body");
1065
- } catch (err) {
1066
- throw new Error(
1067
- `queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
1068
- );
1069
- }
1070
- }
1071
- function jsonContains(haystack, needle) {
1072
- if (Array.isArray(needle)) {
1073
- if (!Array.isArray(haystack)) return false;
1074
- return needle.every((n) => haystack.some((h) => jsonContains(h, n)));
1075
- }
1076
- if (needle !== null && typeof needle === "object") {
1077
- if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
1078
- return false;
1079
- return Object.entries(needle).every(
1080
- ([k, v]) => k in haystack && jsonContains(haystack[k], v)
1081
- );
1082
- }
1083
- return haystack === needle;
1084
- }
1085
1402
  var DEFAULT_SWEEP_LIMIT = 100;
1086
1403
  function selectExpired(items, args) {
1087
1404
  const nowMs = args.now.getTime();
@@ -1106,35 +1423,29 @@ function selectPruneBatch(candidates, opts) {
1106
1423
  );
1107
1424
  return eligible.slice(0, opts.batchSize).map((e) => e.item);
1108
1425
  }
1109
- var NONE = { tag: "none" };
1110
- var RELEASE_RUN = { tag: "release-run" };
1111
- function factEffects(fact) {
1112
- switch (fact.kind) {
1113
- case "step.completed":
1114
- case "step.reset":
1115
- return { tag: "release-step", stepId: fact.stepId, timer: true };
1116
- case "step.failed":
1117
- case "step.canceled":
1118
- return { tag: "release-step", stepId: fact.stepId, timer: false };
1119
- case "flow.completed":
1120
- case "flow.failed":
1121
- case "flow.canceled":
1122
- return RELEASE_RUN;
1123
- case "flow.started":
1124
- case "step.started":
1125
- case "step.retried":
1126
- case "step.skipped":
1127
- case "step.abort-requested":
1128
- case "signal.received":
1129
- case "signal.buffered":
1130
- case "once.recorded":
1131
- case "match.arm-selected":
1132
- case "lease.reaped":
1133
- return NONE;
1426
+ function admitsRunEnd(status) {
1427
+ return status === "pending" || status === "running";
1428
+ }
1429
+ function supersede(args) {
1430
+ const { start, concurrency } = args;
1431
+ switch (concurrency.mode) {
1432
+ case "cancel-in-progress":
1433
+ return Array.from(args.priors, (runId) => ({
1434
+ runId,
1435
+ fact: Facts.flowCanceledByConcurrency({
1436
+ runId,
1437
+ canceledByRunId: start.runId,
1438
+ concurrencyKey: concurrency.key,
1439
+ at: start.at
1440
+ })
1441
+ }));
1134
1442
  }
1135
1443
  }
1136
1444
 
1137
1445
  // src/stream-hub.ts
1446
+ function isStreamOver(state, stepId) {
1447
+ return isTerminalRun(state) || isStepTerminal(stepStateOf(state, stepId));
1448
+ }
1138
1449
  var STREAM_SUBSCRIBER_BUFFER_CAP = 256;
1139
1450
  var STREAM_REPLAY_BUFFER_CAP = 256;
1140
1451
  function makeWake() {
@@ -1195,81 +1506,100 @@ var Subscriber = class {
1195
1506
  }
1196
1507
  }
1197
1508
  };
1509
+ var STREAM_CLOSED_KEYS_CAP = 1024;
1510
+ var EMPTY_CLOSED_STREAM = {
1511
+ [Symbol.asyncIterator]() {
1512
+ return { next: async () => ({ value: void 0, done: true }) };
1513
+ }
1514
+ };
1198
1515
  var InMemoryStreamHub = class _InMemoryStreamHub {
1516
+ // Open channels only: closing one deletes it and records its key.
1199
1517
  channels = /* @__PURE__ */ new Map();
1518
+ closedKeys = /* @__PURE__ */ new Set();
1200
1519
  static key(runId, stepId) {
1201
1520
  return `${runId}::${stepId}`;
1202
1521
  }
1203
- getOrCreate(runId, stepId) {
1204
- const key = _InMemoryStreamHub.key(runId, stepId);
1522
+ openChannel(key) {
1523
+ if (this.closedKeys.has(key)) return void 0;
1205
1524
  let channel = this.channels.get(key);
1206
1525
  if (channel === void 0) {
1207
- channel = { subscribers: /* @__PURE__ */ new Set(), replay: [], closed: false };
1526
+ channel = { subscribers: /* @__PURE__ */ new Set(), replay: [] };
1208
1527
  this.channels.set(key, channel);
1209
1528
  }
1210
1529
  return channel;
1211
1530
  }
1531
+ // Returns the subscribers to end, or undefined when no channel was open.
1532
+ closeChannel(key) {
1533
+ const channel = this.channels.get(key);
1534
+ if (channel === void 0) return void 0;
1535
+ this.channels.delete(key);
1536
+ this.closedKeys.add(key);
1537
+ if (this.closedKeys.size > STREAM_CLOSED_KEYS_CAP) {
1538
+ const oldest = this.closedKeys.values().next().value;
1539
+ if (oldest !== void 0) this.closedKeys.delete(oldest);
1540
+ }
1541
+ const subs = [...channel.subscribers];
1542
+ channel.subscribers.clear();
1543
+ channel.replay.length = 0;
1544
+ return subs;
1545
+ }
1212
1546
  publishChunk(runId, stepId, chunk) {
1213
- const channel = this.getOrCreate(runId, stepId);
1214
- if (channel.closed) return;
1547
+ const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
1548
+ if (channel === void 0) return;
1215
1549
  const event = { kind: "chunk", chunk };
1216
1550
  channel.replay.push(event);
1217
1551
  if (channel.replay.length > STREAM_REPLAY_BUFFER_CAP)
1218
1552
  channel.replay.shift();
1219
1553
  for (const sub of channel.subscribers) sub.push(event);
1220
1554
  }
1555
+ // NB: signalRetry and the close* methods are no-ops when no channel exists.
1556
+ // Both adapters fire them for EVERY step — Postgres cluster-wide — including
1557
+ // non-streaming ones, so creating a channel here would leak one per step.
1221
1558
  signalRetry(runId, stepId, attempt) {
1222
- const channel = this.getOrCreate(runId, stepId);
1223
- if (channel.closed) return;
1559
+ const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
1560
+ if (channel === void 0) return;
1224
1561
  channel.replay.length = 0;
1225
1562
  const event = { kind: "retry", attempt };
1226
1563
  for (const sub of channel.subscribers) sub.push(event);
1227
1564
  }
1228
- // NB: no-op when no channel exists. InMemoryStore.appendFact fires this for
1229
- // EVERY step.completed — including non-streaming steps that never published —
1230
- // so creating a channel here would leak one per such step. Closed-ness is
1231
- // authoritative in the durable facts, not the hub.
1232
1565
  closeOk(runId, stepId) {
1233
- const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
1234
- if (channel === void 0 || channel.closed) return;
1235
- channel.closed = true;
1236
- channel.replay.length = 0;
1237
- for (const sub of channel.subscribers) sub.close();
1238
- channel.subscribers.clear();
1566
+ const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
1567
+ for (const sub of subs ?? []) sub.close();
1239
1568
  }
1240
1569
  closeError(runId, stepId, error) {
1241
- const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
1242
- if (channel === void 0 || channel.closed) return;
1243
- channel.closed = true;
1244
- channel.replay.length = 0;
1570
+ const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
1245
1571
  const event = { kind: "error", error };
1246
- for (const sub of channel.subscribers) {
1572
+ for (const sub of subs ?? []) {
1247
1573
  sub.push(event);
1248
1574
  sub.close();
1249
1575
  }
1250
- channel.subscribers.clear();
1576
+ }
1577
+ apply(runId, effect) {
1578
+ switch (effect.tag) {
1579
+ case "close-ok":
1580
+ this.closeOk(runId, effect.stepId);
1581
+ return;
1582
+ case "close-error":
1583
+ this.closeError(runId, effect.stepId, effect.error);
1584
+ return;
1585
+ case "retry":
1586
+ this.signalRetry(runId, effect.stepId, effect.nextAttempt);
1587
+ return;
1588
+ case "close-run":
1589
+ this.closeRun(runId);
1590
+ return;
1591
+ }
1251
1592
  }
1252
1593
  closeRun(runId) {
1253
1594
  const prefix = `${runId}::`;
1254
- for (const [key, channel] of this.channels) {
1255
- if (!key.startsWith(prefix) || channel.closed) continue;
1256
- channel.closed = true;
1257
- channel.replay.length = 0;
1258
- for (const sub of channel.subscribers) sub.close();
1259
- channel.subscribers.clear();
1595
+ for (const key of this.channels.keys()) {
1596
+ if (!key.startsWith(prefix)) continue;
1597
+ for (const sub of this.closeChannel(key) ?? []) sub.close();
1260
1598
  }
1261
1599
  }
1262
1600
  subscribeStream(runId, stepId, opts) {
1263
- const channel = this.getOrCreate(runId, stepId);
1264
- if (channel.closed) {
1265
- return {
1266
- [Symbol.asyncIterator]() {
1267
- return {
1268
- next: async () => ({ value: void 0, done: true })
1269
- };
1270
- }
1271
- };
1272
- }
1601
+ const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
1602
+ if (channel === void 0) return EMPTY_CLOSED_STREAM;
1273
1603
  const sub = new Subscriber();
1274
1604
  if (opts?.replayBuffered === true) {
1275
1605
  for (const event of channel.replay) sub.push(event);
@@ -1300,6 +1630,116 @@ var InMemoryStreamHub = class _InMemoryStreamHub {
1300
1630
  }
1301
1631
  };
1302
1632
 
1633
+ // src/read-model.ts
1634
+ var SETTLED = /* @__PURE__ */ new Set([
1635
+ "completed",
1636
+ "failed",
1637
+ "canceled",
1638
+ "skipped"
1639
+ ]);
1640
+ function nextRunRow(prev, delta) {
1641
+ if (delta.row === "step") {
1642
+ return delta.status === "reset" && prev !== void 0 && (prev.status === "completed" || prev.status === "failed") ? {
1643
+ ...prev,
1644
+ status: "running",
1645
+ output: null,
1646
+ error: null,
1647
+ completedAt: null
1648
+ } : prev;
1649
+ }
1650
+ switch (delta.status) {
1651
+ case "running":
1652
+ return prev ?? {
1653
+ flowId: delta.flowId,
1654
+ status: "running",
1655
+ input: delta.input,
1656
+ output: null,
1657
+ error: null,
1658
+ startedAt: delta.startedAt,
1659
+ completedAt: null,
1660
+ flowHash: delta.flowHash,
1661
+ codeVersion: delta.codeVersion,
1662
+ parent: delta.parent,
1663
+ canceledByRunId: null
1664
+ };
1665
+ case "completed":
1666
+ return prev && {
1667
+ ...prev,
1668
+ status: "completed",
1669
+ output: delta.output,
1670
+ error: null,
1671
+ completedAt: delta.completedAt
1672
+ };
1673
+ case "failed":
1674
+ return prev && {
1675
+ ...prev,
1676
+ status: "failed",
1677
+ output: null,
1678
+ error: delta.error,
1679
+ completedAt: delta.completedAt
1680
+ };
1681
+ case "canceled":
1682
+ return prev && {
1683
+ ...prev,
1684
+ status: "canceled",
1685
+ output: null,
1686
+ error: null,
1687
+ canceledByRunId: delta.canceledByRunId,
1688
+ completedAt: delta.completedAt
1689
+ };
1690
+ }
1691
+ }
1692
+ function nextStepRow(prev, delta) {
1693
+ if (delta.status === "reset") return void 0;
1694
+ if (prev !== void 0 && SETTLED.has(prev.status)) return prev;
1695
+ switch (delta.status) {
1696
+ case "running":
1697
+ if (prev !== void 0 && prev.attempt >= delta.attempt) return prev;
1698
+ return {
1699
+ attempt: delta.attempt,
1700
+ status: "running",
1701
+ startedAt: delta.startedAt,
1702
+ completedAt: null,
1703
+ output: null,
1704
+ error: null
1705
+ };
1706
+ case "backoff":
1707
+ if (prev === void 0 || prev.error !== null || prev.attempt !== delta.attempt) {
1708
+ return prev;
1709
+ }
1710
+ return { ...prev, error: delta.error };
1711
+ case "completed":
1712
+ case "failed":
1713
+ case "canceled":
1714
+ if (prev === void 0 || prev.attempt < delta.attempt) return prev;
1715
+ return settle(
1716
+ prev,
1717
+ delta.attempt,
1718
+ delta,
1719
+ delta.status === "completed" ? delta.output : null,
1720
+ delta.status === "completed" ? null : delta.error
1721
+ );
1722
+ case "skipped":
1723
+ return settle(
1724
+ prev,
1725
+ prev?.attempt ?? 0,
1726
+ delta,
1727
+ null,
1728
+ null
1729
+ );
1730
+ }
1731
+ }
1732
+ function settle(prev, attempt, delta, output, error) {
1733
+ return {
1734
+ attempt,
1735
+ status: delta.status,
1736
+ startedAt: prev?.startedAt ?? null,
1737
+ completedAt: delta.completedAt,
1738
+ output,
1739
+ error
1740
+ };
1741
+ }
1742
+
1303
1743
  // src/memory.ts
1304
1744
  function leaseKey(runId, stepId, attempt) {
1305
1745
  return `${runId}::${stepId}::${attempt}`;
@@ -1319,8 +1759,9 @@ var InMemoryStore = class {
1319
1759
  keyByActiveRun = /* @__PURE__ */ new Map();
1320
1760
  // Kept past terminal facts so a reopened run can re-take its slot.
1321
1761
  slotByRun = /* @__PURE__ */ new Map();
1322
- childrenByParent = /* @__PURE__ */ new Map();
1323
- summaries = /* @__PURE__ */ new Map();
1762
+ // The read model (Postgres: workflow_run / step_run), fed only by row deltas.
1763
+ runRows = /* @__PURE__ */ new Map();
1764
+ stepRows = /* @__PURE__ */ new Map();
1324
1765
  streamHub = new InMemoryStreamHub();
1325
1766
  // Durable signal-timeout deadlines (the Postgres `timer` table), distinct
1326
1767
  // from InMemoryClock's setTimeout-based scheduler.
@@ -1330,6 +1771,18 @@ var InMemoryStore = class {
1330
1771
  this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
1331
1772
  }
1332
1773
  async appendFact(runId, fact) {
1774
+ this.writeFact(runId, fact);
1775
+ }
1776
+ async endRun(runId, fact) {
1777
+ return this.writeFact(runId, fact);
1778
+ }
1779
+ // The one fact-write path. Synchronous on purpose: with no await between the
1780
+ // read that led to a write and the write itself, every caller gets the
1781
+ // atomicity the Postgres store takes a transaction for.
1782
+ writeFact(runId, fact) {
1783
+ if (isRunEnd(fact) && !admitsRunEnd(this.runRows.get(runId)?.status)) {
1784
+ return false;
1785
+ }
1333
1786
  const list = this.facts.get(runId) ?? [];
1334
1787
  if (fact.kind === "step.reset") {
1335
1788
  const prior = foldRun(runId, list);
@@ -1351,38 +1804,34 @@ var InMemoryStore = class {
1351
1804
  }
1352
1805
  list.push(fact);
1353
1806
  this.facts.set(runId, list);
1354
- const event = runEventOf(fact);
1807
+ const { rows, release, stream, event } = factConsequences(fact);
1808
+ if (rows !== null) this.applyRows(runId, rows);
1809
+ if (release !== null) this.release(runId, release);
1810
+ if (stream !== null) this.streamHub.apply(runId, stream);
1355
1811
  if (event !== null) this.eventHub.publish({ ...event, runId });
1356
- switch (fact.kind) {
1357
- case "step.completed":
1358
- this.streamHub.closeOk(runId, fact.stepId);
1359
- break;
1360
- case "step.failed":
1361
- this.streamHub.closeError(runId, fact.stepId, fact.error);
1362
- break;
1363
- case "step.retried":
1364
- this.streamHub.signalRetry(
1365
- runId,
1366
- fact.stepId,
1367
- fact.attempt + 1
1368
- );
1369
- break;
1370
- case "flow.completed":
1371
- case "flow.failed":
1372
- case "flow.canceled":
1373
- this.streamHub.closeRun(runId);
1374
- break;
1375
- }
1376
- const effects = factEffects(fact);
1377
- switch (effects.tag) {
1378
- case "none":
1379
- return;
1812
+ return true;
1813
+ }
1814
+ applyRows(runId, delta) {
1815
+ const run = nextRunRow(this.runRows.get(runId), delta);
1816
+ if (run !== void 0) this.runRows.set(runId, run);
1817
+ if (delta.row === "run") return;
1818
+ const steps = this.stepRows.get(runId) ?? /* @__PURE__ */ new Map();
1819
+ const step = nextStepRow(steps.get(delta.stepId), delta);
1820
+ if (step === void 0) steps.delete(delta.stepId);
1821
+ else steps.set(delta.stepId, step);
1822
+ this.stepRows.set(runId, steps);
1823
+ }
1824
+ release(runId, release) {
1825
+ switch (release.tag) {
1380
1826
  case "release-step":
1381
- this.releaseLeases(runId, effects.stepId);
1382
- if (effects.timer) {
1383
- this.signalTimers.delete(timerKey(runId, effects.stepId));
1827
+ this.releaseLeases(runId, release.stepId);
1828
+ if (release.timer) {
1829
+ this.signalTimers.delete(timerKey(runId, release.stepId));
1384
1830
  }
1385
1831
  return;
1832
+ case "release-lease":
1833
+ this.leases.delete(leaseKey(runId, release.stepId, release.attempt));
1834
+ return;
1386
1835
  case "release-run": {
1387
1836
  const slot = this.keyByActiveRun.get(runId);
1388
1837
  if (slot === void 0) return;
@@ -1402,64 +1851,48 @@ var InMemoryStore = class {
1402
1851
  }
1403
1852
  }
1404
1853
  async tryStartRun(runId, fact, concurrency) {
1405
- if (this.runExists(runId)) {
1854
+ if (this.runRows.has(runId)) {
1406
1855
  return { started: false, canceled: [] };
1407
1856
  }
1408
1857
  const canceled = [];
1409
1858
  if (concurrency !== void 0) {
1410
1859
  const slot = `${fact.flowId}::${concurrency.key}`;
1411
- const priorRunId = this.activeByKey.get(slot);
1412
- if (priorRunId !== void 0) {
1413
- const cancelFact = Facts.flowCanceledByConcurrency({
1414
- runId: priorRunId,
1415
- at: fact.at,
1416
- canceledByRunId: runId,
1417
- concurrencyKey: concurrency.key
1418
- });
1419
- await this.appendFact(priorRunId, cancelFact);
1420
- canceled.push({ runId: priorRunId, fact: cancelFact });
1860
+ const prior = this.activeByKey.get(slot);
1861
+ for (const c of supersede({
1862
+ start: fact,
1863
+ concurrency,
1864
+ priors: prior === void 0 ? [] : [prior]
1865
+ })) {
1866
+ if (this.writeFact(c.runId, c.fact)) canceled.push(c);
1421
1867
  }
1422
1868
  this.activeByKey.set(slot, runId);
1423
1869
  this.keyByActiveRun.set(runId, slot);
1424
1870
  this.slotByRun.set(runId, slot);
1425
1871
  }
1426
- this.facts.set(runId, [fact]);
1427
- this.eventHub.publish({ type: "flow.started", flowId: fact.flowId, runId });
1428
- const parentRunId = fact.parent?.runId;
1429
- if (parentRunId !== void 0) {
1430
- const set = this.childrenByParent.get(parentRunId) ?? /* @__PURE__ */ new Set();
1431
- set.add(runId);
1432
- this.childrenByParent.set(parentRunId, set);
1433
- }
1872
+ this.writeFact(runId, fact);
1434
1873
  return { started: true, canceled };
1435
1874
  }
1436
- // In-memory has no real tx; we share the underlying maps with tryStartRun,
1437
- // so the implementation is intentionally a straight delegate. The `tx`
1438
- // parameter is accepted for shape-compat with the Store contract.
1875
+ // No real tx to join: every write here is visible, and announced, the moment
1876
+ // it happens, and nothing the caller does later can roll it back. Events stay
1877
+ // exactly as durable as the facts they report.
1439
1878
  async tryStartRunOnTx(_tx, runId, fact, concurrency) {
1440
1879
  return this.tryStartRun(runId, fact, concurrency);
1441
1880
  }
1442
1881
  async listChildren(parentRunId) {
1443
- const set = this.childrenByParent.get(parentRunId);
1444
- if (set === void 0) return [];
1445
- return Array.from(set);
1882
+ return this.childRows(parentRunId).map(([runId]) => runId);
1883
+ }
1884
+ childRows(parentRunId) {
1885
+ return [...this.runRows].filter(
1886
+ ([, row]) => row.parent?.runId === parentRunId
1887
+ );
1446
1888
  }
1447
1889
  // Does a non-terminal child exist for this (parentRunId, stepId)? Used by the
1448
1890
  // reaper to leave a subflow step parked while its child still runs (instead
1449
- // of re-dispatching it at attempt+1). childrenByParent is keyed by parent run
1450
- // only, so filter on the child's parent.stepId.
1891
+ // of re-dispatching it at attempt+1).
1451
1892
  hasActiveChild(parentRunId, parentStepId) {
1452
- const childIds = this.childrenByParent.get(parentRunId);
1453
- if (childIds === void 0) return false;
1454
- for (const childId of childIds) {
1455
- const factList = this.facts.get(childId);
1456
- if (factList === void 0) continue;
1457
- const child = foldRun(childId, factList);
1458
- if (child.parent?.stepId === parentStepId && !isTerminalRun(child)) {
1459
- return true;
1460
- }
1461
- }
1462
- return false;
1893
+ return this.childRows(parentRunId).some(
1894
+ ([, row]) => row.parent?.stepId === parentStepId && (row.status === "pending" || row.status === "running")
1895
+ );
1463
1896
  }
1464
1897
  async loadRunState(runId) {
1465
1898
  return foldRun(runId, this.facts.get(runId) ?? []);
@@ -1497,9 +1930,7 @@ var InMemoryStore = class {
1497
1930
  });
1498
1931
  for (const lease of candidates) {
1499
1932
  const { runId, stepId, attempt } = lease;
1500
- const factList = this.facts.get(runId);
1501
- const state = factList ? foldRun(runId, factList) : null;
1502
- const stepStatus = state ? stepStatusOf(stepStateOf(state, stepId)) : "pending";
1933
+ const flowId = this.runRows.get(runId)?.flowId;
1503
1934
  const decision = decideExpiredLeaseAction({
1504
1935
  lease: {
1505
1936
  runId,
@@ -1507,21 +1938,24 @@ var InMemoryStore = class {
1507
1938
  attempt,
1508
1939
  expiresAt: new Date(lease.expiresAt)
1509
1940
  },
1510
- stepStatus,
1941
+ stepStatus: this.stepRows.get(runId)?.get(stepId)?.status ?? "pending",
1511
1942
  childActive: this.hasActiveChild(runId, stepId),
1512
1943
  now
1513
1944
  });
1514
1945
  if (decision.tag === "skip") continue;
1515
- this.leases.delete(leaseKey(runId, stepId, attempt));
1516
- await this.appendFact(
1517
- runId,
1518
- Facts.leaseReaped({ runId, stepId, attempt, at: now, reapedAt: now })
1519
- );
1520
- await queue.enqueue(runId, stepId, {
1521
- attempt: decision.nextAttempt,
1522
- delayMs: decision.backoffMs,
1523
- ...state?.flowId !== void 0 ? { flowId: state.flowId } : {}
1524
- });
1946
+ const key = leaseKey(runId, stepId, attempt);
1947
+ this.leases.delete(key);
1948
+ try {
1949
+ await queue.enqueue(runId, stepId, {
1950
+ attempt: decision.nextAttempt,
1951
+ delayMs: decision.backoffMs,
1952
+ ...flowId !== void 0 ? { flowId } : {}
1953
+ });
1954
+ } catch (err) {
1955
+ this.leases.set(key, lease);
1956
+ throw err;
1957
+ }
1958
+ this.writeFact(runId, decision.fact);
1525
1959
  reaped.push({
1526
1960
  runId,
1527
1961
  stepId,
@@ -1531,9 +1965,6 @@ var InMemoryStore = class {
1531
1965
  }
1532
1966
  return reaped;
1533
1967
  }
1534
- async settleStep(runId, _stepId, fact) {
1535
- await this.appendFact(runId, fact);
1536
- }
1537
1968
  async settleSignal(args) {
1538
1969
  const { runId, stepId, at, incoming } = args;
1539
1970
  const runState = foldRun(runId, this.facts.get(runId) ?? []);
@@ -1542,11 +1973,11 @@ var InMemoryStore = class {
1542
1973
  case "noop":
1543
1974
  return decision.result;
1544
1975
  case "buffer":
1545
- if (decision.fact !== null) await this.appendFact(runId, decision.fact);
1976
+ if (decision.fact !== null) this.writeFact(runId, decision.fact);
1546
1977
  return decision.result;
1547
1978
  case "deliver":
1548
- await this.appendFact(runId, decision.received);
1549
- await this.appendFact(runId, decision.completed);
1979
+ this.writeFact(runId, decision.received);
1980
+ this.writeFact(runId, decision.completed);
1550
1981
  return decision.result;
1551
1982
  }
1552
1983
  }
@@ -1569,7 +2000,7 @@ var InMemoryStore = class {
1569
2000
  const decision = decideTimeout({ runState, stepId, fireAt, at: now });
1570
2001
  this.signalTimers.delete(timerKey(runId, stepId));
1571
2002
  if (decision.kind === "noop") continue;
1572
- await this.appendFact(runId, decision.fact);
2003
+ this.writeFact(runId, decision.fact);
1573
2004
  timedOut.push({ runId, stepId, attempt: decision.attempt, fireAt });
1574
2005
  }
1575
2006
  return timedOut;
@@ -1579,11 +2010,12 @@ var InMemoryStore = class {
1579
2010
  if (!this.onces.has(key)) this.onces.set(key, value);
1580
2011
  }
1581
2012
  async getOnce(runId, stepId, scope) {
1582
- return this.onces.get(`${runId}::${stepId}::${scope}`) ?? null;
2013
+ const value = this.onces.get(`${runId}::${stepId}::${scope}`);
2014
+ return value === void 0 ? { tag: "miss" } : { tag: "hit", value };
1583
2015
  }
1584
2016
  async runStep(runId, _stepId, _attempt, body) {
1585
2017
  const result = await body(void 0);
1586
- await this.appendFact(runId, result.fact);
2018
+ this.writeFact(runId, result.fact);
1587
2019
  return result.output;
1588
2020
  }
1589
2021
  async upsertSnapshot(args) {
@@ -1605,165 +2037,44 @@ var InMemoryStore = class {
1605
2037
  readGlobalFacts() {
1606
2038
  return this.globalFacts;
1607
2039
  }
1608
- async queryRuns(opts) {
1609
- const where = opts.where ?? {};
1610
- const wanted = where.status && new Set(where.status);
1611
- const matches = (summary) => (where.flowId === void 0 || summary.flowId === where.flowId) && (!wanted || wanted.has(summary.status)) && (where.input === void 0 || jsonContains(summary.input, where.input));
1612
- const summaries = [];
1613
- for (const [runId, factList] of this.facts) {
1614
- const summary = summarize(runId, factList);
1615
- if (summary === null) continue;
1616
- if (matches(summary)) summaries.push(summary);
1617
- }
1618
- for (const summary of this.summaries.values()) {
1619
- if (matches(summary)) summaries.push(summary);
1620
- }
1621
- summaries.sort(compareRunOrder);
1622
- if (opts.latest === true) {
1623
- return { runs: summaries.slice(0, 1), cursor: null };
1624
- }
1625
- const limit = clampQueryLimit(opts.limit);
1626
- const cursor = opts.cursor === void 0 ? null : decodeRunCursor(opts.cursor);
1627
- const rest = cursor === null ? summaries : summaries.filter((s) => isPastCursor(s, cursor));
1628
- const page = rest.slice(0, limit);
1629
- const last = page[page.length - 1];
1630
- const next = rest.length > limit && last !== void 0 ? encodeRunCursor({ startedAt: last.startedAt, runId: last.runId }) : null;
1631
- return { runs: page, cursor: next };
1632
- }
1633
2040
  async describe(runId) {
1634
- const factList = this.facts.get(runId);
1635
- if (factList === void 0 || factList.length === 0) {
1636
- return this.describeSummary(runId);
1637
- }
1638
- const first = factList[0];
1639
- if (first === void 0 || first.kind !== "flow.started") return null;
1640
- const state = foldRun(runId, factList);
1641
- const status = runStatusOf(state);
1642
- let completedAt;
1643
- let output;
1644
- let error;
1645
- let canceledByRunId;
1646
- let concurrencyKey;
1647
- for (let i = isTerminalRun(state) ? factList.length - 1 : -1; i >= 0; i--) {
1648
- const f = factList[i];
1649
- if (f === void 0) continue;
1650
- if (f.kind === "flow.completed") {
1651
- completedAt = f.at;
1652
- output = f.output;
1653
- break;
1654
- }
1655
- if (f.kind === "flow.failed") {
1656
- completedAt = f.at;
1657
- error = f.error;
1658
- break;
1659
- }
1660
- if (f.kind === "flow.canceled") {
1661
- completedAt = f.at;
1662
- if (f.cause === "concurrency" && this.runExists(f.canceledByRunId)) {
1663
- canceledByRunId = f.canceledByRunId;
1664
- }
1665
- break;
1666
- }
1667
- }
1668
- const slot = this.keyByActiveRun.get(runId);
1669
- if (slot !== void 0) {
1670
- const sep = slot.indexOf("::");
1671
- if (sep >= 0) concurrencyKey = slot.slice(sep + 2);
1672
- }
1673
- if (concurrencyKey === void 0) {
1674
- for (const f of factList) {
1675
- if (f.kind === "flow.canceled" && f.cause === "concurrency") {
1676
- concurrencyKey = f.concurrencyKey;
1677
- break;
1678
- }
1679
- }
1680
- }
1681
- const childSet = this.childrenByParent.get(runId);
1682
- const children = childSet ? Array.from(childSet) : [];
1683
- const parent = first.parent;
1684
- const run = {
1685
- runId,
1686
- flowId: first.flowId,
1687
- flowHash: first.flowHash ?? "",
1688
- status,
1689
- startedAt: first.at,
1690
- input: first.input,
1691
- children,
1692
- ...completedAt !== void 0 ? { completedAt } : {},
1693
- ...output !== void 0 ? { output } : {},
1694
- ...error !== void 0 ? { error } : {},
1695
- ...canceledByRunId !== void 0 ? { canceledByRunId } : {},
1696
- ...concurrencyKey !== void 0 ? { concurrencyKey } : {},
1697
- ...parent !== void 0 ? { parent } : {}
1698
- };
1699
- const steps = [];
1700
- const startedAtByStep = /* @__PURE__ */ new Map();
1701
- const completedAtByStep = /* @__PURE__ */ new Map();
1702
- for (const f of factList) {
1703
- if (f.kind === "step.started" && !startedAtByStep.has(f.stepId)) {
1704
- startedAtByStep.set(f.stepId, f.at);
1705
- }
1706
- if ((f.kind === "step.completed" || f.kind === "step.failed" || f.kind === "step.canceled" || f.kind === "step.skipped") && !completedAtByStep.has(f.stepId)) {
1707
- completedAtByStep.set(f.stepId, f.at);
1708
- }
1709
- }
1710
- const now = Date.now();
1711
- for (const [stepId, stepState] of Object.entries(state.steps)) {
1712
- const status2 = stepStatusOf(stepState);
1713
- const attempt = attemptOf(stepState);
1714
- const out = outputOf(stepState);
1715
- const err = errorOf(stepState);
1716
- const startedAt = startedAtByStep.get(stepId);
1717
- const completedAt2 = completedAtByStep.get(stepId);
1718
- let lease;
1719
- let bestExpiry = 0;
1720
- for (const l of this.leases.values()) {
1721
- if (l.runId !== runId || l.stepId !== stepId) continue;
1722
- if (l.expiresAt > now && l.expiresAt > bestExpiry) {
1723
- bestExpiry = l.expiresAt;
1724
- }
1725
- }
1726
- if (bestExpiry > 0) lease = { expiresAt: new Date(bestExpiry) };
1727
- steps.push({
1728
- stepId,
1729
- attempt,
1730
- status: status2,
1731
- ...startedAt !== void 0 ? { startedAt } : {},
1732
- ...completedAt2 !== void 0 ? { completedAt: completedAt2 } : {},
1733
- ...out !== null ? { output: out } : {},
1734
- ...err !== void 0 ? { error: err } : {},
1735
- ...lease !== void 0 ? { lease } : {}
1736
- });
1737
- }
1738
- steps.sort((a, b) => {
1739
- const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
1740
- const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
1741
- if (ta !== tb) return ta - tb;
1742
- return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
1743
- });
1744
- return { run, steps };
1745
- }
1746
- // A run pruned with keepSummary keeps its row in Postgres; the summary is
1747
- // the in-memory equivalent, so describe() stays non-null for it.
1748
- runExists(runId) {
1749
- return this.facts.has(runId) || this.summaries.has(runId);
1750
- }
1751
- describeSummary(runId) {
1752
- const s = this.summaries.get(runId);
1753
- if (s === void 0) return null;
1754
- const childSet = this.childrenByParent.get(runId);
2041
+ const row = this.runRows.get(runId);
2042
+ if (row === void 0) return null;
2043
+ const slot = this.slotByRun.get(runId);
2044
+ const children = this.childRows(runId).sort(([, a], [, b]) => a.startedAt.getTime() - b.startedAt.getTime()).map(([childId]) => childId);
2045
+ const steps = [...this.stepRows.get(runId) ?? []].map(([stepId, step]) => this.stepView(runId, stepId, step)).sort(compareStepOrder);
1755
2046
  return {
1756
2047
  run: {
1757
2048
  runId,
1758
- flowId: s.flowId,
1759
- flowHash: "",
1760
- status: s.status,
1761
- startedAt: s.startedAt,
1762
- input: s.input,
1763
- children: childSet ? Array.from(childSet) : [],
1764
- ...s.completedAt !== null ? { completedAt: s.completedAt } : {}
2049
+ flowId: row.flowId,
2050
+ flowHash: row.flowHash ?? "",
2051
+ status: row.status,
2052
+ startedAt: row.startedAt,
2053
+ input: row.input,
2054
+ children,
2055
+ ...row.completedAt !== null ? { completedAt: row.completedAt } : {},
2056
+ ...row.output !== null ? { output: row.output } : {},
2057
+ ...row.error !== null ? { error: row.error } : {},
2058
+ // Postgres: ON DELETE SET NULL — the view never names a pruned run.
2059
+ ...row.canceledByRunId !== null && this.runRows.has(row.canceledByRunId) ? { canceledByRunId: row.canceledByRunId } : {},
2060
+ ...slot !== void 0 ? { concurrencyKey: slot.slice(row.flowId.length + 2) } : {},
2061
+ ...row.parent !== null ? { parent: row.parent } : {}
1765
2062
  },
1766
- steps: []
2063
+ steps
2064
+ };
2065
+ }
2066
+ stepView(runId, stepId, row) {
2067
+ const lease = this.leases.get(leaseKey(runId, stepId, row.attempt));
2068
+ const live = lease !== void 0 && lease.expiresAt > Date.now();
2069
+ return {
2070
+ stepId,
2071
+ attempt: row.attempt,
2072
+ status: row.status,
2073
+ ...row.startedAt !== null ? { startedAt: row.startedAt } : {},
2074
+ ...row.completedAt !== null ? { completedAt: row.completedAt } : {},
2075
+ ...row.output !== null ? { output: row.output } : {},
2076
+ ...row.error !== null ? { error: row.error } : {},
2077
+ ...live ? { lease: { expiresAt: new Date(lease.expiresAt) } } : {}
1767
2078
  };
1768
2079
  }
1769
2080
  async pruneFacts(opts) {
@@ -1772,24 +2083,15 @@ var InMemoryStore = class {
1772
2083
  for (; ; ) {
1773
2084
  const batch = selectPruneBatch(this.pruneCandidates(), opts);
1774
2085
  if (batch.length === 0) break;
1775
- for (const { factCount, parentRunId, ...summary } of batch) {
1776
- const runId = summary.runId;
2086
+ for (const { runId, factCount } of batch) {
1777
2087
  this.facts.delete(runId);
2088
+ this.stepRows.delete(runId);
1778
2089
  deleteByRunPrefix(this.onces, runId);
1779
2090
  deleteByRunPrefix(this.leases, runId);
1780
2091
  deleteByRunPrefix(this.signalTimers, runId);
1781
- this.childrenByParent.delete(runId);
1782
- if (parentRunId !== void 0) {
1783
- const siblings = this.childrenByParent.get(parentRunId);
1784
- if (siblings !== void 0) {
1785
- siblings.delete(runId);
1786
- if (siblings.size === 0) this.childrenByParent.delete(parentRunId);
1787
- }
1788
- }
1789
- if (opts.keepSummary) {
1790
- this.summaries.set(runId, summary);
1791
- } else {
1792
- this.summaries.delete(runId);
2092
+ if (!opts.keepSummary) {
2093
+ this.runRows.delete(runId);
2094
+ this.slotByRun.delete(runId);
1793
2095
  }
1794
2096
  runsPruned += 1;
1795
2097
  factsPruned += factCount;
@@ -1799,12 +2101,15 @@ var InMemoryStore = class {
1799
2101
  }
1800
2102
  pruneCandidates() {
1801
2103
  const out = [];
1802
- for (const [runId, factList] of this.facts) {
1803
- const summary = summarize(runId, factList);
1804
- if (summary === null) continue;
1805
- const first = factList[0];
1806
- const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parent?.runId : void 0;
1807
- out.push({ ...summary, factCount: factList.length, parentRunId });
2104
+ for (const [runId, row] of this.runRows) {
2105
+ const factList = this.facts.get(runId);
2106
+ if (factList === void 0) continue;
2107
+ out.push({
2108
+ runId,
2109
+ status: row.status,
2110
+ completedAt: row.completedAt,
2111
+ factCount: factList.length
2112
+ });
1808
2113
  }
1809
2114
  return out;
1810
2115
  }
@@ -1815,11 +2120,8 @@ var InMemoryStore = class {
1815
2120
  };
1816
2121
  stream = {
1817
2122
  subscribeStream: (runId, stepId, opts) => {
1818
- const state = foldRun(runId, this.facts.get(runId) ?? []);
1819
- const stepStatus = stepStatusOf(stepStateOf(state, stepId));
1820
- const runIsTerminal = isTerminalRun(state);
1821
- if (runIsTerminal || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
1822
- return EMPTY_CLOSED_STREAM;
2123
+ if (isStreamOver(foldRun(runId, this.facts.get(runId) ?? []), stepId)) {
2124
+ return EMPTY_CLOSED_STREAM2;
1823
2125
  }
1824
2126
  return this.streamHub.subscribeStream(runId, stepId, opts);
1825
2127
  },
@@ -1828,7 +2130,13 @@ var InMemoryStore = class {
1828
2130
  }
1829
2131
  };
1830
2132
  };
1831
- var EMPTY_CLOSED_STREAM = {
2133
+ function compareStepOrder(a, b) {
2134
+ const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
2135
+ const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
2136
+ if (ta !== tb) return ta - tb;
2137
+ return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
2138
+ }
2139
+ var EMPTY_CLOSED_STREAM2 = {
1832
2140
  [Symbol.asyncIterator]() {
1833
2141
  return { next: async () => ({ value: void 0, done: true }) };
1834
2142
  }
@@ -1839,28 +2147,6 @@ function deleteByRunPrefix(map, runId) {
1839
2147
  if (key.startsWith(prefix)) map.delete(key);
1840
2148
  }
1841
2149
  }
1842
- function summarize(runId, facts) {
1843
- const first = facts[0];
1844
- if (first === void 0 || first.kind !== "flow.started") return null;
1845
- const projected = foldRun(runId, facts);
1846
- let completedAt = null;
1847
- for (let i = isTerminalRun(projected) ? facts.length - 1 : -1; i >= 0; i--) {
1848
- const f = facts[i];
1849
- if (f === void 0) continue;
1850
- if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
1851
- completedAt = f.at;
1852
- break;
1853
- }
1854
- }
1855
- return {
1856
- runId,
1857
- flowId: first.flowId,
1858
- status: runStatusOf(projected),
1859
- startedAt: first.at,
1860
- completedAt,
1861
- input: first.input
1862
- };
1863
- }
1864
2150
  var DEFAULT_QUEUE_LEASE_MS = 6e4;
1865
2151
  var InMemoryQueue = class {
1866
2152
  pending = [];
@@ -1953,6 +2239,6 @@ var InMemoryClock = class {
1953
2239
  }
1954
2240
  };
1955
2241
 
1956
- export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_RETRY, DEFAULT_SWEEP_LIMIT, Facts, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, QUERY_RUNS_DEFAULT_LIMIT, QUERY_RUNS_MAX_LIMIT, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, asStepMapWithDefs, attachDef, attemptOf, clampQueryLimit, compact, compareRunOrder, decideExpiredLeaseAction, decideSignal, decideTimeout, decodeRunCursor, defaultSnapshotGonePolicy, dequeueBackoff, encodeRunCursor, errorOf, factEffects, foldRun, getDef, handlerDef, isAbortRequested, isPastCursor, isStepTerminal, isTerminalRun, isTerminalRunEvent, jsonContains, makeEmit, makeSignals, needsStepIds, normalizeNeeds, outputOf, peekDef, resolveNeeds, resolveRetry, resolvedOf, rowDeltaOf, runEventOf, runStatusOf, selectArm, selectExpired, selectPruneBatch, serializeError, setDef, stepBackoff, stepStateOf, stepStatusOf, unwrap, validate, validationError };
1957
- //# sourceMappingURL=chunk-VU2LG4VW.js.map
1958
- //# sourceMappingURL=chunk-VU2LG4VW.js.map
2242
+ export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, Facts, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, admitsRunEnd, asStepMapWithDefs, attachDef, attemptOf, compact, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, dequeueBackoff, errorOf, factConsequences, fingerprintFlows, foldRun, getDef, handlerDef, isAbortRequested, isRunEnd, isStepTerminal, isStreamOver, isTerminalRun, isTerminalRunEvent, makeEmit, makeFlowOf, makeSignals, needsStepIds, normalizeNeeds, outputOf, peekDef, pinRun, registerFlows, requireCurrent, resolveNeeds, resolveRetry, resolvedOf, runCancelCause, runStatusOf, selectExpired, selectPruneBatch, serializeError, stepBackoff, stepStateOf, stepStatusOf, supersede, unwrap, validate, validationError };
2243
+ //# sourceMappingURL=chunk-DPTPJZEG.js.map
2244
+ //# sourceMappingURL=chunk-DPTPJZEG.js.map