@gencow/core 0.1.24 → 0.1.26

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.
Files changed (75) hide show
  1. package/dist/crud.d.ts +2 -2
  2. package/dist/crud.js +225 -208
  3. package/dist/index.d.ts +5 -5
  4. package/dist/index.js +2 -2
  5. package/dist/reactive.js +10 -3
  6. package/dist/retry.js +1 -1
  7. package/dist/rls-db.d.ts +2 -2
  8. package/dist/rls-db.js +1 -5
  9. package/dist/scheduler.d.ts +2 -0
  10. package/dist/scheduler.js +16 -6
  11. package/dist/server.d.ts +0 -1
  12. package/dist/server.js +0 -1
  13. package/dist/storage.js +29 -22
  14. package/dist/v.d.ts +2 -2
  15. package/dist/workflow.js +4 -11
  16. package/dist/workflows-api.js +5 -12
  17. package/package.json +45 -42
  18. package/src/__tests__/auth.test.ts +90 -86
  19. package/src/__tests__/crons.test.ts +69 -67
  20. package/src/__tests__/crud-codegen-integration.test.ts +164 -170
  21. package/src/__tests__/crud-owner-rls.test.ts +308 -301
  22. package/src/__tests__/crud.test.ts +694 -711
  23. package/src/__tests__/dist-exports.test.ts +120 -120
  24. package/src/__tests__/fixtures/basic/auth.ts +16 -16
  25. package/src/__tests__/fixtures/basic/drizzle.config.ts +1 -4
  26. package/src/__tests__/fixtures/basic/index.ts +1 -1
  27. package/src/__tests__/fixtures/basic/schema.ts +1 -1
  28. package/src/__tests__/fixtures/basic/tasks.ts +4 -4
  29. package/src/__tests__/fixtures/common/auth-schema.ts +38 -34
  30. package/src/__tests__/helpers/basic-rls-fixture.ts +80 -78
  31. package/src/__tests__/helpers/pglite-migrations.ts +2 -5
  32. package/src/__tests__/helpers/pglite-rls-session.ts +13 -16
  33. package/src/__tests__/helpers/seed-like-fill.ts +47 -41
  34. package/src/__tests__/helpers/test-gencow-ctx-rls.ts +4 -7
  35. package/src/__tests__/httpaction.test.ts +91 -91
  36. package/src/__tests__/image-optimization.test.ts +570 -574
  37. package/src/__tests__/load.test.ts +321 -308
  38. package/src/__tests__/network-sim.test.ts +238 -215
  39. package/src/__tests__/reactive.test.ts +380 -358
  40. package/src/__tests__/retry.test.ts +99 -84
  41. package/src/__tests__/rls-crud-basic.test.ts +172 -245
  42. package/src/__tests__/rls-crud-no-owner-rls-pglite.test.ts +81 -81
  43. package/src/__tests__/rls-custom-mutation-handlers.test.ts +47 -94
  44. package/src/__tests__/rls-custom-query-handlers.test.ts +92 -92
  45. package/src/__tests__/rls-db-leased-connection.test.ts +2 -6
  46. package/src/__tests__/rls-session-and-policies.test.ts +181 -199
  47. package/src/__tests__/scheduler-durable-v2.test.ts +199 -181
  48. package/src/__tests__/scheduler-durable.test.ts +117 -117
  49. package/src/__tests__/scheduler-exec.test.ts +258 -246
  50. package/src/__tests__/scheduler.test.ts +129 -111
  51. package/src/__tests__/storage.test.ts +282 -269
  52. package/src/__tests__/tsconfig.json +6 -6
  53. package/src/__tests__/validator.test.ts +236 -232
  54. package/src/__tests__/workflow.test.ts +309 -286
  55. package/src/__tests__/ws-integration.test.ts +223 -218
  56. package/src/__tests__/ws-scale.test.ts +168 -159
  57. package/src/auth-config.ts +18 -18
  58. package/src/auth.ts +106 -106
  59. package/src/crons.ts +77 -77
  60. package/src/crud.ts +523 -479
  61. package/src/index.ts +69 -5
  62. package/src/reactive.ts +357 -331
  63. package/src/retry.ts +51 -54
  64. package/src/rls-db.ts +195 -205
  65. package/src/rls.ts +33 -36
  66. package/src/scheduler.ts +237 -211
  67. package/src/server.ts +0 -1
  68. package/src/storage.ts +632 -593
  69. package/src/v.ts +119 -114
  70. package/src/workflow-types.ts +67 -70
  71. package/src/workflow.ts +99 -116
  72. package/src/workflows-api.ts +231 -241
  73. package/dist/db.d.ts +0 -13
  74. package/dist/db.js +0 -16
  75. package/src/db.ts +0 -18
