Skip to the lesson
CivOps AI Academy · M16Email and Text Marketing: Consent, Sending, Journeys and Attribution
0%

Chapter 1 · Sessions 1–2

What the old tool holds, and the tables that replace it

Marketing email is the module where the platform speaks to people outside the company, so it starts with permission: who agreed to hear from you, when, and to what. Session 1 inventories the old tool from its own reports and bills and reads one real message's headers. Session 2 adds the eighteen mkt_ tables, consent and suppression first, tried on the development project before anything reaches production.

35 min5 stepsSessions 1 and 2About 8 hours hands-on across six sessions

By the end of this chapter you can

  • Inventory the old marketing tool: tools, consent counts as printed, lists, templates, automations, bill and export.
  • Read a real message's unsubscribe headers and SPF, DKIM and DMARC results.
  • Check the spine and CRM tables the module points at, and add only what is missing.
  • Have Claude Code write the eighteen mkt_ tables, consent and suppression first, with a made-up seed, a hand-worked fixture and tests, and try them on the development project.

What the module does, and what it replaces

The module grows and nurtures demand with the data under your control: segments, email campaigns and automated journeys, web tracking with consent, lead scoring with a hand-off to the CRM, and attribution of won jobs to the channels that brought them. It replaces HubSpot Marketing Hub, Adobe Marketo Engage, Salesforce Account Engagement (Pardot), ActiveCampaign, Mailchimp, Klaviyo or Customer.io [7]. It does not run a mail server: it sends through an email service provider's API (an ESP, such as Resend, Amazon SES or SendGrid). Web pages and forms are module M17; the sales pipeline is M15.

Consent and suppression in the send querySegment members pass a consent check and a suppression check before they are handed to the email service provider. Contacts without consent, or on the suppression list, are left out. Segment membersmkt_segment_memberConsent checklatest ledger row: grantedSuppression checkemail not on the listHanded to the ESPone message eachLeft out: no consentwithdrawn or never askedLeft out: suppressedunsubscribed or bouncedBoth checks sit inside the send query itself, so no screen or import can skip them.
The send gate. Consent and suppression are checked inside the one query that builds every recipient list, so no screen, import or journey can send around them.
RuleWhat it asks of youWhere the module keeps it
CAN-SPAM Act (US) [1]A working opt-out honoured promptly, the sender's postal address, no misleading subjectTemplate footer; one-click unsubscribe; the suppression list
TCPA (US texts) [2]Consent records for marketing textsThe sms consent purpose only: this module sends no texts
GDPR and ePrivacy; CCPA/CPRAConsent for marketing and tracking where the law requires itmkt_consent, with source, date and the wording agreed to
RFC 7208 (SPF), 6376 (DKIM), 7489 (DMARC) [4][5]Prove mail comes from your domainDNS records on your sending subdomain (Session 4)
RFC 8058 one-click unsubscribe [6]A mail app's unsubscribe button works with one pressList-Unsubscribe and List-Unsubscribe-Post on every message
Google and Yahoo bulk-sender requirements [3]Authentication, one-click unsubscribe, a low complaint rateThe deliverability panel; the 0.3% limit and 0.1% target
Step 1

Session 1: Inventory the old tool from its own reports and bills

50 minutes

Why

The module replaces real things, so it starts from what the old tool says about itself: how many contacts are subscribed, unsubscribed, bounced and complained, which lists and automations are live, and what it costs. Contact lists are personal data, so only counts and names of lists go into the repository; and a guessed saving is the fastest way to lose the argument for switching off.

Do this

Collect these yourself, from the tool's own screens and your invoices (Claude Code never logs in to it, and never sees a contact):

  • Every tool that sends marketing email or texts, its owner and who signs in.
  • Contact counts as the tool prints them: total, subscribed, unsubscribed, bounced, complained.
  • Twenty contacts picked at random: for how many does the tool record where the permission came from? Report only the twenty, never a guess for the whole list.
  • Lists and segments, templates (does each carry a postal address and a working unsubscribe?), and every automation with its trigger, waits and branches.
  • The bill, renewal date and cancellation notice, from the invoice or billing page; and whether the export gives contacts with consent status, lists, templates, engagement history and the suppression list.
Terminal or PowerShell
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code, after replacing the last line with your notes
On a new branch marketing/inventory, write docs/marketing-inventory.md from my notes below, for the tool's owner and finance, in plain English:
1. Tools: name, owner, bill per year, renewal date, notice period, export (contacts with consent / lists / templates / history / suppressions).
2. Contacts by consent status as the tool prints them, with the screen they came from, and the twenty-contact source check.
3. Lists, templates and automations, one line each; mark any automation nobody can explain.
4. The numbers people decide on today, marking every decision that rests on opens.
5. Workarounds.
Rules: use only the numbers in my notes; never estimate; write a missing number as "not yet read: <who can read it>". No email addresses or contact names. Open a pull request titled "Marketing inventory".

My notes:
<paste your notes here>

You will see recreated screen

your marketing tool · Audience · Overview
Contacts
1
StatusContacts
Subscribed6,412
Unsubscribed1,108
Cleaned (bounced)377
Complained9
Plan renews2027-02-142
The old tool's audience overview (every vendor's looks different). Copy the counts exactly as printed, with the date.
  1. Copy the labels too: the tool's 'cleaned' becomes the module's hard_bounce later, and the mapping starts from these words.
  2. The renewal date is your deadline for Session 6.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/marketing-inventory.md)
+| Subscribed | 6,412 | Audience overview, 2026-10-14 |
+| Source recorded, 20 checked | 13 of 20 | sign-up form 9, trade show 4; none recorded 7 |
1
⏺ Pull request #71 adds docs/marketing-inventory.md. The notice period is marked 'not yet read: finance'. I did not extend the twenty-contact check to the whole list.
Claude Code writes counts and gaps, never contacts.
  1. Seven of twenty with no recorded source is a finding: Session 5 will hold contacts like these back, not import them.

Check it worked

docs/marketing-inventory.md is in a pull request with counts as printed and their sources, the twenty-contact check, every list, template and automation, and no email address or name anywhere.

If it goes wrong

You want to give Claude Code the export to count

Do not. A contact list is personal data and stays in a private folder outside the repository. Count from the tool's own screens; Claude Code only ever sees column headings.

Claude Code extends the twenty-contact check to the whole list ("about 35% have no source")

Say: Report only the twenty I checked. Remove the estimate.

You cannot see the bill

Write who can, and ask them for the last invoice and the cancellation terms. Do not use a list price: your plan may differ.

Step 2

Session 1: Read one real message's headers

20 minutes

Why

Two lines in a message's raw source decide whether a mail app can unsubscribe a reader in one press, and one line says whether the message passed SPF, DKIM and DMARC. Reading them on a message the old tool really sent tells you what the new module must at least match, before you build anything.

Do this

Have the old tool send a campaign email to a mailbox you own. Open it, choose Show original (Gmail) or View source (most other mail apps), and copy only these lines: List-Unsubscribe, List-Unsubscribe-Post and Authentication-Results.

Paste into Claude Code, after pasting the three lines
Explain these header lines from one message our old marketing tool sent, in plain words: does it offer one-click unsubscribe (RFC 8058 needs both List-Unsubscribe with an https address and List-Unsubscribe-Post: List-Unsubscribe=One-Click), and did SPF, DKIM and DMARC pass, and for which domain? Then add a section "One real message" to docs/marketing-inventory.md with pass or fail for each, on the same pull request.

<paste the three header lines here>

You will see recreated screen

mail.google.com · Show original
SPFPASS with IP 198.51.100.241
DKIMPASS with domain mail.oldtool.example
DMARCPASS
List-Unsubscribe: <https://oldtool.example/u/8f3a…>, <mailto:u-8f3a@oldtool.example>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
Gmail's Show original. The summary at the top and the lines below are what you copy.
  1. DKIM passes for the tool's domain, not yours: DMARC alignment for your own domain is something the module sets up in Session 4.
  2. Both lines present: the module must offer the same, from your own domain.

Check it worked

