plan: platform mail submission — implementation plan and census card (docs only)
Nine tasks implementing the approved design (docs/superpowers/specs/2026-11-12-platform-mail-submission-design.md): 1 pause on the sender record; 2 EmailTags attribution guard and mail_caller_sends; 3 mailer unit, user, socket, peer rule; 4 the verb at both bind sites, CARLOS_MAIL; 5 mailer SES send (SendRawEmail only), header hygiene, rate, per-box cap; 6 switch, door, reap, switch-off, mailer_unarmed alert; 7 rastrillo submit transport (cross-repo); 8 infra IAM user and policy; 9 Oficina migration. Census card draft for the in-scope tasks; operator steps for Paul. G1-G10 record where the spec could not be built as written; G3, G4, G6, G10 await Paul before Task 6. Reviewed by Claude Fable 5.2 (claude-fable-5-2) under AGENTS.md stopping rules: round 1 (d18a916) CHANGES REQUIRED, 1 P1 (no From for an owned environment created after the flip) + 8 P2; round 2 (130f03f) APPROVE, no P1; its two P2s (mail_caller_sends joins mailAppTables and the claim gate; hand-made-route outage as G10 with an operator check) applied in 7f04a37. Census clean on the branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from plan/platform-mail-submission into main.
2 files changed,
+766
−0
docs/superpowers/notes/census-plan-platform-mail-submission.md+137 −0docs/superpowers/plans/2026-11-13-platform-mail-submission.md+629 −0
CI passed — run details
diff --git a/docs/superpowers/notes/census-plan-platform-mail-submission.md b/docs/superpowers/notes/census-plan-platform-mail-submission.md| new file mode 100644 |
| index 000000000..1bc744ae9 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-plan-platform-mail-submission.md |
| @@ -0,0 +1,137 @@ |
| +# Census approval (planned): platform-mail-submission |
| + |
| +**This is a pre-build card.** It is drafted from the plan, `docs/superpowers/plans/2026-11-13-platform-mail-submission.md`, before any code exists. It is laid out like a `census-proposal-*.md` card so each task's reviewer knows what they will verdict. |
| + |
| +At build time `make census-card` is the authority on which units changed. The builder reconciles this draft against it: a unit `census-card` names and this file does not is added, with its claim. A unit drafted here that does not change is dropped. The builder then writes the CLAIMS file from the "what changed" column and runs: |
| + |
| + make census-propose NAME=platform-mail-submission CLAIMS=docs/superpowers/notes/census-claims-platform-mail-submission.tsv |
| + |
| +That writes the real `census-proposal-platform-mail-submission.md`, its overlay and its chain line, with seals. **Each census-touching task (1, 3, 4, 5, 6 and 8) reruns it under the same NAME with the cumulative CLAIMS file**, so every push of the branch is green. |
| + |
| +**Rev 2** (after Fable round 1 on the plan; the base is `origin/main` `8f8207719`, and the build branch must be cut from it or later) makes six changes: |
| +- adds the Task 1 section (round 1 P2-7); |
| +- adds `rt.Provisioned` and the token rule to Task 4's units (P2-2, P2-6); |
| +- replaces Task 5's credentials constructor with `NewS3StoreFromConfig` over `rootaws.LoadStaticConfig` (P2-3); |
| +- adds `CARLOS_DEPLOYMENT_REGION` (P2-3); |
| +- adds the AccessDenied-as-absent read (P2-4); |
| +- drops the `s3:ListBucket` statement from Task 8 (P2-4). |
| + |
| +**Rev 3** (after Fable round 2, APPROVED) changes no unit's scope. The mailer's AccessDenied read becomes a `release.Store` wrapper inside `internal/mailer`, already covered by that package's `new` row. The remaining rev 3 changes are in `internal/console`, which is out of scope. |
| + |
| +Read sites and dispositions below are predictions. The recorded dispositions of existing units are whatever the chain holds at build time. |
| + |
| +Ruling `census-ruling-platform-mail-submission`. The independent reviewer approves or rejects every change below; nothing goes to the census owner (Paul, #280, 2026-10-26). The reviewer is from the other family than the author: Astra for a Claude author. |
| + |
| +**What the reviewer is asked to settle, across all tasks.** No change lets root open, run, query or follow anything it did not before, from a path or input a tenant, an app or a box agent can create, write or name. |
| + |
| +The root-side changes are three: |
| +- bootstrap's `useradd` for `carlos-mailer`; |
| +- two tmpfiles lines; |
| +- one sysusers line. |
| + |
| +All of them are constants. The two directories they create are root-owned. Root never reads the key file: only `carlos-mailer` does. |
| + |
| +Every other change in scope runs as `carlos` (the agent) or as `carlos-mailer` (the mailer). Each is in scope because it is in the root binary's source. |
| + |
| +--- |
| + |
| +## Task 1: pause on the sender record (`mail_cli.go` only) |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `mail_cli.go` (the `carlos email status` printer and its reply type) | body | unchanged | The CLI reads the pause from the reply's new `pause` block (kind, since), and falls back to `provisioned.active` for an older console. Prints a line. API mode only, run by a person, not root. No read of box state | |
| + |
| +Envelopes re-pinned: `.`. |
| + |
| +## Task 3: mailer unit, user, socket, peer rule |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/host/units/carlos-mailer.service` `external` | new | (1) | New unit, run as static user `carlos-mailer`: `ExecStart=/opt/carlos/carlos mailer serve`. `ConditionPathExists=/etc/carlos-mailer/keys`. `EnvironmentFile=-/etc/carlos/host.env`, read by PID 1, with `UnsetEnvironment=CARLOS_SECRETS_KEY`. `AWS_EC2_METADATA_DISABLED=true`. `IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128`. `StateDirectory=carlos-mailer` 0700. The relay's hardening block. No ReadWritePaths on /data, /run/carlos or /etc. Not root; reads nothing root owns except the key file it is the group of | |
| +| `internal/host/units/carlos-mailer.socket` `external` | new | (1) | New socket: `ListenStream=/run/carlos-mailer/mailer.sock`, `SocketUser=carlos`, `SocketGroup=carlos`, `SocketMode=0600`, `Accept=no`, `ConditionPathExists=/etc/carlos-mailer/keys`. systemd (root) binds it in a root-owned directory, as `carlos-instance-control.socket` does in /run/carlos-control. No read added | |
| +| `internal/host/units/carlos-mailer-arm.path` `external` | new | (1) | New path unit: `PathExists=/etc/carlos-mailer/keys` starts `carlos-mailer.socket`. Armed by bootstrap like every `.path`. Root's systemd stats a path in a root-owned 0750 directory that only root and the operator write | |
| +| `internal/host/units/carlos-instance@.service` `external` | body | unchanged (1) | `InaccessiblePaths=` gains `-/run/carlos-mailer -/etc/carlos-mailer` (optional, so a box before tmpfiles ran still starts the unit). Only hides more | |
| +| `internal/host/units/carlos-instance-cmd@.service` `external` | body | unchanged (1) | The same line. Kept equal to the seed template (`TestCmdTemplateEqualsSeedOutsideTheNamedLines`) | |
| +| `internal/host/units/carlos-instance-gen@.service` `external` | body | unchanged (1) | The same line | |
| +| `internal/host/units/carlos-instance-seed@.service` `external` | body | unchanged (1) | The same line | |
| +| `internal/host/units/carlos-instance-sidecar@.service` `external` | body | unchanged (1) | The same line | |
| +| `internal/host/units/carlos-instance-tty@.service` `external` | body | unchanged (1) | The same line | |
| +| `internal/host/units/carlos-instance-probe.service` `external` | body | unchanged (1) | The same line | |
| +| `internal/host/units/carlos-dbread@.service` `external` | body | unchanged (1) | The same line (already `-`-prefixed style) | |
| +| `internal/host/units/carlos-demo-build@.service` `external` | body | unchanged (1) | The same line | |
| +| `internal/host/bootstrap.go` `const tmpfilesConf` | body | unchanged | Two lines: `d /run/carlos-mailer 0750 root carlos -` and `d /etc/carlos-mailer 0750 root carlos-mailer -`. Root creates two root-owned directories. Constant text; no input. No read added | |
| +| `internal/host/bootstrap.go` `privilegedPlan` | body | unchanged | One more argv: `useradd --system --user-group --no-create-home --shell /usr/sbin/nologin carlos-mailer`, behind the same "user exists" guard as `carlos`. Constant argv; no input. No read added | |
| +| `internal/host/bootstrap.go` `bootstrapWithGroup` | body | unchanged | The sysusers snippet gains `u carlos-mailer - "CARLOS mailer" - /usr/sbin/nologin` before the group line. Constant text. No read added | |
| +| `internal/instancectl/peer_linux.go` `EdgeMainPIDPeer` | new | (0) | Exported constructor that returns `productionPeerOK()`. The existing peer code's bodies do not change. Runs in the mailer (uid `carlos-mailer`), not root | |
| +| `internal/status/snapshot.go` `type Metrics` (the private block) | body | unchanged | One additive field, `MailerArmed bool`. Declaration only | |
| +| the snapshot builder that fills `Metrics` | body | +1 stat, +1 dial | The agent (uid `carlos`) stats `/run/carlos-mailer/mailer.sock` and calls `GET /v1/health` on it with a 2 s timeout, to report `MailerArmed`. It never touches `/etc/carlos-mailer`, which it cannot traverse. Agent, not root; the mailer's peer rule admits the agent's main pid | |
| +| `mailer_cli.go` `runMailerServe` | new | (0) | Box verb `carlos mailer serve`. Takes the socket from `LISTEN_FDS` and serves `internal/mailer` with the peer rule. Not root | |
| +| the command registry node for `mailer serve` | body | unchanged | One `clireg` node, box audience | |
| +| `internal/mailer/server.go`, `internal/mailer/peer.go` (every unit) | new | (0) | New package: `Serve` with peer-vetted `Accept`, `/v1/health`. Not root | |
| + |
| +Envelopes re-pinned: `internal/host/units`, `internal/host`, `internal/instancectl`, `internal/status`, `.`. New envelope: `internal/mailer`. |
| + |
| +## Task 4: the verb at both bind sites, `CARLOS_MAIL` agent-owned |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/activator/backend_exec.go` `type ExecBackend` | body | unchanged | Two fields: `Mail mailsubmit.Forwarder` and `MailSwitch func(acct, app string) bool`. Declaration only | |
| +| `internal/activator/backend_exec.go` `var agentOwnedNames` | body | unchanged | Gains `"CARLOS_MAIL"` | |
| +| `internal/activator/backend_exec.go` `ExecBackend.agentOwnedVars` | body | +whole:Route | Sets `CARLOS_MAIL=submit` when `haveControl`, `rt.Provisioned`, `Mail != nil` and `MailSwitch(account, app)`; an unprovisioned route of a switched app is logged once and never told to submit. Strips it otherwise, including a tenant-supplied value from fileEnv. Reads `rt.App` and `RouteAccount(rt)`; the switch comes from the agent's cache of the console-written sender record. Only narrows what a tenant can set | |
| +| `internal/activator/backend_exec.go` `seedVars` | body | unchanged | Also strips `CARLOS_MAIL` | |
| +| `internal/activator/backend_exec.go` `ExecBackend.spawnChildFrom` | body | unchanged | The inline mount becomes `b.controlMount(rt, tokenReader, n)` | |
| +| `internal/activator/backend_exec.go` `ExecBackend.controlMount` | new | +whole:Route | One mount composer for both bind sites. Timers and updates as today; `mailsubmit.Mount` under its own condition, `Mail != nil` | |
| +| `internal/activator/prepare.go` `ExecBackend.listenControl` | body | unchanged | Calls `controlMount`, the same as the flat site | |
| +| `internal/moves/envreport.go` `var AgentOwnedVars` | body | unchanged | Gains `"CARLOS_MAIL"`. Paired with `agentOwnedNames` by test | |
| +| `internal/mailsubmit/*` (every unit) | new | (0) | New package. `Mount` (`POST /v1/mail`: bearer by the existing verbs' rule, where an empty or unreadable token refuses everything and the compare is constant-time over SHA-256; size and shape checks; stamps account, app and host from the route, never the body) and `SocketForwarder` (HTTP over `/run/carlos-mailer/mailer.sock`). Agent process | |
| +| `internal/mailwire/*` (every unit) | new | (0) | New package, first in the root binary here. Pure wire types and helpers: `Pause`, `Submission`, `SenderView`, key functions, tag names, `IsMailerCaller`, the tier default cap. No I/O | |
| +| `internal/host/mailswitch.go` (every unit) | new | +1 bucket read | The agent's switch cache. A bounded `Get` of `apps/<acct>/<app>/email/senders/app.json` (console-written), decoded as `mailwire.SenderView`. Agent, not root | |
| +| `internal/host/agent.go` `runAgent` | body | unchanged | Wires `eb.Mail`, `eb.MailSwitch` and the cache's refresh on the serial bump. Agent, not root | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/moves`, `internal/host`. New envelopes: `internal/mailsubmit`, `internal/mailwire`. |
| + |
| +## Task 5: the mailer's send |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/mailer/{send,policy,hygiene,rate,counter,keys,routes,ses}.go` (every unit) | new | (n) | The mailer (uid `carlos-mailer`) reads its key file, its own state directory and, through its own IAM user, bucket objects by key (sender records, domain records, instance records), with a denied read taken as absent. Absent always refuses. It calls SES `SendEmail`. Every AWS config comes from `rootaws.LoadStaticConfig` with an explicit region (`CARLOS_MAIL_REGION`, `CARLOS_DEPLOYMENT_REGION`); IMDS and shared config are off. Not root | |
| +| `internal/release/store.go` `NewS3StoreFromConfig` | new | (0) | Constructor: an `S3Store` over a caller-built `aws.Config`, with the same client options as `newS3Store`. No read in itself | |
| +| `internal/release/store.go` `newS3Store` | body | unchanged | Its client options (s3compat, checksums) move into one unexported helper that both constructors call. Behaviour unchanged | |
| +| `internal/provision/reconcile.go` `BoxServesRecord` (and `type BoxScope`) | new | +whole:Record | Exported wrapper over the unchanged `inScope`, `ownsRecord` and `everywhereClass`, so the mailer's "on this box" is the reconciler's. Called only by the mailer | |
| +| `internal/hostenv/hostenv.go` `var Optional` | body | unchanged | Gains `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION`, which select no box authority (AWS regions for the mailer's clients) | |
| +| `mailer_cli.go` `runMailerServe` | body | unchanged | Wires the pipeline; reads host env names listed in the plan | |
| + |
| +Envelopes re-pinned: `internal/mailer`, `internal/release`, `internal/provision`, `internal/hostenv`, `.`. |
| + |
| +## Task 6: switch-side changes in scope |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/release/release.go` `type Manifest` | body | unchanged | Additive `Mail string` (`json:"mail,omitempty"`), as `Label` is | |
| +| `internal/release/release.go` (the manifest validation that calls `caps.ValidCapabilities`) | body | +whole:Manifest | Refuses a `mail` other than `""` and `"submit"`, on ship and on every read. Only refuses more | |
| +| `cli.go` `runShip` | body | unchanged | `--mail` flag, sent and echo-checked | |
| +| the activator spawn paths (`spawnChildFrom`, `spawnUnitFrom`, the rootfs spawn) | body | +staged manifest | With the switch on and the staged manifest's `Mail != "submit"`, log at error level and emit an instance event once per (host, version). Never refuses. Agent | |
| +| the host adopt pass (where it adopts a channel head) | body | +staged manifest | The same log and event when it adopts an undeclared head for a switched app. **Root** reads a field of a manifest it already reads and logs. No new path, no new authority, no refusal (G7) | |
| +| `mail_cli.go` `runEmailSubmission` and the status printer; the registry node | new and body | (0) | CLI only; API mode | |
| + |
| +Envelopes re-pinned: `internal/release`, `internal/activator`, `internal/host`, `.`. |
| + |
| +## Task 8: infra |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `infra/modules/region-host/mailer.tf` `external` | new | (1) | `aws_iam_user.mailer`, `carlos-mailer-<region>` at path `/carlos-mailer/`, and `aws_iam_user_policy.mailer` with two statements: `ses:SendRawEmail` on `identity/*` and `configuration-set/carlos-*` in the mail region; `s3:GetObject` on `apps/*/*/email/senders/*`, `apps/*/*/instances/*` and `accounts/*/email/domains/*`. No `s3:ListBucket`, no write. No access key resource (the key is never in state). The host role gains nothing. Nothing a box's root reads. References no sibling script, so `checkRootExecInputs` needs nothing | |
| +| `infra/modules/region-host/variables.tf` `external` | body | unchanged (1) | `variable "mailer"`, an object `{ses_region, ses_account_id, deployment_bucket_region}` defaulting to null, which means no resources | |
| +| `infra/modules/region-host/outputs.tf` `external` | body | unchanged (1) | `output "mailer_user_name"` | |
| +| the module's host.env parameter assembly (group boxes) `external` | body | unchanged (1) | Sets `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION` from `var.mailer`. A value root writes into host.env from operator input, as every other parameter is | |
| +| `infra/modules/region-host/tests/mailer.tftest.hcl` `external` | new | (1) | Plan-only runs under `mock_provider`: off by default, the exact policy, no access key, no SES on the host role, and the group host.env key. Test-only | |
| + |
| +Envelopes re-pinned: `infra/modules/region-host`. |
| + |
| +--- |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, it compares the change with the unit's recorded disposition and basis. For an envelope, it reads every changed function in the package and what it reaches. It rejects if: |
| +- the change lets root open, run, query or follow anything it did not before, from a path or input a tenant, an app or a box agent can create, write or name; |
| +- the change weakens a check, refusal, validation, argument or environment the basis relies on; |
| +- the diff cannot settle either of these. |
| +Otherwise it approves. Each verdict is recorded on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
diff --git a/docs/superpowers/plans/2026-11-13-platform-mail-submission.md b/docs/superpowers/plans/2026-11-13-platform-mail-submission.md| new file mode 100644 |
| index 000000000..c6a5de03d |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-13-platform-mail-submission.md |
| @@ -0,0 +1,629 @@ |
| +# Platform mail submission Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** An instance of a switched app sends mail by `POST /v1/mail` on its own control socket. The agent stamps the route and forwards the message to a box-local mailer. The mailer accepts only the agent's main process, refuses routes not on its box, applies the sender's From, pause, cap and rate before the send, and sends through SES with one dedicated IAM user per region. No instance of a switched app holds a sending credential. |
| + |
| +**Architecture:** Nine tasks. Tasks 1 and 2 are console and `internal/mail` work: pause moves onto the sender record, and SES `EmailTags` are believed only from the mailer's principal. Task 3 adds the mailer unit, its user, its socket and the peer rule. Task 4 adds the verb at both control-socket bind sites, with `CARLOS_MAIL` agent-owned. Task 5 is the mailer's send pipeline. Task 6 is the per-app switch and its door. Task 7 is rastrillo's `submit` transport, in its own repo. Task 8 is infra: the IAM user, its policy and the runbook. Task 9 migrates the Oficina apps and switches them on. |
| + |
| +**Tech Stack:** Go 1.26 (net/http over unix sockets, `golang.org/x/sys/unix` SO_PEERCRED, `aws-sdk-go-v2/service/sesv2`), systemd units (socket activation, a `.path` arm, sysusers and tmpfiles), OpenTofu modules with `tofu test` mocks. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-12-platform-mail-submission-design.md`, revision 5 plus §9.0 (APPROVED, Fable 5.2 round 3, no P1; Paul's rulings of 2026-11-12; SES spike results 2026-11-13). Every task reads the sections it names. Builds on `2026-09-15-tenant-email-senders-design.md` and `implementation/team-scoped-credentials.md` §3a. |
| + |
| +**Spec review history (carried, stopping rule 1):** round 1, 3 P1s (uid family ×2, attribution ×1); round 2, 1 P1 (attribution) and 6 P2s (uid ×2), so rule 2 applied to both families; round 3, no P1, review stopped. A fourth round on the design needs Paul's go. **This plan does not reopen the design.** The places where the spec cannot be built as written are listed in "Spec gaps" below, each with a recommended answer for Paul. None is fixed silently. |
| + |
| +**Plan review history (stopping rules apply):** |
| +- **Round 1:** Fable 5.2 reviewed rev 1 at `d18a916` and returned CHANGES REQUIRED: 1 P1, 8 P2, 6 P3. |
| + - P1-1 was in a new family, "a switched app's bundles lack `<P>_MAIL_FROM`". |
| + - P2-1 was in the attribution family. That is the family's third round counting the design's two, so this plan applies the fix the reviewer named and does not write a fix of its own (rule 2's third option: one place, a guard test). |
| +- **Rev 2** (this revision) applies all nine fixes and the P3s that were cheap to fold in, and lists the rest under "P3 follow-ups". The table at the end maps each finding to its change. |
| +- **Round 2:** Fable 5.2 reviewed rev 2 at `130f03f` and returned **APPROVED, no P1**, so the review stops here (rule 1). **Rev 3** (this revision) applies its two P2s and three P3s without reopening. |
| + - P2-B is the second round in the family **"one working channel"**: a switched app's route must have a channel that works, or it fails loudly without taking the site down. P1-1 was the first. A third finding in that family goes to Paul as a choice (rule 2); G10 already puts it to him. |
| +- A round 3 needs Paul's go. |
| +- The plan was rebased onto `origin/main` `8f8207719` (#962, `internal/edge` only, touching nothing this plan changes). **The build branch must be cut from `8f8207719` or a later tip**, so the census chain it proposes against is current. |
| + |
| +--- |
| + |
| +## Spec gaps (flagged for Paul before the tasks they gate) |
| + |
| +Each gap names the task it blocks, the spec text, what the code shows, and a recommendation. The tasks below are written to the recommendation and say so where they rely on it. If Paul rules otherwise, only the named task changes. |
| + |
| +| # | Blocks | Spec says | What the code shows | Recommendation | |
| +|---|---|---|---|---| |
| +| G1 | Task 1 | Decision 8 and test 8.13: "a cap pause lifts at the day roll; rate, **plan** and manual pauses do not" | `resumeStaleCapPause` (`internal/console/mailcounts.go:176-206`) lifts **cap and plan** pauses at the day roll, and `PauseKindPlan`'s own comment (`internal/mail/mail.go:84-86`) says it lifts like a cap pause. Decision 8 also says "keeping today's pause kinds" | Keep today's behaviour (cap **and plan** lift at the roll). Read test 8.13 as "rate, manual and per-instance do not". Changing plan pauses would be a billing change this design never argued for | |
| +| G2 | Tasks 6, 7 | §4 "The retry queue stays in the app (rastrillo's existing mail queues)" | rastrillo has **no** mail queue. `mail.Sender.Send` is synchronous (`rastrillo/mail/mail.go:39,153`), and a grep for retry, backoff, outbox and queue in `mail/`, `auth/` and `jobs/` finds nothing | rastrillo's transport retries `503` a bounded number of times inside the caller's deadline and returns `429` as a typed error carrying `Retry-After`, never retrying it hot. Any queue is the app's own. Test 8.10 is met by the typed error plus the bounded retry | |
| +| G3 | Tasks 6, 7 | Decision 10: "When on, no `<P>_SMTP_*` is delivered anywhere"; test 8.1 | The five delivered variables include `<P>_SMTP_FROM` (`EnvNames`, `walk_environment.go:178`). With all five gone, a switched app has **no From address** to put in `from` and `From:` | Deliver one non-secret variable, `<P>_MAIL_FROM` (the sender's `Declared.From`), in place of the five. It goes into the default bundle and every owned environment's bundle: those that exist at the flip, **and every one created while the switch is on** (`mintOwnedEnvironmentMail` delivers it and mints nothing, round 1 P1-1). Releasing an environment removes it. Test 8.1 still holds: no `<P>_SMTP_*` and no AWS key | |
| +| G4 | Task 6 | Decision 10: "**Before §7.4's reap, `carlos email test --submit`** sends through the submit path per route, as proof" | Only the agent can reach an instance's control socket (round 3's own P3). The console has no path to make a route send | Gate the §7.4 reap on **event evidence** instead. The evidence is a per-app, per-day count of Send events **by caller class**, which Task 2 records (`mail_caller_sends`, round 1 P2-1): `mail_events` has no caller column, and every class resolves to sender `app`. The reap needs all three of these:<br>• at least 7 days since the switch;<br>• at least one `mailer` Send for the app;<br>• no `app_user` Send (`carlos-mail-<acct>-<app>`) in the last 7 days.<br>**What this proves:** the app-level SMTP key stopped being used. It does **not** prove that submit works on every route. A route that never sends proves nothing either way, and a route that cannot submit shows up as its app's own failures and the mailer's refusals, not here. `--submit` is left out of this plan | |
| +| G5 | Task 8 | §5: the IAM policy is "conditioned on `ses:FromAddress` matching the platform's verified identities, or on `ses:TenantName`" | One fleet-wide user cannot carry a static `ses:FromAddress` list: identities are created at runtime by the console, per account. Terraform cannot enumerate them | `ses:SendRawEmail` on `arn:aws:ses:<mail_region>:<acct>:identity/*` and `configuration-set/carlos-*` only, with no From condition. The mailer's From check is the gate (as §5 already says); IAM bounds the account, region and resource types. Add the `ses:TenantName` `StringLike carlos-*` condition only once §9 item 3's backfill has landed (it would refuse every untenanted send). Round 3's P3 list already names this | |
| +| G6 | Task 8, Task 9 | §5: key "armed by the operator by hand", and never through `user_data`, SSM or the bucket | Group-mode boxes are launched unattended by their Auto Scaling group (`group-init.sh.tftpl:312-338`). A new or replaced group box has **no key**, so its mailer never starts and every switched instance on it answers `503 MAILER_UNAVAILABLE` until someone arms it. Every automatic delivery path the spec rules out is one uid `carlos` can read | Ask Paul. Options: (a) switched apps run on fixed boxes only, refused by the door; (b) the box reports "mailer armed" in its status record, the door and an alert read it, and the operator arms each new box (a runbook step per scale event); (c) a separate design for unattended key delivery. This plan builds (b)'s report and alert (Task 3 step 6, Task 6 precondition) because it helps under every option | |
| +| G7 | Task 6 | Decision 10: "**Adopting**, rolling back to, or pinning a build whose manifest lacks the declaration is refused" | Every person-facing change of what a route serves goes through a console door. A box's `carlos adopt` (root) also adopts channel heads that a direct-bucket promote (pinfra scripts) moved, without the console | Refuse at every console door that changes what a route serves (one shared check, and a guard test over the route table). At the box, log loudly and raise an event on adopt and on wake, as decision 10 already does for wake. A box-side adopt **refusal** would be new root authority, and the plan does not add it unless Paul asks | |
| +| G8 | Task 6 | §5 Tenants: "The switch refuses an app whose sender would send with an unassociated tenant" | Nothing records whether an identity or configuration set is associated with its tenant (`DomainRecord`, `internal/mail/domain.go:59-66`). Senders spec §4.2.1's backfill is §9 item 3, still open | The door asks SES live (`ListTenantResources`) through the console's provisioner, only when the app sender has a `TenantARN`. The control-plane role may need `ses:ListTenantResources`. That policy is not in this repo (senders spec §4.2 item 2). A sender with no `TenantARN` sends without `TenantName` and needs no association | |
| +| G10 | Task 4, Task 9, operator step 8 | Decision 11: rastrillo "fails loudly at boot when a switched app has neither channel" | With `CARLOS_MAIL` set only for `rt.Provisioned` (round 1 P2-2), a **hand-made route** (a registry row with no instance record) of a switched app has neither channel. Its bundle lost the SMTP variables, so rastrillo refuses at boot: **a mail gap becomes a site outage for that route**. Nothing in the door can see such a route, because the box report keys `RouteVersions` by host, not by app (round 2 P2-B; family "one working channel", second round) | **Paul's choice.** The plan as written takes (a), and the copy and the operator check say so.<br>(a) Accept it, with an operator check before switch-on that every route of the app has an instance record (operator step 8), and the outage named in the `email submission on` copy.<br>(b) Add the app to the box report (a host-to-app map) so the door can refuse.<br>(c) Let rastrillo fall back to logged mail rather than refuse at boot, which reverses decision 11's loud failure | |
| +| G9 | Task 5 | §5 Rate: "a per-sender token bucket" | No rate or burst is given | 2 messages a second, a burst of 20, per sender per box, as package constants. Paul to confirm against the deployment's SES send rate | |
| + |
| +Plan choices that are not gaps, for the plan reviewer (each resolves an item on round 3's P3 list or an unstated detail): |
| + |
| +- **Where the agent reads the switch** (P3): from the app sender record (`apps/<acct>/<app>/email/senders/app.json`, new `submission` block), cached in the agent and refreshed on every serial bump. The console's switch door bumps the serial. One source of truth for the console, the agent and the mailer. |
| +- **Cap unit** (P3): messages, not recipients, matching the console, which counts Send events (one per message). |
| +- **Caller match** (P3): `ses:caller-identity` is the bare user name (§9.0). The mailer's IAM user lives under path `/carlos-mailer/`, outside the console's `/carlos-mail/` (`UserPath`, `policy.go:25`), so `SweepUserBoundaries` and every console reap can never reach it. |
| +- **Three answers beyond §4's list**, all from the mailer through the agent: `403 {"code":"ROUTE_NOT_ON_BOX"}` (decision 4), `403 {"code":"SUBMISSION_OFF"}` (the app sender's switch is off: the mailer sends only for switched apps, which narrows §6's residual to switched apps), and `400 {"code":"REJECTED"}` (SES `MessageRejected`). |
| +- **The mailer's box facts** (region, pools, fleet label, bucket, S3 endpoint) come from `/etc/carlos/host.env` through systemd's `EnvironmentFile=`. PID 1 reads it as root, so the mailer user needs no read access. The unit sets `UnsetEnvironment=CARLOS_SECRETS_KEY`. The AWS regions come from two new optional host.env keys (round 1 P2-3): `CARLOS_MAIL_REGION` (SES; the same name and meaning as the console's) and `CARLOS_DEPLOYMENT_REGION` (the deployment bucket). `CARLOS_REGION` is a placement label and is used only for "on this box". |
| +- **The mailer is a verb of the one `carlos` binary** (`carlos mailer serve`), as `carlos relay serve` is. Its code imports a new small wire package, `internal/mailwire`, and never `internal/mail`. That keeps `internal/mail` (and its IAM and SES walks) out of the root binary and out of census scope (`go list -deps .` today has no `internal/mail`). |
| + |
| +--- |
| + |
| +## Global Constraints |
| + |
| +- Platform branch `feat/platform-mail-submission` from `origin/main`. One commit per task, with each task's review fixes as further commits. Subjects under 80 characters, body after a blank line, ending `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. It lands once, through `amadan branch merge -squash`, after CI is green and the whole-branch review approves. rastrillo work goes on its own branch in `amadan.net/rastrillo/rastrillo` (Task 7). Each Oficina app gets its own branch (Task 9). |
| +- **One session owns this plan** (stopping rule 7). The finish line is the platform branch merged and rolled, the rastrillo branch merged, and the first Oficina app switched on. Status goes on the branch's discussion every 24 hours without a merge (rule 8). |
| +- **Stopping rule 6 (something Paul can see lands first):** the platform branch's merge is observable on its own. `carlos email status` gains a Submission line, and `carlos email submission on --app <a>` answers with its preconditions, naming the routes whose builds do not declare the transport. Paul can run both the day it rolls. Measurement and scaffolding ride in the same merge. |
| +- **Stopping rule 5:** switch-on is the first Alta production team run (Paul, 2026-11-12, "Happy to block"). Until an app is switched, everything is inert: no unit starts without a key, no `CARLOS_MAIL` is set, and no tag is believed from a principal that has never sent. |
| +- Exact values (spec §4, §5, §9.0): |
| + - verb `POST /v1/mail`, bearer `CARLOS_ADMIN_TOKEN`; envelope `{"from","to":[..],"raw"}`; `raw` base64, decoded at most `10 << 20` bytes; at most 50 recipients; the request body capped at `14 << 20` bytes; |
| + - socket `/run/carlos-mailer/mailer.sock`; socket directory `d /run/carlos-mailer 0750 root carlos -`; |
| + - key directory `d /etc/carlos-mailer 0750 root carlos-mailer -`; key file `/etc/carlos-mailer/keys`, `0640 root:carlos-mailer`, operator-armed; |
| + - static user `carlos-mailer`; IAM user `carlos-mailer-<region>` under path `/carlos-mailer/`; |
| + - `IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128`; |
| + - SES tags `account`, `app`, `sender`; IAM action `ses:SendRawEmail` only (§9.0); the API call is SES v2 `SendEmail` with `Content.Raw`. |
| +- **Wire-shape changes are additive** (AGENTS.md). The new sender fields (`pause`, `submission`) and the manifest field (`mail`) are `omitempty` pointers or strings. A record or manifest written before them must parse, and must mean what it meant. |
| +- **When a storage shape changes, the consumer list is everything that parses it** (AGENTS.md). For the sender record that is, today: `internal/mail/{walk.go,walk_environment.go,mail.go}`, `internal/console/{apimail.go,appsettings.go,mailcounts.go,planmail.go,sesevents.go,teamcreds.go}`, `internal/console/templates/app_settings.html` and `mail_cli.go`. After this plan, it also includes `internal/mailwire`, `internal/mailer` and the agent's switch cache (`internal/host/mailswitch.go`). |
| +- A new `carlos` command or subcommand needs its `docs/site/cli.md` heading and its `parity/parity.tsv` row in the same branch. Run `make parity-doc` and `go test . -run 'TestCLIProjection|TestParity'` after. |
| +- Census (AGENTS.md "The census"): overlay name `platform-mail-submission`, claims drafted in `docs/superpowers/notes/census-plan-platform-mail-submission.md`. Tasks **1** (`mail_cli.go`, package `.`), 3, 4, 5, 6 and 8 change in-scope files. Each of them ends with `make census-card` and `make census-propose NAME=platform-mail-submission CLAIMS=<cumulative file>`, rerun under the same NAME, so every push of the branch is green (round 1 P3). |
| +- Local tests are targeted (`go test ./internal/<pkg>/ -run <Name>`). CI runs the full gate. Use the sandbox settings in AGENTS.md "Build & test". |
| +- **No production change from this branch.** No AWS write, no `tofu apply`, no `carlos` command that changes state. The operator steps at the end are Paul's, with scoped approval (AGENTS.md "Production infrastructure needs scoped approval"). |
| +- UI and copy: Task 6 has a UX pass, then a copy review, before its CLI output and refusals are built (AGENTS.md "Every UI change gets a UX pass"). |
| + |
| +## Review Focus |
| + |
| +1. **A flat child, or a nested instance, dialling the mailer socket.** Refused at accept, before a byte is read: not uid `carlos`, or not `carlos-edge.service`'s MainPID. Pinned in Task 3 (`TestMailerPeerRefusesNonAgentPid`, `TestMailerPeerRefusesOtherUid`). |
| +2. **A message whose body names another host.** It is stamped with the socket's route, never the body's. Pinned in Task 4 (`TestMailVerbStampsSocketRoute`). |
| +3. **A forged `account`/`app`/`sender` tag from an SMTP-credentialed app.** It is counted against the caller, never the tag. Pinned in Task 2 (`TestTagsBelievedOnlyFromMailer`, the guard test 8.11). |
| +4. **A sender paused, capped, or sending from a domain it was not granted.** Refused with no SES call. Pinned in Task 5 (`TestMailerPolicyRefusesBeforeSES`). |
| +5. **`Bcc:` and `X-SES-*` in `raw`, including folded and mixed-case forms.** Never reach SES. Pinned in Task 5 (`TestHygieneStripsHeaders`). |
| +6. **A build without the declaration reaching a switched app.** Refused at every console door that changes what a route serves, naming "switch submission off first". Never refused at wake. Pinned in Task 6 (`TestSubmissionGateCoversEveryServeDoor`, `TestWakeNeverRefusedForUndeclaredBuild`). |
| +7. **A new unit line that fails every instance start fleet-wide.** Every added `InaccessiblePaths` entry is `-`-prefixed, and the set of units carrying it equals the set carrying `/run/carlos-control`. Pinned in Task 3 (`TestMailerPathsHiddenFromEveryTenantTemplate`). |
| +8. **A team environment created after the switch** gets `<P>_MAIL_FROM` and no credential, and loses it on release (round 1 P1-1). Pinned in Task 6 (`TestMintOwnedEnvironmentWhileSwitched`, gate 8.1's third case). |
| + |
| +--- |
| + |
| +## Task overview |
| + |
| +| Task | Title | Review under stopping rule 3 | Why | Implementer | Reviewer | |
| +|---|---|---|---|---|---| |
| +| 1 | Pause on the sender record | **Own review** + census | Production storage (sender record shape in production buckets); the abuse brake. Census: `mail_cli.go` is in package `.` (`census-base-scope.txt:1493`) | Opus | Astra | |
| +| 2 | `EmailTags` attribution, decision 6's guard, caller-class counts | **Own review** | Security gate in the attribution family (rule 2 applied twice at design time); billing (counts feed caps and plan limits) | **Opus** (round 1 P2-8) | Astra | |
| +| 3 | Mailer unit, user, socket and peer rule | **Own review** + census | Security gate (peer rule); root (bootstrap's `privilegedPlan`, tmpfiles, sysusers); fleet-wide unit lines | Opus | Astra (census and security) | |
| +| 4 | The verb at both bind sites, `CARLOS_MAIL` agent-owned | **Own review** + census | Security gate (route stamp, agent-owned variable) | Opus | Astra (census and security) | |
| +| 5 | The mailer's SES send, hygiene, rate and cap | **Own review** + census | Security gate (From, pause, cap, box-local routes); production (SES) | Opus | Astra (census and security) | |
| +| 6 | Per-app switch, its door, preconditions, reap, switch-off | **Own review** + census | Security gate (switch preconditions); production storage (bundle writes, IAM user deletes); redirect-class door changes (deploy refusals) | Opus | Astra | |
| +| 7 | rastrillo `submit` transport (cross-repo) | Branch review only | No platform gate; library transport | Sonnet | Opus (rastrillo branch review) | |
| +| 8 | Infra: IAM user and policy, runbook | **Own review** + census | Security gate (IAM policy) | Opus | Astra (census and IAM) | |
| +| 9 | Migration and switch-on for the Oficina apps | Per-app branch review only | Ordinary app changes; switch-on is Paul's operator step | Sonnet (per app) | Opus (per app) | |
| +| — | Whole-branch final review (platform) | — | Fleet-wide blast radius; several interacting invariants | — | **Fable** | |
| + |
| +**Census** reviews are by a model from the other family than the author (Astra for a Claude author). Verdicts are recorded on #280 with the tip. Per-task security reviews also go to Astra, with briefs from the template. The whole-branch review goes to Fable, because the uid and attribution families both crossed rule 2 at design time, and only a whole-branch read can see them meet. |
| + |
| +### Dependencies |
| + |
| +``` |
| +T1 ──► T4 (mailwire types) T1 ──► T5 (pause read) T1 ──► T6 (pause without Provisioned) |
| +T2 ──► T5 goes live (no mailer send may reach a console that cannot attribute it) |
| +T3 ──► T4 (socket path, client) T3 ──► T5 (server skeleton) T3 ──► T8 (unit, user and key path) |
| +T4 ──► T5 (agent-to-mailer protocol) T4 ──► T6 (CARLOS_MAIL) T4 ──► T7 (verb contract) |
| +T5 ──► T6 (status reads the mailer's codes) T5 ──► T8 (IAM actions and S3 keys) |
| +T6, T7, T8 ──► T9 |
| +``` |
| + |
| +Tasks 1 and 2 can start at once and run in parallel. Task 7 can start once Task 4's interface is fixed. It tests against a fake socket and does not wait for the platform merge. |
| + |
| +--- |
| + |
| +### Task 1: Pause on the sender record, keeping the pause kinds |
| + |
| +**Spec:** decision 8; test 8.13; gap G1. |
| + |
| +**Files:** |
| +- Create: `internal/mailwire/mailwire.go`, `internal/mailwire/mailwire_test.go` |
| +- Modify: `internal/mail/mail.go` (`Provisioned` doc, pause kinds `:65-88`), `internal/mail/sender.go` (`type Sender` `:62-100`), `internal/mail/walk.go` (`claimUnserializedSetSenderPaused` `:1203-1263`, `claimUnserializedSetPaused` `:1170`), `internal/mail/walk_environment.go` (`:96-100`, the fresh-mint pause state) |
| +- Modify: `internal/console/mailcounts.go` (`resumeStaleCapPause` `:176-216`, `enforceMailLimits` `:235-330`), `internal/console/planmail.go` (`enforceAccountMail` `:35-95`, `resumePlanMail` `:97`), `internal/console/apimail.go` (status reply), `internal/console/appsettings.go`, `internal/console/templates/app_settings.html`, `mail_cli.go` (status printing) |
| +- Test: `internal/mail/pauseif_test.go`, `internal/mail/sender_test.go`, `internal/console/mailcounts_test.go` (or the existing file holding `resumeStaleCapPause` tests) |
| + |
| +**Interfaces:** |
| +- Produces, in `internal/mailwire` (pure: no AWS, no store writes, no import of `internal/mail`): |
| + - `type Pause struct { Kind string `json:"kind,omitempty"`; At time.Time `json:"at"` }`. `Kind` is one of `""` (manual), `"cap"`, `"rate"`, `"plan"` or `"per-instance"`. |
| + - `const PauseKindCap = "cap"`, `PauseKindRate = "rate"`, `PauseKindPlan = "plan"`, `PauseKindPerInstance = "per-instance"`. `internal/mail`'s existing constants become `= mailwire.PauseKind…`, so there is one definition. |
| + - `func (p *Pause) LiftsAtDayRoll() bool`: true for `cap` and `plan` only (G1). |
| + - `type Submission struct { On bool `json:"on"`; At time.Time `json:"at"`; By string `json:"by,omitempty"`; AppUserReapedAt *time.Time `json:"app_user_reaped_at,omitempty"` }`. It is defined here so Task 4 can read it. Nothing writes it until Task 6. |
| + - `type SenderView struct` with only the fields the mailer and agent read: `ID`, `Declared *struct{ From string }`, `Grant *struct{ Domains []string; DailyCap int }`, `Provisioned *struct{ Active bool; PauseKind string; At time.Time }`, `Pause *Pause`, `Submission *Submission`, `TenantARN string`, `PerInstance bool`, all with `internal/mail`'s JSON names. |
| + - `func (v *SenderView) EffectivePause() *Pause`: `v.Pause` if set; else, when `v.Provisioned != nil && !v.Provisioned.Active`, `&Pause{Kind: v.Provisioned.PauseKind, At: v.Provisioned.At}` (the legacy read); else nil. |
| + - `func SenderKey(acct, app, id string) string` and `func DomainKey(acct, domain string) string`, the same strings as `internal/mail`'s (a test pins them equal). |
| +- Changes in `internal/mail`: |
| + - `Sender` gains `Pause *mailwire.Pause `json:"pause,omitempty"`` and `Submission *mailwire.Submission `json:"submission,omitempty"``. |
| + - `func EffectivePause(sn *Sender) *mailwire.Pause` follows the same rule as `SenderView.EffectivePause`. |
| + - `claimUnserializedSetSenderPaused` writes `sn.Pause` (nil on resume, `{Kind: kind, At: now}` on pause). While `sn.Provisioned != nil`, it **also** does everything it does today: key activation, standalones, owned environments' keys and `Active`/`PauseKind`/`At`. That is decision 8's overlap week. The `ErrNotProvisioned` refusal stays for a sender with neither `Provisioned` nor `Submission.On`. Task 6 relies on the second half. |
| + - The `eligible` callbacks and every reader (`resumeStaleCapPause`, `stillStale`, `enforceMailLimits`, `enforceAccountMail`, `resumePlanMail`, the status reply, the settings page, `mail_cli.go`) read `EffectivePause`, never `Provisioned.Active` directly. `enforceMailLimits`' early return on `sn.Provisioned == nil` becomes a return on "nothing can send" (`Provisioned == nil` and not switched). |
| + |
| +- [ ] **Step 1: Write the failing tests.** |
| + - `TestEffectivePauseLegacyRecord`: a record with `provisioned.active=false, pause_kind="rate"` and no `pause` reads as `Pause{Kind:"rate"}`; with `active=true`, nil. |
| + - `TestSetSenderPausedWritesBoth` (fake provisioner): pause with kind `cap` sets `Pause`, deactivates every key (app, previous, standalones, owned environments) and sets `Provisioned.Active=false, PauseKind="cap"`; resume clears both. |
| + - `TestPauseKindsSurvive` (test 8.13 as G1 reads it): a cap pause and a plan pause from yesterday lift on today's `enforceMailLimits`; a rate pause, a manual pause and a per-instance pause from yesterday do not. |
| + - `TestSenderViewDecodesMailSender`: marshal a fully populated `mail.Sender` and decode it as `mailwire.SenderView`. Every field the view names equals the source (the consumer pin). |
| + - `TestMailwireKeysMatchMail`: `mailwire.SenderKey` and `DomainKey` equal `internal/mail`'s for a table of inputs. |
| + - `TestAdditiveSenderShape`: a pre-change golden sender JSON round-trips through the new `Sender` with no field lost; a sender with `pause` decodes in an old-shape struct (simulated by a copy of the old type) without error. |
| +- [ ] **Step 2: Run** `go test ./internal/mailwire/ ./internal/mail/ -run 'TestEffectivePause|TestSetSenderPausedWritesBoth|TestSenderView|TestMailwireKeys|TestAdditiveSenderShape' && go test ./internal/console/ -run TestPauseKindsSurvive`. Expected: build failure. |
| +- [ ] **Step 3: Implement** to the interfaces. Change every consumer in the list above in the same commit. |
| +- [ ] **Step 4: Run** the same commands, then `go test ./internal/mail/ ./internal/console/ -run 'Pause|Resume|Limit|PlanMail|EmailStatus'`. Expected: PASS. |
| +- [ ] **Step 5: Census** (round 1 P2-7). `mail_cli.go` is in package `.`, which is in the root binary's scope (`internal/provision/testdata/census-base-scope.txt:1493`). Its status printer's change is a census unit. Run `make census-card`, write its claim (the Task 1 section of the census note), and run `make census-propose NAME=platform-mail-submission CLAIMS=<file>`, so this push is green. Every later census-touching task reruns it under the same NAME. |
| +- [ ] **Step 6: Commit** `mail: pause on the sender record, kinds kept`. |
| +- [ ] **Step 7: Review** (own review: production storage, and the census unit). Astra, with the consumer list and the additive-shape rule in the brief. |
| + |
| +### Task 2: `EmailTags` attribution, with decision 6's guard in `SenderOfCaller` |
| + |
| +**Spec:** decision 6; §9.0 (tags arrive on Send, Delivery, Bounce and Complaint; the caller is the bare user name; `X-SES-MESSAGE-TAGS` is honoured without the parameter); test 8.11. |
| + |
| +**Files:** |
| +- Modify: `internal/mail/events.go` (`type Event` `:25-68`, `ParseEvent` `:149-245`) |
| +- Modify: `internal/mail/sender.go` (`SenderOfCaller` `:450-473`) |
| +- Modify: `internal/mailwire/mailwire.go` (tag names, the mailer caller rule) |
| +- Modify: `internal/console/sesevents.go` (`recordAndEnforceMail` `:500`) |
| +- Modify: `internal/console/store.go` (the schema list beside `mail_sender_counts` `:301-312`: one new table), `internal/console/mailcounts.go` (two store methods beside `RecordMailEvent` `:109`) |
| +- Modify: `internal/console/mailevents.go`: `mailAppTables` (`:113`) gains `"mail_caller_sends"`, and `mailAppTimeColumn` (`:190-200`) gains `case "mail_caller_sends": return "day"`. Then `carryMailApp` and `forgetMailApp` move and forget its rows with the app on a rename (`store.go:2656`) or an account move (`store.go:2547`), comparing the day string correctly (`mailAppTimeSince` `:208`) (round 2 P2-A). |
| +- Modify: `internal/console/store_gate.go`: the table map gains `"mail_caller_sends": {Sqid: "account", App: "app"}` beside `mail_sender_counts` (`:231-236`), so the gate's purge and claim checks cover it (round 2 P2-A) |
| +- Test: `internal/mail/events_test.go`, `internal/mail/sender_test.go`, `internal/console/sesevents_test.go`, `internal/console/mailcounts_test.go` |
| + |
| +**Interfaces:** |
| +- `internal/mailwire`: |
| + - `const TagAccount = "account"`, `TagApp = "app"`, `TagSender = "sender"`. |
| + - `const MailerUserPath = "/carlos-mailer/"`, `MailerUserPrefix = "carlos-mailer-"`. |
| + - `func MailerUserName(region string) string` returns `"carlos-mailer-" + region`. |
| + - `func IsMailerCaller(caller string) bool`: true for a bare name matching `^carlos-mailer-[a-z0-9-]{1,48}$`, or for an IAM **user** ARN `arn:aws:iam::<12 digits>:user/carlos-mailer/<that name>`. False for every other shape: an assumed-role ARN, a different path, a `carlos-mail-…` name. |
| +- `Event` gains `Tags map[string]string`, holding only the first value of `account`, `app` and `sender` from `mail.tags`, each through `cleanField` with the existing length bound. |
| +- `func SenderOfCaller(ctx context.Context, s release.Store, caller string, tags map[string]string) (acct, app, sender string, ok bool)`. **The guard is the first statement:** |
| + - if `mailwire.IsMailerCaller(caller)`: return the three tags when `release.ValidAccount`, `release.ValidApp` and `ValidSenderID` all hold; otherwise `("", "", "", false)` and log once per caller per minute ("mailer event without valid tags"). |
| + - otherwise: today's body exactly, and `tags` is never read on this path. |
| +- `recordAndEnforceMail` passes `ev.Tags`. A named result is counted once against the named sender, as today. |
| +- **Caller-class counts** (round 1 P2-1; Task 6's reap reads them; the attribution family's fix as the reviewer named it): |
| + - `func CallerClass(acct, app, caller string) string` in `internal/mail` returns: |
| + - `"mailer"` when `mailwire.IsMailerCaller(caller)`; |
| + - `"app_user"` when the caller's bare name (or a user ARN's last segment) equals `UserName(acct, app)` exactly; |
| + - `"other"` for everything else: `+s+` standalones, `+e+` environment users, and unknown callers. |
| + - A new table, additive (`CREATE TABLE IF NOT EXISTS`): `mail_caller_sends (account TEXT NOT NULL, app TEXT NOT NULL, day TEXT NOT NULL, class TEXT NOT NULL, sends INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (account, app, day, class))`. It is pruned with the same retention as `mail_sender_counts`, and it joins every list an app-keyed mail table joins (files above). |
| + - `func (s *Store) RecordMailCallerSend(ctx context.Context, acct, app, day, class string) error` upserts `sends = sends + 1`. |
| + - `func (s *Store) MailCallerSends(ctx context.Context, acct, app, sinceDay string) (map[string]int64, error)` sums by class over `day >= sinceDay`. |
| + - `recordAndEnforceMail` calls `RecordMailCallerSend` for **Send** events only, and only on the named path (after the live check). The class is computed from `ev.Caller` and the **resolved** account and app, never from tags. A tag can name the app, but only the caller decides the class, so a forged tag can neither hide an `app_user` send nor fake a `mailer` one. |
| + |
| +- [ ] **Step 1: Write the failing tests.** |
| + - `TestParseEventKeepsTags`: a recorded Bounce event with `mail.tags` holding `account`, `app`, `sender` and `ses:caller-identity` yields `Tags` with exactly the three; an over-long value is cut as other fields are. |
| + - `TestTagsBelievedOnlyFromMailer` (**guard test 8.11**), table-driven over `SenderOfCaller`: |
| + - caller `carlos-mail-abc-docs` with tags naming `xyz/sheets/app`: `(abc, docs, app, true)`. The tags are ignored. |
| + - caller `carlos-mail-abc+e+<hash>` (indexed) with forged tags: the index's answer. |
| + - caller `carlos-mailer-eu-west-1` with valid tags: the tags. |
| + - caller `carlos-mailer-eu-west-1` with tags missing, or with an invalid account: `false`. |
| + - caller `arn:aws:sts::123456789012:assumed-role/x/carlos-mailer-eu-west-1` with tags: `false`. |
| + - caller `arn:aws:iam::123456789012:user/carlos-mail/carlos-mailer-eu-west-1`: `false` (wrong path). |
| + - caller `someone-else` with tags: `false`. |
| + - `TestRecordAndEnforceChargesCallerNotForgedTag` (console, fake store): an SMTP app's event with another app's tags increments the caller's counts and never the tagged app's; the same event from the mailer increments the tagged sender's. |
| + - `TestMailerNameNeverParsesAsApp`: `AppOfCaller("carlos-mailer-eu-west-1")` is false. The reason: `carlos-mailer-…` does not start with `carlos-mail-` at all (the character after `mail` is `e`, not `-`), so the prefix cut fails before any account is parsed. Also pin the converse: `IsMailerCaller(UserName(acct, app))` is false for a table of valid accounts and apps (round 1 P3). |
| + - `TestCallerClass`: the mailer's bare name and user ARN give `mailer`; `carlos-mail-abc-docs` for (abc, docs) gives `app_user`; the same name for (abc, sheets) gives `other`; a `+s+` and a `+e+` name give `other`. |
| + - `TestMailCallerSendsCounts` (store): two `mailer` sends, one `app_user` send yesterday and one today, and an `other` send; `MailCallerSends(since=today)` gives `{mailer:2, app_user:1, other:1}`. Pruning removes days past retention. **App rename** (round 2 P2-A): `app_user` sends recorded under the old name, then a rename (`store.go:2656`'s path), then `MailCallerSends` on the new name returns them and the old name returns none. The same holds for an account move (`:2547`). So the reap's 7-day `app_user == 0` check cannot pass because the history stayed behind. |
| + - The existing table-coverage tests over `mailAppTables` and the store gate's map (whatever pins them today) pass with the new table in both. |
| + - `TestCallerClassIgnoresForgedTags` (console): an SMTP app's Send carrying the mailer's tags for itself is counted `app_user`; a Bounce adds nothing to `mail_caller_sends`. |
| +- [ ] **Step 2: Run** `go test ./internal/mail/ -run 'TestParseEventKeepsTags|TestTagsBelievedOnlyFromMailer|TestMailerNameNeverParsesAsApp|TestCallerClass' && go test ./internal/console/ -run 'TestRecordAndEnforceChargesCallerNotForgedTag|TestMailCallerSendsCounts|TestCallerClassIgnoresForgedTags'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** Update the two existing test callers of `SenderOfCaller` (`sender_test.go`, `walk_environment_test.go`) to pass `nil` tags. |
| +- [ ] **Step 4: Run** the same commands, then `go test ./internal/mail/ ./internal/console/ -run 'Caller|SESEvents|RecordMail'`. Expected: PASS. **Watch the guard test fail** once, by moving the guard below the `AppOfCaller` branch, and then restore it (AGENTS.md: a policy change is not done until its test has been watched to fail). |
| +- [ ] **Step 5: Commit** `mail: believe SES tags only from the mailer; count sends by caller class`. |
| +- [ ] **Step 6: Review** (own review: security gate and billing). Astra. The brief names the attribution family, its two design rounds and this plan's round 1 P2-1. Under stopping rule 2, a further finding in this family goes to Paul as a choice, not to a fourth fix. |
| + |
| +### Task 3: The mailer unit, its user, its socket and the peer rule |
| + |
| +**Spec:** decisions 2 and 3; §5 "The unit and its user", "Its socket", "The peer rule"; test 8.3; test 8.9 (unit half); gap G6. |
| + |
| +**Files:** |
| +- Create: `internal/host/units/carlos-mailer.service`, `internal/host/units/carlos-mailer.socket`, `internal/host/units/carlos-mailer-arm.path` |
| +- Modify (each gains `-/run/carlos-mailer -/etc/carlos-mailer` on its `InaccessiblePaths=` line): `carlos-instance@.service`, `carlos-instance-cmd@.service`, `carlos-instance-gen@.service`, `carlos-instance-seed@.service`, `carlos-instance-sidecar@.service`, `carlos-instance-tty@.service`, `carlos-instance-probe.service`, `carlos-dbread@.service`, `carlos-demo-build@.service`. This is every unit with an active, uncommented `InaccessiblePaths=` naming `/run/carlos-control`. The rootfs templates drop that line on purpose (`carlos-instance-rootfs@.service:144-149`), because their root is the image. |
| +- Modify: `internal/host/bootstrap.go` (`const tmpfilesConf` `:65-120`, `privilegedPlan` `:747`, the sysusers write in `bootstrapWithGroup` `:626`) |
| +- Create: `internal/mailer/server.go`, `internal/mailer/peer.go`, `internal/mailer/server_test.go` |
| +- Modify: `internal/instancectl/peer_linux.go`, `internal/instancectl/peer_other.go` (one exported constructor) |
| +- Create: `mailer_cli.go` (repo root: `carlos mailer serve`); modify the command registry (`commands.go` or the package subtree that holds box verbs), `parity/parity.tsv`, `parity/cli.tsv` (regenerated), `docs/site/cli.md` |
| +- Modify: `internal/status/snapshot.go` (the bucket-private `Metrics` block beside `RouteVersions` `:658-668`: `MailerArmed bool `json:"mailer_armed,omitempty"``) and the snapshot builder that fills it (G6 (b)); additive like every `Metrics` field |
| +- Test: `internal/host/units_isolation_test.go`, `internal/host/bootstrap_test.go`, `internal/mailer/server_test.go` |
| + |
| +**Interfaces:** |
| +- `internal/instancectl`: `func EdgeMainPIDPeer() func(net.Conn) error` returns `productionPeerOK()` on Linux, and on other systems a func that returns `errors.ErrUnsupported`. **No body of the existing peer code changes.** The mailer reuses the rule as it is: SO_PEERCRED uid `carlos` **and** pid equal to `carlos-edge.service`'s MainPID, from `systemctl show`. |
| +- `internal/mailer`: |
| + - `type Config struct { Listener net.Listener; PeerOK func(net.Conn) error; Handler http.Handler; Logf func(string, ...any) }` |
| + - `func Serve(ctx context.Context, cfg Config) error`: wraps the listener so `PeerOK` runs inside `Accept` and a refused connection is closed before net/http reads a byte, with refusals logged at most once a second. This is `instancectl`'s `vettedListener` shape, copied, not shared, so `instancectl`'s body stays unchanged. |
| + - `GET /v1/health` answers `200 {"ok":true}`. Task 5 adds `POST /v1/send`. |
| +- `carlos mailer serve`: takes the socket from systemd (`LISTEN_FDS`, one fd; refuses to start with none) and calls `mailer.Serve` with `instancectl.EdgeMainPIDPeer()`. Box audience. Parity row `mailer-serve box …`, with a `docs/site/cli.md` heading. |
| +- Units (exact): |
| + - `carlos-mailer-arm.path`: `[Path] PathExists=/etc/carlos-mailer/keys`, `Unit=carlos-mailer.socket`; `[Install] WantedBy=multi-user.target`. Bootstrap already arms every `.path` (`armedUnits`, `bootstrap.go:233-242`), so the operator's only step is writing the key. |
| + - `carlos-mailer.socket`: `ConditionPathExists=/etc/carlos-mailer/keys`, `ListenStream=/run/carlos-mailer/mailer.sock`, `SocketUser=carlos`, `SocketGroup=carlos`, `SocketMode=0600`, `Accept=no`. Same shape as `carlos-instance-control.socket:11-14`. |
| + - `carlos-mailer.service`: `Requires=carlos-mailer.socket`, `ConditionPathExists=/etc/carlos-mailer/keys`, `EnvironmentFile=-/etc/carlos/host.env`, `UnsetEnvironment=CARLOS_SECRETS_KEY`, `Environment=AWS_EC2_METADATA_DISABLED=true`, `ExecStart=/opt/carlos/carlos mailer serve`, `Restart=always`, `RestartSec=5`, `User=carlos-mailer`, `Group=carlos-mailer`, `StateDirectory=carlos-mailer`, `StateDirectoryMode=0700`, `IPAddressDeny=169.254.169.254/32 fd00:ec2::254/128`, then the relay's hardening block (`carlos-relay.service:20-43`) with `ProtectSystem=strict`, `ProtectProc=invisible`, `RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX`, `MemoryMax=256M`. No `ReadWritePaths` beyond the state directory. |
| + - tmpfiles gains `d /run/carlos-mailer 0750 root carlos -` and `d /etc/carlos-mailer 0750 root carlos-mailer -`. sysusers gains `u carlos-mailer - "CARLOS mailer" - /usr/sbin/nologin`, ordered before the group line. `privilegedPlan` gains `useradd --system --user-group --no-create-home --shell /usr/sbin/nologin carlos-mailer`, guarded like `carlos` (`:788-793`). System apply already runs sysusers before tmpfiles (`systemapply.go:1568`). |
| +- Box status: `Metrics.MailerArmed` is true when `/run/carlos-mailer/mailer.sock` exists **and** `GET /v1/health` answers 200 within 2 s. The agent cannot stat the key itself: `/etc/carlos-mailer` is `0750 root:carlos-mailer`, which uid `carlos` cannot traverse, by §5's rule. The socket exists only once the `.path` unit has seen the key, so it is the right proxy. An alert rule `mailer_unarmed@<box>` fires when a box hosts a route of a switched app and reports `MailerArmed=false` (wired in Task 6, once the switch exists). |
| + |
| +- [ ] **Step 1: Write the failing tests.** |
| + - `TestMailerPathsHiddenFromEveryTenantTemplate` (in `units_isolation_test.go`): derive the set of units whose uncommented `InaccessiblePaths=` names `/run/carlos-control`. Every one also names `-/run/carlos-mailer` and `-/etc/carlos-mailer`, and both are `-`-prefixed. Add `/etc/carlos-mailer/keys` to the credential loop at `:420`. |
| + - `TestCmdTemplateEqualsSeedOutsideTheNamedLines` still passes (the same line goes into both). |
| + - `TestMailerUnitShape`: the three units' directives as listed above. The service has the exact `IPAddressDeny`, `User=carlos-mailer`, `UnsetEnvironment=CARLOS_SECRETS_KEY` and `AWS_EC2_METADATA_DISABLED=true`, and has no `ReadWritePaths=` naming `/data`, `/run/carlos` or `/etc`. The socket has `SocketUser=carlos`, `SocketMode=0600`. **This is test 8.9's unit-file half.** |
| + - `TestTmpfilesMailerLines`, `TestSysusersCreatesMailer`, `TestPrivilegedPlanCreatesMailer`: the exact lines, and the user line ordered before tmpfiles is applied. |
| + - `TestMailerPeerRefusesNonAgentPid`, `TestMailerPeerRefusesOtherUid`, `TestMailerPeerAdmitsAgent` (**test 8.3**): `mailer.Serve` over a real unix socket with an injected `PeerOK` built on `instancectl`'s `edgePeer` test seam, or on a fake taking `(uid, pid)`. A refused peer reads EOF and never reaches the handler. An admitted peer gets `/v1/health`. |
| + - `TestMailerServeRefusesWithoutSocket`: `carlos mailer serve` with no `LISTEN_FDS` exits non-zero with one line. |
| + - `TestBoxReportsMailerArmed`: no socket gives false; a socket whose health answers gives true; a socket that does not answer gives false (a temp run directory). |
| +- [ ] **Step 2: Run** `go test ./internal/host/ -run 'TestMailer|TestTmpfilesMailer|TestSysusersCreatesMailer|TestPrivilegedPlanCreatesMailer|TestCmdTemplateEqualsSeed|TestBoxReportsMailerArmed' && go test ./internal/mailer/ && go test . -run TestMailerServe`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** Then `go test . -run TestCLIProjection -update`, add the parity row and the `docs/site/cli.md` heading, and run `make parity-doc`. |
| +- [ ] **Step 4: Run** the same commands, then `go test ./internal/host/ -run 'Units|Bootstrap|Isolation'`, `go test . -run 'TestCLIProjection|TestParity'` and `go test ./internal/docsite/`. Expected: PASS. Cross-build: `GOOS=darwin go build ./...`, `GOOS=windows go build ./...`. |
| +- [ ] **Step 5: Census card.** Run `make census-card`, and check its units against the Task 3 section of `docs/superpowers/notes/census-plan-platform-mail-submission.md`. Add any unit it names that the plan did not. Rerun `make census-propose NAME=platform-mail-submission` with the cumulative CLAIMS file, so every push of the branch is green (round 1 P3). |
| +- [ ] **Step 6: Verify on a dev box** (paul-mbp devbox or the dev deployment; not production). `systemctl show -p MainPID --value carlos-edge.service` succeeds as user `carlos-mailer` under the unit's hardening. **The peer rule depends on it.** If D-Bus is refused, stop and report: do not loosen the hardening without a review. |
| +- [ ] **Step 7: Commit** `mailer: unit, user, socket and the agent-only peer rule`. |
| +- [ ] **Step 8: Review** (own review: security gate and root). Astra reviews the card and the diff. |
| + |
| +### Task 4: The verb at both bind sites, with `CARLOS_MAIL` agent-owned |
| + |
| +**Spec:** decisions 1 and 11; §4; tests 8.2 and 8.7; "Not available to" seeds, sidecars, cmd and tty. |
| + |
| +**Files:** |
| +- Create: `internal/mailsubmit/verb.go` (the control-socket handler), `internal/mailsubmit/forward.go` (the agent's client to the mailer), `internal/mailsubmit/proto.go` (the agent-to-mailer wire), `internal/mailsubmit/verb_test.go`, `internal/mailsubmit/forward_test.go` |
| +- Create: `internal/host/mailswitch.go`, `internal/host/mailswitch_test.go` |
| +- Modify: `internal/activator/backend_exec.go`: `type ExecBackend` (two fields), the mount in `spawnChildFrom` (`:2546-2556`), `var agentOwnedNames` (`:2749`), `agentOwnedVars` (`:2758`), `seedVars` (`:2789`) |
| +- Modify: `internal/activator/prepare.go` (`listenControl` `:279-303`) |
| +- Modify: `internal/moves/envreport.go` (`AgentOwnedVars` `:62`) |
| +- Modify: `internal/host/agent.go` (`runAgent`, beside `Timers` and `UpdatesReader` `:541-544`) |
| +- Test: `internal/activator/agentowned_moves_test.go`, `internal/activator/backend_exec_test.go` (or a new `mailverb_test.go`) |
| + |
| +**Interfaces:** |
| +- `internal/mailsubmit/proto.go` (shared with Task 5): |
| + - `type Envelope struct { From string `json:"from"`; To []string `json:"to"`; Raw string `json:"raw"` }`: the instance's body. Unknown fields are ignored, never read. |
| + - `type SendRequest struct { Account, App, Host string; From string; To []string; Raw []byte }` (JSON names `account, app, host, from, to, raw`): the agent's stamped request to `POST /v1/send`. |
| + - `type Answer struct { MessageID string `json:"message_id,omitempty"`; Code string `json:"code,omitempty"` }`. |
| + - Codes: `FROM_NOT_ALLOWED`, `CAP_REACHED`, `PAUSED`, `RATE`, `MAILER_UNAVAILABLE`, `ROUTE_NOT_ON_BOX`, `SUBMISSION_OFF`, `REJECTED`, `BAD_REQUEST`. |
| + - `const MaxRaw = 10 << 20`, `MaxRecipients = 50`, `MaxBody = 14 << 20`, `MailerSocket = "/run/carlos-mailer/mailer.sock"`. |
| +- `internal/mailsubmit/verb.go`: |
| + - `type Forwarder interface { Send(ctx context.Context, req SendRequest) (status int, ans Answer, retryAfter string, err error) }` |
| + - `func Mount(mux *http.ServeMux, rt registry.Route, tokenReader func() (string, error), fwd Forwarder)` registers `POST /v1/mail`. It checks, in order: |
| + 1. the bearer, by the existing verbs' rule (`instanceupdates/control.go:37-45`, `schedule/control.go:81-90`): `want, err := tokenReader()`; if `err != nil || want == ""`, answer `401` whatever the request carries (round 1 P2-6). Otherwise compare the SHA-256 of the `Authorization` header with that of `"Bearer " + want`, using `subtle.ConstantTimeCompare`; a mismatch is `401`; |
| + 2. `http.MaxBytesReader(MaxBody)`, the JSON shape, base64 `raw`, at most `MaxRaw`, 1 to 50 recipients, a non-empty `from`, else `400 BAD_REQUEST`. |
| + It then stamps `Account: release.RouteAccount(rt), App: rt.App, Host: rt.Host` from `rt`, **never from the body**, forwards, and copies the mailer's status, answer and `Retry-After`. A dial or transport error is `503 MAILER_UNAVAILABLE`. The From-header comparison and hygiene are the mailer's (Task 5), so the policy lives in one place. |
| +- `internal/mailsubmit/forward.go`: `type SocketForwarder struct { Path string; Timeout time.Duration }` (defaults `MailerSocket`, 60 s). It does an HTTP POST over a fresh unix dial per call. |
| +- `internal/activator`: |
| + - `ExecBackend` gains `Mail mailsubmit.Forwarder` (nil means the verb is not mounted) and `MailSwitch func(acct, app string) bool` (nil means off). |
| + - One mount composer replaces the two copies: `func (b *ExecBackend) controlMount(rt registry.Route, tokenReader func() (string, error), gen uint64) func(*http.ServeMux)`. It returns nil only when `Timers`, `UpdatesReader` and `Mail` are all nil, and mounts the mail verb **under its own condition** (`b.Mail != nil`), never under the `Timers`/`UpdatesReader` one. Both bind sites call it: `spawnChildFrom` (flat) and `listenControl` (nested and rootfs, via `prepare.go:162`). |
| + - `agentOwnedNames` gains `"CARLOS_MAIL"`. `agentOwnedVars` sets `CARLOS_MAIL=submit` when `haveControl && rt.Provisioned && b.Mail != nil && b.MailSwitch != nil && b.MailSwitch(release.RouteAccount(rt), rt.App)`, and **strips** it otherwise. |
| + - **`rt.Provisioned` is in the rule** (round 1 P2-2; the reviewer offered two fixes, and this plan takes the agent-side one). A route with no instance record (a hand-made `carlos route` row) is invisible to the door, and the mailer would answer it `403 ROUTE_NOT_ON_BOX` every time. The door-side alternative would need a host-to-app map in the box report that does not exist (`RouteVersions` is keyed by host alone). So such a route is never told it can submit. |
| + - The residual, stated: an unprovisioned route of a switched app has neither channel (its bundle lost the SMTP variables), so rastrillo refuses at boot. That is decision 11's loud failure. At spawn the agent also logs at error level, once per host, "route has no instance record, so it cannot submit mail for switched app <app>". The remedy is a record (adoption) or switching off. That covers every launch path that composes through it: flat, unit, rootfs, `rootfsenv.go:50` and `claim_snapshot.go:224` (where `haveControl` is false, so it is stripped). |
| + - `seedVars` strips `CARLOS_MAIL` along with the two control-channel variables. |
| +- `internal/moves`: `AgentOwnedVars` gains `"CARLOS_MAIL": true`. `TestAgentOwnedVarsAreMovesBoxOwned` pins the pair. |
| +- `internal/host/mailswitch.go`: |
| + - `type mailSwitchCache struct` holds a `release.Store` and a map from `(acct, app)` to `{on bool; etag string; at time.Time}`. |
| + - `func (c *mailSwitchCache) On(acct, app string) bool`: the cached value. On a miss, one bounded `Get` (2 s) of `mailwire.SenderKey(acct, app, "app")`, decoded as `mailwire.SenderView`, `Submission != nil && Submission.On`. |
| + - `func (c *mailSwitchCache) Refresh(ctx context.Context)`: re-reads every cached key. The agent calls it on each serial bump. |
| + - On a read error with no cached value it answers false and logs once per app per minute. A wake with the switch unreadable gets SMTP variables if the bundle has them, or neither channel, in which case rastrillo refuses at boot (decision 11's loud failure). |
| +- `runAgent` sets `eb.Mail = mailsubmit.SocketForwarder{}` and `eb.MailSwitch = cache.On` on every box. It also adds `cache.Refresh` to the serial-bump pass. |
| + |
| +- [ ] **Step 1: Write the failing tests.** |
| + - `TestMailVerbStampsSocketRoute` (**test 8.2**): a listener for host A with a recording fake forwarder. A body carrying `"host":"B","account":"x","app":"y"` is forwarded with A's account, app and host. |
| + - `TestMailVerbAuth`: a missing or wrong bearer is `401`, and the forwarder is not called; the token is re-read per request (rotate it between two calls). |
| + - `TestMailVerbLimits`: `raw` of `MaxRaw+1` decoded bytes, 51 recipients, 0 recipients, bad base64, and a body over `MaxBody` are each `400 BAD_REQUEST`, with no forward. |
| + - `TestMailVerbPassesThroughAnswers`: a fake forwarder returning `429 CAP_REACHED` with `Retry-After: 3600` reaches the client byte for byte; a forwarder error is `503 MAILER_UNAVAILABLE`. |
| + - `TestMailVerbMountedAtBothBindSites`: a flat spawn (`spawnChildFrom`) and a nested `listenControl` both serve `POST /v1/mail` when `Mail != nil` and `Timers == nil && UpdatesReader == nil`, and neither serves it when `Mail == nil`. |
| + - `TestCarlosMailFollowsTheBind` (**test 8.7**), table over `agentOwnedVars`: switch on with `haveControl` and `Provisioned` gives `CARLOS_MAIL=submit` (with the forwarder stubbed to fail, so mailer health is ignored); switch on without control strips it; switch on with control on a route that is **not** `Provisioned` strips it and logs once; switch off strips a tenant-supplied `CARLOS_MAIL=submit` from `fileEnv`. |
| + - `TestMailVerbRefusesEmptyToken` (round 1 P2-6): a token reader answering `""`, and one answering an error, each give `401` to a request carrying `Authorization: Bearer ` (empty) and to one carrying any token. The forwarder is never called. |
| + - `TestMailerSidePackagesDoNotImportMail` (round 1 P3): walking `internal/mailer`, `internal/mailsubmit`, `internal/mailwire` and `internal/host` with `go/build` (repo-internal imports, recursively) never reaches `internal/mail`, `internal/console` or `aws-sdk-go-v2/service/iam`. This keeps `internal/mail` out of the root binary (the census-scope reason in "Plan choices"). |
| + - `TestSeedVarsStripCarlosMail`. |
| + - `TestAgentOwnedVarsAreMovesBoxOwned` (existing) updated: the pair still matches. |
| + - `TestMailSwitchCache`: a hit, a miss read, a refresh flipping a value, and a read error with no cache answering false. |
| +- [ ] **Step 2: Run** `go test ./internal/mailsubmit/ && go test ./internal/activator/ -run 'TestMailVerb|TestCarlosMail|TestSeedVarsStrip|TestAgentOwnedVars' && go test ./internal/host/ -run 'TestMailSwitchCache|TestMailerSidePackagesDoNotImportMail'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** the same commands, then `go test ./internal/activator/ -run 'Control|Schedule|Updates|AgentOwned|Spawn'` and `go test ./internal/moves/`. Expected: PASS. Cross-build darwin and windows (the mailsubmit dialer must compile there; it is never reached). |
| +- [ ] **Step 5: Census card**, as Task 3 step 5, and rerun `make census-propose NAME=platform-mail-submission` so this push is green (round 1 P3). |
| +- [ ] **Step 6: Commit** `activator: POST /v1/mail on the control socket; CARLOS_MAIL agent-owned`. |
| +- [ ] **Step 7: Review** (own review: security gate). Astra reviews the card and the diff. |
| + |
| +### Task 5: The mailer's SES send, header hygiene, the per-sender token bucket and the per-box cap counter |
| + |
| +**Spec:** decisions 4, 5, 6 and 9; §4.1 (a); §5 "Its credential", "What else the mailer's user may do", "The send", "Header hygiene", "Rate", "Tenants"; §9.0; tests 8.4, 8.5 and 8.6; gap G9. |
| + |
| +**Files:** |
| +- Create: `internal/mailer/send.go`, `internal/mailer/policy.go`, `internal/mailer/hygiene.go`, `internal/mailer/rate.go`, `internal/mailer/counter.go`, `internal/mailer/keys.go`, `internal/mailer/routes.go`, `internal/mailer/ses.go`, with tests beside each |
| +- Modify: `mailer_cli.go` (wire the pipeline) |
| +- Modify: `internal/release/store.go` (one constructor; `newS3Store`'s client options factored out, unchanged) |
| +- Modify: `internal/provision/reconcile.go` (one exported predicate) |
| +- Modify: `internal/hostenv/hostenv.go` (`Optional` gains `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION`) |
| +- Modify: `internal/mailwire/mailwire.go` (`DomainView` and its decode pin, `TenantName`, the tier default cap; round 1 P3) |
| +- Modify: `internal/console/mailcounts.go` (`TierCap("")` reads `mailwire`'s default; round 1 P3) |
| + |
| +**Interfaces:** |
| +- **Regions and credentials** (round 1 P2-3). IMDS is off, so the default chain would find no region, and `CARLOS_REGION` is a placement label, not an AWS region. The mailer names both regions explicitly, from host.env through the unit's `EnvironmentFile=`: |
| + - `CARLOS_MAIL_REGION`: the SES region, the same value as the console's; |
| + - `CARLOS_DEPLOYMENT_REGION`: the deployment bucket's AWS region. |
| + Both are new optional host.env keys. `carlos mailer serve` refuses to start without either, with one journal line naming the missing key. |
| + Every AWS config the mailer builds comes from `rootaws.LoadStaticConfig(ctx, keyID, secret, awsconfig.WithRegion(<region>))` (`internal/rootaws/config.go:45`). That function already refuses `AWS_PROFILE`, empties the shared config files and disables IMDS. The mailer never calls `LoadDefaultConfig`. |
| +- `internal/release`: `func NewS3StoreFromConfig(cfg aws.Config, bucket string) *S3Store` builds the client with the same options `newS3Store` applies today: `s3compat.Options()` and the checksum settings, which honour `CARLOS_S3_ENDPOINT` and `CARLOS_S3_QUIRKS`. Those options move into one unexported helper that both call; neither body's behaviour changes. |
| +- **A missing object reads as absent, not as an error** (round 1 P2-4). The mailer's IAM user has no `s3:ListBucket`, so S3 answers a missing key with `403 AccessDenied`, not `404`, and `s3NotFound` (`store.go:887-896`) does not fold that. The mailer's three reads (sender, instance and domain records) go through **a store wrapper**, not a helper function (round 2 P3): `routeHere` reads through `provision.GetRecord`, which takes a `release.Store` and calls its `Get`. So `type absentOnDeniedStore struct{ release.Store }` overrides `Get` to return an `os.ErrNotExist`-wrapped error for an `AccessDenied` API error, and passes everything else through. The mailer builds its one store as `absentOnDeniedStore{release.NewS3StoreFromConfig(...)}` and hands that same value to `provision.GetRecord` and to its own sender and domain reads. A denial and a real absence both read as "absent". Absent always refuses (`SUBMISSION_OFF`, `ROUTE_NOT_ON_BOX` or `FROM_NOT_ALLOWED`), so the mapping cannot admit anything. A denied read is logged as such, at most once a minute per prefix, so a broken policy is visible and is not mistaken for a real absence. Domain records are read by `mailwire.DomainKey(acct, domain)` for each `Grant.Domains` entry, never listed, so no List grant is needed. |
| +- `internal/provision`: `type BoxScope struct { Region string; Pools []string; FleetBox string }` and `func BoxServesRecord(b BoxScope, rec Record) bool`. It returns exactly `ReconcileConfig{Region: b.Region, Pools: b.Pools, FleetBox: b.FleetBox}.inScope(rec.Region, rec.Pool, everywhereClass(rec)) && …ownsRecord(rec) && !rec.Retired`. It is built from the **same unexported predicates**, which do not change, so "on this box" means what the reconciler means. Where `FleetBox` is set the check is exact; otherwise it is region and pool (decision 4, §6). |
| +- `internal/mailer/keys.go`: the key file format is up to two lines of `<access-key-id> <secret-access-key> <created RFC 3339>`; `#` comments and blank lines are skipped. |
| + - `func LoadKeys(path string) ([]Key, error)` refuses a file that is not mode `0640`, not owned by root, or not group `carlos-mailer`, and refuses more than two keys. |
| + - `type KeyFile struct` holds the loaded keys. `func (k *KeyFile) Newest() Key` returns the key with the **newest** `created`. `func (k *KeyFile) Changed() bool` reports an mtime change, after which the mailer reloads the file and rebuilds its clients, so rotation needs no restart (§5 Rotation). |
| +- `internal/mailer/routes.go`: `func (m *Mailer) routeHere(ctx, acct, app, host string) (bool, error)` reads `provision.RecordKey(acct, app, host)` through `provision.GetRecord` (which refuses a body that disagrees with its key) and returns `provision.BoxServesRecord(m.scope, rec)`. It caches answers for 30 s; a negative answer is cached for 5 s. |
| +- `internal/mailer/policy.go`: `func (m *Mailer) admit(ctx, req mailsubmit.SendRequest) (decision, error)`. Before any SES call, in this order: |
| + 1. `routeHere`, else `403 ROUTE_NOT_ON_BOX` (**test 8.4**). |
| + 2. The app sender (`mailwire.SenderKey(acct, app, "app")`, decoded as `SenderView`, cached 2 s by etag). Absent, or `Submission` off, gives `403 SUBMISSION_OFF`. |
| + 3. `EffectivePause() != nil` gives `429 PAUSED`, with `Retry-After` set to the seconds to the next UTC midnight for `cap`/`plan`, and 3600 otherwise. |
| + 4. Parse `raw`'s header block. Exactly one `From:` whose address (net/mail) equals `req.From`, case-insensitively, else `400 BAD_REQUEST` (§4 "`from` ≠ `From:`"). |
| + 5. The From domain must exactly equal one of `Grant.Domains` whose domain record (`mailwire.DomainKey`, decoded as `mailwire.DomainView`: `Domain`, `Apps`, `Regions[r].{Status, ConfigSet, IdentityARN}`) lists the app and has `Regions[CARLOS_MAIL_REGION].Status == "verified"`, else `403 FROM_NOT_ALLOWED`. The rule matches `SendPolicyJSON`'s `*@<domain>` (`policy.go:171-180`), with the domain compared exactly. |
| + 6. The cap: `counter.Reserve(sender, day, cap)`, where `cap = Grant.DailyCap`, or the tier default when it is 0. At the cap it is `429 CAP_REACHED`, with `Retry-After` to the next UTC midnight. |
| + 7. The rate: `bucket.Take(sender)`, else `429 RATE` with `Retry-After = ceil(seconds to the next token)`, at least 1. A refused take releases the step-6 reservation. |
| + The tier default cap moves from `internal/console`'s `TierCap("")` to a constant in `internal/mailwire`, which both import, so the two cannot disagree. |
| +- `internal/mailer/hygiene.go`: `func StripHeaders(raw []byte) ([]byte, error)` removes every header field named `Bcc` or starting `X-SES-`, case-insensitively, together with its folded continuation lines. Only the header block is touched (up to the first empty line, CRLF or LF). The body is returned byte for byte. A message with no header/body separator is `400 BAD_REQUEST`. |
| +- `internal/mailer/rate.go`: `type Buckets struct`, per `(account, app, sender)`, at `Rate = 2` per second with `Burst = 20` (G9), in memory. |
| +- `internal/mailer/counter.go`: `type Counter struct` in `$STATE_DIRECTORY/counts/<YYYY-MM-DD>.json`, a map from `acct/app/sender` to a count. |
| + - `Reserve` increments and writes with temp file, fsync and rename before the send. `Release` decrements on a send that SES did not accept. |
| + - Files older than 3 days are removed at start. |
| + - A corrupt file is moved aside, logged, and the day restarts from 0. That is the per-box bound §4.1 (a) accepts, and it is logged loudly. |
| +- `internal/mailer/ses.go`: `type SES interface { SendEmail(ctx, *sesv2.SendEmailInput, ...func(*sesv2.Options)) (*sesv2.SendEmailOutput, error) }`. The real client is `sesv2.NewFromConfig` over `rootaws.LoadStaticConfig` with the newest key and `CARLOS_MAIL_REGION`. The S3 store is rebuilt over the same key in `CARLOS_DEPLOYMENT_REGION`. When the key file changes, both clients are rebuilt. The input is: |
| + - `FromEmailAddress: req.From`; |
| + - `Destination.ToAddresses: req.To` (the envelope); |
| + - `Content.Raw.Data`: the stripped raw; |
| + - `ConfigurationSetName`: the domain's `Regions[region].ConfigSet` when non-empty; |
| + - `TenantName: mail.TenantName(acct)` (re-implemented in `mailwire` as `"carlos-" + acct`, with a test pinning it equal) **only** when `SenderView.TenantARN != ""`; |
| + - `EmailTags`: `account`, `app`, `sender`. |
| + SES errors map as follows: `MessageRejected` is `400 REJECTED`; `TooManyRequests` and throttling are `429 RATE` with `Retry-After: 1`; `SendingPaused`, `AccountSuspended` and any other error are `503 MAILER_UNAVAILABLE`. A refusal releases the reservation. |
| +- `POST /v1/send` is served under Task 3's peer rule. Concurrency is at most 4 sends in flight (a semaphore); above that the answer is `503 MAILER_UNAVAILABLE`. |
| +- `carlos mailer serve` reads `CARLOS_DEPLOYMENT_BUCKET`, `CARLOS_DEPLOYMENT_REGION`, `CARLOS_MAIL_REGION`, `CARLOS_REGION` (placement only), `CARLOS_POOLS` (`provision.ParseBoxPools`) and the fleet identity variables (`CARLOS_FLEET`, `CARLOS_FLEET_BOX`, `CARLOS_TUNNEL_NAME`, with the agent's resolution rule). It refuses to start, with one line, without the bucket, either region or a loadable key. The unit then restarts it every 5 s (`Restart=always`, `RestartSec=5`). The socket stays up, so the agent's dial answers `503 MAILER_UNAVAILABLE`, and the box reports `MailerArmed=false` because `/v1/health` fails. That is the stated failure behaviour (round 1 P3). |
| + |
| +- [ ] **Step 1: Write the failing tests** (fake SES recording calls, in-memory `release.Store`, temp state directory): |
| + - `TestMailerRefusesRouteNotOnBox` (**test 8.4**): a record in another region, in another pool, labelled for another fleet box, retired, absent, or with a body naming another host. Each is `403 ROUTE_NOT_ON_BOX`, with no SES call. |
| + - `TestMailerPolicyRefusesBeforeSES` (**test 8.5**): wrong From domain gives `403 FROM_NOT_ALLOWED`; a domain granted but not verified in the mail region, the same; `From:` header ≠ `from` gives `400`; the cap boundary (cap 3: sends 1-3 accepted, the 4th `429 CAP_REACHED`); a paused sender of each kind gives `429 PAUSED` with the right `Retry-After`; a switch-off sender gives `403 SUBMISSION_OFF`. The fake SES saw exactly three calls. |
| + - `TestHygieneStripsHeaders` (**test 8.6**): `Bcc:`, `BCC:` folded over two lines, `X-SES-TENANT`, `X-SES-CONFIGURATION-SET`, `x-ses-message-tags` and a body line starting `Bcc:` after the separator. The first five are gone, the body line is kept, and every other header and the body are byte-identical. Also no separator gives an error, and LF-only line ends work. |
| + - `TestSendInputShape`: the exact `SendEmailInput`. Tags are the three; `ConfigurationSetName` is set when the domain has one; `TenantName` is present only with a `TenantARN`; `Destination` is the envelope, not the headers. |
| + - `TestCounterDurableAcrossRestart`: reserve 2, reopen, reserve 1 more against cap 3, and the 4th is refused; a refused SES send releases its slot; a corrupt file restarts at 0 and is logged. |
| + - `TestRateBucket`: 20 in a burst, then `429 RATE` with `Retry-After: 1`, and after 500 ms one more is admitted. |
| + - `TestKeysFile`: a mode or owner other than `0640 root:carlos-mailer` is refused (a test seam for the owner check); three keys are refused; the newest wins; an mtime change reloads. |
| + - `TestMailerNeverUsesIMDS`: building the SES and S3 clients makes no call to a fake IMDS endpoint set through `AWS_EC2_METADATA_SERVICE_ENDPOINT`, and the configs carry exactly the two named regions. |
| + - `TestMailerRefusesWithoutRegion` (round 1 P2-3): `carlos mailer serve` with `CARLOS_MAIL_REGION` unset, and again with `CARLOS_DEPLOYMENT_REGION` unset, exits non-zero naming the key, before it serves anything. |
| + - `TestMailerReadsAccessDeniedAsAbsent` (round 1 P2-4; through the wrapper, including via `provision.GetRecord`): a fake store answering `AccessDenied` for the sender gives `403 SUBMISSION_OFF`, for the instance record `403 ROUTE_NOT_ON_BOX`, and for a domain record `403 FROM_NOT_ALLOWED`. None reaches SES, and each logs the denial. Any other store error gives `503 MAILER_UNAVAILABLE`. |
| + - `TestDomainViewDecodesMailDomain` (round 1 P3): a fully populated `mail.DomainRecord`, marshalled and decoded as `mailwire.DomainView`, keeps every field the view names. Lives in `internal/mail`'s tests, which can import both. |
| + - `TestTierDefaultCapShared`: `internal/console`'s `TierCap("")` equals `mailwire.DefaultDailyCap`. |
| + - `TestBoxServesRecordMatchesReconciler`: for a table of records and box scopes, `BoxServesRecord` agrees with what a reconcile pass would mint (reuse the reconcile test fixtures). |
| + - `TestHostEnvAllowsMailRegion`: `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION` pass `Assemble` and `AssembleGroup`. |
| +- [ ] **Step 2: Run** `go test ./internal/mailer/ && go test ./internal/provision/ -run TestBoxServesRecord && go test ./internal/hostenv/ -run TestHostEnvAllowsMailRegion && go test ./internal/release/ -run NewS3StoreFromConfig && go test ./internal/mail/ -run TestDomainViewDecodesMailDomain && go test ./internal/console/ -run TestTierDefaultCapShared`. Expected: FAIL. |
| +- [ ] **Step 3: Implement** to the interfaces. |
| +- [ ] **Step 4: Run** the same commands. Expected: PASS. Cross-build darwin and windows. |
| +- [ ] **Step 5: Census card**, as Task 3 step 5, and rerun `census-propose` under the same NAME. The mailer's read of `/etc/carlos-mailer/keys` is **not** a root read (it runs as `carlos-mailer`), but the code is in the root binary, so its units are `new`. |
| +- [ ] **Step 6: Commit** `mailer: policy before the send, hygiene, rate, per-box cap, SES`. |
| +- [ ] **Step 7: Review** (own review: security gate and production). Astra reviews the card and the diff. |
| + |
| +### Task 6: The per-app switch and its door: manifest declaration, preconditions, reap and switch-off |
| + |
| +**Spec:** decisions 5, 10 and 11; §5 "Tenants"; §7 items 2-7; tests 8.1, 8.8 and 8.12; gaps G3, G4, G6, G7 and G8. |
| + |
| +**Files:** |
| +- Modify: `internal/release/release.go` (`type Manifest` `:47`, the manifest validation `:446-470`) |
| +- Modify: `cli.go` (`runShip` `:2464`, the `--mail` flag), `ship_stateless.go`'s neighbour for the echo check, `internal/console/apicli.go` (`handleAPIShip` `:2126`: accept, store and echo `mail`) |
| +- Create: `internal/console/apisubmission.go`, `internal/console/apisubmission_test.go` |
| +- Modify: `internal/console/routedecls.go` (one row beside `:1224`), `internal/console/apimail.go` (status reply gains `submission`), `internal/console/teamcreds.go` (`mintOwnedEnvironmentMail` `:50`, `reapOwnedEnvironmentCredentials` `:90`) |
| +- Modify: `internal/console/alertsignals.go` (a new signal function beside `heartbeatBoxSignals` `:397`; the rule's kind and level in `alertRuleKind` `:472` and `alertRuleLevel` `:485`), `internal/console/alertengine_pass.go` (call it in the pass), the alert copy (`alertRuleCopy`, `alertengine_pass.go:485`, and its approved rows) (round 1 P2-5). All of this is in `internal/console`, outside census scope; nothing lands in `internal/alerting`. |
| +- Modify: `internal/mail/walk.go` (`claimUnserializedEnable` `:761`, `claimUnserializedRotate` `:1031`, `claimUnserializedSetSenderPaused` relaxed for switched senders), `internal/mail/walk_environment.go` (`claimUnserializedEnableEnvironment`), `internal/mail/sweep.go` (the §7.4 reap) |
| +- Create: `internal/mail/submission.go`, `internal/mail/submission_test.go` |
| +- Modify: the console doors that change what a route serves. Step 1 enumerates them; at least `handleAPIPromote` (`apicli.go:909`), `handleAPIRollback` (`:1312`), `handleAPIInstanceChannel`, `handleAPIUpdatesPut`, `handleAPIUpdatesInstall` and `handleAPIUpdatesPolicy`. |
| +- Modify: `internal/activator` (the spawn paths' loud log), `internal/host` (the adopt pass's loud log and event) |
| +- Modify: `mail_cli.go` (`carlos email submission on|off`, the status line), the command registry, `parity/parity.tsv`, `docs/site/cli.md` |
| +- Create: `docs/superpowers/plans/platform-mail-submission-copy.json`, `approved_platform_mail_submission_copy_test.go` |
| +- Test: `internal/console/teamcreds_test.go` (guard tests 17 and 19), `internal/release/release_test.go` |
| + |
| +**Interfaces:** |
| +- `release.Manifest` gains `Mail string `json:"mail,omitempty"`` (additive, as `Label` is). Validation accepts `""` and `"submit"` and refuses anything else, on ship and on read, like `Capabilities`. `carlos ship --mail submit` sets it, and the ship echo is checked as `--stateless` is. **The declaration is a ship flag**, because the Oficina apps have no manifest file to hold `mail = "submit"` (rastrillo has none either). Task 9 adds the flag to each app's deploy. |
| +- `internal/mail/submission.go`: |
| + - `var ErrSubmissionOn = errors.New("mail: submission is on for this app; switch it off first")`. |
| + - `func SwitchOn(ctx, s, p Provisioner, seal, d Deployment, acct, app, actor string, now time.Time) (*Record, error)`, under the claim-mail wrappers like every walk. It sets `Submission{On: true, At: now, By: actor}` on the app sender. It removes the five `<P>_SMTP_*` from the default bundle and from every owned environment's bundle, and writes `<P>_MAIL_FROM` (G3) into each. It runs `ReapEnvironment` for each owned environment's user. It **keeps** the app-level user and key (the overlap week), still governed by pause. |
| + - `func SwitchOff(…)`: clears `Submission.On`, removes `<P>_MAIL_FROM`, and calls `Enable` (re-mint and re-deliver), then `EnableEnvironment` for each owned environment. |
| + - `claimUnserializedEnable` and `claimUnserializedEnableEnvironment` deliver nothing while switched: `Enable` refreshes the policy only, and `EnableEnvironment` returns `ErrSubmissionOn`. `Rotate` refuses with `ErrSubmissionOn`. |
| + - **New owned environments while switched** (round 1 P1-1). `mintOwnedEnvironmentMail` (`teamcreds.go:50`, reached from `teamenv.go:235` and the adopt and fork doors) checks `Submission.On` **explicitly**, rather than relying on `Provisioned == nil`. When the switch is on, it mints **no** IAM user and no key. It calls `mail.DeliverMailFromIn(ctx, s, acct, app, env)`, which writes `<P>_MAIL_FROM` (the app sender's `Declared.From`) into that environment's bundle and nothing else. A bundle does not inherit from the default, so without this a team environment created after the flip would boot with no From, and Task 7's `FromCarlos` would refuse it. |
| + - `func DeliverMailFromIn(ctx, s release.Store, acct, app, env string) error` is idempotent and writes the one variable through `appconfig.ApplyEnvironment`. That makes it a known walk for guard 18 (`TestApplyCallersAreTheKnownWalks`): add it to that test's list in the same commit. |
| + - **Release** (`reapOwnedEnvironmentCredentials` → `ReapEnvironment`) also unsets `<P>_MAIL_FROM` from the environment's bundle, beside the five it unsets today (`unsetSMTPEnvIn`, `walk_environment.go:171-196`). It does this whether or not the record names an environment user, because a switched app's environments have none. |
| + - `claimUnserializedSetSenderPaused` accepts a switched sender with `Provisioned == nil`, and writes only `Pause`. |
| +- `internal/mail/sweep.go`: `ReapAppUserAfterSubmission` reaps the app-level user and key only (never the identity: senders spec #147), sets `Submission.AppUserReapedAt`, and clears `Provisioned`. It runs only when **all** of the following hold (G4): |
| + - the switch has been on for at least 7 days; |
| + - `MailCallerSends(acct, app, since = the switch day)["mailer"] >= 1`; |
| + - `MailCallerSends(acct, app, since = today − 7)["app_user"] == 0`; |
| + - `Provisioned.IAMUser == UserName(acct, app)`. If a rename left the app-level user under its old name, its sends would resolve to the old app and never count as `app_user` for this one, so the reap refuses and logs. Fail-closed; the operator re-enables or reaps by hand. |
| + It reads Task 2's caller-class counts (`Store.MailCallerSends`, round 1 P2-1) through a function argument, `func(acct, app, sinceDay string) (map[string]int64, error)`, so `internal/mail` stays free of the console. A read error skips the reap for that pass. As G4 says, this proves the SMTP key stopped being used, not that every route can submit. |
| +- The door, `POST /api/cli/apps/{account}/{app}/email/submission` with body `{"on": bool}`, `Kind: kindCLI`, `Allow: svcrole.Allow(svcrole.Admin)` (the authority `email enable` has). On `on: true` it checks, in order, and each failure is `409` with the remedy: |
| + 1. the app's mail is declared and enabled; |
| + 2. **every route** of the app (every instance record, owned environments included) has a fresh `StagedVersion` (the box join, `apiinstances.go:1075-1095`) whose manifest has `Mail == "submit"`. A route with no fresh report is refused as "cannot confirm", by name; |
| + 3. every channel those routes follow has a head whose manifest has `Mail == "submit"`, so a wake cannot adopt an undeclared head; |
| + 4. G8: if the app sender has a `TenantARN`, the provisioner confirms that its identity and configuration set are associated with the tenant; |
| + 5. G6 (b): every box that reports one of the app's routes reports `MailerArmed`. |
| +- **The `mailer_unarmed` alert** (round 1 P2-5), in `internal/console/alertsignals.go`: |
| + - `func mailerUnarmedSignals(boxes []status.Box, switched map[string]bool, now time.Time, sig *alertSignals)`. |
| + - `switched` is the set of hosts that belong to a switched app's instance records. The pass builds it from the app senders whose `Submission.On` is set and their instance records, both read through `engineReads.get`, so unchanged objects are not re-read. |
| + - For every fresh box (not `status.BoxStale`) whose `Metrics.RouteVersions` names a host in `switched` while `Metrics.MailerArmed` is false, it adds signal `mailer_unarmed` keyed by the box label, value 1. Every other fresh box gets value 0, so an open incident clears on its own. A stale box adds nothing; the heartbeat rule already covers it. |
| + - `alertRuleKind("mailer_unarmed")` is the box kind and `alertRuleLevel` is warning. The copy row is drafted in step 0. |
| + - `alertengine_pass.go` calls it beside `heartbeatBoxSignals` and passes `sig.cover("mailer_unarmed", unread)`, so a box whose snapshot was unreadable is unknown, not clear. |
| + A flat route is **not** a refusal (decision 7, test 8.8). It then calls `mail.SwitchOn`, bumps the serial, and requests an app-wide restart through the existing restart-gen path (`handleAPIRestart`, `apicli.go:1582`). Running instances then respawn with `CARLOS_MAIL`. Until they do, they send over SMTP on the kept app-level key. `on: false` calls `mail.SwitchOff`, bumps the serial and requests the restart. |
| +- **The precondition holds while on** (decision 10, test 8.12): `func (s *Server) submissionBuildRefusal(ctx, acct, app, version string) *doorRefusal` returns `409` "this build does not declare `--mail submit`, and email submission is on for <app>: switch submission off first (carlos email submission off --app <app>), or ship with --mail submit". Every door from step 1's enumeration calls it before it writes. Waking is never refused. Instead, at spawn, when `MailSwitch` is on and the staged manifest's `Mail != "submit"`, the agent logs at error level and emits an instance event, once per (host, version). The adopt pass does the same when it adopts such a head (G7). |
| +- The status reply and `carlos email status` gain a Submission block: on or off, since when, whether the app-level user is kept or reaped, and the boxes not armed. |
| + |
| +- [ ] **Step 0: UX pass, then copy review** (AGENTS.md). Mock the CLI output of `email submission on|off` and the status block, the five precondition refusals, the build refusal, and the `mailer_unarmed` alert's title and body, at 80 columns. **The `email submission on` confirmation names the G10 outage** (round 2 P2-B). A route with no instance record cannot send mail once this is on, and its app will refuse to start, so check `carlos instances --app <a>` first. Lead with the state. Draft IDs `PMS-C1`.. in `platform-mail-submission-copy.json`. Run the copy-review skill, and apply Paul's edits verbatim. `TestApprovedPlatformMailSubmissionCopy` via `checkApprovedCopy` (`approved_copy_test.go:71`). **Paul's step.** |
| +- [ ] **Step 1: Enumerate the serve doors.** Grep `routedecls.go` for every handler that writes a channel pointer, an instance's channel, an update pin or policy, or a rollback, and list them in `submissionServeDoors` (a slice of route patterns). Write `TestSubmissionGateCoversEveryServeDoor`. It drives each listed door against a switched app with an undeclared build and expects the refusal. It also fails if a route declaration whose handler calls a known pointer, channel or pin writer is missing from the list. That second check is the second-door guard (AGENTS.md "a rule stated as an absence"). |
| +- [ ] **Step 2: Write the failing tests.** |
| + - `TestManifestMailField`: `""` and `"submit"` valid, `"smtp"` refused; a manifest without the key parses as `""` and marshals byte-identically to before (the `Label` rule). |
| + - `TestShipMailFlagEcho`: `carlos ship --mail submit` sends it and refuses a console that does not echo it. |
| + - `TestSwitchedAppRendersNoCredential` (**test 8.1**, golden), three cases. In each, `appconfig.RenderEnv` (`materialize.go:37`) holds no `<P>_SMTP_*` and no `AWS_*` key, and does hold `<P>_MAIL_FROM`: |
| + - the default environment after `SwitchOn`; |
| + - an owned environment that existed at the flip; |
| + - **an owned environment created after the flip**, through the real door path (`teamenv.go:235` → `mintOwnedEnvironmentCredentials`) (round 1 P1-1). |
| + - `TestSubmissionDoorPreconditions` (**test 8.8**): an undeclared route build, an undeclared channel head, an unassociated tenant, an unarmed box and an unreported route each refuse with their copy row. A flat route does not refuse. All declared gives `200`, the serial bumped and the restart requested. |
| + - `TestSubmissionGateCoversEveryServeDoor` and `TestWakeNeverRefusedForUndeclaredBuild` (**test 8.12**): the doors refuse with "switch submission off first"; a spawn with the switch on and an undeclared staged manifest starts, and logs and emits the event once. |
| + - `TestSwitchOffReMints`: `SwitchOff` restores the five variables through `Enable` in the default and owned bundles, and removes `<P>_MAIL_FROM`. |
| + - `TestEnableRotateWhileSwitched`: `Enable` delivers nothing; `Rotate` and `EnableEnvironment` return `ErrSubmissionOn`. |
| + - `TestMintOwnedEnvironmentWhileSwitched` (round 1 P1-1): while switched, `mintOwnedEnvironmentMail` makes **no** `EnsureUser` or `MintKey` call on the fake provisioner, writes no caller index entry, and delivers exactly `<P>_MAIL_FROM` into the new bundle. Releasing that environment removes `<P>_MAIL_FROM`, and its bundle then holds none of the six names. |
| + - `TestMailerUnarmedSignal` (round 1 P2-5): an unarmed fresh box hosting a switched app's route signals 1; the same box armed signals 0; an unarmed box hosting only unswitched routes signals 0; a stale box adds nothing; an unreadable box is covered as unknown. |
| + - `TestPauseSwitchedSenderWithoutProvisioned`: after the reap, `SetSenderPaused` writes `Pause` and no key call is made. |
| + - `TestReapAppUserAfterSubmission` (with a fake `MailCallerSends`): refused at 6 days; refused with an `app_user` send inside the last 7 days; refused with no `mailer` send since the switch; refused on a read error; done otherwise (user and keys deleted, identity kept, caller index entry removed, `AppUserReapedAt` set). An `other` send (a standalone credential) does not block it. |
| + - Guard tests 17 and 19 (`TestOwnedEnvironmentReceivesItsOwnPlatformCredentials` `teamcreds_test.go:101`, `TestReleaseReapsAndRevokingTheCredentialDoesNot` `:232`) gain a switched-app case: the owned environment holds no mail credential, and releasing it reaps nothing that is not there. |
| +- [ ] **Step 3: Run** `go test ./internal/release/ -run TestManifestMailField && go test ./internal/mail/ -run 'Switch|Submission|Reap|EnableRotateWhileSwitched|PauseSwitched' && go test ./internal/console/ -run 'Submission|Switched|OwnedEnvironment|ReleaseReaps|MintOwnedEnvironmentWhileSwitched|MailerUnarmedSignal|ApplyCallersAreTheKnownWalks' && go test ./internal/activator/ -run TestWakeNeverRefused && go test . -run 'TestShipMailFlag|TestApprovedPlatformMailSubmissionCopy'`. Expected: FAIL. |
| +- [ ] **Step 4: Implement**, then the CLI projection, parity row `email-submission email gap email submission on ; email submission off …`, the `docs/site/cli.md` heading, and `make parity-doc`. |
| +- [ ] **Step 5: Run** the same commands, then `go test . -run 'TestCLIProjection|TestParity'`, `go test ./internal/docsite/` and `go test ./internal/console/ -run 'Promote|Rollback|Channel|Updates|Ship|Email'`. Expected: PASS. |
| +- [ ] **Step 6: Census card** (the manifest field and validation, the ship flag, and the activator and host log sites), and rerun `census-propose` under the same NAME. |
| +- [ ] **Step 7: Commit** `email: per-app submission switch, its door and its preconditions`. |
| +- [ ] **Step 8: Review** (own review: security gate and production storage). Astra. |
| + |
| +### Task 7: rastrillo's `submit` transport (cross-repo) |
| + |
| +**Repo:** `amadan.net/rastrillo/rastrillo`, branch `feat/mail-submit` from `origin/main` (`f908c5fa` at the time of writing; the local checkout is 94 commits behind, so cut from origin). |
| + |
| +**Spec:** decision 11; §4; test 8.10; gaps G2 and G3. |
| + |
| +**Files:** |
| +- Create: `mail/submit.go`, `mail/submit_test.go` |
| +- Modify: `mail/mail.go` (a strict constructor beside `FromEnv` `:279-295`), `carlos/schedule.go` (factor the unix-socket `do` `:187-234` into a shared helper, or duplicate it in `mail/` if the factoring would change `ScheduleAt`'s errors; say which in the commit) |
| +- Modify: `docs/site/` (the mail page) |
| + |
| +**Interfaces:** |
| +- `func Submit(socket, token, from string) Sender` returns `*submitSender`, which implements `Sender`, `ListSender` and `Deliverer` (`Delivers() == true`). |
| + - `Send` and `SendList` build the message with the existing `message(from, ListMessage, time.Time)` (`mail.go:304`), and POST `{"from","to","raw"}` to `http://carlos/v1/mail` over `CARLOS_CONTROL_SOCKET` with `Authorization: Bearer <CARLOS_ADMIN_TOKEN>`. The token is re-read from the environment on each call. |
| +- `type SubmitError struct { Status int; Code string; RetryAfter time.Duration }` with `Temporary() bool` (true for 429 and 503). |
| + - `429` returns at once with `RetryAfter` parsed from the header, never retried in the transport (G2). |
| + - `503` is retried up to 3 times, at 1 s and 2 s, inside the context's deadline, then returned. |
| + - `400` and `403` return at once. |
| +- `func FromCarlos(prefix string, logger *slog.Logger) (Sender, error)`: |
| + - `CARLOS_MAIL=submit` **and** `CARLOS_CONTROL_SOCKET` set gives `Submit(socket, token, os.Getenv(prefix+"_MAIL_FROM"))`. An empty `<P>_MAIL_FROM` is an error naming it. |
| + - Otherwise, `<P>_SMTP_HOST` and `<P>_SMTP_FROM` set gives `SMTP(...)`, as `FromEnv` does. |
| + - Otherwise an error: "neither CARLOS_MAIL=submit nor <P>_SMTP_* is set". This is the loud boot failure of decision 11, which apps call where they refuse today. `FromEnv` is unchanged, for the apps that allow logged mail. |
| + |
| +- [ ] **Step 1: Write the failing tests** (an `httptest` server on a temp unix socket): |
| + - `TestSubmitChosenOnlyOnCarlosMail` (test 8.10): `CARLOS_MAIL=submit` with a socket and SMTP variables both set chooses submit; SMTP variables alone choose SMTP; `CARLOS_MAIL=smtp` (an unknown value) falls through to SMTP. |
| + - `TestSubmitBody`: the POST carries the bearer, `from`, `to` and base64 `raw`, whose `From:` equals `from`. |
| + - `TestSubmit429BacksOff`: one request, a `SubmitError` with `RetryAfter=3600s`, and no retry. |
| + - `TestSubmit503Retries`: three 503s then 200 within the deadline succeed after 4 requests; a deadline shorter than the backoff returns the 503 error. |
| + - `TestFromCarlosFailsWithNeitherChannel`. |
| + - `TestSubmitIsConfigured`: `IsConfigured(Submit(...))` is true. |
| +- [ ] **Step 2: Run** `go test ./mail/ -run 'TestSubmit|TestFromCarlos'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** the same, then `go test ./mail/ ./carlos/`. Expected: PASS. |
| +- [ ] **Step 5: Commit, push and describe** on the rastrillo hub, with the branch review (Opus) per rastrillo's own process, and merge there. Tag a version for the apps to pin. |
| + |
| +### Task 8: Infra: the operator-armed key file, the IAM user and its policy, the unit install |
| + |
| +**Spec:** decision 2; §5 "Its credential", "What else the mailer's user may do", "The IAM policy"; §9.0; §9 item 4; test 8.9 (IAM half); gaps G5 and G6. |
| + |
| +The unit install itself is Task 3 (bootstrap and system apply carry the units, sysusers and tmpfiles to every box). This task is the IAM, the module inputs and the runbook. |
| + |
| +**Files:** |
| +- Create: `infra/modules/region-host/mailer.tf`, `infra/modules/region-host/tests/mailer.tftest.hcl` |
| +- Modify: `infra/modules/region-host/variables.tf`, `infra/modules/region-host/outputs.tf`, `infra/modules/region-host/README.md` |
| +- Create: `docs/mailer-runbook.md` (arming, rotation, a new group box, disarming, and the name rule below) |
| + |
| +**Interfaces (module inputs and outputs):** |
| +- `variable "mailer"`: `object({ ses_region = string, ses_account_id = string, deployment_bucket_region = string })`, default `null`. Null means no resources: every deployment that has not switched mail submission on. |
| +- With it set (`count = var.mailer == null ? 0 : 1`): |
| + - `aws_iam_user.mailer`: name `carlos-mailer-${data.aws_region.current.name}`, path `/carlos-mailer/`, tags. **No `aws_iam_access_key`**: the key never enters tofu state; the operator creates it (runbook). |
| + - `aws_iam_user_policy.mailer`, name `carlos-mailer`. Two statements: |
| + 1. `ses:SendRawEmail` on `arn:aws:ses:${ses_region}:${ses_account_id}:identity/*` and `…:configuration-set/carlos-*`, with no condition (G5). |
| + 2. `s3:GetObject` on `${deployment_bucket_arn}/apps/*/*/email/senders/*`, `${deployment_bucket_arn}/apps/*/*/instances/*` and `${deployment_bucket_arn}/accounts/*/email/domains/*`. |
| + **No `s3:ListBucket`** (round 1 P2-4): the mailer reads domain records by key, one per granted domain, and never lists. A missing object therefore answers `403`, which Task 5 reads as absent, and absent always refuses. No `s3:PutObject`, no `s3:DeleteObject`, no IAM action, no `ses:SendEmail`. If the deployment bucket is SSE-KMS, add `kms:Decrypt` on its key, conditioned on `kms:ViaService` S3, and say so in the README. |
| + - `output "mailer_user_name"`. |
| +- The host role gains **nothing** (decision 2). The test asserts it. |
| +- `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION` (Task 5's host.env keys) are set from `var.mailer.ses_region` and `var.mailer.deployment_bucket_region` where the module assembles host.env parameters for group boxes. Fixed boxes get them from their operator-written host.env (runbook, operator step 6). |
| +- **The runbook's name rule** (round 1 P3). `IsMailerCaller` believes any bare name `carlos-mailer-*`. Per §9.0, SES reports an assumed role by its **role** name, bare, so a role named `carlos-mailer-x` would be believed too. Creating one needs IAM authority in the SES account, which only operators hold. The runbook states: no IAM user or role named `carlos-mailer-*` may exist in that account except this module's users, and the account's operators check that with `aws iam list-roles` / `list-users` after any IAM change. An SCP or permissions boundary that refuses `iam:CreateRole` on `carlos-mailer-*` is a follow-up for Paul. |
| +- §9 item 4 (the IMDS gate): no change. The group gate admits uid 0 and `carlos` only (`group-init.sh.tftpl:104-117`), so `carlos-mailer` is refused by nft as well as by its unit's `IPAddressDeny`. The fixed-box gate is `scripts/harden-host.sh` in the infra repo. Confirming that it allowlists rather than denylists is an operator check (below), not a change here. |
| + |
| +- [ ] **Step 1: Write the failing runs** (`command = plan`, mock provider, as `console_mail.tftest.hcl`): |
| + - `mailer_off_by_default`: no `aws_iam_user.mailer`. |
| + - `mailer_on`: the user's name and path; the policy's two statements exactly (actions, resources); **no `s3:ListBucket` and no `s3:Put*`**; no access key resource anywhere in the module. |
| + - `host_role_has_no_ses_from_mailer`: with `mailer` set, the host role's rendered policies contain no `ses:SendRawEmail` (the console's `ses:SendEmail` for `console_mail_from` is untouched). |
| + - `group_host_env_has_mail_region`: a group box's host.env parameters carry `CARLOS_MAIL_REGION` and `CARLOS_DEPLOYMENT_REGION`. |
| +- [ ] **Step 2: Run** from `infra/modules/region-host`: `tofu init -backend=false && tofu test -filter=tests/mailer.tftest.hcl`. Expected: the new runs fail. |
| +- [ ] **Step 3: Implement**, and write `docs/mailer-runbook.md`: the operator steps below in full, with exact commands. |
| +- [ ] **Step 4: Run** the same, and `tofu test` for the whole module. Expected: all pass. |
| +- [ ] **Step 5: Census card.** `infra/modules/region-host`'s envelope is re-pinned. `mailer.tf` references no sibling script, so `checkRootExecInputs` needs nothing new (`census_scope_test.go:305-370`). |
| +- [ ] **Step 6: Commit** `infra: carlos-mailer IAM user and policy, no key in state`. |
| +- [ ] **Step 7: Review** (own review: IAM). Astra reviews the card and the policy. Then the **whole-branch review** of the platform branch (Fable), the census proposal (`make census-propose NAME=platform-mail-submission CLAIMS=…`), its other-family approval on #280, and the merge. |
| + |
| +### Task 9: Migration and switch-on for the Oficina apps |
| + |
| +**Spec:** §7 items 2-6. Depends on Tasks 6, 7 and 8 merged, the platform release rolled, and the operator steps done for the boxes that host the app. |
| + |
| +Per app, in this order: **Alta first** (its team runs are what is blocked), then the apps its teams use, then the rest. Only apps that send mail (`carlos email status --app <a>` shows enabled) are in scope. |
| + |
| +**Files (per app repo, on its own branch):** `go.mod` (re-pin `amadan.net/rastrillo/rastrillo` to Task 7's tag), the app's mail wiring (call `mail.FromCarlos` where it builds its mailer, for example `home/internal/home/keys.go:176-194`, `mapa/internal/mapa/config.go:99-116`, `calendar/cmd/calendar/main.go`), its boot refusal (accept the submit channel), and its deploy invocation (`carlos deploy`/`ship … --mail submit`). |
| + |
| +- [ ] **Step 1: Inventory** which Oficina apps send mail and which rastrillo path each pins. estilo and fichas are frozen on `github.com/carlosframework/rastrillo v0.23.0` only, and need the module-path migration first: a separate, known item. |
| +- [ ] **Step 2: Per app** (Sonnet, one brief per app): the re-pin, `FromCarlos`, the boot refusal, and `--mail submit` on deploy. Tests: the app boots with `CARLOS_MAIL=submit` and a socket, and with SMTP only, and refuses with neither. |
| +- [ ] **Step 3: Deploy** each app. It keeps sending over SMTP: no switch is on yet, so no `CARLOS_MAIL` is set. |
| +- [ ] **Step 4: Switch on**: Paul's operator step (below). `carlos email submission on --app <a>` either refuses with the routes or boxes that block it, or switches. |
| +- [ ] **Step 5: Watch** `carlos email status --app <a>` and the event log for 7 days. The reap then happens on its own (Task 6, G4). The rollback is `carlos email submission off --app <a>`. |
| + |
| +--- |
| + |
| +## Operator steps (Paul, by hand, in sequence) |
| + |
| +Nothing below is done by the plan's implementers. Each production change needs Paul's scoped approval first (AGENTS.md, 2026-09-15): account, region, resources, permissions, cost, cleanup. |
| + |
| +1. **Before Task 6 starts (rulings):** rule on G1-G9. G3 (the From variable), G4 (the reap gate) and G6 (group boxes) change what is built. Confirm or correct G9's rate. |
| +2. **Before Task 6 starts (facts):** §9 item 3, whether the tenant association backfill has landed. If any Oficina app sender has a `TenantARN`, the control-plane role needs `ses:ListTenantResources` (G8). That policy is outside this repo. §9 item 2: the Oficina boxes' layout (information only). |
| +3. **Copy review** for Task 6 step 0. |
| +4. **After the platform merge: release and roll.** |
| + - Cut a platform release and push its tag to the GitHub mirror (AGENTS.md "Deploy reality"). |
| + - Roll the platform binary to the fleet through the usual canary, then stable, channel. The roll installs the three mailer units, the `carlos-mailer` user and the two directories on every box. The units stay inactive, because there is no key yet. |
| + - **Deploy the console and restart it**, then check `curl /api/version` reports the new build. The console must attribute mailer events (Task 2) before any mailer send, and must accept `ship --mail` (Task 6) before any app ships with it (round 1 P3). |
| + - **Update your own `carlos` CLI** to the release before any `carlos ship --mail submit` or `carlos email submission`. An old CLI does not know the flag. |
| +5. **Scoped approval, then the IAM user** for each region that hosts Oficina instances, in the deployment that hosts them (the flagship, `carloku-infrastructure`, whose account ran §9.0's spike: confirm). Bump every `?ref=` to the new tag, set `mailer = { ses_region = "eu-west-1", ses_account_id = "<acct>", deployment_bucket_region = "<bucket region>" }` on the region-host module (round 2 P3), then `tofu init -upgrade`, a read plan, and `tofu apply`. It creates one IAM user and one inline policy per region, at no cost. Then, still under the approval: `aws iam create-access-key --user-name carlos-mailer-<region>`. Keep the secret only in your terminal, never in a file in a repo, SSM, the bucket or `user_data`. |
| +6. **Arm each box that hosts the apps' routes** (fixed boxes, and each current group box): |
| + - open an interactive Session Manager shell, **not** Run Command (a Run Command parameter is stored and listable); |
| + - check that session logging will not record the secret; |
| + - **first**, on a fixed box, add `CARLOS_MAIL_REGION=<ses region>` and `CARLOS_DEPLOYMENT_REGION=<bucket region>` to `/etc/carlos/host.env` if they are not there (a group box has them from the module). The key goes in second, because the key is what starts the unit (round 1 P3). If the key goes in first, the mailer refuses to start and restarts every 5 s, the agent answers `503 MAILER_UNAVAILABLE`, and the box reports not armed until the regions are added (`systemctl restart carlos-mailer.service` then picks them up); |
| + - `stty -echo; sudo install -m 0640 -o root -g carlos-mailer /dev/stdin /etc/carlos-mailer/keys; stty echo`, paste `<key-id> <secret> <created RFC 3339>`, then Ctrl-D. The `stty -echo` keeps the secret off the terminal and out of any session transcript. |
| + The `.path` unit starts the socket. Check `systemctl is-active carlos-mailer.socket` and, after the first send, `journalctl -u carlos-mailer`. `carlos email status` shows the box as armed. |
| + On a fixed box, also check the IMDS gate allowlists uids and so refuses `carlos-mailer` (`nft list ruleset`, against `scripts/harden-host.sh`). |
| +7. **New or replaced group boxes** (G6, pending the ruling): until a ruling, each one needs step 6. The `mailer_unarmed@<box>` alert names it. |
| +8. **Check before each switch-on** (round 2 P2-B, G10): every route of the app has an instance record. Compare the hosts the boxes serve for the app (`carlos instances --app <a>` on each box that hosts it; the remote form is a known product gap, AGENTS.md "Operate via API and CLI") with the app's instance records (`carlos instances --app <a>` in API mode). A host served with no record is a hand-made route. Give it a record (adoption), or remove it, before switching on. Otherwise it stops at its next start (G10). |
| +9. **Per app (Task 9 step 4):** `carlos email submission on --app <a>`. Watch for 7 days. The app-level user's reap is automatic. |
| +10. **Rotation** (any time after step 6; runbook): create the second key, arm it on every box in the region (the mailer uses the newer one), confirm every box with `carlos email status` and the journal, then `aws iam delete-access-key` for the old one. |
| + |
| +--- |
| + |
| +## Census cards |
| + |
| +Drafted, pre-build, in `docs/superpowers/notes/census-plan-platform-mail-submission.md`, with one section per task that changes in-scope files (Tasks 1, 3, 4, 5, 6 and 8), in the census-proposal card format, with the CLAIMS text for each unit. At build time, `make census-card` is the authority on which units changed: the builder reconciles the draft against it, writes the CLAIMS file, and runs `make census-propose NAME=platform-mail-submission CLAIMS=<file>`. That writes the real `census-proposal-platform-mail-submission.md`. |
| + |
| +Out of scope, so no card: `internal/mail` and `internal/console` (both outside `go list -deps .` today, and `TestMailerSidePackagesDoNotImportMail` keeps them out), so all of Task 2 and Task 1 apart from `mail_cli.go`; the console halves of Task 6, including the `mailer_unarmed` alert; rastrillo (Task 7); Markdown under `infra/` and `docs/`. **Task 1 is in scope through `mail_cli.go`** (package `.`, `census-base-scope.txt:1493`; round 1 P2-7). |
| + |
| +--- |
| + |
| +## Round 1 findings → changes (rev 2) |
| + |
| +| Finding | Change in this revision | |
| +|---|---| |
| +| **P1-1** a team environment created after switch-on has no From | G3 now covers environments created while switched. Task 6: `mintOwnedEnvironmentMail` delivers `<P>_MAIL_FROM` via `DeliverMailFromIn` and mints nothing; release unsets it; guard 18's walk list gains it. Tests: `TestMintOwnedEnvironmentWhileSwitched` (replaces "is a no-op"), and gate 8.1's golden gains "owned environment created after the flip" | |
| +| **P2-1** G4's gate cannot be computed | Task 2: `CallerClass`, table `mail_caller_sends`, `Store.RecordMailCallerSend` / `MailCallerSends`, tests `TestCallerClass`, `TestMailCallerSendsCounts`, `TestCallerClassIgnoresForgedTags`. Task 6's reap reads `MailCallerSends`. G4 states what the gate proves and what it does not | |
| +| **P2-2** a route with no instance record | Agent-side choice: `CARLOS_MAIL` only when `rt.Provisioned` (Task 4), with a stated residual and a loud log; tested in `TestCarlosMailFollowsTheBind` | |
| +| **P2-3** no stated AWS region | Task 5: `CARLOS_MAIL_REGION` and new `CARLOS_DEPLOYMENT_REGION`, every config from `rootaws.LoadStaticConfig`, `release.NewS3StoreFromConfig`; `TestMailerRefusesWithoutRegion`. Task 8 sets both for group boxes | |
| +| **P2-4** missing objects answer 403 | Task 5: `readAbsentOnDenied`, with absent always refusing and denials logged; `TestMailerReadsAccessDeniedAsAbsent`. Task 8: the `s3:ListBucket` grant is dropped (domains are read by key) | |
| +| **P2-5** the alert has no task | Task 6: `mailerUnarmedSignals` in `internal/console/alertsignals.go`, called from `alertengine_pass.go`, rule kind, level and copy; `TestMailerUnarmedSignal`. In `internal/console`, so no census row | |
| +| **P2-6** empty or unreadable token | Task 4: the existing verbs' `err != nil \|\| want == ""` rule, with a SHA-256 constant-time compare; `TestMailVerbRefusesEmptyToken` | |
| +| **P2-7** Task 1 changes `mail_cli.go` | Task 1 is "+ census", with a census step; Global Constraints, the census section and the census note's Task 1 section are corrected | |
| +| **P2-8** Task 2 is a security gate | Task 2's implementer is Opus | |
| +| P3 operator step 6 | Regions before the key; the unit's failure behaviour is stated (Task 5, operator step 6); `stty -echo` | |
| +| P3 operator step 4 | The console deployed, restarted and version-checked, and Paul's CLI updated, before `ship --mail` | |
| +| P3 Task 2 test reason | Corrected: `carlos-mailer-` never matches the `carlos-mail-` prefix; the converse is pinned too | |
| +| P3 Task 5 file list | `internal/mailwire` (`DomainView` with `TestDomainViewDecodesMailDomain`, the tier default cap) and `mailcounts.go` added | |
| +| P3 role named `carlos-mailer-*` | Task 8 runbook name rule; an SCP or boundary is on the follow-up list | |
| +| P3 census propose per task | Every census-touching task reruns `census-propose` under the same NAME | |
| +| P3 import guard | `TestMailerSidePackagesDoNotImportMail` (Task 4) | |
| + |
| +## Round 2 findings → changes (rev 3) |
| + |
| +| Finding | Change | |
| +|---|---| |
| +| **P2-A** `mail_caller_sends` must join every app-keyed mail list | Task 2: `mailevents.go` `mailAppTables` and the `day` case in `mailAppTimeColumn`; `store_gate.go` row; rename and account-move cases in `TestMailCallerSendsCounts`. Task 6's reap also refuses while the app-level user's name differs from `UserName(acct, app)` | |
| +| **P2-B** `rt.Provisioned` turns a mail gap into an outage for a hand-made route | G10 puts the choice to Paul (family "one working channel", second round); operator step 8 checks every route has a record before switch-on; the `email submission on` copy names the outage | |
| +| P3 operator step 5 | `deployment_bucket_region` added to the `mailer` object | |
| +| P3 `readAbsentOnDenied` | Now `absentOnDeniedStore`, a `release.Store` wrapper, so `provision.GetRecord`'s read is covered too | |
| +| P3 census note | The glued sentence in the rev 2 note is split | |
| + |
| +### P3 follow-up list (does not start a round) |
| + |
| +- An SCP or permissions boundary in the SES account refusing `iam:CreateRole` and `iam:CreateUser` on `carlos-mailer-*`, so the name rule is enforced rather than only stated. |
| +- The door-side answer to P2-2 (a host-to-app map in the box report), if hand-made routes of switched apps turn out to exist. |