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