The inventory says, for one real message, whether one-click unsubscribe was offered and whether SPF, DKIM and DMARC passed, and for which domain. Then the tool's owner reads the inventory, owner two approves and it merges.

If it goes wrong

There is no List-Unsubscribe-Post line

Then the old tool does not offer one-click unsubscribe as RFC 8058 defines it. Record it: it is a reason to switch, and the new module must do better.

DMARC says fail, or there is no DMARC result

Record it. Your domain may have no DMARC record. Session 4 sets one for the new sending subdomain; changing the main domain's record is a decision for IT.

Eighteen tables, consent and suppression first

Every table carries the spine's standard columns (site_id in place of the specification's tenant_id, as docs/spine-map.md records) and the prefix mkt_. The contact is never copied: every table that names one holds a soft link (a plain uuid with no foreign key) to crm_contact from module M15, so a marketing record survives the CRM being rebuilt. Money is whole cents in an integer column, as in the Foundation.

The eighteen mkt_ tablesSix groups: consent and suppression, audience and tracking, templates and sends, journeys, scoring, and campaigns and money, listing the eighteen mkt_ tables. Consent and suppressionmkt_consentmkt_suppressionAudience and trackingmkt_segmentmkt_segment_membermkt_web_visitTemplates and sendsmkt_email_templatemkt_email_sendmkt_email_eventJourneysmkt_flowmkt_flow_stepmkt_flow_enrollmentScoringmkt_score_rulemkt_score_eventCampaigns and moneymkt_campaignmkt_campaign_membermkt_attribution_touchmkt_ad_accountmkt_ad_spend_daily18 tables in all; crm_contact, crm_lead and crm_opportunity are soft links, not tables you own.
The eighteen tables in six groups. Consent and suppression are built first; the money group last.
GroupTablesKey columns and allowed values
Permission (first)mkt_consent, mkt_suppressionconsent: contact_ref, purpose (marketing_email, sms, tracking, profiling, third_party_sharing), status (granted, withdrawn), source, captured_at, text_version, ip_hash. suppression: email unique (lower case), reason (unsubscribe, hard_bounce, complaint, manual, legal), at
Audiencemkt_segment, mkt_segment_membersegment: name, definition json, is_dynamic, member_count, refreshed_at. member: segment_id, contact_ref, added_at
Sendingmkt_email_template, mkt_email_send, mkt_email_eventtemplate: name, subject, preheader, html, text_body, version, status (draft, approved, archived). send: template_id, segment_id, campaign_id, variant (a, b, control, single), status (draft, scheduled, sending, sent, cancelled), recipients, esp_batch_id. event: email_send_id, contact_ref, event (delivered, open, click, bounce_hard, bounce_soft, complaint, unsubscribe), url, at, esp_event_id
Journeysmkt_flow, mkt_flow_step, mkt_flow_enrollmentflow: trigger json, status (draft, active, paused, archived), version, reentry_allowed. step: step_no, step_type (send_email, wait, branch, update_field, add_to_segment, notify_owner, create_crm_task, webhook, exit), config, next and branch step numbers. enrolment: contact_ref, current_step_no, status (active, completed, exited, errored), next_run_at
Tracking and scoringmkt_web_visit, mkt_score_rule, mkt_score_eventvisit: anonymous_id, contact_ref, url, referrer, utm, visited_at. rule: rule_type (fit, engagement, negative), condition, points, decay_days, active. event: contact_ref, score_rule_id, points, at, expires_at
Money and attributionmkt_campaign, mkt_campaign_member, mkt_attribution_touch, mkt_ad_account, mkt_ad_spend_dailycampaign: campaign_type, status (planned, active, paused, completed), budget, actual_spend, utm_campaign, owner_id. touch: contact_ref, opportunity_ref, channel, touch_type (first, lead_creation, opportunity_creation, close, other), credit. ad account: platform (linkedin, meta, google, tiktok, microsoft). spend: spend_date, spend, impressions, clicks, conversions
Step 3

Session 2: Check the spine and the CRM tables the module points at

20 minutes

Why

The mkt_ tables point at people, roles, approvals, signatures, action items, notifications and the event outbox on the spine, and read contacts and won opportunities from the CRM. Adding only what is missing, in its own migration and with the CRM's own column names, means module M15 can take its tables over later without a copy that drifts.

Do this

Paste into Claude Code
Read docs/spine-map.md if another module has written it, and every file in supabase/migrations. Do not write anything yet.

Module M16 points at these spine tables: core_person, core_job_role, core_comment, core_approval, core_e_signature, core_action_item, core_notification, core_event_outbox and core_audit_log, with core_current_actor(), core_touch_row() and core_audit_row(), as defined in the CivOps module library's spine (00_core_spine.sql). It reads module M15's crm_contact (first_name, last_name, email, owner_id, lifecycle_stage, source, do_not_contact), crm_opportunity (amount, primary_contact_id, owner_id, stage_id) and crm_pipeline_stage (is_won).

