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

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,21 @@ 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
+ }
615
608
  var stepKinds = {
616
609
  "step.started": {
617
610
  fold: (draft, fact) => foldStep(
618
611
  draft,
619
612
  fact.stepId,
620
- (prev) => prev.tag === "pending" || prev.tag === "backoff" ? startTarget(fact.stepKind, fact.attempt) : prev
613
+ (prev) => !isStepTerminal(prev) && fact.attempt > attemptOf(prev) ? startTarget(fact.stepKind, fact.attempt) : prev
621
614
  ),
622
615
  rows: (fact) => ({
623
616
  row: "step",
@@ -625,6 +618,13 @@ var stepKinds = {
625
618
  stepId: fact.stepId,
626
619
  attempt: fact.attempt,
627
620
  startedAt: fact.at
621
+ }),
622
+ release: null,
623
+ stream: null,
624
+ event: (fact) => ({
625
+ type: "step.started",
626
+ stepId: fact.stepId,
627
+ attempt: fact.attempt
628
628
  })
629
629
  },
630
630
  "step.completed": {
@@ -638,6 +638,15 @@ var stepKinds = {
638
638
  status: "completed",
639
639
  stepId: fact.stepId,
640
640
  attempt: fact.attempt,
641
+ output: fact.output,
642
+ completedAt: fact.at
643
+ }),
644
+ release: (fact) => releaseStep(fact.stepId, true),
645
+ stream: (fact) => ({ tag: "close-ok", stepId: fact.stepId }),
646
+ event: (fact) => ({
647
+ type: "step.completed",
648
+ stepId: fact.stepId,
649
+ attempt: fact.attempt,
641
650
  output: fact.output
642
651
  })
643
652
  },
@@ -652,6 +661,20 @@ var stepKinds = {
652
661
  status: "failed",
653
662
  stepId: fact.stepId,
654
663
  attempt: fact.attempt,
664
+ error: fact.error,
665
+ completedAt: fact.at
666
+ }),
667
+ release: (fact) => releaseStep(fact.stepId, false),
668
+ // Only written on terminal failure (retries use step.retried).
669
+ stream: (fact) => ({
670
+ tag: "close-error",
671
+ stepId: fact.stepId,
672
+ error: fact.error
673
+ }),
674
+ event: (fact) => ({
675
+ type: "step.failed",
676
+ stepId: fact.stepId,
677
+ attempt: fact.attempt,
655
678
  error: fact.error
656
679
  })
657
680
  },
@@ -666,65 +689,88 @@ var stepKinds = {
666
689
  status: "canceled",
667
690
  stepId: fact.stepId,
668
691
  attempt: fact.attempt,
669
- error: fact.error ?? null
670
- })
692
+ error: fact.error ?? null,
693
+ completedAt: fact.at
694
+ }),
695
+ release: (fact) => releaseStep(fact.stepId, false),
696
+ stream: null,
697
+ event: null
671
698
  },
672
699
  "step.retried": {
673
700
  fold: (draft, fact) => foldStep(
674
701
  draft,
675
702
  fact.stepId,
676
- (prev) => prev.tag === "running" ? {
703
+ (prev) => inFlight(prev, fact.attempt) ? {
677
704
  tag: "backoff",
678
705
  failedAttempt: fact.attempt,
679
706
  retryAt: fact.nextAttemptAt,
680
707
  error: fact.error
681
708
  } : prev
682
709
  ),
683
- rows: null
710
+ rows: (fact) => ({
711
+ row: "step",
712
+ status: "backoff",
713
+ stepId: fact.stepId,
714
+ attempt: fact.attempt,
715
+ error: fact.error
716
+ }),
717
+ release: null,
718
+ stream: (fact) => ({
719
+ tag: "retry",
720
+ stepId: fact.stepId,
721
+ nextAttempt: fact.attempt + 1
722
+ }),
723
+ // Carries the attempt that FAILED; the next one is attempt + 1.
724
+ event: (fact) => ({
725
+ type: "step.retried",
726
+ stepId: fact.stepId,
727
+ attempt: fact.attempt
728
+ })
684
729
  },
685
730
  "step.skipped": {
686
- // An operator may skip an in-flight step, not just a pending one.
687
731
  fold: (draft, fact) => foldStep(
688
732
  draft,
689
733
  fact.stepId,
690
734
  (prev) => isStepTerminal(prev) ? prev : { tag: "skipped", reason: fact.reason }
691
735
  ),
692
- rows: (fact) => ({ row: "step", status: "skipped", stepId: fact.stepId })
736
+ rows: (fact) => ({
737
+ row: "step",
738
+ status: "skipped",
739
+ stepId: fact.stepId,
740
+ completedAt: fact.at
741
+ }),
742
+ release: null,
743
+ stream: null,
744
+ event: (fact) => ({
745
+ type: "step.skipped",
746
+ stepId: fact.stepId,
747
+ reason: fact.reason
748
+ })
693
749
  },
694
750
  "step.reset": {
695
751
  fold: (draft, fact) => {
696
752
  draft.steps[fact.stepId] = PENDING;
697
- delete draft.selectedArms[fact.stepId];
753
+ draft.resetCounts[fact.stepId] = (draft.resetCounts[fact.stepId] ?? 0) + 1;
698
754
  delete draft.bufferedSignals[fact.stepId];
699
755
  if (draft.phase.tag === "completed" || draft.phase.tag === "failed") {
700
756
  draft.phase = { tag: "running" };
701
757
  }
702
758
  },
703
- rows: (fact) => ({ row: "step", status: "reset", stepId: fact.stepId })
759
+ rows: (fact) => ({ row: "step", status: "reset", stepId: fact.stepId }),
760
+ release: (fact) => releaseStep(fact.stepId, true),
761
+ stream: null,
762
+ event: null
704
763
  },
705
764
  "step.abort-requested": {
706
765
  fold: (draft, fact) => foldStep(
707
766
  draft,
708
767
  fact.stepId,
709
- (prev) => prev.tag === "running" || prev.tag === "awaitingSignal" || prev.tag === "awaitingChild" ? { tag: "aborting", attempt: fact.attempt } : prev
768
+ (prev) => inFlight(prev, fact.attempt) && prev.tag !== "aborting" ? { tag: "aborting", attempt: fact.attempt } : prev
710
769
  ),
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
- })
770
+ rows: null,
771
+ release: null,
772
+ stream: null,
773
+ event: null
728
774
  }
