@nagi-js/core 0.1.1-rc.5 → 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
@@ -617,6 +617,64 @@ interface Store {
617
617
  * Currently only `flow_ref.updated` events flow through this method.
618
618
  */
619
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;
620
678
  }
621
679
  interface QueueMessage {
622
680
  readonly receipt: string;
@@ -661,7 +719,7 @@ interface Clock {
661
719
  interface Trigger {
662
720
  subscribe(handler: (runId: RunId) => void): () => void;
663
721
  }
664
- 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";
665
723
  interface FactBase {
666
724
  readonly runId: RunId;
667
725
  readonly at: Date;
@@ -779,7 +837,21 @@ interface MatchArmSelectedFact extends FactBase {
779
837
  readonly stepId: StepId;
780
838
  readonly arm: string;
781
839
  }
782
- 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;
783
855
  type RunStatus = "pending" | "running" | "completed" | "failed" | "canceled";
784
856
  type StepStatus = "pending" | "running" | "completed" | "failed" | "skipped";
785
857
  interface StepState {
@@ -821,6 +893,20 @@ interface ReplayOpts {
821
893
  * dual-publish.
822
894
  */
823
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;
824
910
  }
825
911
 
826
912
  /**
@@ -1024,6 +1110,7 @@ declare class InMemoryStore implements Store {
1024
1110
  appendGlobalFact(fact: GlobalFact): Promise<void>;
1025
1111
  /** Test-only: peek at the in-memory global fact log. */
1026
1112
  readGlobalFacts(): ReadonlyArray<GlobalFact>;
1113
+ queryRuns(opts: QueryRunsOpts): Promise<QueryRunsResult>;
1027
1114
  }
1028
1115
  /**
1029
1116
  * Project an append-only fact stream into a `RunState`. Public so adapters
@@ -1129,6 +1216,19 @@ interface Wf {
1129
1216
  * effects (idempotency protects); `mode: "inspect"` is a no-op probe.
1130
1217
  */
1131
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>;
1132
1232
  }
1133
1233
  declare class NagiValidationError extends Error {
1134
1234
  readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
@@ -1172,4 +1272,4 @@ declare class NagiSnapshotDriftError extends Error {
1172
1272
  }
1173
1273
  declare function nagi(config: NagiConfig): Promise<Wf>;
1174
1274
 
1175
- 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") {
@@ -629,6 +632,13 @@ var InMemoryStore = class {
629
632
  }
630
633
  }
631
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
+ }
632
642
  }
633
643
  async tryStartRun(runId, fact, concurrency) {
634
644
  if (this.facts.has(runId)) {
@@ -714,7 +724,113 @@ var InMemoryStore = class {
714
724
  readGlobalFacts() {
715
725
  return this.globalFacts;
716
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
+ }
717
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
+ }
718
834
  function projectRunState(runId, facts) {
719
835
  let flowId = "";
720
836
  let status = "pending";
@@ -768,6 +884,9 @@ function projectRunState(runId, facts) {
768
884
  attempts: 0
769
885
  };
770
886
  break;
887
+ case "step.reset":
888
+ delete steps[fact.stepId];
889
+ break;
771
890
  }
772
891
  }
773
892
  return {
@@ -1012,6 +1131,36 @@ function flowTermination(flow2, runState) {
1012
1131
  }
1013
1132
  return { done, failed };
1014
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
+ }
1015
1164
  function extractInput(runState) {
1016
1165
  for (const fact of runState.facts) {
1017
1166
  if (fact.kind === "flow.started") return fact.input;
@@ -1888,6 +2037,7 @@ async function nagi(config) {
1888
2037
  const fireHooks = opts.fireHooks !== false;
1889
2038
  const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
1890
2039
  let replayDeps = baseDeps;
2040
+ let effectiveFlow = liveFlow;
1891
2041
  const pinned = runState.flowHash;
1892
2042
  if (pinned !== void 0) {
1893
2043
  const liveHash = flowHashById.get(liveFlow.id);
@@ -1910,10 +2060,51 @@ async function nagi(config) {
1910
2060
  liveFlow
1911
2061
  );
1912
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);
1913
2091
  }
1914
2092
  }
1915
2093
  await advance(replayDeps, runId);
1916
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);
1917
2108
  }
1918
2109
  };
1919
2110
  }