Tell me in a table which exist (under the specification's name or ours), which are missing, and any that differ. We are one company: our module tables carry site_id in place of tenant_id. Then propose, and wait for my yes: a Marketing section in the one shared docs/spine-map.md (create it if no module has yet; never a second map file), with each core_ and crm_ name and our table for it, site_id in place of tenant_id, and any table that is company-wide; and one migration (npx supabase migration new spine_for_marketing) adding only what is missing, CRM tables with exactly those columns and module M15's names; row-level security on and none of the spine's tenant_isolation policies, because access comes only from docs/matrix.json through scripts/gen-policies.mjs. Never put spine or CRM tables inside the module's own migration.

You will see recreated screen

claude — acme-platform
⏺ Bash(ls supabase/migrations)
⎿ 19 files
⏺ Exist (from the documents module): core_person, core_job_role, core_e_signature, core_action_item, core_event_outbox, core_audit_log and the helpers. Missing: core_comment, core_approval, core_notification, and the three crm_ tables.1
Write spine_for_marketing with the six missing tables?
❯ 1. Yes
  2. No, change the plan
A report first. If you built M06 or M15 already, most of this exists.
  1. Reuse what exists; add only the gap.

Check it worked

You agreed a table of exists and missing and the Marketing section of docs/spine-map.md; after your yes, pull request "Spine for marketing" is green, with no tenant_isolation policies.

If it goes wrong

Claude Code adds crm_contact columns M16 does not need (phone, address)

Say: Only the seven columns I listed, with M15's names. M15 adds the rest when it is built.

Claude Code puts crm_contact inside the marketing migration

Say: Move it to the spine migration. The module migration must never own a table another module owns.

Claude Code adds a tenant_id column or a core_tenant table

Say: We are one company: module tables carry site_id, as docs/spine-map.md records. Remove tenant_id and core_tenant. A second scope column means a second access rule nobody generated.

Step 4

Session 2: One prompt: the tables, consent first, the seed, the hand-worked fixture and the tests

45 minutes

Why

Consent and suppression are built first, in their own migration, so everything after them is built behind them. The rules the database keeps (the ledger only grows, an address is suppressed once, a webhook sent twice makes one row) protect every screen, import and job, including ones not yet written. The twelve made-up contacts are what Session 4 counts by hand: kept on fixed dates as a test fixture, and shifted onto today as the seed the screens show.

Do this

Paste into Claude Code
Read docs/marketing-inventory.md and the spine migration. On a new branch marketing/tables:

1. npx supabase migration new create_marketing_permission: mkt_consent and mkt_suppression with the standard spine columns (site_id where docs/spine-map.md says a row belongs to a site, with an index; core_touch_row() and core_audit_row() triggers) and exactly the columns and allowed values in element M16's table. mkt_suppression.email unique and stored in lower case. mkt_consent only grows: update and delete refused, except setting archived_at on a granted row whose source starts with import:.

2. npx supabase migration new create_marketing: the other sixteen tables the same way. contact_ref, lead_ref and opportunity_ref are plain indexed uuids with no foreign key; money is integer cents. Rules: mkt_email_event unique on esp_event_id when present; mkt_segment_member unique per segment and contact while not archived; mkt_ad_spend_daily unique per ad account, external campaign and date; one active enrolment per contact and flow unless reentry_allowed; fit and engagement rules have positive points, negative rules negative; an approved or archived template and an active flow cannot be edited except to move status forward (a change is a new row, version + 1). Write these rules in docs/mkt-rules.md.

3. Add all eighteen tables to docs/matrix.json with no rights yet, and run scripts/gen-policies.mjs.

4. supabase/seeds/marketing.sql, made up, marked SYNTHETIC, addresses at example.com, safe to run twice, listed under [db.seed] sql_paths in supabase/config.toml (never in supabase/seed.sql), every date below moved by the same number of days so that 2026-09-30 falls on the day the seed runs. Twelve contacts C01–C12 with one owner. Consent: C01–C08 and C11 granted marketing_email 2026-07-01 (source "seed sign-up form", text_version v1); C09 granted 2026-08-10, withdrawn 2026-09-10; C10 none; C12 tracking only; C05 and C06 also tracking. Suppression: C11, hard_bounce, 2026-08-01. Segments "All contacts" (static, 12) and "Clickers" (dynamic: a click in the 30 days to 2026-09-30). Templates: Newsletter v1 approved, v2 draft; Welcome and Welcome reminder v1 approved. Send A 2026-08-01 to C01–C08 and C11: 8 delivered, bounce_hard C11, click C02. Send B 2026-09-20 to C01–C08: 8 delivered, opens C01, C03 (twice), C04, C05; clicks C01 (09-27), C03 (09-20, 09-25), C04 (09-25). Score rules: fit +20 for C03–C06; click +5, decay 30 days; /pricing visit +10, decay 30; negative -5 for C04. Visits: C05 /pricing 2026-08-15, C06 /pricing 2026-09-22. Ad accounts google "Seed search", meta "Seed social"; campaigns Seed search, Seed social, Seed newsletters, Seed referrals, budget 100000 each. Spend: search 20000, 25000, 15000 on 09-28 to 09-30; social 30000, 30000 on 09-29, 09-30. Won opportunities in September: A 600000 (C03), B 450000 (C06), C 300000 (C01). Touches: A paid_search first, email lead_creation, email opportunity_creation, referral close; B paid_social first, email lead_creation, referral close; C referral first. Write the same rows, on exactly these dates, to tests/fixtures/marketing-contacts.json: the hand-worked example Session 4's tests load into a made-up site of their own; no test counts on the seed's dates.

5. pgTAP tests in supabase/tests/marketing.test.sql: row-level security on all eighteen; refused: a consent purpose outside the list, a suppression differing only in capitals, a template status outside the list, an update of a consent row, a fit rule with negative points, an edit of an approved template. After the seed: 12 contacts, 1 suppression, 17 send events in send B.

Do not connect to any Supabase project. Push, open a pull request titled "Marketing: tables", wait for every check, and report in plain words with the number of tests. If a check fails, fix it and wait again.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase migration new create_marketing_permission)
⎿ Created new migration at supabase/migrations/20261103090000_create_marketing_permission.sql
1
⏺ Write(supabase/migrations/20261103090000_create_marketing_permission.sql)
+create unique index mkt_suppression_email_uq
+ on public.mkt_suppression (lower(email));
+create trigger mkt_consent_only_grows before update or delete on public.mkt_consent
+ for each row execute function public.mkt_consent_guard();
2
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m22s
⏺ Pull request #73 is green. 18 tables, 64 tests, 6 of them bad writes that are refused. After the seed: 12 contacts, 1 suppression (C11).
Two migrations, permission first, and the tests that try to break the rules.
  1. The permission tables arrive first, in their own file.
  2. SAM@example.com and sam@example.com are one address: the second insert is refused.

Check it worked

Pull request Marketing: tables is green on GitHub, and docs/mkt-rules.md lists every rule the database now keeps.

Fastest path

Paste the whole prompt once. Adding each rule as you think of it costs a round trip per rule, and the rules that arrive late are the ones a test never covers.

If it goes wrong

CI fails: table mkt_consent is not in docs/matrix.json

The generator is doing its job. Say: Add the eighteen mkt_ tables to docs/matrix.json with no rights and rerun gen-policies.

The summary says green but the check on GitHub is red

Say: Show me the exact command, its exit code and the last 20 lines of the failed log, then fix the cause. The check on the pull request is the evidence; the summary is a claim.

Claude Code adds real-looking addresses to the seed

Say: Use only addresses at example.com, a domain reserved for documentation, and mark every row synthetic. A seeded address on a real domain is one bug away from a real email.

Step 5

Session 2: Try it on the development project, then merge

15 minutes

Why

CI builds the database from nothing; the development project proves the files also apply on top of the Foundation's history, the way production will. You do it yourself because it changes a database; after merge the deploy workflow from Foundation Session 11 applies the same files to production, without the seed.

Do this

Terminal or PowerShell
cd ~/code/acme-platform && git fetch && git switch marketing/tables
Terminal or PowerShell
npx supabase link --project-ref tsrqponmlkjihgfedcba
Terminal or PowerShell
npx supabase db push --include-seed

--include-seed loads the module's made-up rows the first time; after that, reload them with npm run seed:dev. Then open the development project's SQL editor and run the check below.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new

The development project's SQL editor. Check the name at the top says acme-platform-dev.

Supabase SQL Editor ({{sbDevProject}})
-- Expect 12 contacts, 1 suppression, 10 granted marketing_email rows (C01-C09, C11) and 1 withdrawn (C09, later)
select (select count(*) from crm_contact) contacts,
       (select count(*) from mkt_suppression) suppressions,
       (select count(*) from mkt_consent where purpose = 'marketing_email' and status = 'granted') granted,
       (select count(*) from mkt_consent where purpose = 'marketing_email' and status = 'withdrawn') withdrawn;

Owner two approves, you merge, and the deploy run applies the migrations to production:

Open

https://github.com/acme-ops/acme-platform/actions

GitHub Actions: the deploy run for the merge must be green.

You will see recreated screen

Terminal
$ npx supabase db push --include-seed
Do you want to push these migrations to the remote database? • 20261103085000_spine_for_marketing.sql • 20261103090000_create_marketing_permission.sql • 20261103091500_create_marketing.sql [Y/n] y1
Seeding data from supabase/seeds/marketing.sql...
Finished supabase db push.
db push applies exactly the new files to the development project.
  1. Only the new files, on acme-platform-dev. Anything else: answer n and ask why.

Check it worked

On acme-platform-dev the check returns 12, 1, 10 and 1. After merge the deploy run is green, and no seed row is in production.

If it goes wrong

db push lists migrations you did not write

The development project is behind main. Answer n, push main's migrations first, then the branch.

The deploy run fails at migrate

Production is unchanged. Copy the log's error into Claude Code: The production migrate step failed with this error. Explain it and propose a fix as a new migration. Do not touch production.

Knowledge check

Where do the contact counts in docs/marketing-inventory.md come from?

Knowledge check

Why is contact_ref a plain uuid with no foreign key?

References

  1. FTC: CAN-SPAM Act, a compliance guide for business. https://www.ftc.gov/business-guidance/resources/can-spam-act-compliance-guide-business
  2. FCC: Stop unwanted robocalls and texts (the TCPA rules). https://www.fcc.gov/consumers/guides/stop-unwanted-robocalls-and-texts
  3. Google: Email sender guidelines. https://support.google.com/a/answer/81126
  4. IETF RFC 7208: Sender Policy Framework (SPF). https://www.rfc-editor.org/rfc/rfc7208
  5. IETF RFC 7489: DMARC. https://www.rfc-editor.org/rfc/rfc7489
  6. IETF RFC 8058: Signaling One-Click Functionality for List Email Headers. https://www.rfc-editor.org/rfc/rfc8058
  7. Abmatic: best B2B marketing automation platforms 2026. https://abmatic.ai/blog/best-marketing-automation-platforms-b2b-2026

Chapter 2 · Sessions 3–4

Who may do what, the screens, and sending that only reaches people who agreed

Marketing is where programs act for the business all day: a sender, a receiver of delivery events, a journey runner. Session 3 names them in the role matrix next to the people, and builds the screens on all three surfaces plus the contact's own pages. Session 4 builds the send path in the order that keeps people safe: eligibility first, one-click unsubscribe, an authenticated domain, the send and webhook routes, then segments, a journey, scoring and attribution, each counted by hand.

