@hogsend/engine 0.46.1 → 0.50.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/README.md +6 -0
  2. package/package.json +13 -10
  3. package/src/connectors/presets/index.ts +8 -2
  4. package/src/container.ts +149 -7
  5. package/src/destinations/presets/posthog.ts +7 -0
  6. package/src/destinations/presets/segment.ts +5 -0
  7. package/src/env.ts +38 -0
  8. package/src/flags/reconcile.ts +195 -0
  9. package/src/index.ts +79 -0
  10. package/src/journeys/authoring.ts +32 -0
  11. package/src/journeys/define-journey.ts +45 -40
  12. package/src/journeys/execute-journey-run.ts +73 -32
  13. package/src/journeys/journey-boundary.ts +76 -0
  14. package/src/journeys/journey-context.ts +128 -70
  15. package/src/journeys/journey-task-factory.ts +31 -0
  16. package/src/journeys/journey-task-runtime.ts +31 -0
  17. package/src/journeys/journey-version.test.ts +236 -0
  18. package/src/journeys/journey-version.ts +158 -0
  19. package/src/journeys/record-once.ts +28 -2
  20. package/src/lib/connector-actions.test.ts +36 -0
  21. package/src/lib/connector-actions.ts +42 -4
  22. package/src/lib/contacts.ts +49 -0
  23. package/src/lib/conversions.test.ts +33 -0
  24. package/src/lib/conversions.ts +8 -0
  25. package/src/lib/email.ts +23 -2
  26. package/src/lib/enrollment-policy.ts +51 -0
  27. package/src/lib/feed.ts +55 -3
  28. package/src/lib/flags-registry.ts +48 -0
  29. package/src/lib/flags.ts +498 -0
  30. package/src/lib/fx.ts +374 -0
  31. package/src/lib/global-control-readout.ts +166 -0
  32. package/src/lib/groups.ts +362 -0
  33. package/src/lib/ingestion.ts +38 -0
  34. package/src/lib/journey-lift.ts +142 -0
  35. package/src/lib/operator-settings.ts +71 -0
  36. package/src/lib/outbound.ts +147 -0
  37. package/src/lib/preferences.ts +6 -80
  38. package/src/lib/recipient-preferences.ts +53 -0
  39. package/src/lib/sms.ts +21 -2
  40. package/src/lib/stable-stringify.test.ts +42 -0
  41. package/src/lib/stable-stringify.ts +23 -0
  42. package/src/lib/variant.ts +99 -0
  43. package/src/lib/webhook-signing.ts +16 -1
  44. package/src/lists/registry.ts +6 -2
  45. package/src/lists/subscription.ts +13 -0
  46. package/src/routes/admin/contacts.ts +53 -4
  47. package/src/routes/admin/conversions.ts +137 -0
  48. package/src/routes/admin/flags.ts +369 -0
  49. package/src/routes/admin/groups.ts +866 -0
  50. package/src/routes/admin/impact-schemas.ts +44 -0
  51. package/src/routes/admin/impact-wire.test.ts +181 -0
  52. package/src/routes/admin/impact.ts +486 -0
  53. package/src/routes/admin/index.ts +12 -0
  54. package/src/routes/admin/journey-impact.ts +446 -0
  55. package/src/routes/admin/journeys.ts +70 -100
  56. package/src/routes/admin/settings.ts +145 -0
  57. package/src/routes/admin/targeting.ts +256 -0
  58. package/src/routes/events/index.ts +11 -0
  59. package/src/routes/flags/index.ts +120 -0
  60. package/src/routes/groups/index.ts +417 -0
  61. package/src/routes/index.ts +23 -1
  62. package/src/testing.ts +25 -0
  63. package/src/webhook-sources/presets/index.ts +5 -1
  64. package/src/webhook-sources/presets/intercom.ts +230 -0
  65. package/src/webhook-sources/presets/segment.ts +56 -4
  66. package/src/worker.ts +3 -0
  67. package/src/workflows/bucket-backfill.ts +1 -14
  68. package/src/workflows/impact-digest.ts +761 -0
  69. package/src/workflows/journey-blueprint-interpreter.ts +18 -1
package/src/index.ts CHANGED
@@ -1,3 +1,8 @@
1
+ // Install the production Hatchet binding. The `./journeys` authoring subpath
2
+ // intentionally omits this side effect so journey modules stay test-importable
3
+ // without database or Hatchet credentials.
4
+ import "./journeys/journey-task-runtime.js";
5
+
1
6
  // @hogsend/engine — public API surface (the committed semver boundary).
