@hogsend/engine 0.59.0 → 0.60.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 (51) hide show
  1. package/package.json +11 -11
  2. package/src/buckets/bucket-access.ts +19 -10
  3. package/src/buckets/check-membership.ts +55 -8
  4. package/src/buckets/membership-epoch.ts +11 -1
  5. package/src/campaigns/cohort-sql.ts +3 -0
  6. package/src/index.ts +10 -6
  7. package/src/journeys/execute-journey-run.ts +119 -50
  8. package/src/journeys/journey-context.ts +43 -7
  9. package/src/lib/agent/tools.ts +29 -4
  10. package/src/lib/attribution-backfill.ts +27 -4
  11. package/src/lib/attribution.ts +22 -3
  12. package/src/lib/connector-actions.ts +4 -1
  13. package/src/lib/contacts.ts +408 -152
  14. package/src/lib/conversion-dispatch.ts +16 -2
  15. package/src/lib/enrollment-guards.ts +19 -12
  16. package/src/lib/feed.ts +5 -5
  17. package/src/lib/flags.ts +26 -9
  18. package/src/lib/ingestion.ts +14 -2
  19. package/src/lib/journey-lift.ts +17 -5
  20. package/src/lib/preferences.ts +78 -29
  21. package/src/lib/recipient-preferences.ts +16 -2
  22. package/src/lib/revenue.ts +20 -5
  23. package/src/lib/sms-tracked.ts +18 -1
  24. package/src/lib/tracked.ts +19 -8
  25. package/src/lib/tracking-events.ts +28 -0
  26. package/src/lib/unique-violation.ts +44 -0
  27. package/src/routes/admin/buckets.ts +20 -2
  28. package/src/routes/admin/bulk.ts +14 -2
  29. package/src/routes/admin/contacts.ts +4 -3
  30. package/src/routes/admin/conversions.ts +20 -4
  31. package/src/routes/admin/emails.ts +17 -2
  32. package/src/routes/admin/events.ts +32 -41
  33. package/src/routes/admin/funnels.ts +6 -1
  34. package/src/routes/admin/groups.ts +4 -0
  35. package/src/routes/admin/impact.ts +30 -10
  36. package/src/routes/admin/journey-impact.ts +18 -9
  37. package/src/routes/admin/journeys.ts +8 -1
  38. package/src/routes/admin/maintenance.ts +7 -1
  39. package/src/routes/admin/preferences.ts +85 -46
  40. package/src/routes/admin/reporting.ts +25 -5
  41. package/src/routes/admin/targeting.ts +1 -0
  42. package/src/routes/admin/timeline.ts +16 -10
  43. package/src/routes/email/preferences.ts +18 -1
  44. package/src/routes/lists/index.ts +6 -6
  45. package/src/workflows/backfill-contact-id.ts +210 -30
  46. package/src/workflows/bucket-backfill.ts +145 -67
  47. package/src/workflows/bucket-reconcile.ts +150 -50
  48. package/src/workflows/check-alerts.ts +4 -0
  49. package/src/workflows/impact-digest.ts +10 -3
  50. package/src/workflows/journey-blueprint-interpreter.ts +8 -1
  51. package/src/workflows/send-campaign.ts +18 -11
@@ -9,6 +9,7 @@ import {
9
9
  } from "@hatchet-dev/typescript-sdk/v1/index.js";
10
10
  import type { DurationObject } from "@hogsend/core";