40 min5 stepsSessions 3 and 4One rule every send uses

By the end of this chapter you can

  • Write people, programs and the contact into docs/matrix.json, and regenerate policies, route guards and tests.
  • Build the builder, review queue, results, contact and preference screens, and open the public pages by exact path.
  • Build one eligibility function every send uses, and RFC 8058 one-click unsubscribe.
  • Authenticate a sending subdomain and send through an ESP, counting a message as sent only when the ESP returns an id.
  • Build segments, a journey, lead scoring and attribution, and match each to a hand count of the seed.

People, programs and the contact

RoleDoesNever
MarketerBuilds segments, draft templates, draft sends, draft journeys and score rules; reads results and consentApproves; sends to anyone but themselves in test mode; writes consent or suppression
Marketing approverApproves or rejects templates and journeys, signed with meaning approvedApproves their own work
Marketing leadBudgets, ad accounts, spend uploads, manual and legal suppressions; reads everythingUpdates a consent row (except archiving a bad import batch)
CRM ownerReads their own contacts' consent, scores and touches; receives MQL action itemsReads other owners' contacts
Contact (no sign-in)Signs up, sets preferences, unsubscribes, accepts tracking, through signed links and public formsReads anything back except their own choices
mkt_sender (machine)The send route: reads eligibility and approved templates, records each recipient, updates the sendWrites consent; sends an unapproved template
mkt_webhook (machine)The webhook route: inserts events, suppressions on bounce and complaint, withdrawn consent on unsubscribeReads templates or contacts' details beyond matching
mkt_automation, mkt_spend (machine)Journeys, scoring and MQL hand-off; spend and attributionSend directly: journeys only schedule a send the send route checks
mkt_importer (machine, Sessions 5–6)Inserts only: suppressions, contacts with consent source, lists, templates as drafts, historyUpdate anything; approve a template; import a contact without a consent source; sign in after cut-over
Step 6

Session 3: Write people, programs and the contact into the matrix

40 minutes

Why

Every program that sends or receives on the business's behalf is a role with its own sign-in and its own narrow rights, so a bug in one cannot send to people who never agreed. Writing every read and write that Sessions 4 to 6 need, now, and testing each, stops the button that reports success while nothing changes.

Do this

Paste into Claude Code, after pasting the table
Read docs/matrix.json, scripts/gen-policies.mjs, lib/access/routes.ts and docs/mkt-rules.md. On a new branch marketing/access, add module M16:

Roles: mkt_marketer, mkt_approver, mkt_lead, crm_owner (if missing), and machine accounts mkt_sender, mkt_webhook, mkt_automation, mkt_spend and mkt_importer, each with its own sign-in, never the service-role key. The contact has no sign-in: the public routes act for them with only the cells listed for "contact".

Cells: exactly the rights in the M16 role table I paste below. Nobody gets delete. Nobody updates mkt_consent except mkt_lead archiving a granted row whose source starts with import:; mkt_importer only inserts.

Rules (restrictive): an approver never approves a template or flow they created; only mkt_sender may set a send to sending or sent; a crm_owner reads only contacts whose owner_id is theirs and the rows keyed to them. For every update, make sure the role's read rule covers the row after the change.

Screens: /marketing/build (marketer, lead), /marketing/review (approver), /marketing/results (lead, marketer read only), /marketing/contact (marketer, lead, crm_owner). Public by exact path only, nothing else under them: /preferences, /unsubscribe, /api/marketing/signup, /api/marketing/track, /api/marketing/esp-webhook. Staff routes: /api/marketing/send (mkt_sender; marketer and approver in test mode only, to their own address), /api/marketing/automation/run (mkt_automation), /api/marketing/spend/run (mkt_spend), /api/marketing/spend-upload (lead). mkt_importer has no screen and no route: it signs in only from the import workflow.

Write docs/mkt-access-check.md: one line per read or write Sessions 4 to 6 ask for (role, table, action), and remove any cell no line uses. Regenerate the policies with scripts/gen-policies.mjs, lib/access/routes.ts with scripts/gen-routes.mjs, and docs/access-review.md, and turn every line into an allowed test plus these refusals: a marketer approving, an approver approving their own, a marketer inserting a suppression, the webhook route reading templates, the send route inserting consent, a test send to someone else, a signed-out request to each staff screen. Each update test checks the row really changed.

Push, open a pull request titled "Marketing: access", wait for every check, and report.

The M16 role table:
<paste the "People, programs and the contact" table from element M16, chapter 2>

You will see recreated screen

claude — acme-platform
⏺ Write(docs/matrix.json)
+"public": ["/preferences", "/unsubscribe", "/api/marketing/signup",
+ "/api/marketing/track", "/api/marketing/esp-webhook"],
1
⏺ Bash(gh pr checks --watch)
⎿ access / test pass 2m16s
⏺ Pull request #74 is green. 9 new roles; docs/mkt-access-check.md has 58 lines and every line is a passing test; I removed 3 cells nothing used. A signed-out request to /api/marketing/send-test (an address that does not exist) is refused too.2
The public pages are opened one exact address at a time; everything else stays behind sign-in.
  1. Exact paths. A whole folder made public is how a later route ends up open by accident.
  2. A cell nobody uses is a right nobody needs.

Check it worked

Pull request Marketing: access is green, docs/mkt-access-check.md lists every read and write of Sessions 4 to 6 as a passing test, and owner two has read docs/access-review.md.

If it goes wrong

Claude Code calls a group of security warnings false positives

Never accept that for a group. We found routes dismissed that way open on production, able to send email to named people under the company's domain. Say: For each warning separately, show the request with no sign-in and the response you got.

Claude Code makes /api/marketing/ public "so the webhook works"

Say: Only the exact paths listed. A folder made public opens every route filed there later.

An approve button reports success but the status stays draft

The approver's read rule does not cover the approved row. Say: Check each updating role's read rule covers the row after the change, with a test that the row really changed.

Step 7

Session 3: Build the screens, and the contact's pages for a phone

40 minutes

Why

Most contacts open an unsubscribe link on a phone, so the unsubscribe and preference pages are tested on a phone first. Staff screens on three surfaces keep the work where it belongs: building on the operator surface, approval on the supervisor's review queue, results on the manager's view.

Do this

Paste into Claude Code
Before writing any page or route, read the guides in node_modules/next/dist/docs/ for routing and proxy.ts (this Next.js version differs from older guides), and lib/access/routes.ts.

