Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: hold Loops journeys when synchronization is unhealthy
Richie McIlroyf49691036c16
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d4bc896e1..d4b31fb52 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -93,7 +93,7 @@ jobs:- name: Check email libraryrun: |bun run emails:check- bun test scripts/emails scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts+ bun test scripts/emails scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts scripts/loops/watchdog.test.tsbun run tsc --noEmit --strict --jsx react-jsx --allowImportingTsExtensions --target ESNext --module ESNext --moduleResolution bundler --resolveJsonModule --types bun --skipLibCheck scripts/loops/*.ts scripts/emails/*.ts emails/*.ts emails/marketing/*.ts- name: Test web React compatibilitydiff --git a/.github/workflows/loops-safety.yml b/.github/workflows/loops-safety.ymlnew file mode 100644index 000000000..cc2b91a50--- /dev/null+++ b/.github/workflows/loops-safety.yml@@ -0,0 +1,29 @@+name: Loops delivery safety++on:+ schedule:+ - cron: "2-57/5 * * * *"+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: loops-delivery-safety+ cancel-in-progress: false++jobs:+ check:+ if: vars.LOOPS_WATCHDOG_ENABLED == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@v4+ - uses: oven-sh/setup-bun@v2+ with:+ bun-version: "1.4.0"+ - name: Hold lifecycle delivery if synchronization is unhealthy+ env:+ LOOPS_API_KEY: ${{ secrets.LOOPS_API_KEY }}+ LOOPS_HEALTH_SECRET: ${{ secrets.LOOPS_HEALTH_SECRET }}+ run: bun scripts/loops/watchdog.ts --applydiff --git a/apps/web/app/api/cron/sync-loops/health/route.ts b/apps/web/app/api/cron/sync-loops/health/route.tsnew file mode 100644index 000000000..22cfd722d--- /dev/null+++ b/apps/web/app/api/cron/sync-loops/health/route.ts@@ -0,0 +1,58 @@+import { timingSafeEqual } from "node:crypto";+import { readLoopsHealth } from "@cap/database/loops/health";+import {+ HttpApi,+ HttpApiBuilder,+ HttpApiEndpoint,+ HttpApiError,+ HttpApiGroup,+ HttpServerRequest,+} from "@effect/platform";+import { Effect, Layer, Schema } from "effect";+import { apiToHandler } from "@/lib/server";++class Api extends HttpApi.make("LoopsHealthApi").add(+ HttpApiGroup.make("root").add(+ HttpApiEndpoint.get("health")`/api/cron/sync-loops/health`+ .addSuccess(+ Schema.Struct({+ healthy: Schema.Boolean,+ checkedAt: Schema.String,+ totalJobs: Schema.Number,+ overdueJobs: Schema.Number,+ failingJobs: Schema.Number,+ }),+ )+ .addError(HttpApiError.Unauthorized)+ .addError(HttpApiError.InternalServerError),+ ),+) {}++const ApiLive = HttpApiBuilder.api(Api).pipe(+ Layer.provide(+ HttpApiBuilder.group(Api, "root", (handlers) =>+ handlers.handle("health", () =>+ Effect.gen(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ const secret = process.env.LOOPS_HEALTH_SECRET;+ if (!secret) return yield* new HttpApiError.InternalServerError();+ const expected = Buffer.from(`Bearer ${secret}`);+ const actual = Buffer.from(request.headers.authorization ?? "");+ if (+ actual.length !== expected.length ||+ !timingSafeEqual(actual, expected)+ )+ return yield* new HttpApiError.Unauthorized();+ return yield* Effect.tryPromise({+ try: readLoopsHealth,+ catch: () => new HttpApiError.InternalServerError(),+ });+ }),+ ),+ ),+ ),+);++export const GET = apiToHandler(ApiLive);+export const maxDuration = 30;+export const dynamic = "force-dynamic";diff --git a/emails/CATALOG.md b/emails/CATALOG.mdindex 7d7450866..fb2635c1c 100644--- a/emails/CATALOG.md+++ b/emails/CATALOG.md@@ -19,6 +19,8 @@ Current draft journeys require global subscription, capConsent=subscribed, the eTeammate history takes priority over paid/free classification. Ambiguous contacts receive no journey. [Audience classification and consent](../scripts/loops/README.md#audience-rules).+An independent watchdog can block all four automatic journeys by adding an impossible subscription condition to their downstream guards. Recovery never resumes delivery automatically. This does not cancel manually scheduled campaigns; check sync health before every campaign send. See the [outage and resume procedure](../scripts/loops/README.md#outage-protection).+### Independent free-user onboardingEntry: capLifecycleStage changes into free. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.diff --git a/emails/QA.md b/emails/QA.mdindex 55d9897c6..c5437e07e 100644--- a/emails/QA.md+++ b/emails/QA.md@@ -43,14 +43,16 @@ The local suite checks consent precedence, suppression preservation, customer an## Remaining gate before switching-The new implementation uses native Stripe imports, a held SSO fallback, and `loops_sync_jobs` for durable enrichment. Local routing tests cover missing Stripe imports, incomplete billing bootstrap, teammate persistence, an existing account accepting a new invite, global/list opt-outs, missing list membership, replay, identity conflicts and imported holds. The full email-script, profile and lifecycle suites passed 54 tests; existing SSO and Stripe subscription suites passed another 83. Database and web TypeScript checks passed.+The new implementation uses native Stripe imports, a held SSO fallback, and `loops_sync_jobs` for durable enrichment. Local routing tests cover missing Stripe imports, incomplete billing bootstrap, teammate persistence, an existing account accepting a new invite, global/list opt-outs, missing list membership, replay, identity conflicts and imported holds. The email, profile, lifecycle and delivery-check suites now pass 65 tests; existing SSO and Stripe subscription suites passed another 83. Database and web TypeScript checks passed.-Five integration checks passed on an isolated PlanetScale branch: transactional rollback, overlapping claims, expired lease recovery, newer work surviving an older completion, and an indexed due query. A full `db:push` attempt hit the repository's unrelated storage prefix-index quoting bug; the exact generated Loops migration was then applied and independently checked on the empty test branch. No production schema or data changed. The owned schema-only test branch was deleted after verification.+Nine integration checks passed on an isolated PlanetScale branch: transactional rollback, overlapping claims, expired lease recovery, newer work surviving older success/failure acknowledgements, an indexed due query, health classification, clearing recovered failures, and retry timing with replacement leases. A full `db:push` attempt hit the repository's unrelated storage prefix-index quoting bug; the exact generated Loops migration was then applied and independently checked on the empty test branch. No production schema or data changed. The first owned schema-only test branch was deleted after verification; a fresh empty branch was used for the expanded nine-test review run.The worker was exercised from synthetic database records through the real Loops API, including a simulated HTTP 429 followed by a successful retry, free and SSO teammate classification, a free-to-teammate transition, and a later unsubscribe surviving a billing change. Separate live checks cover imported holds and list removals. Loops omits an API-removed list from the returned map; the runtime now treats missing membership as ineligible and never re-adds lists during updates. All owned test contacts were read back held and globally unsubscribed. These checks sent no email and kept production workflows in Draft.The native Stripe integration is connected to Cap Software, Inc. and enabled for customer creation and updates only. A new owned live Stripe customer appeared in Loops; two later name changes updated that same contact. Name import and Product updates and tips list assignment were verified, and a global unsubscribe survived the final Stripe update. No payments, subscriptions or emails were created. The test contact remains held and globally unsubscribed. Both saved event mappings were checked after reload. A separate test-mode Stripe customer did not import through this live connection, is not counted as a passing native test, and was deleted after verification.+The independent GitHub delivery check is implemented but not deployed or enabled. Its local tests cover healthy operation, stale/unavailable health, manual hold, persistent holds after recovery, guarded manual resume, audience drift and partial provider failure. A real Loops API test applied the hold to all four production drafts, read back the downstream filters, and confirmed simulated recovery left them held. This sent no emails. It proves the API mutations on drafts, not the behavior of an already-running journey during a deployed outage. GitHub delays and a Loops API outage can delay or prevent the hold; scheduled campaigns remain a separate manual preflight and cancellation responsibility.+The deployed Cap signup/purchase/invite path has not yet been proven end to end. Production schema/code deployment, recipient Preference Center list-opt-out preservation across native Stripe updates, the final Bento suppression delta, and scheduler monitoring remain cutover gates. The Cap-worker API list-removal check above does not independently prove native Stripe handling of a recipient list opt-out. The worker retries failed updates, but Loops still uses the last successfully synced values during an outage; `capVerifiedAt` is not a native expiry rule.Follow the [cutover runbook](../scripts/loops/README.md#before-any-activation). Test that deployed path using owned inboxes, including outages and retries, before requesting production activation. Keep imported history held, preserve all opt-outs, reconcile fresh Bento changes, check Resend overlap and disable duplicate Bento automation only during the approved cutover.diff --git a/emails/README.md b/emails/README.mdindex 699cecd87..34ad8cd63 100644--- a/emails/README.md+++ b/emails/README.md@@ -12,6 +12,7 @@ Start with the [catalogue and flow maps](CATALOG.md), [copy guidance](VOICE.md),| Flow ordering, delays and milestone branches | [flows.ts](flows.ts) || Campaign targeting | [campaigns.ts](campaigns.ts) || Audience guards and contact properties | [audiences.ts](audiences.ts) |+| Shared downstream guards and emergency holds | [delivery-safety.ts](delivery-safety.ts) || Paid-plan welcome variations | [customer-copy.ts](customer-copy.ts) || Application email purposes and send locations | [application.ts](application.ts) || Registered Loops resource IDs | [resources.json](resources.json) |diff --git a/emails/delivery-safety.ts b/emails/delivery-safety.tsnew file mode 100644index 000000000..10c2b37c3--- /dev/null+++ b/emails/delivery-safety.ts@@ -0,0 +1,19 @@+import { audienceFilter, condition } from "./audiences";+import type { Journey } from "./types";++export const workflowAudience = (journey: Journey) => ({+ match: "all" as const,+ conditions: [+ ...audienceFilter(journey.audience, journey.promotional).conditions,+ condition("capLifecycleEnabled", true),+ condition("capOnboardingEligible", true),+ ],+});++export const heldWorkflowAudience = (journey: Journey) => ({+ ...workflowAudience(journey),+ conditions: [+ ...workflowAudience(journey).conditions,+ condition("subscribed", false),+ ],+});diff --git a/packages/database/loops/health.ts b/packages/database/loops/health.tsnew file mode 100644index 000000000..dbfc95d4c--- /dev/null+++ b/packages/database/loops/health.ts@@ -0,0 +1,70 @@+import mysql, { type Connection, type RowDataPacket } from "mysql2/promise";++export type LoopsHealth = {+ healthy: boolean;+ checkedAt: string;+ totalJobs: number;+ overdueJobs: number;+ failingJobs: number;+};++const expectedHolds = [+ "signup_not_complete",+ "user_removed",+ "identity_change_held",+ "remote_contact_removed",+];++export async function readQueueHealth(+ database: Connection,+): Promise<LoopsHealth> {+ const [rows] = await database.query<RowDataPacket[]>(+ {+ sql: "SELECT COUNT(*) AS totalJobs,COALESCE(SUM(nextAttemptAt<DATE_SUB(UTC_TIMESTAMP(),INTERVAL 5 MINUTE) AND COALESCE(lastError,'') NOT IN (?)),0) AS overdueJobs,COALESCE(SUM(failures>=3 AND COALESCE(lastError,'') NOT IN (?)),0) AS failingJobs FROM loops_sync_jobs",+ timeout: 10_000,+ },+ [expectedHolds, expectedHolds],+ );+ const totalJobs = Number(rows[0]?.totalJobs);+ const overdueJobs = Number(rows[0]?.overdueJobs);+ const failingJobs = Number(rows[0]?.failingJobs);+ if (+ ![totalJobs, overdueJobs, failingJobs].every(+ (value) => Number.isSafeInteger(value) && value >= 0,+ )+ )+ throw new Error("invalid_queue_health");+ return {+ healthy: totalJobs > 0 && overdueJobs === 0 && failingJobs === 0,+ checkedAt: new Date().toISOString(),+ totalJobs,+ overdueJobs,+ failingJobs,+ };+}++export async function readLoopsHealth(): Promise<LoopsHealth> {+ if (+ process.env.LOOPS_SYNC_ENABLED !== "true" ||+ process.env.LOOPS_SYNC_MODE !== "production" ||+ process.env.LOOPS_ENROLLMENT_ENABLED !== "true"+ )+ return {+ healthy: false,+ checkedAt: new Date().toISOString(),+ totalJobs: 0,+ overdueJobs: 0,+ failingJobs: 0,+ };+ if (!process.env.DATABASE_URL) throw new Error("missing_database_url");+ const database = await mysql.createConnection({+ uri: process.env.DATABASE_URL,+ timezone: "Z",+ connectTimeout: 10_000,+ });+ try {+ return await readQueueHealth(database);+ } finally {+ await database.end();+ }+}diff --git a/packages/database/loops/worker.ts b/packages/database/loops/worker.tsindex 1cb2380fd..689bc6216 100644--- a/packages/database/loops/worker.ts+++ b/packages/database/loops/worker.ts@@ -147,6 +147,18 @@ export async function deferJob();}+export async function completeUnchangedJob(+ database: Connection,+ job: Pick<Job, "userId" | "revision">,+ token: string,+ nextAttemptAt: Date,+) {+ await database.execute(+ "UPDATE loops_sync_jobs SET failures=0,lastError=NULL,nextAttemptAt=CASE WHEN revision=? THEN ? ELSE UTC_TIMESTAMP() END,leaseToken=NULL,leaseUntil=NULL WHERE userId=? AND leaseToken=?",+ [job.revision, nextAttemptAt, job.userId, token],+ );+}+export function loopsRuntimeConfig(env: NodeJS.ProcessEnv): LoopsRuntimeConfig {const listId = env.LOOPS_MAILING_LIST_ID;const enrollmentAfter = new Date(env.LOOPS_ENROLLMENT_AFTER ?? "");@@ -259,14 +271,11 @@ export async function runLoopsSync(customerCopy: CustomerCopy) {).digest("hex");if (job.profileHash === hash) {- await cap.execute(- "UPDATE loops_sync_jobs SET nextAttemptAt=CASE WHEN revision=? THEN ? ELSE UTC_TIMESTAMP() END,leaseToken=NULL,leaseUntil=NULL WHERE userId=? AND leaseToken=?",- [- job.revision,- nextProfileCheck(localProfile, new Date()),- job.userId,- token,- ],+ await completeUnchangedJob(+ cap,+ job,+ token,+ nextProfileCheck(localProfile, new Date()),);processed++;continue;diff --git a/scripts/emails/catalog.ts b/scripts/emails/catalog.tsindex 6e0f22f9f..278f9e2b4 100644--- a/scripts/emails/catalog.ts+++ b/scripts/emails/catalog.ts@@ -1,7 +1,7 @@import { readdir, readFile } from "node:fs/promises";import { fileURLToPath } from "node:url";import { applicationEmails } from "../../emails/application";-import { audienceFilter, contactProperties } from "../../emails/audiences";+import { contactProperties } from "../../emails/audiences";import {components,contactFallbacks,@@ -10,6 +10,7 @@ import {} from "../../emails/brand";import { campaignTemplates } from "../../emails/campaigns";import { customerCopy } from "../../emails/customer-copy";+import { workflowAudience } from "../../emails/delivery-safety";import { journeys } from "../../emails/flows";import resources from "../../emails/resources.json";import type { EmailDefinition, Journey } from "../../emails/types";@@ -83,15 +84,6 @@ export const validateTheme = (styles: Record<string, unknown>) =>value > 300),).map(([key]) => `${key} must be a percentage from 100 to 300`);-const workflowFilter = (journey: Journey) => ({- ...audienceFilter(journey.audience, journey.promotional),- conditions: [- ...audienceFilter(journey.audience, journey.promotional).conditions,- { type: "property", key: "capLifecycleEnabled", operator: "isTrue" },- { type: "property", key: "capOnboardingEligible", operator: "isTrue" },- ],-});-export const validateCatalog = async () => {const errors = marketingEmails.flatMap((email) =>validateEmail(email).map((error) => `${email.id}: ${error}`),@@ -215,6 +207,8 @@ export const renderCatalog = () => {"","Teammate history takes priority over paid/free classification. Ambiguous contacts receive no journey. [Audience classification and consent](../scripts/loops/README.md#audience-rules).","",+ "An independent watchdog can block all four automatic journeys by adding an impossible subscription condition to their downstream guards. Recovery never resumes delivery automatically. This does not cancel manually scheduled campaigns; check sync health before every campaign send. See the [outage and resume procedure](../scripts/loops/README.md#outage-protection).",+ "",];for (const journey of journeys) {lines.push(@@ -222,7 +216,7 @@ export const renderCatalog = () => {"",`Entry: capLifecycleStage changes into ${journey.key}. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.`,"",- `Downstream conditions: ${workflowFilter(journey)+ `Downstream conditions: ${workflowAudience(journey).conditions.map((condition) =>`${condition.key} ${condition.operator}${"value" in condition ? ` ${condition.value}` : ""}`,diff --git a/scripts/loops/README.md b/scripts/loops/README.mdindex c7dae6bd4..72640aa76 100644--- a/scripts/loops/README.md+++ b/scripts/loops/README.md@@ -59,7 +59,7 @@ Normal completed signups create or reuse a Stripe customer. The native Loops StrThere is no `marketing_contacts` table. The small `loops_sync_jobs` table stores a user ID, pending revision, retry/lease state, a profile hash, the last synced email and a teammate-join timestamp. It is operational delivery state, not a second subscription database. Queue writes are transactional with signup/invite/SSO changes. Billing webhooks queue updates after persisting billing state; Stripe retries an unsuccessful webhook. Interrupted workers release through expiring leases; completing an older job cannot discard a newer request.-`/api/cron/sync-loops` runs every minute with `CRON_SECRET` authentication. A run has a bounded processing window and stops on rate limiting. Failures stay pending with exponential backoff up to an hour; failed runs return HTTP 500 and log a user ID and a nonsecret reason. Fresh source queries run hourly for recent signups and daily for older accounts, providing reconciliation for milestones and external license changes. Unchanged profile hashes avoid redundant Loops requests. Signup, invite, SSO and billing hooks make relevant changes due immediately. This is eventual synchronization; configure backlog/failure alerts and prove latency before activation. If the scheduler stops, Loops does not automatically expire `capVerifiedAt` or stop already queued emails.+`/api/cron/sync-loops` runs every minute with `CRON_SECRET` authentication. A run has a bounded processing window and stops on rate limiting. Failures stay pending with exponential backoff up to an hour; failed runs return HTTP 500 and log a user ID and a nonsecret reason. Fresh source queries run hourly for recent signups and daily for older accounts, providing reconciliation for milestones and external license changes. Unchanged profile hashes avoid redundant Loops requests. Signup, invite, SSO and billing hooks make relevant changes due immediately. This is eventual synchronization; configure backlog/failure alerts and prove latency before activation. Loops does not automatically expire `capVerifiedAt`. The independent delivery check below closes the four downstream journey guards when the queue becomes unhealthy; it is an additional safeguard, not a real-time expiry guarantee.Loops owns subscription preferences. Normal updates never send `subscribed: true` or change list membership. API list removal can disappear from the returned `mailingLists` map; absence is treated as a hold, never an invitation to re-add the list. Configure list assignment for native imports and retain unsubscribe records in Loops. An SSO contact joins the list only in its initial create request. Keep the private Bento suppression archive and reconcile all negative records into Loops before enabling email workflows. Native contact imports are already enabled; imported contacts cannot enter the managed draft journeys without Cap eligibility fields. Contacts that were removed after a successful sync are not recreated. Changed/deleted Cap identities have their previously synced Loops contact held and are surfaced for reconciliation.@@ -76,9 +76,40 @@ Deploy the generated schema before code that selects the new columns. The unship| `LOOPS_ENROLLMENT_AFTER` | Explicit ISO cutover timestamp; historical signups stay held || `LOOPS_ENROLLMENT_ENABLED=true` | Allows eligible lifecycle stages; leave false until approved cutover || `CRON_SECRET` | Authenticates the scheduled endpoint |+| `LOOPS_HEALTH_SECRET` | Separate read-only credential for the independent delivery check |With the schema available and test configuration set, `bun scripts/loops/seed.ts` reports how many completed signups would be queued. `--apply` queues them without sending anything. `bun scripts/loops/sync.ts --apply` processes a bounded batch using the same worker as the cron route. Test mode fails closed without an allowlist. Set `LOOPS_SYNC_MODE=production` only as part of the reviewed cutover. Seed old completed accounts once after the final suppression reconciliation; subsequent signups enter the queue through the application.+## Independent delivery check++`.github/workflows/loops-safety.yml` runs every five minutes, independently of the Cap cron worker. It is disabled until the repository variable `LOOPS_WATCHDOG_ENABLED` is explicitly set to `true`. Configure GitHub secrets `LOOPS_API_KEY` and `LOOPS_HEALTH_SECRET`, and configure the same health secret in Cap. Scheduled Actions run from the default branch, so this protection is not deployed while the PR remains unmerged.++The authenticated, read-only `/api/cron/sync-loops/health` endpoint reports queue counts without contact data. It reports unhealthy when production sync or enrollment is disabled, the queue is empty, a due job is over five minutes late, or a job has failed three times. Expected holds for incomplete signup and removed/changed identities do not count as delivery failures. An unchanged successful refresh clears old failures; a newly queued change does not inherit an older attempt's retry delay.++The checker rejects unavailable, malformed or stale health responses. On failure or audience drift it adds mutually exclusive subscription conditions to each journey's first audience guard, with scope set to all following nodes, then reads the guards back. One failed update does not stop attempts on the other journeys. An update failure or existing hold fails the Action so it remains visible. Assign an owner to GitHub Actions failure notifications and verify that notification before activation.++The hold persists after recovery. It does not change workflow status, contact subscriptions or campaign schedules. The current four production drafts have this hold applied and independently verified. To inspect them without writes:++```sh+bun run emails:check-loops --structure-only --require-held+```++For an emergency hold, with the Loops API key in the environment:++```sh+bun scripts/loops/watchdog.ts --hold --apply+```++Only after synchronization is healthy and cutover or recovery has been approved, remove the exact known hold with:++```sh+bun scripts/loops/watchdog.ts --resume --apply+```++Resume requires a fresh authenticated health response and refuses changed audience rules. It does not start a draft or unpause a workflow. Contacts that have already exited because of a hold are not automatically replayed; assess recovery separately without bulk re-enrolling history.++GitHub scheduling can be delayed, and a Loops API outage can prevent guard updates. A message already being sent may still arrive. Test a running owned-account journey across an outage in the deployed environment before relying on this protection. Manually pause Loops if the check cannot apply a hold. Campaigns require a fresh health check before scheduling and manual cancellation or pause during an outage; the checker only guards the four registered journeys.+## Before any activation### Optional sender profile picture@@ -94,7 +125,7 @@ Activation is deliberately outside this migration's approved scope. These gates1. Review the final custom drafts and audiences, and configure rotated credentials in the intended environment. September 11 controlled deliveries passed SPF, DKIM and DMARC with inherited `p=quarantine`; the earlier DMARC warning is no longer an observed blocker. Recheck sending-domain status at cutover.2. The native Stripe connection passed an owned live-customer creation/update test, including name sync, list assignment and global unsubscribe preservation. Independently test a recipient Preference Center list opt-out across a Stripe update; the separate Cap-worker API list-removal check is not proof of that native behavior. Import/reconcile the remaining Bento negative records with workflows off. Then deploy the reviewed schema/code in test mode and prove the actual signup, purchase and invite routes with owned accounts.3. Set the explicit cutover timestamp, verify the cron schedule and permissions in the deployed environment, and seed the completed-account sync jobs. Keep enrollment disabled while inspecting the resulting contacts. Preserve existing opt-outs and suppressions; no separate consent-capture step is needed.-4. Add a freshness mechanism and monitoring before live sends. Downstream filters use the last synced fields; `capVerifiedAt` is evidence, not a native expiry guarantee. Prove purchase/invite/opt-out transitions remove contacts before later promotional steps. Pause the workflows during a sustained sync outage; changing an application environment flag alone cannot stop messages already queued in Loops.+4. Configure and enable the independent delivery check above, verify its deployed health endpoint and failure notifications, and prove purchase/invite/opt-out transitions remove contacts before later promotional steps. Exercise its hold and explicit recovery with an owned-account journey. Downstream filters use the last synced fields; `capVerifiedAt` is not a native expiry guarantee. Pause workflows manually if the checker cannot reach Loops, and handle scheduled campaigns separately.5. Reconcile a fresh Bento delta at cutover, including all opt-outs and changed entitlements. Confirm no campaign/flow is queued to send twice, check overlap with Resend recording emails, then disable old Bento marketing automations only as part of the approved cutover. Preserve source history and suppression evidence.6. Test the deployed Cap signup/purchase/invite/opt-out path through Loops to an owned inbox, including a sync outage and retries. The completed synthetic profile-to-Loops tests do not replace this production integration check.7. After explicit activation approval, enable one small cohort of new Cap signups without an existing opt-out or suppression, monitor deliveries, complaints, opt-outs and duplicate suppression, then expand. Do not bulk enroll imported history. Rollback stops new enrollment and pauses Loops before considering re-enabling Bento; never run both senders for the same journey. Retire Bento and rotate remaining credentials after reconciliation.@@ -102,7 +133,7 @@ Activation is deliberately outside this migration's approved scope. These gates## Validation```sh-bun test scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts scripts/emails/catalog.test.ts+bun test scripts/emails scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts scripts/loops/watchdog.test.tsbun run biome check scripts/loops packages/database/schema.ts packages/database/auth/drizzle-adapter.ts packages/database/auth/sso.ts apps/web/app/api/invite/accept/route.tsbun run tsc -b packages/databasebun run --cwd apps/web next typegendiff --git a/scripts/loops/database.test.ts b/scripts/loops/database.test.tsindex 853688aa2..30a5f5632 100644--- a/scripts/loops/database.test.ts+++ b/scripts/loops/database.test.ts@@ -4,12 +4,17 @@ import { User } from "@cap/web-domain";import { eq } from "drizzle-orm";import { drizzle } from "drizzle-orm/mysql2";import mysql, { type Connection, type RowDataPacket } from "mysql2/promise";+import { readQueueHealth } from "../../packages/database/loops/health";import { enqueueLoopsSync } from "../../packages/database/loops/queue";-import { claimJob, deferJob } from "../../packages/database/loops/worker";+import {+ claimJob,+ completeUnchangedJob,+ deferJob,+} from "../../packages/database/loops/worker";import { loopsSyncJobs } from "../../packages/database/schema";const url = process.env.LOOPS_TEST_DATABASE_URL;-const ids = Array.from({ length: 6 }, () =>+const ids = Array.from({ length: 7 }, () =>User.UserId.make(randomUUID().replaceAll("-", "").slice(0, 15)),);@@ -104,6 +109,48 @@ describe.skipIf(!url)("durable Loops queue on an isolated database", () => {).toBe(true);});+ test("health detects an overdue queue and repeated failures without flagging held signups", async () => {+ await enqueueLoopsSync(drizzle(database), ids[5]);+ await database.execute(+ "UPDATE loops_sync_jobs SET nextAttemptAt=DATE_SUB(UTC_TIMESTAMP(),INTERVAL 6 MINUTE),failures=3,lastError='loops_http_429' WHERE userId=?",+ [ids[5]],+ );+ expect(await readQueueHealth(database)).toMatchObject({+ healthy: false,+ overdueJobs: 1,+ failingJobs: 1,+ });+ await database.execute(+ "UPDATE loops_sync_jobs SET lastError='signup_not_complete' WHERE userId=?",+ [ids[5]],+ );+ expect((await readQueueHealth(database)).healthy).toBe(true);+ await enqueueLoopsSync(drizzle(other), ids[5]);+ const [rows] = await database.execute<RowDataPacket[]>(+ "SELECT failures,lastError FROM loops_sync_jobs WHERE userId=?",+ [ids[5]],+ );+ expect(rows[0].failures).toBe(0);+ expect(rows[0].lastError).toBeNull();+ });++ test("a successful unchanged profile clears a recovered failure", async () => {+ await enqueueLoopsSync(drizzle(database), ids[6]);+ await database.execute(+ "UPDATE loops_sync_jobs SET failures=3,lastError='sync_failed' WHERE userId=?",+ [ids[6]],+ );+ const job = await claimJob(database, "recovered-worker", [ids[6]]);+ if (!job) throw new Error("Test job was not claimed");+ await completeUnchangedJob(+ database,+ job,+ "recovered-worker",+ new Date(Date.now() + 60 * 60_000),+ );+ expect((await readQueueHealth(database)).healthy).toBe(true);+ });+test("new invite work stays immediately due when an older attempt fails", async () => {await enqueueLoopsSync(drizzle(database), ids[3]);const old = await claimJob(database, "failing-attempt", [ids[3]]);diff --git a/scripts/loops/provision.ts b/scripts/loops/provision.tsindex 3efde604a..397e640bc 100644--- a/scripts/loops/provision.ts+++ b/scripts/loops/provision.ts@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";import { readFile, writeFile } from "node:fs/promises";import { parseArgs } from "node:util";import { deliveryFormat, emailContent } from "../../emails/brand";+import { workflowAudience } from "../../emails/delivery-safety";import { normalizeLmx } from "../emails/content";import { LoopsApi, LoopsApiError } from "./api";import {@@ -349,11 +350,7 @@ try {`${journey.key}:trigger`,);const guard = await insert("AudienceFilter", `${journey.key}:guard`);- const filter = audienceFilter(journey.audience, journey.promotional);- filter.conditions.push(- condition("capLifecycleEnabled", true),- condition("capOnboardingEligible", true),- );+ const filter = workflowAudience(journey);await update(guard.id,{ audienceFilter: filter, appliesDownstream: true },diff --git a/scripts/loops/verify.ts b/scripts/loops/verify.tsindex 2b368707b..8533ab9ab 100644--- a/scripts/loops/verify.ts+++ b/scripts/loops/verify.ts@@ -1,8 +1,12 @@import assert from "node:assert/strict";import { readFile } from "node:fs/promises";import { fileURLToPath } from "node:url";-import { parseArgs } from "node:util";+import { isDeepStrictEqual, parseArgs } from "node:util";import { components, deliveryFormat, theme } from "../../emails/brand";+import {+ heldWorkflowAudience,+ workflowAudience,+} from "../../emails/delivery-safety";import registry from "../../emails/resources.json";import { assertEmailContent, normalizeLmx } from "../emails/content";import { LoopsApi, LoopsApiError } from "./api";@@ -52,6 +56,7 @@ const { values } = parseArgs({team: { type: "string", default: registry.teamName },"mailing-list": { type: "string", default: registry.resources.mailingList },"structure-only": { type: "boolean", default: false },+ "require-held": { type: "boolean", default: false },},});assert(values.state && values.team && values["mailing-list"]);@@ -101,6 +106,7 @@ if (deliveryFormat === "lmx") {}let emails = 0;let customEmails = 0;+let heldWorkflows = 0;const verifyEmail = async (id: string | undefined,expected: { subject: string; previewText: string; body: string },@@ -170,12 +176,14 @@ for (const journey of journeys) {connect(guardId);node(guardId, "AudienceFilter");const guard = await api.request<Node>(`workflows/${id}/nodes/${guardId}`);- const filter = audienceFilter(journey.audience, journey.promotional);- filter.conditions.push(- condition("capLifecycleEnabled", true),- condition("capOnboardingEligible", true),+ const held = isDeepStrictEqual(+ guard.audienceFilter,+ heldWorkflowAudience(journey),);- assert.deepEqual(guard.audienceFilter, filter);+ if (held) heldWorkflows++;+ else assert.deepEqual(guard.audienceFilter, workflowAudience(journey));+ if (values["require-held"])+ assert(held, "Workflow delivery guard is not held");assert.equal(guard.appliesDownstream, true);for (const message of journey.messages) {const operation = `${journey.key}:${message.key}`;@@ -230,6 +238,7 @@ for (const journey of journeys) {workflow: journey.name,status: "Draft",graphVerified: true,+ deliveryHeld: held,}),);}@@ -263,6 +272,7 @@ console.log(apiEmailContentVerified: emails,customEmailContentRequiresBrowserReview: customEmails,guardianVerifiedEmails: emails,+ deliveryHeldWorkflows: heldWorkflows,allDraft: true,}),);diff --git a/scripts/loops/watchdog.test.ts b/scripts/loops/watchdog.test.tsnew file mode 100644index 000000000..9a088f6f6--- /dev/null+++ b/scripts/loops/watchdog.test.ts@@ -0,0 +1,252 @@+import { describe, expect, test } from "bun:test";+import {+ heldWorkflowAudience,+ workflowAudience,+} from "../../emails/delivery-safety";+import type { LoopsApi } from "./api";+import {+ checkSyncHealth,+ enforceDeliverySafety,+ filterIsHeld,+ healthyReport,+ safetyTargets,+} from "./watchdog";++function fakeProvider() {+ const guards = new Map(+ safetyTargets.map((target) => [+ target.workflowId,+ {+ typeName: "AudienceFilter",+ workflowRevisionId: "revision-1",+ audienceFilter: workflowAudience(target.journey),+ appliesDownstream: true,+ },+ ]),+ );+ const writes: string[] = [];+ let brokenWorkflow: string | undefined;+ const api: Pick<LoopsApi, "request"> = {+ async request<T>(path: string, method = "GET", body?: unknown): Promise<T> {+ if (path === "api-key") return { teamName: "Cap Software, Inc." } as T;+ const target = safetyTargets.find((item) =>+ path.includes(item.workflowId),+ );+ if (!target) throw new Error("Unknown workflow");+ if (path.includes("/nodes/")) {+ const guard = guards.get(target.workflowId);+ if (!guard) throw new Error("Unknown guard");+ if (method === "POST") {+ if (target.workflowId === brokenWorkflow)+ throw new Error("Unavailable");+ const update = body as {+ expectedRevisionId: string;+ payload: Pick<typeof guard, "audienceFilter" | "appliesDownstream">;+ };+ expect(update.expectedRevisionId).toBe(guard.workflowRevisionId);+ Object.assign(guard, update.payload, {+ workflowRevisionId: "revision-2",+ });+ writes.push(target.workflowId);+ }+ return structuredClone(guard) as T;+ }+ return {+ name: target.journey.name,+ mailingListId: target.mailingListId,+ rootNodeId: "trigger",+ nodes: { trigger: { nextNodeIds: [target.guardId] } },+ } as T;+ },+ };+ return {+ api,+ guards,+ writes,+ fail: (id: string) => {+ brokenWorkflow = id;+ },+ };+}++describe("independent delivery safety", () => {+ test("a manual hold blocks healthy journeys and rejects conflicting resume", async () => {+ const provider = fakeProvider();+ await expect(+ enforceDeliverySafety(provider.api, {+ healthy: true,+ apply: true,+ hold: true,+ resume: true,+ }),+ ).rejects.toThrow("Choose either");+ expect(provider.writes).toHaveLength(0);+ const results = await enforceDeliverySafety(provider.api, {+ healthy: true,+ apply: true,+ hold: true,+ });+ expect(results.every((result) => result.action === "held")).toBe(true);+ });++ test("healthy operation never rewrites audiences", async () => {+ const provider = fakeProvider();+ const result = await enforceDeliverySafety(provider.api, {+ healthy: true,+ apply: true,+ });+ expect(result.every((item) => item.action === "healthy")).toBe(true);+ expect(provider.writes).toHaveLength(0);+ });++ test("an outage blocks every downstream journey and recovery never resumes it automatically", async () => {+ const provider = fakeProvider();+ const result = await enforceDeliverySafety(provider.api, {+ healthy: false,+ apply: true,+ });+ expect(result.every((item) => item.action === "held")).toBe(true);+ for (const target of safetyTargets) {+ const guard = provider.guards.get(target.workflowId);+ expect(guard?.audienceFilter).toEqual(+ heldWorkflowAudience(target.journey),+ );+ expect(guard?.appliesDownstream).toBe(true);+ }+ const recovered = await enforceDeliverySafety(provider.api, {+ healthy: true,+ apply: true,+ });+ expect(recovered.every((item) => item.action === "already-held")).toBe(+ true,+ );+ expect(provider.writes).toHaveLength(4);+ });++ test("resuming requires explicit apply and a fresh healthy result", async () => {+ const provider = fakeProvider();+ await expect(+ enforceDeliverySafety(provider.api, {+ healthy: false,+ apply: true,+ resume: true,+ }),+ ).rejects.toThrow("Resume requires");+ await expect(+ enforceDeliverySafety(provider.api, {+ healthy: true,+ apply: false,+ resume: true,+ }),+ ).rejects.toThrow("Resume requires");+ await enforceDeliverySafety(provider.api, { healthy: false, apply: true });+ const result = await enforceDeliverySafety(provider.api, {+ healthy: true,+ apply: true,+ resume: true,+ });+ expect(result.every((item) => item.action === "resumed")).toBe(true);+ for (const target of safetyTargets)+ expect(provider.guards.get(target.workflowId)?.audienceFilter).toEqual(+ workflowAudience(target.journey),+ );+ });++ test("a failed guard update does not prevent holding the other journeys", async () => {+ const provider = fakeProvider();+ provider.fail(safetyTargets[0].workflowId);+ const result = await enforceDeliverySafety(provider.api, {+ healthy: false,+ apply: true,+ });+ expect(result.filter((item) => item.action === "error")).toHaveLength(1);+ expect(result.filter((item) => item.action === "held")).toHaveLength(3);+ });++ test("audience drift closes delivery and cannot be silently overwritten on resume", async () => {+ const provider = fakeProvider();+ const guard = provider.guards.get(safetyTargets[0].workflowId);+ if (!guard) throw new Error("Missing fixture");+ guard.audienceFilter.conditions.push({+ type: "property",+ key: "capHasVideo",+ operator: "isTrue",+ });+ await enforceDeliverySafety(provider.api, { healthy: true, apply: true });+ expect(filterIsHeld(guard.audienceFilter)).toBe(true);+ const resumed = await enforceDeliverySafety(provider.api, {+ healthy: true,+ apply: true,+ resume: true,+ });+ expect(resumed[0].action).toBe("error");+ expect(filterIsHeld(guard.audienceFilter)).toBe(true);+ });++ test("a dry run reports the hold without changing Loops", async () => {+ const provider = fakeProvider();+ const result = await enforceDeliverySafety(provider.api, {+ healthy: false,+ apply: false,+ });+ expect(result.every((item) => item.action === "would-hold")).toBe(true);+ expect(provider.writes).toHaveLength(0);+ });+});++describe("health response boundaries", () => {+ const now = Date.parse("2026-09-11T15:00:00Z");+ const report = {+ healthy: true,+ checkedAt: new Date(now).toISOString(),+ totalJobs: 1,+ overdueJobs: 0,+ failingJobs: 0,+ };++ test("requires a recent nonempty queue without backlog or repeated failures", () => {+ expect(healthyReport(report, now)).toBe(true);+ for (const invalid of [+ null,+ {},+ { ...report, checkedAt: "invalid" },+ { ...report, checkedAt: new Date(now - 60_001).toISOString() },+ { ...report, checkedAt: new Date(now + 5_001).toISOString() },+ { ...report, totalJobs: 0 },+ { ...report, overdueJobs: 1 },+ { ...report, failingJobs: 1 },+ ])+ expect(healthyReport(invalid, now)).toBe(false);+ });++ test("HTTP errors, malformed JSON and network failures hold delivery", async () => {+ expect(+ await checkSyncHealth(+ "secret",+ async () => new Response("error", { status: 500 }),+ ),+ ).toBe(false);+ expect(+ await checkSyncHealth("secret", async () => new Response("not JSON")),+ ).toBe(false);+ expect(+ await checkSyncHealth("secret", async () => {+ throw new Error("offline");+ }),+ ).toBe(false);+ });++ test("health reads never follow redirects with the secret", async () => {+ expect(+ await checkSyncHealth("secret", async (url, options) => {+ expect(url).toBe("https://cap.so/api/cron/sync-loops/health");+ expect(options.redirect).toBe("error");+ expect(options.cache).toBe("no-store");+ return Response.json({+ ...report,+ checkedAt: new Date().toISOString(),+ });+ }),+ ).toBe(true);+ });+});diff --git a/scripts/loops/watchdog.ts b/scripts/loops/watchdog.tsnew file mode 100644index 000000000..673962673--- /dev/null+++ b/scripts/loops/watchdog.ts@@ -0,0 +1,202 @@+import assert from "node:assert/strict";+import { isDeepStrictEqual, parseArgs } from "node:util";+import { condition } from "../../emails/audiences";+import {+ heldWorkflowAudience,+ workflowAudience,+} from "../../emails/delivery-safety";+import { journeys } from "../../emails/flows";+import registry from "../../emails/resources.json";+import type { Journey } from "../../emails/types";+import { LoopsApi } from "./api";++export const healthUrl = "https://cap.so/api/cron/sync-loops/health";++export function healthyReport(value: unknown, now = Date.now()) {+ if (!value || typeof value !== "object") return false;+ const report = value as Record<string, unknown>;+ const checkedAt =+ typeof report.checkedAt === "string" ? Date.parse(report.checkedAt) : NaN;+ return (+ report.healthy === true &&+ typeof report.totalJobs === "number" &&+ Number.isSafeInteger(report.totalJobs) &&+ report.totalJobs > 0 &&+ report.overdueJobs === 0 &&+ report.failingJobs === 0 &&+ Number.isFinite(checkedAt) &&+ checkedAt >= now - 60_000 &&+ checkedAt <= now + 5_000+ );+}++export async function checkSyncHealth(+ secret: string,+ request: (url: string, options: RequestInit) => Promise<Response> = fetch,+) {+ if (!secret) return false;+ try {+ const response = await request(healthUrl, {+ headers: { Authorization: `Bearer ${secret}` },+ cache: "no-store",+ redirect: "error",+ signal: AbortSignal.timeout(15_000),+ });+ return response.ok && healthyReport(await response.json());+ } catch {+ return false;+ }+}++export type SafetyTarget = {+ journey: Journey;+ workflowId: string;+ guardId: string;+ mailingListId: string;+};++export const safetyTargets: SafetyTarget[] = journeys.map((journey) => ({+ journey,+ workflowId:+ registry.resources[journey.key as keyof typeof registry.resources],+ guardId:+ registry.operations[+ `${journey.key}:guard` as keyof typeof registry.operations+ ],+ mailingListId: registry.resources.mailingList,+}));++type Filter = {+ match: "all" | "any";+ conditions: { type: string; key?: string; operator?: string }[];+};+type Guard = {+ typeName: string;+ workflowRevisionId: string;+ audienceFilter: Filter | null;+ appliesDownstream: boolean;+};++export function filterIsHeld(filter: Filter | null) {+ return (+ filter?.match === "all" &&+ ["isTrue", "isFalse"].every((operator) =>+ filter.conditions.some(+ (item) =>+ item.type === "property" &&+ item.key === "subscribed" &&+ item.operator === operator,+ ),+ )+ );+}++export async function enforceDeliverySafety(+ api: Pick<LoopsApi, "request">,+ options: {+ healthy: boolean;+ apply: boolean;+ resume?: boolean;+ hold?: boolean;+ targets?: SafetyTarget[];+ },+) {+ if (options.hold && options.resume)+ throw new Error("Choose either --hold or --resume");+ if (options.resume && (!options.healthy || !options.apply))+ throw new Error("Resume requires healthy synchronization and --apply");+ const identity = await api.request<{ teamName: string }>("api-key");+ assert.equal(identity.teamName, registry.teamName);+ const results: { workflow: string; action: string }[] = [];+ for (const target of options.targets ?? safetyTargets) {+ try {+ const path = `workflows/${target.workflowId}`;+ const workflow = await api.request<{+ name: string;+ mailingListId: string;+ rootNodeId: string;+ nodes: Record<string, { nextNodeIds: string[] }>;+ }>(path);+ assert.equal(workflow.name, target.journey.name);+ assert.equal(workflow.mailingListId, target.mailingListId);+ assert.deepEqual(workflow.nodes[workflow.rootNodeId]?.nextNodeIds, [+ target.guardId,+ ]);+ const nodePath = `${path}/nodes/${target.guardId}`;+ const guard = await api.request<Guard>(nodePath);+ assert.equal(guard.typeName, "AudienceFilter");+ const active = workflowAudience(target.journey);+ const held = heldWorkflowAudience(target.journey);+ const alreadyHeld =+ filterIsHeld(guard.audienceFilter) && guard.appliesDownstream;+ const activeMatches =+ isDeepStrictEqual(guard.audienceFilter, active) &&+ guard.appliesDownstream;+ let nextFilter: Filter | undefined;+ let action: string;+ if (options.resume) {+ assert(+ activeMatches || isDeepStrictEqual(guard.audienceFilter, held),+ "Reconcile changed audience rules before resuming",+ );+ nextFilter = active;+ action = "resumed";+ } else if (alreadyHeld) {+ action = "already-held";+ } else if (options.healthy && !options.hold && activeMatches) {+ action = "healthy";+ } else {+ nextFilter = activeMatches+ ? held+ : {+ match: "all",+ conditions: [+ ...(guard.audienceFilter?.conditions ?? []),+ condition("subscribed", true),+ condition("subscribed", false),+ ],+ };+ action = options.apply ? "held" : "would-hold";+ }+ if (nextFilter && options.apply) {+ await api.request(nodePath, "POST", {+ expectedRevisionId: guard.workflowRevisionId,+ payload: { audienceFilter: nextFilter, appliesDownstream: true },+ });+ const confirmed = await api.request<Guard>(nodePath);+ assert.deepEqual(confirmed.audienceFilter, nextFilter);+ assert.equal(confirmed.appliesDownstream, true);+ }+ results.push({ workflow: target.journey.key, action });+ } catch {+ results.push({ workflow: target.journey.key, action: "error" });+ }+ }+ return results;+}++if (import.meta.main) {+ const { values } = parseArgs({+ options: {+ apply: { type: "boolean", default: false },+ resume: { type: "boolean", default: false },+ hold: { type: "boolean", default: false },+ },+ });+ const healthy = values.hold+ ? false+ : await checkSyncHealth(process.env.LOOPS_HEALTH_SECRET ?? "");+ const results = await enforceDeliverySafety(+ new LoopsApi(process.env.LOOPS_API_KEY ?? ""),+ { healthy, apply: values.apply, resume: values.resume, hold: values.hold },+ );+ console.log(JSON.stringify({ healthy, results }));+ const successfulActions = values.hold+ ? ["held", "already-held"]+ : ["healthy", "resumed"];+ if (+ (!healthy && !values.hold) ||+ results.some((result) => !successfulActions.includes(result.action))+ )+ process.exitCode = 1;+}