@hogsend/engine 0.40.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 (62) 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 +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 +82 -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 +608 -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 +374 -59
  17. package/src/journeys/record-once.ts +110 -0
  18. package/src/lib/blueprints.ts +576 -0
  19. package/src/lib/campaign-send-key.ts +58 -0
  20. package/src/lib/connector-actions.ts +203 -19
  21. package/src/lib/contacts.ts +54 -0
  22. package/src/lib/email-service-types.ts +4 -1
  23. package/src/lib/email.ts +13 -2
  24. package/src/lib/feed.ts +77 -57
  25. package/src/lib/frequency-cap.ts +45 -15
  26. package/src/lib/hatchet-duration.ts +22 -0
  27. package/src/lib/html.ts +1 -0
  28. package/src/lib/ingestion.ts +145 -4
  29. package/src/lib/journey-suppress.ts +87 -0
  30. package/src/lib/links.ts +204 -18
  31. package/src/lib/outbound.ts +20 -0
  32. package/src/lib/preferences.ts +80 -1
  33. package/src/lib/tracked.ts +44 -29
  34. package/src/lib/tracking-event-names.ts +8 -0
  35. package/src/lib/webhook-signing.ts +6 -1
  36. package/src/lists/channels.ts +75 -0
  37. package/src/lists/define-list.ts +34 -0
  38. package/src/lists/registry.ts +29 -2
  39. package/src/mcp/blueprint-tools.ts +460 -0
  40. package/src/routes/admin/blueprints.ts +711 -0
  41. package/src/routes/admin/campaigns.ts +179 -3
  42. package/src/routes/admin/emails.ts +13 -0
  43. package/src/routes/admin/index.ts +4 -0
  44. package/src/routes/admin/journeys.ts +4 -2
  45. package/src/routes/admin/links.ts +303 -36
  46. package/src/routes/admin/lists.ts +51 -0
  47. package/src/routes/campaigns/index.ts +44 -6
  48. package/src/routes/email/preferences.ts +50 -13
  49. package/src/routes/feed/recipient.ts +2 -43
  50. package/src/routes/index.ts +6 -0
  51. package/src/routes/lists/index.ts +138 -18
  52. package/src/routes/tracking/arrive.ts +260 -0
  53. package/src/routes/tracking/click-pipeline.ts +329 -0
  54. package/src/routes/tracking/click.ts +5 -270
  55. package/src/routes/tracking/index.ts +2 -0
  56. package/src/routes/tracking/vanity.ts +64 -0
  57. package/src/worker.ts +5 -0
  58. package/src/workflows/bucket-backfill.ts +4 -2
  59. package/src/workflows/bucket-reconcile.ts +11 -4
  60. package/src/workflows/check-alerts.ts +130 -1
  61. package/src/workflows/journey-blueprint-interpreter.ts +561 -0
  62. package/src/workflows/send-campaign.ts +574 -180