11
11
  import {
12
+ bySubject,
12
13
  durationToMs,
13
14
  evaluateEventCondition,
14
15
  evaluatePropertyConditions,
@@ -229,6 +230,15 @@ export function createJourneyContext(
229
230
  defaultSendWindow,
230
231
  } = config;
231
232
 
233
+ // PRD 05 T4 — the subject a history read is about. The run's resolved
234
+ // `contactId` applies ONLY to the ENROLLED user: `ctx.history.*` takes an
235
+ // arbitrary `userId` from author code, and scoping someone else's key to THIS
236
+ // run's contact would read the wrong person. A key that is not the enrolled
237
+ // one has no contact in hand, so it keeps `bySubject`'s text-key arm — which
238
+ // is exactly today's behavior for it.
239
+ const subjectFor = (targetUserId: string): string | null =>
240
+ targetUserId === userId ? (config.contactId ?? null) : null;
241
+
232
242
  // Replay-stable clock: the real DurableContext.now() is memoized across
233
243
  // replays; a pre-eviction engine (or a test ctx without it) falls back to the
234
244
  // live clock. Only RECOMPUTED instants depend on this — never the DB-key
@@ -477,7 +487,10 @@ export function createJourneyContext(
477
487
  // association map; user scope keeps the enrolled-user predicate.
478
488
  groupScope
479
489
  ? sql`${userEvents.groups} ->> ${groupScope.type} = ${groupScope.key}`
480
- : eq(userEvents.userId, userId),
490
+ : bySubject(userEvents, {
491
+ contactId: config.contactId,
492
+ userKey: userId,
493
+ }),
481
494
  eq(userEvents.event, event),
482
495
  gte(userEvents.occurredAt, scanSince),
483
496
  ...eqPreds,
@@ -676,7 +689,10 @@ export function createJourneyContext(
676
689
  .from(userEvents)
677
690
  .where(
678
691
  and(
679
- eq(userEvents.userId, userId),
692
+ bySubject(userEvents, {
693
+ contactId: config.contactId,
694
+ userKey: userId,
695
+ }),
680
696
  eq(userEvents.event, event),
681
697
  gte(userEvents.occurredAt, since),
682
698
  ),
@@ -815,7 +831,10 @@ export function createJourneyContext(
815
831
  .from(userEvents)
816
832
  .where(
817
833
  and(
818
- eq(userEvents.userId, userId),
834
+ bySubject(userEvents, {
835
+ contactId: config.contactId,
836
+ userKey: userId,
837
+ }),
819
838
  eq(userEvents.event, event),
820
839
  gte(userEvents.occurredAt, scanSince),
821
840
  lte(userEvents.occurredAt, flushInstant),
@@ -1416,7 +1435,11 @@ export function createJourneyContext(
1416
1435
 
1417
1436
  guard: {
1418
1437
  async isSubscribed() {
1419
- const prefs = await checkEmailPreferences({ db, userId });
1438
+ const prefs = await checkEmailPreferences({
1439
+ db,
1440
+ userId,
1441
+ contactId: config.contactId ?? null,
1442
+ });
1420
1443
  return !prefs.unsubscribed;
1421
1444
  },
1422
1445
  },
@@ -1462,7 +1485,12 @@ export function createJourneyContext(
1462
1485
  check: "exists",
1463
1486
  within,
1464
1487
  },
1465
- ctx: { db, userId: targetUserId, journeyContext },
1488
+ ctx: {
1489
+ db,
1490
+ userId: targetUserId,
1491
+ contactId: subjectFor(targetUserId),
1492
+ journeyContext,
1493
+ },
1466
1494
  });
1467
1495
  return { found: result.matched, count: result.count };
1468
1496
  },
@@ -1476,7 +1504,10 @@ export function createJourneyContext(
1476
1504
  .from(journeyStates)
1477
1505
  .where(
1478
1506
  and(
1479
- eq(journeyStates.userId, targetUserId),
1507
+ bySubject(journeyStates, {
1508
+ contactId: subjectFor(targetUserId),
1509
+ userKey: targetUserId,
1510
+ }),
1480
1511
  eq(journeyStates.journeyId, targetJourneyId),
1481
1512
  ),
1482
1513
  );
@@ -1549,7 +1580,12 @@ export function createJourneyContext(
1549
1580
  limit = 50,
1550
1581
  within,
1551
1582
  }): Promise<RecentEvent[]> {
1552
- const conditions = [eq(userEvents.userId, targetUserId)];
1583
+ const conditions = [
1584
+ bySubject(userEvents, {
1585
+ contactId: subjectFor(targetUserId),
1586
+ userKey: targetUserId,
1587
+ }),
1588
+ ];
1553
1589
  if (event) {
1554
1590
  conditions.push(eq(userEvents.event, event));
1555
1591
  }
@@ -1,4 +1,9 @@
1
- import { criteriaBuilder, days, evaluateCondition } from "@hogsend/core";
1
+ import {
2
+ bySubject,
3
+ criteriaBuilder,
4
+ days,
5
+ evaluateCondition,
6
+ } from "@hogsend/core";
2
7
  import {
3
8
  contacts,
4
9
  emailPreferences,
@@ -130,6 +135,9 @@ export function buildAgentTools({
130
135
  return db
131
136
  .select({
132
137
  event: userEvents.event,
138
+ // Display echo of the stamped key — not a scoping predicate. This
139
+ // tool lists the recent event stream instance-wide; there is no
140
+ // subject to scope by.
133
141
  userId: userEvents.userId,
134
142
  source: userEvents.source,
135
143
  occurredAt: userEvents.occurredAt,
@@ -169,10 +177,18 @@ export function buildAgentTools({
169
177
  execute: async ({ id }) => {
170
178
  const contact = await resolveContact({ db, id });
171
179
  if (!contact) return { error: `No contact for "${id}"` };
180
+ // Was `contact.externalId ?? contact.id` — an inline re-derivation of
181
+ // the canonical key that missed a preferences row written under an
182
+ // anonymous id. The owning contact names it directly.
172
183
  const prefs = await db
173
184
  .select()
174
185
  .from(emailPreferences)
175
- .where(eq(emailPreferences.userId, contact.externalId ?? contact.id))
186
+ .where(
187
+ bySubject(emailPreferences, {
188
+ contactId: contact.id,
189
+ userKey: contactKey(contact),
190
+ }),
191
+ )
176
192
  .limit(1);
177
193
  return { contact, preferences: prefs[0] ?? null };
178
194
  },
@@ -189,6 +205,10 @@ export function buildAgentTools({
189
205
  const contact = await resolveContact({ db, id });
190
206
  if (!contact) return { error: `No contact for "${id}"` };
191
207
  const key = contactKey(contact);
208
+ // Read by subject: the contact was just resolved, so both legs scope
209
+ // on the `contact_id` FK and pick up activity from keys this person
210
+ // has since moved off.
211
+ const subject = { contactId: contact.id, userKey: key };
192
212
  const [events, journeys] = await Promise.all([
193
213
  db
194
214
  .select({
@@ -197,7 +217,7 @@ export function buildAgentTools({
197
217
  occurredAt: userEvents.occurredAt,
198
218
  })
199
219
  .from(userEvents)
200
- .where(eq(userEvents.userId, key))
220
+ .where(bySubject(userEvents, subject))
201
221
  .orderBy(desc(userEvents.occurredAt))
202
222
  .limit(limit),
203
223
  db
@@ -209,7 +229,7 @@ export function buildAgentTools({
209
229
  .from(journeyStates)
210
230
  .where(
211
231
  and(
212
- eq(journeyStates.userId, key),
232
+ bySubject(journeyStates, subject),
213
233
  isNull(journeyStates.deletedAt),
214
234
  ),
215
235
  )
@@ -296,6 +316,11 @@ export function buildAgentTools({
296
316
  ctx: {
297
317
  db,
298
318
  userId: contactKey(c),
319
+ // Every row here IS a contact, so the evaluator's event leaf
320
+ // counts that contact's whole history — including events stamped
321
+ // under an earlier anonymous key. Without this the audience
322
+ // preview under-counts anyone who registered after being seen.
323
+ contactId: c.id,
299
324
  journeyContext: (c.properties ?? {}) as Record<string, unknown>,
300
325
  },
301
326
  });
@@ -134,6 +134,7 @@ export async function backfillAttributionBatch(opts: {
134
134
  id: userEvents.id,
135
135
  event: userEvents.event,
136
136
  userId: userEvents.userId,
137
+ contactId: userEvents.contactId,
137
138
  properties: userEvents.properties,
138
139
  value: userEvents.value,
139
140
  currency: userEvents.currency,
@@ -151,9 +152,13 @@ export async function backfillAttributionBatch(opts: {
151
152
  .orderBy(asc(userEvents.id))
152
153
  .limit(limit);
153
154
 
154
- // Batch contact resolution: canonical keys are externalId or the
155
- // contact row uuid. MATCH ONLY — backfill never mints contacts.
156
- const keys = [...new Set(rows.map((row) => row.userId))];
155
+ // Owner resolution. A row stamped with `contact_id` already names its
156
+ // owner, so only the unstamped remainder needs the string lookup:
157
+ // canonical keys are externalId or the contact row uuid. MATCH ONLY —
158
+ // backfill never mints contacts.
159
+ const keys = [
160
+ ...new Set(rows.filter((row) => !row.contactId).map((row) => row.userId)),
161
+ ];
157
162
  const uuidKeys = keys.filter((key) => UUID_RE.test(key));
158
163
  const contactRows =
159
164
  keys.length > 0
@@ -178,7 +183,7 @@ export async function backfillAttributionBatch(opts: {
178
183
  let conversionsFired = 0;
179
184
  let creditsWritten = 0;
180
185
  for (const row of rows) {
181
- const contactId = contactByKey.get(row.userId);
186
+ const contactId = row.contactId ?? contactByKey.get(row.userId);
182
187
  if (!contactId) continue;
183
188
  const fired = await evaluateConversionsAtIngest({
184
189
  db,
@@ -206,6 +211,15 @@ export async function backfillAttributionBatch(opts: {
206
211
  logger,
207
212
  conversionId: conversion.conversionId,
208
213
  userKey: row.userId,
214
+ // Scope the touchpoint path by the OWNER only when the spine row
215
+ // itself carries the stamp. This function replays HISTORY, and
216
+ // pre-upgrade history predates the `contact_id` dual-write entirely:
217
+ // an unstamped trigger row sits among unstamped touchpoints, which a
218
+ // contact-scoped scan cannot reach at all. When the trigger IS
219
+ // stamped, everything older is too (PRD 04's sweep cursors ascending
220
+ // by id), so the contact arm is both safe and the point — it reaches
221
+ // the anon-era touches adoption moved onto this person.
222
+ contactId: row.contactId,
209
223
  value: conversion.value,
210
224
  currency: conversion.currency,
211
225
  occurredAt: row.occurredAt,
@@ -240,11 +254,17 @@ export async function backfillAttributionBatch(opts: {
240
254
  id: conversions.id,
241
255
  definitionId: conversions.definitionId,
242
256
  userKey: conversions.userKey,
257
+ contactId: conversions.contactId,
258
+ // The trigger row's own stamp — the same "is this spine stamped?" test
259
+ // stage 1 applies, joined in because a conversions row always names an
260
+ // owner even when the history behind it predates `contact_id`.
261
+ spineContactId: userEvents.contactId,
243
262
  value: conversions.value,
244
263
  currency: conversions.currency,
245
264
  occurredAt: conversions.occurredAt,
246
265
  })
247
266
  .from(conversions)
267
+ .leftJoin(userEvents, eq(conversions.eventId, userEvents.id))
248
268
  .where(
249
269
  and(
250
270
  inArray(conversions.definitionId, defIds),
@@ -265,6 +285,9 @@ export async function backfillAttributionBatch(opts: {
265
285
  logger,
266
286
  conversionId: row.id,
267
287
  userKey: row.userKey,
288
+ // See stage 1: the owner scopes the path only when the spine carries the
289
+ // stamp; unstamped (pre-upgrade) history is reachable by string key only.
290
+ contactId: row.spineContactId ? row.contactId : null,
268
291
  value: row.value,
269
292
  currency: row.currency,
270
293
  occurredAt: row.occurredAt,
@@ -3,6 +3,7 @@ import {
3
3
  computeAllModels,
4
4
  } from "@hogsend/attribution";
5
5
  import {
6
+ bySubject,
6
7
  type DurationObject,
7
8
  durationToMs,
8
9
  TOUCHPOINT_EVENTS,
@@ -120,6 +121,16 @@ export async function recordAttributionCredits(opts: {
120
121
  conversionId: string;
121
122
  /** The contact's canonical event key (`user_events.user_id`). */
122
123
  userKey: string;
124
+ /**
125
+ * The trusted owner uuid (`conversions.contact_id`). REQUIRED (not
126
+ * optional) for the same reason the enrollment guards' is: an optional
127
+ * field silently defaults a new caller onto the mutable text key, and the
128
+ * touchpoint path is precisely the history written BEFORE the person was
129
+ * identified — a key-scoped read drops the anonymous half of every journey
130
+ * and credits the conversion to nothing. Pass `null` explicitly for a
131
+ * subject with no contact; `userKey` still serves that case.
132
+ */
133
+ contactId: string | null;
123
134
  value: number | null;
124
135
  currency: string | null;
125
136
  /** When the conversion happened. */
@@ -132,8 +143,16 @@ export async function recordAttributionCredits(opts: {
132
143
  */
133
144
  windows?: Partial<Record<TouchpointChannel, DurationObject>>;
134
145
  }): Promise<{ touchpoints: number }> {
135
- const { db, logger, conversionId, userKey, value, currency, occurredAt } =
136
- opts;
146
+ const {
147
+ db,
148
+ logger,
149
+ conversionId,
150
+ userKey,
151
+ contactId,
152
+ value,
153
+ currency,
154
+ occurredAt,
155
+ } = opts;
137
156
  const defaultWindowMs = opts.windowDays * 24 * 60 * 60 * 1000;
138
157
  const channelWindowMs = new Map<TouchpointChannel, number>(
139
158
  Object.entries(opts.windows ?? {}).map(([channel, duration]) => [
@@ -158,7 +177,7 @@ export async function recordAttributionCredits(opts: {
158
177
  .from(userEvents)
159
178
  .where(
160
179
  and(
161
- eq(userEvents.userId, userKey),
180
+ bySubject(userEvents, { contactId, userKey }),
162
181
  inArray(userEvents.event, [...TOUCHPOINT_EVENTS]),
163
182
  gte(userEvents.occurredAt, windowStart),
164
183
  lte(userEvents.occurredAt, occurredAt),
@@ -224,9 +224,12 @@ export async function checkActionAudience(
224
224
  });
225
225
  }
226
226
 
227
+ // PRD 05 T6 — the contact row is in hand, so the read is contact-scoped
228
+ // directly; the old `externalId ?? id` string derivation is the idiom the
229
+ // flip retires.
227
230
  const prefs = await readRecipientPreferences(db, {
228
231
  email: contact.email,
229
- userId: contact.externalId ?? contact.id,
232
+ contactId: contact.id,
230
233
  });
231
234
  if (prefs.unsubscribedAll) {
232
235
  return {