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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -128,8 +128,15 @@ interface TaskConfig<Input, N extends NeedsMap, Output> extends StepConfigBase<I
128
128
  readonly onError?: (event: StepErrorEvent) => void | Promise<void>;
129
129
  readonly onRetry?: (event: StepRetryEvent) => void | Promise<void>;
130
130
  }
131
+ /**
132
+ * One signal step accepts one or more external signal names. Omitting
133
+ * `names` defaults to `[stepId]` (back-compat behavior). Passing `names:
134
+ * [...]` accepts any listed name; first arrival wins, late losers are a
135
+ * no-op + logged. Non-empty tuple type so `names: []` is a compile error.
136
+ */
131
137
  interface SignalConfig<Input, N extends NeedsMap, Schema extends StandardSchemaV1> extends StepConfigBase<Input, N> {
132
138
  readonly schema: Schema;
139
+ readonly names?: readonly [string, ...string[]];
133
140
  }
134
141
  /**
135
142
  * Discriminator mode — exhaustive at compile time. `cases` must cover every
@@ -610,6 +617,64 @@ interface Store {
610
617
  * Currently only `flow_ref.updated` events flow through this method.
611
618
  */
612
619
  appendGlobalFact(fact: GlobalFact): Promise<void>;
620
+ /**
621
+ * Discover runs by their input + flow + status. See {@link QueryRunsOpts}
622
+ * and {@link Wf.queryRuns} (in `runtime.ts`) for the public contract.
623
+ *
624
+ * Adapters MUST order results by `(startedAt DESC, runId DESC)` so cursor
625
+ * pagination is stable across calls. Adapters MUST treat
626
+ * `opts.where.input` as JSONB containment (Postgres `@>` semantics —
627
+ * the row's input is a superset of the filter object, recursively).
628
+ */
629
+ queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
630
+ }
631
+ interface QueryRunsWhere {
632
+ readonly flowId?: string;
633
+ readonly status?: RunStatus | ReadonlyArray<RunStatus>;
634
+ /**
635
+ * JSONB containment against `flow.started.input`. The stored input is a
636
+ * superset of this object — recursive on nested objects, exact on
637
+ * arrays/scalars. Example: `{ videoId: 'abc' }` matches
638
+ * `{ videoId: 'abc', userId: 7 }`.
639
+ *
640
+ * Containment only — no JSONPath, no operators. Combine keys for AND.
641
+ */
642
+ readonly input?: Record<string, Json>;
643
+ }
644
+ /**
645
+ * Options for {@link Wf.queryRuns}.
646
+ *
647
+ * Encoded as a discriminated union on `latest` so the type system rejects
648
+ * `{ latest: true, limit, cursor }` at compile time — those fields are
649
+ * meaningless when only one row is requested. Adapters still validate at
650
+ * runtime as defense-in-depth.
651
+ */
652
+ type QueryRunsOpts = {
653
+ readonly where?: QueryRunsWhere;
654
+ /** Return at most one run — the most recently started match. */
655
+ readonly latest: true;
656
+ readonly limit?: never;
657
+ readonly cursor?: never;
658
+ } | {
659
+ readonly where?: QueryRunsWhere;
660
+ readonly latest?: false;
661
+ /** Page size. Default 50, max 500. */
662
+ readonly limit?: number;
663
+ /** Opaque cursor from a previous `queryRuns` call. */
664
+ readonly cursor?: string;
665
+ };
666
+ interface RunSummary {
667
+ readonly runId: RunId;
668
+ readonly flowId: string;
669
+ readonly status: RunStatus;
670
+ readonly startedAt: Date;
671
+ readonly completedAt: Date | null;
672
+ readonly input: Json;
673
+ }
674
+ interface QueryRunsResult {
675
+ readonly runs: ReadonlyArray<RunSummary>;
676
+ /** Pass to the next `queryRuns` to resume. `null` when no more rows. */
677
+ readonly cursor: string | null;
613
678
  }