@@ -8,7 +8,7 @@ import { v } from "../v.js";
8
8
  import { registerWorkflowsApi } from "../workflows-api.js";
9
9
 
10
10
  const WORKFLOW_TABLE_SETUP = [
11
- `CREATE TABLE IF NOT EXISTS _gencow_workflows (
11
+ `CREATE TABLE IF NOT EXISTS _gencow_workflows (
12
12
  id TEXT PRIMARY KEY,
13
13
  name TEXT NOT NULL,
14
14
  args JSONB NOT NULL DEFAULT '{}'::jsonb,
@@ -25,7 +25,7 @@ const WORKFLOW_TABLE_SETUP = [
25
25
  completed_at TIMESTAMPTZ,
26
26
  user_id TEXT
27
27
  )`,
28
- `CREATE TABLE IF NOT EXISTS _gencow_workflow_steps (
28
+ `CREATE TABLE IF NOT EXISTS _gencow_workflow_steps (
29
29
  id SERIAL PRIMARY KEY,
30
30
  workflow_id TEXT NOT NULL REFERENCES _gencow_workflows(id) ON DELETE CASCADE,
31
31
  step_name TEXT NOT NULL,
@@ -37,7 +37,7 @@ const WORKFLOW_TABLE_SETUP = [
37
37
  completed_at TIMESTAMPTZ,
38
38
  UNIQUE(workflow_id, step_name)
39
39
  )`,
40
- `CREATE TABLE IF NOT EXISTS _gencow_workflow_events (
40
+ `CREATE TABLE IF NOT EXISTS _gencow_workflow_events (
41
41
  id TEXT PRIMARY KEY,
42
42
  workflow_id TEXT NOT NULL REFERENCES _gencow_workflows(id) ON DELETE CASCADE,
43
43
  event_name TEXT NOT NULL,
@@ -48,155 +48,171 @@ const WORKFLOW_TABLE_SETUP = [
48
48
  ] as const;
49
49
 
50
50
  describe("workflow()", () => {
51
- let client: PGlite;
52
- let db: ReturnType<typeof drizzle>;
53
-
54
- function buildCtx(userId: string | null) {
55
- return {
56
- db,
57
- unsafeDb: db,
58
- auth: {
59
- getUserIdentity: () => (
60
- userId
61
- ? { id: userId, email: `${userId}@workflow.test` }
62
- : null
63
- ),
64
- requireAuth: () => {
65
- if (!userId) throw new Error("Authentication required");
66
- return { id: userId, email: `${userId}@workflow.test` };
67
- },
68
- },
69
- storage: {} as any,
70
- scheduler: {
71
- runAfter: () => "unused",
72
- runAt: () => "unused",
73
- cancel: () => false,
74
- cron: () => {},
75
- registerAction: () => {},
76
- executeAction: async () => {},
77
- },
78
- realtime: { emit: () => {}, refresh: () => {} },
79
- retry: async (fn: () => Promise<unknown>) => fn(),
80
- };
51
+ let client: PGlite;
52
+ let db: ReturnType<typeof drizzle>;
53
+
54
+ function buildCtx(userId: string | null) {
55
+ return {
56
+ db,
57
+ unsafeDb: db,
58
+ auth: {
59
+ getUserIdentity: () => (userId ? { id: userId, email: `${userId}@workflow.test` } : null),
60
+ requireAuth: () => {
61
+ if (!userId) throw new Error("Authentication required");
62
+ return { id: userId, email: `${userId}@workflow.test` };
63
+ },
64
+ },
65
+ storage: {} as any,
66
+ scheduler: {
67
+ runAfter: () => "unused",
68
+ runAt: () => "unused",
69
+ cancel: () => false,
70
+ cron: () => {},
71
+ registerAction: () => {},
72
+ executeAction: async () => {},
73
+ },
74
+ realtime: { emit: () => {}, refresh: () => {} },
75
+ retry: async (fn: () => Promise<unknown>) => fn(),
76
+ };
77
+ }
78
+
79
+ beforeAll(async () => {
80
+ client = new PGlite();
81
+ db = drizzle({ client });
82
+ for (const stmt of WORKFLOW_TABLE_SETUP) {
83
+ await client.exec(stmt);
81
84
  }
82
-
83
- beforeAll(async () => {
84
- client = new PGlite();
85
- db = drizzle(client);
86
- for (const stmt of WORKFLOW_TABLE_SETUP) {
87
- await client.exec(stmt);
88
- }
89
- registerWorkflowsApi();
85
+ registerWorkflowsApi();
86
+ });
87
+
88
+ afterAll(async () => {
89
+ await client.close();
90
+ });
91
+
92
+ it("start mutation inserts workflow row and schedules resume action", async () => {
93
+ const name = `agents.workflowStart${Date.now()}`;
94
+ const start = workflow(name, {
95
+ args: { topic: v.string() },
96
+ handler: async () => ({ ok: true }),
90
97
  });
91
98
 
92
- afterAll(async () => {
93
- await client.close();
94
- });
95
-
96
- it("start mutation inserts workflow row and schedules resume action", async () => {
97
- const name = `agents.workflowStart${Date.now()}`;
98
- const start = workflow(name, {
99
- args: { topic: v.string() },
100
- handler: async () => ({ ok: true }),
101
- });
102
-
103
- const scheduled: Array<{ delayMs: number; action: string; args: unknown }> = [];
104
- const result = await start.handler({
105
- db,
106
- unsafeDb: db,
107
- auth: {
108
- getUserIdentity: () => ({ id: "user_workflow_start", email: "owner@test.dev" }),
109
- requireAuth: () => ({ id: "user_workflow_start", email: "owner@test.dev" }),
110
- },
111
- storage: {} as any,
112
- scheduler: {
113
- runAfter: (delayMs, action, args) => {
114
- scheduled.push({ delayMs, action, args });
115
- return "job-start-1";
116
- },
117
- runAt: () => "unused",
118
- cancel: () => false,
119
- cron: () => {},
120
- registerAction: () => {},
121
- executeAction: async () => {},
122
- },
123
- realtime: { emit: () => {}, refresh: () => {} },
124
- retry: async (fn) => fn(),
125
- }, { topic: "durable execution" });
126
-
127
- expect(result.status).toBe("pending");
128
- expect(result.name).toBe(name);
129
- expect(result.scheduledJobId).toBe("job-start-1");
130
- expect(scheduled).toEqual([
131
- {
132
- delayMs: 0,
133
- action: getWorkflowResumeActionName(name),
134
- args: { workflowId: result.id },
135
- },
136
- ]);
137
-
138
- const rowResult = await db.execute(sql`
99
+ const scheduled: Array<{ delayMs: number; action: string; args: unknown }> = [];
100
+ const result = await start.handler(
101
+ {
102
+ db,
103
+ unsafeDb: db,
104
+ auth: {
105
+ getUserIdentity: () => ({ id: "user_workflow_start", email: "owner@test.dev" }),
106
+ requireAuth: () => ({ id: "user_workflow_start", email: "owner@test.dev" }),
107
+ },
108
+ storage: {} as any,
109
+ scheduler: {
110
+ runAfter: (delayMs, action, args) => {
111
+ scheduled.push({ delayMs, action, args });
112
+ return "job-start-1";
113
+ },
114
+ runAt: () => "unused",
115
+ cancel: () => false,
116
+ cron: () => {},
117
+ registerAction: () => {},
118
+ executeAction: async () => {},
119
+ },
120
+ realtime: { emit: () => {}, refresh: () => {} },
121
+ retry: async (fn) => fn(),
122
+ },
123
+ { topic: "durable execution" },
124
+ );
125
+
126
+ expect(result.status).toBe("pending");
127
+ expect(result.name).toBe(name);
128
+ expect(result.scheduledJobId).toBe("job-start-1");
129
+ expect(scheduled).toEqual([
130
+ {
131
+ delayMs: 0,
132
+ action: getWorkflowResumeActionName(name),
133
+ args: { workflowId: result.id },
134
+ },
135
+ ]);
136
+
137
+ const rowResult = await db.execute(sql`
139
138
  SELECT id, name, status, max_retries, user_id, args, realtime_token
140
139
  FROM _gencow_workflows
141
140
  WHERE id = ${result.id}
142
141
  `);
143
- const row = (rowResult as { rows: Array<{ id: string; name: string; status: string; max_retries: number; user_id: string | null; args: unknown; realtime_token: string }> }).rows[0];
144
-
145
- expect(row.id).toBe(result.id);
146
- expect(row.name).toBe(name);
147
- expect(row.status).toBe("pending");
148
- expect(row.max_retries).toBe(3);
149
- expect(row.user_id).toBe("user_workflow_start");
150
- expect(row.args).toEqual({ value: { topic: "durable execution" } });
151
- expect(row.realtime_token.length).toBeGreaterThan(10);
142
+ const row = (
143
+ rowResult as {
144
+ rows: Array<{
145
+ id: string;
146
+ name: string;
147
+ status: string;
148
+ max_retries: number;
149
+ user_id: string | null;
150
+ args: unknown;
151
+ realtime_token: string;
152
+ }>;
153
+ }
154
+ ).rows[0];
155
+
156
+ expect(row.id).toBe(result.id);
157
+ expect(row.name).toBe(name);
158
+ expect(row.status).toBe("pending");
159
+ expect(row.max_retries).toBe(3);
160
+ expect(row.user_id).toBe("user_workflow_start");
161
+ expect(row.args).toEqual({ value: { topic: "durable execution" } });
162
+ expect(row.realtime_token.length).toBeGreaterThan(10);
163
+ });
164
+
165
+ it("scheduler enqueue failure rolls back the workflow row", async () => {
166
+ const name = `agents.workflowRollback${Date.now()}`;
167
+ const start = workflow(name, {
168
+ args: { topic: v.string() },
169
+ handler: async () => ({ ok: true }),
152
170
  });
153
171
 
154
- it("scheduler enqueue failure rolls back the workflow row", async () => {
155
- const name = `agents.workflowRollback${Date.now()}`;
156
- const start = workflow(name, {
157
- args: { topic: v.string() },
158
- handler: async () => ({ ok: true }),
159
- });
160
-
161
- await expect(start.handler({
162
- db,
163
- unsafeDb: db,
164
- auth: {
165
- getUserIdentity: () => null,
166
- requireAuth: () => {
167
- throw new Error("not used");
168
- },
172
+ await expect(
173
+ start.handler(
174
+ {
175
+ db,
176
+ unsafeDb: db,
177
+ auth: {
178
+ getUserIdentity: () => null,
179
+ requireAuth: () => {
180
+ throw new Error("not used");
169
181
  },
170
- storage: {} as any,
171
- scheduler: {
172
- runAfter: () => {
173
- throw new Error("scheduler unavailable");
174
- },
175
- runAt: () => "unused",
176
- cancel: () => false,
177
- cron: () => {},
178
- registerAction: () => {},
179
- executeAction: async () => {},
182
+ },
183
+ storage: {} as any,
184
+ scheduler: {
185
+ runAfter: () => {
186
+ throw new Error("scheduler unavailable");
180
187
  },
181
- realtime: { emit: () => {}, refresh: () => {} },
182
- retry: async (fn) => fn(),
183
- }, { topic: "should rollback" })).rejects.toThrow("scheduler unavailable");
184
-
185
- const countResult = await db.execute(sql`
188
+ runAt: () => "unused",
189
+ cancel: () => false,
190
+ cron: () => {},
191
+ registerAction: () => {},
192
+ executeAction: async () => {},
193
+ },
194
+ realtime: { emit: () => {}, refresh: () => {} },
195
+ retry: async (fn) => fn(),
196
+ },
197
+ { topic: "should rollback" },
198
+ ),
199
+ ).rejects.toThrow("scheduler unavailable");
200
+
201
+ const countResult = await db.execute(sql`
186
202
  SELECT count(*)::int AS c
187
203
  FROM _gencow_workflows
188
204
  WHERE name = ${name}
189
205
  `);
190
- const count = (countResult as { rows: Array<{ c: number }> }).rows[0]?.c ?? 0;
191
- expect(count).toBe(0);
192
- });
206
+ const count = (countResult as { rows: Array<{ c: number }> }).rows[0]?.c ?? 0;
207
+ expect(count).toBe(0);
208
+ });
193
209
 
194
- it("workflows.get returns full snapshot for the owner and hides private workflows from others", async () => {
195
- const getWorkflow = getQueryDef("workflows.get");
196
- expect(getWorkflow).toBeDefined();
210
+ it("workflows.get returns full snapshot for the owner and hides private workflows from others", async () => {
211
+ const getWorkflow = getQueryDef("workflows.get");
212
+ expect(getWorkflow).toBeDefined();
197
213
 
198
- const workflowId = `wf_owned_${Date.now()}`;
199
- await db.execute(sql`
214
+ const workflowId = `wf_owned_${Date.now()}`;
215
+ await db.execute(sql`
200
216
  INSERT INTO _gencow_workflows (
201
217
  id,
202
218
  name,
@@ -230,7 +246,7 @@ describe("workflow()", () => {
230
246
  'owner_workflow'
231
247
  )
232
248
  `);
233
- await db.execute(sql`
249
+ await db.execute(sql`
234
250
  INSERT INTO _gencow_workflow_steps (
235
251
  workflow_id,
236
252
  step_name,
@@ -264,41 +280,43 @@ describe("workflow()", () => {
264
280
  )
265
281
  `);
266
282
 
267
- const ownerSnapshot = await getWorkflow!.handler(buildCtx("owner_workflow") as any, { id: workflowId });
268
- expect(ownerSnapshot).toMatchObject({
269
- id: workflowId,
270
- name: "agents.report",
271
- status: "running",
272
- derivedStatus: "running",
273
- currentStep: "analyze",
274
- args: { topic: "market map" },
275
- result: null,
276
- retryCount: 1,
277
- maxRetries: 3,
278
- });
279
- expect(ownerSnapshot?.realtimeKey).toMatch(new RegExp(`^__gencow\\.workflow\\.state\\.${workflowId}\\.`));
280
- expect(ownerSnapshot?.steps).toHaveLength(2);
281
- expect(ownerSnapshot?.steps[0]).toMatchObject({
282
- name: "search",
283
- status: "completed",
284
- output: { hits: 2 },
285
- });
286
- expect(ownerSnapshot?.steps[1]).toMatchObject({
287
- name: "analyze",
288
- status: "running",
289
- output: null,
290
- });
291
-
292
- const strangerSnapshot = await getWorkflow!.handler(buildCtx("stranger_workflow") as any, { id: workflowId });
293
- expect(strangerSnapshot).toBeNull();
283
+ const ownerSnapshot = await getWorkflow!.handler(buildCtx("owner_workflow") as any, { id: workflowId });
284
+ expect(ownerSnapshot).toMatchObject({
285
+ id: workflowId,
286
+ name: "agents.report",
287
+ status: "running",
288
+ derivedStatus: "running",
289
+ currentStep: "analyze",
290
+ args: { topic: "market map" },
291
+ result: null,
292
+ retryCount: 1,
293
+ maxRetries: 3,
294
+ });
295
+ expect(ownerSnapshot?.realtimeKey).toMatch(new RegExp(`^__gencow\\.workflow\\.state\\.${workflowId}\\.`));
296
+ expect(ownerSnapshot?.steps).toHaveLength(2);
297
+ expect(ownerSnapshot?.steps[0]).toMatchObject({
298
+ name: "search",
299
+ status: "completed",
300
+ output: { hits: 2 },
301
+ });
302
+ expect(ownerSnapshot?.steps[1]).toMatchObject({
303
+ name: "analyze",
304
+ status: "running",
305
+ output: null,
306
+ });
307
+
308
+ const strangerSnapshot = await getWorkflow!.handler(buildCtx("stranger_workflow") as any, {
309
+ id: workflowId,
294
310
  });
311
+ expect(strangerSnapshot).toBeNull();
312
+ });
295
313
 
296
- it("workflows.get allows ownerless public workflows to be polled without auth", async () => {
297
- const getWorkflow = getQueryDef("workflows.get");
298
- expect(getWorkflow).toBeDefined();
314
+ it("workflows.get allows ownerless public workflows to be polled without auth", async () => {
315
+ const getWorkflow = getQueryDef("workflows.get");
316
+ expect(getWorkflow).toBeDefined();
299
317
 
300
- const workflowId = `wf_public_${Date.now()}`;
301
- await db.execute(sql`
318
+ const workflowId = `wf_public_${Date.now()}`;
319
+ await db.execute(sql`
302
320
  INSERT INTO _gencow_workflows (
303
321
  id,
304
322
  name,
@@ -333,23 +351,23 @@ describe("workflow()", () => {
333
351
  )
334
352
  `);
335
353
 
336
- const snapshot = await getWorkflow!.handler(buildCtx(null) as any, { id: workflowId });
337
- expect(snapshot).toMatchObject({
338
- id: workflowId,
339
- status: "completed",
340
- derivedStatus: "completed",
341
- result: { report: "done" },
342
- steps: [],
343
- });
344
- expect(snapshot?.realtimeKey).toMatch(new RegExp(`^__gencow\\.workflow\\.state\\.${workflowId}\\.`));
354
+ const snapshot = await getWorkflow!.handler(buildCtx(null) as any, { id: workflowId });
355
+ expect(snapshot).toMatchObject({
356
+ id: workflowId,
357
+ status: "completed",
358
+ derivedStatus: "completed",
359
+ result: { report: "done" },
360
+ steps: [],
345
361
  });
362
+ expect(snapshot?.realtimeKey).toMatch(new RegExp(`^__gencow\\.workflow\\.state\\.${workflowId}\\.`));
363
+ });
346
364
 
347
- it("workflows.signal persists an event and wakes waiting workflows for the owner only", async () => {
348
- const signalWorkflow = getRegisteredMutations().find((item) => item.name === "workflows.signal");
349
- expect(signalWorkflow).toBeDefined();
365
+ it("workflows.signal persists an event and wakes waiting workflows for the owner only", async () => {
366
+ const signalWorkflow = getRegisteredMutations().find((item) => item.name === "workflows.signal");
367
+ expect(signalWorkflow).toBeDefined();
350
368
 
351
- const workflowId = `wf_signal_${Date.now()}`;
352
- await db.execute(sql`
369
+ const workflowId = `wf_signal_${Date.now()}`;
370
+ await db.execute(sql`
353
371
  INSERT INTO _gencow_workflows (
354
372
  id,
355
373
  name,
@@ -384,83 +402,88 @@ describe("workflow()", () => {
384
402
  )
385
403
  `);
386
404
 
387
- const scheduled: Array<{ delayMs: number; action: string; args: unknown }> = [];
388
- const accepted = await signalWorkflow!.handler({
389
- ...buildCtx("signal_owner"),
390
- scheduler: {
391
- runAfter: (delayMs, action, args) => {
392
- scheduled.push({ delayMs, action, args });
393
- return "job-signal-1";
394
- },
395
- runAt: () => "unused",
396
- cancel: () => false,
397
- cron: () => {},
398
- registerAction: () => {},
399
- executeAction: async () => {},
400
- },
401
- } as any, {
402
- id: workflowId,
403
- event: "approval",
404
- payload: { approved: true },
405
- });
406
-
407
- expect(accepted).toEqual({
408
- ok: true,
409
- workflowId,
410
- event: "approval",
411
- scheduledJobId: "job-signal-1",
412
- });
413
- expect(scheduled).toEqual([
414
- {
415
- delayMs: 0,
416
- action: getWorkflowResumeActionName("agents.waiting"),
417
- args: { workflowId },
418
- },
419
- ]);
420
-
421
- const eventResult = await db.execute(sql`
405
+ const scheduled: Array<{ delayMs: number; action: string; args: unknown }> = [];
406
+ const accepted = await signalWorkflow!.handler(
407
+ {
408
+ ...buildCtx("signal_owner"),
409
+ scheduler: {
410
+ runAfter: (delayMs, action, args) => {
411
+ scheduled.push({ delayMs, action, args });
412
+ return "job-signal-1";
413
+ },
414
+ runAt: () => "unused",
415
+ cancel: () => false,
416
+ cron: () => {},
417
+ registerAction: () => {},
418
+ executeAction: async () => {},
419
+ },
420
+ } as any,
421
+ {
422
+ id: workflowId,
423
+ event: "approval",
424
+ payload: { approved: true },
425
+ },
426
+ );
427
+
428
+ expect(accepted).toEqual({
429
+ ok: true,
430
+ workflowId,
431
+ event: "approval",
432
+ scheduledJobId: "job-signal-1",
433
+ });
434
+ expect(scheduled).toEqual([
435
+ {
436
+ delayMs: 0,
437
+ action: getWorkflowResumeActionName("agents.waiting"),
438
+ args: { workflowId },
439
+ },
440
+ ]);
441
+
442
+ const eventResult = await db.execute(sql`
422
443
  SELECT workflow_id, event_name, payload, consumed_at IS NULL AS is_unconsumed
423
444
  FROM _gencow_workflow_events
424
445
  WHERE workflow_id = ${workflowId}
425
446
  `);
426
- const eventRow = (eventResult as {
427
- rows: Array<{
428
- workflow_id: string;
429
- event_name: string;
430
- payload: unknown;
431
- is_unconsumed: boolean;
432
- }>;
433
- }).rows[0];
434
- expect(eventRow).toEqual({
435
- workflow_id: workflowId,
436
- event_name: "approval",
437
- payload: { value: { approved: true } },
438
- is_unconsumed: true,
439
- });
440
-
441
- const denied = await signalWorkflow!.handler(buildCtx("someone_else") as any, {
442
- id: workflowId,
443
- event: "approval",
444
- payload: { approved: false },
445
- });
446
- expect(denied).toEqual({
447
- ok: false,
448
- workflowId,
449
- event: "approval",
450
- scheduledJobId: null,
451
- });
447
+ const eventRow = (
448
+ eventResult as {
449
+ rows: Array<{
450
+ workflow_id: string;
451
+ event_name: string;
452
+ payload: unknown;
453
+ is_unconsumed: boolean;
454
+ }>;
455
+ }
456
+ ).rows[0];
457
+ expect(eventRow).toEqual({
458
+ workflow_id: workflowId,
459
+ event_name: "approval",
460
+ payload: { value: { approved: true } },
461
+ is_unconsumed: true,
462
+ });
463
+
464
+ const denied = await signalWorkflow!.handler(buildCtx("someone_else") as any, {
465
+ id: workflowId,
466
+ event: "approval",
467
+ payload: { approved: false },
468
+ });
469
+ expect(denied).toEqual({
470
+ ok: false,
471
+ workflowId,
472
+ event: "approval",
473
+ scheduledJobId: null,
452
474
  });
475
+ });
453
476
 
454
- it("workflows.list requires auth and filters to the current owner", async () => {
455
- const listWorkflows = getQueryDef("workflows.list");
456
- expect(listWorkflows).toBeDefined();
477
+ it("workflows.list requires auth and filters to the current owner", async () => {
478
+ const listWorkflows = getQueryDef("workflows.list");
479
+ expect(listWorkflows).toBeDefined();
457
480
 
458
- const userACompleted = `wf_user_a_completed_${Date.now()}`;
459
- const userAWaiting = `wf_user_a_waiting_${Date.now()}`;
460
- const userASleeping = `wf_user_a_sleeping_${Date.now()}`;
461
- const userBRunning = `wf_user_b_running_${Date.now()}`;
481
+ const userACompleted = `wf_user_a_completed_${Date.now()}`;
482
+ const userAWaiting = `wf_user_a_waiting_${Date.now()}`;
483
+ const userASleeping = `wf_user_a_sleeping_${Date.now()}`;
484
+ const userBRunning = `wf_user_b_running_${Date.now()}`;
462
485
 
463
- await db.execute(sql`
486
+ await db.execute(sql`
464
487
  INSERT INTO _gencow_workflows (
465
488
  id,
466
489
  name,
@@ -544,40 +567,40 @@ describe("workflow()", () => {
544
567
  )
545
568
  `);
546
569
 
547
- const ownWorkflows = await listWorkflows!.handler(buildCtx("workflow_user_a") as any, { limit: 10 });
548
- expect(ownWorkflows.map((item: any) => item.id)).toEqual([userAWaiting, userASleeping, userACompleted]);
549
- expect(ownWorkflows.every((item: any) => item.name === "agents.sync")).toBe(true);
550
- expect(ownWorkflows.some((item: any) => item.id === userBRunning)).toBe(false);
551
- expect(ownWorkflows.find((item: any) => item.id === userAWaiting)?.derivedStatus).toBe("waiting");
552
- expect(ownWorkflows.find((item: any) => item.id === userASleeping)?.derivedStatus).toBe("sleeping");
553
-
554
- const completedOnly = await listWorkflows!.handler(
555
- buildCtx("workflow_user_a") as any,
556
- { limit: 10, status: "completed" }
557
- );
558
- expect(completedOnly).toHaveLength(1);
559
- expect(completedOnly[0]?.id).toBe(userACompleted);
560
-
561
- const waitingOnly = await listWorkflows!.handler(
562
- buildCtx("workflow_user_a") as any,
563
- { limit: 10, status: "waiting" }
564
- );
565
- expect(waitingOnly).toHaveLength(1);
566
- expect(waitingOnly[0]?.id).toBe(userAWaiting);
567
-
568
- const sleepingOnly = await listWorkflows!.handler(
569
- buildCtx("workflow_user_a") as any,
570
- { limit: 10, status: "sleeping" }
571
- );
572
- expect(sleepingOnly).toHaveLength(1);
573
- expect(sleepingOnly[0]?.id).toBe(userASleeping);
574
-
575
- await expect(
576
- listWorkflows!.handler(buildCtx(null) as any, { limit: 10 })
577
- ).rejects.toThrow("Authentication required");
578
-
579
- await expect(
580
- listWorkflows!.handler(buildCtx("workflow_user_a") as any, { limit: 10, status: "mystery" })
581
- ).rejects.toThrow('Argument "status": expected one of pending, running, completed, failed');
570
+ const ownWorkflows = await listWorkflows!.handler(buildCtx("workflow_user_a") as any, { limit: 10 });
571
+ expect(ownWorkflows.map((item: any) => item.id)).toEqual([userAWaiting, userASleeping, userACompleted]);
572
+ expect(ownWorkflows.every((item: any) => item.name === "agents.sync")).toBe(true);
573
+ expect(ownWorkflows.some((item: any) => item.id === userBRunning)).toBe(false);
574
+ expect(ownWorkflows.find((item: any) => item.id === userAWaiting)?.derivedStatus).toBe("waiting");
575
+ expect(ownWorkflows.find((item: any) => item.id === userASleeping)?.derivedStatus).toBe("sleeping");
576
+
577
+ const completedOnly = await listWorkflows!.handler(buildCtx("workflow_user_a") as any, {
578
+ limit: 10,
579
+ status: "completed",
580
+ });
581
+ expect(completedOnly).toHaveLength(1);
582
+ expect(completedOnly[0]?.id).toBe(userACompleted);
583
+
584
+ const waitingOnly = await listWorkflows!.handler(buildCtx("workflow_user_a") as any, {
585
+ limit: 10,
586
+ status: "waiting",
582
587
  });
588
+ expect(waitingOnly).toHaveLength(1);
589
+ expect(waitingOnly[0]?.id).toBe(userAWaiting);
590
+
591
+ const sleepingOnly = await listWorkflows!.handler(buildCtx("workflow_user_a") as any, {
592
+ limit: 10,
593
+ status: "sleeping",
594
+ });
595
+ expect(sleepingOnly).toHaveLength(1);
596
+ expect(sleepingOnly[0]?.id).toBe(userASleeping);
597
+
598
+ await expect(listWorkflows!.handler(buildCtx(null) as any, { limit: 10 })).rejects.toThrow(
599
+ "Authentication required",
600
+ );
601
+
602
+ await expect(
603
+ listWorkflows!.handler(buildCtx("workflow_user_a") as any, { limit: 10, status: "mystery" }),
604
+ ).rejects.toThrow('Argument "status": expected one of pending, running, completed, failed');
605
+ });
583
606
  });