# Coordinator email through Keymail

Status: blocked on upstream contract/access, 2026-11-13. This is an integration
proposal, not an available email feature. No mailbox, transport, credentials,
database migration, worker or UI is enabled by this change.

## Evidence and exact blocker

Checked the reachable resources before choosing an implementation:

- MCP resource and resource-template discovery both returned empty lists.
  No Keymail backend or mail-service API is exposed by the tools in this step.
- Repository searches for Keymail find sign-in configuration in
  `internal/equipo/setup/session_handlers.go` (`auth.New`, `KeymailServers`)
  and `github.com/keymaildev/signin v0.1.1` in `go.mod`. Neither establishes a
  mailbox or two-way delivery contract.
- `README.md:50-53` describes CARLOS SMTP credentials for **sign-in mail**.
  These must not be reused for this feature.
- Existing “connector” contracts concern model providers and token scheduling,
  not Keymail delivery.
- The coordinator's repository lookup found only Docs' OAuth client, not a
  Keymail backend. That is supplied investigation evidence, not a fresh backend
  inspection here. No Docs code was changed.

We cannot verify Keymail's mailbox capabilities, authentication scopes, inbound
sender guarantees, delivery semantics or test access. This does **not** establish
that Keymail lacks those capabilities. No guessed endpoints or live probes were
used. The unblocker is a Keymail maintainer supplying a versioned service contract,
an identified backend/repository owner and authorized sandbox access, with fixtures
for the capabilities below. Mailbox provisioning and real sending require separate
explicit authorization even after that contract is available.

## Proposed upstream contract, not discovered API

Ask Keymail to confirm or provide:

1. An explicitly provisioned coordinator identity with stable mailbox ID, verified
   sending domain, inbound address and revocation. Display name must disclose
   “Equipo coordinator”; never impersonate the person. Equipo stores the mapping
   of mailbox, coordinator, team and person. Provisioning is an operator-approved
   operation, not an agent tool.
2. Submission restricted to that mailbox, to one verified recipient, with immutable
   content and a client idempotency key. Reusing the key with different content
   must conflict. Supply retention guarantees, provider message ID, RFC Message-ID,
   correlation headers, structured temporary/permanent errors, Retry-After and
   a lookup-by-key operation for ambiguous submission outcomes.
3. Authenticated inbound and delivery events with stable IDs, mailbox and message
   IDs, signed timestamp, key rotation, replay window, retry/ack semantics and
   reconciliation cursor. Specify signature coverage of raw bytes and envelope,
   not just user-controlled headers. Events include accepted, delivered, deferred,
   permanent bounce and complaint. Acceptance must not be labelled delivery.
4. An explicit sender-verification assertion binding a Keymail authenticated
   subject to its currently verified address, audience, message and mailbox.
   Signing a webhook or reporting SPF/DKIM/DMARC does not by itself bind an
   arbitrary From address to an Equipo person. If this assertion is unavailable
   for external senders, hold their messages for confirmation in an authenticated
   Equipo session before importing them. Do not treat a reply token as identity.
5. Separate least-privilege credentials for sending from one mailbox and reading
   its events, plus rotation/revocation and quotas. No domain administration,
   arbitrary-recipient sending or access to the person's other mail. Provide
   bounded MIME fixtures and attachment retrieval semantics without arbitrary
   URL fetching.

**Required Keymail work is conditional:** if these facilities exist, provide
documentation and sandbox access; otherwise implement only the missing agreed
capabilities. There is no evidence here to claim a particular backend change is
necessary, or to estimate one as completed.

## Equipo ownership and conversation handoff

The new `internal/coordinatormail` package is an isolated, pure policy prototype.
It refuses unconfigured/unapproved outbound, unverified or third-party recipients,
opt-outs, suppressed recipients, undisclosed identity, mismatched reply scopes and
unverified/automatic replies. Its inputs are trusted server-resolved facts, not
JSON request fields. It is **not** a verifier, persistence layer or runtime guard
until a reviewed adapter integrates it. Tests exercise those refusal boundaries.

Leave ongoing conversation-thread work in `internal/equipo/conversation` alone.
Its `EnsureThread` already joins task creation's transaction and `RouteMessage`
has requester and mutation checks. Do not introduce another task/thread store or
call RouteMessage from email. Agree this interface with that work's owner before
wiring it:

- Resolve a stored opaque reply-route hash to mailbox, team, person, verified
  address, coordinator, project, task and existing conversation/thread ID. Bind
  the original outbound Message-ID too. References/In-Reply-To must match that
  stored route; subject text never selects a task. Ambiguity, expired routes,
  deleted tasks and lost access go to quarantine, never automatic task creation.
- Append an **untrusted external discussion** entry to that thread, atomically
  with the inbound event receipt, using a deterministic mutation ID. The thread
  owner must supply a non-executing append boundary; do not assume SendMessage
  is non-executing. Until agreed, no inbound adapter is enabled.