2
7
  //
3
8
  // Content (journeys, webhook sources, workflows) is injected into these
@@ -196,6 +201,11 @@ export {
196
201
  } from "./destinations/registry-singleton.js";
197
202
  // --- Env ---
198
203
  export { API_VERSION, env } from "./env.js";
204
+ // --- Native feature flags (DB-backed, sticky evaluation) ---
205
+ export {
206
+ type FlagReconcileResult,
207
+ reconcileDefinedFlags,
208
+ } from "./flags/reconcile.js";
199
209
  // --- Journeys ---
200
210
  export { BLUEPRINT_RUN_EVENT } from "./journeys/constants.js";
201
211
  export {
@@ -222,6 +232,11 @@ export {
222
232
  deriveJourneyKey,
223
233
  getJourneyBoundary,
224
234
  type JourneyBoundary,
235
+ type JourneyConnectorEffect,
236
+ type JourneyEmailEffect,
237
+ type JourneyFeedEffect,
238
+ type JourneyServiceOverrides,
239
+ type JourneySmsEffect,
225
240
  parseJourneySendSite,
226
241
  registerKey,
227
242
  registerRecordLabel,
@@ -244,9 +259,14 @@ export {
244
259
  resetJourneySources,
245
260
  setJourneySources,
246
261
  } from "./journeys/journey-sources-singleton.js";
262
+ export {
263
+ computeJourneyVersionHash,
264
+ normalizeRunSource,
265
+ } from "./journeys/journey-version.js";
247
266
  export {
248
267
  type RecordNamespace,
249
268
  recordOnce,
269
+ stripRecordNamespaces,
250
270
  } from "./journeys/record-once.js";
251
271
  export {
252
272
  buildJourneyRegistry,
@@ -451,6 +471,11 @@ export type {
451
471
  } from "./lib/email-service-types.js";
452
472
  // --- Enrollment guards ---
453
473
  export { checkEmailPreferences } from "./lib/enrollment-guards.js";
474
+ export {
475
+ type EnrollmentPolicyFacts,
476
+ type EnrollmentPolicyResult,
477
+ evaluateEnrollmentPolicy,
478
+ } from "./lib/enrollment-policy.js";
454
479
  // --- In-app feed (sendFeedItem — sibling of sendEmail/sendConnectorAction) ---
455
480
  export {
456
481
  IN_APP_LIST_ID,
@@ -458,9 +483,42 @@ export {
458
483
  type SendFeedItemResult,
459
484
  sendFeedItem,
460
485
  } from "./lib/feed.js";
486
+ export {
487
+ type EvaluableFlag,
488
+ emptySnapshot,
489
+ evaluateFlag,
490
+ evaluateFlagsForContact,
491
+ evaluateTargeting,
492
+ flagBucket,
493
+ flagUnit,
494
+ loadTargetingSnapshot,
495
+ type TargetingEvalContext,
496
+ type TargetingSnapshot,
497
+ } from "./lib/flags.js";
498
+ export {
499
+ FlagRegistry,
500
+ getFlagRegistry,
501
+ resetFlagRegistry,
502
+ setFlagRegistry,
503
+ } from "./lib/flags-registry.js";
461
504
  export { countRecentSends, isFrequencyCapped } from "./lib/frequency-cap.js";
462
505
  export { addrSpecOf, hostOfFromAddress } from "./lib/from-address.js";
463
506
  export { FunnelRegistry } from "./lib/funnel-registry.js";
507
+ // --- Base-currency FX lens (optional; docs/groups.md §Base-currency lens) ---
508
+ export {
509
+ createFrankfurterFxProvider,
510
+ createFxLens,
511
+ createStaticFxProvider,
512
+ type FxLens,
513
+ type FxRatesToBase,
514
+ fxProviderFromEnv,
515
+ parseFxRatesEnv,
516
+ } from "./lib/fx.js";
517
+ export {
518
+ computeGlobalControlReadout,
519
+ GLOBAL_CONTROL_SCAN_CEILING,
520
+ type GlobalControlReadout,
521
+ } from "./lib/global-control-readout.js";
464
522
  export { hatchet } from "./lib/hatchet.js";
465
523
  export {
466
524
  globalControlPercent,
@@ -488,6 +546,15 @@ export {
488
546
  type IngestResult,
489
547
  ingestEvent,
490
548
  } from "./lib/ingestion.js";
549
+ // --- Reconciled journey-lift helper (impact experiments D4.1) — the ONE
550
+ // implementation of the causal cohort math, shared by /lift (2a), /impact
551
+ // (2b), and the impact digest (3b) ---
552
+ export {
553
+ computeJourneyLift,
554
+ computeLiftValues,
555
+ type JourneyLiftResult,
556
+ type LiftCohort,
557
+ } from "./lib/journey-lift.js";
491
558
  // --- Leader lease (connector-runtime singleton election) ---
492
559
  export {
493
560
  acquireLeaderLease,
@@ -534,6 +601,10 @@ export {
534
601
  // --- Outbound webhooks: emit spine (Section 1.4) ---
535
602
  export {
536
603
  emitOutbound,
604
+ type ImpactDigestEntry,
605
+ type ImpactDigestLiftEntry,
606
+ type ImpactDigestShippedEntry,
607
+ type ImpactVersionCohort,
537
608
  OUTBOUND_EVENTS,
538
609
  type OutboundEventName,
539
610
  type OutboundPayloads,
@@ -785,6 +856,7 @@ export {
785
856
  // --- Integration presets (Section 2.3/2.4) ---
786
857
  export {
787
858
  clerkSource,
859
+ intercomSource,
788
860
  PRESET_SOURCES,
789
861
  type PresetId,
790
862
  presetsFromEnv,
@@ -821,6 +893,13 @@ export {
821
893
  deliverWebhookTask,
822
894
  reapDueWebhookDeliveriesTask,
823
895
  } from "./workflows/deliver-webhook.js";
896
+ export {
897
+ buildImpactDigest,
898
+ detectLiftCrossings,
899
+ detectShippedVersions,
900
+ type ImpactDigestInput,
901
+ impactDigestTask,
902
+ } from "./workflows/impact-digest.js";
824
903
  export { importContactsTask } from "./workflows/import-contacts.js";
825
904
  export {
826
905
  importSuppressionsTask,
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Environment-free journey authoring surface.
3
+ *
4
+ * Journey files should import from this entry point so deterministic tests can
5
+ * load the original module without validating production database or Hatchet
6
+ * credentials. Importing the main `@hogsend/engine` entry in an API/worker
7
+ * process installs the production Hatchet task binding before tasks are read.
8
+ */
9
+ export * from "@hogsend/core";
10
+ export {
11
+ type SendConnectorActionArgs,
12
+ sendConnectorAction,
13
+ } from "../lib/connector-actions.js";
14
+ export {
15
+ type SendEmailOptions,
16
+ type SendEmailResult,
17
+ sendEmail,
18
+ } from "../lib/email.js";
19
+ export {
20
+ type SendFeedItemOptions,
21
+ type SendFeedItemResult,
22
+ sendFeedItem,
23
+ } from "../lib/feed.js";
24
+ export {
25
+ type SendSmsOptions,
26
+ type SendSmsResult,
27
+ sendSms,
28
+ } from "../lib/sms.js";
29
+ export {
30
+ type DefinedJourney,
31
+ defineJourney,
32
+ } from "./define-journey.js";
@@ -6,19 +6,19 @@ import type {
6
6
  JourneyMetaInput,
7
7
  JourneyRunFn,
8
8
  } from "@hogsend/core/types";
9
- import { hatchet } from "../lib/hatchet.js";
10
9
  import {
11
- JOURNEY_EXECUTION_TIMEOUT,
12
- JOURNEY_SCHEDULE_TIMEOUT,
13
- } from "./constants.js";
14
- import {
15
- type EventPayloadInput,
16
- executeJourneyRun,
17
- } from "./execute-journey-run.js";
10
+ createJourneyTask,
11
+ hasJourneyTaskFactory,
12
+ type JourneyTask,
13
+ } from "./journey-task-factory.js";
14
+ import { computeJourneyVersionHash } from "./journey-version.js";
18
15
 
19
16
  export interface DefinedJourney {
20
17
  meta: JourneyMeta;
21
- task: ReturnType<typeof hatchet.durableTask>;
18
+ /** Original author function. Testing harnesses execute this directly. */
19
+ run: JourneyRunFn;
20
+ /** Production Hatchet task, materialized eagerly by the runtime or lazily on access. */
21
+ task: JourneyTask;
22
22
  /**
23
23
  * The journey's `run` function serialized via `Function.prototype.toString()`,
24
24
  * captured at definition time. This is the substrate the Studio journey-graph
@@ -126,7 +126,7 @@ export function defineJourney(options: {
126
126
  const source = captureCallSite();
127
127
  const { trigger, exitOn, ...rest } = options.meta;
128
128
  const triggerWhere = normalizeWhere(trigger.where);
129
- const meta: JourneyMeta = {
129
+ const normalized: JourneyMeta = {
130
130
  ...rest,
131
131
  trigger: {
132
132
  event: trigger.event,
@@ -144,36 +144,41 @@ export function defineJourney(options: {
144
144
  }
145
145
  : {}),
146
146
  };
147
+ // Impact experiments (Decision A): attach the engine-computed content
148
+ // fingerprint AFTER normalization, so `where` builder fns are already
149
+ // resolved POJOs (the hash input is canonical data, never a function).
150
+ // NEVER authored: the spread overwrites any input value (JourneyMetaInput
151
+ // omits versionHash; JS callers are overridden here). Both the eager task
152
+ // path and the lazy authoring-subpath getter below close over this same
153
+ // meta — executeJourneyRun sees the hash with zero further plumbing.
154
+ const meta: JourneyMeta = {
155
+ ...normalized,
156
+ versionHash: computeJourneyVersionHash({
157
+ meta: normalized,
158
+ body: runSource,
159
+ }),
160
+ };
161
+
162
+ const definition = { meta, run: options.run, runSource, source };
147
163
 
148
- const task = hatchet.durableTask({
149
- name: `journey-${meta.id}`,
150
- onEvents: [meta.trigger.event],
151
- executionTimeout: JOURNEY_EXECUTION_TIMEOUT,
152
- // retries STAYS 0 — deliberately. A retry replays `run()` from the top, and
153
- // the tracked mailer / connector machinery is "missed > doubled": a `queued`
154
- // row is RE-DRIVEN and a failed send NULLs its idempotency key (tracked.ts
155
- // ~150-176, 496-514). That is safe only while nothing re-invokes a run whose
156
- // `provider.send()` already delivered but whose durable status flip didn't
157
- // commit — turning retries on would re-deliver that email/connector message
158
- // (a DUPLICATE). Enabling retries requires making sends provider-idempotent
159
- // first (Resend/Postmark `Idempotency-Key`); tracked as a follow-up.
160
- retries: 0,
161
- // `scheduleTimeout` widens the queue-wait ceiling (SDK default ~5m) so a
162
- // durable-wait RESUME re-queued during a redeploy's slot saturation reclaims
163
- // a slot instead of being cancelled (which strands the enrollment). Unlike
164
- // retries this adds NO replay — it is pure head-room, so it is safe on its own.
165
- scheduleTimeout: JOURNEY_SCHEDULE_TIMEOUT,
166
- // The full enrollment + run lifecycle lives in `executeJourneyRun`, shared
167
- // verbatim with the blueprint interpreter task (spec §6) — code journeys
168
- // and blueprints execute through the IDENTICAL machinery.
169
- fn: async (input: EventPayloadInput, hatchetCtx) =>
170
- executeJourneyRun({
171
- meta,
172
- run: options.run,
173
- input,
174
- hatchetCtx,
175
- }),
176
- });
164
+ // Main-engine imports install the production task factory before callers can
165
+ // invoke defineJourney, preserving the existing eager task behavior. The
166
+ // environment-free authoring subpath intentionally leaves it uninstalled;
167
+ // its task getter remains dormant in unit tests and materializes after the
168
+ // production runtime is loaded by a worker.
169
+ if (hasJourneyTaskFactory()) {
170
+ return {
171
+ ...definition,
172
+ task: createJourneyTask(meta, options.run),
173
+ };
174
+ }
177
175
 
178
- return { meta, task, runSource, source };
176
+ let task: JourneyTask | undefined;
177
+ return Object.defineProperty(definition, "task", {
178
+ enumerable: true,
179
+ get: () => {
180
+ task ??= createJourneyTask(meta, options.run);
181
+ return task;
182
+ },
183
+ }) as DefinedJourney;
179
184
  }
@@ -1,10 +1,6 @@
1
1
  import type { Conditions } from "@hatchet-dev/typescript-sdk/v1/index.js";
2
2
  import type { JsonValue } from "@hatchet-dev/typescript-sdk/v1/types.js";
3
- import {
4
- type DurationObject,
5
- durationToMs,
6
- evaluatePropertyConditions,
7
- } from "@hogsend/core";
3
+ import { type DurationObject, durationToMs } from "@hogsend/core";
8
4
  import type {
9
5
  JourneyMeta,
10
6
  JourneyRunFn,
@@ -24,6 +20,7 @@ import {
24
20
  checkEmailPreferences,
25
21
  checkEntryLimit,
26
22
  } from "../lib/enrollment-guards.js";
23
+ import { evaluateEnrollmentPolicy } from "../lib/enrollment-policy.js";
27
24
  import { hatchet } from "../lib/hatchet.js";
28
25
  import { isHeldOut } from "../lib/holdout.js";
29
26
  import { ingestEvent } from "../lib/ingestion.js";
@@ -40,6 +37,7 @@ import {
40
37
  } from "./journey-boundary.js";
41
38
  import { createJourneyContext, TERMINAL_STATUSES } from "./journey-context.js";
42
39
  import { logTransition } from "./journey-log.js";
40
+ import { stripRecordNamespaces } from "./record-once.js";
43
41
  import { getJourneyRegistrySingleton } from "./registry-singleton.js";
44
42
 
45
43
  const logger = createLogger(process.env.LOG_LEVEL);
@@ -134,6 +132,15 @@ export async function insertEnrollment(opts: {
134
132
  * lock-free (the default).
135
133
  */
136
134
  serializeWithGraphLock?: boolean;
135
+ /**
136
+ * Content fingerprint + label of the definition this enrollment enters
137
+ * under (meta.versionHash / meta.version). Stamped once here; never
138
+ * updated — no UPDATE path in the engine ever touches the version
139
+ * columns. Optional for API back-compat (dogfood tests call this
140
+ * directly); executeJourneyRun always passes them.
141
+ */
142
+ journeyVersionHash?: string | null;
143
+ journeyVersionLabel?: string | null;
137
144
  }): Promise<JourneyStateRow | undefined> {
138
145
  const values = {
139
146
  userId: opts.userId,
@@ -143,6 +150,8 @@ export async function insertEnrollment(opts: {
143
150
  status: "active" as const,
144
151
  context: opts.context,
145
152
  hatchetRunId: opts.hatchetRunId,
153
+ journeyVersionHash: opts.journeyVersionHash ?? null,
154
+ journeyVersionLabel: opts.journeyVersionLabel ?? null,
146
155
  };
147
156
  const onConflict = {
148
157
  target: [journeyStates.userId, journeyStates.journeyId],
@@ -266,6 +275,7 @@ export async function executeJourneyRun(
266
275
  // subscription via `ctx.guard.isSubscribed()` after every wait, so
267
276
  // bypassing the entry-time preference gate never emails an unsubscriber.)
268
277
  if (!state) {
278
+ // Preserve the cheap first gate: disabled definitions never touch the DB.
269
279
  if (!meta.enabled) {
270
280
  return { status: "skipped", reason: "journey_disabled" };
271
281
  }
@@ -273,19 +283,15 @@ export async function executeJourneyRun(
273
283
  const configOverride = await db.query.journeyConfigs.findFirst({
274
284
  where: eq(journeyConfigs.journeyId, meta.id),
275
285
  });
276
- if (configOverride && !configOverride.enabled) {
277
- return { status: "skipped", reason: "journey_disabled_by_admin" };
278
- }
279
-
280
- if (meta.trigger.where?.length) {
281
- if (
282
- !evaluatePropertyConditions({
283
- conditions: meta.trigger.where,
284
- properties,
285
- })
286
- ) {
287
- return { status: "skipped", reason: "trigger_conditions_not_met" };
288
- }
286
+ const basePolicy = evaluateEnrollmentPolicy({
287
+ journey: meta,
288
+ properties,
289
+ facts: {
290
+ ...(configOverride ? { adminEnabled: configOverride.enabled } : {}),
291
+ },
292
+ });
293
+ if (!basePolicy.allowed) {
294
+ return { status: "skipped", reason: basePolicy.reason };
289
295
  }
290
296
 
291
297
  const entryAllowed = await checkEntryLimit({
@@ -293,16 +299,23 @@ export async function executeJourneyRun(
293
299
  journey: meta,
294
300
  userId,
295
301
  });
296
- if (!entryAllowed.allowed) {
297
- return {
298
- status: "skipped",
299
- reason: entryAllowed.reason ?? "entry_limit",
300
- };
302
+ const entryPolicy = evaluateEnrollmentPolicy({
303
+ journey: meta,
304
+ properties,
305
+ facts: { entry: entryAllowed },
306
+ });
307
+ if (!entryPolicy.allowed) {
308
+ return { status: "skipped", reason: entryPolicy.reason };
301
309
  }
302
310
 
303
311
  const prefs = await checkEmailPreferences({ db, userId });
304
- if (prefs.unsubscribed) {
305
- return { status: "skipped", reason: "user_unsubscribed" };
312
+ const preferencePolicy = evaluateEnrollmentPolicy({
313
+ journey: meta,
314
+ properties,
315
+ facts: { unsubscribed: prefs.unsubscribed },
316
+ });
317
+ if (!preferencePolicy.allowed) {
318
+ return { status: "skipped", reason: preferencePolicy.reason };
306
319
  }
307
320
 
308
321
  // HOLDOUT DIVERSION (impact plan §4.1) — deliberately LAST in the guard
@@ -320,7 +333,12 @@ export async function executeJourneyRun(
320
333
  percent: meta.holdout.percent,
321
334
  salt: meta.holdout.salt,
322
335
  });
323
- if (diverted) {
336
+ const holdoutPolicy = evaluateEnrollmentPolicy({
337
+ journey: meta,
338
+ properties,
339
+ facts: { heldOut: diverted },
340
+ });
341
+ if (!holdoutPolicy.allowed) {
324
342
  const priorHoldout = await db.query.journeyStates.findFirst({
325
343
  where: and(
326
344
  eq(journeyStates.userId, userId),
@@ -338,7 +356,17 @@ export async function executeJourneyRun(
338
356
  journeyId: meta.id,
339
357
  currentNodeId: "held-out",
340
358
  status: "held_out",
341
- context: properties,
359
+ // Reserved record-once namespaces are STRIPPED from event
360
+ // properties before seeding (injection fix): a publishable-key
361
+ // event must never pre-fill __once__/__digest__/__throttle__/
362
+ // __variants__.
363
+ context: stripRecordNamespaces(properties),
364
+ // Stamped so the per-version lift readout can match control
365
+ // by SAME hash (D4): held_out rows are once-ever per
366
+ // (user, journey), so this diversion-era stamp anchors that
367
+ // version's control cohort forever.
368
+ journeyVersionHash: meta.versionHash ?? null,
369
+ journeyVersionLabel: meta.version ?? null,
342
370
  exitedAt: heldOutAt,
343
371
  })
344
372
  .returning({ id: journeyStates.id });
@@ -392,7 +420,7 @@ export async function executeJourneyRun(
392
420
  }).catch(logger.warn);
393
421
  }
394
422
  }
395
- return { status: "skipped", reason: "held_out" };
423
+ return { status: "skipped", reason: holdoutPolicy.reason };
396
424
  }
397
425
  }
398
426
 
@@ -403,8 +431,13 @@ export async function executeJourneyRun(
403
431
  inArray(journeyStates.status, ["active", "waiting"]),
404
432
  ),
405
433
  });
406
- if (activeState) {
407
- return { status: "skipped", reason: "already_active" };
434
+ const activePolicy = evaluateEnrollmentPolicy({
435
+ journey: meta,
436
+ properties,
437
+ facts: { alreadyActive: Boolean(activeState) },
438
+ });
439
+ if (!activePolicy.allowed) {
440
+ return { status: "skipped", reason: activePolicy.reason };
408
441
  }
409
442
 
410
443
  // A successful insert always returns exactly one row, so undefined here
@@ -416,10 +449,15 @@ export async function executeJourneyRun(
416
449
  userId,
417
450
  userEmail,
418
451
  journeyId: meta.id,
452
+ // Same strip as the held_out site. `extraContext` is engine-supplied
453
+ // (e.g. the blueprint interpreter's __blueprintVersion pin) and is
454
+ // deliberately NOT filtered.
419
455
  context: options.extraContext
420
- ? { ...properties, ...options.extraContext }
421
- : properties,
456
+ ? { ...stripRecordNamespaces(properties), ...options.extraContext }
457
+ : stripRecordNamespaces(properties),
422
458
  hatchetRunId: workflowRunId,
459
+ journeyVersionHash: meta.versionHash ?? null,
460
+ journeyVersionLabel: meta.version ?? null,
423
461
  serializeWithGraphLock: options.serializeEnrollment,
424
462
  });
425
463
  if (!state) {
@@ -547,6 +585,9 @@ export async function executeJourneyRun(
547
585
  seenKeys: new Set<string>(),
548
586
  seenRecordLabels: new Set<string>(),
549
587
  memoize: createMemoize(hatchetCtx),
588
+ // Keep production behavior on the real wall clock while allowing scoped
589
+ // test boundaries to substitute a deterministic virtual clock.
590
+ now: () => new Date(),
550
591
  journeyId: meta.id,
551
592
  // `meta.suppress` is a required DurationObject, but a `{}` / zero
552
593
  // duration must yield 0 (disabled); `durationToMs` maps both to 0.
@@ -15,6 +15,72 @@ export interface HatchetMemoCtx {
15
15
  supportsEviction?: boolean;
16
16
  }
17
17
 
18
+ export interface JourneyEmailEffect {
19
+ to: string;
20
+ userId: string;
21
+ template: string;
22
+ subject?: string;
23
+ props: Record<string, unknown>;
24
+ category: string;
25
+ journeyName?: string;
26
+ journeyStateId?: string;
27
+ idempotencyKey?: string;
28
+ }
29
+
30
+ export interface JourneySmsEffect {
31
+ to: string;
32
+ userId: string;
33
+ template: string;
34
+ props: Record<string, unknown>;
35
+ category: string;
36
+ journeyName?: string;
37
+ journeyStateId?: string;
38
+ idempotencyKey?: string;
39
+ }
40
+
41
+ export interface JourneyConnectorEffect {
42
+ connectorId: string;
43
+ action: string;
44
+ args?: unknown;
45
+ idempotencyKey?: string;
46
+ }
47
+
48
+ export interface JourneyFeedEffect {
49
+ recipient: { userId?: string; email?: string; anonymousId?: string };
50
+ type: string;
51
+ title?: string;
52
+ body?: string;
53
+ blocks?: unknown[];
54
+ actionUrl?: string;
55
+ metadata?: Record<string, unknown>;
56
+ category: string;
57
+ templateKey?: string;
58
+ journeyStateId?: string;
59
+ idempotencyKey?: string;
60
+ }
61
+
62
+ /** Scoped service replacements, primarily for deterministic journey tests. */
63
+ export interface JourneyServiceOverrides {
64
+ email?: (
65
+ effect: JourneyEmailEffect,
66
+ ) => Promise<{ emailSendId: string; sentAt: string }>;
67
+ sms?: (effect: JourneySmsEffect) => Promise<{
68
+ smsSendId: string;
69
+ status: "sent" | "suppressed" | "unsubscribed" | "no_consent" | "skipped";
70
+ reason?: string;
71
+ sentAt?: string;
72
+ }>;
73
+ connector?: (effect: JourneyConnectorEffect) => Promise<unknown>;
74
+ /** Required with `connector`; validates an action before scoped capture. */
75
+ connectorActionExists?: (connectorId: string, action: string) => boolean;
76
+ feed?: (effect: JourneyFeedEffect) => Promise<{
77
+ feedItemId: string | null;
78
+ recipientKey: string | null;
79
+ suppressed: boolean;
80
+ createdAt: string | null;
81
+ }>;
82
+ }
83
+
18
84
  /**
19
85
  * Per-enrollment, per-run state threaded through `AsyncLocalStorage` so the
20
86
  * standalone `sendEmail` / `ctx.trigger` side-effect helpers can be made
@@ -91,6 +157,16 @@ export interface JourneyBoundary {
91
157
  * harness contexts) compile unchanged.
92
158
  */
93
159
  category?: string;
160
+ /** Async-scope-local effects used before process singletons or databases. */
161
+ services?: JourneyServiceOverrides;
162
+ /**
163
+ * Scope-local wall clock for synchronous side-effect metadata such as
164
+ * unsubscribe-token expiry. Production supplies the real clock; deterministic
165
+ * harnesses can supply their virtual clock without installing process-global
166
+ * fake timers. Optional so existing non-production boundary fixtures keep the
167
+ * historical real-time fallback.
168
+ */
169
+ now?: () => Date;
94
170
  }
95
171
 
96
172
  const journeyBoundaryAls = new AsyncLocalStorage<JourneyBoundary>();