On a new branch marketing/screens, against the seed:
- /marketing/build: segments, templates (with status), sends, journeys and score rules.
- /marketing/review: drafts waiting for the approver, oldest first; approve, or reject with a comment.
- /marketing/results: deliverability, MQLs, cost per lead by channel and attribution, each saying which model and which dates, readable across a room (Foundation Session 13's manager view).
- /marketing/contact: one contact's consent ledger newest first, suppression, score and touches.
- /preferences and /unsubscribe: no sign-in, one clear action in a button of at least 44 px.
Routes as stubs that refuse the wrong role correctly; Session 4 fills them in. Take the signed-in person from the session on the server. Screen tests per role, signed out, and at 360 and 390 px. Push, open a pull request titled "Marketing: screens", wait for every check, and give me the preview address.

You will see recreated screen

acme-platform-git-marketing-screens-acme-ops.vercel.app/unsubscribe
Unsubscribe from Acme Bottling marketing email
c03@example.com will get no more marketing email from us.
Unsubscribe1
Or choose what you hear about on the preferences page.
/unsubscribe on a phone: one action, no sign-in, no maze.
  1. One button, at least 44 px tall. The one-click header in Session 4 skips even this page.

Check it worked

Every check is green. On your own phone, /unsubscribe and /preferences on the preview fit the screen with no sideways scrolling; signed in as each test role, each staff screen shows what the matrix says and nothing more.

Fastest path

Sit the marketer at the builder and the approver at the review queue for ten minutes this week, without explaining, and note where each stops.

If it goes wrong

The results page shows numbers before any send exists

Say: Show 'No data' where nothing was measured; never a placeholder number. We have seen dashboards fill empty places so they look finished.

A contact list file appears under public/

Remove it at once. Files in public/ are served to anyone and never pass the sign-in gate. Say: Nothing with an address goes under public/; add a check that fails if one is added.

Every send passes one gate

One database function, mkt_eligible_contacts(purpose, segment_id, contact_ref), is used by every send, count and check. A contact is eligible only if their newest unarchived consent row for the purpose is granted, their lower-cased address is not in mkt_suppression, and the CRM's do_not_contact is false. On the seed, the twelve contacts of "All contacts" give eight: C09 withdrew, C10 never agreed, C11 is suppressed and C12 agreed only to tracking.

Four standards that make mail trustedFour boxes: SPF says which servers may send for a domain, DKIM signs the message, DMARC checks that SPF or DKIM match the visible From domain, and RFC 8058 defines one-click unsubscribe. SPF · RFC 7208Is this server allowedto send for the domain?DKIM · RFC 6376Is the message signedand unaltered?DMARC · RFC 7489Do SPF or DKIM matchthe From domain?Unsubscribe · RFC 8058One click, no login,processed at onceThe ESP signs and sends; you publish the records for your own sending domain.A DMARC check that fails, or a missing one-click unsubscribe, is a reason for mailboxes to refuse bulk mail.
Four standards behind trusted mail. SPF and DKIM prove where a message came from; DMARC ties them to the address people see; RFC 8058 makes the unsubscribe one press.
Step 8

Session 4: The eligibility gate and one-click unsubscribe

35 minutes

Why

Building the rule that protects people before anything can send means no later feature can forget it. One-click unsubscribe is both the law's opt-out and the mailbox providers' requirement: a press of the button in the mail app must suppress the address at once, with no page and no sign-in, and pressing it twice must still mean once.

Do this

Paste into Claude Code
On a new branch marketing/send, write:
1. mkt_eligible_contacts(purpose, segment_id, contact_ref) in a migration, as element M16 describes. Tests on tests/fixtures/marketing-contacts.json, loaded into a made-up site of their own: All contacts gives 8 (C01–C08); with C01's do_not_contact true, 7; contact C03 gives 1; C09 gives 0; a suppressed address is never in the result.
2. /api/marketing/signup: inserts a granted mkt_consent with source (the form's name), text_version and a hashed IP; answers identically whether or not the address was known.
3. /unsubscribe: a POST with body List-Unsubscribe=One-Click, no sign-in, no confirmation page, as RFC 8058 describes; the link carries a token signed with UNSUBSCRIBE_TOKEN_SECRET from the environment; in one transaction insert mkt_suppression (unsubscribe), a withdrawn consent row and a mkt.contact.unsubscribed outbox event. A GET shows the one-button page. Tests: posting twice leaves one suppression row; a forged token is refused and writes nothing.
Show each new test failing with its rule removed, then passing. Push, open a pull request titled "Marketing: send", wait for every check, and report.

You will see recreated screen

claude — acme-platform
⏺ Bash(npm test -- marketing.eligible)
⎿ All contacts: 8 (C01-C08) C01 do_not_contact: 7 C03: 1 · C09: 0 suppressed in result: 0
1
⏺ Bash(npm test -- marketing.unsubscribe)
⎿ one-click POST twice: 1 suppression row forged token: 403, 0 rows written
⏺ The gate and one-click unsubscribe are in pull request #76 and green. Without the suppression check the 'never suppressed' test fails, so it can fail.
The gate first, proved on the seed you can count by hand.
  1. Eight of twelve: the same number you get by reading the fixture.

Check it worked

The tests show 8, 7, 1 and 0 on the fixture, one suppression row after two presses, and a forged token refused.

If it goes wrong

Claude Code checks suppression in the screen, not the function

Say: Suppression and consent are checked inside mkt_eligible_contacts, and every send reads recipients only from it. A rule in a screen protects one screen.

The unsubscribe link works without a token

Anyone could then unsubscribe anyone. Say: Refuse any request whose token does not verify, and test a forged one.

Key or secretWhat it unlocksWhere it livesWho holds itNever
ESP API keySends mail through the ESPVercel environment variables (Production, Preview); the ESP's dashboardOwner one creates it in the ESP and types it into VercelPasted into Claude Code, a file, the repository or a chat
ESP_WEBHOOK_SECRETProves a webhook call came from the ESPVercel environment variablesOwner oneLogged, or skipped "for testing"
UNSUBSCRIBE_TOKEN_SECRETSigns unsubscribe and preference linksVercel environment variablesOwner one; made with openssl rand -hex 32Reused for anything else
Machine account passwords (mkt_sender, mkt_webhook, mkt_automation, mkt_spend)Each program's own sign-inVercel environment variables, and the password managerOwners one and twoReplaced by the service-role key
Step 9

Session 4: Authenticate the domain, then send through the ESP and receive its events

60 minutes

Why

The module never runs a mail server: an ESP already holds the reputation, queues and feedback loops that delivery needs, and building your own is this module's first named pitfall. A subdomain keeps marketing's reputation apart from the company's own mail. A message counts as sent only when the ESP returns its id, because we have seen "sent" shown for mail that never left.

Do this

A day ahead, as a person: choose the ESP (Resend, Amazon SES and SendGrid are the ones the specification names), read its price page, and add a sending subdomain such as news.acme.com in its dashboard. Publish the SPF and DKIM records it shows, and your own DMARC record, at your DNS host (with IT if they run DNS). Then check them from your terminal:

Terminal or PowerShell
nslookup -type=TXT _dmarc.news.acme.com

Create the API key and webhook secret in the ESP, make UNSUBSCRIBE_TOKEN_SECRET with openssl rand -hex 32, and type all three, with the machine accounts' passwords, into Vercel. Add the names, never the values, to docs/KEYS.md.

Open

https://vercel.com/acme-ops/acme-platform/settings/environment-variables

Vercel environment variables (Production and Preview).

Paste into Claude Code
Read the ESP's API and webhook documentation pages first and tell me which you read. On the same branch:
1. Templates and approval: tokens such as [first_name]; the footer must carry our postal address and the unsubscribe link; the approver approves with core_approval and a core_e_signature (meaning approved); an approved template is frozen and an edit makes version 2. Test sends go only to the signed-in person's own address, through /api/marketing/send in test mode, and write no mkt_email_send row.
2. /api/marketing/send, signed in as mkt_sender: recipients only from mkt_eligible_contacts; one message per recipient with List-Unsubscribe (https, with a signed token) and List-Unsubscribe-Post: List-Unsubscribe=One-Click; record each recipient in mkt_campaign_member before calling the ESP and skip anyone already marked sent, so a retry never sends twice; a recipient counts as sent only when the ESP returned a message id; on failure log the ESP's status and reason (never the key, address or body) and show the true count. A --dry-run mode writes the exact requests to a log and sends nothing. If the ESP key is missing, refuse in production; never pretend to send.
3. /api/marketing/esp-webhook, signed in as mkt_webhook: verify the ESP's signature with ESP_WEBHOOK_SECRET and refuse anything else, writing nothing; one mkt_email_event per ESP event id; bounce_hard and complaint insert a suppression (and complaint a withdrawn consent); unsubscribe the same with reason unsubscribe; click or open marks the campaign member responded.
4. The deliverability panel: delivered ÷ sent, complaints ÷ delivered (limit 0.3%, target 0.1%), click-to-open = unique clicks ÷ unique opens shown beside unique clicks ÷ delivered. On the fixture: send B 8 of 8 delivered, 4 unique opens, 3 unique clicks.
5. Tests: a fake ESP that refuses a send gives the honest count and a log line; the same webhook payload twice makes one event; a wrong signature writes nothing; a retried send sends nobody twice.
Push, wait for every check, and report. Do not send to any real address.

When it is green, do one live send yourself from the preview: sign up three mailboxes you own through /api/marketing/signup (source "staff test form"), send an approved template to a segment holding only them, and open each message's raw source.

You will see recreated screen

Terminal
$ nslookup -type=TXT _dmarc.news.acme.com
_dmarc.news.acme.com text = "v=DMARC1; p=none; rua=mailto:dmarc@acme.com"1
The DMARC record for the sending subdomain, as the world sees it.
  1. p=none watches without blocking while you start; the reports to rua show every sender using the domain. Tighten it with IT once the reports are clean.

You will see recreated screen

mail.google.com · Show original
SPFPASS with domain news.acme.com
DKIMPASS with domain news.acme.com
DMARCPASS1
List-Unsubscribe: <https://acme-platform.vercel.app/unsubscribe?t=eyJ…>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
The raw source of the live test message: both one-click lines, and all three checks passing for your subdomain.
  1. DMARC aligned: the From domain matches the domain that passed DKIM.
  2. Press the mail app's Unsubscribe and check the suppression row appears within seconds.

Check it worked

Every check is green; the live test reached your three mailboxes with SPF, DKIM and DMARC passing for your subdomain and both one-click headers present; the send shows 3 sent with three ESP message ids; the same webhook replayed twice made one event.

If it goes wrong

The page says "sent" but nothing arrives

The send route ignored the ESP's refusal. Say: Count a recipient as sent only when the ESP returned a message id; on failure log the status and reason, never the key or address, and show the true count. Add a test with a fake ESP that refuses.

"Send all" works on the preview with no ESP key set

A stand-in is pretending. Say: With no ESP key, the send route must refuse in production and say which service is missing.

Claude Code suggests running a small SMTP server instead of the ESP

Refuse. Building a mail server is the pitfall the specification names first: delivery depends on reputation and feedback loops an ESP already has.

The ESP still shows the domain as unverified

DNS can take hours. Carry on with the dry run, and come back to the live send. Check the records with nslookup before asking the ESP's support.

A journey: trigger, wait, branchA form submission triggers a welcome email, then a two-day wait, then a branch. If the contact clicked, the owner is notified and a CRM task is created; if not, a reminder is sent and the journey exits. The contact's place is one mkt_flow_enrollment row. Triggerform submittedSend emailwelcome messageWait2 daysBranchclicked a link?Yes: notify ownerand create a CRM taskNo: send reminderthen exittruefalsemkt_flow_enrollmentcurrent_step_no, next_run_atOne row per contact marks their place.Each box is a row in mkt_flow_step; branch_true_step_no and branch_false_step_no point at the next rows.
A journey step waits by storing a time. The enrolment keeps next_run_at; the automation job runs every enrolment whose time has come, and its sends still pass the eligibility gate.
Step 10

Session 4: Segments, a journey, scoring and attribution, each matched to a hand count

60 minutes

Why

These four features turn numbers into decisions: who to mail, when to follow up, who sales should call, and which channel earned the money. Each is checked against a hand count of the seed, because a number nobody can recount is a number nobody should act on. Opens are kept but never decide anything, because privacy proxies open mail automatically.

Do this

Paste into Claude Code
On a new branch marketing/automation, signed in as mkt_automation and mkt_spend for the jobs (called by Vercel cron with CRON_SECRET; read Vercel's cron docs for our plan's limits first). Every job takes "now" as a parameter so tests can fix the date, and writes once however often it runs.
1. Segments: one rule per row (field, operator, value) in mkt_segment.definition, only fields on an approved list, values always as query parameters, never joined into SQL. Two live counts: matching and eligible now. Fixture: All contacts 12 and 8; Clickers 3 and 3 (C01, C03, C04).
2. The Welcome journey: send Welcome, wait 2 days, branch on a click since step 1, true: notify_owner, false: send Welcome reminder, then exit. The job never sends: it inserts a single scheduled send with the contact in ext.contact_ref, checked by mkt_eligible_contacts first. Test with C01–C04 (C01, C02 click; C04 suppressed before the clock moves): two notifications, one reminder, C04 exited, three mkt.flow.completed events, nothing new on a second run.
3. Tracking only after consent: no script until the banner is accepted; an anonymous visitor's choice in a first-party cookie, written to mkt_consent when they identify.
4. Scoring: score = sum of unexpired score events; MQL threshold 30 in docs/mkt-rules.md; crossing it writes one mkt.lead.mql event and one action item for the CRM owner. As at 2026-09-30: C01 5, C03 30, C04 20, C05 20, C06 30, others 0; exactly C03 and C06 become MQLs; a second run adds none.
5. Attribution in whole cents for first touch, last touch, linear and W-shaped (write the weights, the rule for a missing touch and where leftover cents go in docs/mkt-rules.md). Fixture: first touch paid_search 600000, paid_social 450000, referral 300000; last touch referral 1350000; linear paid_search 150000, paid_social 150000, email 450000, referral 600000; every model totals 1350000.
Each test shown red first. Push, open a pull request titled "Marketing: automation", wait for every check, and report.

You will see recreated screen

claude — acme-platform
⏺ Bash(npm test -- marketing.automation)
⎿ segments: 12/8, 3/3 journey: 2 notified, 1 reminder, C04 exited, 3 completed; rerun: 0 new MQL: C03, C06; rerun: 0 new attribution: first 1350000 · last 1350000 · linear 1350000 · W 1350000
1
⏺ Pull request #78 is green. Every model reconciles to the 1,350,000 cents of won revenue. Opens are stored but no rule or decision uses them.
Four features, four hand counts, all matching.
  1. Every number here is one you can recount from the fixture with a pencil.

You will see recreated screen

acme-platform-git-marketing-automation-acme-ops.vercel.app/marketing/results
Complaint rate0 of 16 delivered · limit 0.3%
MQLs2 (C03, C06)
1
ChannelWon revenue, first touchCost per won job
paid_search$6,000.00$600.00
paid_social$4,500.00$600.00
referral$3,000.00no spend
The results view on the preview, stating its model and dates on every figure.
  1. The model is named on the table. A cost per job without its model is not a number anyone can check.

Check it worked

Every check is green, and the four hand counts in the tests match the fixture: 8 eligible, Clickers 3, C03 and C06 as MQLs, 1,350,000 cents for all four models. Owner two approves and you merge; the deploy applies the migrations.

If it goes wrong

The journey sends a reminder to C04 after suppression

The job sent directly or skipped the gate. Say: The automation job never sends; it schedules a single send and checks mkt_eligible_contacts for that contact first. Add the C04 test.

Attribution totals are a few cents off

Rounding. Say: Credit in whole cents; give leftover cents to the touch named in docs/mkt-rules.md, so each model totals the revenue exactly.

The job adds a new MQL action item every run

Say: Read before writing: insert the event and the action item only if none exists for that contact and threshold. Test two runs.

Knowledge check

A send is delivered to 5,000 contacts and draws 10 complaints. Where does it stand?

Knowledge check

Why must the send route count a recipient as sent only when the ESP returns a message id?

References

  1. IETF RFC 8058: Signaling One-Click Functionality for List Email Headers. https://www.rfc-editor.org/rfc/rfc8058
  2. Google: Email sender guidelines. https://support.google.com/a/answer/81126
  3. Yahoo Sender Hub: sender best practices. https://senders.yahooinc.com/best-practices/
  4. IETF RFC 6376: DomainKeys Identified Mail (DKIM) Signatures. https://www.rfc-editor.org/rfc/rfc6376
  5. Resend documentation: sending email and webhooks. https://resend.com/docs
  6. Vercel Docs: Cron jobs. https://vercel.com/docs/cron-jobs

Chapter 3 · Sessions 5–6

Move the contacts in, then switch the old tool off

Session 5 imports in an order that cannot hurt anyone: suppressions first, then only contacts whose permission has a source, then lists, templates and history, rehearsed on the development project with a copy IT approved. Session 6 runs old and new side by side, imports for real through the pipeline, proves one-click unsubscribe on a real message, reconciles attribution to won revenue, and cancels the old tool with the saving written down.

30 min4 stepsSessions 5 and 6Ends with the module gate

By the end of this chapter you can

  • Import suppressions before anything that could send, and never import a contact without a consent source.
  • Rehearse the import on the development project with an approved copy, and reconcile every file's counts.
  • Compare a side-by-side week, prove deliverability and one-click unsubscribe, and reconcile attribution to revenue.
  • Import into production through the pipeline, cut over, and cancel with the saving from invoices.

The import order

OrderWhatRule
1Suppressions (unsubscribed, bounced, complained)Before anything else; normalised to lower case; duplicates collapse; never backed out
2Contacts with consentOnly with a status meaning granted, a source and a date; source written import::; text_version the form's if kept, otherwise legacy::
3TemplatesAs drafts, version 1, with the old tool's merge tags and tracked links replaced; the approver approves the ones in use
4ListsFixed lists as static segments; rule-based lists rebuilt by hand and compared
5Engagement historyOld campaigns as completed sends with their events at the original times; opens kept, never used for decisions
6Ad spendEach platform's daily export, uploaded by the marketing lead; a second upload changes nothing
Step 11

Session 5: Map the exports and build an import that runs dry first

45 minutes

Why

The order protects people: if the import stopped halfway, suppressions are already in, so nobody who said no can be mailed. Mapping consent statuses in a document someone reviews, and running dry before any write, means the real run holds no surprises. Running as the mkt_importer account means the database refuses a contact with no source.

Do this

Take every export yourself, today, from the old tool's own account: contacts with consent status, suppressions, lists, templates and engagement history. Write each file's date and row count. Keep the files in a private folder outside the repository. Give Claude Code only each file's heading line.

Paste into Claude Code, after filling the last lines
On a new branch marketing/import:
1. docs/mkt-consent-map.md: for each consent status the old tool uses (I list them below), the mkt_consent purpose and status, and where source, date and wording come from; the old suppression reasons mapped to unsubscribe, hard_bounce, complaint, manual or legal (unknown becomes manual, original text in ext).
2. scripts/import-marketing.mjs, signed in as mkt_importer (insert only), reading files from the private Supabase Storage bucket imports, in the order: suppressions, contacts with consent, templates as drafts, lists, history. Each batch one transaction tagged ext.import_batch. A contact without a granted status, a source and a date is held: counted, never written. Match existing crm_contact on lower-case address. --dry-run writes nothing and prints, per file: rows, imported, held (by reason), duplicates. A second run adds nothing.
3. .github/workflows/import-marketing.yml, run by hand from main with inputs target (dev or production) and dry_run; before writing it checks each file's sha256 and expected row count against docs/imports/marketing-approved.md on main and refuses on any difference; it fails if imported plus held plus duplicates differs from a file's rows; counts go to the job summary.
4. /api/marketing/spend-upload for the marketing lead: a platform's daily spend file, upserted on ad account, external campaign and date, setting mkt_campaign.actual_spend.
5. Tests on made-up rows: a file whose sha256 or row count is not approved is refused; a contact with no source is held; suppressions load before contacts; a second run adds nothing; spend uploaded twice gives Seed search 60000 and Seed social 60000 with the same row count; the importer cannot approve a template.
Push, open a pull request titled "Marketing: import", wait for every check, and report. Do not connect to any project.

The old tool's consent statuses: <list them>
The heading line of each export:
<paste only the first line of each file, never a data row>

You will see recreated screen

claude — acme-platform
⏺ Write(docs/mkt-consent-map.md)
+| Old status | mkt_consent | source | text_version |
+| subscribed | marketing_email granted | import:oldtool:<signup source> | legacy:oldtool:2026-11-10 |
+| cleaned | suppression hard_bounce | | |
+| transactional | held: no marketing consent | | |
1
⏺ Bash(npm test -- marketing.import)
⎿ no-source contact: held, 0 rows written order: 412 suppressions before first contact second run: 0 added spend twice: 60000 / 60000, rows unchanged
⏺ Pull request #80 is green. The workflow refuses any file whose sha256 and row count are not in docs/imports/marketing-approved.md on main.
Headings in, a mapping and an import out. No contact ever reaches Claude Code.
  1. Every old status has a written fate. 'Transactional' is not marketing consent, so those contacts are held.

Check it worked

Pull request Marketing: import is green, and docs/mkt-consent-map.md gives every old status a fate that the tool's owner has read.

If it goes wrong

Claude Code asks for real rows to test with

Give it made-up rows with the same headings, at example.com. Real contacts go only through the workflow.

The script sets do_not_contact false for imported contacts "to be safe"

That is not safe, it is a choice. Say: Keep do_not_contact exactly as the export gives it; held contacts are not written at all.

Imported templates still contain the old tool's tracked links

They stop working when the subscription ends. Say: Replace every link that goes through the old tool's click-tracking address with the original destination, and list each change.

Step 12

Session 5: Rehearse on the development project with an approved copy

40 minutes

Why

The rehearsal finds the surprises (a status nobody mapped, a list rule that cannot be rebuilt) where nothing depends on the result. Real contacts go into the development project only here, only with IT's written approval of that copy, never with the send route able to reach them, and they are removed the same day: the Foundation rule that real data stays out of development is broken once, on purpose, on the record.

Do this

Get IT's written approval to load a copy of the exports into acme-platform-dev for one rehearsal, removed the same day. Contacts are personal data, so the copy is redacted: names replaced and addresses rewritten at example.com, the same value for the same person, so duplicates and suppressions still match. Make sure the development project's environment has no ESP key, so nothing there can send. Create the mkt_importer account in the development project's Authentication and type its sign-in into the GitHub Actions secrets the workflow names.

Open

https://github.com/acme-ops/acme-platform/settings/secrets/actions

GitHub Actions secrets: the importer's sign-in for the development project.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets

Development project Storage: the private bucket imports; upload the redacted copy.

Terminal (Mac), in the export folder
shasum -a 256 *.csv
Paste into Claude Code, after pasting the values
Write docs/imports/marketing-approved.md on a new branch marketing/import-approval: each export file's name, sha256 and row count (I paste them below), the date taken, that the copy is redacted, and IT's approval for one rehearsal on acme-platform-dev, removed the same day (date and role). Open a pull request titled "Marketing: approve import files".

<paste the shasum lines and row counts>

Owner two approves; merge. Run the workflow from main with target dev, dry run first, then for real. The same day, remove the rehearsal rows (Claude Code gives you the statements by ext.import_batch; you run them in the development project's SQL editor) and the files in the bucket, and record the date in docs/mkt-import-report.md.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-marketing.yml

Run workflow: target dev, dry_run true, then false.

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/import-marketing.yml
import-marketing · target dev · dry_run false
2
FileRowsImportedHeldDuplicates
suppressions1,4941,48608
contacts7,9065,2122,694 (no source 2,281; suppressed 401; no address 12)0
templates3838 (drafts)00
The workflow's summary on the development project. Imported plus held plus duplicates equals the file, for every file.
  1. Only the files owner two approved can be imported.
  2. Every held contact has a reason. Held contacts are not in any table and cannot be mailed.

Check it worked

For every file, imported plus held plus duplicates equals the rows in the file; mkt_eligible_contacts over all imported contacts returns no suppressed address; three contacts (one imported, one suppressed, one held) match the old tool side by side; a second run adds nothing. The same day, the rehearsal rows are removed from the development project, the date is in docs/mkt-import-report.md, and IT is told in writing.

Fastest path

Fix every surprise in the mapping, not by hand in the database, and rehearse again. Session 6's production run should then be a formality.

If it goes wrong

The workflow refuses: sha256 not approved

A file changed since you recorded it (often opened and saved in a spreadsheet, which rewrites it). Upload the approved file again, or record the new value through a pull request.

A rebuilt list's count differs from the old tool's

Expected: the old count often includes people the new count rightly excludes. Write each difference and its reason in docs/mkt-import-report.md.

Held contacts appear in a segment

Stop. Held contacts must never be written. Say: Show me where held rows were written, remove them, and add a test that a held contact appears in no table.

One won job, four attribution modelsA won job worth 10,000 dollars with four touches: paid search, web form, email and phone call. First touch gives all of it to paid search, last touch to the phone call, linear 2,500 to each, and W-shaped 3,000, 3,000, 1,000 and 3,000. Every row totals 10,000. Paid search · firstWeb form · leadEmail · otherPhone call · opp.First touch$10,000Last touch$10,000Linear$2,500$2,500$2,500$2,500W-shaped$3,000$3,000$1,000$3,000Every row adds up to the $10,000 won. The model changes only who gets the credit.
The same won job, four ways. The total never changes; only who is credited does. Every model must add up to the won revenue, to the cent.
Step 13

Session 6: Side by side, the real import, and the proof

75 minutes over a week

Why

A week of old and new side by side, compared number by number, is what lets you switch the old tool off without a leap of faith. The real import goes into production through the workflow you rehearsed, with files owner two approved, so production is changed by the pipeline, never by a laptop. One-click unsubscribe is proved on a real message, and attribution is proved to add up to the money actually won.

Do this

Create the mkt_importer account on production and type its production sign-in into the workflow's secrets. Record the production exports' fingerprints and row counts in docs/imports/marketing-approved.md through a pull request owner two approves, upload them to the private bucket imports in production, and run the workflow from main with target production, dry run first.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-marketing.yml

Run workflow: target production, dry_run true, then false. Save the summary.

For the week, send one named list only from the new module and keep the old tool for everyone else, so nobody gets a message twice. Before each new send, load the old tool's latest suppression export the same way. Then send yourself a real message from the module and press your mail app's Unsubscribe.

Paste into Claude Code, after replacing the last line with your notes
On a new branch marketing/cutover, write docs/cutover-marketing.md from my notes below, with the queries I run on production shown beside each number:
1. The week's sends: the old tool's report (named) and the module's counts for recipients, delivered, hard and soft bounces, unsubscribes, complaints and unique clicks; every difference explained.
2. Deliverability: delivered ÷ sent and complaints ÷ delivered with their denominators, against the 0.3% limit and 0.1% target, beside the ESP's own report.
3. One-click unsubscribe on a real message: the time of the press and the suppression row, withdrawn consent and outbox event that followed.
4. Attribution for the period: the four model totals beside won revenue in crm_opportunity, to the cent; cost per lead, MQL and won job by channel with the model stated; mkt_ad_spend_daily beside each ad platform's own report.
5. The import summary from the production run.
Use only my numbers. Open a pull request titled "Marketing: cutover".

My notes:
<paste your notes here>

You will see recreated screen

github.com/acme-ops/acme-platform/blob/main/docs/cutover-marketing.md
1
Week of 2026-11-16Old toolModuleDifference
Recipients1,2121,18725: suppressed 19, withdrawn 4, no source 2
Complaints ÷ delivered0.17%0.08% (1 of 1,169)fewer people who never agreed
2
ModelCreditWon revenue
first touch$84,250.00$84,250.00
W-shaped$84,250.00$84,250.00
docs/cutover-marketing.md: old and new agree, or say why; every model adds up to the money won.
  1. The 25 the module would not mail each have a reason: proof the old tool was mailing people it should not have.
  2. Four models, one total. A model that does not add up is a bug, not an opinion.

Check it worked

Production holds the imported contacts with counts that match the files; the complaint rate is under 0.3% with its denominator; one-click unsubscribe on a real message produced a suppression row within seconds; all four attribution models reconcile to won revenue to the cent.

If it goes wrong

The complaint rate is over 0.3%

Stop and do not cut over. Look at who the sends went to (an imported list with a weak source is the usual cause), fix it, and run the week again.

A difference in the week has no explanation

You are not ready. Find the cause and compare again before cancelling anything.

Ad spend differs from the platform's report for the last two days

Platforms restate recent days and report in their own time zone. Compare closed days only, and write the time zone in the document.

Step 14

Session 6: Finish the DNS, cut over and cancel

30 minutes

Why

The old tool can keep sending from your domain until its last trace is removed: a forgotten form plugin or an old automation. DMARC reports show every sender using the domain. Cancelling only after the final suppression list is loaded means nobody who unsubscribed in the old tool's last days is lost.

Do this

Read a week of DMARC aggregate reports (sent to the rua address you set) for any sender you forgot. Remove the old tool from your SPF record only after its last send. Point every sign-up form at /api/marketing/signup (a setting if your site is built in module M17) and remove the old tool's tracking script.

Terminal or PowerShell
nslookup -type=TXT acme.com
Paste into Claude Code, after replacing the last line with your notes
Add to docs/cutover-marketing.md, on the same branch: the cutover date; who tells the team; the last send from the old tool; which old automations are paused (not deleted); who keeps the final export and where; what happens to an unsubscribe that reaches the old tool afterwards; the final suppression load (rows new since the first load, none eligible); and the saving: the old yearly bill from the invoice minus the ESP and domain costs from their invoices, as arithmetic, with ad spend and any text-message tool left out. Then update docs/marketing-inventory.md: each tool, list, template and automation replaced, retired or still running, with the date. Use only my numbers.

My notes:
<paste your notes here>

On the cutover day, load the old tool's final suppression export through the workflow, read its cancellation terms on your own account page (notice period, export window, how long its sent unsubscribe links keep working), and cancel. Then close the importer the same day:

Paste into Claude Code
The final suppression load is done. On a new branch marketing/close-importer: remove mkt_importer's rights from docs/matrix.json and regenerate with scripts/gen-policies.mjs and scripts/gen-routes.mjs; add a migration that sets the mkt_importer role to NOLOGIN, applied by the deploy workflow; disable import-marketing.yml; add a test that the importer can neither sign in nor insert; mark its secrets retired in docs/KEYS.md and tell me which GitHub secrets to delete. Open a pull request titled "Marketing: close the importer", wait for every check, and report.

You will see recreated screen

Terminal
$ nslookup -type=TXT acme.com
acme.com text = "v=spf1 include:_spf.google.com ~all"1
The SPF record after the old tool's last send: only the ESP remains for the sending subdomain, and the main domain no longer includes the old tool.
  1. The old tool's include is gone. Remove it only after its last send, or its final messages fail SPF.

Check it worked

docs/cutover-marketing.md is on main with the cutover date, rollback plan, final suppression load and the saving from invoices; docs/marketing-inventory.md marks every item; the old tool is cancelled or its end date written; the importer is NOLOGIN and its secrets deleted.

If it goes wrong

DMARC reports show a sender you do not recognise

Find it before tightening anything: usually a website form plugin or a second tool. Point it at the module, or add it to SPF knowingly.

Someone asks to keep the old tool "just for texts"

This module builds no text sending. Keep that tool, leave its bill out of the saving, and say so in the inventory.

Before you go on · The module is done whenTick each one

Knowledge check

What is loaded first in the import, and why?

Knowledge check

The export gives a contact as subscribed but with no source. What does the import do?

References

  1. IETF RFC 7489: DMARC (aggregate reports). https://www.rfc-editor.org/rfc/rfc7489
  2. FTC: CAN-SPAM Act, a compliance guide for business. https://www.ftc.gov/business-guidance/resources/can-spam-act-compliance-guide-business
  3. Improvado: B2B marketing automation platforms (scoring, attribution). https://improvado.io/blog/marketing-automation-tools
  4. GitHub Docs: Manually running a workflow. https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/manually-running-a-workflow

Chapter 4 · 12 questions · 80% passes

Final assessment

Twelve questions across the module. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.

15 min12 questions≈ 15 minutesRetake allowed

Choose one answer for each question, then submit. You will see the right answer and why for every question.

1. What must be true of an address before it is included in a send?
2. Why does mkt_suppression hold one row per email address, with the address unique?
3. A contact withdraws consent for marketing email. What happens in mkt_consent?
4. Why does the module send through an ESP API instead of running its own mail server?
5. A reader presses the Unsubscribe button their mail app shows next to the sender. What does RFC 8058 describe?
6. What does a DMARC check ask?
7. A send is delivered to 5,000 contacts and draws 10 complaints. Where does the complaint rate stand?
8. Why should opens not be the success metric for a campaign?
9. How does the webhook route avoid counting a retried ESP event twice?
10. In a journey, how does a contact wait two days before the next step?
11. A lead's engagement points carry decay_days of 14 and its fit points have none. What happens to a lead who goes quiet?
12. What must be true of the credit under each attribution model for one won job?