729
775
  };
730
776
 
@@ -753,8 +799,8 @@ function foldRun(runId, facts) {
753
799
  flowHash: void 0,
754
800
  codeVersion: void 0,
755
801
  steps: {},
756
- selectedArms: {},
757
- bufferedSignals: {}
802
+ bufferedSignals: {},
803
+ resetCounts: {}
758
804
  };
759
805
  for (const fact of facts) armOf(fact.kind)?.fold(draft, fact);
760
806
  const { parent, flowHash, codeVersion, ...projected } = draft;
@@ -765,10 +811,52 @@ function foldRun(runId, facts) {
765
811
  ...compact({ parent, flowHash, codeVersion })
766
812
  };
767
813
  }
768
- function rowDeltaOf(fact) {
769
- return armOf(fact.kind)?.rows?.(fact) ?? null;
814
+ function factConsequences(fact) {
815
+ const arm = armOf(fact.kind);
816
+ return {
817
+ rows: arm?.rows?.(fact) ?? null,
818
+ release: arm?.release?.(fact) ?? null,
819
+ stream: arm?.stream?.(fact) ?? null,
820
+ event: arm?.event?.(fact) ?? null
821
+ };
770
822
  }
771
823
 
824
+ // src/retry.ts
825
+ var DEFAULT_RETRY = {
826
+ maxAttempts: 3,
827
+ backoff: "exponential",
828
+ initialDelayMs: 1e3,
829
+ maxDelayMs: 6e4
830
+ };
831
+ function resolveRetry(handlerPolicy, runtimeDefault) {
832
+ return handlerPolicy ?? runtimeDefault ?? DEFAULT_RETRY;
833
+ }
834
+ function stepBackoff(policy) {
835
+ const initial = policy.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs;
836
+ const max = policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs;
837
+ return (attempt) => {
838
+ switch (policy.backoff) {
839
+ case "exponential":
840
+ return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
841
+ case "linear":
842
+ return Math.min(initial * Math.max(1, attempt), max);
843
+ case "fixed":
844
+ return Math.min(initial, max);
845
+ }
846
+ };
847
+ }
848
+ var MAX_DEQUEUE_BACKOFF_MS = 3e4;
849
+ var MIN_DEQUEUE_BACKOFF_MS = 50;
850
+ function dequeueBackoff(pollIntervalMs) {
851
+ const base = Math.max(pollIntervalMs, MIN_DEQUEUE_BACKOFF_MS);
852
+ return (consecutiveFailures) => Math.min(base * 2 ** (consecutiveFailures - 1), MAX_DEQUEUE_BACKOFF_MS);
853
+ }
854
+ var SNAPSHOT_GONE_DELIVERY_BUDGET = 60;
855
+ var MAX_SNAPSHOT_GONE_BACKOFF_MS = 3e5;
856
+ var snapshotGoneBackoff = (readCount) => Math.min(readCount * readCount * 1e3, MAX_SNAPSHOT_GONE_BACKOFF_MS);
857
+ var defaultSnapshotGonePolicy = (readCount) => readCount > SNAPSHOT_GONE_DELIVERY_BUDGET ? { action: "fail" } : { action: "retry", delayMs: snapshotGoneBackoff(readCount) };
858
+ var reapBackoff = () => 0;
859
+
772
860
  // src/lease-reaper.ts
773
861
  function decideExpiredLeaseAction(args) {
774
862
  const { lease, stepStatus, childActive, now } = args;
@@ -782,58 +870,17 @@ function decideExpiredLeaseAction(args) {
782
870
  return { tag: "skip", reason: "still-live" };
783
871
  }
784
872
  const nextAttempt = lease.attempt + 1;
785
- return { tag: "reap", nextAttempt, backoffMs: reapBackoff() };
873
+ const { runId, stepId, attempt } = lease;
874
+ return {
875
+ tag: "reap",
876
+ fact: Facts.leaseReaped({ runId, stepId, attempt, at: now, reapedAt: now }),
877
+ nextAttempt,
878
+ backoffMs: reapBackoff()
879
+ };
786
880
  }
787
881
  var DEFAULT_REAPER_INTERVAL_MS = 3e4;
788
882
 
789
883
  // 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
884
  function isTerminalRunEvent(event) {
838
885
  return event.type === "flow.completed" || event.type === "flow.failed" || event.type === "flow.canceled";
839
886
  }
@@ -878,6 +925,327 @@ function safely(handler, envelope) {
878
925
  }
879
926
  }
880
927
 
