carlos / platform Public

transfers plan: one settlement function (Paul's round 2 ruling)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2d1b31d01e17bc04feb2ab6092aedc8ce7c80d03 parent d2c3c5f
3 files changed, +162 −31
  • docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md +53 −31
  • docs/superpowers/reviews/CODEX-FINDINGS-domain-transfers-plan-R2.md +71 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-domain-transfers-plan-R3.md +38 −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-27vlVk
.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/benbjohnson/litestream v0.5.14
go: downloading github.com/superfly/ltx v0.5.1
go: downloading golang.org/x/net v0.62.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading golang.org/x/sys v0.49.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 golang.org/x/crypto v0.58.0
go: downloading github.com/aws/aws-sdk-go-v2/service/sns v1.43.0
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/aws/aws-sdk-go-v2/service/ssm v1.74.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14
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/s3shared v1.19.31
go: downloading golang.org/x/text v0.43.0
go: downloading github.com/prometheus/client_golang v1.17.0
go: downloading github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.18
go: downloading github.com/pion/randutil v0.1.0
go: downloading github.com/pion/transport/v4 v4.0.2
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/beorn7/perks v1.0.1
go: downloading github.com/prometheus/client_model v0.5.0
go: downloading github.com/cespare/xxhash/v2 v2.3.0
go: downloading github.com/prometheus/procfs v0.12.0
go: downloading google.golang.org/protobuf v1.36.10
go: downloading github.com/prometheus/common v0.45.0
go: downloading github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/wlynxg/anet v0.0.5
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/wlynxg/anet v0.0.5
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 github.com/google/uuid v1.6.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading modernc.org/mathutil v1.7.1

amadan: job cancelled — a newer push superseded it
diff --git a/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md b/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md
index de844ef7f..d1b004387 100644
--- a/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md
+++ b/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md
@@ -12,7 +12,7 @@
**Plans in this series:** 1 buy (live). 2a account-level domains (merged 69b44f53, v0.40.3 on dev). **Transfers in (this plan), ahead of 2b and 3 (spec R16).** 2b reconcile/reconverge/alerts. 3 renewals (must ship within a year of the first completed transfer). 4 customer records, change owner, transfer out.
-**Review history:** Astra round 1 on b77e1ec7 (`docs/superpowers/reviews/CODEX-FINDINGS-domain-transfers-plan.md`): NOT READY, 7 P1 and 4 P2, all accepted and folded in, marked **(r1 N)**.
+**Review history:** Astra round 1 on b77e1ec7 (`docs/superpowers/reviews/CODEX-FINDINGS-domain-transfers-plan.md`): NOT READY, 7 P1 and 4 P2, all accepted and folded in, marked **(r1 N)**. Astra round 2 on d2c3c5fc (`CODEX-FINDINGS-domain-transfers-plan-R2.md`): NOT READY, 4 P1 and 1 P2; the payment, refund and unknown-mutation families repeated, so stopping rule 2 applied. **Paul's ruling, 2026-11-22: one settlement function.** Every transfer decision is made by one pure function over a closed set of registrar, payment and refund outcomes, checked by a randomized simulation of outcomes and crash points (Task 6); round 2's findings are resolved inside it, marked **(r2 N)**. Round 3 is the last.
**Switch-on:** rides the buy door (`domainBuyReady`; off while `CARLOS_HOST_CLAIM` is on). The first real transfer is rushedsunlight.com on flagship after the release, with Paul's GO and his auth code (spec §12.7).
@@ -23,7 +23,8 @@
- Registrar-side auto-renew OFF and WHOIS privacy where the TLD allows it, on every transfer (§5.5, §4.4).
- **The auth code is a secret (§7.4, anti-goal):** never logged, never in a URL or query string, never in an error string or `%v`/`%#v` output. It is held in the purchase record from start until the CAS move that records the submit; that same move clears it and the code travels to the registrar from memory only (r1 4). Every pre-submit terminal path (Checkout expired, contact refusal, setup deadline, any failure) clears it too. The CLI reads it from `--auth-code -` (stdin) as well as the flag value.
- **A transfer request is sent at most once (r1 3).** Openprovider offers no idempotency key, so after an unknown answer the engine never resends; it settles only from `TransferStatus` reads, never from a later request's outcome.
-- **Terminal states need confirmed outcomes (r1 1, r1 2):** `done`, `unpaid` and `failed` are entered only once both the registrar outcome and the payment outcome (captured, cancelled, lapsed, or refund confirmed) are known; a lost payment answer is resolved by reading the PaymentIntent (`PaymentCheckout`), never by re-sending and trusting the reply.
+- **One settlement function (Paul, 2026-11-22):** `decideTransfer` (Task 6) is the only place that chooses a transfer's next action or terminal state; the engine only gathers facts, calls it, performs the one action it returns, and records the result. Its invariants (Task 6) are the plan's money rules, and the randomized simulation checks them across every outcome and crash point.
+- **An unknown registrar outcome is never settled by the engine (r2 3).** A transfer whose acceptance or result is unknown stays live (it blocks account deletion and any other purchase of the domain) until the registrar gives a definite answer or an operator records a resolution (Task 6's operator door). Payment lapsing does not end it.
- Refusals before payment (§12.3): not registrable, TLD not marked transferable in the catalog, premium, already registered with Carloku, another ACCOUNT's claim on the apex or `www` (this account's own claims are allowed and left untouched), DNSSEC-signed (a DS record exists), nameservers unreadable, the registrar's transfer check says no, the buying entitlement (custom-domain entitlement incl. sponsored accounts), the daily cap (transfers count with purchases), and the registrar balance covering the transfer cost (§6.3: refuse and alert the operator, as buying does). Neutral refusals stay byte-identical to the buying ones.
- A completed transfer records a `DomainRegistration` with `ZoneID ""`. Every Plan 1/2a path that reads a registration must handle an empty zone: Point refuses it ("its DNS is hosted elsewhere"), the domain page shows records to set at the DNS host.
- No registrar or DNS host name in any customer-facing string; every new string is a draft in a `*_copy.go` file until the copy pass (Task 11). No em or en dashes; curly quotes in prose; nothing says the domain "renews".
@@ -36,7 +37,7 @@
## Review Focus
1. **A wrong or stale auth code.** Expected: the registrar refuses at submit (authorisation cancelled, nothing taken) or fails after acceptance (capture refunded); the card ends Failed with "the transfer code was not accepted" copy and Refunded/Not charged. Tests in Task 6: `TestTransferRefusedAtSubmitCancelsAuthorisation`, `TestTransferFailsAfterAcceptanceRefunds`.
-2. **The losing registrar says nothing for a week.** Expected: the transfer stays waiting (`transfer_submitting` when acceptance is unknown, `transfer_pending` once accepted), status read every 30 minutes, never resent; operator alerts at 24 h unknown and a day before the authorisation lapses; an unconfirmed transfer is then cancelled uncharged and watched for 14 days, and a completion seen later is recorded `unpaid` (auto-renew off) as the customer's. Test in Task 6: `TestTransferUnknownAlertsAndLateCompletionIsUnpaid`.
+2. **The losing registrar says nothing for a week.** Expected: the transfer stays waiting (`transfer_submitting` when acceptance is unknown, `transfer_pending` once accepted), status read every 30 minutes, never resent; operator alerts at 24 h unknown and a day before the authorisation lapses; an unconfirmed transfer stays live (blocking deletion and a second transfer) until the registrar answers or an operator resolves it; a completion after the hold lapsed is recorded `unpaid` (auto-renew off) as the customer's. Tests in Task 6: `TestDecideTransferSimulation`, `TestTransferUnknownStaysLiveBlocksDeletionAndSecondStart`.
3. **Nameservers can't be read** (NXDOMAIN, SERVFAIL, an empty answer, or a resolver timeout). Expected: refused before payment with "we couldn't read this domain's nameservers, try again" copy; a transfer is never sent with no nameservers. Tests in Task 6: `TestTransferStartRefusesUnreadableNameservers` and in Task 2 the adapter refuses an empty list (`TestRequestTransferRefusesEmptyNameservers`).
4. **The auth code leaks.** Expected: absent from every log line, error, URL and stored record after submit; `String`/`GoString` of the request redacted. Tests: Task 2 `TestTransferRequestStringRedactsAuthCode`, Task 6 `TestTransferAuthCodeClearedAtSubmitAndNeverLogged` (captures the log output of a whole transfer and greps for the code).
5. **A transferred domain (no zone) on Plan 2a's paths.** Expected: the Domains page shows "Bought here" with expiry; the domain page shows Renewal, Registered to, Addresses and records to set, plus "DNS hosted elsewhere"; Point refuses with a plain message and writes nothing; account deletion counts it. Tests in Task 8: `TestTransferredDomainPageShowsDNSElsewhere`, `TestPointRefusesDomainWithoutZone`.
@@ -116,15 +117,17 @@
Amount int64
Currency string
}
+ // RefundInfo also carries Attempt int (from the refund's metadata "attempt", set at create) (r2 2)
// Result gains: Refund *RefundInfo
+ // PaymentInfo gains: CaptureBefore time.Time (Stripe's card capture_before; zero when the provider doesn't say) (r2 5)
// Provider gains:
- PrepareRefund(paymentIntent, key string) (Prepared, error) // full refund of a captured PaymentIntent
+ PrepareRefund(paymentIntent, purchase string, attempt int, key string) (Prepared, error) // full refund of a captured PaymentIntent, tagged with purchase and attempt
Refund(ctx context.Context, refundID string) (RefundInfo, error) // read: reconcile a pending or lost refund
Refunds(ctx context.Context, paymentIntent string) ([]RefundInfo, error) // list: find a refund whose create answer was lost past key retention
```
- Stripe: `POST /v1/refunds` (`payment_intent`, idempotency key from `key`), `GET /v1/refunds/{id}`, `GET /v1/refunds?payment_intent=`; outcomes through the existing `classify`, so a lost create is indeterminate. The fake: refund lifecycle with scripted status changes (pending → succeeded or failed). Every `billing.Provider` implementation compiles (`git grep -n 'billing.Provider' -- '*.go'`).
+ Stripe: `POST /v1/refunds` (`payment_intent`, `metadata[purchase]`, `metadata[attempt]`, idempotency key from `key`), `GET /v1/refunds/{id}`, `GET /v1/refunds?payment_intent=`; outcomes through the existing `classify`, so a lost create is indeterminate. The fake: refund lifecycle with scripted status changes (pending → succeeded or failed). Every `billing.Provider` implementation compiles (`git grep -n 'billing.Provider' -- '*.go'`).
-- [ ] **Step 1: Write failing tests:** `TestRefundFormAndIdempotency`, `TestRefundLostAnswerIsIndeterminate`, `TestRefundReadAndListByPaymentIntent`, `TestFakeRefundLifecyclePendingToSucceededOrFailed`.
+- [ ] **Step 1: Write failing tests:** `TestRefundFormAndIdempotency` (metadata purchase and attempt sent), `TestRefundLostAnswerIsIndeterminate`, `TestRefundReadAndListByPaymentIntent` (Attempt parsed from metadata), `TestFakeRefundLifecyclePendingToSucceededOrFailed`, `TestPaymentCheckoutReadsCaptureBefore`.
- [ ] **Step 2: Run** `go test ./internal/billing/... ./internal/billingstripe/ -run Refund`; expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run**; expect PASS; `go vet ./internal/billing/... ./internal/billingstripe/ ./internal/console/`.
@@ -165,20 +168,17 @@
AuthCode string // cleared in the move that enters transfer_submitting (r1 4) and on every pre-submit terminal path; never logged
Nameservers []string // read at check, sent at submit
SubmittedAt time.Time
- Accepted bool // the registrar has the transfer (status pending or completed seen)
- Completed *registrar.Registered // the registrar reported completion; kept while the payment outcome is still being confirmed (r1 1)
- RegistrarFailed string // the registrar reported failure (reason); kept while payment is settled
- Payment string // confirmed payment outcome: "", "captured", "cancelled", "lapsed", "capture_refused"
- RefundID string // the refund being confirmed (r1 2)
- RefundAttempt int // bumps the refund key after a definite refund failure
- Refunded bool // refund confirmed succeeded
- UnknownAlerted, LapseAlerted bool
- NextStatusAt time.Time // next transfer status read (30 min cadence)
- WatchUntil time.Time // a transfer failed as unconfirmed keeps a daily status read until then (14 days)
+ Facts transferFacts // Task 6: the recorded registrar, payment and refund outcomes
+ CaptureBefore time.Time // provider's authorisation deadline, or CreatedAt + 6 days when unknown (r2 5)
+ Alerts map[string]time.Time // alert kind -> last sent (24h-unknown, lapse, weekly-unknown, capture-refused, refund-failed)
+ NextStatusAt time.Time // next registrar status read: 30 minutes for the first 7 days after submit, then daily
+ Resolution string // operator-recorded outcome for an unknown transfer: "failed" or "completed"
+ ResolvedBy string
+ ```
+ ```go
func (s *Store) PendingTransfers(ctx context.Context) ([]DomainPurchase, error) // kind transfer, live
func (s *Store) RegistrationsExpiringBefore(ctx context.Context, t time.Time) ([]DomainRegistration, error) // expires_at < t and expiry_alerted_at = 0
func (s *Store) MarkExpiryAlerted(ctx context.Context, domain string, at time.Time) error
- func (s *Store) WatchedTransfers(ctx context.Context, now time.Time) ([]DomainPurchase, error) // failed transfers with WatchUntil > now
```
Schema: `ALTER TABLE domain_purchases ADD COLUMN kind ...`, `ALTER TABLE domain_registrations ADD COLUMN expiry_alerted_at INTEGER NOT NULL DEFAULT 0` (the duplicate-column tolerant loop). The new states are live (not in `liveDomainPurchaseSQL`'s terminal list), so the one-live-purchase-per-domain index and `DomainObligations` cover transfers. `String()`/`GoString()` on `purchaseDetails` (or wherever purchases are formatted for logs) redact `AuthCode`.
@@ -191,7 +191,7 @@
### Task 6: The transfer engine (risky: per-task review)
**Files:**
-- Create: `internal/console/domaintransfer.go`, `internal/console/domaintransfer_test.go`, `internal/console/domaintransfer_copy.go`
+- Create: `internal/console/domaintransfer.go`, `internal/console/domaintransfer_decide.go`, `internal/console/domaintransfer_decide_test.go` (table and simulation), `internal/console/domaintransfer_test.go`, `internal/console/domaintransfer_copy.go`
- Modify: `internal/console/domainbuy.go` (dispatch transfer-kind purchases to the transfer steps from `advancePurchaseStep`; reuse `purchaseCheckout`, `purchaseMutation`, `movePurchase`, `purchaseAlert`, `purchaseOwnerNotice`), `internal/console/server.go` (`Config.LookupNS func(ctx, name) ([]*net.NS, error)` defaulting to `net.DefaultResolver.LookupNS`, and `Config.LookupDS func(ctx, name) (bool, error)` defaulting to `lookupDS` below)
- Create: `internal/console/dnsds.go`, `internal/console/dnsds_test.go`
@@ -206,21 +206,43 @@
func lookupDS(ctx context.Context, server string, name string) (bool, error) // DS = dnsmessage.Type(43) read as UnknownResource (no TypeDS constant); UDP to server, TCP fallback on truncation; error on SERVFAIL, mismatched ID/question, malformed reply or timeout (r1 9)
// Config gains DNSServer string (host:port; default: the first nameserver in /etc/resolv.conf); tests point it at a local responder.
```
- Steps, each one CAS move (spec §12.4). The registrar and payment outcomes are tracked separately (`Accepted`, `Completed`, `RegistrarFailed`, `Payment`, `Refunded`); a terminal state is entered only when both are known (r1 1):
- 1. `awaiting_payment` → `authorised`: as buying (Checkout, `PaymentCheckout`). Expiry, contact refusal and the setup deadline clear `AuthCode` in their terminal move (r1 4).
- 2. **Submit, once (r1 3, r1 4):** read the `AuthCode` into memory, then CAS `authorised` → `transfer_submitting` recording `SubmittedAt` and clearing `AuthCode`; only after that move commits, `RequestTransfer(...)` with the in-memory code. Accepted (pending) → `Accepted`, `transfer_pending`. `ErrRefused` → cancel the authorisation → `Payment: cancelled` → `failed` (reason). `ErrIndeterminate`, or a crash before or after the call: stay in `transfer_submitting` and NEVER resend; each pass (every 30 minutes) reads `TransferStatus`: pending/completed → `Accepted`, `transfer_pending`; failed → cancel → `failed`; none → keep waiting. Operator alert once at 24 h (`UnknownAlerted`). A day before the authorisation lapses (6 days after `SetupStartedAt`) with status still none: alert (`LapseAlerted`), cancel the authorisation, `failed` with reason `unconfirmed` and `WatchUntil` = now + 14 days (step 5). A crash after the clearing move and before the call leaves status none and ends the same way, nothing charged; the customer starts again with a fresh code.
- 3. **`transfer_pending`, payment:** if `Payment` is "", resolve it first: read `PaymentCheckout` for the PaymentIntent status; `succeeded` → `captured`; `requires_capture` → `Send(PrepareCapture(pi, id+":capture"))`, then read again (never trust a capture reply alone past Stripe's 24 h key retention); `canceled` or expired authorisation → `lapsed`; a definite capture refusal while still `requires_capture` → `capture_refused` with an operator alert. Indeterminate → retry next pass.
- 4. **`transfer_pending`, registrar:** at `NextStatusAt` (every 30 minutes) read `TransferStatus`: completed → store `Completed`; failed → store `RegistrarFailed`. Then settle:
- - `Completed` and `Payment` known → record the registration idempotently (r1 5: factor buying's existing-row check at `registeredPurchase`, `domainbuy.go:983-1000`, into one helper that accepts an existing row only when account, domain and registrar ID match) with `ZoneID ""`, `Expires` from the registrar, the frozen registrant, `AutoRenew` true when `captured`, false otherwise (r1 10); then `done` when `captured`, else `unpaid` (owner notice + operator alert, as `domainbuy.go:709`).
- - `RegistrarFailed` and `Payment` `captured` → `transfer_refunding`; `RegistrarFailed` and anything else → cancel the authorisation if still `requires_capture` (ignore already cancelled or lapsed) → `failed`.
- 5. **`transfer_refunding` (r1 2):** no `RefundID` → first `Refunds(pi)` (a refund created by a lost answer is found here), else `Send(PrepareRefund(pi, fmt.Sprintf("%s:refund:%d", id, RefundAttempt)))` and store its `RefundID`. Then read `Refund(RefundID)`: `succeeded` → `Refunded`, `failed` (reason, "refunded"); `pending`/`requires_action` → stay; `failed`/`canceled` → operator alert, `RefundAttempt++`, clear `RefundID`, retry. Every failed charged transfer ends with a confirmed refund.
- 6. **Watch (r1 3):** the daily pass (Task 7) reads `TransferStatus` for `WatchedTransfers`; a completion means the first request did take effect: record the registration (idempotent helper) as `unpaid` with `AutoRenew` false, operator alert and owner notice. Loss bounded by one transfer fee (spec T6).
+ **The settlement function** (`internal/console/domaintransfer_decide.go`, pure, no I/O):
+ ```go
+ type registrarOutcome int // rNotSent, rUnknown (sent, no definite answer), rPending (accepted), rCompleted, rFailed (r2 4: an enum; the reason is kept beside it)
+ type paymentOutcome int // pUnknown, pAuthorised (requires_capture), pCaptured (succeeded), pCancelled (canceled or lapsed, nothing taken), pFailed (requires_payment_method or another definite failure after a capture attempt, nothing taken) (r2 1)
+ type refundOutcome int // fNone, fPending (current attempt pending or requires_action), fSucceeded (current attempt succeeded AND amount and currency equal the capture), fFailed (current attempt failed or canceled)
+ type transferFacts struct {
+ Registrar registrarOutcome; RegistrarReason string; Completed *registrar.Registered
+ Payment paymentOutcome
+ Refund refundOutcome; RefundAttempt int; RefundID string
+ Resolution string // operator: "", "failed", "completed"
+ Now, SubmittedAt, CaptureBefore time.Time
+ }
+ type transferAction int // aWait, aSubmit, aCapture, aCancelAuthorisation, aCreateRefund, aRecordDone, aRecordUnpaid, aFinishFailed, aAlert
+ type transferDecision struct { Action transferAction; Alert string; Terminal PurchaseState /* "" unless the action ends the purchase */ }
+ func decideTransfer(f transferFacts) transferDecision
+ ```
+ Decision table (exhaustive over the enums; anything not listed is `aWait`):
+ - `rNotSent` + `pAuthorised` → `aSubmit`; `rNotSent` + `pCancelled`/`pFailed` → `aFinishFailed` (not charged).
+ - `rUnknown` → `aWait`, with `aAlert` at 24 h after submit, a day before `CaptureBefore`, then weekly; never terminal (r2 3). `Resolution` "failed" → treat as `rFailed`; "completed" → treat as `rCompleted` with the operator-confirmed registration.
+ - `rPending` + `pAuthorised` → `aCapture`. `rPending` + anything else → `aWait` (a capture refused or failed is alerted once).
+ - `rCompleted` + `pCaptured` → `aRecordDone` (terminal `done`). `rCompleted` + `pAuthorised` → `aCapture`. `rCompleted` + `pCancelled`/`pFailed` → `aRecordUnpaid` (terminal `unpaid`, auto-renew off, owner notice, alert). `rCompleted` + `pUnknown` → `aWait`.
+ - `rFailed` + `pAuthorised` → `aCancelAuthorisation`. `rFailed` + `pCancelled`/`pFailed` → `aFinishFailed` (not charged). `rFailed` + `pCaptured`: refund `fNone` or `fFailed` → `aCreateRefund` (attempt + 1 after a failure, with an alert); `fPending` → `aWait`; `fSucceeded` → `aFinishFailed` (refunded). `rFailed` + `pUnknown` → `aWait`.
+ Invariants, asserted by `TestDecideTransferSimulation` (randomized: 10,000 runs of random registrar, payment and refund answers, lost answers, provider lag and a crash after any step, replayed through the real engine over the fakes and a fresh `Server` on restart; fixed seed printed on failure):
+ I1 a terminal state is only reached with `Registrar` in {rCompleted, rFailed} or an operator resolution; I2 `done` ⇒ captured; I3 `unpaid` ⇒ completed and nothing captured; I4 terminal `failed` ⇒ nothing captured, or a refund of the full captured amount and currency succeeded; I5 `RequestTransfer` is called at most once per purchase; I6 at most one refund attempt is outstanding, and a failed attempt is never selected again (r2 2); I7 the purchase stays live (counted by `DomainObligations`, holding the domain's unique index) until terminal; I8 no `AuthCode` in the record after the submit move.
+
+ **The engine** (`domaintransfer.go`), one pass per live transfer purchase:
+ 1. **Gather facts:** registrar status (`TransferStatus`, at `NextStatusAt` only; before submit it is `rNotSent`; after submit, none or an error is `rUnknown`; the reason is stored beside the outcome); payment (`PaymentCheckout` read of the PaymentIntent: `requires_capture` → pAuthorised, `succeeded` → pCaptured, `canceled` → pCancelled, `requires_payment_method` or a failed capture → pFailed, unreadable → pUnknown; `CaptureBefore` stored when the provider gives it); refund (`Refund(RefundID)`, or when `RefundID` is empty `Refunds(pi)` filtered to metadata purchase = this purchase AND attempt = `RefundAttempt` (r2 2), ignoring other attempts).
+ 2. **Decide:** `decideTransfer(facts)`.
+ 3. **Act**, then record facts and the result in one CAS move: `aSubmit` is the at-most-once submit (CAS to `transfer_submitting` clearing `AuthCode`, then `RequestTransfer` from memory; a crash after the move is `rUnknown`, settled only by status or an operator); `aCapture` `PrepareCapture(pi, id+":capture")`; `aCancelAuthorisation` `PrepareCancelPayment`; `aCreateRefund` `PrepareRefund(pi, id, attempt, fmt.Sprintf("%s:refund:%d", id, attempt))` storing `RefundID`; `aRecordDone`/`aRecordUnpaid` the idempotent registration helper (r1 5) then the terminal move; `aFinishFailed` the terminal move; `aAlert` `alertOperator` (Task 7), recording the send only on delivery.
+ Whatever a send answers, the next pass's fact gathering, not the send's reply, decides what happened.
+ **Operator resolution (r2 3):** `POST /api/cli/accounts/{account}/domains/purchases/{id}/resolve` `{"outcome":"failed"|"completed","note"}`, gated as the existing system-operator doors (find the gate the billing operator pages use: `git grep -n 'systemOperator\|SystemOperator' internal/console`), service-closed, audited; only for a transfer whose registrar outcome is `rUnknown`; records `Resolution` and `ResolvedBy`. "completed" requires the registrar's `Lookup` to show the domain in our account (its `Registered` becomes `Completed`).
Start refusals, all before Checkout: the Global Constraints list, plus `CheckTransfer` and `QuoteTransfer` errors mapped to plain copy (`domaintransfer_copy.go`, drafts). Nameservers come from `LookupNS` (lower-case, trailing dot stripped, sorted); none or an error → refusal. `LookupDS` true → the DNSSEC refusal; error → "couldn't check, try again" refusal (fail closed).
-- [ ] **Step 1: Write failing tests** on a transfer fixture beside `newPurchaseFixture`: `TestTransferHappyPathRecordsRegistrationWithoutZone` (nameservers sent = those read; registrant frozen; registration ZoneID ""; expiry from the fake; payment captured once; claims untouched), `TestTransferStartRefusals` (table: not registrable, TLD unmarked, premium, already ours, another account's apex claim, own apps' claims ALLOWED, DS present, DS lookup error, NS unreadable, empty NS, check says locked, daily cap, sponsored account allowed), `TestTransferRefusedAtSubmitCancelsAuthorisation`, `TestTransferFailsAfterAcceptanceRefunds`, `TestTransferRefundIndeterminateRetriesAndAlertsOnDefiniteFailure`, `TestTransferCaptureFailsThenCompletesIsUnpaid`, `TestTransferUnknownAlertsAndLateCompletionIsUnpaid` (Review Focus 2), `TestTransferIndeterminateSubmitNeverResends` (status none for days: one RequestTransfer call; a day before lapse, cancelled + failed unconfirmed + watched), `TestTransferLostRequestThatAppliedIsFoundByStatus` (`RequestApplies`), `TestTransferCrashAfterClearingMoveFailsUnchargedWhenNeverSent`, `TestTransferCaptureLostAnswerResolvedByPaymentRead` (capture applied, answer lost; restart past key retention; the PaymentIntent read says succeeded, no second capture), `TestTransferCaptureNeverSentStaysPending` (no terminal state until the payment outcome is known), `TestTransferRefundPendingThenSucceeded`, `TestTransferRefundFailedRetriesWithNewKey`, `TestTransferRefundLostAnswerFoundByList`, `TestTransferCompletionReplayAfterCrashBetweenInsertAndMove` (r1 5), `TestTransferUnpaidCompletionAutoRenewOff`, `TestTransferWatchRecordsLateCompletionUnpaid`, `TestTransferAuthCodeClearedOnEveryPreSubmitTerminal`, `TestBuyAndTransferResumeOnlyTheirOwnKind` (r1 8: a buy request for a domain with a live transfer is refused, and the reverse; neither resumes the other's Checkout), `TestTransferStatusReadEveryThirtyMinutesOnly` (a fake clock; count `TransferStatus` calls), `TestTransferAuthCodeClearedAtSubmitAndNeverLogged` (Review Focus 4), `TestTransferResumesAfterRestart` (new Server over the same store mid-`transfer_submitting`: one request, one capture), `TestLookupDSAnswersAndFailures` (a local responder on an ephemeral 127.0.0.1 port via `Config.DNSServer`: DS present, NODATA, NXDOMAIN, SERVFAIL, mismatched ID, malformed, timeout, truncated UDP then TCP; no network).
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestTransfer|TestLookupDS'`; expect FAIL.
+- [ ] **Step 1: Write failing tests:** `TestDecideTransferTable` (every row of the decision table above, incl. pFailed after completion → unpaid, an empty-reason rFailed after capture → refund, a failed refund attempt → a new attempt), `TestDecideTransferSimulation` (invariants I1-I8, randomized as above), and on a transfer fixture beside `newPurchaseFixture`: `TestTransferHappyPathRecordsRegistrationWithoutZone` (nameservers sent = those read; registrant frozen; registration ZoneID ""; expiry from the fake; captured once; claims untouched), `TestTransferStartRefusals` (table: not registrable, TLD unmarked, premium, already ours, another account's apex claim, own apps' claims ALLOWED, DS present, DS lookup error, NS unreadable, empty NS, check says locked, daily cap, registrar balance short, sponsored account allowed), `TestTransferUnknownStaysLiveBlocksDeletionAndSecondStart` (r2 3), `TestTransferOperatorResolveOnlyForUnknownAndAudited`, `TestTransferCaptureBeforeDrivesLapseAlert` (r2 5: authorisation observed late; the alert still comes a day before the provider's deadline; fallback CreatedAt + 6 days), `TestTransferRefundIgnoresFailedEarlierAttemptInList` (r2 2), `TestTransferAuthCodeClearedAtSubmitAndNeverLogged` (Review Focus 4), `TestTransferAuthCodeClearedOnEveryPreSubmitTerminal`, `TestTransferCompletionReplayAfterCrashBetweenInsertAndMove`, `TestBuyAndTransferResumeOnlyTheirOwnKind`, `TestTransferStatusCadence` (30 minutes for 7 days after submit, then daily), `TestLookupDSAnswersAndFailures` (a local responder on an ephemeral 127.0.0.1 port via `Config.DNSServer`: DS present, NODATA, NXDOMAIN, SERVFAIL, mismatched ID, malformed, timeout, truncated UDP then TCP; no network).
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestDecideTransfer|TestTransfer|TestLookupDS|TestBuyAndTransfer'`; expect FAIL.
- [ ] **Step 3: Implement.**
-- [ ] **Step 4: Run** the same plus `-run 'TestPurchase|TestStart|DomainBuy|APIDomain'` (buying unchanged); expect PASS.
+- [ ] **Step 4: Run** the same plus `-run 'TestPurchase|TestStart|DomainBuy|APIDomain'` (buying unchanged); expect PASS. The operator resolve route joins the route registers and parity (Global Constraints).
- [ ] **Step 5: Commit** `console: transfer engine (submit, capture on acceptance, wait, refund)`.
- [ ] **Step 6: Astra and Fable task review** (money flow, secret handling, termination of every path).
@@ -232,7 +254,7 @@
**Interfaces:**
- Consumes: Task 5 `RegistrationsExpiringBefore`, `MarkExpiryAlerted`; `purchaseAlert`.
-- Produces (r1 6): `func (s *Server) alertOperator(ctx context.Context, subject, body string) error` (the paging path `purchaseAlert` uses, returning delivery failure instead of only logging; `purchaseAlert` becomes a logging wrapper over it), and `func (s *Server) domainExpiryPass(ctx context.Context, now time.Time) error`: for each registration expiring within 60 days and not alerted, page the operator naming the domain, account and date ("nothing renews domains yet"), and mark it only when `alertOperator` returned nil. The same daily pass runs the transfer watch (Task 6 step 6). Console.db plus one `TransferStatus` per watched transfer; no bucket calls.
+- Produces (r1 6): `func (s *Server) alertOperator(ctx context.Context, subject, body string) error` (the paging path `purchaseAlert` uses, returning delivery failure instead of only logging; `purchaseAlert` becomes a logging wrapper over it), and `func (s *Server) domainExpiryPass(ctx context.Context, now time.Time) error`: for each registration expiring within 60 days and not alerted, page the operator naming the domain, account and date ("nothing renews domains yet"), and mark it only when `alertOperator` returned nil. Console.db only; no registrar or bucket calls.
- [ ] **Step 1: Write failing tests:** `TestExpiryPassAlertsOnceAtSixtyDays`, `TestExpiryPassIgnoresLaterExpiries`, `TestExpiryPassRetriesAfterFailedDelivery` (first page fails, not marked; next pass delivers and marks).
- [ ] **Step 2: Run** `go test ./internal/console/ -run ExpiryPass`; expect FAIL.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-domain-transfers-plan-R2.md b/docs/superpowers/reviews/CODEX-FINDINGS-domain-transfers-plan-R2.md
new file mode 100644
index 000000000..9cb43a6c7
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-domain-transfers-plan-R2.md
@@ -0,0 +1,71 @@
+Reviewed round 2 at `d2c3c5fcefcd6d83d02e4db8ba7e79ef4a275f34`. No files changed, subagents spawned, or test suites run.
+
+| Round 1 finding | Assessment |
+|---|---|
+| 1 · P1 capture uncertainty | **Partly** — read-back resolves lost capture replies, but a definite payment-failure state remains unhandled; carried below. |
+| 2 · P1 refund completion | **Partly** — refund status is tracked, but failed-attempt recovery can loop; carried below. |
+| 3 · P1 registrar resubmission | **Partly** — one purchase never resends, but premature termination permits a second purchase while the first remains unresolved; carried below. |
+| 4 · P1 auth-code retention | **Resolved** — submission CAS consumes the code; pre-submit terminal paths clear it. |
+| 5 · P1 completion replay | **Resolved** — Task 6 requires the existing-registration identity check and crash test. |
+| 6 · P1 expiry-alert delivery | **Resolved** — Task 7 records delivery only after the error-returning alert succeeds. |
+| 7 · P1 performance fixture | **Resolved** — Task 9 explicitly adds the parameterised target and fake dependencies. |
+| 8 · P2 cross-kind resumption | **Resolved** — admission and resumption explicitly reject the other kind. |
+| 9 · P2 DS testing seam | **Resolved** — resolver-address injection, type 43, response validation and TCP fallback are specified. |
+| 10 · P2 unpaid auto-renew | **Resolved** — unpaid completion explicitly records `AutoRenew: false`. |
+| 11 · P2 record-write census | **Resolved** — Task 12 names both inventories, review, targeted gates and gitleaks exclusion. |
+
+1. **P1 — Task 6: `requires_payment_method` has no settlement path.** Carried from R1 #1.
+
+ [Plan:212](/home/paulca/.cache/tmp/design-domain-transfers/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md:212) handles `succeeded`, `requires_capture` and `canceled`, but only recognises capture refusal while the intent still requires capture. Stripe can return a failed payment to `requires_payment_method`; the existing buying engine explicitly handles that outcome at [domainbuy.go:707](/home/paulca/.cache/tmp/design-domain-transfers/internal/console/domainbuy.go:707). See [https://docs.stripe.com/payments/paymentintents/lifecycle](https://docs.stripe.com/payments/paymentintents/lifecycle).
+
+ **Failure:** capture fails into `requires_payment_method`, then the registrar completes. `Payment` stays empty, so the transfer cannot reach `unpaid` or deliver its unpaid notice.
+
+ **Fix:** specify an exhaustive PaymentIntent outcome table, including confirmed payment failure, and test that outcome followed by both registrar completion and failure across restart.
+
+ **Fault family:** terminal payment states require confirmed payment outcomes.
+
+2. **P1 — Tasks 3 and 6: refund recovery can repeatedly select the failed refund.** Carried from R1 #2.
+
+ [Plan:216](/home/paulca/.cache/tmp/design-domain-transfers/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md:216) clears `RefundID` and increments `RefundAttempt` after failure. The next pass first lists refunds to recover a lost creation response. Nothing distinguishes the failed previous attempt from an outstanding current attempt. Stripe’s list returns existing refunds, without the proposed filtering rule: [https://docs.stripe.com/api/refunds/list](https://docs.stripe.com/api/refunds/list).
+
+ **Failure:** refund R0 fails; its ID is cleared; the next list finds R0 again. The worker reads its failure, clears it again and never sends the replacement refund.
+
+ **Fix:** define refund selection explicitly: exclude failed/canceled attempts, correlate recovered refunds with the current attempt, and verify the full refunded amount and currency before settlement. Test failed R0 remaining in every list while R1 is created, including a lost R1 response and restart.
+
+ **Fault family:** every failed charged transfer must reach a confirmed refund.
+
+3. **P1 — Tasks 5–7: `failed/unconfirmed` releases obligations before the transfer is settled.** Carried from R1 #3.
+
+ [Plan:211](/home/paulca/.cache/tmp/design-domain-transfers/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md:211) cancels the hold and marks an unknown transfer failed, then watches for only 14 days. However, `failed` is excluded from the live-purchase predicate at [domainstore.go:101](/home/paulca/.cache/tmp/design-domain-transfers/internal/console/domainstore.go:101), which controls both domain uniqueness and deletion obligations. Account deletion uses that same predicate at [ownership.go:918](/home/paulca/.cache/tmp/design-domain-transfers/internal/console/ownership.go:918).
+
+ **Failure:** an unresolved transfer becomes failed; an app-less account can now be deleted, or another transfer can start for the same domain. A later completion then belongs to a deleted account or competes with another purchase’s domain-only status reconciliation. Separately, a restart after `WatchUntil` permanently misses even a completion that occurred inside the watch period.
+
+ This contradicts the approved requirement to keep an unknown transfer tracked at [spec:793](/home/paulca/.cache/tmp/design-domain-transfers/docs/superpowers/specs/2026-11-01-domain-registration-design.md:793).
+
+ **Fix:** keep registrar uncertainty as a live obligation, independently of payment lapse. Preserve deletion exclusion and domain uniqueness until a definitive registrar outcome or an explicitly recorded operator resolution. Test deletion, another start, and restart beyond the proposed watch deadline.
+
+ **Fault family:** an unknown external mutation must not be treated as settled.
+
+4. **P1 — Tasks 5 and 6: an empty failure reason loses the registrar’s failure outcome.** New.
+
+ `TransferStatus.Reason` explicitly permits `""` at [plan:86](/home/paulca/.cache/tmp/design-domain-transfers/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md:86), but the durable failure marker is just `RegistrarFailed string` at [plan:170](/home/paulca/.cache/tmp/design-domain-transfers/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md:170). Settlement subsequently depends on that marker being set.
+
+ **Failure:** an accepted, captured transfer returns `TransferFailed` with no mapped reason. Persisting its empty reason leaves the same representation as “failure not observed”; the refund transition is never selected.
+
+ **Fix:** store registrar outcome separately from its optional reason, using an enum or explicit failure flag. Test an empty-reason failure after capture, including restart before refund creation.
+
+ **Fault family:** durable registrar outcomes must remain distinguishable from unknown outcomes.
+
+5. **P2 — Task 6: the pre-expiry alert uses the console’s observation time.** New.
+
+ [Plan:211](/home/paulca/.cache/tmp/design-domain-transfers/docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md:211) equates six days after `SetupStartedAt` with one day before authorisation expiry. Buying sets that field when the console observes authorisation, using `time.Now()`, at [domainbuy.go:639](/home/paulca/.cache/tmp/design-domain-transfers/internal/console/domainbuy.go:639).
+
+ **Failure:** Checkout authorises during a console outage. After recovery, the six-day clock starts late, so the promised warning can arrive after the hold expires.
+
+ **Fix:** persist the provider’s authorisation deadline and schedule against it; define a conservative fallback when unavailable. Test delayed observation. Stripe exposes the card deadline as `capture_before`: [https://docs.stripe.com/payments/place-a-hold-on-a-payment-method](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method).
+
+ **Fault family:** expiry warnings must precede the external deadline.
+
+The payment, refund and unknown-mutation families recur across R1 and R2. [AGENTS.md:55](/home/paulca/.cache/tmp/design-domain-transfers/AGENTS.md:55) therefore requires choosing between refusing the affected cases, cutting the feature, or enforcing the invariant in one place with guard tests or simulation before another fix wave. I recommend one settlement decision function, tested across registrar/payment outcomes and crash boundaries.
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-domain-transfers-plan-R3.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-domain-transfers-plan-R3.md
new file mode 100644
index 000000000..c2162f501
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-domain-transfers-plan-R3.md
@@ -0,0 +1,38 @@
+# Review brief: domain registration transfers-in plan, round 3 of 3 (the last)
+
+Repo carlos/platform, branch `design-domain-transfers`, commit named in the reviewer's prompt.
+Under review: `docs/superpowers/plans/2026-11-21-domain-registration-transfers-in.md`.
+Authorities: `docs/superpowers/specs/2026-11-01-domain-registration-design.md` revision 5 §12 (approved by Paul 2026-11-21, on this branch; §12 is the only part not yet on main, and it is approved), Plans 1 and 2a (merged), `AGENTS.md`, and the code on this branch (main at 21e821a6 plus the spec commits).
+
+You are an independent reviewer. Read the plan as the builder would: an engineer who has not seen this codebase implements each task from its text alone. Check every claim against the code.
+
+## Fixed: do not re-argue
+- Paul's rulings R1-R16 and the builder-check calls B1-B4, C1-C3, T1-T7 (spec §3, §11.2, §12.2, §10, §11.10, §12.9).
+- Registration-only transfers (keep nameservers); DNS moves wait for Plan 4.
+- Buying is off while CARLOS_HOST_CLAIM is on; transfers ride that switch.
+
+## What to check
+1. Money: can any path take money without a transfer that completes or is refunded, or leave an authorisation neither captured nor cancelled forever without an operator alert? Does the state machine terminate on every registrar and payment outcome, including crash between steps?
+2. The auth code: is there any place it can be logged, echoed, put in a URL, or survive in storage after the submit is recorded?
+3. The registrar seam and Openprovider: are the transfer calls and the neutral states mappable from Openprovider's API (`/v1`, or say if only `/v1beta` exists)? Is "best effort" transfer checking safe?
+4. Plan 2a interactions: every path that assumes a bought domain has a zone (Point, pages, purchase card, account deletion, Unpointing, the app-gone path); the one-live-purchase-per-domain index across kinds.
+5. The DS lookup via dnsmessage and the system resolver: correct and testable without the network?
+6. Route registers, parity, census, gitleaks, perf budget: anything CI will fail on that the plan doesn't name?
+7. Task right-sizing, interface consistency, and whether each step lets the builder write exactly one reasonable thing.
+
+## Round 3 (the last)
+
+Round 1 on b77e1ec7 (`CODEX-FINDINGS-domain-transfers-plan.md`, 7 P1, 4 P2) and round 2 on d2c3c5fc (`CODEX-FINDINGS-domain-transfers-plan-R2.md`, 4 P1, 1 P2; payment, refund and unknown-mutation families repeated). **Paul's ruling after round 2 (2026-11-22, stopping rule 2): one settlement function.** Task 6 now puts every transfer decision in a pure `decideTransfer` over closed registrar, payment and refund outcome sets, with invariants I1-I8 checked by a randomized simulation through the real engine; an unknown registrar outcome stays live until a definite answer or an operator resolution. Check the decision table is exhaustive and correct, the invariants are the right ones, and the engine's fact gathering can actually observe each outcome; do not reopen the approach.
+
+First give one line per round 2 P1 and P2: resolved, partly, or not. Then new findings. A NOT READY also says whether the P1s share one cause, and whether refusing the case up front or cutting would remove them.
+
+## 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. Follow-up list; never a reason for another round.
+A P1 states its failure scenario and evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+Findings ranked P1, P2, P3: section or task, problem, evidence (file:line, verified), failure scenario, concrete fix, and the invariant it breaks (its fault family). End with exactly one verdict: READY / READY AFTER FIXES / NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents. Do not run full suites.