@hogsend/engine 0.53.0 → 0.55.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 (39) hide show
  1. package/package.json +12 -11
  2. package/src/buckets/check-membership.ts +45 -3
  3. package/src/connectors/define-action.ts +15 -2
  4. package/src/container.ts +85 -0
  5. package/src/env.ts +21 -0
  6. package/src/index.ts +19 -0
  7. package/src/journeys/durable-law-harness.test.ts +107 -0
  8. package/src/journeys/durable-law-harness.ts +139 -0
  9. package/src/journeys/journey-boundary.test.ts +70 -0
  10. package/src/journeys/journey-boundary.ts +10 -1
  11. package/src/journeys/with-durable-gate.test.ts +258 -0
  12. package/src/journeys/with-durable-gate.ts +141 -0
  13. package/src/lib/bucket-emit.test.ts +145 -0
  14. package/src/lib/bucket-emit.ts +29 -3
  15. package/src/lib/connector-actions.test.ts +292 -1
  16. package/src/lib/connector-actions.ts +65 -6
  17. package/src/lib/email-providers-from-env.ts +15 -16
  18. package/src/lib/enrichment-ledger.ts +207 -0
  19. package/src/lib/enrichment-provider-registry.test.ts +64 -0
  20. package/src/lib/enrichment-provider-registry.ts +35 -0
  21. package/src/lib/enrichment-providers-from-env.apollo.test.ts +30 -0
  22. package/src/lib/enrichment-providers-from-env.test.ts +28 -0
  23. package/src/lib/enrichment-providers-from-env.ts +52 -0
  24. package/src/lib/enrichment-registry-singleton.ts +45 -0
  25. package/src/lib/ingestion.ts +5 -0
  26. package/src/lib/load-optional-plugin.test.ts +133 -0
  27. package/src/lib/load-optional-plugin.ts +142 -0
  28. package/src/lib/outbound.ts +27 -0
  29. package/src/lib/refine-chain.test.ts +764 -0
  30. package/src/lib/refine-chain.ts +583 -0
  31. package/src/lib/refine-traits.test.ts +141 -0
  32. package/src/lib/refine-traits.ts +128 -0
  33. package/src/lib/refine.ts +287 -0
  34. package/src/lib/sms-providers-from-env.ts +11 -11
  35. package/src/lib/webhook-catalog-sync.test.ts +112 -0
  36. package/src/lib/webhook-signing.ts +5 -1
  37. package/src/routes/admin/contacts.ts +113 -13
  38. package/src/workflows/bucket-backfill.ts +14 -0
  39. package/src/workflows/bucket-reconcile.ts +74 -15
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.53.0",
3
+ "version": "0.55.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -53,17 +53,18 @@
53
53
  "svix": "^1.95.1",
54
54
  "winston": "^3.19.0",
55
55
  "zod": "^4.4.3",
56
- "@hogsend/core": "^0.53.0",
57
- "@hogsend/attribution": "^0.53.0",
58
- "@hogsend/db": "^0.53.0",
59
- "@hogsend/email": "^0.53.0",
60
- "@hogsend/plugin-posthog": "^0.53.0",
61
- "@hogsend/plugin-resend": "^0.53.0",
62
- "@hogsend/sms": "^0.53.0"
56
+ "@hogsend/attribution": "^0.55.0",
57
+ "@hogsend/core": "^0.55.0",
58
+ "@hogsend/db": "^0.55.0",
59
+ "@hogsend/email": "^0.55.0",
60
+ "@hogsend/plugin-posthog": "^0.55.0",
61
+ "@hogsend/plugin-resend": "^0.55.0",
62
+ "@hogsend/sms": "^0.55.0"
63
63
  },
64
64
  "optionalDependencies": {
65
- "@hogsend/plugin-postmark": "^0.53.0",
66
- "@hogsend/plugin-twilio": "^0.53.0"
65
+ "@hogsend/plugin-apollo": "^0.55.0",
66
+ "@hogsend/plugin-postmark": "^0.55.0",
67
+ "@hogsend/plugin-twilio": "^0.55.0"
67
68
  },