928
+ // src/canonicalize.ts
929
+ var warnedAboutSourceHash = false;
930
+ function warnSourceHashOnce() {
931
+ if (warnedAboutSourceHash) return;
932
+ warnedAboutSourceHash = true;
933
+ console.warn(
934
+ "[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."
935
+ );
936
+ }
937
+ async function canonicalize(flow) {
938
+ const withDefs = asStepMapWithDefs(flow.steps);
939
+ const ids = Object.keys(withDefs).sort();
940
+ const steps = [];
941
+ for (const id of ids) {
942
+ const step = withDefs[id];
943
+ if (step === void 0) continue;
944
+ steps.push(await canonicalizeStep(id, getDef(step)));
945
+ }
946
+ return {
947
+ flowId: flow.id,
948
+ inputSchema: await canonicalizeSchema(flow.input),
949
+ steps
950
+ };
951
+ }
952
+ async function canonicalizeStep(id, def) {
953
+ const needs = [...needsStepIds(def)].sort();
954
+ const base = { id, kind: def.kind, needs };
955
+ switch (def.kind) {
956
+ // Streaming and activity hash like a task: chunks are ephemeral and the
957
+ // tx boundary is execution, not DAG shape. `kind` alone tells them apart.
958
+ case "task":
959
+ case "activity":
960
+ case "streaming":
961
+ return canonicalizeHandler(base, def);
962
+ case "signal":
963
+ return canonicalizeSignal(base, def);
964
+ case "subflow":
965
+ return canonicalizeSubflow(base, def);
966
+ }
967
+ }
968
+ async function applyGuardAndTimeout(out, def) {
969
+ if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
970
+ if (def.timeoutMs !== void 0 && def.timeoutMs !== "unbounded")
971
+ out.timeoutMs = def.timeoutMs;
972
+ }
973
+ async function canonicalizeHandler(base, def) {
974
+ const out = { ...base };
975
+ await applyGuardAndTimeout(out, def);
976
+ if (def.retry !== void 0) out.retry = normalizeRetry(def.retry);
977
+ return out;
978
+ }
979
+ async function canonicalizeSignal(base, def) {
980
+ const out = { ...base };
981
+ await applyGuardAndTimeout(out, def);
982
+ out.signalSchema = await canonicalizeSchema(def.schema);
983
+ if (def.names !== void 0) {
984
+ out.signalNames = [...def.names].sort();
985
+ }
986
+ return out;
987
+ }
988
+ async function canonicalizeSubflow(base, def) {
989
+ const out = { ...base };
990
+ await applyGuardAndTimeout(out, def);
991
+ out.childFlowId = def.childFlowId;
992
+ out.subflowInputHash = await hashFnSource(def.buildInput);
993
+ return out;
994
+ }
995
+ function normalizeRetry(retry) {
996
+ return {
997
+ maxAttempts: retry.maxAttempts,
998
+ backoff: retry.backoff,
999
+ initialDelayMs: retry.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs,
1000
+ maxDelayMs: retry.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs
1001
+ };
1002
+ }
1003
+ async function canonicalizeSchema(schema) {
1004
+ const props = schema["~standard"];
1005
+ return {
1006
+ vendor: props.vendor,
1007
+ version: props.version,
1008
+ validateHash: await hashFnSource(props.validate)
1009
+ };
1010
+ }
1011
+ async function hashFnSource(fn) {
1012
+ warnSourceHashOnce();
1013
+ return sha256Hex(fn.toString());
1014
+ }
1015
+ async function sha256Canonical(dag) {
1016
+ return sha256Hex(stableStringify(dag));
1017
+ }
1018
+ async function fingerprintFlows(flows) {
1019
+ const entries = [];
1020
+ for (const f of flows) {
1021
+ const dag = await canonicalize(f);
1022
+ entries.push([f.id, await sha256Canonical(dag)]);
1023
+ }
1024
+ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1025
+ return sha256Hex(stableStringify(entries));
1026
+ }
1027
+ function stableStringify(value) {
1028
+ if (value === void 0) return "null";
1029
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1030
+ if (Array.isArray(value)) {
1031
+ return `[${value.map(stableStringify).join(",")}]`;
1032
+ }
1033
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1034
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
1035
+ }
1036
+ async function sha256Hex(input) {
1037
+ const bytes = new TextEncoder().encode(input);
1038
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
1039
+ return hex(new Uint8Array(digest));
1040
+ }
1041
+ function hex(bytes) {
1042
+ let s = "";
1043
+ for (let i = 0; i < bytes.length; i++) {
1044
+ s += bytes[i].toString(16).padStart(2, "0");
1045
+ }
1046
+ return s;
1047
+ }
1048
+
1049
+ // src/flows.ts
1050
+ function requireCurrent(resolution) {
1051
+ if (resolution.kind === "current") return resolution.flow;
1052
+ throw resolution.error;
1053
+ }
1054
+ function makeFlowOf(deps) {
1055
+ const { registry, store, emitLog } = deps;
1056
+ return async (runId, drift) => {
1057
+ const resolution = registry.resolve(await store.loadRunState(runId));
1058
+ if (resolution.kind === "current" || drift === "freeze") return resolution;
1059
+ try {
1060
+ return { kind: "current", flow: await registry.synthesize(resolution) };
1061
+ } catch (err) {
1062
+ if (!(err instanceof NagiRuntimeError)) throw err;
1063
+ emitLog({
1064
+ level: "warn",
1065
+ msg: "flowOf: drift synthesis failed \u2014 treating run as snapshot-gone",
1066
+ attrs: {
1067
+ runId: resolution.error.runId,
1068
+ flowId: resolution.error.flowId,
1069
+ pinnedHash: resolution.error.pinnedHash,
1070
+ error: err.message
1071
+ }
1072
+ });
1073
+ return resolution;
1074
+ }
1075
+ };
1076
+ }
1077
+ function pinRun(runId, flow, flowOf) {
1078
+ const pinned = { kind: "current", flow };
1079
+ return async (id) => id === runId ? pinned : flowOf(id);
1080
+ }
1081
+ async function registerFlows(deps) {
1082
+ const { flows, store, clock } = deps;
1083
+ const byId = /* @__PURE__ */ new Map();
1084
+ const hashById = /* @__PURE__ */ new Map();
1085
+ const streamingStepIds = /* @__PURE__ */ new Set();
1086
+ for (const flow of flows) {
1087
+ if (byId.has(flow.id)) {
1088
+ throw new NagiRuntimeError(
1089
+ `Duplicate flow id "${flow.id}" passed to nagi()`
1090
+ );
1091
+ }
1092
+ byId.set(flow.id, flow);
1093
+ for (const [stepId, step] of Object.entries(
1094
+ asStepMapWithDefs(flow.steps)
1095
+ )) {
1096
+ if (getDef(step).kind !== "streaming") continue;
1097
+ if (store.stream === void 0) {
1098
+ throw new NagiRuntimeError(
1099
+ `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.`
1100
+ );
1101
+ }
1102
+ streamingStepIds.add(stepId);
1103
+ }
1104
+ }
1105
+ for (const flow of flows) {
1106
+ const dag = await canonicalize(flow);
1107
+ const flowHash = await sha256Canonical(dag);
1108
+ hashById.set(flow.id, flowHash);
1109
+ await store.upsertSnapshot({
1110
+ flowHash,
1111
+ flowId: flow.id,
1112
+ dag
1113
+ });
1114
+ const previousHash = await store.getRef(flow.id);
1115
+ if (previousHash !== flowHash) {
1116
+ await store.setRef(flow.id, flowHash);
1117
+ await store.appendGlobalFact(
1118
+ Facts.flowRefUpdated({
1119
+ flowId: flow.id,
1120
+ from: previousHash,
1121
+ to: flowHash,
1122
+ at: clock.now()
1123
+ })
1124
+ );
1125
+ }
1126
+ }
1127
+ function require2(flowId) {
1128
+ const flow = byId.get(flowId);
1129
+ if (!flow) {
1130
+ throw new NagiRuntimeError(
1131
+ `Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
1132
+ );
1133
+ }
1134
+ return flow;
1135
+ }
1136
+ function hashOf(flowId) {
1137
+ const hash = hashById.get(flowId);
1138
+ if (hash === void 0) {
1139
+ throw new NagiRuntimeError(
1140
+ `Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
1141
+ );
1142
+ }
1143
+ return hash;
1144
+ }
1145
+ function resolve(state) {
1146
+ const { runId, flowId, flowHash: pinnedHash } = state;
1147
+ const live = byId.get(flowId);
1148
+ if (pinnedHash === void 0) {
1149
+ if (live === void 0) {
1150
+ throw new NagiRuntimeError(
1151
+ `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
1152
+ );
1153
+ }
1154
+ return { kind: "current", flow: live };
1155
+ }
1156
+ const currentHash = live === void 0 ? null : hashOf(flowId);
1157
+ if (live !== void 0 && currentHash === pinnedHash) {
1158
+ return { kind: "current", flow: live };
1159
+ }
1160
+ const error = new NagiFlowSnapshotGoneError({
1161
+ runId,
1162
+ flowId,
1163
+ pinnedHash,
1164
+ currentHash
1165
+ });
1166
+ return isTerminalRun(state) ? { kind: "gone-terminal", error, live } : { kind: "gone-live", error, live };
1167
+ }
1168
+ const synthesizedByHash = /* @__PURE__ */ new Map();
1169
+ function synthesize(gone) {
1170
+ const { pinnedHash } = gone.error;
1171
+ const cached = synthesizedByHash.get(pinnedHash);
1172
+ if (cached !== void 0) return cached;
1173
+ const pending = synthesizeUncached(gone);
1174
+ synthesizedByHash.set(pinnedHash, pending);
1175
+ pending.catch(() => synthesizedByHash.delete(pinnedHash));
1176
+ return pending;
1177
+ }
1178
+ async function synthesizeUncached(gone) {
1179
+ const { runId, flowId, pinnedHash } = gone.error;
1180
+ if (gone.live === void 0) {
1181
+ throw new NagiRuntimeError(
1182
+ `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
1183
+ );
1184
+ }
1185
+ const snapshot = await store.loadSnapshot(pinnedHash);
1186
+ if (snapshot === null) {
1187
+ throw new NagiRuntimeError(
1188
+ `Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Nothing can resume it.`
1189
+ );
1190
+ }
1191
+ return synthesizeReplayFlow(
1192
+ snapshot.dag,
1193
+ gone.live
1194
+ );
1195
+ }
1196
+ return {
1197
+ get: (flowId) => byId.get(flowId),
1198
+ has: (flowId) => byId.has(flowId),
1199
+ require: require2,
1200
+ hashOf,
1201
+ isStreaming: (stepId) => streamingStepIds.has(stepId),
1202
+ resolve,
1203
+ synthesize
1204
+ };
1205
+ }
1206
+ function synthesizeReplayFlow(dag, liveFlow) {
1207
+ const liveSteps = asStepMapWithDefs(liveFlow.steps);
1208
+ const synthesized = {};
1209
+ for (const canonStep of dag.steps) {
1210
+ const liveStep = liveSteps[canonStep.id];
1211
+ if (liveStep === void 0) {
1212
+ throw new NagiRuntimeError(
1213
+ `Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
1214
+ );
1215
+ }
1216
+ synthesized[canonStep.id] = attachDef(
1217
+ { kind: canonStep.kind, id: canonStep.id },
1218
+ getDef(liveStep)
1219
+ );
1220
+ }
1221
+ for (const canonStep of dag.steps) {
1222
+ const shell = synthesized[canonStep.id];
1223
+ if (shell === void 0) continue;
1224
+ const synthesizedNeeds = {};
1225
+ for (const upstreamId of canonStep.needs) {
1226
+ const upstreamShell = synthesized[upstreamId];
1227
+ if (upstreamShell === void 0) {
1228
+ throw new NagiRuntimeError(
1229
+ `Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
1230
+ );
1231
+ }
1232
+ synthesizedNeeds[upstreamId] = upstreamShell;
1233
+ }
1234
+ setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
1235
+ }
1236
+ return {
1237
+ id: liveFlow.id,
1238
+ input: liveFlow.input,
1239
+ steps: synthesized,
1240
+ ...compact({
1241
+ output: liveFlow.output,
1242
+ onStart: liveFlow.onStart,
1243
+ onComplete: liveFlow.onComplete,
1244
+ onError: liveFlow.onError
1245
+ })
1246
+ };
1247
+ }
1248
+
881
1249
  // src/validate.ts
