@hogsend/engine 0.40.0 → 0.42.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.
Files changed (69) hide show
  1. package/package.json +11 -8
  2. package/src/buckets/check-membership.ts +6 -1
  3. package/src/campaigns/cohort-sql.ts +198 -0
  4. package/src/campaigns/define-campaign.ts +207 -28
  5. package/src/campaigns/reconcile.ts +105 -11
  6. package/src/campaigns/steps.ts +48 -0
  7. package/src/connectors/define-action.ts +70 -0
  8. package/src/container.ts +124 -42
  9. package/src/destinations/presets/posthog.ts +7 -1
  10. package/src/index.ts +96 -2
  11. package/src/journeys/constants.ts +10 -0
  12. package/src/journeys/define-journey.ts +14 -405
  13. package/src/journeys/execute-journey-run.ts +641 -0
  14. package/src/journeys/graph/build-graph.ts +212 -56
  15. package/src/journeys/journey-boundary.ts +54 -0
  16. package/src/journeys/journey-context.ts +406 -59
  17. package/src/journeys/record-once.ts +110 -0
  18. package/src/lib/blueprint-lock.ts +21 -0
  19. package/src/lib/blueprints.ts +803 -0
  20. package/src/lib/campaign-send-key.ts +58 -0
  21. package/src/lib/connector-actions.ts +203 -19
  22. package/src/lib/contacts.ts +54 -0
  23. package/src/lib/email-service-types.ts +4 -1
  24. package/src/lib/email.ts +13 -2
  25. package/src/lib/event-names.ts +143 -0
  26. package/src/lib/feed.ts +77 -57
  27. package/src/lib/frequency-cap.ts +45 -15
  28. package/src/lib/hatchet-duration.ts +22 -0
  29. package/src/lib/html.ts +1 -0
  30. package/src/lib/ingestion.ts +145 -4
  31. package/src/lib/journey-suppress.ts +87 -0
  32. package/src/lib/links.ts +204 -18
  33. package/src/lib/outbound.ts +20 -0
  34. package/src/lib/preferences.ts +80 -1
  35. package/src/lib/tracked.ts +44 -29
  36. package/src/lib/tracking-event-names.ts +8 -0
  37. package/src/lib/tracking.ts +1 -5
  38. package/src/lib/webhook-signing.ts +6 -1
  39. package/src/lists/channels.ts +75 -0
  40. package/src/lists/define-list.ts +34 -0
  41. package/src/lists/registry.ts +29 -2
  42. package/src/mcp/authoring-guide.ts +160 -0
  43. package/src/mcp/blueprint-tools.ts +390 -0
  44. package/src/middleware/require-admin.ts +13 -0
  45. package/src/routes/admin/api-keys.ts +72 -0
  46. package/src/routes/admin/blueprints.ts +795 -0
  47. package/src/routes/admin/campaigns.ts +179 -3
  48. package/src/routes/admin/emails.ts +13 -0
  49. package/src/routes/admin/events.ts +55 -0
  50. package/src/routes/admin/index.ts +4 -0
  51. package/src/routes/admin/journeys.ts +4 -2
  52. package/src/routes/admin/links.ts +303 -36
  53. package/src/routes/admin/lists.ts +51 -0
  54. package/src/routes/campaigns/index.ts +44 -6
  55. package/src/routes/email/preferences.ts +50 -13
  56. package/src/routes/feed/recipient.ts +2 -43
  57. package/src/routes/index.ts +6 -0
  58. package/src/routes/lists/index.ts +138 -18
  59. package/src/routes/tracking/arrive.ts +260 -0
  60. package/src/routes/tracking/click-pipeline.ts +329 -0
  61. package/src/routes/tracking/click.ts +5 -270
  62. package/src/routes/tracking/index.ts +2 -0
  63. package/src/routes/tracking/vanity.ts +64 -0
  64. package/src/worker.ts +5 -0
  65. package/src/workflows/bucket-backfill.ts +4 -2
  66. package/src/workflows/bucket-reconcile.ts +11 -4
  67. package/src/workflows/check-alerts.ts +130 -1
  68. package/src/workflows/journey-blueprint-interpreter.ts +656 -0
  69. package/src/workflows/send-campaign.ts +574 -180
