@nagi-js/core 0.1.1-rc.6 → 0.1.1-rc.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -44,7 +44,7 @@ interface Register {
44
44
  type Tx = Register extends {
45
45
  tx: infer T;
46
46
  } ? T : unknown;
47
- type StepKind = "task" | "signal" | "match";
47
+ type StepKind = "task" | "signal" | "match" | "subflow";
48
48
  interface Step<Output = unknown> {
49
49
  readonly kind: StepKind;
50
50
  readonly id: StepId;
@@ -198,6 +198,33 @@ interface MatchGuardConfig<Input, N extends NeedsMap, M extends StepMap> {
198
198
  type MatchArmOutput<M extends StepMap> = {
199
199
  readonly [K in keyof M]: StepOutput<M[K]>;
200
200
  };
201
+ /**
202
+ * Config for `b.subflow(child, config)`. The `input` callback derives the
203
+ * child flow's input from the parent's own input + resolved needs. Typed
204
+ * against `FlowInput<Child>` so the child's input schema is honored at
205
+ * compile time.
206
+ *
207
+ * The child flow runs as an independent run on the same store/queue. Its
208
+ * `flow.started` fact records `parentRunId` + `parentStepId`, which links
209
+ * its eventual `flow.completed` back to this subflow step (see RFC 0006
210
+ * for the wake-parent mechanism).
211
+ */
212
+ interface SubflowConfig<Input, N extends NeedsMap, Child extends Flow> extends StepConfigBase<Input, N> {
213
+ readonly input: (args: {
214
+ readonly input: NoInfer<Input>;
215
+ readonly needs: NoInfer<NeedsOutputs<N>>;
216
+ }) => FlowInput<Child>;
217
+ }
218
+ /**
219
+ * The structural output of a subflow step. `childRunId` lets callers
220
+ * correlate to the child run for debugging / OTel tracing; `output` carries
221
+ * the child flow's own final output (whatever its `flow({ output })` reducer
222
+ * produced).
223
+ */
224
+ interface SubflowStepOutput<ChildOutput> {
225
+ readonly childRunId: RunId;
226
+ readonly output: ChildOutput;
227
+ }
201
228
  /** Across all cases of a discriminator match — the union of arm outputs. */
202
229
  type MatchDiscriminatorOutput<D extends string, M extends Record<D, StepMap>> = {
203
230
  [K in D]: MatchArmOutput<M[K]>;
@@ -254,6 +281,22 @@ interface StepEntryConfig<Input, A extends Record<string, unknown>, Needs extend
254
281
  interface Builder<Input = unknown, A extends Record<string, unknown> = Record<never, never>> {
255
282
  task<N extends NeedsMap, Output>(config: TaskConfig<Input, N, Output>): Step<Output>;
256
283
  signal<N extends NeedsMap, S extends StandardSchemaV1>(config: SignalConfig<Input, N, S>): Step<InferSchemaOutput<S>>;
284
+ /**
285
+ * Embed another flow as a step. The child flow runs as an independent
286
+ * run on the same store/queue; this step parks in `running` until the
287
+ * child reaches a terminal state, then completes with the child's output.
288
+ *
289
+ * const transcript = b.subflow(transcriptionFlow, {
290
+ * needs: { audio },
291
+ * input: ({ needs }) => ({ audioUrl: needs.audio.url }),
292
+ * });
293
+ * // typed: Step<{ childRunId: RunId; output: FlowOutput<typeof transcriptionFlow> }>
294
+ *
295
+ * The child must be registered with `nagi({ flows: [parent, child] })` —
296
+ * subflow registration is strict, not auto-include. A child failure
297
+ * bubbles up as this step's failure with the child's error.
298
+ */
299
+ subflow<N extends NeedsMap, Child extends Flow>(child: Child, config: SubflowConfig<Input, N, Child>): Step<SubflowStepOutput<FlowOutput<Child>>>;
257
300
  match<N extends NeedsMap, D extends string, Cases extends {
258
301
  readonly [K in D]: (b: Builder<Input>) => BuildResult<Input, StepMap>;
259
302
  }>(config: {
@@ -573,7 +616,7 @@ interface Store {
573
616
  */
574
617
  runStep<T extends Json>(runId: RunId, stepId: StepId, attempt: AttemptNumber, body: (tx: Tx) => Promise<{
575
618
  readonly output: T;
576
- readonly fact: StepCompletedFact | StepFailedFact;
619
+ readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
577
620
  }>): Promise<T>;
578
621
  /**
579
622
  * Deduped store of canonical flow DAGs, keyed by content hash. Inserts are
@@ -627,6 +670,34 @@ interface Store {
627
670
  * the row's input is a superset of the filter object, recursively).
628
671
  */
629
672
  queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
673
+ /**
674
+ * Return the run ids of every direct child run spawned by `parentRunId`
675
+ * via `b.subflow()`. Identified by `flow.started.parentRunId === parentRunId`.
676
+ * Order is unspecified.
677
+ *
678
+ * Used by `wf.cancel(runId)` to cascade cancellation transitively. Indexed
679
+ * lookup: Postgres adapter persists `parent_run_id` as a column on
680
+ * `workflow_run` with a btree index; in-memory adapter maintains a
681
+ * `parent → set<children>` map updated on `tryStartRun`.
682
+ */
683
+ listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
684
+ /**
685
+ * Retention prune. Deletes facts (and run-scoped per-step rows) for terminal
686
+ * runs whose `completed_at < opts.olderThan` and whose status is in
687
+ * `opts.statuses`. See {@link PruneOpts} and {@link Wf.pruneFacts} (in
688
+ * `runtime.ts`) for the public contract.
689
+ *
690
+ * Adapters MUST:
691
+ * - Never prune runs in non-terminal status (`pending` / `running`). The
692
+ * public type forbids it; this is defense-in-depth.
693
+ * - Delete in batches of `opts.batchSize` until no more victims remain.
694
+ * Postgres uses `FOR UPDATE SKIP LOCKED` so concurrent pruners share work
695
+ * safely; in-memory is single-process and atomic between awaits.
696
+ * - When `opts.keepSummary` is true, retain a summary row visible to
697
+ * `queryRuns` (postgres keeps the `workflow_run` row; in-memory keeps a
698
+ * `RunSummary` shadow). When false, the run is fully removed.
699
+ */
700
+ pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
630
701
  }
631
702
  interface QueryRunsWhere {
632
703
  readonly flowId?: string;
@@ -676,6 +747,47 @@ interface QueryRunsResult {
676
747
  /** Pass to the next `queryRuns` to resume. `null` when no more rows. */
677
748
  readonly cursor: string | null;
678
749
  }
750
+ /**
751
+ * Statuses {@link Wf.pruneFacts} accepts. Restricted to terminal statuses —
752
+ * `pending` and `running` are excluded at the type level so the compiler
753
+ * rejects `statuses: ["running"]`. The runtime re-validates as defense in
754
+ * depth for JS callers / `as any` escape hatches.
755
+ */
756
+ type PrunableStatus = Extract<RunStatus, "completed" | "failed" | "canceled">;
757
+ /**
758
+ * Options for {@link Wf.pruneFacts}. Retention sweep over terminal runs.
759
+ *
760
+ * The prune is keyed on `workflow_run.completed_at`. Runs whose
761
+ * `completed_at` is null (still active) are skipped regardless of `statuses`.
762
+ */
763
+ interface PruneOpts {
764
+ /** Prune runs whose `completed_at < olderThan`. */
765
+ readonly olderThan: Date;
766
+ /**
767
+ * Terminal statuses to prune. Default: `["completed"]`. `pending` /
768
+ * `running` are never prunable (compile-time and runtime).
769
+ */
770
+ readonly statuses?: ReadonlyArray<PrunableStatus>;
771
+ /**
772
+ * Per-batch deletion size. Default: 1000. Postgres uses one transaction
773
+ * per batch so a large prune doesn't hold locks across the whole table.
774
+ */
775
+ readonly batchSize?: number;
776
+ /**
777
+ * When true (default), retain a summary row so the run is still visible to
778
+ * `queryRuns` — facts/steps/leases/timers/dedupes are still deleted. When
779
+ * false, the run is fully removed (and `queryRuns` no longer finds it).
780
+ *
781
+ * Trade-off: kept summaries cost ~80 bytes per run (postgres) / one
782
+ * `RunSummary` (in-memory). Use `false` only if `queryRuns` history is
783
+ * not needed past the retention window.
784
+ */
785
+ readonly keepSummary?: boolean;
786
+ }
787
+ interface PruneResult {
788
+ readonly runsPruned: number;
789
+ readonly factsPruned: number;
790
+ }
679
791
  interface QueueMessage {
680
792
  readonly receipt: string;
681
793
  readonly runId: RunId;
@@ -719,7 +831,7 @@ interface Clock {
719
831
  interface Trigger {
720
832
  subscribe(handler: (runId: RunId) => void): () => void;
721
833
  }
722
- type FactKind = "flow.started" | "flow.completed" | "flow.failed" | "flow.canceled" | "step.started" | "step.completed" | "step.failed" | "step.retried" | "step.skipped" | "step.reset" | "signal.sent" | "signal.received" | "once.recorded" | "match.arm-selected";
834
+ type FactKind = "flow.started" | "flow.completed" | "flow.failed" | "flow.canceled" | "step.started" | "step.completed" | "step.failed" | "step.canceled" | "step.retried" | "step.skipped" | "step.reset" | "step.abort-requested" | "signal.sent" | "signal.received" | "once.recorded" | "match.arm-selected";
723
835
  interface FactBase {
724
836
  readonly runId: RunId;
725
837
  readonly at: Date;
@@ -742,6 +854,16 @@ interface FlowStartedFact extends FactBase {
742
854
  * "Topology vs handler code."
743
855
  */
744
856
  readonly codeVersion?: string;
857
+ /**
858
+ * For runs spawned by `b.subflow()`: the parent run that started this
859
+ * child, and the parent step id awaiting its completion. The pair forms a
860
+ * back-pointer the runtime uses to wake the parent step when this run
861
+ * reaches `flow.completed` / `flow.failed`. See RFC 0006 (issue #10).
862
+ *
863
+ * Both undefined for runs started directly via `wf.start()`.
864
+ */
865
+ readonly parentRunId?: RunId;
866
+ readonly parentStepId?: StepId;
745
867
  }
746
868
  /**
747
869
  * A non-run-scoped event, recorded as a side effect of nagi runtime activity
@@ -770,17 +892,36 @@ interface FlowFailedFact extends FactBase {
770
892
  readonly error: SerializedError;
771
893
  }
772
894
  /**
773
- * Recorded on a prior run when a new `wf.start()` with the same concurrency
774
- * group supersedes it. The fact lives in the canceled run's fact log (not
775
- * the new run's) — observers reading that run's history see exactly when and
776
- * why it was canceled.
895
+ * Recorded when a run reaches the canceled terminal status. Three cause
896
+ * paths share the same fact kind:
897
+ *
898
+ * - `"concurrency"` — a new `wf.start()` with the same concurrency group
899
+ * superseded this run. `canceledByRunId` is the new run; `concurrencyKey`
900
+ * is the shared key.
901
+ * - `"explicit"` — `wf.cancel(runId)` was called. `canceledByRunId === runId`,
902
+ * `concurrencyKey` carries the caller's `reason` string (back-compat).
903
+ * - `"operator"` — `wf.operator().abort(runId, { actor, note? })` was called.
904
+ * `actor` is required; `note` is optional human context. `canceledByRunId
905
+ * === runId`, `concurrencyKey === ""`.
906
+ *
907
+ * The `cause` field is the canonical discriminator. It is optional in the
908
+ * type for back-compat with pre-cause facts: projectors treat a missing
909
+ * `cause` as `"concurrency"` (the original semantic).
777
910
  */
778
911
  interface FlowCanceledFact extends FactBase {
779
912
  readonly kind: "flow.canceled";
780
- /** The new run that took over this run's concurrency slot. */
913
+ readonly cause?: "concurrency" | "explicit" | "operator";
914
+ /** The new run that took over this run's concurrency slot, or self for explicit/operator cancels. */
781
915
  readonly canceledByRunId: RunId;
782
- /** The shared concurrency key between this run and `canceledByRunId`. */
916
+ /**
917
+ * For `"concurrency"`: the shared concurrency key. For `"explicit"`: the
918
+ * caller's `reason` string (legacy carrier). For `"operator"`: empty.
919
+ */
783
920
  readonly concurrencyKey: string;
921
+ /** Operator who triggered the cancel. Present when `cause === "operator"`. */
922
+ readonly actor?: string;
923
+ /** Free-form audit note from the operator. */
924
+ readonly note?: string;
784
925
  }
785
926
  interface StepStartedFact extends FactBase {
786
927
  readonly kind: "step.started";
@@ -799,6 +940,25 @@ interface StepFailedFact extends FactBase {
799
940
  readonly attempt: AttemptNumber;
800
941
  readonly error: SerializedError;
801
942
  }
943
+ /**
944
+ * Terminal classification for a step whose attempt did not produce a
945
+ * `step.completed` output because the run was canceled while it was in
946
+ * flight — either because a newer `wf.start()` superseded this run via a
947
+ * concurrency group, or because the handler honored `ctx.signal` (composed
948
+ * with a user-supplied timeout, etc.) and threw an `AbortError`.
949
+ *
950
+ * Recorded in place of `step.completed` / `step.failed` so observers can
951
+ * discriminate "canceled mid-execution" from "handler errored". Not retried.
952
+ * `error` is preserved when the cancellation surfaced as a thrown
953
+ * `AbortError`; absent when classification happened at the boundary (handler
954
+ * returned normally on an already-canceled run).
955
+ */
956
+ interface StepCanceledFact extends FactBase {
957
+ readonly kind: "step.canceled";
958
+ readonly stepId: StepId;
959
+ readonly attempt: AttemptNumber;
960
+ readonly error?: SerializedError;
961
+ }
802
962
  interface StepRetriedFact extends FactBase {
803
963
  readonly kind: "step.retried";
804
964
  readonly stepId: StepId;
@@ -808,7 +968,28 @@ interface StepRetriedFact extends FactBase {
808
968
  interface StepSkippedFact extends FactBase {
809
969
  readonly kind: "step.skipped";
810
970
  readonly stepId: StepId;
811
- readonly reason: "when-false" | "transitive";
971
+ /**
972
+ * - `"when-false"` — the step's `when` predicate returned false.
973
+ * - `"transitive"` — an upstream dependency was skipped or failed.
974
+ * - `"manual"` — an operator explicitly skipped this step via
975
+ * `wf.operator().skip()`. `actor` + optional `note` + `cascade` are
976
+ * populated; the other reasons leave them undefined.
977
+ */
978
+ readonly reason: "when-false" | "transitive" | "manual";
979
+ /** Operator who triggered a manual skip. */
980
+ readonly actor?: string;
981
+ /** Free-form audit note for a manual skip. */
982
+ readonly note?: string;
983
+ /**
984
+ * For manual skips only. `"skip"` (default) keeps the existing locked
985
+ * semantic: downstream steps with `needs: { x }` are transitively skipped.
986
+ * `"continue"` lets downstream run with `needs.x === null` — same shape
987
+ * `resolveNeeds` produces for any skipped step, but the scheduler stops
988
+ * propagating the skip past this step. The handler is responsible for
989
+ * tolerating the null value; the type contract on `needs.x` (locked as
990
+ * unconditional `Output`) does not change.
991
+ */
992
+ readonly cascade?: "skip" | "continue";
812
993
  }
813
994
  interface SignalSentFact extends FactBase {
814
995
  readonly kind: "signal.sent";
@@ -840,20 +1021,57 @@ interface MatchArmSelectedFact extends FactBase {
840
1021
  /**
841
1022
  * Marks a step as cleared from the projected `RunState.steps` so the next
842
1023
  * `nextRunnable()` pass treats it (and any cascaded descendants) as runnable
843
- * again. Emitted by `wf.replay(runId, { from })` — one fact per step that the
844
- * runtime resolved as part of the cascade. The user-named step has
845
- * `cascadedFrom === undefined`; transitively reset descendants record the
846
- * originating step so read-side UIs can group them.
1024
+ * again. Emitted by `wf.replay(runId, { from })` and `wf.operator().retry()` —
1025
+ * one fact per step that the runtime resolved as part of the cascade. The
1026
+ * user-named step has `cascadedFrom === undefined`; transitively reset
1027
+ * descendants record the originating step so read-side UIs can group them.
1028
+ *
1029
+ * `actor` and `note` are populated only when the reset came from
1030
+ * `wf.operator().retry()`. Both are absent on user-driven `wf.replay({from})`
1031
+ * calls so the existing fact log shape is preserved.
847
1032
  */
848
1033
  interface StepResetFact extends FactBase {
849
1034
  readonly kind: "step.reset";
850
1035
  readonly stepId: StepId;
851
1036
  /** The user-named `from` step that caused this reset, when this fact is a cascaded descendant. */
852
1037
  readonly cascadedFrom?: StepId;
1038
+ /** Operator who triggered the retry. */
1039
+ readonly actor?: string;
1040
+ /** Free-form audit note from the operator. */
1041
+ readonly note?: string;
853
1042
  }
854
- type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | StepResetFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
1043
+ /**
1044
+ * Operator-initiated signal that a step's in-flight attempt should abort.
1045
+ * The cancel watcher in `executeTask` polls for this fact and calls
1046
+ * `ctx.signal.abort()` when it lands for the current `(stepId, attempt)`.
1047
+ *
1048
+ * This fact does not mutate projected state on its own — the resulting
1049
+ * `step.canceled` fact (recorded once the handler returns / throws) is what
1050
+ * marks the attempt terminal. Audit fields (`actor`, `note`) carry through
1051
+ * to the read-side.
1052
+ *
1053
+ * Emitted by `wf.operator().retry()` when called on a `running` step; the
1054
+ * subsequent `step.reset` + advance happens after the in-flight attempt
1055
+ * settles, so a single retry call writes:
1056
+ *
1057
+ * step.abort-requested (audit)
1058
+ * ... (handler aborts; step.canceled lands via boundary check)
1059
+ * step.reset (cascade)
1060
+ * ... (advance re-enqueues)
1061
+ */
1062
+ interface StepAbortRequestedFact extends FactBase {
1063
+ readonly kind: "step.abort-requested";
1064
+ readonly stepId: StepId;
1065
+ /** Attempt number being aborted — matches the in-flight attempt. */
1066
+ readonly attempt: AttemptNumber;
1067
+ /** Operator who requested the abort. */
1068
+ readonly actor: string;
1069
+ /** Free-form audit note. */
1070
+ readonly note?: string;
1071
+ }
1072
+ type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepCanceledFact | StepRetriedFact | StepSkippedFact | StepResetFact | StepAbortRequestedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
855
1073
  type RunStatus = "pending" | "running" | "completed" | "failed" | "canceled";
856
- type StepStatus = "pending" | "running" | "completed" | "failed" | "skipped";
1074
+ type StepStatus = "pending" | "running" | "completed" | "failed" | "canceled" | "skipped";
857
1075
  interface StepState {
858
1076
  readonly stepId: StepId;
859
1077
  readonly status: StepStatus;
@@ -908,6 +1126,81 @@ interface ReplayOpts {
908
1126
  */
909
1127
  readonly from?: StepId;
910
1128
  }
1129
+ /**
1130
+ * Audit fields common to every operator action. `actor` is free-form — the
1131
+ * adapter logs whatever the caller supplies. Authorization lives upstream
1132
+ * (HTTP / CLI / etc.), not in core; the operator surface trusts its caller.
1133
+ */
1134
+ interface OperatorAuditOpts {
1135
+ /** Identifier for the human or system that triggered this operation. */
1136
+ readonly actor: string;
1137
+ /** Optional free-form audit note recorded on the resulting fact(s). */
1138
+ readonly note?: string;
1139
+ }
1140
+ interface OperatorSkipOpts extends OperatorAuditOpts {
1141
+ /**
1142
+ * - `"skip"` (default) — downstream `needs.x` steps are transitively
1143
+ * skipped, matching the locked semantic for `when:false` and failure
1144
+ * propagation. Type contract on `needs.x` is preserved.
1145
+ * - `"continue"` — downstream `needs.x` steps run. The handler sees
1146
+ * `needs.x === null` (same shape `resolveNeeds` produces for any
1147
+ * skipped step). The handler is responsible for tolerating the null
1148
+ * value; the type contract on `needs.x` (locked as unconditional
1149
+ * `Output`) is not changed at the type level.
1150
+ */
1151
+ readonly cascade?: "skip" | "continue";
1152
+ }
1153
+ /**
1154
+ * Operator-facing API for unsticking runs. Returned by `wf.operator()`.
1155
+ * Every action appends an audit-bearing fact to the run's fact log so the
1156
+ * intervention is observable to downstream tooling without read-modify-write
1157
+ * against the materialized tables.
1158
+ *
1159
+ * Authorization is the caller's responsibility — typically a thin HTTP /
1160
+ * CLI wrapper checks who is allowed to call these before delegating.
1161
+ */
1162
+ interface Operator {
1163
+ /**
1164
+ * Mark `stepId` as skipped, regardless of its current state. Appends
1165
+ * `step.skipped` with `reason: "manual"`. Behavior on downstream cascade
1166
+ * is controlled by `opts.cascade`.
1167
+ *
1168
+ * Idempotent on already-terminal steps: a skip of a `completed` step is
1169
+ * a logged no-op, not a re-classification — the fact log preserves the
1170
+ * earlier `step.completed` and observers see both. To force a re-run,
1171
+ * use {@link retry} instead.
1172
+ *
1173
+ * Throws {@link NagiValidationError} if `stepId` is not a step in the
1174
+ * run's flow. Throws {@link NagiRuntimeError} if the run is already
1175
+ * terminal.
1176
+ */
1177
+ skip(runId: RunId, stepId: StepId, opts: OperatorSkipOpts): Promise<void>;
1178
+ /**
1179
+ * Re-run `stepId` and its descendants. Equivalent to
1180
+ * `wf.replay(runId, { from: stepId })` for terminal-state steps, with
1181
+ * audit fields stamped onto the resulting `step.reset` facts.
1182
+ *
1183
+ * For a step in `running` state, first appends
1184
+ * `step.abort-requested` so the in-flight handler's `ctx.signal`
1185
+ * aborts, waits for the attempt to land its `step.canceled` fact, then
1186
+ * proceeds with the reset cascade. The whole call resolves once the
1187
+ * step is ready to re-dispatch.
1188
+ *
1189
+ * Throws {@link NagiValidationError} if `stepId` is not a step in the
1190
+ * run's flow. Throws {@link NagiRuntimeError} if the run is `canceled`
1191
+ * (use a new run instead).
1192
+ */
1193
+ retry(runId: RunId, stepId: StepId, opts: OperatorAuditOpts): Promise<void>;
1194
+ /**
1195
+ * Cancel an entire run and all subflow descendants. Appends `flow.canceled`
1196
+ * with `cause: "operator"` and the operator's audit fields. In-flight step
1197
+ * handlers see their `ctx.signal` abort (via the dispatch-side cancel
1198
+ * watcher) and reclassify as `step.canceled` per the boundary check.
1199
+ *
1200
+ * Idempotent on already-terminal runs (logged no-op).
1201
+ */
1202
+ abort(runId: RunId, opts: OperatorAuditOpts): Promise<void>;
1203
+ }
911
1204
 
912
1205
  /**
913
1206
  * Construct a flow.
@@ -974,6 +1267,16 @@ interface CanonicalStep {
974
1267
  readonly matchMode?: "discriminator" | "guard";
975
1268
  readonly matchOnHash?: string;
976
1269
  readonly matchArms?: readonly CanonicalMatchArm[];
1270
+ /**
1271
+ * The referenced child flow's id. Topology changes in the child do NOT
1272
+ * propagate into the parent's hash — child carries its own `flowHash` on
1273
+ * its own `flow.started` fact. The parent's hash captures only the
1274
+ * structural fact "this step starts a child of this flow id with this
1275
+ * input mapping."
1276
+ */
1277
+ readonly childFlowId?: string;
1278
+ /** Hash of the `input: ({ input, needs }) => ChildInput` callback source. */
1279
+ readonly subflowInputHash?: string;
977
1280
  }
978
1281
  interface CanonicalDag {
979
1282
  readonly flowId: string;
@@ -1072,6 +1375,20 @@ declare class InMemoryStore implements Store {
1072
1375
  private readonly activeByKey;
1073
1376
  /** Reverse lookup so terminal facts can free the slot in O(1). */
1074
1377
  private readonly keyByActiveRun;
1378
+ /**
1379
+ * Index: parentRunId → set of child run ids spawned by `b.subflow()`.
1380
+ * Populated in `tryStartRun` when `fact.parentRunId` is set. Used by
1381
+ * `listChildren()` to power transitive cancel cascade in O(children).
1382
+ */
1383
+ private readonly childrenByParent;
1384
+ /**
1385
+ * Pruned-but-kept summaries. Populated by `pruneFacts` when `keepSummary`
1386
+ * is true so that `queryRuns` still surfaces runs whose facts were dropped.
1387
+ * Mirrors the postgres adapter's retained `workflow_run` row after a prune.
1388
+ * Also blocks `tryStartRun` from reusing a pruned runId — matching the
1389
+ * postgres `INSERT ... ON CONFLICT DO NOTHING` semantic on `run_id`.
1390
+ */
1391
+ private readonly summaries;
1075
1392
  private readonly leaseMs;
1076
1393
  constructor(opts?: InMemoryStoreOpts);
1077
1394
  appendFact(runId: RunId, fact: Fact): Promise<void>;
@@ -1085,6 +1402,7 @@ declare class InMemoryStore implements Store {
1085
1402
  readonly fact: FlowCanceledFact;
1086
1403
  }>;
1087
1404
  }>;
1405
+ listChildren(parentRunId: RunId): Promise<ReadonlyArray<RunId>>;
1088
1406
  loadRunState(runId: RunId): Promise<RunState>;
1089
1407
  claimStep(runId: RunId, stepId: StepId, attempt: AttemptNumber): Promise<ClaimToken | null>;
1090
1408
  completeStep(runId: RunId, stepId: StepId, output: Json, fact: Fact): Promise<void>;
@@ -1094,7 +1412,7 @@ declare class InMemoryStore implements Store {
1094
1412
  getOnce(runId: RunId, stepId: StepId, scope: string): Promise<Json | null>;
1095
1413
  runStep<T extends Json>(runId: RunId, stepId: StepId, _attempt: AttemptNumber, body: (tx: Tx) => Promise<{
1096
1414
  readonly output: T;
1097
- readonly fact: StepCompletedFact | StepFailedFact;
1415
+ readonly fact: StepCompletedFact | StepFailedFact | StepCanceledFact;
1098
1416
  }>): Promise<T>;
1099
1417
  upsertSnapshot(args: {
1100
1418
  readonly flowHash: string;
@@ -1111,6 +1429,7 @@ declare class InMemoryStore implements Store {
1111
1429
  /** Test-only: peek at the in-memory global fact log. */
1112
1430
  readGlobalFacts(): ReadonlyArray<GlobalFact>;
1113
1431
  queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
1432
+ pruneFacts(opts: Required<PruneOpts>): Promise<PruneResult>;
1114
1433
  }
1115
1434
  /**
1116
1435
  * Project an append-only fact stream into a `RunState`. Public so adapters
@@ -1204,11 +1523,30 @@ interface StartOpts {
1204
1523
  */
1205
1524
  readonly runId?: RunId;
1206
1525
  }
1526
+ interface CancelOpts {
1527
+ /**
1528
+ * Caller-supplied reason recorded on the `flow.canceled` fact. Surfaces in
1529
+ * the cascaded `step.failed` error message for any parent waiting on this
1530
+ * run via `b.subflow()`. Default: "explicit wf.cancel()".
1531
+ */
1532
+ readonly reason?: string;
1533
+ }
1207
1534
  interface Wf {
1208
1535
  /** Begin a new run. Returns the runId. */
1209
1536
  start<F extends Flow>(flow: F, input: FlowInput<F>, opts?: StartOpts): Promise<RunId>;
1210
1537
  /** Resolve a `b.signal()` step waiting on external input. */
1211
1538
  signal(runId: RunId, stepName: string, payload: unknown): Promise<void>;
1539
+ /**
1540
+ * Cancel a pending or running run. Writes `flow.canceled` to the run's
1541
+ * fact log and cascades transitively to every child run spawned by
1542
+ * `b.subflow()`. Idempotent: cancelling a run that's already terminal
1543
+ * (`completed` / `failed` / `canceled`) is a logged no-op.
1544
+ *
1545
+ * For canceled child runs, the parent's subflow step (if still running)
1546
+ * transitions to `failed` with a structured cancel error — the parent
1547
+ * doesn't hang waiting for a child that will never finish.
1548
+ */
1549
+ cancel(runId: RunId, opts?: CancelOpts): Promise<void>;
1212
1550
  /** Construct a worker; call `run` / `runOnce` / `runUntilEmpty` on it. */
1213
1551
  worker(config?: WorkerConfig): Worker;
1214
1552
  /**
@@ -1229,6 +1567,33 @@ interface Wf {
1229
1567
  * forbids `limit` / `cursor` at the type level.
1230
1568
  */
1231
1569
  queryRuns(opts?: QueryRunsOpts): Promise<QueryRunsResult>;
1570
+ /**
1571
+ * Operator-facing API for unsticking runs: `skip`, `retry`, `abort`. Each
1572
+ * action appends an audit-bearing fact to the run's fact log so the
1573
+ * intervention shows up in the read-side without read-modify-write
1574
+ * against materialized tables. See {@link Operator}.
1575
+ *
1576
+ * Authorization is the caller's responsibility — typically a thin
1577
+ * HTTP/CLI wrapper gates who is allowed to call these.
1578
+ */
1579
+ operator(): Operator;
1580
+ /**
1581
+ * Retention sweep over terminal runs. Deletes facts (and per-step rows,
1582
+ * leases, timers, dedupes) for runs whose `completedAt < olderThan` and
1583
+ * whose status is in `statuses` (default `["completed"]`). `pending` /
1584
+ * `running` runs are excluded at compile time via {@link PrunableStatus}
1585
+ * and re-validated at runtime.
1586
+ *
1587
+ * `keepSummary: true` (default) retains a summary row so `queryRuns` still
1588
+ * lists the pruned run; the postgres adapter keeps the `workflow_run` row
1589
+ * and the in-memory adapter keeps a shadow {@link RunSummary}. After a
1590
+ * prune, `loadRunState` and `replay` for that run return an empty state —
1591
+ * documented trade-off: you traded fact-fidelity for storage.
1592
+ *
1593
+ * Idempotent and safe under concurrent callers (postgres uses
1594
+ * `FOR UPDATE SKIP LOCKED` on the victim set).
1595
+ */
1596
+ pruneFacts(opts: PruneOpts): Promise<PruneResult>;
1232
1597
  }
1233
1598
  declare class NagiValidationError extends Error {
1234
1599
  readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
@@ -1272,4 +1637,4 @@ declare class NagiSnapshotDriftError extends Error {
1272
1637
  }
1273
1638
  declare function nagi(config: NagiConfig): Promise<Wf>;
1274
1639
 
1275
- export { type AsStepMap, type AttemptNumber, type BackoffStrategy, type BuildResult, type Builder, type BuilderAccumulator, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type ConcurrencyMode, type Fact, type FactKind, type Flow, type FlowCanceledFact, type FlowCompleteEvent, type FlowCompletedFact, type FlowConcurrency, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, type FlowInput, type FlowOutput, type FlowRefUpdatedFact, type FlowStartEvent, type FlowStartedFact, type GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, type InferSchemaInput, type InferSchemaOutput, type Json, type Logger, type MatchArm, type MatchArmGuard, type MatchArmOtherwise, type MatchArmOutput, type MatchArmSelectedFact, type MatchArmShape, type MatchDiscriminatorConfig, type MatchDiscriminatorOutput, type MatchGuardConfig, type Millis, NagiCanceledError, type NagiConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type QueryRunsOpts, type QueryRunsResult, type QueryRunsWhere, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type RetryPolicy, type RunId, type RunState, type RunStatus, type RunSummary, type SerializedError, type SignalConfig, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepEntryConfig, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepResetFact, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };
1640
+ export { type AsStepMap, type AttemptNumber, type BackoffStrategy, type BuildResult, type Builder, type BuilderAccumulator, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type ConcurrencyMode, type Fact, type FactKind, type Flow, type FlowCanceledFact, type FlowCompleteEvent, type FlowCompletedFact, type FlowConcurrency, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, type FlowInput, type FlowOutput, type FlowRefUpdatedFact, type FlowStartEvent, type FlowStartedFact, type GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, type InferSchemaInput, type InferSchemaOutput, type Json, type Logger, type MatchArm, type MatchArmGuard, type MatchArmOtherwise, type MatchArmOutput, type MatchArmSelectedFact, type MatchArmShape, type MatchDiscriminatorConfig, type MatchDiscriminatorOutput, type MatchGuardConfig, type Millis, NagiCanceledError, type NagiConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Operator, type OperatorAuditOpts, type OperatorSkipOpts, type PrunableStatus, type PruneOpts, type PruneResult, type QueryRunsOpts, type QueryRunsResult, type QueryRunsWhere, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type RetryPolicy, type RunId, type RunState, type RunStatus, type RunSummary, type SerializedError, type SignalConfig, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepAbortRequestedFact, type StepCanceledFact, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepEntryConfig, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepResetFact, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, type SubflowConfig, type SubflowStepOutput, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };