@hogsend/engine 0.39.0 → 0.41.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 (64) hide show
  1. package/package.json +9 -7
  2. package/src/buckets/check-membership.ts +6 -1
  3. package/src/campaigns/cohort-sql.ts +198 -0
  4. package/src/campaigns/define-campaign.ts +301 -0
  5. package/src/campaigns/reconcile.ts +391 -0
  6. package/src/campaigns/steps.ts +48 -0
  7. package/src/connectors/define-action.ts +70 -0
  8. package/src/container.ts +144 -42
  9. package/src/destinations/presets/posthog.ts +7 -1
  10. package/src/env.ts +14 -0
  11. package/src/index.ts +98 -3
  12. package/src/journeys/constants.ts +10 -0
  13. package/src/journeys/define-journey.ts +14 -405
  14. package/src/journeys/execute-journey-run.ts +608 -0
  15. package/src/journeys/graph/build-graph.ts +212 -56
  16. package/src/journeys/journey-boundary.ts +54 -0
  17. package/src/journeys/journey-context.ts +374 -59
  18. package/src/journeys/record-once.ts +110 -0
  19. package/src/lib/auth.ts +33 -1
  20. package/src/lib/blueprints.ts +576 -0
  21. package/src/lib/campaign-send-key.ts +58 -0
  22. package/src/lib/connector-actions.ts +203 -19
  23. package/src/lib/contacts.ts +54 -0
  24. package/src/lib/email-service-types.ts +4 -1
  25. package/src/lib/email.ts +13 -2
  26. package/src/lib/feed.ts +77 -57
  27. package/src/lib/frequency-cap.ts +45 -15
  28. package/src/lib/hatchet-duration.ts +22 -0
  29. package/src/lib/html.ts +1 -0
  30. package/src/lib/ingestion.ts +145 -4
  31. package/src/lib/journey-suppress.ts +87 -0
  32. package/src/lib/links.ts +204 -18
  33. package/src/lib/outbound.ts +20 -0
  34. package/src/lib/preferences.ts +80 -1
  35. package/src/lib/tracked.ts +44 -29
  36. package/src/lib/tracking-event-names.ts +8 -0
  37. package/src/lib/webhook-signing.ts +6 -1
  38. package/src/lists/channels.ts +75 -0
  39. package/src/lists/define-list.ts +34 -0
  40. package/src/lists/registry.ts +29 -2
  41. package/src/mcp/blueprint-tools.ts +460 -0
  42. package/src/routes/admin/blueprints.ts +711 -0
  43. package/src/routes/admin/campaigns.ts +341 -0
  44. package/src/routes/admin/emails.ts +13 -0
  45. package/src/routes/admin/index.ts +6 -0
  46. package/src/routes/admin/journeys.ts +4 -2
  47. package/src/routes/admin/links.ts +303 -36
  48. package/src/routes/admin/lists.ts +51 -0
  49. package/src/routes/campaigns/index.ts +297 -50
  50. package/src/routes/email/preferences.ts +50 -13
  51. package/src/routes/feed/recipient.ts +2 -43
  52. package/src/routes/index.ts +6 -0
  53. package/src/routes/lists/index.ts +138 -18
  54. package/src/routes/tracking/arrive.ts +260 -0
  55. package/src/routes/tracking/click-pipeline.ts +329 -0
  56. package/src/routes/tracking/click.ts +5 -270
  57. package/src/routes/tracking/index.ts +2 -0
  58. package/src/routes/tracking/vanity.ts +64 -0
  59. package/src/worker.ts +27 -0
  60. package/src/workflows/bucket-backfill.ts +4 -2
  61. package/src/workflows/bucket-reconcile.ts +11 -4
  62. package/src/workflows/check-alerts.ts +130 -1
  63. package/src/workflows/journey-blueprint-interpreter.ts +561 -0
  64. package/src/workflows/send-campaign.ts +673 -127
@@ -0,0 +1,391 @@
1
+ /**
2
+ * Boot-time reconciler for code-defined campaigns ({@link defineCampaign}).
3
+ *
4
+ * Runs once at worker start (before the Hatchet listener blocks), mirroring
5
+ * `enqueueBucketBackfills`: fire-and-forget, best-effort, never blocks or
6
+ * crashes boot. For each definition it upserts the `campaigns` row keyed by
7
+ * `campaign-def:<id>` (the definition idempotency key):
8
+ *
9
+ * - No row yet + `sendAt` in the future → insert `scheduled` and create a
10
+ * Hatchet scheduled run at `sendAt` (punctual primary; the reaper's
11
+ * due-scheduled sweep is the backstop if the schedule call fails).
12
+ * - No row yet + `sendAt` recently due (within {@link defineGraceMs}) → the
13
+ * deploy simply landed a beat after the send time; insert + enqueue now.
14
+ * - No row yet + `sendAt` stale (past the grace window) → insert `expired`
15
+ * and warn loudly. A late deploy NEVER fires a surprise blast; bump
16
+ * `sendAt` (or delete the file) to resolve.
17
+ * - Row exists and is still `scheduled` → sync mutable fields (name,
18
+ * audience, template, props, subject, from, sendAt, steps) so editing the
19
+ * file and redeploying updates the pending broadcast — the git-ops loop. A
20
+ * moved `sendAt` gets a fresh scheduled run; the stale run no-ops via the
21
+ * send task's early-fire guard.
22
+ * - Row exists in any other status (`sent`/`canceled`/`expired`/`failed`/
23
+ * in-flight/`waiting`) → no-op. `sent` is the natural "retired" end state;
24
+ * an operator `canceled` is never resurrected by a redeploy. Editing steps
25
+ * mid-flight is deliberately unsupported in v1 — once the campaign leaves
26
+ * `scheduled` (running or waiting between waves), the row is the source of
27
+ * truth.
28
+ */
29
+ import type { CampaignSendStep } from "@hogsend/core";
30
+ import { campaigns } from "@hogsend/db";
31
+ import {
32
+ getTemplateDefinition,
33
+ getTemplateNames,
34
+ type TemplateName,
35
+ } from "@hogsend/email";
36
+ import { and, eq, sql } from "drizzle-orm";
37
+ import type { HogsendClient } from "../container.js";
38
+ import { sendCampaignTask } from "../workflows/send-campaign.js";
39
+ import {
40
+ audienceOf,
41
+ DEFINED_CAMPAIGN_KEY_PREFIX,
42
+ type DefinedCampaign,
43
+ } from "./define-campaign.js";
44
+
45
+ /**
46
+ * How far past its `sendAt` a NEVER-SEEN definition may be and still send at
47
+ * first reconcile (covers a deploy that lands minutes after the scheduled
48
+ * instant). Anything staler is stamped `expired` instead — a definition
49
+ * committed with last week's date must not blast on deploy.
50
+ */
51
+ function defineGraceMs(): number {
52
+ return Number(process.env.CAMPAIGN_DEFINE_GRACE_MS ?? 60 * 60 * 1000);
53
+ }
54
+
55
+ export interface ReconcileResult {
56
+ created: number;
57
+ updated: number;
58
+ expired: number;
59
+ skipped: number;
60
+ }
61
+
62
+ export async function reconcileDefinedCampaigns(opts: {
63
+ client: HogsendClient;
64
+ campaigns: DefinedCampaign[];
65
+ }): Promise<ReconcileResult> {
66
+ const { client } = opts;
67
+ const { db, logger, listRegistry, bucketRegistry, templates } = client;
68
+ const result: ReconcileResult = {
69
+ created: 0,
70
+ updated: 0,
71
+ expired: 0,
72
+ skipped: 0,
73
+ };
74
+
75
+ const templateNames = new Set<string>(getTemplateNames(templates));
76
+ const seenIds = new Set<string>();
77
+
78
+ for (const campaign of opts.campaigns) {
79
+ const meta = campaign.meta;
80
+ if (seenIds.has(meta.id)) {
81
+ logger.error("campaigns: duplicate defineCampaign id — skipping", {
82
+ campaignId: meta.id,
83
+ });
84
+ result.skipped++;
85
+ continue;
86
+ }
87
+ seenIds.add(meta.id);
88
+
89
+ if (!meta.enabled) {
90
+ result.skipped++;
91
+ continue;
92
+ }
93
+
94
+ // Validate against the wired registries (same checks POST /v1/campaigns
95
+ // applies). Warn + skip rather than throw: one broken definition must not
96
+ // take down worker boot for every journey.
97
+ const { audienceKind, audienceId } = audienceOf(meta);
98
+ const audienceKnown =
99
+ audienceKind === "list"
100
+ ? listRegistry.has(audienceId)
101
+ : bucketRegistry.has(audienceId);
102
+ if (!audienceKnown) {
103
+ logger.error("campaigns: unknown audience — skipping definition", {
104
+ campaignId: meta.id,
105
+ audienceKind,
106
+ audienceId,
107
+ });
108
+ result.skipped++;
109
+ continue;
110
+ }
111
+ // A list-audience campaign resolves recipients by SUBSCRIPTION. A channel
112
+ // preference list (`kind:"channel"`) gates a delivery transport (the in-app
113
+ // feed, a connector), not an email topic — a channel audience would EMAIL
114
+ // everyone not opted out of e.g. the discord channel. Mirror the unknown-
115
+ // audience config-error path: warn + skip, never throw (one bad definition
116
+ // must not take down worker boot for every campaign).
117
+ if (audienceKind === "list" && listRegistry.isChannel(audienceId)) {
118
+ logger.error(
119
+ "campaigns: channel-list audience — skipping definition (a channel preference list cannot be a campaign audience)",
120
+ { campaignId: meta.id, audienceId },
121
+ );
122
+ result.skipped++;
123
+ continue;
124
+ }
125
+ // Validate EVERY send step's template, not just the mirrored first-step
126
+ // `meta.template` — a broken template on step 3 must be caught at deploy
127
+ // time, not mid-campaign two days into a wait.
128
+ const sendSteps = meta.steps.filter(
129
+ (s): s is CampaignSendStep => s.kind === "send",
130
+ );
131
+ const unknownTemplates = sendSteps
132
+ .map((s) => s.template)
133
+ .filter((t) => !templateNames.has(t));
134
+ if (unknownTemplates.length > 0) {
135
+ logger.error("campaigns: unknown template — skipping definition", {
136
+ campaignId: meta.id,
137
+ templates: unknownTemplates,
138
+ });
139
+ result.skipped++;
140
+ continue;
141
+ }
142
+
143
+ // A bucket campaign borrows consent from each template's declared
144
+ // category (a bucket is behavior, not consent — docs/audience-model.md).
145
+ // A categoryless template leaves suppression + List-Unsubscribe with
146
+ // nothing beyond unsubscribedAll/suppressed, so its compliance story is
147
+ // only as good as the template's category. Warn, don't skip — the send is
148
+ // legal-by-default, just weaker than it should be.
149
+ if (audienceKind === "bucket") {
150
+ for (const s of sendSteps) {
151
+ const definition = getTemplateDefinition({
152
+ key: s.template as TemplateName,
153
+ registry: templates,
154
+ });
155
+ if (!definition.category) {
156
+ logger.warn(
157
+ "campaigns: bucket-audience campaign template has no category — consent/unsubscribe fall back to the global opt-out only",
158
+ { campaignId: meta.id, template: s.template },
159
+ );
160
+ }
161
+ }
162
+ }
163
+
164
+ // The stored steps blob: multi-step definitions persist `{ v: 1, steps }`;
165
+ // a single-step definition stores NULL — the legacy row shape — so its
166
+ // per-send idempotency keys stay byte-for-byte legacy (campaignSendKey
167
+ // contract). The cast crosses the db package's opaque element type (db
168
+ // cannot import @hogsend/core; the engine narrows at read time).
169
+ const stepsBlob =
170
+ meta.steps.length > 1
171
+ ? {
172
+ v: 1 as const,
173
+ steps: meta.steps as unknown as Array<Record<string, unknown>>,
174
+ }
175
+ : null;
176
+
177
+ const idempotencyKey = `${DEFINED_CAMPAIGN_KEY_PREFIX}${meta.id}`;
178
+ const existingRows = await db
179
+ .select({
180
+ id: campaigns.id,
181
+ status: campaigns.status,
182
+ name: campaigns.name,
183
+ audienceKind: campaigns.audienceKind,
184
+ audienceId: campaigns.audienceId,
185
+ templateKey: campaigns.templateKey,
186
+ props: campaigns.props,
187
+ fromEmail: campaigns.fromEmail,
188
+ subject: campaigns.subject,
189
+ steps: campaigns.steps,
190
+ scheduledAt: campaigns.scheduledAt,
191
+ })
192
+ .from(campaigns)
193
+ .where(eq(campaigns.idempotencyKey, idempotencyKey))
194
+ .limit(1);
195
+ const existing = existingRows[0];
196
+
197
+ const now = Date.now();
198
+ const due = meta.sendAt.getTime() <= now;
199
+ const stale = meta.sendAt.getTime() < now - defineGraceMs();
200
+
201
+ if (!existing) {
202
+ if (stale) {
203
+ await db.insert(campaigns).values({
204
+ name: meta.name,
205
+ status: "expired",
206
+ audienceKind,
207
+ audienceId,
208
+ templateKey: meta.template,
209
+ props: meta.props ?? {},
210
+ fromEmail: meta.from ?? null,
211
+ subject: meta.subject ?? null,
212
+ steps: stepsBlob,
213
+ scheduledAt: meta.sendAt,
214
+ idempotencyKey,
215
+ });
216
+ logger.warn(
217
+ "campaigns: defined campaign sendAt is stale — marked expired, NOT sent",
218
+ {
219
+ campaignId: meta.id,
220
+ sendAt: meta.sendAt.toISOString(),
221
+ graceMs: defineGraceMs(),
222
+ },
223
+ );
224
+ result.expired++;
225
+ continue;
226
+ }
227
+
228
+ const inserted = await db
229
+ .insert(campaigns)
230
+ .values({
231
+ name: meta.name,
232
+ status: "scheduled",
233
+ audienceKind,
234
+ audienceId,
235
+ templateKey: meta.template,
236
+ props: meta.props ?? {},
237
+ fromEmail: meta.from ?? null,
238
+ subject: meta.subject ?? null,
239
+ steps: stepsBlob,
240
+ scheduledAt: meta.sendAt,
241
+ idempotencyKey,
242
+ })
243
+ // Two worker replicas reconciling concurrently: the loser of the
244
+ // partial-unique insert race simply defers to the winner's row. The
245
+ // `targetWhere` predicate must match the PARTIAL unique index
246
+ // (`WHERE idempotency_key IS NOT NULL`) or Postgres cannot infer the
247
+ // conflict arbiter (42P10).
248
+ .onConflictDoNothing({
249
+ target: campaigns.idempotencyKey,
250
+ where: sql`idempotency_key is not null`,
251
+ })
252
+ .returning({ id: campaigns.id });
253
+ const rowId = inserted[0]?.id;
254
+ if (!rowId) {
255
+ result.skipped++;
256
+ continue;
257
+ }
258
+
259
+ await scheduleOrEnqueue({ client, rowId, sendAt: meta.sendAt, due });
260
+ logger.info("campaigns: defined campaign scheduled", {
261
+ campaignId: meta.id,
262
+ rowId,
263
+ sendAt: meta.sendAt.toISOString(),
264
+ });
265
+ result.created++;
266
+ continue;
267
+ }
268
+
269
+ if (existing.status !== "scheduled") {
270
+ // sent (retired) / canceled / expired / failed / in-flight — the row is
271
+ // the source of truth once it has left `scheduled`.
272
+ result.skipped++;
273
+ continue;
274
+ }
275
+
276
+ const changed =
277
+ existing.name !== meta.name ||
278
+ existing.audienceKind !== audienceKind ||
279
+ existing.audienceId !== audienceId ||
280
+ existing.templateKey !== meta.template ||
281
+ canonicalJson(existing.props ?? {}) !== canonicalJson(meta.props ?? {}) ||
282
+ (existing.fromEmail ?? null) !== (meta.from ?? null) ||
283
+ (existing.subject ?? null) !== (meta.subject ?? null) ||
284
+ canonicalJson(existing.steps ?? null) !== canonicalJson(stepsBlob) ||
285
+ existing.scheduledAt?.getTime() !== meta.sendAt.getTime();
286
+
287
+ if (!changed) {
288
+ result.skipped++;
289
+ continue;
290
+ }
291
+
292
+ const sendAtMoved =
293
+ existing.scheduledAt?.getTime() !== meta.sendAt.getTime();
294
+
295
+ // CAS on `scheduled` so an edit never clobbers a row that went live (or
296
+ // was canceled) between the read above and this write.
297
+ const updated = await db
298
+ .update(campaigns)
299
+ .set({
300
+ name: meta.name,
301
+ audienceKind,
302
+ audienceId,
303
+ templateKey: meta.template,
304
+ props: meta.props ?? {},
305
+ fromEmail: meta.from ?? null,
306
+ subject: meta.subject ?? null,
307
+ steps: stepsBlob,
308
+ scheduledAt: meta.sendAt,
309
+ updatedAt: new Date(),
310
+ })
311
+ .where(
312
+ and(eq(campaigns.id, existing.id), eq(campaigns.status, "scheduled")),
313
+ )
314
+ .returning({ id: campaigns.id });
315
+
316
+ if (updated.length > 0 && sendAtMoved) {
317
+ // Fresh run at the new instant; the run created for the OLD instant
318
+ // finds `scheduledAt` still in the future when it fires and skips
319
+ // (send task early-fire guard), or finds the row terminal.
320
+ await scheduleOrEnqueue({
321
+ client,
322
+ rowId: existing.id,
323
+ sendAt: meta.sendAt,
324
+ due,
325
+ });
326
+ }
327
+ logger.info("campaigns: defined campaign updated", {
328
+ campaignId: meta.id,
329
+ rowId: existing.id,
330
+ sendAt: meta.sendAt.toISOString(),
331
+ });
332
+ result.updated++;
333
+ }
334
+
335
+ return result;
336
+ }
337
+
338
+ /**
339
+ * Key-order-canonical JSON for the changed-comparison. `existing.props` /
340
+ * `existing.steps` round-trip through Postgres jsonb, which does NOT preserve
341
+ * object key order (jsonb canonicalizes it), so a plain `JSON.stringify`
342
+ * comparison against the freshly-authored definition would report a permanent
343
+ * phantom "changed" for any multi-key object — an unchanged definition
344
+ * rewritten (and logged as updated) on every worker boot. Arrays keep their
345
+ * order; only object keys are sorted.
346
+ */
347
+ function canonicalJson(value: unknown): string {
348
+ return JSON.stringify(sortKeysDeep(value));
349
+ }
350
+
351
+ function sortKeysDeep(value: unknown): unknown {
352
+ if (Array.isArray(value)) return value.map(sortKeysDeep);
353
+ if (value !== null && typeof value === "object") {
354
+ return Object.fromEntries(
355
+ Object.entries(value as Record<string, unknown>)
356
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
357
+ .map(([key, entry]) => [key, sortKeysDeep(entry)]),
358
+ );
359
+ }
360
+ return value;
361
+ }
362
+
363
+ /**
364
+ * Create the punctual trigger for a scheduled row: a Hatchet scheduled run at
365
+ * `sendAt`, or an immediate enqueue when already due (within grace).
366
+ * Best-effort — on failure the row stays `scheduled` and the reaper's
367
+ * due-scheduled sweep promotes it.
368
+ */
369
+ async function scheduleOrEnqueue(opts: {
370
+ client: HogsendClient;
371
+ rowId: string;
372
+ sendAt: Date;
373
+ due: boolean;
374
+ }): Promise<void> {
375
+ const { client, rowId, sendAt, due } = opts;
376
+ try {
377
+ if (due) {
378
+ await sendCampaignTask.runNoWait({ campaignId: rowId });
379
+ } else {
380
+ await sendCampaignTask.schedule(sendAt, { campaignId: rowId });
381
+ }
382
+ } catch (err) {
383
+ client.logger.warn(
384
+ "campaigns: schedule/enqueue failed (reaper will promote)",
385
+ {
386
+ rowId,
387
+ error: err instanceof Error ? err.message : String(err),
388
+ },
389
+ );
390
+ }
391
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Authoring sugar for campaign steps ({@link defineCampaign} `steps:`).
3
+ * Each helper returns the plain stored POJO ({@link CampaignStep} —
4
+ * `campaigns.steps` blob entries): `step.send` normalizes a `where` builder
5
+ * to `ConditionEval[]` HERE, at authoring time (the same
6
+ * normalize-at-definition pattern as `trigger.where` in `defineJourney`), so
7
+ * the stored form is always introspectable data. Channel steps
8
+ * (`step.discord.post` / `.dm`, …) are phase 2.
9
+ */
10
+ import {
11
+ type CampaignSendStep,
12
+ type CampaignWaitStep,
13
+ type CampaignWhere,
14
+ type DurationObject,
15
+ normalizeCampaignWhere,
16
+ } from "@hogsend/core";
17
+ import type { TemplateName } from "@hogsend/email";
18
+
19
+ export const step = {
20
+ /**
21
+ * A per-recipient email wave. `where` filters the campaign's cohort
22
+ * (builder or declarative conditions — engagement terminals with no
23
+ * template scope to "any prior send of this campaign"); only valid on
24
+ * steps after the first (validated by `defineCampaign`).
25
+ */
26
+ send(opts: {
27
+ template: TemplateName;
28
+ props?: Record<string, unknown>;
29
+ subject?: string;
30
+ from?: string;
31
+ where?: CampaignWhere;
32
+ }): CampaignSendStep {
33
+ const where = normalizeCampaignWhere(opts.where);
34
+ return {
35
+ kind: "send",
36
+ template: opts.template,
37
+ ...(opts.props !== undefined ? { props: opts.props } : {}),
38
+ ...(opts.subject !== undefined ? { subject: opts.subject } : {}),
39
+ ...(opts.from !== undefined ? { from: opts.from } : {}),
40
+ ...(where !== undefined ? { where } : {}),
41
+ };
42
+ },
43
+
44
+ /** A durable gap between waves. Minimum 5 minutes (validated). */
45
+ wait(duration: DurationObject): CampaignWaitStep {
46
+ return { kind: "wait", duration };
47
+ },
48
+ };
@@ -36,6 +36,27 @@ export interface ConnectorActionCtx {
36
36
  resolveContact(ref: string): Promise<ResolvedActionContact | null>;
37
37
  }
38
38
 
39
+ /**
40
+ * Declares an action MEMBER-DIRECTED — aimed at an individual recipient rather
41
+ * than a channel/ops surface. Its presence gates the action on the recipient's
42
+ * channel preferences (the auto-registered per-connector opt-out list) before
43
+ * the plugin runs; enforcement lands in a later phase. Absent audience =
44
+ * ops/channel-directed = never gated.
45
+ */
46
+ export interface MemberAudience<A = unknown> {
47
+ kind: "member";
48
+ /**
49
+ * Candidate recipient refs (email | externalId | platform id | namespaced key
50
+ * like "telegram:<chatId>"), tried in order; first resolving contact wins.
51
+ * Returning undefined (or throwing) fails OPEN — the send proceeds.
52
+ *
53
+ * Method shorthand (bivariant) so a `DefinedConnectorAction<DmArgs, …>` stays
54
+ * assignable to the erased `DefinedConnectorAction[]` the registry/plugin
55
+ * index files use (same reason `run` is method shorthand).
56
+ */
57
+ ref(args: A): string | string[] | undefined;
58
+ }
59
+
39
60
  export interface DefinedConnectorAction<A = unknown, R = unknown> {
40
61
  /** The connector this action belongs to (e.g. "discord"). Keys the registry. */
41
62
  connectorId: string;
@@ -43,6 +64,12 @@ export interface DefinedConnectorAction<A = unknown, R = unknown> {
43
64
  name: string;
44
65
  /** Optional human description (Studio enumeration / docs). */
45
66
  description?: string;
67
+ /**
68
+ * When set, declares the action member-directed: the engine will gate it on
69
+ * the recipient's channel preferences before the plugin runs (enforcement
70
+ * lands in a later phase). Absent = ops/channel-directed = never gated.
71
+ */
72
+ audience?: MemberAudience<A>;
46
73
  /** Perform the outbound action. Single-object-in, result-out. */
47
74
  run(args: A, ctx: ConnectorActionCtx): Promise<R>;
48
75
  }
@@ -53,3 +80,46 @@ export function defineConnectorAction<A, R>(
53
80
  ): DefinedConnectorAction<A, R> {
54
81
  return def;
55
82
  }
83
+
84
+ /**
85
+ * The verdict returned when the engine SKIPS a member-directed connector action
86
+ * because the resolved recipient opted out — either the global master opt-out
87
+ * (`unsubscribed_all`) or the per-connector channel list (`channel_unsubscribed`).
88
+ *
89
+ * A plain JSON-safe POJO so it is memo-recordable and replays VERBATIM through
90
+ * both the Hatchet durable `memo` (Layer 1) AND the `connector_deliveries.result`
91
+ * jsonb round-trip (Layer 2) — although a skip in practice NEVER writes a
92
+ * delivery row (the gate runs BEFORE the ledger claim), so a skip is observable
93
+ * only via logs + this returned value.
94
+ *
95
+ * The shape DELIBERATELY does NOT mimic per-action result shapes (it carries no
96
+ * `messageId`/`delivered`): the `skipped: true` discriminant must be
97
+ * unambiguous. An existing consumer reading `result.delivered` gets `undefined`
98
+ * (falsy) on a skip — which degrades in the correct direction (treated as "not
99
+ * delivered").
100
+ */
101
+ export interface ConnectorActionSkipped {
102
+ skipped: true;
103
+ reason: "unsubscribed_all" | "channel_unsubscribed";
104
+ connectorId: string;
105
+ action: string;
106
+ }
107
+
108
+ /**
109
+ * Narrow an outbound-action result to a {@link ConnectorActionSkipped} verdict.
110
+ * Checks a non-null object with `skipped === true` plus string
111
+ * `reason`/`connectorId`/`action` — enough to disambiguate from every per-action
112
+ * result shape.
113
+ */
114
+ export function isConnectorActionSkipped(
115
+ r: unknown,
116
+ ): r is ConnectorActionSkipped {
117
+ if (typeof r !== "object" || r === null) return false;
118
+ const v = r as Record<string, unknown>;
119
+ return (
120
+ v.skipped === true &&
121
+ typeof v.reason === "string" &&
122
+ typeof v.connectorId === "string" &&
123
+ typeof v.action === "string"
124
+ );
125
+ }