@hogsend/engine 0.46.0 → 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 (70) 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/readiness.ts +8 -8
  57. package/src/routes/admin/settings.ts +145 -0
  58. package/src/routes/admin/targeting.ts +256 -0
  59. package/src/routes/events/index.ts +11 -0
  60. package/src/routes/flags/index.ts +120 -0
  61. package/src/routes/groups/index.ts +417 -0
  62. package/src/routes/index.ts +23 -1
  63. package/src/testing.ts +25 -0
  64. package/src/webhook-sources/presets/index.ts +5 -1
  65. package/src/webhook-sources/presets/intercom.ts +230 -0
  66. package/src/webhook-sources/presets/segment.ts +56 -4
  67. package/src/worker.ts +3 -0
  68. package/src/workflows/bucket-backfill.ts +1 -14
  69. package/src/workflows/impact-digest.ts +761 -0
  70. package/src/workflows/journey-blueprint-interpreter.ts +18 -1
@@ -0,0 +1,158 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { JourneyMeta } from "@hogsend/core/types";
3
+ import { stableStringify } from "../lib/stable-stringify.js";
4
+
5
+ /**
6
+ * Bump when normalization/hash-input rules change. Forks every hash exactly
7
+ * once on upgrade (a global, labeled refork — honest and self-documenting).
8
+ * FROZEN COMPATIBILITY CONTRACT (replay law) locked by the golden-value
9
+ * tests in journey-version.test.ts.
10
+ */
11
+ const HASH_INPUT_VERSION = "hsv1";
12
+
13
+ type ScanState =
14
+ | "code"
15
+ | "single"
16
+ | "double"
17
+ | "template"
18
+ | "lineComment"
19
+ | "blockComment";
20
+
21
+ /**
22
+ * Deterministic, dependency-free normalization of a Function.prototype
23
+ * .toString() capture, so formatting- and comment-only edits do not fork a
24
+ * version cohort:
25
+ * 1. strip // line and block comments with a string-aware single-pass
26
+ * scanner (states: code | single | double | template | lineComment |
27
+ * blockComment; a \ inside any string state consumes the next char;
28
+ * each stripped comment is replaced by one space),
29
+ * 2. collapse every whitespace run to a single space, trim.
30
+ * KNOWN LIMITS (documented, deterministic): (a) a // inside a regex literal
31
+ * is misread as a comment start and mangles the rest of that line; (b) the
32
+ * scanner exits `template` state at the first backtick, so a nested
33
+ * template or a string/comment inside ${...} is misclassified. In both
34
+ * cases the output is still a pure function of the input, so the hash
35
+ * stays stable — the only cost is fork-detection fidelity on those lines.
36
+ * Never throws; empty input → "".
37
+ */
38
+ export function normalizeRunSource(source: string): string {
39
+ let out = "";
40
+ let state: ScanState = "code";
41
+ for (let i = 0; i < source.length; i++) {
42
+ const ch = source[i] as string;
43
+ const next = source[i + 1];
44
+ switch (state) {
45
+ case "code":
46
+ if (ch === "/" && next === "/") {
47
+ state = "lineComment";
48
+ i++;
49
+ } else if (ch === "/" && next === "*") {
50
+ state = "blockComment";
51
+ i++;
52
+ } else {
53
+ out += ch;
54
+ if (ch === "'") state = "single";
55
+ else if (ch === '"') state = "double";
56
+ else if (ch === "`") state = "template";
57
+ }
58
+ break;
59
+ case "single":
60
+ case "double":
61
+ case "template":
62
+ out += ch;
63
+ if (ch === "\\") {
64
+ if (next !== undefined) {
65
+ out += next;
66
+ i++;
67
+ }
68
+ } else if (
69
+ (state === "single" && ch === "'") ||
70
+ (state === "double" && ch === '"') ||
71
+ (state === "template" && ch === "`")
72
+ ) {
73
+ state = "code";
74
+ }
75
+ break;
76
+ case "lineComment":
77
+ if (ch === "\n") {
78
+ out += " ";
79
+ state = "code";
80
+ }
81
+ break;
82
+ case "blockComment":
83
+ if (ch === "*" && next === "/") {
84
+ out += " ";
85
+ state = "code";
86
+ i++;
87
+ }
88
+ break;
89
+ }
90
+ }
91
+ return out.replace(/\s+/g, " ").trim();
92
+ }
93
+
94
+ /**
95
+ * Content fingerprint of one journey version: sha256, first 12 hex chars
96
+ * (48 bits — per-journey version counts are tiny; collision negligible).
97
+ * Input = HASH_INPUT_VERSION + "\n" + normalizeRunSource(body ?? "") +
98
+ * "\n" + stableStringify(hashable meta).
99
+ *
100
+ * Hashable meta = the meta MINUS `enabled` (toggling — including the
101
+ * journey_configs admin override — is not a content change), `version`
102
+ * (display label), `versionHash` (self), `name`, `description` (display
103
+ * only — display fields don't fork cohorts; this exclusion list is FROZEN
104
+ * at first release, since changing it later reforks every journey once).
105
+ * Everything else is included BY DEFAULT via rest-destructuring — id,
106
+ * trigger, entryLimit, entryPeriod, exitOn, category, suppress, holdout,
107
+ * goal, sourceBucketId, reactionKind, dwellSchedule, and any FUTURE meta
108
+ * field — because missing a real behavior change is worse than a spurious
109
+ * fork.
110
+ *
111
+ * For blueprints, `body` is stableStringify(row.graph), which ALSO passes
112
+ * through normalizeRunSource. Safe: stableStringify emits no whitespace or
113
+ * comments outside JSON strings, and // inside double-quoted string values
114
+ * (URLs in graph node config) is protected by the string-aware scanner,
115
+ * including \" escapes.
116
+ *
117
+ * ACCEPTED HASH CHURN ACROSS BUILD MODES: runSource is captured from the
118
+ * RUNNING artifact (define-journey.ts) — tsx dev output differs from the
119
+ * consumer tsup bundle, and esbuild identifier aliasing / toolchain-bump
120
+ * emit drift can fork a prod cohort once with zero content change.
121
+ * Accepted: forks are append-only cohort noise; labels give continuity.
122
+ * All readout/digest consumers MUST treat a new hash as "possible new
123
+ * version", never proof of change.
124
+ *
125
+ * TEMPLATE EDITS ARE NOT IN THE HASH: email template components (the
126
+ * consumer's src/emails/*.tsx) are referenced by registry KEY, and that
127
+ * key is all the run source carries — rewriting template copy forks NO
128
+ * cohort. Documented operator practice: bump `meta.version` (the display
129
+ * label) when you rework a template; the impact digest reports a label
130
+ * change as a first-class shipped signal (change: "new_label"). The real
131
+ * fix — folding a rendered-template-registry hash into the body input —
132
+ * is an explicit out-of-scope follow-up.
133
+ *
134
+ * Determinism: `where` builder fns are resolved ONCE into POJOs by
135
+ * normalizeWhere at defineJourney time, so the hashed meta is canonical
136
+ * data, never a function; stableStringify sorts keys and drops undefined,
137
+ * so key order and optional-field spreading cannot churn the hash. NO RNG,
138
+ * NO clock (the replay law).
139
+ */
140
+ export function computeJourneyVersionHash(opts: {
141
+ meta: JourneyMeta;
142
+ /** runSource for code journeys; stableStringify(graph) for blueprints. */
143
+ body?: string;
144
+ }): string {
145
+ const {
146
+ enabled: _e,
147
+ version: _v,
148
+ versionHash: _h,
149
+ name: _n,
150
+ description: _d,
151
+ ...hashable
152
+ } = opts.meta;
153
+ const body = opts.body ? normalizeRunSource(opts.body) : "";
154
+ return createHash("sha256")
155
+ .update(`${HASH_INPUT_VERSION}\n${body}\n${stableStringify(hashable)}`)
156
+ .digest("hex")
157
+ .slice(0, 12);
158
+ }
@@ -5,15 +5,20 @@ import { eq, sql } from "drizzle-orm";
5
5
  * under. A closed union — the ONLY values reachable at the SQL path, so the
