Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
chore: move marketing emails and Loops tooling to the private cap-marketing repo
Richie McIlroy1c1a01492e41
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d0d6e27d6..f1bdd0e32 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -93,11 +93,10 @@ jobs:- name: Test workspace toolingrun: node --test scripts/bun-scripts.test.mjs scripts/check-tauri-plugin-versions.test.mjs- - name: Check email library+ - name: Test Loops profile syncrun: |- bun run emails:check- bun test scripts/emails scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts scripts/loops/watchdog.test.ts- bun 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+ bun test scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts+ bun run tsc --noEmit --strict --jsx react-jsx --allowImportingTsExtensions --target ESNext --module ESNext --moduleResolution bundler --resolveJsonModule --types bun --skipLibCheck scripts/loops/*.ts- name: Test render farm orchestrationrun: |diff --git a/.github/workflows/database-profile-reliability.yml b/.github/workflows/database-profile-reliability.ymlindex 26d2b2c4c..83c853aae 100644--- a/.github/workflows/database-profile-reliability.yml+++ b/.github/workflows/database-profile-reliability.yml@@ -56,4 +56,3 @@ jobs:scripts/loops/sources.test.tsscripts/loops/profile.test.tsscripts/loops/lifecycle.test.ts- scripts/loops/watchdog.test.tsdiff --git a/.github/workflows/loops-safety.yml b/.github/workflows/loops-safety.ymldeleted file mode 100644index 27f24d5c3..000000000--- a/.github/workflows/loops-safety.yml+++ /dev/null@@ -1,31 +0,0 @@-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@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0- with:- persist-credentials: false- - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0- with:- bun-version: "1.4.0"- - name: Check lifecycle delivery and report required manual pauses- env:- LOOPS_API_KEY: ${{ secrets.LOOPS_API_KEY }}- LOOPS_HEALTH_SECRET: ${{ secrets.LOOPS_HEALTH_SECRET }}- run: bun scripts/loops/watchdog.ts --applydiff --git a/AGENTS.md b/AGENTS.mdindex 3c2d080f2..de4484400 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -54,6 +54,7 @@ Additionally, `unused_must_use = "deny"` applies to all Rust code: every `Result- `packages/*` shared libs (e.g., `database`, `ui`, `ui-solid`, `utils`, `web-*`).- `crates/*` Rust media/recording/rendering/camera crates.- `scripts/*`, `infra/`, and `packages/local-docker/` for tooling and local services.+- Marketing and lifecycle emails (copy, Loops journeys and campaigns, the email catalogue and voice guide) and their Loops tooling live in the private repo [CapSoftware/cap-marketing](https://github.com/CapSoftware/cap-marketing). View and edit them there. This repo keeps only the runtime profile sync in `packages/database/loops/` (with its tests and runners in `scripts/loops/`) and the transactional emails in `packages/database/emails/`.## Build, Test, Develop- Install: `bun install`; setup: `bun run env-setup` then `bun run cap-setup`.diff --git a/emails/AGENTS.md b/emails/AGENTS.mddeleted file mode 100644index 57b21350b..000000000--- a/emails/AGENTS.md+++ /dev/null@@ -1,11 +0,0 @@-# Working on Cap emails--- Start with `README.md`, `CATALOG.md` and `VOICE.md`. Use the catalogue to identify the email, flow, audience and actual send source before editing.-- Keep marketing content in `marketing/`, branding and sender defaults in `brand.ts`, customer-specific prose in `customer-copy.ts`, and ordering/delays in `flows.ts`. Do not add another copy of these definitions under `scripts/`.-- Keep email IDs and existing flow step keys stable. Declare variables and provide appropriate fallbacks. Preserve opt-outs, teammate exclusions, customer segmentation and imported-contact holds.-- Delivery uses custom MJML from `mjml.ts`. Generate archives with `bun run emails:export --output /absolute/path`, then upload the intended archive through Code in the Loops draft editor. The Loops API cannot read or update MJML emails; do not convert them back to native format to bypass this limitation. Reconcile intentional dashboard edits into source first.-- Regenerate `CATALOG.md` using `bun run emails:catalog`; never edit it by hand. Run `bun run emails:check`, scoped Biome, and relevant tests. After a remote draft update, run `bun run emails:check-loops --structure-only` and review every changed email in the browser, including metadata, variable fallbacks, loaded images and footer. API structure checks cannot establish MJML content parity.-- Keep the canonical Cap icon and vector wordmark together; never recreate the lettering with a font. Use `capGreeting` with `Hey,` as the complete fallback; never concatenate a space with an optional first name. Preserve the single address/unsubscribe footer without an opt-in explanation.-- Keep Resend application templates and sending behavior in their current locations; update `application.ts` when introducing or removing a send path. Listing a template does not establish that its handler is reachable or deployed.-- These commands do not authorize sending, publishing, activating flows, enrolling contacts or deploying production schema. Follow the user's current scope.-- Store only nonsecret resource IDs here. Keep credentials, contact exports and suppression registries outside Git.diff --git a/emails/CATALOG.md b/emails/CATALOG.mddeleted file mode 100644index 197368387..000000000--- a/emails/CATALOG.md+++ /dev/null@@ -1,729 +0,0 @@-# Cap email catalogue--Generated from the email library with `bun run emails:catalog`. Edit the source files, then regenerate. [Editing guide](README.md).--## Lifecycle flows--These are the locally configured journeys. This document is not a live status check. Imports remain held. Run `bun run emails:check-loops --structure-only --allow-live` to verify the remote workflow structure and status; review custom MJML content in the browser.--| Flow | Audience | Schedule after entry | Emails |-| --- | --- | --- | --- |-| [Independent free-user onboarding](https://app.loops.so/workflows/cmtvpih6201fp0jznodf8fpwz) | free | Day 0, Day 2, Day 5, Day 9 | 4 |-| [Customer onboarding](https://app.loops.so/workflows/cmtvpilm601f40jzwx3474cko) | customer | Day 0, Day 3, Day 7 | 3 |-| [Free activation and Pro conversion v2](https://app.loops.so/workflows/cmtxlhkcw0dta0jzkd6an7xz0) | free | Day 0, Day 1, Day 3, Day 8, Day 10, Day 12 | 6 |-| [Teammate onboarding](https://app.loops.so/workflows/cmtvpm0ag01it0j37w02o6wav) | teammate | Day 0, Day 3 | 2 |-| [Former customer follow-up](https://app.loops.so/workflows/cmtvpm8zm01ii0j01cz7d15qr) | former | Day 14 | 1 |--Completed signups reach Loops through Stripe; SSO uses a small direct fallback. Cap supplies targeting through a durable sync queue, without a separate marketing opt-in step. Existing opt-outs and suppressions take precedence. Historical imports stay held; a new accepted invitation can start teammate help only.--Journeys require global subscription, capConsent=subscribed, the exact audience, lifecycle enabled and onboarding eligible. capConsent is a legacy migration guard, not a separate consent-capture requirement for new signups. These filters continue to apply downstream. Free/former promotional flows additionally exclude teammates and require promotional eligibility.--Teammate history takes priority over paid/free classification. Ambiguous contacts receive no journey. [Audience classification and consent](../scripts/loops/README.md#audience-rules).--The independent watchdog checks every registered journey and alerts when an active flow requires a manual pause. It can hold paused/draft journeys with an impossible subscription condition. Recovery never resumes delivery automatically. Check sync health before campaign sends. See the [outage and resume procedure](../scripts/loops/README.md#outage-protection) and [onboarding runtime](onboarding-runtime.md).--### Independent free-user onboarding--Entry: capLifecycleStage changes into free. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.--Downstream conditions: subscribed isTrue; capConsent equals subscribed; capAudience equals free; capTeammate isFalse; capPromotionalEligible isTrue; capLifecycleEnabled isTrue; capOnboardingEligible isTrue.--```mermaid-flowchart TD- entry["Stage becomes free"] --> guard["Consent and audience guards"]- guard --> email0["Day 0: welcome"]- email0 --> wait1["Wait 2 days"]- wait1 --> branch1{"capHasVideo is false?"}- branch1 -->|Yes| email1["Day 2: record"]- branch1 -->|No: skip| next1((Continue))- email1 --> next1- next1 --> wait2["Wait 3 days"]- wait2 --> branch2{"capHasSharedVideo is false?"}- branch2 -->|Yes| email2["Day 5: share"]- branch2 -->|No: skip| next2((Continue))- email2 --> next2- next2 --> wait3["Wait 4 days"]- wait3 --> email3["Day 9: plans"]- email3 --> exit["End"]-```--| Day | Subject and source | Send condition |-| --- | --- | --- |-| 0 | [Welcome to Cap](../emails/marketing/free-welcome.ts) | Journey guards |-| 2 | [A quick way to try Cap](../emails/marketing/free-record.ts) | `capHasVideo=false` |-| 5 | [Send your next explanation as a Cap](../emails/marketing/free-share.ts) | `capHasSharedVideo=false` |-| 9 | [Using Cap for work?](../emails/marketing/free-plans.ts) | Journey guards |--### Customer onboarding--Entry: capLifecycleStage changes into customer. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.--Downstream conditions: subscribed isTrue; capConsent equals subscribed; capAudience equals customer; capLifecycleEnabled isTrue; capOnboardingEligible isTrue.--```mermaid-flowchart TD- entry["Stage becomes customer"] --> guard["Consent and audience guards"]- guard --> email0["Day 0: welcome"]- email0 --> wait1["Wait 3 days"]- wait1 --> email1["Day 3: workflow"]- email1 --> wait2["Wait 4 days"]- wait2 --> email2["Day 7: feedback"]- email2 --> exit["End"]-```--| Day | Subject and source | Send condition |-| --- | --- | --- |-| 0 | [Thanks for choosing {contact.capPlanName}](../emails/marketing/customer-welcome.ts) | Journey guards |-| 3 | [One less thing to explain twice](../emails/marketing/customer-workflow.ts) | Journey guards |-| 7 | [How is Cap working for you?](../emails/marketing/customer-feedback.ts) | Journey guards |--### Free activation and Pro conversion v2--Entry: capLifecycleStage changes into free-v2. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.--Downstream conditions: subscribed isTrue; capConsent equals subscribed; capAudience equals free; capTeammate isFalse; capPromotionalEligible isTrue; capLifecycleEnabled isTrue; capOnboardingEligible isTrue; capLifecycleStage equals free-v2.--```mermaid-flowchart TD- entry["Stage becomes free-v2"] --> guard["Consent and audience guards"]- guard --> email0["Day 0: welcome"]- email0 --> wait1["Wait 1 days"]- wait1 --> branch1{"capNeedsRecordingHelp is true?"}- branch1 -->|Yes| email1["Day 1: record"]- branch1 -->|No: skip| next1((Continue))- email1 --> next1- next1 --> wait2["Wait 2 days"]- wait2 --> branch2{"capReadyForPro is true?"}- branch2 -->|Yes| email2["Day 3: plans"]- branch2 -->|No: skip| next2((Continue))- email2 --> next2- next2 --> wait3["Wait 5 days"]- wait3 --> branch3{"capNeedsSharingHelp is true?"}- branch3 -->|Yes| email3["Day 8: share"]- branch3 -->|No: skip| next3((Continue))- email3 --> next3- next3 --> wait4["Wait 2 days"]- wait4 --> branch4{"capReadyForPro is true?"}- branch4 -->|Yes| email4["Day 10: ai"]- branch4 -->|No: skip| next4((Continue))- email4 --> next4- next4 --> wait5["Wait 2 days"]- wait5 --> branch5{"capNeedsRecordingHelp is true?"}- branch5 -->|Yes| email5["Day 12: help"]- branch5 -->|No: skip| next5((Continue))- email5 --> next5- next5 --> exit["End"]-```--| Day | Subject and source | Send condition |-| --- | --- | --- |-| 0 | [Your first Cap only needs 30 seconds](../emails/marketing/free-v2-welcome.ts) | Journey guards |-| 1 | [One small thing to record today](../emails/marketing/free-v2-record.ts) | `capNeedsRecordingHelp=true` |-| 3 | [Some explanations need more than five minutes](../emails/marketing/free-v2-plans.ts) | `capReadyForPro=true` |-| 8 | [Put your recording to work](../emails/marketing/free-v2-share.ts) | `capNeedsSharingHelp=true` |-| 10 | [Record the walkthrough. Skip the extra write-up.](../emails/marketing/free-v2-ai.ts) | `capReadyForPro=true` |-| 12 | [Anything getting in the way?](../emails/marketing/free-v2-help.ts) | `capNeedsRecordingHelp=true` |--### Teammate onboarding--Entry: capLifecycleStage changes into teammate. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.--Downstream conditions: subscribed isTrue; capConsent equals subscribed; capAudience equals teammate; capLifecycleEnabled isTrue; capOnboardingEligible isTrue.--```mermaid-flowchart TD- entry["Stage becomes teammate"] --> guard["Consent and audience guards"]- guard --> email0["Day 0: welcome"]- email0 --> wait1["Wait 3 days"]- wait1 --> email1["Day 3: handoff"]- email1 --> exit["End"]-```--| Day | Subject and source | Send condition |-| --- | --- | --- |-| 0 | [Welcome to your team in Cap](../emails/marketing/teammate-welcome.ts) | Journey guards |-| 3 | [Make your next handoff easier](../emails/marketing/teammate-handoff.ts) | Journey guards |--### Former customer follow-up--Entry: capLifecycleStage changes into former. Re-entry is disabled. Delays below are relative to the previous step; day numbers are cumulative from entry.--Downstream conditions: subscribed isTrue; capConsent equals subscribed; capAudience equals former; capTeammate isFalse; capPromotionalEligible isTrue; capLifecycleEnabled isTrue; capOnboardingEligible isTrue.--```mermaid-flowchart TD- entry["Stage becomes former"] --> guard["Consent and audience guards"]- guard --> wait0["Wait 14 days"]- wait0 --> email0["Day 14: feedback"]- email0 --> exit["End"]-```--| Day | Subject and source | Send condition |-| --- | --- | --- |-| 14 | [Could I ask about your time with Cap?](../emails/marketing/former-feedback.ts) | Journey guards |--## Campaign templates--Campaigns are manually scheduled product updates, with no automatic enrollment. Both require subscription, capConsent=subscribed and their exact audience. The free template also requires promotional eligibility and excludes teammates.--| Campaign | Audience | Subject and source | Loops ID |-| --- | --- | --- | --- |-| Cap v0.6 launch \| Customers | customer | [Meet Cap v0.6, our biggest update yet](../emails/marketing/customer-update.ts) | `cmtvpmfxc01ls0j0nnlffombv` |-| Cap v0.6 launch \| Noncustomers | free | [Meet Cap v0.6, our biggest update yet](../emails/marketing/free-update.ts) | `cmtvpmjej01kr0j18cxoz2n0y` |-| Case study and logo wall invite \| Cap Pro multi-seat org owners | customer | [Could we feature your team in a Cap case study?](../emails/marketing/customer-case-study.ts) | `cmumrftj50y4j0jy2giifxlnk` |--## Branding and personalization--Shared design, logo, signature, footer, sender and fallbacks: [emails/brand.ts](../emails/brand.ts). Custom MJML delivery is generated by [emails/mjml.ts](../emails/mjml.ts).--Sender: Richie from Cap; local part `richie` on the Loops sending domain. Reply-to: [email protected].--The shared header uses the canonical Cap icon and vector wordmark, with white backing for contrast on dark backgrounds. The complete greeting is `capGreeting`, with `Hey,` as its fallback. One compact footer contains the company, address and unsubscribe link.--Customer welcome variations come from [customer-copy.ts](customer-copy.ts); eligibility is resolved from account and license state in the profile sync.--| Plan | Welcome variation |-| --- | --- |-| Cap Pro | With Cap Pro, you can share recordings with a link and work on them with your team. Your plan also includes the desktop commercial license, so you can use Cap for client work too. |-| Cap Self-hosted | For your self-hosted setup, start with the instructions supplied with your purchase. If you get stuck anywhere, reply with what you're seeing and I'll help you sort it. |-| Cap Desktop | Your desktop license lets you use Cap's recorder and editor for commercial work. You can activate it in the app with the license details from your purchase email. |-| Cap | If you need a hand getting set up, just reply and I'll help you sort it. |--## Marketing email copy--The excerpts below show content, not an email-client render. Branding and required Loops footer content are composed separately.--### free-welcome--Help an independent free user make their first recording.--**Subject:** Welcome to Cap--**Preview:** Richie here. Great to have you with us :)--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-welcome.ts](../emails/marketing/free-welcome.ts)--{contact.capGreeting}--Richie here, founder of Cap. Thanks for giving it a go :)--The easiest way to start is to record something you'd normally type out. A quick explanation or a bit of feedback is plenty.--Use Instant Mode when you want a shareable link, or Studio Mode to edit your recording and export it locally.--Download Cap here.--If you have any questions, just reply to this email. I'd love to help.--### free-record--Offer recording help when no cloud video is known.--**Subject:** A quick way to try Cap--**Preview:** You don't need a script or a perfect take.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-record.ts](../emails/marketing/free-record.ts)--{contact.capGreeting}--If you're still finding your feet with Cap, try this: open something on your screen and spend 30 seconds explaining it out loud.--No script or perfect take needed. In Studio Mode, you can trim it afterwards and keep the recording on your own device.--Need the app? You can download Cap here.--If something's stopping you from recording, reply and let me know what happened. I'll help you sort it.--### free-share--Offer sharing guidance when no shared cloud video is known.--**Subject:** Send your next explanation as a Cap--**Preview:** A short recording and one sentence are enough.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-share.ts](../emails/marketing/free-share.ts)--{contact.capGreeting}--Next time you're typing a long explanation, try showing it in Cap instead.--Record the bit that's hard to explain, then send the link with a sentence about what you need. Something like: “Here's the bug I mentioned. Can you see the same thing?”--It doesn't have to be polished to be useful.--Open your Cap library.--### free-plans--Explain current plan options to eligible independent noncustomers.--**Subject:** Using Cap for work?--**Preview:** Here's how the Desktop License and Cap Pro compare.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-plans.ts](../emails/marketing/free-plans.ts)--{contact.capGreeting}--If you're thinking about using Cap for work, there are two options.--A Desktop License covers commercial use of the recorder and editor. It's a good fit if you mainly edit and export videos yourself.--Cap Pro adds cloud sharing and collaboration, and includes the desktop commercial license. That's the one to look at if you're sharing recordings with clients or your team.--Compare the plans here.--Not sure which you need? Reply with what you're using Cap for and I'll point you in the right direction.--### customer-welcome--Welcome a paying customer with copy matching their paid plan.--**Subject:** Thanks for choosing {contact.capPlanName}--**Preview:** Thanks for backing what we're building.--**Variables:** `contact.capCustomerWelcome` (fallback: If you need a hand getting set up, just reply and I'll help you sort it.); `contact.capPlanName` (fallback: Cap); `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/customer-welcome.ts](../emails/marketing/customer-welcome.ts)--{contact.capGreeting}--Richie here, founder of Cap. Thanks so much for supporting what we're building. It means a lot.--{contact.capCustomerWelcome}--What are you planning to use Cap for? Just reply and let me know. I'd love to hear.--### customer-workflow--Help a customer build a repeatable recording habit.--**Subject:** One less thing to explain twice--**Preview:** A recording you can keep coming back to.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/customer-workflow.ts](../emails/marketing/customer-workflow.ts)--{contact.capGreeting}--A quick idea for your next recording: pick a question you keep answering and record the walkthrough once.--It could be how to set something up, where to find a setting, or how you want a piece of work done. Give it a title you'll recognise later, then save or share it wherever you normally answer that question.--The next time someone asks, you've already got it ready.--Anything making that harder than it should be? Reply and tell me.--### customer-feedback--Ask a customer what is useful and what needs improvement.--**Subject:** How is Cap working for you?--**Preview:** I'd love to hear what's working and what isn't.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/customer-feedback.ts](../emails/marketing/customer-feedback.ts)--{contact.capGreeting}--How are you getting on with Cap?--I'd love to know if there's anything you wish worked differently, or something that's getting in your way.--Just reply here. I read every reply, and hearing how people actually use Cap helps me decide what we should work on next.--Thanks again for backing us :)--### free-v2-welcome--Help a new independent free user record and share one useful explanation.--**Subject:** Your first Cap only needs 30 seconds--**Preview:** Record one thing, send the link, and you're off.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-v2-welcome.ts](../emails/marketing/free-v2-welcome.ts)--{contact.capGreeting}--Richie here, founder of Cap. Thanks for giving it a go :)--For your first recording, pick something you'd normally explain in a long message. Open Cap, choose Instant Mode, and spend 30 seconds showing it on screen.--Once it's ready, send the link to someone who needs that explanation. No polished presentation needed.--Download Cap and make your first recording--If you get stuck, reply here and I'll help.--### free-v2-record--Offer a small first cloud recording task when no completed video is visible.--**Subject:** One small thing to record today--**Preview:** Try explaining something you already know.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-v2-record.ts](../emails/marketing/free-v2-record.ts)--{contact.capGreeting}--If you're still finding your feet with Cap, try recording a quick walkthrough of something you already know: a setting, a page, or a problem you want to show someone.--Choose Instant Mode, keep it short, then send the link when it's ready.--Get started with your first recording--If screen or microphone permissions are getting in the way, reply with what you're seeing and I'll help you sort it.--### free-v2-plans--Offer Pro to active free users through a specific cloud-sharing benefit.--**Subject:** Some explanations need more than five minutes--**Preview:** Share the full walkthrough with Cap Pro.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-v2-plans.ts](../emails/marketing/free-v2-plans.ts)--{contact.capGreeting}--Five minutes works for a quick question. A full walkthrough sometimes needs longer.--Cap Pro removes the five-minute limit on cloud recordings and gives you unlimited shareable links, so you can send the whole explanation in one video.--It also includes the desktop commercial license for work recordings.--Pro is US$12 per user, billed monthly. Annual billing is also available.--Upgrade to Cap Pro--### free-v2-share--Help an active user put a completed recording into a real conversation.--**Subject:** Put your recording to work--**Preview:** Send the link with one sentence about what you need.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-v2-share.ts](../emails/marketing/free-v2-share.ts)--{contact.capGreeting}--A useful way to share a Cap is to add one sentence telling the other person what you need from them.--"Here's the bit I'm stuck on. Can you take a look?"--Or: "Here's how to change that setting. Does that solve it?"--Open your recordings--Send the link wherever you're already having the conversation.--### free-v2-ai--Show active free users how Pro reduces the work around a recording.--**Subject:** Record the walkthrough. Skip the extra write-up.--**Preview:** Give people a summary and chapters alongside your video.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-v2-ai.ts](../emails/marketing/free-v2-ai.ts)--{contact.capGreeting}--A recording saves you typing everything out. Writing a summary afterwards can feel like doing the job twice.--Cap Pro generates a title, summary, transcript and clickable chapters for your recordings. The person watching can get the context, then jump to the part they need.--That's especially useful for walkthroughs people come back to later.--See Cap Pro--### free-v2-help--Invite a reply from users who have not reached a completed cloud recording.--**Subject:** Anything getting in the way?--**Preview:** Reply and tell me where you're getting stuck.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-v2-help.ts](../emails/marketing/free-v2-help.ts)--{contact.capGreeting}--If you haven't found a useful way to fit Cap into your day yet, is anything getting in the way?--Maybe you're not sure what to record, something isn't working, or it isn't quite what you expected.--Reply and let me know. If I can help you get a useful first recording out of it, I'd like to.--### teammate-welcome--Help an invited teammate find their workspace without promoting upgrades.--**Subject:** Welcome to your team in Cap--**Preview:** Here's where to find your team's recordings.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/teammate-welcome.ts](../emails/marketing/teammate-welcome.ts)--{contact.capGreeting}--Richie here, founder of Cap. Great to have you with us :)--Open your dashboard and select your team's organisation. You'll find the recordings they've shared with you there.--If you can't see the right organisation, check with the person who invited you. They can confirm which email address they used and your access.--You can also reply here if you need a hand.--### teammate-handoff--Help a teammate share useful context with their organization.--**Subject:** Make your next handoff easier--**Preview:** Show your teammate the bit that's hard to put into words.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/teammate-handoff.ts](../emails/marketing/teammate-handoff.ts)--{contact.capGreeting}--Next time you hand something over to a teammate, try recording the part that's tricky to explain in a message.--Show what changed and what you need them to look at. Even a short recording can save a lot of back and forth.--Open your team workspace. Before sending a recording, check its sharing settings so the right people can watch it.--If anything about sharing with your team feels awkward, reply and let me know.--### former-feedback--Ask an eligible former cloud customer for feedback after paid access ends.--**Subject:** Could I ask about your time with Cap?--**Preview:** I'd appreciate your honest feedback.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/former-feedback.ts](../emails/marketing/former-feedback.ts)--{contact.capGreeting}--Could I ask what made you decide to stop using your paid Cap plan?--Was something missing, did something not work properly, or did you just not need it anymore?--If you've got a moment to reply, I'd really appreciate it. And if there was a problem I can help with, I'd like to try.--Thanks for giving Cap a go.--### customer-update--One-off Cap v0.6 launch announcement for customers, leading to the release video and update details.--**Subject:** Meet Cap v0.6, our biggest update yet--**Preview:** 3D scenes, animated titles and Studio Sound. See what's new in the launch video.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/customer-update.ts](../emails/marketing/customer-update.ts)--{contact.capGreeting}--Cap v0.6 is here, and it's our biggest release yet.--We've rebuilt the editor so you can do more with the recordings you already make. Add 3D scenes, animated titles and moving backgrounds, without opening another editing app.--Studio Sound reduces microphone noise, and the new export screen shows estimated file size and time before you save.--The easiest way to see the difference is the launch video. The release page also has the download and full details.--Watch Cap v0.6 in action →--Thanks for supporting Cap. I can't wait to see what you make with this one :)--### free-update--One-off Cap v0.6 launch announcement for eligible independent noncustomers, showing the demo workflow through the release video.--**Subject:** Meet Cap v0.6, our biggest update yet--**Preview:** Meet Cap v0.6: 3D scenes, animated titles and cleaner audio, all in one app.--**Variables:** `contact.capGreeting` (fallback: Hey,)--**Edit:** [emails/marketing/free-update.ts](../emails/marketing/free-update.ts)--{contact.capGreeting}--Cap v0.6 is here, and it's our biggest release yet.--We've rebuilt the editor to turn your screen recordings into polished demos. Record your screen, add a 3D scene, animated titles and a moving background, then export a video you'll want to share.--There's also Studio Sound to reduce microphone noise, plus faster exports. Whether it's a product demo, a client walkthrough or a team update, you can make it in Cap.--The release video is the best way to see what's new:--See Cap v0.6 in action →--### customer-case-study--Invite Cap Pro organisation owners with more than one seat to reply if they'd like their team featured in a website case study.--**Subject:** Could we feature your team in a Cap case study?--**Preview:** Reply and I'll send over a short Q&A.--**Variables:** `contact.capTeamGreeting` (fallback: Hey team,)--**Edit:** [emails/marketing/customer-case-study.ts](../emails/marketing/customer-case-study.ts)--{contact.capTeamGreeting}--We're putting together case studies for the Cap website, and I'd love to feature your team in one.--If you're enjoying Cap and would like to be involved, just reply to this email and I'll send you a short Q&A to fill in.--It'd really help Cap move into the next stage of our growth, and help us tell other great teams like yours all about Cap.--Thanks so much for supporting us :)--## Application emails--These are repository send paths and retained templates, not confirmation of production delivery. They continue through Resend and keep their existing React Email layouts. Loops audience filters do not control them. Shared marketing branding does not automatically restyle these templates.--| Email | Trigger | Recipients | Template |-| --- | --- | --- | --- |-| Login verification code | Web or mobile email authentication request | The person signing in | [otp-email](../packages/database/emails/otp-email.tsx) |-| Organization invitation | An organization invitation is issued through the web action or public API | The invited teammate | [organization-invite](../packages/database/emails/organization-invite.tsx) |-| Recording viewer invitation | A recording owner invites someone to view the recording | The invited viewer | [video-viewer-invite](../packages/database/emails/video-viewer-invite.tsx) |-| Requested download links | The person requests download links by email | The requesting email address | [download-link](../packages/database/emails/download-link.tsx) |-| First shareable recording | Desktop API creates the first eligible shareable recording | The recording owner | [first-shareable-link](../packages/database/emails/first-shareable-link.tsx) |-| New comment notification | An eligible comment notification is created | The notification recipient | [new-comment](../packages/database/emails/new-comment.tsx) |-| First view notification | An eligible recording receives its first view | The recording owner | [first-view](../packages/database/emails/first-view.tsx) |-| Payment failed / final retry | Stripe invoice payment fails | The billing account user | [payment-failed](../packages/database/emails/payment-failed.tsx) |-| Signed BAA delivery | A business associate agreement is signed | The signer, with the configured notice recipients copied | [signed-baa](../packages/database/emails/signed-baa.tsx) |-| Desktop feedback notification | Legacy desktop feedback handler | Cap support, with the user copied | [feedback](../packages/database/emails/feedback.tsx) |-| Messenger support notification | An eligible support conversation requests an email notification | Cap support; replies go to the user | [messenger-support-email](../packages/database/emails/messenger-support-email.tsx) |-| Account deletion request notification | An account deletion request is submitted | Cap support; replies go to the requester | [messenger-support-email](../packages/database/emails/messenger-support-email.tsx) |-| Mobile content report notification | A mobile content report is submitted | Cap support; replies go to the reporter | [messenger-support-email](../packages/database/emails/messenger-support-email.tsx) |-| Legacy login link template | No current send call found in this checkout | None configured | [login-link](../packages/database/emails/login-link.tsx) |--### Login verification code--OTP authentication; does not subscribe the recipient to marketing.--Send source: [packages/database/auth/auth-options.ts](../packages/database/auth/auth-options.ts), [apps/web/app/api/mobile/[...route]/route.ts](../apps/web/app/api/mobile/%5B...route%5D/route.ts).--### Organization invitation--An invitation is not permission to send promotions.--Send source: [apps/web/actions/organization/send-invites.ts](../apps/web/actions/organization/send-invites.ts), [apps/web/app/api/v1/[...route]/route.ts](../apps/web/app/api/v1/%5B...route%5D/route.ts).--### Recording viewer invitation--Transactional viewing access; does not subscribe the viewer to marketing.--Send source: [apps/web/actions/videos/viewer-invites.ts](../apps/web/actions/videos/viewer-invites.ts).--### Requested download links--Uses the existing Resend marketing sender flag; Loops audience filters do not govern this send.--Send source: [apps/web/actions/send-download-link.ts](../apps/web/actions/send-download-link.ts).--### First shareable recording--Scheduled in Resend for five minutes later; uses the existing marketing sender flag. Check overlap before activating Loops recording reminders.--Send source: [apps/web/app/api/desktop/[...route]/video.ts](../apps/web/app/api/desktop/%5B...route%5D/video.ts).--### New comment notification--Notification preferences and exclusions are applied by Notification.ts.--Send source: [apps/web/lib/Notification.ts](../apps/web/lib/Notification.ts).--### First view notification--Notification preferences and first-view checks are applied by Notification.ts.--Send source: [apps/web/lib/Notification.ts](../apps/web/lib/Notification.ts).--### Payment failed / final retry--Different subject and content for the final attempt; deduplicated by invoice and attempt.--Send source: [apps/web/app/api/webhooks/stripe/route.ts](../apps/web/app/api/webhooks/stripe/route.ts).--### Signed BAA delivery--Includes the signed PDF and tracks delivery state; preserve attachment and CC behavior.--Send source: [apps/web/actions/organization/signed-baa.ts](../apps/web/actions/organization/signed-baa.ts).--### Desktop feedback notification--Source-defined handler; inspect route reachability before relying on it.--Send source: [apps/web/app/api/desktop/[...route]/root.ts](../apps/web/app/api/desktop/%5B...route%5D/root.ts).--### Messenger support notification--The support service reserves notification state before sending.--Send source: [apps/web/lib/messenger/support-email.ts](../apps/web/lib/messenger/support-email.ts).--### Account deletion request notification--Deduplicated by deletion request ID.--Send source: [apps/web/lib/account-deletion-request.ts](../apps/web/lib/account-deletion-request.ts).--### Mobile content report notification--Deduplicated by report ID.--Send source: [apps/web/lib/account-deletion-request.ts](../apps/web/lib/account-deletion-request.ts).--### Legacy login link template--Retained source template; current email login uses verification codes.--Send source: No current call site.diff --git a/emails/QA.md b/emails/QA.mddeleted file mode 100644index 0ad6904dd..000000000--- a/emails/QA.md+++ /dev/null@@ -1,62 +0,0 @@-# Loops migration verification — 11 September 2026--All four production workflows and both campaign templates remain drafts. No actual customer received a test email. The four temporary QA workflows are paused, and all 36 owned QA contacts from the two test runs are held and globally unsubscribed.--## What was exercised--The controlled test used the real `classifyProfile` and `contactUpdate` logic with synthetic fixtures, wrote those properties to Loops, and received real workflow emails in owned Cap inbox aliases. Each QA flow required an exact recipient allowlist and a separate QA trigger property; production lifecycle stages stayed idle. Timers were compressed to two minutes, with the production audience guards and milestone branches retained.--| Scenario | Received | Result |-| -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | ---------------------------------------------------------- |-| Independent free user | 4 | Welcome, recording, sharing and plan guidance |-| Customer | 3 | Customer sequence only |-| Teammate | 2 | Workspace help only; no promotions |-| Former customer | 1 | Feedback request |-| Recording and sharing milestones already complete | 2 | Both reminders skipped; welcome and plan guidance retained |-| Purchase after welcome | 1 | Later free-user promotions stopped |-| Invitation after welcome | 1 | Later free-user promotions stopped |-| Global unsubscribe after welcome | 1 | Later messages stopped |-| Mailing-list unsubscribe after welcome | 1 | Later messages stopped |-| Held, denied consent, list opt-out, unknown audience, customer in free flow, teammate in free flow, disabled lifecycle, ineligible onboarding, unknown consent | 0 across all 9 cases | No enrollment emails |--Exactly 16 workflow emails arrived. Trigger replay during the journey and after completion did not produce extra mail. A later mailbox reconciliation still found exactly 16. Transitions happened before the next timer elapsed. This proves the tested Loops behavior when fresh properties reach Loops, not the latency or reliability of a production scheduler that has not been deployed.--An initial allowlist configuration prevented all sends. It was corrected to apply once at entry; the downstream production audience guards remained active. The initial run's contacts were held before the successful run. All test workflows were paused afterward and every QA contact was independently read back with lifecycle flags false, both stages idle and global subscription false.--## Copy and rendering--All 12 messages were reviewed against the private Bento sequence/broadcast archive and rewritten around one useful action. The [voice guide](VOICE.md) records each email's purpose. Prices, promotions and unsupported activity claims were removed. This is an editorial conversion hypothesis; no measured conversion lift is claimed.--The final drafts were uploaded as generated custom MJML and reviewed in the actual Loops editor for copy, links, subject, preview, sender, reply address, fallback values and one compact footer. Loops' native opt-in explanation is absent. A native line-height mistake was fixed: LMX interprets line height as a percentage, so `26` collapsed the footer; custom delivery now uses explicit 26px body and 19px footer line heights.--The final header exports the actual Cap component's vector paths, including its original wordmark, to a 486×160 PNG. It is displayed at 120px wide with its natural aspect ratio. The image's left edge and body copy start at 28px in the 600px email. The PNG is fully opaque with white backing so the original dark lettering remains legible against dark backgrounds. The final received email's logo bytes matched the local PNG by SHA-256. There is no replacement font or separate text approximation. Cross-client automatic dark-mode transformations and every mobile email client have not been exhaustively tested.--Controlled previews to `[email protected]` verified an absent name renders `Hey,`, a supplied name renders `Hey Richie,`, and the customer plan name and plan-specific prose appear correctly. The inbox preview text is retained. The final logo preview is separate from the earlier icon-only and temporary text-wordmark previews; use the newest preview when reviewing the design.--All 16 workflow messages and the inspected final-layout previews arrived in Gmail's inbox with SPF, DKIM and DMARC passing, plus one-click unsubscribe headers. Category placement varied. Authentication and these observed deliveries do not guarantee future inbox placement or eliminate spam complaints.--## Local regression checks--The profile replay used the archived 10 September snapshot at a fixed date: 64,288 source profiles, zero audience or consent changes, every profile held, and no customer or teammate made promotion-eligible. Greeting output was checked for every profile. This was a historical regression replay, not a fresh production reconciliation.--The local suite checks consent precedence, suppression preservation, customer and teammate classification, milestones, enrollment holds, missing/blank names, source variables, fallback contracts, footer uniqueness, preserved links and unsupported template blocks. Scoped TypeScript and formatting checks cover the touched scripts. The read-only Loops verifier checks graph structure and confirms all 12 emails use custom format. Custom MJML content cannot be fetched through the beta API; browser review is required, and the default full-content check fails explicitly rather than claiming parity.--## 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 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.--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.--A separate recipient Preference Center test used an existing delivered QA message. The owned contact was globally subscribed with the Product updates and tips list selected, then the recipient switched that list off while leaving global subscription on. Updating the owned Stripe fixture delivered the new name to the same Loops contact and preserved its absent list membership. No new email, payment or subscription was created. The contact was held throughout and globally unsubscribed again afterward.--The deployed Cap signup/purchase/invite path has not yet been proven end to end. Production schema/code deployment, the final Bento suppression delta, and deployed scheduler monitoring remain cutover gates. 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.--Private contact data, message bodies, action logs, API verification and import receipts remain outside Git. The [delivery receipt](delivery-receipt.json) records reviewed local archive hashes and draft identifiers; it is historical evidence, not live drift detection.diff --git a/emails/README.md b/emails/README.mddeleted file mode 100644index 226f955ab..000000000--- a/emails/README.md+++ /dev/null@@ -1,66 +0,0 @@-# Cap email library--Start with the [catalogue and flow maps](CATALOG.md), [copy guidance](VOICE.md), and [QA results](QA.md). The catalogue includes four Loops journeys, two campaign templates, all 12 marketing emails, customer variations, and the existing Resend application email inventory.--## Where to make changes--| Change | Source |-| --------------------------------------------------------------- | ---------------------------------------------- |-| Copy, subject, preview and purpose | [marketing/](marketing/) |-| Logo, colours, spacing, signature, footer, sender and fallbacks | [brand.ts](brand.ts) |-| Shared delivery layout | [mjml.ts](mjml.ts) |-| 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) |-| Last reviewed upload hashes | [delivery-receipt.json](delivery-receipt.json) |--Each marketing file uses a small shared content vocabulary: Paragraph, Link, Strong, Em, Br and Image. The MJML renderer combines that copy with the shared design. Images use descriptive alt text and a click destination, with files declared in the email's `assets` array under `emails/assets/`. Exports bundle these files alongside the logo. Unsupported new blocks fail export instead of silently disappearing. `scripts/loops/program.ts` is a compatibility export, not another copy source.--The header uses the actual Cap vector artwork from `packages/ui/src/components/icons/Logo.tsx`. `bun run emails:logo` renders its original paths to the checked-in PNG with white backing. This preserves the wordmark and keeps its dark lettering visible on dark backgrounds. Do not rebuild the wordmark with a font or substitute the icon alone. The image and body share the same left edge.--## Edit and upload--From the repository root:--```sh-bun run emails:catalog-bun run emails:check-bun test scripts/emails scripts/loops/profile.test.ts-bun run emails:export --output /absolute/path/to/reviewed-exports-```--The export creates one ZIP and MJML file per email, plus a manifest containing subjects, preview text, sender fields, fallbacks and hashes. Every ZIP contains `index.mjml` and its logo. All copy and design changes start here in source; the generated catalogue is never edited by hand.--In the intended Loops draft, choose **Code → Upload another email → Select**, select its ZIP, and upload. A native email uses **Code → Select** for its first conversion. Review the actual subject, preview text, sender, reply address and every variable fallback against the manifest. Uploading the body does not update these metadata fields automatically. Wait for the logo to load, inspect all copy and links, confirm one footer, and verify the email remains a draft.--Keep `capGreeting` as a complete salutation with `Hey,` as its fallback. Profile sync supplies `Hey Richie,` only when a nonblank name is known. Previously imported contacts need an approved profile refresh before their new greeting property is populated; until then the fallback applies. Changes to `customer-copy.ts` also require a profile refresh and do not instantly change stored Loops properties.--## Verification boundaries--With `LOOPS_API_KEY` supplied through the environment:--```sh-bun run emails:check-loops --structure-only-```--This read-only command checks the team, mailing list, draft statuses, workflow graphs, downstream audience guards, branch reconnections, delays, campaign targeting and custom email format. Loops' beta API returns HTTP 409 for reading or updating custom MJML emails, so their contents and Guardian results require browser review. Running without `--structure-only` deliberately fails when content cannot be verified; it never treats an unreadable email as a content match.--The historical upload receipt records the local export hashes reviewed in the browser. It is not live drift detection. Reconcile intentional dashboard edits into source before uploading replacements. Do not switch back to native format to bypass the API limitation: native footers reintroduce the automatic opt-in explanation. The legacy provisioner refuses `--apply` while custom MJML delivery is configured.--Local commands and read-only checks never send or enroll contacts. Preview sends require the user's sending scope; this migration's QA used only owned Cap inboxes. Production activation remains a separate cutover action.--## Adding emails and flows--1. Add `marketing/<stable-id>.ts` implementing `EmailDefinition`. Declare every variable and a suitable shared fallback.-2. Register the email in `flows.ts` or `campaigns.ts`. Preserve existing IDs and step keys because resource receipts refer to them.-3. Regenerate the catalogue. Check consent, customer and teammate exclusions, downstream guards, milestone behavior and re-entry rules.-4. Create the intended draft graph through the supported migration tooling, then upload the generated custom email and record its resource IDs. The existing provisioner is guarded against overwriting the custom programme; extending graphs needs a scoped implementation.-5. Run the local and graph checks, inspect each changed render, then commit definitions and generated catalogue together.--Resend application templates stay under `packages/database/emails/`; the inventory links to them without duplicating their content. Their sending behavior and layout are unchanged. Loops marketing guards do not control Resend, and the first-recording email needs an overlap check before lifecycle activation.--Keep credentials, contacts, suppression hashes and exports outside Git. The [migration runbook](../scripts/loops/README.md) owns imports, suppression seeding, production integration and cutover.diff --git a/emails/VOICE.md b/emails/VOICE.mddeleted file mode 100644index 9f0988a1e..000000000--- a/emails/VOICE.md+++ /dev/null@@ -1,46 +0,0 @@-# Writing emails from Richie--Use this alongside the [catalogue](CATALOG.md). The reference is Richie's actual Bento mail: the welcome sequence (36459), Studio Mode explanation (47417), tips (47847), team introduction (47848), founder story (31811), and recent product/security updates (75230, 75463, 76365). The private archive contains six sequence templates and 66 broadcasts. Do not put subscriber exports or personalised unsubscribe links in this repository.--## Voice--Start with the complete `capGreeting` property: “Hey Richie,” when a nonblank name is known, otherwise “Hey,”. Keep “Hey,” as the Loops fallback too. Introduce Richie in a welcome email; later emails can get straight to the point. Use contractions, ordinary words and British spelling. Write “reply and let me know”, not “your feedback helps us make better decisions”. An occasional `:)` fits the originals; using one in every email does not.--Use first person for something Richie is asking or offering, and “we” for work the Cap team has done. Keep promises realistic. Do not invent a personal anecdote, say Richie noticed someone's activity, or imply a manually written one-to-one message. Replies go to `[email protected]`.--Give each email one reason to exist and one main action. Usually 60–120 words is enough. A question that invites a reply can be the entire action. Keep advice specific: what to record, where to find the workspace, or which paid plan covers the recipient's need. Read the result aloud and cut anything that could appear in any software company's email.--Do not automatically carry forward historical prices, discounts, countdowns, launch dates, team size, platform support or compliance claims. Verify them against the current product and approved offer. No fake `Re:`, invented urgency or claims of guaranteed results. Local recordings are not visible to this sync, so “you haven't recorded yet” is not a supported claim.--## Design--`brand.ts` owns the sender, canonical Cap logo artwork, “Cheers, Richie” signature, footer, background, 16px body type, line height, paragraph spacing and link colour. `mjml.ts` renders these into every upload. Keep bodies as simple paragraphs; an individual email should not duplicate the design. The logo PNG is exported from the canonical Cap component, including its exact vector wordmark. Its white backing preserves contrast on dark backgrounds without substituting a different font. Keep it at its natural aspect ratio, with no extra left inset.--Use one descriptive text link when a click is needed. Feedback emails can have no link. Keep the essential message readable with images blocked. Custom MJML contains exactly one company/address/unsubscribe footer, without the automatic opt-in explanation. Use `{unsubscribe_link}` so Loops supplies the actual link. Body line height is 26px and footer line height is 19px; native LMX uses percentages, not pixels. Check the actual render after upload and wait for images to load.--## Review of the current programme--| Email | Main action | Editorial decision |-| ------------------------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |-| Free welcome | Download and make a first recording | Personal introduction, two recording modes, no upgrade pitch. |-| Free recording help | Try a short recording | Conditional advice, no claim that local recording activity is known. |-| Free sharing help | Share a useful explanation | One concrete bug-report example and library link. |-| Free plan guidance | Compare paid plans | Explain Desktop versus Pro by use case; no stale price or coupon. |-| Customer welcome | Reply with intended use | Thank the customer, use the actual plan variation, remove a desktop download link that did not fit self-hosted customers. |-| Customer workflow | Record an answer once | Practical habit that works with local exports or cloud sharing. |-| Customer feedback | Reply with a problem or request | One short question, no survey or upgrade diversion. |-| Teammate welcome | Find the right organisation | Practical access help; no promotion. |-| Teammate handoff | Share context with the team | One task and an access check; no promotion. |-| Former customer feedback | Explain why they left | Offer help without a coupon, pressure or automatic re-enrolment. |-| Customer campaign | Read the changelog or reply | Honest evergreen invitation; no invented announcement. |-| Free-user campaign | Reconsider Cap for a real task | Ask what put them off; no claim that a specific missing feature is fixed. |--The two campaign drafts are reusable evergreen starting points. A feature announcement should replace the subject, preview and body with the specific verified feature and how to use it. Review targeting and content for every campaign; do not repeatedly send the same generic update to the whole imported list.--## Conversion and learning--The sequence first helps the recipient get value, then explains the paid option where appropriate. Customers receive usage and feedback emails. Teammates receive workspace help. Unknown identities receive nothing. Recording/sharing reminders are skipped when the corresponding known cloud milestone is complete.--Measure first recording and first share after onboarding, paid conversion after plan guidance, useful replies, and retained usage for customers. Compare eligible delivered recipients over a defined window; report unsubscribes, complaints and bounces alongside conversions. Open rate alone is not a reliable conversion measure, and historical Bento opens/clicks do not establish which copy causes purchases.--Start with this baseline and change one meaningful variable at a time once there is enough traffic: the plan email's subject, the main action, or timing. Keep audience and consent rules identical across variants. Purchase attribution and these conversion reports still need to be connected to the live enrollment service before claiming a measured uplift.diff --git a/emails/application.ts b/emails/application.tsdeleted file mode 100644index 331f0947b..000000000--- a/emails/application.ts+++ /dev/null@@ -1,154 +0,0 @@-export type ApplicationEmail = {- id: string;- name: string;- trigger: string;- recipients: string;- notes: string;- template: string;- sources: string[];-};--export const applicationEmails: ApplicationEmail[] = [- {- id: "verification-code",- name: "Login verification code",- trigger: "Web or mobile email authentication request",- recipients: "The person signing in",- notes: "OTP authentication; does not subscribe the recipient to marketing.",- template: "otp-email",- sources: [- "packages/database/auth/auth-options.ts",- "apps/web/app/api/mobile/[...route]/route.ts",- ],- },- {- id: "organization-invite",- name: "Organization invitation",- trigger:- "An organization invitation is issued through the web action or public API",- recipients: "The invited teammate",- notes: "An invitation is not permission to send promotions.",- template: "organization-invite",- sources: [- "apps/web/actions/organization/send-invites.ts",- "apps/web/app/api/v1/[...route]/route.ts",- ],- },- {- id: "video-viewer-invite",- name: "Recording viewer invitation",- trigger: "A recording owner invites someone to view the recording",- recipients: "The invited viewer",- notes:- "Transactional viewing access; does not subscribe the viewer to marketing.",- template: "video-viewer-invite",- sources: ["apps/web/actions/videos/viewer-invites.ts"],- },- {- id: "download-link",- name: "Requested download links",- trigger: "The person requests download links by email",- recipients: "The requesting email address",- notes:- "Uses the existing Resend marketing sender flag; Loops audience filters do not govern this send.",- template: "download-link",- sources: ["apps/web/actions/send-download-link.ts"],- },- {- id: "first-shareable-link",- name: "First shareable recording",- trigger: "Desktop API creates the first eligible shareable recording",- recipients: "The recording owner",- notes:- "Scheduled in Resend for five minutes later; uses the existing marketing sender flag. Check overlap before activating Loops recording reminders.",- template: "first-shareable-link",- sources: ["apps/web/app/api/desktop/[...route]/video.ts"],- },- {- id: "new-comment",- name: "New comment notification",- trigger: "An eligible comment notification is created",- recipients: "The notification recipient",- notes:- "Notification preferences and exclusions are applied by Notification.ts.",- template: "new-comment",- sources: ["apps/web/lib/Notification.ts"],- },- {- id: "first-view",- name: "First view notification",- trigger: "An eligible recording receives its first view",- recipients: "The recording owner",- notes:- "Notification preferences and first-view checks are applied by Notification.ts.",- template: "first-view",- sources: ["apps/web/lib/Notification.ts"],- },- {- id: "payment-failed",- name: "Payment failed / final retry",- trigger: "Stripe invoice payment fails",- recipients: "The billing account user",- notes:- "Different subject and content for the final attempt; deduplicated by invoice and attempt.",- template: "payment-failed",- sources: ["apps/web/app/api/webhooks/stripe/route.ts"],- },- {- id: "signed-baa",- name: "Signed BAA delivery",- trigger: "A business associate agreement is signed",- recipients: "The signer, with the configured notice recipients copied",- notes:- "Includes the signed PDF and tracks delivery state; preserve attachment and CC behavior.",- template: "signed-baa",- sources: ["apps/web/actions/organization/signed-baa.ts"],- },- {- id: "desktop-feedback",- name: "Desktop feedback notification",- trigger: "Legacy desktop feedback handler",- recipients: "Cap support, with the user copied",- notes:- "Source-defined handler; inspect route reachability before relying on it.",- template: "feedback",- sources: ["apps/web/app/api/desktop/[...route]/root.ts"],- },- {- id: "messenger-support",- name: "Messenger support notification",- trigger: "An eligible support conversation requests an email notification",- recipients: "Cap support; replies go to the user",- notes: "The support service reserves notification state before sending.",- template: "messenger-support-email",- sources: ["apps/web/lib/messenger/support-email.ts"],- },- {- id: "account-deletion",- name: "Account deletion request notification",- trigger: "An account deletion request is submitted",- recipients: "Cap support; replies go to the requester",- notes: "Deduplicated by deletion request ID.",- template: "messenger-support-email",- sources: ["apps/web/lib/account-deletion-request.ts"],- },- {- id: "content-report",- name: "Mobile content report notification",- trigger: "A mobile content report is submitted",- recipients: "Cap support; replies go to the reporter",- notes: "Deduplicated by report ID.",- template: "messenger-support-email",- sources: ["apps/web/lib/account-deletion-request.ts"],- },- {- id: "login-link",- name: "Legacy login link template",- trigger: "No current send call found in this checkout",- recipients: "None configured",- notes:- "Retained source template; current email login uses verification codes.",- template: "login-link",- sources: [],- },-];diff --git a/emails/assets/cap-logo.png b/emails/assets/cap-logo.pngdeleted file mode 100644index 0dc5b4f09..000000000Binary files a/emails/assets/cap-logo.png and /dev/null differdiff --git a/emails/assets/cap-v06-player.jpg b/emails/assets/cap-v06-player.jpgdeleted file mode 100644index fdd5f70f9..000000000Binary files a/emails/assets/cap-v06-player.jpg and /dev/null differdiff --git a/emails/audiences.ts b/emails/audiences.tsdeleted file mode 100644index 31fb13bbc..000000000--- a/emails/audiences.ts+++ /dev/null@@ -1,61 +0,0 @@-export const contactProperties = {- capGreeting: "string",- capAudience: "string",- capOrigin: "string",- capConsent: "string",- capTeammate: "boolean",- capCustomer: "boolean",- capPlanName: "string",- capMultiSeatOwner: "boolean",- capTeamGreeting: "string",- capCustomerWelcome: "string",- capPromotionalEligible: "boolean",- capOnboardingEligible: "boolean",- capLifecycleEnabled: "boolean",- capLifecycleStage: "string",- capHasVideo: "boolean",- capHasSharedVideo: "boolean",- capReadyForPro: "boolean",- capNeedsSharingHelp: "boolean",- capNeedsRecordingHelp: "boolean",- capFreeOnboardingVariant: "string",- capFreeOnboardingExperiment: "string",- capFreeOnboardingAssignedAt: "date",- capVerifiedAt: "date",- capImportedAt: "date",- capSignupAt: "date",- capSourceTags: "string",- capSourceGroup: "string",-} as const;--export type Condition = {- type: "property";- key: string;- operator: "equals" | "isTrue" | "isFalse";- value?: string;-};--export const condition = (key: string, value: string | boolean): Condition =>- typeof value === "boolean"- ? { type: "property", key, operator: value ? "isTrue" : "isFalse" }- : { type: "property", key, operator: "equals", value };--export const audienceFilter = (- audience: string,- promotional: boolean,- additionalConditions: Condition[] = [],-) => ({- match: "all" as const,- conditions: [- condition("subscribed", true),- condition("capConsent", "subscribed"),- condition("capAudience", audience),- ...(promotional- ? [- condition("capTeammate", false),- condition("capPromotionalEligible", true),- ]- : []),- ...additionalConditions,- ],-});diff --git a/emails/brand.ts b/emails/brand.tsdeleted file mode 100644index fd095530d..000000000--- a/emails/brand.ts+++ /dev/null@@ -1,87 +0,0 @@-export const brandingVersion = 6;--export const deliveryFormat: "mjml" | "lmx" = "mjml";--export const bodyLineHeightPercent = 160;--export const logo = {- src: "https://images.vialoops.com/cmtvpmjen01ks0j18ebmp77uk/img/cmtwz64ty00qx0j0poxsc4u7x.png",- file: "emails/assets/cap-logo.png",- width: 120,- borderRadius: 0,-};--export const signature = ["Cheers,", "Richie"];--export const footer = {- company: "Cap Software, Inc.",- address: "1111B S Governors Ave, Dover, DE 19904, United States",- unsubscribeLabel: "Unsubscribe",-};--export const theme = {- name: `Cap lifecycle v${brandingVersion}`,- styles: {- backgroundColor: "#ffffff",- bodyColor: "#ffffff",- bodyXPadding: 28,- bodyYPadding: 28,- bodyFontFamily: "Helvetica",- bodyFontCategory: "sans-serif",- textBaseColor: "#252525",- textBaseFontSize: 16,- textBaseLineHeight: bodyLineHeightPercent,- textLinkColor: "#3159d6",- heading1Color: "#171717",- heading1FontSize: 26,- heading1LineHeight: 130,- heading2FontSize: 21,- buttonBodyColor: "#3159d6",- buttonTextColor: "#ffffff",- buttonTextFontSize: 16,- buttonBorderRadius: 8,- buttonBodyXPadding: 18,- buttonBodyYPadding: 12,- },-};--export const components = [- {- name: `Cap lifecycle header v${brandingVersion}`,- lmx: `<Image src="${logo.src}" alt="Cap" width="${logo.width}" borderRadius="${logo.borderRadius}" paddingBottom="24" />`,- },- {- name: `Cap lifecycle signature v${brandingVersion}`,- lmx: `<Paragraph lineHeight="${bodyLineHeightPercent}" paddingTop="8">${signature.join("<Br />")}</Paragraph>`,- },-];--export const sender = {- fromName: "Richie from Cap",- fromEmail: "richie",- replyToEmail: "[email protected]",- emailFormat: "styled",-};--export const contactFallbacks = {- capGreeting: "Hey,",- capTeamGreeting: "Hey team,",- capPlanName: "Cap",- capCustomerWelcome:- "If you need a hand getting set up, just reply and I'll help you sort it.",-};--export type BrandIds = { theme: string; header: string; signature: string };--export const paragraphSpacing = 16;--export const emailContent = (- message: { subject: string; previewText: string; body: string },- ids: BrandIds,-) => ({- subject: message.subject,- previewText: message.previewText,- ...sender,- lmx: `<Style themeId="${ids.theme}" />\n<Component componentId="${ids.header}" />\n${message.body.replaceAll("<Paragraph>", `<Paragraph lineHeight="${bodyLineHeightPercent}" paddingBottom="${paragraphSpacing}">`)}\n<Component componentId="${ids.signature}" />`,- contactPropertiesFallbacks: contactFallbacks,-});diff --git a/emails/campaigns.ts b/emails/campaigns.tsdeleted file mode 100644index 579cb5de8..000000000--- a/emails/campaigns.ts+++ /dev/null@@ -1,31 +0,0 @@-import { condition } from "./audiences";-import { customerCaseStudy } from "./marketing/customer-case-study";-import { customerUpdate } from "./marketing/customer-update";-import { freeUpdate } from "./marketing/free-update";-import type { Campaign } from "./types";--export const campaignTemplates: Campaign[] = [- {- ...customerUpdate,- name: "Cap v0.6 launch | Customers",- audience: "customer",- promotional: false,- },- {- ...freeUpdate,- name: "Cap v0.6 launch | Noncustomers",- audience: "free",- promotional: true,- },- {- ...customerCaseStudy,- name: "Case study and logo wall invite | Cap Pro multi-seat org owners",- audience: "customer",- promotional: false,- audienceConditions: [- condition("capPlanName", "Cap Pro"),- condition("capTeammate", false),- condition("capMultiSeatOwner", true),- ],- },-];diff --git a/emails/delivery-receipt.json b/emails/delivery-receipt.jsondeleted file mode 100644index d08f84623..000000000--- a/emails/delivery-receipt.json+++ /dev/null@@ -1,151 +0,0 @@-{- "recordedAt": "2026-09-11T13:14:46.625Z",- "format": "mjml",- "scope": "Browser-reviewed draft uploads; historical record, not live drift detection",- "logoSource": "packages/ui/src/components/icons/Logo.tsx",- "reviewed": {- "draft": true,- "canonicalLogo": true,- "singleFooter": true,- "greetingFallback": true,- "metadata": true- },- "emails": [- {- "id": "free-welcome",- "sha256": "2c655d03647af236d1cf4a45a60073121ee027e6799ed473069dd04d0a450813",- "containerId": "cmtvpih6201fp0jznodf8fpwz",- "nodeId": "n4",- "subject": "Welcome to Cap",- "previewText": "Richie here. Great to have you with us :)",- "fallbacks": {- "capGreeting": "Hey,"- }- },- {- "id": "free-record",- "sha256": "00372d4d5a911b3433f958c3e163ef90bb0653f6e2b483172b60ed87da6a6e79",- "containerId": "cmtvpih6201fp0jznodf8fpwz",- "nodeId": "n9",- "subject": "A quick way to try Cap",- "previewText": "You don't need a script or a perfect take.",- "fallbacks": {- "capGreeting": "Hey,"- }- },- {- "id": "free-share",- "sha256": "974a3ae5f158f66aaed3451f29964cc348b19bc0c56a86f3a7c755412cf3bf1e",- "containerId": "cmtvpih6201fp0jznodf8fpwz",- "nodeId": "n14",- "subject": "Send your next explanation as a Cap",- "previewText": "A short recording and one sentence are enough.",- "fallbacks": {- "capGreeting": "Hey,"- }- },- {- "id": "free-plans",- "sha256": "ce4635d7a6fad264ec0405c25525a999291e498bc8a93d898a81e92db696e2fb",- "containerId": "cmtvpih6201fp0jznodf8fpwz",- "nodeId": "n16",- "subject": "Using Cap for work?",- "previewText": "Here's how the Desktop License and Cap Pro compare.",- "fallbacks": {- "capGreeting": "Hey,"- }- },- {- "id": "customer-welcome",- "sha256": "91481e642ffb79d6d413b68a6232ec60616b203bd03813035f04e308302ab780",- "containerId": "cmtvpilm601f40jzwx3474cko",- "nodeId": "n4",- "subject": "Thanks for choosing {capPlanName}",- "previewText": "Thanks for backing what we're building.",- "fallbacks": {- "capCustomerWelcome": "If you need a hand getting set up, just reply and I'll help you sort it.",- "capPlanName": "Cap",- "capGreeting": "Hey,"- }- },- {- "id": "customer-workflow",- "sha256": "e335467f93d9377de9bb83050ffb7294567a1cbcf9062ba0319b7ed3c861e1e5",- "containerId": "cmtvpilm601f40jzwx3474cko",- "nodeId": "n6",- "subject": "One less thing to explain twice",- "previewText": "A recording you can keep coming back to.",- "fallbacks": {- "capGreeting": "Hey,"- }- },- {- "id": "customer-feedback",- "sha256": "d3d6bec25066bb422d92400e220d23a4626b9dffae8f442abefb6c36e5c819b4",- "containerId": "cmtvpilm601f40jzwx3474cko",- "nodeId": "n8",- "subject": "How is Cap working for you?",- "previewText": "I'd love to hear what's working and what isn't.",- "fallbacks": {- "capGreeting": "Hey,"- }- },- {- "id": "teammate-welcome",- "sha256": "39cf59dde6b58b7512122143c3a0571e0a79e837fdbd84c3211a52326acb2ae2",- "containerId": "cmtvpm0ag01it0j37w02o6wav",- "nodeId": "n4",- "subject": "Welcome to your team in Cap",- "previewText": "Here's where to find your team's recordings.",- "fallbacks": {- "capGreeting": "Hey,"- }- },- {- "id": "teammate-handoff",- "sha256": "fe1e7a5ae897734a26c7fd5821205a077ff358ebf74c43e44322a721a2201f14",- "containerId": "cmtvpm0ag01it0j37w02o6wav",- "nodeId": "n6",- "subject": "Make your next handoff easier",- "previewText": "Show your teammate the bit that's hard to put into words.",- "fallbacks": {- "capGreeting": "Hey,"- }- },- {- "id": "former-feedback",- "sha256": "1d896cd1e5e1be97de072aaf831d307ad01d616483712bb8aeef483c0409ad17",- "containerId": "cmtvpm8zm01ii0j01cz7d15qr",- "nodeId": "n5",- "subject": "Could I ask about your time with Cap?",- "previewText": "I'd appreciate your honest feedback.",- "fallbacks": {- "capGreeting": "Hey,"- }- },- {- "id": "customer-update",- "sha256": "68bc2b5e24a1544f4fa1ee50247a89cce55e4c4a91b4c4d5442a91284874bc9b",- "containerId": "cmtvpmfxc01ls0j0nnlffombv",- "nodeId": null,- "subject": "Cap v0.6 is here. Meet your new editor.",- "previewText": "3D scenes, animated titles and Studio Sound. See what's new in the launch video.",- "fallbacks": {- "capGreeting": "Hey,"- },- "reviewedAt": "2026-09-15T16:14:18.915Z"- },- {- "id": "free-update",- "sha256": "0cac3fc76d189e9934df5b33ab05a15e29272c6b0d01141b9e9fa66f1568f713",- "containerId": "cmtvpmjej01kr0j18cxoz2n0y",- "nodeId": null,- "subject": "Cap v0.6 is here. See what you can make.",- "previewText": "Meet Cap v0.6: 3D scenes, animated titles and cleaner audio, all in one app.",- "fallbacks": {- "capGreeting": "Hey,"- },- "reviewedAt": "2026-09-15T16:14:18.915Z"- }- ]-}diff --git a/emails/delivery-safety.ts b/emails/delivery-safety.tsdeleted file mode 100644index 8a3ed9c84..000000000--- a/emails/delivery-safety.ts+++ /dev/null@@ -1,22 +0,0 @@-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),- ...(journey.key === "free-v2"- ? [condition("capLifecycleStage", "free-v2")]- : []),- ],-});--export const heldWorkflowAudience = (journey: Journey) => ({- ...workflowAudience(journey),- conditions: [- ...workflowAudience(journey).conditions,- condition("subscribed", false),- ],-});diff --git a/emails/flows.ts b/emails/flows.tsdeleted file mode 100644index 710e823d6..000000000--- a/emails/flows.ts+++ /dev/null@@ -1,102 +0,0 @@-import { customerFeedback } from "./marketing/customer-feedback";-import { customerWelcome } from "./marketing/customer-welcome";-import { customerWorkflow } from "./marketing/customer-workflow";-import { formerFeedback } from "./marketing/former-feedback";-import { freePlans } from "./marketing/free-plans";-import { freeRecord } from "./marketing/free-record";-import { freeShare } from "./marketing/free-share";-import { freeV2Ai } from "./marketing/free-v2-ai";-import { freeV2Help } from "./marketing/free-v2-help";-import { freeV2Plans } from "./marketing/free-v2-plans";-import { freeV2Record } from "./marketing/free-v2-record";-import { freeV2Share } from "./marketing/free-v2-share";-import { freeV2Welcome } from "./marketing/free-v2-welcome";-import { freeWelcome } from "./marketing/free-welcome";-import { teammateHandoff } from "./marketing/teammate-handoff";-import { teammateWelcome } from "./marketing/teammate-welcome";-import type { Journey } from "./types";--export const journeys: Journey[] = [- {- key: "free",- name: "Cap | Independent free-user onboarding",- audience: "free",- promotional: true,- messages: [- { ...freeWelcome, delayDays: 0 },- {- ...freeRecord,- delayDays: 2,- onlyIf: { property: "capHasVideo", value: false },- },- {- ...freeShare,- delayDays: 3,- onlyIf: { property: "capHasSharedVideo", value: false },- },- { ...freePlans, delayDays: 4 },- ],- },- {- key: "customer",- name: "Cap | Customer onboarding",- audience: "customer",- promotional: false,- messages: [- { ...customerWelcome, delayDays: 0 },- { ...customerWorkflow, delayDays: 3 },- { ...customerFeedback, delayDays: 4 },- ],- },- {- key: "free-v2",- name: "Cap | Free activation and Pro conversion v2",- audience: "free",- promotional: true,- messages: [- { ...freeV2Welcome, delayDays: 0 },- {- ...freeV2Record,- delayDays: 1,- onlyIf: { property: "capNeedsRecordingHelp", value: true },- },- {- ...freeV2Plans,- delayDays: 2,- onlyIf: { property: "capReadyForPro", value: true },- },- {- ...freeV2Share,- delayDays: 5,- onlyIf: { property: "capNeedsSharingHelp", value: true },- },- {- ...freeV2Ai,- delayDays: 2,- onlyIf: { property: "capReadyForPro", value: true },- },- {- ...freeV2Help,- delayDays: 2,- onlyIf: { property: "capNeedsRecordingHelp", value: true },- },- ],- },- {- key: "teammate",- name: "Cap | Teammate onboarding",- audience: "teammate",- promotional: false,- messages: [- { ...teammateWelcome, delayDays: 0 },- { ...teammateHandoff, delayDays: 3 },- ],- },- {- key: "former",- name: "Cap | Former customer follow-up",- audience: "former",- promotional: true,- messages: [{ ...formerFeedback, delayDays: 14 }],- },-];diff --git a/emails/index.ts b/emails/index.tsdeleted file mode 100644index 16566da99..000000000--- a/emails/index.ts+++ /dev/null@@ -1,5 +0,0 @@-export { audienceFilter, condition, contactProperties } from "./audiences";-export { components, theme } from "./brand";-export { campaignTemplates } from "./campaigns";-export { journeys } from "./flows";-export const programVersion = "cap-lifecycle-v1";diff --git a/emails/marketing/customer-case-study.ts b/emails/marketing/customer-case-study.tsdeleted file mode 100644index d05509e99..000000000--- a/emails/marketing/customer-case-study.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { EmailDefinition } from "../types";--export const customerCaseStudy = {- id: "customer-case-study",- key: "customer-case-study",- purpose:- "Invite Cap Pro organisation owners with more than one seat to reply if they'd like their team featured in a website case study.",- subject: "Could we feature your team in a Cap case study?",- previewText: "Reply and I'll send over a short Q&A.",- variables: ["capTeamGreeting"],- body: [- "<Paragraph>{contact.capTeamGreeting}</Paragraph>",- "<Paragraph>We're putting together case studies for the Cap website, and I'd love to feature your team in one.</Paragraph>",- "<Paragraph>If you're enjoying Cap and would like to be involved, just reply to this email and I'll send you a short Q&A to fill in.</Paragraph>",- "<Paragraph>It'd really help Cap move into the next stage of our growth, and help us tell other great teams like yours all about Cap.</Paragraph>",- "<Paragraph>Thanks so much for supporting us :)</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/customer-feedback.ts b/emails/marketing/customer-feedback.tsdeleted file mode 100644index 849f56d17..000000000--- a/emails/marketing/customer-feedback.ts+++ /dev/null@@ -1,17 +0,0 @@-import type { EmailDefinition } from "../types";--export const customerFeedback = {- id: "customer-feedback",- key: "feedback",- purpose: "Ask a customer what is useful and what needs improvement.",- subject: "How is Cap working for you?",- previewText: "I'd love to hear what's working and what isn't.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>How are you getting on with Cap?</Paragraph>",- "<Paragraph>I'd love to know if there's anything you wish worked differently, or something that's getting in your way.</Paragraph>",- "<Paragraph>Just reply here. I read every reply, and hearing how people actually use Cap helps me decide what we should work on next.</Paragraph>",- "<Paragraph>Thanks again for backing us :)</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/customer-update.ts b/emails/marketing/customer-update.tsdeleted file mode 100644index 5bba72f53..000000000--- a/emails/marketing/customer-update.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { EmailDefinition } from "../types";--export const customerUpdate = {- id: "customer-update",- key: "customer-update",- purpose:- "One-off Cap v0.6 launch announcement for customers, leading to the release video and update details.",- subject: "Meet Cap v0.6, our biggest update yet",- previewText:- "3D scenes, animated titles and Studio Sound. See what's new in the launch video.",- variables: ["capGreeting"],- assets: ["emails/assets/cap-v06-player.jpg"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph><Strong>Cap v0.6 is here, and it's our biggest release yet.</Strong></Paragraph>",- `<Image src="img/cap-v06-player.jpg" alt="Watch the Cap v0.6 launch video" href="https://cap.so/blog/cap-v06?utm_source=loops&utm_medium=email&utm_campaign=cap_v06_launch&utm_content=customers" />`,- "<Paragraph>We've rebuilt the editor so you can do more with the recordings you already make. Add 3D scenes, animated titles and moving backgrounds, without opening another editing app.</Paragraph>",- "<Paragraph>Studio Sound reduces microphone noise, and the new export screen shows estimated file size and time before you save.</Paragraph>",- "<Paragraph>The easiest way to see the difference is the launch video. The release page also has the download and full details.</Paragraph>",- `<Paragraph><Link href="https://cap.so/blog/cap-v06?utm_source=loops&utm_medium=email&utm_campaign=cap_v06_launch&utm_content=customers">Watch Cap v0.6 in action →</Link></Paragraph>`,- "<Paragraph>Thanks for supporting Cap. I can't wait to see what you make with this one :)</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/customer-welcome.ts b/emails/marketing/customer-welcome.tsdeleted file mode 100644index 0e94bae92..000000000--- a/emails/marketing/customer-welcome.ts+++ /dev/null@@ -1,16 +0,0 @@-import type { EmailDefinition } from "../types";--export const customerWelcome = {- id: "customer-welcome",- key: "welcome",- purpose: "Welcome a paying customer with copy matching their paid plan.",- subject: "Thanks for choosing {contact.capPlanName}",- previewText: "Thanks for backing what we're building.",- variables: ["capCustomerWelcome", "capPlanName", "capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>Richie here, founder of Cap. Thanks so much for supporting what we're building. It means a lot.</Paragraph>",- "<Paragraph>{contact.capCustomerWelcome}</Paragraph>",- "<Paragraph>What are you planning to use Cap for? Just reply and let me know. I'd love to hear.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/customer-workflow.ts b/emails/marketing/customer-workflow.tsdeleted file mode 100644index b67f5d688..000000000--- a/emails/marketing/customer-workflow.ts+++ /dev/null@@ -1,17 +0,0 @@-import type { EmailDefinition } from "../types";--export const customerWorkflow = {- id: "customer-workflow",- key: "workflow",- purpose: "Help a customer build a repeatable recording habit.",- subject: "One less thing to explain twice",- previewText: "A recording you can keep coming back to.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>A quick idea for your next recording: pick a question you keep answering and record the walkthrough once.</Paragraph>",- "<Paragraph>It could be how to set something up, where to find a setting, or how you want a piece of work done. Give it a title you'll recognise later, then save or share it wherever you normally answer that question.</Paragraph>",- "<Paragraph>The next time someone asks, you've already got it ready.</Paragraph>",- "<Paragraph>Anything making that harder than it should be? Reply and tell me.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/former-feedback.ts b/emails/marketing/former-feedback.tsdeleted file mode 100644index c562ce310..000000000--- a/emails/marketing/former-feedback.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { EmailDefinition } from "../types";--export const formerFeedback = {- id: "former-feedback",- key: "feedback",- purpose:- "Ask an eligible former cloud customer for feedback after paid access ends.",- subject: "Could I ask about your time with Cap?",- previewText: "I'd appreciate your honest feedback.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>Could I ask what made you decide to stop using your paid Cap plan?</Paragraph>",- "<Paragraph>Was something missing, did something not work properly, or did you just not need it anymore?</Paragraph>",- "<Paragraph>If you've got a moment to reply, I'd really appreciate it. And if there was a problem I can help with, I'd like to try.</Paragraph>",- "<Paragraph>Thanks for giving Cap a go.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-plans.ts b/emails/marketing/free-plans.tsdeleted file mode 100644index bd538dc03..000000000--- a/emails/marketing/free-plans.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { EmailDefinition } from "../types";--export const freePlans = {- id: "free-plans",- key: "plans",- purpose: "Explain current plan options to eligible independent noncustomers.",- subject: "Using Cap for work?",- previewText: "Here's how the Desktop License and Cap Pro compare.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>If you're thinking about using Cap for work, there are two options.</Paragraph>",- "<Paragraph>A <Strong>Desktop License</Strong> covers commercial use of the recorder and editor. It's a good fit if you mainly edit and export videos yourself.</Paragraph>",- "<Paragraph><Strong>Cap Pro</Strong> adds cloud sharing and collaboration, and includes the desktop commercial license. That's the one to look at if you're sharing recordings with clients or your team.</Paragraph>",- `<Paragraph><Link href="https://cap.so/pricing">Compare the plans here</Link>.</Paragraph>`,- "<Paragraph>Not sure which you need? Reply with what you're using Cap for and I'll point you in the right direction.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-record.ts b/emails/marketing/free-record.tsdeleted file mode 100644index e19b6463c..000000000--- a/emails/marketing/free-record.ts+++ /dev/null@@ -1,17 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeRecord = {- id: "free-record",- key: "record",- purpose: "Offer recording help when no cloud video is known.",- subject: "A quick way to try Cap",- previewText: "You don't need a script or a perfect take.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>If you're still finding your feet with Cap, try this: open something on your screen and spend 30 seconds explaining it out loud.</Paragraph>",- "<Paragraph>No script or perfect take needed. In Studio Mode, you can trim it afterwards and keep the recording on your own device.</Paragraph>",- `<Paragraph>Need the app? <Link href="https://cap.so/download">You can download Cap here</Link>.</Paragraph>`,- "<Paragraph>If something's stopping you from recording, reply and let me know what happened. I'll help you sort it.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-share.ts b/emails/marketing/free-share.tsdeleted file mode 100644index dc467885e..000000000--- a/emails/marketing/free-share.ts+++ /dev/null@@ -1,17 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeShare = {- id: "free-share",- key: "share",- purpose: "Offer sharing guidance when no shared cloud video is known.",- subject: "Send your next explanation as a Cap",- previewText: "A short recording and one sentence are enough.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>Next time you're typing a long explanation, try showing it in Cap instead.</Paragraph>",- "<Paragraph>Record the bit that's hard to explain, then send the link with a sentence about what you need. Something like: “Here's the bug I mentioned. Can you see the same thing?”</Paragraph>",- "<Paragraph>It doesn't have to be polished to be useful.</Paragraph>",- `<Paragraph><Link href="https://cap.so/dashboard">Open your Cap library</Link>.</Paragraph>`,- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-update.ts b/emails/marketing/free-update.tsdeleted file mode 100644index 8d8e67392..000000000--- a/emails/marketing/free-update.ts+++ /dev/null@@ -1,22 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeUpdate = {- id: "free-update",- key: "free-update",- purpose:- "One-off Cap v0.6 launch announcement for eligible independent noncustomers, showing the demo workflow through the release video.",- subject: "Meet Cap v0.6, our biggest update yet",- previewText:- "Meet Cap v0.6: 3D scenes, animated titles and cleaner audio, all in one app.",- variables: ["capGreeting"],- assets: ["emails/assets/cap-v06-player.jpg"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph><Strong>Cap v0.6 is here, and it's our biggest release yet.</Strong></Paragraph>",- `<Image src="img/cap-v06-player.jpg" alt="Watch the Cap v0.6 launch video" href="https://cap.so/blog/cap-v06?utm_source=loops&utm_medium=email&utm_campaign=cap_v06_launch&utm_content=noncustomers" />`,- "<Paragraph>We've rebuilt the editor to turn your screen recordings into polished demos. Record your screen, add a 3D scene, animated titles and a moving background, then export a video you'll want to share.</Paragraph>",- "<Paragraph>There's also Studio Sound to reduce microphone noise, plus faster exports. Whether it's a product demo, a client walkthrough or a team update, you can make it in Cap.</Paragraph>",- "<Paragraph>The release video is the best way to see what's new:</Paragraph>",- `<Paragraph><Link href="https://cap.so/blog/cap-v06?utm_source=loops&utm_medium=email&utm_campaign=cap_v06_launch&utm_content=noncustomers">See Cap v0.6 in action →</Link></Paragraph>`,- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-v2-ai.ts b/emails/marketing/free-v2-ai.tsdeleted file mode 100644index c75e1a8dc..000000000--- a/emails/marketing/free-v2-ai.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeV2Ai = {- id: "free-v2-ai",- key: "ai",- purpose:- "Show active free users how Pro reduces the work around a recording.",- subject: "Record the walkthrough. Skip the extra write-up.",- previewText: "Give people a summary and chapters alongside your video.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>A recording saves you typing everything out. Writing a summary afterwards can feel like doing the job twice.</Paragraph>",- "<Paragraph><Strong>Cap Pro</Strong> generates a title, summary, transcript and clickable chapters for your recordings. The person watching can get the context, then jump to the part they need.</Paragraph>",- "<Paragraph>That's especially useful for walkthroughs people come back to later.</Paragraph>",- '<Paragraph><Link href="https://cap.so/login?next=%2Fdashboard%2Fsettings%2Forganization%2Fbilling%3Futm_source%3Dloops%26utm_medium%3Demail%26utm_campaign%3Dfree-pro-v2%26utm_content%3Dai">See Cap Pro</Link></Paragraph>',- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-v2-help.ts b/emails/marketing/free-v2-help.tsdeleted file mode 100644index bda06ad14..000000000--- a/emails/marketing/free-v2-help.ts+++ /dev/null@@ -1,17 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeV2Help = {- id: "free-v2-help",- key: "help",- purpose:- "Invite a reply from users who have not reached a completed cloud recording.",- subject: "Anything getting in the way?",- previewText: "Reply and tell me where you're getting stuck.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>If you haven't found a useful way to fit Cap into your day yet, is anything getting in the way?</Paragraph>",- "<Paragraph>Maybe you're not sure what to record, something isn't working, or it isn't quite what you expected.</Paragraph>",- "<Paragraph>Reply and let me know. If I can help you get a useful first recording out of it, I'd like to.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-v2-plans.ts b/emails/marketing/free-v2-plans.tsdeleted file mode 100644index c3ca23de5..000000000--- a/emails/marketing/free-v2-plans.ts+++ /dev/null@@ -1,19 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeV2Plans = {- id: "free-v2-plans",- key: "plans",- purpose:- "Offer Pro to active free users through a specific cloud-sharing benefit.",- subject: "Some explanations need more than five minutes",- previewText: "Share the full walkthrough with Cap Pro.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>Five minutes works for a quick question. A full walkthrough sometimes needs longer.</Paragraph>",- "<Paragraph><Strong>Cap Pro</Strong> removes the five-minute limit on cloud recordings and gives you unlimited shareable links, so you can send the whole explanation in one video.</Paragraph>",- "<Paragraph>It also includes the desktop commercial license for work recordings.</Paragraph>",- "<Paragraph>Pro is US$12 per user, billed monthly. Annual billing is also available.</Paragraph>",- '<Paragraph><Link href="https://cap.so/login?next=%2Fdashboard%2Fsettings%2Forganization%2Fbilling%3Futm_source%3Dloops%26utm_medium%3Demail%26utm_campaign%3Dfree-pro-v2%26utm_content%3Dplans">Upgrade to Cap Pro</Link></Paragraph>',- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-v2-record.ts b/emails/marketing/free-v2-record.tsdeleted file mode 100644index 0a304ba80..000000000--- a/emails/marketing/free-v2-record.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeV2Record = {- id: "free-v2-record",- key: "record",- purpose:- "Offer a small first cloud recording task when no completed video is visible.",- subject: "One small thing to record today",- previewText: "Try explaining something you already know.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>If you're still finding your feet with Cap, try recording a quick walkthrough of something you already know: a setting, a page, or a problem you want to show someone.</Paragraph>",- "<Paragraph>Choose <Strong>Instant Mode</Strong>, keep it short, then send the link when it's ready.</Paragraph>",- '<Paragraph><Link href="https://cap.so/download?utm_source=loops&utm_medium=email&utm_campaign=free-pro-v2&utm_content=record">Get started with your first recording</Link></Paragraph>',- "<Paragraph>If screen or microphone permissions are getting in the way, reply with what you're seeing and I'll help you sort it.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-v2-share.ts b/emails/marketing/free-v2-share.tsdeleted file mode 100644index fef7f2892..000000000--- a/emails/marketing/free-v2-share.ts+++ /dev/null@@ -1,19 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeV2Share = {- id: "free-v2-share",- key: "share",- purpose:- "Help an active user put a completed recording into a real conversation.",- subject: "Put your recording to work",- previewText: "Send the link with one sentence about what you need.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>A useful way to share a Cap is to add one sentence telling the other person what you need from them.</Paragraph>",- "<Paragraph>\"Here's the bit I'm stuck on. Can you take a look?\"</Paragraph>",- '<Paragraph>Or: "Here\'s how to change that setting. Does that solve it?"</Paragraph>',- '<Paragraph><Link href="https://cap.so/login?next=%2Fdashboard%2Fcaps%3Futm_source%3Dloops%26utm_medium%3Demail%26utm_campaign%3Dfree-pro-v2%26utm_content%3Dshare">Open your recordings</Link></Paragraph>',- "<Paragraph>Send the link wherever you're already having the conversation.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-v2-welcome.ts b/emails/marketing/free-v2-welcome.tsdeleted file mode 100644index 6df065412..000000000--- a/emails/marketing/free-v2-welcome.ts+++ /dev/null@@ -1,19 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeV2Welcome = {- id: "free-v2-welcome",- key: "welcome",- purpose:- "Help a new independent free user record and share one useful explanation.",- subject: "Your first Cap only needs 30 seconds",- previewText: "Record one thing, send the link, and you're off.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>Richie here, founder of Cap. Thanks for giving it a go :)</Paragraph>",- "<Paragraph>For your first recording, pick something you'd normally explain in a long message. Open Cap, choose <Strong>Instant Mode</Strong>, and spend 30 seconds showing it on screen.</Paragraph>",- "<Paragraph>Once it's ready, send the link to someone who needs that explanation. No polished presentation needed.</Paragraph>",- '<Paragraph><Link href="https://cap.so/download?utm_source=loops&utm_medium=email&utm_campaign=free-pro-v2&utm_content=welcome">Download Cap and make your first recording</Link></Paragraph>',- "<Paragraph>If you get stuck, reply here and I'll help.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/free-welcome.ts b/emails/marketing/free-welcome.tsdeleted file mode 100644index ae0f55a48..000000000--- a/emails/marketing/free-welcome.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { EmailDefinition } from "../types";--export const freeWelcome = {- id: "free-welcome",- key: "welcome",- purpose: "Help an independent free user make their first recording.",- subject: "Welcome to Cap",- previewText: "Richie here. Great to have you with us :)",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>Richie here, founder of Cap. Thanks for giving it a go :)</Paragraph>",- "<Paragraph>The easiest way to start is to record something you'd normally type out. A quick explanation or a bit of feedback is plenty.</Paragraph>",- "<Paragraph>Use Instant Mode when you want a shareable link, or Studio Mode to edit your recording and export it locally.</Paragraph>",- `<Paragraph><Link href="https://cap.so/download">Download Cap here</Link>.</Paragraph>`,- "<Paragraph>If you have any questions, just reply to this email. I'd love to help.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/teammate-handoff.ts b/emails/marketing/teammate-handoff.tsdeleted file mode 100644index df6124f7f..000000000--- a/emails/marketing/teammate-handoff.ts+++ /dev/null@@ -1,17 +0,0 @@-import type { EmailDefinition } from "../types";--export const teammateHandoff = {- id: "teammate-handoff",- key: "handoff",- purpose: "Help a teammate share useful context with their organization.",- subject: "Make your next handoff easier",- previewText: "Show your teammate the bit that's hard to put into words.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>Next time you hand something over to a teammate, try recording the part that's tricky to explain in a message.</Paragraph>",- "<Paragraph>Show what changed and what you need them to look at. Even a short recording can save a lot of back and forth.</Paragraph>",- `<Paragraph><Link href="https://cap.so/dashboard">Open your team workspace</Link>. Before sending a recording, check its sharing settings so the right people can watch it.</Paragraph>`,- "<Paragraph>If anything about sharing with your team feels awkward, reply and let me know.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/marketing/teammate-welcome.ts b/emails/marketing/teammate-welcome.tsdeleted file mode 100644index c8091b76f..000000000--- a/emails/marketing/teammate-welcome.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { EmailDefinition } from "../types";--export const teammateWelcome = {- id: "teammate-welcome",- key: "welcome",- purpose:- "Help an invited teammate find their workspace without promoting upgrades.",- subject: "Welcome to your team in Cap",- previewText: "Here's where to find your team's recordings.",- variables: ["capGreeting"],- body: [- "<Paragraph>{contact.capGreeting}</Paragraph>",- "<Paragraph>Richie here, founder of Cap. Great to have you with us :)</Paragraph>",- "<Paragraph><Link href=\"https://cap.so/dashboard\">Open your dashboard</Link> and select your team's organisation. You'll find the recordings they've shared with you there.</Paragraph>",- "<Paragraph>If you can't see the right organisation, check with the person who invited you. They can confirm which email address they used and your access.</Paragraph>",- "<Paragraph>You can also reply here if you need a hand.</Paragraph>",- ].join(""),-} satisfies EmailDefinition;diff --git a/emails/mjml.ts b/emails/mjml.tsdeleted file mode 100644index 7cfa3b8ce..000000000--- a/emails/mjml.ts+++ /dev/null@@ -1,67 +0,0 @@-import {- bodyLineHeightPercent,- footer,- logo,- paragraphSpacing,- signature,- theme,-} from "./brand";-import type { EmailDefinition } from "./types";--const escape = (value: string) =>- value- .replaceAll("&", "&")- .replaceAll("<", "<")- .replaceAll(">", ">")- .replaceAll('"', """);--export const mjmlVariables = (value: string) =>- value.replace(/\{contact\.(\w+)\}/g, "{$1}");--const renderBody = (body: string) => {- for (const [, tag] of body.matchAll(/<\/?([A-Za-z][\w]*)\b/g)) {- if (!["Paragraph", "Link", "Strong", "Em", "Br", "Image"].includes(tag))- throw new Error(`Unsupported marketing content tag: ${tag}`);- }- return mjmlVariables(- body- .replaceAll(- "<Image ",- '<mj-image align="left" padding="0 0 20px" border-radius="12px" ',- )- .replaceAll("<Paragraph>", "<mj-text>")- .replaceAll("</Paragraph>", "</mj-text>\n")- .replaceAll(- "<Link ",- `<a style="color:${theme.styles.textLinkColor};text-decoration:underline" `,- )- .replaceAll("</Link>", "</a>")- .replaceAll("<Strong>", "<strong>")- .replaceAll("</Strong>", "</strong>")- .replaceAll("<Em>", "<em>")- .replaceAll("</Em>", "</em>")- .replaceAll("<Br />", "<br />"),- );-};--export const renderMjml = (email: EmailDefinition) => `<mjml lang="en">- <mj-head>- <mj-title>${escape(mjmlVariables(email.subject))}</mj-title>- <mj-preview>${escape(mjmlVariables(email.previewText))}</mj-preview>- <mj-attributes>- <mj-all font-family="Helvetica, Arial, sans-serif" />- <mj-text font-size="${theme.styles.textBaseFontSize}px" line-height="${Math.round((theme.styles.textBaseFontSize * bodyLineHeightPercent) / 100)}px" color="${theme.styles.textBaseColor}" padding="0 0 ${paragraphSpacing}px" />- </mj-attributes>- </mj-head>- <mj-body width="600px" background-color="${theme.styles.backgroundColor}">- <mj-section background-color="${theme.styles.bodyColor}" padding="${theme.styles.bodyYPadding}px ${theme.styles.bodyXPadding}px">- <mj-column>- <mj-image src="img/cap-logo.png" alt="Cap" width="${logo.width}px" align="left" padding="0 0 24px" />- ${renderBody(email.body)}- <mj-text padding="8px 0 0">${signature.map(escape).join("<br />")}</mj-text>- <mj-text font-size="12px" line-height="19px" color="#6b7280" padding="24px 0 0">${escape(footer.company)}<br />${escape(footer.address)}<br /><a href="{unsubscribe_link}" style="color:#6b7280;text-decoration:underline">${escape(footer.unsubscribeLabel)}</a></mj-text>- </mj-column>- </mj-section>- </mj-body>-</mjml>-`;diff --git a/emails/onboarding-runtime.md b/emails/onboarding-runtime.mddeleted file mode 100644index fa61e5d08..000000000--- a/emails/onboarding-runtime.md+++ /dev/null@@ -1,33 +0,0 @@-# Free onboarding runtime--The `free-v2` journey uses the templates and conditional delays in `flows.ts`. The existing `free` journey remains available. Assignment is disabled by default.--## Enrollment--`LOOPS_FREE_EXPERIMENT_ENABLED=true` enables new assignments for signups on or after `LOOPS_FREE_EXPERIMENT_AFTER`. Configure a future boundary only after verifying the deployed code, contact properties, workflow, and custom email uploads.--A deterministic user-ID bucket assigns eligible independent free accounts equally between the two journeys. Loops stores the experiment ID, variant, and assignment timestamp together with the first lifecycle-stage update. Assignment survives later purchases and unsubscribes; subsequent updates do not replace it.--Existing enrolled users, imports, customers, invitees, teammate history, incomplete signups, and unsubscribed accounts cannot enter. The `free-v2` downstream guard additionally requires `capLifecycleStage=free-v2`. Consent, list membership, and audience guards apply throughout delivery. Product and billing changes use the existing durable sync queue.--## Activation signals--Accounts created from September 12, 2026 UTC use the new readiness query in either journey. Older accounts retain their existing queries and profile fingerprints. This fixed signal boundary is independent of the enrollment switch.--A completed cloud video requires positive duration, no screenshot flag or upload row, and a verified processing job or explicit published output/legacy completion marker with no processing job. Pending or failed uploads and processing suppress Pro and sharing follow-ups, including when an older video is complete.--`capHasSharedVideo` uses `firstViewEmailSentAt` on a completed video as a proxy for a non-owner page visit. It does not prove playback, and notification preferences can make it undercount. Local Studio recordings are not observed. Imported or uploaded videos can establish cloud readiness.--Follow-ups are suppressed for 24 hours after the latest synchronized application-notification signal. Profiles refresh hourly for new accounts, so this is not an atomic frequency lock across Loops and Resend; a refresh-to-delivery race remains possible. The configured journey allows at most three lifecycle messages in seven days, separated by at least 24 hours.--Pro links preserve the organization-billing destination through the existing login `next` parameter. Opening a link does not initiate payment.--## Verification and recovery--Create a new custom-email workflow with `scripts/loops/provision.ts --new-journey free-v2`, using the required private receipt, verified team and mailing list. New-journey mode refuses unrelated existing workflows. Export with `bun run emails:export --output <private directory>`, upload the archives in Loops, and review metadata, fallbacks, body, images, and footer. Store only nonsecret resource IDs in `resources.json`.--Run `bun run emails:check-loops --structure-only --allow-live` to verify remote structure and state. Omit `--allow-live` when only drafts are expected. API checks cannot establish custom-MJML content parity; browser review remains necessary. Every registered journey is included in the independent watchdog.--To stop new assignments, set `LOOPS_FREE_EXPERIMENT_ENABLED=false` and deploy. Existing assignments continue their journeys. Pause the corresponding Loops workflow when delivery itself must stop. Do not change the fixed activation boundary or reset assignment properties.--Before reverting to code without variant-aware routing, pause both free workflows and reconcile enrolled contacts: older code would route treatment contacts back to `free`. Never bulk resubscribe, re-enroll, or clear imported holds during recovery.diff --git a/emails/resources.json b/emails/resources.jsondeleted file mode 100644index 9df9a742f..000000000--- a/emails/resources.json+++ /dev/null@@ -1,73 +0,0 @@-{- "version": "cap-lifecycle-v1",- "teamName": "Cap Software, Inc.",- "resources": {- "theme": "cmtwxic0t0p030j03i4w01h9t",- "Cap lifecycle header v1": "cmtvpigup01e80j0xjmwxqzxu",- "Cap lifecycle signature v1": "cmtvpih0q01da0j20hgcd7ygv",- "free": "cmtvpih6201fp0jznodf8fpwz",- "customer": "cmtvpilm601f40jzwx3474cko",- "teammate": "cmtvpm0ag01it0j37w02o6wav",- "former": "cmtvpm8zm01ii0j01cz7d15qr",- "segment:customer-update": "cmtvpmfc201jw0j1b50wngv06",- "customer-update": "cmtvpmfxc01ls0j0nnlffombv",- "segment:free-update": "cmtvpmit001kb0j1v86w1bx2w",- "free-update": "cmtvpmjej01kr0j18cxoz2n0y",- "segment:customer-case-study": "cmumsn39j1mym0jx6xfs00g4y",- "customer-case-study": "cmumrftj50y4j0jy2giifxlnk",- "mailingList": "cmtvqgqjj027l0j10fbgb2uvy",- "Cap lifecycle header v2": "cmtwvpzle14zq0iydhsxuvn7j",- "Cap lifecycle signature v2": "cmtwvvcxf14yz0jzwk5rv3zsy",- "Cap lifecycle header v3": "cmtwwcneg16710j1dkycroiiq",- "Cap lifecycle signature v3": "cmtwwco1c15vb0iyd13663y8e",- "Cap lifecycle header v4": "cmtwwvlli00ao0jzwvjb03ixz",- "Cap lifecycle signature v4": "cmtwwvm6316gh0jzwdvr0bsgo",- "Cap lifecycle header v5": "cmtwx1d1q0oys0jyw6yq91naz",- "Cap lifecycle signature v5": "cmtwx4qyk0odg0j03ibll1cad",- "Cap lifecycle header v6": "cmtwxickf0d570jzvtpz1dyyh",- "Cap lifecycle signature v6": "cmtwxid5g17tp0jyc2mu1hgwj",- "free-v2": "cmtxlhkcw0dta0jzkd6an7xz0"- },- "operations": {- "free:guard": "n3",- "free:welcome:email": "n4",- "free:record:timer": "n5",- "free:record:branch": "n6",- "free:record:email": "n9",- "free:share:timer": "n10",- "free:share:branch": "n11",- "free:share:email": "n14",- "free:plans:timer": "n15",- "free:plans:email": "n16",- "customer:guard": "n3",- "customer:welcome:email": "n4",- "customer:workflow:timer": "n5",- "customer:workflow:email": "n6",- "customer:feedback:timer": "n7",- "customer:feedback:email": "n8",- "teammate:guard": "n3",- "teammate:welcome:email": "n4",- "teammate:handoff:timer": "n5",- "teammate:handoff:email": "n6",- "former:guard": "n3",- "former:feedback:timer": "n4",- "former:feedback:email": "n5",- "free-v2:guard": "n3",- "free-v2:welcome:email": "n4",- "free-v2:record:timer": "n5",- "free-v2:record:branch": "n6",- "free-v2:record:email": "n9",- "free-v2:plans:timer": "n10",- "free-v2:plans:branch": "n11",- "free-v2:plans:email": "n14",- "free-v2:share:timer": "n15",- "free-v2:share:branch": "n16",- "free-v2:share:email": "n19",- "free-v2:ai:timer": "n20",- "free-v2:ai:branch": "n21",- "free-v2:ai:email": "n24",- "free-v2:help:timer": "n25",- "free-v2:help:filter": "n27",- "free-v2:help:email": "n29"- }-}diff --git a/emails/types.ts b/emails/types.tsdeleted file mode 100644index 8fa2e5ad1..000000000--- a/emails/types.ts+++ /dev/null@@ -1,31 +0,0 @@-import type { Condition } from "./audiences";-import type { contactFallbacks } from "./brand";--export type Audience = "free" | "customer" | "teammate" | "former";-export type EmailDefinition = {- id: string;- key: string;- purpose: string;- subject: string;- previewText: string;- body: string;- assets?: string[];- variables: (keyof typeof contactFallbacks)[];-};-export type Message = EmailDefinition & {- delayDays: number;- onlyIf?: { property: string; value: boolean };-};-export type Journey = {- key: string;- name: string;- audience: Audience;- promotional: boolean;- messages: Message[];-};-export type Campaign = EmailDefinition & {- name: string;- audience: Audience;- promotional: boolean;- audienceConditions?: Condition[];-};diff --git a/package.json b/package.jsonindex 579fd6379..bb12861f1 100644--- a/package.json+++ b/package.json@@ -1,11 +1,6 @@{"type": "module","scripts": {- "emails:catalog": "bun scripts/emails/manage.ts",- "emails:check": "bun scripts/emails/manage.ts --check",- "emails:check-loops": "bun scripts/loops/verify.ts",- "emails:export": "bun scripts/emails/export-mjml.ts",- "emails:logo": "bun scripts/emails/export-logo.ts","build": "dotenv -e .env -- turbo run build","build:web": "turbo run build:web","build:web:docker": "bun run --filter=@cap/web build:docker",diff --git a/scripts/emails/catalog.test.ts b/scripts/emails/catalog.test.tsdeleted file mode 100644index 1f6c02559..000000000--- a/scripts/emails/catalog.test.ts+++ /dev/null@@ -1,135 +0,0 @@-import { describe, expect, test } from "bun:test";-import { components, emailContent } from "../../emails/brand";-import { journeys } from "../../emails/flows";-import { freeWelcome } from "../../emails/marketing/free-welcome";-import {- catalogExcerpt,- flowSteps,- renderCatalog,- validateCatalog,- validateEmail,- validateTheme,-} from "./catalog";-import { assertEmailContent, normalizeLmx } from "./content";--describe("email library", () => {- test("catalogue excerpts keep malformed markup inert", () => {- expect(catalogExcerpt("<script>alert(1)</script>")).toBe(- "<script>alert(1)</script>",- );- expect(catalogExcerpt("<Paragraph>Hello</Paragraph><script src=x")).toBe(- "Hello\n\n<script src=x",- );- expect(- catalogExcerpt("<Paragraph>Record & share<Br />Next step</Paragraph>"),- ).toBe("Record & share\nNext step");- expect(catalogExcerpt("<Paragraph>Q&A</Paragraph>")).toBe("Q&A");- expect(catalogExcerpt("<Paragraph>&lt;b&gt;</Paragraph>")).toBe(- "&lt;b&gt;",- );- });- test("every template and known application send source is registered", async () => {- expect(await validateCatalog()).toEqual([]);- });- test("line heights reject pixel values that collapse the Loops footer", () => {- expect(validateTheme({ textBaseLineHeight: 26 })).toEqual([- "textBaseLineHeight must be a percentage from 100 to 300",- ]);- expect(- validateTheme({ textBaseLineHeight: 160, heading1LineHeight: 130 }),- ).toEqual([]);- expect(validateTheme({ textBaseLineHeight: Number.NaN })).toHaveLength(1);- });- test("variables in subjects require a declared contract and fallback", () => {- expect(- validateEmail({ ...freeWelcome, subject: "Hello {contact.company}" }),- ).toContain("Undeclared contact variable: contact.company");- expect(- validateEmail({ ...freeWelcome, subject: "Hello {data.firstName}" }),- ).toContain("Undeclared contact variable: data.firstName");- });- test("per-email branding overrides and template references are rejected", () => {- expect(- validateEmail({- ...freeWelcome,- body: `${freeWelcome.body}<Style themeId="other" />`,- }),- ).toContain(- "Use shared branding; do not embed Style or Component in email bodies",- );- expect(- validateEmail({- ...freeWelcome,- body: freeWelcome.body.replace(- "<Paragraph>",- '<Paragraph textColor="#ff0000">',- ),- }),- ).toContain("Put visual branding in emails/brand.ts");- });- test("relative delays become cumulative days, including skipped reminders", () => {- expect(flowSteps(journeys[0]).map((step) => step.day)).toEqual([- 0, 2, 5, 9,- ]);- const catalogue = renderCatalog();- expect(catalogue).toContain("branch1 -->|No: skip| next1((Continue))");- expect(catalogue).toContain('next1 --> wait2["Wait 3 days"]');- });-});--describe("Loops content comparison", () => {- const ids = { theme: "theme", header: "header", signature: "signature" };- const content = emailContent(freeWelcome, ids);- test("accepts editor formatting while retaining semantic whitespace", () => {- expect(- normalizeLmx('<Button align="left" href="https://cap.so">Go</Button>'),- ).toBe(normalizeLmx('<Button href="https://cap.so">Go</Button>'));- expect(- normalizeLmx("<Paragraph><Strong>A</Strong> B</Paragraph>"),- ).not.toBe(normalizeLmx("<Paragraph><Strong>A</Strong>B</Paragraph>"));- const expanded = content.lmx- .replace(- '<Component componentId="header" />',- `<Component componentId="header">\n${components[0].lmx}\n</Component>`,- )- .replace(- '<Component componentId="signature" />',- `<Component componentId="signature">\n${components[1].lmx}\n</Component>`,- );- expect(() =>- assertEmailContent({ ...content, lmx: expanded }, freeWelcome, ids),- ).not.toThrow();- });- test("detects added content, changed links, styling and component overrides", () => {- for (const lmx of [- `${content.lmx}<Paragraph>Unexpected promotion</Paragraph>`,- content.lmx.replace("https://cap.so/download", "https://example.com"),- content.lmx.replace("<Paragraph ", '<Paragraph textColor="#ff0000" '),- content.lmx.replace(- '<Component componentId="header" />',- '<Component componentId="header"><Paragraph>Changed header</Paragraph></Component>',- ),- ]) {- expect(lmx).not.toBe(content.lmx);- expect(() =>- assertEmailContent({ ...content, lmx }, freeWelcome, ids),- ).toThrow();- }- });- test("detects changed sender metadata and fallbacks", () => {- expect(() =>- assertEmailContent(- { ...content, fromName: "Another sender" },- freeWelcome,- ids,- ),- ).toThrow();- expect(() =>- assertEmailContent(- { ...content, contactPropertiesFallbacks: {} },- freeWelcome,- ids,- ),- ).toThrow();- });-});diff --git a/scripts/emails/catalog.ts b/scripts/emails/catalog.tsdeleted file mode 100644index 71825b697..000000000--- a/scripts/emails/catalog.ts+++ /dev/null@@ -1,361 +0,0 @@-import { readdir, readFile } from "node:fs/promises";-import { fileURLToPath } from "node:url";-import { applicationEmails } from "../../emails/application";-import { contactProperties } from "../../emails/audiences";-import {- components,- contactFallbacks,- sender,- theme,-} 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";--export const root = new URL("../../", import.meta.url);-export const marketingEmails = [- ...journeys.flatMap((journey) => journey.messages),- ...campaignTemplates,-];--export const validateEmail = (email: EmailDefinition) => {- const errors: string[] = [];- if (!/^[a-z][a-z0-9-]+$/.test(email.id)) errors.push("Invalid email ID");- for (const field of ["purpose", "subject", "previewText", "body"] as const) {- if (!email[field].trim()) errors.push(`Missing ${field}`);- }- if (/<(?:Style|Component)\b/.test(email.body))- errors.push(- "Use shared branding; do not embed Style or Component in email bodies",- );- if (- /\b(?:bgColor|textColor|fontSize|fontFamily|borderRadius|lineHeight)\s*=/.test(- email.body,- )- )- errors.push("Put visual branding in emails/brand.ts");- const content = `${email.subject}\n${email.previewText}\n${email.body}`;- const variables = [...content.matchAll(/\{([^{}]+)\}/g)].map(- (match) => match[1],- );- const declared = new Set<string>(email.variables);- for (const variable of variables) {- const key = variable.replace(/^contact\./, "");- if (!variable.startsWith("contact.") || !declared.has(key))- errors.push(`Undeclared contact variable: ${variable}`);- if (!Object.hasOwn(contactFallbacks, key))- errors.push(`Missing fallback: ${key}`);- }- for (const key of declared) {- if (!variables.includes(`contact.${key}`))- errors.push(`Unused declared variable: ${key}`);- }- if (new TextEncoder().encode(email.body).length > 95_000)- errors.push(- "Email body leaves insufficient space for branding under the 100 KB LMX limit",- );- for (const match of email.body.matchAll(- /<(?:Button|Link|Image)\b([^>]*)>/g,- )) {- const href = /\bhref="([^"]+)"/.exec(match[1])?.[1];- if (!href || !/^(https:\/\/|mailto:)/.test(href))- errors.push("Buttons and links need an https or mailto destination");- }- const assetNames = (email.assets ?? []).map((path) => path.split("/").at(-1));- if (- new Set(assetNames).size !== assetNames.length ||- assetNames.includes("cap-logo.png") ||- (email.assets ?? []).some((path) => !/^emails\/assets\/[^/]+$/.test(path))- )- errors.push("Email assets need unique filenames under emails/assets");- for (const match of email.body.matchAll(/<Image\b([^>]*)>/g)) {- const src = /\bsrc="img\/([^"]+)"/.exec(match[1])?.[1];- const alt = /\balt="([^"]+)"/.exec(match[1])?.[1];- if (!src || !assetNames.includes(src) || !alt)- errors.push(- "Images need descriptive alt text and a declared bundled asset",- );- }- return errors;-};--export const flowSteps = (journey: Journey) => {- let day = 0;- return journey.messages.map((message) => {- day += message.delayDays;- return { ...message, day };- });-};--export const validateTheme = (styles: Record<string, unknown>) =>- Object.entries(styles)- .filter(- ([key, value]) =>- /lineheight$/i.test(key) &&- (typeof value !== "number" ||- !Number.isFinite(value) ||- value < 100 ||- value > 300),- )- .map(([key]) => `${key} must be a percentage from 100 to 300`);-export const validateCatalog = async () => {- const errors = marketingEmails.flatMap((email) =>- validateEmail(email).map((error) => `${email.id}: ${error}`),- );- errors.push(...validateTheme(theme.styles));- for (const component of components) {- for (const [, value] of component.lmx.matchAll(/\blineHeight="([^"]*)"/g))- errors.push(...validateTheme({ lineHeight: Number(value) }));- }- const allIds = [...marketingEmails, ...applicationEmails].map(- (email) => email.id,- );- if (new Set(allIds).size !== allIds.length)- errors.push("Duplicate email IDs");- for (const journey of journeys) {- if (!journey.messages.length) errors.push(`Empty journey: ${journey.key}`);- const keys = journey.messages.map((message) => message.key);- if (new Set(keys).size !== keys.length)- errors.push(`Duplicate steps: ${journey.key}`);- if (journey.audience === "teammate" && journey.promotional)- errors.push("Teammates cannot receive promotional journeys");- for (const message of journey.messages) {- if (!Number.isInteger(message.delayDays) || message.delayDays < 0)- errors.push(`Invalid delay: ${message.id}`);- if (- message.onlyIf &&- contactProperties[- message.onlyIf.property as keyof typeof contactProperties- ] !== "boolean"- )- errors.push(`Unknown boolean milestone: ${message.onlyIf.property}`);- }- }- const files = (await readdir(new URL("emails/marketing/", root))).filter(- (file) => file.endsWith(".ts"),- );- const expected = marketingEmails.map((email) => `${email.id}.ts`);- for (const file of new Set([...files, ...expected])) {- if (!files.includes(file) || !expected.includes(file))- errors.push(`Unregistered or missing email: ${file}`);- }- const templateFiles = (- await readdir(new URL("packages/database/emails/", root))- ).filter((file) => file.endsWith(".tsx"));- const registeredTemplates = applicationEmails.map(- (email) => `${email.template}.tsx`,- );- for (const file of new Set([...templateFiles, ...registeredTemplates])) {- if (!templateFiles.includes(file) || !registeredTemplates.includes(file))- errors.push(`Unregistered or missing application template: ${file}`);- }- const sources = new Set(applicationEmails.flatMap((email) => email.sources));- for (const source of sources) {- try {- await readFile(new URL(source, root), "utf8");- } catch {- errors.push(`Missing application source: ${source}`);- }- }- for (const folder of [- "apps/web/actions",- "apps/web/app",- "apps/web/lib",- "packages/database/auth",- ]) {- for await (const file of new Bun.Glob("**/*.{ts,tsx}").scan(- fileURLToPath(new URL(`${folder}/`, root)),- )) {- const source = `${folder}/${file}`;- const text = await readFile(new URL(source, root), "utf8");- if (/\bsendEmail\s*\(/.test(text) && !sources.has(source))- errors.push(`Unregistered application send source: ${source}`);- }- }- return errors;-};--const cell = (text: string) =>- text.replaceAll("|", "\\|").replaceAll("\n", " ");-const sourceLink = (source: string, label = source) =>- `[${label}](../${source.replaceAll("[", "%5B").replaceAll("]", "%5D")})`;-const sourceFor = (email: EmailDefinition) => `emails/marketing/${email.id}.ts`;-const resourceIds: Record<string, string> = resources.resources;-const flowUrl = (key: string) =>- `https://app.loops.so/workflows/${resourceIds[key]}`;--export const catalogExcerpt = (body: string) =>- body- .replace(/<\/(Paragraph|Button)>/g, "\n\n")- .replace(/<Br\s*\/>/g, "\n")- .replace(/<\/?(?:Paragraph|Button|Link|Strong|Em|Image)\b[^>]*>/g, "")- .replaceAll("&", "&")- .replaceAll("&", "&")- .replaceAll("<", "<")- .replaceAll(">", ">")- .trim();--export const renderCatalog = () => {- const lines = [- "# Cap email catalogue",- "",- "Generated from the email library with `bun run emails:catalog`. Edit the source files, then regenerate. [Editing guide](README.md).",- "",- "## Lifecycle flows",- "",- "These are the locally configured journeys. This document is not a live status check. Imports remain held. Run `bun run emails:check-loops --structure-only --allow-live` to verify the remote workflow structure and status; review custom MJML content in the browser.",- "",- "| Flow | Audience | Schedule after entry | Emails |",- "| --- | --- | --- | --- |",- ...journeys.map(- (journey) =>- `| [${cell(journey.name.replace("Cap | ", ""))}](${flowUrl(journey.key)}) | ${journey.audience} | ${flowSteps(- journey,- )- .map((message) => `Day ${message.day}`)- .join(", ")} | ${journey.messages.length} |`,- ),- "",- "Completed signups reach Loops through Stripe; SSO uses a small direct fallback. Cap supplies targeting through a durable sync queue, without a separate marketing opt-in step. Existing opt-outs and suppressions take precedence. Historical imports stay held; a new accepted invitation can start teammate help only.",- "",- "Journeys require global subscription, capConsent=subscribed, the exact audience, lifecycle enabled and onboarding eligible. capConsent is a legacy migration guard, not a separate consent-capture requirement for new signups. These filters continue to apply downstream. Free/former promotional flows additionally exclude teammates and require promotional eligibility.",- "",- "Teammate history takes priority over paid/free classification. Ambiguous contacts receive no journey. [Audience classification and consent](../scripts/loops/README.md#audience-rules).",- "",- "The independent watchdog checks every registered journey and alerts when an active flow requires a manual pause. It can hold paused/draft journeys with an impossible subscription condition. Recovery never resumes delivery automatically. Check sync health before campaign sends. See the [outage and resume procedure](../scripts/loops/README.md#outage-protection) and [onboarding runtime](onboarding-runtime.md).",- "",- ];- for (const journey of journeys) {- lines.push(- `### ${journey.name.replace("Cap | ", "")}`,- "",- `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: ${workflowAudience(journey)- .conditions.map(- (condition) =>- `${condition.key} ${condition.operator}${"value" in condition ? ` ${condition.value}` : ""}`,- )- .join("; ")}.`,- "",- "```mermaid",- "flowchart TD",- ` entry["Stage becomes ${journey.key}"] --> guard["Consent and audience guards"]`,- );- let previous = "guard";- for (const [index, message] of flowSteps(journey).entries()) {- if (message.delayDays) {- lines.push(- ` ${previous} --> wait${index}["Wait ${message.delayDays} days"]`,- );- previous = `wait${index}`;- }- if (message.onlyIf) {- lines.push(- ` ${previous} --> branch${index}{"${message.onlyIf.property} is ${message.onlyIf.value}?"}`,- ` branch${index} -->|Yes| email${index}["Day ${message.day}: ${message.key}"]`,- ` branch${index} -->|No: skip| next${index}((Continue))`,- ` email${index} --> next${index}`,- );- previous = `next${index}`;- } else {- lines.push(- ` ${previous} --> email${index}["Day ${message.day}: ${message.key}"]`,- );- previous = `email${index}`;- }- }- lines.push(- ` ${previous} --> exit["End"]`,- "```",- "",- "| Day | Subject and source | Send condition |",- "| --- | --- | --- |",- ...flowSteps(journey).map(- (message) =>- `| ${message.day} | ${sourceLink(sourceFor(message), cell(message.subject))} | ${message.onlyIf ? `\`${message.onlyIf.property}=${message.onlyIf.value}\`` : "Journey guards"} |`,- ),- "",- );- }- lines.push(- "## Campaign templates",- "",- "Campaigns are manually scheduled product updates, with no automatic enrollment. Both require subscription, capConsent=subscribed and their exact audience. The free template also requires promotional eligibility and excludes teammates.",- "",- "| Campaign | Audience | Subject and source | Loops ID |",- "| --- | --- | --- | --- |",- ...campaignTemplates.map(- (email) =>- `| ${cell(email.name.replace("Cap | ", ""))} | ${email.audience} | ${sourceLink(sourceFor(email), cell(email.subject))} | \`${resourceIds[email.key]}\` |`,- ),- "",- "## Branding and personalization",- "",- `Shared design, logo, signature, footer, sender and fallbacks: ${sourceLink("emails/brand.ts")}. Custom MJML delivery is generated by ${sourceLink("emails/mjml.ts")}.`,- "",- `Sender: ${sender.fromName}; local part \`${sender.fromEmail}\` on the Loops sending domain. Reply-to: ${sender.replyToEmail}.`,- "",- "The shared header uses the canonical Cap icon and vector wordmark, with white backing for contrast on dark backgrounds. The complete greeting is `capGreeting`, with `Hey,` as its fallback. One compact footer contains the company, address and unsubscribe link.",- "",- "Customer welcome variations come from [customer-copy.ts](customer-copy.ts); eligibility is resolved from account and license state in the profile sync.",- "",- "| Plan | Welcome variation |",- "| --- | --- |",- ...Object.values(customerCopy).map(- (copy) => `| ${copy.plan} | ${cell(copy.welcome)} |`,- ),- "",- "## Marketing email copy",- "",- "The excerpts below show content, not an email-client render. Branding and required Loops footer content are composed separately.",- "",- );- for (const email of marketingEmails) {- lines.push(- `### ${email.id}`,- "",- email.purpose,- "",- `**Subject:** ${email.subject}`,- "",- `**Preview:** ${email.previewText}`,- "",- `**Variables:** ${email.variables.map((key) => `\`contact.${key}\` (fallback: ${contactFallbacks[key]})`).join("; ")}`,- "",- `**Edit:** ${sourceLink(sourceFor(email))}`,- "",- ...catalogExcerpt(email.body).split("\n"),- "",- );- }- lines.push(- "## Application emails",- "",- "These are repository send paths and retained templates, not confirmation of production delivery. They continue through Resend and keep their existing React Email layouts. Loops audience filters do not control them. Shared marketing branding does not automatically restyle these templates.",- "",- "| Email | Trigger | Recipients | Template |",- "| --- | --- | --- | --- |",- ...applicationEmails.map(- (email) =>- `| ${email.name} | ${cell(email.trigger)} | ${cell(email.recipients)} | ${sourceLink(`packages/database/emails/${email.template}.tsx`, email.template)} |`,- ),- "",- );- for (const email of applicationEmails) {- lines.push(- `### ${email.name}`,- "",- email.notes,- "",- `Send source: ${email.sources.length ? email.sources.map((source) => sourceLink(source)).join(", ") : "No current call site"}.`,- "",- );- }- return `${lines.join("\n").trim()}\n`;-};--export const catalogPath = fileURLToPath(new URL("emails/CATALOG.md", root));diff --git a/scripts/emails/content.ts b/scripts/emails/content.tsdeleted file mode 100644index 13b6653d1..000000000--- a/scripts/emails/content.ts+++ /dev/null@@ -1,47 +0,0 @@-import assert from "node:assert/strict";-import { type BrandIds, components, emailContent } from "../../emails/brand";--export const normalizeLmx = (lmx: string) =>- lmx- .trim()- .replace(/>\s*\n\s*</g, "><")- .replace(- /<Strong><Link([^>]*)>([^<]*)<\/Link><\/Strong>/g,- "<Link$1><Strong>$2</Strong></Link>",- )- .replace(- /<(\w+)((?:\s+[\w]+="[^"]*")*)\s*(\/?)>/g,- (_, tag: string, attributes: string, closing: string) => {- const normalized = [...attributes.matchAll(/([\w]+)="([^"]*)"/g)]- .filter(([, key, value]) => key !== "align" || value !== "left")- .map(([, key, value]) => `${key}="${value}"`)- .sort();- return `<${tag}${normalized.length ? ` ${normalized.join(" ")}` : ""}${closing ? " /" : ""}>`;- },- );--export const assertEmailContent = (- actual: Record<string, unknown>,- message: { subject: string; previewText: string; body: string },- ids: BrandIds,-) => {- const expected = emailContent(message, ids);- for (const [key, value] of Object.entries(expected)) {- if (key !== "lmx")- assert.deepEqual(actual[key], value, `Email ${key} differs`);- }- assert.equal(typeof actual.lmx, "string");- let expanded = expected.lmx;- for (const [index, id] of [ids.header, ids.signature].entries()) {- expanded = expanded.replace(- `<Component componentId="${id}" />`,- `<Component componentId="${id}">${components[index].lmx}</Component>`,- );- }- const normalized = normalizeLmx(actual.lmx as string);- assert(- normalized === normalizeLmx(expanded) ||- normalized === normalizeLmx(expected.lmx),- "Email LMX differs from local body, branding references or shared component content",- );-};diff --git a/scripts/emails/export-logo.ts b/scripts/emails/export-logo.tsdeleted file mode 100644index 24334196a..000000000--- a/scripts/emails/export-logo.ts+++ /dev/null@@ -1,26 +0,0 @@-import { writeFile } from "node:fs/promises";-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import sharp from "sharp";-import { logo } from "../../emails/brand";-import { Logo } from "../../packages/ui/src/components/icons/Logo";--const markup = renderToStaticMarkup(- createElement(Logo, { viewBoxDimensions: "4 4 97.21 32" }),-);-const svg = markup.match(/<svg[\s\S]*<\/svg>/)?.[0];-if (!svg) throw new Error("Cap logo did not render an SVG");-const backed = svg- .replace("<svg ", '<svg width="486" height="160" ')- .replace(- /<path/,- '<rect x="4" y="4" width="97.21" height="32" fill="#ffffff" /><path',- );-await writeFile(- new URL(`../../${logo.file}`, import.meta.url),- await sharp(Buffer.from(backed))- .flatten({ background: "#ffffff" })- .png()- .toBuffer(),-);-console.log(`Rendered the canonical Cap logo to ${logo.file}`);diff --git a/scripts/emails/export-mjml.ts b/scripts/emails/export-mjml.tsdeleted file mode 100644index 61ea32466..000000000--- a/scripts/emails/export-mjml.ts+++ /dev/null@@ -1,67 +0,0 @@-import { execFileSync } from "node:child_process";-import { createHash } from "node:crypto";-import {- copyFile,- mkdir,- mkdtemp,- readFile,- rm,- writeFile,-} from "node:fs/promises";-import { tmpdir } from "node:os";-import { basename, join, resolve } from "node:path";-import { parseArgs } from "node:util";-import { contactFallbacks, logo, sender } from "../../emails/brand";-import { mjmlVariables, renderMjml } from "../../emails/mjml";-import { marketingEmails, root, validateCatalog } from "./catalog";--const { values } = parseArgs({ options: { output: { type: "string" } } });-if (!values.output) throw new Error("Pass --output with the export directory");-const errors = await validateCatalog();-if (errors.length) throw new Error(errors.join("\n"));-const output = resolve(values.output);-await mkdir(output, { recursive: true });-const asset = await readFile(new URL(logo.file, root));-const manifest = [];-for (const email of marketingEmails) {- const temporary = await mkdtemp(join(tmpdir(), "cap-email-"));- try {- await mkdir(join(temporary, "img"));- const mjml = renderMjml(email);- await writeFile(join(temporary, "index.mjml"), mjml);- await writeFile(join(temporary, "img/cap-logo.png"), asset);- const hash = createHash("sha256").update(mjml).update(asset);- for (const path of email.assets ?? []) {- const image = await readFile(new URL(path, root));- await writeFile(join(temporary, "img", basename(path)), image);- hash.update(image);- }- const archive = join(temporary, `${email.id}.zip`);- execFileSync("zip", ["-q", "-r", archive, "index.mjml", "img"], {- cwd: temporary,- });- await copyFile(archive, join(output, `${email.id}.zip`));- await writeFile(join(output, `${email.id}.mjml`), mjml);- manifest.push({- id: email.id,- file: `${email.id}.zip`,- sha256: hash.digest("hex"),- subject: mjmlVariables(email.subject),- previewText: mjmlVariables(email.previewText),- ...sender,- emailFormat: "mjml",- fallbacks: Object.fromEntries(- email.variables.map((key) => [key, contactFallbacks[key]]),- ),- });- } finally {- await rm(temporary, { recursive: true, force: true });- }-}-await writeFile(- join(output, "manifest.json"),- `${JSON.stringify(manifest, null, 2)}\n`,-);-console.log(- `Exported ${manifest.length} email archives and manifest to ${output}`,-);diff --git a/scripts/emails/manage.ts b/scripts/emails/manage.tsdeleted file mode 100644index 3ab377ad9..000000000--- a/scripts/emails/manage.ts+++ /dev/null@@ -1,26 +0,0 @@-import { readFile, writeFile } from "node:fs/promises";-import { parseArgs } from "node:util";-import {- catalogPath,- marketingEmails,- renderCatalog,- validateCatalog,-} from "./catalog";--const { values } = parseArgs({- options: { check: { type: "boolean", default: false } },-});-const errors = await validateCatalog();-if (errors.length) throw new Error(errors.join("\n"));-const content = renderCatalog();-if (values.check) {- const saved = await readFile(catalogPath, "utf8").catch(() => "");- if (saved !== content)- throw new Error("Email catalogue is stale. Run bun run emails:catalog.");- console.log(- `Email catalogue, ${marketingEmails.length} marketing messages, variables and application source inventory verified.`,- );-} else {- await writeFile(catalogPath, content);- console.log(`Updated ${catalogPath}`);-}diff --git a/scripts/emails/mjml.test.ts b/scripts/emails/mjml.test.tsdeleted file mode 100644index de082aff5..000000000--- a/scripts/emails/mjml.test.ts+++ /dev/null@@ -1,39 +0,0 @@-import { describe, expect, test } from "bun:test";-import { contactFallbacks, footer, logo } from "../../emails/brand";-import { freeWelcome } from "../../emails/marketing/free-welcome";-import { renderMjml } from "../../emails/mjml";-import { marketingEmails } from "./catalog";--describe("marketing delivery templates", () => {- test("every email retains its links and has one concise unsubscribe footer", () => {- for (const email of marketingEmails) {- const mjml = renderMjml(email);- expect(mjml.match(/href="\{unsubscribe_link\}"/g)).toHaveLength(1);- expect(mjml).toContain(footer.address);- expect(mjml).not.toContain("You are receiving");- expect(mjml).not.toContain("{contact.");- expect(mjml).not.toContain("Hey {firstName},");- expect(mjml).toContain("<mj-preview>");- for (const [, href] of email.body.matchAll(/href="([^"]+)"/g))- expect(mjml).toContain(`href="${href}"`);- }- });- test("greeting fallback contains the complete salutation", () => {- expect(contactFallbacks.capGreeting).toBe("Hey,");- expect(renderMjml(freeWelcome)).toContain(- "<mj-text>{capGreeting}</mj-text>",- );- });- test("logo and text share the same zero left padding", () => {- const mjml = renderMjml(freeWelcome);- expect(mjml).toContain(`width="${logo.width}px" align="left"`);- expect(mjml).toContain('src="img/cap-logo.png" alt="Cap"');- expect(mjml).toContain('padding="0 0 24px"');- expect(mjml).toContain('padding="0 0 16px"');- });- test("unsupported new content blocks fail instead of silently disappearing", () => {- expect(() =>- renderMjml({ ...freeWelcome, body: "<Columns>Unsupported</Columns>" }),- ).toThrow("Unsupported marketing content tag");- });-});diff --git a/scripts/loops/README.md b/scripts/loops/README.mdindex f2345e3c3..53d505d7a 100644--- a/scripts/loops/README.md+++ b/scripts/loops/README.md@@ -1,149 +1,8 @@-# Cap lifecycle email migration+# Loops profile sync-Marketing source and shared branding now live in [emails/](../../emails/README.md). Start with the [email catalogue and flow maps](../../emails/CATALOG.md); regenerate it with `bun run emails:catalog`. Run `bun run emails:check` for local checks and `bun run emails:check-loops --structure-only` for read-only graph checks. Custom MJML content requires browser review; see the email library instructions.+This folder holds the tests and manual runners for the Loops profile sync in [`packages/database/loops/`](../../packages/database/loops/), which the web app runs from `/api/cron/sync-loops`.-This prepares Cap's Bento audience and replacement Loops journeys. Provisioning creates drafts only. Importing and syncing keep `capLifecycleEnabled=false`, `capOnboardingEligible=false`, and `capLifecycleStage=idle`. No script activates workflows, sends messages, or replays historical events.+- `bun scripts/loops/seed.ts` reports how many completed signups would be queued; `--apply` queues them.+- `bun scripts/loops/sync.ts --apply` processes a bounded batch with the same worker as the cron route.-The September 2026 repository audit found no Bento SDK, environment variable, or send call to replace. Bento's marketing automations were configured outside this repository. Existing Resend authentication, invitation, billing, notification, support, and BAA emails remain in place.--## Audience rules--| Audience | Evidence | Draft journey |-| --------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |-| Independent free user | Independent signup or a matching personal organization created at signup, with no paid entitlement or uncertain customer history | Welcome, recording help on day 2, sharing help on day 5, plan guidance on day 9 |-| Customer | Active/trialing/paid/past-due Cap Pro, a paid organization seat, or a currently valid desktop/self-hosted license | Plan-specific welcome, a reusable recording idea on day 3, feedback on day 7 |-| Teammate | Invitation, SSO, another owner's organization, third-party subscription, or a previously recorded teammate flag | Workspace setup, then handoff guidance on day 3; no promotional journey |-| Former customer | Canceled cloud subscription with no desktop/self-hosted license history | Feedback request after 14 days |-| Unknown | Missing identity/origin, stale customer tags, expired license evidence, or ambiguous entitlement | No journey or campaign audience |--Teammate evidence takes priority and is retained after membership changes. A future independently initiated purchase does not automatically erase that history. Customer classification uses Cap and the separate license database, not Bento's historical customer tag alone. A license's active flag is insufficient without a future renewal date.--The production enrollment policy is automatic addition to Loops on completed Cap signup, including completed teammate signup. No separate marketing opt-in checkbox or consent-evidence record is required by this product policy. Existing global unsubscribes, mailing-list opt-outs, bounces and suppressions still take precedence; another signup or profile update must not resubscribe an existing contact. Creating an invitation alone does not enroll its recipient. Teammates receive workspace help only, while independent users and customers receive their matching journeys.--The current draft journeys require a global subscription, `capConsent=subscribed`, the correct audience, and both enrollment flags. `capConsent` is a legacy migration guard; it must not introduce a separate consent-capture step for new signups. The audience filter applies downstream. Free/former promotional journeys also require `capTeammate=false` and `capPromotionalEligible=true`. Recording/sharing branches skip the corresponding reminder when the known cloud milestone is complete; local-only recordings cannot be observed by this sync.--All imported contacts remain held, including recent signups. Historical contacts must never be enrolled by replaying a contact-created event or bulk changing their lifecycle stage.--## Consent and private data--`prepare.ts` excludes source opt-outs, suppression flags, bounces, complaints, and conflicting negative subscription fields from the positive import. It also produces a normalized-email SHA-256 registry for every source row. Retain that registry even when excluded addresses are not created in Loops. Hashes are sensitive matching identifiers, not anonymous data.--Before native Stripe imports can feed live journeys, every Bento opt-out must exist in Loops as an unsubscribed contact or an equivalent provider suppression, including addresses missing from the positive import. A private hash archive alone cannot block a later native Stripe import. Reconcile existing destination records without changing their identities; create missing negative records only in a held, unsubscribed state with workflow triggers off. Do not import excluded addresses as new subscribed contacts. Loops-native global and mailing-list opt-outs must survive migration and later syncs. The normal sync never writes `subscribed=true` to an existing contact and never replaces mailing-list preferences. Missing imported contacts are not recreated.--Keep exports, prepared contacts, CSVs, registry files, receipts, database connection strings, and API keys outside Git, in a private directory. Do not expose license keys; the classifier only needs email, entitlement kind, active status, and renewal date.--## Commands--Run from the repository root with Bun 1.4. Supply `LOOPS_API_KEY` through the process environment. Every API command checks the exact expected team name. Cap's migration account is **Cap Software, Inc.**; a separate Loops account named **Cap** must not be used.--```sh-bun scripts/loops/provision.ts --team 'Cap Software, Inc.' --dry-run-bun scripts/loops/verify.ts --team 'Cap Software, Inc.' --state "$LOOPS_PRIVATE_DIR/provision-state.json" --mailing-list "$LOOPS_MAILING_LIST_ID" --structure-only-bun scripts/loops/prepare.ts --sources "$LOOPS_PRIVATE_DIR" --output "$LOOPS_PRIVATE_DIR/import"-bun scripts/loops/import.ts --team 'Cap Software, Inc.' --contacts "$LOOPS_PRIVATE_DIR/import/contacts.json" --receipt "$LOOPS_PRIVATE_DIR/import/receipt.jsonl" --mailing-list "$LOOPS_MAILING_LIST_ID"-```--Review the dry-run counts, then add `--apply` to import. Use the same receipt to resume after interruption; existing identities are checked and enriched without resubscribing. Invalid rows are recorded privately. Correct their input before using `--retry-invalid`. A network-interrupted create may have succeeded, so reconcile through the same importer rather than deleting/recreating contacts.--The source directory must contain arrays in `bento-contacts.json`, `cap-users.json`, `cap-memberships.json`, `license-licenses.json`, `cap-invites.json`, `cap-sso.json`, and `cap-videos.json`. Their shapes are defined in `profile.ts`, `prepare.ts`, and `sources.ts`. Preserve original source CSVs. Fresh source snapshots are required; preparation refuses files older than 24 hours.--The native Loops CSV importer can be used for the reviewed positive file. Check every column mapping, select the migration mailing list, and leave **Trigger workflows** off. Loops matches user ID before email; resolve destination identity conflicts first. Export the destination afterward and reconcile all intended addresses, opt-outs, audience fields, and enrollment holds. Native CSV imports and API receipts are separate records.--The legacy native provisioner uses revision checks and a private receipt, but now refuses `--apply` because managed emails use custom MJML. Generate uploads with `emails:export` and review them in the browser. `verify.ts --structure-only` checks graphs, downstream filters, reconnections, timing, segments, mailing lists, draft status and custom format. The beta API cannot read MJML content or verify its Guardian results. Never treat a structure check as content parity.--## Repository rollout--Normal completed signups create or reuse a Stripe customer. The native Loops Stripe integration is connected and enabled for `customer.created` and `customer.updated`. Both import names and assign the Product updates and tips list; additional custom events are blank. All other Stripe event types are disabled and production email workflows remain drafts. Cap then supplies the audience, greeting, paid/license entitlement and recording milestones. A contact cannot enter onboarding until Cap has completed its billing bootstrap and supplied the audience. SSO skips Stripe, so the worker creates those contacts directly, held and marked as teammates before enrollment.--`users.marketingOrigin` permanently identifies teammates. Invitation provisioning excludes sales immediately in local state; accepting an invite queues helpful onboarding. SSO provisioning does the same when a membership or onboarding is new. An existing imported account accepting a new invite after cutover can receive teammate help; importing historical records alone never starts a sequence. Every workflow has re-entry disabled and checks its audience downstream. Teammates cannot move back into a sales audience after leaving an organisation or buying a plan.--There 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. 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.--Deploy the generated schema before code that selects the new columns. The unshipped migration containing `marketing_contacts` was replaced using Drizzle's migration tooling; no production table was dropped. The implementation is currently behind disabled environment gates:--| Variable | Purpose |-| ------------------------------- | ------------------------------------------------------------------------ |-| `LOOPS_SYNC_ENABLED=true` | Enables queue writes and processing; otherwise both are off |-| `LOOPS_SYNC_MODE=test` | Default mode; restricts processing to the explicit owned-email allowlist |-| `LOOPS_TEST_EMAILS` | Comma-separated owned test addresses |-| `LOOPS_API_KEY` | Loops API key for Cap Software, Inc. |-| `LOOPS_MAILING_LIST_ID` | Product updates and tips list |-| `LOOPS_LICENSE_DATABASE_URL` | Read-only license database connection |-| `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.--Sync fingerprints include the contact's effective signup and teammate-join eligibility, rather than the raw enrollment switch or cutoff date. Enabling enrollment or moving a future cutoff does not invalidate every historical profile. A signup or join crossing the cutoff, or disabling an eligible contact's enrollment, still changes its fingerprint and requires synchronization.--## 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. For draft or paused journeys, it can add mutually exclusive subscription conditions to the first audience guard, with scope set to all following nodes, then read 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.--For a running journey, Loops rejects audience edits with HTTP 400: "This operation is not allowed while the workflow is sending." The checker reports `manual-pause-required`, fails the Action, and explicitly warns that delivery has not stopped. Pause the affected workflows in the Loops UI before applying a hold or changing their guards. This monitor does not automatically stop active delivery. Assign an owner to GitHub Actions failure notifications and verify that notification before activation; do not launch on an assumption of automatic pausing.--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, first pause active workflows in the Loops UI. Then, with the Loops API key in the environment, apply persistent audience holds to the stopped workflows:--```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 even stopped-workflow guard updates. Running workflows keep sending until they are manually paused; a message already being sent may still arrive. Verify the alert and manual-response procedure with an owned-account journey before relying on it. Campaigns require a fresh health check before scheduling and manual cancellation or pause during an outage; the checker only inspects the four registered journeys.--## Before any activation--### Optional sender profile picture--On September 11, 2026, `mail.cap.so` was added in Google Workspace as a **user alias domain for cap.so**. Google verified it automatically without a DNS change or a new paid seat. Richie's existing `[email protected]` photo was already visible to anyone. Gmail was not activated for the alias domain; incoming mail still uses Cloudflare Email Routing, and Loops' SES envelope MX/SPF and the inherited DMARC policy were independently checked unchanged after setup.--The existing photo was visibly confirmed beside `Richie from Cap <[email protected]>` on the received `[PREVIEW] Take another look at Cap` email in Richie's Gmail inbox after setup. No additional email was sent for this check. Avatar display remains client-specific, and other recipients may see a cached picture until their client updates. See [Loops' sending-avatar guide](https://loops.so/docs/deliverability/adding-a-sending-avatar). This setup did not activate any Loops flow or change the production cutover gates below.--### Production cutover--Activation is deliberately outside this migration's approved scope. These gates remain necessary:--1. 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 owned live-customer creation/update tests, including name sync, list assignment, global unsubscribe preservation and a recipient Preference Center mailing-list opt-out surviving a later native update. 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 a future `LOOPS_ENROLLMENT_AFTER` 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. 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 failure detection, manual pause, hold and explicit recovery with an owned-account journey. The September 11 live test confirmed that the API cannot change guards while Sending; automatic stopping remains unresolved. Approve an operational plan with manual pausing, or keep delivery off until a supported automatic control is available. Downstream filters use the last synced fields; `capVerifiedAt` is not a native expiry guarantee. 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, choose a future enrollment boundary with enough setup time. While that boundary is still in the future, enable production sync/enrollment and the independent delivery check, confirm healthy queue results, explicitly remove the delivery holds, and start the reviewed Loops workflows. Complete those steps before the boundary so the first eligible signup is processed by an already-running workflow; if setup overruns, move the boundary forward before allowing enrollment. This release admits new signups after the boundary, not a numerically limited cohort. Monitor deliveries, complaints, opt-outs and duplicate suppression. Do not bulk enroll imported history or replay stage changes emitted while workflows were drafts or held. 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.--## Validation--```sh-bun test scripts/emails scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts scripts/loops/watchdog.test.ts-bun 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.ts-bun run tsc -b packages/database-bun run --cwd apps/web next typegen-bun run tsc -b apps/web-```--Unit tests cover consent conflicts, conservative customer classification, teammate suppression, imported enrollment holds, identity preservation, and stable sync fingerprints. They do not prove production email delivery or a live cutover.--See [QA results and remaining limitations](../../emails/QA.md) for the controlled live Loops tests and the separate production integration gate.+Marketing and lifecycle email content, Loops journeys and campaigns, the email catalogue, the provisioning and verification tooling, and the delivery watchdog live in the private repo [CapSoftware/cap-marketing](https://github.com/CapSoftware/cap-marketing). View and edit them there.diff --git a/scripts/loops/api.ts b/scripts/loops/api.tsdeleted file mode 100644index 240abab9e..000000000--- a/scripts/loops/api.ts+++ /dev/null@@ -1,91 +0,0 @@-export type Json =- | null- | boolean- | number- | string- | Json[]- | { [key: string]: Json };--export class LoopsApiError extends Error {- constructor(- public status: number,- public path: string,- public details: unknown,- ) {- super(`Loops ${status} at ${path}`);- }-}--export class LoopsApi {- private nextRequestAt = 0;-- constructor(- private key: string,- private intervalMs = 750,- ) {- if (!key) throw new Error("LOOPS_API_KEY is required");- if (intervalMs < 125)- throw new Error("Keep requests below the Loops team rate limit");- }-- async request<T>(path: string, method = "GET", body?: unknown): Promise<T> {- for (let attempt = 0; ; attempt++) {- const scheduledAt = Math.max(Date.now(), this.nextRequestAt);- this.nextRequestAt = scheduledAt + this.intervalMs;- await new Promise((resolve) =>- setTimeout(resolve, Math.max(0, scheduledAt - Date.now())),- );- let response: Response;- let result: unknown;- try {- response = await fetch(`https://app.loops.so/api/v1/${path}`, {- method,- headers: {- Authorization: `Bearer ${this.key}`,- "Content-Type": "application/json",- },- body: body === undefined ? undefined : JSON.stringify(body),- signal: AbortSignal.timeout(30_000),- });- result = await response.json();- } catch (error) {- if (attempt >= 4 || (method !== "GET" && method !== "PUT")) throw error;- this.nextRequestAt = Math.max(- this.nextRequestAt,- Date.now() + 1000 * 2 ** attempt,- );- continue;- }- if (response.ok) return result as T;- const retryable =- response.status === 429 ||- (response.status >= 500 && (method === "GET" || method === "PUT"));- if (!retryable || attempt >= 4) {- throw new LoopsApiError(response.status, path, result);- }- const retryAfter = Number(response.headers.get("retry-after"));- this.nextRequestAt = Math.max(- this.nextRequestAt,- Date.now() +- Math.max(- Number.isFinite(retryAfter) ? retryAfter * 1000 : 0,- 1000 * 2 ** attempt,- ),- );- }- }-- async list<T>(path: string): Promise<T[]> {- const rows: T[] = [];- let cursor: string | null = null;- do {- const page: { data: T[]; pagination: { nextCursor: string | null } } =- await this.request(- `${path}?perPage=50${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`,- );- rows.push(...page.data);- cursor = page.pagination.nextCursor;- } while (cursor);- return rows;- }-}diff --git a/scripts/loops/import.ts b/scripts/loops/import.tsdeleted file mode 100644index 1e63cf18b..000000000--- a/scripts/loops/import.ts+++ /dev/null@@ -1,182 +0,0 @@-import { appendFile, chmod, readFile } from "node:fs/promises";-import { parseArgs } from "node:util";-import { LoopsApi, LoopsApiError } from "./api";-import { type ContactProfile, emailHash } from "./profile";-import { importContactUpdate, type RemoteContact } from "./sync-policy";--type Receipt = {- hash: string;- status: "created" | "existing" | "updated" | "invalid";- id?: string;- detail?: unknown;-};-const { values } = parseArgs({- options: {- contacts: { type: "string" },- receipt: { type: "string" },- team: { type: "string" },- apply: { type: "boolean", default: false },- limit: { type: "string" },- "mailing-list": { type: "string" },- "retry-invalid": { type: "boolean", default: false },- },-});-if (!values.contacts || !values.receipt || !values.team)- throw new Error("Pass --contacts, --receipt and --team");-const filename = values.receipt;-const profiles: ContactProfile[] = JSON.parse(- await readFile(values.contacts, "utf8"),-);-const hashes = new Set<string>();-for (const profile of profiles) {- const hash = emailHash(profile.email);- if (- hashes.has(hash) ||- !profile.subscribed ||- profile.capConsent !== "subscribed" ||- profile.capLifecycleEnabled ||- profile.capOnboardingEligible ||- profile.capLifecycleStage !== "idle"- )- throw new Error(- "Import must contain unique, positively subscribed, held contacts",- );- hashes.add(hash);-}-const prior: Receipt[] = [];-try {- for (const line of (await readFile(filename, "utf8"))- .split("\n")- .filter(Boolean))- prior.push(JSON.parse(line));-} catch (error) {- if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))- throw error;-}-const latest = new Map(prior.map((row) => [row.hash, row]));-const done = new Set(- [...latest.values()]- .filter(- (row) =>- row.status !== "existing" &&- !(values["retry-invalid"] && row.status === "invalid"),- )- .map((row) => row.hash),-);-const limit = values.limit ? Number(values.limit) : profiles.length;-if (!Number.isSafeInteger(limit) || limit < 1) throw new Error("Invalid limit");-const pending = profiles- .filter((profile) => !done.has(emailHash(profile.email)))- .slice(0, limit);-const api = new LoopsApi(process.env.LOOPS_API_KEY ?? "", 150);-const identity = await api.request<{ success: boolean; teamName: string }>(- "api-key",-);-if (!identity.success || identity.teamName !== values.team)- throw new Error("Wrong Loops team");-const workflows = await api.list<{ id: string }>("workflows");-for (const row of workflows) {- const workflow = await api.request<{ status: string }>(`workflows/${row.id}`);- if (workflow.status !== "Draft")- throw new Error("Contact import requires all workflows to remain drafts");-}-const lists = await api.request<{ id: string; name: string }[]>("lists");-const listId =- values["mailing-list"] ??- lists.find((list) => list.name === "Product updates and tips")?.id;-if (listId && !lists.some((list) => list.id === listId))- throw new Error("Unknown mailing list");-console.log(- JSON.stringify({- team: identity.teamName,- mode: values.apply ? "create missing contacts" : "dry run",- total: profiles.length,- alreadyProcessed: done.size,- pending: pending.length,- mailingListId: listId ?? null,- }),-);-if (!values.apply) process.exit(0);-await appendFile(filename, "", { mode: 0o600 });-await chmod(filename, 0o600);-let next = 0;-let stopped = false;-let completed = 0;-const counts = { created: 0, existing: 0, updated: 0, invalid: 0 };-const worker = async () => {- while (!stopped && next < pending.length) {- const profile = pending[next++];- if (!profile) return;- const hash = emailHash(profile.email);- let receipt: Receipt;- try {- const result = await api.request<{ success: boolean; id: string }>(- "contacts/create",- "POST",- { ...profile, ...(listId ? { mailingLists: { [listId]: true } } : {}) },- );- if (!result.success || !result.id)- throw new Error(- "Unexpected create response; reconcile before retrying",- );- receipt = { hash, status: "created", id: result.id };- } catch (error) {- if (error instanceof LoopsApiError && error.status === 409) {- const contacts = await api.request<RemoteContact[]>(- `contacts/find?email=${encodeURIComponent(profile.email)}`,- );- const contact = contacts[0];- if (contacts.length !== 1 || !contact) {- stopped = true;- throw new Error(- "Resolve the existing contact identity before resuming",- );- }- await api.request(- "contacts/update",- "PUT",- importContactUpdate(profile, contact, listId),- );- receipt = { hash, status: "updated", id: contact.id };- } else if (error instanceof LoopsApiError && error.status === 400)- receipt = { hash, status: "invalid", detail: error.details };- else {- stopped = true;- throw error;- }- }- await appendFile(filename, `${JSON.stringify(receipt)}\n`);- counts[receipt.status]++;- completed++;- if (completed % 250 === 0)- console.log(- JSON.stringify({ processed: done.size + completed, ...counts }),- );- }-};-const results = await Promise.allSettled(- Array.from({ length: 8 }, async () => {- try {- await worker();- } catch (error) {- stopped = true;- throw error;- }- }),-);-console.log(- JSON.stringify({- processed: done.size + completed,- ...counts,- remaining: profiles.length - done.size - completed,- }),-);-for (const result of results)- if (result.status === "rejected") {- console.error(- result.reason instanceof LoopsApiError- ? `Import stopped with HTTP ${result.reason.status}; resume with the same receipt`- : "Import stopped; reconcile the receipt before resuming",- );- process.exitCode = 1;- }diff --git a/scripts/loops/prepare.ts b/scripts/loops/prepare.tsdeleted file mode 100644index e86952156..000000000--- a/scripts/loops/prepare.ts+++ /dev/null@@ -1,141 +0,0 @@-import { chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises";-import path from "node:path";-import { parseArgs } from "node:util";-import {- type CapUser,- classifyProfile,- emailHash,- type License,- type Membership,- normalizeEmail,- type SourceContact,-} from "./profile";--const { values } = parseArgs({- options: { sources: { type: "string" }, output: { type: "string" } },-});-if (!values.sources || !values.output)- throw new Error("Pass private --sources and --output directories");-const sourceDirectory = values.sources;-const read = async <T>(name: string): Promise<T[]> => {- const filename = path.join(sourceDirectory, `${name}.json`);- if (Date.now() - (await stat(filename)).mtimeMs > 24 * 60 * 60_000)- throw new Error(`Refresh stale source ${name}`);- return JSON.parse(await readFile(filename, "utf8"));-};-const [source, users, members, licenses, invites, sso, videos] =- await Promise.all([- read<SourceContact>("bento-contacts"),- read<CapUser>("cap-users"),- read<Membership>("cap-memberships"),- read<License>("license-licenses"),- read<{ invitedEmail: string; status: string; expiresAt: string }>(- "cap-invites",- ),- read<{ userId: string }>("cap-sso"),- read<{ ownerId: string; total: number; hasPublicVideo: number }>(- "cap-videos",- ),- ]);-const group = <T>(rows: T[], key: (row: T) => string) => {- const result = new Map<string, T[]>();- for (const row of rows) {- const id = key(row);- result.set(id, [...(result.get(id) ?? []), row]);- }- return result;-};-const byEmail = group(users, (user) => normalizeEmail(user.email));-const memberMap = group(members, (member) => member.userId);-const licenseMap = group(licenses, (license) => normalizeEmail(license.email));-const invited = new Set(- invites.map((invite) => normalizeEmail(invite.invitedEmail)),-);-const ssoUsers = new Set(sso.map((account) => account.userId));-const videoMap = new Map(videos.map((video) => [video.ownerId, video]));-const seen = new Set<string>();-const now = new Date();-const profiles = source.map((contact) => {- if (- !["unsubscribed_at", "unsubscribed_reason", "flag"].every(- (key) => typeof contact[key] === "string",- )- )- throw new Error("Source is missing Bento subscription/suppression columns");- const email = normalizeEmail(contact.email);- if (!email || seen.has(email))- throw new Error("Source contains an empty or duplicate normalized email");- seen.add(email);- const matchingUsers = byEmail.get(email) ?? [];- if (matchingUsers.length > 1)- throw new Error(- "Multiple Cap identities match an email; resolve before importing",- );- const user = matchingUsers[0];- const video = user ? videoMap.get(user.id) : undefined;- return classifyProfile({- source: contact,- user,- memberships: user ? (memberMap.get(user.id) ?? []) : [],- licenses: licenseMap.get(email) ?? [],- invited: invited.has(email),- sso: user ? ssoUsers.has(user.id) : false,- hasVideo: Boolean(video?.total),- hasSharedVideo: Boolean(video?.hasPublicVideo),- now,- });-});-const positive = profiles.filter((profile) => profile.subscribed);-const registry = profiles.map((profile) => ({- emailHash: emailHash(profile.email),- consent: profile.capConsent,- teammate: profile.capTeammate,- userId: profile.userId.startsWith("bento:") ? null : profile.userId,- source: "bento-migration",- imported: true,-}));-await mkdir(values.output, { recursive: true, mode: 0o700 });-await chmod(values.output, 0o700);-const write = async (name: string, content: string) => {- const filename = path.join(values.output ?? "", name);- await writeFile(filename, content, { mode: 0o600 });- await chmod(filename, 0o600);-};-await write("contacts.json", JSON.stringify(positive));-await write("consent-registry.json", JSON.stringify(registry));-const keys = Object.keys(- positive[0] ?? {},-) as (keyof (typeof positive)[number])[];-const csvCell = (value: unknown) =>- `"${String(value ?? "").replaceAll('"', '""')}"`;-await write(- "contacts.csv",- [- keys.map(csvCell).join(","),- ...positive.map((profile) =>- keys.map((key) => csvCell(profile[key])).join(","),- ),- ].join("\r\n"),-);-const counts = (key: "capAudience" | "capConsent") =>- profiles.reduce<Record<string, number>>((result, row) => {- result[row[key]] = (result[row[key]] ?? 0) + 1;- return result;- }, {});-const summary = {- preparedAt: now.toISOString(),- source: profiles.length,- import: positive.length,- excluded: profiles.length - positive.length,- consent: counts("capConsent"),- audiences: counts("capAudience"),- importAudiences: positive.reduce<Record<string, number>>((result, row) => {- result[row.capAudience] = (result[row.capAudience] ?? 0) + 1;- return result;- }, {}),- allImportsHeld: positive.every(- (row) => !row.capLifecycleEnabled && row.capLifecycleStage === "idle",- ),-};-await write("summary.json", JSON.stringify(summary, null, 2));-console.log(JSON.stringify(summary, null, 2));diff --git a/scripts/loops/profile.test.ts b/scripts/loops/profile.test.tsindex b77a89b9a..b4e9eccab 100644--- a/scripts/loops/profile.test.ts+++ b/scripts/loops/profile.test.ts@@ -8,7 +8,6 @@ import {type ProfileInput,sourceConsent,} from "./profile";-import { audienceFilter, journeys } from "./program";import {contactUpdate,importContactUpdate,@@ -363,32 +362,3 @@ test("verification timestamps do not churn the sync fingerprint", () => {profileFingerprint({ ...profile, capTeammate: true }),);});--test("every journey requires subscription consent and promotional journeys exclude teammates", () => {- assert.equal(- journeys.reduce((count, journey) => count + journey.messages.length, 0),- 16,- );- for (const journey of journeys) {- const filter = audienceFilter(journey.audience, journey.promotional);- assert.ok(- filter.conditions.some(- (condition) =>- condition.key === "subscribed" && condition.operator === "isTrue",- ),- );- assert.ok(- filter.conditions.some(- (condition) =>- condition.key === "capConsent" && condition.value === "subscribed",- ),- );- if (journey.promotional)- assert.ok(- filter.conditions.some(- (condition) =>- condition.key === "capTeammate" && condition.operator === "isFalse",- ),- );- }-});diff --git a/scripts/loops/program.ts b/scripts/loops/program.tsdeleted file mode 100644index 014fee51c..000000000--- a/scripts/loops/program.ts+++ /dev/null@@ -1,10 +0,0 @@-export {- audienceFilter,- campaignTemplates,- components,- condition,- contactProperties,- journeys,- programVersion,- theme,-} from "../../emails";diff --git a/scripts/loops/provision.ts b/scripts/loops/provision.tsdeleted file mode 100644index 0a9339a93..000000000--- a/scripts/loops/provision.ts+++ /dev/null@@ -1,533 +0,0 @@-import assert from "node:assert/strict";-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 {- audienceFilter,- campaignTemplates,- components,- condition,- contactProperties,- journeys,- programVersion,- theme,-} from "./program";--type Named = { id: string; name: string };-type Node = {- id: string;- typeName: string;- nextNodeIds: string[];- emailMessageId?: string;-};-type Workflow = Named & {- status: string;- description: string;- mailingListId: string | null;- workflowRevisionId: string | null;- rootNodeId: string;- nodes: Record<string, Node>;-};-type Email = {- contentRevisionId: string | null;- subject: string;- lmx: string;- contactPropertiesFallbacks?: Record<string, string>;-};-type Receipt = {- teamName: string;- version: string;- resources: Record<string, string>;- operations: Record<string, string>;- definitions: Record<string, string>;- guardian: Record<string, { errors: unknown[]; warnings: unknown[] }>;-};--const { values } = parseArgs({- options: {- apply: { type: "boolean", default: false },- "dry-run": { type: "boolean", default: false },- state: { type: "string" },- team: { type: "string" },- "mailing-list": { type: "string" },- "new-journey": { type: "string" },- },-});--if (values.apply && values["dry-run"])- throw new Error("Choose --apply or --dry-run");-if (!values.team)- throw new Error("Pass --team with the expected Loops team name");-if (values.apply && !values.state)- throw new Error("--apply requires a private --state file");-const selectedJourneys = values["new-journey"]- ? journeys.filter((journey) => journey.key === values["new-journey"])- : journeys;-if (!selectedJourneys.length) throw new Error("Unknown journey");-const selectedCampaigns = values["new-journey"] ? [] : campaignTemplates;-if (values.apply && deliveryFormat === "mjml" && !values["new-journey"])- throw new Error(- "Managed emails use custom MJML. Run emails:export and upload reviewed archives in the Loops editor; the API cannot edit this format.",- );--const api = new LoopsApi(process.env.LOOPS_API_KEY ?? "");-const identity = await api.request<{ success: boolean; teamName: string }>(- "api-key",-);-if (!identity.success || identity.teamName !== values.team)- throw new Error("Wrong Loops team");--let receipt: Receipt = {- teamName: identity.teamName,- version: programVersion,- resources: {},- operations: {},- definitions: {},- guardian: {},-};-if (values.state) {- try {- receipt = {- ...receipt,- ...JSON.parse(await readFile(values.state, "utf8")),- };- } catch (error) {- if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))- throw error;- }-}-if (- receipt.teamName !== identity.teamName ||- receipt.version !== programVersion-) {- throw new Error("State file belongs to a different team or program");-}--const save = async () => {- if (values.apply && values.state) {- await writeFile(values.state, `${JSON.stringify(receipt, null, 2)}\n`, {- mode: 0o600,- });- }-};-const hash = (value: unknown) =>- createHash("sha256").update(JSON.stringify(value)).digest("hex");-const named = (rows: Named[], name: string) => {- const matches = rows.filter((row) => row.name === name);- if (matches.length > 1) throw new Error(`Duplicate managed name: ${name}`);- return matches[0];-};--try {- const existingProperties = await api.request<{ key: string; type: string }[]>(- "contacts/properties",- );- const lists = await api.request<Named[]>("lists");- const workflows = await api.list<Workflow>("workflows");- if (values["new-journey"]) {- const match = named(workflows, selectedJourneys[0].name);- const existing = match- ? await api.request<Workflow>(`workflows/${match.id}`)- : undefined;- if (- existing &&- (receipt.resources[values["new-journey"]] !== existing.id ||- !existing.description.includes("created-for-mjml-upload"))- )- throw new Error(- "New-journey mode cannot edit an existing managed workflow",- );- }- const themes = await api.list<Named>("themes");- const sharedComponents = await api.list<Named>("components");- const segments = await api.list<Named>("audience-segments");- const campaigns = await api.list<- Named & { status: string; emailMessageId: string }- >("campaigns");- const listId =- values["mailing-list"] ?? named(lists, "Product updates and tips")?.id;- if (listId && !lists.some((list) => list.id === listId))- throw new Error("Unknown mailing list");- console.log(- JSON.stringify({- team: identity.teamName,- mode: values.apply ? "apply drafts" : "dry run",- workflows: selectedJourneys.length,- emails: selectedJourneys.reduce(- (count, journey) => count + journey.messages.length,- 0,- ),- campaignTemplates: selectedCampaigns.length,- mailingListId:- listId ?? "Create Product updates and tips in the Loops dashboard",- }),- );- if (!values.apply) process.exit(0);- if (!listId)- console.log(- "Mailing list is pending dashboard setup; resources remain drafts.",- );- if (listId) receipt.resources.mailingList = listId;- await save();-- for (const [name, type] of Object.entries(contactProperties)) {- const existing = existingProperties.find(- (property) => property.key === name,- );- if (existing && existing.type !== type)- throw new Error(`Wrong property type: ${name}`);- if (!existing)- await api.request("contacts/properties", "POST", { name, type });- }-- const ensure = async (- path: string,- rows: Named[],- definition: { name: string },- key: string,- ) => {- const existing = named(rows, definition.name);- if (existing && path === "themes") {- const current = await api.request<{ styles: Record<string, unknown> }>(- `${path}/${existing.id}`,- );- for (const [style, value] of Object.entries(theme.styles))- assert.deepEqual(- current.styles[style],- value,- "Shared theme changed; create a new branding version before updating drafts",- );- }- if (existing && path === "components") {- const current = await api.request<{ lmx: string }>(- `${path}/${existing.id}`,- );- const expected = components.find(- (component) => component.name === definition.name,- );- assert(expected);- assert.equal(- normalizeLmx(current.lmx),- normalizeLmx(expected.lmx),- "Shared component changed; create a new branding version before updating drafts",- );- }- const resource =- existing ?? (await api.request<Named>(path, "POST", definition));- receipt.resources[key] = resource.id;- await save();- return resource.id;- };- const themeId = values["new-journey"]- ? receipt.resources.theme- : await ensure("themes", themes, theme, "theme");- assert(themeId, "New MJML drafts require the existing brand registry");- const componentIds: string[] = [];- for (const component of components) {- componentIds.push(- values["new-journey"]- ? receipt.resources[component.name]- : await ensure(- "components",- sharedComponents,- component,- component.name,- ),- );- }- const editEmail = async (- id: string,- message: { subject: string; previewText: string; body: string },- ) => {- const definition = emailContent(message, {- theme: themeId,- header: componentIds[0],- signature: componentIds[1],- });- const current = await api.request<Email>(`email-messages/${id}`);- if (- receipt.definitions[id] !== hash(definition) ||- current.subject !== definition.subject- ) {- const result = await api.request<{ warnings?: unknown[] }>(- `email-messages/${id}`,- "POST",- {- expectedRevisionId: current.contentRevisionId,- ...definition,- contactPropertiesFallbacks: {- ...Object.fromEntries(- Object.keys(current.contactPropertiesFallbacks ?? {})- .filter(- (key) =>- !Object.hasOwn(definition.contactPropertiesFallbacks, key),- )- .map((key) => [key, null]),- ),- ...definition.contactPropertiesFallbacks,- },- },- );- if (result.warnings?.length)- console.log(- JSON.stringify({ email: id, compileWarnings: result.warnings }),- );- receipt.definitions[id] = hash(definition);- await save();- }- const guardian = await api.request<{- errors: unknown[];- warnings: unknown[];- }>(`email-messages/${id}/guardian`);- receipt.guardian[id] = guardian;- await save();- if (guardian.errors.length)- throw new Error(- `Guardian errors for ${id}: ${JSON.stringify(guardian.errors)}`,- );- };-- for (const journey of selectedJourneys) {- const existing = named(workflows, journey.name);- let workflow = existing- ? await api.request<Workflow>(`workflows/${existing.id}`)- : await api.request<Workflow>("workflows", "POST", {- name: journey.name,- description: `${programVersion}; ${values["new-journey"] ? "created-for-mjml-upload; " : ""}managed by scripts/loops/provision.ts. ${journey.messages.map((m) => m.delayDays).join(", ")} day relative delays. Imports never enroll.`,- mailingListId: listId,- });- if (workflow.status !== "Draft")- throw new Error(`Refusing to edit non-draft workflow ${journey.name}`);- if (!workflow.description.includes(programVersion))- throw new Error("Existing workflow is not owned by this program");- if (listId && workflow.mailingListId !== listId) {- const changed = await api.request<{- status: string;- workflow?: Workflow;- }>(`workflows/${workflow.id}/mailing-list`, "POST", {- expectedRevisionId: workflow.workflowRevisionId,- mailingListId: listId,- });- if (!changed.workflow)- throw new Error(- "Mailing-list assignment needs review; no queued contacts were discarded",- );- workflow = changed.workflow;- }- receipt.resources[journey.key] = workflow.id;- await save();- const exitIds = Object.entries(workflow.nodes)- .filter(([, n]) => n.typeName === "ExitAction")- .map(([id]) => id);- if (exitIds.length !== 1)- throw new Error(`Expected one shared exit in ${journey.name}`);- const exitId = exitIds[0];- const update = async (id: string, payload: unknown, operation: string) => {- const digest = hash(payload);- if (receipt.definitions[operation] === digest) return;- const result = await api.request<{ workflow: Workflow }>(- `workflows/${workflow.id}/nodes/${id}`,- "POST",- {- expectedRevisionId: workflow.workflowRevisionId,- payload,- },- );- workflow = result.workflow;- receipt.definitions[operation] = digest;- await save();- };- const insert = async (- type: string,- operation: string,- fromNodeId?: string,- ) => {- const recordedId = receipt.operations[operation];- if (recordedId) {- const node = workflow.nodes[recordedId];- if (!node || node.typeName !== type)- throw new Error(`Managed node changed: ${operation}`);- return { ...node, id: recordedId };- }- const result = await api.request<{ node: Node; workflow: Workflow }>(- `workflows/${workflow.id}/nodes`,- "POST",- {- expectedRevisionId: workflow.workflowRevisionId,- nodeTypeName: type,- ...(fromNodeId- ? { insertMode: "between", fromNodeId, toNodeId: exitId }- : { insertMode: "before", beforeNodeId: exitId }),- },- );- workflow = result.workflow;- receipt.operations[operation] = result.node.id;- await save();- return result.node;- };- await update(- workflow.rootNodeId,- {- typeName: "ContactPropertyTrigger",- contactPropertyQuery: {- key: "capLifecycleStage",- is: { operator: "equal", value: journey.key },- was: { operator: "not_equal", value: journey.key },- },- reEligible: false,- },- `${journey.key}:trigger`,- );- const guard = await insert("AudienceFilter", `${journey.key}:guard`);- const filter = workflowAudience(journey);- await update(- guard.id,- { audienceFilter: filter, appliesDownstream: true },- `${journey.key}:guard-config`,- );- for (const message of journey.messages) {- const operation = `${journey.key}:${message.key}`;- if (message.delayDays) {- const timer = await insert("TimerAction", `${operation}:timer`);- await update(- timer.id,- { amount: message.delayDays, unit: "d" },- `${operation}:timer-config`,- );- }- let fromNodeId: string | undefined;- if (message.onlyIf && message === journey.messages.at(-1)) {- const filter = await insert("AudienceFilter", `${operation}:filter`);- await update(- filter.id,- {- audienceFilter: {- match: "all",- conditions: [- condition(message.onlyIf.property, message.onlyIf.value),- ],- },- appliesDownstream: false,- },- `${operation}:filter-config`,- );- fromNodeId = filter.id;- } else if (message.onlyIf) {- const branch = await insert("BranchNode", `${operation}:branch`);- const children = workflow.nodes[branch.id].nextNodeIds;- if (children.length !== 2)- throw new Error("Expected two milestone branches");- for (let index = 0; index < 2; index++) {- await update(- children[index],- {- audienceFilter: {- match: "all",- conditions: [- condition(- message.onlyIf.property,- index === 0 ? message.onlyIf.value : !message.onlyIf.value,- ),- ],- },- appliesDownstream: false,- },- `${operation}:branch-${index}`,- );- }- fromNodeId = children[0];- }- const email = await insert(- "SendEmailAction",- `${operation}:email`,- fromNodeId,- );- if (!email.emailMessageId) throw new Error("Missing email message ID");- await editEmail(email.emailMessageId, message);- }- const verified = await api.request<Workflow>(`workflows/${workflow.id}`);- if (verified.status !== "Draft")- throw new Error("Workflow status changed unexpectedly");- console.log(- JSON.stringify({- name: journey.name,- id: verified.id,- status: verified.status,- nodes: Object.keys(verified.nodes).length,- }),- );- }-- for (const template of selectedCampaigns) {- const segmentName = `${template.name} audience`;- const segmentId = await ensure(- "audience-segments",- segments,- {- name: segmentName,- description:- "Managed by Cap lifecycle v1. Verify current consent and entitlements before scheduling.",- filter: audienceFilter(- template.audience,- template.promotional,- template.audienceConditions,- ),- } as { name: string },- `segment:${template.key}`,- );- const existing = named(campaigns, template.name);- const campaign = existing- ? await api.request<{- id: string;- status: string;- emailMessageId: string;- }>(`campaigns/${existing.id}`)- : await api.request<{- id: string;- status: string;- emailMessageId: string;- }>("campaigns", "POST", {- name: template.name,- mailingListId: listId,- audienceSegmentId: segmentId,- });- const current = await api.request<{ status: string }>(- `campaigns/${campaign.id}`,- );- if (current.status !== "Draft")- throw new Error("Refusing to edit a non-draft campaign");- if (listId)- await api.request(`campaigns/${campaign.id}`, "POST", {- mailingListId: listId,- audienceSegmentId: segmentId,- });- receipt.resources[template.key] = campaign.id;- await save();- await editEmail(campaign.emailMessageId, template);- console.log(- JSON.stringify({ name: template.name, id: campaign.id, status: "Draft" }),- );- }- await save();- console.log(- "Verified draft resources. No publish, activation, event, or send request was made.",- );-} catch (error) {- if (error instanceof LoopsApiError)- console.error(- JSON.stringify({- status: error.status,- path: error.path,- details: error.details,- }),- );- else- console.error(- error instanceof Error ? error.message : "Provisioning failed",- );- process.exitCode = 1;-}diff --git a/scripts/loops/sources.ts b/scripts/loops/sources.tsdeleted file mode 100644index 6acdafca0..000000000--- a/scripts/loops/sources.ts+++ /dev/null@@ -1,60 +0,0 @@-import mysql, { type Connection, type RowDataPacket } from "mysql2/promise";-import type { CapUser, License, Membership } from "./profile";--const rows = async <T>(db: Connection, sql: string): Promise<T[]> => {- const [result] = await db.query<(RowDataPacket & T)[]>(sql);- return result;-};--export async function readSources(capUrl: string, licenseUrl: string) {- const cap = await mysql.createConnection({ uri: capUrl, dateStrings: true });- try {- const license = await mysql.createConnection({- uri: licenseUrl,- dateStrings: true,- });- try {- const users = await rows<CapUser>(- cap,- "SELECT id,email,name,lastName,stripeSubscriptionStatus,thirdPartyStripeSubscriptionId,inviteQuota,created_at,defaultOrgId,marketingOrigin FROM users",- );- const memberships = await rows<Membership>(- cap,- "SELECT m.userId,m.organizationId,m.hasProSeat,o.ownerId,o.tombstoneAt,o.workosConnectionId,o.createdAt FROM organization_members m JOIN organizations o ON o.id=m.organizationId",- );- const invites = await rows<{ invitedEmail: string }>(- cap,- "SELECT invitedEmail FROM organization_invites WHERE status IN ('pending','accepted')",- );- const sso = await rows<{ userId: string }>(- cap,- "SELECT DISTINCT userId FROM accounts WHERE provider='workos'",- );- const videos = await rows<{- ownerId: string;- total: number;- hasPublicVideo: number;- }>(- cap,- "SELECT ownerId,COUNT(*) AS total,MAX(CASE WHEN public=1 THEN 1 ELSE 0 END) AS hasPublicVideo FROM videos GROUP BY ownerId",- );- const licenses = await rows<License>(- license,- "SELECT u.email,l.subscriptionActive,l.nextRenewalDate,'desktop' AS kind FROM commercialLicenses l JOIN user u ON u.id=l.userId UNION ALL SELECT u.email,l.subscriptionActive,l.nextRenewalDate,'selfhosted' AS kind FROM selfHostedLicenses l JOIN user u ON u.id=l.userId",- );- return {- users,- memberships,- invites,- sso,- videos,- licenses,- verifiedAt: new Date(),- };- } finally {- await license.end();- }- } finally {- await cap.end();- }-}diff --git a/scripts/loops/verify.ts b/scripts/loops/verify.tsdeleted file mode 100644index e06593737..000000000--- a/scripts/loops/verify.ts+++ /dev/null@@ -1,311 +0,0 @@-import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";-import { fileURLToPath } from "node:url";-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";-import {- audienceFilter,- campaignTemplates,- condition,- journeys,- programVersion,-} from "./program";--type Node = {- typeName: string;- nextNodeIds: string[];- emailMessageId?: string;- amount?: number;- unit?: string;- contactPropertyQuery?: unknown;- reEligible?: boolean;- audienceFilter?: unknown;- appliesDownstream?: boolean;-};-type Workflow = {- status: string;- name: string;- mailingListId: string;- rootNodeId: string;- nodes: Record<string, Node>;-};-type Email = Record<string, unknown> & {- subject: string;- previewText: string;- fromEmail: string;- replyToEmail: string;- lmx: string;- contactPropertiesFallbacks: Record<string, string>;-};--const { values } = parseArgs({- options: {- state: {- type: "string",- default: fileURLToPath(- new URL("../../emails/resources.json", import.meta.url),- ),- },- 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 },- "allow-live": { type: "boolean", default: false },- journey: { type: "string" },- },-});-assert(values.state && values.team && values["mailing-list"]);-const receipt: {- version: string;- teamName: string;- resources: Record<string, string>;- operations: Record<string, string>;-} = JSON.parse(await readFile(values.state, "utf8"));-assert.equal(receipt.version, programVersion);-assert.equal(receipt.teamName, values.team);-const api = new LoopsApi(process.env.LOOPS_API_KEY ?? "");-const identity = await api.request<{ teamName: string }>("api-key");-assert.equal(identity.teamName, values.team);-const brandIds = {- theme: receipt.resources.theme,- header: receipt.resources[components[0].name],- signature: receipt.resources[components[1].name],-};-assert(- brandIds.theme && brandIds.header && brandIds.signature,- "Brand IDs missing from resources.json",-);-if (deliveryFormat === "lmx") {- const remoteTheme = await api.request<{- name: string;- styles: Record<string, unknown>;- }>(`themes/${brandIds.theme}`);- assert.equal(remoteTheme.name, theme.name);- for (const [key, value] of Object.entries(theme.styles))- assert.deepEqual(- remoteTheme.styles[key],- value,- `Shared theme differs: ${key}`,- );- for (const component of components) {- const remote = await api.request<{ name: string; lmx: string }>(- `components/${receipt.resources[component.name]}`,- );- assert.equal(remote.name, component.name);- assert.equal(- normalizeLmx(remote.lmx),- normalizeLmx(component.lmx),- `Shared component differs: ${component.name}`,- );- }-}-let emails = 0;-let customEmails = 0;-let heldWorkflows = 0;-const verifyEmail = async (- id: string | undefined,- expected: { subject: string; previewText: string; body: string },-) => {- assert(id);- let email: Email;- try {- email = await api.request<Email>(`email-messages/${id}`);- } catch (error) {- if (- error instanceof LoopsApiError &&- error.status === 409 &&- typeof error.details === "object" &&- error.details !== null &&- "message" in error.details &&- error.details.message === "MJML format is not supported via API."- ) {- assert.equal(deliveryFormat, "mjml");- customEmails++;- return;- }- throw error;- }- assert.notEqual(- deliveryFormat,- "mjml",- "Managed email is still in native format",- );- assertEmailContent(email, expected, brandIds);- const guardian = await api.request<{- errors: unknown[];- warnings: unknown[];- }>(`email-messages/${id}/guardian`);- assert.deepEqual(guardian.errors, []);- assert.deepEqual(guardian.warnings, []);- emails++;-};--const selectedJourneys = values.journey- ? journeys.filter((journey) => journey.key === values.journey)- : journeys;-assert(selectedJourneys.length, "Unknown journey");-const selectedCampaigns = values.journey ? [] : campaignTemplates;-for (const journey of selectedJourneys) {- const id = receipt.resources[journey.key];- const workflow = await api.request<Workflow>(`workflows/${id}`);- assert(- (values["allow-live"]- ? ["Draft", "Sending", "Paused", "PausedAndQueueing"]- : ["Draft"]- ).includes(workflow.status),- `Unexpected workflow status: ${workflow.status}`,- );- assert.equal(workflow.name, journey.name);- assert.equal(workflow.mailingListId, values["mailing-list"]);- const visited = new Set<string>();- const node = (nodeId: string, type: string) => {- assert(!visited.has(nodeId), `Duplicate managed node: ${nodeId}`);- visited.add(nodeId);- const result = workflow.nodes[nodeId];- assert.equal(result?.typeName, type);- return result;- };- const trigger = node(workflow.rootNodeId, "ContactPropertyTrigger");- assert.equal(trigger.reEligible, false);- assert.deepEqual(trigger.contactPropertyQuery, {- key: "capLifecycleStage",- is: { value: journey.key, operator: "equal" },- was: { value: journey.key, operator: "not_equal" },- });- let previous = [workflow.rootNodeId];- const connect = (next: string) => {- for (const prior of previous)- assert.deepEqual(workflow.nodes[prior].nextNodeIds, [next]);- previous = [next];- };- const guardId = receipt.operations[`${journey.key}:guard`];- connect(guardId);- node(guardId, "AudienceFilter");- const guard = await api.request<Node>(`workflows/${id}/nodes/${guardId}`);- const held = isDeepStrictEqual(- guard.audienceFilter,- heldWorkflowAudience(journey),- );- 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}`;- if (message.delayDays) {- const timerId = receipt.operations[`${operation}:timer`];- connect(timerId);- const timer = node(timerId, "TimerAction");- assert.equal(timer.amount, message.delayDays);- assert.equal(timer.unit, "d");- }- let skipped: string | undefined;- if (message.onlyIf && message === journey.messages.at(-1)) {- const filterId = receipt.operations[`${operation}:filter`];- connect(filterId);- node(filterId, "AudienceFilter");- const filter = await api.request<Node>(- `workflows/${id}/nodes/${filterId}`,- );- assert.deepEqual(filter.audienceFilter, {- match: "all",- conditions: [condition(message.onlyIf.property, message.onlyIf.value)],- });- assert.equal(filter.appliesDownstream, false);- } else if (message.onlyIf) {- const branchId = receipt.operations[`${operation}:branch`];- connect(branchId);- const branch = node(branchId, "BranchNode");- assert.equal(branch.nextNodeIds.length, 2);- for (let index = 0; index < 2; index++) {- const childId = branch.nextNodeIds[index];- node(childId, "AudienceFilter");- const child = await api.request<Node>(- `workflows/${id}/nodes/${childId}`,- );- assert.deepEqual(child.audienceFilter, {- match: "all",- conditions: [- condition(- message.onlyIf.property,- index === 0 ? message.onlyIf.value : !message.onlyIf.value,- ),- ],- });- assert.equal(child.appliesDownstream, false);- }- previous = [branch.nextNodeIds[0]];- skipped = branch.nextNodeIds[1];- }- const emailId = receipt.operations[`${operation}:email`];- connect(emailId);- const email = node(emailId, "SendEmailAction");- await verifyEmail(email.emailMessageId, message);- if (skipped) previous.push(skipped);- }- const exits = Object.entries(workflow.nodes).filter(- ([, value]) => value.typeName === "ExitAction",- );- assert.equal(exits.length, 1);- connect(exits[0][0]);- assert.deepEqual(node(exits[0][0], "ExitAction").nextNodeIds, []);- assert.equal(visited.size, Object.keys(workflow.nodes).length);- console.log(- JSON.stringify({- workflow: journey.name,- status: workflow.status,- graphVerified: true,- deliveryHeld: held,- }),- );-}--for (const template of selectedCampaigns) {- const campaign = await api.request<{- status: string;- mailingListId: string;- audienceSegmentId: string;- emailMessageId: string;- }>(`campaigns/${receipt.resources[template.key]}`);- assert.equal(campaign.status, "Draft");- assert.equal(campaign.mailingListId, values["mailing-list"]);- assert.equal(- campaign.audienceSegmentId,- receipt.resources[`segment:${template.key}`],- );- const segment = await api.request<{ filter: unknown }>(- `audience-segments/${campaign.audienceSegmentId}`,- );- assert.deepEqual(- segment.filter,- audienceFilter(- template.audience,- template.promotional,- template.audienceConditions,- ),- );- await verifyEmail(campaign.emailMessageId, template);-}-console.log(- JSON.stringify({- workflows: selectedJourneys.length,- campaigns: selectedCampaigns.length,- apiEmailContentVerified: emails,- customEmailContentRequiresBrowserReview: customEmails,- guardianVerifiedEmails: emails,- deliveryHeldWorkflows: heldWorkflows,- liveStatesAllowed: values["allow-live"],- }),-);-if (customEmails && !values["structure-only"])- throw new Error(- "Workflow structure and draft states passed. Custom MJML content is unavailable through the API; verify its rendered body, metadata, logo, footer and fallbacks in the browser. Use --structure-only to request only the API checks.",- );diff --git a/scripts/loops/watchdog.test.ts b/scripts/loops/watchdog.test.tsdeleted file mode 100644index ca34b8b54..000000000--- a/scripts/loops/watchdog.test.ts+++ /dev/null@@ -1,372 +0,0 @@-import { describe, expect, test } from "bun:test";-import {- heldWorkflowAudience,- workflowAudience,-} from "../../emails/delivery-safety";-import { type LoopsApi, LoopsApiError } from "./api";-import {- checkSyncHealth,- enforceDeliverySafety,- filterIsHeld,- healthyReport,- safetyTargets,-} from "./watchdog";--function fakeProvider(status = "Draft") {- const guards = new Map(- safetyTargets.map((target) => [- target.workflowId,- {- typeName: "AudienceFilter",- workflowRevisionId: "revision-1",- audienceFilter: workflowAudience(target.journey),- appliesDownstream: true,- },- ]),- );- const writes: string[] = [];- const attemptedWrites: string[] = [];- let brokenWorkflow: string | undefined;- let startedWorkflow: string | undefined;- let startedOnWrite = false;- let startError: Error | 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") {- attemptedWrites.push(target.workflowId);- if (target.workflowId === startedWorkflow) {- startedOnWrite = true;- if (startError) throw startError;- }- if (status === "Sending" || target.workflowId === startedWorkflow)- throw new LoopsApiError(400, path, {- message:- "This operation is not allowed while the workflow is sending.",- });- 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,- status:- target.workflowId === startedWorkflow && startedOnWrite- ? "Sending"- : status,- mailingListId: target.mailingListId,- rootNodeId: "trigger",- nodes: { trigger: { nextNodeIds: [target.guardId] } },- } as T;- },- };- return {- api,- guards,- writes,- attemptedWrites,- startDuringWrite: (id: string, error?: Error) => {- startedWorkflow = id;- startError = error;- },- 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("concurrent activation is detected even when the provider error format changes", async () => {- for (const error of [- new LoopsApiError(400, "nodes/guard", { error: "Workflow is active" }),- new SyntaxError("Unexpected response encoding"),- ]) {- const provider = fakeProvider();- provider.startDuringWrite(safetyTargets[0].workflowId, error);- const result = await enforceDeliverySafety(provider.api, {- healthy: false,- apply: true,- });- expect(result[0].action).toBe("manual-pause-required");- expect(provider.attemptedWrites).toHaveLength(safetyTargets.length);- }- });-- 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 holds stopped journeys and recovery never resumes them 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(safetyTargets.length);- });-- test("an unhealthy running journey requires manual pause without attempting forbidden edits", async () => {- const provider = fakeProvider("Sending");- const result = await enforceDeliverySafety(provider.api, {- healthy: false,- apply: true,- });- expect(- result.every((item) => item.action === "manual-pause-required"),- ).toBe(true);- expect(provider.attemptedWrites).toHaveLength(0);- for (const guard of provider.guards.values())- expect(filterIsHeld(guard.audienceFilter)).toBe(false);- });-- test("explicit holds on running journeys require manual pause even during a dry run", async () => {- for (const apply of [true, false]) {- const provider = fakeProvider("Sending");- const result = await enforceDeliverySafety(provider.api, {- healthy: true,- hold: true,- apply,- });- expect(- result.every((item) => item.action === "manual-pause-required"),- ).toBe(true);- expect(provider.attemptedWrites).toHaveLength(0);- }- });-- test("a journey starting between read and write still reports the manual pause requirement", async () => {- const provider = fakeProvider();- provider.startDuringWrite(safetyTargets[0].workflowId);- const result = await enforceDeliverySafety(provider.api, {- healthy: false,- apply: true,- });- expect(result[0].action).toBe("manual-pause-required");- expect(result.slice(1).every((item) => item.action === "held")).toBe(true);- });-- test("unknown workflow states fail without edits", async () => {- const provider = fakeProvider("Unknown");- const result = await enforceDeliverySafety(provider.api, {- healthy: false,- apply: true,- });- expect(result.every((item) => item.action === "error")).toBe(true);- expect(provider.attemptedWrites).toHaveLength(0);- });-- test("healthy running journeys are not rewritten when already resumed", async () => {- const provider = fakeProvider("Sending");- const result = await enforceDeliverySafety(provider.api, {- healthy: true,- apply: true,- resume: true,- });- expect(result.every((item) => item.action === "resumed")).toBe(true);- expect(provider.attemptedWrites).toHaveLength(0);- });-- test("removing a hold requires pausing a running workflow first", async () => {- const provider = fakeProvider("Sending");- for (const target of safetyTargets) {- const guard = provider.guards.get(target.workflowId);- if (!guard) throw new Error("Missing fixture");- guard.audienceFilter = heldWorkflowAudience(target.journey);- }- const result = await enforceDeliverySafety(provider.api, {- healthy: true,- apply: true,- resume: true,- });- expect(- result.every((item) => item.action === "manual-pause-required"),- ).toBe(true);- expect(provider.attemptedWrites).toHaveLength(0);- });-- 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(- safetyTargets.length - 1,- );- });-- 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 fail the health check", 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.tsdeleted file mode 100644index acb85933a..000000000--- a/scripts/loops/watchdog.ts+++ /dev/null@@ -1,246 +0,0 @@-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) {- let sending = false;- let attemptedUpdate = false;- try {- const path = `workflows/${target.workflowId}`;- const workflow = await api.request<{- name: string;- status: string;- mailingListId: string;- rootNodeId: string;- nodes: Record<string, { nextNodeIds: string[] }>;- }>(path);- assert.equal(workflow.name, target.journey.name);- sending = workflow.status === "Sending";- assert(- ["Draft", "Sending", "Paused", "PausedAndQueueing"].includes(- workflow.status,- ),- "Unknown workflow status",- );- 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 &&- isDeepStrictEqual(nextFilter, guard.audienceFilter) &&- guard.appliesDownstream- )- nextFilter = undefined;- if (nextFilter && sending) {- results.push({- workflow: target.journey.key,- action: "manual-pause-required",- });- continue;- }- if (nextFilter && options.apply) {- attemptedUpdate = true;- 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 {- if (attemptedUpdate && !sending) {- try {- const latest = await api.request<{ status: string }>(- `workflows/${target.workflowId}`,- );- sending = latest.status === "Sending";- } catch {- sending = false;- }- }- results.push({- workflow: target.journey.key,- action: sending ? "manual-pause-required" : "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 manualPause = results.filter(- (result) => result.action === "manual-pause-required",- );- if (manualPause.length)- console.error(- `Pause these workflows in Loops now: ${manualPause.map((result) => result.workflow).join(", ")}. The Loops API cannot edit audience filters while a workflow is sending. Delivery has not been stopped.`,- );- const successfulActions = values.hold- ? ["held", "already-held"]- : ["healthy", "resumed"];- if (- (!healthy && !values.hold) ||- results.some((result) => !successfulActions.includes(result.action))- )- process.exitCode = 1;-}