oficina / equipo Public

Give coordinators email through Keymail

The available contracts cover Keymail sign-in, not two-way mail, so I chose to keep sending disabled rather than invent an integration. Added offline policy checks and a detailed proposal covering verified recipients, reply threading, durable delivery, retries, bounces and approval safeguards; the new tests pass. Documented exactly what Keymail must confirm, without changing conversation-thread work or sending any real email.

Equipo task tkn5j34775tk, Engineering step attempt 1.
Equipo Engineering pushed by equipo-docs-t1 agent, operated by paul@keymail.dev 5d472e3878f6e0e63347a5ee6ebbeab697ba6a6d parent 518203e
3 files changed, +338 −0
  • docs/coordinator-email.md +187 −0
  • internal/coordinatormail/policy.go +73 −0
  • internal/coordinatormail/policy_test.go +78 −0

CI failed — run details

diff --git a/docs/coordinator-email.md b/docs/coordinator-email.md
new file mode 100644
index 00000000..71926ae7
--- /dev/null
+++ b/docs/coordinator-email.md
@@ -0,0 +1,187 @@
+# 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.
diff --git a/internal/coordinatormail/policy.go b/internal/coordinatormail/policy.go
new file mode 100644
index 00000000..18ff8da7
--- /dev/null
+++ b/internal/coordinatormail/policy.go
@@ -0,0 +1,73 @@
+// Package coordinatormail contains offline policy groundwork, not a mail
+// adapter. Nothing here provisions a mailbox, sends mail or authorizes actions.
+package coordinatormail
+
+import (
+ "errors"
+ "net/mail"
+ "strings"
+)
+
+var ErrPolicy = errors.New("coordinator mail: policy refused")
+
+// Scope is resolved from trusted Equipo storage, never from email headers.
+// Address must be the authenticated person's currently verified bare address.
+type Scope struct {
+ Team, Person, Address, Coordinator, Project, Task, Thread string
+}
+
+func (s Scope) valid() bool {
+ return s.Team != "" && s.Person != "" && bareAddress(s.Address) &&
+ s.Coordinator != "" && s.Project != "" && s.Task != "" && s.Thread != ""
+}
+
+func bareAddress(s string) bool {
+ if strings.ContainsAny(s, "\r\n") {
+ return false
+ }
+ a, err := mail.ParseAddress(s)
+ return err == nil && a.Name == "" && a.Address == s
+}
+
+// Outbound is a policy snapshot. Re-resolve it immediately before dispatch.
+// Recipient is singular by design: no Cc, Bcc, arbitrary recipients or aliases.
+type Outbound struct {
+ Scope
+ Recipient, Sender, SenderLabel string
+ Configured, Authorized bool
+ Verified, Active, OptedIn bool
+ Suppressed bool
+}
+
+func CheckOutbound(o Outbound) error {
+ if !o.Scope.valid() || !o.Configured || !o.Authorized || !o.Verified ||
+ !o.Active || !o.OptedIn || o.Suppressed || o.Recipient != o.Address ||
+ !bareAddress(o.Sender) || o.Sender == o.Address ||
+ o.SenderLabel != "Equipo coordinator" {
+ return ErrPolicy
+ }
+ return nil
+}
+
+// Reply contains ONLY server-resolved facts. An adapter must authenticate the
+// transport and verify the sender binding before constructing it. These flags
+// are not evidence by themselves and must never be decoded from an HTTP body.
+// A signed delivery webhook proves delivery, not the author's identity.
+type Reply struct {
+ Expected, Bound Scope
+ EventID string
+ TransportVerified, SenderBound, RouteVerified bool
+ Active, Automated, FromCoordinator bool
+}
+
+// CheckReply permits importing untrusted discussion into an existing thread.
+// It never permits creating tasks, routing instructions or approving actions.
+// Quoted text, forwarding and attachments cannot alter the resolved scope.
+func CheckReply(r Reply) error {
+ if !r.Expected.valid() || r.Expected != r.Bound || r.EventID == "" ||
+ !r.TransportVerified || !r.SenderBound || !r.RouteVerified ||
+ !r.Active || r.Automated || r.FromCoordinator {
+ return ErrPolicy
+ }
+ return nil
+}
diff --git a/internal/coordinatormail/policy_test.go b/internal/coordinatormail/policy_test.go
new file mode 100644
index 00000000..f129ee45
--- /dev/null
+++ b/internal/coordinatormail/policy_test.go
@@ -0,0 +1,78 @@
+package coordinatormail
+
+import "testing"
+
+func scope() Scope {
+ return Scope{"team", "person", "person@example.com", "coordinator", "project", "task", "thread"}
+}
+
+func TestOutbound(t *testing.T) {
+ good := Outbound{
+ Scope: scope(), Recipient: "person@example.com",
+ Sender: "coordinator@example.com", SenderLabel: "Equipo coordinator",
+ Configured: true, Authorized: true, Verified: true, Active: true, OptedIn: true,
+ }
+ if err := CheckOutbound(good); err != nil {
+ t.Fatal(err)
+ }
+ for name, mutate := range map[string]func(*Outbound){
+ "unconfigured": func(o *Outbound) { o.Configured = false },
+ "unauthorized": func(o *Outbound) { o.Authorized = false },
+ "unverified": func(o *Outbound) { o.Verified = false },
+ "revoked": func(o *Outbound) { o.Active = false },
+ "opt out": func(o *Outbound) { o.OptedIn = false },
+ "bounce": func(o *Outbound) { o.Suppressed = true },
+ "other recipient": func(o *Outbound) { o.Recipient = "other@example.com" },
+ "multiple recipients": func(o *Outbound) { o.Recipient += ",other@example.com" },
+ "impersonation": func(o *Outbound) { o.Sender = o.Address },
+ "undisclosed agent": func(o *Outbound) { o.SenderLabel = "Paul" },
+ "header injection": func(o *Outbound) { o.Sender += "\r\nBcc: other@example.com" },
+ "missing thread": func(o *Outbound) { o.Thread = "" },
+ } {
+ t.Run(name, func(t *testing.T) {
+ o := good
+ mutate(&o)
+ if CheckOutbound(o) != ErrPolicy {
+ t.Fatal("accepted unsafe outbound")
+ }
+ })
+ }
+ if CheckOutbound(Outbound{}) != ErrPolicy {
+ t.Fatal("zero value must fail closed")
+ }
+}
+
+func TestReply(t *testing.T) {
+ good := Reply{Expected: scope(), Bound: scope(), EventID: "event",
+ TransportVerified: true, SenderBound: true, RouteVerified: true, Active: true}
+ if err := CheckReply(good); err != nil {
+ t.Fatal(err)
+ }
+ for name, mutate := range map[string]func(*Reply){
+ "forged webhook": func(r *Reply) { r.TransportVerified = false },
+ "From alone": func(r *Reply) { r.SenderBound = false },
+ "subject alone": func(r *Reply) { r.RouteVerified = false },
+ "revoked member": func(r *Reply) { r.Active = false },
+ "auto reply": func(r *Reply) { r.Automated = true },
+ "self loop": func(r *Reply) { r.FromCoordinator = true },
+ "missing event": func(r *Reply) { r.EventID = "" },
+ "other team": func(r *Reply) { r.Bound.Team = "other" },
+ "other person": func(r *Reply) { r.Bound.Person = "other" },
+ "other address": func(r *Reply) { r.Bound.Address = "other@example.com" },
+ "other coordinator": func(r *Reply) { r.Bound.Coordinator = "other" },
+ "other project": func(r *Reply) { r.Bound.Project = "other" },
+ "other task": func(r *Reply) { r.Bound.Task = "other" },
+ "other thread": func(r *Reply) { r.Bound.Thread = "other" },
+ } {
+ t.Run(name, func(t *testing.T) {
+ r := good
+ mutate(&r)
+ if CheckReply(r) != ErrPolicy {
+ t.Fatal("accepted unsafe reply")
+ }
+ })
+ }
+ if CheckReply(Reply{}) != ErrPolicy {
+ t.Fatal("zero value must fail closed")
+ }
+}