68
69
  "devDependencies": {
69
70
  "@types/node": "^22.15.3",
@@ -75,7 +76,7 @@
75
76
  },
76
77
  "scripts": {
77
78
  "check-types": "tsc --noEmit",
78
- "test": "tsx --test src/**/*.test.ts",
79
+ "test": "tsx --test 'src/**/*.test.ts'",
79
80
  "lint": "biome check .",
80
81
  "clean": "rm -rf node_modules .turbo"
81
82
  }
@@ -51,6 +51,16 @@ export async function checkBucketMembership(opts: {
51
51
  logger: Logger;
52
52
  userId: string;
53
53
  userEmail: string | null;
54
+ /**
55
+ * The subject contact's resolved row id (`contacts.id`) — `ingestEvent` has
56
+ * already resolved the contact before calling us, so it threads the id here
57
+ * and we carry it into every `emitBucketTransition` as the ENGINE-INTERNAL
58
+ * provenance pin. Without it, a transition for a contact whose canonical key
59
+ * is its `anonymous_id` re-ingests a bare `userId` and mints a phantom
60
+ * `external_id` twin (issue #608). Optional: a caller without a resolved
61
+ * contact degrades to the pin-less emit.
62
+ */
63
+ contactId?: string;
54
64
  event: string;
55
65
  /**
56
66
  * D2: the event payload — candidate-narrowing ONLY. It NO LONGER participates
@@ -71,6 +81,7 @@ export async function checkBucketMembership(opts: {
71
81
  hatchet,
72
82
  logger,
73
83
  userId,
84
+ contactId,
74
85
  event,
75
86
  eventProperties,
76
87
  contactProperties: contactPropertiesPatch,
@@ -209,6 +220,7 @@ export async function checkBucketMembership(opts: {
209
220
  bucket,
210
221
  userId,
211
222
  userEmail,
223
+ contactId,
212
224
  });
213
225
  if (transition) transitions.push(transition);
214
226
  } else if (wasMember && isMember) {
@@ -227,6 +239,7 @@ export async function checkBucketMembership(opts: {
227
239
  active,
228
240
  userId,
229
241
  userEmail,
242
+ contactId,
230
243
  });
231
244
  if (transition) transitions.push(transition);
232
245
  }
@@ -244,8 +257,19 @@ async function handleJoin(opts: {
244
257
  bucket: BucketMeta;
245
258
  userId: string;
246
259
  userEmail: string | null;
260
+ /** Provenance pin for the emit — see `checkBucketMembership` (issue #608). */
261
+ contactId?: string;
247
262
  }): Promise<BucketTransition | null> {
248
- const { db, registry, hatchet, logger, bucket, userId, userEmail } = opts;
263
+ const {
264
+ db,
265
+ registry,
266
+ hatchet,
267
+ logger,
268
+ bucket,
269
+ userId,
270
+ userEmail,
271
+ contactId,
272
+ } = opts;
249
273
 
250
274
  // entryCount ordinal = 1 + count of ALL prior memberships (active + left) for
251
275
  // this (user, bucket) (Section 6.3 / 8.2). priorCount also drives the entryLimit
@@ -312,6 +336,10 @@ async function handleJoin(opts: {
312
336
  bucket,
313
337
  userId,
314
338
  userEmail,
339
+ // Pin the re-ingest to the already-resolved contact row so an
340
+ // anonymous-only contact's transition folds in instead of minting a
341
+ // phantom twin (issue #608).
342
+ contactId,
315
343
  epoch,
316
344
  source: "event",
317
345
  });
@@ -335,9 +363,20 @@ async function handleLeave(opts: {
335
363
  active: typeof bucketMemberships.$inferSelect;
336
364
  userId: string;
337
365
  userEmail: string | null;
366
+ /** Provenance pin for the emit — see `checkBucketMembership` (issue #608). */
367
+ contactId?: string;
338
368
  }): Promise<BucketTransition | null> {
339
- const { db, registry, hatchet, logger, bucket, active, userId, userEmail } =
340
- opts;
369
+ const {
370
+ db,
371
+ registry,
372
+ hatchet,
373
+ logger,
374
+ bucket,
375
+ active,
376
+ userId,
377
+ userEmail,
378
+ contactId,
379
+ } = opts;
341
380
 
342
381
  // minDwell DEFERS (never silently drops) the leave (Section 6.3). We set a
343
382
  // pending-leave deadline on expiresAt = enteredAt + minDwell so the reconcile
@@ -401,6 +440,9 @@ async function handleLeave(opts: {
401
440
  bucket,
402
441
  userId,
403
442
  userEmail,
443
+ // Same provenance pin as the join emit — a leave re-ingests through the
444
+ // identical path and would mint the same phantom twin (issue #608).
445
+ contactId,
404
446
  epoch: flipped.entryCount,
405
447
  source: "event",
406
448
  reason: "criteria",
@@ -21,6 +21,16 @@ export interface ResolvedActionContact {
21
21
  email: string | null;
22
22
  discordId: string | null;
23
23
  externalId: string | null;
24
+ /**
25
+ * Provenance (`contacts.source`) — the id of the origin that minted the
26
+ * contact ("api"/"posthog"/a Contact Source id like "clay"). Consulted by the
27
+ * cold-channel gate: a value naming a registered Contact Source classifies
28
+ * the contact as a cold prospect. OPTIONAL (additive) so pre-existing
29
+ * constructors of this public shape keep compiling; the engine's resolver
30
+ * always populates it, and an absent value is treated as "not a prospect"
31
+ * (fail open), matching the gate's posture.
32
+ */
33
+ source?: string | null;
24
34
  properties: Record<string, unknown>;
25
35
  }
26
36
 
@@ -84,7 +94,10 @@ export function defineConnectorAction<A, R>(
84
94
  /**
85
95
  * The verdict returned when the engine SKIPS a member-directed connector action
86
96
  * because the resolved recipient opted out — either the global master opt-out
87
- * (`unsubscribed_all`) or the per-connector channel list (`channel_unsubscribed`).
97
+ * (`unsubscribed_all`) or the per-connector channel list (`channel_unsubscribed`)
98
+ * — or because the recipient is a cold prospect (their `contacts.source` names a
99
+ * registered Contact Source) whose source posture blocks this connector's
100
+ * channel (`cold_channel_blocked`).
88
101
  *
89
102
  * A plain JSON-safe POJO so it is memo-recordable and replays VERBATIM through
90
103
  * both the Hatchet durable `memo` (Layer 1) AND the `connector_deliveries.result`
@@ -100,7 +113,7 @@ export function defineConnectorAction<A, R>(
100
113
  */
101
114
  export interface ConnectorActionSkipped {
102
115
  skipped: true;
103
- reason: "unsubscribed_all" | "channel_unsubscribed";
116
+ reason: "unsubscribed_all" | "channel_unsubscribed" | "cold_channel_blocked";
104
117
  connectorId: string;
105
118
  action: string;
106
119
  }
package/src/container.ts CHANGED
@@ -9,6 +9,7 @@ import type {
9
9
  DefinedFlag,
10
10
  DefinedFunnel,
11
11
  EmailProvider,
12
+ EnrichmentProvider,
12
13
  FunnelStageEntry,
13
14
  FxRateProvider,
14
15
  JourneySourceLocation,
@@ -100,6 +101,9 @@ import type {
100
101
  EmailService,
101
102
  FrequencyCapConfig,
102
103
  } from "./lib/email-service-types.js";
104
+ import { EnrichmentProviderRegistry } from "./lib/enrichment-provider-registry.js";
105
+ import { enrichmentProvidersFromEnv } from "./lib/enrichment-providers-from-env.js";
106
+ import { setEnrichmentProviders } from "./lib/enrichment-registry-singleton.js";
103
107
  import { FlagRegistry, setFlagRegistry } from "./lib/flags-registry.js";
104
108
  import { FunnelRegistry } from "./lib/funnel-registry.js";
105
109
  import { createFxLens, type FxLens, fxProviderFromEnv } from "./lib/fx.js";
@@ -206,6 +210,18 @@ export interface HogsendClient {
206
210
  * Undefined when no SMS provider is configured.
207
211
  */
208
212
  smsProvider?: SmsProvider;
213
+ /**
214
+ * The container-held registry of enrichment providers, keyed by `meta.id` —
215
+ * the enrichment sibling of {@link smsProviders}. Empty when no enrichment
216
+ * provider is configured.
217
+ */
218
+ enrichmentProviders: EnrichmentProviderRegistry;
219
+ /**
220
+ * The single resolved active enrichment provider `refineContact()` looks up
221
+ * through. Undefined when no enrichment provider is configured — a deploy
222
+ * with no enrichment is a valid deploy (refinement stays inert).
223
+ */
224
+ enrichmentProvider?: EnrichmentProvider;
209
225
  /**
210
226
  * The container-held registry of CRM providers, keyed by `meta.id`. The
211
227
  * `POST /v1/webhooks/crm/:providerId` route resolves the verifying provider
@@ -444,6 +460,31 @@ export interface HogsendClientOptions {
444
460
  linkTracking?: boolean;
445
461
  linkHost?: string;
446
462
  };
463
+ /**
464
+ * Enrichment (Refinement) is a first-class provider kind mirroring
465
+ * {@link email}/{@link sms}. The engine owns the cohesive refinement
466
+ * pipeline (ledger → TTL/negative cache → budget cap → ingest write), and
467
+ * the {@link EnrichmentProvider} (Apollo, Clay, …) is only the swappable
468
+ * vendor wire under it.
469
+ *
470
+ * - `provider` — a single enrichment provider. Merged LAST (after env
471
+ * presets and `providers`), so it wins on id collision.
472
+ * - `providers` — register MANY providers into the
473
+ * {@link EnrichmentProviderRegistry}.
474
+ * - `defaultProvider` — the active provider id `refineContact()` looks up
475
+ * through. Resolves as `defaultProvider ?? ENRICHMENT_PROVIDER ?? "apollo"`.
476
+ * If it names an unregistered provider, the container throws at boot.
477
+ * When nothing is explicitly requested and exactly ONE provider is
478
+ * registered, that one is used (the SMS DX rule).
479
+ *
480
+ * Omitting `enrichment` entirely (or configuring no provider) leaves
481
+ * refinement inert — a deploy with no enrichment is a valid deploy.
482
+ */
483
+ enrichment?: {
484
+ provider?: EnrichmentProvider;
485
+ providers?: EnrichmentProvider[];
486
+ defaultProvider?: string;
487
+ };
447
488
  /**
448
489
  * The OPTIONAL base-currency FX lens (docs/groups.md §Base-currency lens).
449
490
  * OFF unless a base currency resolves — with no `fx.baseCurrency` pin, no
@@ -1238,6 +1279,48 @@ export function createHogsendClient(
1238
1279
 
1239
1280
  setSmsService(smsService);
1240
1281
 
1282
+ // --- Enrichment providers (Refinement; parallel to email/SMS above) -------
1283
+ // Merge order mirrors email/SMS exactly: env presets FIRST, then
1284
+ // `providers`, then the single `provider` LAST (last-writer-wins on
1285
+ // `meta.id`). Resolve the active provider as
1286
+ // `defaultProvider ?? ENRICHMENT_PROVIDER ?? "apollo"`, with the SMS DX
1287
+ // rule (sole registered provider wins when nothing is explicitly requested)
1288
+ // and the same "an EXPLICIT id that misses throws, zero-config boots inert"
1289
+ // posture — refinement not being configured is a valid deploy.
1290
+ const enrichmentProviders = new EnrichmentProviderRegistry([
1291
+ ...enrichmentProvidersFromEnv(env),
1292
+ ...(opts.enrichment?.providers ?? []),
1293
+ ...(opts.enrichment?.provider ? [opts.enrichment.provider] : []),
1294
+ ]);
1295
+ const enrichmentActiveId =
1296
+ opts.enrichment?.defaultProvider ?? env.ENRICHMENT_PROVIDER ?? "apollo";
1297
+ const enrichmentExplicit = Boolean(
1298
+ opts.enrichment?.defaultProvider ?? env.ENRICHMENT_PROVIDER,
1299
+ );
1300
+ let enrichmentProvider = enrichmentProviders.get(enrichmentActiveId);
1301
+ if (
1302
+ !enrichmentProvider &&
1303
+ !enrichmentExplicit &&
1304
+ enrichmentProviders.count() === 1
1305
+ ) {
1306
+ enrichmentProvider = enrichmentProviders.getAll()[0];
1307
+ }
1308
+ if (enrichmentExplicit && !enrichmentProvider) {
1309
+ throw new Error(
1310
+ `enrichment provider "${enrichmentActiveId}" is not registered (registered: ${
1311
+ enrichmentProviders
1312
+ .getAll()
1313
+ .map((p) => p.meta.id)
1314
+ .join(", ") || "none"
1315
+ }). Set APOLLO_API_KEY (with @hogsend/plugin-apollo installed), or pass enrichment.provider.`,
1316
+ );
1317
+ }
1318
+ // Process singleton: `refineContact()` (a standalone import, like
1319
+ // sendEmail/sendSms) runs in journey tasks and crons with no client
1320
+ // reference; both the API and worker call createHogsendClient, so the
1321
+ // singleton is installed in both processes.
1322
+ setEnrichmentProviders(enrichmentProviders, enrichmentProvider);
1323
+
1241
1324
  // Wire better-auth's secondary storage to the SHARED engine Redis (the same
1242
1325
  // singleton backing the PostHog cache + worker heartbeat — never a second
1243
1326
  // pool). Passing `secondaryStorage` flips better-auth's rate-limit store from
@@ -1567,6 +1650,8 @@ export function createHogsendClient(
1567
1650
  smsService,
1568
1651
  smsProviders,
1569
1652
  smsProvider,
1653
+ enrichmentProviders,
1654
+ enrichmentProvider,
1570
1655
  crmProviders,
1571
1656
  funnels,
1572
1657
  flagRegistry,
package/src/env.ts CHANGED
@@ -177,6 +177,27 @@ export const env = createEnv({
177
177
  TWILIO_ACCOUNT_SID: z.string().min(1).optional(),
178
178
  TWILIO_AUTH_TOKEN: z.string().min(1).optional(),
179
179
  TWILIO_MESSAGING_SERVICE_SID: z.string().min(1).optional(),
180
+ // --- Enrichment (provider-neutral, BYO enrichment provider) ---
181
+ // The active enrichment provider id the container resolves from the
182
+ // EnrichmentProviderRegistry. Absent → "apollo" when a provider is
183
+ // registered; with no provider configured, refinement is inert.
184
+ ENRICHMENT_PROVIDER: z.string().optional(),
185
+ // --- Apollo (default enrichment provider, opt-in) ---
186
+ // A preset provider is built only when the key is present (guarded dynamic
187
+ // import in enrichment-providers-from-env.ts — the plugin package stays an
188
+ // optionalDependency).
189
+ APOLLO_API_KEY: z.string().min(1).optional(),
190
+ // How long a ledger row (hit OR miss) satisfies a lookup before the vendor
191
+ // is asked again. Every lookup costs money — the TTL is the cache side of
192
+ // the enrichment_lookups ledger.
193
+ ENRICHMENT_TTL_DAYS: z.coerce.number().int().positive().default(90),
194
+ // Hard monthly budget cap on vendor lookups. 0 (default) = uncapped; a
195
+ // positive cap FAILS CLOSED when exhausted.
196
+ ENRICHMENT_MONTHLY_LOOKUPS: z.coerce
197
+ .number()
198
+ .int()
199
+ .nonnegative()
200
+ .default(0),
180
201
  // Hatchet connection contract. The @hatchet-dev SDK also reads these straight
181
202
  // from process.env via its own config-loader, so this schema is a presence /
182
203
  // shape check that keeps the contract in one place — the values still flow to
package/src/index.ts CHANGED
@@ -477,6 +477,17 @@ export type {
477
477
  SendTrackedEmailOptions,
478
478
  TrackedSendResult,
479
479
  } from "./lib/email-service-types.js";
480
+ // --- Enrichment provider registry (Refinement; container-held, keyed by meta.id) ---
481
+ // The contract itself (EnrichmentProvider, defineEnrichmentProvider, …) is
482
+ // re-exported via `export * from "@hogsend/core"` above.
483
+ export { EnrichmentProviderRegistry } from "./lib/enrichment-provider-registry.js";
484
+ export { enrichmentProvidersFromEnv } from "./lib/enrichment-providers-from-env.js";
485
+ export {
486
+ getEnrichmentProvider,
487
+ getEnrichmentProviderRegistry,
488
+ resetEnrichmentProviders,
489
+ setEnrichmentProviders,
490
+ } from "./lib/enrichment-registry-singleton.js";
480
491
  // --- Enrollment guards ---
481
492
  export { checkEmailPreferences } from "./lib/enrollment-guards.js";
482
493
  export {
@@ -649,6 +660,14 @@ export {
649
660
  getRedis,
650
661
  getRedisIfConnected,
651
662
  } from "./lib/redis.js";
663
+ // --- Refinement (`refineContact` — a STANDALONE import, never on `ctx`) ---
664
+ export {
665
+ REFINE_EVENT,
666
+ type RefineContactOptions,
667
+ type RefineContactResult,
668
+ refineContact,
669
+ } from "./lib/refine.js";
670
+ export { flattenTraits } from "./lib/refine-traits.js";
652
671
  // --- Self-service password reset (engine-owned, self-contained email) ---
653
672
  export { sendResetPasswordEmail } from "./lib/reset-email.js";
654
673
  // --- Revenue rollups (the event spine's value/currency columns) ---
@@ -0,0 +1,107 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import {
4
+ assertUniformDurableJournal,
5
+ createRecordingBoundary,
6
+ } from "./durable-law-harness.js";
7
+ import { getJourneyBoundary } from "./journey-boundary.js";
8
+
9
+ // A hand-rolled durable helper standing in for any future one: `broken`
10
+ // re-creates defect 4 exactly — one path early-returns BEFORE the memoize.
11
+ async function helper(opts: {
12
+ skip: boolean;
13
+ broken?: boolean;
14
+ }): Promise<string> {
15
+ const boundary = getJourneyBoundary();
16
+ if (!boundary) return opts.skip ? "skipped" : "done";
17
+ if (opts.broken && opts.skip) return "skipped"; // defect 4: zero durable calls
18
+ return boundary.memoize(["key-1"], async () =>
19
+ opts.skip ? "skipped" : "done",
20
+ );
21
+ }
22
+
23
+ test("the harness passes a helper whose journal is identical across paths, and returns each verdict", async () => {
24
+ const { results, journal } = await assertUniformDurableJournal({
25
+ paths: {
26
+ skip: () => helper({ skip: true }),
27
+ done: () => helper({ skip: false }),
28
+ },
29
+ });
30
+
31
+ assert.deepEqual(journal, ['memoize:["key-1"]']);
32
+ assert.equal(results.skip, "skipped");
33
+ assert.equal(results.done, "done");
34
+ });
35
+
36
+ test("the harness FAILS a helper with one path issuing zero durable calls — defect 4's exact shape", async () => {
37
+ await assert.rejects(
38
+ assertUniformDurableJournal({
39
+ paths: {
40
+ done: () => helper({ skip: false, broken: true }),
41
+ skip: () => helper({ skip: true, broken: true }),
42
+ },
43
+ }),
44
+ /durable journal for path "skip" diverged/,
45
+ );
46
+ });
47
+
48
+ test("the harness FAILS a helper whose paths issue DIFFERENT durable calls", async () => {
49
+ await assert.rejects(
50
+ assertUniformDurableJournal({
51
+ expectedJournal: ['memoize:["key-1"]'],
52
+ paths: {
53
+ other: async () => {
54
+ const boundary = getJourneyBoundary();
55
+ assert.ok(boundary);
56
+ return boundary.memoize(["key-2"], async () => "done");
57
+ },
58
+ },
59
+ }),
60
+ /durable journal for path "other" diverged/,
61
+ );
62
+ });
63
+
64
+ test("an all-paths-empty journal never passes silently — asserting emptiness must be explicit", async () => {
65
+ // Implicit reference journal + zero durable calls anywhere = the shape a
66
+ // test asserted as CORRECT for defect 4. The harness refuses to bless it...
67
+ await assert.rejects(
68
+ assertUniformDurableJournal({
69
+ paths: { a: async () => "x", b: async () => "y" },
70
+ }),
71
+ /is EMPTY/,
72
+ );
73
+
74
+ // ...unless the author spells the emptiness out.
75
+ const { journal } = await assertUniformDurableJournal({
76
+ expectedJournal: [],
77
+ paths: { a: async () => "x" },
78
+ });
79
+ assert.deepEqual(journal, []);
80
+ });
81
+
82
+ test("each path runs in its OWN fresh boundary — journals never bleed across paths", async () => {
83
+ const { journal } = await assertUniformDurableJournal({
84
+ paths: {
85
+ first: () => helper({ skip: false }),
86
+ second: () => helper({ skip: false }),
87
+ },
88
+ });
89
+ // Two paths, one memoize EACH — not two accumulated in one journal.
90
+ assert.deepEqual(journal, ['memoize:["key-1"]']);
91
+ });
92
+
93
+ test("createRecordingBoundary skip strategy journals the memoize but never enters the closure", async () => {
94
+ const { boundary, durableCalls } = createRecordingBoundary({
95
+ memoStrategy: "skip",
96
+ recordedValue: "recorded",
97
+ });
98
+ let entered = 0;
99
+ const result = await boundary.memoize(["key-1"], async () => {
100
+ entered += 1;
101
+ return "live";
102
+ });
103
+
104
+ assert.equal(result, "recorded");
105
+ assert.equal(entered, 0);
106
+ assert.deepEqual(durableCalls, ['memoize:["key-1"]']);
107
+ });
@@ -0,0 +1,139 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ type JourneyBoundary,
4
+ runWithJourneyBoundary,
5
+ } from "./journey-boundary.js";
6
+
7
+ /**
8
+ * Test support for the positional-journal law — NOT part of the engine's
9
+ * public surface, and imported only by `*.test.ts` files.
10
+ *
11
+ * The technique here is the extraction of `refine-chain.test.ts`'s AC 11
12
+ * test, which was the ONLY reason defect 4 of the positional-journal class
13
+ * (a skip path issuing ZERO durable calls, with a test asserting that as
14
+ * correct) was catchable at all. Return values cannot prove the law — it is
15
+ * about WHICH durable calls were issued, in WHICH order — so the harness
16
+ * records exactly that and nothing else.
17
+ */
18
+
19
+ export interface RecordingBoundary {
20
+ boundary: JourneyBoundary;
21
+ /** One entry per durable call, in issuance order. */
22
+ durableCalls: string[];
23
+ }
24
+
25
+ export interface RecordingBoundaryOptions {
26
+ /** The nearest authored wait label, as `ctx.sleep`/`waitForEvent` would set. */
27
+ currentLabel?: string;
28
+ /**
29
+ * "run" (default) enters the memo closure, as a first run does. "skip"
30
+ * models an eviction-capable engine REPLAYING a recorded value without
31
+ * re-entering the closure — the memoize is journalled, the closure never
32
+ * runs, and {@link RecordingBoundaryOptions.recordedValue} is returned.
33
+ */
34
+ memoStrategy?: "run" | "skip";
35
+ /** What a "skip" memoize resolves to (the recorded verdict). */
36
+ recordedValue?: unknown;
37
+ runAnchor?: string;
38
+ stateId?: string;
39
+ }
40
+
41
+ /**
42
+ * A stub journey boundary that RECORDS every durable call it is issued.
43
+ * Each recorded entry is `memoize:<JSON of the deps array>` — the same
44
+ * byte-comparable shape `refine-chain.test.ts` established.
45
+ */
46
+ export function createRecordingBoundary(
47
+ opts: RecordingBoundaryOptions = {},
48
+ ): RecordingBoundary {
49
+ const durableCalls: string[] = [];
50
+ const boundary: JourneyBoundary = {
51
+ stateId: opts.stateId ?? "state-1",
52
+ runAnchor: opts.runAnchor ?? "run-1",
53
+ currentLabel: opts.currentLabel,
54
+ seenKeys: new Set(),
55
+ seenRecordLabels: new Set(),
56
+ memoize: async (deps, fn) => {
57
+ durableCalls.push(`memoize:${JSON.stringify(deps)}`);
58
+ if (opts.memoStrategy === "skip") {
59
+ return opts.recordedValue as never;
60
+ }
61
+ return fn();
62
+ },
63
+ };
64
+ return { boundary, durableCalls };
65
+ }
66
+
67
+ export interface UniformJournalOptions<T> {
68
+ /**
69
+ * The return paths to drive, by name. Each runs inside its OWN fresh
70
+ * recording boundary; the name is what a failure message points at.
71
+ */
72
+ paths: Record<string, () => Promise<T>>;
73
+ /**
74
+ * The exact journal every path must issue. Optional — when omitted, every
75
+ * path is asserted byte-identical to the FIRST path's journal, which must
76
+ * then be NON-empty: an all-paths-empty journal is exactly the shape of
77
+ * defect 4 (zero durable calls asserted as correct), so asserting emptiness
78
+ * requires spelling it out here explicitly.
79
+ */
80
+ expectedJournal?: string[];
81
+ /** Applied to every path's boundary. */
82
+ boundary?: Omit<RecordingBoundaryOptions, "memoStrategy" | "recordedValue">;
83
+ }
84
+
85
+ /**
86
+ * THE LAW, as a reusable assertion: drive a durable function through N
87
+ * different return paths and require the durable-call journal to be
88
+ * byte-identical across every one of them.
89
+ *
90
+ * The Hatchet journal is positional. If ANY return path of a durable helper
91
+ * issues a different sequence of durable calls than any other, then a replay
92
+ * whose live state selects a different path shifts every later durable call
93
+ * — the run is killed with a non-determinism error at best, and double-spends
94
+ * at worst. Verdicts may differ; journals may not.
95
+ *
96
+ * Returns each path's result (keyed by path name) so the caller can go on to
97
+ * assert the verdicts genuinely differ, plus the reference journal.
98
+ */
99
+ export async function assertUniformDurableJournal<T>(
100
+ opts: UniformJournalOptions<T>,
101
+ ): Promise<{ results: Record<string, T>; journal: string[] }> {
102
+ const names = Object.keys(opts.paths);
103
+ assert.ok(names.length > 0, "assertUniformDurableJournal: no paths given");
104
+
105
+ const results: Record<string, T> = {};
106
+ const journals: Record<string, string[]> = {};
107
+
108
+ for (const name of names) {
109
+ const { boundary, durableCalls } = createRecordingBoundary(opts.boundary);
110
+ const path = opts.paths[name];
111
+ assert.ok(path, `assertUniformDurableJournal: path "${name}" missing`);
112
+ results[name] = await runWithJourneyBoundary(boundary, path);
113
+ journals[name] = durableCalls;
114
+ }
115
+
116
+ const first = names[0] as string;
117
+ const reference = opts.expectedJournal ?? (journals[first] as string[]);
118
+ if (opts.expectedJournal === undefined) {
119
+ assert.ok(
120
+ reference.length > 0,
121
+ `durable journal for path "${first}" is EMPTY — a durable helper inside ` +
122
+ "a boundary that issues zero durable calls is defect 4 of the " +
123
+ "positional-journal class. If an empty journal is genuinely intended, " +
124
+ "pass `expectedJournal: []` explicitly.",
125
+ );
126
+ }
127
+
128
+ for (const name of names) {
129
+ assert.deepEqual(
130
+ journals[name],
131
+ reference,
132
+ `durable journal for path "${name}" diverged — the positional-journal ` +
133
+ "law requires EVERY return path to issue a byte-identical sequence " +
134
+ "of durable calls",
135
+ );
136
+ }
137
+
138
+ return { results, journal: reference };
139
+ }