614
679
  interface QueueMessage {
615
680
  readonly receipt: string;
@@ -654,7 +719,7 @@ interface Clock {
654
719
  interface Trigger {
655
720
  subscribe(handler: (runId: RunId) => void): () => void;
656
721
  }
657
- type FactKind = "flow.started" | "flow.completed" | "flow.failed" | "flow.canceled" | "step.started" | "step.completed" | "step.failed" | "step.retried" | "step.skipped" | "signal.sent" | "signal.received" | "once.recorded" | "match.arm-selected";
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";
658
723
  interface FactBase {
659
724
  readonly runId: RunId;
660
725
  readonly at: Date;
@@ -754,6 +819,12 @@ interface SignalReceivedFact extends FactBase {
754
819
  readonly kind: "signal.received";
755
820
  readonly stepId: StepId;
756
821
  readonly payload: Json;
822
+ /**
823
+ * The alias the caller sent, when the resolved signal step accepts
824
+ * multiple names (or a single name != stepId). Absent when the incoming
825
+ * name equals the step id — the back-compat single-name case.
826
+ */
827
+ readonly signalName?: string;
757
828
  }
758
829
  interface OnceRecordedFact extends FactBase {
759
830
  readonly kind: "once.recorded";
@@ -766,7 +837,21 @@ interface MatchArmSelectedFact extends FactBase {
766
837
  readonly stepId: StepId;
767
838
  readonly arm: string;
768
839
  }
769
- type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
840
+ /**
841
+ * Marks a step as cleared from the projected `RunState.steps` so the next
842
+ * `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.
847
+ */
848
+ interface StepResetFact extends FactBase {
849
+ readonly kind: "step.reset";
850
+ readonly stepId: StepId;
851
+ /** The user-named `from` step that caused this reset, when this fact is a cascaded descendant. */
852
+ readonly cascadedFrom?: StepId;
853
+ }
854
+ type Fact = FlowStartedFact | FlowCompletedFact | FlowFailedFact | FlowCanceledFact | StepStartedFact | StepCompletedFact | StepFailedFact | StepRetriedFact | StepSkippedFact | StepResetFact | SignalSentFact | SignalReceivedFact | OnceRecordedFact | MatchArmSelectedFact;
770
855
  type RunStatus = "pending" | "running" | "completed" | "failed" | "canceled";
771
856
  type StepStatus = "pending" | "running" | "completed" | "failed" | "skipped";
772
857
  interface StepState {
@@ -808,6 +893,20 @@ interface ReplayOpts {
808
893
  * dual-publish.
809
894
  */
810
895
  readonly fireHooks?: boolean;
896
+ /**
897
+ * Replay starting from a specific step instead of the default "first
898
+ * incomplete" behavior. The runtime appends `step.reset` facts for `from`
899
+ * and every transitive descendant, then re-dispatches — completed steps
900
+ * downstream of `from` re-run, completed steps upstream are preserved.
901
+ *
902
+ * - Throws `NagiValidationError` if `from` is not a registered step in the
903
+ * effective flow (the snapshot topology under drift + `allowDrift`, else
904
+ * the live flow).
905
+ * - Throws `NagiRuntimeError` if the run is still `running` — resetting
906
+ * mid-flight races in-flight workers.
907
+ * - Ignored under `mode: "inspect"` (inspect remains side-effect-free).
908
+ */
909
+ readonly from?: StepId;
811
910
  }
812
911
 
813
912
  /**
@@ -865,6 +964,13 @@ interface CanonicalStep {
865
964
  readonly retry?: CanonicalRetryPolicy;
866
965
  readonly timeoutMs?: Millis;
867
966
  readonly signalSchema?: CanonicalSchema;
967
+ /**
968
+ * External signal names this step accepts, sorted lexicographically. Only
969
+ * present when the caller supplied `name` / `names` on `b.signal`; absent
970
+ * for the default "name == step id" case so pre-RFC-0004 flows hash
971
+ * byte-identically.
972
+ */
973
+ readonly signalNames?: readonly string[];
868
974
  readonly matchMode?: "discriminator" | "guard";
869
975
  readonly matchOnHash?: string;
870
976
  readonly matchArms?: readonly CanonicalMatchArm[];
@@ -1004,6 +1110,7 @@ declare class InMemoryStore implements Store {
1004
1110
  appendGlobalFact(fact: GlobalFact): Promise<void>;
1005
1111
  /** Test-only: peek at the in-memory global fact log. */
1006
1112
  readGlobalFacts(): ReadonlyArray<GlobalFact>;
1113
+ queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
1007
1114
  }
1008
1115
  /**
1009
1116
  * Project an append-only fact stream into a `RunState`. Public so adapters
@@ -1109,6 +1216,19 @@ interface Wf {
1109
1216
  * effects (idempotency protects); `mode: "inspect"` is a no-op probe.
1110
1217
  */
1111
1218
  replay(runId: RunId, opts?: ReplayOpts): Promise<void>;
1219
+ /**
1220
+ * Discover runs by flow / status / input. Read-only — does not create or
1221
+ * mutate runs. Use this to power read-side surfaces like "current run for
1222
+ * video X" without coupling consumers to nagi's storage schema.
1223
+ *
1224
+ * Filtering on `input` is JSONB containment: the stored input is a
1225
+ * superset of the filter object (recursive on nested objects).
1226
+ *
1227
+ * Pagination is keyset on `(startedAt, runId)` DESC. Pass the returned
1228
+ * `cursor` to the next call. `latest: true` returns at most one run and
1229
+ * forbids `limit` / `cursor` at the type level.
1230
+ */
1231
+ queryRuns(opts?: QueryRunsOpts): Promise<QueryRunsResult>;
1112
1232
  }
1113
1233
  declare class NagiValidationError extends Error {
1114
1234
  readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
@@ -1152,4 +1272,4 @@ declare class NagiSnapshotDriftError extends Error {
1152
1272
  }
1153
1273
  declare function nagi(config: NagiConfig): Promise<Wf>;
1154
1274
 
1155
- export { type AsStepMap, type AttemptNumber, type BackoffStrategy, type BuildResult, type Builder, type BuilderAccumulator, type CanonicalDag, type CanonicalMatchArm, type CanonicalRetryPolicy, type CanonicalSchema, type CanonicalStep, type ClaimToken, type Clock, type ConcurrencyMode, type Fact, type FactKind, type Flow, type FlowCanceledFact, type FlowCompleteEvent, type FlowCompletedFact, type FlowConcurrency, type FlowConfig, type FlowErrorEvent, type FlowEvent, type FlowFailedFact, type FlowHooks, type FlowInput, type FlowOutput, type FlowRefUpdatedFact, type FlowStartEvent, type FlowStartedFact, type GlobalFact, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, type InferSchemaInput, type InferSchemaOutput, type Json, type Logger, type MatchArm, type MatchArmGuard, type MatchArmOtherwise, type MatchArmOutput, type MatchArmSelectedFact, type MatchArmShape, type MatchDiscriminatorConfig, type MatchDiscriminatorOutput, type MatchGuardConfig, type Millis, NagiCanceledError, type NagiConfig, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, type NeedsMap, type NeedsOutputs, type OnceRecordedFact, type Queue, type QueueDequeueOpts, type QueueEnqueueOpts, type QueueMessage, type Register, type ReplayMode, type ReplayOpts, type RetryPolicy, type RunId, type RunState, type RunStatus, type SerializedError, type SignalConfig, type SignalReceivedEvent, type SignalReceivedFact, type SignalSentEvent, type SignalSentFact, type SnapshotChangedEdge, type SnapshotChangedField, type SnapshotDiff, StandardSchemaV1, type StartOpts, type Step, type StepCompleteEvent, type StepCompletedFact, type StepCtx, type StepEntryConfig, type StepErrorEvent, type StepEvent, type StepFailedFact, type StepId, type StepKind, type StepMap, type StepOutput, type StepRetriedFact, type StepRetryEvent, type StepSkippedFact, type StepStartEvent, type StepStartedFact, type StepState, type StepStatus, type Store, type TaskConfig, type Trigger, type Tx, type Wf, type Worker, type WorkerConfig, type WorkerRunOnceOpts, type WorkerRunResult, type WorkerRunUntilEmptyOpts, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };
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 };
package/dist/index.js CHANGED
@@ -37,12 +37,15 @@ function matchArms(def) {
37
37
  return def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
38
38
  }
39
39
  function readSelectedArm(matchId, runState) {
40
+ let selected = null;
40
41
  for (const fact of runState.facts) {
41
42
  if (fact.kind === "match.arm-selected" && fact.stepId === matchId) {
42
- return fact.arm;
43
+ selected = fact.arm;
44
+ } else if (fact.kind === "step.reset" && fact.stepId === matchId) {
45
+ selected = null;
43
46
  }
44
47
  }
45
- return null;
48
+ return selected;
46
49
  }
47
50
  function selectArm(def, args) {
48
51
  if (def.mode === "discriminator") {
@@ -104,6 +107,7 @@ function makeBuilder() {
104
107
  kind: "signal",
105
108
  needs: config.needs ?? {},
106
109
  schema: config.schema,
110
+ ...config.names !== void 0 ? { names: config.names } : {},
107
111
  ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
108
112
  ...config.when !== void 0 ? {
109
113
  when: config.when
@@ -227,6 +231,7 @@ function flow(config) {
227
231
  idByIdentity,
228
232
  out: finalSteps
229
233
  });
234
+ assertSignalNameUniqueness(config.id, finalSteps);
230
235
  return {
231
236
  id: config.id,
232
237
  input: config.input,
@@ -328,6 +333,28 @@ function walkAndRewrite(args) {
328
333
  out[id] = attachDef({ kind: finalizedDef.kind, id }, finalizedDef);
329
334
  }
330
335
  }
336
+ function assertSignalNameUniqueness(flowId, finalSteps) {
337
+ const owners = /* @__PURE__ */ new Map();
338
+ for (const stepId of Object.keys(finalSteps)) {
339
+ owners.set(stepId, `step id "${stepId}"`);
340
+ }
341
+ for (const [stepId, step] of Object.entries(finalSteps)) {
342
+ const def = step.__def;
343
+ if (def === void 0 || def.kind !== "signal") continue;
344
+ if (def.names === void 0) continue;
345
+ for (const alias of def.names) {
346
+ if (alias === stepId) continue;
347
+ const prior = owners.get(alias);
348
+ const here = `alias of step "${stepId}"`;
349
+ if (prior !== void 0 && prior !== here) {
350
+ throw new Error(
351
+ `Flow "${flowId}": signal name "${alias}" is declared as both ${prior} and ${here}. Pick one \u2014 signal names share a namespace with step ids.`
352
+ );
353
+ }
354
+ owners.set(alias, here);
355
+ }
356
+ }
357
+ }
331
358
 
332
359
  // src/canonicalize.ts
333
360
  var DEFAULT_RETRY = {
@@ -375,6 +402,9 @@ async function canonicalizeSignal(base, def) {
375
402
  if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
376
403
  if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
377
404
  out.signalSchema = await canonicalizeSchema(def.schema);
405
+ if (def.names !== void 0) {
406
+ out.signalNames = [...def.names].sort();
407
+ }
378
408
  return out;
379
409
  }
380
410
  async function canonicalizeMatch(base, def) {
@@ -602,6 +632,13 @@ var InMemoryStore = class {
602
632
  }
603
633
  }
604
634
  }
635
+ if (fact.kind === "step.reset") {
636
+ const leasePrefix = `${runId}::${fact.stepId}::`;
637
+ for (const key of this.leases.keys()) {
638
+ if (key.startsWith(leasePrefix)) this.leases.delete(key);
639
+ }
640
+ this.outputs.delete(`${runId}::${fact.stepId}`);
641
+ }
605
642
  }
606
643
  async tryStartRun(runId, fact, concurrency) {
607
644
  if (this.facts.has(runId)) {
@@ -687,7 +724,113 @@ var InMemoryStore = class {
687
724
  readGlobalFacts() {
688
725
  return this.globalFacts;
689
726
  }
727
+ async queryRuns(opts) {
728
+ const where = opts.where ?? {};
729
+ const statuses = where.status === void 0 ? void 0 : Array.isArray(where.status) ? where.status : [where.status];
730
+ const summaries = [];
731
+ for (const [runId, factList] of this.facts) {
732
+ const summary = summarize(runId, factList);
733
+ if (summary === null) continue;
734
+ if (where.flowId !== void 0 && summary.flowId !== where.flowId)
735
+ continue;
736
+ if (statuses !== void 0 && !statuses.includes(summary.status))
737
+ continue;
738
+ if (where.input !== void 0 && !containsJson(summary.input, where.input))
739
+ continue;
740
+ summaries.push(summary);
741
+ }
742
+ summaries.sort((a, b) => {
743
+ const t = b.startedAt.getTime() - a.startedAt.getTime();
744
+ if (t !== 0) return t;
745
+ return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
746
+ });
747
+ if (opts.latest === true) {
748
+ return { runs: summaries.slice(0, 1), cursor: null };
749
+ }
750
+ const limit = clampLimit(opts.limit);
751
+ let start = 0;
752
+ if (opts.cursor !== void 0) {
753
+ const c = decodeCursor(opts.cursor);
754
+ start = summaries.findIndex(
755
+ (s) => s.startedAt.getTime() < c.t || s.startedAt.getTime() === c.t && s.runId < c.r
756
+ );
757
+ if (start === -1) start = summaries.length;
758
+ }
759
+ const page = summaries.slice(start, start + limit);
760
+ const hasMore = start + limit < summaries.length;
761
+ const last = page[page.length - 1];
762
+ const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
763
+ return { runs: page, cursor };
764
+ }
690
765
  };
766
+ function summarize(runId, facts) {
767
+ const first = facts[0];
768
+ if (first === void 0 || first.kind !== "flow.started") return null;
769
+ const projected = projectRunState(runId, facts);
770
+ let completedAt = null;
771
+ for (let i = facts.length - 1; i >= 0; i--) {
772
+ const f = facts[i];
773
+ if (f === void 0) continue;
774
+ if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
775
+ completedAt = f.at;
776
+ break;
777
+ }
778
+ }
779
+ return {
780
+ runId,
781
+ flowId: first.flowId,
782
+ status: projected.status,
783
+ startedAt: first.at,
784
+ completedAt,
785
+ input: first.input
786
+ };
787
+ }
788
+ var DEFAULT_LIMIT = 50;
789
+ var MAX_LIMIT = 500;
790
+ function clampLimit(limit) {
791
+ if (limit === void 0) return DEFAULT_LIMIT;
792
+ if (!Number.isInteger(limit) || limit < 1) return DEFAULT_LIMIT;
793
+ return Math.min(limit, MAX_LIMIT);
794
+ }
795
+ function encodeCursor(c) {
796
+ const bytes = new TextEncoder().encode(JSON.stringify(c));
797
+ let binary = "";
798
+ for (let i = 0; i < bytes.length; i++) {
799
+ binary += String.fromCharCode(bytes[i]);
800
+ }
801
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
802
+ }
803
+ function decodeCursor(s) {
804
+ try {
805
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/");
806
+ const binary = atob(b64);
807
+ const bytes = new Uint8Array(binary.length);
808
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
809
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
810
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
811
+ return parsed;
812
+ }
813
+ throw new Error("malformed cursor body");
814
+ } catch (err) {
815
+ throw new Error(
816
+ `queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
817
+ );
818
+ }
819
+ }
820
+ function containsJson(haystack, needle) {
821
+ if (Array.isArray(needle)) {
822
+ if (!Array.isArray(haystack)) return false;
823
+ return needle.every((n) => haystack.some((h) => containsJson(h, n)));
824
+ }
825
+ if (needle !== null && typeof needle === "object") {
826
+ if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
827
+ return false;
828
+ return Object.entries(needle).every(
829
+ ([k, v]) => k in haystack && containsJson(haystack[k], v)
830
+ );
831
+ }
832
+ return haystack === needle;
833
+ }
691
834
  function projectRunState(runId, facts) {
692
835
  let flowId = "";
693
836
  let status = "pending";
@@ -741,6 +884,9 @@ function projectRunState(runId, facts) {
741
884
  attempts: 0
742
885
  };
743
886
  break;
887
+ case "step.reset":
888
+ delete steps[fact.stepId];
889
+ break;
744
890
  }
745
891
  }
746
892
  return {
@@ -985,6 +1131,36 @@ function flowTermination(flow2, runState) {
985
1131
  }
986
1132
  return { done, failed };
987
1133
  }
1134
+ function descendantsOf(flow2, stepId) {
1135
+ const children = /* @__PURE__ */ new Map();
1136
+ const addEdge = (from, to) => {
1137
+ const bucket = children.get(from);
1138
+ if (bucket) bucket.push(to);
1139
+ else children.set(from, [to]);
1140
+ };
1141
+ for (const [id, step] of Object.entries(flow2.steps)) {
1142
+ const def = getDef(step);
1143
+ for (const upstreamId of needsStepIds(def)) addEdge(upstreamId, id);
1144
+ if (def.kind === "match") {
1145
+ for (const arm of matchArms(def)) {
1146
+ for (const armStepId of arm.stepIds) addEdge(id, armStepId);
1147
+ }
1148
+ }
1149
+ }
1150
+ const out = [stepId];
1151
+ const seen = /* @__PURE__ */ new Set([stepId]);
1152
+ for (let i = 0; i < out.length; i++) {
1153
+ const current = out[i];
1154
+ if (current === void 0) continue;
1155
+ for (const child of children.get(current) ?? []) {
1156
+ if (seen.has(child)) continue;
1157
+ if (!(child in flow2.steps)) continue;
1158
+ seen.add(child);
1159
+ out.push(child);
1160
+ }
1161
+ }
1162
+ return out;
1163
+ }
988
1164
  function extractInput(runState) {
989
1165
  for (const fact of runState.facts) {
990
1166
  if (fact.kind === "flow.started") return fact.input;
@@ -1753,7 +1929,7 @@ async function nagi(config) {
1753
1929
  await advance(dispatchDeps, runId);
1754
1930
  return runId;
1755
1931
  },
1756
- async signal(runId, stepName, payload) {
1932
+ async signal(runId, signalName, payload) {
1757
1933
  const runState = await config.store.loadRunState(runId);
1758
1934
  const flow2 = flowsById.get(runState.flowId);
1759
1935
  if (!flow2) {
@@ -1761,53 +1937,71 @@ async function nagi(config) {
1761
1937
  `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
1762
1938
  );
1763
1939
  }
1764
- const step = flow2.steps[stepName];
1765
- if (!step) {
1766
- throw new NagiRuntimeError(
1767
- `Flow "${flow2.id}" has no step named "${stepName}".`
1768
- );
1940
+ let stepId;
1941
+ let def;
1942
+ const direct = flow2.steps[signalName];
1943
+ if (direct !== void 0) {
1944
+ const d = getDef(direct);
1945
+ if (d.kind === "signal" && d.names === void 0) {
1946
+ stepId = signalName;
1947
+ def = d;
1948
+ }
1769
1949
  }
1770
- const def = getDef(step);
1771
- if (def.kind !== "signal") {
1950
+ if (stepId === void 0) {
1951
+ for (const [id, s] of Object.entries(flow2.steps)) {
1952
+ const d = getDef(s);
1953
+ if (d.kind === "signal" && d.names?.includes(signalName)) {
1954
+ stepId = id;
1955
+ def = d;
1956
+ break;
1957
+ }
1958
+ }
1959
+ }
1960
+ if (stepId === void 0 || def === void 0) {
1772
1961
  throw new NagiRuntimeError(
1773
- `Step "${stepName}" is a ${def.kind}, not a signal.`
1962
+ `Flow "${flow2.id}" has no signal step accepting "${signalName}".`
1774
1963
  );
1775
1964
  }
1776
- const stepState = runState.steps[stepName];
1965
+ const stepState = runState.steps[stepId];
1777
1966
  if (stepState?.status !== "running") {
1967
+ if (stepState?.status === "completed") {
1968
+ config.logger?.info("nagi: signal arrived after step resolved", {
1969
+ runId,
1970
+ stepId,
1971
+ signalName
1972
+ });
1973
+ return;
1974
+ }
1778
1975
  throw new NagiRuntimeError(
1779
- `Step "${stepName}" is not waiting for signal (status: ${stepState?.status ?? "pending"}).`
1976
+ `Step "${stepId}" is not waiting for signal (status: ${stepState?.status ?? "pending"}).`
1780
1977
  );
1781
1978
  }
1782
1979
  const validated = await validate(def.schema, payload);
1783
1980
  const attempt = stepState.attempts > 0 ? stepState.attempts : 1;
1981
+ const carriesAlias = signalName !== stepId;
1784
1982
  await config.store.appendFact(runId, {
1785
1983
  kind: "signal.received",
1786
1984
  runId,
1787
- stepId: stepName,
1985
+ stepId,
1788
1986
  payload: validated,
1789
- at: clock.now()
1987
+ at: clock.now(),
1988
+ ...carriesAlias ? { signalName } : {}
1790
1989
  });
1791
1990
  const completedFact = {
1792
1991
  kind: "step.completed",
1793
1992
  runId,
1794
- stepId: stepName,
1993
+ stepId,
1795
1994
  attempt,
1796
1995
  output: validated,
1797
1996
  at: clock.now()
1798
1997
  };
1799
- await config.store.completeStep(
1800
- runId,
1801
- stepName,
1802
- validated,
1803
- completedFact
1804
- );
1998
+ await config.store.completeStep(runId, stepId, validated, completedFact);
1805
1999
  await fireHook(
1806
2000
  config.hooks?.onSignalReceived,
1807
2001
  {
1808
2002
  runId,
1809
2003
  flowId: flow2.id,
1810
- stepId: stepName,
2004
+ stepId,
1811
2005
  attempt,
1812
2006
  kind: "signal",
1813
2007
  payload: validated,
@@ -1843,6 +2037,7 @@ async function nagi(config) {
1843
2037
  const fireHooks = opts.fireHooks !== false;
1844
2038
  const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
1845
2039
  let replayDeps = baseDeps;
2040
+ let effectiveFlow = liveFlow;
1846
2041
  const pinned = runState.flowHash;
1847
2042
  if (pinned !== void 0) {
1848
2043
  const liveHash = flowHashById.get(liveFlow.id);
@@ -1865,10 +2060,51 @@ async function nagi(config) {
1865
2060
  liveFlow
1866
2061
  );
1867
2062
  replayDeps = { ...baseDeps, flowFor: async () => synthesized };
2063
+ effectiveFlow = synthesized;
2064
+ }
2065
+ }
2066
+ if (opts.from !== void 0) {
2067
+ if (runState.status === "running") {
2068
+ throw new NagiRuntimeError(
2069
+ `Run ${runId} is still running \u2014 replay({ from }) would race in-flight workers. Wait for the run to settle (completed / failed) before resetting from a step.`
2070
+ );
2071
+ }
2072
+ if (!(opts.from in effectiveFlow.steps)) {
2073
+ throw new NagiValidationError([
2074
+ {
2075
+ message: `replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
2076
+ path: ["from"]
2077
+ }
2078
+ ]);
2079
+ }
2080
+ const cascade = descendantsOf(effectiveFlow, opts.from);
2081
+ const at = clock.now();
2082
+ for (const stepId of cascade) {
2083
+ const fact = stepId === opts.from ? { kind: "step.reset", runId, at, stepId } : {
2084
+ kind: "step.reset",
2085
+ runId,
2086
+ at,
2087
+ stepId,
2088
+ cascadedFrom: opts.from
2089
+ };
2090
+ await config.store.appendFact(runId, fact);
1868
2091
  }
1869
2092
  }
1870
2093
  await advance(replayDeps, runId);
1871
2094
  if (!fireHooks) await drainInline(replayDeps);
2095
+ },
2096
+ async queryRuns(opts = {}) {
2097
+ if (opts.latest === true) {
2098
+ if (opts.limit !== void 0 || opts.cursor !== void 0) {
2099
+ throw new NagiValidationError([
2100
+ {
2101
+ message: "queryRuns: `latest: true` is incompatible with `limit` / `cursor` \u2014 `latest` returns at most one row.",
2102
+ path: ["latest"]
2103
+ }
2104
+ ]);
2105
+ }
2106
+ }
2107
+ return config.store.queryRuns(opts);
1872
2108
  }
1873
2109
  };
1874
2110
  }