@@ -0,0 +1,561 @@
1
+ import type { JsonValue } from "@hatchet-dev/typescript-sdk/v1/types.js";
2
+ import {
3
+ type BlueprintGraph,
4
+ BlueprintNodeExecutionError,
5
+ BlueprintUnreachableNodeError,
6
+ type DurationObject,
7
+ evaluateCondition,
8
+ type JourneyEdge,
9
+ type JourneyNode,
10
+ type PropertyCondition,
11
+ serializeBlueprintError,
12
+ validateBlueprintGraph,
13
+ } from "@hogsend/core";
14
+ import type {
15
+ JourneyContext,
16
+ JourneyMeta,
17
+ JourneyUser,
18
+ } from "@hogsend/core/types";
19
+ import { type Database, journeyBlueprints, journeyStates } from "@hogsend/db";
20
+ import type { TemplateName } from "@hogsend/email";
21
+ import { and, eq, notInArray } from "drizzle-orm";
22
+ import {
23
+ BLUEPRINT_RUN_EVENT,
24
+ JOURNEY_EXECUTION_TIMEOUT,
25
+ JOURNEY_SCHEDULE_TIMEOUT,
26
+ } from "../journeys/constants.js";
27
+ import { JourneyExitedError } from "../journeys/errors.js";
28
+ import {
29
+ type EventPayloadInput,
30
+ executeJourneyRun,
31
+ } from "../journeys/execute-journey-run.js";
32
+ import { TERMINAL_STATUSES } from "../journeys/journey-context.js";
33
+ import { logTransition } from "../journeys/journey-log.js";
34
+ import { sendConnectorAction } from "../lib/connector-actions.js";
35
+ import { getDb } from "../lib/db.js";
36
+ import { sendEmail } from "../lib/email.js";
37
+ import { hatchet } from "../lib/hatchet.js";
38
+ import { createLogger } from "../lib/logger.js";
39
+
40
+ const logger = createLogger(process.env.LOG_LEVEL);
41
+
42
+ /** A `journey_blueprints` row as Drizzle returns it. */
43
+ export type JourneyBlueprintRow = typeof journeyBlueprints.$inferSelect;
44
+
45
+ /**
46
+ * Build the `JourneyMeta` the shared run lifecycle consumes from a
47
+ * `journey_blueprints` row. The row's trigger/entry/exit/suppress columns
48
+ * mirror `JourneyMeta` 1:1 by design (spec §4) so the SAME enrollment-guard
49
+ * functions `defineJourney` uses receive it verbatim — `status !== "enabled"`
50
+ * is the blueprint's `meta.enabled === false`. The jsonb columns are opaque in
51
+ * `@hogsend/db` (db cannot import core), so this is the single read-site
52
+ * narrowing, per the `campaigns.steps` convention.
53
+ */
54
+ export function blueprintMetaFromRow(row: JourneyBlueprintRow): JourneyMeta {
55
+ const triggerWhere = (row.triggerWhere ?? undefined) as
56
+ | PropertyCondition[]
57
+ | undefined;
58
+ return {
59
+ id: row.id,
60
+ name: row.name,
61
+ ...(row.description ? { description: row.description } : {}),
62
+ enabled: row.status === "enabled",
63
+ trigger: {
64
+ event: row.triggerEvent,
65
+ ...(triggerWhere?.length ? { where: triggerWhere } : {}),
66
+ },
67
+ entryLimit: row.entryLimit,
68
+ ...(row.entryPeriod
69
+ ? { entryPeriod: row.entryPeriod as DurationObject }
70
+ : {}),
71
+ ...(row.exitOn?.length
72
+ ? { exitOn: row.exitOn as NonNullable<JourneyMeta["exitOn"]> }
73
+ : {}),
74
+ // `{}` / zero duration disables the suppress guard — same contract as
75
+ // JourneyMeta.suppress (the boundary maps it to suppressMs: 0).
76
+ suppress: (row.suppress ?? {}) as DurationObject,
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Errors the per-node wrap must NOT swallow into a `BlueprintNodeExecutionError`:
82
+ * - `JourneyExitedError` — a control-flow signal (exitOn / cancel / the
83
+ * `end-exited` node); the lifecycle catch maps it to `status: "exited"`.
84
+ * - Hatchet's AbortError — a graceful-shutdown RELEASE; wrapping it would
85
+ * defeat the lifecycle's abort detection and poison the enrollment with a
86
+ * false "failed".
87
+ * - Blueprint errors already carrying their node id.
88
+ */
89
+ function isWalkPassThroughError(err: unknown): boolean {
90
+ if (err instanceof JourneyExitedError) return true;
91
+ if (
92
+ err instanceof BlueprintNodeExecutionError ||
93
+ err instanceof BlueprintUnreachableNodeError
94
+ ) {
95
+ return true;
96
+ }
97
+ return (
98
+ err instanceof Error &&
99
+ (err.name === "AbortError" ||
100
+ (err as { code?: string }).code === "ABORT_ERR")
101
+ );
102
+ }
103
+
104
+ /** Narrow a required meta field, throwing the typed node error when absent.
105
+ * Unreachable for a graph that passed `validateBlueprintGraph` (the schema
106
+ * requires per-variant meta) — jsonb defense-in-depth plus TS narrowing. */
107
+ function requireNodeMeta<T>(
108
+ blueprintId: string,
109
+ node: { id: string; type: string },
110
+ field: string,
111
+ value: T | undefined | null,
112
+ ): T {
113
+ if (value === undefined || value === null) {
114
+ throw new BlueprintNodeExecutionError(
115
+ blueprintId,
116
+ node.id,
117
+ `${node.type} node is missing required meta.${field}`,
118
+ );
119
+ }
120
+ return value;
121
+ }
122
+
123
+ export interface WalkBlueprintGraphOptions {
124
+ blueprintId: string;
125
+ /** A graph that passed {@link validateBlueprintGraph}. */
126
+ graph: BlueprintGraph;
127
+ user: JourneyUser;
128
+ ctx: JourneyContext;
129
+ db: Database;
130
+ }
131
+
132
+ /**
133
+ * Tree-walk a validated blueprint graph, executing each node through the
134
+ * EXACT same primitives a code journey calls (spec §6): `ctx.sleep`,
135
+ * `ctx.waitForEvent`, `ctx.checkpoint`, `ctx.trigger`, `sendEmail()`,
136
+ * `sendConnectorAction()`, `evaluateCondition()`. Every label/idempotencyLabel
137
+ * is the node id — as replay-stable as a hand-authored `ctx.sleep({ label })`
138
+ * — so the existing two-layer exactly-once machinery applies unchanged.
139
+ *
140
+ * The dispatch is an exhaustive `switch` over the FULL `JourneyNodeType`
141
+ * union with a compiler-enforced `never` default (spec §6.1): adding a node
142
+ * type without an interpreter case is a compile error, and the four
143
+ * non-executable display-tier types throw typed errors as defense-in-depth
144
+ * (validation already rejected them).
145
+ */
146
+ export async function walkBlueprintGraph(
147
+ opts: WalkBlueprintGraphOptions,
148
+ ): Promise<void> {
149
+ const { blueprintId, graph, user, ctx, db } = opts;
150
+
151
+ // The execution tier is a compile-asserted narrowing of the display tier,
152
+ // so widening to `JourneyNode` is free — and it is what lets the switch
153
+ // below cover the FULL node-type vocabulary (a `BlueprintNode`-typed switch
154
+ // could not even name the non-executable cases).
155
+ const nodes: JourneyNode[] = graph.nodes;
156
+ const nodesById = new Map<string, JourneyNode>(
157
+ nodes.map((node) => [node.id, node]),
158
+ );
159
+ const outgoing = new Map<string, JourneyEdge[]>();
160
+ for (const edge of graph.edges) {
161
+ const list = outgoing.get(edge.source) ?? [];
162
+ list.push(edge);
163
+ outgoing.set(edge.source, list);
164
+ }
165
+
166
+ const start = nodes.find((node) => node.type === "start");
167
+ if (!start) {
168
+ // Unreachable post-validation (findStartNodeIssues) — defense-in-depth.
169
+ throw new BlueprintNodeExecutionError(
170
+ blueprintId,
171
+ "start",
172
+ "graph has no start node",
173
+ );
174
+ }
175
+
176
+ /** The single unconditional next hop. Zero outgoing edges ends the walk —
177
+ * the run returns and the lifecycle marks the enrollment completed, exactly
178
+ * like a code journey's `run()` running off the end of its body. */
179
+ const defaultNext = (node: JourneyNode): string | null => {
180
+ const edges = outgoing.get(node.id) ?? [];
181
+ if (edges.length === 0) return null;
182
+ if (edges.length === 1) {
183
+ // length === 1 → the single element exists; TS can't see that.
184
+ return edges[0]?.target ?? null;
185
+ }
186
+ throw new BlueprintNodeExecutionError(
187
+ blueprintId,
188
+ node.id,
189
+ `a ${node.type} node cannot fork (${edges.length} outgoing edges)`,
190
+ );
191
+ };
192
+
193
+ /** Pick the outgoing edge whose `kind` matches, throwing when absent. */
194
+ const nextByKind = (node: JourneyNode, kind: JourneyEdge["kind"]): string => {
195
+ const edge = (outgoing.get(node.id) ?? []).find((e) => e.kind === kind);
196
+ if (!edge) {
197
+ throw new BlueprintNodeExecutionError(
198
+ blueprintId,
199
+ node.id,
200
+ `no outgoing edge with kind "${kind}"`,
201
+ );
202
+ }
203
+ return edge.target;
204
+ };
205
+
206
+ /** Execute one node; returns the next node id, or null to end the walk. */
207
+ const executeNode = async (node: JourneyNode): Promise<string | null> => {
208
+ switch (node.type) {
209
+ case "start":
210
+ return defaultNext(node);
211
+
212
+ case "sleep": {
213
+ const duration = requireNodeMeta(
214
+ blueprintId,
215
+ node,
216
+ "duration",
217
+ node.meta?.duration,
218
+ );
219
+ await ctx.sleep({
220
+ duration: duration as DurationObject,
221
+ label: node.id,
222
+ });
223
+ return defaultNext(node);
224
+ }
225
+
226
+ case "wait": {
227
+ const event = requireNodeMeta(
228
+ blueprintId,
229
+ node,
230
+ "event",
231
+ node.meta?.event,
232
+ );
233
+ const timeout = requireNodeMeta(
234
+ blueprintId,
235
+ node,
236
+ "timeout",
237
+ node.meta?.timeout,
238
+ );
239
+ const result = await ctx.waitForEvent({
240
+ event,
241
+ timeout: timeout as DurationObject,
242
+ label: node.id,
243
+ });
244
+ // A forking wait branches on the answer (validation guarantees the
245
+ // answered/timedOut pair); a single unconditional edge (or none)
246
+ // continues regardless of the outcome.
247
+ const edges = outgoing.get(node.id) ?? [];
248
+ if (edges.length === 2) {
249
+ return nextByKind(node, result.timedOut ? "timedOut" : "answered");
250
+ }
251
+ return defaultNext(node);
252
+ }
253
+
254
+ case "send": {
255
+ const template = requireNodeMeta(
256
+ blueprintId,
257
+ node,
258
+ "template",
259
+ node.meta?.template,
260
+ );
261
+ // subject omitted → the tracked mailer falls back to the template
262
+ // registry's defaultSubject. idempotencyLabel = the node id (unique
263
+ // per graph), so the derived exactly-once key is branch-stable even
264
+ // when two sends of the same template share a nearest wait label.
265
+ await sendEmail({
266
+ to: user.email,
267
+ userId: user.id,
268
+ journeyStateId: user.stateId,
269
+ template: template as TemplateName,
270
+ journeyName: user.journeyName,
271
+ props: user.properties,
272
+ idempotencyLabel: node.meta?.idempotencyLabel ?? node.id,
273
+ });
274
+ return defaultNext(node);
275
+ }
276
+
277
+ case "connector": {
278
+ const connectorId = requireNodeMeta(
279
+ blueprintId,
280
+ node,
281
+ "connectorId",
282
+ node.meta?.connectorId,
283
+ );
284
+ const action = requireNodeMeta(
285
+ blueprintId,
286
+ node,
287
+ "action",
288
+ node.meta?.action,
289
+ );
290
+ // KNOWN PRE-EXISTING GAP (spec §15): sendConnectorAction's Layer-2
291
+ // backstop covers replays, but in degraded (pre-eviction) mode a
292
+ // crash between the provider call and the status flip can still
293
+ // double-send — same exposure a code journey's connector call has.
294
+ await sendConnectorAction({
295
+ connectorId,
296
+ action,
297
+ idempotencyLabel: node.id,
298
+ });
299
+ return defaultNext(node);
300
+ }
301
+
302
+ case "checkpoint":
303
+ await ctx.checkpoint(node.id);
304
+ return defaultNext(node);
305
+
306
+ case "trigger": {
307
+ const event = requireNodeMeta(
308
+ blueprintId,
309
+ node,
310
+ "event",
311
+ node.meta?.event,
312
+ );
313
+ await ctx.trigger({
314
+ event,
315
+ userId: user.id,
316
+ userEmail: user.email,
317
+ idempotencyLabel: node.id,
318
+ });
319
+ return defaultNext(node);
320
+ }
321
+
322
+ case "branch":
323
+ case "decision": {
324
+ const conditions = node.meta?.conditions;
325
+ if (!conditions?.length) {
326
+ throw new BlueprintNodeExecutionError(
327
+ blueprintId,
328
+ node.id,
329
+ `${node.type} node has no conditions to evaluate`,
330
+ );
331
+ }
332
+ // AND across the array (a single composite condition expresses OR).
333
+ // Recorded via ctx.once so the verdict is durable on ANY engine: a
334
+ // decision may read live DB state (event / email_engagement
335
+ // conditions), and a replay re-evaluating it could flip the branch —
336
+ // diverging the positional durable journal AND selecting a different
337
+ // downstream template. Exactly the non-deterministic-discriminant
338
+ // case ctx.once exists for; the node id keys the record.
339
+ const passed = await ctx.once(`decision:${node.id}`, async () => {
340
+ for (const condition of conditions) {
341
+ const matched = await evaluateCondition({
342
+ condition,
343
+ ctx: { db, userId: user.id, journeyContext: user.properties },
344
+ });
345
+ if (!matched) return false;
346
+ }
347
+ return true;
348
+ });
349
+ return nextByKind(
350
+ node,
351
+ passed ? "conditional-true" : "conditional-false",
352
+ );
353
+ }
354
+
355
+ case "end-completed":
356
+ // Terminal: the run returns and the shared lifecycle marks the
357
+ // enrollment completed + pushes journey:completed — identical to a
358
+ // code journey's run() returning normally.
359
+ return null;
360
+
361
+ case "end-exited": {
362
+ // Terminal: flip the row terminal the same way checkExits does, then
363
+ // abort the run via the SAME control-flow signal a mid-wait exit
364
+ // uses — the lifecycle catch maps it to { status: "exited" } without
365
+ // a "failed" write or a journey:failed push. Idempotent on replay
366
+ // (the guarded update no-ops once terminal).
367
+ const [exited] = await db
368
+ .update(journeyStates)
369
+ .set({
370
+ status: "exited",
371
+ exitedAt: new Date(),
372
+ updatedAt: new Date(),
373
+ })
374
+ .where(
375
+ and(
376
+ eq(journeyStates.id, user.stateId),
377
+ notInArray(journeyStates.status, [...TERMINAL_STATUSES]),
378
+ ),
379
+ )
380
+ .returning({ id: journeyStates.id });
381
+ if (exited) {
382
+ logTransition({
383
+ db,
384
+ journeyStateId: user.stateId,
385
+ from: null,
386
+ to: "end-exited",
387
+ action: "exited",
388
+ });
389
+ }
390
+ throw new JourneyExitedError(user.stateId);
391
+ }
392
+
393
+ case "end-failed":
394
+ // Terminal: matches a code journey's thrown error — the lifecycle
395
+ // marks the row "failed" (structured errorMessage via serializeError),
396
+ // pushes journey:failed, and rethrows so the Hatchet run fails.
397
+ throw new BlueprintNodeExecutionError(
398
+ blueprintId,
399
+ node.id,
400
+ "the walk reached an end-failed terminal node",
401
+ );
402
+
403
+ // Non-executable display-tier types (NON_EXECUTABLE_NODE_TYPES).
404
+ // Unreachable in practice — validateBlueprintGraph rejected them at
405
+ // save time AND again at execution time — but the switch covers the
406
+ // FULL JourneyNodeType vocabulary so reaching one throws the typed
407
+ // error instead of walking past it silently (spec §6.1).
408
+ case "sleepUntil":
409
+ case "capture":
410
+ case "digest":
411
+ case "unknown":
412
+ throw new BlueprintNodeExecutionError(
413
+ blueprintId,
414
+ node.id,
415
+ `node type "${node.type}" is not executable in a blueprint`,
416
+ );
417
+
418
+ default: {
419
+ // Compiler-enforced exhaustiveness: adding a JourneyNodeType without
420
+ // an interpreter case is a COMPILE error, not a silent no-op.
421
+ const _exhaustive: never = node;
422
+ throw new BlueprintNodeExecutionError(
423
+ blueprintId,
424
+ (_exhaustive as JourneyNode).id,
425
+ `unhandled node type: ${(_exhaustive as JourneyNode).type}`,
426
+ );
427
+ }
428
+ }
429
+ };
430
+
431
+ let currentId: string | null = start.id;
432
+ let steps = 0;
433
+ while (currentId !== null) {
434
+ const node = nodesById.get(currentId);
435
+ if (!node) {
436
+ // An edge pointed at a node that does not exist. Unreachable post-
437
+ // validation (findInvalidEdgeEndpoints) — defense-in-depth.
438
+ throw new BlueprintUnreachableNodeError(blueprintId, currentId);
439
+ }
440
+ // Acyclicity backstop: a validated graph visits each node at most once,
441
+ // so a walk longer than the node count means a cycle slipped past
442
+ // validation — fail loudly instead of spinning durable sleeps forever.
443
+ steps += 1;
444
+ if (steps > nodes.length) {
445
+ throw new BlueprintNodeExecutionError(
446
+ blueprintId,
447
+ node.id,
448
+ "tree-walk exceeded the graph's node count — the graph is not acyclic",
449
+ );
450
+ }
451
+ try {
452
+ currentId = await executeNode(node);
453
+ } catch (err) {
454
+ if (isWalkPassThroughError(err)) throw err;
455
+ // Any other failure is pinned to the node that raised it, so
456
+ // journeyStates.errorMessage / Studio can point at exactly what broke.
457
+ throw new BlueprintNodeExecutionError(blueprintId, node.id, err);
458
+ }
459
+ }
460
+ }
461
+
462
+ /**
463
+ * The event payload `checkBlueprintTriggers` pushes for each matching enabled
464
+ * blueprint — one push per (blueprint, user) enrollment attempt.
465
+ */
466
+ export interface BlueprintRunPayload {
467
+ blueprintId: JsonValue;
468
+ blueprintVersion: JsonValue;
469
+ userId: JsonValue;
470
+ userEmail: JsonValue;
471
+ triggerProperties: JsonValue;
472
+ [key: string]: JsonValue;
473
+ }
474
+
475
+ /**
476
+ * The generic blueprint interpreter — ONE statically-registered durable task
477
+ * for ALL blueprints, ever (spec §5): blueprints created/edited/enabled at
478
+ * runtime need no worker redeploy because dispatch is a DB lookup at ingest
479
+ * (`checkBlueprintTriggers`) feeding this task via `blueprint:run`, not a
480
+ * per-blueprint `onEvents` registration.
481
+ *
482
+ * Each run loads the blueprint row, re-validates the stored graph
483
+ * (defense-in-depth — jsonb is not trusted at execution time either), builds
484
+ * the row's `JourneyMeta` mirror, and hands the tree-walk to the SAME
485
+ * `executeJourneyRun` lifecycle `defineJourney` tasks use — identical
486
+ * enrollment guards, replay recovery, journey context, replay-safety
487
+ * boundary, and terminal transitions.
488
+ */
489
+ export const journeyBlueprintInterpreter = hatchet.durableTask({
490
+ name: "journey-blueprint-interpreter",
491
+ onEvents: [BLUEPRINT_RUN_EVENT],
492
+ executionTimeout: JOURNEY_EXECUTION_TIMEOUT,
493
+ // retries STAYS 0 — same "missed > doubled" rationale as define-journey's
494
+ // task config: a retry replays side effects whose durable status flip may
495
+ // not have committed.
496
+ retries: 0,
497
+ scheduleTimeout: JOURNEY_SCHEDULE_TIMEOUT,
498
+ fn: async (input: BlueprintRunPayload, hatchetCtx) => {
499
+ const db = getDb();
500
+ const blueprintId = input.blueprintId as string;
501
+
502
+ const row = await db.query.journeyBlueprints.findFirst({
503
+ where: eq(journeyBlueprints.id, blueprintId),
504
+ });
505
+ if (!row) {
506
+ logger.warn("blueprint run skipped: blueprint not found", {
507
+ blueprintId,
508
+ });
509
+ return { status: "skipped", reason: "blueprint_not_found" };
510
+ }
511
+
512
+ // Defense-in-depth (spec §6): a saved blueprint already passed
513
+ // validateBlueprintGraph at save time, but the graph column is still
514
+ // jsonb — never execute it without re-validating.
515
+ const validated = validateBlueprintGraph(row.graph);
516
+ if (!validated.valid) {
517
+ logger.error(
518
+ "blueprint run skipped: stored graph failed execution-time validation",
519
+ { blueprintId, issues: validated.issues },
520
+ );
521
+ return { status: "skipped", reason: "invalid_blueprint_graph" };
522
+ }
523
+
524
+ // Version pin (spec §12): the version this run enrolled under, recorded
525
+ // into journeyStates.context.__blueprintVersion on FIRST entry (a replay
526
+ // recovers the existing row — extraContext is never re-written). v1 keeps
527
+ // no graph history, so a drifted row can only execute the CURRENT graph —
528
+ // surface the drift loudly instead of failing the run.
529
+ const enrolledVersion =
530
+ typeof input.blueprintVersion === "number"
531
+ ? input.blueprintVersion
532
+ : row.version;
533
+ if (enrolledVersion !== row.version) {
534
+ logger.warn(
535
+ "blueprint version drifted since this run was dispatched; executing the current graph",
536
+ { blueprintId, enrolledVersion, currentVersion: row.version },
537
+ );
538
+ }
539
+
540
+ const meta = blueprintMetaFromRow(row);
541
+ const graph = validated.graph;
542
+
543
+ return executeJourneyRun({
544
+ meta,
545
+ run: (user, ctx) =>
546
+ walkBlueprintGraph({ blueprintId: row.id, graph, user, ctx, db }),
547
+ input: {
548
+ userId: input.userId,
549
+ userEmail: input.userEmail,
550
+ properties: input.triggerProperties,
551
+ } satisfies EventPayloadInput,
552
+ hatchetCtx,
553
+ extraContext: { __blueprintVersion: enrolledVersion },
554
+ // Structured errorMessage (spec §6.1): { blueprintId, nodeId, message }
555
+ // as JSON in the SAME journeyStates.errorMessage field code journeys
556
+ // use, so Studio's error display needs no blueprint-specific branching.
557
+ serializeError: (err) =>
558
+ JSON.stringify(serializeBlueprintError(row.id, err)),
559
+ });
560
+ },
561
+ });