- Retain source provenance and provider/event IDs. From, quoted/forwarded text,
  attachments and model interpretations never grant authority. Even a verified
  sender does not approve spending, permissions, execution, deployment or other
  sensitive actions by email. Existing authenticated approval gates remain.

## Durable delivery design required before enabling

Use Equipo's SQL store, not an in-memory queue. Keep a separate mail delivery
ledger from device notification acknowledgments. Existing integration points are
`internal/equipo/notifications/outbox.go`, its person-scoped Event model and
migration `0031_notifications.sql`. Do not alter their device cursor semantics.

In a transaction with selection of an eligible source event, insert:

- delivery ID; unique `(team, person, source_event, channel)`; immutable scope,
  content hash, preference revision and sender identity; provider idempotency key;
- state, attempt count, next-attempt time, lease owner/expiry, provider IDs,
  timestamps and sanitized error code;
- an append-only audit entry containing actor, decision, scope and correlation ID,
  never tokens, raw MIME or message bodies.

States: queued -> submitting -> accepted -> delivered. Temporary failures become
retry_wait; permanent failures become failed; bounces become bounced; complaints
or opt-out become suppressed. Unknown submission outcome becomes uncertain, not
a fresh send. Lease claims use compare-and-swap and fencing. After a crash, query
by the **same** key before resubmitting identical content. If upstream cannot
resolve uncertainty or its idempotency retention has expired, stop for operator
reconciliation, never retry with a new key. Exactly-once mail cannot be promised
without upstream guarantees.

Proposed initial limits: five submission attempts total within 24 hours, delays
of 1 minute, 5 minutes, 30 minutes and 2 hours plus bounded jitter. Honor a longer
Retry-After only within the deadline, otherwise stop. Every provider attempt must
be recorded before I/O. Recheck verified address, membership, recipient consent,
mailbox authorization and suppression before each attempt. Address changes cancel
old queued mail rather than rewriting its recipient under the same key.

Deduplicate status events and inbound receipts with unique
`(provider, mailbox_id, event_id)` constraints, plus a mailbox-scoped stable
provider message ID for repeated inbound events. Persist receipt, audit and
thread append atomically before acknowledging. Reject conflicting payload hashes
for the same ID. Apply status changes monotonically: a late accepted/delivered
event must not erase a bounce or complaint. Persist hard-bounce/complaint
suppression before scheduling further mail; soft bounces consume the bounded
retry budget. Re-enablement requires authenticated confirmation.

Default preference is off. Authenticated person settings explicitly opt in per
coordinator/project and notification category, support quiet hours and frequency
caps, and can disable all email. Device subscriptions are not email consent.
Include a clear sender, project/task context, why the mail was sent and an
authenticated preference link. Never send to addresses supplied in prompts,
headers, forwarded messages, Cc or Bcc. This initial slice covers existing task
threads only.

## Inbound containment and loops

Do not reply automatically to inbound mail. Filter coordinator-originated mail,
delivery reports, Auto-Submitted messages and bulk/list traffic. Suppress email
notifications for the imported message's source event, and do not allow that
event to trigger an automatic coordinator email response. Rate-limit by mailbox
and bound pending/quarantine storage. Bounce handling uses authenticated provider
events, not text that claims to be a bounce.

Initially quarantine attachments, do not feed them to tools or models. Bound raw
MIME to 10 MiB, decoded aggregate to 10 MiB, part count to 20 and nesting to 5;
reject over-limit messages before expansion. Do not unpack archives, execute
files, load remote images or follow attachment URLs. Render plain text safely;
keep quoted/forwarded content labelled as untrusted context. A later explicit
attachment import must use `internal/attach` byte sniffing, filename cleanup,
image metadata stripping and limits, with private storage, access checks and
authenticated downloads. Malware scanning and retention/deletion policies must
be agreed before enabling attachment import. Logs must omit mail bodies and
credentials; raw quarantined mail requires restricted access and bounded retention.

## Release acceptance, beyond the offline policy tests

Before opt-in is offered, run sandbox contract tests for:

- Restart after provider acceptance but before local commit; concurrent workers;
  expired leases; repeated source events; key/content conflicts; uncertainty
  without lookup. Each produces at most one provider submission identity.
- Duplicate/reordered webhook events, lost acknowledgments, replayed/invalid
  signatures, rotation, forged From and valid DKIM without subject binding.
- Cross-person/team/project/task routes, stolen reply token, subject spoofing,
  revoked membership, changed address and ambiguous References. No new task.
- Atomic thread append/receipt rollback; retries append once and never execute
  instructions. Approval-required actions still require the existing UI flow.
- Opt-out racing dispatch, hard/soft bounces, complaints, retry exhaustion,
  rate limits, self loops and automatic replies.
- Oversized/nested MIME, malicious HTML, archives, remote URLs and quoted
  instructions. No authority or automatic tool access from any content.

This change implements only offline policy tests. Persistence, webhook verification,
preference UI, conversation handoff and all above end-to-end tests remain release
blockers. No real sending, provisioning, paid service or broader permission was used.