6
6
  * token can be interpolated into the jsonb path (see {@link recordOnce}) while
7
7
  * `key`/value stay bound parameters. */
8
- export type RecordNamespace = "__once__" | "__digest__" | "__throttle__";
8
+ export type RecordNamespace =
9
+ | "__once__"
10
+ | "__digest__"
11
+ | "__throttle__"
12
+ | "__variants__";
9
13
 
10
- // Closed-union → validated path token. NOT user input: only these three literals
14
+ // Closed-union → validated path token. NOT user input: only these four literals
11
15
  // reach the interpolated jsonb path below, so it is injection-safe. `key` and the
12
16
  // JSON-stringified value are ALWAYS bound parameters regardless.
13
17
  const NAMESPACE_TOKEN: Record<RecordNamespace, string> = {
14
18
  __once__: "__once__",
15
19
  __digest__: "__digest__",
16
20
  __throttle__: "__throttle__",
21
+ __variants__: "__variants__",
17
22
  };
18
23
 
19
24
  /** Extract the `(namespace)` sub-bag from an already-fetched context, `{}` when
@@ -108,3 +113,24 @@ export async function recordOnce<T>(opts: {
108
113
  }
109
114
  return value;
110
115
  }
116
+
117
+ /**
118
+ * Drop ALL reserved record-once namespace keys from an event-properties bag.
119
+ * Enrollment seeds `journey_states.context` from trigger-event properties
120
+ * (execute-journey-run.ts — BOTH the fresh-entry and held_out inserts);
121
+ * without this strip a publishable-key browser event carrying e.g.
122
+ * `__variants__` could pre-fill a reserved bag — choosing its own ctx.variant
123
+ * arm AND injecting arbitrary strings into the impact readout's GROUP BY
124
+ * dimension. One filter protects every bag at once. Engine-supplied
125
+ * `extraContext` (e.g. `__blueprintVersion`) is deliberately NOT passed
126
+ * through this filter.
127
+ */
128
+ export function stripRecordNamespaces<T>(
129
+ properties: Record<string, T>,
130
+ ): Record<string, T> {
131
+ return Object.fromEntries(
132
+ Object.entries(properties).filter(
133
+ ([key]) => !Object.hasOwn(NAMESPACE_TOKEN, key),
134
+ ),
135
+ ) as Record<string, T>;
136
+ }
@@ -0,0 +1,36 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import {
4
+ type JourneyBoundary,
5
+ runWithJourneyBoundary,
6
+ } from "../journeys/journey-boundary.js";
7
+ import { sendConnectorAction } from "./connector-actions.js";
8
+
9
+ test("a scoped connector override requires registration validation before capture", async () => {
10
+ let captures = 0;
11
+ const boundary: JourneyBoundary = {
12
+ stateId: "test-state",
13
+ runAnchor: "test-run",
14
+ currentLabel: undefined,
15
+ seenKeys: new Set(),
16
+ seenRecordLabels: new Set(),
17
+ memoize: async (_deps, fn) => fn(),
18
+ services: {
19
+ connector: async () => {
20
+ captures += 1;
21
+ return { delivered: true };
22
+ },
23
+ },
24
+ };
25
+
26
+ await assert.rejects(
27
+ runWithJourneyBoundary(boundary, () =>
28
+ sendConnectorAction({
29
+ connectorId: "discord",
30
+ action: "unregistered",
31
+ }),
32
+ ),
33
+ /requires connectorActionExists/,
34
+ );
35
+ assert.equal(captures, 0);
36
+ });
@@ -6,7 +6,6 @@ import type {
6
6
  DefinedConnectorAction,
7
7
  ResolvedActionContact,
8
8
  } from "../connectors/define-action.js";