882
1250
  async function validate(schema, value) {
883
1251
  const result = await schema["~standard"].validate(value);
@@ -953,10 +1321,9 @@ function decideTimeout(args) {
953
1321
  };
954
1322
  }
955
1323
  function makeSignals(deps) {
956
- const { dispatcher, store, clock, registry, hooks, flowHooks, emitLog } = deps;
1324
+ const { dispatcher, store, clock, flowOf, hooks, flowHooks, emitLog } = deps;
957
1325
  async function signal(runId, signalName, payload) {
958
- const runState = await store.loadRunState(runId);
959
- const flow = registry.require(runState.flowId);
1326
+ const flow = requireCurrent(await flowOf(runId));
960
1327
  const resolved = resolveSignalStep(flow, signalName);
961
1328
  if (resolved === null) {
962
1329
  throw new NagiRuntimeError(
@@ -1029,59 +1396,6 @@ function resolveSignalStep(flow, signalName) {
1029
1396
  }
1030
1397
 
1031
1398
  // 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
1399
  var DEFAULT_SWEEP_LIMIT = 100;
1086
1400
  function selectExpired(items, args) {
1087
1401
  const nowMs = args.now.getTime();
@@ -1106,35 +1420,29 @@ function selectPruneBatch(candidates, opts) {
1106
1420
  );
1107
1421
  return eligible.slice(0, opts.batchSize).map((e) => e.item);
1108
1422
  }
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;
1423
+ function admitsRunEnd(status) {
1424
+ return status === "pending" || status === "running";
1425
+ }
1426
+ function supersede(args) {
1427
+ const { start, concurrency } = args;
1428
+ switch (concurrency.mode) {
1429
+ case "cancel-in-progress":
1430
+ return Array.from(args.priors, (runId) => ({
1431
+ runId,
1432
+ fact: Facts.flowCanceledByConcurrency({
1433
+ runId,
1434
+ canceledByRunId: start.runId,
1435
+ concurrencyKey: concurrency.key,
1436
+ at: start.at
1437
+ })
1438
+ }));
1134
1439
  }
1135
1440
  }
1136
1441
 
1137
1442
  // src/stream-hub.ts
1443
+ function isStreamOver(state, stepId) {
1444
+ return isTerminalRun(state) || isStepTerminal(stepStateOf(state, stepId));
1445
+ }
1138
1446
  var STREAM_SUBSCRIBER_BUFFER_CAP = 256;
1139
1447
  var STREAM_REPLAY_BUFFER_CAP = 256;
1140
1448
  function makeWake() {
@@ -1195,81 +1503,100 @@ var Subscriber = class {
1195
1503
  }
1196
1504
  }
1197
1505
  };
1506
+ var STREAM_CLOSED_KEYS_CAP = 1024;
1507
+ var EMPTY_CLOSED_STREAM = {
1508
+ [Symbol.asyncIterator]() {
1509
+ return { next: async () => ({ value: void 0, done: true }) };
1510
+ }
1511
+ };
1198
1512
  var InMemoryStreamHub = class _InMemoryStreamHub {
1513
+ // Open channels only: closing one deletes it and records its key.
1199
1514
  channels = /* @__PURE__ */ new Map();
1515
+ closedKeys = /* @__PURE__ */ new Set();
1200
1516
  static key(runId, stepId) {
1201
1517
  return `${runId}::${stepId}`;
1202
1518
  }
1203
- getOrCreate(runId, stepId) {
1204
- const key = _InMemoryStreamHub.key(runId, stepId);
1519
+ openChannel(key) {
1520
+ if (this.closedKeys.has(key)) return void 0;
1205
1521
  let channel = this.channels.get(key);
1206
1522
  if (channel === void 0) {
1207
- channel = { subscribers: /* @__PURE__ */ new Set(), replay: [], closed: false };
1523
+ channel = { subscribers: /* @__PURE__ */ new Set(), replay: [] };
1208
1524
  this.channels.set(key, channel);
1209
1525
  }
1210
1526
  return channel;
1211
1527
  }
1528
+ // Returns the subscribers to end, or undefined when no channel was open.
1529
+ closeChannel(key) {
1530
+ const channel = this.channels.get(key);
1531
+ if (channel === void 0) return void 0;
1532
+ this.channels.delete(key);
1533
+ this.closedKeys.add(key);
1534
+ if (this.closedKeys.size > STREAM_CLOSED_KEYS_CAP) {
1535
+ const oldest = this.closedKeys.values().next().value;
1536
+ if (oldest !== void 0) this.closedKeys.delete(oldest);
1537
+ }
1538
+ const subs = [...channel.subscribers];
1539
+ channel.subscribers.clear();
1540
+ channel.replay.length = 0;
1541
+ return subs;
1542
+ }
1212
1543
  publishChunk(runId, stepId, chunk) {
1213
- const channel = this.getOrCreate(runId, stepId);
1214
- if (channel.closed) return;
1544
+ const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
1545
+ if (channel === void 0) return;
1215
1546
  const event = { kind: "chunk", chunk };
1216
1547
  channel.replay.push(event);
1217
1548
  if (channel.replay.length > STREAM_REPLAY_BUFFER_CAP)
1218
1549
  channel.replay.shift();
1219
1550
  for (const sub of channel.subscribers) sub.push(event);
1220
1551
  }
1552
+ // NB: signalRetry and the close* methods are no-ops when no channel exists.
1553
+ // Both adapters fire them for EVERY step — Postgres cluster-wide — including
1554
+ // non-streaming ones, so creating a channel here would leak one per step.
1221
1555
  signalRetry(runId, stepId, attempt) {
1222
- const channel = this.getOrCreate(runId, stepId);
1223
- if (channel.closed) return;
1556
+ const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
1557
+ if (channel === void 0) return;
1224
1558
  channel.replay.length = 0;
1225
1559
  const event = { kind: "retry", attempt };
1226
1560
  for (const sub of channel.subscribers) sub.push(event);
1227
1561
  }
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
1562
  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();
1563
+ const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
1564
+ for (const sub of subs ?? []) sub.close();
1239
1565
  }
1240
1566
  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;
1567
+ const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
1245
1568
  const event = { kind: "error", error };
1246
- for (const sub of channel.subscribers) {
1569
+ for (const sub of subs ?? []) {
1247
1570
  sub.push(event);
1248
1571
  sub.close();
1249
1572
  }
1250
- channel.subscribers.clear();
1573
+ }
1574
+ apply(runId, effect) {
1575
+ switch (effect.tag) {
1576
+ case "close-ok":
1577
+ this.closeOk(runId, effect.stepId);
1578
+ return;
1579
+ case "close-error":
1580
+ this.closeError(runId, effect.stepId, effect.error);
1581
+ return;
1582
+ case "retry":
1583
+ this.signalRetry(runId, effect.stepId, effect.nextAttempt);
1584
+ return;
1585
+ case "close-run":
1586
+ this.closeRun(runId);
1587
+ return;
1588
+ }
1251
1589
  }
1252
1590
  closeRun(runId) {
1253
1591
  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();
1592
+ for (const key of this.channels.keys()) {
1593
+ if (!key.startsWith(prefix)) continue;
1594
+ for (const sub of this.closeChannel(key) ?? []) sub.close();
1260
1595
  }
1261
1596
  }
1262
1597
  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
- }
1598
+ const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
1599
+ if (channel === void 0) return EMPTY_CLOSED_STREAM;
1273
1600
  const sub = new Subscriber();
1274
1601
  if (opts?.replayBuffered === true) {
1275
1602
  for (const event of channel.replay) sub.push(event);
@@ -1300,6 +1627,111 @@ var InMemoryStreamHub = class _InMemoryStreamHub {
1300
1627
  }
1301
1628
  };
1302
1629
 
1630
+ // src/read-model.ts
1631
+ var SETTLED = /* @__PURE__ */ new Set([
1632
+ "completed",
1633
+ "failed",
1634
+ "canceled",
1635
+ "skipped"
1636
+ ]);
1637
+ function nextRunRow(prev, delta) {
1638
+ if (delta.row === "step") {
1639
+ return delta.status === "reset" && prev !== void 0 && (prev.status === "completed" || prev.status === "failed") ? {
1640
+ ...prev,
1641
+ status: "running",
1642
+ output: null,
1643
+ error: null,
1644
+ completedAt: null
1645
+ } : prev;
1646
+ }
1647
+ switch (delta.status) {
1648
+ case "running":
1649
+ return prev ?? {
1650
+ flowId: delta.flowId,
1651
+ status: "running",
1652
+ input: delta.input,
1653
+ output: null,
1654
+ error: null,
1655
+ startedAt: delta.startedAt,
1656
+ completedAt: null,
1657
+ flowHash: delta.flowHash,
1658
+ codeVersion: delta.codeVersion,
1659
+ parent: delta.parent,
1660
+ canceledByRunId: null
1661
+ };
1662
+ case "completed":
1663
+ return prev && {
1664
+ ...prev,
1665
+ status: "completed",
1666
+ output: delta.output,
1667
+ error: null,
1668
+ completedAt: delta.completedAt
1669
+ };
1670
+ case "failed":
1671
+ return prev && {
1672
+ ...prev,
1673
+ status: "failed",
1674
+ output: null,
1675
+ error: delta.error,
1676
+ completedAt: delta.completedAt
1677
+ };
1678
+ case "canceled":
1679
+ return prev && {
1680
+ ...prev,
1681
+ status: "canceled",
1682
+ output: null,
1683
+ error: null,
1684
+ canceledByRunId: delta.canceledByRunId,
1685
+ completedAt: delta.completedAt
1686
+ };
1687
+ }
1688
+ }
1689
+ function nextStepRow(prev, delta) {
1690
+ if (delta.status === "reset") return void 0;
1691
+ if (prev !== void 0 && SETTLED.has(prev.status)) return prev;
1692
+ switch (delta.status) {
1693
+ case "running":
1694
+ if (prev !== void 0 && prev.attempt >= delta.attempt) return prev;
1695
+ return {
1696
+ attempt: delta.attempt,
1697
+ status: "running",
1698
+ startedAt: delta.startedAt,
1699
+ completedAt: null,
1700
+ output: null,
1701
+ error: null
1702
+ };
1703
+ case "backoff":
1704
+ if (prev === void 0 || prev.error !== null || prev.attempt !== delta.attempt) {
1705
+ return prev;
1706
+ }
1707
+ return { ...prev, error: delta.error };
1708
+ case "completed":
1709
+ return settle(prev, delta.attempt, delta, delta.output, null);
1710
+ case "failed":
1711
+ return settle(prev, delta.attempt, delta, null, delta.error);
1712
+ case "canceled":
1713
+ return settle(prev, delta.attempt, delta, null, delta.error);
1714
+ case "skipped":
1715
+ return settle(
1716
+ prev,
1717
+ prev?.attempt ?? 0,
1718
+ delta,
1719
+ null,
1720
+ null
1721
+ );
1722
+ }
1723
+ }
1724
+ function settle(prev, attempt, delta, output, error) {
1725
+ return {
1726
+ attempt,
1727
+ status: delta.status,
1728
+ startedAt: prev?.startedAt ?? null,
1729
+ completedAt: delta.completedAt,
1730
+ output,
1731
+ error
1732
+ };
1733
+ }
1734
+
1303
1735
  // src/memory.ts
1304
1736
  function leaseKey(runId, stepId, attempt) {
1305
1737
  return `${runId}::${stepId}::${attempt}`;
@@ -1319,8 +1751,9 @@ var InMemoryStore = class {
1319
1751
  keyByActiveRun = /* @__PURE__ */ new Map();
1320
1752
  // Kept past terminal facts so a reopened run can re-take its slot.
1321
1753
  slotByRun = /* @__PURE__ */ new Map();
1322
- childrenByParent = /* @__PURE__ */ new Map();
1323
- summaries = /* @__PURE__ */ new Map();
1754
+ // The read model (Postgres: workflow_run / step_run), fed only by row deltas.
1755
+ runRows = /* @__PURE__ */ new Map();
1756
+ stepRows = /* @__PURE__ */ new Map();
1324
1757
  streamHub = new InMemoryStreamHub();
1325
1758
  // Durable signal-timeout deadlines (the Postgres `timer` table), distinct
1326
1759
  // from InMemoryClock's setTimeout-based scheduler.
@@ -1330,6 +1763,18 @@ var InMemoryStore = class {
1330
1763
  this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
1331
1764
  }
1332
1765
  async appendFact(runId, fact) {
1766
+ this.writeFact(runId, fact);
1767
+ }
1768
+ async endRun(runId, fact) {
1769
+ return this.writeFact(runId, fact);
1770
+ }
1771
+ // The one fact-write path. Synchronous on purpose: with no await between the
1772
+ // read that led to a write and the write itself, every caller gets the
1773
+ // atomicity the Postgres store takes a transaction for.
1774
+ writeFact(runId, fact) {
1775
+ if (isRunEnd(fact) && !admitsRunEnd(this.runRows.get(runId)?.status)) {
1776
+ return false;
1777
+ }
1333
1778
  const list = this.facts.get(runId) ?? [];
1334
1779
  if (fact.kind === "step.reset") {
1335
1780
  const prior = foldRun(runId, list);
@@ -1351,38 +1796,34 @@ var InMemoryStore = class {
1351
1796
  }
1352
1797
  list.push(fact);
1353
1798
  this.facts.set(runId, list);
1354
- const event = runEventOf(fact);
1799
+ const { rows, release, stream, event } = factConsequences(fact);
1800
+ if (rows !== null) this.applyRows(runId, rows);
1801
+ if (release !== null) this.release(runId, release);
1802
+ if (stream !== null) this.streamHub.apply(runId, stream);
1355
1803
  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;
1804
+ return true;
1805
+ }
1806
+ applyRows(runId, delta) {
1807
+ const run = nextRunRow(this.runRows.get(runId), delta);
1808
+ if (run !== void 0) this.runRows.set(runId, run);
1809
+ if (delta.row === "run") return;
1810
+ const steps = this.stepRows.get(runId) ?? /* @__PURE__ */ new Map();
1811
+ const step = nextStepRow(steps.get(delta.stepId), delta);
1812
+ if (step === void 0) steps.delete(delta.stepId);
1813
+ else steps.set(delta.stepId, step);
1814
+ this.stepRows.set(runId, steps);
1815
+ }
1816
+ release(runId, release) {
1817
+ switch (release.tag) {
1380
1818
  case "release-step":
1381
- this.releaseLeases(runId, effects.stepId);
1382
- if (effects.timer) {
1383
- this.signalTimers.delete(timerKey(runId, effects.stepId));
1819
+ this.releaseLeases(runId, release.stepId);
1820
+ if (release.timer) {
1821
+ this.signalTimers.delete(timerKey(runId, release.stepId));
1384
1822
  }
1385
1823
  return;
1824
+ case "release-lease":
1825
+ this.leases.delete(leaseKey(runId, release.stepId, release.attempt));
1826
+ return;
1386
1827
  case "release-run": {
1387
1828
  const slot = this.keyByActiveRun.get(runId);
1388
1829
  if (slot === void 0) return;
@@ -1402,64 +1843,48 @@ var InMemoryStore = class {
1402
1843
  }
1403
1844
  }
1404
1845
  async tryStartRun(runId, fact, concurrency) {
1405
- if (this.runExists(runId)) {
1846
+ if (this.runRows.has(runId)) {
1406
1847
  return { started: false, canceled: [] };
1407
1848
  }
1408
1849
  const canceled = [];
1409
1850
  if (concurrency !== void 0) {
1410
1851
  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 });
1852
+ const prior = this.activeByKey.get(slot);
1853
+ for (const c of supersede({
1854
+ start: fact,
1855
+ concurrency,
1856
+ priors: prior === void 0 ? [] : [prior]
1857
+ })) {
1858
+ if (this.writeFact(c.runId, c.fact)) canceled.push(c);
1421
1859
  }
1422
1860
  this.activeByKey.set(slot, runId);
1423
1861
  this.keyByActiveRun.set(runId, slot);
1424
1862
  this.slotByRun.set(runId, slot);
1425
1863
  }
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
- }
1864
+ this.writeFact(runId, fact);
1434
1865
  return { started: true, canceled };
1435
1866
  }
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.
1867
+ // No real tx to join: every write here is visible, and announced, the moment
1868
+ // it happens, and nothing the caller does later can roll it back. Events stay
1869
+ // exactly as durable as the facts they report.
1439
1870
  async tryStartRunOnTx(_tx, runId, fact, concurrency) {
1440
1871
  return this.tryStartRun(runId, fact, concurrency);
1441
1872
  }
1442
1873
  async listChildren(parentRunId) {
1443
- const set = this.childrenByParent.get(parentRunId);
1444
- if (set === void 0) return [];
1445
- return Array.from(set);
1874
+ return this.childRows(parentRunId).map(([runId]) => runId);
1875
+ }
1876
+ childRows(parentRunId) {
1877
+ return [...this.runRows].filter(
1878
+ ([, row]) => row.parent?.runId === parentRunId
1879
+ );
1446
1880
  }
1447
1881
  // Does a non-terminal child exist for this (parentRunId, stepId)? Used by the
1448
1882
  // 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.
1883
+ // of re-dispatching it at attempt+1).
1451
1884
  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;
1885
+ return this.childRows(parentRunId).some(
1886
+ ([, row]) => row.parent?.stepId === parentStepId && (row.status === "pending" || row.status === "running")
1887
+ );
1463
1888
  }
1464
1889
  async loadRunState(runId) {
1465
1890
  return foldRun(runId, this.facts.get(runId) ?? []);
@@ -1497,9 +1922,7 @@ var InMemoryStore = class {
1497
1922
  });
1498
1923
  for (const lease of candidates) {
1499
1924
  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";
1925
+ const flowId = this.runRows.get(runId)?.flowId;
1503
1926
  const decision = decideExpiredLeaseAction({
1504
1927
  lease: {
1505
1928
  runId,
@@ -1507,21 +1930,24 @@ var InMemoryStore = class {
1507
1930
  attempt,
1508
1931
  expiresAt: new Date(lease.expiresAt)
1509
1932
  },
1510
- stepStatus,
1933
+ stepStatus: this.stepRows.get(runId)?.get(stepId)?.status ?? "pending",
1511
1934
  childActive: this.hasActiveChild(runId, stepId),
1512
1935
  now
1513
1936
  });
1514
1937
  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
- });
1938
+ const key = leaseKey(runId, stepId, attempt);
1939
+ this.leases.delete(key);
1940
+ try {
1941
+ await queue.enqueue(runId, stepId, {
1942
+ attempt: decision.nextAttempt,
1943
+ delayMs: decision.backoffMs,
1944
+ ...flowId !== void 0 ? { flowId } : {}
1945
+ });
1946
+ } catch (err) {
1947
+ this.leases.set(key, lease);
1948
+ throw err;
1949
+ }
1950
+ this.writeFact(runId, decision.fact);
1525
1951
  reaped.push({
1526
1952
  runId,
1527
1953
  stepId,
@@ -1531,9 +1957,6 @@ var InMemoryStore = class {
1531
1957
  }
1532
1958
  return reaped;
1533
1959
  }
1534
- async settleStep(runId, _stepId, fact) {
1535
- await this.appendFact(runId, fact);
1536
- }
1537
1960
  async settleSignal(args) {
1538
1961
  const { runId, stepId, at, incoming } = args;
1539
1962
  const runState = foldRun(runId, this.facts.get(runId) ?? []);
@@ -1542,11 +1965,11 @@ var InMemoryStore = class {
1542
1965
  case "noop":
1543
1966
  return decision.result;
1544
1967
  case "buffer":
1545
- if (decision.fact !== null) await this.appendFact(runId, decision.fact);
1968
+ if (decision.fact !== null) this.writeFact(runId, decision.fact);
1546
1969
  return decision.result;
1547
1970
  case "deliver":
1548
- await this.appendFact(runId, decision.received);
1549
- await this.appendFact(runId, decision.completed);
1971
+ this.writeFact(runId, decision.received);
1972
+ this.writeFact(runId, decision.completed);
1550
1973
  return decision.result;
1551
1974
  }
1552
1975
  }
@@ -1569,7 +1992,7 @@ var InMemoryStore = class {
1569
1992
  const decision = decideTimeout({ runState, stepId, fireAt, at: now });
1570
1993
  this.signalTimers.delete(timerKey(runId, stepId));
1571
1994
  if (decision.kind === "noop") continue;
1572
- await this.appendFact(runId, decision.fact);
1995
+ this.writeFact(runId, decision.fact);
1573
1996
  timedOut.push({ runId, stepId, attempt: decision.attempt, fireAt });
1574
1997
  }
1575
1998
  return timedOut;
@@ -1579,11 +2002,12 @@ var InMemoryStore = class {
1579
2002
  if (!this.onces.has(key)) this.onces.set(key, value);
1580
2003
  }
1581
2004
  async getOnce(runId, stepId, scope) {
1582
- return this.onces.get(`${runId}::${stepId}::${scope}`) ?? null;
2005
+ const value = this.onces.get(`${runId}::${stepId}::${scope}`);
2006
+ return value === void 0 ? { tag: "miss" } : { tag: "hit", value };
1583
2007
  }
1584
2008
  async runStep(runId, _stepId, _attempt, body) {
1585
2009
  const result = await body(void 0);
1586
- await this.appendFact(runId, result.fact);
2010
+ this.writeFact(runId, result.fact);
1587
2011
  return result.output;
1588
2012
  }
1589
2013
  async upsertSnapshot(args) {
@@ -1605,165 +2029,44 @@ var InMemoryStore = class {
1605
2029
  readGlobalFacts() {
1606
2030
  return this.globalFacts;
1607
2031
  }
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
2032
  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);
2033
+ const row = this.runRows.get(runId);
2034
+ if (row === void 0) return null;
2035
+ const slot = this.slotByRun.get(runId);
2036
+ const children = this.childRows(runId).sort(([, a], [, b]) => a.startedAt.getTime() - b.startedAt.getTime()).map(([childId]) => childId);
2037
+ const steps = [...this.stepRows.get(runId) ?? []].map(([stepId, step]) => this.stepView(runId, stepId, step)).sort(compareStepOrder);
1755
2038
  return {
1756
2039
  run: {
1757
2040
  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 } : {}
2041
+ flowId: row.flowId,
2042
+ flowHash: row.flowHash ?? "",
2043
+ status: row.status,
2044
+ startedAt: row.startedAt,
2045
+ input: row.input,
2046
+ children,
2047
+ ...row.completedAt !== null ? { completedAt: row.completedAt } : {},
2048
+ ...row.output !== null ? { output: row.output } : {},
2049
+ ...row.error !== null ? { error: row.error } : {},
2050
+ // Postgres: ON DELETE SET NULL — the view never names a pruned run.
2051
+ ...row.canceledByRunId !== null && this.runRows.has(row.canceledByRunId) ? { canceledByRunId: row.canceledByRunId } : {},
2052
+ ...slot !== void 0 ? { concurrencyKey: slot.slice(row.flowId.length + 2) } : {},
2053
+ ...row.parent !== null ? { parent: row.parent } : {}
1765
2054
  },
1766
- steps: []
2055
+ steps
2056
+ };
2057
+ }
2058
+ stepView(runId, stepId, row) {
2059
+ const lease = this.leases.get(leaseKey(runId, stepId, row.attempt));
2060
+ const live = lease !== void 0 && lease.expiresAt > Date.now();
2061
+ return {
2062
+ stepId,
2063
+ attempt: row.attempt,
2064
+ status: row.status,
2065
+ ...row.startedAt !== null ? { startedAt: row.startedAt } : {},
2066
+ ...row.completedAt !== null ? { completedAt: row.completedAt } : {},
2067
+ ...row.output !== null ? { output: row.output } : {},
2068
+ ...row.error !== null ? { error: row.error } : {},
2069
+ ...live ? { lease: { expiresAt: new Date(lease.expiresAt) } } : {}
1767
2070
  };
1768
2071
  }
1769
2072
  async pruneFacts(opts) {
@@ -1772,24 +2075,15 @@ var InMemoryStore = class {
1772
2075
  for (; ; ) {
1773
2076
  const batch = selectPruneBatch(this.pruneCandidates(), opts);
1774
2077
  if (batch.length === 0) break;
1775
- for (const { factCount, parentRunId, ...summary } of batch) {
1776
- const runId = summary.runId;
2078
+ for (const { runId, factCount } of batch) {
1777
2079
  this.facts.delete(runId);
2080
+ this.stepRows.delete(runId);
1778
2081
  deleteByRunPrefix(this.onces, runId);
1779
2082
  deleteByRunPrefix(this.leases, runId);
1780
2083
  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);
2084
+ if (!opts.keepSummary) {
2085
+ this.runRows.delete(runId);
2086
+ this.slotByRun.delete(runId);
1793
2087
  }
1794
2088
  runsPruned += 1;
1795
2089
  factsPruned += factCount;
@@ -1799,12 +2093,15 @@ var InMemoryStore = class {
1799
2093
  }
1800
2094
  pruneCandidates() {
1801
2095
  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 });
2096
+ for (const [runId, row] of this.runRows) {
2097
+ const factList = this.facts.get(runId);
2098
+ if (factList === void 0) continue;
2099
+ out.push({
2100
+ runId,
2101
+ status: row.status,
2102
+ completedAt: row.completedAt,
2103
+ factCount: factList.length
2104
+ });
1808
2105
  }
1809
2106
  return out;
1810
2107
  }
@@ -1815,11 +2112,8 @@ var InMemoryStore = class {
1815
2112
  };
1816
2113
  stream = {
1817
2114
  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;
2115
+ if (isStreamOver(foldRun(runId, this.facts.get(runId) ?? []), stepId)) {
2116
+ return EMPTY_CLOSED_STREAM2;
1823
2117
  }
1824
2118
  return this.streamHub.subscribeStream(runId, stepId, opts);
1825
2119
  },
@@ -1828,7 +2122,13 @@ var InMemoryStore = class {
1828
2122
  }
1829
2123
  };
1830
2124
  };
1831
- var EMPTY_CLOSED_STREAM = {
2125
+ function compareStepOrder(a, b) {
2126
+ const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
2127
+ const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
2128
+ if (ta !== tb) return ta - tb;
2129
+ return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
2130
+ }
2131
+ var EMPTY_CLOSED_STREAM2 = {
1832
2132
  [Symbol.asyncIterator]() {
1833
2133
  return { next: async () => ({ value: void 0, done: true }) };
1834
2134
  }
@@ -1839,28 +2139,6 @@ function deleteByRunPrefix(map, runId) {
1839
2139
  if (key.startsWith(prefix)) map.delete(key);
1840
2140
  }
1841
2141
  }
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
2142
  var DEFAULT_QUEUE_LEASE_MS = 6e4;
1865
2143
  var InMemoryQueue = class {
1866
2144
  pending = [];
@@ -1953,6 +2231,6 @@ var InMemoryClock = class {
1953
2231
  }
1954
2232
  };
1955
2233
 
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
2234
+ 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 };
2235
+ //# sourceMappingURL=chunk-PUAV56FC.js.map
2236
+ //# sourceMappingURL=chunk-PUAV56FC.js.map