From f034ecd8794e88e010f90e6faaa6c617ded707eb Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 06:26:41 +0000 Subject: [PATCH 001/260] fix(skills): ship a variant's own reference folder in its bundle The migrate group keeps Statsig's mapping and SDK reference under references/statsig/, and its step files point there, but the generator copied only the top-level reference files. Copy references// into each variant's bundle, and nothing of the other variants. Co-Authored-By: Claude Opus 5.5 --- scripts/lib/skill-generator.js | 32 +++++++++++++ .../skill-generator-references-folder.test.js | 47 +++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/scripts/lib/skill-generator.js b/scripts/lib/skill-generator.js index 454142acd..9af3e0455 100644 --- a/scripts/lib/skill-generator.js +++ b/scripts/lib/skill-generator.js @@ -594,6 +594,31 @@ function generateFrontmatter(skill, version) { return '---\n' + yaml.dump(frontmatter) + '---\n\n'; } +/** + * Copy the markdown files of a variant's own folder, `references//`, + * into the bundle. A group keeps what differs per vendor or platform there, so + * each bundle ships only its own variant's files. Returns their listing entries. + */ +function copyVariantReferences({ sourceDir, targetDir, variantId, configDir }) { + if (!fs.existsSync(sourceDir)) return []; + + const files = fs.readdirSync(sourceDir, { withFileTypes: true }) + .filter(entry => entry.isFile() && entry.name.endsWith('.md')) + .sort((a, b) => a.name.localeCompare(b.name)); + fs.mkdirSync(targetDir, { recursive: true }); + + return files.map(file => { + const parsed = matter(fs.readFileSync(path.join(sourceDir, file.name), 'utf8')); + const body = expandPartials(parsed.content, configDir).replace(/^\n+/, '').replace(/\s+$/, ''); + fs.writeFileSync(path.join(targetDir, file.name), body, 'utf8'); + const heading = body.match(/^#\s+(.+)$/m)?.[1]; + return { + filename: `${variantId}/${file.name}`, + description: parsed.data.description || heading || file.name, + }; + }); +} + /** * Generate a complete skill package * @@ -717,6 +742,13 @@ async function generateSkill({ }); } } + + references.push(...copyVariantReferences({ + sourceDir: path.join(sourceReferencesDir, skill._shortId), + targetDir: path.join(referencesDir, skill._shortId), + variantId: skill._shortId, + configDir, + })); } // Helper to process a doc entry (string URL or {url, title} object). diff --git a/scripts/lib/tests/skill-generator-references-folder.test.js b/scripts/lib/tests/skill-generator-references-folder.test.js index d5108e5f8..925f520be 100644 --- a/scripts/lib/tests/skill-generator-references-folder.test.js +++ b/scripts/lib/tests/skill-generator-references-folder.test.js @@ -69,4 +69,51 @@ describe('generateSkill local references', () => { expect(readFileSync(generatedRef, 'utf8')).toBe('# Product analytics best practices\n\nDetails'); expect(readFileSync(generatedSkill, 'utf8')).toContain('references/product-analytics.md'); }); + + it("ships a variant's own reference folder and no other variant's", async () => { + createFixture({ + skills: { + migrate: { + 'description.md': '# Migrate\n\n{references}\n', + references: { + '1-presence.md': '---\nnext_step: null\n---\n\n# Presence\n\nRead `references//mapping.md`.', + statsig: { 'mapping.md': '# Statsig mapping' }, + amplitude: { 'mapping.md': '# Amplitude mapping' }, + }, + }, + }, + }, tmpDir); + + const config = { + migrate: { + type: 'skill', + template: 'description.md', + variants: [ + { id: 'statsig', display_name: 'Statsig' }, + { id: 'amplitude', display_name: 'Amplitude' }, + ], + }, + }; + + const statsig = expandSkillGroups(config, tmpDir).find((skill) => skill.id === 'migrate-statsig'); + const outputDir = join(tmpDir, 'out'); + + await generateSkill({ + skill: statsig, + version: 'test', + repoRoot: tmpDir, + configDir: tmpDir, + outputDir, + skipPatterns: { global: [], examples: {} }, + commandmentsConfig: { commandments: {} }, + skillTemplate: statsig._template, + sharedDocs: [], + }); + + const references = join(outputDir, 'migrate-statsig', 'references'); + expect(readFileSync(join(references, 'statsig', 'mapping.md'), 'utf8')).toBe('# Statsig mapping'); + expect(existsSync(join(references, 'amplitude'))).toBe(false); + expect(readFileSync(join(outputDir, 'migrate-statsig', 'SKILL.md'), 'utf8')) + .toContain('`references/statsig/mapping.md`'); + }); }); From 177e7414815c7dcb830e128647371eadad887d38 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 06:40:11 +0000 Subject: [PATCH 002/260] refactor(skills): share the email sender setup as a partial Move the sender setup of send-transactional-email's STEP 3 into context/shared/email-sender-setup.md, so the email migration skill includes the same text. A partial now takes the indentation of its {{> name}} line on every line, so it nests under a step. The built send skill is unchanged byte for byte. Co-Authored-By: Claude Opus 5.5 --- context/shared/email-sender-setup.md | 15 +++++++++++++++ scripts/lib/skill-generator.js | 10 ++++++---- scripts/lib/tests/partial-includes.test.js | 8 ++++++++ 3 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 context/shared/email-sender-setup.md diff --git a/context/shared/email-sender-setup.md b/context/shared/email-sender-setup.md new file mode 100644 index 000000000..bdf95e3c5 --- /dev/null +++ b/context/shared/email-sender-setup.md @@ -0,0 +1,15 @@ +--- +title: Set up an email sender +--- + +- First check that the PostHog MCP has the sender tools: `integrations-email-create`, `integrations-email-verify-create`, `integrations-domain-connect-check-retrieve`, and `integrations-domain-connect-apply-url-create`. When they are missing, go to the last bullet of this step. +- When the `setting-up-an-email-domain` skill is available, follow it. It covers the details. +- Ask which domain to send from. Recommend a subdomain such as `mail.example.com`. Use the person's own domain, never a free mailbox domain such as gmail.com. +- Never create a sender for an address that already has one: creating it again marks it unverified. For an existing unverified sender, skip to its records. +- Create the sender with `integrations-email-create`, then get its DNS records with `integrations-email-verify-create`. +- PostHog never writes DNS. Call `integrations-domain-connect-check-retrieve` with the domain. When `supported` is true, give the person the URL from `integrations-domain-connect-apply-url-create`: they approve the records at their DNS host. Otherwise, give them the records that are not `success` as a table with type, name, value, and priority. +- Always include both SPF records, merged into an existing `v=spf1` record when there is one. Never add a second `_dmarc` record when the domain already has one. +- Call `integrations-email-verify-create` again after the records are published, at least a minute apart. `success` means done. `failed` means fix the records, then verify again. After about 15 minutes of `pending` with every record published, stop and tell the person that DNS is still propagating and they can ask you to check again later. +- A 403 that says the person lacks permissions in the project means a project admin must verify the sender. Do not retry. +- **When the sender tools are missing or refused**, the agent setup for sender domains is not available to this person yet. Do not try other integration tools. Ask the person to verify a sender in PostHog: Workflows, then Channels, then add an email sender on their domain and follow the DNS steps (https://posthog.com/docs/workflows/configure-channels). Wait until they confirm that the sender shows as verified, then continue. + diff --git a/scripts/lib/skill-generator.js b/scripts/lib/skill-generator.js index 9af3e0455..35eb4697e 100644 --- a/scripts/lib/skill-generator.js +++ b/scripts/lib/skill-generator.js @@ -55,16 +55,18 @@ function loadYaml(configPath) { // A line that is exactly `{{> name}}` is replaced at build time with the body // of `/shared/name.md` (frontmatter stripped), so shared prose like // the MCP tool-calling grammar lives in one canonical file and every skill that -// includes it stays in sync. -const PARTIAL_DIRECTIVE = /^[ \t]*\{\{>\s*([a-z0-9-]+)\s*\}\}[ \t]*$/gm; +// includes it stays in sync. The directive's indentation applies to every line +// of the partial, so a partial can nest under a step. +const PARTIAL_DIRECTIVE = /^([ \t]*)\{\{>\s*([a-z0-9-]+)\s*\}\}[ \t]*$/gm; function expandPartials(body, configDir) { - return body.replace(PARTIAL_DIRECTIVE, (_match, name) => { + return body.replace(PARTIAL_DIRECTIVE, (_match, indent, name) => { const partialPath = path.join(configDir, 'shared', `${name}.md`); if (!fs.existsSync(partialPath)) { throw new Error(`Partial include {{> ${name}}} references missing file ${partialPath}`); } - return matter(fs.readFileSync(partialPath, 'utf8')).content.trim(); + const partial = matter(fs.readFileSync(partialPath, 'utf8')).content.trim(); + return partial.replace(/^(?=.)/gm, indent); }); } diff --git a/scripts/lib/tests/partial-includes.test.js b/scripts/lib/tests/partial-includes.test.js index 5ebaa8e66..3741c14a3 100644 --- a/scripts/lib/tests/partial-includes.test.js +++ b/scripts/lib/tests/partial-includes.test.js @@ -42,6 +42,14 @@ describe('expandPartials', () => { expect(out).toContain('After.'); }); + it("indents every line of the partial as far as the directive, so it nests in a step's list", () => { + writeFileSync(join(tmpDir, 'shared', 'sender.md'), '---\ntitle: Sender\n---\n\n- First bullet.\n- Second bullet.\n'); + + const out = expandPartials('STEP 3: Set up a sender.\n {{> sender}}\n\nSTEP 4: Send.', tmpDir); + + expect(out).toBe('STEP 3: Set up a sender.\n - First bullet.\n - Second bullet.\n\nSTEP 4: Send.'); + }); + it('throws when the referenced partial does not exist', () => { expect(() => expandPartials('{{> missing-partial}}', tmpDir)).toThrow(/missing-partial/); }); From 8169d7ec86ab68871010032ea15222f77611d0e6 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 06:40:11 +0000 Subject: [PATCH 003/260] feat(skills): add the migrate-email skill with a Resend variant v0 prepares a move off Resend and changes no send call site. It finds every Resend send, classifies each one as ready to move or staying on Resend with a reason, sets up the PostHog sender next to Resend's DNS records, imports Resend's suppression list when the import tool exists, hands over the project secret key, checks the sending tier, and writes posthog-migrate-email-resend-report.md with a summary block. Steps are provider-neutral; references/resend/ holds what is specific to Resend. Statsig and Resend now publish as wizard migrate subcommands. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 10 +- context/skills/migrate-email/config.yaml | 17 ++++ context/skills/migrate-email/description.md | 55 +++++++++++ .../migrate-email/references/1-detect.md | 38 ++++++++ .../migrate-email/references/2-preflight.md | 41 ++++++++ .../migrate-email/references/3-inventory.md | 61 ++++++++++++ .../migrate-email/references/4-sender.md | 38 ++++++++ .../references/5-suppressions.md | 39 ++++++++ .../skills/migrate-email/references/6-key.md | 32 +++++++ .../migrate-email/references/7-report.md | 76 +++++++++++++++ .../references/resend/account.md | 42 ++++++++ .../references/resend/mapping.md | 46 +++++++++ .../references/resend/sdk-reference.md | 90 +++++++++++++++++ context/skills/migrate/config.yaml | 2 +- scripts/lib/tests/migrate-email-skill.test.js | 96 +++++++++++++++++++ 15 files changed, 681 insertions(+), 2 deletions(-) create mode 100644 context/skills/migrate-email/config.yaml create mode 100644 context/skills/migrate-email/description.md create mode 100644 context/skills/migrate-email/references/1-detect.md create mode 100644 context/skills/migrate-email/references/2-preflight.md create mode 100644 context/skills/migrate-email/references/3-inventory.md create mode 100644 context/skills/migrate-email/references/4-sender.md create mode 100644 context/skills/migrate-email/references/5-suppressions.md create mode 100644 context/skills/migrate-email/references/6-key.md create mode 100644 context/skills/migrate-email/references/7-report.md create mode 100644 context/skills/migrate-email/references/resend/account.md create mode 100644 context/skills/migrate-email/references/resend/mapping.md create mode 100644 context/skills/migrate-email/references/resend/sdk-reference.md create mode 100644 scripts/lib/tests/migrate-email-skill.test.js diff --git a/AGENTS.md b/AGENTS.md index 9bbb4e2c6..2d5c0779e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,11 +72,12 @@ longer exist — only some keep an alias. | `wizard integrate` | `wizard` (default flow) | command removed | | `wizard events-audit` | `wizard audit events` | moved into `audit` family | | `wizard audit` (single) | `wizard audit ` | now a family — see audit subcommands below | +| `wizard migrate` (single) | `wizard migrate ` | becomes a family with the wizard's family command — see migrate subcommands below | | `wizard audit-3000` | *removed* | retired | | `wizard revenue` | `wizard revenue-analytics` | renamed (old `revenue` removed) | | `wizard upload-sourcemaps` | `wizard upload-source-maps` | renamed; `upload-sourcemaps` kept as alias | -**Audit subcommands** — the one family today backed by skills from this repo: +**Audit subcommands**, backed by skills from this repo: | Subcommand | Backing skill | |---|---| @@ -88,6 +89,13 @@ longer exist — only some keep an alias. | `wizard audit session-replay` | `audit-session-replay` | | `wizard audit web-analytics` | *(wizard-native, not a skill here)* | +**Migrate subcommands**, published as `cliEntries` with `parentCommand: migrate`. Until the wizard runs `migrate` as a family, bare `wizard migrate` keeps running `migrate-statsig`: + +| Subcommand | Backing skill | +|---|---| +| `wizard migrate statsig` | `migrate-statsig` | +| `wizard migrate resend` | `migrate-email-resend` | + **Commands vs. skills:** those audit subcommands **are** skills, promoted to commands via `cli: role: command`. A `role: skill` skill is reachable only via `wizard skill `. Same machinery, two surfaces — so `wizard audit ` diff --git a/context/skills/migrate-email/config.yaml b/context/skills/migrate-email/config.yaml new file mode 100644 index 000000000..6b0b83c37 --- /dev/null +++ b/context/skills/migrate-email/config.yaml @@ -0,0 +1,17 @@ +# Email migration skill group - move transactional email from another provider to PostHog, one variant per provider +type: skill +template: description.md +category: migrate +description: Migrate transactional email from {display_name} to PostHog. Use when asked to migrate from {display_name}, replace {display_name} with PostHog, or switch email providers. It finds every {display_name} send in the code, sets up the sender and DNS next to {display_name}'s records, imports {display_name}'s suppression list, hands over the PostHog secret key, and writes a migration report. It changes no send call site yet. +tags: [migration, workflows] +cli: + role: command + parentCommand: migrate +references: + preamble: "**Read ONLY this file.** Do not read any other reference file until this one tells you to." +shared_docs: + - https://posthog.com/docs/workflows/transactional-email-api.md +variants: + - id: resend + display_name: Resend + tags: [resend] diff --git a/context/skills/migrate-email/description.md b/context/skills/migrate-email/description.md new file mode 100644 index 000000000..174a82b6a --- /dev/null +++ b/context/skills/migrate-email/description.md @@ -0,0 +1,55 @@ +# Migrate transactional email from {display_name} to PostHog + +Use this skill to move an app's transactional email, such as welcome emails, password resets, and receipts, from {display_name} to PostHog. + +This version prepares the move and changes no send call site. It finds every {display_name} send, sets up the PostHog sender and its DNS records next to {display_name}'s, imports {display_name}'s suppression list, hands over the PostHog secret key, and writes a report. Both providers can send during the cutover. + +The transactional email API is in beta. PostHog enables it per project. + +## Workflow + +{workflow} + +Read the step files in order, one at a time. Each step names the next one. Do not read a step before the one before it tells you to. + +## Provider files + +The folder `references//` holds everything specific to {display_name}. The steps tell you when to read each file: + +- `sdk-reference.md`: how {display_name} looks in code, so you can find every send. +- `mapping.md`: how each send field maps to PostHog, and what keeps a call site on {display_name}. +- `account.md`: {display_name}'s DNS records and how to export its suppression list. + +Everything you need is on disk. Do not fetch {display_name}'s docs. + +## Plan file + +The plan file `.posthog-email-migration-plan.md` lives at the project root. Step 3 writes it, the later steps update it, and the last step writes the report from it and deletes it. + +## Rules + +- Change no send call site. This version only prepares the move. +- Never touch DNS or the {display_name} account. Give the person the records and the links, and let them make the change. +- Never remove the {display_name} package, its client, or its API key. +- Never create, upload, or edit a template in PostHog. +- Never write a recipient's email address into a file in the repository, the plan, or the report. Count addresses instead. +- Keep keys in environment variables. Never hardcode a key, and never ask the person to paste one into the chat. +- Do not commit. The person reviews the diff and commits. + +## Inside the PostHog Wizard + +Read this section only when the Wizard's `wizard_ask` tool exists. Some runtimes name its tools `mcp__wizard-tools__wizard_ask` and `mcp__wizard-tools__set_env_values`: use the names the runtime shows. The Wizard has no chat, so the person answers through its tools. + +- The PostHog tools of this skill run through `posthog_exec`. Check that a tool exists with `search `. +- The Wizard's login may not carry the scopes of the `workflows-*` and `integrations-*` tools, so a missing tool does not mean the API is off. Step 2 says how to tell. +- Ask every question with `wizard_ask`, never in plain text. Batch the questions of one step into one call. +- Emit the `[STATUS]` line each step names when you start it, and the `[ABORT]` line a step names when it stops the run. +- Ask for a key with `wizard_ask` and `sensitive: true`, then pass the answer to `set_env_values` with the variable name the step gives. The answer is a reference that only `set_env_values` can read, so the key never shows in the run. + +Outside the Wizard, skip the `[STATUS]` lines, and tell the person why you stopped instead of an `[ABORT]` line. + +## Reference files + +{references} + +`transactional-email-api.md` is the transactional email API page. It covers senders, the send forms, `posthog-node`, idempotency, and every error code. diff --git a/context/skills/migrate-email/references/1-detect.md b/context/skills/migrate-email/references/1-detect.md new file mode 100644 index 000000000..94881bc9c --- /dev/null +++ b/context/skills/migrate-email/references/1-detect.md @@ -0,0 +1,38 @@ +--- +title: Find the email provider in the code +next_step: 2-preflight.md +--- + +# Step 1, find the email provider in the code + +Discovery only. Do not change any file. + +## Status + +``` +[STATUS] Looking for the email provider +``` + +## Procedure + +Read the provider's `sdk-reference.md`. It lists the provider's packages, imports, clients, and HTTP host, and the packages that look related but are not the provider. + +The provider is in this project when at least one of these is true: + +- Its package is in a dependency manifest, such as `package.json`, `requirements.txt`, `pyproject.toml`, `Gemfile`, `composer.json`, or `go.mod`. +- Source code imports it or creates its client. +- Source code calls its HTTP host. + +Search the source code, not only the manifest: a package without a call site is not a migration. Skip `node_modules`, build output, and lockfiles. + +A rendering package alone, such as `@react-email/components`, is not the provider. It only tells you how some emails are rendered. + +When you find nothing, stop before any change: + +``` +[ABORT] no email provider sends found +``` + +Do not widen the search to other email providers. That outcome is correct, not a failure to work around. + +When you find the provider, note each file that uses it for Step 3, and continue. diff --git a/context/skills/migrate-email/references/2-preflight.md b/context/skills/migrate-email/references/2-preflight.md new file mode 100644 index 000000000..ffd88264d --- /dev/null +++ b/context/skills/migrate-email/references/2-preflight.md @@ -0,0 +1,41 @@ +--- +title: Check that the project can send +next_step: 3-inventory.md +--- + +# Step 2, check that the project can send + +Do not change any file. + +## Status + +``` +[STATUS] Checking the PostHog project +``` + +## The transactional email API + +Check which PostHog MCP tools exist. + +- When there are no PostHog tools at all, the PostHog MCP is not connected or not signed in. Ask the person to connect it, and wait. +- When other PostHog tools exist but `workflows-upload-email-template` and `workflows-send-email` don't, the transactional email API is not enabled for this project. Stop and tell the person: the API is in beta, and they can ask PostHog in-app to enable it for their project. Then emit: + +``` +[ABORT] transactional email api not enabled +``` + +- When both tools exist, the API is on. Record `api: on`. + +Inside the Wizard, a missing tool can mean that the login lacks its scope, so missing tools do not stop the run. Record `api: not confirmed` and continue. The report asks the person to confirm it. + +## The sending tier + +PostHog gives each project a sending allowance: how many emails it sends per hour and per day. A new project starts on a low tier, and the tier grows with low bounce and complaint rates. Emails above the allowance are not dropped, they are sent later. So a cutover with more mail than the tier allows delays email, such as password resets. + +- Ask the person how many emails the app sends in its busiest hour and on its busiest day. +- Ask them to compare these numbers with the "Sending allowance" in PostHog: Workflows, then Messaging, then Reputation. +- Record the answer as `tier: fits`, `tier: too low`, or `tier: not checked` when they don't know. Do not stop on `too low`: the report tells the person to move the sends in parts, or to ask PostHog about a higher tier, before cutover. + +## Write down + +Keep `api` and `tier` for Step 3, which writes them into the plan file. diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md new file mode 100644 index 000000000..1755818f0 --- /dev/null +++ b/context/skills/migrate-email/references/3-inventory.md @@ -0,0 +1,61 @@ +--- +title: List and classify every send +next_step: 4-sender.md +--- + +# Step 3, list and classify every send + +List every place the code sends email through the provider, and decide for each one whether PostHog can send it. Change no source file. The only file you write is the plan file. + +## Status + +``` +[STATUS] Listing every send +[STATUS] Writing the migration plan +``` + +## Find the sends + +Read the provider's `sdk-reference.md` for the call shapes, and its `mapping.md` for the fields. + +A **site** is one place in the code that calls the provider to send, such as one `emails.send(...)` call or one HTTP request to the send endpoint. A helper that wraps the call is one site, however many places call the helper. Read the callers of a helper anyway: they decide values such as how many recipients a send has. + +For each site, read the surrounding code and record: + +- The file and the line of the call. +- How it sends: `sdk`, `http`, or `smtp`. +- The content: `template` for a template stored at the provider, `react` for a component the provider renders, `html`, or `text`. A site that sets both `html` and `text` is `html`. +- Every field the site sets, including fields set on the payload object after it is created and fields set through options, such as an idempotency key. +- Where `from` comes from: the literal address, or the name of the environment variable or config value that holds it. + +Also list every other call to the provider that is not a send, such as reading an email's status, contacts, or domains. These calls stay on the provider. Note what each one does, because a site whose code reads the status back stays on the provider too. + +## Classify each site + +Go through `mapping.md` field by field. A site **moves** when PostHog can send every field it sets. A site **stays** on the provider when any one field or feature keeps it there: record that field or feature as the reason. Never plan to drop a field. + +When the code passes a value you can't read, such as a list of recipients built at run time, follow it to its callers. When you still can't tell, the site stays, and the reason says what you could not check. + +## Write the plan file + +Write `.posthog-email-migration-plan.md` at the project root with three sections. Never write an email address of a recipient into it. A `from` address is fine. + +A phase checklist, in this order. Tick `preflight` with what Step 2 recorded, and `inventory` once the file is written. Later steps tick the rest. + +``` +- [x] preflight — api: — tier: +- [x] inventory — sites, stay on the provider +- [ ] sender +- [ ] suppressions +- [ ] key +``` + +A sites table, one row per site, in source tree order: + +``` +| site | file | line | sends | content | from | moves | reason | +``` + +`moves` is `yes` or `no`. `reason` is empty when the site moves. + +A list of the other provider calls, each with its file, line, and what it does. diff --git a/context/skills/migrate-email/references/4-sender.md b/context/skills/migrate-email/references/4-sender.md new file mode 100644 index 000000000..87a968c06 --- /dev/null +++ b/context/skills/migrate-email/references/4-sender.md @@ -0,0 +1,38 @@ +--- +title: Set up the senders and their DNS records +next_step: 5-suppressions.md +--- + +# Step 4, set up the senders and their DNS records + +PostHog sends from a verified sender: an address on a domain whose DNS records PostHog checked. Set up a sender for each domain the app sends from, next to the provider's records, so both providers can send during the cutover. Never change DNS yourself, and never change the provider account. + +## Status + +``` +[STATUS] Setting up the PostHog sender +``` + +## List the addresses + +Collect every `from` in the plan's sites table. When a `from` comes from an environment variable or a config value, read it from the example env file or the config, or ask the person for the address. A `from` can carry a name, such as `Example `: the sender is the address in it. + +Group the addresses by domain. Each domain needs one verified sender. + +## Check for verified senders + +Call `integrations-list` with `kind=email`, and read every page. A sender with `config.verified: true` can send. When the list shows senders without `config`, call `integrations-email-verify-create` once on the sender for the address: `success` means it is verified, and `pending` or `failed` means you continue from its records below. When the sender tools are missing, or the verify answers 403, ask the person whether a sender is verified for each domain. + +The first sender that verifies becomes the project's default sender. A send without `from` uses it. + +## Set up each domain without a verified sender + +Read the provider's `account.md` first. It lists the records the provider keeps on the domain and the label PostHog must not take. Keep every one of the provider's records: removing one stops the provider's sends before the cutover is done. + +Send from the domain of the existing `from` address, so the emails keep their sender. Ask for another domain only when the person wants one. + +{{> email-sender-setup}} + +## Write down + +Tick the `sender` phase in the plan file: `- [x] sender — / verified — dns_ready: `. `dns_ready` is `true` only when every domain has a verified sender. List each domain that is not verified, with what the person still has to do. diff --git a/context/skills/migrate-email/references/5-suppressions.md b/context/skills/migrate-email/references/5-suppressions.md new file mode 100644 index 000000000..02471b58b --- /dev/null +++ b/context/skills/migrate-email/references/5-suppressions.md @@ -0,0 +1,39 @@ +--- +title: Import the suppression list +next_step: 6-key.md +--- + +# Step 5, import the suppression list + +The provider keeps a suppression list: addresses that hard-bounced or marked an email as spam. It skips them on every send. PostHog keeps its own list and starts empty, so without an import the first PostHog sends go to these addresses again. That hurts the sending reputation of the project and the domain. Import the list before cutover. + +## Status + +``` +[STATUS] Importing the suppression list +``` + +## Check the import tool + +Look for the PostHog MCP tool `email-suppressions-add`, and read its schema with `info`. + +When it is missing, the import is not available to this person yet. Do not try other tools, and do not use the opt-out tools: opt-outs are marketing preferences, and transactional email ignores them. Tick the phase as `- [ ] suppressions — not imported: no import tool`, and continue to the next step. The report tells the person to add the addresses in PostHog (Workflows, then Messaging, then Suppression list) before cutover. + +## Get the list + +Read the provider's `account.md`. It says how to export the list, which entries to take, and how each entry maps to PostHog. + +- Prefer the export the person downloads from the provider's dashboard. Ask them where they saved the file. +- Read the list from the provider's API only when the person gives you a key that can read it, through an environment variable that `account.md` names. The app's own sending key usually can't. +- Keep the list out of the repository. Read the file where the person saved it, or write the API's answer to a file in the system's temporary folder, and delete that file when the import is done. + +## Import it + +- Send the entries to `email-suppressions-add` in batches of the size its schema allows. Give each entry the source and the reason `account.md` names. +- Repeating an import is safe: an address already on the list stays on it. +- Never print the addresses, and never write them into the plan or the report. Count them. +- When a call fails, read its error and fix the call. When it fails again, stop the import and record how many entries you imported. + +## Write down + +Tick the phase in the plan file: `- [x] suppressions — / imported`. When the list is empty, write `- [x] suppressions — empty list`. When the person has no export and no key, write `- [ ] suppressions — not imported: `. diff --git a/context/skills/migrate-email/references/6-key.md b/context/skills/migrate-email/references/6-key.md new file mode 100644 index 000000000..0b4a08208 --- /dev/null +++ b/context/skills/migrate-email/references/6-key.md @@ -0,0 +1,32 @@ +--- +title: Hand over the PostHog secret key +next_step: 7-report.md +--- + +# Step 6, hand over the PostHog secret key + +PostHog's send needs a project secret API key on the server. The provider's key stays where it is until the cutover is done. + +## Status + +``` +[STATUS] Setting up the PostHog secret key +``` + +## The PostHog key + +- Ask the person to create a project secret API key (it starts with `phs_`) with the `hog_flow:write` scope in their PostHog project settings. +- The key goes into `POSTHOG_PROJECT_SECRET_API_KEY`, in the env file the app loads its provider key from, such as `.env` or `.env.local`. Check that git ignores that file. When it doesn't, ask the person where the key goes. +- Ask the person to add the key to that file themselves. Inside the Wizard, ask for it and store it as the "Inside the PostHog Wizard" section of `SKILL.md` says. +- Add the variable name, without a value, to the project's env example file when it has one. +- Never hardcode the key, never commit it, and never ask the person to paste it into the chat. + +## Every other place the provider key lives + +The provider's `sdk-reference.md` names its key's environment variable. Search the whole repository for that name, including CI workflows, deploy and hosting config, Docker and compose files, env example files, and docs. Skip `node_modules` and build output. + +List each place with its file and line. Each one needs `POSTHOG_PROJECT_SECRET_API_KEY` too before the cutover, for example as a CI secret or a hosting environment variable. Do not change these files: the person adds the secret where the platform stores it. + +## Write down + +Tick the phase in the plan file: `- [x] key — POSTHOG_PROJECT_SECRET_API_KEY set in `, or `- [ ] key — not set: `. Under the phase list, add the places of the provider key. diff --git a/context/skills/migrate-email/references/7-report.md b/context/skills/migrate-email/references/7-report.md new file mode 100644 index 000000000..0dfb9a330 --- /dev/null +++ b/context/skills/migrate-email/references/7-report.md @@ -0,0 +1,76 @@ +--- +title: Write the migration report +next_step: null +--- + +# Step 7, write the migration report + +The report comes from the plan file. Invent nothing. + +## Status + +``` +[STATUS] Writing the migration report +``` + +## Write the report + +Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email--report.md` at the project root, where `` is the name of the provider folder under `references/`. Use the structure below, then delete the plan file. Never write a recipient's email address into the report. + +```markdown +# Email migration report: to PostHog + + + +## Send call sites + +| File | Line | Content | Status | +|------|------|---------|--------| + +: ".> + +## Other calls + +.> + +## Sender and DNS + + + +## Suppression list + + + +## PostHog secret key + + + +## Sending tier + + + +## Before cutover + + + +## Summary +``` + +End the report with the summary block, as the last thing in the file. The Wizard reads it, so keep the keys and their order: + +```yaml +from: +sites_found: +sites_rewritten: +sites_left: +dns_ready: +suppressions_ready: +``` + +This version changes no site, so `sites_rewritten` is `0`. Sites that are ready to move count in `sites_found` only. + +After the report is written, print its path: + +``` +Created migration report: +``` diff --git a/context/skills/migrate-email/references/resend/account.md b/context/skills/migrate-email/references/resend/account.md new file mode 100644 index 000000000..dfd42d4b5 --- /dev/null +++ b/context/skills/migrate-email/references/resend/account.md @@ -0,0 +1,42 @@ +# Resend account + +What the migration needs from the person's Resend account. The agent never changes the account: it reads what the person exports or allows. + +## DNS records + +A domain verified at Resend carries these records. Keep all of them until the cutover is done. + +| Record | Name | What it does | +|---|---|---| +| `TXT` (DKIM) | `resend._domainkey` | Signs Resend's mail | +| `MX` | `send` | Return path for Resend's bounces | +| `TXT` (SPF) | `send` | Allows Resend to send for the return path | +| `TXT` (DMARC) | `_dmarc` | Optional, shared by every provider on the domain | + +- `send` is Resend's default return-path label. A domain can use a custom one: the Resend dashboard shows it under Domains. +- PostHog's sender uses its own label for its MAIL FROM, `feedback` by default. Never give PostHog the label Resend uses. +- PostHog's DKIM records have their own names, so they sit next to `resend._domainkey`. +- Keep the one `_dmarc` record. Never add a second one. + +## Suppression list + +Resend suppresses an address after a hard bounce or a spam complaint, and keeps addresses the team added by hand. + +**Export from the dashboard (preferred).** In Resend: Emails, then Suppressions, then **Download CSV**. Read the header row to find the address column and the origin column. + +**Read from the API.** `GET https://api.resend.com/suppressions?limit=100` with `Authorization: Bearer $RESEND_SUPPRESSIONS_API_KEY`. + +- The answer is `{ "object": "list", "has_more": , "data": [{ "id", "email", "origin", "source_id", "created_at" }] }`. +- Page with `after=` until `has_more` is `false`. +- Resend allows 10 requests per second per team. Wait and retry on `429`. +- A sending-only key can't read the list. Ask the person to create a full-access key, store it in `RESEND_SUPPRESSIONS_API_KEY` for the import, and delete the key in Resend afterwards. + +**Map each entry.** + +| Resend `origin` | PostHog source | Reason | +|---|---|---| +| `bounce` | bounce | `Imported from Resend: hard bounce` | +| `complaint` | complaint | `Imported from Resend: spam complaint` | +| `manual` | manual | `Imported from Resend: added by hand` | + +**Leave out unsubscribed contacts.** A Resend contact with `unsubscribed: true` still gets transactional email, and PostHog's opt-outs apply to marketing messages only. They are not suppressions. diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md new file mode 100644 index 000000000..eecb90fb0 --- /dev/null +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -0,0 +1,46 @@ +# Resend to PostHog mapping + +This file decides, field by field, whether PostHog can send a Resend call site. A site moves only when every field it sets moves. Otherwise it stays on Resend, and the reason names the first field or feature that keeps it there. `transactional-email-api.md` has the PostHog side in full. + +## Fields + +| Resend | PostHog | A site stays on Resend when | +|---|---|---| +| `from` | `from` | Never. It needs a verified sender (Step 4) | +| `to` | `to` | `to` can hold more than one address. A list with exactly one address moves as that address | +| `subject` | `subject` | Never | +| `html` | `html` | Never | +| `text` | `text` | Never | +| `react` | `html`, rendered in the app | Never. The app renders the component | +| `template` | a local template in the app's code | The template uses syntax beyond variables and fallbacks | +| `cc`, `bcc` | `cc`, `bcc` | An entry carries a name, such as `Jane `, or there are more than 10 | +| `replyTo` / `reply_to` | `replyTo` / `reply_to` | Never | +| `headers` | `headers` | A header is one PostHog sets itself (`From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Sender`, `Return-Path`, `Auto-Submitted`, any `Content-*`, `X-PostHog-*`, `X-SES-*`), a value has a line break or a non-ASCII character, or there are more than 10 | +| `tags` | `tags` | A name or value has characters other than ASCII letters, digits, `_`, and `-`, a name starts with `ph_`, or there are more than 10 | +| `attachments` | `attachments` | An attachment uses `path` (a URL Resend fetches), the files can be more than 10 or more than 512 KB in total, or a file type is one mailbox providers block, such as `.exe` | +| `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | Never. The key keeps its value | +| `scheduledAt` / `scheduled_at` | none | Always | +| `topicId` / `topic_id` | none | Always | + +## Calls + +| Resend call | A site stays on Resend when | +|---|---| +| `emails.send`, `emails.create`, `Emails.send`, `POST /emails` | A field above keeps it | +| `batch.send`, `Batch.send`, `POST /emails/batch` | Always | +| SMTP through `smtp.resend.com` | Always. PostHog has no SMTP relay | +| Laravel's or Rails' `resend` mailer | Always. PostHog has no mailer driver | +| A send in a language other than JavaScript or TypeScript | Always, until the skill moves that language | + +## Code around the send + +| Code | A site stays on Resend when | +|---|---| +| `if (error.name === '...')` | The name is not one of PostHog's: `validation_error`, `missing_api_key`, `invalid_permission`, `not_found`, `concurrent_idempotent_requests`, `invalid_idempotent_request`, `rate_limit_exceeded`, `monthly_quota_exceeded`, `service_unavailable`, `application_error` | +| `emails.get(id)` and a branch on `last_event` | Always: the send and its status read stay together. PostHog's status is not `last_event` | +| `data.id` stored for a webhook or a status read | Always, when Resend webhooks or status reads use the id | + +## Content + +- `html`, `text`, and `react` content is rendered for one recipient before the send. PostHog sends it as it is. +- A `template` site needs the template's content from the Resend dashboard, because the code has only its id. PostHog's Liquid escapes HTML in a variable's value. A variable the app fills with HTML keeps the site on Resend. diff --git a/context/skills/migrate-email/references/resend/sdk-reference.md b/context/skills/migrate-email/references/resend/sdk-reference.md new file mode 100644 index 000000000..fa3cf5f02 --- /dev/null +++ b/context/skills/migrate-email/references/resend/sdk-reference.md @@ -0,0 +1,90 @@ +# Resend SDK reference + +This file says what Resend looks like in a codebase. It does not describe PostHog. `mapping.md` maps each field to PostHog. + +## Key + +The API key lives in `RESEND_API_KEY` by convention. Apps also use their own names, such as `PRIVATE_RESEND_API_KEY`: take the name the client reads. + +## Packages + +- Node.js: `resend`. +- Python: `resend` (PyPI). +- Ruby: `resend` (RubyGems), and `resend-rails`. +- PHP: `resend/resend-php`, and `resend/resend-laravel` for Laravel. +- Go: `github.com/resend/resend-go`. +- Elixir: `resend` (Hex). +- Java: `com.resend:resend-java`. +- .NET: `Resend`. +- Rust: `resend-rs`. + +These are not Resend, and alone they are not a migration: `@react-email/components`, `@react-email/render`, `react-email`, and `jsx-email` render emails, and `nodemailer` sends through any SMTP server. + +## Clients + +```js +import { Resend } from 'resend' +const resend = new Resend(process.env.RESEND_API_KEY) +``` + +```python +import resend +resend.api_key = os.environ["RESEND_API_KEY"] +``` + +Look for `new Resend(`, `from 'resend'`, `require('resend')`, `import resend`, `Resend::`, and `resend.NewClient(`. + +## Sends + +**Node.js.** `resend.emails.send(payload, options?)`, and its alias `resend.emails.create(...)`. The answer is `{ data, error }`: `data.id` is the email's id, and `error` has `name`, `message`, and `statusCode`. The SDK does not throw on API errors. + +```js +const { data, error } = await resend.emails.send({ + from: 'Example ', + to: ['jane@example.com'], + subject: 'Welcome', + html: '

Welcome

', +}, { idempotencyKey: `welcome:${user.id}` }) +``` + +**Python.** `resend.Emails.send(params)`, with the same fields in snake_case, and `options={"idempotency_key": ...}`. It raises on API errors. + +**Batch.** `resend.batch.send([...])` in Node.js and `resend.Batch.send([...])` in Python send up to 100 emails in one call. + +**HTTP.** `POST https://api.resend.com/emails` with `Authorization: Bearer `, a JSON body with the snake_case fields, and an optional `Idempotency-Key` header. `POST https://api.resend.com/emails/batch` is the batch send. Look for `api.resend.com` in `fetch`, `axios`, `got`, `requests`, `httpx`, and `curl` calls. + +**SMTP.** Resend also takes mail over SMTP at `smtp.resend.com`, with the user `resend` and the API key as the password. Look for that host in Nodemailer transports, `MAIL_HOST` or `SMTP_HOST` settings, and framework mail config. + +**Frameworks.** Laravel's `resend` mailer (`MAIL_MAILER=resend`) and Rails' `resend` delivery method send every framework mail through Resend: each mailable or mailer that sends is a site. + +## Send fields + +| Node.js field | HTTP field | Value | +|---|---|---| +| `from` | `from` | One address, with an optional name: `Name ` | +| `to` | `to` | One address, or a list of up to 50 | +| `subject` | `subject` | String | +| `html` | `html` | String | +| `text` | `text` | String. Resend derives one from `html` when it is absent | +| `react` | (none) | A React element that the Node.js SDK renders to HTML | +| `cc`, `bcc` | `cc`, `bcc` | One address or a list | +| `replyTo` | `reply_to` | One address or a list | +| `headers` | `headers` | Object of custom headers | +| `tags` | `tags` | List of `{ name, value }` | +| `attachments` | `attachments` | List of `{ filename, content, path, contentType, contentId }`. `content` is a Buffer or base64, `path` is a URL Resend fetches | +| `scheduledAt` | `scheduled_at` | A time to send later | +| `topicId` | `topic_id` | A topic the recipient can unsubscribe from | +| `template` | `template` | `{ id, variables }`: a template stored at Resend | +| `idempotencyKey` option | `Idempotency-Key` header | Up to 256 characters, kept for 24 hours | + +## Templates stored at Resend + +A send with `template: { id: 'tmpl_...', variables: { FIRST_NAME: 'Jane' } }` renders a template from the Resend dashboard. Its content is not in the code. The template reads variables as `{{{FIRST_NAME}}}`, with an optional fallback: `{{{FIRST_NAME|there}}}`. + +## Status reads + +`resend.emails.get(id)` and `GET https://api.resend.com/emails/{id}` return the email with `last_event`, such as `delivered`, `bounced`, or `complained`. Code that branches on `last_event` reads Resend's delivery state. + +## Other APIs + +`resend.contacts`, `resend.audiences`, `resend.segments`, `resend.broadcasts`, `resend.domains`, `resend.apiKeys`, `resend.webhooks`, and their HTTP routes are not transactional sends. diff --git a/context/skills/migrate/config.yaml b/context/skills/migrate/config.yaml index c56409d57..d4e2cb5a8 100644 --- a/context/skills/migrate/config.yaml +++ b/context/skills/migrate/config.yaml @@ -5,7 +5,7 @@ description: Migrate an existing analytics or feature-flag vendor to PostHog. Re tags: [migration] cli: role: command - command: migrate + parentCommand: migrate references: preamble: "**Read ONLY this file.** Do not read any other reference file until this one tells you to." shared_docs: [] diff --git a/scripts/lib/tests/migrate-email-skill.test.js b/scripts/lib/tests/migrate-email-skill.test.js new file mode 100644 index 000000000..29ca4ea6c --- /dev/null +++ b/scripts/lib/tests/migrate-email-skill.test.js @@ -0,0 +1,96 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'fs'; +import { join, relative } from 'path'; +import { tmpdir } from 'os'; + +const CONFIG_DIR = join(process.cwd(), 'context'); +const DOCS_URL = 'https://posthog.com/docs/workflows/transactional-email-api.md'; +const DOCS_PAGE = '# Transactional email API\n\nSend one email to one person from your server code.\n'; +const REFERENCE_PATH = /references\/[A-Za-z0-9_./-]+\.md/g; + +async function loadSkills() { + vi.resetModules(); + vi.stubEnv('DOCS_CACHE_TTL_MS', '0'); + vi.stubGlobal('fetch', async (url) => { + if (url !== DOCS_URL) return new Response('not found', { status: 404, statusText: 'Not Found' }); + return new Response(DOCS_PAGE, { status: 200 }); + }); + const generator = await import('../skill-generator.js'); + const skills = generator.expandSkillGroups(generator.loadSkillsConfig(CONFIG_DIR), CONFIG_DIR); + return { generator, skills }; +} + +async function buildSkill(skillId, outputDir) { + const { generator, skills } = await loadSkills(); + const skill = skills.find((candidate) => candidate.id === skillId); + expect(skill).toBeDefined(); + + await generator.generateSkill({ + skill, + version: 'test', + repoRoot: process.cwd(), + configDir: CONFIG_DIR, + outputDir, + skipPatterns: { global: [], examples: {} }, + commandmentsConfig: { commandments: {} }, + skillTemplate: skill._template, + sharedDocs: skill._sharedDocs, + }); + return join(outputDir, skillId); +} + +function markdownFiles(dir) { + return readdirSync(dir, { withFileTypes: true, recursive: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith('.md')) + .map((entry) => join(entry.parentPath, entry.name)); +} + +function unresolvedReferences(skillDir) { + const missing = []; + for (const file of markdownFiles(skillDir)) { + for (const reference of readFileSync(file, 'utf8').match(REFERENCE_PATH) ?? []) { + if (!existsSync(join(skillDir, reference))) missing.push(`${relative(skillDir, file)} → ${reference}`); + } + } + return missing; +} + +describe('migrate-email skill', () => { + let outputDir; + + afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + if (outputDir) rmSync(outputDir, { recursive: true, force: true }); + }); + + it.each(['migrate-email-resend', 'migrate-statsig'])( + 'builds %s as a bundle whose every reference path resolves', + async (skillId) => { + outputDir = mkdtempSync(join(tmpdir(), 'migrate-skill-')); + + const skillDir = await buildSkill(skillId, outputDir); + + expect(readFileSync(join(skillDir, 'SKILL.md'), 'utf8')).toMatch(new RegExp(`^---\\nname: ${skillId}\\n`)); + expect(unresolvedReferences(skillDir)).toEqual([]); + }, + ); + + it('bundles the send API reference and the Resend files without the send skill', async () => { + outputDir = mkdtempSync(join(tmpdir(), 'migrate-skill-')); + + const skillDir = await buildSkill('migrate-email-resend', outputDir); + + expect(readFileSync(join(skillDir, 'references', 'transactional-email-api.md'), 'utf8')).toBe(DOCS_PAGE); + expect(existsSync(join(skillDir, 'references', 'resend', 'sdk-reference.md'))).toBe(true); + expect(markdownFiles(skillDir).map((file) => readFileSync(file, 'utf8')).join('\n')).not.toMatch(/\{\{>|\{display_name\}|\{references\}/); + }); + + it('publishes Resend and Statsig as wizard migrate subcommands', async () => { + const { skills } = await loadSkills(); + const cliOf = (id) => skills.find((skill) => skill.id === id)?._cli; + + expect(cliOf('migrate-email-resend')).toEqual({ role: 'command', parentCommand: 'migrate', command: 'resend' }); + expect(cliOf('migrate-statsig')).toEqual({ role: 'command', parentCommand: 'migrate', command: 'statsig' }); + }); +}); From 5e019aa3ba673a1980571f0ee27c3fac61695675 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 06:46:19 +0000 Subject: [PATCH 004/260] fix(skills): keep migrate-email's summary values bare and define a site Fixture runs wrote reasons into the summary block, which the Wizard can't parse, and counted a forwarding helper as one site or as each caller. The report step now shows bare values, and a site is the place that decides a send's content and fields. Co-Authored-By: Claude Opus 5.5 --- .../migrate-email/references/3-inventory.md | 5 +++- .../migrate-email/references/7-report.md | 23 ++++++++++++------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index 1755818f0..884e90052 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -18,7 +18,10 @@ List every place the code sends email through the provider, and decide for each Read the provider's `sdk-reference.md` for the call shapes, and its `mapping.md` for the fields. -A **site** is one place in the code that calls the provider to send, such as one `emails.send(...)` call or one HTTP request to the send endpoint. A helper that wraps the call is one site, however many places call the helper. Read the callers of a helper anyway: they decide values such as how many recipients a send has. +A **site** is one place in the code that decides what a send contains: its content and its fields. Usually that is the `emails.send(...)` call or the HTTP request itself. + +- When a helper builds the send from a few parameters, such as a subject and a template name, the helper is one site, however many places call it. Read its callers anyway: they decide values such as how many recipients a send has. +- When a helper only forwards a payload that its callers build, each caller is a site, and the helper is not. For each site, read the surrounding code and record: diff --git a/context/skills/migrate-email/references/7-report.md b/context/skills/migrate-email/references/7-report.md index 0dfb9a330..6869e754e 100644 --- a/context/skills/migrate-email/references/7-report.md +++ b/context/skills/migrate-email/references/7-report.md @@ -56,18 +56,25 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- ## Summary ``` -End the report with the summary block, as the last thing in the file. The Wizard reads it, so keep the keys and their order: +End the report with the summary block, as the last thing in the file. The Wizard parses it, so keep the keys, their order, and bare values: a whole number, `true`, `false`, or the provider folder name. Never add a comment or a reason to a value. The reasons are in the tables above. For example: ```yaml -from: -sites_found: -sites_rewritten: -sites_left: -dns_ready: -suppressions_ready: +from: resend +sites_found: 3 +sites_rewritten: 0 +sites_left: 1 +dns_ready: false +suppressions_ready: true ``` -This version changes no site, so `sites_rewritten` is `0`. Sites that are ready to move count in `sites_found` only. +- `from`: the provider folder name. +- `sites_found`: every row of the sites table. +- `sites_rewritten`: the sites this run changed to send with PostHog. This version changes none, so it is `0`. +- `sites_left`: the sites that stay on the provider. +- `dns_ready`: `true` when every sending domain has a verified sender. +- `suppressions_ready`: `true` when the suppression list was imported or was empty. + +Sites that are ready to move count in `sites_found` only. After the report is written, print its path: From 6e902dc5ffc67178253e4a5682de11ef4169be11 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:52:37 +0000 Subject: [PATCH 005/260] fix(skills): point migrate-email at the transactional email docs and the sending skill The send-transactional-email skill is gone from this stack, so migrate-email bundles the transactional email pages and names the sending-transactional-emails skill for the general move. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/config.yaml | 3 ++- context/skills/migrate-email/description.md | 4 +++- .../references/resend/mapping.md | 2 +- scripts/lib/tests/migrate-email-skill.test.js | 19 +++++++++++++------ 4 files changed, 19 insertions(+), 9 deletions(-) diff --git a/context/skills/migrate-email/config.yaml b/context/skills/migrate-email/config.yaml index 6b0b83c37..2accfcd59 100644 --- a/context/skills/migrate-email/config.yaml +++ b/context/skills/migrate-email/config.yaml @@ -10,7 +10,8 @@ cli: references: preamble: "**Read ONLY this file.** Do not read any other reference file until this one tells you to." shared_docs: - - https://posthog.com/docs/workflows/transactional-email-api.md + - https://posthog.com/docs/workflows/transactional-emails.md + - https://posthog.com/docs/workflows/transactional-emails/api.md variants: - id: resend display_name: Resend diff --git a/context/skills/migrate-email/description.md b/context/skills/migrate-email/description.md index 174a82b6a..7bb85a8d2 100644 --- a/context/skills/migrate-email/description.md +++ b/context/skills/migrate-email/description.md @@ -52,4 +52,6 @@ Outside the Wizard, skip the `[STATUS]` lines, and tell the person why you stopp {references} -`transactional-email-api.md` is the transactional email API page. It covers senders, the send forms, `posthog-node`, idempotency, and every error code. +`transactional-emails.md` is the transactional email overview. It covers how to create a transactional email and its API key, idempotency, and the error codes. `api.md` covers the send route, including content from your code, and the checks of a send. + +When the `sending-transactional-emails` skill is available, read it too. Its `moving-from-other-providers.md` moves any provider's sends to a PostHog template. This skill adds what is specific to {display_name}: it finds every send, sets up the sender next to {display_name}'s DNS records, imports {display_name}'s suppression list, and hands over the key. diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index eecb90fb0..8649ddbd8 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -1,6 +1,6 @@ # Resend to PostHog mapping -This file decides, field by field, whether PostHog can send a Resend call site. A site moves only when every field it sets moves. Otherwise it stays on Resend, and the reason names the first field or feature that keeps it there. `transactional-email-api.md` has the PostHog side in full. +This file decides, field by field, whether PostHog can send a Resend call site. A site moves only when every field it sets moves. Otherwise it stays on Resend, and the reason names the first field or feature that keeps it there. `api.md` has the PostHog side in full. ## Fields diff --git a/scripts/lib/tests/migrate-email-skill.test.js b/scripts/lib/tests/migrate-email-skill.test.js index 29ca4ea6c..8ffca7b6e 100644 --- a/scripts/lib/tests/migrate-email-skill.test.js +++ b/scripts/lib/tests/migrate-email-skill.test.js @@ -4,16 +4,18 @@ import { join, relative } from 'path'; import { tmpdir } from 'os'; const CONFIG_DIR = join(process.cwd(), 'context'); -const DOCS_URL = 'https://posthog.com/docs/workflows/transactional-email-api.md'; -const DOCS_PAGE = '# Transactional email API\n\nSend one email to one person from your server code.\n'; +const DOCS_PAGES = { + 'https://posthog.com/docs/workflows/transactional-emails.md': '# Transactional emails\n\nSend one email to one person.\n', + 'https://posthog.com/docs/workflows/transactional-emails/api.md': '# Send transactional emails with the API\n', +}; const REFERENCE_PATH = /references\/[A-Za-z0-9_./-]+\.md/g; async function loadSkills() { vi.resetModules(); vi.stubEnv('DOCS_CACHE_TTL_MS', '0'); vi.stubGlobal('fetch', async (url) => { - if (url !== DOCS_URL) return new Response('not found', { status: 404, statusText: 'Not Found' }); - return new Response(DOCS_PAGE, { status: 200 }); + if (!(url in DOCS_PAGES)) return new Response('not found', { status: 404, statusText: 'Not Found' }); + return new Response(DOCS_PAGES[url], { status: 200 }); }); const generator = await import('../skill-generator.js'); const skills = generator.expandSkillGroups(generator.loadSkillsConfig(CONFIG_DIR), CONFIG_DIR); @@ -76,12 +78,17 @@ describe('migrate-email skill', () => { }, ); - it('bundles the send API reference and the Resend files without the send skill', async () => { + it('bundles the transactional email docs and the Resend files', async () => { outputDir = mkdtempSync(join(tmpdir(), 'migrate-skill-')); const skillDir = await buildSkill('migrate-email-resend', outputDir); - expect(readFileSync(join(skillDir, 'references', 'transactional-email-api.md'), 'utf8')).toBe(DOCS_PAGE); + expect(readFileSync(join(skillDir, 'references', 'transactional-emails.md'), 'utf8')).toBe( + DOCS_PAGES['https://posthog.com/docs/workflows/transactional-emails.md'], + ); + expect(readFileSync(join(skillDir, 'references', 'api.md'), 'utf8')).toBe( + DOCS_PAGES['https://posthog.com/docs/workflows/transactional-emails/api.md'], + ); expect(existsSync(join(skillDir, 'references', 'resend', 'sdk-reference.md'))).toBe(true); expect(markdownFiles(skillDir).map((file) => readFileSync(file, 'utf8')).join('\n')).not.toMatch(/\{\{>|\{display_name\}|\{references\}/); }); From 0286e235e3c0d2ac05e102d3e3ab130e1b721513 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:02:02 +0000 Subject: [PATCH 006/260] fix(skills): check migrate-email's API access with the real tools and PostHog's reply-to rules The preflight looked for two MCP tools that don't exist. It now looks for the make-transactional pair, and a missing pair records the API as not confirmed instead of stopping, because it can also mean a missing scope. The mapping now keeps a site on Resend for reply-to addresses with a name or more than 10, and lists every reserved header and the header and tag length limits. Co-Authored-By: Claude Opus 5.5 --- .../skills/migrate-email/references/2-preflight.md | 11 +++-------- .../skills/migrate-email/references/resend/mapping.md | 6 +++--- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/context/skills/migrate-email/references/2-preflight.md b/context/skills/migrate-email/references/2-preflight.md index ffd88264d..a643d9be2 100644 --- a/context/skills/migrate-email/references/2-preflight.md +++ b/context/skills/migrate-email/references/2-preflight.md @@ -18,15 +18,10 @@ Do not change any file. Check which PostHog MCP tools exist. - When there are no PostHog tools at all, the PostHog MCP is not connected or not signed in. Ask the person to connect it, and wait. -- When other PostHog tools exist but `workflows-upload-email-template` and `workflows-send-email` don't, the transactional email API is not enabled for this project. Stop and tell the person: the API is in beta, and they can ask PostHog in-app to enable it for their project. Then emit: +- When `workflows-make-email-template-transactional-prepare` and `workflows-make-email-template-transactional-execute` exist, the API is on. Record `api: on`. +- When other PostHog tools exist but that pair doesn't, either the login lacks the `hog_flow:write` scope, or transactional email is not on for the project yet. A missing tool cannot tell these apart. Tell the person both causes, record `api: not confirmed`, and continue. The report asks them to confirm it before cutover. -``` -[ABORT] transactional email api not enabled -``` - -- When both tools exist, the API is on. Record `api: on`. - -Inside the Wizard, a missing tool can mean that the login lacks its scope, so missing tools do not stop the run. Record `api: not confirmed` and continue. The report asks the person to confirm it. +Do not call a tool that changes anything to find out. ## The sending tier diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 8649ddbd8..097d84c87 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -14,9 +14,9 @@ This file decides, field by field, whether PostHog can send a Resend call site. | `react` | `html`, rendered in the app | Never. The app renders the component | | `template` | a local template in the app's code | The template uses syntax beyond variables and fallbacks | | `cc`, `bcc` | `cc`, `bcc` | An entry carries a name, such as `Jane `, or there are more than 10 | -| `replyTo` / `reply_to` | `replyTo` / `reply_to` | Never | -| `headers` | `headers` | A header is one PostHog sets itself (`From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Sender`, `Return-Path`, `Auto-Submitted`, any `Content-*`, `X-PostHog-*`, `X-SES-*`), a value has a line break or a non-ASCII character, or there are more than 10 | -| `tags` | `tags` | A name or value has characters other than ASCII letters, digits, `_`, and `-`, a name starts with `ph_`, or there are more than 10 | +| `replyTo` / `reply_to` | `replyTo` / `reply_to`, as a list | An entry carries a name, such as `Jane `, there are more than 10, or the code builds the value at run time and you cannot tell that it holds bare addresses only. A single address moves as a list of one | +| `headers` | `headers` | A header is one PostHog sets itself (`From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Sender`, `Return-Path`, `Auto-Submitted`, `DKIM-Signature`, `Received`, any `Content-*`, `X-PostHog-*`, `X-SES-*`), a name is longer than 126 characters, a value is longer than 870 characters or has a line break or a non-ASCII character, or there are more than 10 | +| `tags` | `tags` | A name or value has characters other than ASCII letters, digits, `_`, and `-` or is longer than 256 characters, a name starts with `ph_`, or there are more than 10 | | `attachments` | `attachments` | An attachment uses `path` (a URL Resend fetches), the files can be more than 10 or more than 512 KB in total, or a file type is one mailbox providers block, such as `.exe` | | `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | Never. The key keeps its value | | `scheduledAt` / `scheduled_at` | none | Always | From 0920218521daeb77280e41f90bb5f0e409d853c2 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:00:11 +0000 Subject: [PATCH 007/260] refactor(skills): share the posthog-node client setup as a partial Co-Authored-By: Claude Opus 5.5 --- context/shared/email-node-client.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 context/shared/email-node-client.md diff --git a/context/shared/email-node-client.md b/context/shared/email-node-client.md new file mode 100644 index 000000000..3f26ccb42 --- /dev/null +++ b/context/shared/email-node-client.md @@ -0,0 +1,7 @@ +--- +title: Configure the posthog-node client for email +--- + +- Reuse the app's existing `posthog-node` client when it has one, and add `secretKey`. Keep `enableLocalEvaluation: false` unless the key also has `feature_flag:read` and the app uses local evaluation. +- When the project token or the host is not configured yet, get the token from the PostHog MCP `projects-get` tool (`api_token`). The host is `https://us.i.posthog.com` for US Cloud and `https://eu.i.posthog.com` for EU Cloud. Ask the person which one when you can't tell. +- When `host` is a reverse proxy or a self-hosted instance, also set `appHost` to the PostHog app URL, such as `https://us.posthog.com`. posthog-node never sends the secret key to a proxy, and without `appHost` the send fails with `missing_app_host`. From 64a2397db57f938a5052a733e1c67ac83b13baae Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:00:11 +0000 Subject: [PATCH 008/260] feat(skills): move Resend sends to posthog-node in migrate-email The migrate-email skill now rewrites every call site PostHog can send: hosted Resend templates become local templates, React and html/text sites send rendered content, and the client carries migratedFrom. It checks the build and one email on one person before it writes the report. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/config.yaml | 2 +- context/skills/migrate-email/description.md | 12 ++-- .../migrate-email/references/3-inventory.md | 4 ++ .../skills/migrate-email/references/6-key.md | 2 +- .../migrate-email/references/7-rewrite.md | 68 +++++++++++++++++++ .../migrate-email/references/8-verify.md | 48 +++++++++++++ .../references/{7-report.md => 9-report.md} | 30 +++++--- .../references/resend/account.md | 18 ++++- .../references/resend/mapping.md | 41 ++++++++++- .../references/resend/sdk-reference.md | 7 +- scripts/lib/tests/migrate-email-skill.test.js | 19 ++++++ 11 files changed, 227 insertions(+), 24 deletions(-) create mode 100644 context/skills/migrate-email/references/7-rewrite.md create mode 100644 context/skills/migrate-email/references/8-verify.md rename context/skills/migrate-email/references/{7-report.md => 9-report.md} (58%) diff --git a/context/skills/migrate-email/config.yaml b/context/skills/migrate-email/config.yaml index 2accfcd59..8becd4c82 100644 --- a/context/skills/migrate-email/config.yaml +++ b/context/skills/migrate-email/config.yaml @@ -2,7 +2,7 @@ type: skill template: description.md category: migrate -description: Migrate transactional email from {display_name} to PostHog. Use when asked to migrate from {display_name}, replace {display_name} with PostHog, or switch email providers. It finds every {display_name} send in the code, sets up the sender and DNS next to {display_name}'s records, imports {display_name}'s suppression list, hands over the PostHog secret key, and writes a migration report. It changes no send call site yet. +description: Migrate transactional email from {display_name} to PostHog. Use when asked to migrate from {display_name}, replace {display_name} with PostHog, or switch email providers. It finds every {display_name} send in the code, sets up the sender and DNS next to {display_name}'s records, imports {display_name}'s suppression list, moves each send PostHog can take to posthog-node, and writes a migration report that lists the sends that stay. tags: [migration, workflows] cli: role: command diff --git a/context/skills/migrate-email/description.md b/context/skills/migrate-email/description.md index 7bb85a8d2..9eaf4cf41 100644 --- a/context/skills/migrate-email/description.md +++ b/context/skills/migrate-email/description.md @@ -2,7 +2,7 @@ Use this skill to move an app's transactional email, such as welcome emails, password resets, and receipts, from {display_name} to PostHog. -This version prepares the move and changes no send call site. It finds every {display_name} send, sets up the PostHog sender and its DNS records next to {display_name}'s, imports {display_name}'s suppression list, hands over the PostHog secret key, and writes a report. Both providers can send during the cutover. +It finds every {display_name} send, sets up the PostHog sender and its DNS records next to {display_name}'s, imports {display_name}'s suppression list, and hands over the PostHog secret key. Then it moves every send PostHog can take to `posthog-node`, checks one email on one person, and writes a report. Sends PostHog can't take stay on {display_name} with a reason, so both providers send during the cutover. The transactional email API is in beta. PostHog enables it per project. @@ -17,8 +17,8 @@ Read the step files in order, one at a time. Each step names the next one. Do no The folder `references//` holds everything specific to {display_name}. The steps tell you when to read each file: - `sdk-reference.md`: how {display_name} looks in code, so you can find every send. -- `mapping.md`: how each send field maps to PostHog, and what keeps a call site on {display_name}. -- `account.md`: {display_name}'s DNS records and how to export its suppression list. +- `mapping.md`: how each send field maps to PostHog, what keeps a call site on {display_name}, and how to rewrite a site that moves. +- `account.md`: {display_name}'s DNS records, and how to get its templates and its suppression list. Everything you need is on disk. Do not fetch {display_name}'s docs. @@ -28,10 +28,10 @@ The plan file `.posthog-email-migration-plan.md` lives at the project root. Step ## Rules -- Change no send call site. This version only prepares the move. +- Change only the call sites that move, and only in Step 7. Leave every site that stays as it is. - Never touch DNS or the {display_name} account. Give the person the records and the links, and let them make the change. -- Never remove the {display_name} package, its client, or its API key. -- Never create, upload, or edit a template in PostHog. +- Never remove the {display_name} package or its API key. The report tells the person when to remove them. +- Never create, upload, or edit a template in PostHog. A moved local template uploads on its first send. - Never write a recipient's email address into a file in the repository, the plan, or the report. Count addresses instead. - Keep keys in environment variables. Never hardcode a key, and never ask the person to paste one into the chat. - Do not commit. The person reviews the diff and commits. diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index 884e90052..452109d72 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -39,6 +39,8 @@ Go through `mapping.md` field by field. A site **moves** when PostHog can send e When the code passes a value you can't read, such as a list of recipients built at run time, follow it to its callers. When you still can't tell, the site stays, and the reason says what you could not check. +A `template` site needs the template's content to be classified. Read the provider's `account.md`, and ask the person once for every template the sites send: copy from the dashboard, or read through the API. Keep the content for Step 7, and never write it into the plan. When the person can't give the content, the site stays. + ## Write the plan file Write `.posthog-email-migration-plan.md` at the project root with three sections. Never write an email address of a recipient into it. A `from` address is fine. @@ -51,6 +53,8 @@ A phase checklist, in this order. Tick `preflight` with what Step 2 recorded, an - [ ] sender - [ ] suppressions - [ ] key +- [ ] rewrite +- [ ] verify ``` A sites table, one row per site, in source tree order: diff --git a/context/skills/migrate-email/references/6-key.md b/context/skills/migrate-email/references/6-key.md index 0b4a08208..0c39a80d5 100644 --- a/context/skills/migrate-email/references/6-key.md +++ b/context/skills/migrate-email/references/6-key.md @@ -1,6 +1,6 @@ --- title: Hand over the PostHog secret key -next_step: 7-report.md +next_step: 7-rewrite.md --- # Step 6, hand over the PostHog secret key diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md new file mode 100644 index 000000000..f107996d0 --- /dev/null +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -0,0 +1,68 @@ +--- +title: Move every site that can move +next_step: 8-verify.md +--- + +# Step 7, move every site that can move + +Rewrite each site whose `moves` is `yes` in the plan to send with `posthog-node`. The provider's `mapping.md` has the rewrite of each field, call, and content form under "Rewrite". + +## Status + +``` +[STATUS] Setting up posthog-node for email +[STATUS] Moving the send call sites +``` + +## Before you change code + +- Change only the sites whose `moves` is `yes`. Never change a site that stays, and never change a line that a site that stays still needs. +- When no site moves, tick the phase in the plan with `none moved` and go to the next step. + +## Set up the client + +Install or upgrade `posthog-node` with the project's package manager, to a version that has `posthog.emails`. + +Configure one server-side client for email. Set `migratedFrom` to the provider folder name, once on the client, so PostHog knows which sends a migration moved: + +```js +import { PostHog } from 'posthog-node' + +export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { + host: process.env.POSTHOG_HOST, + secretKey: process.env.POSTHOG_PROJECT_SECRET_API_KEY, + migratedFrom: 'resend', + enableLocalEvaluation: false, +}) +``` + +{{> email-node-client}} +- A reused client gets `migratedFrom` too. +- Put a new client in its own server-only module, next to the provider's client, and import it where the sites send. +- Use the env variable names the app already uses for the PostHog token and host. Add each new name, without a value, to the env example file. + +## Find the user ID + +PostHog shows each email on the person the send names with `distinctId`. Use the ID the app already identifies people with in PostHog: + +- Find the app's identify call, such as `posthog.identify(user.id)` in posthog-js, or the `distinctId` of its `posthog-node` captures. +- At each site, pass the same ID for the recipient, such as `distinctId: user.id`. Follow the recipient back through the callers when the site only has the address. +- When the recipient is not a user of the app, such as a team inbox, or the site has no way to know the user, leave `distinctId` out and note it in the plan row. +- When the app identifies no one in PostHog, use the app's own user ID, and note it for the report. + +## Rewrite each site + +For each site that moves, in plan order: + +- Rewrite the call as the provider's `mapping.md` says, for the site's content form: `html` and `text` content, a component the app renders, or a template stored at the provider. +- Give each send a `templateKey` that names the kind of email, such as `welcome` or `password-reset`, with letters, digits, `-`, and `_` only. Two sites that send the same email share a key. A template stored at the provider keeps the key `mapping.md` gives it. +- A template stored at the provider becomes a module that exports `subject` and `html`, and `text` when it has one, in an `emails/` folder next to the server code. The site imports it and passes `templateData`. +- Install `@react-email/render` with the project's package manager when a site renders a component and the app doesn't have it. +- Keep the site's idempotency key, error branches, logging, and return value working as before. Keep the code around the send unchanged where you can. +- Never add a field that the old call didn't set, apart from `templateKey` and `distinctId`. + +When a site turns out to need something `mapping.md` keeps on the provider, undo its change, set `moves` to `no` with the reason, and go on. + +## Write down + +Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each new dependency, and each new env variable name. diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md new file mode 100644 index 000000000..61ee2c3a7 --- /dev/null +++ b/context/skills/migrate-email/references/8-verify.md @@ -0,0 +1,48 @@ +--- +title: Check the moved sites +next_step: 9-report.md +--- + +# Step 8, check the moved sites + +Check that the app still builds, its tests still pass, and one moved email reaches one person in PostHog. When no site moved in Step 7, tick the phase with `nothing to check` and go to the next step. + +## Status + +``` +[STATUS] Checking the moved sites +[STATUS] Sending a test email +``` + +## Build and tests + +- Run the project's typecheck, such as its `typecheck` script or `tsc --noEmit`, or its build when it has no typecheck. Fix each error in a line you changed. An error in a file you didn't change was there before: note it, and leave it. +- Run the tests that cover the files you changed. A test that mocks the provider's client for a moved site now mocks `posthog.emails.send` with the same assertions. Never delete or skip a test. +- Search the changed files for the provider's calls: a moved site has none left, and each moved site has one `posthog.emails.send`. + +## One email on one person + +The chain to prove: PostHog sends the email, records its engagement on the person, and that person's product events show next to it. + +Skip this part and record `not checked` with the reason when the API is not confirmed on, no sender is verified, or `POSTHOG_PROJECT_SECRET_API_KEY` is not set. + +1. Ask the person whether to send one test email. Say that it sends a real email, and that the first send of a local template uploads it to the PostHog project. When they say no, record `not checked: declined`. +2. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. +3. When the send fails, find its code in `transactional-email-api.md`, tell the person the fix, and record it. Never retry a send yourself. +4. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID over the last hour: + + ```sql + SELECT event, timestamp FROM events + WHERE distinct_id = '' AND timestamp > now() - INTERVAL 1 HOUR + ORDER BY timestamp + ``` + +5. The chain holds when the result has `$workflows_email_sent`, an engagement event such as `$workflows_email_delivered` or `$workflows_email_opened`, and at least one product event of the app. Delivery events arrive after the provider reports back: when only the send shows, wait a minute and run the query once more. + +When the MCP has no SQL tool, ask the person to open their person in PostHog and tell you which of the three they see. + +Never write the address or the distinct ID into a file. + +## Write down + +Tick the phase in the plan: `- [x] verify — typecheck: , tests: , chain: `. diff --git a/context/skills/migrate-email/references/7-report.md b/context/skills/migrate-email/references/9-report.md similarity index 58% rename from context/skills/migrate-email/references/7-report.md rename to context/skills/migrate-email/references/9-report.md index 6869e754e..08441c30b 100644 --- a/context/skills/migrate-email/references/7-report.md +++ b/context/skills/migrate-email/references/9-report.md @@ -3,7 +3,7 @@ title: Write the migration report next_step: null --- -# Step 7, write the migration report +# Step 9, write the migration report The report comes from the plan file. Invent nothing. @@ -20,14 +20,16 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- ```markdown # Email migration report: to PostHog - + ## Send call sites -| File | Line | Content | Status | -|------|------|---------|--------| +| File | Line | Content | Key | Status | +|------|------|---------|-----|--------| -: ".> +", or "Stays on : ".> + + ## Other calls @@ -45,13 +47,23 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- +## Checks + + + ## Sending tier ## Before cutover -
+The moved sites send through PostHog as soon as this code is deployed. Everything in this list has to be done before that deploy. + + + +## After cutover + + ## Summary ``` @@ -61,7 +73,7 @@ End the report with the summary block, as the last thing in the file. The Wizard ```yaml from: resend sites_found: 3 -sites_rewritten: 0 +sites_rewritten: 2 sites_left: 1 dns_ready: false suppressions_ready: true @@ -69,13 +81,11 @@ suppressions_ready: true - `from`: the provider folder name. - `sites_found`: every row of the sites table. -- `sites_rewritten`: the sites this run changed to send with PostHog. This version changes none, so it is `0`. +- `sites_rewritten`: the sites this run moved to send with PostHog. - `sites_left`: the sites that stay on the provider. - `dns_ready`: `true` when every sending domain has a verified sender. - `suppressions_ready`: `true` when the suppression list was imported or was empty. -Sites that are ready to move count in `sites_found` only. - After the report is written, print its path: ``` diff --git a/context/skills/migrate-email/references/resend/account.md b/context/skills/migrate-email/references/resend/account.md index dfd42d4b5..f4c38602e 100644 --- a/context/skills/migrate-email/references/resend/account.md +++ b/context/skills/migrate-email/references/resend/account.md @@ -18,18 +18,32 @@ A domain verified at Resend carries these records. Keep all of them until the cu - PostHog's DKIM records have their own names, so they sit next to `resend._domainkey`. - Keep the one `_dmarc` record. Never add a second one. +## Full-access key + +The app's own Resend key is usually a sending-only key, and it can't read templates or the suppression list. When the person chooses the API over the dashboard, ask them to create a full-access key in Resend, store it in `RESEND_FULL_ACCESS_API_KEY` in the git-ignored env file, and delete the key in Resend after the migration. Never print the key, and never write it into another file. + +## Template content + +A site that sends a template stored at Resend needs the template's content. + +**Copy from the dashboard.** In Resend: Templates, then the template. Ask the person for its HTML, its plain text when it has one, its subject, its `from` and reply-to when they are set, and each variable's fallback. + +**Read from the API.** `GET https://api.resend.com/templates/{id or alias}` with `Authorization: Bearer $RESEND_FULL_ACCESS_API_KEY`. The answer holds `alias`, `name`, `subject`, `from`, `reply_to`, `html`, `text`, and `variables`, a list of `{ key, type, fallback_value }`. + +The content goes only into the template module the rewrite writes. Never write it into the plan or the report. + ## Suppression list Resend suppresses an address after a hard bounce or a spam complaint, and keeps addresses the team added by hand. **Export from the dashboard (preferred).** In Resend: Emails, then Suppressions, then **Download CSV**. Read the header row to find the address column and the origin column. -**Read from the API.** `GET https://api.resend.com/suppressions?limit=100` with `Authorization: Bearer $RESEND_SUPPRESSIONS_API_KEY`. +**Read from the API.** `GET https://api.resend.com/suppressions?limit=100` with `Authorization: Bearer $RESEND_FULL_ACCESS_API_KEY`. - The answer is `{ "object": "list", "has_more": , "data": [{ "id", "email", "origin", "source_id", "created_at" }] }`. - Page with `after=` until `has_more` is `false`. - Resend allows 10 requests per second per team. Wait and retry on `429`. -- A sending-only key can't read the list. Ask the person to create a full-access key, store it in `RESEND_SUPPRESSIONS_API_KEY` for the import, and delete the key in Resend afterwards. +- A sending-only key can't read the list. Use the full-access key below. **Map each entry.** diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 097d84c87..cf8bc23f6 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -12,13 +12,13 @@ This file decides, field by field, whether PostHog can send a Resend call site. | `html` | `html` | Never | | `text` | `text` | Never | | `react` | `html`, rendered in the app | Never. The app renders the component | -| `template` | a local template in the app's code | The template uses syntax beyond variables and fallbacks | +| `template` | a local template in the app's code | Its content can't be read, it uses syntax beyond variables and fallbacks, or the app fills a variable with HTML | | `cc`, `bcc` | `cc`, `bcc` | An entry carries a name, such as `Jane `, or there are more than 10 | | `replyTo` / `reply_to` | `replyTo` / `reply_to`, as a list | An entry carries a name, such as `Jane `, there are more than 10, or the code builds the value at run time and you cannot tell that it holds bare addresses only. A single address moves as a list of one | | `headers` | `headers` | A header is one PostHog sets itself (`From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Sender`, `Return-Path`, `Auto-Submitted`, `DKIM-Signature`, `Received`, any `Content-*`, `X-PostHog-*`, `X-SES-*`), a name is longer than 126 characters, a value is longer than 870 characters or has a line break or a non-ASCII character, or there are more than 10 | | `tags` | `tags` | A name or value has characters other than ASCII letters, digits, `_`, and `-` or is longer than 256 characters, a name starts with `ph_`, or there are more than 10 | | `attachments` | `attachments` | An attachment uses `path` (a URL Resend fetches), the files can be more than 10 or more than 512 KB in total, or a file type is one mailbox providers block, such as `.exe` | -| `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | Never. The key keeps its value | +| `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | The key can hold a space or a non-ASCII character, or be longer than 255 characters. Otherwise the key keeps its value and its meaning: both providers keep a key for 24 hours | | `scheduledAt` / `scheduled_at` | none | Always | | `topicId` / `topic_id` | none | Always | @@ -43,4 +43,39 @@ This file decides, field by field, whether PostHog can send a Resend call site. ## Content - `html`, `text`, and `react` content is rendered for one recipient before the send. PostHog sends it as it is. -- A `template` site needs the template's content from the Resend dashboard, because the code has only its id. PostHog's Liquid escapes HTML in a variable's value. A variable the app fills with HTML keeps the site on Resend. +- A `template` site needs the template's content, because the code has only its id. `account.md` says how to get it. +- Resend inserts a variable's value as it is. PostHog's Liquid escapes HTML in a value, so `` shows as text. A variable is HTML when the code fills it with markup or with a renderer's output. A variable the app fills with plain values, such as names, numbers, and URLs, renders the same. +- A template that holds anything other than `{{{VAR}}}` and `{{{VAR|fallback}}}` placeholders, such as a section, a loop, or a condition, stays on Resend. + +## Rewrite + +How a site that moves is written with `posthog-node`. Step 7 says when to use each part. + +**The call.** `resend.emails.send(payload, { idempotencyKey })` and `resend.emails.create(...)` become one `posthog.emails.send({ ... })`. The options object goes away: `idempotencyKey` moves into the payload. + +**The fields.** + +- `to: ['jane@example.com']` becomes `to: 'jane@example.com'`. A value that is a list with one entry becomes that entry. +- `from`, `subject`, `html`, `text`, `replyTo`, `cc`, `bcc`, `headers`, and `tags` keep their names and values. +- `attachments` keep `filename`, `content`, `contentType`, and `contentId`. +- Each send gets a `templateKey`, as Step 7 says. + +**React.** `react: ` becomes `html: await render()`, with `import { render } from '@react-email/render'`. Keep a `text` the site already passes. + +**HTTP.** A `fetch` or `axios` call to `https://api.resend.com/emails` becomes `posthog.emails.send` with the camelCase fields: `reply_to` becomes `replyTo`, and the `Idempotency-Key` header becomes `idempotencyKey`. Code that read the response status reads `error` instead. + +**Templates stored at Resend.** The template becomes a module in the app's code, in the format of the send skill's local template: a `subject` and an `html` string, and a `text` string when the template has one. + +- `{{{NAME}}}` becomes `{{ variables.NAME }}`. The name keeps its case. +- `{{{NAME|there}}}` becomes `{{ variables.NAME | default: "there" }}`. A variable with a `fallback_value` in the template's definition gets the same `default`. Escape a `"` in the fallback as `\"`. +- Liquid's `default` also replaces an empty string, which Resend inserts as it is. When the code can pass an empty string for a variable with a fallback, the email shows the fallback instead. Note it in the report. +- The site sends `templateKey`, `subject`, `html`, `text` when there is one, and `templateData` with the site's `variables` object unchanged. +- The site's own `subject`, `from`, and `replyTo` win over the template's. When the site has none, use the template's: put its `from` and `replyTo` on the send, and its subject in the module. +- The template's alias, or its name in lowercase with `-` between words, becomes the `templateKey` and the module's file name. + +**The answer.** posthog-node answers `{ data, error }` like Resend and never throws on an API error. + +- `data.id` is PostHog's message id. Code that logs it or stores it for the app's own use keeps working. +- `error.name` uses Resend's names, so `if (error.name === 'rate_limit_exceeded')` keeps working. `error.message` and `error.statusCode` keep their names. + +**The Resend client.** Keep `new Resend(...)` and its import while any site or other call still uses it. When nothing uses it, remove the import and the client, and keep the `resend` package and its key: the person removes them after the cutover. diff --git a/context/skills/migrate-email/references/resend/sdk-reference.md b/context/skills/migrate-email/references/resend/sdk-reference.md index fa3cf5f02..f88d47b29 100644 --- a/context/skills/migrate-email/references/resend/sdk-reference.md +++ b/context/skills/migrate-email/references/resend/sdk-reference.md @@ -79,7 +79,12 @@ const { data, error } = await resend.emails.send({ ## Templates stored at Resend -A send with `template: { id: 'tmpl_...', variables: { FIRST_NAME: 'Jane' } }` renders a template from the Resend dashboard. Its content is not in the code. The template reads variables as `{{{FIRST_NAME}}}`, with an optional fallback: `{{{FIRST_NAME|there}}}`. +A send with `template: { id: '...', variables: { PRODUCT: 'Laptop' } }` renders a template from the Resend dashboard. `id` is the template's id or its alias. Its content is not in the code. + +- The template reads variables as `{{{PRODUCT}}}`, with an optional fallback: `{{{PRODUCT|a laptop}}}`. A variable's definition in the template can also carry a `fallback_value`. +- A variable's type is `string` or `number`. +- The template can hold a default `from`, `subject`, and `reply_to`. A value the send passes wins over the default. +- A send with `template` passes no `html`, `text`, or `react`. ## Status reads diff --git a/scripts/lib/tests/migrate-email-skill.test.js b/scripts/lib/tests/migrate-email-skill.test.js index 8ffca7b6e..546138455 100644 --- a/scripts/lib/tests/migrate-email-skill.test.js +++ b/scripts/lib/tests/migrate-email-skill.test.js @@ -93,6 +93,25 @@ describe('migrate-email skill', () => { expect(markdownFiles(skillDir).map((file) => readFileSync(file, 'utf8')).join('\n')).not.toMatch(/\{\{>|\{display_name\}|\{references\}/); }); + it('moves the supported sites and checks them before it writes the report', async () => { + outputDir = mkdtempSync(join(tmpdir(), 'migrate-skill-')); + + const skillDir = await buildSkill('migrate-email-resend', outputDir); + const workflow = readFileSync(join(skillDir, 'SKILL.md'), 'utf8').match(/^\d+\. `references\/[^`]+`/gm); + + expect(workflow.map((step) => step.replace(/^\d+\. /, ''))).toEqual([ + '`references/1-detect.md`', + '`references/2-preflight.md`', + '`references/3-inventory.md`', + '`references/4-sender.md`', + '`references/5-suppressions.md`', + '`references/6-key.md`', + '`references/7-rewrite.md`', + '`references/8-verify.md`', + '`references/9-report.md`', + ]); + }); + it('publishes Resend and Statsig as wizard migrate subcommands', async () => { const { skills } = await loadSkills(); const cliOf = (id) => skills.find((skill) => skill.id === id)?._cli; From ad4b0c7a70cc48ab28234f49f4dd9b9e65552f3d Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:07:57 +0000 Subject: [PATCH 009/260] fix(skills): keep migrate-email from splitting sends or faking the old provider in tests Fixture runs looped over or truncated a one-recipient list, and one run mocked posthog-node to rebuild a Resend request. The rewrite now narrows the helper's parameter to one address, and the verify step asserts on the fields posthog.emails.send gets. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/8-verify.md | 2 +- context/skills/migrate-email/references/resend/mapping.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 61ee2c3a7..2bd615b8f 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -17,7 +17,7 @@ Check that the app still builds, its tests still pass, and one moved email reach ## Build and tests - Run the project's typecheck, such as its `typecheck` script or `tsc --noEmit`, or its build when it has no typecheck. Fix each error in a line you changed. An error in a file you didn't change was there before: note it, and leave it. -- Run the tests that cover the files you changed. A test that mocks the provider's client for a moved site now mocks `posthog.emails.send` with the same assertions. Never delete or skip a test. +- Run the tests that cover the files you changed. A test that mocks the provider's client or intercepts its HTTP requests for a moved site now mocks `posthog.emails.send` and asserts on the fields it gets, with the same expected values. Never turn a PostHog send back into the provider's request shape to keep an old assertion. Never delete or skip a test. - Search the changed files for the provider's calls: a moved site has none left, and each moved site has one `posthog.emails.send`. ## One email on one person diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index cf8bc23f6..40d54826d 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -56,6 +56,7 @@ How a site that moves is written with `posthog-node`. Step 7 says when to use ea **The fields.** - `to: ['jane@example.com']` becomes `to: 'jane@example.com'`. A value that is a list with one entry becomes that entry. +- When a helper takes a list of recipients and every caller passes one address, change the parameter to one address and update the callers, so the type keeps a second address out. Never send one email per address in a loop, and never drop the addresses after the first. - `from`, `subject`, `html`, `text`, `replyTo`, `cc`, `bcc`, `headers`, and `tags` keep their names and values. - `attachments` keep `filename`, `content`, `contentType`, and `contentId`. - Each send gets a `templateKey`, as Step 7 says. From b2965cc70daf9be4a38c4dc72e3117262c694abd Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:14:55 +0000 Subject: [PATCH 010/260] fix(skills): handle suppressed recipients and dynamic subjects in migrate-email A moved site now treats recipient_suppressed like a send that went out, a site-built subject becomes a module placeholder so the template hash stays stable, fallbacks use single quotes, and the report warns that idempotency keys don't cross providers. The rules and Step 7 no longer contradict the mapping. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/description.md | 2 +- context/skills/migrate-email/references/7-rewrite.md | 9 +++++---- .../skills/migrate-email/references/resend/mapping.md | 8 +++++--- scripts/lib/tests/migrate-email-skill.test.js | 2 +- 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/context/skills/migrate-email/description.md b/context/skills/migrate-email/description.md index 9eaf4cf41..52937c8b1 100644 --- a/context/skills/migrate-email/description.md +++ b/context/skills/migrate-email/description.md @@ -28,7 +28,7 @@ The plan file `.posthog-email-migration-plan.md` lives at the project root. Step ## Rules -- Change only the call sites that move, and only in Step 7. Leave every site that stays as it is. +- Change send code only in Step 7, and fix it only in Step 8: the sites that move, and the helpers, callers, and tests they need. Leave every site that stays as it is. - Never touch DNS or the {display_name} account. Give the person the records and the links, and let them make the change. - Never remove the {display_name} package or its API key. The report tells the person when to remove them. - Never create, upload, or edit a template in PostHog. A moved local template uploads on its first send. diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index f107996d0..1670e95c9 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -23,7 +23,7 @@ Rewrite each site whose `moves` is `yes` in the plan to send with `posthog-node` Install or upgrade `posthog-node` with the project's package manager, to a version that has `posthog.emails`. -Configure one server-side client for email. Set `migratedFrom` to the provider folder name, once on the client, so PostHog knows which sends a migration moved: +Configure one server-side client for email. Set `migratedFrom` to the provider folder name, such as `resend`, once on the client, so PostHog knows which sends a migration moved: ```js import { PostHog } from 'posthog-node' @@ -31,7 +31,7 @@ import { PostHog } from 'posthog-node' export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { host: process.env.POSTHOG_HOST, secretKey: process.env.POSTHOG_PROJECT_SECRET_API_KEY, - migratedFrom: 'resend', + migratedFrom: '', enableLocalEvaluation: false, }) ``` @@ -59,10 +59,11 @@ For each site that moves, in plan order: - A template stored at the provider becomes a module that exports `subject` and `html`, and `text` when it has one, in an `emails/` folder next to the server code. The site imports it and passes `templateData`. - Install `@react-email/render` with the project's package manager when a site renders a component and the app doesn't have it. - Keep the site's idempotency key, error branches, logging, and return value working as before. Keep the code around the send unchanged where you can. -- Never add a field that the old call didn't set, apart from `templateKey` and `distinctId`. +- `posthog.emails.send` never throws on an API error: it returns `{ data, error }`. When the old call threw on an error, or the code checked an HTTP status, check `error` so the site fails the same way. +- Never add a field that the old call didn't set, apart from `templateKey`, `distinctId`, and the template defaults `mapping.md` names. When a site turns out to need something `mapping.md` keeps on the provider, undo its change, set `moves` to `no` with the reason, and go on. ## Write down -Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each new dependency, and each new env variable name. +Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each site that got a branch for a suppressed recipient, each idempotency key a retry across the deploy could send twice, each new dependency, and each new env variable name. diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 40d54826d..6797511c4 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -18,7 +18,7 @@ This file decides, field by field, whether PostHog can send a Resend call site. | `headers` | `headers` | A header is one PostHog sets itself (`From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Sender`, `Return-Path`, `Auto-Submitted`, `DKIM-Signature`, `Received`, any `Content-*`, `X-PostHog-*`, `X-SES-*`), a name is longer than 126 characters, a value is longer than 870 characters or has a line break or a non-ASCII character, or there are more than 10 | | `tags` | `tags` | A name or value has characters other than ASCII letters, digits, `_`, and `-` or is longer than 256 characters, a name starts with `ph_`, or there are more than 10 | | `attachments` | `attachments` | An attachment uses `path` (a URL Resend fetches), the files can be more than 10 or more than 512 KB in total, or a file type is one mailbox providers block, such as `.exe` | -| `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | The key can hold a space or a non-ASCII character, or be longer than 255 characters. Otherwise the key keeps its value and its meaning: both providers keep a key for 24 hours | +| `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | The key can hold a space or a non-ASCII character, or be longer than 255 characters. Otherwise the key keeps its value, and PostHog keeps it for 24 hours as Resend does. The two providers don't share keys: a retry that runs after the deploy, of a send Resend already took, sends a second email. Note it in the report | | `scheduledAt` / `scheduled_at` | none | Always | | `topicId` / `topic_id` | none | Always | @@ -45,7 +45,7 @@ This file decides, field by field, whether PostHog can send a Resend call site. - `html`, `text`, and `react` content is rendered for one recipient before the send. PostHog sends it as it is. - A `template` site needs the template's content, because the code has only its id. `account.md` says how to get it. - Resend inserts a variable's value as it is. PostHog's Liquid escapes HTML in a value, so `` shows as text. A variable is HTML when the code fills it with markup or with a renderer's output. A variable the app fills with plain values, such as names, numbers, and URLs, renders the same. -- A template that holds anything other than `{{{VAR}}}` and `{{{VAR|fallback}}}` placeholders, such as a section, a loop, or a condition, stays on Resend. +- A template that holds anything other than `{{{VAR}}}` and `{{{VAR|fallback}}}` placeholders, such as a section, a loop, or a condition, stays on Resend. So does a fallback that holds both `'` and `"`. ## Rewrite @@ -68,15 +68,17 @@ How a site that moves is written with `posthog-node`. Step 7 says when to use ea **Templates stored at Resend.** The template becomes a module in the app's code, in the format of the send skill's local template: a `subject` and an `html` string, and a `text` string when the template has one. - `{{{NAME}}}` becomes `{{ variables.NAME }}`. The name keeps its case. -- `{{{NAME|there}}}` becomes `{{ variables.NAME | default: "there" }}`. A variable with a `fallback_value` in the template's definition gets the same `default`. Escape a `"` in the fallback as `\"`. +- `{{{NAME|there}}}` becomes `{{ variables.NAME | default: 'there' }}`. A variable with a `fallback_value` in the template's definition gets the same `default`. Quote a fallback that holds a `'` with `"` instead. Liquid has no escape character in a quoted value. - Liquid's `default` also replaces an empty string, which Resend inserts as it is. When the code can pass an empty string for a variable with a fallback, the email shows the fallback instead. Note it in the report. - The site sends `templateKey`, `subject`, `html`, `text` when there is one, and `templateData` with the site's `variables` object unchanged. - The site's own `subject`, `from`, and `replyTo` win over the template's. When the site has none, use the template's: put its `from` and `replyTo` on the send, and its subject in the module. +- The module's subject is fixed text with placeholders. When the site builds its subject from values, such as `` `Order #${order.id}` ``, write the subject in the module as `Order #{{ variables.ORDER_ID }}` and add each value to `templateData`. Never send a subject that changes per email with `templateData`: PostHog hashes the subject with the template, so each email would upload a new version of the template. - The template's alias, or its name in lowercase with `-` between words, becomes the `templateKey` and the module's file name. **The answer.** posthog-node answers `{ data, error }` like Resend and never throws on an API error. - `data.id` is PostHog's message id. Code that logs it or stores it for the app's own use keeps working. - `error.name` uses Resend's names, so `if (error.name === 'rate_limit_exceeded')` keeps working. `error.message` and `error.statusCode` keep their names. +- Resend takes a send to a suppressed address and drops it later. PostHog refuses it with `error.code` `recipient_suppressed` (name `validation_error`), and refuses the whole send when a `cc` or `bcc` address is suppressed. When the site throws, retries, or reports a failure on any error, add `if (error?.code === 'recipient_suppressed')` before that branch and handle it the way the site handled a send that went out: log it and go on. Note each site that got this branch in the report. **The Resend client.** Keep `new Resend(...)` and its import while any site or other call still uses it. When nothing uses it, remove the import and the client, and keep the `resend` package and its key: the person removes them after the cutover. diff --git a/scripts/lib/tests/migrate-email-skill.test.js b/scripts/lib/tests/migrate-email-skill.test.js index 546138455..2dee17a33 100644 --- a/scripts/lib/tests/migrate-email-skill.test.js +++ b/scripts/lib/tests/migrate-email-skill.test.js @@ -93,7 +93,7 @@ describe('migrate-email skill', () => { expect(markdownFiles(skillDir).map((file) => readFileSync(file, 'utf8')).join('\n')).not.toMatch(/\{\{>|\{display_name\}|\{references\}/); }); - it('moves the supported sites and checks them before it writes the report', async () => { + it('runs the rewrite and verify steps between the key and the report', async () => { outputDir = mkdtempSync(join(tmpdir(), 'migrate-skill-')); const skillDir = await buildSkill('migrate-email-resend', outputDir); From f8f4feace4d6c790cac3dde9734618cb18b8ecf4 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:17:02 +0000 Subject: [PATCH 011/260] fix(skills): keep a suppressed copy address from passing as a sent email Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/resend/mapping.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 6797511c4..d9bbd837d 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -70,7 +70,7 @@ How a site that moves is written with `posthog-node`. Step 7 says when to use ea - `{{{NAME}}}` becomes `{{ variables.NAME }}`. The name keeps its case. - `{{{NAME|there}}}` becomes `{{ variables.NAME | default: 'there' }}`. A variable with a `fallback_value` in the template's definition gets the same `default`. Quote a fallback that holds a `'` with `"` instead. Liquid has no escape character in a quoted value. - Liquid's `default` also replaces an empty string, which Resend inserts as it is. When the code can pass an empty string for a variable with a fallback, the email shows the fallback instead. Note it in the report. -- The site sends `templateKey`, `subject`, `html`, `text` when there is one, and `templateData` with the site's `variables` object unchanged. +- The site sends `templateKey`, `subject`, `html`, `text` when there is one, and `templateData` with the site's `variables` object, plus the subject values below. - The site's own `subject`, `from`, and `replyTo` win over the template's. When the site has none, use the template's: put its `from` and `replyTo` on the send, and its subject in the module. - The module's subject is fixed text with placeholders. When the site builds its subject from values, such as `` `Order #${order.id}` ``, write the subject in the module as `Order #{{ variables.ORDER_ID }}` and add each value to `templateData`. Never send a subject that changes per email with `templateData`: PostHog hashes the subject with the template, so each email would upload a new version of the template. - The template's alias, or its name in lowercase with `-` between words, becomes the `templateKey` and the module's file name. @@ -79,6 +79,7 @@ How a site that moves is written with `posthog-node`. Step 7 says when to use ea - `data.id` is PostHog's message id. Code that logs it or stores it for the app's own use keeps working. - `error.name` uses Resend's names, so `if (error.name === 'rate_limit_exceeded')` keeps working. `error.message` and `error.statusCode` keep their names. -- Resend takes a send to a suppressed address and drops it later. PostHog refuses it with `error.code` `recipient_suppressed` (name `validation_error`), and refuses the whole send when a `cc` or `bcc` address is suppressed. When the site throws, retries, or reports a failure on any error, add `if (error?.code === 'recipient_suppressed')` before that branch and handle it the way the site handled a send that went out: log it and go on. Note each site that got this branch in the report. +- Resend takes a send to a suppressed address and drops it later. PostHog refuses it with `error.code` `recipient_suppressed` (name `validation_error`). When the site sets no `cc` or `bcc`, and it throws, retries, or reports a failure on any error, add `if (error?.code === 'recipient_suppressed')` before that branch and handle it the way the site handled a send that went out: log it and go on. Note each site that got this branch in the report. +- PostHog also refuses the whole send when a `cc` or `bcc` address is suppressed, where Resend still delivered to `to`. Give a site with `cc` or `bcc` no such branch: the error keeps failing the site, and the report says that a suppressed copy address now stops the email. **The Resend client.** Keep `new Resend(...)` and its import while any site or other call still uses it. When nothing uses it, remove the import and the client, and keep the `resend` package and its key: the person removes them after the cutover. From 8dcd459afc9348e0fdbe043ddd6ef7aa2b1e948f Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:18:15 +0000 Subject: [PATCH 012/260] fix(skills): warn that retrying a send with a suppressed copy address uses sending cap Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/resend/mapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index d9bbd837d..e942fa824 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -80,6 +80,6 @@ How a site that moves is written with `posthog-node`. Step 7 says when to use ea - `data.id` is PostHog's message id. Code that logs it or stores it for the app's own use keeps working. - `error.name` uses Resend's names, so `if (error.name === 'rate_limit_exceeded')` keeps working. `error.message` and `error.statusCode` keep their names. - Resend takes a send to a suppressed address and drops it later. PostHog refuses it with `error.code` `recipient_suppressed` (name `validation_error`). When the site sets no `cc` or `bcc`, and it throws, retries, or reports a failure on any error, add `if (error?.code === 'recipient_suppressed')` before that branch and handle it the way the site handled a send that went out: log it and go on. Note each site that got this branch in the report. -- PostHog also refuses the whole send when a `cc` or `bcc` address is suppressed, where Resend still delivered to `to`. Give a site with `cc` or `bcc` no such branch: the error keeps failing the site, and the report says that a suppressed copy address now stops the email. +- PostHog also refuses the whole send when a `cc` or `bcc` address is suppressed, where Resend still delivered to `to`. Give a site with `cc` or `bcc` no such branch: the error keeps failing the site, and the report says that a suppressed copy address now stops the email, and that a job runner that retries the site repeats the refusal, each attempt using the project's sending cap. **The Resend client.** Keep `new Resend(...)` and its import while any site or other call still uses it. When nothing uses it, remove the import and the client, and keep the `resend` package and its key: the person removes them after the cutover. From 154e8f57ffdfe3f0573582fdc2955e211c6c1d38 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:52:56 +0000 Subject: [PATCH 013/260] fix(skills): leave migratedFrom off the posthog-node client in migrate-email posthog-node has no migratedFrom option. The Wizard records the migration on its setup wizard finished event instead. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/7-rewrite.md | 4 +--- context/skills/migrate-email/references/8-verify.md | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index 1670e95c9..259e94eb7 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -23,7 +23,7 @@ Rewrite each site whose `moves` is `yes` in the plan to send with `posthog-node` Install or upgrade `posthog-node` with the project's package manager, to a version that has `posthog.emails`. -Configure one server-side client for email. Set `migratedFrom` to the provider folder name, such as `resend`, once on the client, so PostHog knows which sends a migration moved: +Configure one server-side client for email: ```js import { PostHog } from 'posthog-node' @@ -31,13 +31,11 @@ import { PostHog } from 'posthog-node' export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { host: process.env.POSTHOG_HOST, secretKey: process.env.POSTHOG_PROJECT_SECRET_API_KEY, - migratedFrom: '', enableLocalEvaluation: false, }) ``` {{> email-node-client}} -- A reused client gets `migratedFrom` too. - Put a new client in its own server-only module, next to the provider's client, and import it where the sites send. - Use the env variable names the app already uses for the PostHog token and host. Add each new name, without a value, to the env example file. diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 2bd615b8f..902a38314 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -28,7 +28,7 @@ Skip this part and record `not checked` with the reason when the API is not conf 1. Ask the person whether to send one test email. Say that it sends a real email, and that the first send of a local template uploads it to the PostHog project. When they say no, record `not checked: declined`. 2. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. -3. When the send fails, find its code in `transactional-email-api.md`, tell the person the fix, and record it. Never retry a send yourself. +3. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. 4. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID over the last hour: ```sql From 9cd85f5eee40e774040c8327d28ac0c5363a5029 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:02:16 +0000 Subject: [PATCH 014/260] fix(skills): check that posthog-node has the code form before migrate-email rewrites a site A posthog-node release with posthog.emails can still lack templateKey, local template content, or the extra send fields. The rewrite now checks the installed types for what each moving site needs, and keeps a site on Resend when the latest release lacks it. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/7-rewrite.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index 259e94eb7..9eed3ea1a 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -21,7 +21,13 @@ Rewrite each site whose `moves` is `yes` in the plan to send with `posthog-node` ## Set up the client -Install or upgrade `posthog-node` with the project's package manager, to a version that has `posthog.emails`. +Install or upgrade `posthog-node` to its latest release with the project's package manager. `posthog.emails` alone is not enough: early releases send only a template stored in PostHog, by `templateId`. Check the installed package's types for what the moving sites need: + +- every site: `posthog.emails.send` takes `templateKey` with `subject` and `html` or `text`; +- a template stored at the provider: `templateData` takes the local template's content; +- a site that sets `cc`, `bcc`, `replyTo`, `headers`, `tags`, or `attachments`: the send takes that field. + +When the latest release lacks one of these, change no site that needs it. Mark each such row `moves: no — posthog-node has no yet`, tell the person, and go on with the rest. When no site is left, tick the phase with `none moved` and go to the next step. Configure one server-side client for email: From 41ca66aa8bb64d6db4e1ea454ae1c0651099b327 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:37:20 +0000 Subject: [PATCH 015/260] fix(skills): detect resend over smtp, stop without sends, and record partial imports in migrate-email Step 1 now admits the SMTP host and a framework mailer and needs at least one send; step 3 stops when it finds no site. A suppression import that stops partway stays unticked and lands in the report's "Before cutover" list. A template site needs its content from the person or stays on Resend. The sender setup is inlined into step 4, which keeps the existing `from` domain and records an unverified domain instead of waiting. AGENTS.md says the migrate subcommands run once the wizard runs migrate as a family. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- context/shared/email-sender-setup.md | 15 --------------- .../skills/migrate-email/references/1-detect.md | 11 +++++++---- .../migrate-email/references/3-inventory.md | 8 ++++++++ .../skills/migrate-email/references/4-sender.md | 10 +++++++++- .../migrate-email/references/5-suppressions.md | 2 +- .../skills/migrate-email/references/7-report.md | 4 ++-- .../migrate-email/references/resend/mapping.md | 2 +- 8 files changed, 29 insertions(+), 25 deletions(-) delete mode 100644 context/shared/email-sender-setup.md diff --git a/AGENTS.md b/AGENTS.md index 2d5c0779e..45bd33c7b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,7 +89,7 @@ longer exist — only some keep an alias. | `wizard audit session-replay` | `audit-session-replay` | | `wizard audit web-analytics` | *(wizard-native, not a skill here)* | -**Migrate subcommands**, published as `cliEntries` with `parentCommand: migrate`. Until the wizard runs `migrate` as a family, bare `wizard migrate` keeps running `migrate-statsig`: +**Migrate subcommands**, published as `cliEntries` with `parentCommand: migrate`. They run once the wizard runs `migrate` as a family. Until then, `wizard migrate` stays a flat command that runs `migrate-statsig`, and the wizard rejects a vendor after it: | Subcommand | Backing skill | |---|---| diff --git a/context/shared/email-sender-setup.md b/context/shared/email-sender-setup.md deleted file mode 100644 index bdf95e3c5..000000000 --- a/context/shared/email-sender-setup.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Set up an email sender ---- - -- First check that the PostHog MCP has the sender tools: `integrations-email-create`, `integrations-email-verify-create`, `integrations-domain-connect-check-retrieve`, and `integrations-domain-connect-apply-url-create`. When they are missing, go to the last bullet of this step. -- When the `setting-up-an-email-domain` skill is available, follow it. It covers the details. -- Ask which domain to send from. Recommend a subdomain such as `mail.example.com`. Use the person's own domain, never a free mailbox domain such as gmail.com. -- Never create a sender for an address that already has one: creating it again marks it unverified. For an existing unverified sender, skip to its records. -- Create the sender with `integrations-email-create`, then get its DNS records with `integrations-email-verify-create`. -- PostHog never writes DNS. Call `integrations-domain-connect-check-retrieve` with the domain. When `supported` is true, give the person the URL from `integrations-domain-connect-apply-url-create`: they approve the records at their DNS host. Otherwise, give them the records that are not `success` as a table with type, name, value, and priority. -- Always include both SPF records, merged into an existing `v=spf1` record when there is one. Never add a second `_dmarc` record when the domain already has one. -- Call `integrations-email-verify-create` again after the records are published, at least a minute apart. `success` means done. `failed` means fix the records, then verify again. After about 15 minutes of `pending` with every record published, stop and tell the person that DNS is still propagating and they can ask you to check again later. -- A 403 that says the person lacks permissions in the project means a project admin must verify the sender. Do not retry. -- **When the sender tools are missing or refused**, the agent setup for sender domains is not available to this person yet. Do not try other integration tools. Ask the person to verify a sender in PostHog: Workflows, then Channels, then add an email sender on their domain and follow the DNS steps (https://posthog.com/docs/workflows/configure-channels). Wait until they confirm that the sender shows as verified, then continue. - diff --git a/context/skills/migrate-email/references/1-detect.md b/context/skills/migrate-email/references/1-detect.md index 94881bc9c..fd4a47d30 100644 --- a/context/skills/migrate-email/references/1-detect.md +++ b/context/skills/migrate-email/references/1-detect.md @@ -15,19 +15,22 @@ Discovery only. Do not change any file. ## Procedure -Read the provider's `sdk-reference.md`. It lists the provider's packages, imports, clients, and HTTP host, and the packages that look related but are not the provider. +Read the provider's `sdk-reference.md`. It lists the provider's packages, imports, clients, send calls, HTTP host, SMTP host, and framework mailers, and the packages that look related but are not the provider. The provider is in this project when at least one of these is true: - Its package is in a dependency manifest, such as `package.json`, `requirements.txt`, `pyproject.toml`, `Gemfile`, `composer.json`, or `go.mod`. - Source code imports it or creates its client. - Source code calls its HTTP host. +- Source code, mail config, or an example env file names its SMTP host or its framework mailer. -Search the source code, not only the manifest: a package without a call site is not a migration. Skip `node_modules`, build output, and lockfiles. +Search the source code, not only the manifest. Skip `node_modules`, build output, and lockfiles. + +The migration needs at least one send: a send call, a request to the send route, or mail through the SMTP host or the framework mailer. A package without a send is not a migration, and neither are calls that only read contacts, domains, or an email's status. A rendering package alone, such as `@react-email/components`, is not the provider. It only tells you how some emails are rendered. -When you find nothing, stop before any change: +When you find no send, stop before any change: ``` [ABORT] no email provider sends found @@ -35,4 +38,4 @@ When you find nothing, stop before any change: Do not widen the search to other email providers. That outcome is correct, not a failure to work around. -When you find the provider, note each file that uses it for Step 3, and continue. +When you find a send, note each file that uses the provider for Step 3, and continue. diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index 884e90052..174ffc477 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -33,12 +33,20 @@ For each site, read the surrounding code and record: Also list every other call to the provider that is not a send, such as reading an email's status, contacts, or domains. These calls stay on the provider. Note what each one does, because a site whose code reads the status back stays on the provider too. +When you find no site, stop before you write the plan file: + +``` +[ABORT] no email provider sends found +``` + ## Classify each site Go through `mapping.md` field by field. A site **moves** when PostHog can send every field it sets. A site **stays** on the provider when any one field or feature keeps it there: record that field or feature as the reason. Never plan to drop a field. When the code passes a value you can't read, such as a list of recipients built at run time, follow it to its callers. When you still can't tell, the site stays, and the reason says what you could not check. +A `template` site needs the template's content to be classified. Ask the person once for a copy of every template the sites send, from the provider's dashboard, and never write it into the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. + ## Write the plan file Write `.posthog-email-migration-plan.md` at the project root with three sections. Never write an email address of a recipient into it. A `from` address is fine. diff --git a/context/skills/migrate-email/references/4-sender.md b/context/skills/migrate-email/references/4-sender.md index 87a968c06..e5901d7d7 100644 --- a/context/skills/migrate-email/references/4-sender.md +++ b/context/skills/migrate-email/references/4-sender.md @@ -31,7 +31,15 @@ Read the provider's `account.md` first. It lists the records the provider keeps Send from the domain of the existing `from` address, so the emails keep their sender. Ask for another domain only when the person wants one. -{{> email-sender-setup}} +- First check that the PostHog MCP has the sender tools: `integrations-email-create`, `integrations-email-verify-create`, `integrations-domain-connect-check-retrieve`, and `integrations-domain-connect-apply-url-create`. When they are missing, go to the last bullet. +- When the `setting-up-an-email-domain` skill is available, read it for the details of the records. Where it differs from this step, this step wins. +- Never create a sender for an address that already has one: creating it again marks it unverified. For an existing unverified sender, skip to its records. +- Create the sender with `integrations-email-create`, then get its DNS records with `integrations-email-verify-create`. +- PostHog never writes DNS. Call `integrations-domain-connect-check-retrieve` with the domain. When `supported` is true, give the person the URL from `integrations-domain-connect-apply-url-create`: they approve the records at their DNS host. Otherwise, give them the records that are not `success` as a table with type, name, value, and priority. +- Always include both SPF records, merged into an existing `v=spf1` record when there is one. Never add a second `_dmarc` record when the domain already has one. +- Call `integrations-email-verify-create` again after the records are published, at least a minute apart. `success` means verified. `failed` means fix the records, then verify again. After about 15 minutes of `pending` with every record published, tell the person that DNS is still propagating and that they can ask you to check again later, record the domain as not verified, and continue. +- A 403 that says the person lacks permissions in the project means a project admin must verify the sender. Do not retry: record the domain as not verified, and continue. +- When the sender tools are missing or refused, do not try other integration tools. Ask the person to add a sender on the domain in PostHog: Workflows, then Channels, then add an email sender, and follow the DNS steps (https://posthog.com/docs/workflows/configure-channels). Record the domain as not verified unless they confirm it shows as verified, and continue. ## Write down diff --git a/context/skills/migrate-email/references/5-suppressions.md b/context/skills/migrate-email/references/5-suppressions.md index 02471b58b..916a21439 100644 --- a/context/skills/migrate-email/references/5-suppressions.md +++ b/context/skills/migrate-email/references/5-suppressions.md @@ -36,4 +36,4 @@ Read the provider's `account.md`. It says how to export the list, which entries ## Write down -Tick the phase in the plan file: `- [x] suppressions — / imported`. When the list is empty, write `- [x] suppressions — empty list`. When the person has no export and no key, write `- [ ] suppressions — not imported: `. +Tick the phase in the plan file only when every entry is imported: `- [x] suppressions — / imported`. When the list is empty, write `- [x] suppressions — empty list`. When the import stopped partway, write `- [ ] suppressions — / imported: `. When the person has no export and no key, write `- [ ] suppressions — not imported: `. diff --git a/context/skills/migrate-email/references/7-report.md b/context/skills/migrate-email/references/7-report.md index 6869e754e..eaa7a69ee 100644 --- a/context/skills/migrate-email/references/7-report.md +++ b/context/skills/migrate-email/references/7-report.md @@ -51,7 +51,7 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- ## Before cutover - + ## Summary ``` @@ -72,7 +72,7 @@ suppressions_ready: true - `sites_rewritten`: the sites this run changed to send with PostHog. This version changes none, so it is `0`. - `sites_left`: the sites that stay on the provider. - `dns_ready`: `true` when every sending domain has a verified sender. -- `suppressions_ready`: `true` when the suppression list was imported or was empty. +- `suppressions_ready`: `true` when every entry of the suppression list was imported, or the list was empty. Sites that are ready to move count in `sites_found` only. diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 097d84c87..8a27a39c7 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -12,7 +12,7 @@ This file decides, field by field, whether PostHog can send a Resend call site. | `html` | `html` | Never | | `text` | `text` | Never | | `react` | `html`, rendered in the app | Never. The app renders the component | -| `template` | a local template in the app's code | The template uses syntax beyond variables and fallbacks | +| `template` | a local template in the app's code | Its content can't be read, it uses syntax beyond variables and fallbacks, or the app fills a variable with HTML | | `cc`, `bcc` | `cc`, `bcc` | An entry carries a name, such as `Jane `, or there are more than 10 | | `replyTo` / `reply_to` | `replyTo` / `reply_to`, as a list | An entry carries a name, such as `Jane `, there are more than 10, or the code builds the value at run time and you cannot tell that it holds bare addresses only. A single address moves as a list of one | | `headers` | `headers` | A header is one PostHog sets itself (`From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Sender`, `Return-Path`, `Auto-Submitted`, `DKIM-Signature`, `Received`, any `Content-*`, `X-PostHog-*`, `X-SES-*`), a name is longer than 126 characters, a value is longer than 870 characters or has a line break or a non-ASCII character, or there are more than 10 | From 0e526b923515d9b0ba3a765c6498d6ae3b04f2b8 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:37:20 +0000 Subject: [PATCH 016/260] refactor(scripts): ship variant references through the local reference loop The selected variant's `references//` files now go through the same loop as the root reference files, so the separate copy helper is gone. The partial expander drops the indentation it gained for the sender partial, which nothing includes any more, and the bundle test drops the migrate-statsig case that guarded nothing. Co-Authored-By: Claude Opus 5.5 --- scripts/lib/skill-generator.js | 69 ++++++------------- scripts/lib/tests/migrate-email-skill.test.js | 15 ++-- scripts/lib/tests/partial-includes.test.js | 8 --- 3 files changed, 27 insertions(+), 65 deletions(-) diff --git a/scripts/lib/skill-generator.js b/scripts/lib/skill-generator.js index 35eb4697e..c5b355059 100644 --- a/scripts/lib/skill-generator.js +++ b/scripts/lib/skill-generator.js @@ -55,18 +55,16 @@ function loadYaml(configPath) { // A line that is exactly `{{> name}}` is replaced at build time with the body // of `/shared/name.md` (frontmatter stripped), so shared prose like // the MCP tool-calling grammar lives in one canonical file and every skill that -// includes it stays in sync. The directive's indentation applies to every line -// of the partial, so a partial can nest under a step. -const PARTIAL_DIRECTIVE = /^([ \t]*)\{\{>\s*([a-z0-9-]+)\s*\}\}[ \t]*$/gm; +// includes it stays in sync. +const PARTIAL_DIRECTIVE = /^[ \t]*\{\{>\s*([a-z0-9-]+)\s*\}\}[ \t]*$/gm; function expandPartials(body, configDir) { - return body.replace(PARTIAL_DIRECTIVE, (_match, indent, name) => { + return body.replace(PARTIAL_DIRECTIVE, (_match, name) => { const partialPath = path.join(configDir, 'shared', `${name}.md`); if (!fs.existsSync(partialPath)) { throw new Error(`Partial include {{> ${name}}} references missing file ${partialPath}`); } - const partial = matter(fs.readFileSync(partialPath, 'utf8')).content.trim(); - return partial.replace(/^(?=.)/gm, indent); + return matter(fs.readFileSync(partialPath, 'utf8')).content.trim(); }); } @@ -596,29 +594,12 @@ function generateFrontmatter(skill, version) { return '---\n' + yaml.dump(frontmatter) + '---\n\n'; } -/** - * Copy the markdown files of a variant's own folder, `references//`, - * into the bundle. A group keeps what differs per vendor or platform there, so - * each bundle ships only its own variant's files. Returns their listing entries. - */ -function copyVariantReferences({ sourceDir, targetDir, variantId, configDir }) { - if (!fs.existsSync(sourceDir)) return []; - - const files = fs.readdirSync(sourceDir, { withFileTypes: true }) +function markdownReferenceNames(dir, prefix) { + if (!fs.existsSync(dir)) return []; + return fs.readdirSync(dir, { withFileTypes: true }) .filter(entry => entry.isFile() && entry.name.endsWith('.md')) - .sort((a, b) => a.name.localeCompare(b.name)); - fs.mkdirSync(targetDir, { recursive: true }); - - return files.map(file => { - const parsed = matter(fs.readFileSync(path.join(sourceDir, file.name), 'utf8')); - const body = expandPartials(parsed.content, configDir).replace(/^\n+/, '').replace(/\s+$/, ''); - fs.writeFileSync(path.join(targetDir, file.name), body, 'utf8'); - const heading = body.match(/^#\s+(.+)$/m)?.[1]; - return { - filename: `${variantId}/${file.name}`, - description: parsed.data.description || heading || file.name, - }; - }); + .map(entry => path.posix.join(prefix, entry.name)) + .sort((a, b) => a.localeCompare(b)); } /** @@ -694,21 +675,22 @@ async function generateSkill({ // Group config injects a shared `preamble`; per-file `next_step` frontmatter drives continuation links. const sourceReferencesDir = path.join(configDir, 'skills', ...skill._group.split('/'), 'references'); if (fs.existsSync(sourceReferencesDir)) { - const localReferences = fs.readdirSync(sourceReferencesDir, { withFileTypes: true }) - .filter(entry => entry.isFile() && entry.name.endsWith('.md')) - .sort((a, b) => a.name.localeCompare(b.name)); + const localReferences = [ + ...markdownReferenceNames(sourceReferencesDir, ''), + ...markdownReferenceNames(path.join(sourceReferencesDir, skill._shortId), skill._shortId), + ]; const refsConfig = skill._references || {}; for (const reference of localReferences) { - const sourcePath = path.join(sourceReferencesDir, reference.name); + const sourcePath = path.join(sourceReferencesDir, reference); const parsed = matter(fs.readFileSync(sourcePath, 'utf8')); const nextFile = parsed.data.next_step; const isWorkflowStep = 'next_step' in parsed.data; let body = expandPartials(parsed.content, configDir).replace(/^\n+/, '').replace(/\s+$/, ''); const headingMatch = body.match(/^#\s+(.+)$/m); - const displayTitle = parsed.data.title || headingMatch?.[1] || reference.name; - const displayDescription = parsed.data.description || headingMatch?.[1] || reference.name; + const displayTitle = parsed.data.title || headingMatch?.[1] || reference; + const displayDescription = parsed.data.description || headingMatch?.[1] || reference; if (nextFile) { if (refsConfig.preamble && headingMatch) { @@ -726,31 +708,22 @@ async function generateSkill({ ? `---\n${yaml.dump(emittedFrontmatter, { lineWidth: -1 })}---\n\n${body}` : body; - fs.writeFileSync( - path.join(referencesDir, reference.name), - fileContent, - 'utf8' - ); + const targetPath = path.join(referencesDir, reference); + fs.mkdirSync(path.dirname(targetPath), { recursive: true }); + fs.writeFileSync(targetPath, fileContent, 'utf8'); references.push({ - filename: reference.name, + filename: reference, description: displayDescription, }); if (isWorkflowStep) { workflowSteps.push({ - filename: reference.name, + filename: reference, title: displayTitle, }); } } - - references.push(...copyVariantReferences({ - sourceDir: path.join(sourceReferencesDir, skill._shortId), - targetDir: path.join(referencesDir, skill._shortId), - variantId: skill._shortId, - configDir, - })); } // Helper to process a doc entry (string URL or {url, title} object). diff --git a/scripts/lib/tests/migrate-email-skill.test.js b/scripts/lib/tests/migrate-email-skill.test.js index 8ffca7b6e..14044d5ef 100644 --- a/scripts/lib/tests/migrate-email-skill.test.js +++ b/scripts/lib/tests/migrate-email-skill.test.js @@ -66,17 +66,14 @@ describe('migrate-email skill', () => { if (outputDir) rmSync(outputDir, { recursive: true, force: true }); }); - it.each(['migrate-email-resend', 'migrate-statsig'])( - 'builds %s as a bundle whose every reference path resolves', - async (skillId) => { - outputDir = mkdtempSync(join(tmpdir(), 'migrate-skill-')); + it('builds migrate-email-resend as a bundle whose every reference path resolves', async () => { + outputDir = mkdtempSync(join(tmpdir(), 'migrate-skill-')); - const skillDir = await buildSkill(skillId, outputDir); + const skillDir = await buildSkill('migrate-email-resend', outputDir); - expect(readFileSync(join(skillDir, 'SKILL.md'), 'utf8')).toMatch(new RegExp(`^---\\nname: ${skillId}\\n`)); - expect(unresolvedReferences(skillDir)).toEqual([]); - }, - ); + expect(readFileSync(join(skillDir, 'SKILL.md'), 'utf8')).toMatch(/^---\nname: migrate-email-resend\n/); + expect(unresolvedReferences(skillDir)).toEqual([]); + }); it('bundles the transactional email docs and the Resend files', async () => { outputDir = mkdtempSync(join(tmpdir(), 'migrate-skill-')); diff --git a/scripts/lib/tests/partial-includes.test.js b/scripts/lib/tests/partial-includes.test.js index 3741c14a3..5ebaa8e66 100644 --- a/scripts/lib/tests/partial-includes.test.js +++ b/scripts/lib/tests/partial-includes.test.js @@ -42,14 +42,6 @@ describe('expandPartials', () => { expect(out).toContain('After.'); }); - it("indents every line of the partial as far as the directive, so it nests in a step's list", () => { - writeFileSync(join(tmpDir, 'shared', 'sender.md'), '---\ntitle: Sender\n---\n\n- First bullet.\n- Second bullet.\n'); - - const out = expandPartials('STEP 3: Set up a sender.\n {{> sender}}\n\nSTEP 4: Send.', tmpDir); - - expect(out).toBe('STEP 3: Set up a sender.\n - First bullet.\n - Second bullet.\n\nSTEP 4: Send.'); - }); - it('throws when the referenced partial does not exist', () => { expect(() => expandPartials('{{> missing-partial}}', tmpDir)).toThrow(/missing-partial/); }); From 8c841cdfa7eff05a74c65c3754680e333de34808 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:44:30 +0000 Subject: [PATCH 017/260] fix(skills): tie migrate-email's test send to its own events and report every behaviour change Step 8 checks that the app sends to the MCP's project, notes the start of the test, and counts only events since then whose workflow matches the send. It compares typecheck errors with a baseline step 7 takes before it changes code. A template's content waits in a temporary file for step 7 instead of in memory, an HTML fallback keeps a template on Resend, and a derived templateKey is normalized and unique. The report lists each suppressed-recipient branch, copy-address refusal, and cross-provider idempotency risk, and reminds the person to delete the full-access Resend key. The posthog-node client setup is inlined into step 7, and description.md says this skill wins over the general moving guide. Co-Authored-By: Claude Opus 5.5 --- context/shared/email-node-client.md | 7 ------- context/skills/migrate-email/description.md | 2 +- .../migrate-email/references/3-inventory.md | 2 +- .../migrate-email/references/7-rewrite.md | 9 ++++++--- .../migrate-email/references/8-verify.md | 19 ++++++++++--------- .../migrate-email/references/9-report.md | 6 +++--- .../references/resend/account.md | 6 +++--- .../references/resend/mapping.md | 6 +++--- 8 files changed, 27 insertions(+), 30 deletions(-) delete mode 100644 context/shared/email-node-client.md diff --git a/context/shared/email-node-client.md b/context/shared/email-node-client.md deleted file mode 100644 index 3f26ccb42..000000000 --- a/context/shared/email-node-client.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: Configure the posthog-node client for email ---- - -- Reuse the app's existing `posthog-node` client when it has one, and add `secretKey`. Keep `enableLocalEvaluation: false` unless the key also has `feature_flag:read` and the app uses local evaluation. -- When the project token or the host is not configured yet, get the token from the PostHog MCP `projects-get` tool (`api_token`). The host is `https://us.i.posthog.com` for US Cloud and `https://eu.i.posthog.com` for EU Cloud. Ask the person which one when you can't tell. -- When `host` is a reverse proxy or a self-hosted instance, also set `appHost` to the PostHog app URL, such as `https://us.posthog.com`. posthog-node never sends the secret key to a proxy, and without `appHost` the send fails with `missing_app_host`. diff --git a/context/skills/migrate-email/description.md b/context/skills/migrate-email/description.md index 52937c8b1..9f7b47bbe 100644 --- a/context/skills/migrate-email/description.md +++ b/context/skills/migrate-email/description.md @@ -54,4 +54,4 @@ Outside the Wizard, skip the `[STATUS]` lines, and tell the person why you stopp `transactional-emails.md` is the transactional email overview. It covers how to create a transactional email and its API key, idempotency, and the error codes. `api.md` covers the send route, including content from your code, and the checks of a send. -When the `sending-transactional-emails` skill is available, read it too. Its `moving-from-other-providers.md` moves any provider's sends to a PostHog template. This skill adds what is specific to {display_name}: it finds every send, sets up the sender next to {display_name}'s DNS records, imports {display_name}'s suppression list, and hands over the key. +When the `sending-transactional-emails` skill is available, read it for the PostHog side of a send. Its `moving-from-other-providers.md` moves sends to a template stored in PostHog. This skill moves {display_name}'s sends to `posthog-node` with the content in the app's code instead. Where the two disagree, this skill's steps win. diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index 4a27f1b2e..6d7521f26 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -45,7 +45,7 @@ Go through `mapping.md` field by field. A site **moves** when PostHog can send e When the code passes a value you can't read, such as a list of recipients built at run time, follow it to its callers. When you still can't tell, the site stays, and the reason says what you could not check. -A `template` site needs the template's content to be classified. Read the provider's `account.md`, and ask the person once for every template the sites send: copy from the dashboard, or read through the API. Keep the content for Step 7, and never write it into the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. +A `template` site needs the template's content to be classified. Read the provider's `account.md`, and ask the person once for every template the sites send: copy from the dashboard, or read through the API. Save each template's content for Step 7 in a file in the system's temporary folder, never in the repository or the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. ## Write the plan file diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index 9eed3ea1a..57a037094 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -18,6 +18,7 @@ Rewrite each site whose `moves` is `yes` in the plan to send with `posthog-node` - Change only the sites whose `moves` is `yes`. Never change a site that stays, and never change a line that a site that stays still needs. - When no site moves, tick the phase in the plan with `none moved` and go to the next step. +- Run the project's typecheck, such as its `typecheck` script or `tsc --noEmit`, or its build when it has no typecheck, and keep its errors: Step 8 compares with them. ## Set up the client @@ -41,7 +42,9 @@ export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { }) ``` -{{> email-node-client}} +- Reuse the app's existing `posthog-node` client when it has one, and add `secretKey`. Keep `enableLocalEvaluation: false` unless the key also has `feature_flag:read` and the app uses local evaluation. +- When the project token or the host is not configured yet, get the token from the PostHog MCP `projects-get` tool (`api_token`). The host is `https://us.i.posthog.com` for US Cloud and `https://eu.i.posthog.com` for EU Cloud. Ask the person which one when you can't tell. +- When `host` is a reverse proxy or a self-hosted instance, also set `appHost` to the PostHog app URL, such as `https://us.posthog.com`. posthog-node never sends the secret key to a proxy, and without `appHost` the send fails with `missing_app_host`. - Put a new client in its own server-only module, next to the provider's client, and import it where the sites send. - Use the env variable names the app already uses for the PostHog token and host. Add each new name, without a value, to the env example file. @@ -60,7 +63,7 @@ For each site that moves, in plan order: - Rewrite the call as the provider's `mapping.md` says, for the site's content form: `html` and `text` content, a component the app renders, or a template stored at the provider. - Give each send a `templateKey` that names the kind of email, such as `welcome` or `password-reset`, with letters, digits, `-`, and `_` only. Two sites that send the same email share a key. A template stored at the provider keeps the key `mapping.md` gives it. -- A template stored at the provider becomes a module that exports `subject` and `html`, and `text` when it has one, in an `emails/` folder next to the server code. The site imports it and passes `templateData`. +- A template stored at the provider becomes a module that exports `subject` and `html`, and `text` when it has one, in an `emails/` folder next to the server code. Write it from the file Step 3 saved, never from memory, and delete that file once the module is written. The site imports the module and passes `templateData`. - Install `@react-email/render` with the project's package manager when a site renders a component and the app doesn't have it. - Keep the site's idempotency key, error branches, logging, and return value working as before. Keep the code around the send unchanged where you can. - `posthog.emails.send` never throws on an API error: it returns `{ data, error }`. When the old call threw on an error, or the code checked an HTTP status, check `error` so the site fails the same way. @@ -70,4 +73,4 @@ When a site turns out to need something `mapping.md` keeps on the provider, undo ## Write down -Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each site that got a branch for a suppressed recipient, each idempotency key a retry across the deploy could send twice, each new dependency, and each new env variable name. +Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each site that got a branch for a suppressed recipient, each site with `cc` or `bcc` that a suppressed copy address now stops, each idempotency key a retry across the deploy could send twice, each new dependency, and each new env variable name. diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 902a38314..815353510 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -16,7 +16,7 @@ Check that the app still builds, its tests still pass, and one moved email reach ## Build and tests -- Run the project's typecheck, such as its `typecheck` script or `tsc --noEmit`, or its build when it has no typecheck. Fix each error in a line you changed. An error in a file you didn't change was there before: note it, and leave it. +- Run the project's typecheck, such as its `typecheck` script or `tsc --noEmit`, or its build when it has no typecheck. Fix each error that is not in the list Step 7 kept, in any file: the rewrite caused it. An error in that list was there before: note it, and leave it. - Run the tests that cover the files you changed. A test that mocks the provider's client or intercepts its HTTP requests for a moved site now mocks `posthog.emails.send` and asserts on the fields it gets, with the same expected values. Never turn a PostHog send back into the provider's request shape to keep an old assertion. Never delete or skip a test. - Search the changed files for the provider's calls: a moved site has none left, and each moved site has one `posthog.emails.send`. @@ -26,20 +26,21 @@ The chain to prove: PostHog sends the email, records its engagement on the perso Skip this part and record `not checked` with the reason when the API is not confirmed on, no sender is verified, or `POSTHOG_PROJECT_SECRET_API_KEY` is not set. -1. Ask the person whether to send one test email. Say that it sends a real email, and that the first send of a local template uploads it to the PostHog project. When they say no, record `not checked: declined`. -2. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. -3. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. -4. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID over the last hour: +1. Check that the app sends to the MCP's project: compare the project token the app reads, from its env file, with `api_token` from the PostHog MCP `projects-get` tool. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. +2. Ask the person whether to send one test email. Say that it sends a real email, and that the first send of a local template uploads it to the PostHog project. When they say no, record `not checked: declined`. +3. Note the current time in UTC as the start of the test. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. +4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. +5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test: ```sql - SELECT event, timestamp FROM events - WHERE distinct_id = '' AND timestamp > now() - INTERVAL 1 HOUR + SELECT event, timestamp, properties.$workflow_id AS workflow FROM events + WHERE distinct_id = '' AND timestamp >= '' ORDER BY timestamp ``` -5. The chain holds when the result has `$workflows_email_sent`, an engagement event such as `$workflows_email_delivered` or `$workflows_email_opened`, and at least one product event of the app. Delivery events arrive after the provider reports back: when only the send shows, wait a minute and run the query once more. +6. The chain holds when the result has a `$workflows_email_sent`, an engagement event such as `$workflows_email_delivered` or `$workflows_email_opened` with the same `workflow`, and at least one product event of the app. An event from before the start of the test belongs to another email. Delivery events arrive after the provider reports back: when only the send shows, wait a minute and run the query once more. -When the MCP has no SQL tool, ask the person to open their person in PostHog and tell you which of the three they see. +When the MCP has no SQL tool, ask the person to open their person in PostHog and tell you which of the three they see after the start of the test. Never write the address or the distinct ID into a file. diff --git a/context/skills/migrate-email/references/9-report.md b/context/skills/migrate-email/references/9-report.md index 6543ecfe6..5462c62b8 100644 --- a/context/skills/migrate-email/references/9-report.md +++ b/context/skills/migrate-email/references/9-report.md @@ -29,7 +29,7 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- ", or "Stays on : ".> - + ## Other calls @@ -59,11 +59,11 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- The moved sites send through PostHog as soon as this code is deployed. Everything in this list has to be done before that deploy. - + ## After cutover - + ## Summary ``` diff --git a/context/skills/migrate-email/references/resend/account.md b/context/skills/migrate-email/references/resend/account.md index f4c38602e..93146a650 100644 --- a/context/skills/migrate-email/references/resend/account.md +++ b/context/skills/migrate-email/references/resend/account.md @@ -20,7 +20,7 @@ A domain verified at Resend carries these records. Keep all of them until the cu ## Full-access key -The app's own Resend key is usually a sending-only key, and it can't read templates or the suppression list. When the person chooses the API over the dashboard, ask them to create a full-access key in Resend, store it in `RESEND_FULL_ACCESS_API_KEY` in the git-ignored env file, and delete the key in Resend after the migration. Never print the key, and never write it into another file. +The app's own Resend key is usually a sending-only key, and it can't read templates or the suppression list. When the person chooses the API over the dashboard, ask them to create a full-access key in Resend, store it in `RESEND_FULL_ACCESS_API_KEY` in the git-ignored env file, and note in the plan that the run created it. The report tells the person to delete it. Never print the key, and never write it into another file. ## Template content @@ -30,7 +30,7 @@ A site that sends a template stored at Resend needs the template's content. **Read from the API.** `GET https://api.resend.com/templates/{id or alias}` with `Authorization: Bearer $RESEND_FULL_ACCESS_API_KEY`. The answer holds `alias`, `name`, `subject`, `from`, `reply_to`, `html`, `text`, and `variables`, a list of `{ key, type, fallback_value }`. -The content goes only into the template module the rewrite writes. Never write it into the plan or the report. +The content goes only into the temporary file Step 3 saves and the template module the rewrite writes. Never write it into the plan or the report. ## Suppression list @@ -43,7 +43,7 @@ Resend suppresses an address after a hard bounce or a spam complaint, and keeps - The answer is `{ "object": "list", "has_more": , "data": [{ "id", "email", "origin", "source_id", "created_at" }] }`. - Page with `after=` until `has_more` is `false`. - Resend allows 10 requests per second per team. Wait and retry on `429`. -- A sending-only key can't read the list. Use the full-access key below. +- A sending-only key can't read the list. Use the full-access key above. **Map each entry.** diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index e942fa824..3820a6900 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -45,7 +45,7 @@ This file decides, field by field, whether PostHog can send a Resend call site. - `html`, `text`, and `react` content is rendered for one recipient before the send. PostHog sends it as it is. - A `template` site needs the template's content, because the code has only its id. `account.md` says how to get it. - Resend inserts a variable's value as it is. PostHog's Liquid escapes HTML in a value, so `` shows as text. A variable is HTML when the code fills it with markup or with a renderer's output. A variable the app fills with plain values, such as names, numbers, and URLs, renders the same. -- A template that holds anything other than `{{{VAR}}}` and `{{{VAR|fallback}}}` placeholders, such as a section, a loop, or a condition, stays on Resend. So does a fallback that holds both `'` and `"`. +- A template that holds anything other than `{{{VAR}}}` and `{{{VAR|fallback}}}` placeholders, such as a section, a loop, or a condition, stays on Resend. So does a fallback that holds both `'` and `"`, and a fallback that holds HTML, such as a link: Liquid escapes the fallback too, so the markup shows as text. ## Rewrite @@ -72,8 +72,8 @@ How a site that moves is written with `posthog-node`. Step 7 says when to use ea - Liquid's `default` also replaces an empty string, which Resend inserts as it is. When the code can pass an empty string for a variable with a fallback, the email shows the fallback instead. Note it in the report. - The site sends `templateKey`, `subject`, `html`, `text` when there is one, and `templateData` with the site's `variables` object, plus the subject values below. - The site's own `subject`, `from`, and `replyTo` win over the template's. When the site has none, use the template's: put its `from` and `replyTo` on the send, and its subject in the module. -- The module's subject is fixed text with placeholders. When the site builds its subject from values, such as `` `Order #${order.id}` ``, write the subject in the module as `Order #{{ variables.ORDER_ID }}` and add each value to `templateData`. Never send a subject that changes per email with `templateData`: PostHog hashes the subject with the template, so each email would upload a new version of the template. -- The template's alias, or its name in lowercase with `-` between words, becomes the `templateKey` and the module's file name. +- The module's subject is fixed text with placeholders. When the site builds its subject from values, such as `` `Order #${order.id}` ``, write the subject in the module as `Order #{{ variables.ORDER_ID }}` and add each value to `templateData`. Never send a subject that changes per email with `templateData`: posthog-node hashes a local template's subject and content, so each email would upload a new version of the template. A send without `templateData` sends rendered content and uploads nothing. +- The template's alias, or its name when it has no alias, becomes the `templateKey` and the module's file name: in lowercase, with each run of characters other than letters, digits, `-`, and `_` replaced by one `-`, and no `-` at either end. When two templates get the same key, add `-2`, `-3`, and so on to the later ones. **The answer.** posthog-node answers `{ data, error }` like Resend and never throws on an API error. From 4ad8c6e8a7b89c5d8673442af13deb03172ee968 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:49:59 +0000 Subject: [PATCH 018/260] fix(skills): let migrate-email move on when DNS waits and read templates from files Step 4 records a domain as not verified, with its records or Domain Connect link, when the person can't publish them during the run. Step 3 asks the person to save each template from the dashboard to a file outside the repository and reads it, since the Wizard can't take pasted HTML. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/3-inventory.md | 2 +- context/skills/migrate-email/references/4-sender.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index 174ffc477..160f32877 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -45,7 +45,7 @@ Go through `mapping.md` field by field. A site **moves** when PostHog can send e When the code passes a value you can't read, such as a list of recipients built at run time, follow it to its callers. When you still can't tell, the site stays, and the reason says what you could not check. -A `template` site needs the template's content to be classified. Ask the person once for a copy of every template the sites send, from the provider's dashboard, and never write it into the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. +A `template` site needs the template's content to be classified. Ask the person once to copy every template the sites send from the provider's dashboard into files outside the repository, and to tell you where they saved them. Read those files, and never write the content into the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. ## Write the plan file diff --git a/context/skills/migrate-email/references/4-sender.md b/context/skills/migrate-email/references/4-sender.md index e5901d7d7..10dee3458 100644 --- a/context/skills/migrate-email/references/4-sender.md +++ b/context/skills/migrate-email/references/4-sender.md @@ -38,6 +38,7 @@ Send from the domain of the existing `from` address, so the emails keep their se - PostHog never writes DNS. Call `integrations-domain-connect-check-retrieve` with the domain. When `supported` is true, give the person the URL from `integrations-domain-connect-apply-url-create`: they approve the records at their DNS host. Otherwise, give them the records that are not `success` as a table with type, name, value, and priority. - Always include both SPF records, merged into an existing `v=spf1` record when there is one. Never add a second `_dmarc` record when the domain already has one. - Call `integrations-email-verify-create` again after the records are published, at least a minute apart. `success` means verified. `failed` means fix the records, then verify again. After about 15 minutes of `pending` with every record published, tell the person that DNS is still propagating and that they can ask you to check again later, record the domain as not verified, and continue. +- When the person can't publish the records during this run, such as when another team owns DNS, record the domain as not verified with its records or its Domain Connect link, and continue. - A 403 that says the person lacks permissions in the project means a project admin must verify the sender. Do not retry: record the domain as not verified, and continue. - When the sender tools are missing or refused, do not try other integration tools. Ask the person to add a sender on the domain in PostHog: Workflows, then Channels, then add an email sender, and follow the DNS steps (https://posthog.com/docs/workflows/configure-channels). Record the domain as not verified unless they confirm it shows as verified, and continue. From 8452a8265f8601b8eb53b425bf187b997abefbf8 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:53:20 +0000 Subject: [PATCH 019/260] fix(skills): pin migrate-email's test start to the database clock and keep template files traceable Step 8 takes the start of the test from `execute-sql` and compares Unix timestamps, so the project's timezone can't shift the window. The plan lists each saved template file, step 7 reads the module from it, and step 9 deletes every listed file. A derived templateKey falls back to the template id when the name normalizes to nothing and stays unique across the run. Step 8 may fix other posthog-node code the upgrade breaks, and the report lists those files. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/description.md | 2 +- context/skills/migrate-email/references/3-inventory.md | 2 +- context/skills/migrate-email/references/7-rewrite.md | 2 +- context/skills/migrate-email/references/8-verify.md | 8 ++++---- context/skills/migrate-email/references/9-report.md | 4 ++-- context/skills/migrate-email/references/resend/mapping.md | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/context/skills/migrate-email/description.md b/context/skills/migrate-email/description.md index 9f7b47bbe..745723a67 100644 --- a/context/skills/migrate-email/description.md +++ b/context/skills/migrate-email/description.md @@ -28,7 +28,7 @@ The plan file `.posthog-email-migration-plan.md` lives at the project root. Step ## Rules -- Change send code only in Step 7, and fix it only in Step 8: the sites that move, and the helpers, callers, and tests they need. Leave every site that stays as it is. +- Change send code only in Step 7, and fix it only in Step 8: the sites that move, the helpers, callers, and tests they need, and other `posthog-node` code that the upgrade breaks. Leave every site that stays as it is. - Never touch DNS or the {display_name} account. Give the person the records and the links, and let them make the change. - Never remove the {display_name} package or its API key. The report tells the person when to remove them. - Never create, upload, or edit a template in PostHog. A moved local template uploads on its first send. diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index 03d30f39e..4d00be176 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -45,7 +45,7 @@ Go through `mapping.md` field by field. A site **moves** when PostHog can send e When the code passes a value you can't read, such as a list of recipients built at run time, follow it to its callers. When you still can't tell, the site stays, and the reason says what you could not check. -A `template` site needs the template's content to be classified. Read the provider's `account.md`, and ask the person once for every template the sites send: copies from the dashboard that they save in files outside the repository and tell you where, or a read through the API. Save each template's content for Step 7 in a file in the system's temporary folder, never in the repository or the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. +A `template` site needs the template's content to be classified. Read the provider's `account.md`, and ask the person once for every template the sites send: copies from the dashboard that they save in files outside the repository and tell you where, or a read through the API. Save each template's content in a file in the system's temporary folder, never in the repository or the plan, and list each file's path with its site under the sites table. When the person can't give the content, the site stays, and the reason is `template content not checked`. ## Write the plan file diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index 57a037094..aa98de9dd 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -63,7 +63,7 @@ For each site that moves, in plan order: - Rewrite the call as the provider's `mapping.md` says, for the site's content form: `html` and `text` content, a component the app renders, or a template stored at the provider. - Give each send a `templateKey` that names the kind of email, such as `welcome` or `password-reset`, with letters, digits, `-`, and `_` only. Two sites that send the same email share a key. A template stored at the provider keeps the key `mapping.md` gives it. -- A template stored at the provider becomes a module that exports `subject` and `html`, and `text` when it has one, in an `emails/` folder next to the server code. Write it from the file Step 3 saved, never from memory, and delete that file once the module is written. The site imports the module and passes `templateData`. +- A template stored at the provider becomes a module that exports `subject` and `html`, and `text` when it has one, in an `emails/` folder next to the server code. Write it from the file the plan lists for the site, never from memory. The site imports the module and passes `templateData`. - Install `@react-email/render` with the project's package manager when a site renders a component and the app doesn't have it. - Keep the site's idempotency key, error branches, logging, and return value working as before. Keep the code around the send unchanged where you can. - `posthog.emails.send` never throws on an API error: it returns `{ data, error }`. When the old call threw on an error, or the code checked an HTTP status, check `error` so the site fails the same way. diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 815353510..5e473f92f 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -16,7 +16,7 @@ Check that the app still builds, its tests still pass, and one moved email reach ## Build and tests -- Run the project's typecheck, such as its `typecheck` script or `tsc --noEmit`, or its build when it has no typecheck. Fix each error that is not in the list Step 7 kept, in any file: the rewrite caused it. An error in that list was there before: note it, and leave it. +- Run the project's typecheck, such as its `typecheck` script or `tsc --noEmit`, or its build when it has no typecheck. Fix each error that is not in the list Step 7 kept, in any file: the rewrite or the posthog-node upgrade caused it. Note each file you fix outside the moved sites for the report. An error in that list was there before: note it, and leave it. - Run the tests that cover the files you changed. A test that mocks the provider's client or intercepts its HTTP requests for a moved site now mocks `posthog.emails.send` and asserts on the fields it gets, with the same expected values. Never turn a PostHog send back into the provider's request shape to keep an old assertion. Never delete or skip a test. - Search the changed files for the provider's calls: a moved site has none left, and each moved site has one `posthog.emails.send`. @@ -28,19 +28,19 @@ Skip this part and record `not checked` with the reason when the API is not conf 1. Check that the app sends to the MCP's project: compare the project token the app reads, from its env file, with `api_token` from the PostHog MCP `projects-get` tool. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. 2. Ask the person whether to send one test email. Say that it sends a real email, and that the first send of a local template uploads it to the PostHog project. When they say no, record `not checked: declined`. -3. Note the current time in UTC as the start of the test. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. +3. Run `SELECT toUnixTimestamp(now())` through the PostHog MCP `execute-sql` tool, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. 4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. 5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test: ```sql SELECT event, timestamp, properties.$workflow_id AS workflow FROM events - WHERE distinct_id = '' AND timestamp >= '' + WHERE distinct_id = '' AND toUnixTimestamp(timestamp) >= ORDER BY timestamp ``` 6. The chain holds when the result has a `$workflows_email_sent`, an engagement event such as `$workflows_email_delivered` or `$workflows_email_opened` with the same `workflow`, and at least one product event of the app. An event from before the start of the test belongs to another email. Delivery events arrive after the provider reports back: when only the send shows, wait a minute and run the query once more. -When the MCP has no SQL tool, ask the person to open their person in PostHog and tell you which of the three they see after the start of the test. +When the MCP has no SQL tool, ask the person to open their person in PostHog and tell you which of the three they see since they triggered the test email. Never write the address or the distinct ID into a file. diff --git a/context/skills/migrate-email/references/9-report.md b/context/skills/migrate-email/references/9-report.md index 5462c62b8..649265c70 100644 --- a/context/skills/migrate-email/references/9-report.md +++ b/context/skills/migrate-email/references/9-report.md @@ -15,7 +15,7 @@ The report comes from the plan file. Invent nothing. ## Write the report -Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email--report.md` at the project root, where `` is the name of the provider folder under `references/`. Use the structure below, then delete the plan file. Never write a recipient's email address into the report. +Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email--report.md` at the project root, where `` is the name of the provider folder under `references/`. Use the structure below. Then delete every template file the plan lists, and the plan file. Never write a recipient's email address into the report. ```markdown # Email migration report: to PostHog @@ -49,7 +49,7 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- ## Checks - + ## Sending tier diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 3820a6900..26d8e2f31 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -73,7 +73,7 @@ How a site that moves is written with `posthog-node`. Step 7 says when to use ea - The site sends `templateKey`, `subject`, `html`, `text` when there is one, and `templateData` with the site's `variables` object, plus the subject values below. - The site's own `subject`, `from`, and `replyTo` win over the template's. When the site has none, use the template's: put its `from` and `replyTo` on the send, and its subject in the module. - The module's subject is fixed text with placeholders. When the site builds its subject from values, such as `` `Order #${order.id}` ``, write the subject in the module as `Order #{{ variables.ORDER_ID }}` and add each value to `templateData`. Never send a subject that changes per email with `templateData`: posthog-node hashes a local template's subject and content, so each email would upload a new version of the template. A send without `templateData` sends rendered content and uploads nothing. -- The template's alias, or its name when it has no alias, becomes the `templateKey` and the module's file name: in lowercase, with each run of characters other than letters, digits, `-`, and `_` replaced by one `-`, and no `-` at either end. When two templates get the same key, add `-2`, `-3`, and so on to the later ones. +- The template's alias, or its name when it has no alias, becomes the `templateKey` and the module's file name: in lowercase, with each run of characters other than letters, digits, `-`, and `_` replaced by one `-`, and no `-` at either end. When that leaves nothing, use the template's id the same way. When the key is already taken by another email of this run, add `-2`, `-3`, and so on. **The answer.** posthog-node answers `{ data, error }` like Resend and never throws on an API error. From 53a190cde2beecc9d3e57d3ea7d36f6bf1ea0859 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:57:23 +0000 Subject: [PATCH 020/260] fix(skills): keep migrate-email's test clock uncached and report dependency upgrades The clock query carries a fresh random literal so a cached answer can't widen the test window. Step 3 may write the template files it saves, the dashboard copy includes the template's alias or name for its key, and a major dependency upgrade lands in the report's "Before cutover" list. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/3-inventory.md | 2 +- context/skills/migrate-email/references/7-rewrite.md | 2 +- context/skills/migrate-email/references/8-verify.md | 2 +- context/skills/migrate-email/references/9-report.md | 2 +- context/skills/migrate-email/references/resend/account.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index 4d00be176..58a3f528a 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -5,7 +5,7 @@ next_step: 4-sender.md # Step 3, list and classify every send -List every place the code sends email through the provider, and decide for each one whether PostHog can send it. Change no source file. The only file you write is the plan file. +List every place the code sends email through the provider, and decide for each one whether PostHog can send it. Change no source file. The only files you write are the plan file and the template files below. ## Status diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index aa98de9dd..bedada723 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -73,4 +73,4 @@ When a site turns out to need something `mapping.md` keeps on the provider, undo ## Write down -Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each site that got a branch for a suppressed recipient, each site with `cc` or `bcc` that a suppressed copy address now stops, each idempotency key a retry across the deploy could send twice, each new dependency, and each new env variable name. +Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each site that got a branch for a suppressed recipient, each site with `cc` or `bcc` that a suppressed copy address now stops, each idempotency key a retry across the deploy could send twice, each new dependency, each upgraded one with its old and new version, and each new env variable name. diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 5e473f92f..1eacd6213 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -28,7 +28,7 @@ Skip this part and record `not checked` with the reason when the API is not conf 1. Check that the app sends to the MCP's project: compare the project token the app reads, from its env file, with `api_token` from the PostHog MCP `projects-get` tool. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. 2. Ask the person whether to send one test email. Say that it sends a real email, and that the first send of a local template uploads it to the PostHog project. When they say no, record `not checked: declined`. -3. Run `SELECT toUnixTimestamp(now())` through the PostHog MCP `execute-sql` tool, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. +3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. 4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. 5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test: diff --git a/context/skills/migrate-email/references/9-report.md b/context/skills/migrate-email/references/9-report.md index 649265c70..c943df576 100644 --- a/context/skills/migrate-email/references/9-report.md +++ b/context/skills/migrate-email/references/9-report.md @@ -59,7 +59,7 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- The moved sites send through PostHog as soon as this code is deployed. Everything in this list has to be done before that deploy. - + ## After cutover diff --git a/context/skills/migrate-email/references/resend/account.md b/context/skills/migrate-email/references/resend/account.md index 93146a650..5241f7831 100644 --- a/context/skills/migrate-email/references/resend/account.md +++ b/context/skills/migrate-email/references/resend/account.md @@ -26,7 +26,7 @@ The app's own Resend key is usually a sending-only key, and it can't read templa A site that sends a template stored at Resend needs the template's content. -**Copy from the dashboard.** In Resend: Templates, then the template. Ask the person for its HTML, its plain text when it has one, its subject, its `from` and reply-to when they are set, and each variable's fallback. +**Copy from the dashboard.** In Resend: Templates, then the template. Ask the person for its alias or name, its HTML, its plain text when it has one, its subject, its `from` and reply-to when they are set, and each variable's fallback. **Read from the API.** `GET https://api.resend.com/templates/{id or alias}` with `Authorization: Bearer $RESEND_FULL_ACCESS_API_KEY`. The answer holds `alias`, `name`, `subject`, `from`, `reply_to`, `html`, `text`, and `variables`, a list of `{ key, type, fallback_value }`. From 50b5f27f18ca54047bd71adca497025b9c1f335c Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:58:28 +0000 Subject: [PATCH 021/260] fix(skills): keep migrate-email's chain query uncached on its rerun Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/8-verify.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 1eacd6213..17f9ad725 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -30,10 +30,10 @@ Skip this part and record `not checked` with the reason when the API is not conf 2. Ask the person whether to send one test email. Say that it sends a real email, and that the first send of a local template uploads it to the PostHog project. When they say no, record `not checked: declined`. 3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. 4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. -5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test: +5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test, with a new random string each time you run it: ```sql - SELECT event, timestamp, properties.$workflow_id AS workflow FROM events + SELECT event, timestamp, properties.$workflow_id AS workflow, '' AS run FROM events WHERE distinct_id = '' AND toUnixTimestamp(timestamp) >= ORDER BY timestamp ``` From 8f77354c203d8e7e4efcd377d3a0725872dc5fd1 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 15:02:22 +0000 Subject: [PATCH 022/260] fix(skills): keep cc, bcc, headers, tags and attachments sites on Resend, and move templates only to PostHog The first PostHog release sends a template made in PostHog by template id, or rendered html and text. A Resend template site moves only once the person makes the template in PostHog, or stays on Resend for now. Co-Authored-By: Claude Opus 5.5 --- .../skills/migrate-email/references/3-inventory.md | 2 +- .../skills/migrate-email/references/7-report.md | 2 +- .../migrate-email/references/resend/mapping.md | 14 ++++++++------ 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index 160f32877..2def92d75 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -45,7 +45,7 @@ Go through `mapping.md` field by field. A site **moves** when PostHog can send e When the code passes a value you can't read, such as a list of recipients built at run time, follow it to its callers. When you still can't tell, the site stays, and the reason says what you could not check. -A `template` site needs the template's content to be classified. Ask the person once to copy every template the sites send from the provider's dashboard into files outside the repository, and to tell you where they saved them. Read those files, and never write the content into the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. +A `template` site moves only to a template made in PostHog, and the person makes that template. Ask the person once, for every template the sites send, whether to move it to PostHog or keep it on the provider for now. A template they keep stays, and the reason is `kept on for now`. For each template they move, ask them to copy it from the provider's dashboard into a file outside the repository, and to tell you where they saved it. Read those files to classify the site, and never write the content into the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. ## Write the plan file diff --git a/context/skills/migrate-email/references/7-report.md b/context/skills/migrate-email/references/7-report.md index eaa7a69ee..e7f4c39ce 100644 --- a/context/skills/migrate-email/references/7-report.md +++ b/context/skills/migrate-email/references/7-report.md @@ -51,7 +51,7 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- ## Before cutover - + ## Summary ``` diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 8a27a39c7..0630178d0 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -12,12 +12,12 @@ This file decides, field by field, whether PostHog can send a Resend call site. | `html` | `html` | Never | | `text` | `text` | Never | | `react` | `html`, rendered in the app | Never. The app renders the component | -| `template` | a local template in the app's code | Its content can't be read, it uses syntax beyond variables and fallbacks, or the app fills a variable with HTML | -| `cc`, `bcc` | `cc`, `bcc` | An entry carries a name, such as `Jane `, or there are more than 10 | +| `template` | a template made in PostHog, sent by its `templateId` with `templateData` | The person keeps it on Resend for now, its content can't be read, it uses syntax beyond variables and fallbacks, the app fills a variable with HTML, or the site sets `from`, `replyTo`, or `subject` next to it | +| `cc`, `bcc` | none | Always | | `replyTo` / `reply_to` | `replyTo` / `reply_to`, as a list | An entry carries a name, such as `Jane `, there are more than 10, or the code builds the value at run time and you cannot tell that it holds bare addresses only. A single address moves as a list of one | -| `headers` | `headers` | A header is one PostHog sets itself (`From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Sender`, `Return-Path`, `Auto-Submitted`, `DKIM-Signature`, `Received`, any `Content-*`, `X-PostHog-*`, `X-SES-*`), a name is longer than 126 characters, a value is longer than 870 characters or has a line break or a non-ASCII character, or there are more than 10 | -| `tags` | `tags` | A name or value has characters other than ASCII letters, digits, `_`, and `-` or is longer than 256 characters, a name starts with `ph_`, or there are more than 10 | -| `attachments` | `attachments` | An attachment uses `path` (a URL Resend fetches), the files can be more than 10 or more than 512 KB in total, or a file type is one mailbox providers block, such as `.exe` | +| `headers` | none | Always | +| `tags` | none | Always | +| `attachments` | none | Always | | `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | Never. The key keeps its value | | `scheduledAt` / `scheduled_at` | none | Always | | `topicId` / `topic_id` | none | Always | @@ -43,4 +43,6 @@ This file decides, field by field, whether PostHog can send a Resend call site. ## Content - `html`, `text`, and `react` content is rendered for one recipient before the send. PostHog sends it as it is. -- A `template` site needs the template's content from the Resend dashboard, because the code has only its id. PostHog's Liquid escapes HTML in a variable's value. A variable the app fills with HTML keeps the site on Resend. +- A `template` site moves only to a template made in PostHog. This skill never makes one: the person makes it from the Resend template, makes it transactional, and gives you its template ID. Until then the site stays on Resend. +- The check needs the template's content from the Resend dashboard, because the code has only its id. In the PostHog template, `{{{NAME}}}` becomes `{{ variables.NAME }}`, and `{{{NAME|there}}}` becomes `{{ variables.NAME | default: 'there' }}`. PostHog's Liquid escapes HTML in a variable's value, so a variable the app fills with HTML keeps the site on Resend. +- The PostHog template carries its own sender, reply-to address, and subject. A site that sets `from`, `replyTo`, or `subject` next to `template` stays on Resend. From b9d785e82a5fdfb7aa1aaee7f13835d037fe2c51 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 15:05:32 +0000 Subject: [PATCH 023/260] Drop local templates and parked fields from the cutover steps Under the scope cut, a moved template site sends a template made in PostHog by templateId with templateData. Rendered sends keep templateKey, subject, html and text. No local-template module, no upload on first send, and no cc, bcc, headers, tags or attachments. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/description.md | 4 ++-- .../migrate-email/references/7-rewrite.md | 17 ++++++++--------- .../skills/migrate-email/references/8-verify.md | 2 +- .../migrate-email/references/resend/account.md | 4 ++-- 4 files changed, 13 insertions(+), 14 deletions(-) diff --git a/context/skills/migrate-email/description.md b/context/skills/migrate-email/description.md index 745723a67..b36e4c43a 100644 --- a/context/skills/migrate-email/description.md +++ b/context/skills/migrate-email/description.md @@ -31,7 +31,7 @@ The plan file `.posthog-email-migration-plan.md` lives at the project root. Step - Change send code only in Step 7, and fix it only in Step 8: the sites that move, the helpers, callers, and tests they need, and other `posthog-node` code that the upgrade breaks. Leave every site that stays as it is. - Never touch DNS or the {display_name} account. Give the person the records and the links, and let them make the change. - Never remove the {display_name} package or its API key. The report tells the person when to remove them. -- Never create, upload, or edit a template in PostHog. A moved local template uploads on its first send. +- Never create, upload, or edit a template in PostHog. The person makes each template that moves to PostHog. - Never write a recipient's email address into a file in the repository, the plan, or the report. Count addresses instead. - Keep keys in environment variables. Never hardcode a key, and never ask the person to paste one into the chat. - Do not commit. The person reviews the diff and commits. @@ -54,4 +54,4 @@ Outside the Wizard, skip the `[STATUS]` lines, and tell the person why you stopp `transactional-emails.md` is the transactional email overview. It covers how to create a transactional email and its API key, idempotency, and the error codes. `api.md` covers the send route, including content from your code, and the checks of a send. -When the `sending-transactional-emails` skill is available, read it for the PostHog side of a send. Its `moving-from-other-providers.md` moves sends to a template stored in PostHog. This skill moves {display_name}'s sends to `posthog-node` with the content in the app's code instead. Where the two disagree, this skill's steps win. +When the `sending-transactional-emails` skill is available, read it for the PostHog side of a send. Its `moving-from-other-providers.md` moves sends to a template stored in PostHog. This skill moves {display_name}'s sends to `posthog-node`, with the content in the app's code, or to a template the person makes in PostHog. Where the two disagree, this skill's steps win. diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index bedada723..3e7444ab1 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -22,11 +22,10 @@ Rewrite each site whose `moves` is `yes` in the plan to send with `posthog-node` ## Set up the client -Install or upgrade `posthog-node` to its latest release with the project's package manager. `posthog.emails` alone is not enough: early releases send only a template stored in PostHog, by `templateId`. Check the installed package's types for what the moving sites need: +Install or upgrade `posthog-node` to its latest release with the project's package manager. `posthog.emails` alone is not enough: early releases send only a template made in PostHog, by `templateId`. Check the installed package's types for what the moving sites need: -- every site: `posthog.emails.send` takes `templateKey` with `subject` and `html` or `text`; -- a template stored at the provider: `templateData` takes the local template's content; -- a site that sets `cc`, `bcc`, `replyTo`, `headers`, `tags`, or `attachments`: the send takes that field. +- a site with `html`, `text`, or a component: `posthog.emails.send` takes `templateKey` with `subject` and `html` or `text`; +- a site that sets `replyTo`: the send takes `replyTo`. When the latest release lacks one of these, change no site that needs it. Mark each such row `moves: no — posthog-node has no yet`, tell the person, and go on with the rest. When no site is left, tick the phase with `none moved` and go to the next step. @@ -61,16 +60,16 @@ PostHog shows each email on the person the send names with `distinctId`. Use the For each site that moves, in plan order: -- Rewrite the call as the provider's `mapping.md` says, for the site's content form: `html` and `text` content, a component the app renders, or a template stored at the provider. -- Give each send a `templateKey` that names the kind of email, such as `welcome` or `password-reset`, with letters, digits, `-`, and `_` only. Two sites that send the same email share a key. A template stored at the provider keeps the key `mapping.md` gives it. -- A template stored at the provider becomes a module that exports `subject` and `html`, and `text` when it has one, in an `emails/` folder next to the server code. Write it from the file the plan lists for the site, never from memory. The site imports the module and passes `templateData`. +- Rewrite the call as the provider's `mapping.md` says, for the site's content form: `html` and `text` content, a component the app renders, or a template made in PostHog. +- Give each send with rendered content a `templateKey` that names the kind of email, such as `welcome` or `password-reset`, with letters, digits, `-`, and `_` only. Two sites that send the same email share a key. +- A site that moves to a template made in PostHog sends the template ID the person gave in Step 3, never one you guess. - Install `@react-email/render` with the project's package manager when a site renders a component and the app doesn't have it. - Keep the site's idempotency key, error branches, logging, and return value working as before. Keep the code around the send unchanged where you can. - `posthog.emails.send` never throws on an API error: it returns `{ data, error }`. When the old call threw on an error, or the code checked an HTTP status, check `error` so the site fails the same way. -- Never add a field that the old call didn't set, apart from `templateKey`, `distinctId`, and the template defaults `mapping.md` names. +- Never add a field that the old call didn't set, apart from `templateKey`, `templateId`, and `distinctId`. `templateData` takes the place of the provider's template variables. When a site turns out to need something `mapping.md` keeps on the provider, undo its change, set `moves` to `no` with the reason, and go on. ## Write down -Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each site that got a branch for a suppressed recipient, each site with `cc` or `bcc` that a suppressed copy address now stops, each idempotency key a retry across the deploy could send twice, each new dependency, each upgraded one with its old and new version, and each new env variable name. +Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`, or its `templateId` for a template made in PostHog. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each site that got a branch for a suppressed recipient, each idempotency key a retry across the deploy could send twice, each new dependency, each upgraded one with its old and new version, and each new env variable name. diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 17f9ad725..36fa7e6dd 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -27,7 +27,7 @@ The chain to prove: PostHog sends the email, records its engagement on the perso Skip this part and record `not checked` with the reason when the API is not confirmed on, no sender is verified, or `POSTHOG_PROJECT_SECRET_API_KEY` is not set. 1. Check that the app sends to the MCP's project: compare the project token the app reads, from its env file, with `api_token` from the PostHog MCP `projects-get` tool. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. -2. Ask the person whether to send one test email. Say that it sends a real email, and that the first send of a local template uploads it to the PostHog project. When they say no, record `not checked: declined`. +2. Ask the person whether to send one test email. Say that it sends a real email. When they say no, record `not checked: declined`. 3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. 4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. 5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test, with a new random string each time you run it: diff --git a/context/skills/migrate-email/references/resend/account.md b/context/skills/migrate-email/references/resend/account.md index 5241f7831..c3922cdb6 100644 --- a/context/skills/migrate-email/references/resend/account.md +++ b/context/skills/migrate-email/references/resend/account.md @@ -24,13 +24,13 @@ The app's own Resend key is usually a sending-only key, and it can't read templa ## Template content -A site that sends a template stored at Resend needs the template's content. +A site whose template the person moves to PostHog needs the template's content, to check it before they make the PostHog template. **Copy from the dashboard.** In Resend: Templates, then the template. Ask the person for its alias or name, its HTML, its plain text when it has one, its subject, its `from` and reply-to when they are set, and each variable's fallback. **Read from the API.** `GET https://api.resend.com/templates/{id or alias}` with `Authorization: Bearer $RESEND_FULL_ACCESS_API_KEY`. The answer holds `alias`, `name`, `subject`, `from`, `reply_to`, `html`, `text`, and `variables`, a list of `{ key, type, fallback_value }`. -The content goes only into the temporary file Step 3 saves and the template module the rewrite writes. Never write it into the plan or the report. +The content goes only into the temporary file Step 3 saves. Never write it into the plan or the report. ## Suppression list From 5edeb92e44ae895988144f6a37d734c06589c7e7 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 15:51:07 +0000 Subject: [PATCH 024/260] feat(migrate-email): set migratedFrom on the posthog-node client posthog-node's migratedFrom client option sends the provider a send moved from with every email request. Step 7 now sets it, and the Resend mapping names its value. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/7-rewrite.md | 4 +++- context/skills/migrate-email/references/resend/mapping.md | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index 3e7444ab1..0169fb194 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -38,10 +38,12 @@ export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { host: process.env.POSTHOG_HOST, secretKey: process.env.POSTHOG_PROJECT_SECRET_API_KEY, enableLocalEvaluation: false, + migratedFrom: '', }) ``` -- Reuse the app's existing `posthog-node` client when it has one, and add `secretKey`. Keep `enableLocalEvaluation: false` unless the key also has `feature_flag:read` and the app uses local evaluation. +- Set `migratedFrom` to the value that the provider's `mapping.md` names under "The PostHog client". posthog-node sends it with every email request, so PostHog knows that the sends moved from that provider. +- Reuse the app's existing `posthog-node` client when it has one, and add `secretKey` and `migratedFrom`. Keep `enableLocalEvaluation: false` unless the key also has `feature_flag:read` and the app uses local evaluation. - When the project token or the host is not configured yet, get the token from the PostHog MCP `projects-get` tool (`api_token`). The host is `https://us.i.posthog.com` for US Cloud and `https://eu.i.posthog.com` for EU Cloud. Ask the person which one when you can't tell. - When `host` is a reverse proxy or a self-hosted instance, also set `appHost` to the PostHog app URL, such as `https://us.posthog.com`. posthog-node never sends the secret key to a proxy, and without `appHost` the send fails with `missing_app_host`. - Put a new client in its own server-only module, next to the provider's client, and import it where the sites send. diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 24a9341e8..59edca2ed 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -55,6 +55,8 @@ This file decides, field by field, whether PostHog can send a Resend call site. How a site that moves is written with `posthog-node`. Step 7 says when to use each part. +**The PostHog client.** Set `migratedFrom: 'resend'` on the `posthog-node` client that Step 7 configures. + **The call.** `resend.emails.send(payload, { idempotencyKey })` and `resend.emails.create(...)` become one `posthog.emails.send({ ... })`. The options object goes away: `idempotencyKey` moves into the payload. **The fields.** From 64cf8efd22d4cb2f2d4ec160a76e9301e515ba1a Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:03:00 +0000 Subject: [PATCH 025/260] fix(migrate-email): ask for the PostHog template ID before a template site moves Review round 1 on #451: - Step 3 asks for the template ID once the person made the template in PostHog. A template without one stays: PostHog template not made yet. - Step 7 checks that the client takes migratedFrom, and undoes the posthog-node install when no site is left to move. - Template files from an API read are deleted once their site is classified, and the full-access Resend key right after Step 5. - Step 8 reads only the token's line of the env file, and picks a signed-in flow for the test email. - replyTo moves as one address or a list. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/3-inventory.md | 4 +++- context/skills/migrate-email/references/5-suppressions.md | 2 ++ context/skills/migrate-email/references/7-rewrite.md | 5 +++-- context/skills/migrate-email/references/8-verify.md | 4 ++-- context/skills/migrate-email/references/9-report.md | 6 +++--- context/skills/migrate-email/references/resend/account.md | 2 +- context/skills/migrate-email/references/resend/mapping.md | 2 +- 7 files changed, 15 insertions(+), 10 deletions(-) diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index cb9f12f2f..bc243b7fd 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -47,7 +47,9 @@ When the code passes a value you can't read, such as a list of recipients built A `template` site moves only to a template made in PostHog, and the person makes that template. Ask the person once, for every template the sites send, whether to move it to PostHog or keep it on the provider for now. A template they keep stays, and the reason is `kept on for now`. -A template they move needs its content to be classified. Read the provider's `account.md`, and ask the person once for every template they move: copies from the dashboard that they save in files outside the repository and tell you where, or a read through the API. Save each template's content in a file in the system's temporary folder, never in the repository or the plan, and list each file's path with its site under the sites table. When the person can't give the content, the site stays, and the reason is `template content not checked`. +A template they move needs its content to be classified. Read the provider's `account.md`, and ask the person once for every template they move: copies from the dashboard that they save in files outside the repository and tell you where, or a read through the API. Read the person's copies where they saved them. Write an API answer to a file in the system's temporary folder, never in the repository or the plan, and delete that file as soon as its site is classified. When the person can't give the content, the site stays, and the reason is `template content not checked`. + +A template whose content passes the checks moves only once the person has made it in PostHog. Ask them once, for every such template, to make it in PostHog from the provider's template, make it transactional, and give you its template ID. Tell them how its placeholders change, as `mapping.md` says under "Content". Record each template ID with its site under the sites table. A template without an ID stays, and the reason is `PostHog template not made yet`. ## Write the plan file diff --git a/context/skills/migrate-email/references/5-suppressions.md b/context/skills/migrate-email/references/5-suppressions.md index 916a21439..5f6559b9c 100644 --- a/context/skills/migrate-email/references/5-suppressions.md +++ b/context/skills/migrate-email/references/5-suppressions.md @@ -37,3 +37,5 @@ Read the provider's `account.md`. It says how to export the list, which entries ## Write down Tick the phase in the plan file only when every entry is imported: `- [x] suppressions — / imported`. When the list is empty, write `- [x] suppressions — empty list`. When the import stopped partway, write `- [ ] suppressions — / imported: `. When the person has no export and no key, write `- [ ] suppressions — not imported: `. + +When the plan says the run created a full-access provider key, ask the person now to delete it at the provider and remove its variable from the env file, as `account.md` says. Note in the plan whether they did. diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index 0169fb194..0bd2c3674 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -25,9 +25,10 @@ Rewrite each site whose `moves` is `yes` in the plan to send with `posthog-node` Install or upgrade `posthog-node` to its latest release with the project's package manager. `posthog.emails` alone is not enough: early releases send only a template made in PostHog, by `templateId`. Check the installed package's types for what the moving sites need: - a site with `html`, `text`, or a component: `posthog.emails.send` takes `templateKey` with `subject` and `html` or `text`; -- a site that sets `replyTo`: the send takes `replyTo`. +- a site that sets `replyTo`: the send takes `replyTo`; +- the client: the client options take `migratedFrom`. -When the latest release lacks one of these, change no site that needs it. Mark each such row `moves: no — posthog-node has no yet`, tell the person, and go on with the rest. When no site is left, tick the phase with `none moved` and go to the next step. +When the latest release lacks one of these, change no site that needs it. Mark each such row `moves: no — posthog-node has no yet`, tell the person, and go on with the rest. When the client options lack `migratedFrom`, leave it out of the client. When no site is left, undo the install or upgrade of `posthog-node`, tick the phase with `none moved`, and go to the next step. Configure one server-side client for email: diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 36fa7e6dd..6779afb76 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -26,9 +26,9 @@ The chain to prove: PostHog sends the email, records its engagement on the perso Skip this part and record `not checked` with the reason when the API is not confirmed on, no sender is verified, or `POSTHOG_PROJECT_SECRET_API_KEY` is not set. -1. Check that the app sends to the MCP's project: compare the project token the app reads, from its env file, with `api_token` from the PostHog MCP `projects-get` tool. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. +1. Check that the app sends to the MCP's project: compare the project token the app reads with `api_token` from the PostHog MCP `projects-get` tool. Read only the token's line of the env file, by searching for the token variable's name: the file also holds secret keys, so never open all of it. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. 2. Ask the person whether to send one test email. Say that it sends a real email. When they say no, record `not checked: declined`. -3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app while they are signed in as themselves, such as a signup or a password reset, so the email goes to an address they own. Ask them to tell you when it is sent and to open the email. +3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app that sends it to an address they own while they are signed in as themselves, such as a signup. A flow that runs signed out, such as a password reset, sends product events on another distinct ID. Ask them to tell you when it is sent and to open the email. 4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. 5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test, with a new random string each time you run it: diff --git a/context/skills/migrate-email/references/9-report.md b/context/skills/migrate-email/references/9-report.md index 407921979..12e291a89 100644 --- a/context/skills/migrate-email/references/9-report.md +++ b/context/skills/migrate-email/references/9-report.md @@ -15,7 +15,7 @@ The report comes from the plan file. Invent nothing. ## Write the report -Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email--report.md` at the project root, where `` is the name of the provider folder under `references/`. Use the structure below. Then delete every template file the plan lists, and the plan file. Never write a recipient's email address into the report. +Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email--report.md` at the project root, where `` is the name of the provider folder under `references/`. Use the structure below. Then delete the plan file. Never write a recipient's email address into the report. ```markdown # Email migration report: to PostHog @@ -59,11 +59,11 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- The moved sites send through PostHog as soon as this code is deployed. Everything in this list has to be done before that deploy. - + ## After cutover - + ## Summary ``` diff --git a/context/skills/migrate-email/references/resend/account.md b/context/skills/migrate-email/references/resend/account.md index c3922cdb6..66b1f929d 100644 --- a/context/skills/migrate-email/references/resend/account.md +++ b/context/skills/migrate-email/references/resend/account.md @@ -20,7 +20,7 @@ A domain verified at Resend carries these records. Keep all of them until the cu ## Full-access key -The app's own Resend key is usually a sending-only key, and it can't read templates or the suppression list. When the person chooses the API over the dashboard, ask them to create a full-access key in Resend, store it in `RESEND_FULL_ACCESS_API_KEY` in the git-ignored env file, and note in the plan that the run created it. The report tells the person to delete it. Never print the key, and never write it into another file. +The app's own Resend key is usually a sending-only key, and it can't read templates or the suppression list. When the person chooses the API over the dashboard, ask them to create a full-access key in Resend, store it in `RESEND_FULL_ACCESS_API_KEY` in the git-ignored env file, and note in the plan that the run created it. Its last use is the suppression import in Step 5. At the end of Step 5, ask the person to delete the key in Resend and remove its variable from the env file, and note in the plan whether they did. The report reminds them when they didn't. Never print the key, and never write it into another file. ## Template content diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 59edca2ed..e93ba0ec7 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -14,7 +14,7 @@ This file decides, field by field, whether PostHog can send a Resend call site. | `react` | `html`, rendered in the app | Never. The app renders the component | | `template` | a template made in PostHog, sent by its `templateId` with `templateData` | The person keeps it on Resend for now, its content can't be read, it uses syntax beyond variables and fallbacks, the app fills a variable with HTML, or the site sets `from`, `replyTo`, or `subject` next to it | | `cc`, `bcc` | none | Always | -| `replyTo` / `reply_to` | `replyTo` / `reply_to`, as a list | An entry carries a name, such as `Jane `, there are more than 10, or the code builds the value at run time and you cannot tell that it holds bare addresses only. A single address moves as a list of one | +| `replyTo` / `reply_to` | `replyTo`, one address or a list | An entry carries a name, such as `Jane `, there are more than 10, or the code builds the value at run time and you cannot tell that it holds bare addresses only | | `headers` | none | Always | | `tags` | none | Always | | `attachments` | none | Always | From 85f60962c4cdb1bbe24efb6462c5335bceb1b290 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:08:02 +0000 Subject: [PATCH 026/260] fix(migrate-email): check each PostHog template and its sender before cutover Review round 2 on #451: - Step 3 asks for the address a PostHog template sends from and writes it in the site's from column, so Step 4 sets up a sender for its domain. - The report asks the person to send a test of each PostHog template and check that it is transactional, has a verified sender and fills its variables. - Step 5 asks to delete the full-access key on every way out of the step, and after a partial import only once the person won't repeat it. - Step 8 allows a signed-out flow: the person signs in as the recipient afterwards, so product events show on the same distinct ID. - migratedFrom is set only when the client options take it. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/3-inventory.md | 2 +- context/skills/migrate-email/references/5-suppressions.md | 6 ++++-- context/skills/migrate-email/references/7-rewrite.md | 4 ++-- context/skills/migrate-email/references/8-verify.md | 2 +- context/skills/migrate-email/references/9-report.md | 2 +- context/skills/migrate-email/references/resend/account.md | 2 +- context/skills/migrate-email/references/resend/mapping.md | 2 +- 7 files changed, 11 insertions(+), 9 deletions(-) diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index bc243b7fd..7d21b665b 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -49,7 +49,7 @@ A `template` site moves only to a template made in PostHog, and the person makes A template they move needs its content to be classified. Read the provider's `account.md`, and ask the person once for every template they move: copies from the dashboard that they save in files outside the repository and tell you where, or a read through the API. Read the person's copies where they saved them. Write an API answer to a file in the system's temporary folder, never in the repository or the plan, and delete that file as soon as its site is classified. When the person can't give the content, the site stays, and the reason is `template content not checked`. -A template whose content passes the checks moves only once the person has made it in PostHog. Ask them once, for every such template, to make it in PostHog from the provider's template, make it transactional, and give you its template ID. Tell them how its placeholders change, as `mapping.md` says under "Content". Record each template ID with its site under the sites table. A template without an ID stays, and the reason is `PostHog template not made yet`. +A template whose content passes the checks moves only once the person has made it in PostHog. Ask them once, for every such template, to make it in PostHog from the provider's template, make it transactional, and give you its template ID and the address it sends from, usually the provider template's sender. Tell them how its placeholders change, as `mapping.md` says under "Content". Record each template ID with its site under the sites table, and write the address in the site's `from` column, so Step 4 sets up a sender for its domain. A template without an ID stays, and the reason is `PostHog template not made yet`. ## Write the plan file diff --git a/context/skills/migrate-email/references/5-suppressions.md b/context/skills/migrate-email/references/5-suppressions.md index 5f6559b9c..b04becbb7 100644 --- a/context/skills/migrate-email/references/5-suppressions.md +++ b/context/skills/migrate-email/references/5-suppressions.md @@ -17,7 +17,7 @@ The provider keeps a suppression list: addresses that hard-bounced or marked an Look for the PostHog MCP tool `email-suppressions-add`, and read its schema with `info`. -When it is missing, the import is not available to this person yet. Do not try other tools, and do not use the opt-out tools: opt-outs are marketing preferences, and transactional email ignores them. Tick the phase as `- [ ] suppressions — not imported: no import tool`, and continue to the next step. The report tells the person to add the addresses in PostHog (Workflows, then Messaging, then Suppression list) before cutover. +When it is missing, the import is not available to this person yet. Do not try other tools, and do not use the opt-out tools: opt-outs are marketing preferences, and transactional email ignores them. Tick the phase as `- [ ] suppressions — not imported: no import tool`, ask about the full-access key as the last section says, and continue to the next step. The report tells the person to add the addresses in PostHog (Workflows, then Messaging, then Suppression list) before cutover. ## Get the list @@ -38,4 +38,6 @@ Read the provider's `account.md`. It says how to export the list, which entries Tick the phase in the plan file only when every entry is imported: `- [x] suppressions — / imported`. When the list is empty, write `- [x] suppressions — empty list`. When the import stopped partway, write `- [ ] suppressions — / imported: `. When the person has no export and no key, write `- [ ] suppressions — not imported: `. -When the plan says the run created a full-access provider key, ask the person now to delete it at the provider and remove its variable from the env file, as `account.md` says. Note in the plan whether they did. +## The full-access key + +Every way out of this step ends here. When the plan says the run created a full-access provider key, ask the person now to delete it at the provider and remove its variable from the env file, as `account.md` says. When the import stopped partway, ask only once the person decides not to repeat it. Note in the plan whether they did. diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index 0bd2c3674..e07c02fb1 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -43,8 +43,8 @@ export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { }) ``` -- Set `migratedFrom` to the value that the provider's `mapping.md` names under "The PostHog client". posthog-node sends it with every email request, so PostHog knows that the sends moved from that provider. -- Reuse the app's existing `posthog-node` client when it has one, and add `secretKey` and `migratedFrom`. Keep `enableLocalEvaluation: false` unless the key also has `feature_flag:read` and the app uses local evaluation. +- When the client options take `migratedFrom`, set it to the value that the provider's `mapping.md` names under "The PostHog client". posthog-node sends it with every email request, so PostHog knows that the sends moved from that provider. +- Reuse the app's existing `posthog-node` client when it has one, and add `secretKey`, and `migratedFrom` when the client options take it. Keep `enableLocalEvaluation: false` unless the key also has `feature_flag:read` and the app uses local evaluation. - When the project token or the host is not configured yet, get the token from the PostHog MCP `projects-get` tool (`api_token`). The host is `https://us.i.posthog.com` for US Cloud and `https://eu.i.posthog.com` for EU Cloud. Ask the person which one when you can't tell. - When `host` is a reverse proxy or a self-hosted instance, also set `appHost` to the PostHog app URL, such as `https://us.posthog.com`. posthog-node never sends the secret key to a proxy, and without `appHost` the send fails with `missing_app_host`. - Put a new client in its own server-only module, next to the provider's client, and import it where the sites send. diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 6779afb76..3bd221056 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -28,7 +28,7 @@ Skip this part and record `not checked` with the reason when the API is not conf 1. Check that the app sends to the MCP's project: compare the project token the app reads with `api_token` from the PostHog MCP `projects-get` tool. Read only the token's line of the env file, by searching for the token variable's name: the file also holds secret keys, so never open all of it. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. 2. Ask the person whether to send one test email. Say that it sends a real email. When they say no, record `not checked: declined`. -3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app that sends it to an address they own while they are signed in as themselves, such as a signup. A flow that runs signed out, such as a password reset, sends product events on another distinct ID. Ask them to tell you when it is sent and to open the email. +3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app that sends it to an address they own, such as a signup or a password reset. Ask them to open the email, then to sign in as the user it went to and use the app for a moment, so that the app's product events show on the same distinct ID. Ask them to tell you when they are done. 4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. 5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test, with a new random string each time you run it: diff --git a/context/skills/migrate-email/references/9-report.md b/context/skills/migrate-email/references/9-report.md index 12e291a89..4562e9f1a 100644 --- a/context/skills/migrate-email/references/9-report.md +++ b/context/skills/migrate-email/references/9-report.md @@ -59,7 +59,7 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- The moved sites send through PostHog as soon as this code is deployed. Everything in this list has to be done before that deploy. - + ## After cutover diff --git a/context/skills/migrate-email/references/resend/account.md b/context/skills/migrate-email/references/resend/account.md index 66b1f929d..22e6461c9 100644 --- a/context/skills/migrate-email/references/resend/account.md +++ b/context/skills/migrate-email/references/resend/account.md @@ -20,7 +20,7 @@ A domain verified at Resend carries these records. Keep all of them until the cu ## Full-access key -The app's own Resend key is usually a sending-only key, and it can't read templates or the suppression list. When the person chooses the API over the dashboard, ask them to create a full-access key in Resend, store it in `RESEND_FULL_ACCESS_API_KEY` in the git-ignored env file, and note in the plan that the run created it. Its last use is the suppression import in Step 5. At the end of Step 5, ask the person to delete the key in Resend and remove its variable from the env file, and note in the plan whether they did. The report reminds them when they didn't. Never print the key, and never write it into another file. +The app's own Resend key is usually a sending-only key, and it can't read templates or the suppression list. When the person chooses the API over the dashboard, ask them to create a full-access key in Resend, store it in `RESEND_FULL_ACCESS_API_KEY` in the git-ignored env file, and note in the plan that the run created it. Its last use is the suppression import in Step 5. At the end of Step 5, on every way out of it, ask the person to delete the key in Resend and remove its variable from the env file, and note in the plan whether they did. The report reminds them when they didn't. Never print the key, and never write it into another file. ## Template content diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index e93ba0ec7..4e2f7993d 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -55,7 +55,7 @@ This file decides, field by field, whether PostHog can send a Resend call site. How a site that moves is written with `posthog-node`. Step 7 says when to use each part. -**The PostHog client.** Set `migratedFrom: 'resend'` on the `posthog-node` client that Step 7 configures. +**The PostHog client.** Set `migratedFrom: 'resend'` on the `posthog-node` client that Step 7 configures, when its client options take it. **The call.** `resend.emails.send(payload, { idempotencyKey })` and `resend.emails.create(...)` become one `posthog.emails.send({ ... })`. The options object goes away: `idempotencyKey` moves into the payload. From a759ff460e5d556f7a27910add5b26171051f432 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:14:51 +0000 Subject: [PATCH 027/260] fix(migrate-email): ask about a repeat import and test a send that names a person Review round 3 on #451: - Step 5 asks once whether to repeat an import that stopped partway, and asks about the full-access key after that answer or the repeat. - Step 8's test email comes from a moved site that passes distinctId; without one, the chain is recorded as not checked. - The client example marks migratedFrom as conditional. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/5-suppressions.md | 4 ++-- context/skills/migrate-email/references/7-rewrite.md | 2 +- context/skills/migrate-email/references/8-verify.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/context/skills/migrate-email/references/5-suppressions.md b/context/skills/migrate-email/references/5-suppressions.md index b04becbb7..48c55e11b 100644 --- a/context/skills/migrate-email/references/5-suppressions.md +++ b/context/skills/migrate-email/references/5-suppressions.md @@ -32,7 +32,7 @@ Read the provider's `account.md`. It says how to export the list, which entries - Send the entries to `email-suppressions-add` in batches of the size its schema allows. Give each entry the source and the reason `account.md` names. - Repeating an import is safe: an address already on the list stays on it. - Never print the addresses, and never write them into the plan or the report. Count them. -- When a call fails, read its error and fix the call. When it fails again, stop the import and record how many entries you imported. +- When a call fails, read its error and fix the call. When it fails again, stop the import, record how many entries you imported, and ask the person once whether to repeat it now. Repeat it when they say yes. ## Write down @@ -40,4 +40,4 @@ Tick the phase in the plan file only when every entry is imported: `- [x] suppre ## The full-access key -Every way out of this step ends here. When the plan says the run created a full-access provider key, ask the person now to delete it at the provider and remove its variable from the env file, as `account.md` says. When the import stopped partway, ask only once the person decides not to repeat it. Note in the plan whether they did. +Every way out of this step ends here. When the plan says the run created a full-access provider key, ask the person now to delete it at the provider and remove its variable from the env file, as `account.md` says. After a partial import, ask once the person said no to a repeat, or the repeat ended. Note in the plan whether they did. diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index e07c02fb1..eefe42ebe 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -39,7 +39,7 @@ export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { host: process.env.POSTHOG_HOST, secretKey: process.env.POSTHOG_PROJECT_SECRET_API_KEY, enableLocalEvaluation: false, - migratedFrom: '', + migratedFrom: '', // only when the client options take it }) ``` diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 3bd221056..1b29050e9 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -28,7 +28,7 @@ Skip this part and record `not checked` with the reason when the API is not conf 1. Check that the app sends to the MCP's project: compare the project token the app reads with `api_token` from the PostHog MCP `projects-get` tool. Read only the token's line of the env file, by searching for the token variable's name: the file also holds secret keys, so never open all of it. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. 2. Ask the person whether to send one test email. Say that it sends a real email. When they say no, record `not checked: declined`. -3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app that sends it to an address they own, such as a signup or a password reset. Ask them to open the email, then to sign in as the user it went to and use the app for a moment, so that the app's product events show on the same distinct ID. Ask them to tell you when they are done. +3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app that sends it to an address they own, from a site that passes `distinctId`, such as a signup or a password reset. When no moved site passes `distinctId`, record `not checked: no moved site names a person`, and skip the rest of this part. Ask them to open the email, then to sign in as the user it went to and use the app for a moment, so that the app's product events show on the same distinct ID. Ask them to tell you when they are done. 4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. 5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test, with a new random string each time you run it: From 5c8a34b8b86a5d521ad389f83c37a82d2266fdad Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:26:55 +0000 Subject: [PATCH 028/260] fix(migrate-email): ask for the PostHog template ID and sender before a template site moves Review round 1 on #450: - Step 3 checks a template site's other fields before it asks about the template, and asks for the PostHog template ID and the address it sends from. A template without an ID stays: PostHog template not made yet. The address goes in the from column, so Step 4 sets up its domain. - mapping.md quotes a fallback that holds ' with ", carries a definition-level fallback_value, notes that default replaces an empty string, and keeps a fallback with both quotes or HTML on Resend. - The report asks the person to test each PostHog template before cutover. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/3-inventory.md | 4 +++- context/skills/migrate-email/references/7-report.md | 2 +- context/skills/migrate-email/references/resend/mapping.md | 6 +++++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index 2def92d75..8ad9ba5ec 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -45,7 +45,9 @@ Go through `mapping.md` field by field. A site **moves** when PostHog can send e When the code passes a value you can't read, such as a list of recipients built at run time, follow it to its callers. When you still can't tell, the site stays, and the reason says what you could not check. -A `template` site moves only to a template made in PostHog, and the person makes that template. Ask the person once, for every template the sites send, whether to move it to PostHog or keep it on the provider for now. A template they keep stays, and the reason is `kept on for now`. For each template they move, ask them to copy it from the provider's dashboard into a file outside the repository, and to tell you where they saved it. Read those files to classify the site, and never write the content into the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. +A `template` site moves only to a template made in PostHog, and the person makes that template. Check the site's other fields first: a site that another field keeps on the provider stays with that reason, and needs no question about its template. Ask the person once, for every other template the sites send, whether to move it to PostHog or keep it on the provider for now. A template they keep stays, and the reason is `kept on for now`. For each template they move, ask them to copy it from the provider's dashboard into a file outside the repository, and to tell you where they saved it. Read those files to classify the site, and never write the content into the plan. When the person can't give the content, the site stays, and the reason is `template content not checked`. + +A template whose content passes the checks moves only once the person has made it in PostHog. Ask them once, for every such template, to make it in PostHog from the provider's template, make it transactional, and give you its template ID and the address it sends from, usually the provider template's sender. Tell them how its placeholders change, as `mapping.md` says under "Content". Record each template ID with its site under the sites table, and write the address in the site's `from` column, so Step 4 sets up a sender for its domain. A template without an ID stays, and the reason is `PostHog template not made yet`. ## Write the plan file diff --git a/context/skills/migrate-email/references/7-report.md b/context/skills/migrate-email/references/7-report.md index e7f4c39ce..8a321c0f0 100644 --- a/context/skills/migrate-email/references/7-report.md +++ b/context/skills/migrate-email/references/7-report.md @@ -51,7 +51,7 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- ## Before cutover - + ## Summary ``` diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 0630178d0..31be4fd5e 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -44,5 +44,9 @@ This file decides, field by field, whether PostHog can send a Resend call site. - `html`, `text`, and `react` content is rendered for one recipient before the send. PostHog sends it as it is. - A `template` site moves only to a template made in PostHog. This skill never makes one: the person makes it from the Resend template, makes it transactional, and gives you its template ID. Until then the site stays on Resend. -- The check needs the template's content from the Resend dashboard, because the code has only its id. In the PostHog template, `{{{NAME}}}` becomes `{{ variables.NAME }}`, and `{{{NAME|there}}}` becomes `{{ variables.NAME | default: 'there' }}`. PostHog's Liquid escapes HTML in a variable's value, so a variable the app fills with HTML keeps the site on Resend. +- The check needs the template's content from the Resend dashboard, because the code has only its id. +- In the PostHog template, `{{{NAME}}}` becomes `{{ variables.NAME }}`, and the name keeps its case. `{{{NAME|there}}}` becomes `{{ variables.NAME | default: 'there' }}`, and a variable with a `fallback_value` in the template's definition gets the same `default`. Quote a fallback that holds a `'` with `"` instead. Liquid has no escape character in a quoted value. +- Liquid's `default` also replaces an empty string, which Resend inserts as it is. When the code can pass an empty string for a variable with a fallback, the email shows the fallback instead. Note it in the report. +- Resend inserts a variable's value as it is. PostHog's Liquid escapes HTML in a value, so `` shows as text. A variable is HTML when the code fills it with markup or with a renderer's output, and such a variable keeps the site on Resend. A variable the app fills with plain values, such as names, numbers, and URLs, renders the same. +- A template that holds anything other than `{{{VAR}}}` and `{{{VAR|fallback}}}` placeholders, such as a section, a loop, or a condition, stays on Resend. So does a fallback that holds both `'` and `"`, and a fallback that holds HTML, such as a link: Liquid escapes the fallback too, so the markup shows as text. - The PostHog template carries its own sender, reply-to address, and subject. A site that sets `from`, `replyTo`, or `subject` next to `template` stays on Resend. From efa493348628cc8f01b1afc53b3e02d6f0f25141 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:39:13 +0000 Subject: [PATCH 029/260] fix(skills): read Dirent.path when parentPath is missing in the migrate-email test Node 20.11, the oldest release engines allows, has no Dirent.parentPath, so the bundle tests threw before their assertions. Use the same parentPath ?? path fallback as build-phases.js. Co-Authored-By: Claude Opus 5.5 --- scripts/lib/tests/migrate-email-skill.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/lib/tests/migrate-email-skill.test.js b/scripts/lib/tests/migrate-email-skill.test.js index 14044d5ef..67217f510 100644 --- a/scripts/lib/tests/migrate-email-skill.test.js +++ b/scripts/lib/tests/migrate-email-skill.test.js @@ -44,7 +44,7 @@ async function buildSkill(skillId, outputDir) { function markdownFiles(dir) { return readdirSync(dir, { withFileTypes: true, recursive: true }) .filter((entry) => entry.isFile() && entry.name.endsWith('.md')) - .map((entry) => join(entry.parentPath, entry.name)); + .map((entry) => join(entry.parentPath ?? entry.path, entry.name)); } function unresolvedReferences(skillDir) { From 2c368531a9a0718218f90b2c76933a3101968317 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:39:22 +0000 Subject: [PATCH 030/260] fix(migrate-email): match account.md's template-content rule to Step 3 account.md said template content goes only into a temporary file, while Step 3 reads the person's dashboard copies where they saved them. Only an API answer goes into the temporary file now. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/resend/account.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/context/skills/migrate-email/references/resend/account.md b/context/skills/migrate-email/references/resend/account.md index 22e6461c9..920c5a8d4 100644 --- a/context/skills/migrate-email/references/resend/account.md +++ b/context/skills/migrate-email/references/resend/account.md @@ -30,7 +30,7 @@ A site whose template the person moves to PostHog needs the template's content, **Read from the API.** `GET https://api.resend.com/templates/{id or alias}` with `Authorization: Bearer $RESEND_FULL_ACCESS_API_KEY`. The answer holds `alias`, `name`, `subject`, `from`, `reply_to`, `html`, `text`, and `variables`, a list of `{ key, type, fallback_value }`. -The content goes only into the temporary file Step 3 saves. Never write it into the plan or the report. +Read the person's copies where they saved them. An API answer goes only into the temporary file Step 3 writes, which Step 3 deletes once the site is classified. Never write the content into the plan or the report. ## Suppression list From 8dcf6e74a3d41ad5ecce98ab6da44bfe1c47e406 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:49:02 +0000 Subject: [PATCH 031/260] fix(migrate-email): keep a site on Resend when its idempotency key doesn't fit PostHog's PostHog takes an idempotency key of 1 to 255 printable ASCII characters without spaces. A site whose key can hold a space or a non-ASCII character, or run longer, stays on Resend. The report names each key a retry across the deploy could send twice, since the providers don't share keys. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/7-report.md | 2 +- context/skills/migrate-email/references/resend/mapping.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/context/skills/migrate-email/references/7-report.md b/context/skills/migrate-email/references/7-report.md index 8a321c0f0..fc974a0c9 100644 --- a/context/skills/migrate-email/references/7-report.md +++ b/context/skills/migrate-email/references/7-report.md @@ -51,7 +51,7 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- ## Before cutover - + ## Summary ``` diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index 31be4fd5e..a3d12a58e 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -18,7 +18,7 @@ This file decides, field by field, whether PostHog can send a Resend call site. | `headers` | none | Always | | `tags` | none | Always | | `attachments` | none | Always | -| `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | Never. The key keeps its value | +| `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | The key can hold a space or a non-ASCII character, or be longer than 255 characters. Otherwise the key keeps its value, and PostHog keeps it for 24 hours as Resend does. The two providers don't share keys: a retry that runs after the deploy, of a send Resend already took, sends a second email. Note it in the report | | `scheduledAt` / `scheduled_at` | none | Always | | `topicId` / `topic_id` | none | Always | From 07dbf3a6d437e002f66801ef7a973514a96e870c Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:49:17 +0000 Subject: [PATCH 032/260] fix(migrate-email): name PostHog's idempotency key rule exactly Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/resend/mapping.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/context/skills/migrate-email/references/resend/mapping.md b/context/skills/migrate-email/references/resend/mapping.md index a3d12a58e..d72d5ed3a 100644 --- a/context/skills/migrate-email/references/resend/mapping.md +++ b/context/skills/migrate-email/references/resend/mapping.md @@ -18,7 +18,7 @@ This file decides, field by field, whether PostHog can send a Resend call site. | `headers` | none | Always | | `tags` | none | Always | | `attachments` | none | Always | -| `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | The key can hold a space or a non-ASCII character, or be longer than 255 characters. Otherwise the key keeps its value, and PostHog keeps it for 24 hours as Resend does. The two providers don't share keys: a retry that runs after the deploy, of a send Resend already took, sends a second email. Note it in the report | +| `idempotencyKey` / `Idempotency-Key` | `idempotencyKey` / `Idempotency-Key` | The key can hold anything but visible ASCII characters, such as a space, or be longer than 255 characters. PostHog takes 1 to 255 visible ASCII characters. Otherwise the key keeps its value, and PostHog keeps it for 24 hours as Resend does. The two providers don't share keys: a retry that runs after the deploy, of a send Resend already took, sends a second email. Note it in the report | | `scheduledAt` / `scheduled_at` | none | Always | | `topicId` / `topic_id` | none | Always | From 21f683e38f1d2986e6d7ebec9bd960ebdf35c258 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:49:52 +0000 Subject: [PATCH 033/260] fix(migrate-email): end Step 8's email check when the person declines the test email Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/8-verify.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 1b29050e9..c0efde366 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -27,7 +27,7 @@ The chain to prove: PostHog sends the email, records its engagement on the perso Skip this part and record `not checked` with the reason when the API is not confirmed on, no sender is verified, or `POSTHOG_PROJECT_SECRET_API_KEY` is not set. 1. Check that the app sends to the MCP's project: compare the project token the app reads with `api_token` from the PostHog MCP `projects-get` tool. Read only the token's line of the env file, by searching for the token variable's name: the file also holds secret keys, so never open all of it. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. -2. Ask the person whether to send one test email. Say that it sends a real email. When they say no, record `not checked: declined`. +2. Ask the person whether to send one test email. Say that it sends a real email. When they say no, record `not checked: declined`, and skip the rest of this part. 3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app that sends it to an address they own, from a site that passes `distinctId`, such as a signup or a password reset. When no moved site passes `distinctId`, record `not checked: no moved site names a person`, and skip the rest of this part. Ask them to open the email, then to sign in as the user it went to and use the app for a moment, so that the app's product events show on the same distinct ID. Ask them to tell you when they are done. 4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. 5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test, with a new random string each time you run it: From d1578595a5c728361869f3d7b27c3096eacfe778 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:31:31 +0000 Subject: [PATCH 034/260] docs(migrate-email): say where a send without distinctId lands Rename "Find the user ID" to "Link emails to your users", name the identify() ID, say that without distinctId PostHog records the email on a separate person keyed by the address, and add invites and signup checks to the cases that leave it out. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/7-rewrite.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index eefe42ebe..795cf7031 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -50,13 +50,14 @@ export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { - Put a new client in its own server-only module, next to the provider's client, and import it where the sites send. - Use the env variable names the app already uses for the PostHog token and host. Add each new name, without a value, to the env example file. -## Find the user ID +## Link emails to your users -PostHog shows each email on the person the send names with `distinctId`. Use the ID the app already identifies people with in PostHog: +PostHog records each send, and its sent, opened and clicked events when engagement events are on, against the person the send names with `distinctId`. Pass the ID the app already passes to `identify()`: - Find the app's identify call, such as `posthog.identify(user.id)` in posthog-js, or the `distinctId` of its `posthog-node` captures. - At each site, pass the same ID for the recipient, such as `distinctId: user.id`. Follow the recipient back through the callers when the site only has the address. -- When the recipient is not a user of the app, such as a team inbox, or the site has no way to know the user, leave `distinctId` out and note it in the plan row. +- Without `distinctId`, PostHog records the email against a person whose distinct ID is the recipient's address. Unless the app identifies people by their address, that is a separate person from the user. +- When the recipient isn't a user yet, such as an invite or a check during signup, isn't a user at all, such as a team inbox, or the site has no way to know the user, leave `distinctId` out and note it in the plan row. - When the app identifies no one in PostHog, use the app's own user ID, and note it for the report. ## Rewrite each site From 5dcdd2180bfd06f5a5daadbbceda8e1296b6da30 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:35:35 +0000 Subject: [PATCH 035/260] docs(migrate-email): test Step 8 on a site that passes distinctId Step 7 now leaves distinctId off an address check before the account exists, so Step 8 picks its test site from the plan rows that pass one. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/references/7-rewrite.md | 2 +- context/skills/migrate-email/references/8-verify.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index 795cf7031..08484a90d 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -57,7 +57,7 @@ PostHog records each send, and its sent, opened and clicked events when engageme - Find the app's identify call, such as `posthog.identify(user.id)` in posthog-js, or the `distinctId` of its `posthog-node` captures. - At each site, pass the same ID for the recipient, such as `distinctId: user.id`. Follow the recipient back through the callers when the site only has the address. - Without `distinctId`, PostHog records the email against a person whose distinct ID is the recipient's address. Unless the app identifies people by their address, that is a separate person from the user. -- When the recipient isn't a user yet, such as an invite or a check during signup, isn't a user at all, such as a team inbox, or the site has no way to know the user, leave `distinctId` out and note it in the plan row. +- When the recipient isn't a user yet, such as an invite or an address check before the account exists, isn't a user at all, such as a team inbox, or the site has no way to know the user, leave `distinctId` out and note it in the plan row. - When the app identifies no one in PostHog, use the app's own user ID, and note it for the report. ## Rewrite each site diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index c0efde366..75f522ee6 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -28,7 +28,7 @@ Skip this part and record `not checked` with the reason when the API is not conf 1. Check that the app sends to the MCP's project: compare the project token the app reads with `api_token` from the PostHog MCP `projects-get` tool. Read only the token's line of the env file, by searching for the token variable's name: the file also holds secret keys, so never open all of it. When they differ, record `not checked: the app uses another project`, tell the person which project the app uses, and skip the rest of this part. 2. Ask the person whether to send one test email. Say that it sends a real email. When they say no, record `not checked: declined`, and skip the rest of this part. -3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app that sends it to an address they own, from a site that passes `distinctId`, such as a signup or a password reset. When no moved site passes `distinctId`, record `not checked: no moved site names a person`, and skip the rest of this part. Ask them to open the email, then to sign in as the user it went to and use the app for a moment, so that the app's product events show on the same distinct ID. Ask them to tell you when they are done. +3. Run `SELECT toUnixTimestamp(now()), ''` through the PostHog MCP `execute-sql` tool, so the answer can't come from a cached run, and keep the number as the start of the test; skip this when the MCP has no SQL tool. Ask them to trigger one moved email in their local app that sends it to an address they own, from a site whose plan row shows it passes `distinctId`, such as a password reset or a welcome email after signup. When no moved site passes `distinctId`, record `not checked: no moved site names a person`, and skip the rest of this part. Ask them to open the email, then to sign in as the user it went to and use the app for a moment, so that the app's product events show on the same distinct ID. Ask them to tell you when they are done. 4. When the send fails, find its code in `transactional-emails.md` or `api.md`, tell the person the fix, and record it. Never retry a send yourself. 5. Find the person's distinct ID: the value the moved site passed as `distinctId`. Run a SQL query through the PostHog MCP `execute-sql` tool for that distinct ID since the start of the test, with a new random string each time you run it: From 78d36da0a7c6a81f802246b551ddef4f47c0ecf7 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:14:46 +0000 Subject: [PATCH 036/260] feat(skills): move SendGrid sends to PostHog in every SDK language Add a SendGrid variant to migrate-email, and make the shared steps move a site in any language with a PostHog email send, from posthog-sdks.md. Step 3 records each site's language and the provider's webhook handlers, and the report lists the PostHog events that take their place. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/config.yaml | 5 +- context/skills/migrate-email/description.md | 8 +- .../migrate-email/references/1-detect.md | 2 +- .../migrate-email/references/3-inventory.md | 7 +- .../migrate-email/references/7-rewrite.md | 42 ++- .../migrate-email/references/8-verify.md | 6 +- .../migrate-email/references/9-report.md | 6 +- .../migrate-email/references/posthog-sdks.md | 239 ++++++++++++++++++ .../references/sendgrid/account.md | 63 +++++ .../references/sendgrid/mapping.md | 133 ++++++++++ .../references/sendgrid/sdk-reference.md | 184 ++++++++++++++ scripts/lib/tests/migrate-email-skill.test.js | 29 ++- 12 files changed, 686 insertions(+), 38 deletions(-) create mode 100644 context/skills/migrate-email/references/posthog-sdks.md create mode 100644 context/skills/migrate-email/references/sendgrid/account.md create mode 100644 context/skills/migrate-email/references/sendgrid/mapping.md create mode 100644 context/skills/migrate-email/references/sendgrid/sdk-reference.md diff --git a/context/skills/migrate-email/config.yaml b/context/skills/migrate-email/config.yaml index 8becd4c82..1d9496364 100644 --- a/context/skills/migrate-email/config.yaml +++ b/context/skills/migrate-email/config.yaml @@ -2,7 +2,7 @@ type: skill template: description.md category: migrate -description: Migrate transactional email from {display_name} to PostHog. Use when asked to migrate from {display_name}, replace {display_name} with PostHog, or switch email providers. It finds every {display_name} send in the code, sets up the sender and DNS next to {display_name}'s records, imports {display_name}'s suppression list, moves each send PostHog can take to posthog-node, and writes a migration report that lists the sends that stay. +description: Migrate transactional email from {display_name} to PostHog. Use when asked to migrate from {display_name}, replace {display_name} with PostHog, or switch email providers. It finds every {display_name} send in the code, sets up the sender and DNS next to {display_name}'s records, imports {display_name}'s suppression list, moves each send PostHog can take to the PostHog SDK in the app's language, and writes a migration report that lists the sends that stay. tags: [migration, workflows] cli: role: command @@ -16,3 +16,6 @@ variants: - id: resend display_name: Resend tags: [resend] + - id: sendgrid + display_name: SendGrid + tags: [sendgrid] diff --git a/context/skills/migrate-email/description.md b/context/skills/migrate-email/description.md index b36e4c43a..2a91d25f9 100644 --- a/context/skills/migrate-email/description.md +++ b/context/skills/migrate-email/description.md @@ -2,7 +2,7 @@ Use this skill to move an app's transactional email, such as welcome emails, password resets, and receipts, from {display_name} to PostHog. -It finds every {display_name} send, sets up the PostHog sender and its DNS records next to {display_name}'s, imports {display_name}'s suppression list, and hands over the PostHog secret key. Then it moves every send PostHog can take to `posthog-node`, checks one email on one person, and writes a report. Sends PostHog can't take stay on {display_name} with a reason, so both providers send during the cutover. +It finds every {display_name} send, sets up the PostHog sender and its DNS records next to {display_name}'s, imports {display_name}'s suppression list, and hands over the PostHog secret key. Then it moves every send PostHog can take to the PostHog SDK in the app's language, checks one email on one person, and writes a report. Sends PostHog can't take stay on {display_name} with a reason, so both providers send during the cutover. The transactional email API is in beta. PostHog enables it per project. @@ -20,6 +20,8 @@ The folder `references//` holds everything specific to {display_name}. - `mapping.md`: how each send field maps to PostHog, what keeps a call site on {display_name}, and how to rewrite a site that moves. - `account.md`: {display_name}'s DNS records, and how to get its templates and its suppression list. +`posthog-sdks.md`, next to the step files, has PostHog's email send in each language the sites can move in. + Everything you need is on disk. Do not fetch {display_name}'s docs. ## Plan file @@ -28,7 +30,7 @@ The plan file `.posthog-email-migration-plan.md` lives at the project root. Step ## Rules -- Change send code only in Step 7, and fix it only in Step 8: the sites that move, the helpers, callers, and tests they need, and other `posthog-node` code that the upgrade breaks. Leave every site that stays as it is. +- Change send code only in Step 7, and fix it only in Step 8: the sites that move, the helpers, callers, and tests they need, and other PostHog SDK code that the upgrade breaks. Leave every site that stays as it is. - Never touch DNS or the {display_name} account. Give the person the records and the links, and let them make the change. - Never remove the {display_name} package or its API key. The report tells the person when to remove them. - Never create, upload, or edit a template in PostHog. The person makes each template that moves to PostHog. @@ -54,4 +56,4 @@ Outside the Wizard, skip the `[STATUS]` lines, and tell the person why you stopp `transactional-emails.md` is the transactional email overview. It covers how to create a transactional email and its API key, idempotency, and the error codes. `api.md` covers the send route, including content from your code, and the checks of a send. -When the `sending-transactional-emails` skill is available, read it for the PostHog side of a send. Its `moving-from-other-providers.md` moves sends to a template stored in PostHog. This skill moves {display_name}'s sends to `posthog-node`, with the content in the app's code, or to a template the person makes in PostHog. Where the two disagree, this skill's steps win. +When the `sending-transactional-emails` skill is available, read it for the PostHog side of a send. Its `moving-from-other-providers.md` moves sends to a template stored in PostHog. This skill moves {display_name}'s sends to the PostHog SDK, with the content in the app's code, or to a template the person makes in PostHog. Where the two disagree, this skill's steps win. diff --git a/context/skills/migrate-email/references/1-detect.md b/context/skills/migrate-email/references/1-detect.md index fd4a47d30..51d270902 100644 --- a/context/skills/migrate-email/references/1-detect.md +++ b/context/skills/migrate-email/references/1-detect.md @@ -19,7 +19,7 @@ Read the provider's `sdk-reference.md`. It lists the provider's packages, import The provider is in this project when at least one of these is true: -- Its package is in a dependency manifest, such as `package.json`, `requirements.txt`, `pyproject.toml`, `Gemfile`, `composer.json`, or `go.mod`. +- Its package is in a dependency manifest, such as `package.json`, `requirements.txt`, `pyproject.toml`, `Gemfile`, `composer.json`, `go.mod`, a `.csproj` file, `mix.exs`, or `Cargo.toml`. - Source code imports it or creates its client. - Source code calls its HTTP host. - Source code, mail config, or an example env file names its SMTP host or its framework mailer. diff --git a/context/skills/migrate-email/references/3-inventory.md b/context/skills/migrate-email/references/3-inventory.md index b65ec83a2..c72e246e4 100644 --- a/context/skills/migrate-email/references/3-inventory.md +++ b/context/skills/migrate-email/references/3-inventory.md @@ -26,6 +26,7 @@ A **site** is one place in the code that decides what a send contains: its conte For each site, read the surrounding code and record: - The file and the line of the call. +- The language it is written in, such as `ts`, `py`, `rb`, `php`, `go`, `cs`, `ex`, or `rs`. - How it sends: `sdk`, `http`, or `smtp`. - The content: `template` for a template stored at the provider, `react` for a component the provider renders, `html`, or `text`. A site that sets both `html` and `text` is `html`. - Every field the site sets, including fields set on the payload object after it is created and fields set through options, such as an idempotency key. @@ -33,6 +34,8 @@ For each site, read the surrounding code and record: Also list every other call to the provider that is not a send, such as reading an email's status, contacts, or domains. These calls stay on the provider. Note what each one does, because a site whose code reads the status back stays on the provider too. +When `sdk-reference.md` has a "Webhooks" section, also list each webhook handler: a route of the app that receives the provider's delivery events. Note the events it handles, what it does with them, and how it finds the send an event belongs to, such as by the provider's message id, by a value the send set, or by the recipient's address. `mapping.md` says under "Webhooks" which sites a handler keeps on the provider. + When you find no site, stop before you write the plan file: ``` @@ -70,9 +73,9 @@ A phase checklist, in this order. Tick `preflight` with what Step 2 recorded, an A sites table, one row per site, in source tree order: ``` -| site | file | line | sends | content | from | moves | reason | +| site | file | line | lang | sends | content | from | moves | reason | ``` `moves` is `yes` or `no`. `reason` is empty when the site moves. -A list of the other provider calls, each with its file, line, and what it does. +A list of the other provider calls, each with its file, line, and what it does, and a list of the webhook handlers, each with its file, line, the events it handles, and how it finds the send. diff --git a/context/skills/migrate-email/references/7-rewrite.md b/context/skills/migrate-email/references/7-rewrite.md index 08484a90d..1a41a737e 100644 --- a/context/skills/migrate-email/references/7-rewrite.md +++ b/context/skills/migrate-email/references/7-rewrite.md @@ -5,12 +5,12 @@ next_step: 8-verify.md # Step 7, move every site that can move -Rewrite each site whose `moves` is `yes` in the plan to send with `posthog-node`. The provider's `mapping.md` has the rewrite of each field, call, and content form under "Rewrite". +Rewrite each site whose `moves` is `yes` in the plan to send with PostHog's SDK in the site's language. The provider's `mapping.md` has the rewrite of each field, call, and content form under "Rewrite". ## Status ``` -[STATUS] Setting up posthog-node for email +[STATUS] Setting up the PostHog SDK for email [STATUS] Moving the send call sites ``` @@ -18,35 +18,27 @@ Rewrite each site whose `moves` is `yes` in the plan to send with `posthog-node` - Change only the sites whose `moves` is `yes`. Never change a site that stays, and never change a line that a site that stays still needs. - When no site moves, tick the phase in the plan with `none moved` and go to the next step. -- Run the project's typecheck, such as its `typecheck` script or `tsc --noEmit`, or its build when it has no typecheck, and keep its errors: Step 8 compares with them. +- Run the project's typecheck for each language a moving site is written in, such as its `typecheck` script, `tsc --noEmit`, `mypy`, `go vet`, or `dotnet build`, or its build when it has no typecheck, and keep its errors: Step 8 compares with them. ## Set up the client -Install or upgrade `posthog-node` to its latest release with the project's package manager. `posthog.emails` alone is not enough: early releases send only a template made in PostHog, by `templateId`. Check the installed package's types for what the moving sites need: +Each site moves with the PostHog SDK of the language it is written in. Read the part of `posthog-sdks.md` for each such language. A site in a language that `posthog-sdks.md` doesn't list stays: mark its row `moves: no — PostHog has no email send in yet`. -- a site with `html`, `text`, or a component: `posthog.emails.send` takes `templateKey` with `subject` and `html` or `text`; -- a site that sets `replyTo`: the send takes `replyTo`; -- the client: the client options take `migratedFrom`. - -When the latest release lacks one of these, change no site that needs it. Mark each such row `moves: no — posthog-node has no yet`, tell the person, and go on with the rest. When the client options lack `migratedFrom`, leave it out of the client. When no site is left, undo the install or upgrade of `posthog-node`, tick the phase with `none moved`, and go to the next step. +Install or upgrade the language's PostHog SDK to its latest release with the project's package manager. `emails.send` alone is not enough: early releases send only a template made in PostHog. Check the installed package's types or source for what the moving sites need, as `posthog-sdks.md` says under "Check the installed release": -Configure one server-side client for email: +- a site with `html`, `text`, or a component: the send takes `templateKey` with `subject` and `html` or `text`; +- each other field a site sets, such as `replyTo`, `cc`, `bcc`, or `attachments`: the send takes it; +- the client: the client options take `migratedFrom`. -```js -import { PostHog } from 'posthog-node' +When the latest release lacks one of these, change no site that needs it. Mark each such row `moves: no — has no yet`, tell the person, and go on with the rest. When the client options lack `migratedFrom`, leave it out of the client. When no site in a language is left, undo the install or upgrade of that language's SDK. When no site is left at all, tick the phase with `none moved`, and go to the next step. -export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { - host: process.env.POSTHOG_HOST, - secretKey: process.env.POSTHOG_PROJECT_SECRET_API_KEY, - enableLocalEvaluation: false, - migratedFrom: '', // only when the client options take it -}) -``` +Configure one server-side client per language, as `posthog-sdks.md` shows: -- When the client options take `migratedFrom`, set it to the value that the provider's `mapping.md` names under "The PostHog client". posthog-node sends it with every email request, so PostHog knows that the sends moved from that provider. -- Reuse the app's existing `posthog-node` client when it has one, and add `secretKey`, and `migratedFrom` when the client options take it. Keep `enableLocalEvaluation: false` unless the key also has `feature_flag:read` and the app uses local evaluation. +- Set the secret key from `POSTHOG_PROJECT_SECRET_API_KEY`. +- When the client options take `migratedFrom`, set it to the value that the provider's `mapping.md` names under "The PostHog client". The SDK sends it with every email request, so PostHog knows that the sends moved from that provider. +- Reuse the app's existing PostHog client in that language when it has one, and add the secret key, and `migratedFrom` when the client options take it. Where `posthog-sdks.md` says the secret key turns on local feature flag evaluation, keep it off unless the key also has `feature_flag:read` and the app uses local evaluation. - When the project token or the host is not configured yet, get the token from the PostHog MCP `projects-get` tool (`api_token`). The host is `https://us.i.posthog.com` for US Cloud and `https://eu.i.posthog.com` for EU Cloud. Ask the person which one when you can't tell. -- When `host` is a reverse proxy or a self-hosted instance, also set `appHost` to the PostHog app URL, such as `https://us.posthog.com`. posthog-node never sends the secret key to a proxy, and without `appHost` the send fails with `missing_app_host`. +- When the host is a reverse proxy or a self-hosted instance, also set the app host to the PostHog app URL, such as `https://us.posthog.com`. The SDK never sends the secret key to a proxy, and without the app host the send fails with `missing_app_host`. - Put a new client in its own server-only module, next to the provider's client, and import it where the sites send. - Use the env variable names the app already uses for the PostHog token and host. Add each new name, without a value, to the env example file. @@ -54,7 +46,7 @@ export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { PostHog records each send, and its sent, opened and clicked events when engagement events are on, against the person the send names with `distinctId`. Pass the ID the app already passes to `identify()`: -- Find the app's identify call, such as `posthog.identify(user.id)` in posthog-js, or the `distinctId` of its `posthog-node` captures. +- Find the app's identify call, such as `posthog.identify(user.id)` in posthog-js, or the distinct ID of its server-side captures. - At each site, pass the same ID for the recipient, such as `distinctId: user.id`. Follow the recipient back through the callers when the site only has the address. - Without `distinctId`, PostHog records the email against a person whose distinct ID is the recipient's address. Unless the app identifies people by their address, that is a separate person from the user. - When the recipient isn't a user yet, such as an invite or an address check before the account exists, isn't a user at all, such as a team inbox, or the site has no way to know the user, leave `distinctId` out and note it in the plan row. @@ -69,11 +61,11 @@ For each site that moves, in plan order: - A site that moves to a template made in PostHog sends the template ID the person gave in Step 3, never one you guess. - Install `@react-email/render` with the project's package manager when a site renders a component and the app doesn't have it. - Keep the site's idempotency key, error branches, logging, and return value working as before. Keep the code around the send unchanged where you can. -- `posthog.emails.send` never throws on an API error: it returns `{ data, error }`. When the old call threw on an error, or the code checked an HTTP status, check `error` so the site fails the same way. +- Keep the site failing the same way it did. `posthog-sdks.md` says how the SDK reports an error in each language: Node.js answers `{ data, error }` and never throws on an API error, and the other languages raise or return an error value. When the old call threw on an error, or the code checked a status, check PostHog's error so the site fails the same way, as the provider's `mapping.md` says under "Rewrite". - Never add a field that the old call didn't set, apart from `templateKey`, `templateId`, and `distinctId`. `templateData` takes the place of the provider's template variables. When a site turns out to need something `mapping.md` keeps on the provider, undo its change, set `moves` to `no` with the reason, and go on. ## Write down -Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`, or its `templateId` for a template made in PostHog. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each site that got a branch for a suppressed recipient, each idempotency key a retry across the deploy could send twice, each new dependency, each upgraded one with its old and new version, and each new env variable name. +Tick the phase in the plan: `- [x] rewrite — sites moved`. Add a `key` column to the sites table with each moved site's `templateKey`, or its `templateId` for a template made in PostHog. Under the table, note each site without a `distinctId`, each fallback that an empty string now replaces, each site that got a branch for a suppressed recipient, each idempotency key a retry across the deploy could send twice, each value the move changed, such as a recipient name the To line loses, each new dependency, each upgraded one with its old and new version, and each new env variable name. diff --git a/context/skills/migrate-email/references/8-verify.md b/context/skills/migrate-email/references/8-verify.md index 75f522ee6..dfcde4f9e 100644 --- a/context/skills/migrate-email/references/8-verify.md +++ b/context/skills/migrate-email/references/8-verify.md @@ -16,9 +16,9 @@ Check that the app still builds, its tests still pass, and one moved email reach ## Build and tests -- Run the project's typecheck, such as its `typecheck` script or `tsc --noEmit`, or its build when it has no typecheck. Fix each error that is not in the list Step 7 kept, in any file: the rewrite or the posthog-node upgrade caused it. Note each file you fix outside the moved sites for the report. An error in that list was there before: note it, and leave it. -- Run the tests that cover the files you changed. A test that mocks the provider's client or intercepts its HTTP requests for a moved site now mocks `posthog.emails.send` and asserts on the fields it gets, with the same expected values. Never turn a PostHog send back into the provider's request shape to keep an old assertion. Never delete or skip a test. -- Search the changed files for the provider's calls: a moved site has none left, and each moved site has one `posthog.emails.send`. +- Run the typechecks Step 7 ran, or each build when there is no typecheck. Fix each error that is not in the list Step 7 kept, in any file: the rewrite or the PostHog SDK upgrade caused it. Note each file you fix outside the moved sites for the report. An error in that list was there before: note it, and leave it. +- Run the tests that cover the files you changed. A test that mocks the provider's client or intercepts its HTTP requests for a moved site now mocks the PostHog email send and asserts on the fields it gets, with the same expected values. Never turn a PostHog send back into the provider's request shape to keep an old assertion. Never delete or skip a test. +- Search the changed files for the provider's calls: a moved site has none left, and each moved site has one PostHog email send. ## One email on one person diff --git a/context/skills/migrate-email/references/9-report.md b/context/skills/migrate-email/references/9-report.md index 4562e9f1a..7a2eec126 100644 --- a/context/skills/migrate-email/references/9-report.md +++ b/context/skills/migrate-email/references/9-report.md @@ -35,6 +35,10 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- .> +## Webhook handlers + + events it handles, and the PostHog events that take their place for the moved sends, from `mapping.md` under "Webhooks". Say that the handler keeps getting events for the sites that stay, that moved sends no longer reach it, that PostHog records their events on the person only when engagement events are on for the project, and that a webhook destination in PostHog (Data pipelines, then Destinations) can post those events to an endpoint, in PostHog's shape, not the provider's.> + ## Sender and DNS @@ -59,7 +63,7 @@ Read `.posthog-email-migration-plan.md`. Write `posthog-migrate-email- The moved sites send through PostHog as soon as this code is deployed. Everything in this list has to be done before that deploy. - + ## After cutover diff --git a/context/skills/migrate-email/references/posthog-sdks.md b/context/skills/migrate-email/references/posthog-sdks.md new file mode 100644 index 000000000..898b20009 --- /dev/null +++ b/context/skills/migrate-email/references/posthog-sdks.md @@ -0,0 +1,239 @@ +--- +title: PostHog's email send in each language +description: The PostHog SDK, client, send, and errors for each language a site can move in +--- + +# PostHog's email send in each language + +How each PostHog server SDK sends an email. Step 7 reads the part for each language a moving site is written in. The provider's `mapping.md` gives the fields in their Node.js names: use the names below for other languages. + +Every SDK sends one email per call to one `to` address, in one of two forms: + +- **Code form:** `templateKey`, `subject`, and `html`, `text`, or both, with optional `from`, `replyTo`, `cc`, `bcc`, `attachments`, and `captureEngagement`. +- **Template form:** `templateId` with optional `templateData`, for a template made in PostHog. It takes none of the code form's fields. + +Both forms take `distinctId`, `idempotencyKey`, and `maxRetries`. No SDK takes `headers`, `tags`, a send time, several `to` addresses, or an attachment by path or URL: read a file into its content first. + +## Check the installed release + +Read the installed package's own types or source, not this file, to see what it takes. Early releases send only the template form, and the fields came in this order: + +1. `emails.send` with the template form. +2. The code form (`templateKey`, `subject`, `html`, `text`, `from`, `replyTo`, `captureEngagement`), and the client option `migratedFrom`. +3. `cc`, `bcc`, and `attachments`, in Node.js, Python, Go, and Elixir. Ruby, PHP, .NET, and Rust have no `cc`, `bcc`, or `attachments` yet. + +A language with no row below has no PostHog email send yet, such as Java, Kotlin, Swift, or Dart: its sites stay on the provider with the reason `PostHog has no email send in yet`. + +## Names in each language + +| Node.js | Python | Ruby, PHP, Elixir | Go | .NET | Rust builder | +|---|---|---|---|---|---| +| `to` | `to` | `to` | `To` | `To` | `new(to, …)` | +| `distinctId` | `distinct_id` | `distinct_id` | `DistinctID` | `DistinctId` | `.distinct_id()` | +| `idempotencyKey` | `idempotency_key` | `idempotency_key` | `IdempotencyKey` | `IdempotencyKey` | `.idempotency_key()` | +| `templateId` | `template_id` | `template_id` | `TemplateID` | `TemplateId` (a `Guid`) | `TemplateEmail::new(to, id)` | +| `templateData` | `template_data` | `template_data` | `TemplateData` | `TemplateData` | `.template_data()` | +| `templateKey` | `template_key` | `template_key` | `TemplateKey` | `TemplateKey` | `CodeEmail::new(to, key, subject)` | +| `subject`, `html`, `text` | the same | the same | `Subject`, `HTML`, `Text` | `Subject`, `Html`, `Text` | `.html()`, `.text()` | +| `from` | `from_` | `from` | `From` | `From` | `.from()` | +| `replyTo` | `reply_to` | `reply_to` | `ReplyTo` (`[]string`) | `ReplyTo` (a list) | `.reply_to()`, once per address | +| `cc`, `bcc` | `cc`, `bcc` | `cc`, `bcc` (Elixir only) | `Cc`, `Bcc` (`[]string`) | none | none | +| `attachments` | `attachments` | `attachments` (Elixir only) | `Attachments` | none | none | +| `captureEngagement` | `capture_engagement` | `capture_engagement` | `CaptureEngagement` (`*bool`) | `CaptureEngagement` | `.capture_engagement()` | + +An attachment is `{ filename, content, contentType, contentId }`, in each language's case, and `contentId` shows the file inline as ``: + +- Node.js: `content` is a `Buffer`, a `Uint8Array`, or a base64 string. +- Python: `content` is `bytes` or a base64 string. +- Go: `Content` is `[]byte` of the raw file. Decode a base64 string first. +- Elixir: `content` is the raw binary. Decode a base64 string first: the SDK encodes it again. + +## Node.js: `posthog-node` + +```js +import { PostHog } from 'posthog-node' + +export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN, { + host: process.env.POSTHOG_HOST, + secretKey: process.env.POSTHOG_PROJECT_SECRET_API_KEY, + enableLocalEvaluation: false, + migratedFrom: '', +}) + +const { data, error } = await posthog.emails.send({ + to: 'jane@example.com', + distinctId: user.id, + templateKey: 'welcome', + subject: 'Welcome', + html, +}) +``` + +- Errors: `send` never throws on an API error. It answers `{ data, error }`: `data.id` is the message id, and `error` has `name`, `code`, `message`, and `statusCode`. A bad argument comes back as `error` too. +- `enableLocalEvaluation: false`: the secret key also turns on local feature flag evaluation. Keep it off unless the key has `feature_flag:read` and the app uses local evaluation. +- A component the provider rendered, such as React Email, is rendered in the app with `render` from `@react-email/render`, and sent as `html`. + +## Python: `posthog` + +```python +from posthog import Posthog +from posthog.emails import EmailError + +posthog = Posthog( + os.environ["POSTHOG_PROJECT_TOKEN"], + host=os.environ["POSTHOG_HOST"], + secret_key=os.environ["POSTHOG_PROJECT_SECRET_API_KEY"], + migrated_from="", +) + +result = posthog.emails.send( + to="jane@example.com", + distinct_id=str(user.id), + template_key="welcome", + subject="Welcome", + html=html, +) +``` + +- Errors: `send` raises `posthog.emails.EmailError` on an API error, with `.code`, `.name`, `.status_code`, and `.message`. A bad argument raises `TypeError` or `ValueError`. It answers a result whose `.id` is the message id. +- Async apps use `AsyncPosthog` from `posthog`, and `await posthog.emails.send(...)`. + +## Go: `github.com/posthog/posthog-go` + +```go +client, err := posthog.NewWithConfig(os.Getenv("POSTHOG_PROJECT_TOKEN"), posthog.Config{ + Endpoint: os.Getenv("POSTHOG_HOST"), + SecretKey: os.Getenv("POSTHOG_PROJECT_SECRET_API_KEY"), + MigratedFrom: "", +}) + +result, err := client.Emails().Send(ctx, posthog.CodeEmail{ + To: "jane@example.com", + DistinctID: user.ID, + TemplateKey: "welcome", + Subject: "Welcome", + HTML: html, +}) +``` + +- The template form is `posthog.TemplateEmail{To, TemplateID, TemplateData, ...}`. +- Errors: `Send` answers `(*SendEmailResult, error)`, and `result.ID` is the message id. The error is always a `*posthog.EmailError`, with `Code`, `Name`, `Message`, and `StatusCode`. Read it with `errors.As`. +- A site with no `context.Context` passes `context.Background()`. + +## Ruby: `posthog-ruby` + +```ruby +posthog = PostHog::Client.new( + api_key: ENV['POSTHOG_PROJECT_TOKEN'], + host: ENV['POSTHOG_HOST'], + secret_key: ENV['POSTHOG_PROJECT_SECRET_API_KEY'], + migrated_from: '' +) + +result = posthog.emails.send( + to: 'jane@example.com', + distinct_id: user.id.to_s, + template_key: 'welcome', + subject: 'Welcome', + html: html +) +``` + +- Errors: `send` raises `PostHog::EmailError` on an API error, with `#code`, `#name`, `#status_code`, and `#message`. A bad argument raises `ArgumentError`. It answers a result whose `id` is the message id. + +## PHP: `posthog/posthog-php` + +```php +PostHog::init(getenv('POSTHOG_PROJECT_TOKEN'), [ + 'host' => getenv('POSTHOG_HOST'), + 'migrated_from' => '', +], secretKey: getenv('POSTHOG_PROJECT_SECRET_API_KEY')); + +$result = PostHog::emails()->send([ + 'to' => 'jane@example.com', + 'distinct_id' => (string) $user->id, + 'template_key' => 'welcome', + 'subject' => 'Welcome', + 'html' => $html, +]); +``` + +- An app that creates a client object uses `new \PostHog\Client($token, $options, secretKey: ...)` and `$client->emails()`. +- Errors: `send` throws `PostHog\EmailError` on an API error and on a bad argument, with `getErrorCode()`, `getErrorName()`, `getStatusCode()`, and `getMessage()`. It answers a result whose `getId()` is the message id. + +## .NET: `PostHog` + +```csharp +var posthog = new PostHogClient(new PostHogOptions +{ + ProjectToken = Environment.GetEnvironmentVariable("POSTHOG_PROJECT_TOKEN"), + HostUrl = new Uri(Environment.GetEnvironmentVariable("POSTHOG_HOST")), + SecretKey = Environment.GetEnvironmentVariable("POSTHOG_PROJECT_SECRET_API_KEY"), + MigratedFrom = "", +}); + +var sent = await posthog.Emails.SendAsync(new SendCodeEmailOptions +{ + To = "jane@example.com", + DistinctId = user.Id.ToString(), + TemplateKey = "welcome", + Subject = "Welcome", + Html = html, +}); +``` + +- The template form is `new SendTemplateEmailOptions { To, TemplateId, TemplateData }`. +- Apps that use dependency injection register the client with `AddPostHog` and take `IPostHogEmails`. +- Errors: `SendAsync` throws `PostHog.Emails.EmailException` on an API error, with `Code`, `Name`, `StatusCode`, and `Message`. A bad argument throws `ArgumentException`. `sent.Id` is the message id. There is no sync send. + +## Elixir: `posthog` + +```elixir +# config/runtime.exs +config :posthog, + api_key: System.get_env("POSTHOG_PROJECT_TOKEN"), + api_host: System.get_env("POSTHOG_HOST"), + secret_key: System.get_env("POSTHOG_PROJECT_SECRET_API_KEY"), + migrated_from: "", + enable_local_evaluation: false +``` + +```elixir +PostHog.Emails.send( + to: "jane@example.com", + distinct_id: to_string(user.id), + template_key: "welcome", + subject: "Welcome", + html: html +) +``` + +- Errors: `send` answers `{:ok, %PostHog.Emails.SendResult{id: id}}` or `{:error, %PostHog.Emails.Error{}}`, with `:code` (a string), `:name` (an atom, such as `:validation_error`), `:message`, and `:status_code`. A bad argument answers `{:error, ...}` too. +- `enable_local_evaluation: false`: the secret key also turns on local feature flag evaluation, as in Node.js. + +## Rust: `posthog-rs` + +```rust +let options = ClientOptionsBuilder::default() + .api_key(std::env::var("POSTHOG_PROJECT_TOKEN")?) + .host(std::env::var("POSTHOG_HOST")?) + .secret_key(std::env::var("POSTHOG_PROJECT_SECRET_API_KEY")?) + .migrated_from("") + .build()?; +let posthog = posthog_rs::client(options).await; + +let sent = posthog + .emails() + .send(CodeEmail::new("jane@example.com", "welcome", "Welcome").html(html).distinct_id(user.id.to_string())) + .await?; +``` + +- The template form is `TemplateEmail::new(to, template_id).template_data(json)`. +- Errors: `send` answers `Result`, and `sent.id` is the message id. Read `error.code()` and `error.kind()`. A build without the `async-client` feature sends without `.await`. + +## The answer in every language + +- The message id is PostHog's. It is not the provider's id. +- `name` follows Resend's error names, such as `validation_error` or `rate_limit_exceeded`. `code` is PostHog's own code, such as `recipient_suppressed`, `sender_not_verified`, or `quota_limited`. Branch on `code`. +- PostHog refuses a send to a suppressed address with the code `recipient_suppressed` (name `validation_error`). +- Every SDK retries network errors and rate limits on its own, with the same idempotency key, twice by default. diff --git a/context/skills/migrate-email/references/sendgrid/account.md b/context/skills/migrate-email/references/sendgrid/account.md new file mode 100644 index 000000000..31d7164cf --- /dev/null +++ b/context/skills/migrate-email/references/sendgrid/account.md @@ -0,0 +1,63 @@ +# SendGrid account + +What the migration needs from the person's SendGrid account. The agent never changes the account: it reads what the person exports or allows. + +## DNS records + +A domain authenticated at SendGrid carries these records. Keep all of them until the cutover is done. The SendGrid dashboard shows the exact names under Settings, then Sender Authentication. + +| Record | Name | What it does | +|---|---|---| +| `CNAME` | `em`, such as `em1234` | Return path for SendGrid's bounces, and its SPF | +| `CNAME` (DKIM) | `s1._domainkey`, `s2._domainkey` | Signs SendGrid's mail | +| `CNAME` | `url` and a second label of digits | Link branding, only when it is set up | +| `TXT` (DMARC) | `_dmarc` | Optional, shared by every provider on the domain | + +- A domain set up without automated security has an `MX` and an SPF `TXT` record on `em`, and a DKIM `TXT` record at `m1._domainkey`, in place of the CNAMEs. +- PostHog's sender uses its own label for its MAIL FROM, `feedback` by default. Never give PostHog a label SendGrid uses. +- PostHog's DKIM records have their own names, so they sit next to `s1._domainkey` and `s2._domainkey`. +- Keep the one `_dmarc` record. Never add a second one. +- A domain whose SPF record names `include:sendgrid.net` keeps it. Merge PostHog's include into that record. + +## Read-only key + +The app's own SendGrid key is usually a key with the Mail Send permission only, and it can't read templates or suppressions. When the person chooses the API over the dashboard, ask them to create a restricted key in SendGrid (Settings, then API Keys) with read access to Template Engine and Suppressions only, store it in `SENDGRID_READ_API_KEY` in the git-ignored env file, and note in the plan that the run created it. Its last use is the suppression import in Step 5. At the end of Step 5, on every way out of it, ask the person to delete the key in SendGrid and remove its variable from the env file, and note in the plan whether they did. The report reminds them when they didn't. Never print the key, and never write it into another file. + +The steps call this key the full-access provider key. + +## Template content + +A site whose template the person moves to PostHog needs the content of its active version, to check it before they make the PostHog template. + +**Copy from the dashboard.** In SendGrid: Email API, then Dynamic Templates, then the template, then its active version. Ask the person for the template's id, the version's subject, its HTML from the code editor, and its plain text when it has one. + +**Read from the API.** `GET https://api.sendgrid.com/v3/templates/{template_id}` with `Authorization: Bearer $SENDGRID_READ_API_KEY`. The answer holds `id`, `name`, `generation` (`dynamic` or `legacy`), and `versions`, a list of `{ id, active, name, subject, html_content, plain_content }`. Take the version whose `active` is `1`. + +Read the person's copies where they saved them. An API answer goes only into the temporary file Step 3 writes, which Step 3 deletes once the site is classified. Never write the content into the plan or the report. + +## Suppression list + +SendGrid keeps several suppression lists. It skips an address on any of them on every send. + +**Export from the dashboard (preferred).** In SendGrid: Suppressions, then each of Bounces, Spam Reports, and Invalid Emails, then **Export CSV**. Ask the person where they saved each file. Read the header row to find the address column. + +**Read from the API.** With `Authorization: Bearer $SENDGRID_READ_API_KEY`: + +- `GET https://api.sendgrid.com/v3/suppression/bounces` +- `GET https://api.sendgrid.com/v3/suppression/spam_reports` +- `GET https://api.sendgrid.com/v3/suppression/invalid_emails` + +Each answers a list of `{ created, email, reason, status }`. Page with `limit=500` and `offset`, adding 500 each time, until a page has fewer than 500 entries. Wait and retry on `429`. + +**Map each entry.** + +| SendGrid list | PostHog source | Reason | +|---|---|---| +| Bounces | bounce | `Imported from SendGrid: bounce` | +| Invalid Emails | bounce | `Imported from SendGrid: invalid address` | +| Spam Reports | complaint | `Imported from SendGrid: spam report` | + +**Leave out the other lists.** + +- **Blocks** are temporary refusals by a receiving server. SendGrid retries those addresses, and so does PostHog. +- **Global unsubscribes and group unsubscribes** are marketing preferences, and PostHog's opt-outs apply to marketing messages only. At SendGrid a global unsubscribe also stopped transactional mail, unless the send bypassed it. Once the sends move, these addresses get transactional email again. Count them, and tell the person the count in the report. diff --git a/context/skills/migrate-email/references/sendgrid/mapping.md b/context/skills/migrate-email/references/sendgrid/mapping.md new file mode 100644 index 000000000..27226927c --- /dev/null +++ b/context/skills/migrate-email/references/sendgrid/mapping.md @@ -0,0 +1,133 @@ +# SendGrid to PostHog mapping + +This file decides, field by field, whether PostHog can send a SendGrid call site. A site moves only when every field it sets moves. Otherwise it stays on SendGrid, and the reason names the first field or feature that keeps it there. `api.md` has the PostHog side in full, and `posthog-sdks.md` has PostHog's names in each language. + +PostHog fields are written in their Node.js names here, such as `replyTo`. Use the name `posthog-sdks.md` gives for the site's language, such as `reply_to` in Python. + +## Fields + +| SendGrid | PostHog | A site stays on SendGrid when | +|---|---|---| +| `from` | `from` | Never. `{ email, name }` becomes `'Name '`. It needs a verified sender (Step 4) | +| `to` | `to` | It holds more than one address. A list with one entry moves as that entry. `{ email, name }` moves as the bare address: note in the plan row that the To line loses the name | +| `subject` | `subject` | Never | +| `text`, `html` | `text`, `html` | Never | +| `content` | `text` for `text/plain`, `html` for `text/html` | It holds another type, or two entries of one type | +| `templateId` with `dynamicTemplateData` | a template made in PostHog, sent by its `templateId` with `templateData` | See "Templates". A legacy template, whose id has no `d-` prefix, always stays | +| `substitutions` | none | Always | +| `cc`, `bcc` | `cc`, `bcc` | The installed SDK has no `cc` or `bcc` (Step 7 checks), there are more than 10 of either, or the code builds the list at run time and you cannot tell it stays at 10 or fewer. `{ email, name }` moves as the bare address, as for `to` | +| `replyTo`, `replyToList` | `replyTo`, one address or a list | An entry carries a name, there are more than 10, or the code builds the value at run time and you cannot tell that it holds bare addresses only | +| `attachments` | `attachments` | The installed SDK has no `attachments`, there are more than 10 files, a `disposition` is `inline` without a `contentId`, or the files can add up to more than 512 KB, such as an upload of the user's or a PDF of unbounded length. PostHog takes at most 10 files and 512 KB in all | +| `headers` | `headers` | The installed SDK has no `headers`, or there are more than 10 | +| `customArgs` | `tags`, one `{ name, value }` per entry | The installed SDK has no `tags`, there are more than 10, or a webhook handler reads them back (see "Webhooks") | +| `categories` | `tags`, `{ name: 'category', value: }` | The installed SDK has no `tags`, or the site sets more than one category: PostHog tags are name and value pairs, not a list of labels | +| `trackingSettings` that turns `openTracking` or `clickTracking` off | `captureEngagement: false` | The installed SDK has no `captureEngagement`, or the settings do anything else, such as `subscriptionTracking` or `ganalytics`. `false` turns off both open and click capture: note it in the plan row | +| `sendAt` / `send_at` | none | Always | +| `batchId` / `batch_id` | none | Always | +| `asm` | none | Always: PostHog has no unsubscribe groups on a transactional send | +| `ipPoolName` / `ip_pool_name` | none | Always | +| `mailSettings` / `mail_settings` | none | Always. Sandbox mode is not a send | +| `personalizations` | the fields of its one entry | It holds more than one entry. One entry moves when each field in it moves | + +A SendGrid send has no idempotency key, so the moved site sends none either. PostHog's SDK makes one for each call and reuses it on its own retries. + +## Calls + +| SendGrid call | A site stays on SendGrid when | +|---|---| +| `sgMail.send(msg)`, `SendGridAPIClient.send`, `sg.client.mail._('send').post`, `$sendgrid->send`, `client.Send`, `SendEmailAsync`, `POST /v3/mail/send` | A field above keeps it | +| `sgMail.send(msg, true)`, `sgMail.sendMultiple`, `sgMail.send([...])`, `Mail(..., is_multiple=True)`, `CreateSingleEmailToMultipleRecipients`, `CreateMultipleEmailsToMultipleRecipients` | Always: each sends several emails in one call | +| SMTP through `smtp.sendgrid.net` | Always. PostHog has no SMTP relay | +| A framework mailer (Django, Rails, Laravel, Swoosh, Bamboo) | Always. PostHog has no mailer driver | +| A send in a language whose PostHog SDK has no email send (`posthog-sdks.md` lists them), such as Java | Always | + +## Code around the send + +SendGrid's SDKs report an error in two ways. The Node.js and Python SDKs throw. The Ruby, PHP, Go, and .NET SDKs answer a response, and the code reads its status code. `posthog-sdks.md` says how PostHog's SDK reports an error in each language. Keep the site failing the same way it did, as the Rewrite section says. + +| Code | A site stays on SendGrid when | +|---|---| +| A `catch` or `except` that reads `err.code`, `err.response.body.errors`, `e.status_code`, or `e.body` | It branches on a SendGrid error text or `field` value. A branch on the HTTP status moves: read PostHog's status code | +| A check of `response.statusCode`, `status_code`, `statusCode()`, or `StatusCode` | Never. Read PostHog's error instead, as the Rewrite section says | +| The `X-Message-Id` header stored for a webhook or a status read | Always, when the Event Webhook or the Email Activity API uses it | +| The `X-Message-Id` header logged or stored for the app's own use | Never. Use PostHog's message id | + +## Templates + +A dynamic template site moves only to a template made in PostHog. This skill never makes one: the person makes it from the SendGrid template, makes it transactional, and gives you its template ID. Until then the site stays on SendGrid. The check needs the content of the template's active version, because the code has only its id. `account.md` says how to get it. + +SendGrid's Handlebars becomes Liquid in the PostHog template. Values move under `variables`, and each name keeps its case: + +| SendGrid | PostHog | +|---|---| +| `{{name}}` | `{{ variables.name }}` | +| `{{user.first_name}}` | `{{ variables.user.first_name }}` | +| `{{#if paid}}…{{else}}…{{/if}}` | `{% if variables.paid %}…{% else %}…{% endif %}` | +| `{{#unless paid}}…{{/unless}}` | `{% unless variables.paid %}…{% endunless %}` | +| `{{#each items}}{{this.name}}{{/each}}` | `{% for item in variables.items %}{{ item.name }}{% endfor %}` | +| `{{insert name "default=there"}}` | `{{ variables.name \| default: 'there' }}` | +| The version's `subject` | The PostHog template's subject, with the same conversions | + +Write the `\|` above as a plain `|`. The table escapes it. + +- Handlebars `{{name}}` escapes HTML, and so does PostHog's Liquid, so plain values render the same. +- `{{{name}}}` inserts HTML as it is. PostHog's Liquid escapes it, so a template that uses triple braces stays on SendGrid. +- Any other helper, such as `{{#equals}}`, `{{formatDate}}`, `{{#greaterThan}}`, `{{length}}`, or `{{#and}}`, keeps the template on SendGrid. So does `{{@index}}`, a partial, and a block inside `{{#each}}` that reads a value outside the loop with `../`. +- Liquid's `default` also replaces an empty string. When the code can pass an empty string for such a value, the email shows the fallback. Note it in the report. +- The PostHog template carries its own sender, reply-to address, and subject. A site that sets `from`, `replyTo`, or `subject` next to `templateId` moves only when the value is the same in every send, and the person puts it into the PostHog template. Otherwise it stays. +- A site that sets `cc`, `bcc`, `attachments`, `headers`, `customArgs`, or `categories` next to `templateId` stays: a template made in PostHog sends with its own settings. + +## Webhooks + +The Event Webhook stops getting events for a site that moves. PostHog records the events of a moved send on the person it names with `distinctId`, when engagement events are on for the project: + +| SendGrid event | PostHog event | +|---|---| +| `processed` | `$workflows_email_sent` | +| `delivered` | `$workflows_email_delivered` | +| `bounce` | `$workflows_email_bounced` | +| `spamreport` | `$workflows_email_blocked` | +| `open` | `$workflows_email_opened` | +| `click` | `$workflows_email_link_clicked` | +| `dropped` | none. PostHog refuses the send instead, such as with `recipient_suppressed` | +| `deferred`, `unsubscribe`, `group_unsubscribe`, `group_resubscribe` | none | + +PostHog's events carry no SendGrid `sg_message_id` and no `custom_args`. A site whose events a handler matches by message id or by a custom arg stays on SendGrid. For every other handler, the report tells the person which events it handles, which PostHog events take their place, and that a webhook destination in PostHog (Data pipelines, then Destinations) can post them to an endpoint. The handler itself keeps working for the sites that stay. Never change it. + +## Rewrite + +How a site that moves is written with PostHog's SDK. Step 7 says when to use each part, and `posthog-sdks.md` has the client and the send in each language. + +**The PostHog client.** Set `migratedFrom: 'sendgrid'` on the client that Step 7 configures, when its client options take it. + +**The call.** The SendGrid send becomes one PostHog send. Build its fields from the message the site built: + +- `sgMail.send(msg)`: the fields of `msg`. +- Python `Mail(from_email=, to_emails=, subject=, html_content=, plain_text_content=)` and its setters: `from`, `to`, `subject`, `html`, `text`, and each field a setter sets. +- Ruby `SendGrid::Mail.new(from, subject, to, content)` and its personalization: the same fields. +- PHP `setFrom`, `addTo`, `setSubject`, `addContent`, and the other setters: the same fields. +- Go `mail.NewSingleEmail(from, subject, to, plainText, html)`, or `NewV3Mail` with one personalization: the same fields. +- .NET `MailHelper.CreateSingleEmail(from, to, subject, plainText, html)`, or a `SendGridMessage`: the same fields. +- A raw HTTP body or `@sendgrid/client` request: the fields of its one personalization, `from`, `subject`, and `content`. + +**The fields.** + +- `{ email: 'hello@mail.example.com', name: 'Example' }` in `from` becomes `'Example '`. A `from` without a name becomes the bare address. +- `to`, `cc`, and `bcc` become bare addresses. A list with one entry in `to` becomes that entry. When a helper takes a list of recipients and every caller passes one address, change the parameter to one address and update the callers. Never send one email per address in a loop. +- `content` entries become `text` and `html`. +- An attachment `{ content, filename, type, contentId }` becomes `{ content, filename, contentType: type, contentId }`. `content` stays the same base64 string. Drop `disposition`: `contentId` makes a file inline. +- `customArgs: { orderId: '123' }` becomes `tags: [{ name: 'orderId', value: '123' }]`. A value that isn't a string becomes its string. +- A send with rendered content gets a `templateKey`, as Step 7 says. + +**Templates made in PostHog.** The site sends `templateId` with the template ID the person gave, and `templateData` with the site's `dynamicTemplateData`. It sends no `templateKey`, `subject`, `html`, `text`, `from`, or `replyTo`: the template holds them. + +**Errors.** Keep the site failing the same way it did: + +- **Node.js.** `posthog.emails.send` never throws on an API error: it answers `{ data, error }`. Where `sgMail.send` threw into a `catch`, throw from the error so the same `catch` runs: `if (error) throw Object.assign(new Error(error.message), { code: error.statusCode })`. `err.code` keeps holding the HTTP status. A read of `err.response.body` becomes a read of `err.message`. +- **Python.** PostHog's SDK raises too. Replace `except HTTPError` and its subclasses with the PostHog exception `posthog-sdks.md` names, and `e.status_code` with its status code. +- **Ruby, PHP, Go, and .NET.** The code read SendGrid's status code. Read PostHog's error the way `posthog-sdks.md` says for the language, and keep each branch: a status of 400 or more becomes "there is an error", and a branch on one status, such as 429, reads PostHog's status code. +- PostHog refuses a send to a suppressed address with `recipient_suppressed`, where SendGrid took it and dropped it later. When the site throws, retries, or reports a failure on any error, handle `recipient_suppressed` before that branch the way the site handled a send that went out: log it and go on. Note each site that got this branch in the report. + +**The answer.** The message id of a moved send is PostHog's. Code that logged `X-Message-Id`, or stored it for the app's own use, takes PostHog's message id instead. + +**The SendGrid client.** Keep the SendGrid client, its import, and `setApiKey` while any site or other call still uses them. When nothing uses them, remove the import and the client, and keep the package and its key: the person removes them after the cutover. diff --git a/context/skills/migrate-email/references/sendgrid/sdk-reference.md b/context/skills/migrate-email/references/sendgrid/sdk-reference.md new file mode 100644 index 000000000..cc1ca6f49 --- /dev/null +++ b/context/skills/migrate-email/references/sendgrid/sdk-reference.md @@ -0,0 +1,184 @@ +# SendGrid SDK reference + +This file says what SendGrid looks like in a codebase. It does not describe PostHog. `mapping.md` maps each field to PostHog. + +## Key + +The API key lives in `SENDGRID_API_KEY` by convention. Apps also use their own names, such as `SENDGRID_KEY`: take the name the client reads. + +## Packages + +| Language | Package | Send | +|---|---|---| +| Node.js | `@sendgrid/mail`, and `@sendgrid/client` for raw API requests | `sgMail.send(msg)` | +| Python | `sendgrid` (PyPI) | `SendGridAPIClient(key).send(Mail(...))` | +| Ruby | `sendgrid-ruby` | `SendGrid::API.new(api_key:).client.mail._('send').post(request_body:)` | +| PHP | `sendgrid/sendgrid` | `(new \SendGrid($key))->send($email)` | +| Go | `github.com/sendgrid/sendgrid-go` with `helpers/mail` | `sendgrid.NewSendClient(key).Send(message)` | +| .NET | `SendGrid` (NuGet), and `SendGrid.Extensions.DependencyInjection` | `client.SendEmailAsync(msg)` | +| Java | `com.sendgrid:sendgrid-java` | `sg.api(request)` with `Mail` | + +These are not SendGrid's send SDK, and alone they are not a migration: `@sendgrid/eventwebhook` checks webhook signatures, `@sendgrid/inbound-mail-parser` reads inbound mail, and `nodemailer` sends through any SMTP server. + +## Clients and sends + +**Node.js.** `sgMail.send(msg)` answers `[response, body]`: `response.statusCode` is `202`, and `response.headers['x-message-id']` is the message id. It throws a `ResponseError` on an API error: `err.code` is the HTTP status, and `err.response.body.errors` is a list of `{ message, field, help }`. + +```js +import sgMail from '@sendgrid/mail' +sgMail.setApiKey(process.env.SENDGRID_API_KEY) + +await sgMail.send({ + to: 'jane@example.com', + from: { email: 'hello@mail.example.com', name: 'Example' }, + subject: 'Welcome', + text: 'Welcome', + html: '

Welcome

', +}) +``` + +- `sgMail.send(msg)` with a list in `to` sends **one** email that every address sees. +- `sgMail.send(msg, true)` and `sgMail.sendMultiple(msg)` send one email per address in `to`. +- `sgMail.send([msg1, msg2])` sends several emails in one call. +- `@sendgrid/client`: `client.request({ method: 'POST', url: '/v3/mail/send', body })` sends the HTTP body below. + +**Python.** It raises `python_http_client.exceptions.HTTPError` and its subclasses, such as `BadRequestsError` and `TooManyRequestsError`, on an API error. `e.status_code` and `e.body` hold the answer. A success answers a response with `status_code` `202` and the message id in `headers['X-Message-Id']`. + +```python +from sendgrid import SendGridAPIClient +from sendgrid.helpers.mail import Mail + +message = Mail( + from_email=("hello@mail.example.com", "Example"), + to_emails="jane@example.com", + subject="Welcome", + html_content="

Welcome

", + plain_text_content="Welcome", +) +response = SendGridAPIClient(os.environ["SENDGRID_API_KEY"]).send(message) +``` + +- `Mail(..., is_multiple=True)` sends one email per address in `to_emails`. +- `message.template_id` and `message.dynamic_template_data` send a dynamic template. +- `message.add_cc(...)`, `message.add_bcc(...)`, `message.reply_to = ReplyTo(...)`, `message.attachment = Attachment(FileContent(...), FileName(...), FileType(...), Disposition(...), ContentId(...))`, `message.category = Category(...)`, `message.custom_arg = CustomArg(...)`, `message.header = Header(...)`, `message.send_at = SendAt(...)`, and `message.asm = Asm(...)` set the other fields. +- `sg.client.mail.send.post(request_body=data)` sends a raw HTTP body. + +**Ruby.** The send answers a response with `status_code` (a string, such as `"202"`), `body`, and `headers`. It does not raise on an API error: the code reads `status_code`. + +```ruby +require 'sendgrid-ruby' + +mail = SendGrid::Mail.new( + SendGrid::Email.new(email: 'hello@mail.example.com', name: 'Example'), + 'Welcome', + SendGrid::Email.new(email: 'jane@example.com'), + SendGrid::Content.new(type: 'text/html', value: '

Welcome

') +) +sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) +response = sg.client.mail._('send').post(request_body: mail.to_json) +``` + +A `SendGrid::Personalization` with `add_to`, `add_cc`, `add_bcc`, and `add_dynamic_template_data` builds the recipients, and `mail.template_id`, `mail.reply_to`, `mail.add_attachment`, `mail.add_category`, `mail.add_custom_arg`, `mail.add_header`, `mail.send_at`, and `mail.asm` set the rest. + +**PHP.** `send` answers a response with `statusCode()`, `headers()`, and `body()`. It does not throw on an API error, only on a network error. + +```php +$email = new \SendGrid\Mail\Mail(); +$email->setFrom('hello@mail.example.com', 'Example'); +$email->setSubject('Welcome'); +$email->addTo('jane@example.com'); +$email->addContent('text/html', '

Welcome

'); +$response = (new \SendGrid(getenv('SENDGRID_API_KEY')))->send($email); +``` + +The other setters are `addCc`, `addBcc`, `setReplyTo`, `addAttachment($content, $type, $filename, $disposition, $contentId)`, `setTemplateId`, `addDynamicTemplateDatas`, `addCategory`, `addCustomArg`, `addHeader`, `setSendAt`, and `setAsm`. + +**Go.** `Send` answers `(*rest.Response, error)`. `err` is set only for a network error: an API error is a `response.StatusCode` of 400 or more. The message id is in `response.Headers["X-Message-Id"]`. + +```go +from := mail.NewEmail("Example", "hello@mail.example.com") +to := mail.NewEmail("", "jane@example.com") +message := mail.NewSingleEmail(from, "Welcome", to, "Welcome", "

Welcome

") +response, err := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY")).Send(message) +``` + +`mail.NewV3Mail()` with `mail.NewPersonalization()` (`AddTos`, `AddCCs`, `AddBCCs`, `SetDynamicTemplateData`) builds the full form, with `SetTemplateID`, `SetReplyTo`, `AddAttachment`, `AddCategories`, `SetCustomArg`, `SetHeader`, `SetSendAt`, and `SetASM`. + +**.NET.** `SendEmailAsync` answers a `Response` with `StatusCode`, `IsSuccessStatusCode`, `Headers`, and `Body`. It does not throw on an API error unless the client options set `HttpErrorAsException`. + +```csharp +var client = new SendGridClient(Environment.GetEnvironmentVariable("SENDGRID_API_KEY")); +var msg = MailHelper.CreateSingleEmail( + new EmailAddress("hello@mail.example.com", "Example"), + new EmailAddress("jane@example.com"), + "Welcome", "Welcome", "

Welcome

"); +var response = await client.SendEmailAsync(msg); +``` + +`MailHelper.CreateSingleEmailToMultipleRecipients` and `CreateMultipleEmailsToMultipleRecipients` send to several addresses. A `SendGridMessage` takes `SetFrom`, `AddTo`, `AddCc`, `AddBcc`, `SetReplyTo`, `AddAttachment(filename, base64Content, type, disposition, contentId)`, `SetTemplateId`, `SetTemplateData`, `AddCategory`, `AddCustomArg`, `AddHeader`, `SetSendAt`, and `SetAsm`. Apps that use dependency injection take an `ISendGridClient`. + +**HTTP.** `POST https://api.sendgrid.com/v3/mail/send`, or `api.eu.sendgrid.com` for an EU subuser, with `Authorization: Bearer `. A success answers `202` with no body and the message id in the `X-Message-Id` header. An error answers `{ "errors": [{ "message", "field", "help" }] }`. Look for `api.sendgrid.com` in `fetch`, `axios`, `got`, `requests`, `httpx`, `net/http`, and `curl` calls. + +```json +{ + "personalizations": [{ "to": [{ "email": "jane@example.com" }], "dynamic_template_data": { "name": "Jane" } }], + "from": { "email": "hello@mail.example.com", "name": "Example" }, + "subject": "Welcome", + "content": [{ "type": "text/plain", "value": "Welcome" }, { "type": "text/html", "value": "

Welcome

" }] +} +``` + +**SMTP.** SendGrid takes mail over SMTP at `smtp.sendgrid.net`, with the user `apikey` and the API key as the password. Look for that host in Nodemailer transports, `EMAIL_HOST`, `MAIL_HOST`, or `SMTP_HOST` settings, and framework mail config. An `X-SMTPAPI` header carries SendGrid options over SMTP. + +**Frameworks.** Mailers that send every framework mail through SendGrid: `django-sendgrid-v5` and `django-anymail` with its SendGrid backend in Django, `sendgrid-actionmailer` in Rails, `s-ichikawa/laravel-sendgrid-driver` (`MAIL_MAILER=sendgrid`) in Laravel, and the SendGrid adapters of Swoosh and Bamboo in Elixir. Each mailable or mailer that sends is a site. + +## Send fields + +Node.js names, with the HTTP names where they differ. The other SDKs use the same names in their own case. + +| Node.js field | HTTP field | Value | +|---|---|---| +| `from` | `from` | An address, or `{ email, name }` | +| `to` | `personalizations[].to` | An address, `{ email, name }`, or a list of them | +| `cc`, `bcc` | `personalizations[].cc`, `bcc` | Same as `to` | +| `replyTo` | `reply_to` | An address, or `{ email, name }` | +| `replyToList` | `reply_to_list` | A list of `{ email, name }` | +| `subject` | `subject` | String | +| `text`, `html` | `content` | Strings. HTTP sends `[{ type: 'text/plain', value }, { type: 'text/html', value }]` | +| `content` | `content` | A list of `{ type, value }` | +| `templateId` | `template_id` | A dynamic template (`d-...`), or a legacy template | +| `dynamicTemplateData` | `personalizations[].dynamic_template_data` | Object that fills a dynamic template | +| `substitutions` | `personalizations[].substitutions` | Values for a legacy template's `-name-` tags | +| `attachments` | `attachments` | A list of `{ content, filename, type, disposition, contentId }`. `content` is base64 | +| `categories` | `categories` | A list of strings | +| `customArgs` | `custom_args` | Object of string values, sent back in webhook events | +| `headers` | `headers` | Object of custom headers | +| `sendAt` | `send_at` | A Unix time, up to 72 hours ahead | +| `batchId` | `batch_id` | A batch that can be cancelled or paused | +| `asm` | `asm` | `{ groupId, groupsToDisplay }`: an unsubscribe group | +| `ipPoolName` | `ip_pool_name` | String | +| `mailSettings` | `mail_settings` | Such as `sandboxMode`, `bypassListManagement`, `footer` | +| `trackingSettings` | `tracking_settings` | Such as `clickTracking`, `openTracking`, `subscriptionTracking`, `ganalytics` | +| `personalizations` | `personalizations` | A list of recipient groups, each with its own `to`, `cc`, `bcc`, `subject`, data, and `sendAt` | + +## Templates stored at SendGrid + +A send with `templateId: 'd-...'` and `dynamicTemplateData` renders a dynamic template from the SendGrid dashboard. Its content is not in the code. + +- A dynamic template uses Handlebars: `{{name}}`, `{{user.name}}`, `{{{raw}}}`, `{{#if}}`, `{{#unless}}`, `{{#each}}`, and helpers such as `{{#equals}}`, `{{formatDate}}`, and `{{insert}}`. +- A template has versions. The active version holds `subject`, `html_content`, and `plain_content`. +- A legacy template has an id without the `d-` prefix, and reads `substitutions` as `-name-` tags. + +## Status reads + +The Email Activity API (`GET https://api.sendgrid.com/v3/messages`) reads a message's delivery state. Code that reads it reads SendGrid's state. + +## Webhooks + +The Event Webhook posts a JSON list of events to an endpoint of the app. Each event has `email`, `timestamp`, `event`, `sg_event_id`, `sg_message_id`, and the send's `custom_args` and `category`. `event` is one of `processed`, `dropped`, `deferred`, `delivered`, `bounce`, `open`, `click`, `spamreport`, `unsubscribe`, `group_unsubscribe`, and `group_resubscribe`. + +Look for routes that read `sg_message_id` or `sg_event_id`, `EventWebhook` and `verifySignature` from `@sendgrid/eventwebhook`, and the `X-Twilio-Email-Event-Webhook-Signature` header. + +## Other APIs + +Marketing Campaigns, contacts, lists, segments, unsubscribe groups, suppressions, templates, API keys, subusers, and stats (`/v3/marketing/*`, `/v3/contactdb/*`, `/v3/asm/*`, `/v3/suppression/*`, `/v3/templates`, `/v3/api_keys`, `/v3/stats`) are not transactional sends. diff --git a/scripts/lib/tests/migrate-email-skill.test.js b/scripts/lib/tests/migrate-email-skill.test.js index ff7b5bf48..a7feb5c81 100644 --- a/scripts/lib/tests/migrate-email-skill.test.js +++ b/scripts/lib/tests/migrate-email-skill.test.js @@ -9,6 +9,8 @@ const DOCS_PAGES = { 'https://posthog.com/docs/workflows/transactional-emails/api.md': '# Send transactional emails with the API\n', }; const REFERENCE_PATH = /references\/[A-Za-z0-9_./-]+\.md/g; +const PROVIDERS = ['resend', 'sendgrid']; +const PROVIDER_FILES = ['sdk-reference.md', 'mapping.md', 'account.md']; async function loadSkills() { vi.resetModules(); @@ -109,11 +111,34 @@ describe('migrate-email skill', () => { ]); }); - it('publishes Resend and Statsig as wizard migrate subcommands', async () => { + it.each(PROVIDERS)('builds migrate-email-%s with its provider files, the SDK file, and no other provider', async (provider) => { + outputDir = mkdtempSync(join(tmpdir(), 'migrate-skill-')); + + const skillDir = await buildSkill(`migrate-email-${provider}`, outputDir); + + expect(unresolvedReferences(skillDir)).toEqual([]); + for (const file of PROVIDER_FILES) { + expect(existsSync(join(skillDir, 'references', provider, file))).toBe(true); + } + expect(existsSync(join(skillDir, 'references', 'posthog-sdks.md'))).toBe(true); + const otherProviders = PROVIDERS.filter((other) => other !== provider); + expect(otherProviders.filter((other) => existsSync(join(skillDir, 'references', other)))).toEqual([]); + }); + + it('names a migratedFrom value equal to the provider folder in each mapping', () => { + for (const provider of PROVIDERS) { + const mapping = readFileSync(join(CONFIG_DIR, 'skills', 'migrate-email', 'references', provider, 'mapping.md'), 'utf8'); + expect(mapping, provider).toContain(`migratedFrom: '${provider}'`); + } + }); + + it('publishes each provider and Statsig as wizard migrate subcommands', async () => { const { skills } = await loadSkills(); const cliOf = (id) => skills.find((skill) => skill.id === id)?._cli; - expect(cliOf('migrate-email-resend')).toEqual({ role: 'command', parentCommand: 'migrate', command: 'resend' }); + for (const provider of PROVIDERS) { + expect(cliOf(`migrate-email-${provider}`)).toEqual({ role: 'command', parentCommand: 'migrate', command: provider }); + } expect(cliOf('migrate-statsig')).toEqual({ role: 'command', parentCommand: 'migrate', command: 'statsig' }); }); }); From 356b218acce5b3a44f59998b53813ac4863d68ae Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:27:54 +0000 Subject: [PATCH 037/260] feat(skills): move Postmark sends to PostHog in every SDK language Add the postmark variant of migrate-email: the SDK reference for the official Node.js, Python, Ruby, PHP, .NET and Java SDKs and the community Python and Go packages, the field, call, template and webhook mapping, and the account file with Postmark's DNS records, template reads and per-stream suppression import. Co-Authored-By: Claude Opus 5.5 --- context/skills/migrate-email/config.yaml | 3 + .../references/postmark/account.md | 58 +++++ .../references/postmark/mapping.md | 146 +++++++++++++ .../references/postmark/sdk-reference.md | 205 ++++++++++++++++++ scripts/lib/tests/migrate-email-skill.test.js | 2 +- 5 files changed, 413 insertions(+), 1 deletion(-) create mode 100644 context/skills/migrate-email/references/postmark/account.md create mode 100644 context/skills/migrate-email/references/postmark/mapping.md create mode 100644 context/skills/migrate-email/references/postmark/sdk-reference.md diff --git a/context/skills/migrate-email/config.yaml b/context/skills/migrate-email/config.yaml index 1d9496364..8907c5e41 100644 --- a/context/skills/migrate-email/config.yaml +++ b/context/skills/migrate-email/config.yaml @@ -19,3 +19,6 @@ variants: - id: sendgrid display_name: SendGrid tags: [sendgrid] + - id: postmark + display_name: Postmark + tags: [postmark] diff --git a/context/skills/migrate-email/references/postmark/account.md b/context/skills/migrate-email/references/postmark/account.md new file mode 100644 index 000000000..bfe5700f0 --- /dev/null +++ b/context/skills/migrate-email/references/postmark/account.md @@ -0,0 +1,58 @@ +# Postmark account + +What the migration needs from the person's Postmark account. The agent never changes the account: it reads what the person exports or allows. + +## DNS records + +A domain verified at Postmark carries these records. Keep all of them until the cutover is done. Postmark shows the exact names and values on the domain's DNS Settings page. + +| Record | Name | What it does | +|---|---|---| +| `TXT` (DKIM) | `pm._domainkey`, such as `20240115123456pm._domainkey` | Signs Postmark's mail | +| `CNAME` (Return-Path) | `pm-bounces` by default, or the label the person chose | Points to `pm.mtasv.net`. Takes Postmark's bounces, and aligns its SPF | +| `TXT` (DMARC) | `_dmarc` | Optional, shared by every provider on the domain | + +- While Postmark renews a DKIM key, the domain carries a second `pm._domainkey` record for the new key. Keep both. +- PostHog's sender uses its own label for its MAIL FROM, `feedback` by default. Never give PostHog the Return-Path label Postmark uses. +- PostHog's DKIM records have their own names, so they sit next to Postmark's `pm._domainkey` record. +- Keep the one `_dmarc` record. Never add a second one. +- Postmark needs no SPF record on the domain itself: its Return-Path covers SPF. A domain whose SPF record names `include:spf.mtasv.net`, from an older Postmark setup, keeps it. Merge PostHog's include into that record, or into whatever `v=spf1` record the domain has. + +## Migration token + +Postmark's Server API tokens can't be limited to reads: each one can send mail and change the server's settings. The app's own token can read templates and suppressions, but the run doesn't use it. When the person chooses the API over the dashboard, ask them to generate a separate Server API token for the migration on the server the app sends from (the server, then API Tokens, then Generate New; a server holds up to three tokens), store it in `POSTMARK_MIGRATION_SERVER_TOKEN` in the git-ignored env file, and note in the plan that the run created it. Its last use is the suppression import in Step 5. At the end of Step 5, on every way out of it, ask the person to delete the token in Postmark (the server, then API Tokens) and remove its variable from the env file, and note in the plan whether they did. The report reminds them when they didn't. Never print the token, and never write it into another file. + +The steps call this key the full-access provider key. + +## Template content + +A site whose template the person moves to PostHog needs the template's content, to check it before they make the PostHog template. + +**Copy from the dashboard.** In Postmark: the server, then Templates, then the template. Ask the person for the template's id or alias, its subject, its HTML, and its text body when it has one. When the template uses a layout, ask for the layout's HTML and text too. + +**Read from the API.** `GET https://api.postmarkapp.com/templates/{templateIdOrAlias}` with `Accept: application/json` and `X-Postmark-Server-Token: $POSTMARK_MIGRATION_SERVER_TOKEN`. The answer holds `TemplateId`, `Alias`, `Name`, `Subject`, `HtmlBody`, `TextBody`, `TemplateType` (`Standard` or `Layout`), `LayoutTemplate`, and `Active`. When `LayoutTemplate` holds an alias, read that layout with the same route. + +Read the person's copies where they saved them. An API answer goes only into the temporary file Step 3 writes, which Step 3 deletes once the site is classified. Never write the content into the plan or the report. + +## Suppression list + +Postmark keeps one suppression list per message stream. It refuses a send to an address on the stream's list with error code `406`. Import the list of `outbound`, the default transactional stream, which the moved sites send through. + +**Export from the dashboard (preferred).** In Postmark: the server, then the `outbound` stream, then Suppressions, then **Export**. It saves a JSON file. Ask the person where they saved it. Read its fields to find each entry's address and reason. + +**Read from the API.** `GET https://api.postmarkapp.com/message-streams/outbound/suppressions/dump` with `Accept: application/json` and `X-Postmark-Server-Token: $POSTMARK_MIGRATION_SERVER_TOKEN`. It answers `{ "Suppressions": [{ "EmailAddress", "SuppressionReason", "Origin", "CreatedAt" }] }` for the whole stream in one call, with no paging. Wait and retry on `429`. + +**Map each entry.** + +| `SuppressionReason` | PostHog source | Reason | +|---|---|---| +| `HardBounce` | bounce | `Imported from Postmark: hard bounce` | +| `SpamComplaint` | complaint | `Imported from Postmark: spam complaint` | +| `ManualSuppression` | manual | `Imported from Postmark: manual suppression` | + +`ManualSuppression` covers an address the app or a person at Postmark suppressed, and a recipient who unsubscribed from the stream. Each one stopped this stream's mail at Postmark, so each one moves. + +**Leave out the other lists.** + +- **Broadcast streams** hold the suppressions of marketing mail, such as unsubscribes from a newsletter. PostHog's opt-outs apply to marketing messages only, and transactional email ignores them. Count the entries of each broadcast stream, and tell the person the count in the report. +- **Other transactional streams** belong to the sites that send through them, and those sites stay on Postmark. Leave their lists where they are. diff --git a/context/skills/migrate-email/references/postmark/mapping.md b/context/skills/migrate-email/references/postmark/mapping.md new file mode 100644 index 000000000..611af07e7 --- /dev/null +++ b/context/skills/migrate-email/references/postmark/mapping.md @@ -0,0 +1,146 @@ +# Postmark to PostHog mapping + +This file decides, field by field, whether PostHog can send a Postmark call site. A site moves only when every field it sets moves. Otherwise it stays on Postmark, and the reason names the first field or feature that keeps it there. `api.md` has the PostHog side in full, and `posthog-sdks.md` has PostHog's names in each language. + +Postmark fields are written in their HTTP names here, such as `HtmlBody`. Python and Ruby code uses snake case, such as `html_body`, and `postmark-python` names `From` as `sender`. PostHog fields are written in their Node.js names, such as `replyTo`. Use the name `posthog-sdks.md` gives for the site's language, such as `reply_to` in Python. + +## Fields + +| Postmark | PostHog | A site stays on Postmark when | +|---|---|---| +| `From` | `from` | Never. `Name
` moves as it is. It needs a verified sender (Step 4) | +| `To` | `to` | It holds more than one address: a comma in the string, a list in Ruby, PHP, or `postmarker`, or a value the code builds at run time that you cannot tell holds one address. `Name
` moves as the bare address: note in the plan row that the To line loses the name | +| `Subject` | `subject` | Never | +| `HtmlBody`, `TextBody` | `html`, `text` | Never | +| `TemplateId` or `TemplateAlias`, with `TemplateModel` | a template made in PostHog, sent by its `templateId` with `templateData` | See "Templates" | +| `InlineCss` | none | Never on its own. It only shapes how Postmark renders its template, and the PostHog template holds its own HTML | +| `Cc`, `Bcc` | `cc`, `bcc`, a list of addresses | The installed SDK has no `cc` or `bcc` (Step 7 checks), there are more than 10 of either, or the code builds the value at run time and you cannot tell it stays at 10 or fewer. `Name
` moves as the bare address, as for `To` | +| `ReplyTo` | `replyTo`, one address or a list | An entry carries a name, there are more than 10, or the code builds the value at run time and you cannot tell that it holds bare addresses only | +| `Attachments` | `attachments` | The installed SDK has no `attachments`, there are more than 10 files, or the files can add up to more than 512 KB, such as an upload of the user's or a PDF of unbounded length. PostHog takes at most 10 files and 512 KB in all | +| `Headers` | `headers` | The installed SDK has no `headers`, or there are more than 10 | +| `Metadata` | `tags`, one `{ name, value }` per entry | The installed SDK has no `tags`, there are more than 10, or a webhook handler reads them back (see "Webhooks") | +| `Tag` | `tags`, `{ name: 'tag', value: }` | The installed SDK has no `tags`, or a webhook handler reads it back | +| `TrackOpens: false`, or `TrackLinks: 'None'` | `captureEngagement: false` | The installed SDK has no `captureEngagement`. `false` turns off both open and click capture: note it in the plan row | +| `TrackOpens: true`, or `TrackLinks` set to `HtmlAndText`, `HtmlOnly`, or `TextOnly` | none | Never. PostHog captures opens and clicks when engagement events are on for the project. Note in the plan row that `HtmlOnly` or `TextOnly` now tracks links in both parts | +| `MessageStream: 'outbound'` | none | Never. `outbound` is the default transactional stream | +| `MessageStream` naming any other stream | none | Always: the stream has its own settings, suppressions, and webhooks at Postmark | + +Count only the fields the code sets. `postmarker`'s `emails.send` sends `TrackLinks: "None"` when the code doesn't pass it: that default is not a field of the site. + +A Postmark send has no idempotency key, so the moved site sends none either. PostHog's SDK makes one for each call and reuses it on its own retries. + +## Calls + +| Postmark call | A site stays on Postmark when | +|---|---| +| `sendEmail`, `outbound.send`, `emails.send` (`postmarker`), `deliver`, `deliver_message`, PHP `sendEmail` and `sendEmailModel`, `SendMessageAsync`, Go `SendEmail`, `POST /email` | A field above keeps it | +| `sendEmailWithTemplate`, `outbound.send_with_template`, `emails.send_with_template`, `deliver_with_template`, `deliver_message_with_template`, PHP `sendEmailWithTemplate`, `SendEmailWithTemplateAsync`, `POST /email/withTemplate` | See "Templates" | +| `sendEmailBatch`, `sendEmailBatchWithTemplates`, `sendBulkEmail`, `send_batch`, `send_batch_with_template`, `send_bulk`, `deliver_in_batches`, `deliver_in_batches_with_templates`, `deliver_messages`, PHP `sendEmailBatch` and `sendEmailBatchWithTemplate`, `SendMessagesAsync`, Go `SendEmailBatch`, `POST /email/batch`, `/email/batchWithTemplates`, `/email/bulk` | Always: each sends several emails in one call | +| SMTP through `smtp.postmarkapp.com` or `smtp-broadcasts.postmarkapp.com` | Always. PostHog has no SMTP relay | +| A framework mailer (`postmark-rails`, a Django backend, Laravel or Symfony `postmark`, Swoosh, Bamboo, `nodemailer-postmark-transport`) | Always. PostHog has no mailer driver | +| A send in a language whose PostHog SDK has no email send (`posthog-sdks.md` lists them), such as Java | Always | + +## Code around the send + +Postmark's SDKs throw on an API error: Node.js, both Python SDKs, Ruby, PHP, and .NET. The Go community packages return an error. A raw HTTP call reads the status code or the `ErrorCode` in the answer. `posthog-sdks.md` says how PostHog's SDK reports an error in each language. Keep the site failing the same way it did, as the Rewrite section says. + +| Code | A site stays on Postmark when | +|---|---| +| A `catch`, `except`, or `rescue` that only logs or rethrows the error | Never | +| A branch on the HTTP status: `err.statusCode`, `e.http_status`, `e.status_code`, `getHttpStatusCode()` | Never. Read PostHog's status code | +| A branch on an inactive recipient: `InactiveRecipientsError`, `InactiveRecipientException`, `Postmark::InactiveRecipientError`, or `ErrorCode` `406` | Never. PostHog refuses a suppressed address with the code `recipient_suppressed` | +| A branch on another Postmark `ErrorCode`, or on the error's message text | Always | +| A read of the inactive addresses from the error (`recipients`, `inactive_recipients`) | Always | +| A check of `ErrorCode` or `Message` in a send's answer | Never. Read PostHog's error instead, as the Rewrite section says | +| `MessageID` stored for a webhook handler or a status read | Always, when a webhook handler or the Messages or Bounces API uses it | +| `MessageID` logged or stored for the app's own use | Never. Use PostHog's message id | + +## Templates + +A template site moves only to a template made in PostHog. This skill never makes one: the person makes it from the Postmark template, makes it transactional, and gives you its template ID. Until then the site stays on Postmark. The check needs the template's subject, HTML body, and text body, because the code has only its id or alias. `account.md` says how to get them. + +A template with a layout (its `LayoutTemplate` names one) renders inside that layout at `{{{ @content }}}`. The check needs the layout's content too, and the person makes one PostHog template from both: the layout's HTML with the template's HTML in place of `{{{ @content }}}`, and the same for the text body. Tell them so when you ask them to make it. + +Postmark's Mustachio becomes Liquid in the PostHog template. Values move under `variables`, and each name keeps its case: + +| Postmark | PostHog | +|---|---| +| `{{name}}`, `{{ name }}` | `{{ variables.name }}` | +| `{{person.first_name}}` | `{{ variables.person.first_name }}` | +| `{{#paid}}…{{/paid}}`, where `paid` is true or false | `{% if variables.paid %}…{% endif %}` | +| `{{^paid}}…{{/paid}}`, where `paid` is true or false | `{% unless variables.paid %}…{% endunless %}` | +| `{{#person}}{{first_name}}{{/person}}`, where `person` is an object | `{% if variables.person %}{{ variables.person.first_name }}{% endif %}` | +| `{{#each items}}{{name}}{{/each}}` | `{% for item in variables.items %}{{ item.name }}{% endfor %}` | +| `{{.}}` inside `{{#each items}}` | `{{ item }}` | +| `{{../company}}` inside `{{#each items}}`, where `company` is a top-level key of `TemplateModel` | `{{ variables.company }}` | +| The template's `Subject` | The PostHog template's subject, with the same conversions | + +- Mustachio escapes HTML in values, and so does PostHog's Liquid, so plain values render the same. +- `{{{name}}}` and `{{& name}}` insert HTML as it is. PostHog's Liquid escapes it, so a template that uses them stays on Postmark. The layout's own `{{{ @content }}}` is the one exception: the person replaces it with the template. +- `{{{ pm:unsubscribe }}}` keeps the template on Postmark: it is Postmark's unsubscribe link. +- An inverted section `{{^items}}` on a list or an object, a section `{{#items}}` on a list without `each`, a name inside `{{#person}}` that the site doesn't put on `person`, and `../` that reads anything but a top-level key all keep the template on Postmark. +- The PostHog template carries its own sender, reply-to address, and subject. A Postmark template send always sets `From`: the site moves only when `From` is the same in every send, and the person makes the PostHog template send from it. The same holds for `ReplyTo` when the site sets it. Otherwise it stays. +- A site that sets `Cc`, `Bcc`, `Attachments`, `Headers`, `Metadata`, `Tag`, `TrackOpens`, `TrackLinks`, or a `MessageStream` other than `outbound` next to the template stays: a template made in PostHog sends with its own settings. +- With `InlineCss` on, its default, Postmark moved the template's `