@nagi-js/postgres 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lymo, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,95 @@
1
+ import { Kysely } from 'kysely';
2
+ import { Millis, Store, Trigger } from '@nagi-js/core';
3
+
4
+ interface Migration {
5
+ readonly id: string;
6
+ readonly sql: (schema: string) => string;
7
+ }
8
+ /**
9
+ * v0 schema for `@nagi-js/postgres`. Each migration's `sql` builds a script
10
+ * for a configurable schema name — the default in `migrate()` is `nagi`.
11
+ *
12
+ * Inline strings, never `fs.readFileSync` — preserves edge-runtime safety
13
+ * (the adapter must be importable on Cloudflare Workers / Deno Deploy).
14
+ */
15
+ declare const migrations: readonly Migration[];
16
+ interface MigrateOpts {
17
+ /** Schema name; default `nagi`. */
18
+ readonly schema?: string;
19
+ }
20
+ /**
21
+ * Apply pending migrations idempotently. Maintains a `<schema>.schema_migrations`
22
+ * table; migrations whose ids are already recorded there are skipped.
23
+ *
24
+ * Each migration runs inside its own transaction, so a partial failure leaves
25
+ * the bookkeeping table consistent.
26
+ */
27
+ declare function migrate<DB>(db: Kysely<DB>, opts?: MigrateOpts): Promise<{
28
+ applied: readonly string[];
29
+ skipped: readonly string[];
30
+ }>;
31
+
32
+ interface PostgresStoreOpts<DB = unknown> {
33
+ /** User-supplied Kysely instance. Driver (`pg`, `postgres.js`, Neon) is the user's choice. */
34
+ readonly db: Kysely<DB>;
35
+ /** Schema name; default `nagi`. Must match `/^[A-Za-z_][A-Za-z0-9_]*$/`. */
36
+ readonly schema?: string;
37
+ /** Lease duration in milliseconds; default 60_000. */
38
+ readonly leaseMs?: Millis;
39
+ /**
40
+ * If provided, the store emits `pg_notify(<channel>, runId)` after writing
41
+ * each fact. Pair with `postgresTrigger({ listen, channel })` to wake
42
+ * schedulers without polling.
43
+ */
44
+ readonly notifyChannel?: string;
45
+ }
46
+ declare function postgresStore<DB = unknown>(opts: PostgresStoreOpts<DB>): Store;
47
+
48
+ /**
49
+ * Minimal shape the trigger needs from a LISTEN-capable Postgres client.
50
+ * Compatible with `pg.Client` (Node) and a thin wrapper over `pg.Pool` /
51
+ * `@neondatabase/serverless`'s `Client`. Kysely does not expose a long-lived
52
+ * connection for LISTEN, so this is a separate driver handle by design.
53
+ */
54
+ interface ListenClient {
55
+ query(text: string): Promise<unknown>;
56
+ on(event: "notification", handler: (msg: NotificationMessage) => void): void;
57
+ removeListener?(event: "notification", handler: (msg: NotificationMessage) => void): void;
58
+ off?(event: "notification", handler: (msg: NotificationMessage) => void): void;
59
+ }
60
+ interface NotificationMessage {
61
+ readonly channel: string;
62
+ readonly payload?: string | undefined;
63
+ }
64
+ interface PostgresTriggerOpts {
65
+ /**
66
+ * Long-lived LISTEN client. The trigger calls `LISTEN <channel>` on it once
67
+ * and never closes it — lifetime is the user's. Reuse one client per
68
+ * worker process; do not share with query workloads (pg's `Pool` rotates
69
+ * connections, which would drop `LISTEN` state).
70
+ */
71
+ readonly listen: ListenClient;
72
+ /** NOTIFY channel name. Default `nagi`. Must match the Store's `notifyChannel`. */
73
+ readonly channel?: string;
74
+ }
75
+ /**
76
+ * Wake the scheduler when the Store writes facts. Pair with
77
+ * `postgresStore({ notifyChannel })` so every `appendFact` /
78
+ * `completeStep` / `failStep` emits `pg_notify(channel, runId)`.
79
+ *
80
+ * Subscribers receive only the `runId`. The scheduler is responsible for
81
+ * loading the run's state and deciding what to advance.
82
+ */
83
+ declare function postgresTrigger(opts: PostgresTriggerOpts): Trigger;
84
+
85
+ /**
86
+ * Generate a UUIDv7 string in canonical 8-4-4-4-12 hex form.
87
+ *
88
+ * `tttttttt-tttt-7rrr-vrrr-rrrrrrrrrrrr`
89
+ *
90
+ * where `t` is the millisecond timestamp, `7` is the version nibble, `v` is
91
+ * the variant nibble (high two bits `10`), and `r` is random.
92
+ */
93
+ declare function uuidv7(now?: number): string;
94
+
95
+ export { type ListenClient, type MigrateOpts, type Migration, type NotificationMessage, type PostgresStoreOpts, type PostgresTriggerOpts, migrate, migrations, postgresStore, postgresTrigger, uuidv7 };
package/dist/index.js ADDED
@@ -0,0 +1,465 @@
1
+ import { sql } from 'kysely';
2
+ import { projectRunState } from '@nagi-js/core';
3
+
4
+ // src/migrations.ts
5
+ var migrations = [
6
+ {
7
+ id: "0001_init",
8
+ sql: (schema) => `
9
+ CREATE SCHEMA IF NOT EXISTS ${schema};
10
+
11
+ CREATE TABLE IF NOT EXISTS ${schema}.workflow_run (
12
+ run_id text PRIMARY KEY,
13
+ flow_id text NOT NULL,
14
+ status text NOT NULL CHECK (status IN ('pending','running','completed','failed')),
15
+ input jsonb NOT NULL,
16
+ output jsonb,
17
+ error jsonb,
18
+ started_at timestamptz NOT NULL DEFAULT now(),
19
+ completed_at timestamptz
20
+ );
21
+ CREATE INDEX IF NOT EXISTS workflow_run_flow_status_idx
22
+ ON ${schema}.workflow_run (flow_id, status);
23
+
24
+ CREATE TABLE IF NOT EXISTS ${schema}.step_run (
25
+ run_id text NOT NULL,
26
+ step_id text NOT NULL,
27
+ attempt integer NOT NULL,
28
+ status text NOT NULL CHECK (status IN ('pending','running','completed','failed','skipped')),
29
+ output jsonb,
30
+ error jsonb,
31
+ started_at timestamptz,
32
+ completed_at timestamptz,
33
+ PRIMARY KEY (run_id, step_id, attempt)
34
+ );
35
+ CREATE INDEX IF NOT EXISTS step_run_lookup_idx
36
+ ON ${schema}.step_run (run_id, step_id, attempt DESC);
37
+
38
+ CREATE TABLE IF NOT EXISTS ${schema}.fact (
39
+ run_id text NOT NULL,
40
+ fact_id text NOT NULL,
41
+ kind text NOT NULL,
42
+ at timestamptz NOT NULL,
43
+ payload jsonb NOT NULL,
44
+ PRIMARY KEY (run_id, fact_id)
45
+ );
46
+ CREATE INDEX IF NOT EXISTS fact_run_id_idx
47
+ ON ${schema}.fact (run_id, fact_id);
48
+
49
+ CREATE TABLE IF NOT EXISTS ${schema}.lease (
50
+ run_id text NOT NULL,
51
+ step_id text NOT NULL,
52
+ attempt integer NOT NULL,
53
+ token text NOT NULL,
54
+ expires_at timestamptz NOT NULL,
55
+ PRIMARY KEY (run_id, step_id, attempt)
56
+ );
57
+ CREATE INDEX IF NOT EXISTS lease_expires_idx
58
+ ON ${schema}.lease (expires_at);
59
+
60
+ CREATE TABLE IF NOT EXISTS ${schema}.timer (
61
+ run_id text NOT NULL,
62
+ step_id text NOT NULL,
63
+ fire_at timestamptz NOT NULL,
64
+ PRIMARY KEY (run_id, step_id)
65
+ );
66
+ CREATE INDEX IF NOT EXISTS timer_fire_at_idx
67
+ ON ${schema}.timer (fire_at);
68
+
69
+ CREATE TABLE IF NOT EXISTS ${schema}.dedupe (
70
+ run_id text NOT NULL,
71
+ step_id text NOT NULL,
72
+ scope text NOT NULL,
73
+ value jsonb NOT NULL,
74
+ recorded_at timestamptz NOT NULL DEFAULT now(),
75
+ PRIMARY KEY (run_id, step_id, scope)
76
+ );
77
+ `
78
+ }
79
+ ];
80
+ async function migrate(db, opts = {}) {
81
+ const schema = opts.schema ?? "nagi";
82
+ assertValidSchema(schema);
83
+ const applied = [];
84
+ const skipped = [];
85
+ await sql.raw(
86
+ `CREATE SCHEMA IF NOT EXISTS ${schema};
87
+ CREATE TABLE IF NOT EXISTS ${schema}.schema_migrations (
88
+ id text PRIMARY KEY,
89
+ applied_at timestamptz NOT NULL DEFAULT now()
90
+ );`
91
+ ).execute(db);
92
+ for (const m of migrations) {
93
+ await db.transaction().execute(async (tx) => {
94
+ const existing = await sql`
95
+ SELECT id FROM ${sql.raw(`${schema}.schema_migrations`)}
96
+ WHERE id = ${m.id}
97
+ `.execute(tx);
98
+ if (existing.rows.length > 0) {
99
+ skipped.push(m.id);
100
+ return;
101
+ }
102
+ await sql.raw(m.sql(schema)).execute(tx);
103
+ await sql`
104
+ INSERT INTO ${sql.raw(`${schema}.schema_migrations`)} (id) VALUES (${m.id})
105
+ `.execute(tx);
106
+ applied.push(m.id);
107
+ });
108
+ }
109
+ return { applied, skipped };
110
+ }
111
+ function assertValidSchema(schema) {
112
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema)) {
113
+ throw new Error(
114
+ `@nagi-js/postgres: invalid schema name "${schema}". Must match /^[A-Za-z_][A-Za-z0-9_]*$/.`
115
+ );
116
+ }
117
+ }
118
+
119
+ // src/uuidv7.ts
120
+ var HEX = "0123456789abcdef";
121
+ function toHex(bytes) {
122
+ let out = "";
123
+ for (let i = 0; i < bytes.length; i++) {
124
+ const b = bytes[i];
125
+ out += HEX[b >> 4];
126
+ out += HEX[b & 15];
127
+ }
128
+ return out;
129
+ }
130
+ function uuidv7(now = Date.now()) {
131
+ const bytes = new Uint8Array(16);
132
+ const ts = Math.floor(now);
133
+ const hi = Math.floor(ts / 4294967296);
134
+ const lo = ts >>> 0;
135
+ bytes[0] = hi >>> 8 & 255;
136
+ bytes[1] = hi & 255;
137
+ bytes[2] = lo >>> 24 & 255;
138
+ bytes[3] = lo >>> 16 & 255;
139
+ bytes[4] = lo >>> 8 & 255;
140
+ bytes[5] = lo & 255;
141
+ const rand = new Uint8Array(10);
142
+ crypto.getRandomValues(rand);
143
+ for (let i = 0; i < 10; i++) {
144
+ bytes[6 + i] = rand[i];
145
+ }
146
+ bytes[6] = bytes[6] & 15 | 112;
147
+ bytes[8] = bytes[8] & 63 | 128;
148
+ const hex = toHex(bytes);
149
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
150
+ }
151
+
152
+ // src/store.ts
153
+ var DEFAULT_LEASE_MS = 6e4;
154
+ var SCHEMA_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
155
+ function postgresStore(opts) {
156
+ return new PostgresStore(opts);
157
+ }
158
+ var PostgresStore = class {
159
+ db;
160
+ schema;
161
+ leaseMs;
162
+ notifyChannel;
163
+ constructor(opts) {
164
+ if (!SCHEMA_RE.test(opts.schema ?? "nagi")) {
165
+ throw new Error(
166
+ `@nagi-js/postgres: invalid schema name "${opts.schema}". Must match /^[A-Za-z_][A-Za-z0-9_]*$/.`
167
+ );
168
+ }
169
+ this.db = opts.db;
170
+ this.schema = opts.schema ?? "nagi";
171
+ this.leaseMs = opts.leaseMs ?? DEFAULT_LEASE_MS;
172
+ this.notifyChannel = opts.notifyChannel;
173
+ }
174
+ /** Schema-qualified table name for raw SQL interpolation. */
175
+ t(table) {
176
+ return `${this.schema}.${table}`;
177
+ }
178
+ async appendFact(runId, fact) {
179
+ await this.db.transaction().execute(async (trx) => {
180
+ await this.insertFact(trx, runId, fact);
181
+ await this.applyFactToMaterialized(trx, runId, fact);
182
+ });
183
+ await this.maybeNotify(runId);
184
+ }
185
+ async tryStartRun(runId, fact) {
186
+ const started = await this.db.transaction().execute(async (trx) => {
187
+ const insert = await sql`
188
+ INSERT INTO ${sql.raw(this.t("workflow_run"))}
189
+ (run_id, flow_id, status, input, started_at)
190
+ VALUES
191
+ (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at})
192
+ ON CONFLICT (run_id) DO NOTHING
193
+ RETURNING run_id
194
+ `.execute(trx);
195
+ if (insert.rows.length === 0) {
196
+ return false;
197
+ }
198
+ await this.insertFact(trx, runId, fact);
199
+ return true;
200
+ });
201
+ if (started) {
202
+ await this.maybeNotify(runId);
203
+ }
204
+ return { started };
205
+ }
206
+ async loadRunState(runId) {
207
+ const rows = await sql`
208
+ SELECT kind, at, payload
209
+ FROM ${sql.raw(this.t("fact"))}
210
+ WHERE run_id = ${runId}
211
+ ORDER BY fact_id ASC
212
+ `.execute(this.db);
213
+ const facts = rows.rows.map(
214
+ (r) => reviveFact(r.kind, r.at, r.payload)
215
+ );
216
+ return projectRunState(runId, facts);
217
+ }
218
+ async claimStep(runId, stepId, attempt) {
219
+ const token = `lease-${crypto.randomUUID()}`;
220
+ const expiresAt = new Date(Date.now() + this.leaseMs);
221
+ const result = await sql`
222
+ INSERT INTO ${sql.raw(this.t("lease"))} (run_id, step_id, attempt, token, expires_at)
223
+ VALUES (${runId}, ${stepId}, ${attempt}, ${token}, ${expiresAt})
224
+ ON CONFLICT (run_id, step_id, attempt) DO UPDATE
225
+ SET token = EXCLUDED.token, expires_at = EXCLUDED.expires_at
226
+ WHERE ${sql.raw(this.t("lease"))}.expires_at < now()
227
+ RETURNING token
228
+ `.execute(this.db);
229
+ const row = result.rows[0];
230
+ return row ? row.token : null;
231
+ }
232
+ async completeStep(runId, stepId, output, fact) {
233
+ await this.db.transaction().execute(async (trx) => {
234
+ await this.upsertStepCompleted(
235
+ trx,
236
+ runId,
237
+ stepId,
238
+ fact.kind === "step.completed" ? fact.attempt : 1,
239
+ output
240
+ );
241
+ await this.insertFact(trx, runId, fact);
242
+ await this.applyFactToMaterialized(trx, runId, fact);
243
+ await this.deleteLease(trx, runId, stepId);
244
+ });
245
+ await this.maybeNotify(runId);
246
+ }
247
+ async failStep(runId, stepId, error, fact) {
248
+ await this.db.transaction().execute(async (trx) => {
249
+ await this.upsertStepFailed(
250
+ trx,
251
+ runId,
252
+ stepId,
253
+ fact.kind === "step.failed" ? fact.attempt : 1,
254
+ error
255
+ );
256
+ await this.insertFact(trx, runId, fact);
257
+ await this.applyFactToMaterialized(trx, runId, fact);
258
+ await this.deleteLease(trx, runId, stepId);
259
+ });
260
+ await this.maybeNotify(runId);
261
+ }
262
+ async getStepOutput(runId, stepId) {
263
+ const r = await sql`
264
+ SELECT output
265
+ FROM ${sql.raw(this.t("step_run"))}
266
+ WHERE run_id = ${runId} AND step_id = ${stepId} AND status = 'completed'
267
+ ORDER BY attempt DESC
268
+ LIMIT 1
269
+ `.execute(this.db);
270
+ return r.rows[0]?.output ?? null;
271
+ }
272
+ async recordOnce(runId, stepId, scope, value) {
273
+ await sql`
274
+ INSERT INTO ${sql.raw(this.t("dedupe"))} (run_id, step_id, scope, value)
275
+ VALUES (${runId}, ${stepId}, ${scope}, ${jsonb(value)})
276
+ ON CONFLICT (run_id, step_id, scope) DO NOTHING
277
+ `.execute(this.db);
278
+ }
279
+ async getOnce(runId, stepId, scope) {
280
+ const r = await sql`
281
+ SELECT value
282
+ FROM ${sql.raw(this.t("dedupe"))}
283
+ WHERE run_id = ${runId} AND step_id = ${stepId} AND scope = ${scope}
284
+ `.execute(this.db);
285
+ return r.rows[0]?.value ?? null;
286
+ }
287
+ async runStep(runId, stepId, attempt, body) {
288
+ const output = await this.db.transaction().execute(async (trx) => {
289
+ const result = await body(trx);
290
+ if (result.fact.kind === "step.completed") {
291
+ await this.upsertStepCompleted(
292
+ trx,
293
+ runId,
294
+ stepId,
295
+ attempt,
296
+ result.fact.output
297
+ );
298
+ } else {
299
+ await this.upsertStepFailed(
300
+ trx,
301
+ runId,
302
+ stepId,
303
+ attempt,
304
+ result.fact.error
305
+ );
306
+ }
307
+ await this.insertFact(trx, runId, result.fact);
308
+ await this.deleteLease(trx, runId, stepId);
309
+ return result.output;
310
+ });
311
+ await this.maybeNotify(runId);
312
+ return output;
313
+ }
314
+ async insertFact(trx, runId, fact) {
315
+ await sql`
316
+ INSERT INTO ${sql.raw(this.t("fact"))} (run_id, fact_id, kind, at, payload)
317
+ VALUES (${runId}, ${uuidv7()}, ${fact.kind}, ${fact.at}, ${jsonb(serializeFactPayload(fact))})
318
+ `.execute(trx);
319
+ }
320
+ async applyFactToMaterialized(trx, runId, fact) {
321
+ switch (fact.kind) {
322
+ case "flow.started":
323
+ await sql`
324
+ INSERT INTO ${sql.raw(this.t("workflow_run"))} (run_id, flow_id, status, input, started_at)
325
+ VALUES (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at})
326
+ ON CONFLICT (run_id) DO NOTHING
327
+ `.execute(trx);
328
+ return;
329
+ case "flow.completed":
330
+ await sql`
331
+ UPDATE ${sql.raw(this.t("workflow_run"))}
332
+ SET status = 'completed', output = ${jsonb(fact.output)}, completed_at = ${fact.at}
333
+ WHERE run_id = ${runId}
334
+ `.execute(trx);
335
+ return;
336
+ case "flow.failed":
337
+ await sql`
338
+ UPDATE ${sql.raw(this.t("workflow_run"))}
339
+ SET status = 'failed', error = ${jsonb(fact.error)}, completed_at = ${fact.at}
340
+ WHERE run_id = ${runId}
341
+ `.execute(trx);
342
+ return;
343
+ case "step.started":
344
+ await sql`
345
+ INSERT INTO ${sql.raw(this.t("step_run"))} (run_id, step_id, attempt, status, started_at)
346
+ VALUES (${runId}, ${fact.stepId}, ${fact.attempt}, 'running', ${fact.at})
347
+ ON CONFLICT (run_id, step_id, attempt) DO UPDATE
348
+ SET status = 'running', started_at = EXCLUDED.started_at
349
+ `.execute(trx);
350
+ return;
351
+ case "step.skipped":
352
+ await sql`
353
+ INSERT INTO ${sql.raw(this.t("step_run"))} (run_id, step_id, attempt, status)
354
+ VALUES (${runId}, ${fact.stepId}, 0, 'skipped')
355
+ ON CONFLICT (run_id, step_id, attempt) DO UPDATE SET status = 'skipped'
356
+ `.execute(trx);
357
+ return;
358
+ case "once.recorded":
359
+ await sql`
360
+ INSERT INTO ${sql.raw(this.t("dedupe"))} (run_id, step_id, scope, value)
361
+ VALUES (${runId}, ${fact.stepId}, ${fact.scope}, ${jsonb(fact.value)})
362
+ ON CONFLICT (run_id, step_id, scope) DO NOTHING
363
+ `.execute(trx);
364
+ return;
365
+ // step.completed / step.failed are materialized by runStep / completeStep / failStep
366
+ // before insertFact, so applyFactToMaterialized is a no-op for them.
367
+ case "step.completed":
368
+ case "step.failed":
369
+ case "step.retried":
370
+ case "signal.sent":
371
+ case "signal.received":
372
+ case "match.arm-selected":
373
+ return;
374
+ }
375
+ }
376
+ async upsertStepCompleted(trx, runId, stepId, attempt, output) {
377
+ await sql`
378
+ INSERT INTO ${sql.raw(this.t("step_run"))}
379
+ (run_id, step_id, attempt, status, output, started_at, completed_at)
380
+ VALUES
381
+ (${runId}, ${stepId}, ${attempt}, 'completed', ${jsonb(output)}, now(), now())
382
+ ON CONFLICT (run_id, step_id, attempt) DO UPDATE
383
+ SET status = 'completed', output = EXCLUDED.output, completed_at = now()
384
+ `.execute(trx);
385
+ }
386
+ async upsertStepFailed(trx, runId, stepId, attempt, error) {
387
+ await sql`
388
+ INSERT INTO ${sql.raw(this.t("step_run"))}
389
+ (run_id, step_id, attempt, status, error, started_at, completed_at)
390
+ VALUES
391
+ (${runId}, ${stepId}, ${attempt}, 'failed', ${jsonb(error)}, now(), now())
392
+ ON CONFLICT (run_id, step_id, attempt) DO UPDATE
393
+ SET status = 'failed', error = EXCLUDED.error, completed_at = now()
394
+ `.execute(trx);
395
+ }
396
+ async deleteLease(trx, runId, stepId) {
397
+ await sql`
398
+ DELETE FROM ${sql.raw(this.t("lease"))}
399
+ WHERE run_id = ${runId} AND step_id = ${stepId}
400
+ `.execute(trx);
401
+ }
402
+ async maybeNotify(runId) {
403
+ if (!this.notifyChannel) return;
404
+ await sql`SELECT pg_notify(${this.notifyChannel}, ${runId})`.execute(
405
+ this.db
406
+ );
407
+ }
408
+ };
409
+ function serializeFactPayload(fact) {
410
+ const { kind: _kind, at: _at, runId: _runId, ...rest } = fact;
411
+ return rest;
412
+ }
413
+ function reviveFact(kind, at, payload) {
414
+ const body = payload ?? {};
415
+ return {
416
+ kind,
417
+ at: at instanceof Date ? at : new Date(at),
418
+ ...body
419
+ };
420
+ }
421
+ function jsonb(value) {
422
+ return sql`${JSON.stringify(value)}::jsonb`;
423
+ }
424
+
425
+ // src/trigger.ts
426
+ function postgresTrigger(opts) {
427
+ const channel = opts.channel ?? "nagi";
428
+ assertValidChannel(channel);
429
+ const handlers = /* @__PURE__ */ new Set();
430
+ let started = false;
431
+ const onNotification = (msg) => {
432
+ if (msg.channel !== channel) return;
433
+ const runId = msg.payload ?? "";
434
+ if (!runId) return;
435
+ for (const h of handlers) h(runId);
436
+ };
437
+ return {
438
+ subscribe(handler) {
439
+ handlers.add(handler);
440
+ if (!started) {
441
+ started = true;
442
+ opts.listen.on("notification", onNotification);
443
+ void opts.listen.query(`LISTEN ${channel}`).catch((err) => {
444
+ queueMicrotask(() => {
445
+ throw err;
446
+ });
447
+ });
448
+ }
449
+ return () => {
450
+ handlers.delete(handler);
451
+ };
452
+ }
453
+ };
454
+ }
455
+ function assertValidChannel(channel) {
456
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(channel)) {
457
+ throw new Error(
458
+ `@nagi-js/postgres: invalid NOTIFY channel "${channel}". Must match /^[A-Za-z_][A-Za-z0-9_]*$/.`
459
+ );
460
+ }
461
+ }
462
+
463
+ export { migrate, migrations, postgresStore, postgresTrigger, uuidv7 };
464
+ //# sourceMappingURL=index.js.map
465
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/migrations.ts","../src/uuidv7.ts","../src/store.ts","../src/trigger.ts"],"names":["sql"],"mappings":";;;;AAeO,IAAM,UAAA,GAAmC;AAAA,EAC9C;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,GAA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;AAI7C,QAAA,KAAK,IAAA,CAAK,OAAO,KAAA,CAAM,CAAA,OAAA,EAAU,OAAO,CAAA,CAAE,CAAA,CAAE,KAAA,CAAM,CAAC,GAAA,KAAQ;AACzD,UAAA,cAAA,CAAe,MAAM;AACnB,YAAA,MAAM,GAAA;AAAA,UACR,CAAC,CAAA;AAAA,QACH,CAAC,CAAA;AAAA,MACH;AAEA,MAAA,OAAO,MAAM;AACX,QAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AAAA,MACzB,CAAA;AAAA,IACF;AAAA,GACF;AACF;AAMA,SAAS,mBAAmB,OAAA,EAAuB;AACjD,EAAA,IAAI,CAAC,0BAAA,CAA2B,IAAA,CAAK,OAAO,CAAA,EAAG;AAC7C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,8CAA8C,OAAO,CAAA,yCAAA;AAAA,KACvD;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nexport interface Migration {\n readonly id: string;\n readonly sql: (schema: string) => string;\n}\n\n/**\n * v0 schema for `@nagi-js/postgres`. Each migration's `sql` builds a script\n * for a configurable schema name — the default in `migrate()` is `nagi`.\n *\n * Inline strings, never `fs.readFileSync` — preserves edge-runtime safety\n * (the adapter must be importable on Cloudflare Workers / Deno Deploy).\n */\nexport const migrations: readonly Migration[] = [\n {\n id: \"0001_init\",\n sql: (schema) => `\n CREATE SCHEMA IF NOT EXISTS ${schema};\n\n CREATE TABLE IF NOT EXISTS ${schema}.workflow_run (\n run_id text PRIMARY KEY,\n flow_id text NOT NULL,\n status text NOT NULL CHECK (status IN ('pending','running','completed','failed')),\n input jsonb NOT NULL,\n output jsonb,\n error jsonb,\n started_at timestamptz NOT NULL DEFAULT now(),\n completed_at timestamptz\n );\n CREATE INDEX IF NOT EXISTS workflow_run_flow_status_idx\n ON ${schema}.workflow_run (flow_id, status);\n\n CREATE TABLE IF NOT EXISTS ${schema}.step_run (\n run_id text NOT NULL,\n step_id text NOT NULL,\n attempt integer NOT NULL,\n status text NOT NULL CHECK (status IN ('pending','running','completed','failed','skipped')),\n output jsonb,\n error jsonb,\n started_at timestamptz,\n completed_at timestamptz,\n PRIMARY KEY (run_id, step_id, attempt)\n );\n CREATE INDEX IF NOT EXISTS step_run_lookup_idx\n ON ${schema}.step_run (run_id, step_id, attempt DESC);\n\n CREATE TABLE IF NOT EXISTS ${schema}.fact (\n run_id text NOT NULL,\n fact_id text NOT NULL,\n kind text NOT NULL,\n at timestamptz NOT NULL,\n payload jsonb NOT NULL,\n PRIMARY KEY (run_id, fact_id)\n );\n CREATE INDEX IF NOT EXISTS fact_run_id_idx\n ON ${schema}.fact (run_id, fact_id);\n\n CREATE TABLE IF NOT EXISTS ${schema}.lease (\n run_id text NOT NULL,\n step_id text NOT NULL,\n attempt integer NOT NULL,\n token text NOT NULL,\n expires_at timestamptz NOT NULL,\n PRIMARY KEY (run_id, step_id, attempt)\n );\n CREATE INDEX IF NOT EXISTS lease_expires_idx\n ON ${schema}.lease (expires_at);\n\n CREATE TABLE IF NOT EXISTS ${schema}.timer (\n run_id text NOT NULL,\n step_id text NOT NULL,\n fire_at timestamptz NOT NULL,\n PRIMARY KEY (run_id, step_id)\n );\n CREATE INDEX IF NOT EXISTS timer_fire_at_idx\n ON ${schema}.timer (fire_at);\n\n CREATE TABLE IF NOT EXISTS ${schema}.dedupe (\n run_id text NOT NULL,\n step_id text NOT NULL,\n scope text NOT NULL,\n value jsonb NOT NULL,\n recorded_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (run_id, step_id, scope)\n );\n `,\n },\n];\n\nexport interface MigrateOpts {\n /** Schema name; default `nagi`. */\n readonly schema?: string;\n}\n\n/**\n * Apply pending migrations idempotently. Maintains a `<schema>.schema_migrations`\n * table; migrations whose ids are already recorded there are skipped.\n *\n * Each migration runs inside its own transaction, so a partial failure leaves\n * the bookkeeping table consistent.\n */\nexport async function migrate<DB>(\n db: Kysely<DB>,\n opts: MigrateOpts = {},\n): Promise<{ applied: readonly string[]; skipped: readonly string[] }> {\n const schema = opts.schema ?? \"nagi\";\n assertValidSchema(schema);\n\n const applied: string[] = [];\n const skipped: string[] = [];\n\n // Bootstrap the bookkeeping table outside any user migration. Idempotent.\n await sql\n .raw(\n `CREATE SCHEMA IF NOT EXISTS ${schema};\n CREATE TABLE IF NOT EXISTS ${schema}.schema_migrations (\n id text PRIMARY KEY,\n applied_at timestamptz NOT NULL DEFAULT now()\n );`,\n )\n .execute(db);\n\n for (const m of migrations) {\n await db.transaction().execute(async (tx) => {\n const existing = await sql<{ id: string }>`\n SELECT id FROM ${sql.raw(`${schema}.schema_migrations`)}\n WHERE id = ${m.id}\n `.execute(tx);\n if (existing.rows.length > 0) {\n skipped.push(m.id);\n return;\n }\n await sql.raw(m.sql(schema)).execute(tx);\n await sql`\n INSERT INTO ${sql.raw(`${schema}.schema_migrations`)} (id) VALUES (${m.id})\n `.execute(tx);\n applied.push(m.id);\n });\n }\n\n return { applied, skipped };\n}\n\n/**\n * Reject schema names with anything other than `[A-Za-z_][A-Za-z0-9_]*` to\n * guard against SQL injection — the schema name is interpolated raw into\n * every DDL string. Kysely's `sql` tag cannot bind identifiers, only values.\n */\nfunction assertValidSchema(schema: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema)) {\n throw new Error(\n `@nagi-js/postgres: invalid schema name \"${schema}\". Must match /^[A-Za-z_][A-Za-z0-9_]*$/.`,\n );\n }\n}\n","// UUIDv7 generator per RFC 9562 § 5.7.\n// Time-ordered: 48-bit Unix milliseconds, 4-bit version (7), 12-bit\n// sub-millisecond random, 2-bit variant (10), 62-bit random tail. Lex-sortable\n// at millisecond resolution; collisions within the same ms are decided by the\n// 74 random bits.\n//\n// Edge-safe: uses `crypto.getRandomValues` only — no node:crypto, no Buffer.\n\nconst HEX = \"0123456789abcdef\";\n\nfunction toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i++) {\n const b = bytes[i] as number;\n out += HEX[b >> 4];\n out += HEX[b & 0x0f];\n }\n return out;\n}\n\n/**\n * Generate a UUIDv7 string in canonical 8-4-4-4-12 hex form.\n *\n * `tttttttt-tttt-7rrr-vrrr-rrrrrrrrrrrr`\n *\n * where `t` is the millisecond timestamp, `7` is the version nibble, `v` is\n * the variant nibble (high two bits `10`), and `r` is random.\n */\nexport function uuidv7(now: number = Date.now()): string {\n const bytes = new Uint8Array(16);\n\n // 48-bit timestamp in big-endian, ms since unix epoch.\n // Math.floor required because Date.now() is already an integer but we want\n // to be explicit and tolerate fractional millisecond inputs from tests.\n const ts = Math.floor(now);\n // JS bitwise ops are 32-bit, so split the 48-bit value into high-16 / low-32.\n const hi = Math.floor(ts / 0x1_0000_0000);\n const lo = ts >>> 0;\n bytes[0] = (hi >>> 8) & 0xff;\n bytes[1] = hi & 0xff;\n bytes[2] = (lo >>> 24) & 0xff;\n bytes[3] = (lo >>> 16) & 0xff;\n bytes[4] = (lo >>> 8) & 0xff;\n bytes[5] = lo & 0xff;\n\n // 10 random bytes for the rest; we overlay the version/variant nibbles after.\n const rand = new Uint8Array(10);\n crypto.getRandomValues(rand);\n for (let i = 0; i < 10; i++) {\n bytes[6 + i] = rand[i] as number;\n }\n\n // Version 7 in the high nibble of byte 6.\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x70;\n // Variant 10xx in the high two bits of byte 8.\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80;\n\n const hex = toHex(bytes);\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","import type {\n AttemptNumber,\n ClaimToken,\n Fact,\n FlowStartedFact,\n Json,\n Millis,\n RunId,\n RunState,\n SerializedError,\n StepCompletedFact,\n StepFailedFact,\n StepId,\n Store,\n Tx,\n} from \"@nagi-js/core\";\nimport { projectRunState } from \"@nagi-js/core\";\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\nimport { uuidv7 } from \"./uuidv7\";\n\nconst DEFAULT_LEASE_MS: Millis = 60_000;\nconst SCHEMA_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport interface PostgresStoreOpts<DB = unknown> {\n /** User-supplied Kysely instance. Driver (`pg`, `postgres.js`, Neon) is the user's choice. */\n readonly db: Kysely<DB>;\n /** Schema name; default `nagi`. Must match `/^[A-Za-z_][A-Za-z0-9_]*$/`. */\n readonly schema?: string;\n /** Lease duration in milliseconds; default 60_000. */\n readonly leaseMs?: Millis;\n /**\n * If provided, the store emits `pg_notify(<channel>, runId)` after writing\n * each fact. Pair with `postgresTrigger({ listen, channel })` to wake\n * schedulers without polling.\n */\n readonly notifyChannel?: string;\n}\n\nexport function postgresStore<DB = unknown>(\n opts: PostgresStoreOpts<DB>,\n): Store {\n return new PostgresStore(opts);\n}\n\nclass PostgresStore<DB = unknown> implements Store {\n private readonly db: Kysely<DB>;\n private readonly schema: string;\n private readonly leaseMs: Millis;\n private readonly notifyChannel: string | undefined;\n\n constructor(opts: PostgresStoreOpts<DB>) {\n if (!SCHEMA_RE.test(opts.schema ?? \"nagi\")) {\n throw new Error(\n `@nagi-js/postgres: invalid schema name \"${opts.schema}\". Must match /^[A-Za-z_][A-Za-z0-9_]*$/.`,\n );\n }\n this.db = opts.db;\n this.schema = opts.schema ?? \"nagi\";\n this.leaseMs = opts.leaseMs ?? DEFAULT_LEASE_MS;\n this.notifyChannel = opts.notifyChannel;\n }\n\n /** Schema-qualified table name for raw SQL interpolation. */\n private t(table: string): string {\n return `${this.schema}.${table}`;\n }\n\n async appendFact(runId: RunId, fact: Fact): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n await this.insertFact(trx, runId, fact);\n await this.applyFactToMaterialized(trx, runId, fact);\n });\n await this.maybeNotify(runId);\n }\n\n async tryStartRun(\n runId: RunId,\n fact: FlowStartedFact,\n ): Promise<{ readonly started: boolean }> {\n // Race-safe atomic insert. We lean on the `workflow_run.run_id` PRIMARY\n // KEY: `ON CONFLICT DO NOTHING` plus `RETURNING run_id` lets us detect in\n // one round-trip whether THIS call is the writer that created the run.\n // The fact insert and notify happen only on the winning branch — losers\n // get a clean idempotent no-op with no `flow.started` double-emit.\n const started = await this.db.transaction().execute(async (trx) => {\n const insert = await sql<{ run_id: string }>`\n INSERT INTO ${sql.raw(this.t(\"workflow_run\"))}\n (run_id, flow_id, status, input, started_at)\n VALUES\n (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at})\n ON CONFLICT (run_id) DO NOTHING\n RETURNING run_id\n `.execute(trx);\n\n if (insert.rows.length === 0) {\n return false;\n }\n await this.insertFact(trx, runId, fact);\n return true;\n });\n\n if (started) {\n await this.maybeNotify(runId);\n }\n return { started };\n }\n\n async loadRunState(runId: RunId): Promise<RunState> {\n const rows = await sql<{\n kind: string;\n at: Date;\n payload: unknown;\n }>`\n SELECT kind, at, payload\n FROM ${sql.raw(this.t(\"fact\"))}\n WHERE run_id = ${runId}\n ORDER BY fact_id ASC\n `.execute(this.db);\n\n const facts: Fact[] = rows.rows.map((r) =>\n reviveFact(r.kind, r.at, r.payload),\n );\n return projectRunState(runId, facts);\n }\n\n async claimStep(\n runId: RunId,\n stepId: StepId,\n attempt: AttemptNumber,\n ): Promise<ClaimToken | null> {\n const token = `lease-${crypto.randomUUID()}`;\n const expiresAt = new Date(Date.now() + this.leaseMs);\n\n const result = await sql<{ token: string }>`\n INSERT INTO ${sql.raw(this.t(\"lease\"))} (run_id, step_id, attempt, token, expires_at)\n VALUES (${runId}, ${stepId}, ${attempt}, ${token}, ${expiresAt})\n ON CONFLICT (run_id, step_id, attempt) DO UPDATE\n SET token = EXCLUDED.token, expires_at = EXCLUDED.expires_at\n WHERE ${sql.raw(this.t(\"lease\"))}.expires_at < now()\n RETURNING token\n `.execute(this.db);\n\n const row = result.rows[0];\n return row ? (row.token as ClaimToken) : null;\n }\n\n async completeStep(\n runId: RunId,\n stepId: StepId,\n output: Json,\n fact: Fact,\n ): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n await this.upsertStepCompleted(\n trx,\n runId,\n stepId,\n fact.kind === \"step.completed\" ? fact.attempt : 1,\n output,\n );\n await this.insertFact(trx, runId, fact);\n await this.applyFactToMaterialized(trx, runId, fact);\n await this.deleteLease(trx, runId, stepId);\n });\n await this.maybeNotify(runId);\n }\n\n async failStep(\n runId: RunId,\n stepId: StepId,\n error: SerializedError,\n fact: Fact,\n ): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n await this.upsertStepFailed(\n trx,\n runId,\n stepId,\n fact.kind === \"step.failed\" ? fact.attempt : 1,\n error,\n );\n await this.insertFact(trx, runId, fact);\n await this.applyFactToMaterialized(trx, runId, fact);\n await this.deleteLease(trx, runId, stepId);\n });\n await this.maybeNotify(runId);\n }\n\n async getStepOutput(runId: RunId, stepId: StepId): Promise<Json | null> {\n const r = await sql<{ output: Json | null }>`\n SELECT output\n FROM ${sql.raw(this.t(\"step_run\"))}\n WHERE run_id = ${runId} AND step_id = ${stepId} AND status = 'completed'\n ORDER BY attempt DESC\n LIMIT 1\n `.execute(this.db);\n return r.rows[0]?.output ?? null;\n }\n\n async recordOnce(\n runId: RunId,\n stepId: StepId,\n scope: string,\n value: Json,\n ): Promise<void> {\n await sql`\n INSERT INTO ${sql.raw(this.t(\"dedupe\"))} (run_id, step_id, scope, value)\n VALUES (${runId}, ${stepId}, ${scope}, ${jsonb(value)})\n ON CONFLICT (run_id, step_id, scope) DO NOTHING\n `.execute(this.db);\n }\n\n async getOnce(\n runId: RunId,\n stepId: StepId,\n scope: string,\n ): Promise<Json | null> {\n const r = await sql<{ value: Json | null }>`\n SELECT value\n FROM ${sql.raw(this.t(\"dedupe\"))}\n WHERE run_id = ${runId} AND step_id = ${stepId} AND scope = ${scope}\n `.execute(this.db);\n return r.rows[0]?.value ?? null;\n }\n\n async runStep<T extends Json>(\n runId: RunId,\n stepId: StepId,\n attempt: AttemptNumber,\n body: (tx: Tx) => Promise<{\n readonly output: T;\n readonly fact: StepCompletedFact | StepFailedFact;\n }>,\n ): Promise<T> {\n // The handler runs inside this Kysely tx; its ctx.tx points to the same\n // tx, so user-written domain rows commit atomically with the fact write\n // and step_run upsert below. If body() throws, the tx is rolled back —\n // dispatcher's outer handleStepError will record `step.failed` separately.\n const output = await this.db.transaction().execute(async (trx) => {\n const result = await body(trx as unknown as Tx);\n if (result.fact.kind === \"step.completed\") {\n await this.upsertStepCompleted(\n trx,\n runId,\n stepId,\n attempt,\n result.fact.output,\n );\n } else {\n await this.upsertStepFailed(\n trx,\n runId,\n stepId,\n attempt,\n result.fact.error,\n );\n }\n await this.insertFact(trx, runId, result.fact);\n await this.deleteLease(trx, runId, stepId);\n return result.output;\n });\n\n await this.maybeNotify(runId);\n return output;\n }\n\n private async insertFact(\n trx: Kysely<DB>,\n runId: RunId,\n fact: Fact,\n ): Promise<void> {\n await sql`\n INSERT INTO ${sql.raw(this.t(\"fact\"))} (run_id, fact_id, kind, at, payload)\n VALUES (${runId}, ${uuidv7()}, ${fact.kind}, ${fact.at}, ${jsonb(serializeFactPayload(fact))})\n `.execute(trx);\n }\n\n private async applyFactToMaterialized(\n trx: Kysely<DB>,\n runId: RunId,\n fact: Fact,\n ): Promise<void> {\n switch (fact.kind) {\n case \"flow.started\":\n // `tryStartRun` is the canonical entry point for `flow.started`. This\n // branch only fires if a caller threads the fact through `appendFact`\n // directly (e.g. tests). Use DO NOTHING to preserve idempotent\n // semantics — never clobber an existing run row.\n await sql`\n INSERT INTO ${sql.raw(this.t(\"workflow_run\"))} (run_id, flow_id, status, input, started_at)\n VALUES (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at})\n ON CONFLICT (run_id) DO NOTHING\n `.execute(trx);\n return;\n case \"flow.completed\":\n await sql`\n UPDATE ${sql.raw(this.t(\"workflow_run\"))}\n SET status = 'completed', output = ${jsonb(fact.output)}, completed_at = ${fact.at}\n WHERE run_id = ${runId}\n `.execute(trx);\n return;\n case \"flow.failed\":\n await sql`\n UPDATE ${sql.raw(this.t(\"workflow_run\"))}\n SET status = 'failed', error = ${jsonb(fact.error as unknown as Json)}, completed_at = ${fact.at}\n WHERE run_id = ${runId}\n `.execute(trx);\n return;\n case \"step.started\":\n await sql`\n INSERT INTO ${sql.raw(this.t(\"step_run\"))} (run_id, step_id, attempt, status, started_at)\n VALUES (${runId}, ${fact.stepId}, ${fact.attempt}, 'running', ${fact.at})\n ON CONFLICT (run_id, step_id, attempt) DO UPDATE\n SET status = 'running', started_at = EXCLUDED.started_at\n `.execute(trx);\n return;\n case \"step.skipped\":\n await sql`\n INSERT INTO ${sql.raw(this.t(\"step_run\"))} (run_id, step_id, attempt, status)\n VALUES (${runId}, ${fact.stepId}, 0, 'skipped')\n ON CONFLICT (run_id, step_id, attempt) DO UPDATE SET status = 'skipped'\n `.execute(trx);\n return;\n case \"once.recorded\":\n await sql`\n INSERT INTO ${sql.raw(this.t(\"dedupe\"))} (run_id, step_id, scope, value)\n VALUES (${runId}, ${fact.stepId}, ${fact.scope}, ${jsonb(fact.value)})\n ON CONFLICT (run_id, step_id, scope) DO NOTHING\n `.execute(trx);\n return;\n // step.completed / step.failed are materialized by runStep / completeStep / failStep\n // before insertFact, so applyFactToMaterialized is a no-op for them.\n case \"step.completed\":\n case \"step.failed\":\n case \"step.retried\":\n case \"signal.sent\":\n case \"signal.received\":\n case \"match.arm-selected\":\n return;\n }\n }\n\n private async upsertStepCompleted(\n trx: Kysely<DB>,\n runId: RunId,\n stepId: StepId,\n attempt: AttemptNumber,\n output: Json,\n ): Promise<void> {\n await sql`\n INSERT INTO ${sql.raw(this.t(\"step_run\"))}\n (run_id, step_id, attempt, status, output, started_at, completed_at)\n VALUES\n (${runId}, ${stepId}, ${attempt}, 'completed', ${jsonb(output)}, now(), now())\n ON CONFLICT (run_id, step_id, attempt) DO UPDATE\n SET status = 'completed', output = EXCLUDED.output, completed_at = now()\n `.execute(trx);\n }\n\n private async upsertStepFailed(\n trx: Kysely<DB>,\n runId: RunId,\n stepId: StepId,\n attempt: AttemptNumber,\n error: SerializedError,\n ): Promise<void> {\n await sql`\n INSERT INTO ${sql.raw(this.t(\"step_run\"))}\n (run_id, step_id, attempt, status, error, started_at, completed_at)\n VALUES\n (${runId}, ${stepId}, ${attempt}, 'failed', ${jsonb(error as unknown as Json)}, now(), now())\n ON CONFLICT (run_id, step_id, attempt) DO UPDATE\n SET status = 'failed', error = EXCLUDED.error, completed_at = now()\n `.execute(trx);\n }\n\n private async deleteLease(\n trx: Kysely<DB>,\n runId: RunId,\n stepId: StepId,\n ): Promise<void> {\n await sql`\n DELETE FROM ${sql.raw(this.t(\"lease\"))}\n WHERE run_id = ${runId} AND step_id = ${stepId}\n `.execute(trx);\n }\n\n private async maybeNotify(runId: RunId): Promise<void> {\n if (!this.notifyChannel) return;\n // pg_notify takes (channel text, payload text). Bind both as parameters.\n await sql`SELECT pg_notify(${this.notifyChannel}, ${runId})`.execute(\n this.db,\n );\n }\n}\n\n/**\n * Build the JSON payload column for a fact. Stores the full discriminated\n * union body (minus `kind`/`at` which are already separate columns).\n */\nfunction serializeFactPayload(fact: Fact): Json {\n // Strip the redundantly-stored top-level fields. `runId` is the row key.\n const { kind: _kind, at: _at, runId: _runId, ...rest } = fact;\n return rest as unknown as Json;\n}\n\n/**\n * Re-hydrate a Fact from a fact-table row. The DB carries `kind` + `at` in\n * their own columns, and the rest of the discriminated-union body in `payload`.\n */\nfunction reviveFact(kind: string, at: Date, payload: unknown): Fact {\n const body = (payload ?? {}) as Record<string, unknown>;\n return {\n kind: kind as Fact[\"kind\"],\n at: at instanceof Date ? at : new Date(at as string),\n ...body,\n } as Fact;\n}\n\n/**\n * Bind a `Json` value as a jsonb-typed parameter. `pg` will send strings as\n * TEXT and objects as JSON, but jsonb columns require an explicit cast for\n * the parameter to be typed correctly across all primitive cases. The\n * returned Kysely `sql` fragment expands to `$N::jsonb` when interpolated.\n */\nfunction jsonb(value: Json) {\n return sql`${JSON.stringify(value)}::jsonb`;\n}\n","import type { RunId, Trigger } from \"@nagi-js/core\";\n\n/**\n * Minimal shape the trigger needs from a LISTEN-capable Postgres client.\n * Compatible with `pg.Client` (Node) and a thin wrapper over `pg.Pool` /\n * `@neondatabase/serverless`'s `Client`. Kysely does not expose a long-lived\n * connection for LISTEN, so this is a separate driver handle by design.\n */\nexport interface ListenClient {\n query(text: string): Promise<unknown>;\n on(event: \"notification\", handler: (msg: NotificationMessage) => void): void;\n removeListener?(\n event: \"notification\",\n handler: (msg: NotificationMessage) => void,\n ): void;\n off?(\n event: \"notification\",\n handler: (msg: NotificationMessage) => void,\n ): void;\n}\n\nexport interface NotificationMessage {\n readonly channel: string;\n readonly payload?: string | undefined;\n}\n\nexport interface PostgresTriggerOpts {\n /**\n * Long-lived LISTEN client. The trigger calls `LISTEN <channel>` on it once\n * and never closes it — lifetime is the user's. Reuse one client per\n * worker process; do not share with query workloads (pg's `Pool` rotates\n * connections, which would drop `LISTEN` state).\n */\n readonly listen: ListenClient;\n /** NOTIFY channel name. Default `nagi`. Must match the Store's `notifyChannel`. */\n readonly channel?: string;\n}\n\n/**\n * Wake the scheduler when the Store writes facts. Pair with\n * `postgresStore({ notifyChannel })` so every `appendFact` /\n * `completeStep` / `failStep` emits `pg_notify(channel, runId)`.\n *\n * Subscribers receive only the `runId`. The scheduler is responsible for\n * loading the run's state and deciding what to advance.\n */\nexport function postgresTrigger(opts: PostgresTriggerOpts): Trigger {\n const channel = opts.channel ?? \"nagi\";\n assertValidChannel(channel);\n\n const handlers = new Set<(runId: RunId) => void>();\n let started = false;\n\n const onNotification = (msg: NotificationMessage): void => {\n if (msg.channel !== channel) return;\n const runId = (msg.payload ?? \"\") as RunId;\n if (!runId) return;\n for (const h of handlers) h(runId);\n };\n\n return {\n subscribe(handler: (runId: RunId) => void): () => void {\n handlers.add(handler);\n\n // Lazy: only start LISTEN when the first subscriber attaches.\n if (!started) {\n started = true;\n opts.listen.on(\"notification\", onNotification);\n // Fire-and-forget — the user controls the LISTEN client lifecycle.\n // Errors here surface as `query()` promise rejections; we propagate\n // to the next microtask so they don't get silently swallowed.\n void opts.listen.query(`LISTEN ${channel}`).catch((err) => {\n queueMicrotask(() => {\n throw err;\n });\n });\n }\n\n return () => {\n handlers.delete(handler);\n };\n },\n };\n}\n\n/**\n * Same identifier rule as the schema name — interpolated raw into\n * `LISTEN <channel>` since pg has no parameter binding for identifiers.\n */\nfunction assertValidChannel(channel: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(channel)) {\n throw new Error(\n `@nagi-js/postgres: invalid NOTIFY channel \"${channel}\". Must match /^[A-Za-z_][A-Za-z0-9_]*$/.`,\n );\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@nagi-js/postgres",
3
+ "version": "0.1.0",
4
+ "description": "Postgres Store adapter for nagi (Kysely-shaped).",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "keywords": [
9
+ "nagi",
10
+ "workflow",
11
+ "postgres",
12
+ "kysely",
13
+ "durable",
14
+ "store",
15
+ "adapter"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "registry": "https://registry.npmjs.org/",
23
+ "provenance": false
24
+ },
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js",
29
+ "default": "./dist/index.js"
30
+ }
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "dependencies": {
38
+ "@nagi-js/core": "0.1.0"
39
+ },
40
+ "peerDependencies": {
41
+ "kysely": "^0.28.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/pg": "^8.11.0",
45
+ "kysely": "^0.28.0",
46
+ "pg": "^8.13.0"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/lymo-inc/nagi.git",
51
+ "directory": "packages/postgres"
52
+ },
53
+ "homepage": "https://github.com/lymo-inc/nagi#readme",
54
+ "bugs": {
55
+ "url": "https://github.com/lymo-inc/nagi/issues"
56
+ },
57
+ "scripts": {
58
+ "build": "tsup",
59
+ "dev": "tsup --watch",
60
+ "test": "vitest run",
61
+ "test:watch": "vitest",
62
+ "test:types": "vitest run --typecheck",
63
+ "typecheck": "tsc --noEmit"
64
+ }
65
+ }