@marianmeres/workflow 1.0.0

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/README.md ADDED
@@ -0,0 +1,227 @@
1
+ # @marianmeres/workflow
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/@marianmeres/workflow.svg)](https://www.npmjs.com/package/@marianmeres/workflow)
4
+ [![JSR version](https://jsr.io/badges/@marianmeres/workflow)](https://jsr.io/@marianmeres/workflow)
5
+ [![License](https://img.shields.io/npm/l/@marianmeres/workflow)](LICENSE)
6
+
7
+ A durable workflow / orchestration framework for long-lived state machines. Built on PostgreSQL.
8
+
9
+ Instances persist across process restarts, sleep for days waiting for a signal or a timer, and resume from disk via [`@marianmeres/fsm`](https://jsr.io/@marianmeres/fsm)'s `fromSnapshot`. Effects run as [`@marianmeres/steve`](https://jsr.io/@marianmeres/steve) jobs (transactional outbox). The scheduler and inbox correlator are driven by [`@marianmeres/cron`](https://jsr.io/@marianmeres/cron). Schema is managed by [`@marianmeres/migrate`](https://jsr.io/@marianmeres/migrate).
10
+
11
+ **Ships no domain code.** Userland brings the definitions, handlers, and matchers. The framework provides the dispatch core and the durability story.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ deno add jsr:@marianmeres/workflow
17
+ ```
18
+
19
+ ```sh
20
+ npm install @marianmeres/workflow
21
+ ```
22
+
23
+ Required peer: a PostgreSQL connection (`pg.Pool`).
24
+
25
+ ## Mental Model
26
+
27
+ A workflow is a **finite state machine with durable, long-lived instances**. Three concepts kept rigorously separate:
28
+
29
+ - **Definition** — Static, versioned, JSON-serializable graph of states. Pure data; handler/matcher ids are strings.
30
+ - **Instance** — One running occurrence of a definition. Lives as a row in `__workflow_instances`. Carries a *cursor* (current node) and a separate *execution_state* (lifecycle status).
31
+ - **Driver** — The advance engine. Stateless. Loads an instance, applies an outcome, dispatches the next step. Implemented as a steve job handler.
32
+
33
+ Each FSM state declares its **node kind** via `meta`:
34
+
35
+ | Kind | When the driver sees this state |
36
+ |---|---|
37
+ | `pure` | Fire `ENTER` to route via guards. Inline-expand. |
38
+ | `effectful` | Enqueue an effect handler job. Wait for completion. |
39
+ | `suspending` | Park the instance (`waiting`). Wake on `wake_at` (`TIMEOUT`) or matched inbox signal (`MATCHED`). |
40
+ | `terminal` | Mark instance `completed`. |
41
+
42
+ The user's handler returns `{ outcome, data }`. The driver calls `fsm.transition(outcome, data)`. The transition table picks the next state. There is no AI nondeterminism inside the FSM logic — return a label, look up the next node.
43
+
44
+ ## Example
45
+
46
+ A supplier-replenishment workflow: detect low stock → send order email → wait up to 60s for a reply → classify with AI → write the order.
47
+
48
+ ```typescript
49
+ import pg from "pg";
50
+ import { Jobs } from "@marianmeres/steve";
51
+ import { Cron } from "@marianmeres/cron";
52
+ import {
53
+ createMigrate,
54
+ Workflow,
55
+ WorkflowInboxCorrelator,
56
+ WorkflowScheduler,
57
+ type WorkflowDefinition,
58
+ } from "@marianmeres/workflow";
59
+
60
+ // 1. Define the workflow (pure data — handler/matcher names are strings)
61
+ const stockReplenishment: WorkflowDefinition = {
62
+ id: "stock_replenishment",
63
+ version: "1.0.0",
64
+ fsm: {
65
+ initial: "detect_low_stock",
66
+ states: {
67
+ detect_low_stock: {
68
+ meta: { kind: "effectful", handler: "checkInventory" },
69
+ on: { LOW: "send_order", OK: "_end_ok" },
70
+ },
71
+ send_order: {
72
+ meta: { kind: "effectful", handler: "sendOrderEmail" },
73
+ on: { SENT: "await_reply", FAILED: "_end_failed" },
74
+ },
75
+ await_reply: {
76
+ meta: { kind: "suspending", matcher: "matchEmailReply", timeoutSec: 60 },
77
+ on: { MATCHED: "classify_reply", TIMEOUT: "_end_timeout" },
78
+ },
79
+ classify_reply: {
80
+ meta: { kind: "effectful", handler: "aiClassifyReply" },
81
+ on: { CONFIRMED: "write_order", DENIED: "_end_denied", UNKNOWN: "_end_unknown" },
82
+ },
83
+ write_order: {
84
+ meta: { kind: "effectful", handler: "persistOrder" },
85
+ on: { OK: "_end_ok" },
86
+ },
87
+ _end_ok: { meta: { kind: "terminal" }, on: {} },
88
+ _end_failed: { meta: { kind: "terminal" }, on: {} },
89
+ _end_timeout: { meta: { kind: "terminal" }, on: {} },
90
+ _end_denied: { meta: { kind: "terminal" }, on: {} },
91
+ _end_unknown: { meta: { kind: "terminal" }, on: {} },
92
+ },
93
+ },
94
+ };
95
+
96
+ // 2. Connect + migrate
97
+ const pool = new pg.Pool({ /* ... */ });
98
+ await createMigrate(pool).up("latest");
99
+
100
+ // 3. Construct the runtime: steve.Jobs + cron.Cron are owned by *you*. The
101
+ // workflow framework attaches its handlers to them and the consumer owns
102
+ // the start/stop lifecycle. Share them with your app's other job/cron work
103
+ // if you want — they coexist by type/name on the same underlying tables.
104
+ const jobs = new Jobs({ db: pool });
105
+ const cron = new Cron({ db: pool });
106
+
107
+ // 4. Construct the Workflow. It registers `workflow.advance` + one
108
+ // `workflow.effect.<name>` handler per registered handler on the injected
109
+ // Jobs (via `jobs.setHandler`).
110
+ const wf = new Workflow({
111
+ db: pool,
112
+ jobs,
113
+ projectId: "default",
114
+ definitions: [stockReplenishment],
115
+ handlers: {
116
+ checkInventory: async (args) => ({ outcome: "LOW", data: { stock: 3 } }),
117
+ sendOrderEmail: async (args) => ({ outcome: "SENT", data: { messageId: "..." } }),
118
+ aiClassifyReply: async (args) => ({ outcome: "CONFIRMED", data: {} }),
119
+ persistOrder: async (args) => ({ outcome: "OK", data: { orderId: "..." } }),
120
+ },
121
+ matchers: {
122
+ matchEmailReply: ({ signal }) => signal.source === "email",
123
+ },
124
+ });
125
+
126
+ // 5. Attach the scheduler + correlator ticks to the injected Cron.
127
+ const scheduler = new WorkflowScheduler({ cron, workflow: wf });
128
+ const correlator = new WorkflowInboxCorrelator({ cron, workflow: wf });
129
+ await scheduler.register();
130
+ await correlator.register();
131
+
132
+ // 6. Start the runtimes. The consumer owns these.
133
+ await jobs.start(4);
134
+ await cron.start(2);
135
+
136
+ // 7. Create an instance
137
+ const instance = await wf.create({
138
+ definitionId: "stock_replenishment",
139
+ definitionVersion: "1.0.0",
140
+ correlationToken: crypto.randomUUID(),
141
+ });
142
+
143
+ // 8. When an external signal arrives, append it to the inbox. The
144
+ // correlator's next tick matches it to the waiting instance and fires
145
+ // `MATCHED` on the FSM.
146
+ await wf.appendInbox({
147
+ source: "email",
148
+ correlationToken: instance.correlation_token!,
149
+ payload: { subject: "Re: order", body: "yes please" },
150
+ });
151
+
152
+ // 9. Graceful shutdown — stop what you started.
153
+ await cron.stop();
154
+ await jobs.stop();
155
+ ```
156
+
157
+ ## How It Works
158
+
159
+ ```
160
+ ┌─ User application ─────────────────────────────────────────────────┐
161
+ │ WorkflowDefinition (pure data) + Handlers + Matchers │
162
+ │ steve.Jobs + cron.Cron (consumer-owned; start/stop) │
163
+ └────────────────────────────┬───────────────────────────────────────┘
164
+ ▼
165
+ ┌─ @marianmeres/workflow ────────────────────────────────────────────┐
166
+ │ Workflow WorkflowScheduler WorkflowInboxCorrelator │
167
+ │ │ attaches to │ attaches tick to │ attaches tick to │
168
+ │ │ injected Jobs │ injected Cron │ injected Cron │
169
+ │ ▼ ▼ ▼ │
170
+ │ __workflow_instances · __workflow_inbox · __workflow_history │
171
+ └────────────────────────────┬───────────────────────────────────────┘
172
+ ▼
173
+ PostgreSQL
174
+ ```
175
+
176
+ The framework owns no runtime processes. It registers job and cron handlers on the `Jobs` and `Cron` instances you pass in; you call `start()` / `stop()` on them. This lets the workflow's jobs/crons coexist with your application's own — they share `__job` / `__cron` tables and coexist by `type` / `name`. Sharing one runtime per process is cheaper than running parallel pollers.
177
+
178
+ A single steve job type — **`workflow.advance`** — encapsulates one step of the driver. Its payload is `{ project_id, instance_id, outcome?, outcome_data? }`. The handler:
179
+
180
+ 1. Locks the instance row inside a transaction.
181
+ 2. If an `outcome` was supplied (wake from effect / signal / timer), applies it via `fsm.transition(outcome, data)`. If the FSM rejects, the instance is marked `failed`.
182
+ 3. Loops on the current state's `meta.kind`, settling at the first terminal / effectful / suspending state and persisting the new cursor + execution_state in the same transaction.
183
+ 4. For effectful nodes, enqueues a **`workflow.effect.<handlerName>`** steve job. On its success, the effect handler enqueues a fresh advance carrying the outcome. On terminal failure, the instance is marked `failed`.
184
+
185
+ The **scheduler** runs as a registered cron job (default `* * * * *`). Each tick atomically flips `waiting` + `wake_at <= now()` rows to `pending`, clears `wake_at`, and enqueues a `workflow.advance` with `outcome: 'TIMEOUT'`.
186
+
187
+ The **correlator** runs as a registered cron job (default `* * * * *`). Each tick claims a batch of unprocessed `__workflow_inbox` rows, finds the waiting instance with the matching `correlation_token`, runs the user's `matcher` for the current state, and enqueues a `workflow.advance` with `outcome: 'MATCHED'` plus the signal payload.
188
+
189
+ ## Versioning Definitions
190
+
191
+ Each instance row stores `definition_version`. The framework looks up the definition by exact `(id, version)` match — **pin-and-freeze**. Bump the version for any change to the graph, payload schema, or handler semantics. Keep old versions registered until the last instance using them drains. Git remembers; the DB stores only a pointer.
192
+
193
+ ## Persistence Guarantees & Idempotency
194
+
195
+ - The advance step is a single PG transaction: cursor / execution_state / wake_at / history are all written together with the effect-job insert.
196
+ - Steve retries effect handlers per `effectMaxAttempts`. A worker crash mid-effect leaves the job in `running`; steve auto-cleanup reaps it after `~5min` and retries.
197
+ - **Handlers must be idempotent.** A handler can run multiple times for the same instance if a worker crashes after the side effect but before steve records completion. Use upserts, idempotency keys, or check the existing state.
198
+
199
+ ## Failure Modes
200
+
201
+ | Failure | Behavior |
202
+ |---|---|
203
+ | Effect handler throws repeatedly | Instance marked `failed`; `effect_failed` history entry. |
204
+ | FSM rejects the outcome label | Instance marked `failed`; `transition_rejected` history entry. |
205
+ | Pure node with no guard matching | Instance marked `failed`; `transition_rejected` history entry. |
206
+ | Definition missing on advance | Instance marked `failed`. Keep old versions registered until drained. |
207
+
208
+ ## Observability
209
+
210
+ Every transition, dispatch, signal, and failure is appended to `__workflow_history`. Read it via:
211
+
212
+ ```typescript
213
+ import { getHistory } from "@marianmeres/workflow";
214
+ const events = await getHistory(pool, instanceId);
215
+ ```
216
+
217
+ ## Multi-tenancy
218
+
219
+ Pass `projectId` to `Workflow`, `WorkflowScheduler`, and `WorkflowInboxCorrelator`. All three tables (and Cron's internal tables) carry `project_id`. One process can scope workers to a tenant while another scopes to a different tenant; the `FOR UPDATE SKIP LOCKED` claiming keeps them disjoint.
220
+
221
+ ## API
222
+
223
+ See [API.md](API.md) for the full reference. See [AGENTS.md](AGENTS.md) for the agent-oriented guide.
224
+
225
+ ## License
226
+
227
+ [MIT](LICENSE)
@@ -0,0 +1,56 @@
1
+ import type { Cron } from "@marianmeres/cron";
2
+ import type { Workflow } from "./workflow.js";
3
+ /** Options accepted by {@link WorkflowInboxCorrelator}. */
4
+ export interface WorkflowInboxCorrelatorOptions {
5
+ /**
6
+ * Externally-owned `@marianmeres/cron` `Cron` instance. The correlator
7
+ * registers its tick handler on this instance when `register()` is called.
8
+ * The consumer owns the lifecycle: `await cron.start(N)` / `await cron.stop()`.
9
+ */
10
+ cron: Cron;
11
+ /** The Workflow whose waiting instances this correlator delivers signals to. */
12
+ workflow: Workflow;
13
+ /** Cron expression for the tick. Default: every minute. */
14
+ tickExpression?: string;
15
+ /** IANA timezone for the cron expression. */
16
+ timezone?: string | null;
17
+ /** Maximum number of inbox rows claimed per tick. Default: 100. */
18
+ tickBatchSize?: number;
19
+ /** Custom name for the registered cron job. Default: `workflow.correlator.<projectId>`. */
20
+ tickName?: string;
21
+ }
22
+ /**
23
+ * Cron-driven correlator that matches `__workflow_inbox` rows to waiting
24
+ * workflow instances. On each tick:
25
+ *
26
+ * 1. Claim a batch of unprocessed inbox rows (`FOR UPDATE SKIP LOCKED`).
27
+ * 2. For each row, find a waiting instance with the same correlation_token.
28
+ * 3. Resolve the instance's current-state `meta.matcher` (if any), call it
29
+ * against the signal. The matcher is the semantic filter — the token is
30
+ * just the index lookup.
31
+ * 4. On match: enqueue an advance with `outcome: 'MATCHED'` carrying the
32
+ * signal payload, mark the inbox row processed, history entry.
33
+ * 5. On no-match (or no waiting instance): mark inbox row processed with
34
+ * `signal_rejected` history entry against the instance (if there was one).
35
+ *
36
+ * Like {@link WorkflowScheduler}, the correlator does not own its `Cron`. The
37
+ * caller constructs a `Cron`, passes it in, runs its lifecycle. Call
38
+ * `register()` once after construction to attach the tick.
39
+ */
40
+ export declare class WorkflowInboxCorrelator {
41
+ #private;
42
+ readonly cron: Cron;
43
+ readonly projectId: string;
44
+ readonly tickExpression: string;
45
+ readonly tickName: string;
46
+ constructor(options: WorkflowInboxCorrelatorOptions);
47
+ /**
48
+ * Registers the tick on the injected `Cron`. Idempotent — re-registering an
49
+ * existing name updates the expression/options but preserves `next_run_at`.
50
+ */
51
+ register(): Promise<void>;
52
+ /** Removes the tick from the injected `Cron`. */
53
+ unregister(): Promise<void>;
54
+ /** Runs one tick immediately. Exposed for testing and on-demand matches. */
55
+ tickOnce(): Promise<number>;
56
+ }
@@ -0,0 +1,144 @@
1
+ import { clog } from "./log.js";
2
+ import { appendHistory } from "./persistence/history.js";
3
+ import { claimUnprocessed, markProcessed } from "./persistence/inbox.js";
4
+ import { findWaitingByCorrelation } from "./persistence/instances.js";
5
+ import { withTransaction } from "./persistence/tx.js";
6
+ import { EXECUTION_STATE, HISTORY_EVENT, } from "./types.js";
7
+ const DEFAULT_TICK_EXPRESSION = "* * * * *";
8
+ /**
9
+ * Cron-driven correlator that matches `__workflow_inbox` rows to waiting
10
+ * workflow instances. On each tick:
11
+ *
12
+ * 1. Claim a batch of unprocessed inbox rows (`FOR UPDATE SKIP LOCKED`).
13
+ * 2. For each row, find a waiting instance with the same correlation_token.
14
+ * 3. Resolve the instance's current-state `meta.matcher` (if any), call it
15
+ * against the signal. The matcher is the semantic filter — the token is
16
+ * just the index lookup.
17
+ * 4. On match: enqueue an advance with `outcome: 'MATCHED'` carrying the
18
+ * signal payload, mark the inbox row processed, history entry.
19
+ * 5. On no-match (or no waiting instance): mark inbox row processed with
20
+ * `signal_rejected` history entry against the instance (if there was one).
21
+ *
22
+ * Like {@link WorkflowScheduler}, the correlator does not own its `Cron`. The
23
+ * caller constructs a `Cron`, passes it in, runs its lifecycle. Call
24
+ * `register()` once after construction to attach the tick.
25
+ */
26
+ export class WorkflowInboxCorrelator {
27
+ cron;
28
+ projectId;
29
+ tickExpression;
30
+ tickName;
31
+ #workflow;
32
+ #tickBatchSize;
33
+ #timezone;
34
+ constructor(options) {
35
+ this.cron = options.cron;
36
+ this.#workflow = options.workflow;
37
+ this.projectId = options.workflow.projectId;
38
+ this.tickExpression = options.tickExpression ?? DEFAULT_TICK_EXPRESSION;
39
+ this.tickName = options.tickName ?? `workflow.correlator.${this.projectId}`;
40
+ this.#tickBatchSize = options.tickBatchSize ?? 100;
41
+ this.#timezone = options.timezone;
42
+ }
43
+ /**
44
+ * Registers the tick on the injected `Cron`. Idempotent — re-registering an
45
+ * existing name updates the expression/options but preserves `next_run_at`.
46
+ */
47
+ async register() {
48
+ await this.cron.register(this.tickName, this.tickExpression, async () => {
49
+ await this.#tick();
50
+ }, {
51
+ timezone: this.#timezone,
52
+ });
53
+ }
54
+ /** Removes the tick from the injected `Cron`. */
55
+ async unregister() {
56
+ await this.cron.unregister(this.tickName);
57
+ }
58
+ /** Runs one tick immediately. Exposed for testing and on-demand matches. */
59
+ async tickOnce() {
60
+ return await this.#tick();
61
+ }
62
+ async #tick() {
63
+ let processed = 0;
64
+ await withTransaction(this.#workflow.db, async (client) => {
65
+ const rows = await claimUnprocessed(client, this.projectId, this.#tickBatchSize);
66
+ for (const row of rows) {
67
+ await this.#processOne(client, row);
68
+ processed++;
69
+ }
70
+ });
71
+ if (processed > 0)
72
+ clog.debug?.(`correlator: processed ${processed} signals`);
73
+ return processed;
74
+ }
75
+ async #processOne(client, row) {
76
+ const instance = await findWaitingByCorrelation(client, this.projectId, row.correlation_token);
77
+ if (!instance) {
78
+ await markProcessed(client, row.id);
79
+ return;
80
+ }
81
+ const def = this.#workflow.registry.getDefinition(instance.definition_id, instance.definition_version);
82
+ const stateCfg = def?.fsm.states[instance.cursor];
83
+ const meta = stateCfg?.meta;
84
+ // Run matcher if any. No matcher = correlation_token alone is the gate.
85
+ let matched = true;
86
+ if (meta && meta.kind === "suspending" && meta.matcher) {
87
+ const matcherFn = this.#workflow.registry.getMatcher(meta.matcher);
88
+ if (!matcherFn) {
89
+ clog.error?.(`correlator: matcher "${meta.matcher}" not registered for instance ${instance.id}`);
90
+ await appendHistory(client, {
91
+ project_id: this.projectId,
92
+ instance_id: instance.id,
93
+ event_type: HISTORY_EVENT.SIGNAL_REJECTED,
94
+ from_node: instance.cursor,
95
+ data: { reason: `unregistered matcher "${meta.matcher}"` },
96
+ });
97
+ await markProcessed(client, row.id);
98
+ return;
99
+ }
100
+ try {
101
+ matched = await matcherFn({
102
+ instanceId: instance.id,
103
+ projectId: this.projectId,
104
+ context: instance.context,
105
+ signal: row,
106
+ });
107
+ }
108
+ catch (e) {
109
+ clog.error?.(`correlator: matcher "${meta.matcher}" threw: ${e}`);
110
+ matched = false;
111
+ }
112
+ }
113
+ if (!matched) {
114
+ await appendHistory(client, {
115
+ project_id: this.projectId,
116
+ instance_id: instance.id,
117
+ event_type: HISTORY_EVENT.SIGNAL_REJECTED,
118
+ from_node: instance.cursor,
119
+ data: { source: row.source, inbox_id: row.id },
120
+ });
121
+ await markProcessed(client, row.id);
122
+ return;
123
+ }
124
+ await appendHistory(client, {
125
+ project_id: this.projectId,
126
+ instance_id: instance.id,
127
+ event_type: HISTORY_EVENT.SIGNAL_RECEIVED,
128
+ from_node: instance.cursor,
129
+ data: { source: row.source, inbox_id: row.id },
130
+ });
131
+ await markProcessed(client, row.id);
132
+ // Flip to pending so the scheduler / a re-tick won't double-fire. The
133
+ // advance handler will load and route based on cursor/meta.
134
+ await client.query(`UPDATE __workflow_instances
135
+ SET execution_state = $2, wake_at = NULL, updated_at = now()
136
+ WHERE id = $1`, [instance.id, EXECUTION_STATE.PENDING]);
137
+ await this.#workflow.enqueueAdvance(this.#workflow.db, {
138
+ project_id: this.projectId,
139
+ instance_id: instance.id,
140
+ outcome: "MATCHED",
141
+ outcome_data: row.payload,
142
+ });
143
+ }
144
+ }
@@ -0,0 +1,20 @@
1
+ import type { WorkflowDefinition } from "./types.js";
2
+ /**
3
+ * Validates a workflow definition against a set of registered handler/matcher
4
+ * names. Throws on any structural problem.
5
+ *
6
+ * Checks:
7
+ * - id and version are non-empty strings
8
+ * - fsm.initial exists in fsm.states
9
+ * - every state has a `meta` field with a known `kind`
10
+ * - every `effectful` state names a handler that is in `availableHandlers`
11
+ * - every `suspending` state's matcher (if present) is in `availableMatchers`
12
+ * - every transition target string resolves to a defined state
13
+ * - at least one terminal state exists
14
+ */
15
+ export declare function validateDefinition(def: WorkflowDefinition, available: {
16
+ handlers: ReadonlySet<string>;
17
+ matchers: ReadonlySet<string>;
18
+ }): void;
19
+ /** Composite key used in the definition registry. */
20
+ export declare function defKey(id: string, version: string): string;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Validates a workflow definition against a set of registered handler/matcher
3
+ * names. Throws on any structural problem.
4
+ *
5
+ * Checks:
6
+ * - id and version are non-empty strings
7
+ * - fsm.initial exists in fsm.states
8
+ * - every state has a `meta` field with a known `kind`
9
+ * - every `effectful` state names a handler that is in `availableHandlers`
10
+ * - every `suspending` state's matcher (if present) is in `availableMatchers`
11
+ * - every transition target string resolves to a defined state
12
+ * - at least one terminal state exists
13
+ */
14
+ export function validateDefinition(def, available) {
15
+ if (!def.id || typeof def.id !== "string") {
16
+ throw new Error(`Workflow definition: id must be a non-empty string`);
17
+ }
18
+ if (!def.version || typeof def.version !== "string") {
19
+ throw new Error(`Workflow definition "${def.id}": version must be a non-empty string`);
20
+ }
21
+ if (!def.fsm || typeof def.fsm !== "object") {
22
+ throw new Error(`Workflow definition "${def.id}@${def.version}": missing fsm`);
23
+ }
24
+ if (!def.fsm.initial || typeof def.fsm.initial !== "string") {
25
+ throw new Error(`Workflow definition "${def.id}@${def.version}": fsm.initial must be a non-empty string`);
26
+ }
27
+ if (!def.fsm.states || typeof def.fsm.states !== "object") {
28
+ throw new Error(`Workflow definition "${def.id}@${def.version}": fsm.states must be an object`);
29
+ }
30
+ if (!(def.fsm.initial in def.fsm.states)) {
31
+ throw new Error(`Workflow definition "${def.id}@${def.version}": initial state "${def.fsm.initial}" not in states`);
32
+ }
33
+ const stateNames = new Set(Object.keys(def.fsm.states));
34
+ let terminalCount = 0;
35
+ for (const [stateName, stateCfg] of Object.entries(def.fsm.states)) {
36
+ const meta = stateCfg.meta;
37
+ if (!meta || typeof meta !== "object") {
38
+ throw new Error(`Workflow definition "${def.id}@${def.version}": state "${stateName}" is missing meta`);
39
+ }
40
+ const kind = meta.kind;
41
+ switch (kind) {
42
+ case "pure":
43
+ break;
44
+ case "effectful": {
45
+ const h = meta.handler;
46
+ if (!h || typeof h !== "string") {
47
+ throw new Error(`Workflow definition "${def.id}@${def.version}": ` +
48
+ `effectful state "${stateName}" is missing a handler`);
49
+ }
50
+ if (!available.handlers.has(h)) {
51
+ throw new Error(`Workflow definition "${def.id}@${def.version}": ` +
52
+ `state "${stateName}" references unregistered handler "${h}"`);
53
+ }
54
+ break;
55
+ }
56
+ case "suspending": {
57
+ const m = meta.matcher;
58
+ if (m !== undefined) {
59
+ if (typeof m !== "string") {
60
+ throw new Error(`Workflow definition "${def.id}@${def.version}": ` +
61
+ `state "${stateName}" matcher must be a string`);
62
+ }
63
+ if (!available.matchers.has(m)) {
64
+ throw new Error(`Workflow definition "${def.id}@${def.version}": ` +
65
+ `state "${stateName}" references unregistered matcher "${m}"`);
66
+ }
67
+ }
68
+ break;
69
+ }
70
+ case "terminal":
71
+ terminalCount++;
72
+ break;
73
+ default:
74
+ throw new Error(`Workflow definition "${def.id}@${def.version}": ` +
75
+ `state "${stateName}" has unknown meta.kind "${String(kind)}"`);
76
+ }
77
+ // transition target validation
78
+ const on = stateCfg.on;
79
+ for (const [eventName, transition] of Object.entries(on ?? {})) {
80
+ const targets = [];
81
+ if (typeof transition === "string") {
82
+ targets.push(transition);
83
+ }
84
+ else if (Array.isArray(transition)) {
85
+ for (const t of transition)
86
+ targets.push(t.target);
87
+ }
88
+ else if (transition && typeof transition === "object") {
89
+ targets.push(transition.target);
90
+ }
91
+ for (const t of targets) {
92
+ if (t === undefined)
93
+ continue; // internal transition (action-only)
94
+ if (!stateNames.has(t)) {
95
+ throw new Error(`Workflow definition "${def.id}@${def.version}": ` +
96
+ `state "${stateName}" on event "${eventName}" targets unknown state "${t}"`);
97
+ }
98
+ }
99
+ }
100
+ }
101
+ if (terminalCount < 1) {
102
+ throw new Error(`Workflow definition "${def.id}@${def.version}": ` +
103
+ `needs at least one terminal state`);
104
+ }
105
+ }
106
+ /** Composite key used in the definition registry. */
107
+ export function defKey(id, version) {
108
+ return `${id}@${version}`;
109
+ }
@@ -0,0 +1,71 @@
1
+ import type pg from "pg";
2
+ import type { WorkflowRegistry } from "./registry.js";
3
+ import { type AdvanceJobPayload, type EffectJobPayload, JOB_TYPE_ADVANCE } from "./types.js";
4
+ /**
5
+ * Synthetic event fired by the driver when entering a pure (decision) state,
6
+ * so the user's guarded transitions can route by inspecting context.
7
+ *
8
+ * Pure nodes typically look like:
9
+ *
10
+ * foo: {
11
+ * meta: { kind: "pure" },
12
+ * on: {
13
+ * ENTER: [
14
+ * { target: "go_left", guard: (ctx) => ctx.x > 5 },
15
+ * { target: "go_right" },
16
+ * ],
17
+ * },
18
+ * }
19
+ */
20
+ export declare const PURE_ENTER_EVENT = "ENTER";
21
+ /**
22
+ * Function the driver uses to enqueue follow-up steve jobs. Supplied by the
23
+ * `Workflow` class — the driver itself doesn't reach back into steve.Jobs.
24
+ */
25
+ export interface JobEnqueuer {
26
+ enqueueAdvance(client: pg.PoolClient | pg.Client | pg.Pool, payload: AdvanceJobPayload): Promise<void>;
27
+ enqueueEffect(client: pg.PoolClient | pg.Client | pg.Pool, handler: string, payload: EffectJobPayload): Promise<void>;
28
+ }
29
+ /**
30
+ * The `workflow.advance` job body.
31
+ *
32
+ * Wrapped in a single PG transaction:
33
+ * 1. Lock the instance row.
34
+ * 2. If in a terminal execution_state, no-op.
35
+ * 3. If `outcome` was supplied, apply it via fsm.transition(outcome, data).
36
+ * - Reject → mark failed, append history.
37
+ * 4. Loop on the current state's meta.kind:
38
+ * - terminal → mark completed, return.
39
+ * - pure → fire `ENTER` synthetic event (with guards) and loop.
40
+ * - effectful → enqueue an effect job + mark running, return.
41
+ * - suspending → mark waiting, set wake_at/correlation_token, return.
42
+ */
43
+ export declare function runAdvance(pool: pg.Pool, registry: WorkflowRegistry, enqueuer: JobEnqueuer, payload: AdvanceJobPayload): Promise<void>;
44
+ /**
45
+ * The `workflow.effect.<handlerName>` job body.
46
+ *
47
+ * 1. Looks up the user handler in the registry by `payload.handler`.
48
+ * 2. Loads the instance to grab the current context (no lock — handlers run
49
+ * outside the advance tx).
50
+ * 3. Runs the handler.
51
+ * 4. On success: enqueues a `workflow.advance` job with the outcome + data.
52
+ * 5. On throw: re-throws so steve records the attempt as failed (steve retries
53
+ * per the job's `max_attempts`). When steve gives up, the on-failed hook in
54
+ * Workflow marks the instance failed.
55
+ *
56
+ * Handlers must be idempotent — steve may retry the handler if a worker crashes
57
+ * mid-execution, and even successful handlers can run twice if completion-write
58
+ * fails after the advance has been enqueued.
59
+ */
60
+ export declare function runEffect(pool: pg.Pool, registry: WorkflowRegistry, enqueuer: JobEnqueuer, payload: EffectJobPayload, signal?: AbortSignal): Promise<{
61
+ outcome: string;
62
+ data?: Record<string, unknown>;
63
+ }>;
64
+ /**
65
+ * Called by the Workflow layer when steve gives up on an effect job (all
66
+ * attempts exhausted or expired). Marks the workflow instance as failed.
67
+ */
68
+ export declare function failEffectJob(pool: pg.Pool, payload: EffectJobPayload, reason: string): Promise<void>;
69
+ /** Composite steve job-type string for an effect handler. */
70
+ export declare function effectJobType(handlerName: string): string;
71
+ export { JOB_TYPE_ADVANCE };