@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,803 @@
1
+ /**
2
+ * Journey Blueprint service layer — the ONE write path for
3
+ * `journey_blueprints`, shared verbatim by the admin routes
4
+ * (`routes/admin/blueprints.ts`) and the agent-facing tools
5
+ * (`mcp/blueprint-tools.ts`). Spec §9's "the MCP tool is a thin wrapper over
6
+ * these — no parallel auth or storage path" is enforced structurally: both
7
+ * surfaces call these functions in-process, so there is nothing to drift.
8
+ *
9
+ * This module is the save-time sandbox boundary of the whole feature
10
+ * (spec §8): a graph is NEVER written without passing
11
+ * {@link validateBlueprintGraphForSave} — `validateBlueprintGraph` (field
12
+ * shapes + structural checks, @hogsend/core) layered with the engine-side
13
+ * registry checks core cannot do (template keys, connector actions).
14
+ *
15
+ * Conventions (shared by both surfaces):
16
+ * - the blueprint id IS the graph's `journeyId` (one id, one namespace —
17
+ * `journeyStates.journeyId` points at it, same as a code journey's meta.id)
18
+ * - `version` bumps on any update that includes `graph` (metadata-only edits
19
+ * don't bump; we deliberately don't deep-diff — jsonb normalizes key order,
20
+ * so equality checks would be unreliable, and a spurious bump is harmless)
21
+ * - a graph-changing update is REJECTED (`in_flight` failure) while the
22
+ * blueprint has any active/waiting `journeyStates` rows — Hatchet's
23
+ * durable sleep/wait primitives are matched positionally on replay, so
24
+ * changing the node sequence out from under a suspended run can desync
25
+ * its replay journal. Code journeys don't have this hazard (their
26
+ * `run()` is immutable compiled code); a blueprint's graph is a mutable
27
+ * row, so this is an explicit gate, not an implicit guarantee
28
+ * - enabling always re-runs validation against the CURRENT registries — a
29
+ * template unregistered since save is caught here, not at 2am mid-run
30
+ * - expected failures are result objects (discriminated on `ok`/`code`)
31
+ * carrying the structured `BlueprintValidationIssue[]` verbatim — never a
32
+ * caught exception's `.message`
33
+ */
34
+ import {
35
+ type BlueprintGraph,
36
+ type BlueprintValidationIssue,
37
+ type BlueprintValidationResult,
38
+ blueprintGraphSchema,
39
+ isReservedEventName,
40
+ type JourneyGraph,
41
+ journeyGraphSchema,
42
+ RESERVED_EVENT_NAMESPACES,
43
+ validateBlueprintGraph,
44
+ } from "@hogsend/core";
45
+ import { propertyConditionSchema } from "@hogsend/core/schemas";
46
+ import { journeyBlueprints, journeyStates } from "@hogsend/db";
47
+ import { getTemplateNames } from "@hogsend/email";
48
+ import { z } from "@hono/zod-openapi";
49
+ import { and, count, eq, inArray, isNull } from "drizzle-orm";
50
+ import type { HogsendClient } from "../container.js";
51
+ import { blueprintGraphLock } from "./blueprint-lock.js";
52
+
53
+ export type BlueprintRow = typeof journeyBlueprints.$inferSelect;
54
+ /** The opaque jsonb type of the `graph` column (db cannot import core). */
55
+ type BlueprintGraphColumn = BlueprintRow["graph"];
56
+
57
+ /** What graph validation needs from the container. */
58
+ export type BlueprintRegistryContainer = Pick<
59
+ HogsendClient,
60
+ "templates" | "connectorActionRegistry"
61
+ >;
62
+
63
+ /** What the write operations need from the container. */
64
+ export type BlueprintServiceContainer = Pick<
65
+ HogsendClient,
66
+ "db" | "registry" | "templates" | "connectorActionRegistry"
67
+ >;
68
+
69
+ // ---------------------------------------------------------------------------
70
+ // Save-time validation — core checks + engine registry checks
71
+ // ---------------------------------------------------------------------------
72
+
73
+ /**
74
+ * The engine-side half of the save-time sandbox (spec §8): every node input
75
+ * is checked against a KNOWN registry, so a `send` of a template that isn't
76
+ * registered (or a connector action that doesn't exist) fails at save time
77
+ * with a structured issue, not at run time. @hogsend/core cannot do these —
78
+ * the registries live in the container.
79
+ */
80
+ function findRegistryIssues(
81
+ graph: BlueprintGraph,
82
+ container: BlueprintRegistryContainer,
83
+ ): BlueprintValidationIssue[] {
84
+ const issues: BlueprintValidationIssue[] = [];
85
+ const templateKeys = new Set<string>(getTemplateNames(container.templates));
86
+ graph.nodes.forEach((node, index) => {
87
+ if (node.type === "send" && !templateKeys.has(node.meta.template)) {
88
+ issues.push({
89
+ nodeId: node.id,
90
+ path: ["nodes", index, "meta", "template"],
91
+ code: "unknown_template",
92
+ message: `node "${node.id}": "${node.meta.template}" is not a registered template key`,
93
+ });
94
+ }
95
+ if (node.type === "connector") {
96
+ const { connectorId, action } = node.meta;
97
+ if (!container.connectorActionRegistry.get(connectorId, action)) {
98
+ issues.push({
99
+ nodeId: node.id,
100
+ path: ["nodes", index, "meta", "connectorId"],
101
+ code: "unknown_connector_action",
102
+ message: `node "${node.id}": no connector action "${connectorId}:${action}" is registered`,
103
+ });
104
+ }
105
+ }
106
+ // Reserved namespaces (email./journey./bucket./contact., dot or colon)
107
+ // are engine-emitted — a trigger node forging one would feed synthetic
108
+ // engine events through the full ingest pipeline. Same rule the semantic
109
+ // link send path enforces; the interpreter re-throws as defense-in-depth.
110
+ if (node.type === "trigger" && isReservedEventName(node.meta.event)) {
111
+ issues.push({
112
+ nodeId: node.id,
113
+ path: ["nodes", index, "meta", "event"],
114
+ code: "reserved_event",
115
+ message: `node "${node.id}": event "${node.meta.event}" uses a reserved namespace (${RESERVED_EVENT_NAMESPACES.join("/")}) — engine-emitted events cannot be forged by a blueprint`,
116
+ });
117
+ }
118
+ });
119
+ return issues;
120
+ }
121
+
122
+ /** The structured `invalid_graph` failure for a reserved trigger EVENT (the
123
+ * blueprint-record field, not a graph node) — shared by create and update. */
124
+ function reservedTriggerEventFailure(
125
+ triggerEvent: string,
126
+ ): BlueprintInvalidGraphFailure {
127
+ return {
128
+ ok: false,
129
+ code: "invalid_graph",
130
+ error: "triggerEvent uses a reserved event namespace",
131
+ issues: [
132
+ {
133
+ path: ["triggerEvent"],
134
+ code: "reserved_event",
135
+ message: `triggerEvent "${triggerEvent}" uses a reserved namespace (${RESERVED_EVENT_NAMESPACES.join("/")}) — engine-emitted events cannot trigger a blueprint`,
136
+ },
137
+ ],
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Full save-time validation: `validateBlueprintGraph` (field shapes +
143
+ * structural checks) plus the registry checks above. Used by create, update
144
+ * (when `graph` is present), enable (re-check against CURRENT registries),
145
+ * and every validate surface — one validation story for every write path.
146
+ *
147
+ * When the graph parses field-wise but fails STRUCTURALLY, the registry
148
+ * issues are still appended to the report — an iterating agent gets the whole
149
+ * "what's wrong" list in one round instead of discovering the unknown
150
+ * template only after fixing the cycle.
151
+ */
152
+ export function validateBlueprintGraphForSave(
153
+ graph: unknown,
154
+ container: BlueprintRegistryContainer,
155
+ ): BlueprintValidationResult {
156
+ const result = validateBlueprintGraph(graph);
157
+ if (result.valid) {
158
+ const issues = findRegistryIssues(result.graph, container);
159
+ if (issues.length > 0) return { valid: false, issues };
160
+ return result;
161
+ }
162
+ // Structural failure: the field shapes may still have parsed, in which case
163
+ // the send/connector nodes are inspectable — report registry problems too.
164
+ const parsed = blueprintGraphSchema.safeParse(graph);
165
+ if (!parsed.success) return result;
166
+ return {
167
+ valid: false,
168
+ issues: [
169
+ ...result.issues,
170
+ ...findRegistryIssues(
171
+ parsed.data as unknown as BlueprintGraph,
172
+ container,
173
+ ),
174
+ ],
175
+ };
176
+ }
177
+
178
+ // ---------------------------------------------------------------------------
179
+ // Shared input schemas — one source of truth for admin routes AND tools
180
+ // ---------------------------------------------------------------------------
181
+
182
+ /**
183
+ * Execution-tier duration INPUT: strict keys so `{ days: 3 }` is rejected
184
+ * loudly instead of becoming a silent zero (`durationToMs` ignores unknown
185
+ * keys). Empty `{}` is allowed — for `suppress` it means "disabled", same
186
+ * contract as JourneyMeta.suppress.
187
+ */
188
+ export const blueprintDurationInputSchema = z.strictObject({
189
+ hours: z.number().nonnegative().optional(),
190
+ minutes: z.number().nonnegative().optional(),
191
+ seconds: z.number().nonnegative().optional(),
192
+ });
193
+
194
+ /**
195
+ * `entryPeriod` variant: requires a POSITIVE duration. Key presence alone is
196
+ * not enough — `{ hours: 0 }` (or `{ seconds: 0 }`) still makes
197
+ * `durationToMs(...) === 0`, which silently turns `once_per_period` into
198
+ * `unlimited` (cutoff === now, so every trigger re-enrolls). That is the one
199
+ * place a zero-length duration is a footgun, not a "disabled" contract
200
+ * (unlike `suppress`, where `{}` is the documented "disabled" sentinel), so
201
+ * refine on the summed value, not on presence. Omitting `entryPeriod` entirely
202
+ * stays legal: `checkEntryLimit` defaults an undefined period to 24h.
203
+ */
204
+ export const blueprintEntryPeriodInputSchema =
205
+ blueprintDurationInputSchema.refine(
206
+ (d) => (d.hours ?? 0) + (d.minutes ?? 0) + (d.seconds ?? 0) > 0,
207
+ {
208
+ message:
209
+ "entryPeriod must be a positive duration (hours/minutes/seconds)",
210
+ },
211
+ );
212
+
213
+ export const blueprintExitOnInputSchema = z.array(
214
+ z.object({
215
+ event: z.string().min(1),
216
+ where: z.array(propertyConditionSchema).optional(),
217
+ }),
218
+ );
219
+
220
+ export const blueprintStatusSchema = z.enum(["draft", "enabled", "disabled"]);
221
+ export const blueprintEntryLimitSchema = z.enum([
222
+ "once",
223
+ "once_per_period",
224
+ "unlimited",
225
+ ]);
226
+ export const blueprintSourceSchema = z.enum(["mcp", "studio", "api"]);
227
+
228
+ // The graph is accepted as `unknown` and validated by
229
+ // validateBlueprintGraphForSave — so a malformed graph ALWAYS yields the
230
+ // structured issue list, never a schema layer's generic error.
231
+ export const blueprintGraphInputSchema = z.unknown();
232
+
233
+ /**
234
+ * The create payload MINUS `source` — provenance is stamped by the surface
235
+ * (the admin route takes it from the request body; the agent tools hard-code
236
+ * `"mcp"`), never trusted to mean the same thing across surfaces.
237
+ */
238
+ export const blueprintCreateBaseSchema = z.object({
239
+ name: z.string().min(1),
240
+ description: z.string().optional(),
241
+ /**
242
+ * Defaults to "draft"; a caller MAY create directly enabled (spec §10 —
243
+ * post-hoc oversight, no forced staging step). "disabled" makes no sense
244
+ * at creation and is rejected.
245
+ */
246
+ status: z.enum(["draft", "enabled"]).default("draft"),
247
+ triggerEvent: z.string().min(1),
248
+ triggerWhere: z.array(propertyConditionSchema).optional(),
249
+ entryLimit: blueprintEntryLimitSchema,
250
+ entryPeriod: blueprintEntryPeriodInputSchema.optional(),
251
+ exitOn: blueprintExitOnInputSchema.optional(),
252
+ suppress: blueprintDurationInputSchema,
253
+ graph: blueprintGraphInputSchema,
254
+ createdBy: z.string().min(1).optional(),
255
+ });
256
+
257
+ /**
258
+ * Partial-update fields. `status` is deliberately absent — transitions go
259
+ * through enable/disable so enabling always re-validates. `source`/`createdBy`
260
+ * are provenance and immutable. Nullable fields accept null to clear.
261
+ * Callers layer their own "at least one field" refinement on top (the routes
262
+ * on the body, the tools excluding `id`).
263
+ */
264
+ export const blueprintPatchFieldsSchema = z.object({
265
+ name: z.string().min(1).optional(),
266
+ description: z.string().nullable().optional(),
267
+ triggerEvent: z.string().min(1).optional(),
268
+ triggerWhere: z.array(propertyConditionSchema).nullable().optional(),
269
+ entryLimit: blueprintEntryLimitSchema.optional(),
270
+ entryPeriod: blueprintEntryPeriodInputSchema.nullable().optional(),
271
+ exitOn: blueprintExitOnInputSchema.nullable().optional(),
272
+ suppress: blueprintDurationInputSchema.optional(),
273
+ graph: blueprintGraphInputSchema.optional(),
274
+ });
275
+
276
+ export type CreateBlueprintInput = z.infer<typeof blueprintCreateBaseSchema> & {
277
+ source: z.infer<typeof blueprintSourceSchema>;
278
+ };
279
+ export type UpdateBlueprintPatch = z.infer<typeof blueprintPatchFieldsSchema>;
280
+
281
+ // ---------------------------------------------------------------------------
282
+ // Serialization — flat row shape shared by routes and tools
283
+ // ---------------------------------------------------------------------------
284
+
285
+ // Row serialization is FLAT (column names verbatim: triggerEvent,
286
+ // triggerWhere, …) so a read → edit → update loop round-trips 1:1 with the
287
+ // write inputs above. Stored jsonb is echoed loosely (the strict shapes were
288
+ // enforced at write time).
289
+ export const serializedBlueprintSchema = z.object({
290
+ id: z.string(),
291
+ name: z.string(),
292
+ description: z.string().nullable(),
293
+ status: blueprintStatusSchema,
294
+ version: z.number(),
295
+ triggerEvent: z.string(),
296
+ triggerWhere: z.array(z.record(z.string(), z.unknown())).nullable(),
297
+ entryLimit: blueprintEntryLimitSchema,
298
+ entryPeriod: z.record(z.string(), z.number()).nullable(),
299
+ exitOn: z
300
+ .array(
301
+ z.object({
302
+ event: z.string(),
303
+ where: z.array(z.record(z.string(), z.unknown())).optional(),
304
+ }),
305
+ )
306
+ .nullable(),
307
+ suppress: z.record(z.string(), z.number()),
308
+ graph: journeyGraphSchema,
309
+ source: blueprintSourceSchema,
310
+ createdBy: z.string().nullable(),
311
+ promotedAt: z.string().nullable(),
312
+ promotedToJourneyId: z.string().nullable(),
313
+ createdAt: z.string(),
314
+ updatedAt: z.string(),
315
+ });
316
+
317
+ export type SerializedBlueprint = z.infer<typeof serializedBlueprintSchema>;
318
+
319
+ export function serializeBlueprint(row: BlueprintRow): SerializedBlueprint {
320
+ return {
321
+ id: row.id,
322
+ name: row.name,
323
+ description: row.description,
324
+ status: row.status,
325
+ version: row.version,
326
+ triggerEvent: row.triggerEvent,
327
+ triggerWhere: row.triggerWhere ?? null,
328
+ entryLimit: row.entryLimit,
329
+ entryPeriod: (row.entryPeriod ?? null) as Record<string, number> | null,
330
+ exitOn: row.exitOn ?? null,
331
+ suppress: row.suppress as Record<string, number>,
332
+ graph: row.graph as unknown as JourneyGraph,
333
+ source: row.source,
334
+ createdBy: row.createdBy,
335
+ promotedAt: row.promotedAt?.toISOString() ?? null,
336
+ promotedToJourneyId: row.promotedToJourneyId,
337
+ createdAt: row.createdAt.toISOString(),
338
+ updatedAt: row.updatedAt.toISOString(),
339
+ };
340
+ }
341
+
342
+ // ---------------------------------------------------------------------------
343
+ // Operations — precise per-operation result unions
344
+ // ---------------------------------------------------------------------------
345
+
346
+ export type BlueprintInvalidGraphFailure = {
347
+ ok: false;
348
+ code: "invalid_graph";
349
+ error: string;
350
+ issues: BlueprintValidationIssue[];
351
+ };
352
+ export type BlueprintNotFoundFailure = {
353
+ ok: false;
354
+ code: "not_found";
355
+ error: string;
356
+ };
357
+
358
+ export type CreateBlueprintResult =
359
+ | { ok: true; blueprint: BlueprintRow }
360
+ | { ok: false; code: "conflict"; error: string }
361
+ | BlueprintInvalidGraphFailure;
362
+
363
+ export type BlueprintPromotedFailure = {
364
+ ok: false;
365
+ code: "promoted";
366
+ error: string;
367
+ };
368
+
369
+ /**
370
+ * Optimistic-concurrency loss: a concurrent graph edit committed a version bump
371
+ * between this caller reading the row and its guarded update — retryable (re-read
372
+ * and re-apply the edit onto the new version). Maps to 409, like `in_flight`.
373
+ */
374
+ export type BlueprintVersionConflictFailure = {
375
+ ok: false;
376
+ code: "version_conflict";
377
+ error: string;
378
+ };
379
+
380
+ export type UpdateBlueprintResult =
381
+ | { ok: true; blueprint: BlueprintRow }
382
+ | BlueprintNotFoundFailure
383
+ | BlueprintInvalidGraphFailure
384
+ | { ok: false; code: "in_flight"; error: string }
385
+ | BlueprintVersionConflictFailure
386
+ | BlueprintPromotedFailure;
387
+
388
+ export type EnableBlueprintResult =
389
+ | { ok: true; blueprint: BlueprintRow }
390
+ | BlueprintNotFoundFailure
391
+ | BlueprintPromotedFailure
392
+ | BlueprintInvalidGraphFailure;
393
+
394
+ export type DisableBlueprintResult =
395
+ | { ok: true; blueprint: BlueprintRow }
396
+ | BlueprintNotFoundFailure;
397
+
398
+ export type PromoteBlueprintResult =
399
+ | { ok: true; blueprint: BlueprintRow }
400
+ | BlueprintNotFoundFailure
401
+ | { ok: false; code: "already_promoted"; error: string };
402
+
403
+ export async function findBlueprintRow(opts: {
404
+ db: HogsendClient["db"];
405
+ id: string;
406
+ }): Promise<BlueprintRow | null> {
407
+ const rows = await opts.db
408
+ .select()
409
+ .from(journeyBlueprints)
410
+ .where(eq(journeyBlueprints.id, opts.id))
411
+ .limit(1);
412
+ return rows[0] ?? null;
413
+ }
414
+
415
+ function notFound(id: string): BlueprintNotFoundFailure {
416
+ return { ok: false, code: "not_found", error: `Blueprint "${id}" not found` };
417
+ }
418
+
419
+ /** Shared "already promoted" description for enable's and promote's errors. */
420
+ function describePromotion(
421
+ existing: Pick<BlueprintRow, "promotedAt" | "promotedToJourneyId">,
422
+ ): string {
423
+ const target = existing.promotedToJourneyId ?? "unknown journey";
424
+ const when = existing.promotedAt?.toISOString() ?? "unknown date";
425
+ return `promoted to code journey "${target}" on ${when}`;
426
+ }
427
+
428
+ /**
429
+ * Create a blueprint. The graph is validated (schema + structure +
430
+ * template/connector registries) before anything is written — an invalid
431
+ * graph is never saved. The blueprint id is the graph's `journeyId`.
432
+ */
433
+ export async function createBlueprint(opts: {
434
+ container: BlueprintServiceContainer;
435
+ input: CreateBlueprintInput;
436
+ }): Promise<CreateBlueprintResult> {
437
+ const { container, input } = opts;
438
+
439
+ if (isReservedEventName(input.triggerEvent)) {
440
+ return reservedTriggerEventFailure(input.triggerEvent);
441
+ }
442
+
443
+ const result = validateBlueprintGraphForSave(input.graph, container);
444
+ if (!result.valid) {
445
+ return {
446
+ ok: false,
447
+ code: "invalid_graph",
448
+ error: "Blueprint graph failed validation",
449
+ issues: result.issues,
450
+ };
451
+ }
452
+
453
+ // The graph's journeyId IS the blueprint id — one id, one namespace.
454
+ //
455
+ // KNOWN GAP (documented, not fixed): this only guards the direction where
456
+ // a blueprint is created AFTER a colliding code journey is already
457
+ // registered. The reverse — deploying a NEW code journey whose id matches
458
+ // an EXISTING blueprint's id — isn't guarded anywhere; both would then
459
+ // share journeyStates.journeyId, and exit-condition resolution favors the
460
+ // registered code journey. Closing this needs a boot-time cross-check
461
+ // against journey_blueprints, deliberately left for when this actually
462
+ // bites someone rather than adding DB-dependent boot machinery now.
463
+ const id = result.graph.journeyId;
464
+ if (container.registry.has(id)) {
465
+ return {
466
+ ok: false,
467
+ code: "conflict",
468
+ error: `"${id}" is a registered code journey — blueprint ids share the journey id namespace`,
469
+ };
470
+ }
471
+
472
+ // onConflictDoNothing + returning: the empty result IS the duplicate
473
+ // check, atomically (no read-then-insert race).
474
+ const inserted = await container.db
475
+ .insert(journeyBlueprints)
476
+ .values({
477
+ id,
478
+ name: input.name,
479
+ description: input.description ?? null,
480
+ status: input.status,
481
+ triggerEvent: input.triggerEvent,
482
+ triggerWhere: input.triggerWhere ?? null,
483
+ entryLimit: input.entryLimit,
484
+ entryPeriod: input.entryPeriod ?? null,
485
+ exitOn: input.exitOn ?? null,
486
+ suppress: input.suppress,
487
+ graph: result.graph as unknown as BlueprintGraphColumn,
488
+ source: input.source,
489
+ createdBy: input.createdBy ?? null,
490
+ })
491
+ .onConflictDoNothing({ target: journeyBlueprints.id })
492
+ .returning();
493
+
494
+ const row = inserted[0];
495
+ if (!row) {
496
+ return {
497
+ ok: false,
498
+ code: "conflict",
499
+ error: `Blueprint "${id}" already exists`,
500
+ };
501
+ }
502
+ return { ok: true, blueprint: row };
503
+ }
504
+
505
+ /**
506
+ * Partial update. A `graph` change is re-validated the same way create is and
507
+ * bumps `version` by 1 (in-flight runs stay pinned to the version they enrolled
508
+ * under, spec §12). The graph write runs in a transaction under a
509
+ * blueprint-keyed advisory lock so its in-flight count + update is atomic
510
+ * against a concurrent enrollment insert (which takes the same lock) and is
511
+ * guarded on the version read (`version_conflict` on a concurrent edit) and on
512
+ * `promotedAt IS NULL` (`promoted` on a concurrent promote). Metadata-only edits
513
+ * do not bump, need no lock, and are never blocked. Status transitions go
514
+ * through enable/disable, not here.
515
+ */
516
+ export async function updateBlueprint(opts: {
517
+ container: BlueprintServiceContainer;
518
+ id: string;
519
+ patch: UpdateBlueprintPatch;
520
+ }): Promise<UpdateBlueprintResult> {
521
+ const { container, id, patch } = opts;
522
+
523
+ if (
524
+ patch.triggerEvent !== undefined &&
525
+ isReservedEventName(patch.triggerEvent)
526
+ ) {
527
+ return reservedTriggerEventFailure(patch.triggerEvent);
528
+ }
529
+
530
+ const existing = await findBlueprintRow({ db: container.db, id });
531
+ if (!existing) return notFound(id);
532
+ if (existing.promotedAt) {
533
+ return {
534
+ ok: false,
535
+ code: "promoted",
536
+ error: `Blueprint "${id}" was ${describePromotion(existing)} — it is frozen and cannot be edited`,
537
+ };
538
+ }
539
+
540
+ let validatedGraph: BlueprintGraph | undefined;
541
+ if (patch.graph !== undefined) {
542
+ const result = validateBlueprintGraphForSave(patch.graph, container);
543
+ if (!result.valid) {
544
+ return {
545
+ ok: false,
546
+ code: "invalid_graph",
547
+ error: "Blueprint graph failed validation",
548
+ issues: result.issues,
549
+ };
550
+ }
551
+ if (result.graph.journeyId !== id) {
552
+ return {
553
+ ok: false,
554
+ code: "invalid_graph",
555
+ error: "Graph journeyId does not match the blueprint id",
556
+ issues: [
557
+ {
558
+ path: ["journeyId"],
559
+ code: "journey_id_mismatch",
560
+ message: `graph.journeyId "${result.graph.journeyId}" must match the blueprint id "${id}" — the id is immutable`,
561
+ },
562
+ ],
563
+ };
564
+ }
565
+ validatedGraph = result.graph;
566
+ }
567
+
568
+ const set: Partial<typeof journeyBlueprints.$inferInsert> = {
569
+ updatedAt: new Date(),
570
+ };
571
+ if (patch.name !== undefined) set.name = patch.name;
572
+ if (patch.description !== undefined) set.description = patch.description;
573
+ if (patch.triggerEvent !== undefined) set.triggerEvent = patch.triggerEvent;
574
+ if (patch.triggerWhere !== undefined) set.triggerWhere = patch.triggerWhere;
575
+ if (patch.entryLimit !== undefined) set.entryLimit = patch.entryLimit;
576
+ if (patch.entryPeriod !== undefined) set.entryPeriod = patch.entryPeriod;
577
+ if (patch.exitOn !== undefined) set.exitOn = patch.exitOn;
578
+ if (patch.suppress !== undefined) set.suppress = patch.suppress;
579
+
580
+ // Metadata-only edit: no graph, no version bump, no in-flight hazard (the
581
+ // node sequence is untouched, so no suspended run can desync). One guarded
582
+ // update on `promotedAt IS NULL` closes the promote race the early check
583
+ // above cannot (registry validation / reads happen in between).
584
+ if (validatedGraph === undefined) {
585
+ const updated = await container.db
586
+ .update(journeyBlueprints)
587
+ .set(set)
588
+ .where(
589
+ and(eq(journeyBlueprints.id, id), isNull(journeyBlueprints.promotedAt)),
590
+ )
591
+ .returning();
592
+ const row = updated[0];
593
+ if (row) return { ok: true, blueprint: row };
594
+ const raced = await findBlueprintRow({ db: container.db, id });
595
+ if (!raced) return notFound(id);
596
+ return {
597
+ ok: false,
598
+ code: "promoted",
599
+ error: `Blueprint "${id}" was ${describePromotion(raced)} — it is frozen and cannot be edited`,
600
+ };
601
+ }
602
+
603
+ // Graph edit. Two hazards, both closed inside one transaction under a
604
+ // blueprint-keyed advisory lock (the enrollment insert path takes the SAME
605
+ // lock — blueprint-lock.ts):
606
+ // 1. in-flight: a run must not become active/waiting BETWEEN the count and
607
+ // the write, or a graph edit lands under a just-started run and desyncs
608
+ // its positional Hatchet replay journal. The lock serializes the
609
+ // count+update against enrollment inserts, so the count is authoritative.
610
+ // 2. lost update: two concurrent graph edits serialize on the lock, and the
611
+ // `version = existing.version` predicate makes the loser (whose read
612
+ // predates the winner's bump) match zero rows and return
613
+ // `version_conflict` instead of overwriting the winner's graph.
614
+ // The `promotedAt IS NULL` predicate additionally closes the promote race.
615
+ set.graph = validatedGraph as unknown as BlueprintGraphColumn;
616
+ set.version = existing.version + 1;
617
+
618
+ return container.db.transaction(async (tx) => {
619
+ await tx.execute(blueprintGraphLock(id));
620
+
621
+ const [inFlight] = await tx
622
+ .select({ count: count() })
623
+ .from(journeyStates)
624
+ .where(
625
+ and(
626
+ eq(journeyStates.journeyId, id),
627
+ isNull(journeyStates.deletedAt),
628
+ inArray(journeyStates.status, ["active", "waiting"]),
629
+ ),
630
+ );
631
+ if (inFlight && inFlight.count > 0) {
632
+ return {
633
+ ok: false,
634
+ code: "in_flight",
635
+ error: `Cannot edit this blueprint's graph while ${inFlight.count} enrollment(s) are active or waiting — editing a live graph can desync Hatchet's replay journal for an in-flight run. Wait for enrollments to drain, or disable the blueprint and let them finish, before editing the graph.`,
636
+ };
637
+ }
638
+
639
+ const updated = await tx
640
+ .update(journeyBlueprints)
641
+ .set(set)
642
+ .where(
643
+ and(
644
+ eq(journeyBlueprints.id, id),
645
+ isNull(journeyBlueprints.promotedAt),
646
+ eq(journeyBlueprints.version, existing.version),
647
+ ),
648
+ )
649
+ .returning();
650
+ const row = updated[0];
651
+ if (row) return { ok: true, blueprint: row };
652
+
653
+ // Zero rows: blueprints are never hard-deleted, so the id still exists —
654
+ // the guard that failed is `promotedAt` (a concurrent promote) or `version`
655
+ // (a concurrent graph edit committed its bump). Re-read inside the txn
656
+ // (READ COMMITTED sees the committed winner) to return the precise code.
657
+ const [raced] = await tx
658
+ .select()
659
+ .from(journeyBlueprints)
660
+ .where(eq(journeyBlueprints.id, id))
661
+ .limit(1);
662
+ if (!raced) return notFound(id);
663
+ if (raced.promotedAt) {
664
+ return {
665
+ ok: false,
666
+ code: "promoted",
667
+ error: `Blueprint "${id}" was ${describePromotion(raced)} — it is frozen and cannot be edited`,
668
+ };
669
+ }
670
+ return {
671
+ ok: false,
672
+ code: "version_conflict",
673
+ error: `Blueprint "${id}" changed under you (version ${existing.version} → ${raced.version}) — re-read it and re-apply your edit onto the current graph.`,
674
+ };
675
+ });
676
+ }
677
+
678
+ /**
679
+ * Enable — the moment a graph goes live, so the stored graph is re-validated
680
+ * against the CURRENT registries first (a blueprint whose template/connector
681
+ * vanished since save cannot go live). Idempotent when already enabled. A
682
+ * promoted blueprint cannot be re-enabled — the code journey is the source
683
+ * of truth (spec §11).
684
+ */
685
+ export async function enableBlueprint(opts: {
686
+ container: BlueprintServiceContainer;
687
+ id: string;
688
+ }): Promise<EnableBlueprintResult> {
689
+ const { container, id } = opts;
690
+
691
+ const existing = await findBlueprintRow({ db: container.db, id });
692
+ if (!existing) return notFound(id);
693
+ if (existing.promotedAt) {
694
+ return {
695
+ ok: false,
696
+ code: "promoted",
697
+ error: `Blueprint "${id}" was ${describePromotion(existing)} — the code journey is the source of truth; it cannot be re-enabled`,
698
+ };
699
+ }
700
+
701
+ const result = validateBlueprintGraphForSave(existing.graph, container);
702
+ if (!result.valid) {
703
+ return {
704
+ ok: false,
705
+ code: "invalid_graph",
706
+ error:
707
+ "Stored graph no longer passes validation — fix it before enabling",
708
+ issues: result.issues,
709
+ };
710
+ }
711
+
712
+ // Guarded on promotedAt IS NULL to close the window between the check
713
+ // above and this write — a concurrent promote can land while
714
+ // validateBlueprintGraphForSave is awaited, and without this guard the
715
+ // blind UPDATE below would silently re-enable a blueprint that just got
716
+ // promoted, leaving status="enabled" alongside promotedAt/
717
+ // promotedToJourneyId set.
718
+ const updated = await container.db
719
+ .update(journeyBlueprints)
720
+ .set({ status: "enabled", updatedAt: new Date() })
721
+ .where(
722
+ and(eq(journeyBlueprints.id, id), isNull(journeyBlueprints.promotedAt)),
723
+ )
724
+ .returning();
725
+
726
+ const row = updated[0];
727
+ if (row) return { ok: true, blueprint: row };
728
+
729
+ const raced = await findBlueprintRow({ db: container.db, id });
730
+ if (!raced) return notFound(id);
731
+ return {
732
+ ok: false,
733
+ code: "promoted",
734
+ error: `Blueprint "${id}" was ${describePromotion(raced)} — the code journey is the source of truth; it cannot be re-enabled`,
735
+ };
736
+ }
737
+
738
+ /**
739
+ * Disable — new enrollments stop on the next event; in-flight runs keep
740
+ * going (spec §12 — matches how code journeys behave when enabled flips
741
+ * off). Idempotent when already disabled.
742
+ */
743
+ export async function disableBlueprint(opts: {
744
+ container: BlueprintServiceContainer;
745
+ id: string;
746
+ }): Promise<DisableBlueprintResult> {
747
+ const { container, id } = opts;
748
+
749
+ const updated = await container.db
750
+ .update(journeyBlueprints)
751
+ .set({ status: "disabled", updatedAt: new Date() })
752
+ .where(eq(journeyBlueprints.id, id))
753
+ .returning();
754
+
755
+ const row = updated[0];
756
+ if (!row) return notFound(id);
757
+ return { ok: true, blueprint: row };
758
+ }
759
+
760
+ /**
761
+ * Promote — record that a generated code journey is now the source of truth
762
+ * for this blueprint (spec §11). Stamps `promotedAt`/`promotedToJourneyId`
763
+ * and disables the blueprint in one update; `enableBlueprint` refuses a
764
+ * promoted blueprint from then on. This is ONLY the DB state transition —
765
+ * codegen (blueprint → `defineJourney()` file) lives in the CLI, not here.
766
+ * NOT idempotent: a second promote is `already_promoted` (the caller decides
767
+ * whether that's fine or a mistake — the first promotion's target stands).
768
+ */
769
+ export async function promoteBlueprint(opts: {
770
+ container: BlueprintServiceContainer;
771
+ id: string;
772
+ journeyId: string;
773
+ }): Promise<PromoteBlueprintResult> {
774
+ const { container, id, journeyId } = opts;
775
+
776
+ // A single conditional UPDATE covers both "does it exist" and "is it
777
+ // already promoted" atomically — no separate pre-fetch on the (common)
778
+ // success path. The fallback lookup below only runs to tell the two
779
+ // failure cases apart and build the right error message.
780
+ const updated = await container.db
781
+ .update(journeyBlueprints)
782
+ .set({
783
+ status: "disabled",
784
+ promotedAt: new Date(),
785
+ promotedToJourneyId: journeyId,
786
+ updatedAt: new Date(),
787
+ })
788
+ .where(
789
+ and(eq(journeyBlueprints.id, id), isNull(journeyBlueprints.promotedAt)),
790
+ )
791
+ .returning();
792
+
793
+ const row = updated[0];
794
+ if (row) return { ok: true, blueprint: row };
795
+
796
+ const existing = await findBlueprintRow({ db: container.db, id });
797
+ if (!existing) return notFound(id);
798
+ return {
799
+ ok: false,
800
+ code: "already_promoted",
801
+ error: `Blueprint "${id}" was already ${describePromotion(existing)}`,
802
+ };
803
+ }