9
- import { env } from "../env.js";
10
9
  import {
11
10
  deriveJourneyKey,
12
11
  getJourneyBoundary,
@@ -15,9 +14,13 @@ import {
15
14
  import { getListRegistry } from "../lists/registry-singleton.js";
16
15
  import { getDb } from "./db.js";
17
16
  import { createLogger } from "./logger.js";
18
- import { readRecipientPreferences } from "./preferences.js";
17
+ import { readRecipientPreferences } from "./recipient-preferences.js";
19
18
 
20
- const logger = createLogger(env.LOG_LEVEL);
19
+ // This module is part of the side-effect-free journey-authoring surface used by
20
+ // `@hogsend/testing`. Reading the raw optional value keeps importing a journey
21
+ // from validating the complete production environment; the full container still
22
+ // validates env at boot.
23
+ const logger = createLogger(process.env.LOG_LEVEL);
21
24
 
22
25
  /**
23
26
  * Matches the canonical UUID form of `contacts.id` (8-4-4-4-12 hex). Gates the
@@ -240,6 +243,42 @@ export interface SendConnectorActionArgs {
240
243
  export async function sendConnectorAction(
241
244
  input: SendConnectorActionArgs,
242
245
  ): Promise<unknown> {
246
+ const boundary = getJourneyBoundary();
247
+ const override = boundary?.services?.connector;
248
+ if (boundary && override) {
249
+ const actionExists = boundary.services?.connectorActionExists;
250
+ if (!actionExists) {
251
+ throw new Error(
252
+ "Scoped connector override requires connectorActionExists validation",
253
+ );
254
+ }
255
+ if (!actionExists(input.connectorId, input.action)) {
256
+ throw new Error(
257
+ `no connector action "${input.connectorId}:${input.action}" is registered ` +
258
+ "(pass it via createJourneyTest({ connectorActions }))",
259
+ );
260
+ }
261
+ const site =
262
+ input.idempotencyLabel ??
263
+ boundary.currentLabel ??
264
+ `${input.connectorId}:${input.action}`;
265
+ const scopedKey = deriveJourneyKey({
266
+ kind: "connector",
267
+ anchor: boundary.runAnchor,
268
+ site,
269
+ discriminant: `${input.connectorId}:${input.action}`,
270
+ });
271
+ registerKey(boundary, scopedKey);
272
+ return boundary.memoize([scopedKey], () =>
273
+ override({
274
+ connectorId: input.connectorId,
275
+ action: input.action,
276
+ ...(input.args !== undefined ? { args: input.args } : {}),
277
+ idempotencyKey: scopedKey,
278
+ }),
279
+ );
280
+ }
281
+
243
282
  const action = getConnectorActionRegistry().get(
244
283
  input.connectorId,
245
284
  input.action,
@@ -300,7 +339,6 @@ export async function sendConnectorAction(
300
339
 
301
340
  // Outside a journey run (an admin/manual send) there is no replay to defend
302
341
  // against and no boundary to key from — gate then run the action directly.
303
- const boundary = getJourneyBoundary();
304
342
  if (!boundary) return gate(doRun);
305
343
 
306
344
  // The replay-stable, branch-derived key shared by BOTH defense layers. `site`
@@ -7,6 +7,7 @@ import {
7
7
  deals,
8
8
  emailPreferences,
9
9
  emailSends,
10
+ groupMemberships,
10
11
  journeyStates,
11
12
  userEvents,
12
13
  } from "@hogsend/db";
@@ -963,6 +964,14 @@ async function mergeContacts(
963
964
  .set({ contactId: survivor.id })
964
965
  .where(eq(crmLinks.contactId, loser.id));
965
966
 
967
+ // (vi-c) group_memberships FOLD: another contact_id uuid FK the key
968
+ // rewrites never touch. The loser is SOFT-deleted, so `onDelete: cascade`
969
+ // never fires — without this the loser's memberships are stranded on a dead
970
+ // row (the survivor's drawer shows "no groups", and the group's member
971
+ // count/list disagree). uq(group_id, contact_id) forbids a blind rewrite
972
+ // when BOTH already belong to the same group, so fold-then-rewrite.
973
+ await foldGroupMemberships(tx, survivor.id, loser.id);
974
+
966
975
  // (ix) RECORD aliases for each loser key → survivor.
967
976
  await recordMergeAliases(tx, survivor.id, loser);
968
977
  }
@@ -1279,6 +1288,46 @@ async function foldBucketMemberships(
1279
1288
  .where(inArray(bucketMemberships.userId, loserKeys));
1280
1289
  }
1281
1290
 
1291
+ /**
1292
+ * group_memberships fold (vi-c). Unlike buckets this join is keyed on the uuid
1293
+ * `contact_id`, and it carries no lifecycle (no status/dwell/left_at) — just
1294
+ * `role` + `joined_at` — so the fold is a plain dedupe-then-rewrite:
1295
+ * 1. DROP the loser's membership in any group the survivor ALREADY belongs to
1296
+ * (uq(group_id, contact_id) forbids two rows for the same (group, contact);
1297
+ * the survivor's row wins, keeping its authoritative role/joinedAt).
1298
+ * 2. Re-point the rest onto the survivor.
1299
+ * Hard-delete (not soft-leave) matches how a membership is removed everywhere
1300
+ * else in the group service.
1301
+ */
1302
+ async function foldGroupMemberships(
1303
+ tx: Tx,
1304
+ survivorId: string,
1305
+ loserId: string,
1306
+ ): Promise<void> {
1307
+ const survivorGroups = await tx
1308
+ .select({ groupId: groupMemberships.groupId })
1309
+ .from(groupMemberships)
1310
+ .where(eq(groupMemberships.contactId, survivorId));
1311
+
1312
+ const occupied = survivorGroups.map((g) => g.groupId);
1313
+
1314
+ if (occupied.length > 0) {
1315
+ await tx
1316
+ .delete(groupMemberships)
1317
+ .where(
1318
+ and(
1319
+ eq(groupMemberships.contactId, loserId),
1320
+ inArray(groupMemberships.groupId, occupied),
1321
+ ),
1322
+ );
1323
+ }
1324
+
1325
+ await tx
1326
+ .update(groupMemberships)
1327
+ .set({ contactId: survivorId, updatedAt: new Date() })
1328
+ .where(eq(groupMemberships.contactId, loserId));
1329
+ }
1330
+
1282
1331
  /**
1283
1332
  * email_preferences FOLD (risk 6 — suppression/unsubscribe must NEVER be lost).
1284
1333
  * For each of the loser's pref rows, fold it into whatever currently sits at
@@ -0,0 +1,33 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { defineConversion } from "@hogsend/core";
4
+ import { ConversionRegistry } from "./conversions.js";
5
+
6
+ const signup = defineConversion({
7
+ id: "signup-completed",
8
+ name: "Signup completed",
9
+ trigger: { event: "signup.completed" },
10
+ });
11
+ // A wildcard definition (trigger.event "*") lands in the registry's separate
12
+ // `wildcard` list — `has()` must see it via `all`, not `byEvent`.
13
+ const wildcard = defineConversion({
14
+ id: "any-valued",
15
+ name: "Any valued event",
16
+ trigger: { event: "*" },
17
+ });
18
+
19
+ test("has() finds a definition registered under a named trigger", () => {
20
+ const registry = new ConversionRegistry([signup]);
21
+ assert.equal(registry.has("signup-completed"), true);
22
+ });
23
+
24
+ test("has() finds a WILDCARD definition (trigger.event '*')", () => {
25
+ const registry = new ConversionRegistry([wildcard]);
26
+ assert.equal(registry.has("any-valued"), true);
27
+ });
28
+
29
+ test("has() is false for an unknown id and on an empty registry", () => {
30
+ const registry = new ConversionRegistry([signup, wildcard]);
31
+ assert.equal(registry.has("signup-complete"), false); // typo'd id
32
+ assert.equal(new ConversionRegistry().has("signup-completed"), false);
33
+ });
@@ -64,6 +64,14 @@ export class ConversionRegistry {
64
64
  count(): number {
65
65
  return this.all.length;
66
66
  }
67
+
68
+ /**
69
+ * Membership check over ALL definitions (named-trigger + wildcard) by
70
+ * `meta.id` — the container's `meta.goal` boot validation reads this.
71
+ */
72
+ has(id: string): boolean {
73
+ return this.all.some((def) => def.meta.id === id);
74
+ }
67
75
  }
68
76
 
69
77
  const singleton = createOptionalSingleton<ConversionRegistry>();
package/src/lib/email.ts CHANGED
@@ -75,8 +75,6 @@ export interface SendEmailResult {
75
75
  export async function sendEmail(
76
76
  opts: SendEmailOptions,
77
77
  ): Promise<SendEmailResult> {
78
- const service = getEmailService();
79
-
80
78
  // Exactly-once across a durable replay. When inside a journey run, derive a
81
79
  // deterministic, branch-stable key (anchored on the replay-stable
82
80
  // `boundary.runAnchor` = Hatchet run id, NOT the freshly-minted stateId) so a
@@ -109,6 +107,7 @@ export async function sendEmail(
109
107
  secret: process.env.BETTER_AUTH_SECRET,
110
108
  externalId: opts.userId,
111
109
  email: opts.to,
110
+ ...(boundary?.now ? { now: boundary.now() } : {}),
112
111
  });
113
112
  }
114
113
 
@@ -157,6 +156,24 @@ export async function sendEmail(
157
156
  headers,
158
157
  } as unknown as EmailServiceSendOptions;
159
158
 
159
+ const effect = {
160
+ to: opts.to,
161
+ userId: opts.userId,
162
+ template: String(opts.template),
163
+ ...(opts.subject !== undefined ? { subject: opts.subject } : {}),
164
+ props: sendOptions.props as Record<string, unknown>,
165
+ category: boundary?.category ?? "journey",
166
+ ...(opts.journeyName !== undefined
167
+ ? { journeyName: opts.journeyName }
168
+ : {}),
169
+ ...(opts.journeyStateId !== undefined
170
+ ? { journeyStateId: opts.journeyStateId }
171
+ : {}),
172
+ ...(resolvedIdempotencyKey
173
+ ? { idempotencyKey: resolvedIdempotencyKey }
174
+ : {}),
175
+ };
176
+
160
177
  // Layer 1 (fast path): when inside a journey on an eviction-capable engine,
161
178
  // run the provider send through Hatchet's durable `memo` so a replay returns
162
179
  // the recorded `{ emailSendId, sentAt }` WITHOUT re-hitting the provider or
@@ -164,6 +181,10 @@ export async function sendEmail(
164
181
  // eviction is unavailable — Layer 2 (the DB key above) still guarantees
165
182
  // exactly-once. Outside a journey, send directly (no boundary).
166
183
  const doSend = async (): Promise<SendEmailResult> => {
184
+ if (boundary?.services?.email) {
185
+ return boundary.services.email(effect);
186
+ }
187
+ const service = getEmailService();
167
188
  const result = await service.send(sendOptions);
168
189
  return {
169
190
  emailSendId: result.emailSendId,
@@ -0,0 +1,51 @@
1
+ import { evaluatePropertyConditions } from "@hogsend/core";
2
+ import type { JourneyMeta } from "@hogsend/core/types";
3
+
4
+ export interface EnrollmentPolicyFacts {
5
+ /** Omit when there is no persisted admin override. */
6
+ adminEnabled?: boolean;
7
+ entry?: { allowed: boolean; reason?: string };
8
+ unsubscribed?: boolean;
9
+ heldOut?: boolean;
10
+ alreadyActive?: boolean;
11
+ }
12
+
13
+ export type EnrollmentPolicyResult =
14
+ | { allowed: true }
15
+ | { allowed: false; reason: string };
16
+
17
+ /** Pure enrollment guard ordering shared by production and test fixtures. */
18
+ export function evaluateEnrollmentPolicy(opts: {
19
+ journey: JourneyMeta;
20
+ properties: Record<string, unknown>;
21
+ facts?: EnrollmentPolicyFacts;
22
+ }): EnrollmentPolicyResult {
23
+ const { journey, properties, facts = {} } = opts;
24
+ if (!journey.enabled) return { allowed: false, reason: "journey_disabled" };
25
+ if (facts.adminEnabled === false) {
26
+ return { allowed: false, reason: "journey_disabled_by_admin" };
27
+ }
28
+ if (
29
+ journey.trigger.where?.length &&
30
+ !evaluatePropertyConditions({
31
+ conditions: journey.trigger.where,
32
+ properties,
33
+ })
34
+ ) {
35
+ return { allowed: false, reason: "trigger_conditions_not_met" };
36
+ }
37
+ if (facts.entry && !facts.entry.allowed) {
38
+ return {
39
+ allowed: false,
40
+ reason: facts.entry.reason ?? "entry_limit",
41
+ };
42
+ }
43
+ if (facts.unsubscribed) {
44
+ return { allowed: false, reason: "user_unsubscribed" };
45
+ }
46
+ if (facts.heldOut) return { allowed: false, reason: "held_out" };
47
+ if (facts.alreadyActive) {
48
+ return { allowed: false, reason: "already_active" };
49
+ }
50
+ return { allowed: true };
51
+ }
package/src/lib/feed.ts CHANGED
@@ -9,7 +9,7 @@ import { getListRegistry } from "../lists/registry-singleton.js";
9
9
  import { resolveOrCreateContact, resolveRecipient } from "./contacts.js";
10
10
  import { getDb } from "./db.js";
11
11
  import { createLogger } from "./logger.js";
12
- import { readRecipientPreferences } from "./preferences.js";
12
+ import { readRecipientPreferences } from "./recipient-preferences.js";
13
13
  import { getRedis } from "./redis.js";
14
14
 
15
15
  const logger = createLogger(process.env.LOG_LEVEL);
@@ -76,10 +76,63 @@ export interface SendFeedItemResult {
76
76
  export async function sendFeedItem(
77
77
  opts: SendFeedItemOptions,
78
78
  ): Promise<SendFeedItemResult> {
79
- const db = getDb();
80
79
  const { recipient } = opts;
80
+ // Keep the production recipient contract in front of the scoped test
81
+ // override. The normal path eventually enforces this in
82
+ // `resolveOrCreateContact`, but an override deliberately avoids the database;
83
+ // without this pure check a zero-recipient feed item passed in journey tests
84
+ // and failed only in production.
85
+ if (
86
+ !recipient.userId?.trim() &&
87
+ !recipient.email?.trim() &&
88
+ !recipient.anonymousId?.trim()
89
+ ) {
90
+ throw new Error(
91
+ "resolveOrCreateContact requires at least one of userId, email, " +
92
+ "anonymousId, discordId",
93
+ );
94
+ }
81
95
  const category = opts.category ?? IN_APP_LIST_ID;
82
96
 
97
+ const boundary = getJourneyBoundary();
98
+ const override = boundary?.services?.feed;
99
+ if (boundary && override) {
100
+ let overrideKey: string | undefined = opts.idempotencyKey;
101
+ if (!overrideKey) {
102
+ const site = opts.idempotencyLabel ?? boundary.currentLabel ?? opts.type;
103
+ overrideKey = deriveJourneyKey({
104
+ kind: "send",
105
+ anchor: boundary.runAnchor,
106
+ site,
107
+ discriminant: `feed:${opts.type}`,
108
+ });
109
+ registerKey(boundary, overrideKey);
110
+ }
111
+ const runOverride = () =>
112
+ override({
113
+ recipient,
114
+ type: opts.type,
115
+ ...(opts.title !== undefined ? { title: opts.title } : {}),
116
+ ...(opts.body !== undefined ? { body: opts.body } : {}),
117
+ ...(opts.blocks !== undefined ? { blocks: opts.blocks } : {}),
118
+ ...(opts.actionUrl !== undefined ? { actionUrl: opts.actionUrl } : {}),
119
+ ...(opts.metadata !== undefined ? { metadata: opts.metadata } : {}),
120
+ category,
121
+ ...(opts.templateKey !== undefined
122
+ ? { templateKey: opts.templateKey }
123
+ : {}),
124
+ ...(opts.journeyStateId !== undefined
125
+ ? { journeyStateId: opts.journeyStateId }
126
+ : {}),
127
+ ...(overrideKey ? { idempotencyKey: overrideKey } : {}),
128
+ });
129
+ return overrideKey
130
+ ? boundary.memoize([overrideKey], runOverride)
131
+ : runOverride();
132
+ }
133
+
134
+ const db = getDb();
135
+
83
136
  // (1) Resolve recipient → canonical key. Throws on a zero-key recipient (same
84
137
  // contract as `resolveOrCreateContact`). This is a server/journey-side send —
85
138
  // never a browser write — so no `restrictToAnonymous` clamp.
@@ -108,7 +161,6 @@ export async function sendFeedItem(
108
161
  // preference verdict INSIDE the memo closure (step 3) so the skip/allow verdict
109
162
  // is RECORDED by the durable memo and replays verbatim — the live-flipped
110
163
  // preference is never re-read on a replay.
111
- const boundary = getJourneyBoundary();
112
164
  let key: string | undefined = opts.idempotencyKey;
113
165
  if (!key && boundary) {
114
166
  const site = opts.idempotencyLabel ?? boundary.currentLabel ?? opts.type;
@@ -0,0 +1,48 @@
1
+ import type { DefinedFlag } from "@hogsend/core";
2
+ import type { Logger } from "./logger.js";
3
+ import { createOptionalSingleton } from "./singleton.js";
4
+
5
+ /**
6
+ * Registry of code-defined feature flags ({@link defineFlag}), the flag sibling
7
+ * of `ConversionRegistry`. Indexed by `meta.key`; a duplicate key warns and is
8
+ * skipped (first definition wins) so one fat-fingered copy-paste never silently
9
+ * shadows another flag. Constructed by `createHogsendClient` from `opts.flags`
10
+ * and installed on the process singleton so the boot reconciler + Studio can
11
+ * read it without a client reference.
12
+ */
13
+ export class FlagRegistry {
14
+ private byKey = new Map<string, DefinedFlag>();
15
+
16
+ constructor(definitions: DefinedFlag[] = [], logger?: Logger) {
17
+ for (const def of definitions) {
18
+ const key = def.meta.key;
19
+ if (this.byKey.has(key)) {
20
+ logger?.warn("flags: duplicate defineFlag key — skipping", { key });
21
+ continue;
22
+ }
23
+ this.byKey.set(key, def);
24
+ }
25
+ }
26
+
27
+ get(key: string): DefinedFlag | undefined {
28
+ return this.byKey.get(key);
29
+ }
30
+
31
+ has(key: string): boolean {
32
+ return this.byKey.has(key);
33
+ }
34
+
35
+ getAll(): DefinedFlag[] {
36
+ return [...this.byKey.values()];
37
+ }
38
+
39
+ count(): number {
40
+ return this.byKey.size;
41
+ }
42
+ }
43
+
44
+ const singleton = createOptionalSingleton<FlagRegistry>();
45
+ export const setFlagRegistry = singleton.set;
46
+ export const getFlagRegistry = singleton.get;
47
+ /** Reset the singleton — only for test cleanup. */
48
+ export const resetFlagRegistry = singleton.reset;