docs: instance senders (#148) design and slice 1 plan
Spec docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md (rev 5, approved by Paul 2026-11-30: decision 17, account SES tenant for v1 with follow-up #1546, single-app address grants) after three Astra rounds; slice 1 plan docs/superpowers/plans/2026-11-30-instance-senders-1-own-address.md, Astra READY at round 3. Docs only. Squashed from instance-senders-submission into main.
14 files changed,
+1,616
−0
docs/superpowers/plans/2026-11-30-instance-senders-1-own-address.md+313 −0docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R1.md+97 −0docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R2.md+69 −0docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R3.md+13 −0docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R1.md+61 −0docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R2.md+71 −0docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R3.md+72 −0docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md+417 −0docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R1.md+88 −0docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R2.md+78 −0docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R3.md+44 −0docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R1.md+87 −0docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R2.md+101 −0docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R3.md+105 −0
CI cancelled — superseded by a newer push — run details
CI log
=== gate === go: downloading go1.26.10 (linux/arm64) go version go1.26.10 linux/arm64 opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1 tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz tofu: downloaded, digest verified aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip aws: downloaded, digest verified archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip archive: downloaded, digest verified installed in /tmp/carlos-opentofu-YRrwLT .amadan/test-gate.sh go: downloading github.com/aws/aws-sdk-go-v2 v1.44.0 go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0 go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5 go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0 go: downloading github.com/aws/smithy-go v1.28.1 go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e go: downloading golang.org/x/net v0.62.0 go: downloading modernc.org/sqlite v1.55.0 go: downloading github.com/aws/aws-sdk-go-v2/service/sns v1.43.0 go: downloading github.com/aws/aws-sdk-go-v2/service/acm v1.45.0 go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0 go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2 go: downloading github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.37.0 go: downloading github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1 go: downloading github.com/aws/aws-sdk-go-v2/service/sts v1.45.6 go: downloading golang.org/x/sys v0.49.0 go: downloading golang.org/x/crypto v0.58.0 go: downloading github.com/oschwald/maxminddb-golang v1.13.1 go: downloading github.com/aws/aws-sdk-go-v2/service/sesv2 v1.66.6 go: downloading github.com/pion/logging v0.2.4 go: downloading github.com/pion/stun/v3 v3.1.5 go: downloading github.com/pion/turn/v4 v4.1.4 go: downloading github.com/pierrec/lz4/v4 v4.1.22 go: downloading github.com/prometheus/procfs v0.12.0 go: downloading google.golang.org/protobuf v1.36.10 go: downloading github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.18 go: downloading github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.40 go: downloading github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.38 go: downloading github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23 go: downloading github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.40 go: downloading github.com/aws/aws-sdk-go-v2/service/ssm v1.74.0 go: downloading github.com/klauspost/compress v1.20.2 go: downloading github.com/pion/dtls/v3 v3.1.4 go: downloading github.com/pion/transport/v4 v4.0.2 go: downloading github.com/pion/randutil v0.1.0 go: downloading golang.org/x/text v0.43.0 go: downloading github.com/wlynxg/anet v0.0.5 go: downloading modernc.org/sqlite v1.55.0 go: downloading github.com/klauspost/compress v1.20.2 go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0 go: downloading github.com/pierrec/lz4/v4 v4.1.22 go: downloading modernc.org/libc v1.74.1 go: downloading modernc.org/libc v1.74.1 go: downloading modernc.org/memory v1.11.0 go: downloading github.com/dustin/go-humanize v1.0.1 go: downloading modernc.org/mathutil v1.7.1 go: downloading github.com/google/uuid v1.6.0 go: downloading github.com/google/uuid v1.6.0 go: downloading modernc.org/mathutil v1.7.1 go: downloading github.com/dustin/go-humanize v1.0.1 go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec amadan: job cancelled — a newer push superseded it
diff --git a/docs/superpowers/plans/2026-11-30-instance-senders-1-own-address.md b/docs/superpowers/plans/2026-11-30-instance-senders-1-own-address.md| new file mode 100644 |
| index 000000000..b0b3471f0 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-30-instance-senders-1-own-address.md |
| @@ -0,0 +1,313 @@ |
| +# Instance senders, slice 1: an instance sends as its own address — 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:** In an app switched to submission and to per-instance mode, each instance sends only as the exact addresses granted to its own sender, with its own pause, cap, rate and counts, onboarded by an app backend holding a `mail` service credential. |
| + |
| +**Architecture:** A sender record keyed by `provision.InstanceID(host)` (`Scope: instance`) is chosen by the mailer from the route it already stamps; the app sender carries the per-instance switch and a fail-closed pause so an old mailer refuses rather than sends. Address grants are canonical, single-app-domain, and reserved through one function that keeps every reservation key named on its record. Console doors behind a new `svcrole.Mail` and `carlos email instance|addresses|per-instance` verbs drive it. |
| + |
| +**Tech Stack:** Go, the release store (bucket, CAS by etag), the mail claim gate, SES v2 via the box-local mailer, `clireg`, `parity/parity.tsv`, `docs/site/cli.md`. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md` (revision 5, approved by Paul 2026-11-30). This plan is spec §9 slice 1. Owned domains (slice 2) are out of scope. |
| + |
| +**Review history.** Round 1 (Astra, `a3463409a`): NOT READY, 5 P1s and 4 P2s (`CODEX-FINDINGS-instance-senders-1-R1.md`), all answered in revision 2 (Appendix A). Round 2 (Astra, `f909e67e4`): NOT READY, 2 P1s and 3 P2s (`CODEX-FINDINGS-instance-senders-1-R2.md`). The census-completeness family had a finding in both rounds, so **stopping rule 2 applies**: revision 3 stops enumerating which tasks touch census scope and instead states the invariant and checks it at every task boundary (Global Constraints, "Census"). Revision 3 answers the rest (Appendix B). Round 3 (Astra, `d6d492631`): **READY**, no findings; every round-2 finding resolved (`CODEX-FINDINGS-instance-senders-1-R3.md`). The review stops here (stopping rule 1). |
| + |
| +## Global Constraints |
| + |
| +- AGENTS.md "Build & test" and "Writing Go here": `go build ./...`, `go vet ./...`, `make test`, `gofmt -l .` clean; `make staticcheck` and `make code-health` before push; new CLI commands return errors (no `log.Fatal`); tests wait on signals, never `time.Sleep`; `errors.Is`/`%w`; `apiinstances.go`, `walk.go`, `planmail.go` and `mail_cli.go` get call sites only, logic goes in new files (file/function ratchet). |
| +- Wire shapes are additive: new JSON fields are `omitempty`; records written before this change parse and behave as today. |
| +- Every new `carlos` command: a `docs/site/cli.md` heading and `parity/parity.tsv` row in the same branch; every new console route: a `routeDecls` entry and parity row; `make parity-doc` re-run. |
| +- **Census (stopping rule 2: invariant, one check, every boundary).** *Invariant: every task's tip passes the census.* Which files are in scope is not this plan's to list (the root binary's dependency set decides it, AGENTS.md "What is in scope"; `internal/svcrole` and `services.go` are in it as well as the mail packages). So **every task's last step before its commit** is the same boundary check: run `make census-card`; if it prints any unit or envelope the current proposal does not cover, append one claim line per unit to `docs/superpowers/notes/census-claims-instance-senders-1.tsv` and run `make census-propose NAME=instance-senders-1 CLAIMS=docs/superpowers/notes/census-claims-instance-senders-1.tsv`; then `go test ./internal/provision/ -run 'Plan14|Census' -count=1` passes. Tasks below say "**Boundary check**" for this step. The whole-branch reviewer approves the final card (Task 9). |
| +- **Claim gate.** Every exported mutation runs inside `WithClaimMailResource` + `claimMailAdmitted(ctx, s, acct, claimMailPlan{Apps: []string{app}}, …)` with no `Refresh`. **An expected refusal is decided before the first write** (claim_gate.go:425–427 retains the gate when an admitted call errors after any mutation attempt). Recovery of pending state runs as its **own** admitted call that returns nil, before the call that may refuse. |
| +- **UX and copy before build** (AGENTS.md "Every UI change gets a UX pass"): Task 6 settles every user-facing string and the CLI output layout before Tasks 7 and 8 write code. |
| +- Delegation: each task names its implementer model; per-task Astra review only where marked (stopping rule 3). |
| +- No AWS or production change in Tasks 1–8. Task 9's live verification needs Paul's scoped approval first. |
| +- Exact values: tag `i-` + lowercase unpadded base32 (`a-z2-7`); address ≤ 254 bytes, ASCII, lowercased; ≤ 50 addresses per sender; refusal code `NO_SENDER` (HTTP 403); pause kind `per-instance`; address key `apps/<acct>/<app>/email/addresses/<canonical>.json`, body `{"sender":"<id>"}`. |
| + |
| +## Review Focus |
| + |
| +1. **A From with a display name and different case** (`"Paul" <PAUL@keymail.dev>` against a grant of `paul@keymail.dev`) sends. Tests: Task 1 `TestCheckInstanceFrom`, Task 5 `TestAdmitPerInstanceChoosesRouteSender`. |
| +2. **An address given in a non-canonical form** (`Paul@KeyMail.dev`, spaces, display name, `+tag`, non-ASCII, single-label domain) is stored canonical or refused 400 naming the rule. Tests: Task 1 `TestCanonicalAddress`, Task 7 `TestInstanceSenderDoors`. |
| +3. **Two backend calls creating one instance's sender at once** leave one record, both succeed. Test: Task 4 `TestCreateInstanceSenderIdempotentConcurrent`. |
| +4. **The app's domain losing verification after a grant** refuses `403 FROM_NOT_ALLOWED`. Test: Task 5 `TestAdmitInstanceFromRules`. |
| +5. **An instance deleted and recreated at the same host** while its old sender is `Removing`: create is refused until removal finishes, with copy that says so. Tests: Task 4 `TestCreateRefusals`, Task 7 `TestInstanceDeleteRefusedWithSender`. |
| + |
| +--- |
| + |
| +### Task 1: Wire shapes and pure rules in `mailwire` |
| + |
| +**Implementer:** Sonnet. **Per-task review:** no. |
| + |
| +**Files:** |
| +- Modify: `internal/mailwire/mailwire.go` (fields) |
| +- Create: `internal/mailwire/instance.go`, `internal/mailwire/instance_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `SenderView` gains `Scope string` (`scope,omitempty`), `Host string` (`host,omitempty`), `Removing *time.Time` (`removing,omitempty`), `InstancesPause *Pause` (`instances_pause,omitempty`); `GrantView` gains `Addresses []string` (`addresses,omitempty`). |
| + - `const ScopeInstance = "instance"`. |
| + - `func CanonicalAddress(s string) (string, error)`; errors `ErrAddressSyntax`, `ErrAddressNotASCII`, `ErrAddressTooLong`, `ErrAddressDomain`. |
| + - `func SenderTag(id string) string`; `func SenderFromTag(tag string) (string, bool)`. |
| + - `func CheckInstanceFrom(sn, appSender *SenderView, from, app, region string, dv *DomainView) FromVerdict` — address half; `dv` is the From domain's record. |
| + |
| +- [ ] **Step 1: Failing tests** in `instance_test.go`: |
| + - `TestCanonicalAddress`: `"Paul@KeyMail.example"` → `"paul@keymail.example"`; `" paul@x.example "` → `"paul@x.example"`; `"paul+tag@x.example"` kept; `"\"P\" <paul@x.example>"`, `"a@b@c.example"`, `"paul@"`, `"a, b@c.example"` → `ErrAddressSyntax`; `"pål@x.example"` → `ErrAddressNotASCII`; 255 bytes → `ErrAddressTooLong`; `"paul@x"` (one label) and `"paul@-x.example"` → `ErrAddressDomain`. |
| + - `TestSenderTagRoundTrip`: `SenderTag("app") == "app"`; for `"alice.keymail.example"`, a 40-character host and InstanceID's long form (`"_" + 22 chars + "-" + 16 hex`): tag matches `^i-[a-z2-7]+$`, length ≤ 105, `SenderFromTag` returns `(id, true)`. |
| + - `TestSenderFromTagRejects`: `"i-"`, `"i-!!"`, `"i-"+b32("app")`, `"i-"+b32("a/b")`, `"x-abc"`, `""` → `false`. |
| + - `TestCheckInstanceFrom` (table): grant `["paul@x.example"]`, app sender granted `x.example`, record verified with config set and listing the app → `FromSendable` for `paul@x.example` and `PAUL@X.EXAMPLE`; `FromNotGranted` for `dana@x.example`, for an address present only in the Go test's `Reserving`/`Releasing` list (not in `Grant.Addresses`), and when the app sender lacks the domain; status `pending` → `FromNotVerified`; no config set → `FromNoConfigSet`. |
| + - `TestSenderViewDecodesLegacy`: today's app-sender JSON (a fixture copied from `internal/mail` tests) decodes with the new fields zero. |
| +- [ ] **Step 2: Run** `go test ./internal/mailwire/ -count=1` — FAIL (undefined). |
| +- [ ] **Step 3: Implement** `instance.go`. `CanonicalAddress` order: `TrimSpace`; ASCII check; `net/mail.ParseAddress`, refuse when `Name != ""` or the parsed address is not equal-fold to the trimmed input; length ≤ 254; **lowercase**; then the domain half must match `internal/mail`'s `domainRe` (copied; Task 2 pins them equal). `SenderTag`: `base32.StdEncoding.WithPadding(base32.NoPadding)`, lowercased. `CheckInstanceFrom`: lowercase `from`, require it in `sn.Grant.Addresses`, then `CheckFromDomain(appSender.Grant.Domains, domain, app, region, dv)`. |
| +- [ ] **Step 4: Run** Step 2 — PASS. |
| +- [ ] **Step 5: Boundary check** (Global Constraints, "Census"). |
| +- [ ] **Step 6: Commit** `mailwire: instance sender wire fields, canonical address, sender tag`. |
| + |
| +--- |
| + |
| +### Task 2: The sender model in `internal/mail` |
| + |
| +**Implementer:** Sonnet. **Per-task review:** no. |
| + |
| +**Files:** |
| +- Modify: `internal/mail/sender.go` (fields, `CanSend`, `SenderOfCaller` mailer branch) |
| +- Create: `internal/mail/senders_strict.go`, `internal/mail/sender_instance_test.go`; extend the existing mail↔mailwire pinning test (`grep -rln 'SenderAppID' internal/mail/*_test.go`) |
| +- Test also: `internal/console/sesevents_instance_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1. |
| +- Produces: |
| + - `Sender` gains `Reserving`, `Releasing []string` (`reserving`/`releasing,omitempty`), `Removing *time.Time`, `InstancesPause *mailwire.Pause` (`instances_pause,omitempty`); `GrantBlock` gains `Addresses []string` (`addresses,omitempty`). |
| + - `func ListSendersStrict(ctx, s release.Store, acct, app string) ([]*Sender, error)`, `ErrSenderInventory`. |
| + - `func InstanceSenders(all []*Sender) []*Sender`. |
| + |
| +- [ ] **Step 1: Failing tests:** |
| + - `TestCanSendInstanceSender`: instance sender → true; with `Removing` → false; today's app-sender cases unchanged. |
| + - `TestSenderOfCallerDecodesInstanceTag`: mailer caller, tags with `SenderTag("a.x.example")` → `(acct, app, "a.x.example", true)`; raw `"a.x.example"` tag → false; non-mailer caller with those tags → today's parse result. |
| + - `TestListSendersStrictFailsOnUnreadable`: one unreadable or malformed instance sender → `ErrSenderInventory`; all readable → all, app first. |
| + - Pinning: a `Sender` with every new field marshals and decodes into `mailwire.SenderView` with them intact; mailwire's domain regexp string equals `domainRe`'s. |
| + - `TestEventsChargeOnlyTheTaggedInstance` (console): two instance senders A and B in a switched app; feed `recordAndEnforceMail` Send events tagged `SenderTag(A)` from caller `carlos-mailer-eu-west-1` until A passes `MinSendsForRates`, then Bounce events over `BounceThreshold`: A's record is paused `rate`; B's is not; `mail_sender_counts` rows are keyed `A`. Same events from a non-mailer caller are not charged to A. |
| +- [ ] **Step 2: Run** `go test ./internal/mail/ ./internal/console/ -run 'TestCanSendInstanceSender|TestSenderOfCallerDecodesInstanceTag|TestListSendersStrict|Pin|Parity|TestEventsChargeOnlyTheTaggedInstance' -count=1` — FAIL. |
| +- [ ] **Step 3: Implement.** `CanSend`: add `|| (sn.Scope == ScopeInstance && sn.Removing == nil)`. Mailer branch of `SenderOfCaller`: decode `tags[TagSender]` with `SenderFromTag`. `ListSendersStrict` follows `ListSenders`' order and returns the error instead of skipping. |
| +- [ ] **Step 4: Run** Step 2, then `go test ./internal/mail/ ./internal/console/ -count=1` — PASS. |
| +- [ ] **Step 5: Boundary check.** |
| +- [ ] **Step 6: Commit** `mail: instance sender fields, strict inventory, tag decode`. |
| + |
| +--- |
| + |
| +### Task 3: Address reservations (decisions 6 and 15) |
| + |
| +**Implementer:** Opus. **Per-task review:** Astra (uniqueness of sending authority). |
| + |
| +**Files:** |
| +- Create: `internal/mail/addresses.go`, `internal/mail/addresses_test.go`, `internal/mail/addresses_guard_test.go` |
| +- Modify: `internal/mail/walk.go` — one refusal call each in `claimUnserializedEnsureDomain` (before the app joins `Apps`, before any write) and `claimUnserializedRemoveDomain` (before any write). |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 1–2. |
| +- Produces: |
| + - `func AddressKey(acct, app, canonical string) string`; `const MaxSenderAddresses = 50`. |
| + - `func GrantAddress(ctx, s, acct, app, id, address string, now time.Time) (*Sender, error)`, `func RevokeAddress(ctx, s, acct, app, id, address string, now time.Time) (*Sender, error)`, `func RecoverAddresses(ctx, s, acct, app, id string) (*Sender, error)` — each exported wrapper is one admitted call. `GrantAddress` and `RevokeAddress` first call `RecoverAddresses` (its own admitted call), then make every refusal decision read-only, then write. |
| + - Errors: `ErrAddressTaken`, `ErrAddressDomainShared`, `ErrAddressDomainNotApp`, `ErrTooManyAddresses`, `ErrSenderRemoving` (grant only; revoke and recover are allowed while `Removing`), and `type AddressesInUseError struct{ Domain string; Count int }` with `Is(target error) bool` matching `ErrAddressesInUse`, so a door can name the count (spec decision 13). |
| + - `func preflightGrants(ctx, s, acct, app, id string, canonical []string) error` — every read-only refusal for a whole batch (each address's key, domain record, app sender grant, the limit counted over the batch plus existing grants); shared by `GrantAddress` and Task 4's create. |
| + - `func addressesUseDomain(ctx, s, acct, app, domain string) (int, error)` — grants, reservations and releases on `domain`, from `ListSendersStrict`. |
| + |
| +- [ ] **Step 1: Failing tests** (`addresses_test.go`): |
| + - `TestGrantCanonical`: `"Paul@KeyMail.example"` → `Grant.Addresses == ["paul@keymail.example"]`, key body `{"sender":"<id>"}`, `Reserving` empty. |
| + - `TestGrantTakenRefusedBeforeWrite`: A holds it; B's grant (any case) → `ErrAddressTaken` with **zero** writes by B's call (count on the store fake). |
| + - `TestGrantRefusalsBeforeWrite`: shared domain (`Apps: ["a","b"]`) → `ErrAddressDomainShared`; app sender not granted the domain → `ErrAddressDomainNotApp`; 51st → `ErrTooManyAddresses`; `Removing` → `ErrSenderRemoving`; each with zero writes. |
| + - `TestGateReleasedAfterRefusal`: through the production `ClaimMailStore` wrapper (the gate fakes the console's claim-mail tests use; find them with `grep -rln NewClaimMailStore internal/console/*_test.go`): grant to A, refused grant to B, then another gated mutation (grant a different address to B) succeeds. |
| + - `TestRevokeDeletesOnlyOwnKey`: revoke removes grant and key; a key naming another sender is never deleted. |
| + - `TestDomainChangesRefusedWhileAddressesUse`: app B's `EnsureDomain` of A's address domain, with a grant, only a `Reserving`, or only a `Releasing` → `ErrAddressesInUse`; A's `RemoveDomain` of it → `ErrAddressesInUse`; both with zero writes. |
| +- [ ] **Step 2: The guard** (`addresses_guard_test.go`), `TestAddressReservationInvariant`: seeded `math/rand` (seed printed on failure), two senders, three addresses, random sequences of grant, revoke and recover, with a store wrapper failing the Nth write for every N. After each run: every address key's body names a sender whose record lists the address in `Grant.Addresses`, `Reserving` or `Releasing`, or the key is absent; no address in two records' `Grant.Addresses`; after `RecoverAddresses` on both, `Reserving` and `Releasing` are empty. (Task 4 adds removal to this guard.) |
| +- [ ] **Step 3: Run** `go test ./internal/mail/ -run 'TestGrant|TestGate|TestRevoke|TestDomainChanges|TestAddressReservationInvariant' -count=1` — FAIL. |
| +- [ ] **Step 4: Implement** decision 15 in `addresses.go`. Grant: recover (own call) → read record, domain record, app sender and the address key (read-only) → refuse if any check fails → CAS append to `Reserving` → create-only `Put` of the key (a conflict here, after the read-only check under the gate, is an inconsistency: return it as an error, which correctly retains the gate) → CAS move to `Grant.Addresses`. Revoke: recover → CAS move to `Releasing` → `Get` the key, `DeleteIfMatch` its etag only if it names this sender → CAS remove from `Releasing`. Recover: for each `Reserving` address, finish the grant if the key names this sender, else drop it from `Reserving`; for each `Releasing`, finish the revoke. |
| +- [ ] **Step 5: Run** Step 3, then `go test ./internal/mail/ -count=1` — PASS. |
| +- [ ] **Step 6: Boundary check.** |
| +- [ ] **Step 7: Commit** `mail: address reservations with a stated invariant and guard`. |
| +- [ ] **Step 8: Astra review** of the task diff (brief from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`; stopping rules); findings file beside this plan. |
| + |
| +--- |
| + |
| +### Task 4: Instance sender lifecycle, per-instance mode, plan pause |
| + |
| +**Implementer:** Opus. **Per-task review:** Astra (production storage and the mode switch). |
| + |
| +**Files:** |
| +- Create: `internal/mail/instancesender.go`, `internal/mail/perinstance.go`, `internal/console/planmail_instance.go`, tests `internal/mail/instancesender_test.go`, `internal/mail/perinstance_test.go`, `internal/console/planmail_instance_test.go` |
| +- Modify (call sites only): `internal/mail/submission.go` (`claimUnserializedSwitchOff`: strict-inventory refusal before any write), `internal/mail/walk.go` (`claimUnserializedTeardown`: instance senders first), `internal/console/planmail.go` (one call at the top of the per-app loop, before `free`), `internal/mail/addresses_guard_test.go` (removal joins the guard) |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 2–3. |
| +- Produces: |
| + - `func CreateInstanceSender(ctx, s, acct, app, host string, addresses []string, actor string, now time.Time) (*Sender, error)` — idempotent; requires only `Switched` app sender (spec decision 1), **not** per-instance mode, so a backend creates every sender before turning the mode on. Errors `ErrSubmissionOff`, `ErrSenderRemoving`, and every `preflightGrants` refusal. **Admission contract:** recovery of an existing record (if any) is its own admitted call; then one admitted call canonicalises every address, runs `preflightGrants` over the **whole batch** and the `Removing`/submission checks, all read-only, and only then writes (the record create, then each grant's reserve → key → grant). A refusal is therefore never returned after a write in that call. |
| + - `func SetInstanceSenderCap(ctx, s, acct, app, host string, dailyCap int, actor string, now time.Time) (*Sender, error)` — CAS on the instance sender's `Grant.DailyCap` alone (addresses, pending lists and pause preserved); operator-only through the pause door. |
| + - `func RemoveInstanceSender(ctx, s, acct, app, host string, now time.Time) error` — CAS `Removing` (if not set) → `RecoverAddresses` → `RevokeAddress` for every grant → strict check that `Grant.Addresses`, `Reserving` and `Releasing` are empty → `DeleteIfMatch` the record. Idempotent; absent record is success. |
| + - `func SetPerInstance(ctx, s, acct, app string, on bool, actor string, now time.Time) (*Sender, error)` — on: requires `Switched` and `Submission.AppUserReapedAt != nil` (`ErrAppUserNotReaped`); one CAS sets `PerInstance` and `Pause{Kind: PauseKindPerInstance, At: now}`. Off: `ListSendersStrict` must succeed and hold no instance sender (`ErrInstanceSendersExist`); one CAS clears both. Refusals before any write. |
| + - `func SetInstancesPause(ctx, s, acct, app string, p *mailwire.Pause) error` (nil clears). |
| + - `func HasInstanceSender(ctx, s, acct, app, host string) (bool, error)`. |
| + - Console: `func (s *Server) planPausePerInstanceApp(ctx context.Context, acct *Account, app string, kind string, now time.Time) (handled bool, err error)` — reads the app sender **first**; when `PerInstance`, writes `InstancesPause` (or leaves it if already the day's), audits, and returns `handled = true` so the loop skips sender enumeration for that app. The resume path clears it under `planMailSpent`. |
| + |
| +- [ ] **Step 1: Failing tests:** |
| + - `TestCreateInstanceSenderIdempotentConcurrent`: two goroutines released by one channel create one host → one record, both return it, `ID == provision.InstanceID(host)`, `Scope == ScopeInstance`, `Host == host`. |
| + - `TestCreateRefusals`: submission off → `ErrSubmissionOff`; `Removing` → `ErrSenderRemoving`; per-instance off → allowed. |
| + - `TestCreateWithTakenAddressesReleasesGate` (production `ClaimMailStore` wrapper): a new sender whose only address is taken, and a new sender whose **second** address is taken, are each refused with zero writes (no record, no key); afterwards another gated mutation succeeds. |
| + - `TestSetInstanceSenderCap`: changes only that sender's cap; its addresses, pending lists and pause, the app sender and a sibling are byte-identical. |
| + - `TestRemoveFromEveryInterruptedState`: start removal from a sender left with (a) an address only in `Reserving` with its key written, (b) only in `Reserving` without a key, (c) in `Releasing` with the key, (d) in `Releasing` without it, and (e) with a failure injected at each of removal's own writes then re-run: afterwards no record and no address key. |
| + - Guard extension: `TestAddressReservationInvariant` adds `RemoveInstanceSender` to its random operations; the invariant also requires no key whose sender record is absent. |
| + - `TestSetPerInstance`: on is one Put setting both fields; refused before `AppUserReapedAt`; off refused with an instance sender and with an unreadable one (`ErrSenderInventory`); off clears both. |
| + - `TestSwitchOffRefusedWithInstanceSenders`: `ErrInstanceSendersExist`, and `ErrSenderInventory` when one is unreadable; zero writes. |
| + - `TestTeardownRemovesInstanceSenders`: no instance sender or address key remains; an unreadable instance sender fails teardown. |
| + - `TestResumeAppSenderRefusedPerInstance`: `ErrPerInstance` (regression). |
| + - `TestPlanPausePerInstanceApp` (console): an app put in per-instance mode by a real `mail.SetPerInstance`, with one instance sender whose key the store fake fails to read; the account reaches its plan limit → the app sender's `InstancesPause.Kind == PauseKindPlan`; **no** write to any instance sender; `resumePlanMail` with the allowance free clears it. |
| +- [ ] **Step 2: Run** `go test ./internal/mail/ ./internal/console/ -run 'TestCreateInstanceSender|TestCreateRefusals|TestRemoveFromEveryInterruptedState|TestAddressReservationInvariant|TestSetPerInstance|TestSwitchOffRefused|TestTeardownRemovesInstanceSenders|TestResumeAppSender|TestPlanPausePerInstanceApp' -count=1` — FAIL. |
| +- [ ] **Step 3: Implement** as the Interfaces say. |
| +- [ ] **Step 4: Run** Step 2, then `go test ./internal/mail/ ./internal/console/ -count=1` — PASS. |
| +- [ ] **Step 5: Boundary check.** |
| +- [ ] **Step 6: Commit** `mail: instance sender lifecycle and per-instance mode`. |
| +- [ ] **Step 7: Astra review** as in Task 3. |
| + |
| +--- |
| + |
| +### Task 5: The mailer chooses the instance's sender |
| + |
| +**Implementer:** Opus. **Per-task review:** Astra (security gate), with the census card. |
| + |
| +**Files:** |
| +- Modify: `internal/mailer/policy.go` (`admit`, `decision`, sender cache by id), `internal/mailer/ses.go` (tenant and tag from `decision`), `internal/mailsubmit/proto.go` (`CodeNoSender = "NO_SENDER"`) |
| +- Create: `internal/mailer/policy_instance_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1; Task 4's `mail.SetPerInstance` (test-only, to produce the app sender's JSON). |
| +- Produces: `decision` gains `senderID string` and `tenant string` (from the **app** sender: `mailwire.TenantName(acct)` when the app sender's `TenantARN != ""`); `func (m *Mailer) senderByID(ctx, acct, app, id string, now time.Time) (*mailwire.SenderView, error)`; rate and counter key `acct + "/" + app + "/" + senderID`; tag `mailwire.SenderTag(senderID)`. |
| + |
| +- [ ] **Step 1: Failing tests** (existing harness, fake SES): |
| + - `TestAdmitPerInstanceChoosesRouteSender`: app sender per-instance (written by `mail.SetPerInstance` on a mem store); A granted `paul@x.example`; message from A as `"Paul" <PAUL@x.example>` is sent with tag `SenderTag(A)`, `TenantName` = account tenant, counter key `acct/app/<A>`. |
| + - `TestAdmitPerInstanceNoFallback`: host with no record, record `Host` ≠ stamp, `Removing`, empty `Scope` → 403 `NO_SENDER`, zero SES calls. |
| + - `TestAdmitInstanceFromRules`: `dana@x.example` → 403 `FROM_NOT_ALLOWED`; A as B's address → 403; domain record flipped to `pending` → 403 `FROM_NOT_ALLOWED`. |
| + - `TestAdmitInstancePauses`: instance sender paused → 429 `PAUSED`; app sender `InstancesPause` → 429 `PAUSED`; the app sender's per-instance pause is not read for an instance. |
| + - `TestAdmitRateAndCapPerInstance`: A exhausts its rate burst (`Burst` = 20) → 429 `RATE` for A while B sends; A at its cap → 429 `CAP_REACHED` while B sends. |
| + - `TestPreInstanceAdmitFailsClosed`: a test-local `admitPreInstance` performing today's steps 2–3 (read app sender, `EffectivePause`) on the JSON `SetPerInstance` wrote → 429 `PAUSED`. |
| + - Every existing `internal/mailer` test passes unchanged (app-sender path byte-for-byte as today). |
| +- [ ] **Step 2: Run** `go test ./internal/mailer/ ./internal/mailsubmit/ -count=1` — new tests FAIL. |
| +- [ ] **Step 3: Implement** spec §6 steps 2, 3, 5, 6, 7. |
| +- [ ] **Step 4: Run** Step 2 — PASS. |
| +- [ ] **Step 5: Boundary check** (claims for the mailer: "admit reads one more sender record by key under the existing read grant; no new read class"). |
| +- [ ] **Step 6: Commit** `mailer: per-instance senders chosen by the stamped route`. |
| +- [ ] **Step 7: Astra review** of the diff and card (AGENTS.md "Getting a change approved"); record the verdict on #280. |
| + |
| +--- |
| + |
| +### Task 6: Copy and CLI output, before any door or verb is built |
| + |
| +**Implementer:** Sonnet (drafting); the session runs the reviews. **Per-task review:** the copy review is the gate. |
| + |
| +**Files:** |
| +- Create: `internal/console/mailinstance_copy.go` (one struct, `mailInstanceCopy`, every door message), `docs/superpowers/notes/instance-senders-cli-output.md` (the output mock) |
| + |
| +- [ ] **Step 1: Draft** every door message (each 409 listed in Task 7, the 400 per `CanonicalAddress` error, the instance-delete refusal "remove its email sender first: carlos email instance rm --app <a> --host <h>", and the `domains rm`/`domains add` refusal naming how many instance addresses use the domain), the `mail` role's line in `carlos services` help (the three role lists in `services.go:37,175–176`), into `mailInstanceCopy` and the notes file, and mock in the notes file: `carlos email instance status` and the per-instance lines of `carlos email status`, in each state (sending, paused with kind, held by the app's plan pause, removing, pending addresses). |
| +- [ ] **Step 2: UX pass** on the mock: state first (`sending` / `paused (cap)` / `held (plan)` / `removing`), then addresses, then today's sent and bounced; readable in about a dozen words; fix and re-mock. |
| +- [ ] **Step 3: Copy review** with the `copy-review` skill over the struct, the mock and the `cli.md` prose Task 8 will add (drafted here in the notes file); apply edits verbatim. |
| +- [ ] **Step 4: Boundary check** (normally nothing: copy struct is console-only). |
| +- [ ] **Step 5: Commit** `email: instance sender copy and CLI output, reviewed`. |
| + |
| +--- |
| + |
| +### Task 7: The `mail` role and the console doors |
| + |
| +**Implementer:** Opus. **Per-task review:** Astra (a new role and doors). |
| + |
| +**Files:** |
| +- Modify: `internal/svcrole/svcrole.go` (`Mail Role = "mail"` in the catalogue, inside Admin's union, doc comment), `services.go` (the three role lists at `:37` and `:175–176`, with Task 6's approved wording), `internal/console/routedecls.go`, `internal/console/svcroutes_test.go`, `internal/console/apiinstances.go` (one call in `handleAPIInstanceDelete` after the shape check), `internal/console/apimail.go` (`handleAPIEmailPause`: optional `host` routing both pause and `daily_cap` to the instance sender via `SetSenderPausedIf`/`SetInstanceSenderCap`; `handleAPIEmailDomainRemove` and `handleAPIEmailDomainEnsure`: map `AddressesInUseError` to 409 with the count; `emailReply` sender entries: additive fields), `parity/parity.tsv` |
| +- Create: `internal/console/apiinstancesender.go`, `internal/console/apiinstancesender_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 2–4, 6 (`mailInstanceCopy`). |
| +- Produces routes (`Kind: kindCLI`, `Allow: svcrole.Allow(svcrole.Mail)` unless stated): |
| + - `POST /api/cli/apps/{account}/{app}/instances/{host}/email` → `handleAPIInstanceSenderCreate`, body `{"addresses":[...]}`. |
| + - `GET …/instances/{host}/email` → `handleAPIInstanceSenderStatus`. |
| + - `DELETE …/instances/{host}/email` → `handleAPIInstanceSenderRemove`. |
| + - `PUT …/instances/{host}/email/addresses/{address}` → `handleAPIInstanceAddressGrant`; `DELETE` same path → `handleAPIInstanceAddressRevoke`. |
| + - `POST /api/cli/apps/{account}/{app}/email/per-instance` `{"on": bool}` → `handleAPIEmailPerInstance`, `Allow: svcrole.Allow(svcrole.Admin)`. |
| + - Reply type (console): `type apiInstanceSenderReply struct { Host string \`json:"host"\`; ID string \`json:"id"\`; Addresses []string \`json:"addresses"\`; Pending []string \`json:"pending,omitempty"\`; Removing *time.Time \`json:"removing,omitempty"\`; State string \`json:"state"\`; Pause *mailwire.Pause \`json:"pause,omitempty"\`; DailyCap int \`json:"daily_cap"\`; Counts map[string]int \`json:"counts"\` }` — `Counts` keys exactly the existing sender entries' (`sends`, `bounces`, `complaints`, `rejects`, `deliveries`); `State` is one of `sending`, `paused`, `held`, `removing` (`held` = the app sender's `InstancesPause`). |
| + - `emailReply`'s existing `senders` entries gain, for instance senders only, `addresses`, `pending`, `removing`, `state`, and `active = state == "sending"` (instance senders hold no credential, so today's `Provisioned != nil` rule would read every one as paused; the app-sender entry keeps today's `active`). |
| + - Status codes: 404 unknown account/app/instance (today's bytes); 400 bad address (copy per error); 409 for `ErrAddressTaken` (neutral copy), `ErrAddressDomainShared`, `ErrAddressDomainNotApp`, `ErrTooManyAddresses`, `ErrSenderRemoving`, `ErrSubmissionOff`, `ErrInstanceSendersExist`, `ErrAppUserNotReaped`, `ErrSenderInventory` (502, "could not read every sender — try again"); 409 on instance delete with a sender. |
| + |
| +- [ ] **Step 1: Failing tests:** |
| + - `svcroutes_test.go`: `mail` reaches exactly the five instance-sender doors; `instance`, `operate`, `publish`, `deploy`, `service`, `usage` refused on them; Admin reaches them; `mail` refused on `email/pause`, `email/per-instance`, `email/events`, `email/credentials`, `email/submission` and every non-email door. |
| + - `TestInstanceSenderDoors`: create with `["Paul@x.example"]` → 200, `addresses: ["paul@x.example"]`, `state: "sending"`; `"pål@x.example"` → 400 with the not-ASCII copy; taken address → 409 neutral copy; remove → 200, status → 404. |
| + - `TestInstanceDeleteRefusedWithSender`: 409 with the copy; recreate at the host while `Removing` → 409 `ErrSenderRemoving` copy; after removal finishes, instance delete proceeds. |
| + - `TestMailWriteBudgetServicePrincipal`: a `mail` service principal is metered by `allowWrite` (`svcprincipal.go:855`), not the person budget. |
| + - `TestEmailPauseHost`: with `host`, pause-only, cap-only, and pause plus cap each change only that instance sender; the app sender and a sibling are byte-identical. |
| + - `TestDomainRemoveRefusedForInstanceAddresses`: `domains rm` of a domain with an instance grant, with only a reservation, and with only a release → 409 whose body names the count; `domains add` of that domain by another app → 409 likewise. |
| + - `TestServicesHelpNamesEveryRole` (root package, existing) passes with `mail` in the catalogue. |
| + - `TestEmailStatusInstanceEntries`: `GET …/email` keeps every top-level field; an unpaused instance sender's entry has `active: true`, `state: "sending"`; one held by `InstancesPause` has `state: "held"`, `active: false`. |
| + - `TestInstanceSenderWritesClassifyToApp`: every bucket write by create, grant, revoke and remove, captured through the production `ClaimMailStore` wrapper, classifies (`hostops.ClassifyMutation`) to exactly `{(account, app)}`. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ ./internal/svcrole/ -run 'Svc|Role|TestInstanceSender|TestInstanceDelete|TestMailWriteBudget|TestEmailPauseHost|TestEmailStatusInstance|TestDomainRemoveRefused|Classify' -count=1 && go test . -run TestServicesHelpNamesEveryRole -count=1` — FAIL. |
| +- [ ] **Step 3: Implement.** Handlers: `apiAccountApp`; `provision.ValidHostShape(host)`; instance record required at create only; path addresses through `mailwire.CanonicalAddress` first; calls through `s.claimMailStore()`; the write budget chooses `allowWrite` for a service principal (`principalFrom(ctx)`), the person budget otherwise. |
| +- [ ] **Step 4: Parity rows** for the six routes; `make parity-doc`. |
| +- [ ] **Step 5: Run** Step 2, then `go test ./internal/console/ ./internal/svcrole/ -count=1` — PASS. |
| +- [ ] **Step 6: Boundary check** (`internal/svcrole` and `services.go` are in census scope). |
| +- [ ] **Step 7: Commit** `console: mail role and instance sender doors`. |
| +- [ ] **Step 8: Astra review** as in Task 3. |
| + |
| +--- |
| + |
| +### Task 8: CLI verbs and docs |
| + |
| +**Implementer:** Sonnet. **Per-task review:** no. |
| + |
| +**Files:** |
| +- Create: `mail_instance_cli.go`, `mail_instance_cli_test.go` |
| +- Modify: `mail_cli.go` (clireg nodes only: `instance` → `create|status|rm`, `addresses` → `add|rm`, `per-instance` → `on|off`; `--host` on `pause`/`resume`; usage text), `docs/site/cli.md`, `parity/parity.tsv` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 7 routes and JSON; Task 6's approved output and prose. |
| +- Produces: CLI wire types in `mail_instance_cli.go` — `apiInstanceSender` (decoding `apiInstanceSenderReply`'s JSON names exactly) and additive fields on `mail_cli.go`'s `apiEmailSender` (`Addresses`, `Pending`, `Removing`, `State`); `runEmailInstance{Create,Status,Rm}`, `runEmailAddresses{Add,Rm}`, `runEmailPerInstance(args []string, on bool)`, all `func(args []string) error`; `printInstanceSender(w io.Writer, s apiInstanceSender)`. `carlos email status` renders an instance sender's line from `State` (falling back to today's `Active` rendering when `State` is empty, for an older console). |
| + |
| +- [ ] **Step 1: Failing tests:** golden output of `printInstanceSender` and of `carlos email status` per state, exactly Task 6's approved mock; an end-to-end test from an `httptest` console reply through `runEmailStatus`'s printer (an unpaused instance sender prints `sending`, not paused); flag parsing (`--app`, `--host` required; address required for `addresses add|rm`); a 409 prints the door's message and returns an error; `internal/docsite` and parity tests fail before the headings exist. |
| +- [ ] **Step 2: Run** `go test . ./internal/docsite/ -run 'Instance|Addresses|PerInstance|EmailStatus|Docsite|Parity' -count=1` — FAIL. |
| +- [ ] **Step 3: Implement** the verbs; add `docs/site/cli.md` headings for `carlos email instance`, `carlos email addresses`, `carlos email per-instance`, and `--host` on `pause`/`resume`, with Task 6's approved prose and one fenced example each. |
| +- [ ] **Step 4: Boundary check.** |
| +- [ ] **Step 5: Run** Step 2 and `make parity-doc && git diff --exit-code parity/` — PASS. |
| +- [ ] **Step 6: Commit** `carlos email: instance, addresses and per-instance verbs`. |
| + |
| +--- |
| + |
| +### Task 9: Gate, whole-branch review, land, roll, verify |
| + |
| +**Implementer:** the session (Opus). **Review:** Astra, whole branch. |
| + |
| +- [ ] **Step 1: Full local gate** once: `go build ./... && go vet ./... && make test && gofmt -l . && make staticcheck && make code-health && make race` — clean. |
| +- [ ] **Step 2: Final census card.** `make census-card` shows nothing beyond the proposal; if it does, re-run `make census-propose` with the claims file; commit. |
| +- [ ] **Step 3: Push**; `amadan ci status carlos/platform -branch <branch>` exits 0. |
| +- [ ] **Step 4: Whole-branch Astra review**, including the final census card (template; stopping rules); record the census verdict on #280. |
| +- [ ] **Step 5: Land** with `amadan branch merge carlos/platform <branch> -squash -expect <tip> -message "…"`; read `main`'s CI. |
| +- [ ] **Step 6: Roll** console and agents by the routine roll (AGENTS.md "Deploy reality"); confirm the boxes hosting the verification app run the new mailer. |
| +- [ ] **Step 7: Ask Paul for scoped approval** of the live check, stating: deployment and account, region, the verified domain used, sends to the SES mailbox simulator only, the throwaway app's lifetime (from preparation to teardown, at least seven days because per-instance mode needs the app-level user reaped: `internal/mail/sweep.go:90–109`), and cleanup. Preparation once approved: create the app, `submission on`, run its daily sends through submission until the reap. |
| +- [ ] **Step 8: Verify** after the reap: `per-instance on`; `instance create` for hosts A and B with one address each; from A as A's address (delivered to the simulator), as B's (`403 FROM_NOT_ALLOWED`), from a host with no sender (`403 NO_SENDER`); `carlos email status` shows one `sending` line per instance with its count. Tear the app down; record the transcript on the branch; reply on #148; update the spec's status line. |
| + |
| +--- |
| + |
| +## Appendix A — plan review round 1 (Astra, `a3463409a`) |
| + |
| +| Finding | Answer | |
| +|---|---| |
| +| P1-1 a refusal after a write retains the claim gate | Global Constraints "Claim gate"; Task 3: refusals read-only before any write, recovery its own admitted call; `TestGrantTakenRefusedBeforeWrite`, `TestGateReleasedAfterRefusal` | |
| +| P1-2 plan-pause branch unreachable behind the pause predicate | Task 4 `planPausePerInstanceApp` runs first in the per-app loop; test uses a real `SetPerInstance` and an unreadable instance sender | |
| +| P1-3 removal recovers after its release pass | Task 4 `RemoveInstanceSender`: recover → revoke all → strict empty check → delete; revoke and recover allowed while `Removing`; `TestRemoveFromEveryInterruptedState`; removal joins the guard | |
| +| P1-4 canonicalisation order and invalid fixtures | Task 1: lowercase before the domain rule; fixtures use `x.example`; single-label is its own refusal (`ErrAddressDomain`) | |
| +| P1-5 census card stale before the final gate | Global Constraints "Census": Tasks 1, 5, 8 each re-propose; Task 9 Step 2 final card, reviewed in Step 4 | |
| +| P2-6 response and CLI types | Task 7 `apiInstanceSenderReply` and additive sender-entry fields with `state`/`active`; Task 8 CLI decoding types and the end-to-end status test | |
| +| P2-7 isolation guards lacking cases | Task 2 `TestEventsChargeOnlyTheTaggedInstance`; Task 1 pending addresses not sendable; Task 4 submission-off strict inventory; Task 5 rate isolation; Task 4 guard includes removal | |
| +| P2-8 UX and copy after build | New Task 6 before the doors and the CLI | |
| +| P2-9 verification needs a reaped app and scoped approval | Task 9 Steps 7–8 | |
| + |
| +## Appendix B — plan review round 2 (Astra, `f909e67e4`) |
| + |
| +| Finding | Answer | |
| +|---|---| |
| +| P1-1 adding `mail` breaks `TestServicesHelpNamesEveryRole` | Task 6 drafts the `services.go` role-list wording; Task 7 changes `services.go` and runs the test | |
| +| P1-2 census fails at Task 7's tip (census family, second round: **rule 2**) | No more per-task enumeration: Global Constraints "Census" states the invariant and puts one boundary check at the end of every task | |
| +| P2-3 create-with-addresses admission contract | Task 3 `preflightGrants` over the whole batch; Task 4 create's admission contract; `TestCreateWithTakenAddressesReleasesGate` | |
| +| P2-4 `domains rm` refusal never reaches its HTTP contract | `AddressesInUseError{Domain, Count}`; Task 6 copy; Task 7 maps it to 409 in `domains rm` and `domains add`; `TestDomainRemoveRefusedForInstanceAddresses` | |
| +| P2-5 instance cap changes unspecified | Task 4 `SetInstanceSenderCap`; Task 7 routes `host` + `daily_cap`; `TestSetInstanceSenderCap`, `TestEmailPauseHost` | |
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R1.md b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R1.md| new file mode 100644 |
| index 000000000..16c03c935 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R1.md |
| @@ -0,0 +1,97 @@ |
| +# Review findings: instance senders slice 1 plan, round 1 (Astra, gpt-6-astra, on a3463409a) |
| + |
| +Reviewed `a3463409a81e87a1e66702d473cb398a0fc05c74` against the approved spec and unchanged code from `43dce353f`. No files changed, subagents spawned, or tests run. |
| + |
| +Paths below are repository-relative. “Plan” means `docs/superpowers/plans/2026-11-30-instance-senders-1-own-address.md`. |
| + |
| +1. **P1 — Task 3: an ordinary address conflict retains the shared mail gate.** |
| + |
| + **Evidence:** Plan:129 prescribes writing `Reserving`, attempting the occupied key, clearing `Reserving`, then returning `ErrAddressTaken`. `internal/mail/claim_gate.go:425–427` retains the gate whenever an admitted call returns an error after any mutation attempt; lines 463–465 explicitly leave it held for reconciliation. |
| + |
| + **Failure scenario:** Sender A owns an address. Sender B requests it. Even with successful cleanup, B’s expected 409 leaves the shared gate retained and blocks subsequent gated mail work. |
| + |
| + **Fix:** Specify how expected business refusals complete without retaining an uncertain operation. Preflight ownership under the gate before mutation, and handle any recovered or partially completed work explicitly. Add a production-wrapper test that grants to A, refuses B, then successfully performs another gated mutation. |
| + |
| + **Invariant:** A normal uniqueness refusal must not strand the shared mutation gate. |
| + |
| +2. **P1 — Task 4: the prescribed plan-pause branch is unreachable for a normally switched app.** |
| + |
| + **Evidence:** Plan:150 sets `PauseKindPerInstance`; Plan:165 instructs replacing the branch at `planmail.go:105`. But `internal/console/planmail.go:88–90,102–103` skips any sender whose existing pause is neither absent nor an hourly hold. The permanent per-instance pause therefore skips the new branch. The remaining loop still pauses individual instance senders at line 109. |
| + |
| + **Failure scenario:** The account reaches its plan limit. `InstancesPause` is never written; readable instance senders receive individual pauses, while an unreadable sender skipped by `ListSenders` can continue sending. This also fails Plan:163’s “no per-instance-sender pause writes” assertion. |
| + |
| + **Fix:** Read and handle the app sender’s per-instance mode before the ordinary pause predicate and sender enumeration. Write the app-level hold and skip individual plan-pause writes for that app. Test with a real `SetPerInstance` result and an injected instance-sender read failure. |
| + |
| + **Invariant:** Account plan enforcement reaches every instance independently of instance inventory completeness. |
| + |
| +3. **P1 — Task 4: removal recovers pending grants after its release pass.** |
| + |
| + **Evidence:** Plan:149 orders removal as `Removing` → revoke every grant → recover → delete record. Plan:129 defines reservation recovery as completing the transition into `Grant.Addresses`. |
| + |
| + **Failure scenario:** A failed grant leaves an address in `Reserving`, with its reservation key already present and no completed grant. Removal’s grant loop is empty. Recovery completes the grant, then removal deletes the sender record, leaving the address key without its owning record. |
| + |
| + **Fix:** Recover pending transitions before enumerating addresses to release, then drain all grants and pending state before deleting the record. Explicitly permit cleanup while `Removing` is set; Plan:126’s blanket refusal currently leaves that ambiguous. Test removal starting from each interrupted grant/revoke state, not only failures during removal itself. |
| + |
| + **Invariant:** Every owned address key remains named on an existing sender record until the key is gone. |
| + |
| +4. **P1 — Tasks 1 and 6: canonicalization instructions and success fixtures contradict domain validation.** |
| + |
| + **Evidence:** Plan:60 applies the copied domain regexp before `strings.ToLower`. `internal/mail/domain.go:81–84` accepts lowercase domains only and requires at least two labels. Plan:52 nevertheless requires `Paul@KeyMail.dev` to succeed; Plan:222 requires `Paul@x` to return 200. |
| + |
| + **Failure scenario:** Following Task 1 literally rejects its mixed-case success case. Task 6’s single-label success fixture remains invalid even after fixing case normalization. |
| + |
| + **Fix:** Validate the lowercased domain after checking ASCII and address syntax. Use a valid domain such as `x.example` in successful door fixtures. Keep uppercase-domain and single-label rejection cases as separate tests. |
| + |
| + **Invariant:** Canonicalization accepts equivalent valid addresses and consistently rejects invalid domains. |
| + |
| +5. **P1 — Tasks 5–8: the census card becomes stale before the final gate.** |
| + |
| + **Evidence:** Plan:194 generates the card in Task 5. Task 7 subsequently creates `mail_instance_cli.go` and modifies root-package `mail_cli.go` at Plan:242–243. No later step refreshes the proposal before Task 8’s full gate. `internal/provision/plan14_root_reads_test.go:677–679` reports changed source envelopes, and lines 700–713 fail the census on those discrepancies. |
| + |
| + **Failure scenario:** Task 5’s census passes, Task 7 changes the root source envelope, and Task 8’s `make test` fails before the branch can reach review or merge. |
| + |
| + **Fix:** Refresh the census proposal after the last in-scope change, before the final gate, and have the whole-branch reviewer approve that final card. State which intermediate task commits are expected to pass the census. |
| + |
| + **Invariant:** Census approval and fingerprints describe the actual branch tip. |
| + |
| +6. **P2 — Tasks 6–7: the response and CLI integration contracts need correction.** |
| + |
| + **Evidence:** Plan:217 calls `apiMailCounts` an existing type; no Go declaration exists. The CLI has `apiEmailCounts` at `mail_cli.go:302`, while console counts use `MailCounts` at `internal/console/mailcounts.go:24`. Task 7 also consumes Task 6’s unexported console `apiInstanceSender` without specifying a CLI wire type. Finally, `emailReply` already returns `senders` at `apimail.go:503`; its entries use `counts` and credential-based `active` at lines 448–459. Existing CLI rendering interprets `active:false` as paused (`mail_cli.go:1601–1621,1635`). |
| + |
| + **Failure scenario:** Implementers must invent missing types and reconciliation between `today` and `counts`. Leaving the existing status path unchanged displays an unpaused instance sender as paused because it has no `Provisioned` credential. |
| + |
| + **Fix:** Define console response types and separate CLI decoding types explicitly. Extend the existing sender entries additively, and specify rendering for instance senders, removal, addresses, and effective app-level holds. Test the complete API-to-`email status` path. |
| + |
| + **Invariant:** Public status accurately represents sending state and preserves existing response fields. |
| + |
| +7. **P2 — Tasks 1–5: several required isolation guards lack distinguishing cases.** |
| + |
| + **Evidence:** Plan:159–163 covers an unreadable inventory for per-instance-off and teardown, but not submission-off or continued plan enforcement. Plan:189 names rate and cap isolation but specifies only a cap case. Plan:85–86 tests `CanSend` and tag decoding without proving encoded events count and trigger bounce enforcement against only their sender. Plan:55 omits addresses held only in `Reserving` or `Releasing`. |
| + |
| + **Failure scenario:** A regression can pass the listed tests while submission-off uses best-effort inventory, rate buckets remain shared, event attribution pauses a sibling, or pending addresses become sendable. |
| + |
| + **Fix:** Add those explicit cases, including production event ingestion and two-sender enforcement assertions. Extend the reservation guard to invoke the actual Task 4 removal operation once available. |
| + |
| + **Invariant:** Decisions 10, 15 and 16 are proved at their enforcement points, not only through helper tests. |
| + |
| +8. **P2 — Tasks 6–7: UX and copy review occur after the doors are built and reviewed.** |
| + |
| + **Evidence:** Task 6 implements, commits and reviews door strings at Plan:229–233. Their copy review occurs only at Plan:253. Task 7 likewise writes output goldens and docs before that review. AGENTS.md requires the UX pass before review or build and copy review in the intended layout. |
| + |
| + **Failure scenario:** Task 6 ships its implementation to security review with unreviewed user-facing language; subsequent copy changes can invalidate output assertions. |
| + |
| + **Fix:** Move the UX and copy-review prerequisites ahead of the affected implementation tasks, then build tests from approved copy. |
| + |
| + **Invariant:** User-facing changes follow the required UX → copy approval → implementation order. |
| + |
| +9. **P2 — Task 8: the throwaway-app verification cannot immediately enable per-instance mode.** |
| + |
| + **Evidence:** Plan:268 performs `submission on` followed immediately by `per-instance on`. Plan:150 requires `AppUserReapedAt`. `internal/mail/sweep.go:90,95–109` requires at least seven days of submission and observed mailer sends before the normal app-user reap. |
| + |
| + **Failure scenario:** A newly prepared app stops at `ErrAppUserNotReaped`, so the promised visible verification cannot run as written. |
| + |
| + **Fix:** Use a designated dev fixture already switched and reaped, or describe the supported preparation and waiting period. Specify the authorized live-test scope; an already verified domain alone does not establish authorization for account-level resource changes. |
| + |
| + **Invariant:** The verification procedure satisfies the same migration preconditions as the feature. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R2.md b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R2.md| new file mode 100644 |
| index 000000000..dd091091b |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R2.md |
| @@ -0,0 +1,69 @@ |
| +# Review findings: instance senders slice 1 plan, round 2 (Astra, gpt-6-astra, on f909e67e4) |
| + |
| +R1 status: |
| + |
| +- P1-1 — **Partly resolved, now P2:** standalone grant refusals are covered; create-with-addresses still lacks a concrete admission contract and distinguishing test. |
| +- P1-2 — **Resolved:** plan enforcement handles the app before sender enumeration and the ordinary pause predicate. |
| +- P1-3 — **Resolved:** removal recovers pending transitions before draining grants. |
| +- P1-4 — **Resolved:** normalization precedes domain validation; successful fixtures use valid domains. |
| +- P1-5 — **Partly resolved, remains P1:** final refresh is specified, but Task 7’s `svcrole` change is omitted from intermediate census coverage. |
| +- P2-6 — **Resolved:** response types, CLI decoding and effective-state rendering are specified. |
| +- P2-7 — **Resolved:** the previously missing isolation cases are now listed. |
| +- P2-8 — **Resolved:** UX and copy review precede door and CLI implementation. |
| +- P2-9 — **Resolved:** verification includes scoped approval and the reap waiting period. |
| + |
| +Reviewed `f909e67e41d62fe9df15212fcf220be0d8651c25`. No files changed, tests run or subagents spawned. References below are repository-relative; “Plan” denotes the reviewed plan. |
| + |
| +1. **P1 — Task 7: adding the role breaks the existing service-help test.** |
| + |
| + **Evidence:** Plan:212 adds `svcrole.Mail`, but neither Task 7 nor Task 8 includes `services.go`. Its three role lists remain explicit at `services.go:37,175–176`. `services_roles_help_test.go:33–44` compares each list against `svcrole.All()`, excluding only specified existing roles. |
| + |
| + **Failure scenario:** Once `mail` enters the catalogue, `TestServicesHelpNamesEveryRole` fails. Task 7’s selected package tests miss it; the later full gate encounters it. |
| + |
| + **Fix:** Include all three service-help lists in Task 6’s copy review and Task 7’s implementation. Run the existing root-package test. |
| + |
| + **Invariant:** Adding a service role updates every enforced public role catalogue in the same task. |
| + |
| +2. **P1 — Task 7: the census still fails at an intermediate task tip. Carries R1 P1-5.** |
| + |
| + **Evidence:** Plan:20 identifies only Tasks 1, 5 and 8 as changing census-scoped files. Task 7 changes `internal/svcrole/svcrole.go` at Plan:212. That file is explicitly in `internal/provision/testdata/census-base-scope.txt:1472`, and its package envelope is pinned in `internal/provision/testdata/census-base.tsv:5442`. Envelope differences fail at `internal/provision/plan14_root_reads_test.go:677–679,700–713`. |
| + |
| + **Failure scenario:** Task 7 commits the catalogue change without refreshing its census proposal. Its tip fails `make test`, contrary to Plan:20. Task 8’s later refresh does not make Task 7 green retrospectively. |
| + |
| + **Fix:** Include Task 7’s `svcrole` change—and the required `services.go` change—in census claims and proposal generation before that task commits. |
| + |
| + **Invariant:** Every promised green task tip has fingerprints covering all its in-scope changes. |
| + |
| + This is the second round in the census-completeness fault family. Apply stopping rule 2: replace the manually enumerated task assumption with one enforced check that discovers census changes at each task boundary, rather than continuing package-by-package corrections. |
| + |
| +3. **P2 — Tasks 3–4: create-with-addresses lacks the admission contract needed to preserve the refusal fix. Carries R1 P1-1 at reduced severity.** |
| + |
| + **Evidence:** Plan:21 requires expected refusals before writes. Plan:108 gives recovery its own admitted call, while Plan:139 delegates create’s addresses to `GrantAddress`. However, nested admission is not independent: `internal/mail/claim_gate.go:389–397` invokes nested work inside the existing admission. Its attempts accumulate in the outer operation (`claim_gate.go:163–165`), and an error after any write retains the gate (`claim_gate.go:425–427`). |
| + |
| + **Failure scenario:** An implementation creates the sender, grants the first address, then discovers that the second belongs to another sender. Returning the expected conflict retains the gate. The prescribed standalone-grant test does not distinguish this implementation. |
| + |
| + **Fix:** Specify whole-request preflight and recovery boundaries for create-with-addresses. Add production-wrapper tests for a new sender with a taken address, and a batch whose later address conflicts; after refusal, another gated mutation must succeed. |
| + |
| + **Invariant:** Expected business refusals do not retain the shared gate, including through composed mutations. |
| + |
| +4. **P2 — Tasks 3, 6–7: the domain-removal refusal never reaches its required HTTP contract.** |
| + |
| + **Evidence:** Spec decision 13 requires a `409` naming the dependent-address count. Plan:109 introduces `ErrAddressesInUse`, but Plan:212 does not assign changes to the existing domain-removal handler, and Plan:225 omits this error. `internal/console/apimail.go:1212–1237` handles two existing refusal types, then returns a generic `502`. |
| + |
| + **Failure scenario:** Removing a domain used by instance addresses is safely refused internally, but the operator receives a transient-failure message telling them to retry, without the required count. |
| + |
| + **Fix:** Carry the dependency count in the error/result, review its copy in Task 6, and map it to `409` in the existing handler. Test grants, pending reservations and pending releases through that HTTP door. |
| + |
| + **Invariant:** A dependency refusal identifies the actionable conflict and implements decision 13’s public contract. |
| + |
| +5. **P2 — Tasks 7–8: instance cap changes are unspecified and untested.** |
| + |
| + **Evidence:** The spec’s §5 keeps both pause and cap operator-only on the existing pause door. Plan:212 adds `host`, but Plan:232 tests only pausing. Today the cap branch always calls app-level `mail.ApplyGrant` (`internal/console/apimail.go:1608–1620`); that function reads the app record and replaces its grant (`internal/mail/walk.go:1012–1026`). |
| + |
| + **Failure scenario:** Adding host selection only to pause/resume leaves a request containing `host` and `daily_cap` changing the app sender’s cap, while the intended instance’s cap stays unchanged. |
| + |
| + **Fix:** Specify a host-scoped cap mutation that preserves address grants and pending transitions. Test cap-only and combined cap/pause requests, asserting that the app sender and sibling sender remain unchanged. |
| + |
| + **Invariant:** Every operator mutation carrying an instance host affects that instance sender alone. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R3.md b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R3.md| new file mode 100644 |
| index 000000000..ef5695ff7 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R3.md |
| @@ -0,0 +1,13 @@ |
| +# Review findings: instance senders slice 1 plan, round 3 (Astra, gpt-6-astra, on d6d492631) |
| + |
| +- **R2 P1-1 — Resolved.** Tasks 6–7 include all three `services.go` role lists and run `TestServicesHelpNamesEveryRole`, which checks them against `svcrole.All()`. |
| +- **R2 P1-2 — Resolved.** The global census boundary check now applies before every task commit, including Task 7. It discovers changes and requires the census tests to pass. |
| +- **R2 P2-3 — Resolved.** Tasks 3–4 specify whole-batch preflight before any create/grant write, separate recovery admission, and production-wrapper tests covering both first-address and later-address conflicts. |
| +- **R2 P2-4 — Resolved.** Tasks 3, 6 and 7 carry the dependent-address count, review its message, map the refusal to HTTP 409, and test grants, reservations and releases through the domain doors. |
| +- **R2 P2-5 — Resolved.** Tasks 4 and 7 specify a host-scoped cap mutation and tests for pause-only, cap-only and combined requests, preserving the app and sibling senders. |
| + |
| +No new P1, P2 or P3 findings in revision 3’s diff. |
| + |
| +Reviewed `d6d492631a7d6327120cacb0c256ff4fcc10f75f` against revision 2 and the relevant code at `origin/main` `43dce353f`. No files changed, tests run or subagents spawned. This verdict covers the plan revision, not its future implementation. |
| + |
| +**READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R1.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R1.md| new file mode 100644 |
| index 000000000..df85c5c8c |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R1.md |
| @@ -0,0 +1,61 @@ |
| +# Review brief: instance senders slice 1 plan, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `instance-senders-submission`, commit named in the reviewer's prompt. |
| +Under review: `docs/superpowers/plans/2026-11-30-instance-senders-1-own-address.md`. |
| +Authorities: `docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md` |
| +(revision 5, APPROVED by Paul 2026-11-30, on this branch; the plan implements its §9 slice 1), |
| +`docs/superpowers/specs/2026-11-12-platform-mail-submission-design.md` (merged), AGENTS.md, |
| +and the code on `origin/main` `43dce353f`. |
| + |
| +You are an independent reviewer. Read the plan, the spec, then the code it |
| +names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The spec is approved, including Paul's rulings in its §12 (decision 9's |
| + tenant cut, decision 6's single-app address grants, decision 17). |
| + Report only places where the plan fails to implement the spec, or would |
| + not work as written. |
| + |
| +## What to check |
| + |
| +1. **Coverage.** Every slice-1 decision the spec's §9 lists (1, 2, 3, 4(b), |
| + 6, 10, 11, 12, 15, 16, the address and teardown parts of 13, the |
| + address-key part of 14) has a task that implements it and a test that |
| + proves it. |
| +2. **Will it work against the code.** Named files, functions, patterns |
| + (claim gate wrappers, `ClassifyMutation`, `allowWrite`, clireg, parity, |
| + docsite, census) exist and behave as the plan assumes. |
| +3. **Ordering.** Does any task consume something a later task produces? |
| + Does each task leave the tree green? |
| +4. **Fail-closed and isolation tests.** Are decision 2's old-mailer check, |
| + decision 15's guard and decision 16's strict inventory tested in a way |
| + that would fail if the property broke? |
| +5. **AGENTS.md rules.** File/function size ratchet, new CLI commands return |
| + errors, no sleeps, parity/cli.md, census, delegation, per-task review |
| + sizing, no AWS change. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the task, the problem, the evidence |
| +(file:line, verified), the failure scenario, a concrete fix and the |
| +invariant it breaks. End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R2.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R2.md| new file mode 100644 |
| index 000000000..eb0570596 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R2.md |
| @@ -0,0 +1,71 @@ |
| +# Review brief: instance senders slice 1 plan, round 2 of 3 |
| + |
| +Repo carlos/platform, branch `instance-senders-submission`, commit named in the reviewer's prompt. |
| +Under review: `docs/superpowers/plans/2026-11-30-instance-senders-1-own-address.md`. |
| +Authorities: `docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md` |
| +(revision 5, APPROVED by Paul 2026-11-30, on this branch; the plan implements its §9 slice 1), |
| +`docs/superpowers/specs/2026-11-12-platform-mail-submission-design.md` (merged), AGENTS.md, |
| +and the code on `origin/main` `43dce353f`. |
| + |
| +You are an independent reviewer. Read the plan, the spec, then the code it |
| +names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The spec is approved, including Paul's rulings in its §12 (decision 9's |
| + tenant cut, decision 6's single-app address grants, decision 17). |
| + Report only places where the plan fails to implement the spec, or would |
| + not work as written. |
| + |
| +## What to check |
| + |
| +1. **Coverage.** Every slice-1 decision the spec's §9 lists (1, 2, 3, 4(b), |
| + 6, 10, 11, 12, 15, 16, the address and teardown parts of 13, the |
| + address-key part of 14) has a task that implements it and a test that |
| + proves it. |
| +2. **Will it work against the code.** Named files, functions, patterns |
| + (claim gate wrappers, `ClassifyMutation`, `allowWrite`, clireg, parity, |
| + docsite, census) exist and behave as the plan assumes. |
| +3. **Ordering.** Does any task consume something a later task produces? |
| + Does each task leave the tree green? |
| +4. **Fail-closed and isolation tests.** Are decision 2's old-mailer check, |
| + decision 15's guard and decision 16's strict inventory tested in a way |
| + that would fail if the property broke? |
| +5. **AGENTS.md rules.** File/function size ratchet, new CLI commands return |
| + errors, no sleeps, parity/cli.md, census, delegation, per-task review |
| + sizing, no AWS change. |
| + |
| +## Round 2 |
| + |
| +Earlier rounds: `docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-R1.md` |
| +(round 1, Astra). First give one line per P1 and P2 from round 1: resolved, |
| +partly, or not. Carry every unresolved or partly resolved finding forward at |
| +its current severity, then add new findings. The verdict covers everything |
| +outstanding. The plan's Appendix A maps each finding to its answer. |
| +Revision 2 renumbers tasks (a copy-and-UX Task 6 is new; doors are Task 7, |
| +CLI Task 8, landing Task 9). |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the task, the problem, the evidence |
| +(file:line, verified), the failure scenario, a concrete fix and the |
| +invariant it breaks. End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R3.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R3.md| new file mode 100644 |
| index 000000000..27912c8c9 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-senders-1-R3.md |
| @@ -0,0 +1,72 @@ |
| +# Review brief: instance senders slice 1 plan, round 3 of 3 |
| + |
| +Repo carlos/platform, branch `instance-senders-submission`, commit named in the reviewer's prompt. |
| +Under review: `docs/superpowers/plans/2026-11-30-instance-senders-1-own-address.md`. |
| +Authorities: `docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md` |
| +(revision 5, APPROVED by Paul 2026-11-30, on this branch; the plan implements its §9 slice 1), |
| +`docs/superpowers/specs/2026-11-12-platform-mail-submission-design.md` (merged), AGENTS.md, |
| +and the code on `origin/main` `43dce353f`. |
| + |
| +You are an independent reviewer. Read the plan, the spec, then the code it |
| +names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The spec is approved, including Paul's rulings in its §12 (decision 9's |
| + tenant cut, decision 6's single-app address grants, decision 17). |
| + Report only places where the plan fails to implement the spec, or would |
| + not work as written. |
| + |
| +## What to check |
| + |
| +1. **Coverage.** Every slice-1 decision the spec's §9 lists (1, 2, 3, 4(b), |
| + 6, 10, 11, 12, 15, 16, the address and teardown parts of 13, the |
| + address-key part of 14) has a task that implements it and a test that |
| + proves it. |
| +2. **Will it work against the code.** Named files, functions, patterns |
| + (claim gate wrappers, `ClassifyMutation`, `allowWrite`, clireg, parity, |
| + docsite, census) exist and behave as the plan assumes. |
| +3. **Ordering.** Does any task consume something a later task produces? |
| + Does each task leave the tree green? |
| +4. **Fail-closed and isolation tests.** Are decision 2's old-mailer check, |
| + decision 15's guard and decision 16's strict inventory tested in a way |
| + that would fail if the property broke? |
| +5. **AGENTS.md rules.** File/function size ratchet, new CLI commands return |
| + errors, no sleeps, parity/cli.md, census, delegation, per-task review |
| + sizing, no AWS change. |
| + |
| +## Round 3 |
| + |
| +Earlier rounds: `CODEX-FINDINGS-instance-senders-1-R1.md` and `-R2.md` |
| +beside the plan (both Astra). Stopping rule 2 triggered for the census |
| +family in round 2; revision 3 states the invariant and checks it at every |
| +task boundary instead of enumerating tasks. This round is limited to |
| +revision 3's diff against revision 2 (`f909e67e4..HEAD`) and whether it |
| +removes round 2's findings. First give one line per round-2 P1 and P2: |
| +resolved, partly, or not. Then new findings only in the diff. A fourth |
| +round needs Paul's go. Appendix B maps each finding to its answer. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the task, the problem, the evidence |
| +(file:line, verified), the failure scenario, a concrete fix and the |
| +invariant it breaks. End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |
diff --git a/docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md b/docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md| new file mode 100644 |
| index 000000000..61594fe55 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md |
| @@ -0,0 +1,417 @@ |
| +# Instance senders on mail submission (#148) |
| + |
| +**Date:** 2026-11-30 · **Status:** **APPROVED by Paul, 2026-11-30**, revision 5 (his rulings, §12; no review round, as they are rulings, not fixes) · |
| +**Branch:** `instance-senders-submission` from `origin/main` `43dce353f` |
| +· **Author:** Claude Opus 5.5, for Paul. |
| + |
| +**Review history (stopping rules apply).** |
| +- Round 1: Astra on revision 1 (`cf3a28e4a`), NOT READY: 5 P1s, 3 P2s |
| + in five fault families (`CODEX-FINDINGS-instance-senders-R1.md`). |
| +- Round 2: Astra on revision 2 (`6bb283e9a`), NOT READY: 4 P1s, 2 P2s |
| + (`CODEX-FINDINGS-instance-senders-R2.md`). Two families had findings |
| + in both rounds, **"ownership across authorization boundaries"** (R1 |
| + P1-3, R2 P1-1) and **"deletion versus live tenant associations"** (R1 |
| + P1-5, R2 P1-2), and both arose only from per-instance SES tenants. A |
| + third, **"global reservations need an owner-scoped recovery path"** |
| + (R1 P2-8, R2 P1-3), also recurred. **Stopping rule 2 applies to all |
| + three; revision 3 writes no third fix.** It takes rule 2's options: |
| + - **cut** per-instance SES tenants (decision 9), which removes both |
| + tenant families, and recorded for Paul to reverse (§12); |
| + - **refuse up front** address grants on a domain another app shares |
| + (decision 6), so no instance operation touches another app's |
| + resource; |
| + - **state the invariant, enforce it in one place, guard it with a |
| + test** for reservations (decision 15) and for enforcement |
| + inventories (decision 16). |
| +- Round 3: Astra on revision 3 (`456201938`), NOT READY: 1 P1, 2 P2s |
| + (`CODEX-FINDINGS-instance-senders-R3.md`). Every round-2 finding was |
| + resolved except the authorization family, now in its **third** round: |
| + removing an instance-owned domain runs `RemoveDomain`, whose policy |
| + refresh admits every app sharing any of the app's other verified |
| + domains (`walk.go:2365`, `claim_gate.go:302-357,389-395`). It affects |
| + owned domains (slice 2) only. Revision 4 applies round 3's two P2s |
| + without reopening the review and writes **no fix for the P1**: the |
| + options are put to Paul (§12 item 3). **The review has stopped; a |
| + fourth round needs Paul's go.** |
| +- **Paul's rulings, 2026-11-30** (§12): option (a) for round 3's P1 |
| + (decision 17), the tenant cut accepted for v1 (decision 9, follow-up |
| + #1546), and single-app address grants confirmed (decision 6). |
| + Revision 5 records them. No review round follows a ruling. |
| + |
| +**Builds on (all merged):** |
| +`2026-11-12-platform-mail-submission-design.md` (the mailer, decisions |
| +1–11), `2026-09-15-tenant-email-senders-design.md` (the sender record §5, |
| +counts and pauses §8). **Supersedes, for apps switched to submission:** |
| +the senders spec §6 (instance senders by IAM user, the per-instance |
| +config overlay, `ConfigAck`), and |
| +`docs/superpowers/plans/2026-09-15-tenant-email-5-instance-senders.md`, |
| +which was never built. |
| + |
| +**Stopping rule 5.** Who asks: Paul, for keymail (#148 reply, |
| +2026-11-30), and titogo (#148, 2026-09-15). What they get: one instance |
| +per customer, each with its own sending addresses and domains, its own |
| +cap, pause, rate and counts, and no way to send as a sibling. When it |
| +switches on: keymail's move to one CARLOS instance per mailbox |
| +(designed on `keymail/keymail`), at its first canary mailbox. keymail |
| +is blocked on this; until it lands keymail keeps sending through its |
| +own SES path. |
| + |
| +--- |
| + |
| +## 1. The problem |
| + |
| +Tenant email has two kinds of sender today: the app sender, and, on |
| +paper, the instance sender. Only the first exists (`sender.go:33-37`: |
| +"An app sender on a domain the account verified is the only combination |
| +this release produces"). |
| + |
| +Since platform mail submission merged (`9eec02360`), every instance of a |
| +switched app sends as the **app sender** (submission decision 5). The |
| +mailer reads one sender per app (`internal/mailer/policy.go:231-243`), |
| +counts and rate-limits against `acct/app/app` (`policy.go:196`), and |
| +tags every send `sender=app` (`internal/mailer/ses.go:83`). So for a |
| +multi-tenant app: |
| + |
| +- every instance can send from every domain granted to the app, as any |
| + local part on it; |
| +- one customer's bounces pause every customer (`enforceMailLimits`, |
| + `internal/console/mailcounts.go:333`, keyed by sender); |
| +- every customer shares one daily cap and one rate bucket. |
| + |
| +Two consumers need the opposite: |
| + |
| +- **titogo** (#148): one instance per customer account, each customer |
| + on their own domain. |
| +- **keymail** (#148 reply): one instance per mailbox. Every mailbox |
| + sends as its own `<local>@keymail.dev`, and its owner can attach any |
| + number of their own domains (the first real case is three on one |
| + mailbox) and send from any address on them. One mailbox must never be |
| + able to send as another's address or domain. |
| + |
| +## 2. The design in one paragraph |
| + |
| +**An instance sender is a sender record keyed by an instance, and the |
| +mailer picks it by the route it already stamps.** The agent stamps every |
| +submitted message with the route that owns the control socket |
| +(submission decision 1). In an app switched to **per-instance mode**, |
| +`admit` reads the sender whose id is that route's instance id, never |
| +the app sender, and applies that sender's pause, From rule, rate and cap, |
| +and tags the send with that sender. Nothing new is delivered into the |
| +instance: no IAM user, no key, no config overlay. An instance sender's |
| +From rule has two parts: **domains it owns** (claimed for that sender |
| +alone, verified like any CARLOS domain) and **exact addresses** on a |
| +domain only its app holds. The doors that manage them admit a new |
| +service role, `mail`, so an app's backend can onboard its customers |
| +without holding Admin. |
| + |
| +## 3. Approaches |
| + |
| +| | Approach | For | Against | |
| +|---|---|---|---| |
| +| A | **Plan 5: an IAM user, key and config overlay per instance** (senders spec §6) | Designed and reviewed; works for unswitched apps | 5,000 IAM users per account, not adjustable (senders spec §12); a credential in every instance, readable by flat siblings (submission §1.3); needs the overlay layer, which has no writer (`internal/appconfig/instances.go:386`, no callers outside tests) and `ConfigAck` work; never built | |
| +| B | **Instance senders keyed by the stamped route, on submission** | No credential anywhere; isolation is the stamp the mailer already trusts (submission §6); reuses the sender record, per-sender counts (`mail_sender_counts`) and per-sender pauses; the mailer's IAM and bucket grants already cover it (`infra/modules/region-host/mailer.tf:64,81`) | Only for apps switched to submission | |
| +| C | **One owned environment per customer** (team-scoped credentials §3a) | Exists today: an owned environment gets its own SMTP user | Binding an instance into an owned environment is a person's act (`docs/site/cli.md`, carlos env); still one IAM user and one credential per customer; replaced by submission for switched apps (submission "Replaces") | |
| + |
| +**Chosen: B.** Both consumers are building new on submission, and B is |
| +the only one that needs no credential and no new delivery path. An |
| +unswitched app that wants per-instance senders switches to submission |
| +first; A stays unbuilt, and this document closes Plan 5. |
| + |
| +## 4. Decisions |
| + |
| +| # | Decision | Rejected | |
| +|---|---|---| |
| +| 1 | **Instance senders exist only in an app switched to submission.** Creating one is refused while the app sender's `Submission` is off; `submission off` is refused while any instance sender exists (it would strand them with no channel and no credential). | Instance senders for SMTP apps (approach A) | |
| +| 2 | **Per-instance mode is a switch on the app sender, and it fails closed on an old mailer.** `carlos email per-instance on|off --app <a>`, Admin only, like `submission on`. **On** is one CAS write on the app sender that sets the existing `PerInstance` field (`sender.go:92`) **and** `Pause{Kind: per-instance}` (`mailwire.PauseKindPerInstance`, `mailwire.go:40`). A mailer that predates this design never reads `PerInstance` (`policy.go:137-155`), so it meets the pause at step 3 and refuses every send `429 PAUSED`: mail is delayed on a box that has not rolled, never sent as the app sender. A mailer that has rolled branches on `PerInstance` before it reads the app sender's pause (§6). An instance with no sender is refused `403 NO_SENDER`; there is no fallback to the app sender. **Off** is refused while any instance sender exists (decision 16's strict inventory); it clears both fields in one CAS. Rolling the mailer back below this design therefore also fails closed. `on` is refused while the app-level IAM user still exists (submission §7.4's week, `mailwire.Submission.AppUserReapedAt`, `mailwire.go:74`), so no SMTP credential bypasses the mode. | A mixed mode with fallback to the app sender; a box-version precondition (the pause makes one unnecessary, and covers later placement and rollback, which a check at the flip would not) | |
| +| 3 | **The record.** `apps/<acct>/<app>/email/senders/<id>.json`, `id = provision.InstanceID(host)` (`provision.go:3263`; a host of 40 characters or less is its own id, `:3229`), `Scope: instance`, `Host: <host>`. The shape is today's `Sender` (`sender.go:64`); it uses `Grant.Domains`, `Grant.DailyCap` and `Pause`, and gains `Grant.Addresses []string` (`addresses`), `Reserving []string` (`reserving`), `Releasing []string` (`releasing`) and `Removing *time.Time` (`removing`), all additive. `Provisioned`, `Standalone`, `Environments`, `Submission`, `TenantARN` and `Salt` are always empty on an instance sender. Inside the app prefix, so `release.PurgeApp` sweeps it (`sender.go:146-150`). | A new record family | |
| +| 4 | **Two kinds of From.** (a) **Owned domains** (`Grant.Domains`): claimed and verified for this sender alone; any address on them. (b) **Exact addresses** (`Grant.Addresses`): a canonical address (decision 6) whose domain is granted to and sendable by the **app sender** (`CheckFromDomain` on the app sender's grant), e.g. `paul@keymail.dev`. A From must satisfy one of the two. | Domains only, which would leave every keymail mailbox either unable to send as `@keymail.dev` or able to send as all of it | |
| +| 5 | **Instance ownership of a domain is exclusive; app sharing is unchanged.** Today several apps of one account may share a domain (`EnsureDomain` adds the app, `walk.go:221`, pinned by `walk_domain_test.go:117`), and that stays exactly as it is between **app senders**. What is new is that a domain is either app-held (non-empty `Apps`) or held by exactly one instance sender (`Senders`, decision 7), never both. The global claim gains `Sender` (omitempty, `sender`), written only for an instance-held claim. An instance sender's `domains add` is refused with the neutral `ErrDomainClaimed` when the domain record has any `Apps` or another `Senders` entry, or the claim names another (app, sender); the app sender's `domains add` is refused when the record has any `Senders`. `claimDomain`, `takeLapsedClaim` and `VerifyDomain` apply the same rule, so a lapsed instance claim is taken only as a whole and a same-account re-claim by another sender is no longer a silent success (`domainclaim.go:306`). Existing records have no `Senders` and no claim `Sender`, so nothing that exists today changes owner or loses authority. | Exclusivity between apps too, which would retire live shared domains | |
| +| 6 | **Addresses are canonical, held by one sender, and only on a domain no other app shares.** Canonical form: `net/mail.ParseAddress` of exactly one address with no display name, ASCII only, at most 254 bytes, the domain `ValidDomain`, and the **whole address lowercased**. Every door canonicalises before it validates, reserves, grants, revokes or cleans up, and stores only the canonical form; the mailer lowercases the From before comparing (it already compares case-insensitively, `policy.go:283`). **Refused up front (rule 2; confirmed by Paul, 2026-11-30, §12 item 2):** an address grant whose domain record's `Apps` is anything other than exactly `[<this app>]`, and another app's `domains add` of a domain on which this app holds any address grant. The second refusal reads, under the gate, a strict inventory (decision 16 (b)) of every instance sender's `Grant.Addresses`, `Reserving` and `Releasing`, so a pending reservation blocks sharing as a grant does (round 3 P2-3). So an address's domain belongs to one app, and its uniqueness is per app: a create-only key `apps/<acct>/<app>/email/addresses/<canonical>.json` → `{sender}`, inside the app prefix (so `release.PurgeApp` sweeps it), whose write is the uniqueness check. Reservation and release follow decision 15. The mailer never reads it. | Account-wide keys outside the app prefix (round 2 P1-3); grants on shared domains, which needed every sharing app's authority (round 2 P1-1); case-sensitive keys | |
| +| 7 | **The domain record names its instance senders.** `DomainRecord` gains `Senders []string` (`senders`), entries `<app>/<sender id>`. `mailwire.DomainView` gains `Senders`. An instance-held domain's identity is associated with the **account tenant** exactly as an app-held one is today (`walk.go:354-374`), so its removal is today's path (`walk.go:1669-1676`) with nothing added. | Reusing `Apps`, which every app-sender path reads as an app grant | |
| +| 8 | **The mailer's From rule for an instance sender** is one new pure function beside `CheckFromDomain` (`mailwire.go:242`): `CheckInstanceFrom(sender, appSender, from, app, region, dvFrom)`. Owned: domain in `sender.Grant.Domains`, record lists `<app>/<id>` in `Senders`, verified with identity and configuration set in the region. Address: canonical match in `sender.Grant.Addresses` (never `Reserving` or `Releasing`), and `CheckFromDomain(appSender.Grant.Domains, domain, app, region, dv) == FromSendable`. Same verdict codes; `403 FROM_NOT_ALLOWED` either way. | Two rules in two places | |
| +| 9 | **Cut: no per-instance SES tenant.** An instance sender sends with the app sender's tenant, exactly as every instance does today (`ses.go:86-87`). `admit`'s decision therefore carries the tenant **from the app sender** in its own field, separate from the instance record used for authorization and limits, because `sendInput` today derives it from `d.sender.TenantARN` (`ses.go:86`), which is empty on an instance sender (round 3 P2-2). Isolation of cap, rate, pause and counts is CARLOS's own (decision 10) and does not depend on SES tenants; what is given up is SES's own per-tenant reputation pause. Per-instance tenants were the sole source of round 1 P1-5 and round 2 P1-1 and P1-2 (association ownership across shared identities, legacy association inventories, tenant migration), and the per-identity association quota is unknown (§12). They become their own design once that quota is read. **Accepted by Paul for v1, 2026-11-30** (§12 item 1); per-instance tenants are follow-up #1546. | Per-instance tenants (revisions 1–2) | |
| +| 10 | **Counts, caps, pauses and rate per instance sender, with no new mechanism.** The mailer's counter and rate key become `acct/app/<sender id>` (`policy.go:196`). The console already counts and enforces per sender (`sesevents.go:563-631`, `mailcounts.go:333`) and believes the tag only from the mailer (`SenderOfCaller`, `sender.go:510-519`). One change: `CanSend` (`sender.go:142`) is true for a `Scope: instance` sender that is not `Removing`, since one exists only in a switched app (decision 1); today it would read false and `enforceMailLimits` would never pause one. | Counting per app | |
| +| 11 | **The `sender` tag is encoded, because an instance id is a hostname.** SES documents tag values as `[A-Za-z0-9_-]` (SDK `types.go:2065-2069`, `API_MessageTag`), and an instance id usually contains dots. Submission §9.0 found a dotted value accepted in practice; this design follows the documented contract, not the observation. `mailwire.SenderTag(id)`: `app` for the app sender (unchanged on the wire, so events from today's mailer still attribute), otherwise `i-` followed by the lowercase, unpadded base32 of the id (alphabet `a-z2-7`; at most 105 characters for a 64-byte id, inside SES's 256). `mailwire.SenderFromTag(tag)` is its exact inverse: `app` → `app`; `i-` + valid base32 whose decoding passes `ValidSenderID` and is not `app` → that id; anything else → invalid. `SenderOfCaller`'s mailer branch decodes with it, and an invalid tag goes to `logMailerUntagged` as an untagged event does today. Base32 is injective and `i-` cannot begin `app`, so the encoding is collision-free. | Sending the raw id | |
| +| 12 | **The `mail` role.** One new catalogue entry, `svcrole.Mail`, inside Admin's union (so every Admin credential keeps reaching it), as the senders spec §6.1 designed it. It reaches the instance-sender doors in §5 and nothing else. A keymail or titogo backend holds a `mail` credential beside its `instance` one; neither can deploy with it. The mail write gate takes the service budget for service principals (senders spec §6.1, "Rate budget"). | Admin for the backend, which can deploy (senders spec §6.1) | |
| +| 13 | **Removal is ordered, retry-safe, and refused while anything depends on it.** *Instance delete* is refused (`409`, "remove its email sender first") while the instance has a sender, in `handleAPIInstanceDelete` (`apiinstances.go:3444`) before anything is retired. *Sender delete* first CASes `Removing` onto the record (from then on the mailer refuses its sends `403 NO_SENDER` and `CanSend` is false), then, each step idempotent and re-run from the top on retry: release every address (decision 15); remove each owned domain by `RemoveDomain`'s rules (identity deleted only if this claim created it, account tenant disassociated as today, claim released, stale DNS records printed); delete the record last. *App-sender `domains rm`* is refused while any instance sender's address grant, reservation or release uses that domain (`409`, naming the count). *App teardown* (`Teardown`, `walk.go:2339`) runs sender delete for every instance sender in decision 16's strict inventory, then the app sender as today; an incomplete inventory fails the teardown rather than skipping a sender. | Cascading from instance delete, which would tear down SES state as a side effect of a route retirement that deliberately keeps data (`apiinstances.go:3439-3443`) | |
| +| 14 | **Every instance write is owned by its own app alone, and the boundaries say so.** By decisions 5, 6 and 9, no instance-door operation touches a resource another app holds: an owned domain has no `Apps`, an address grant's domain has `Apps == [app]`, and no tenant association is added. So scope (account, app) is the complete admission set. Two readers must still learn the new shapes, or they refuse them: the storage classifier's and the backend guard's `domainRecordApps` (`internal/hostops/mutation_classifier.go:295`, `internal/console/claim_backends.go:440`) also return `AppScope{account, app}` for each valid `Senders` entry's app (an instance-held record has empty `Apps`, which `ownerUnion` would refuse, `mutation_classifier.go:248`), and the address key, being under `apps/<acct>/<app>/`, classifies to its app by its path. **Guard test:** every instance door's writes, through the production wrappers, classify to exactly `{(account, app)}`. | Admission across sharing apps (round 2 P1-1), made unnecessary by refusing the shared case | |
| +| 15 | **Invariant: every address key a sender owns is named on its record until the key is gone.** One function, `mail.SetAddress(ctx, acct, app, id, canonical, grant bool)`, is the only writer of `Grant.Addresses`, `Reserving`, `Releasing` and the address keys. **Grant:** CAS the address into `Reserving` → create the key `{sender: id}` (an existing key naming this sender is success; naming another is the uniqueness refusal, and the address leaves `Reserving`) → CAS it from `Reserving` into `Grant.Addresses`. **Revoke:** CAS it from `Grant.Addresses` into `Releasing` → delete the key if it names this sender (`DeleteIfMatch` on the read etag) → CAS it out of `Releasing`. **Recovery:** every door and sender delete first completes any address left in `Reserving` or `Releasing` by re-running its remaining steps; a key whose body names another sender is never deleted. The mailer honours only `Grant.Addresses`. **Guard test:** a randomized test injects a failure at every step of every interleaving of grant, revoke, recovery and sender delete, and checks after each run that every key is named on its sender's record or absent, and that no two records hold one address. | Reserve-then-grant with no durable inventory (round 2 P1-3) | |
| +| 16 | **Enforcement and completeness never rest on a best-effort listing.** `ListSenders` skips an unreadable non-app sender (`mail.go:337-346`). (a) **The plan pause does not list instance senders.** It writes one field on the app sender, `InstancesPause *Pause` (`instances_pause`, additive), which the mailer reads at step 3 for every instance sender of the app, and `resumePlanMail` clears it by the same rule (`planMailSpent`) as today's plan holds (`planmail.go:93-109,174`). So the account-wide plan pause reaches every instance by one read the mailer already makes. (b) **Mode switches and teardown use `ListSendersStrict`**, which fails if any listed key cannot be read or decoded: "no instance sender exists" and "every instance sender removed" are answered only from a complete read. **Guard test:** an injected read failure on one instance sender makes `per-instance off`, `submission off` and teardown fail, and does not stop the plan pause. | Pausing each instance sender through `ListSenders` (round 2 P1-4) | |
| +| 17 | **Owned domains only in an app that shares no domain (Paul's ruling, 2026-11-30, §12 item 3, option (a)).** An instance sender's `domains add` is refused while any of the app's domain records lists another app; the app sender's `domains add` of a domain whose record lists another app is refused while any instance sender of the app holds a domain, reserved, held or releasing. Both are read under the mail gate, from a strict `ListDomains` and decision 16 (b)'s strict sender inventory. So `RemoveDomain`'s refresh closure (`walk.go:2042,2365`; `claim_gate.go:302-357`) is the app alone whenever an instance-owned domain is removed, and single-app admission (decision 14) is complete. keymail and titogo share no domains. | A removal path without the policy refresh (option (c), needing a fourth review round); cutting owned domains (option (b)) | |
| + |
| +**`PerInstance` already has readers, and they keep their meaning.** A |
| +resume aimed at the app sender is refused with `ErrPerInstance` |
| +(`walk.go:1298,1362`), so nothing lifts decision 2's pause except |
| +`per-instance off`; `resumeStaleCapPause` skips a per-instance app |
| +sender (`mailcounts.go:266`); the domain-wide event fallback skips it |
| +(`sesevents.go:663`); the plan pause's per-sender loop skips it |
| +(`planmail.go:105`), and decision 16 (a) replaces that skip with the |
| +`InstancesPause` write. |
| + |
| +## 5. The doors |
| + |
| +All under `/api/cli/apps/{account}/{app}/instances/{host}/email`, |
| +`Kind: kindCLI`, `Allow: svcrole.Allow(svcrole.Mail)`, each with its |
| +`parity/parity.tsv` row and `docs/site/cli.md` heading: |
| + |
| +``` |
| +POST .../email create the sender (idempotent); body {addresses?} |
| +GET .../email status: addresses, domains with DNS records and per-region state, pause, today's counts |
| +DELETE .../email remove the sender (decision 13) |
| +POST .../email/domains {domain}: claim, ensure identity, return the records to publish |
| +POST .../email/domains/{domain}/verify poll SES |
| +DELETE .../email/domains/{domain} release (RemoveDomain's rules) |
| +PUT .../email/addresses/{address} grant an exact address (decisions 6, 15) |
| +DELETE .../email/addresses/{address} revoke it |
| +``` |
| + |
| +App-level, Admin only: |
| + |
| +``` |
| +POST /api/cli/apps/{account}/{app}/email/per-instance {on: bool} decision 2 |
| +``` |
| + |
| +Every write goes through the mail claim gate (`ClaimMailStore`, |
| +`claim_gate.go:91`) with scope (account, app), which decision 14 makes |
| +complete. The host is checked with `provision.ValidHostShape` and must |
| +name an existing instance record of the app at create (not at delete or |
| +status, which outlive the record as instance delete does). An address |
| +in a path is canonicalised (decision 6) before anything else reads it. |
| + |
| +Pause and cap stay operator-only: the existing closed |
| +`POST .../email/pause` (`routedecls.go:1431`) gains an optional |
| +`host`, and `carlos email pause` gains `--host`. |
| + |
| +**CLI.** `carlos email instance create|status|rm --app <a> --host <h>`, |
| +`carlos email domains add|verify|rm --app <a> --host <h> <domain>` (the |
| +existing verbs, scoped by `--host`), `carlos email addresses add|rm |
| +--app <a> --host <h> <address>`, `carlos email per-instance on|off |
| +--app <a>`. `carlos email status --app <a>` gains one line per instance |
| +sender (the API reply's `senders` array; existing top-level fields keep |
| +describing the app sender, so an older CLI still works). |
| + |
| +## 6. The mailer, step by step |
| + |
| +**Wire projection.** `mailwire.SenderView` (`mailwire.go:99`) gains |
| +`Scope` (`scope`), `Host` (`host`), `Removing` (`removing`) and |
| +`InstancesPause` (`instances_pause`); `GrantView` (`mailwire.go:83`) |
| +gains `Addresses` (`addresses`); `DomainView` gains `Senders` |
| +(`senders`). Every name equals `mail.Sender`'s and `mail.DomainRecord`'s, |
| +and the wire-parity tests decode real persisted JSON of both shapes, |
| +old and new, and check the legacy defaults (absent `scope` reads as the |
| +app sender). |
| + |
| +`admit` (`policy.go:123`) keeps steps 1 and 4 and changes the rest: |
| + |
| +1. Route on this box (unchanged). |
| +2. Read the app sender (unchanged). Not switched: `403 SUBMISSION_OFF`. |
| + **If `PerInstance`:** read `SenderKey(acct, app, InstanceID(host))` |
| + through the same TTL cache; absent, `Scope != instance`, |
| + `Host != req.Host`, or `Removing` set: `403 NO_SENDER`. That record |
| + is "the sender" for every step below. Otherwise the app sender is, |
| + as today. |
| +3. Pause. For the app sender, its `EffectivePause`, as today. For an |
| + instance sender, its own `EffectivePause`, else the app sender's |
| + `InstancesPause` (decision 16 (a)); the app sender's own |
| + per-instance pause (decision 2) is not read. |
| +4. One From (unchanged). |
| +5. From rule: `CheckFromDomain` for the app sender (unchanged), |
| + `CheckInstanceFrom` for an instance sender (decision 8). Address |
| + grants read the app sender's domain record, owned domains their own. |
| +6. Rate, 7. cap: keyed `acct/app/<sender id>`. |
| + |
| +The send names the app sender's tenant, carried in the decision's own |
| +field (decision 9), and tags |
| +`sender=SenderTag(id)` (decision 11). The mailer's bucket reads are |
| +unchanged (`mailer.tf:81-84`: senders, instance records, domain |
| +records). The mailer is in the root binary's dependency set, so each |
| +slice that touches it carries a census card (AGENTS.md, "The census"). |
| + |
| +**Rollout order.** The mailer release ships and rolls before any app |
| +turns per-instance mode on. Decision 2 makes the order a matter of |
| +availability, not safety: a box still on the old mailer holds that |
| +app's mail (`429 PAUSED`, which the app's queue retries) until it |
| +rolls. |
| + |
| +## 7. What this protects, and what it does not |
| + |
| +- **An instance sends only as its own sender.** The sender is chosen by |
| + the stamped route (submission §6), never by the body, and per-instance |
| + mode leaves no fallback, on a new mailer or an old one (decision 2). |
| +- **An instance sends only from its own domains and addresses.** A |
| + domain or canonical address is held by one sender (decisions 5, 6, |
| + 15), and the From rule checks the sender's own grant (decision 8). |
| +- **One instance's abuse pauses that instance.** Its counts, cap and |
| + rate are its own (decision 10). The account-wide plan pause still |
| + stops every instance (decision 16 (a)). SES's own reputation |
| + enforcement still acts on the account tenant, as today (decision 9). |
| +- **The backend's reach.** A `mail` credential can create senders, claim |
| + domains and grant addresses for any instance of its app. It cannot |
| + deploy, read recipients (`GET .../email/events` stays Admin), pause, |
| + raise a cap, switch modes or mint a credential. A domain it claims |
| + sends nothing until its DNS proves control. |
| +- **Residual, unchanged:** submission §6's same-box residual (a |
| + compromised flat instance can submit as a neighbour on its box) now |
| + reaches that neighbour's sender rather than the app sender. Its cap, |
| + pause and From rule bound it. |
| + |
| +## 8. Testing |
| + |
| +1. **Chosen by route.** In per-instance mode, a message on host A's |
| + socket is sent as A's sender, counted and rate-limited under |
| + `acct/app/A`, tagged `SenderTag(A)`, and named with the app |
| + sender's account tenant although A's `TenantARN` is empty (fake SES). |
| +2. **No fallback, and fail-closed.** Per-instance mode, an instance with |
| + no sender, a record whose `Host` differs from the stamp, or a |
| + `Removing` sender: `403 NO_SENDER`, no SES call. Today's `admit`, |
| + kept as a test fixture, given an app sender written by |
| + `per-instance on`: `429 PAUSED`, no SES call. |
| +3. **From rule.** Owned domain: sendable; another instance's domain, |
| + unverified domain, or a domain the record does not list for this |
| + sender: `403`. Address: canonical grant sendable in any case of the |
| + From; an address only in `Reserving` or `Releasing`, another local |
| + part on the same domain, or an address whose domain the app sender |
| + lacks: `403`. Table test over `CheckInstanceFrom`. |
| +4. **One owner.** An instance sender's claim of an app-held or |
| + other-sender-held domain, and the app sender's `domains add` of an |
| + instance-held one, are refused, including through `takeLapsedClaim` |
| + and `VerifyDomain`; a same-sender re-claim is idempotent; two apps |
| + still share a domain as today. Decision 17: an instance sender's |
| + `domains add` in an app with any shared domain is refused, and an |
| + app's `domains add` of a shared domain is refused while an instance |
| + sender holds a domain; removing an instance-owned domain admits |
| + exactly `{(account, app)}` through the production wrappers. An address grant on a domain whose |
| + `Apps` is not exactly `[app]` is refused, and so is another app's |
| + `domains add` of a domain with this app's address grants, or with |
| + only a reservation or release pending (also in decision 15's |
| + failure-injection scenarios). `Paul@x` |
| + and `paul@x` granted to two senders, in either order and through |
| + both create-with-addresses and address add: the second is refused. |
| +5. **Reservations (decision 15's guard).** The randomized |
| + failure-injection test. |
| +6. **Tags.** `SenderTag`/`SenderFromTag` round-trip short dotted hosts, |
| + long hashed ids and `app`; malformed tags (`i-` with bad base32, a |
| + decoding that fails `ValidSenderID`, `i-` decoding to `app`) are |
| + invalid; a mailer event tagged `SenderTag(A)` is counted against A; a |
| + forged tag from a non-mailer caller is counted against its caller |
| + (guard 8.11, extended). |
| +7. **The switches.** Create refused while submission is off; submission |
| + off and per-instance off refused while any instance sender exists; |
| + per-instance on refused while the app-level IAM user exists; resume |
| + of the app sender refused while per-instance. |
| +8. **Limits per sender.** `CanSend` true for an instance sender, false |
| + once `Removing`; an instance sender over its cap or bounce rate is |
| + paused alone; the plan pause sets `InstancesPause` and the mailer |
| + refuses every instance sender `429 PAUSED`; resume clears it. |
| +9. **Inventories (decision 16's guard).** The injected read failure. |
| +10. **Removal.** Instance delete refused while a sender exists; app |
| + `domains rm` refused while an address grant, reservation or release |
| + uses the domain; sender remove leaves no identity, claim, address |
| + key or record, and finishes when re-run after a failure injected at |
| + each step; app teardown removes every instance sender. |
| +11. **Boundaries (decision 14's guard).** Through the production |
| + wrappers, every instance door's writes classify to exactly |
| + `{(account, app)}`; an instance-held domain record write is not |
| + refused by `ownerUnion`. |
| +12. **Roles.** `svcroutes_test.go` pins `mail` to exactly the §5 |
| + instance doors; `instance`, `operate`, `publish` and `deploy` are |
| + refused; Admin reaches them; pause and per-instance stay off `mail`. |
| +13. **Wire additivity.** A sender, claim or domain record written before |
| + this change parses and behaves as today. |
| +14. **CLI and docs.** Parity rows and `cli.md` headings; `docsite` and |
| + parity tests green. |
| + |
| +## 9. Order of work |
| + |
| +Each slice is one branch, landed before the next starts (stopping |
| +rules 6 and 7). Nothing in a slice is dormant: each switches on for |
| +keymail's canary when it lands. |
| + |
| +1. **An instance sends as its own address (visible first).** Decisions |
| + 1, 2, 3, 4(b), 6, 10, 11, 12, 15, 16, the address and teardown parts |
| + of 13 (including the app-sender `domains rm` refusal for address |
| + grants), and the address-key part of 14; per-instance mode; |
| + `instance create|status|rm` and `addresses add|rm`; the mailer's |
| + choice, pause read, address rule, keys, tag and wire projection. |
| + What Paul can see: `carlos email status` with a line and counts per |
| + instance, and a keymail canary mailbox sending as itself and refused |
| + as its neighbour. |
| +2. **Owned domains.** Decisions 4(a), 5, 7, 8's owned half, 17 and the |
| + domain parts of 13 and 14; the domain doors and CLI. Visible: a |
| + custom domain's records printed, verified, and sent from by one |
| + instance only. |
| + |
| +## 10. Out of scope |
| + |
| +- Instance senders for apps on SMTP credentials (approach A). |
| +- Per-instance SES tenants (decision 9's cut; follow-up #1546). |
| +- Inbound mail, and anything keymail does with it. |
| +- #147's addresses under identities CARLOS does not own; decision 4(b) |
| + is only for domains the app sender holds. |
| +- A console page for instance senders. The CLI and API come first; a |
| + page is a later UI change with its own UX pass. |
| +- Per-instance uids (submission §11, item 1), which would close §7's |
| + residual. |
| + |
| +## 11. Facts for the tenant follow-up |
| + |
| +The cut design (per-instance tenants) needs, before it is written: the |
| +SES quotas on tenants per account and region, and on resource |
| +associations per tenant and per identity (every keymail mailbox's |
| +tenant would be associated with the one `keymail.dev` identity). Both |
| +are read-only reads of Service Quotas, needing no approval. |
| + |
| +## 12. Paul's rulings (2026-11-30) |
| + |
| +1. **Decision 9's cut: accepted for v1.** Instance senders share the |
| + account's SES tenant; SES's own reputation pause acts on the account, |
| + while CARLOS's cap, rate, bounce and complaint pauses act per |
| + instance. Per-instance tenants are a separate Feature Request, |
| + **#1546**, after §11's quota read. |
| +2. **Decision 6's refusal: confirmed.** Address grants only on a domain |
| + held by one app. keymail's `keymail.dev` and titogo's platform domain |
| + are each held by one app. |
| +3. **Round 3's P1: option (a), refuse up front** (decision 17). Options |
| + (b), cutting owned domains, and (c), a removal path without the |
| + policy refresh and a fourth review round, were declined. Slice 2 is |
| + planned with decision 17. |
| + |
| +Related request filed for keymail's use of instances: **#1547**, that an |
| +armed one-shot timer due within the idle window keeps an instance |
| +resident (documented and guaranteed), or an explicit keep-awake signal. |
| + |
| +--- |
| + |
| +## Appendix A — round 1 (Astra, revision 1 `cf3a28e4a`) |
| + |
| +| Finding | Family | Answer (revision 2; revision 3 where it changed) | |
| +|---|---|---| |
| +| P1-1 instance ids are not valid SES tag values | sender identity through transport | Decision 11; test 8.6. Resolved in round 2 | |
| +| P1-2 no mailer-version precondition | every enforcement point understands the switch | Decision 2's fail-closed pause; test 8.2. Resolved in round 2 | |
| +| P1-3 classifier and guard reject the new shapes | ownership across authorization boundaries | Decision 14. Round 2 found it partly resolved; revision 3 takes rule 2 (Appendix B) | |
| +| P1-4 address equality | address equivalence | Decision 6. Resolved in round 2 | |
| +| P1-5 removal ignores instance-tenant associations | deletion vs live associations | Revision 3 cuts per-instance tenants (decision 9), so no association is added and removal is today's | |
| +| P2-6 shared legacy domains | ownership migration | Decision 5. Resolved in round 2 | |
| +| P2-7 mailer wire projection | projection parity | §6. Resolved in round 2 | |
| +| P2-8 caller-index reservation | global reservation cleanup | No caller-index entry exists after the cut (no slug, no tenant) | |
| + |
| +## Appendix B — round 2 (Astra, revision 2 `6bb283e9a`) |
| + |
| +| Finding | Family | Answer (revision 3) | |
| +|---|---|---| |
| +| P1-1 holding the gate does not admit every owner of a shared identity (carries R1 P1-3) | ownership across authorization boundaries, **second round: rule 2** | Refuse up front: address grants only on single-app domains (decision 6), and no tenant associations (decision 9), so (account, app) is complete; stated and guarded (decision 14, test 8.11) | |
| +| P1-2 `Tenants` has no legacy default (carries R1 P1-5) | deletion vs live associations, **second round: rule 2** | Cut: per-instance tenants and `Tenants` are gone (decision 9); removal is today's path (decision 7) | |
| +| P1-3 address cleanup loses retry information | global reservations need recovery, **second round with R1 P2-8: rule 2** | Invariant in one function with a randomized failure-injection guard (decision 15); keys inside the app prefix (decision 6) | |
| +| P1-4 `ListSenders` is not a complete inventory | completeness of enforcement inventories | `InstancesPause` on the app sender for the plan pause; `ListSendersStrict` for switches and teardown; guarded (decision 16) | |
| +| P2-5 slice 1 defers the address guard on `domains rm` | slice dependencies | Moved into slice 1 (§9) | |
| +| P2-6 no tenant migration for existing senders | rollout migration | Moot after the cut | |
| + |
| +## Appendix C — round 3 (Astra, revision 3 `456201938`) |
| + |
| +| Finding | Family | Answer (revision 4) | |
| +|---|---|---| |
| +| P1-1 `RemoveDomain`'s refresh admission exceeds (account, app) (carries R2 P1-1) | ownership across authorization boundaries, **third round** | No fix written (rule 2). Paul ruled option (a): decision 17 refuses the shared case up front | |
| +| P2-2 tenant selection lost when the instance record is "the sender" | transport preserves enforcement resources | Decision 9: the tenant travels from the app sender in its own decision field; test 8.1 | |
| +| P2-3 the sharing refusal ignores pending reservations | exclusivity through recoverable transitions | Decision 6 reads `Grant.Addresses`, `Reserving` and `Releasing` strictly; test 8.4 and decision 15's scenarios | |
| + |
| +**P3 follow-up list:** none raised. |
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R1.md b/docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R1.md| new file mode 100644 |
| index 000000000..36441cef3 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R1.md |
| @@ -0,0 +1,88 @@ |
| +# Review findings: instance senders spec, round 1 (Astra, gpt-6-astra, on cf3a28e4a) |
| + |
| +Reviewed `cf3a28e4a2b0fe511fff6174f12dade0c422886c` against `43dce353f`. No files changed, subagents spawned or tests run. |
| + |
| +1. **P1 — Decision 10 / §6: instance IDs are not valid SES message-tag values.** |
| + |
| + `InstanceID("alice.keymail.dev")` returns that hostname unchanged ([provision.go:3263](internal/provision/provision.go:3263)). Decision 10 puts it directly in `sender=<id>`, replacing the current literal `app` at [ses.go:83](internal/mailer/ses.go:83). SES message-tag values exclude periods. This is documented both in the pinned SDK’s `types.go:2065–2069` and [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_MessageTag.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_MessageTag.html). |
| + |
| + **Failure:** ordinary hostname-backed senders reach SES with an invalid tag and cannot send. Merely encoding the outgoing tag also breaks attribution: `SenderOfCaller` currently returns the tag unchanged as the sender record ID ([sender.go:513](internal/mail/sender.go:513)). |
| + |
| + **Fix:** define a collision-free SES-safe encoding and its inverse in the trusted-mailer attribution branch. Test short dotted hosts, long hashed IDs, malformed encodings and attribution back to the original record. |
| + |
| + **Fault family:** sender identity must survive transport and attribution unchanged. |
| + |
| +2. **P1 — Decision 2 / §9 slice 1: enabling per-instance mode has no mailer-version precondition.** |
| + |
| + The existing mailer reads `PerInstance` into `SenderView`, but `admit` never branches on it: it selects the app sender, checks its grant and charges `…/app` ([policy.go:137](internal/mailer/policy.go:137), `:173–196`). The proposed switch checks submission and removal of the app IAM user, neither of which proves the running mailer understands instance senders. |
| + |
| + **Failure:** the console enables per-instance mode while a serving box still runs the current mailer. An instance without a sender—or with only one exact address—can continue sending through the app grant. This is additional to the explicitly accepted same-box residual. |
| + |
| + **Fix:** require verified deployment of a supporting mailer before enabling the switch, covering every eligible serving box and subsequent placement/rollback. Alternatively, specify a compatibility pause that makes old mailers refuse, with a rollout procedure that proves it is effective before enabling instance sends. |
| + |
| + **Fault family:** every serving enforcement point must understand the isolation switch. |
| + |
| +3. **P1 — Decisions 7 and 9 / §5: the existing authority boundaries reject the new resource shapes.** |
| + |
| + Holding `ClaimMailStore`’s gate does not resolve these two incompatibilities: |
| + |
| + - A new instance-owned domain has empty `Apps`. The storage classifier reads only `Apps` ([mutation_classifier.go:295](internal/hostops/mutation_classifier.go:295)); `ownerUnion` rejects a `Put` with no owners at `:248`. The proposed `Senders` field therefore produces `ErrIdentity`. |
| + - `EnsureTenant` and tenant-resource associations resolve tenant names exclusively through `TenantName(account)` ([claim_backends.go:595](internal/console/claim_backends.go:595), `:604`). An instance tenant produced by `SenderNames` matches none of those names (`:493–504`), and the authorization boundary rejects the empty scope (`:55`). |
| + |
| + **Failure:** slice 2 cannot persist its first instance-owned domain; slice 3 cannot create or associate its first instance tenant through the prescribed production path. |
| + |
| + **Fix:** explicitly include the storage classifier, backend authorization and gate admission readers in these slices. Resolve `Senders` to validated app ownership, and authorize instance tenant names by exact forward derivation from their owning sender. Preserve the existing account-tenant path and add tests through the guarded production wrappers. |
| + |
| + **Fault family:** resource ownership must be understood by every authorization boundary. |
| + |
| +4. **P1 — Decisions 6 and 8: address uniqueness uses a different equality rule from sending.** |
| + |
| + Decision 6 indexes the supplied `<address>`; decision 8 compares grants case-insensitively ([spec:96–98](docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md:96)). No canonicalization is specified. The existing mailer also deliberately accepts case-insensitive envelope/header equality ([policy.go:283](internal/mailer/policy.go:283)). |
| + |
| + **Failure:** A claims `Paul@keymail.dev`; B claims `paul@keymail.dev`. Their create-only keys differ, but both grants authorize the same From address. Serializing the writes does not prevent this. |
| + |
| + **Fix:** define one validated canonical address representation before constructing any index key or grant. Use it for create, lookup, revoke and cleanup. Test conflicting case variants through both create-with-addresses and address-add. |
| + |
| + **Fault family:** uniqueness and authorization must use the same address equivalence. |
| + |
| +5. **P1 — Decisions 9 and 13: domain removal does not account for instance-tenant associations.** |
| + |
| + The reused removal path disassociates only `TenantName(acct)`, then calls `DeleteIdentity` ([walk.go:1669](internal/mail/walk.go:1669)). Decision 9 adds associations to instance tenants, while decision 13 releases domains **before** deleting the instance tenant. |
| + |
| + **Failure:** removing an instance sender with an owned domain reaches identity deletion while its instance-tenant association still exists. SES refuses; claim release and tenant deletion remain unreached. Likewise, removing an app-owned domain used by address grants encounters associations belonging to those instance tenants. AWS explicitly requires removing associations before deleting the resource: [https://docs.aws.amazon.com/ses/latest/dg/tenants.html](https://docs.aws.amazon.com/ses/latest/dg/tenants.html). |
| + |
| + **Fix:** specify association ownership and removal order for owned domains and shared address identities. Disassociate the relevant instance tenant before deleting an owned identity. For app-domain removal, either refuse while address grants reference it or explicitly revoke those grants and associations first. Require retry-safe cleanup and tests with a fake that rejects deletion of associated identities. |
| + |
| + **Fault family:** resource deletion must account for every live association. |
| + |
| +6. **P2 — Decision 5 / wire compatibility: existing shared domains have no migration policy.** |
| + |
| + Current code intentionally supports multiple apps on one domain: `EnsureDomain` adds the app at [walk.go:221](internal/mail/walk.go:221), and [walk_domain_test.go:117](internal/mail/walk_domain_test.go:117) pins that behavior. The claim’s `App` records its first claimant, not its complete owner set ([domainclaim.go:162](internal/mail/domainclaim.go:162)). |
| + |
| + **Failure:** adding an absent-as-`app` sender field does not establish exclusive ownership for existing `Apps=[A,B]` records. B’s formerly idempotent domain-add becomes a refusal, while its existing grant remains usable. App-local address indexes can also allocate the same address independently under those shared grants. |
| + |
| + **Fix:** state a grandfathering or migration policy. Refuse transition to exclusive instance ownership until legacy references are resolved, and define the address-uniqueness scope for shared legacy domains. Cover `claimDomain`, `takeLapsedClaim`, verification and release consistently. |
| + |
| + **Fault family:** ownership migration must preserve or explicitly retire existing authority. |
| + |
| +7. **P2 — Decisions 3 and 9 / §6: the mailer’s wire projection is missing required additions.** |
| + |
| + `SenderView` has no `Scope`, `Host` or `TenantName`; `GrantView` has no `Addresses` ([mailwire.go:83](internal/mailwire/mailwire.go:83), `:99`). The spec explicitly extends `DomainView`, but does not give the corresponding sender-view changes. |
| + |
| + **Failure:** changing `mail.Sender` alone leaves the mailer unable to perform the specified scope/host checks, address authorization or tenant selection. |
| + |
| + **Fix:** list these projection fields and their exact JSON names, placing scope/host/addresses in slice 1 and tenant name in slice 3. Extend wire-parity tests to decode actual persisted sender JSON and verify legacy defaults. |
| + |
| + **Fault family:** persisted authority and enforcement projections must agree. |
| + |
| +8. **P2 — Decision 13: deletion omits the caller-index reservation created by decision 9.** |
| + |
| + `ResolveSenderNames` writes a global caller index ([sender.go:458](internal/mail/sender.go:458)). These keys lie outside the app prefix and require explicit deletion (`:350–355`). Existing teardown deletes indexes through provisioned IAM users, environments and standalones ([walk.go:1760](internal/mail/walk.go:1760)); all three are empty for the proposed instance sender. |
| + |
| + **Failure:** sender deletion and app purge leave the instance sender’s global name reservation behind. |
| + |
| + **Fix:** explicitly delete the sender-owned caller-index entry after tenant cleanup, with ownership checks and persisted naming information sufficient for retries. Include it in purge/recovery coverage. |
| + |
| + **Fault family:** every global reservation needs an owner-scoped cleanup path. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R2.md b/docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R2.md| new file mode 100644 |
| index 000000000..42de77f39 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R2.md |
| @@ -0,0 +1,78 @@ |
| +# Review findings: instance senders spec, round 2 (Astra, gpt-6-astra, on 6bb283e9a) |
| + |
| +Reviewed `6bb283e9a3f23be359c15ca0acc68b598c936980` against `origin/main` `43dce353f9c1e3ca6b28f0abb2091e4e61fd0fab`. No files changed, subagents spawned or tests run. |
| + |
| +Round 1 disposition: |
| + |
| +- **P1-1 — Resolved:** decision 11 specifies SES-safe encoding and attribution decoding. |
| +- **P1-2 — Resolved:** the atomic per-instance flag and persistent pause make the existing mailer refuse after its normal cache expiry. |
| +- **P1-3 — Partly resolved:** classifier and tenant resolution are addressed; shared-domain admission remains incomplete. Carried as P1 below. |
| +- **P1-4 — Resolved:** decision 6 uses the same canonical address for uniqueness and authorization. |
| +- **P1-5 — Partly resolved:** new associations have an explicit removal order, but legacy associations lack a compatible reading. Carried as P1 below. |
| +- **P2-6 — Resolved:** app sharing is preserved, with account-wide address uniqueness. |
| +- **P2-7 — Resolved:** §6 names the required projection fields and parity tests. |
| +- **P2-8 — Resolved:** decision 13 explicitly removes the caller-index reservation, with an ownership check. |
| + |
| +1. **P1 — Decision 14 / §5: holding the mail gate does not admit every owner of a shared identity.** |
| + |
| + **Evidence:** §5 specifies scope `(account, app)` at spec lines 146–148. The backend resolves every domain member plus the claim’s original app at `internal/console/claim_backends.go:440–449,468–476`. `internal/hostops/mutation_classifier.go:372–379` requires authority for **each** resulting scope. Nested admission cannot widen the original set: `internal/mail/claim_gate.go:389–400`. |
| + |
| + **Failure:** apps A and B share a domain, which decision 5 expressly preserves. Creating or adding an address grant for A’s instance in slice 3 associates A’s tenant with that identity and updates its `Tenants`. Admission for A alone cannot authorize the operation involving A and B. The revised name resolver does not fix this. |
| + |
| + **Fix:** specify the complete admission set before effects: all persisted domain members, the claim app, and the sender’s app, across every identity touched by create, address-add and delete. Exercise shared-domain operations through the production wrappers, including nested teardown. |
| + |
| + **Fault family:** resource ownership must be understood by every authorization boundary. **Carries R1 P1-3.** |
| + |
| +2. **P1 — Decisions 7 and 13: `Tenants` has no legacy default, so existing domains cannot be removed.** |
| + |
| + **Evidence:** decision 13 replaces account-only disassociation with iteration over `Tenants` (spec line 110). Existing `RegionState` has no such field (`internal/mail/domain.go:43–55`), yet existing provisioning associates the account tenant (`internal/mail/walk.go:354–374`). Removal currently explicitly disassociates that tenant before deleting the identity (`walk.go:1669–1676`). |
| + |
| + **Failure:** an existing domain decodes with empty `Tenants`. The proposed removal performs no disassociation, then SES refuses identity deletion because the account association still exists. Claim release remains unreached. AWS documents that associations must be removed before deleting associated resources: [https://docs.aws.amazon.com/ses/latest/dg/tenants.html](https://docs.aws.amazon.com/ses/latest/dg/tenants.html). |
| + |
| + **Fix:** define a backward-compatible effective association set that includes legacy account associations, or require a verified migration before changing removal. Preserve that inventory when `EnsureDomain` rebuilds `RegionState` at `walk.go:345–349`. Test removal of actual pre-change JSON and an ordinary domain re-ensure followed by removal. |
| + |
| + **Fault family:** resource deletion must account for every live association. **Carries R1 P1-5.** |
| + |
| +3. **P1 — Decisions 6 and 13: address cleanup loses its retry information before deleting the reservation.** |
| + |
| + **Evidence:** decision 6 creates the account-level index **before** the grant (spec line 103); decision 13 removes the grant **before** deleting its index and retries by walking the remaining grants (line 110). Sender records lie inside the app prefix, while the proposed address index lies outside it (`internal/mail/sender.go:146–153`). |
| + |
| + **Failure:** removal persists the grant deletion, then index deletion fails. On retry, the address is no longer among the sender’s grants. Cleanup can delete the sender record while leaving an account-wide reservation that permanently refuses another sender. Creation has the corresponding gap if index creation succeeds but grant persistence fails. |
| + |
| + **Fix:** retain a durable pending-address inventory until both operations finish, or perform a strict owner-scoped index sweep during recovery and sender deletion. Specify ownership-checked deletion and recovery for both create-before-grant and revoke-before-index failures. |
| + |
| + **Fault family:** every global reservation needs a durable owner-scoped recovery path. |
| + |
| +4. **P1 — §4’s existing-reader claim: `ListSenders` does not reliably return every instance sender.** |
| + |
| + **Evidence:** the spec says the plan pause reaches every instance through existing `ListSenders` (lines 119–121). That function silently skips a non-app sender whose read fails or whose JSON cannot decode (`internal/mail/mail.go:337–346`). The plan pause relies on this listing (`internal/console/planmail.go:95–109`). |
| + |
| + **Failure:** after the account reaches its plan limit, a transient read failure for one instance sender makes enforcement omit it without reporting an incomplete inventory. That sender remains unpaused and can continue sending from a mailer with a readable or cached record. The same listing is unsuitable for the proposed “any sender exists” and exhaustive teardown checks. |
| + |
| + **Fix:** require a strict sender inventory for account enforcement, mode transitions and teardown. A listed-but-unreadable sender must prevent a successful completeness result. Add a test injecting a read failure for one non-app sender. |
| + |
| + **Fault family:** decisions requiring complete ownership or enforcement inventories must fail closed on incomplete reads. |
| + |
| +5. **P2 — §9: slice 1 defers an address dependency guard to slice 2.** |
| + |
| + **Evidence:** slice 1 enables address grants (spec lines 290–298), but the app-domain removal refusal is assigned to slice 2 (lines 299–302). Existing removal checks only the app’s declared From (`internal/mail/walk.go:2006–2013`) before detaching the domain. |
| + |
| + **Failure:** during slice 1, an instance uses an address on a secondary app domain. Removing that domain succeeds and breaks the instance’s sending, contrary to decision 13’s dependency refusal. |
| + |
| + **Fix:** move the app-domain removal guard into slice 1, together with the address grant and revoke operations. |
| + |
| + **Fault family:** each shipped slice must preserve the dependencies it introduces. |
| + |
| +6. **P2 — §9 slice 3: existing instance senders have no tenant migration.** |
| + |
| + **Evidence:** slices 1 and 2 deliberately use the account tenant. Slice 3 specifies association on create, verify and address grant, but no transition for existing senders (spec lines 295,303–308). Decision 9 creates the tenant at sender creation (line 106). |
| + |
| + **Failure:** the canary sender created in slice 1 can reach slice 3 without another create, verify or grant operation. Its existing grants never acquire the promised tenant associations or tenant selection. |
| + |
| + **Fix:** specify an idempotent migration for existing instance senders. Reserve and create the tenant, associate all current resources, then publish `TenantName` only after those operations succeed. Define interruption and retry behavior. |
| + |
| + **Fault family:** rollout must migrate existing authority before selecting its new enforcement resources. |
| + |
| +The authorization and association families now recur across rounds 1 and 2. Under stopping rule 2, choose a narrower supported case—such as refusing shared-domain instance associations—or centralize the ownership and association invariants with guard tests before another fix round. No P3 findings. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R3.md b/docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R3.md| new file mode 100644 |
| index 000000000..a33682d7f |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R3.md |
| @@ -0,0 +1,44 @@ |
| +# Review findings: instance senders spec, round 3 (Astra, gpt-6-astra, on 456201938) |
| + |
| +- **R2 P1-1 — Partly resolved:** tenant-association writes are gone, but the existing domain-removal admission closure still exceeds `(account, app)`. Carried below. |
| +- **R2 P1-2 — Resolved:** removing `Tenants` preserves today’s account-tenant disassociation. |
| +- **R2 P1-3 — Resolved:** decision 15 retains durable reservation and release information until cleanup finishes. |
| +- **R2 P1-4 — Resolved:** `InstancesPause` removes the instance-list dependency from plan enforcement; switches and teardown require strict reads. |
| +- **R2 P2-5 — Resolved:** the app-domain removal guard moves into slice 1. |
| +- **R2 P2-6 — Resolved:** cutting instance tenants removes the migration requirement. |
| + |
| +Reviewed `4562019385474245a043cb15a364beee70175847`, limited to revision 3 and outstanding findings, against main `43dce353f`. No files changed, subagents spawned or tests run. |
| + |
| +1. **P1 — Decision 14 / sender deletion: single-app admission still cannot execute the existing domain-removal path.** |
| + |
| + **Evidence:** the spec declares `(account, app)` complete at lines 125 and 161–163, and retains `RemoveDomain`’s removal rules at line 124. However, `RemoveDomain` requests `Apps: [app], Domain: domain, Refresh: true` at `internal/mail/walk.go:2365`. The refresh closure includes other verified domains belonging to that app and all their members (`internal/mail/claim_gate.go:302–357`). Nested admission refuses any additional app at `claim_gate.go:389–395`. Removal also explicitly calls `RefreshPolicies` at `walk.go:2042`. |
| + |
| + **Failure scenario:** app A shares an existing verified domain with B, which decision 5 still permits. A’s instance owns a separate, exclusive domain. Deleting that instance sender under A-only admission invokes the removal path, whose refresh closure includes B. It fails with `ErrClaimMailPending`. Neither the tenant cut nor refusing address grants on shared domains prevents this case. |
| + |
| + **Fix:** specify an instance-owned domain removal path that does not invoke app IAM-policy refresh or its admission closure, and test it through production wrappers with A also holding an unrelated shared domain. Alternatively, refuse that app configuration before creating instance-owned domains. |
| + |
| + **Fault family:** resource ownership must be understood by every authorization boundary. **Carries R2 P1-1.** |
| + |
| +2. **P2 — Decisions 3 and 9 / §6: preserving tenant selection requires an explicit change to the send path.** |
| + |
| + **Evidence:** instance `TenantARN` is always empty (spec line 114), while the selected instance becomes “the sender” for subsequent steps (lines 195–199). Today `admit` returns that selected record in `decision.sender` (`internal/mailer/policy.go:227`), and `sendInput` includes `TenantName` only when `d.sender.TenantARN` is nonempty (`internal/mailer/ses.go:86–87`). |
| + |
| + **Failure scenario:** following the new selection logic while retaining today’s send construction omits `TenantName` for every instance send, despite decision 9 promising the app sender’s tenant. |
| + |
| + **Fix:** explicitly carry tenant selection from the app sender separately from the instance record used for authorization and limits. Add a fake-SES assertion that an instance with empty `TenantARN` sends with the app’s account tenant. |
| + |
| + **Fault family:** transport must preserve the selected enforcement resources. |
| + |
| +3. **P2 — Decisions 6 and 15: the sharing refusal omits pending reservations.** |
| + |
| + **Evidence:** decision 6 refuses another app’s domain addition only when an address **grant** exists (spec line 117). Decision 15 introduces durable `Reserving` state and completes it during recovery (line 126). The domain-removal refusal expressly covers grants, reservations and releases (line 124); the sharing refusal does not. Existing app-domain addition adds membership at `internal/mail/walk.go:221`. |
| + |
| + **Failure scenario:** A persists a reservation but does not finish granting it. After recovery of the failed operation permits further work, B adds the domain because no completed grant exists. A’s specified reservation recovery can then publish the grant on a now-shared domain. |
| + |
| + **Fix:** make the sharing guard inspect `Grant.Addresses`, `Reserving` and `Releasing` using a strict inventory under the gate. Include domain sharing in decision 15’s failure-injection scenarios. |
| + |
| + **Fault family:** exclusive ownership must hold throughout recoverable transitions. |
| + |
| +No P3 findings. The sole P1 has one cause: the existing refresh admission closure. Refusing apps with shared-domain dependencies up front, or cutting instance-owned domains while landing the address-only slice, removes that case. No fourth review round is authorized. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R1.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R1.md| new file mode 100644 |
| index 000000000..6d599610b |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R1.md |
| @@ -0,0 +1,87 @@ |
| +# Review brief: instance senders on mail submission (spec), round 1 of 3 |
| + |
| +Repo carlos/platform, branch `instance-senders-submission`, commit named in the reviewer's prompt. |
| +Under review: `docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md`. |
| +Authorities: `docs/superpowers/specs/2026-11-12-platform-mail-submission-design.md`, |
| +`docs/superpowers/specs/2026-09-15-tenant-email-senders-design.md` (both merged on main), |
| +and the code on `origin/main` `43dce353f`. Do not review against unmerged branches; if this |
| +work needs one, say so as a P1 and stop. |
| + |
| +You are an independent reviewer. Read the document, then the code it |
| +names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul's rulings on the submission design (its §11): the layout |
| + precondition is cut with the residual stated, and the cap counter is per |
| + box. Report only mechanisms in this spec that fail to honour them. |
| +- The choice to build on submission rather than Plan 5 (approach B) is the |
| + author's proposal, put to Paul on discussion #148. Challenge it only if B |
| + cannot work as written. |
| + |
| +## What to check |
| + |
| +1. **Isolation.** Can an instance of a per-instance app send as anything |
| + other than its own sender: another instance's domain or address, the |
| + app sender's domains, or with no sender at all? Check §6's admit order |
| + against `internal/mailer/policy.go` and the stamp (submission §6). |
| +2. **Ownership races.** Decisions 5 and 6: can two senders (or the app |
| + sender and an instance sender) both end up holding one domain or one |
| + address, through the claim (`internal/mail/domainclaim.go`, including |
| + `takeLapsedClaim` and same-account re-claims), the domain record's |
| + `Apps`/`Senders`, or the address index? Is the claim gate |
| + (`claim_gate.go`) enough for the writes named? |
| +3. **Existing readers of the shapes changed.** `PerInstance`, `CanSend`, |
| + `DomainRecord.Apps`, the claim, `SenderView`: does anything that parses |
| + or branches on them (event fallback, plan pause, resume, policy |
| + refresh, teardown, status, `ListDomains` users) misbehave once instance |
| + senders exist? Wire additivity of every added field. |
| +4. **Counting and pausing.** Decision 10: does `enforceMailLimits`, |
| + `resumeStaleCapPause`, the plan pause and `SenderOfCaller` actually work |
| + for an instance sender id as claimed, with the mailer's tag? |
| +5. **Teardown.** Decision 13: instance delete, sender delete, app teardown |
| + and purge. Can SES identities, claims, tenants or index keys be stranded, |
| + or can a delete remove something another sender still uses? |
| +6. **The `mail` role.** Decision 11: is it correctly placed in |
| + `internal/svcrole` (inside Admin's union), does it reach only §5's |
| + doors, and does anything in it let a credential mint a credential, |
| + raise a cap or read recipients (AGENTS.md "A credential never mints a |
| + credential")? |
| +7. **SES.** Decision 9: tenants per sender, association with shared |
| + identities for address grants, the mailer's IAM (`infra/modules/region-host/mailer.tf`). |
| + Anything that would fail at send time. |
| +8. **Order of work.** §9: does slice 1 stand alone (nothing it needs is in |
| + slice 2 or 3), and does each slice leave nothing dormant? |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section or task, the problem, |
| +the evidence (file:line, verified), the failure scenario, a concrete |
| +fix and the invariant or trust boundary it breaks (that is its fault |
| +family). End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +In round 3, a NOT READY also says whether the P1s share one cause, and |
| +whether refusing the case up front or cutting the feature would remove |
| +them. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R2.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R2.md| new file mode 100644 |
| index 000000000..4d5d9aef5 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R2.md |
| @@ -0,0 +1,101 @@ |
| +# Review brief: instance senders on mail submission (spec), round 2 of 3 |
| + |
| +Repo carlos/platform, branch `instance-senders-submission`, commit named in the reviewer's prompt. |
| +Under review: `docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md`. |
| +Authorities: `docs/superpowers/specs/2026-11-12-platform-mail-submission-design.md`, |
| +`docs/superpowers/specs/2026-09-15-tenant-email-senders-design.md` (both merged on main), |
| +and the code on `origin/main` `43dce353f`. Do not review against unmerged branches; if this |
| +work needs one, say so as a P1 and stop. |
| + |
| +You are an independent reviewer. Read the document, then the code it |
| +names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul's rulings on the submission design (its §11): the layout |
| + precondition is cut with the residual stated, and the cap counter is per |
| + box. Report only mechanisms in this spec that fail to honour them. |
| +- The choice to build on submission rather than Plan 5 (approach B) is the |
| + author's proposal, put to Paul on discussion #148. Challenge it only if B |
| + cannot work as written. |
| + |
| +## What to check |
| + |
| +1. **Isolation.** Can an instance of a per-instance app send as anything |
| + other than its own sender: another instance's domain or address, the |
| + app sender's domains, or with no sender at all? Check §6's admit order |
| + against `internal/mailer/policy.go` and the stamp (submission §6). |
| +2. **Ownership races.** Decisions 5 and 6: can two senders (or the app |
| + sender and an instance sender) both end up holding one domain or one |
| + address, through the claim (`internal/mail/domainclaim.go`, including |
| + `takeLapsedClaim` and same-account re-claims), the domain record's |
| + `Apps`/`Senders`, or the address index? Is the claim gate |
| + (`claim_gate.go`) enough for the writes named? |
| +3. **Existing readers of the shapes changed.** `PerInstance`, `CanSend`, |
| + `DomainRecord.Apps`, the claim, `SenderView`: does anything that parses |
| + or branches on them (event fallback, plan pause, resume, policy |
| + refresh, teardown, status, `ListDomains` users) misbehave once instance |
| + senders exist? Wire additivity of every added field. |
| +4. **Counting and pausing.** Decision 10: does `enforceMailLimits`, |
| + `resumeStaleCapPause`, the plan pause and `SenderOfCaller` actually work |
| + for an instance sender id as claimed, with the mailer's tag? |
| +5. **Teardown.** Decision 13: instance delete, sender delete, app teardown |
| + and purge. Can SES identities, claims, tenants or index keys be stranded, |
| + or can a delete remove something another sender still uses? |
| +6. **The `mail` role.** Decision 11: is it correctly placed in |
| + `internal/svcrole` (inside Admin's union), does it reach only §5's |
| + doors, and does anything in it let a credential mint a credential, |
| + raise a cap or read recipients (AGENTS.md "A credential never mints a |
| + credential")? |
| +7. **SES.** Decision 9: tenants per sender, association with shared |
| + identities for address grants, the mailer's IAM (`infra/modules/region-host/mailer.tf`). |
| + Anything that would fail at send time. |
| +8. **Order of work.** §9: does slice 1 stand alone (nothing it needs is in |
| + slice 2 or 3), and does each slice leave nothing dormant? |
| + |
| +## Round 2 |
| + |
| +Earlier rounds: `docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R1.md` |
| +(round 1, Astra, on revision 1). The round number counts every earlier |
| +review of this design or change, under any file name or reviewer. |
| + |
| +First give one line per P1 and P2 from round 1: resolved, partly, or not. |
| +Carry every unresolved or partly resolved finding forward at its current |
| +severity, then add new findings. The verdict covers everything |
| +outstanding, earlier rounds included. The spec's Appendix A maps each |
| +finding to its answer. Revision 2 adds decisions 11 (tag encoding) and 14 |
| +(authorization boundaries) and rewrites 2, 5, 6, 7, 9 and 13: check those |
| +mechanisms against the code as hard as the originals. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section or task, the problem, |
| +the evidence (file:line, verified), the failure scenario, a concrete |
| +fix and the invariant or trust boundary it breaks (that is its fault |
| +family). End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +In round 3, a NOT READY also says whether the P1s share one cause, and |
| +whether refusing the case up front or cutting the feature would remove |
| +them. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R3.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R3.md| new file mode 100644 |
| index 000000000..cc1247a91 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-instance-senders-R3.md |
| @@ -0,0 +1,105 @@ |
| +# Review brief: instance senders on mail submission (spec), round 3 of 3 |
| + |
| +Repo carlos/platform, branch `instance-senders-submission`, commit named in the reviewer's prompt. |
| +Under review: `docs/superpowers/specs/2026-11-30-instance-senders-on-submission-design.md`. |
| +Authorities: `docs/superpowers/specs/2026-11-12-platform-mail-submission-design.md`, |
| +`docs/superpowers/specs/2026-09-15-tenant-email-senders-design.md` (both merged on main), |
| +and the code on `origin/main` `43dce353f`. Do not review against unmerged branches; if this |
| +work needs one, say so as a P1 and stop. |
| + |
| +You are an independent reviewer. Read the document, then the code it |
| +names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul's rulings on the submission design (its §11): the layout |
| + precondition is cut with the residual stated, and the cap counter is per |
| + box. Report only mechanisms in this spec that fail to honour them. |
| +- The choice to build on submission rather than Plan 5 (approach B) is the |
| + author's proposal, put to Paul on discussion #148. Challenge it only if B |
| + cannot work as written. |
| + |
| +## What to check |
| + |
| +1. **Isolation.** Can an instance of a per-instance app send as anything |
| + other than its own sender: another instance's domain or address, the |
| + app sender's domains, or with no sender at all? Check §6's admit order |
| + against `internal/mailer/policy.go` and the stamp (submission §6). |
| +2. **Ownership races.** Decisions 5 and 6: can two senders (or the app |
| + sender and an instance sender) both end up holding one domain or one |
| + address, through the claim (`internal/mail/domainclaim.go`, including |
| + `takeLapsedClaim` and same-account re-claims), the domain record's |
| + `Apps`/`Senders`, or the address index? Is the claim gate |
| + (`claim_gate.go`) enough for the writes named? |
| +3. **Existing readers of the shapes changed.** `PerInstance`, `CanSend`, |
| + `DomainRecord.Apps`, the claim, `SenderView`: does anything that parses |
| + or branches on them (event fallback, plan pause, resume, policy |
| + refresh, teardown, status, `ListDomains` users) misbehave once instance |
| + senders exist? Wire additivity of every added field. |
| +4. **Counting and pausing.** Decision 10: does `enforceMailLimits`, |
| + `resumeStaleCapPause`, the plan pause and `SenderOfCaller` actually work |
| + for an instance sender id as claimed, with the mailer's tag? |
| +5. **Teardown.** Decision 13: instance delete, sender delete, app teardown |
| + and purge. Can SES identities, claims, tenants or index keys be stranded, |
| + or can a delete remove something another sender still uses? |
| +6. **The `mail` role.** Decision 11: is it correctly placed in |
| + `internal/svcrole` (inside Admin's union), does it reach only §5's |
| + doors, and does anything in it let a credential mint a credential, |
| + raise a cap or read recipients (AGENTS.md "A credential never mints a |
| + credential")? |
| +7. **SES.** Decision 9: tenants per sender, association with shared |
| + identities for address grants, the mailer's IAM (`infra/modules/region-host/mailer.tf`). |
| + Anything that would fail at send time. |
| +8. **Order of work.** §9: does slice 1 stand alone (nothing it needs is in |
| + slice 2 or 3), and does each slice leave nothing dormant? |
| + |
| +## Round 3 |
| + |
| +Earlier rounds: `docs/superpowers/specs/CODEX-FINDINGS-instance-senders-R1.md` |
| +(round 1) and `CODEX-FINDINGS-instance-senders-R2.md` (round 2), both |
| +Astra. **Stopping rule 2 has triggered** for three families (see the |
| +spec's review history). Revision 3 does not write third fixes: it cuts |
| +per-instance SES tenants (decision 9), refuses address grants on shared |
| +domains up front (decision 6), and states two invariants enforced in one |
| +place with guard tests (decisions 15 and 16). **This round is limited to |
| +revision 3's diff against revision 2 (`6bb283e9a..HEAD`) and to whether |
| +those choices remove the findings.** Do not reopen resolved findings. |
| + |
| +First give one line per P1 and P2 from round 2: resolved, partly, or not. |
| +Carry every unresolved or partly resolved finding forward at its current |
| +severity, then add new findings only in the revision 3 diff. The verdict |
| +covers everything outstanding. Appendix B maps each round-2 finding to |
| +its answer. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section or task, the problem, |
| +the evidence (file:line, verified), the failure scenario, a concrete |
| +fix and the invariant or trust boundary it breaks (that is its fault |
| +family). End with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +In round 3, a NOT READY also says whether the P1s share one cause, and |
| +whether refusing the case up front or cutting the feature would remove |
| +them. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |