Files
HiveGrid-Wireframes/hivegrid-cloud/docs/boilerplate-mapping/M09-email-inbox.md
T

126 lines
21 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Boilerplate-Abgleich: M09 — Email-Inbox + Sync
| Feld | Wert |
|---|---|
| Modul-ID | M09 |
| Name | Email Inbox + Sync (Gmail/Outlook) |
| Milestones | M096 (Gmail/Outlook-OAuth + Sende-Domain), M097 (Sync + Inbox-UI + Threading + Auto-Verknüpfung), M098 (Versand + Vorlagen), M099 (Tracking + Delivery-Status + Bounces) |
| Block | Block 5 · Pflichtenheft 9.1-9.7 |
| Spec | `_bmad-output/specs/M09-email-inbox.md` |
| **Reuse-Level** | **medium** (solides E-Mail-/Worker-/Adapter-Fundament vorhanden; der Kern von M09 — User-Mailbox-OAuth-Sync, Push-Webhooks, DKIM-Sende-Domain, Auto-Match — fehlt komplett und ist neu zu bauen) |
> Quelle Boilerplate (NUR GELESEN): `/Users/raffaelsheikh/Documents/GitHub/boilerplate`. Verifiziert per Grep/Read, nicht nur aus Inventur übernommen.
## Kurz-Verdict
Die Boilerplate liefert ein **Sending-/Marketing-/Transaktions-Mail-Fundament** (MailerSend-Provider, Queue, Templates, Outbox-Mail-Routing, Bounce-Webhook-Pattern, Open/Click-Tracking) und ein generisches **App-/DataConnection-/Sync-Run-Modell** (`appsEngine.prisma`) plus ein vorbildliches **Provider-Adapter-Pattern** (`marketing-outbound`). Das ist **gut für M098/M099** und als **Vorlage** für das Adapter-Interface aus Block J nutzbar.
Der **fachliche Kern von M09 fehlt aber vollständig**: Es gibt **keine** Gmail-/Microsoft-Mailbox-OAuth-Anbindung (mit Mail-Scopes), **keine** Pub/Sub- oder Graph-Subscription-Push-Sync, **keine** DKIM/SPF/DMARC-Sende-Domain-Verifikation, **keine** Auto-Match-Logik (Mail→Kontakt/Deal/Projekt) und das vorhandene `email.prisma`-Modell ist viel zu dünn (kein Tenant-Scope auf `Email`, kein Thread, keine Labels, kein gespiegelter Mailbox-Zustand).
---
## Übernehmbar aus Boilerplate
| Boilerplate-Pfad | Was | Wie nutzbar |
|---|---|---|
| `packages/mail/src/types.ts` | `MailProvider`-Interface, `SendMailInput` (to/cc/bcc/subject/html/text/attachments/`inReplyTo`/`references`/`replyTo`/`sendAt`/`idempotencyKey`/`tenantId`/`priorityOverride`), `SendMailResult` | **als-vorlage** für den Outbound-Compose-Send-Pfad (M098). Versand geht in M09 jedoch über die **User-Mailbox** (Gmail-API `messages.send` / Graph `sendMail`), nicht über MailerSend → Interface-Form übernehmen, Implementierung neu |
| `packages/mail/src/queue.ts`, `packages/mail/src/mailersend.ts` | `createQueuedMailProvider()` (Versand async via Queue) + MailerSend-Provider | **als-vorlage** für transaktionalen Versand über System-Domain `noreply@hivegrid.de` (Spec Block C, Fallback). MailerSend-Provider zeigt das Provider-Adapter-Muster für SMTP-Side |
| `packages/mail/src/templates-react/` (`render.ts`, `_layout/`, `transactional/`) | React-Email-Templates + Layout-Primitives (BaseLayout, Header, Footer, Button mit `assertSafeUrl`) | **1:1** für transaktionale HiveGrid-Mails (Booking-Confirmation etc. = `Email`-Modell der Spec); `assertSafeUrl`/`InvalidActionUrlError` direkt für sichere Action-Links |
| `packages/marketing-outbound/src/types.ts` | `MarketingOutboundAdapter<TConfig>`-Interface (`type`/`parseConfig`/`send`), `adapterRegistry`/`resolveAdapter`, `adapterFetch()` (Timeout + SSRF-Allowlist), `maskEmailIfRequested()` (PII) | **als-vorlage** für `EmailProviderInterface` (Spec Block J / LP-11): identisches "Adapter-Interface + Registry + `resolveAdapter`"-Pattern für `GmailAdapter`/`MicrosoftAdapter`. SSRF-/PII-Helfer-Muster übernehmen |
| `packages/queue/src/payloads.ts`, `names.ts`, `producers.ts` | `queueNames.email`, `TransactionalMailJob`, `WebhookDeliveryJob`, `enqueueJob()`, `buildIdempotentJobId()`, `buildRetryJobOptions()` | **1:1/anpassen** — Basis für M09-Jobs (Initial-Sync, Push-Verarbeitung, Webhook-Renewal, Token-Refresh, DNS-Probe, Bounce). Neue typisierte Job-Payloads + ggf. neue Queue-Namen ergänzen |
| `packages/queue/src/priority.ts` | `resolveJobPriorityForTenant()` (plan-basiert), Prioritäten CRITICAL/HIGH/NORMAL/LOW | **1:1** für Quotenschutz/Drosselung pro Tenant (M098 9.6, M099) |
| `apps/worker/src/jobs/transactional-mail-outbox*` (Gruppe `mail`) | Outbox→Mail-Versand-Job, Worker-Gruppe `mail` (Concurrency 5) | **als-vorlage** für die M09-Worker-Jobs; Gruppen-/Concurrency-Modell direkt übernehmen |
| `apps/worker/src/outbox/event-router.ts` | `DEFAULT_OUTBOX_ROUTING` mit Prefix→Queue (u.a. `mail.`, `webhook.`, `notification.`, `audit.`, longest-prefix-wins) | **anpassen** — neue Prefixes (z.B. `email.sync.`, `email.match.`) registrieren für M09-Outbox-Events |
| `apps/worker/src/index.ts` + `apps/worker/src/jobs/*` (Cron-Muster, z.B. `dsgvo-grace-cron.ts` 24h, `workflow-execution-stalled-reconciler` 5m) | Single-instance Cron-Scheduler-Registrierung | **als-vorlage** für die M09-Cron-Jobs: DNS-Verifikation alle 5 Min (Block C), Microsoft-Subscription-Renewal täglich (Block D), Token-Refresh alle 30 Min (Block B), Fallback-Polling-Watchdog 4h (Block D) |
| `apps/api/src/email-sequences/provider-webhook-route.ts` + `apps/api/src/webhooks/mailersend-signature.ts` | Inbound-Provider-Webhook-Route mit Signaturverifikation + Bounce-Event-Mapping (`hard_bounced`/`soft_bounced`/`rejected`/`spam_complaint`) | **als-vorlage** für die Push-/Bounce-Webhook-Endpunkte: `/api/v1/webhooks/email/gmail`, `/api/v1/webhooks/email/microsoft` (Block D) und Delivery-/Bounce-Webhooks (M099). Hard-/Soft-Bounce-Mapping direkt wiederverwendbar |
| `apps/api/src/route-access-inventory.ts` (Klasse `webhook-signature`) | Auth-Klassen-Matrix inkl. `webhook-signature` für signierte Provider-Webhooks | **1:1** — neue M09-Webhook-Routen unter `webhook-signature` einordnen |
| `apps/web/app/modules/admin-sso/client.server.ts` + `state.server.ts` + `apps/web/app/routes/auth.admin.callback.tsx` | `openid-client`-Wrapper: Issuer-Discovery, PKCE/state/nonce-Generierung, Code-Exchange im Callback | **als-vorlage** für den OAuth-Connect-Flow (Block B). ACHTUNG: existierend nur für **Login-SSO (Authentik OIDC)**, NICHT für Gmail/Graph mit Mail-Scopes → Flow-Skelett übernehmen, Provider/Scopes/Token-Storage neu |
| `packages/storage/src/index.ts` + `signed/` + `scan/` | S3/Scaleway-Adapter, Signed-Upload/Download-URLs, ClamAV-/magic-bytes-Virus-Scan, Quarantäne | **1:1** für `EmailAttachment`-Storage (Spec: `tenants/{tenantId}/emails/{messageId}/{filename}`, LP-13 EU-Storage), Lazy-Download von Provider-Side, Download-Links im Detail-View |
| `packages/db/src/outbox.ts` (`publishOutboxEvent`) + `prisma/schema/outbox.prisma` | Transaktionales Outbox-Pattern (atomarer Side-Effect mit DB-Write, `dispatchKey`-Idempotenz) | **1:1** — jeder M09-Side-Effect (neue Mail gespiegelt → Auto-Match → Activity → Notification) läuft über Outbox |
| `packages/db/src/client.server.ts`, `transactions.server.ts` | `getWriteDbClient`/`getReadDbClient`, `runDbTransaction` | **1:1** Fundament; Read-Replica für Inbox-Listen-Heavy-Queries |
| `packages/db/src/dsgvo/user-fk-map.ts` | Pflicht-Karte aller User-FKs (CI-Test bricht sonst) | **anpassen (Pflicht)** — neue M09-Modelle mit User-FK (`owner_user_id`, `manual_override_user_id`, `EmailRead.reader…`) eintragen |
| `packages/realtime/src/*` (SSE) | SSE-Event-Serialisierung + Notification-Stream | **1:1** für Live-Inbox-Badge (Sidebar `badge: 'count'` für ungelesene Mails, Integration-Contracts §2) + Sync-Status-Live-Update |
| `packages/search/src/*` (Meilisearch, tenant-scoped, Outbox-Reindex) + `schemas/` | Such-Index-Pattern, `bulkIndex`, `searchInIndex`, Outbox-Publisher | **als-vorlage** für Inbox-Volltext-Suche (M097: Subject+Body+Absender). Spec nennt zusätzlich Trigram-Index in Postgres als Alternative — Meili-Pattern ist die saubere Querschnitt-Variante |
| `packages/i18n/*` + `apps/web/app/locale/*` (Namespace `mail` existiert) | i18n-Setup de/en, Klartext-Keys, `assertI18nLabel`-Zwang | **1:1** — alle M09-Klartext-Diagnose-Texte (LP-10) als i18n-Keys; vorhandener `mail`-Namespace erweiterbar |
| App-Shell: `packages/view-models`, `packages/ui-app` (Registry-Factories), `apps/web/app/application/sidebar/*`, `uiRegistry.ts` | Datengetriebene Sidebar mit Permission/Flag-Gating, `VMState`-Statusmodell, Breadcrumb-Registry, stabile `data-ui-id` | **1:1/anpassen** — Inbox-Route + Sidebar-Eintrag (Gruppe KOMMUNIKATION, Integration-Contracts §1) + Breadcrumb + View-Model-Vertrag |
| `packages/ui-mock` + Hot-Swap (`HotSwapPageRenderer`) + `apps/storybook` (lost-pixel, axe) | Hot-Swap-Drill, Visual-Regression, a11y-Gates | **1:1** für die DoD-Pflichten (Hot-Swap-Drill, Visual-Snapshot) |
| `prisma/schema/notifications.prisma` (`NotificationDelivery`, prefs, `DeviceToken`) + Notification-Wiring (Contracts §7 `notify()`) | Notification-Querschnitt In-App/Email/Push | **1:1** für OAuth-Disconnect-/revoked-/Send-Fehler-Benachrichtigungen (Block B/D, LP-10) |
| `prisma/schema/core.prisma` (`AuditEvent` Hash-Kette) + Audit-Wiring (Contracts §6, auto via Middleware; `auditEvent()` manuell für Nicht-Prisma) | Tamper-evidenter Audit-Trail | **1:1** — manueller Match-Override loggt `audit_event` (Spec AV #6); externe Provider-Calls manuell auditieren |
| `prisma/schema/featureFlags.prisma` + Feature-Flag-Querschnitt | Modul ohne Deploy abschaltbar (DoD-Pflicht) | **1:1** |
| `packages/entitlements` / Permissions (`permissions.prisma`, Contracts §10) | RBAC-Fundament + Permission-Key-Konvention | **anpassen** — neue Keys `email.read_own`/`email.read_all`/`email.write`/`email.admin` + Bundle-Mapping (Spec Block I) ergänzen |
---
## Vorhandene Daten-Modelle (Prisma) — Bestand vs. Bedarf
Schema-Pfad: `/Users/raffaelsheikh/Documents/GitHub/boilerplate/prisma/schema/`
### `email.prisma` (10 Modelle) — teilweise relevant, aber dünn
- **`Email`** (`messageId @unique`, `type` inbound/outbound, `date`, `subject`, `fromEmail/fromName`, `toEmail/toName`, `textBody`, `htmlBody`) — deckt grob die HiveGrid-eigene `Email`-Entität (Spec Block A, transaktionale Mails) ab. **Lücken ggü. Spec:** **kein `tenantId`** (nur indirekt über `TenantInboundAddress`), kein `direction`-Enum, keine `cc/bcc`-Arrays am Modell (CC via separatem `EmailCc`-Modell), kein `delivery_status`/`bounce_type`/`bounce_reason`, keine `related_contact/company/deal/project`-FKs, kein `archived_at`, kein `provider_message_id` vom SMTP-Provider getrennt.
- **`EmailRead`** (`emailId`, `userId`, `createdAt`) — existiert, aber semantisch **anders**: trackt "von HiveGrid-User gelesen", nicht "vom Empfänger gelesen" (Spec `EmailRead` = Pixel-Tracking mit `reader_ip`/`reader_user_agent`). → **anpassen/erweitern**.
- **`EmailCc`** — separate CC-Tabelle. Spec modelliert cc/bcc als Arrays direkt am Message-Modell. → Designentscheidung.
- **`EmailAttachment`** (`name`, `type`, `length`, `content`, `publicUrl`, `storageBucket`, `storageProvider`) — gute Basis für Spec-`EmailAttachment`. **Lücken:** kein `parent_kind`/`parent_id`-Polymorphismus (hängt fest an `Email`), kein `provider_attachment_id`/`download_status` für Lazy-Download.
- **`EmailSender`** (`provider`, `stream`, `apiKey`, `fromEmail`, `replyToEmail`) — SMTP-Sender-Config. Nutzbar als Anker für transaktionalen Versand, **aber** das ist NICHT die DKIM-verifizierte `TenantSendingDomain` der Spec (kein `dkim_*`, kein `verification_status`).
- **`TenantInboundAddress`** (`address @unique`) — Name kollidiert mit Spec-`TenantInboundAddress`, ist aber simpler (kein `local_part`/`full_address`/`purpose`-Enum/`archived_at`). → **anpassen** oder neues Modell.
- **`Campaign`, `OutboundEmail`, `OutboundEmailOpen`, `OutboundEmailClick`** — Marketing-Kampagnen + Open/Click-Tracking. **Gehört primär zu M10 (Marketing)**, aber `OutboundEmail` (mit `sentAt`/`deliveredAt`/`bouncedAt`/`spamComplainedAt`/`unsubscribedAt`) ist ein **direkter Template-Bestand für M099** (Delivery-Status + Bounce-Tracking) und für Spec-`Email.delivery_status`.
### `appsEngine.prisma` (5 Modelle) — Template für OAuth-Connection + Sync-Runs
- **`App`** (`@@unique([tenantId, type])`, `config` JSON, `isActive`) — "installierte App pro Tenant". **als-vorlage** für die Email-Integration-Aktivierung pro Tenant.
- **`DataConnection`** (`type` "oauth2"/"rest-api"/"webhook", `config` = **encrypted JSON credentials**) — **direkt relevant** als Speicherort-Muster für OAuth-Tokens. Spec verlangt aber dedizierte Felder (`oauth_access_token_encrypted`, `oauth_refresh_token_encrypted`, `oauth_token_expires_at`, `oauth_scope_granted`, `sync_status`, `webhook_subscription_id`, `webhook_expires_at`) → entweder `DataConnection.config` als JSON nutzen ODER (empfohlen) dediziertes `EmailIntegrationMailbox`-Modell bauen.
- **`AppSyncRun`** (`status` pending/running/completed/partial/failed, `executionMode` manual/scheduled/webhook, `itemsProcessed/created/updated/failed`, `error`) — **als-vorlage** für `EmailIntegrationSyncCursor.initial_sync_status`/`progress` (Block A/D) und für Sync-Run-Observability.
- **`AppSyncRunLog`**, **`AppSyncItem`** (Source→Destination-Mapping + Rollback) — nützliches Muster für Per-Message-Sync-Logging, eher als Vorlage denn 1:1.
### `accounts.prisma` — OAuth-Bestand
- **`User.googleId`/`User.githubId` (`@unique`)** — Login-OAuth-Identitäten. **NICHT** das, was M09 braucht (das sind Auth-Login-IDs, keine Mailbox-Connections mit `gmail.modify`/`Mail.ReadWrite`-Scopes + Refresh-Tokens). Nur als Hinweis, dass Google-OAuth-Login schon existiert.
### `emailSequences.prisma` (3) + `marketingLeads.prisma` (`MarketingIntegration`)
- Bounce-/Open-/Click-Felder + verschlüsselte `configJson` — Template-Bestand für M099 und für verschlüsselte Provider-Config (relevanter für M10).
**Vorgesehener Ort für neue HiveGrid-Modelle:** `prisma/schema/app.prisma` (leerer Platzhalter `// custom database models`) — hier kommen die M09-eigenen Modelle hinein, ohne Boilerplate-Domänen zu verändern.
---
## Lücken / komplett neu zu bauen
Verifiziert: kein Treffer in `packages/`, `apps/`, `prisma/` für Gmail-API/`googleapis`, Pub/Sub, `graph.microsoft`/Graph-Subscriptions, `gmail.modify`/`Mail.ReadWrite`-Scopes, DKIM/SPF/DMARC, Sending-Domain-Verifikation. (Grep-Treffer auf "gmail/google/dkim" waren ausschließlich Falsch-Positive in feature-flags, config-catalog, Email-Template-Texten und `node_modules`.)
1. **Mailbox-OAuth-Connect (Block B) — KOMPLETT NEU.** Gmail-OAuth (`gmail.modify`/`gmail.send`/`gmail.labels`/`userinfo.email`) und Microsoft-OAuth (`Mail.ReadWrite`/`Mail.Send`/`User.Read`/`offline_access`). Vorhandener `openid-client`-Flow (Admin-SSO) nur als Skelett. Token-Refresh-Worker, Disconnect+Token-Revoke, `sync_status`-Lifecycle.
2. **Push-Sync (Block D) — KOMPLETT NEU.** Gmail-Watch-API + Pub/Sub-Push-Endpoint, Microsoft-Graph-Subscription auf `/me/messages` + tägliches Renewal (3-Tage-Lifetime), `historyId`/`deltaToken`-Cursor-Sync, Fallback-Polling-Watchdog (4h). Webhook-Routen `/api/v1/webhooks/email/{gmail,microsoft}` (Signatur-/Token-Verifikation analog `mailersend-signature`).
3. **Provider-Adapter `EmailProviderInterface` (Block J / LP-11) — NEU (Pattern vorhanden).** `connect/disconnect/fetchMessages/getMessage/sendMessage/subscribeToWebhook/renewWebhook/revokeWebhook/markRead/downloadAttachment` + `GmailAdapter`/`MicrosoftAdapter`. Interface-/Registry-Muster aus `marketing-outbound` als Vorlage; Implementierungen neu. Klartext-Fehler-Übersetzung pro Adapter (LP-10).
4. **Sende-Domain DKIM/SPF/DMARC (Block C) — KOMPLETT NEU.** `TenantSendingDomain`-Modell (Spec-Version), DKIM-Schlüsselpaar-Generierung (2048 Bit, encrypted Private-Key), DNS-TXT-Record-Bau (DKIM/SPF/DMARC), DNS-Lookup-Verification-Cron (alle 5 Min, 7-Tage-Timeout), Copy-to-Clipboard-UI. Plattform-Fundament für M10.
5. **Auto-Match-Logik (Block E) — KOMPLETT NEU.** Mail→Kontakt (Email-Match gegen `ContactEmail`/`Lead.email`), Mail→Deal/Projekt (Subject-Pattern `[Deal #X]`/`[Auftrag #X]`/`[Lead #X]`), Heuristik (genau-1-offener-Deal → medium), manueller Override (hält stand), Edge-Cases (Mehrfach-Contacts, eigene Adresse, Newsletter/Bulk via List-Unsubscribe-Header). Setzt M042 (Kontakt), M060/M066 (Deal/Auftrag) voraus.
6. **Vollständiges M09-Datenmodell — NEU (Teil-Bestand).** `EmailIntegrationMailbox`, `EmailIntegrationMessage` (mit Thread/Labels/Match-Feldern/Trigram-Suche), `EmailIntegrationSyncCursor`, `EmailIntegrationWebhookEvent` (mit Retention 30/90 Tage). Bestehende `Email`/`EmailAttachment`/`EmailRead`/`TenantInboundAddress` müssen erweitert oder zugunsten Spec-konformer Modelle ergänzt werden (Tenant-Scope, direction, Match-FKs, delivery_status, polymorphe Attachments).
7. **Inbox-UI (Block F) — NEU (Shell-/Komponenten-Fundament vorhanden).** Listen-View mit Filtern (Mailbox/Direction/Read/Verknüpfung/Datum/Anhang), Volltext-Suche, Bulk-Actions, Cursor-Pagination; Detail-View mit Thread-Aggregat, CSP-gehärtetem HTML-Body-Render ("Bilder anzeigen"-Toggle = Tracking-Pixel-Schutz), Attachment-Liste, Verknüpfungs-Editor, Reply/Reply-All/Forward, Provider-Deep-Link. shadcn-Tabellen/Modale/Forms aus `apps/web` wiederverwendbar, aber inbox-spezifische Komponenten neu.
8. **Outbound-Compose (Block G) — NEU.** Rich-Text-Editor (TipTap laut Milestone-Hinweis in Deps; verifizieren), To/CC/BCC mit Contact-Autocomplete, Mailbox-Auswahl, Anhang-Upload (≤25 MB), Send über User-Mailbox (nicht MailerSend), Save-as-Draft, Compose-Aufruf aus Kontakt-/Deal-/Projekt-/Inbox-Kontext mit Pre-Fill + Subject-Pattern. BCC-Logging-Adresse.
9. **OAuth-Token-Encryption (KMS) — NEU/zu klären.** Kein dediziertes Crypto-/KMS-Paket gefunden (nur `…Encrypted`-Spalten-Konvention + verschlüsselte `configJson` in marketing/appsEngine). Konkretes KMS-Setup (Scaleway-managed-Key) ist offener Detail-Punkt der Spec.
10. **Vorlagen + Variable-Resolution (M098 9.7) — NEU.** Quick-Reply-Templates + `{{first_name}}`-Resolver gegen Kontakt-Properties. React-Email/Render vorhanden, aber Variable-Resolver gegen CRM-Daten neu.
11. **Bounce-/Sperrliste (M099) — NEU (Teil-Bestand).** Hard-Bounce→Sperrliste-Auto-Add pro Tenant, Soft-Bounce 3×-Retry/24h. Bounce-Event-Mapping (hard/soft/rejected/spam) aus `email-sequences/provider-webhook-route.ts` wiederverwendbar; Sperrlisten-Modell + Kontakt-Detail-Hinweis neu.
12. **Activity-Stream-Integration (Block H) — Wiring NEU.** `email_received`/`email_sent`/`email_match_changed` via `logActivity` (Contracts §5, Service kommt aus M045). Permission-gegateter Activity-Inhalt (`email.read_own` vs. nur "Email-Aktivität (nicht einsehbar)").
---
## Empfohlenes Vorgehen (Reihenfolge)
**Phase 0 — Fundament aus BP übernehmen (1:1), bevor M09-Logik beginnt:**
1. Datenmodell in `prisma/schema/app.prisma` anlegen (`EmailIntegrationMailbox/Message/SyncCursor/WebhookEvent`, Spec-`TenantSendingDomain`, erweitertes `Email`/`EmailAttachment`/`EmailRead`/`TenantInboundAddress`). Forward-Only-Migration mit Inverse-SQL-Kommentar (DoD). **`user-fk-map.ts` zwingend ergänzen** (sonst CI-Bruch).
2. Permission-Keys + Bundle-Mapping (Block I) in `packages/entitlements` ergänzen; Sidebar-Eintrag (Gruppe KOMMUNIKATION) + Route + Breadcrumb + Feature-Flag verdrahten (Integration-Contracts §1-4, §10).
3. Outbox-Routing-Prefixes + neue typisierte Queue-Jobs + Worker-Gruppe `mail`/neue Gruppe registrieren (aus `packages/queue` + `apps/worker`-Mustern).
**Phase 1 — M096 (Connect-Fundament):**
4. OAuth-Connect-Flow aus `admin-sso/client.server.ts`-Skelett ableiten, aber Gmail-/Graph-Provider + Mail-Scopes + verschlüsseltes Token-Storage neu. Token-Refresh-Cron (Muster aus `apps/worker/src/jobs`).
5. `EmailProviderInterface` + `GmailAdapter`/`MicrosoftAdapter` nach `marketing-outbound`-Adapter-Pattern (Registry + `resolveAdapter` + `adapterFetch`-Härtung).
6. DKIM/SPF/DMARC-Sende-Domain komplett neu (Schlüsselgenerierung, DNS-Record-Bau, 5-Min-Verifikations-Cron, 7-Tage-Timeout).
**Phase 2 — M097 (Sync + Inbox):**
7. Push-Webhook-Routen (Gmail Pub/Sub, Microsoft Graph) nach `provider-webhook-route.ts`-Muster + Signatur-/Token-Verifikation; Initial-Sync-Job mit Cursor; Renewal-/Watchdog-Cron.
8. Auto-Match-Logik (neu) + Activity-Wiring (`logActivity`) + Outbox.
9. Inbox-UI (Liste+Detail) auf App-Shell/shadcn-Fundament; Volltext-Suche via `packages/search`-Pattern; Attachments via `packages/storage` (signed URLs, EU-Bucket); SSE-Badge via `packages/realtime`.
**Phase 3 — M098/M099 (Versand + Tracking):**
10. Outbound-Compose + Send über User-Mailbox (Adapter `sendMessage`), Spiegelung als `direction=outbound`-Message; Vorlagen + Variable-Resolver; transaktionaler Fallback-Versand über MailerSend/`packages/mail` für System-Mails.
11. Delivery-Status/Bounce: Bounce-Webhook + hard/soft-Mapping (aus `email-sequences` übernehmen), Sperrliste pro Tenant, Quotenschutz via `queue/priority.ts`-Plan-Prioritäten.
**Querschnitt durchgängig (DoD):** i18n-Keys (Namespace `mail` erweitern), Klartext-Diagnose (LP-10) aus M002-Catalog, View-Model-Pflicht (Contracts §11), Audit auto/manuell, Notifications via `notify()`, Smoke-Test + Hot-Swap-Drill + Visual-Snapshot, Customer-Portal-Sichtbarkeit explizit (Default: nicht sichtbar), Permission-Denied→404.
**Vor Bau zu validieren (Spec-Hinweis):** Microsoft-3-Tage-Renewal-Lifecycle und DKIM-DNS-Check mit echter Domain; konkretes KMS-Setup für Token-Verschlüsselung; ob TipTap tatsächlich in den Boilerplate-Deps liegt (Milestone-Annahme).