@@ -0,0 +1,795 @@
1
+ /**
2
+ * Admin routes for Journey Blueprints (spec §9) — the HTTP surface of the
3
+ * blueprint service layer (`lib/blueprints.ts`), which owns the CRUD +
4
+ * lifecycle logic AND the save-time sandbox boundary (spec §8): a graph is
5
+ * NEVER written to `journey_blueprints` without passing
6
+ * `validateBlueprintGraphForSave`. The agent tools
7
+ * (`mcp/blueprint-tools.ts`, spec §9) wrap the SAME service functions — no
8
+ * parallel auth or storage path; this file only maps service results to
9
+ * HTTP statuses.
10
+ *
11
+ * Auth/rate-limit/audit come from the parent `adminRouter` middleware stack.
12
+ *
13
+ * Result → status mapping (uniform across handlers):
14
+ * - `invalid_graph` → 422 with the structured `BlueprintValidationIssue[]`
15
+ * verbatim (never a caught exception message)
16
+ * - `not_found` → 404, `conflict`/`promoted`/`already_promoted`/`in_flight`
17
+ * → 409
18
+ *
19
+ * A graph-changing update is REJECTED (`in_flight` → 409) while the
20
+ * blueprint has any active/waiting `journeyStates` rows — Hatchet's durable
21
+ * sleep/wait primitives are matched positionally on replay, so changing the
22
+ * node sequence out from under a suspended run can desync its replay
23
+ * journal. Code journeys don't have this hazard (their `run()` is immutable
24
+ * compiled code); a blueprint's graph is a mutable row, so this is an
25
+ * explicit gate, enforced in the service layer (`lib/blueprints.ts`), not
26
+ * an implicit guarantee. Wait for enrollments to drain (or disable and let
27
+ * them finish) before editing a live graph.
28
+ */
29
+ import { type JourneyGraph, journeyGraphSchema } from "@hogsend/core";
30
+ import { journeyBlueprints, journeyStates } from "@hogsend/db";
31
+ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
32
+ import { and, count, desc, eq, inArray, isNull } from "drizzle-orm";
33
+ import type { AppEnv } from "../../app.js";
34
+ import {
35
+ blueprintCreateBaseSchema,
36
+ blueprintGraphInputSchema,
37
+ blueprintPatchFieldsSchema,
38
+ blueprintSourceSchema,
39
+ blueprintStatusSchema,
40
+ createBlueprint,
41
+ disableBlueprint,
42
+ enableBlueprint,
43
+ findBlueprintRow,
44
+ promoteBlueprint,
45
+ serializeBlueprint,
46
+ serializedBlueprintSchema,
47
+ updateBlueprint,
48
+ validateBlueprintGraphForSave,
49
+ } from "../../lib/blueprints.js";
50
+ import { errorSchema, paginationQuerySchema } from "../../lib/schemas.js";
51
+ import { serializeState, stateSchema } from "./journeys.js";
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // Schemas
55
+ // ---------------------------------------------------------------------------
56
+
57
+ const createBodySchema = blueprintCreateBaseSchema.extend({
58
+ source: blueprintSourceSchema,
59
+ });
60
+
61
+ // Partial update (shared field shapes from the service layer). The routes add
62
+ // the "at least one field" refinement on the whole body.
63
+ const patchBodySchema = blueprintPatchFieldsSchema.refine(
64
+ (body) => Object.values(body).some((v) => v !== undefined),
65
+ { message: "PATCH body must set at least one field" },
66
+ );
67
+
68
+ const validationIssueSchema = z.object({
69
+ nodeId: z.string().optional(),
70
+ edgeId: z.string().optional(),
71
+ path: z.array(z.union([z.string(), z.number()])),
72
+ code: z.string(),
73
+ message: z.string(),
74
+ });
75
+
76
+ /** 422 body for any write rejected by graph validation. */
77
+ const invalidGraphSchema = z.object({
78
+ error: z.string(),
79
+ issues: z.array(validationIssueSchema),
80
+ });
81
+
82
+ /**
83
+ * 409 body: the neutral error message PLUS the machine-readable service `code`
84
+ * (`conflict` | `in_flight` | `promoted` | `already_promoted` |
85
+ * `version_conflict`). A programmatic caller (e.g. `@hogsend/mcp`) branches on
86
+ * `code` instead of sniffing the message. `error` stays present and unchanged
87
+ * for existing consumers.
88
+ */
89
+ const conflictSchema = z.object({
90
+ error: z.string(),
91
+ code: z.enum([
92
+ "conflict",
93
+ "in_flight",
94
+ "promoted",
95
+ "already_promoted",
96
+ "version_conflict",
97
+ ]),
98
+ });
99
+
100
+ /** The dry-run validate report — 200 either way (a failed validation is a
101
+ * successful validation CALL; this is the agent's iterate-in-a-loop surface). */
102
+ const validationReportSchema = z.object({
103
+ valid: z.boolean(),
104
+ issues: z.array(validationIssueSchema),
105
+ });
106
+
107
+ const countsSchema = z.object({
108
+ active: z.number(),
109
+ waiting: z.number(),
110
+ completed: z.number(),
111
+ failed: z.number(),
112
+ exited: z.number(),
113
+ });
114
+
115
+ // Row serialization is FLAT (column names verbatim: triggerEvent,
116
+ // triggerWhere, …) so a GET → edit → PATCH loop round-trips 1:1 with the
117
+ // write bodies above — shape + serializer live in the service layer,
118
+ // shared with the agent tools.
119
+ const blueprintSchema = serializedBlueprintSchema;
120
+
121
+ // List rows omit the graph blob (fetch one / the graph route carry it).
122
+ const blueprintListItemSchema = blueprintSchema
123
+ .omit({ graph: true })
124
+ .extend({ counts: countsSchema });
125
+
126
+ const blueprintDetailSchema = blueprintSchema.extend({
127
+ counts: countsSchema,
128
+ recentStates: z.array(stateSchema),
129
+ });
130
+
131
+ const emptyCounts = {
132
+ active: 0,
133
+ waiting: 0,
134
+ completed: 0,
135
+ failed: 0,
136
+ exited: 0,
137
+ };
138
+
139
+ // ---------------------------------------------------------------------------
140
+ // Route definitions
141
+ // ---------------------------------------------------------------------------
142
+
143
+ const listRouteDef = createRoute({
144
+ method: "get",
145
+ path: "/",
146
+ tags: ["Admin — Blueprints"],
147
+ summary: "List journey blueprints",
148
+ request: {
149
+ query: paginationQuerySchema.extend({
150
+ status: blueprintStatusSchema.optional(),
151
+ }),
152
+ },
153
+ responses: {
154
+ 200: {
155
+ content: {
156
+ "application/json": {
157
+ schema: z.object({
158
+ blueprints: z.array(blueprintListItemSchema),
159
+ total: z.number(),
160
+ limit: z.number(),
161
+ offset: z.number(),
162
+ }),
163
+ },
164
+ },
165
+ description: "Paginated blueprint list with per-blueprint state counts",
166
+ },
167
+ },
168
+ });
169
+
170
+ const createRouteDef = createRoute({
171
+ method: "post",
172
+ path: "/",
173
+ tags: ["Admin — Blueprints"],
174
+ summary: "Create a journey blueprint",
175
+ description:
176
+ "The blueprint id is the graph's `journeyId`. The graph is validated " +
177
+ "(`validateBlueprintGraph` + template/connector registry checks) before " +
178
+ "anything is written — an invalid graph is never saved. Defaults to " +
179
+ '`status: "draft"`; pass `status: "enabled"` to go live immediately ' +
180
+ "(spec §10 — no forced staging step).",
181
+ request: {
182
+ body: {
183
+ content: { "application/json": { schema: createBodySchema } },
184
+ },
185
+ },
186
+ responses: {
187
+ 201: {
188
+ content: {
189
+ "application/json": {
190
+ schema: z.object({ blueprint: blueprintSchema }),
191
+ },
192
+ },
193
+ description: "Blueprint created",
194
+ },
195
+ 409: {
196
+ content: { "application/json": { schema: conflictSchema } },
197
+ description:
198
+ "Blueprint id already exists, or collides with a registered code journey",
199
+ },
200
+ 422: {
201
+ content: { "application/json": { schema: invalidGraphSchema } },
202
+ description: "Graph failed validation — structured issues included",
203
+ },
204
+ },
205
+ });
206
+
207
+ const validateRouteDef = createRoute({
208
+ method: "post",
209
+ path: "/validate",
210
+ tags: ["Admin — Blueprints"],
211
+ summary: "Validate a blueprint graph (dry-run, no write, no id required)",
212
+ description:
213
+ "The iterate-in-a-loop call for an authoring agent: validates an " +
214
+ "arbitrary graph body through the exact checks create/PATCH/enable run " +
215
+ "(schema + structure + template/connector registries) and returns the " +
216
+ "structured issue list. Always 200 — `valid: false` is a successful " +
217
+ "validation call, not an error.",
218
+ request: {
219
+ body: {
220
+ content: {
221
+ "application/json": {
222
+ schema: z.object({ graph: blueprintGraphInputSchema }),
223
+ },
224
+ },
225
+ },
226
+ },
227
+ responses: {
228
+ 200: {
229
+ content: { "application/json": { schema: validationReportSchema } },
230
+ description: "Validation report",
231
+ },
232
+ },
233
+ });
234
+
235
+ const getRouteDef = createRoute({
236
+ method: "get",
237
+ path: "/{id}",
238
+ tags: ["Admin — Blueprints"],
239
+ summary: "Get blueprint detail",
240
+ request: {
241
+ params: z.object({ id: z.string() }),
242
+ },
243
+ responses: {
244
+ 200: {
245
+ content: {
246
+ "application/json": {
247
+ schema: z.object({ blueprint: blueprintDetailSchema }),
248
+ },
249
+ },
250
+ description: "Blueprint detail with counts and recent states",
251
+ },
252
+ 404: {
253
+ content: { "application/json": { schema: errorSchema } },
254
+ description: "Blueprint not found",
255
+ },
256
+ },
257
+ });
258
+
259
+ const patchRouteDef = createRoute({
260
+ method: "patch",
261
+ path: "/{id}",
262
+ tags: ["Admin — Blueprints"],
263
+ summary: "Update a journey blueprint",
264
+ description:
265
+ "Partial update. A `graph` change is re-validated the same way create " +
266
+ "is and bumps `version` by 1 — but is rejected (409) while the " +
267
+ "blueprint has any active/waiting enrollment, since a graph edit can " +
268
+ "desync Hatchet's replay journal for a run suspended mid-graph. " +
269
+ "Metadata-only edits do not bump and are never blocked. Status " +
270
+ "transitions go through /enable and /disable, not PATCH. A blueprint " +
271
+ "promoted to code (see /promote) is frozen and rejects every update " +
272
+ "(409) — the code journey is the source of truth.",
273
+ request: {
274
+ params: z.object({ id: z.string() }),
275
+ body: {
276
+ content: { "application/json": { schema: patchBodySchema } },
277
+ },
278
+ },
279
+ responses: {
280
+ 200: {
281
+ content: {
282
+ "application/json": {
283
+ schema: z.object({ blueprint: blueprintSchema }),
284
+ },
285
+ },
286
+ description: "Blueprint updated",
287
+ },
288
+ 404: {
289
+ content: { "application/json": { schema: errorSchema } },
290
+ description: "Blueprint not found",
291
+ },
292
+ 409: {
293
+ content: { "application/json": { schema: conflictSchema } },
294
+ description:
295
+ "Graph change rejected — the blueprint has active/waiting " +
296
+ "enrollments, was promoted to code, or was edited concurrently " +
297
+ "(version conflict — re-read and retry)",
298
+ },
299
+ 422: {
300
+ content: { "application/json": { schema: invalidGraphSchema } },
301
+ description:
302
+ "Graph failed validation, or its journeyId does not match the blueprint id",
303
+ },
304
+ },
305
+ });
306
+
307
+ const validateByIdRouteDef = createRoute({
308
+ method: "post",
309
+ path: "/{id}/validate",
310
+ tags: ["Admin — Blueprints"],
311
+ summary: "Re-validate a saved blueprint's stored graph (dry-run, no write)",
312
+ description:
313
+ "Runs the STORED graph through the current validation + registry checks. " +
314
+ "Useful after registry drift (e.g. a template was unregistered since " +
315
+ "save). To validate a graph that is not saved yet, use POST /validate.",
316
+ request: {
317
+ params: z.object({ id: z.string() }),
318
+ },
319
+ responses: {
320
+ 200: {
321
+ content: { "application/json": { schema: validationReportSchema } },
322
+ description: "Validation report for the stored graph",
323
+ },
324
+ 404: {
325
+ content: { "application/json": { schema: errorSchema } },
326
+ description: "Blueprint not found",
327
+ },
328
+ },
329
+ });
330
+
331
+ const enableRouteDef = createRoute({
332
+ method: "post",
333
+ path: "/{id}/enable",
334
+ tags: ["Admin — Blueprints"],
335
+ summary: "Enable a blueprint (new events start enrolling)",
336
+ description:
337
+ "Re-validates the stored graph against the CURRENT registries first — " +
338
+ "a blueprint whose template/connector vanished since save cannot go " +
339
+ "live. Idempotent when already enabled.",
340
+ request: {
341
+ params: z.object({ id: z.string() }),
342
+ },
343
+ responses: {
344
+ 200: {
345
+ content: {
346
+ "application/json": {
347
+ schema: z.object({ blueprint: blueprintSchema }),
348
+ },
349
+ },
350
+ description: "Blueprint enabled",
351
+ },
352
+ 404: {
353
+ content: { "application/json": { schema: errorSchema } },
354
+ description: "Blueprint not found",
355
+ },
356
+ 409: {
357
+ content: { "application/json": { schema: conflictSchema } },
358
+ description:
359
+ "Blueprint was promoted to code — the code journey is the source of truth",
360
+ },
361
+ 422: {
362
+ content: { "application/json": { schema: invalidGraphSchema } },
363
+ description: "Stored graph no longer passes validation",
364
+ },
365
+ },
366
+ });
367
+
368
+ const disableRouteDef = createRoute({
369
+ method: "post",
370
+ path: "/{id}/disable",
371
+ tags: ["Admin — Blueprints"],
372
+ summary: "Disable a blueprint (stops new enrollments)",
373
+ description:
374
+ "New enrollments stop on the next event; in-flight runs keep going " +
375
+ "(spec §12 — matches how code journeys behave when enabled flips off). " +
376
+ "Idempotent when already disabled.",
377
+ request: {
378
+ params: z.object({ id: z.string() }),
379
+ },
380
+ responses: {
381
+ 200: {
382
+ content: {
383
+ "application/json": {
384
+ schema: z.object({ blueprint: blueprintSchema }),
385
+ },
386
+ },
387
+ description: "Blueprint disabled",
388
+ },
389
+ 404: {
390
+ content: { "application/json": { schema: errorSchema } },
391
+ description: "Blueprint not found",
392
+ },
393
+ },
394
+ });
395
+
396
+ const promoteRouteDef = createRoute({
397
+ method: "post",
398
+ path: "/{id}/promote",
399
+ tags: ["Admin — Blueprints"],
400
+ summary: "Mark a blueprint as promoted to a code journey",
401
+ description:
402
+ "Records that a generated code journey is now the source of truth " +
403
+ "(spec §11): stamps `promotedAt`/`promotedToJourneyId` and disables the " +
404
+ "blueprint in one update. A promoted blueprint can never be re-enabled. " +
405
+ "This is ONLY the DB state transition — codegen (blueprint → " +
406
+ "`defineJourney()` file) happens in the CLI, not here.",
407
+ request: {
408
+ params: z.object({ id: z.string() }),
409
+ body: {
410
+ content: {
411
+ "application/json": {
412
+ schema: z.object({ journeyId: z.string().min(1) }),
413
+ },
414
+ },
415
+ },
416
+ },
417
+ responses: {
418
+ 200: {
419
+ content: {
420
+ "application/json": {
421
+ schema: z.object({ blueprint: blueprintSchema }),
422
+ },
423
+ },
424
+ description: "Blueprint promoted and disabled",
425
+ },
426
+ 404: {
427
+ content: { "application/json": { schema: errorSchema } },
428
+ description: "Blueprint not found",
429
+ },
430
+ 409: {
431
+ content: { "application/json": { schema: conflictSchema } },
432
+ description: "Blueprint was already promoted",
433
+ },
434
+ },
435
+ });
436
+
437
+ // Byte-identical response shape to GET /v1/admin/journeys/{id}/graph — the
438
+ // SAME Studio flow-view component renders either without modification
439
+ // (spec §3/§9). `templateKey` needs no resolution cascade here: a blueprint
440
+ // send node always carries the literal registry key.
441
+ const graphRouteDef = createRoute({
442
+ method: "get",
443
+ path: "/{id}/graph",
444
+ tags: ["Admin — Blueprints"],
445
+ summary: "Blueprint visual workflow graph with per-node live/failed metrics",
446
+ request: {
447
+ params: z.object({ id: z.string() }),
448
+ },
449
+ responses: {
450
+ 200: {
451
+ content: {
452
+ "application/json": {
453
+ schema: z.object({
454
+ graph: journeyGraphSchema,
455
+ metrics: z.object({
456
+ enrolled: z.number(),
457
+ terminals: z.object({
458
+ completed: z.number(),
459
+ failed: z.number(),
460
+ exited: z.number(),
461
+ }),
462
+ nodes: z.record(
463
+ z.string(),
464
+ z.object({
465
+ live: z.number(),
466
+ failed: z.number(),
467
+ templateKey: z.string().optional(),
468
+ templatePath: z.string().optional(),
469
+ }),
470
+ ),
471
+ }),
472
+ }),
473
+ },
474
+ },
475
+ description: "Blueprint graph (IR) plus retroactive per-node metrics",
476
+ },
477
+ 404: {
478
+ content: { "application/json": { schema: errorSchema } },
479
+ description: "Blueprint not found",
480
+ },
481
+ },
482
+ });
483
+
484
+ // ---------------------------------------------------------------------------
485
+ // Handlers
486
+ // ---------------------------------------------------------------------------
487
+
488
+ // Registered statement-per-route rather than as one `.openapi()` chain: the
489
+ // chain form accumulates every route's request/response schema into the
490
+ // router's generic type, and this router is type-checked inside every
491
+ // consumer's DTS build (tsup noExternal) — nine routes of accumulated zod
492
+ // generics OOM the DTS worker. Statement form discards each call's return
493
+ // type while keeping per-handler type safety. The router is mounted
494
+ // internally by the adminRouter, never consumed via hono/client, so no
495
+ // client-side type info is lost.
496
+ export const blueprintsRouter = new OpenAPIHono<AppEnv>();
497
+
498
+ blueprintsRouter.openapi(listRouteDef, async (c) => {
499
+ const { db } = c.get("container");
500
+ const { limit, offset, status } = c.req.valid("query");
501
+
502
+ const where = status ? eq(journeyBlueprints.status, status) : undefined;
503
+
504
+ const [rows, totalRows] = await Promise.all([
505
+ db
506
+ .select()
507
+ .from(journeyBlueprints)
508
+ .where(where)
509
+ .orderBy(desc(journeyBlueprints.createdAt))
510
+ .limit(limit)
511
+ .offset(offset),
512
+ db.select({ count: count() }).from(journeyBlueprints).where(where),
513
+ ]);
514
+
515
+ const ids = rows.map((row) => row.id);
516
+ const statusCounts =
517
+ ids.length > 0
518
+ ? await db
519
+ .select({
520
+ journeyId: journeyStates.journeyId,
521
+ status: journeyStates.status,
522
+ count: count(),
523
+ })
524
+ .from(journeyStates)
525
+ .where(
526
+ and(
527
+ inArray(journeyStates.journeyId, ids),
528
+ isNull(journeyStates.deletedAt),
529
+ ),
530
+ )
531
+ .groupBy(journeyStates.journeyId, journeyStates.status)
532
+ : [];
533
+
534
+ const countsMap = new Map<string, typeof emptyCounts>();
535
+ for (const row of statusCounts) {
536
+ const existing = countsMap.get(row.journeyId) ?? { ...emptyCounts };
537
+ existing[row.status as keyof typeof emptyCounts] = row.count;
538
+ countsMap.set(row.journeyId, existing);
539
+ }
540
+
541
+ return c.json(
542
+ {
543
+ blueprints: rows.map((row) => {
544
+ const { graph: _graph, ...rest } = serializeBlueprint(row);
545
+ return { ...rest, counts: countsMap.get(row.id) ?? { ...emptyCounts } };
546
+ }),
547
+ total: totalRows[0]?.count ?? 0,
548
+ limit,
549
+ offset,
550
+ },
551
+ 200,
552
+ );
553
+ });
554
+
555
+ blueprintsRouter.openapi(createRouteDef, async (c) => {
556
+ const container = c.get("container");
557
+ const body = c.req.valid("json");
558
+
559
+ const result = await createBlueprint({ container, input: body });
560
+ if (!result.ok) {
561
+ if (result.code === "invalid_graph") {
562
+ return c.json({ error: result.error, issues: result.issues }, 422);
563
+ }
564
+ return c.json({ error: result.error, code: result.code }, 409);
565
+ }
566
+ return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 201);
567
+ });
568
+
569
+ blueprintsRouter.openapi(validateRouteDef, async (c) => {
570
+ const container = c.get("container");
571
+ const { graph } = c.req.valid("json");
572
+
573
+ const result = validateBlueprintGraphForSave(graph, container);
574
+ return c.json(
575
+ result.valid
576
+ ? { valid: true, issues: [] }
577
+ : { valid: false, issues: result.issues },
578
+ 200,
579
+ );
580
+ });
581
+
582
+ blueprintsRouter.openapi(getRouteDef, async (c) => {
583
+ const { db } = c.get("container");
584
+ const { id } = c.req.valid("param");
585
+
586
+ const row = await findBlueprintRow({ db, id });
587
+ if (!row) {
588
+ return c.json({ error: "Blueprint not found" }, 404);
589
+ }
590
+
591
+ const [statusCounts, recentRows] = await Promise.all([
592
+ db
593
+ .select({ status: journeyStates.status, count: count() })
594
+ .from(journeyStates)
595
+ .where(
596
+ and(eq(journeyStates.journeyId, id), isNull(journeyStates.deletedAt)),
597
+ )
598
+ .groupBy(journeyStates.status),
599
+ db
600
+ .select()
601
+ .from(journeyStates)
602
+ .where(
603
+ and(eq(journeyStates.journeyId, id), isNull(journeyStates.deletedAt)),
604
+ )
605
+ .orderBy(desc(journeyStates.updatedAt))
606
+ .limit(10),
607
+ ]);
608
+
609
+ const counts = { ...emptyCounts };
610
+ for (const statusRow of statusCounts) {
611
+ counts[statusRow.status as keyof typeof emptyCounts] = statusRow.count;
612
+ }
613
+
614
+ return c.json(
615
+ {
616
+ blueprint: {
617
+ ...serializeBlueprint(row),
618
+ counts,
619
+ recentStates: recentRows.map(serializeState),
620
+ },
621
+ },
622
+ 200,
623
+ );
624
+ });
625
+
626
+ blueprintsRouter.openapi(patchRouteDef, async (c) => {
627
+ const container = c.get("container");
628
+ const { id } = c.req.valid("param");
629
+ const body = c.req.valid("json");
630
+
631
+ const result = await updateBlueprint({ container, id, patch: body });
632
+ if (!result.ok) {
633
+ if (result.code === "invalid_graph") {
634
+ return c.json({ error: result.error, issues: result.issues }, 422);
635
+ }
636
+ if (
637
+ result.code === "in_flight" ||
638
+ result.code === "promoted" ||
639
+ result.code === "version_conflict"
640
+ ) {
641
+ return c.json({ error: result.error, code: result.code }, 409);
642
+ }
643
+ return c.json({ error: result.error }, 404);
644
+ }
645
+ return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 200);
646
+ });
647
+
648
+ blueprintsRouter.openapi(validateByIdRouteDef, async (c) => {
649
+ const container = c.get("container");
650
+ const { id } = c.req.valid("param");
651
+
652
+ const row = await findBlueprintRow({ db: container.db, id });
653
+ if (!row) {
654
+ return c.json({ error: "Blueprint not found" }, 404);
655
+ }
656
+
657
+ const result = validateBlueprintGraphForSave(row.graph, container);
658
+ return c.json(
659
+ result.valid
660
+ ? { valid: true, issues: [] }
661
+ : { valid: false, issues: result.issues },
662
+ 200,
663
+ );
664
+ });
665
+
666
+ blueprintsRouter.openapi(enableRouteDef, async (c) => {
667
+ const container = c.get("container");
668
+ const { id } = c.req.valid("param");
669
+
670
+ const result = await enableBlueprint({ container, id });
671
+ if (!result.ok) {
672
+ if (result.code === "invalid_graph") {
673
+ return c.json({ error: result.error, issues: result.issues }, 422);
674
+ }
675
+ if (result.code === "promoted") {
676
+ return c.json({ error: result.error, code: result.code }, 409);
677
+ }
678
+ return c.json({ error: result.error }, 404);
679
+ }
680
+ return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 200);
681
+ });
682
+
683
+ blueprintsRouter.openapi(disableRouteDef, async (c) => {
684
+ const container = c.get("container");
685
+ const { id } = c.req.valid("param");
686
+
687
+ const result = await disableBlueprint({ container, id });
688
+ if (!result.ok) {
689
+ return c.json({ error: result.error }, 404);
690
+ }
691
+ return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 200);
692
+ });
693
+
694
+ blueprintsRouter.openapi(promoteRouteDef, async (c) => {
695
+ const container = c.get("container");
696
+ const { id } = c.req.valid("param");
697
+ const { journeyId } = c.req.valid("json");
698
+
699
+ const result = await promoteBlueprint({ container, id, journeyId });
700
+ if (!result.ok) {
701
+ if (result.code === "already_promoted") {
702
+ return c.json({ error: result.error, code: result.code }, 409);
703
+ }
704
+ return c.json({ error: result.error }, 404);
705
+ }
706
+ return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 200);
707
+ });
708
+
709
+ blueprintsRouter.openapi(graphRouteDef, async (c) => {
710
+ const { db, templates } = c.get("container");
711
+ const { id } = c.req.valid("param");
712
+
713
+ const row = await findBlueprintRow({ db, id });
714
+ if (!row) {
715
+ return c.json({ error: "Blueprint not found" }, 404);
716
+ }
717
+
718
+ const graph = row.graph as unknown as JourneyGraph;
719
+
720
+ // Same grouped query as the code-journey graph route: per-node live/failed
721
+ // AND the status totals in one pass. A blueprint enrollment is a normal
722
+ // journey_states row with journeyId = the blueprint id.
723
+ const perNode = await db
724
+ .select({
725
+ nodeId: journeyStates.currentNodeId,
726
+ status: journeyStates.status,
727
+ count: count(),
728
+ })
729
+ .from(journeyStates)
730
+ .where(
731
+ and(eq(journeyStates.journeyId, id), isNull(journeyStates.deletedAt)),
732
+ )
733
+ .groupBy(journeyStates.currentNodeId, journeyStates.status);
734
+
735
+ const nodeMetrics: Record<
736
+ string,
737
+ {
738
+ live: number;
739
+ failed: number;
740
+ templateKey?: string;
741
+ templatePath?: string;
742
+ }
743
+ > = {};
744
+ for (const node of graph.nodes) {
745
+ nodeMetrics[node.id] = { live: 0, failed: 0 };
746
+ }
747
+
748
+ const statusTotals: Record<string, number> = {};
749
+ for (const perNodeRow of perNode) {
750
+ const n = Number(perNodeRow.count);
751
+ statusTotals[perNodeRow.status] =
752
+ (statusTotals[perNodeRow.status] ?? 0) + n;
753
+ const nodeId = perNodeRow.nodeId;
754
+ if (!nodeId) continue;
755
+ const entry = nodeMetrics[nodeId] ?? { live: 0, failed: 0 };
756
+ if (perNodeRow.status === "active" || perNodeRow.status === "waiting") {
757
+ entry.live += n;
758
+ } else if (perNodeRow.status === "failed") {
759
+ entry.failed += n;
760
+ }
761
+ nodeMetrics[nodeId] = entry;
762
+ }
763
+
764
+ const enrolled = Object.values(statusTotals).reduce((a, b) => a + b, 0);
765
+
766
+ // Send-node template resolution is trivial here (unlike the code-journey
767
+ // route's 4-step cascade): a blueprint send node ALWAYS carries the
768
+ // literal registry key — blueprintGraphSchema requires it.
769
+ for (const node of graph.nodes) {
770
+ if (node.type !== "send") continue;
771
+ const key = node.meta?.template;
772
+ if (!key) continue;
773
+ const entry = nodeMetrics[node.id] ?? { live: 0, failed: 0 };
774
+ entry.templateKey = key;
775
+ const def = (templates as Record<string, { sourcePath?: string }>)[key];
776
+ if (def?.sourcePath) entry.templatePath = def.sourcePath;
777
+ nodeMetrics[node.id] = entry;
778
+ }
779
+
780
+ return c.json(
781
+ {
782
+ graph,
783
+ metrics: {
784
+ enrolled,
785
+ terminals: {
786
+ completed: statusTotals.completed ?? 0,
787
+ failed: statusTotals.failed ?? 0,
788
+ exited: statusTotals.exited ?? 0,
789
+ },
790
+ nodes: nodeMetrics,
791
+ },
792
+ },
793
+ 200,
794
+ );
795
+ });